BlueGit

ict rusty-teams

feat(agents): delegate a message to an agent CLI from the hover toolbar

Robot button runs Claude Code, Copilot CLI or any CLI on the message with
its thread as context. Run chip under the message, Agents rail entry, toast
on finish, Open session in a terminal, Settings > Agents. Agents reply via
the teams MCP propose_message tool. Hover toolbar groups split by a line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-12 · 7 weeks ago

Hash
4c147312d13a38a4edfafa074b9f6cb206704e33
Parent
6207eafb
57 files changed +6513 −102
Cargo.lock +14 −0
@@ -109,6 +109,18 @@ dependencies = [
109 109 "zeroize",
110 110 ]
111 111
112 [[package]]
113 name = "agents"
114 version = "0.1.0"
115 dependencies = [
116 "serde",
117 "serde_json",
118 "tempfile",
119 "thiserror 2.0.21",
120 "tokio",
121 "uuid",
122 ]
123
112 124 [[package]]
113 125 name = "ahash"
114 126 version = "0.8.12"
@@ -263,6 +275,7 @@ checksum = "fb5dfbc6d8d2675589ccbe4d0fd61df2419075625f8c1a62325e718e2b0049f9"
263 275 name = "app"
264 276 version = "0.1.0"
265 277 dependencies = [
278 "agents",
266 279 "calling",
267 280 "chatsvc",
268 281 "chrono",
@@ -9170,6 +9183,7 @@ dependencies = [
9170 9183 "libc",
9171 9184 "mio",
9172 9185 "pin-project-lite",
9186 "signal-hook-registry",
9173 9187 "socket2",
9174 9188 "tokio-macros",
9175 9189 "windows-sys 0.61.2",
@@ -109,6 +109,18 @@ dependencies = [
109 "zeroize",
109 "zeroize",
110]
110]
111
111
112[[package]]
113name = "agents"
114version = "0.1.0"
115dependencies = [
116 "serde",
117 "serde_json",
118 "tempfile",
119 "thiserror 2.0.21",
120 "tokio",
121 "uuid",
122]
123
112[[package]]
124[[package]]
113name = "ahash"
125name = "ahash"
114version = "0.8.12"
126version = "0.8.12"
@@ -263,6 +275,7 @@ checksum = "fb5dfbc6d8d2675589ccbe4d0fd61df2419075625f8c1a62325e718e2b0049f9"
263name = "app"
275name = "app"
264version = "0.1.0"
276version = "0.1.0"
265dependencies = [
277dependencies = [
278 "agents",
266 "calling",
279 "calling",
267 "chatsvc",
280 "chatsvc",
268 "chrono",
281 "chrono",
@@ -9170,6 +9183,7 @@ dependencies = [
9170 "libc",
9183 "libc",
9171 "mio",
9184 "mio",
9172 "pin-project-lite",
9185 "pin-project-lite",
9186 "signal-hook-registry",
9173 "socket2",
9187 "socket2",
9174 "tokio-macros",
9188 "tokio-macros",
9175 "windows-sys 0.61.2",
9189 "windows-sys 0.61.2",
Cargo.toml +2 −1
@@ -23,11 +23,12 @@ serde = { version = "1", features = ["derive"] }
23 23 serde_json = "1"
24 24 tempfile = "3"
25 25 thiserror = "2"
26 tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "time", "io-util", "sync"] }
26 tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "time", "io-util", "sync", "process"] }
27 27 tokio-tungstenite = { version = "0.28", default-features = false, features = ["connect", "handshake"] }
28 28 url = "2"
29 29 uuid = { version = "1", default-features = false, features = ["v4"] }
30 30
31 agents = { path = "crates/agents" }
31 32 session = { path = "crates/session" }
32 33 graph = { path = "crates/graph" }
33 34 store = { path = "crates/store" }
@@ -23,11 +23,12 @@ serde = { version = "1", features = ["derive"] }
23serde_json = "1"
23serde_json = "1"
24tempfile = "3"
24tempfile = "3"
25thiserror = "2"
25thiserror = "2"
26tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "time", "io-util", "sync"] }
26tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "time", "io-util", "sync", "process"] }
27tokio-tungstenite = { version = "0.28", default-features = false, features = ["connect", "handshake"] }
27tokio-tungstenite = { version = "0.28", default-features = false, features = ["connect", "handshake"] }
28url = "2"
28url = "2"
29uuid = { version = "1", default-features = false, features = ["v4"] }
29uuid = { version = "1", default-features = false, features = ["v4"] }
30
30
31agents = { path = "crates/agents" }
31session = { path = "crates/session" }
32session = { path = "crates/session" }
32graph = { path = "crates/graph" }
33graph = { path = "crates/graph" }
33store = { path = "crates/store" }
34store = { path = "crates/store" }
README.md +1 −0
@@ -71,6 +71,7 @@
71 71 - Agents read allowed chats, channels, meetings and transcripts, and propose replies
72 72 - A proposal shows as a card above the composer: Send, Edit or Discard. Agents never send
73 73 - One-click install for Claude Code, Codex CLI, Copilot CLI, VS Code and Cursor, Windows and WSL. WSL needs `networkingMode=mirrored`
74 - Delegate a message to a coding-agent CLI (Claude Code, Copilot, any CLI) from the hover toolbar: progress chip, Agents rail entry, toast when it finishes, Open session
74 75
75 76 **App**
76 77 - Dark theme, opens instantly from the cache
@@ -71,6 +71,7 @@
71- Agents read allowed chats, channels, meetings and transcripts, and propose replies
71- Agents read allowed chats, channels, meetings and transcripts, and propose replies
72- A proposal shows as a card above the composer: Send, Edit or Discard. Agents never send
72- A proposal shows as a card above the composer: Send, Edit or Discard. Agents never send
73- One-click install for Claude Code, Codex CLI, Copilot CLI, VS Code and Cursor, Windows and WSL. WSL needs `networkingMode=mirrored`
73- One-click install for Claude Code, Codex CLI, Copilot CLI, VS Code and Cursor, Windows and WSL. WSL needs `networkingMode=mirrored`
74- Delegate a message to a coding-agent CLI (Claude Code, Copilot, any CLI) from the hover toolbar: progress chip, Agents rail entry, toast when it finishes, Open session
74
75
75**App**
76**App**
76- Dark theme, opens instantly from the cache
77- Dark theme, opens instantly from the cache
ROADMAP.md +6 −6
@@ -186,13 +186,13 @@ After parity. Not counted in the parity score.
186 186
187 187 | Feature | State | Note |
188 188 |---|---|---|
189 | Local API in the app | Missing | Tokens, chat access and agent state stay in the app. CLI and MCP are thin clients |
189 | Delegate a message to an agent CLI (Claude Code, Copilot, any CLI) from the hover toolbar | Done | Robot button in the hover toolbar, actions and agents in Settings > Agents |
190 | Run status: chip under the message, Agents rail entry, toast, Open session | Done | Live step and time on the chip, Agents rail popover with running and done runs, toast on finish or failure, Open session resumes the agent session in a terminal |
191 | Local API in the app | Partial | MCP only, no CLI. Tokens and chat access stay in the app |
190 192 | CLI `rt`: watch, read, search, claim, propose, release | Missing | First. `rt watch --once` blocks until the next event, so any agent can wait on it |
191 | MCP server on the same API | Missing | After the CLI. `wait_for_event(timeout)` long-polls, progress pings keep it alive |
192 | Agent access per chat, off by default | Missing | Other chats are invisible to agents, search included |
193 | Proposals: card above the composer, send, edit, discard | Missing | Agents never send. A proposal is stale once you answered first |
194 | Agent status per chat: working, proposal ready, declined | Missing | Claim with heartbeat, clears itself when the agent stops |
195 | Agent sees you type or send and can abort | Missing | `user_typing` and `user_sent` events in the watch stream |
193 | MCP server on the same API | Done | Read tools and `propose_message` only, Settings > MCP |
194 | Agent permissions in Settings: chats/channels All/Selected/None, propose, calendar, transcripts | Done | Other chats are invisible to agents, search included |
195 | Proposals: card above the composer, send, edit, discard | Done | Agents never send. A proposal is stale once you answered first |
196 196
197 197 ## Out of scope
198 198
@@ -186,13 +186,13 @@ After parity. Not counted in the parity score.
186
186
187| Feature | State | Note |
187| Feature | State | Note |
188|---|---|---|
188|---|---|---|
189| Local API in the app | Missing | Tokens, chat access and agent state stay in the app. CLI and MCP are thin clients |
189| Delegate a message to an agent CLI (Claude Code, Copilot, any CLI) from the hover toolbar | Done | Robot button in the hover toolbar, actions and agents in Settings > Agents |
190| Run status: chip under the message, Agents rail entry, toast, Open session | Done | Live step and time on the chip, Agents rail popover with running and done runs, toast on finish or failure, Open session resumes the agent session in a terminal |
191| Local API in the app | Partial | MCP only, no CLI. Tokens and chat access stay in the app |
190| CLI `rt`: watch, read, search, claim, propose, release | Missing | First. `rt watch --once` blocks until the next event, so any agent can wait on it |
192| CLI `rt`: watch, read, search, claim, propose, release | Missing | First. `rt watch --once` blocks until the next event, so any agent can wait on it |
191| MCP server on the same API | Missing | After the CLI. `wait_for_event(timeout)` long-polls, progress pings keep it alive |
193| MCP server on the same API | Done | Read tools and `propose_message` only, Settings > MCP |
192| Agent access per chat, off by default | Missing | Other chats are invisible to agents, search included |
194| Agent permissions in Settings: chats/channels All/Selected/None, propose, calendar, transcripts | Done | Other chats are invisible to agents, search included |
193| Proposals: card above the composer, send, edit, discard | Missing | Agents never send. A proposal is stale once you answered first |
195| Proposals: card above the composer, send, edit, discard | Done | Agents never send. A proposal is stale once you answered first |
194| Agent status per chat: working, proposal ready, declined | Missing | Claim with heartbeat, clears itself when the agent stops |
195| Agent sees you type or send and can abort | Missing | `user_typing` and `user_sent` events in the watch stream |
196
196
197## Out of scope
197## Out of scope
198
198
crates/agents/Cargo.toml added +16 −0
@@ -0,0 +1,16 @@
1 [package]
2 name = "agents"
3 edition.workspace = true
4 version.workspace = true
5 license.workspace = true
6 publish.workspace = true
7
8 [dependencies]
9 serde.workspace = true
10 serde_json.workspace = true
11 thiserror.workspace = true
12 tokio.workspace = true
13 uuid.workspace = true
14
15 [dev-dependencies]
16 tempfile.workspace = true
@@ -0,0 +1,16 @@
1[package]
2name = "agents"
3edition.workspace = true
4version.workspace = true
5license.workspace = true
6publish.workspace = true
7
8[dependencies]
9serde.workspace = true
10serde_json.workspace = true
11thiserror.workspace = true
12tokio.workspace = true
13uuid.workspace = true
14
15[dev-dependencies]
16tempfile.workspace = true
crates/agents/src/action.rs added +42 −0
@@ -0,0 +1,42 @@
1 use serde::{Deserialize, Serialize};
2
3 const ANSWER_TEMPLATE: &str = "{sender} asked me in the Teams chat \"{chat}\":\n\n{message}\n\nEarlier messages in this chat:\n{thread}\n\nResearch what is needed, then propose my reply with the `propose_message` tool of the `teams` MCP server: conversation_id \"{conversation_id}\", reply_to_message_id \"{message_id}\", session_id \"{session_id}\", agent \"{agent}\". Never send anything yourself. {extra}";
4 const BUILD_TEMPLATE: &str = "{sender} asked me in the Teams chat \"{chat}\" to build something:\n\n{message}\n\nEarlier messages in this chat:\n{thread}\n\nBuild what is asked in this repository. When done, propose a short reply to {sender} with the `propose_message` tool of the `teams` MCP server: conversation_id \"{conversation_id}\", reply_to_message_id \"{message_id}\", session_id \"{session_id}\", agent \"{agent}\". {extra}";
5
6 #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
7 #[serde(default)]
8 pub struct AgentAction {
9 pub id: String,
10 pub label: String,
11 pub agent_id: String,
12 pub working_dir: String,
13 pub prompt_template: String,
14 pub ask_extra_instructions: bool,
15 pub extra_args: String,
16 }
17
18 impl AgentAction {
19 pub fn answer_this(agent_id: &str) -> Self {
20 Self {
21 id: "answer-this".to_string(),
22 label: "Answer this".to_string(),
23 agent_id: agent_id.to_string(),
24 working_dir: "~".to_string(),
25 prompt_template: ANSWER_TEMPLATE.to_string(),
26 ask_extra_instructions: false,
27 extra_args: "--allowedTools WebSearch,WebFetch,Read,Grep,Glob,mcp__teams".to_string(),
28 }
29 }
30
31 pub fn build_this(agent_id: &str) -> Self {
32 Self {
33 id: "build-this".to_string(),
34 label: "Build this".to_string(),
35 agent_id: agent_id.to_string(),
36 working_dir: "~".to_string(),
37 prompt_template: BUILD_TEMPLATE.to_string(),
38 ask_extra_instructions: true,
39 extra_args: "--permission-mode auto".to_string(),
40 }
41 }
42 }
@@ -0,0 +1,42 @@
1use serde::{Deserialize, Serialize};
2
3const ANSWER_TEMPLATE: &str = "{sender} asked me in the Teams chat \"{chat}\":\n\n{message}\n\nEarlier messages in this chat:\n{thread}\n\nResearch what is needed, then propose my reply with the `propose_message` tool of the `teams` MCP server: conversation_id \"{conversation_id}\", reply_to_message_id \"{message_id}\", session_id \"{session_id}\", agent \"{agent}\". Never send anything yourself. {extra}";
4const BUILD_TEMPLATE: &str = "{sender} asked me in the Teams chat \"{chat}\" to build something:\n\n{message}\n\nEarlier messages in this chat:\n{thread}\n\nBuild what is asked in this repository. When done, propose a short reply to {sender} with the `propose_message` tool of the `teams` MCP server: conversation_id \"{conversation_id}\", reply_to_message_id \"{message_id}\", session_id \"{session_id}\", agent \"{agent}\". {extra}";
5
6#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
7#[serde(default)]
8pub struct AgentAction {
9 pub id: String,
10 pub label: String,
11 pub agent_id: String,
12 pub working_dir: String,
13 pub prompt_template: String,
14 pub ask_extra_instructions: bool,
15 pub extra_args: String,
16}
17
18impl AgentAction {
19 pub fn answer_this(agent_id: &str) -> Self {
20 Self {
21 id: "answer-this".to_string(),
22 label: "Answer this".to_string(),
23 agent_id: agent_id.to_string(),
24 working_dir: "~".to_string(),
25 prompt_template: ANSWER_TEMPLATE.to_string(),
26 ask_extra_instructions: false,
27 extra_args: "--allowedTools WebSearch,WebFetch,Read,Grep,Glob,mcp__teams".to_string(),
28 }
29 }
30
31 pub fn build_this(agent_id: &str) -> Self {
32 Self {
33 id: "build-this".to_string(),
34 label: "Build this".to_string(),
35 agent_id: agent_id.to_string(),
36 working_dir: "~".to_string(),
37 prompt_template: BUILD_TEMPLATE.to_string(),
38 ask_extra_instructions: true,
39 extra_args: "--permission-mode auto".to_string(),
40 }
41 }
42}
crates/agents/src/context.rs added +132 −0
@@ -0,0 +1,132 @@
1 use crate::action::AgentAction;
2 use crate::template::{Values, render};
3
4 const THREAD_LIMIT: usize = 20;
5
6 #[derive(Clone, Debug, Default, PartialEq, Eq)]
7 pub struct ThreadMessage {
8 pub sender: String,
9 pub text: String,
10 pub time: String,
11 }
12
13 #[derive(Clone, Debug, Default, PartialEq, Eq)]
14 pub struct MessageContext {
15 pub sender: String,
16 pub chat: String,
17 pub conversation_id: String,
18 pub message_id: String,
19 pub message: String,
20 pub thread: Vec<ThreadMessage>,
21 }
22
23 fn render_thread(thread: &[ThreadMessage]) -> String {
24 if thread.is_empty() {
25 return "(none)".to_string();
26 }
27 let skipped = thread.len().saturating_sub(THREAD_LIMIT);
28 thread[skipped..]
29 .iter()
30 .map(|entry| format!("{} ({}): {}", entry.sender, entry.time, entry.text))
31 .collect::<Vec<_>>()
32 .join("\n")
33 }
34
35 pub fn build_prompt(
36 action: &AgentAction,
37 context: &MessageContext,
38 extra: &str,
39 session_id: &str,
40 agent_id: &str,
41 ) -> String {
42 let values = Values {
43 message: context.message.clone(),
44 sender: context.sender.clone(),
45 chat: context.chat.clone(),
46 conversation_id: context.conversation_id.clone(),
47 message_id: context.message_id.clone(),
48 thread: render_thread(&context.thread),
49 extra: extra.to_string(),
50 session_id: session_id.to_string(),
51 agent: agent_id.to_string(),
52 ..Values::default()
53 };
54 let rendered =
55 render(&action.prompt_template, &values).unwrap_or_else(|_| action.prompt_template.clone());
56 rendered.trim().to_string()
57 }
58
59 #[cfg(test)]
60 mod tests {
61 use super::*;
62
63 fn context(thread_length: usize) -> MessageContext {
64 MessageContext {
65 sender: "Ada".to_string(),
66 chat: "Ops".to_string(),
67 conversation_id: "19:abc".to_string(),
68 message_id: "42".to_string(),
69 message: "Where is the report?".to_string(),
70 thread: (0..thread_length)
71 .map(|index| ThreadMessage {
72 sender: format!("User{index}"),
73 text: format!("text {index}"),
74 time: "10:00".to_string(),
75 })
76 .collect(),
77 }
78 }
79
80 #[test]
81 fn answer_prompt_renders_ids() {
82 let prompt = build_prompt(
83 &AgentAction::answer_this("claude"),
84 &context(0),
85 "",
86 "sid-9",
87 "claude",
88 );
89 assert!(
90 prompt.starts_with("Ada asked me in the Teams chat \"Ops\":\n\nWhere is the report?")
91 );
92 assert!(prompt.contains("Earlier messages in this chat:\n(none)\n\n"));
93 assert!(prompt.contains("conversation_id \"19:abc\", reply_to_message_id \"42\", session_id \"sid-9\", agent \"claude\"."));
94 assert!(prompt.ends_with("Never send anything yourself."));
95 }
96
97 #[test]
98 fn build_prompt_is_trimmed_and_takes_extra() {
99 let prompt = build_prompt(
100 &AgentAction::build_this("claude"),
101 &context(1),
102 "",
103 "sid-9",
104 "claude",
105 );
106 assert!(prompt.ends_with("agent \"claude\"."));
107 assert!(prompt.contains("propose a short reply to Ada"));
108 assert!(prompt.contains("User0 (10:00): text 0"));
109 let with_extra = build_prompt(
110 &AgentAction::build_this("claude"),
111 &context(1),
112 "Use Rust",
113 "sid-9",
114 "claude",
115 );
116 assert!(with_extra.ends_with("agent \"claude\". Use Rust"));
117 }
118
119 #[test]
120 fn thread_keeps_last_twenty() {
121 let prompt = build_prompt(
122 &AgentAction::build_this("claude"),
123 &context(25),
124 "",
125 "sid-9",
126 "claude",
127 );
128 assert!(!prompt.contains("User4 "));
129 assert!(prompt.contains("User5 (10:00)"));
130 assert!(prompt.contains("User24 (10:00)"));
131 }
132 }
@@ -0,0 +1,132 @@
1use crate::action::AgentAction;
2use crate::template::{Values, render};
3
4const THREAD_LIMIT: usize = 20;
5
6#[derive(Clone, Debug, Default, PartialEq, Eq)]
7pub struct ThreadMessage {
8 pub sender: String,
9 pub text: String,
10 pub time: String,
11}
12
13#[derive(Clone, Debug, Default, PartialEq, Eq)]
14pub struct MessageContext {
15 pub sender: String,
16 pub chat: String,
17 pub conversation_id: String,
18 pub message_id: String,
19 pub message: String,
20 pub thread: Vec<ThreadMessage>,
21}
22
23fn render_thread(thread: &[ThreadMessage]) -> String {
24 if thread.is_empty() {
25 return "(none)".to_string();
26 }
27 let skipped = thread.len().saturating_sub(THREAD_LIMIT);
28 thread[skipped..]
29 .iter()
30 .map(|entry| format!("{} ({}): {}", entry.sender, entry.time, entry.text))
31 .collect::<Vec<_>>()
32 .join("\n")
33}
34
35pub fn build_prompt(
36 action: &AgentAction,
37 context: &MessageContext,
38 extra: &str,
39 session_id: &str,
40 agent_id: &str,
41) -> String {
42 let values = Values {
43 message: context.message.clone(),
44 sender: context.sender.clone(),
45 chat: context.chat.clone(),
46 conversation_id: context.conversation_id.clone(),
47 message_id: context.message_id.clone(),
48 thread: render_thread(&context.thread),
49 extra: extra.to_string(),
50 session_id: session_id.to_string(),
51 agent: agent_id.to_string(),
52 ..Values::default()
53 };
54 let rendered =
55 render(&action.prompt_template, &values).unwrap_or_else(|_| action.prompt_template.clone());
56 rendered.trim().to_string()
57}
58
59#[cfg(test)]
60mod tests {
61 use super::*;
62
63 fn context(thread_length: usize) -> MessageContext {
64 MessageContext {
65 sender: "Ada".to_string(),
66 chat: "Ops".to_string(),
67 conversation_id: "19:abc".to_string(),
68 message_id: "42".to_string(),
69 message: "Where is the report?".to_string(),
70 thread: (0..thread_length)
71 .map(|index| ThreadMessage {
72 sender: format!("User{index}"),
73 text: format!("text {index}"),
74 time: "10:00".to_string(),
75 })
76 .collect(),
77 }
78 }
79
80 #[test]
81 fn answer_prompt_renders_ids() {
82 let prompt = build_prompt(
83 &AgentAction::answer_this("claude"),
84 &context(0),
85 "",
86 "sid-9",
87 "claude",
88 );
89 assert!(
90 prompt.starts_with("Ada asked me in the Teams chat \"Ops\":\n\nWhere is the report?")
91 );
92 assert!(prompt.contains("Earlier messages in this chat:\n(none)\n\n"));
93 assert!(prompt.contains("conversation_id \"19:abc\", reply_to_message_id \"42\", session_id \"sid-9\", agent \"claude\"."));
94 assert!(prompt.ends_with("Never send anything yourself."));
95 }
96
97 #[test]
98 fn build_prompt_is_trimmed_and_takes_extra() {
99 let prompt = build_prompt(
100 &AgentAction::build_this("claude"),
101 &context(1),
102 "",
103 "sid-9",
104 "claude",
105 );
106 assert!(prompt.ends_with("agent \"claude\"."));
107 assert!(prompt.contains("propose a short reply to Ada"));
108 assert!(prompt.contains("User0 (10:00): text 0"));
109 let with_extra = build_prompt(
110 &AgentAction::build_this("claude"),
111 &context(1),
112 "Use Rust",
113 "sid-9",
114 "claude",
115 );
116 assert!(with_extra.ends_with("agent \"claude\". Use Rust"));
117 }
118
119 #[test]
120 fn thread_keeps_last_twenty() {
121 let prompt = build_prompt(
122 &AgentAction::build_this("claude"),
123 &context(25),
124 "",
125 "sid-9",
126 "claude",
127 );
128 assert!(!prompt.contains("User4 "));
129 assert!(prompt.contains("User5 (10:00)"));
130 assert!(prompt.contains("User24 (10:00)"));
131 }
132}
crates/agents/src/invocation.rs added +528 −0
@@ -0,0 +1,528 @@
1 use std::path::{Path, PathBuf};
2
3 use crate::action::AgentAction;
4 use crate::profile::{AgentProfile, Environment};
5 use crate::template::{UnknownPlaceholder, Values, placeholders_in, render, split_command};
6
7 const WSL_PROGRAM: &str = "wsl.exe";
8 const WSL_SCRIPT: &str = r#"case "$1" in "~"*) dir="$HOME${1#\~}";; *) dir="$1";; esac; cd "$dir" && shift && exec "$@""#;
9
10 #[derive(Clone, Debug, PartialEq, Eq)]
11 pub struct Invocation {
12 pub program: String,
13 pub args: Vec<String>,
14 pub cwd: Option<PathBuf>,
15 pub stdin: Option<String>,
16 }
17
18 #[derive(Clone, Debug, PartialEq, Eq)]
19 pub struct McpEndpoint {
20 pub url: String,
21 pub token: String,
22 }
23
24 #[derive(Clone, Debug, PartialEq, Eq)]
25 pub struct RunPlan {
26 pub run: Invocation,
27 pub stop: Option<Invocation>,
28 pub cleanup: Vec<PathBuf>,
29 }
30
31 #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
32 pub enum InvocationError {
33 #[error("the command is empty")]
34 EmptyCommand,
35 #[error(transparent)]
36 UnknownPlaceholder(#[from] UnknownPlaceholder),
37 #[error("cannot write the MCP config: {0}")]
38 McpConfig(String),
39 }
40
41 fn expand_home(path: &str) -> String {
42 let remainder = match path.strip_prefix('~') {
43 Some(remainder) if remainder.is_empty() || remainder.starts_with(['/', '\\']) => remainder,
44 _ => return path.to_string(),
45 };
46 match std::env::var("HOME").or_else(|_| std::env::var("USERPROFILE")) {
47 Ok(home) => format!("{home}{remainder}"),
48 Err(_) => path.to_string(),
49 }
50 }
51
52 fn mcp_config_json(endpoint: &McpEndpoint) -> String {
53 serde_json::json!({
54 "mcpServers": {
55 "teams": {
56 "type": "http",
57 "url": endpoint.url,
58 "headers": {"Authorization": format!("Bearer {}", endpoint.token)},
59 }
60 }
61 })
62 .to_string()
63 }
64
65 pub fn wsl_path(path: &str) -> String {
66 let mut characters = path.chars();
67 match (characters.next(), characters.next(), characters.next()) {
68 (Some(drive), Some(':'), Some('/' | '\\')) if drive.is_ascii_alphabetic() => format!(
69 "/mnt/{}/{}",
70 drive.to_ascii_lowercase(),
71 path[3..].replace('\\', "/")
72 ),
73 _ => path.to_string(),
74 }
75 }
76
77 fn write_mcp_config(
78 directory: &Path,
79 session_id: &str,
80 endpoint: &McpEndpoint,
81 ) -> Result<PathBuf, InvocationError> {
82 let to_error = |error: std::io::Error| InvocationError::McpConfig(error.to_string());
83 std::fs::create_dir_all(directory).map_err(to_error)?;
84 let path = directory.join(format!("mcp-{session_id}.json"));
85 let mut options = std::fs::OpenOptions::new();
86 options.write(true).create(true).truncate(true);
87 #[cfg(unix)]
88 std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
89 let mut file = options.open(&path).map_err(to_error)?;
90 std::io::Write::write_all(&mut file, mcp_config_json(endpoint).as_bytes()).map_err(to_error)?;
91 Ok(path)
92 }
93
94 fn mcp_config_argument(flag: &str, path: &Path, environment: &Environment) -> String {
95 let text = path.to_string_lossy();
96 let text = match environment {
97 Environment::Wsl { .. } if cfg!(windows) => wsl_path(&text),
98 _ => text.into_owned(),
99 };
100 if flag.ends_with("additional-mcp-config") {
101 format!("@{text}")
102 } else {
103 text
104 }
105 }
106
107 fn wsl_prefix(environment: &Environment) -> Vec<String> {
108 match environment {
109 Environment::Wsl {
110 distro: Some(distro),
111 } => vec!["-d".to_string(), distro.clone()],
112 _ => Vec::new(),
113 }
114 }
115
116 fn working_directory(profile: &AgentProfile, action: &AgentAction) -> String {
117 match profile.environment {
118 Environment::Host => expand_home(&action.working_dir),
119 Environment::Wsl { .. } => action.working_dir.clone(),
120 }
121 }
122
123 pub fn build_invocation(
124 profile: &AgentProfile,
125 action: &AgentAction,
126 prompt: &str,
127 session_id: &str,
128 mcp: Option<&McpEndpoint>,
129 mcp_config_directory: Option<&Path>,
130 ) -> Result<RunPlan, InvocationError> {
131 let working_dir = working_directory(profile, action);
132 let values = Values {
133 session_id: session_id.to_string(),
134 agent: profile.id.clone(),
135 prompt: prompt.to_string(),
136 cwd: working_dir.clone(),
137 ..Values::default()
138 };
139 let raw_tokens: Vec<String> = split_command(&profile.command)
140 .into_iter()
141 .chain(split_command(&action.extra_args))
142 .collect();
143 if raw_tokens.is_empty() {
144 return Err(InvocationError::EmptyCommand);
145 }
146 let uses_prompt_placeholder = raw_tokens
147 .iter()
148 .any(|token| placeholders_in(token).iter().any(|name| name == "prompt"));
149 let mut tokens = raw_tokens
150 .iter()
151 .map(|token| render(token, &values))
152 .collect::<Result<Vec<_>, _>>()?;
153 let mut cleanup = Vec::new();
154 if let Some(endpoint) = mcp
155 && let Some(directory) = mcp_config_directory
156 && !profile.mcp_config_flag.is_empty()
157 {
158 let path = write_mcp_config(directory, session_id, endpoint)?;
159 tokens.push(profile.mcp_config_flag.clone());
160 tokens.push(mcp_config_argument(
161 &profile.mcp_config_flag,
162 &path,
163 &profile.environment,
164 ));
165 cleanup.push(path);
166 }
167 let stdin = (!uses_prompt_placeholder).then(|| prompt.to_string());
168
169 match &profile.environment {
170 Environment::Host => {
171 let mut tokens = tokens.into_iter();
172 let program = tokens.next().ok_or(InvocationError::EmptyCommand)?;
173 Ok(RunPlan {
174 run: Invocation {
175 program,
176 args: tokens.collect(),
177 cwd: Some(PathBuf::from(working_dir)),
178 stdin,
179 },
180 stop: None,
181 cleanup,
182 })
183 }
184 Environment::Wsl { .. } => {
185 let mut args = wsl_prefix(&profile.environment);
186 let mut stop_args = args.clone();
187 args.extend(
188 ["-e", "sh", "-lc", WSL_SCRIPT, "sh"]
189 .into_iter()
190 .map(String::from),
191 );
192 args.push(working_dir);
193 args.extend(tokens);
194 stop_args.extend(["-e", "pkill", "-f", session_id].map(String::from));
195 Ok(RunPlan {
196 run: Invocation {
197 program: WSL_PROGRAM.to_string(),
198 args,
199 cwd: None,
200 stdin,
201 },
202 stop: Some(Invocation {
203 program: WSL_PROGRAM.to_string(),
204 args: stop_args,
205 cwd: None,
206 stdin: None,
207 }),
208 cleanup,
209 })
210 }
211 }
212 }
213
214 pub fn open_session_invocation(
215 profile: &AgentProfile,
216 action: &AgentAction,
217 session_id: &str,
218 ) -> Result<Invocation, InvocationError> {
219 let values = Values {
220 session_id: session_id.to_string(),
221 agent: profile.id.clone(),
222 cwd: working_directory(profile, action),
223 ..Values::default()
224 };
225 let mut tokens = split_command(&profile.open_session_command)
226 .iter()
227 .map(|token| render(token, &values))
228 .collect::<Result<Vec<_>, _>>()?
229 .into_iter();
230 let program = tokens.next().ok_or(InvocationError::EmptyCommand)?;
231 Ok(Invocation {
232 program,
233 args: tokens.collect(),
234 cwd: None,
235 stdin: None,
236 })
237 }
238
239 pub fn version_check_invocation(profile: &AgentProfile) -> Invocation {
240 let program = split_command(&profile.command)
241 .into_iter()
242 .next()
243 .unwrap_or_default();
244 match &profile.environment {
245 Environment::Host => Invocation {
246 program,
247 args: vec!["--version".to_string()],
248 cwd: None,
249 stdin: None,
250 },
251 Environment::Wsl { .. } => {
252 let mut args = wsl_prefix(&profile.environment);
253 args.extend(
254 ["-e", "sh", "-lc", WSL_SCRIPT, "sh", "~"]
255 .into_iter()
256 .map(String::from),
257 );
258 args.push(program);
259 args.push("--version".to_string());
260 Invocation {
261 program: WSL_PROGRAM.to_string(),
262 args,
263 cwd: None,
264 stdin: None,
265 }
266 }
267 }
268 }
269
270 #[cfg(test)]
271 mod tests {
272 use super::*;
273
274 #[test]
275 fn wsl_invocation_has_exact_args() {
276 let mut profile = AgentProfile::claude_wsl();
277 profile.environment = Environment::Wsl {
278 distro: Some("Ubuntu".to_string()),
279 };
280 let action = AgentAction::answer_this("claude");
281 let plan = build_invocation(&profile, &action, "hi there", "sid-1", None, None).unwrap();
282 let expected_args: Vec<String> = [
283 "-d",
284 "Ubuntu",
285 "-e",
286 "sh",
287 "-lc",
288 WSL_SCRIPT,
289 "sh",
290 "~",
291 "claude",
292 "-p",
293 "--output-format",
294 "stream-json",
295 "--verbose",
296 "--session-id",
297 "sid-1",
298 "--allowedTools",
299 "WebSearch,WebFetch,Read,Grep,Glob,mcp__teams",
300 ]
301 .map(String::from)
302 .to_vec();
303 assert_eq!(plan.run.program, "wsl.exe");
304 assert_eq!(plan.run.args, expected_args);
305 assert_eq!(plan.run.cwd, None);
306 assert_eq!(plan.run.stdin.as_deref(), Some("hi there"));
307 let stop = plan.stop.unwrap();
308 assert_eq!(stop.program, "wsl.exe");
309 assert_eq!(
310 stop.args,
311 ["-d", "Ubuntu", "-e", "pkill", "-f", "sid-1"].map(String::from)
312 );
313 }
314
315 #[test]
316 fn prompt_placeholder_goes_in_args_without_stdin() {
317 let profile = AgentProfile::copilot_wsl();
318 let action = AgentAction::answer_this("copilot");
319 let plan = build_invocation(&profile, &action, "a b\nc", "sid-2", None, None).unwrap();
320 assert_eq!(plan.run.stdin, None);
321 assert_eq!(plan.run.args[..2], ["-e".to_string(), "sh".to_string()]);
322 let prompt_position = plan.run.args.iter().position(|arg| arg == "-p").unwrap() + 1;
323 assert_eq!(plan.run.args[prompt_position], "a b\nc");
324 }
325
326 #[test]
327 fn host_invocation_expands_home() {
328 let mut action = AgentAction::build_this("claude-host");
329 action.working_dir = "~/work".to_string();
330 let plan = build_invocation(
331 &AgentProfile::claude_host(),
332 &action,
333 "p",
334 "sid-3",
335 None,
336 None,
337 )
338 .unwrap();
339 let home = std::env::var("HOME")
340 .or_else(|_| std::env::var("USERPROFILE"))
341 .unwrap();
342 assert_eq!(plan.run.program, "claude");
343 assert_eq!(plan.run.cwd, Some(PathBuf::from(format!("{home}/work"))));
344 assert_eq!(plan.run.stdin.as_deref(), Some("p"));
345 assert!(
346 plan.run
347 .args
348 .ends_with(&["--permission-mode".to_string(), "auto".to_string()])
349 );
350 assert_eq!(plan.stop, None);
351 }
352
353 fn endpoint() -> McpEndpoint {
354 McpEndpoint {
355 url: "http://127.0.0.1:9/mcp".to_string(),
356 token: "tok".to_string(),
357 }
358 }
359
360 #[test]
361 fn mcp_endpoint_writes_a_config_file_and_passes_its_path() {
362 let directory = tempfile::tempdir().unwrap();
363 let action = AgentAction::answer_this("claude");
364 let plan = build_invocation(
365 &AgentProfile::claude_host(),
366 &action,
367 "p",
368 "sid",
369 Some(&endpoint()),
370 Some(directory.path()),
371 )
372 .unwrap();
373 let flag_position = plan
374 .run
375 .args
376 .iter()
377 .position(|arg| arg == "--mcp-config")
378 .unwrap();
379 let expected_path = directory.path().join("mcp-sid.json");
380 assert_eq!(
381 plan.run.args[flag_position + 1],
382 expected_path.to_string_lossy()
383 );
384 assert_eq!(plan.cleanup, vec![expected_path.clone()]);
385 assert!(!plan.run.args.iter().any(|arg| arg.contains("tok")));
386 let json: serde_json::Value =
387 serde_json::from_str(&std::fs::read_to_string(&expected_path).unwrap()).unwrap();
388 let server = &json["mcpServers"]["teams"];
389 assert_eq!(server["type"], "http");
390 assert_eq!(server["url"], "http://127.0.0.1:9/mcp");
391 assert_eq!(server["headers"]["Authorization"], "Bearer tok");
392 #[cfg(unix)]
393 assert_eq!(
394 std::os::unix::fs::PermissionsExt::mode(
395 &std::fs::metadata(&expected_path).unwrap().permissions()
396 ) & 0o777,
397 0o600
398 );
399 }
400
401 #[test]
402 fn mcp_flag_is_omitted_without_endpoint_or_directory() {
403 let directory = tempfile::tempdir().unwrap();
404 let action = AgentAction::answer_this("claude");
405 let profile = AgentProfile::claude_host();
406 let without_endpoint =
407 build_invocation(&profile, &action, "p", "sid", None, Some(directory.path())).unwrap();
408 assert!(
409 !without_endpoint
410 .run
411 .args
412 .iter()
413 .any(|arg| arg == "--mcp-config")
414 );
415 let without_directory =
416 build_invocation(&profile, &action, "p", "sid", Some(&endpoint()), None).unwrap();
417 assert!(
418 !without_directory
419 .run
420 .args
421 .iter()
422 .any(|arg| arg == "--mcp-config")
423 );
424 assert!(without_directory.cleanup.is_empty());
425 }
426
427 #[test]
428 fn copilot_takes_the_config_path_with_an_at_prefix() {
429 let directory = tempfile::tempdir().unwrap();
430 let action = AgentAction::answer_this("copilot");
431 let plan = build_invocation(
432 &AgentProfile::copilot_wsl(),
433 &action,
434 "p",
435 "sid",
436 Some(&endpoint()),
437 Some(directory.path()),
438 )
439 .unwrap();
440 let flag_position = plan
441 .run
442 .args
443 .iter()
444 .position(|arg| arg == "--additional-mcp-config")
445 .unwrap();
446 assert_eq!(
447 plan.run.args[flag_position + 1],
448 format!(
449 "@{}",
450 directory.path().join("mcp-sid.json").to_string_lossy()
451 )
452 );
453 }
454
455 #[test]
456 fn windows_paths_translate_to_the_wsl_mount() {
457 assert_eq!(
458 wsl_path(r"C:\Users\x\AppData\mcp-1.json"),
459 "/mnt/c/Users/x/AppData/mcp-1.json"
460 );
461 assert_eq!(wsl_path("D:/data/mcp.json"), "/mnt/d/data/mcp.json");
462 assert_eq!(wsl_path("/tmp/mcp.json"), "/tmp/mcp.json");
463 assert_eq!(wsl_path("relative/mcp.json"), "relative/mcp.json");
464 }
465
466 #[test]
467 fn agent_placeholder_renders_profile_id() {
468 let mut profile = AgentProfile::claude_host();
469 profile.command = "tool --agent {agent}".to_string();
470 let mut action = AgentAction::build_this("x");
471 action.extra_args = String::new();
472 let plan = build_invocation(&profile, &action, "p", "s", None, None).unwrap();
473 assert_eq!(plan.run.args, ["--agent", "claude-host"].map(String::from));
474 }
475
476 #[test]
477 fn empty_command_is_an_error() {
478 let mut profile = AgentProfile::claude_host();
479 profile.command = String::new();
480 let mut action = AgentAction::build_this("x");
481 action.extra_args = String::new();
482 assert_eq!(
483 build_invocation(&profile, &action, "p", "s", None, None),
484 Err(InvocationError::EmptyCommand)
485 );
486 }
487
488 #[test]
489 fn open_session_renders_cwd_and_session() {
490 let action = AgentAction::build_this("claude");
491 let invocation =
492 open_session_invocation(&AgentProfile::claude_wsl(), &action, "sid-4").unwrap();
493 assert_eq!(invocation.program, "wt.exe");
494 assert_eq!(
495 invocation.args,
496 ["wsl.exe", "--cd", "~", "-e", "claude", "--resume", "sid-4"].map(String::from)
497 );
498 }
499
500 #[test]
501 fn version_check_runs_the_first_token_in_the_same_environment() {
502 let host = version_check_invocation(&AgentProfile::claude_host());
503 assert_eq!(host.program, "claude");
504 assert_eq!(host.args, ["--version"].map(String::from));
505 let mut wsl_profile = AgentProfile::claude_wsl();
506 wsl_profile.environment = Environment::Wsl {
507 distro: Some("Ubuntu".to_string()),
508 };
509 let wsl = version_check_invocation(&wsl_profile);
510 assert_eq!(wsl.program, "wsl.exe");
511 assert_eq!(
512 wsl.args,
513 [
514 "-d",
515 "Ubuntu",
516 "-e",
517 "sh",
518 "-lc",
519 WSL_SCRIPT,
520 "sh",
521 "~",
522 "claude",
523 "--version"
524 ]
525 .map(String::from)
526 );
527 }
528 }
@@ -0,0 +1,528 @@
1use std::path::{Path, PathBuf};
2
3use crate::action::AgentAction;
4use crate::profile::{AgentProfile, Environment};
5use crate::template::{UnknownPlaceholder, Values, placeholders_in, render, split_command};
6
7const WSL_PROGRAM: &str = "wsl.exe";
8const WSL_SCRIPT: &str = r#"case "$1" in "~"*) dir="$HOME${1#\~}";; *) dir="$1";; esac; cd "$dir" && shift && exec "$@""#;
9
10#[derive(Clone, Debug, PartialEq, Eq)]
11pub struct Invocation {
12 pub program: String,
13 pub args: Vec<String>,
14 pub cwd: Option<PathBuf>,
15 pub stdin: Option<String>,
16}
17
18#[derive(Clone, Debug, PartialEq, Eq)]
19pub struct McpEndpoint {
20 pub url: String,
21 pub token: String,
22}
23
24#[derive(Clone, Debug, PartialEq, Eq)]
25pub struct RunPlan {
26 pub run: Invocation,
27 pub stop: Option<Invocation>,
28 pub cleanup: Vec<PathBuf>,
29}
30
31#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
32pub enum InvocationError {
33 #[error("the command is empty")]
34 EmptyCommand,
35 #[error(transparent)]
36 UnknownPlaceholder(#[from] UnknownPlaceholder),
37 #[error("cannot write the MCP config: {0}")]
38 McpConfig(String),
39}
40
41fn expand_home(path: &str) -> String {
42 let remainder = match path.strip_prefix('~') {
43 Some(remainder) if remainder.is_empty() || remainder.starts_with(['/', '\\']) => remainder,
44 _ => return path.to_string(),
45 };
46 match std::env::var("HOME").or_else(|_| std::env::var("USERPROFILE")) {
47 Ok(home) => format!("{home}{remainder}"),
48 Err(_) => path.to_string(),
49 }
50}
51
52fn mcp_config_json(endpoint: &McpEndpoint) -> String {
53 serde_json::json!({
54 "mcpServers": {
55 "teams": {
56 "type": "http",
57 "url": endpoint.url,
58 "headers": {"Authorization": format!("Bearer {}", endpoint.token)},
59 }
60 }
61 })
62 .to_string()
63}
64
65pub fn wsl_path(path: &str) -> String {
66 let mut characters = path.chars();
67 match (characters.next(), characters.next(), characters.next()) {
68 (Some(drive), Some(':'), Some('/' | '\\')) if drive.is_ascii_alphabetic() => format!(
69 "/mnt/{}/{}",
70 drive.to_ascii_lowercase(),
71 path[3..].replace('\\', "/")
72 ),
73 _ => path.to_string(),
74 }
75}
76
77fn write_mcp_config(
78 directory: &Path,
79 session_id: &str,
80 endpoint: &McpEndpoint,
81) -> Result<PathBuf, InvocationError> {
82 let to_error = |error: std::io::Error| InvocationError::McpConfig(error.to_string());
83 std::fs::create_dir_all(directory).map_err(to_error)?;
84 let path = directory.join(format!("mcp-{session_id}.json"));
85 let mut options = std::fs::OpenOptions::new();
86 options.write(true).create(true).truncate(true);
87 #[cfg(unix)]
88 std::os::unix::fs::OpenOptionsExt::mode(&mut options, 0o600);
89 let mut file = options.open(&path).map_err(to_error)?;
90 std::io::Write::write_all(&mut file, mcp_config_json(endpoint).as_bytes()).map_err(to_error)?;
91 Ok(path)
92}
93
94fn mcp_config_argument(flag: &str, path: &Path, environment: &Environment) -> String {
95 let text = path.to_string_lossy();
96 let text = match environment {
97 Environment::Wsl { .. } if cfg!(windows) => wsl_path(&text),
98 _ => text.into_owned(),
99 };
100 if flag.ends_with("additional-mcp-config") {
101 format!("@{text}")
102 } else {
103 text
104 }
105}
106
107fn wsl_prefix(environment: &Environment) -> Vec<String> {
108 match environment {
109 Environment::Wsl {
110 distro: Some(distro),
111 } => vec!["-d".to_string(), distro.clone()],
112 _ => Vec::new(),
113 }
114}
115
116fn working_directory(profile: &AgentProfile, action: &AgentAction) -> String {
117 match profile.environment {
118 Environment::Host => expand_home(&action.working_dir),
119 Environment::Wsl { .. } => action.working_dir.clone(),
120 }
121}
122
123pub fn build_invocation(
124 profile: &AgentProfile,
125 action: &AgentAction,
126 prompt: &str,
127 session_id: &str,
128 mcp: Option<&McpEndpoint>,
129 mcp_config_directory: Option<&Path>,
130) -> Result<RunPlan, InvocationError> {
131 let working_dir = working_directory(profile, action);
132 let values = Values {
133 session_id: session_id.to_string(),
134 agent: profile.id.clone(),
135 prompt: prompt.to_string(),
136 cwd: working_dir.clone(),
137 ..Values::default()
138 };
139 let raw_tokens: Vec<String> = split_command(&profile.command)
140 .into_iter()
141 .chain(split_command(&action.extra_args))
142 .collect();
143 if raw_tokens.is_empty() {
144 return Err(InvocationError::EmptyCommand);
145 }
146 let uses_prompt_placeholder = raw_tokens
147 .iter()
148 .any(|token| placeholders_in(token).iter().any(|name| name == "prompt"));
149 let mut tokens = raw_tokens
150 .iter()
151 .map(|token| render(token, &values))
152 .collect::<Result<Vec<_>, _>>()?;
153 let mut cleanup = Vec::new();
154 if let Some(endpoint) = mcp
155 && let Some(directory) = mcp_config_directory
156 && !profile.mcp_config_flag.is_empty()
157 {
158 let path = write_mcp_config(directory, session_id, endpoint)?;
159 tokens.push(profile.mcp_config_flag.clone());
160 tokens.push(mcp_config_argument(
161 &profile.mcp_config_flag,
162 &path,
163 &profile.environment,
164 ));
165 cleanup.push(path);
166 }
167 let stdin = (!uses_prompt_placeholder).then(|| prompt.to_string());
168
169 match &profile.environment {
170 Environment::Host => {
171 let mut tokens = tokens.into_iter();
172 let program = tokens.next().ok_or(InvocationError::EmptyCommand)?;
173 Ok(RunPlan {
174 run: Invocation {
175 program,
176 args: tokens.collect(),
177 cwd: Some(PathBuf::from(working_dir)),
178 stdin,
179 },
180 stop: None,
181 cleanup,
182 })
183 }
184 Environment::Wsl { .. } => {
185 let mut args = wsl_prefix(&profile.environment);
186 let mut stop_args = args.clone();
187 args.extend(
188 ["-e", "sh", "-lc", WSL_SCRIPT, "sh"]
189 .into_iter()
190 .map(String::from),
191 );
192 args.push(working_dir);
193 args.extend(tokens);
194 stop_args.extend(["-e", "pkill", "-f", session_id].map(String::from));
195 Ok(RunPlan {
196 run: Invocation {
197 program: WSL_PROGRAM.to_string(),
198 args,
199 cwd: None,
200 stdin,
201 },
202 stop: Some(Invocation {
203 program: WSL_PROGRAM.to_string(),
204 args: stop_args,
205 cwd: None,
206 stdin: None,
207 }),
208 cleanup,
209 })
210 }
211 }
212}
213
214pub fn open_session_invocation(
215 profile: &AgentProfile,
216 action: &AgentAction,
217 session_id: &str,
218) -> Result<Invocation, InvocationError> {
219 let values = Values {
220 session_id: session_id.to_string(),
221 agent: profile.id.clone(),
222 cwd: working_directory(profile, action),
223 ..Values::default()
224 };
225 let mut tokens = split_command(&profile.open_session_command)
226 .iter()
227 .map(|token| render(token, &values))
228 .collect::<Result<Vec<_>, _>>()?
229 .into_iter();
230 let program = tokens.next().ok_or(InvocationError::EmptyCommand)?;
231 Ok(Invocation {
232 program,
233 args: tokens.collect(),
234 cwd: None,
235 stdin: None,
236 })
237}
238
239pub fn version_check_invocation(profile: &AgentProfile) -> Invocation {
240 let program = split_command(&profile.command)
241 .into_iter()
242 .next()
243 .unwrap_or_default();
244 match &profile.environment {
245 Environment::Host => Invocation {
246 program,
247 args: vec!["--version".to_string()],
248 cwd: None,
249 stdin: None,
250 },
251 Environment::Wsl { .. } => {
252 let mut args = wsl_prefix(&profile.environment);
253 args.extend(
254 ["-e", "sh", "-lc", WSL_SCRIPT, "sh", "~"]
255 .into_iter()
256 .map(String::from),
257 );
258 args.push(program);
259 args.push("--version".to_string());
260 Invocation {
261 program: WSL_PROGRAM.to_string(),
262 args,
263 cwd: None,
264 stdin: None,
265 }
266 }
267 }
268}
269
270#[cfg(test)]
271mod tests {
272 use super::*;
273
274 #[test]
275 fn wsl_invocation_has_exact_args() {
276 let mut profile = AgentProfile::claude_wsl();
277 profile.environment = Environment::Wsl {
278 distro: Some("Ubuntu".to_string()),
279 };
280 let action = AgentAction::answer_this("claude");
281 let plan = build_invocation(&profile, &action, "hi there", "sid-1", None, None).unwrap();
282 let expected_args: Vec<String> = [
283 "-d",
284 "Ubuntu",
285 "-e",
286 "sh",
287 "-lc",
288 WSL_SCRIPT,
289 "sh",
290 "~",
291 "claude",
292 "-p",
293 "--output-format",
294 "stream-json",
295 "--verbose",
296 "--session-id",
297 "sid-1",
298 "--allowedTools",
299 "WebSearch,WebFetch,Read,Grep,Glob,mcp__teams",
300 ]
301 .map(String::from)
302 .to_vec();
303 assert_eq!(plan.run.program, "wsl.exe");
304 assert_eq!(plan.run.args, expected_args);
305 assert_eq!(plan.run.cwd, None);
306 assert_eq!(plan.run.stdin.as_deref(), Some("hi there"));
307 let stop = plan.stop.unwrap();
308 assert_eq!(stop.program, "wsl.exe");
309 assert_eq!(
310 stop.args,
311 ["-d", "Ubuntu", "-e", "pkill", "-f", "sid-1"].map(String::from)
312 );
313 }
314
315 #[test]
316 fn prompt_placeholder_goes_in_args_without_stdin() {
317 let profile = AgentProfile::copilot_wsl();
318 let action = AgentAction::answer_this("copilot");
319 let plan = build_invocation(&profile, &action, "a b\nc", "sid-2", None, None).unwrap();
320 assert_eq!(plan.run.stdin, None);
321 assert_eq!(plan.run.args[..2], ["-e".to_string(), "sh".to_string()]);
322 let prompt_position = plan.run.args.iter().position(|arg| arg == "-p").unwrap() + 1;
323 assert_eq!(plan.run.args[prompt_position], "a b\nc");
324 }
325
326 #[test]
327 fn host_invocation_expands_home() {
328 let mut action = AgentAction::build_this("claude-host");
329 action.working_dir = "~/work".to_string();
330 let plan = build_invocation(
331 &AgentProfile::claude_host(),
332 &action,
333 "p",
334 "sid-3",
335 None,
336 None,
337 )
338 .unwrap();
339 let home = std::env::var("HOME")
340 .or_else(|_| std::env::var("USERPROFILE"))
341 .unwrap();
342 assert_eq!(plan.run.program, "claude");
343 assert_eq!(plan.run.cwd, Some(PathBuf::from(format!("{home}/work"))));
344 assert_eq!(plan.run.stdin.as_deref(), Some("p"));
345 assert!(
346 plan.run
347 .args
348 .ends_with(&["--permission-mode".to_string(), "auto".to_string()])
349 );
350 assert_eq!(plan.stop, None);
351 }
352
353 fn endpoint() -> McpEndpoint {
354 McpEndpoint {
355 url: "http://127.0.0.1:9/mcp".to_string(),
356 token: "tok".to_string(),
357 }
358 }
359
360 #[test]
361 fn mcp_endpoint_writes_a_config_file_and_passes_its_path() {
362 let directory = tempfile::tempdir().unwrap();
363 let action = AgentAction::answer_this("claude");
364 let plan = build_invocation(
365 &AgentProfile::claude_host(),
366 &action,
367 "p",
368 "sid",
369 Some(&endpoint()),
370 Some(directory.path()),
371 )
372 .unwrap();
373 let flag_position = plan
374 .run
375 .args
376 .iter()
377 .position(|arg| arg == "--mcp-config")
378 .unwrap();
379 let expected_path = directory.path().join("mcp-sid.json");
380 assert_eq!(
381 plan.run.args[flag_position + 1],
382 expected_path.to_string_lossy()
383 );
384 assert_eq!(plan.cleanup, vec![expected_path.clone()]);
385 assert!(!plan.run.args.iter().any(|arg| arg.contains("tok")));
386 let json: serde_json::Value =
387 serde_json::from_str(&std::fs::read_to_string(&expected_path).unwrap()).unwrap();
388 let server = &json["mcpServers"]["teams"];
389 assert_eq!(server["type"], "http");
390 assert_eq!(server["url"], "http://127.0.0.1:9/mcp");
391 assert_eq!(server["headers"]["Authorization"], "Bearer tok");
392 #[cfg(unix)]
393 assert_eq!(
394 std::os::unix::fs::PermissionsExt::mode(
395 &std::fs::metadata(&expected_path).unwrap().permissions()
396 ) & 0o777,
397 0o600
398 );
399 }
400
401 #[test]
402 fn mcp_flag_is_omitted_without_endpoint_or_directory() {
403 let directory = tempfile::tempdir().unwrap();
404 let action = AgentAction::answer_this("claude");
405 let profile = AgentProfile::claude_host();
406 let without_endpoint =
407 build_invocation(&profile, &action, "p", "sid", None, Some(directory.path())).unwrap();
408 assert!(
409 !without_endpoint
410 .run
411 .args
412 .iter()
413 .any(|arg| arg == "--mcp-config")
414 );
415 let without_directory =
416 build_invocation(&profile, &action, "p", "sid", Some(&endpoint()), None).unwrap();
417 assert!(
418 !without_directory
419 .run
420 .args
421 .iter()
422 .any(|arg| arg == "--mcp-config")
423 );
424 assert!(without_directory.cleanup.is_empty());
425 }
426
427 #[test]
428 fn copilot_takes_the_config_path_with_an_at_prefix() {
429 let directory = tempfile::tempdir().unwrap();
430 let action = AgentAction::answer_this("copilot");
431 let plan = build_invocation(
432 &AgentProfile::copilot_wsl(),
433 &action,
434 "p",
435 "sid",
436 Some(&endpoint()),
437 Some(directory.path()),
438 )
439 .unwrap();
440 let flag_position = plan
441 .run
442 .args
443 .iter()
444 .position(|arg| arg == "--additional-mcp-config")
445 .unwrap();
446 assert_eq!(
447 plan.run.args[flag_position + 1],
448 format!(
449 "@{}",
450 directory.path().join("mcp-sid.json").to_string_lossy()
451 )
452 );
453 }
454
455 #[test]
456 fn windows_paths_translate_to_the_wsl_mount() {
457 assert_eq!(
458 wsl_path(r"C:\Users\x\AppData\mcp-1.json"),
459 "/mnt/c/Users/x/AppData/mcp-1.json"
460 );
461 assert_eq!(wsl_path("D:/data/mcp.json"), "/mnt/d/data/mcp.json");
462 assert_eq!(wsl_path("/tmp/mcp.json"), "/tmp/mcp.json");
463 assert_eq!(wsl_path("relative/mcp.json"), "relative/mcp.json");
464 }
465
466 #[test]
467 fn agent_placeholder_renders_profile_id() {
468 let mut profile = AgentProfile::claude_host();
469 profile.command = "tool --agent {agent}".to_string();
470 let mut action = AgentAction::build_this("x");
471 action.extra_args = String::new();
472 let plan = build_invocation(&profile, &action, "p", "s", None, None).unwrap();
473 assert_eq!(plan.run.args, ["--agent", "claude-host"].map(String::from));
474 }
475
476 #[test]
477 fn empty_command_is_an_error() {
478 let mut profile = AgentProfile::claude_host();
479 profile.command = String::new();
480 let mut action = AgentAction::build_this("x");
481 action.extra_args = String::new();
482 assert_eq!(
483 build_invocation(&profile, &action, "p", "s", None, None),
484 Err(InvocationError::EmptyCommand)
485 );
486 }
487
488 #[test]
489 fn open_session_renders_cwd_and_session() {
490 let action = AgentAction::build_this("claude");
491 let invocation =
492 open_session_invocation(&AgentProfile::claude_wsl(), &action, "sid-4").unwrap();
493 assert_eq!(invocation.program, "wt.exe");
494 assert_eq!(
495 invocation.args,
496 ["wsl.exe", "--cd", "~", "-e", "claude", "--resume", "sid-4"].map(String::from)
497 );
498 }
499
500 #[test]
501 fn version_check_runs_the_first_token_in_the_same_environment() {
502 let host = version_check_invocation(&AgentProfile::claude_host());
503 assert_eq!(host.program, "claude");
504 assert_eq!(host.args, ["--version"].map(String::from));
505 let mut wsl_profile = AgentProfile::claude_wsl();
506 wsl_profile.environment = Environment::Wsl {
507 distro: Some("Ubuntu".to_string()),
508 };
509 let wsl = version_check_invocation(&wsl_profile);
510 assert_eq!(wsl.program, "wsl.exe");
511 assert_eq!(
512 wsl.args,
513 [
514 "-d",
515 "Ubuntu",
516 "-e",
517 "sh",
518 "-lc",
519 WSL_SCRIPT,
520 "sh",
521 "~",
522 "claude",
523 "--version"
524 ]
525 .map(String::from)
526 );
527 }
528}
crates/agents/src/lib.rs added +24 −0
@@ -0,0 +1,24 @@
1 mod action;
2 mod context;
3 mod invocation;
4 mod parse;
5 mod profile;
6 mod runner;
7 mod settings;
8 mod template;
9
10 pub use action::AgentAction;
11 pub use context::{MessageContext, ThreadMessage, build_prompt};
12 pub use invocation::{
13 Invocation, InvocationError, McpEndpoint, RunPlan, build_invocation, open_session_invocation,
14 version_check_invocation, wsl_path,
15 };
16 pub use parse::{OutputParser, RunEvent, parse_line};
17 pub use profile::{AgentProfile, Environment, OutputFormat};
18 pub use runner::{RunOutcome, RunStatus, RunUpdate, probe, run};
19 pub use settings::{AgentSettings, SETTINGS_KEY, SettingsProblem};
20 pub use template::{UnknownPlaceholder, Values, placeholders_in, render, split_command};
21
22 pub fn new_session_id() -> String {
23 uuid::Uuid::new_v4().to_string()
24 }
@@ -0,0 +1,24 @@
1mod action;
2mod context;
3mod invocation;
4mod parse;
5mod profile;
6mod runner;
7mod settings;
8mod template;
9
10pub use action::AgentAction;
11pub use context::{MessageContext, ThreadMessage, build_prompt};
12pub use invocation::{
13 Invocation, InvocationError, McpEndpoint, RunPlan, build_invocation, open_session_invocation,
14 version_check_invocation, wsl_path,
15};
16pub use parse::{OutputParser, RunEvent, parse_line};
17pub use profile::{AgentProfile, Environment, OutputFormat};
18pub use runner::{RunOutcome, RunStatus, RunUpdate, probe, run};
19pub use settings::{AgentSettings, SETTINGS_KEY, SettingsProblem};
20pub use template::{UnknownPlaceholder, Values, placeholders_in, render, split_command};
21
22pub fn new_session_id() -> String {
23 uuid::Uuid::new_v4().to_string()
24}
crates/agents/src/parse/claude.rs added +118 −0
@@ -0,0 +1,118 @@
1 use std::path::Path;
2
3 use serde_json::Value;
4
5 use super::{RunEvent, truncate};
6
7 const COMMAND_LIMIT: usize = 60;
8
9 pub(super) fn parse_line(line: &str) -> Vec<RunEvent> {
10 let Ok(value) = serde_json::from_str::<Value>(line) else {
11 return Vec::new();
12 };
13 match value.get("type").and_then(Value::as_str) {
14 Some("system") if value.get("subtype").and_then(Value::as_str) == Some("init") => {
15 session_id_events(&value)
16 }
17 Some("assistant") => assistant_events(&value),
18 Some("result") => result_events(&value),
19 _ => Vec::new(),
20 }
21 }
22
23 fn session_id_events(value: &Value) -> Vec<RunEvent> {
24 value
25 .get("session_id")
26 .and_then(Value::as_str)
27 .map(|session_id| vec![RunEvent::SessionId(session_id.to_string())])
28 .unwrap_or_default()
29 }
30
31 fn assistant_events(value: &Value) -> Vec<RunEvent> {
32 let Some(blocks) = value.pointer("/message/content").and_then(Value::as_array) else {
33 return Vec::new();
34 };
35 blocks
36 .iter()
37 .filter_map(|block| match block.get("type").and_then(Value::as_str) {
38 Some("tool_use") => Some(RunEvent::Step(tool_label(block))),
39 Some("text") => block
40 .get("text")
41 .and_then(Value::as_str)
42 .filter(|text| !text.trim().is_empty())
43 .map(|text| RunEvent::Text(text.to_string())),
44 _ => None,
45 })
46 .collect()
47 }
48
49 fn result_events(value: &Value) -> Vec<RunEvent> {
50 let mut events = session_id_events(value);
51 let subtype = value.get("subtype").and_then(Value::as_str).unwrap_or("");
52 let is_error = value
53 .get("is_error")
54 .and_then(Value::as_bool)
55 .unwrap_or(false);
56 let result = value.get("result").and_then(Value::as_str);
57 if subtype == "success" && !is_error {
58 events.push(RunEvent::Final(result.unwrap_or_default().to_string()));
59 } else {
60 let message = result.filter(|text| !text.is_empty()).unwrap_or(subtype);
61 events.push(RunEvent::Failed(message.to_string()));
62 }
63 events
64 }
65
66 fn input_text<'a>(input: &'a Value, key: &str) -> &'a str {
67 input.get(key).and_then(Value::as_str).unwrap_or("")
68 }
69
70 fn file_name(path: &str) -> String {
71 Path::new(path)
72 .file_name()
73 .map(|name| name.to_string_lossy().into_owned())
74 .unwrap_or_else(|| path.to_string())
75 }
76
77 fn host_of(url: &str) -> String {
78 let without_scheme = url.split_once("://").map_or(url, |(_, rest)| rest);
79 without_scheme
80 .split(['/', ':', '?', '#'])
81 .next()
82 .unwrap_or(without_scheme)
83 .to_string()
84 }
85
86 fn tool_label(block: &Value) -> String {
87 let name = block.get("name").and_then(Value::as_str).unwrap_or("tool");
88 let null = Value::Null;
89 let input = block.get("input").unwrap_or(&null);
90 match name {
91 "Read" => format!("Reading {}", file_name(input_text(input, "file_path"))),
92 "Edit" | "Write" | "MultiEdit" | "NotebookEdit" => {
93 let path = match input_text(input, "file_path") {
94 "" => input_text(input, "notebook_path"),
95 path => path,
96 };
97 format!("Editing {}", file_name(path))
98 }
99 "Bash" => {
100 let description = input_text(input, "description");
101 let detail = if description.is_empty() {
102 truncate(input_text(input, "command"), COMMAND_LIMIT)
103 } else {
104 description.to_string()
105 };
106 format!("Running {detail}")
107 }
108 "Grep" => format!("Searching \"{}\"", input_text(input, "pattern")),
109 "Glob" => format!("Finding {}", input_text(input, "pattern")),
110 "WebSearch" => format!("Searching web: {}", input_text(input, "query")),
111 "WebFetch" => format!("Reading {}", host_of(input_text(input, "url"))),
112 "Task" | "Agent" => "Running subagent".to_string(),
113 "TodoWrite" => "Planning".to_string(),
114 "mcp__teams__propose_message" => "Proposing reply".to_string(),
115 other if other.starts_with("mcp__teams__") => "Reading Teams".to_string(),
116 other => other.to_string(),
117 }
118 }
@@ -0,0 +1,118 @@
1use std::path::Path;
2
3use serde_json::Value;
4
5use super::{RunEvent, truncate};
6
7const COMMAND_LIMIT: usize = 60;
8
9pub(super) fn parse_line(line: &str) -> Vec<RunEvent> {
10 let Ok(value) = serde_json::from_str::<Value>(line) else {
11 return Vec::new();
12 };
13 match value.get("type").and_then(Value::as_str) {
14 Some("system") if value.get("subtype").and_then(Value::as_str) == Some("init") => {
15 session_id_events(&value)
16 }
17 Some("assistant") => assistant_events(&value),
18 Some("result") => result_events(&value),
19 _ => Vec::new(),
20 }
21}
22
23fn session_id_events(value: &Value) -> Vec<RunEvent> {
24 value
25 .get("session_id")
26 .and_then(Value::as_str)
27 .map(|session_id| vec![RunEvent::SessionId(session_id.to_string())])
28 .unwrap_or_default()
29}
30
31fn assistant_events(value: &Value) -> Vec<RunEvent> {
32 let Some(blocks) = value.pointer("/message/content").and_then(Value::as_array) else {
33 return Vec::new();
34 };
35 blocks
36 .iter()
37 .filter_map(|block| match block.get("type").and_then(Value::as_str) {
38 Some("tool_use") => Some(RunEvent::Step(tool_label(block))),
39 Some("text") => block
40 .get("text")
41 .and_then(Value::as_str)
42 .filter(|text| !text.trim().is_empty())
43 .map(|text| RunEvent::Text(text.to_string())),
44 _ => None,
45 })
46 .collect()
47}
48
49fn result_events(value: &Value) -> Vec<RunEvent> {
50 let mut events = session_id_events(value);
51 let subtype = value.get("subtype").and_then(Value::as_str).unwrap_or("");
52 let is_error = value
53 .get("is_error")
54 .and_then(Value::as_bool)
55 .unwrap_or(false);
56 let result = value.get("result").and_then(Value::as_str);
57 if subtype == "success" && !is_error {
58 events.push(RunEvent::Final(result.unwrap_or_default().to_string()));
59 } else {
60 let message = result.filter(|text| !text.is_empty()).unwrap_or(subtype);
61 events.push(RunEvent::Failed(message.to_string()));
62 }
63 events
64}
65
66fn input_text<'a>(input: &'a Value, key: &str) -> &'a str {
67 input.get(key).and_then(Value::as_str).unwrap_or("")
68}
69
70fn file_name(path: &str) -> String {
71 Path::new(path)
72 .file_name()
73 .map(|name| name.to_string_lossy().into_owned())
74 .unwrap_or_else(|| path.to_string())
75}
76
77fn host_of(url: &str) -> String {
78 let without_scheme = url.split_once("://").map_or(url, |(_, rest)| rest);
79 without_scheme
80 .split(['/', ':', '?', '#'])
81 .next()
82 .unwrap_or(without_scheme)
83 .to_string()
84}
85
86fn tool_label(block: &Value) -> String {
87 let name = block.get("name").and_then(Value::as_str).unwrap_or("tool");
88 let null = Value::Null;
89 let input = block.get("input").unwrap_or(&null);
90 match name {
91 "Read" => format!("Reading {}", file_name(input_text(input, "file_path"))),
92 "Edit" | "Write" | "MultiEdit" | "NotebookEdit" => {
93 let path = match input_text(input, "file_path") {
94 "" => input_text(input, "notebook_path"),
95 path => path,
96 };
97 format!("Editing {}", file_name(path))
98 }
99 "Bash" => {
100 let description = input_text(input, "description");
101 let detail = if description.is_empty() {
102 truncate(input_text(input, "command"), COMMAND_LIMIT)
103 } else {
104 description.to_string()
105 };
106 format!("Running {detail}")
107 }
108 "Grep" => format!("Searching \"{}\"", input_text(input, "pattern")),
109 "Glob" => format!("Finding {}", input_text(input, "pattern")),
110 "WebSearch" => format!("Searching web: {}", input_text(input, "query")),
111 "WebFetch" => format!("Reading {}", host_of(input_text(input, "url"))),
112 "Task" | "Agent" => "Running subagent".to_string(),
113 "TodoWrite" => "Planning".to_string(),
114 "mcp__teams__propose_message" => "Proposing reply".to_string(),
115 other if other.starts_with("mcp__teams__") => "Reading Teams".to_string(),
116 other => other.to_string(),
117 }
118}
crates/agents/src/parse/copilot.rs added +66 −0
@@ -0,0 +1,66 @@
1 use serde_json::Value;
2
3 use super::{RunEvent, truncate};
4
5 const DETAIL_LIMIT: usize = 60;
6
7 pub(super) fn parse_line(line: &str, last_text: &mut Option<String>) -> Vec<RunEvent> {
8 let Ok(value) = serde_json::from_str::<Value>(line) else {
9 return Vec::new();
10 };
11 match value.get("type").and_then(Value::as_str) {
12 Some("tool.execution_start") => vec![RunEvent::Step(step_label(&value))],
13 Some("assistant.message") => assistant_events(&value, last_text),
14 Some("result") => result_events(&value, last_text),
15 _ => Vec::new(),
16 }
17 }
18
19 fn assistant_events(value: &Value, last_text: &mut Option<String>) -> Vec<RunEvent> {
20 let content = value
21 .pointer("/data/content")
22 .and_then(Value::as_str)
23 .unwrap_or("");
24 if content.trim().is_empty() {
25 return Vec::new();
26 }
27 *last_text = Some(content.to_string());
28 vec![RunEvent::Text(content.to_string())]
29 }
30
31 fn result_events(value: &Value, last_text: &Option<String>) -> Vec<RunEvent> {
32 let mut events = Vec::new();
33 if let Some(session_id) = value.get("sessionId").and_then(Value::as_str) {
34 events.push(RunEvent::SessionId(session_id.to_string()));
35 }
36 let exit_code = value.get("exitCode").and_then(Value::as_i64).unwrap_or(0);
37 match last_text {
38 Some(text) if exit_code == 0 => events.push(RunEvent::Final(text.clone())),
39 _ if exit_code != 0 => events.push(RunEvent::Failed(format!(
40 "agent exited with code {exit_code}"
41 ))),
42 _ => events.push(RunEvent::Failed("agent returned no answer".to_string())),
43 }
44 events
45 }
46
47 fn step_label(value: &Value) -> String {
48 let title = value
49 .pointer("/data/toolTitle")
50 .and_then(Value::as_str)
51 .or_else(|| value.pointer("/data/toolName").and_then(Value::as_str))
52 .unwrap_or("Tool");
53 match tool_detail(value.pointer("/data/arguments")) {
54 Some(detail) => format!("{title}: {}", truncate(&detail, DETAIL_LIMIT)),
55 None => title.to_string(),
56 }
57 }
58
59 fn tool_detail(arguments: Option<&Value>) -> Option<String> {
60 let arguments = arguments?.as_object()?;
61 ["path", "command"]
62 .iter()
63 .find_map(|key| arguments.get(*key).and_then(Value::as_str))
64 .or_else(|| arguments.values().find_map(Value::as_str))
65 .map(str::to_string)
66 }
@@ -0,0 +1,66 @@
1use serde_json::Value;
2
3use super::{RunEvent, truncate};
4
5const DETAIL_LIMIT: usize = 60;
6
7pub(super) fn parse_line(line: &str, last_text: &mut Option<String>) -> Vec<RunEvent> {
8 let Ok(value) = serde_json::from_str::<Value>(line) else {
9 return Vec::new();
10 };
11 match value.get("type").and_then(Value::as_str) {
12 Some("tool.execution_start") => vec![RunEvent::Step(step_label(&value))],
13 Some("assistant.message") => assistant_events(&value, last_text),
14 Some("result") => result_events(&value, last_text),
15 _ => Vec::new(),
16 }
17}
18
19fn assistant_events(value: &Value, last_text: &mut Option<String>) -> Vec<RunEvent> {
20 let content = value
21 .pointer("/data/content")
22 .and_then(Value::as_str)
23 .unwrap_or("");
24 if content.trim().is_empty() {
25 return Vec::new();
26 }
27 *last_text = Some(content.to_string());
28 vec![RunEvent::Text(content.to_string())]
29}
30
31fn result_events(value: &Value, last_text: &Option<String>) -> Vec<RunEvent> {
32 let mut events = Vec::new();
33 if let Some(session_id) = value.get("sessionId").and_then(Value::as_str) {
34 events.push(RunEvent::SessionId(session_id.to_string()));
35 }
36 let exit_code = value.get("exitCode").and_then(Value::as_i64).unwrap_or(0);
37 match last_text {
38 Some(text) if exit_code == 0 => events.push(RunEvent::Final(text.clone())),
39 _ if exit_code != 0 => events.push(RunEvent::Failed(format!(
40 "agent exited with code {exit_code}"
41 ))),
42 _ => events.push(RunEvent::Failed("agent returned no answer".to_string())),
43 }
44 events
45}
46
47fn step_label(value: &Value) -> String {
48 let title = value
49 .pointer("/data/toolTitle")
50 .and_then(Value::as_str)
51 .or_else(|| value.pointer("/data/toolName").and_then(Value::as_str))
52 .unwrap_or("Tool");
53 match tool_detail(value.pointer("/data/arguments")) {
54 Some(detail) => format!("{title}: {}", truncate(&detail, DETAIL_LIMIT)),
55 None => title.to_string(),
56 }
57}
58
59fn tool_detail(arguments: Option<&Value>) -> Option<String> {
60 let arguments = arguments?.as_object()?;
61 ["path", "command"]
62 .iter()
63 .find_map(|key| arguments.get(*key).and_then(Value::as_str))
64 .or_else(|| arguments.values().find_map(Value::as_str))
65 .map(str::to_string)
66}
crates/agents/src/parse/mod.rs added +69 −0
@@ -0,0 +1,69 @@
1 mod claude;
2 mod copilot;
3 mod text;
4
5 use crate::profile::OutputFormat;
6
7 #[derive(Clone, Debug, PartialEq, Eq)]
8 pub enum RunEvent {
9 Step(String),
10 Text(String),
11 Final(String),
12 SessionId(String),
13 Failed(String),
14 }
15
16 #[derive(Debug)]
17 pub struct OutputParser {
18 format: OutputFormat,
19 last_text: Option<String>,
20 all_output: String,
21 }
22
23 impl OutputParser {
24 pub fn new(format: OutputFormat) -> Self {
25 Self {
26 format,
27 last_text: None,
28 all_output: String::new(),
29 }
30 }
31
32 pub fn feed(&mut self, line: &str) -> Vec<RunEvent> {
33 match self.format {
34 OutputFormat::ClaudeStreamJson => claude::parse_line(line),
35 OutputFormat::CopilotJsonl => copilot::parse_line(line, &mut self.last_text),
36 OutputFormat::Text => text::parse_line(line, &mut self.all_output),
37 }
38 }
39
40 pub fn finish(&mut self) -> Vec<RunEvent> {
41 match self.format {
42 OutputFormat::Text => text::finish(&self.all_output),
43 OutputFormat::ClaudeStreamJson | OutputFormat::CopilotJsonl => Vec::new(),
44 }
45 }
46 }
47
48 pub fn parse_line(format: OutputFormat, line: &str) -> Vec<RunEvent> {
49 OutputParser::new(format).feed(line)
50 }
51
52 pub(crate) fn truncate(text: &str, max_chars: usize) -> String {
53 match text.char_indices().nth(max_chars) {
54 Some((byte_index, _)) => format!("{}...", &text[..byte_index]),
55 None => text.to_string(),
56 }
57 }
58
59 #[cfg(test)]
60 mod tests {
61 use super::*;
62
63 #[test]
64 fn truncate_respects_char_boundaries() {
65 assert_eq!(truncate("abc", 3), "abc");
66 assert_eq!(truncate("abcd", 3), "abc...");
67 assert_eq!(truncate("äöüß", 2), "äö...");
68 }
69 }
@@ -0,0 +1,69 @@
1mod claude;
2mod copilot;
3mod text;
4
5use crate::profile::OutputFormat;
6
7#[derive(Clone, Debug, PartialEq, Eq)]
8pub enum RunEvent {
9 Step(String),
10 Text(String),
11 Final(String),
12 SessionId(String),
13 Failed(String),
14}
15
16#[derive(Debug)]
17pub struct OutputParser {
18 format: OutputFormat,
19 last_text: Option<String>,
20 all_output: String,
21}
22
23impl OutputParser {
24 pub fn new(format: OutputFormat) -> Self {
25 Self {
26 format,
27 last_text: None,
28 all_output: String::new(),
29 }
30 }
31
32 pub fn feed(&mut self, line: &str) -> Vec<RunEvent> {
33 match self.format {
34 OutputFormat::ClaudeStreamJson => claude::parse_line(line),
35 OutputFormat::CopilotJsonl => copilot::parse_line(line, &mut self.last_text),
36 OutputFormat::Text => text::parse_line(line, &mut self.all_output),
37 }
38 }
39
40 pub fn finish(&mut self) -> Vec<RunEvent> {
41 match self.format {
42 OutputFormat::Text => text::finish(&self.all_output),
43 OutputFormat::ClaudeStreamJson | OutputFormat::CopilotJsonl => Vec::new(),
44 }
45 }
46}
47
48pub fn parse_line(format: OutputFormat, line: &str) -> Vec<RunEvent> {
49 OutputParser::new(format).feed(line)
50}
51
52pub(crate) fn truncate(text: &str, max_chars: usize) -> String {
53 match text.char_indices().nth(max_chars) {
54 Some((byte_index, _)) => format!("{}...", &text[..byte_index]),
55 None => text.to_string(),
56 }
57}
58
59#[cfg(test)]
60mod tests {
61 use super::*;
62
63 #[test]
64 fn truncate_respects_char_boundaries() {
65 assert_eq!(truncate("abc", 3), "abc");
66 assert_eq!(truncate("abcd", 3), "abc...");
67 assert_eq!(truncate("äöüß", 2), "äö...");
68 }
69}
crates/agents/src/parse/text.rs added +17 −0
@@ -0,0 +1,17 @@
1 use super::{RunEvent, truncate};
2
3 const STEP_LIMIT: usize = 80;
4
5 pub(super) fn parse_line(line: &str, all_output: &mut String) -> Vec<RunEvent> {
6 all_output.push_str(line);
7 all_output.push('\n');
8 let trimmed = line.trim();
9 if trimmed.is_empty() {
10 return Vec::new();
11 }
12 vec![RunEvent::Step(truncate(trimmed, STEP_LIMIT))]
13 }
14
15 pub(super) fn finish(all_output: &str) -> Vec<RunEvent> {
16 vec![RunEvent::Final(all_output.trim().to_string())]
17 }
@@ -0,0 +1,17 @@
1use super::{RunEvent, truncate};
2
3const STEP_LIMIT: usize = 80;
4
5pub(super) fn parse_line(line: &str, all_output: &mut String) -> Vec<RunEvent> {
6 all_output.push_str(line);
7 all_output.push('\n');
8 let trimmed = line.trim();
9 if trimmed.is_empty() {
10 return Vec::new();
11 }
12 vec![RunEvent::Step(truncate(trimmed, STEP_LIMIT))]
13}
14
15pub(super) fn finish(all_output: &str) -> Vec<RunEvent> {
16 vec![RunEvent::Final(all_output.trim().to_string())]
17}
crates/agents/src/profile.rs added +74 −0
@@ -0,0 +1,74 @@
1 use serde::{Deserialize, Serialize};
2
3 const CLAUDE_COMMAND: &str =
4 "claude -p --output-format stream-json --verbose --session-id {session_id}";
5 const COPILOT_COMMAND: &str = "copilot -p {prompt} --output-format json --session-id {session_id}";
6
7 #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
8 pub enum Environment {
9 #[default]
10 Host,
11 Wsl {
12 distro: Option<String>,
13 },
14 }
15
16 #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
17 pub enum OutputFormat {
18 #[default]
19 ClaudeStreamJson,
20 CopilotJsonl,
21 Text,
22 }
23
24 #[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
25 #[serde(default)]
26 pub struct AgentProfile {
27 pub id: String,
28 pub name: String,
29 pub environment: Environment,
30 pub command: String,
31 pub output: OutputFormat,
32 pub open_session_command: String,
33 pub mcp_config_flag: String,
34 }
35
36 impl AgentProfile {
37 pub fn claude_wsl() -> Self {
38 Self {
39 id: "claude".to_string(),
40 name: "Claude Code (WSL)".to_string(),
41 environment: Environment::Wsl { distro: None },
42 command: CLAUDE_COMMAND.to_string(),
43 output: OutputFormat::ClaudeStreamJson,
44 open_session_command: "wt.exe wsl.exe --cd {cwd} -e claude --resume {session_id}"
45 .to_string(),
46 mcp_config_flag: "--mcp-config".to_string(),
47 }
48 }
49
50 pub fn claude_host() -> Self {
51 Self {
52 id: "claude-host".to_string(),
53 name: "Claude Code".to_string(),
54 environment: Environment::Host,
55 command: CLAUDE_COMMAND.to_string(),
56 output: OutputFormat::ClaudeStreamJson,
57 open_session_command: "wt.exe -d {cwd} claude --resume {session_id}".to_string(),
58 mcp_config_flag: "--mcp-config".to_string(),
59 }
60 }
61
62 pub fn copilot_wsl() -> Self {
63 Self {
64 id: "copilot".to_string(),
65 name: "Copilot CLI (WSL)".to_string(),
66 environment: Environment::Wsl { distro: None },
67 command: COPILOT_COMMAND.to_string(),
68 output: OutputFormat::CopilotJsonl,
69 open_session_command: "wt.exe wsl.exe --cd {cwd} -e copilot --resume {session_id}"
70 .to_string(),
71 mcp_config_flag: "--additional-mcp-config".to_string(),
72 }
73 }
74 }
@@ -0,0 +1,74 @@
1use serde::{Deserialize, Serialize};
2
3const CLAUDE_COMMAND: &str =
4 "claude -p --output-format stream-json --verbose --session-id {session_id}";
5const COPILOT_COMMAND: &str = "copilot -p {prompt} --output-format json --session-id {session_id}";
6
7#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
8pub enum Environment {
9 #[default]
10 Host,
11 Wsl {
12 distro: Option<String>,
13 },
14}
15
16#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
17pub enum OutputFormat {
18 #[default]
19 ClaudeStreamJson,
20 CopilotJsonl,
21 Text,
22}
23
24#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
25#[serde(default)]
26pub struct AgentProfile {
27 pub id: String,
28 pub name: String,
29 pub environment: Environment,
30 pub command: String,
31 pub output: OutputFormat,
32 pub open_session_command: String,
33 pub mcp_config_flag: String,
34}
35
36impl AgentProfile {
37 pub fn claude_wsl() -> Self {
38 Self {
39 id: "claude".to_string(),
40 name: "Claude Code (WSL)".to_string(),
41 environment: Environment::Wsl { distro: None },
42 command: CLAUDE_COMMAND.to_string(),
43 output: OutputFormat::ClaudeStreamJson,
44 open_session_command: "wt.exe wsl.exe --cd {cwd} -e claude --resume {session_id}"
45 .to_string(),
46 mcp_config_flag: "--mcp-config".to_string(),
47 }
48 }
49
50 pub fn claude_host() -> Self {
51 Self {
52 id: "claude-host".to_string(),
53 name: "Claude Code".to_string(),
54 environment: Environment::Host,
55 command: CLAUDE_COMMAND.to_string(),
56 output: OutputFormat::ClaudeStreamJson,
57 open_session_command: "wt.exe -d {cwd} claude --resume {session_id}".to_string(),
58 mcp_config_flag: "--mcp-config".to_string(),
59 }
60 }
61
62 pub fn copilot_wsl() -> Self {
63 Self {
64 id: "copilot".to_string(),
65 name: "Copilot CLI (WSL)".to_string(),
66 environment: Environment::Wsl { distro: None },
67 command: COPILOT_COMMAND.to_string(),
68 output: OutputFormat::CopilotJsonl,
69 open_session_command: "wt.exe wsl.exe --cd {cwd} -e copilot --resume {session_id}"
70 .to_string(),
71 mcp_config_flag: "--additional-mcp-config".to_string(),
72 }
73 }
74}
crates/agents/src/runner.rs added +244 −0
@@ -0,0 +1,244 @@
1 use std::collections::VecDeque;
2 use std::process::Stdio;
3 use std::sync::{Arc, Mutex};
4
5 use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
6 use tokio::process::Command;
7 use tokio::sync::{mpsc, oneshot};
8
9 use crate::invocation::{Invocation, RunPlan};
10 use crate::parse::{OutputParser, RunEvent};
11 use crate::profile::OutputFormat;
12
13 const STDERR_TAIL_LINES: usize = 20;
14 const PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
15
16 #[derive(Clone, Debug, PartialEq, Eq)]
17 pub enum RunUpdate {
18 Event(RunEvent),
19 Stderr(String),
20 }
21
22 #[derive(Clone, Debug, PartialEq, Eq)]
23 pub enum RunStatus {
24 Completed {
25 final_text: String,
26 },
27 Failed {
28 message: String,
29 stderr_tail: Vec<String>,
30 },
31 Stopped,
32 }
33
34 #[derive(Clone, Debug, PartialEq, Eq)]
35 pub struct RunOutcome {
36 pub status: RunStatus,
37 pub exit_code: Option<i32>,
38 }
39
40 fn command_for(invocation: &Invocation) -> Command {
41 let mut command = Command::new(&invocation.program);
42 command.args(&invocation.args);
43 if let Some(cwd) = &invocation.cwd {
44 command.current_dir(cwd);
45 }
46 command.kill_on_drop(true);
47 #[cfg(windows)]
48 command.creation_flags(0x0800_0000);
49 command
50 }
51
52 fn failed(message: String, stderr_tail: Vec<String>, exit_code: Option<i32>) -> RunOutcome {
53 RunOutcome {
54 status: RunStatus::Failed {
55 message,
56 stderr_tail,
57 },
58 exit_code,
59 }
60 }
61
62 async fn run_stop_invocation(invocation: &Invocation) {
63 let mut command = command_for(invocation);
64 command
65 .stdin(Stdio::null())
66 .stdout(Stdio::null())
67 .stderr(Stdio::null());
68 if let Ok(mut child) = command.spawn() {
69 let _ = child.wait().await;
70 }
71 }
72
73 fn snapshot(tail: &Mutex<VecDeque<String>>) -> Vec<String> {
74 tail.lock()
75 .map(|lines| lines.iter().cloned().collect())
76 .unwrap_or_default()
77 }
78
79 pub async fn run(
80 plan: RunPlan,
81 format: OutputFormat,
82 events: mpsc::UnboundedSender<RunUpdate>,
83 stop: oneshot::Receiver<()>,
84 ) -> RunOutcome {
85 let cleanup = plan.cleanup.clone();
86 let outcome = run_plan(plan, format, events, stop).await;
87 for path in cleanup {
88 let _ = std::fs::remove_file(path);
89 }
90 outcome
91 }
92
93 async fn run_plan(
94 plan: RunPlan,
95 format: OutputFormat,
96 events: mpsc::UnboundedSender<RunUpdate>,
97 mut stop: oneshot::Receiver<()>,
98 ) -> RunOutcome {
99 let mut command = command_for(&plan.run);
100 command
101 .stdin(Stdio::piped())
102 .stdout(Stdio::piped())
103 .stderr(Stdio::piped());
104 let mut child = match command.spawn() {
105 Ok(child) => child,
106 Err(error) => {
107 return failed(
108 format!("cannot start {}: {error}", plan.run.program),
109 Vec::new(),
110 None,
111 );
112 }
113 };
114 let (Some(stdin), Some(stdout), Some(stderr)) =
115 (child.stdin.take(), child.stdout.take(), child.stderr.take())
116 else {
117 return failed(
118 "cannot attach to the process pipes".to_string(),
119 Vec::new(),
120 None,
121 );
122 };
123
124 let prompt = plan.run.stdin.clone();
125 let stdin_task = tokio::spawn(async move {
126 let mut stdin = stdin;
127 if let Some(prompt) = prompt {
128 let _ = stdin.write_all(prompt.as_bytes()).await;
129 }
130 let _ = stdin.shutdown().await;
131 });
132
133 let stderr_tail = Arc::new(Mutex::new(VecDeque::new()));
134 let stderr_task = {
135 let stderr_tail = Arc::clone(&stderr_tail);
136 let events = events.clone();
137 tokio::spawn(async move {
138 let mut lines = BufReader::new(stderr).lines();
139 while let Ok(Some(line)) = lines.next_line().await {
140 if let Ok(mut tail) = stderr_tail.lock() {
141 if tail.len() == STDERR_TAIL_LINES {
142 tail.pop_front();
143 }
144 tail.push_back(line.clone());
145 }
146 let _ = events.send(RunUpdate::Stderr(line));
147 }
148 })
149 };
150
151 let mut parser = OutputParser::new(format);
152 let mut final_text: Option<String> = None;
153 let mut failure_message: Option<String> = None;
154 let mut stdout_lines = BufReader::new(stdout).lines();
155 let mut stop_armed = true;
156
157 let mut handle_events = |parsed: Vec<RunEvent>| {
158 for event in parsed {
159 match &event {
160 RunEvent::Final(text) => final_text = Some(text.clone()),
161 RunEvent::Failed(message) => failure_message = Some(message.clone()),
162 _ => {}
163 }
164 let _ = events.send(RunUpdate::Event(event));
165 }
166 };
167
168 loop {
169 tokio::select! {
170 stop_result = &mut stop, if stop_armed => {
171 if stop_result.is_ok() {
172 let _ = child.kill().await;
173 if let Some(stop_invocation) = &plan.stop {
174 run_stop_invocation(stop_invocation).await;
175 }
176 stdin_task.abort();
177 stderr_task.abort();
178 return RunOutcome { status: RunStatus::Stopped, exit_code: None };
179 }
180 stop_armed = false;
181 }
182 line = stdout_lines.next_line() => match line {
183 Ok(Some(line)) => handle_events(parser.feed(&line)),
184 _ => break,
185 }
186 }
187 }
188 handle_events(parser.finish());
189
190 let exit_code = child.wait().await.ok().and_then(|status| status.code());
191 let _ = stdin_task.await;
192 let _ = stderr_task.await;
193 let tail = snapshot(&stderr_tail);
194
195 match (exit_code, final_text) {
196 (Some(0), Some(final_text)) => RunOutcome {
197 status: RunStatus::Completed { final_text },
198 exit_code,
199 },
200 _ => {
201 let message = failure_message
202 .or_else(|| tail.last().cloned())
203 .unwrap_or_else(|| match exit_code {
204 Some(code) => format!("exited with code {code}"),
205 None => "exited without a result".to_string(),
206 });
207 failed(message, tail, exit_code)
208 }
209 }
210 }
211
212 fn first_line(bytes: &[u8]) -> Option<String> {
213 String::from_utf8_lossy(bytes)
214 .lines()
215 .map(str::trim)
216 .find(|line| !line.is_empty())
217 .map(str::to_string)
218 }
219
220 pub async fn probe(invocation: &Invocation) -> Result<String, String> {
221 let mut command = command_for(invocation);
222 command
223 .stdin(Stdio::null())
224 .stdout(Stdio::piped())
225 .stderr(Stdio::piped());
226 let child = command
227 .spawn()
228 .map_err(|error| format!("cannot start {}: {error}", invocation.program))?;
229 let output = tokio::time::timeout(PROBE_TIMEOUT, child.wait_with_output())
230 .await
231 .map_err(|_| "no answer within 10 seconds".to_string())?
232 .map_err(|error| error.to_string())?;
233 if output.status.success() {
234 return Ok(first_line(&output.stdout)
235 .or_else(|| first_line(&output.stderr))
236 .unwrap_or_default());
237 }
238 Err(first_line(&output.stderr)
239 .or_else(|| first_line(&output.stdout))
240 .unwrap_or_else(|| match output.status.code() {
241 Some(code) => format!("exited with code {code}"),
242 None => "exited without a result".to_string(),
243 }))
244 }
@@ -0,0 +1,244 @@
1use std::collections::VecDeque;
2use std::process::Stdio;
3use std::sync::{Arc, Mutex};
4
5use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
6use tokio::process::Command;
7use tokio::sync::{mpsc, oneshot};
8
9use crate::invocation::{Invocation, RunPlan};
10use crate::parse::{OutputParser, RunEvent};
11use crate::profile::OutputFormat;
12
13const STDERR_TAIL_LINES: usize = 20;
14const PROBE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(10);
15
16#[derive(Clone, Debug, PartialEq, Eq)]
17pub enum RunUpdate {
18 Event(RunEvent),
19 Stderr(String),
20}
21
22#[derive(Clone, Debug, PartialEq, Eq)]
23pub enum RunStatus {
24 Completed {
25 final_text: String,
26 },
27 Failed {
28 message: String,
29 stderr_tail: Vec<String>,
30 },
31 Stopped,
32}
33
34#[derive(Clone, Debug, PartialEq, Eq)]
35pub struct RunOutcome {
36 pub status: RunStatus,
37 pub exit_code: Option<i32>,
38}
39
40fn command_for(invocation: &Invocation) -> Command {
41 let mut command = Command::new(&invocation.program);
42 command.args(&invocation.args);
43 if let Some(cwd) = &invocation.cwd {
44 command.current_dir(cwd);
45 }
46 command.kill_on_drop(true);
47 #[cfg(windows)]
48 command.creation_flags(0x0800_0000);
49 command
50}
51
52fn failed(message: String, stderr_tail: Vec<String>, exit_code: Option<i32>) -> RunOutcome {
53 RunOutcome {
54 status: RunStatus::Failed {
55 message,
56 stderr_tail,
57 },
58 exit_code,
59 }
60}
61
62async fn run_stop_invocation(invocation: &Invocation) {
63 let mut command = command_for(invocation);
64 command
65 .stdin(Stdio::null())
66 .stdout(Stdio::null())
67 .stderr(Stdio::null());
68 if let Ok(mut child) = command.spawn() {
69 let _ = child.wait().await;
70 }
71}
72
73fn snapshot(tail: &Mutex<VecDeque<String>>) -> Vec<String> {
74 tail.lock()
75 .map(|lines| lines.iter().cloned().collect())
76 .unwrap_or_default()
77}
78
79pub async fn run(
80 plan: RunPlan,
81 format: OutputFormat,
82 events: mpsc::UnboundedSender<RunUpdate>,
83 stop: oneshot::Receiver<()>,
84) -> RunOutcome {
85 let cleanup = plan.cleanup.clone();
86 let outcome = run_plan(plan, format, events, stop).await;
87 for path in cleanup {
88 let _ = std::fs::remove_file(path);
89 }
90 outcome
91}
92
93async fn run_plan(
94 plan: RunPlan,
95 format: OutputFormat,
96 events: mpsc::UnboundedSender<RunUpdate>,
97 mut stop: oneshot::Receiver<()>,
98) -> RunOutcome {
99 let mut command = command_for(&plan.run);
100 command
101 .stdin(Stdio::piped())
102 .stdout(Stdio::piped())
103 .stderr(Stdio::piped());
104 let mut child = match command.spawn() {
105 Ok(child) => child,
106 Err(error) => {
107 return failed(
108 format!("cannot start {}: {error}", plan.run.program),
109 Vec::new(),
110 None,
111 );
112 }
113 };
114 let (Some(stdin), Some(stdout), Some(stderr)) =
115 (child.stdin.take(), child.stdout.take(), child.stderr.take())
116 else {
117 return failed(
118 "cannot attach to the process pipes".to_string(),
119 Vec::new(),
120 None,
121 );
122 };
123
124 let prompt = plan.run.stdin.clone();
125 let stdin_task = tokio::spawn(async move {
126 let mut stdin = stdin;
127 if let Some(prompt) = prompt {
128 let _ = stdin.write_all(prompt.as_bytes()).await;
129 }
130 let _ = stdin.shutdown().await;
131 });
132
133 let stderr_tail = Arc::new(Mutex::new(VecDeque::new()));
134 let stderr_task = {
135 let stderr_tail = Arc::clone(&stderr_tail);
136 let events = events.clone();
137 tokio::spawn(async move {
138 let mut lines = BufReader::new(stderr).lines();
139 while let Ok(Some(line)) = lines.next_line().await {
140 if let Ok(mut tail) = stderr_tail.lock() {
141 if tail.len() == STDERR_TAIL_LINES {
142 tail.pop_front();
143 }
144 tail.push_back(line.clone());
145 }
146 let _ = events.send(RunUpdate::Stderr(line));
147 }
148 })
149 };
150
151 let mut parser = OutputParser::new(format);
152 let mut final_text: Option<String> = None;
153 let mut failure_message: Option<String> = None;
154 let mut stdout_lines = BufReader::new(stdout).lines();
155 let mut stop_armed = true;
156
157 let mut handle_events = |parsed: Vec<RunEvent>| {
158 for event in parsed {
159 match &event {
160 RunEvent::Final(text) => final_text = Some(text.clone()),
161 RunEvent::Failed(message) => failure_message = Some(message.clone()),
162 _ => {}
163 }
164 let _ = events.send(RunUpdate::Event(event));
165 }
166 };
167
168 loop {
169 tokio::select! {
170 stop_result = &mut stop, if stop_armed => {
171 if stop_result.is_ok() {
172 let _ = child.kill().await;
173 if let Some(stop_invocation) = &plan.stop {
174 run_stop_invocation(stop_invocation).await;
175 }
176 stdin_task.abort();
177 stderr_task.abort();
178 return RunOutcome { status: RunStatus::Stopped, exit_code: None };
179 }
180 stop_armed = false;
181 }
182 line = stdout_lines.next_line() => match line {
183 Ok(Some(line)) => handle_events(parser.feed(&line)),
184 _ => break,
185 }
186 }
187 }
188 handle_events(parser.finish());
189
190 let exit_code = child.wait().await.ok().and_then(|status| status.code());
191 let _ = stdin_task.await;
192 let _ = stderr_task.await;
193 let tail = snapshot(&stderr_tail);
194
195 match (exit_code, final_text) {
196 (Some(0), Some(final_text)) => RunOutcome {
197 status: RunStatus::Completed { final_text },
198 exit_code,
199 },
200 _ => {
201 let message = failure_message
202 .or_else(|| tail.last().cloned())
203 .unwrap_or_else(|| match exit_code {
204 Some(code) => format!("exited with code {code}"),
205 None => "exited without a result".to_string(),
206 });
207 failed(message, tail, exit_code)
208 }
209 }
210}
211
212fn first_line(bytes: &[u8]) -> Option<String> {
213 String::from_utf8_lossy(bytes)
214 .lines()
215 .map(str::trim)
216 .find(|line| !line.is_empty())
217 .map(str::to_string)
218}
219
220pub async fn probe(invocation: &Invocation) -> Result<String, String> {
221 let mut command = command_for(invocation);
222 command
223 .stdin(Stdio::null())
224 .stdout(Stdio::piped())
225 .stderr(Stdio::piped());
226 let child = command
227 .spawn()
228 .map_err(|error| format!("cannot start {}: {error}", invocation.program))?;
229 let output = tokio::time::timeout(PROBE_TIMEOUT, child.wait_with_output())
230 .await
231 .map_err(|_| "no answer within 10 seconds".to_string())?
232 .map_err(|error| error.to_string())?;
233 if output.status.success() {
234 return Ok(first_line(&output.stdout)
235 .or_else(|| first_line(&output.stderr))
236 .unwrap_or_default());
237 }
238 Err(first_line(&output.stderr)
239 .or_else(|| first_line(&output.stdout))
240 .unwrap_or_else(|| match output.status.code() {
241 Some(code) => format!("exited with code {code}"),
242 None => "exited without a result".to_string(),
243 }))
244}
crates/agents/src/settings.rs added +154 −0
@@ -0,0 +1,154 @@
1 use serde::{Deserialize, Serialize};
2
3 use crate::action::AgentAction;
4 use crate::profile::AgentProfile;
5 use crate::template::{is_known_placeholder, placeholders_in};
6
7 pub const SETTINGS_KEY: &str = "agents.settings";
8
9 #[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
10 pub enum SettingsProblem {
11 #[error("action {action_id} references unknown agent {agent_id}")]
12 UnknownAgent { action_id: String, agent_id: String },
13 #[error("agent {agent_id} has an empty command")]
14 EmptyCommand { agent_id: String },
15 #[error("{item_id} uses unknown placeholder {{{placeholder}}}")]
16 UnknownPlaceholder {
17 item_id: String,
18 placeholder: String,
19 },
20 }
21
22 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
23 #[serde(default)]
24 pub struct AgentSettings {
25 pub agents: Vec<AgentProfile>,
26 pub actions: Vec<AgentAction>,
27 }
28
29 impl Default for AgentSettings {
30 fn default() -> Self {
31 Self {
32 agents: vec![AgentProfile::claude_wsl(), AgentProfile::copilot_wsl()],
33 actions: vec![
34 AgentAction::answer_this("claude"),
35 AgentAction::build_this("claude"),
36 ],
37 }
38 }
39 }
40
41 fn check_placeholders(item_id: &str, texts: &[&str], problems: &mut Vec<SettingsProblem>) {
42 for text in texts {
43 for placeholder in placeholders_in(text) {
44 if !is_known_placeholder(&placeholder) {
45 problems.push(SettingsProblem::UnknownPlaceholder {
46 item_id: item_id.to_string(),
47 placeholder,
48 });
49 }
50 }
51 }
52 }
53
54 impl AgentSettings {
55 pub fn to_json(&self) -> String {
56 serde_json::to_string(self).unwrap_or_else(|_| "{}".to_string())
57 }
58
59 pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
60 serde_json::from_str(json)
61 }
62
63 pub fn validate(&self) -> Vec<SettingsProblem> {
64 let mut problems = Vec::new();
65 for agent in &self.agents {
66 if agent.command.trim().is_empty() {
67 problems.push(SettingsProblem::EmptyCommand {
68 agent_id: agent.id.clone(),
69 });
70 }
71 check_placeholders(
72 &agent.id,
73 &[&agent.command, &agent.open_session_command],
74 &mut problems,
75 );
76 }
77 for action in &self.actions {
78 if !self.agents.iter().any(|agent| agent.id == action.agent_id) {
79 problems.push(SettingsProblem::UnknownAgent {
80 action_id: action.id.clone(),
81 agent_id: action.agent_id.clone(),
82 });
83 }
84 check_placeholders(
85 &action.id,
86 &[&action.prompt_template, &action.extra_args],
87 &mut problems,
88 );
89 }
90 problems
91 }
92 }
93
94 #[cfg(test)]
95 mod tests {
96 use super::*;
97
98 #[test]
99 fn default_round_trips_and_is_valid() {
100 let settings = AgentSettings::default();
101 let loaded = AgentSettings::from_json(&settings.to_json()).unwrap();
102 assert_eq!(loaded, settings);
103 assert!(settings.validate().is_empty());
104 }
105
106 #[test]
107 fn empty_object_loads_defaults() {
108 assert_eq!(
109 AgentSettings::from_json("{}").unwrap(),
110 AgentSettings::default()
111 );
112 }
113
114 #[test]
115 fn partial_json_fills_missing_fields() {
116 let loaded = AgentSettings::from_json(
117 r#"{"agents":[{"id":"x","command":"x {session_id}"}],"actions":[{"id":"a","agent_id":"x"}]}"#,
118 )
119 .unwrap();
120 assert_eq!(loaded.agents.len(), 1);
121 assert_eq!(
122 loaded.agents[0].output,
123 crate::OutputFormat::ClaudeStreamJson
124 );
125 assert_eq!(loaded.actions[0].working_dir, "");
126 let only_actions = AgentSettings::from_json(r#"{"actions":[]}"#).unwrap();
127 assert_eq!(only_actions.agents.len(), 2);
128 }
129
130 #[test]
131 fn validate_finds_problems() {
132 let mut settings = AgentSettings::default();
133 settings.actions[0].agent_id = "ghost".to_string();
134 settings.agents[1].command = String::new();
135 settings.agents[0].command.push_str(" {bogus}");
136 settings.actions[1].prompt_template.push_str(" {nope}");
137 let problems = settings.validate();
138 assert!(problems.contains(&SettingsProblem::UnknownAgent {
139 action_id: "answer-this".to_string(),
140 agent_id: "ghost".to_string(),
141 }));
142 assert!(problems.contains(&SettingsProblem::EmptyCommand {
143 agent_id: "copilot".to_string(),
144 }));
145 assert!(problems.contains(&SettingsProblem::UnknownPlaceholder {
146 item_id: "claude".to_string(),
147 placeholder: "bogus".to_string(),
148 }));
149 assert!(problems.contains(&SettingsProblem::UnknownPlaceholder {
150 item_id: "build-this".to_string(),
151 placeholder: "nope".to_string(),
152 }));
153 }
154 }
@@ -0,0 +1,154 @@
1use serde::{Deserialize, Serialize};
2
3use crate::action::AgentAction;
4use crate::profile::AgentProfile;
5use crate::template::{is_known_placeholder, placeholders_in};
6
7pub const SETTINGS_KEY: &str = "agents.settings";
8
9#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
10pub enum SettingsProblem {
11 #[error("action {action_id} references unknown agent {agent_id}")]
12 UnknownAgent { action_id: String, agent_id: String },
13 #[error("agent {agent_id} has an empty command")]
14 EmptyCommand { agent_id: String },
15 #[error("{item_id} uses unknown placeholder {{{placeholder}}}")]
16 UnknownPlaceholder {
17 item_id: String,
18 placeholder: String,
19 },
20}
21
22#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
23#[serde(default)]
24pub struct AgentSettings {
25 pub agents: Vec<AgentProfile>,
26 pub actions: Vec<AgentAction>,
27}
28
29impl Default for AgentSettings {
30 fn default() -> Self {
31 Self {
32 agents: vec![AgentProfile::claude_wsl(), AgentProfile::copilot_wsl()],
33 actions: vec![
34 AgentAction::answer_this("claude"),
35 AgentAction::build_this("claude"),
36 ],
37 }
38 }
39}
40
41fn check_placeholders(item_id: &str, texts: &[&str], problems: &mut Vec<SettingsProblem>) {
42 for text in texts {
43 for placeholder in placeholders_in(text) {
44 if !is_known_placeholder(&placeholder) {
45 problems.push(SettingsProblem::UnknownPlaceholder {
46 item_id: item_id.to_string(),
47 placeholder,
48 });
49 }
50 }
51 }
52}
53
54impl AgentSettings {
55 pub fn to_json(&self) -> String {
56 serde_json::to_string(self).unwrap_or_else(|_| "{}".to_string())
57 }
58
59 pub fn from_json(json: &str) -> Result<Self, serde_json::Error> {
60 serde_json::from_str(json)
61 }
62
63 pub fn validate(&self) -> Vec<SettingsProblem> {
64 let mut problems = Vec::new();
65 for agent in &self.agents {
66 if agent.command.trim().is_empty() {
67 problems.push(SettingsProblem::EmptyCommand {
68 agent_id: agent.id.clone(),
69 });
70 }
71 check_placeholders(
72 &agent.id,
73 &[&agent.command, &agent.open_session_command],
74 &mut problems,
75 );
76 }
77 for action in &self.actions {
78 if !self.agents.iter().any(|agent| agent.id == action.agent_id) {
79 problems.push(SettingsProblem::UnknownAgent {
80 action_id: action.id.clone(),
81 agent_id: action.agent_id.clone(),
82 });
83 }
84 check_placeholders(
85 &action.id,
86 &[&action.prompt_template, &action.extra_args],
87 &mut problems,
88 );
89 }
90 problems
91 }
92}
93
94#[cfg(test)]
95mod tests {
96 use super::*;
97
98 #[test]
99 fn default_round_trips_and_is_valid() {
100 let settings = AgentSettings::default();
101 let loaded = AgentSettings::from_json(&settings.to_json()).unwrap();
102 assert_eq!(loaded, settings);
103 assert!(settings.validate().is_empty());
104 }
105
106 #[test]
107 fn empty_object_loads_defaults() {
108 assert_eq!(
109 AgentSettings::from_json("{}").unwrap(),
110 AgentSettings::default()
111 );
112 }
113
114 #[test]
115 fn partial_json_fills_missing_fields() {
116 let loaded = AgentSettings::from_json(
117 r#"{"agents":[{"id":"x","command":"x {session_id}"}],"actions":[{"id":"a","agent_id":"x"}]}"#,
118 )
119 .unwrap();
120 assert_eq!(loaded.agents.len(), 1);
121 assert_eq!(
122 loaded.agents[0].output,
123 crate::OutputFormat::ClaudeStreamJson
124 );
125 assert_eq!(loaded.actions[0].working_dir, "");
126 let only_actions = AgentSettings::from_json(r#"{"actions":[]}"#).unwrap();
127 assert_eq!(only_actions.agents.len(), 2);
128 }
129
130 #[test]
131 fn validate_finds_problems() {
132 let mut settings = AgentSettings::default();
133 settings.actions[0].agent_id = "ghost".to_string();
134 settings.agents[1].command = String::new();
135 settings.agents[0].command.push_str(" {bogus}");
136 settings.actions[1].prompt_template.push_str(" {nope}");
137 let problems = settings.validate();
138 assert!(problems.contains(&SettingsProblem::UnknownAgent {
139 action_id: "answer-this".to_string(),
140 agent_id: "ghost".to_string(),
141 }));
142 assert!(problems.contains(&SettingsProblem::EmptyCommand {
143 agent_id: "copilot".to_string(),
144 }));
145 assert!(problems.contains(&SettingsProblem::UnknownPlaceholder {
146 item_id: "claude".to_string(),
147 placeholder: "bogus".to_string(),
148 }));
149 assert!(problems.contains(&SettingsProblem::UnknownPlaceholder {
150 item_id: "build-this".to_string(),
151 placeholder: "nope".to_string(),
152 }));
153 }
154}
crates/agents/src/template.rs added +198 −0
@@ -0,0 +1,198 @@
1 const PLACEHOLDERS: [&str; 11] = [
2 "message",
3 "sender",
4 "chat",
5 "conversation_id",
6 "message_id",
7 "thread",
8 "extra",
9 "cwd",
10 "session_id",
11 "agent",
12 "prompt",
13 ];
14
15 #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
16 #[error("unknown placeholder {{{0}}}")]
17 pub struct UnknownPlaceholder(pub String);
18
19 #[derive(Clone, Debug, Default)]
20 pub struct Values {
21 pub message: String,
22 pub sender: String,
23 pub chat: String,
24 pub conversation_id: String,
25 pub message_id: String,
26 pub thread: String,
27 pub extra: String,
28 pub cwd: String,
29 pub session_id: String,
30 pub agent: String,
31 pub prompt: String,
32 }
33
34 impl Values {
35 fn get(&self, name: &str) -> Option<&str> {
36 match name {
37 "message" => Some(&self.message),
38 "sender" => Some(&self.sender),
39 "chat" => Some(&self.chat),
40 "conversation_id" => Some(&self.conversation_id),
41 "message_id" => Some(&self.message_id),
42 "thread" => Some(&self.thread),
43 "extra" => Some(&self.extra),
44 "cwd" => Some(&self.cwd),
45 "session_id" => Some(&self.session_id),
46 "agent" => Some(&self.agent),
47 "prompt" => Some(&self.prompt),
48 _ => None,
49 }
50 }
51 }
52
53 pub(crate) fn is_known_placeholder(name: &str) -> bool {
54 PLACEHOLDERS.contains(&name)
55 }
56
57 fn next_placeholder(text: &str) -> Option<(usize, usize, &str)> {
58 let mut search_from = 0;
59 while let Some(offset) = text[search_from..].find('{') {
60 let start = search_from + offset;
61 let rest = &text[start + 1..];
62 if let Some(end) = rest.find('}') {
63 let name = &rest[..end];
64 let is_identifier = !name.is_empty()
65 && name
66 .chars()
67 .all(|character| character.is_ascii_alphanumeric() || character == '_');
68 if is_identifier {
69 return Some((start, start + end + 2, name));
70 }
71 }
72 search_from = start + 1;
73 }
74 None
75 }
76
77 pub fn placeholders_in(template: &str) -> Vec<String> {
78 let mut names = Vec::new();
79 let mut remaining = template;
80 while let Some((_, end, name)) = next_placeholder(remaining) {
81 names.push(name.to_string());
82 remaining = &remaining[end..];
83 }
84 names
85 }
86
87 pub fn render(template: &str, values: &Values) -> Result<String, UnknownPlaceholder> {
88 let mut output = String::with_capacity(template.len());
89 let mut remaining = template;
90 while let Some((start, end, name)) = next_placeholder(remaining) {
91 let value = values
92 .get(name)
93 .ok_or_else(|| UnknownPlaceholder(name.to_string()))?;
94 output.push_str(&remaining[..start]);
95 output.push_str(value);
96 remaining = &remaining[end..];
97 }
98 output.push_str(remaining);
99 Ok(output)
100 }
101
102 pub fn split_command(command: &str) -> Vec<String> {
103 let mut tokens = Vec::new();
104 let mut current = String::new();
105 let mut in_token = false;
106 let mut quote: Option<char> = None;
107 for character in command.chars() {
108 match quote {
109 Some(open) if character == open => quote = None,
110 Some(_) => current.push(character),
111 None if character == '"' || character == '\'' => {
112 quote = Some(character);
113 in_token = true;
114 }
115 None if character.is_whitespace() => {
116 if in_token {
117 tokens.push(std::mem::take(&mut current));
118 in_token = false;
119 }
120 }
121 None => {
122 current.push(character);
123 in_token = true;
124 }
125 }
126 }
127 if in_token {
128 tokens.push(current);
129 }
130 tokens
131 }
132
133 #[cfg(test)]
134 mod tests {
135 use super::*;
136
137 fn values() -> Values {
138 Values {
139 sender: "Ada".to_string(),
140 prompt: "line one\nline two".to_string(),
141 session_id: "abc".to_string(),
142 ..Values::default()
143 }
144 }
145
146 #[test]
147 fn renders_known_placeholders() {
148 let rendered = render("{sender} id={session_id} {extra}!", &values()).unwrap();
149 assert_eq!(rendered, "Ada id=abc !");
150 }
151
152 #[test]
153 fn rejects_unknown_placeholder() {
154 let error = render("hello {nope}", &values()).unwrap_err();
155 assert_eq!(error, UnknownPlaceholder("nope".to_string()));
156 }
157
158 #[test]
159 fn keeps_non_placeholder_braces() {
160 assert_eq!(
161 render("{\"a\": 1} { x }", &values()).unwrap(),
162 "{\"a\": 1} { x }"
163 );
164 }
165
166 #[test]
167 fn does_not_rescan_substituted_values() {
168 let mut substituted = values();
169 substituted.sender = "{prompt}".to_string();
170 assert_eq!(render("{sender}", &substituted).unwrap(), "{prompt}");
171 }
172
173 #[test]
174 fn lists_placeholders() {
175 assert_eq!(
176 placeholders_in("a {message} b {x} {message}"),
177 vec!["message", "x", "message"]
178 );
179 }
180
181 #[test]
182 fn splits_with_quotes() {
183 assert_eq!(
184 split_command(r#"sh -c "echo 'a b'" 'c d' "" e"#),
185 vec!["sh", "-c", "echo 'a b'", "c d", "", "e"]
186 );
187 }
188
189 #[test]
190 fn prompt_stays_one_token() {
191 let tokens = split_command("copilot -p {prompt} --x");
192 let rendered: Vec<String> = tokens
193 .iter()
194 .map(|token| render(token, &values()).unwrap())
195 .collect();
196 assert_eq!(rendered, vec!["copilot", "-p", "line one\nline two", "--x"]);
197 }
198 }
@@ -0,0 +1,198 @@
1const PLACEHOLDERS: [&str; 11] = [
2 "message",
3 "sender",
4 "chat",
5 "conversation_id",
6 "message_id",
7 "thread",
8 "extra",
9 "cwd",
10 "session_id",
11 "agent",
12 "prompt",
13];
14
15#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
16#[error("unknown placeholder {{{0}}}")]
17pub struct UnknownPlaceholder(pub String);
18
19#[derive(Clone, Debug, Default)]
20pub struct Values {
21 pub message: String,
22 pub sender: String,
23 pub chat: String,
24 pub conversation_id: String,
25 pub message_id: String,
26 pub thread: String,
27 pub extra: String,
28 pub cwd: String,
29 pub session_id: String,
30 pub agent: String,
31 pub prompt: String,
32}
33
34impl Values {
35 fn get(&self, name: &str) -> Option<&str> {
36 match name {
37 "message" => Some(&self.message),
38 "sender" => Some(&self.sender),
39 "chat" => Some(&self.chat),
40 "conversation_id" => Some(&self.conversation_id),
41 "message_id" => Some(&self.message_id),
42 "thread" => Some(&self.thread),
43 "extra" => Some(&self.extra),
44 "cwd" => Some(&self.cwd),
45 "session_id" => Some(&self.session_id),
46 "agent" => Some(&self.agent),
47 "prompt" => Some(&self.prompt),
48 _ => None,
49 }
50 }
51}
52
53pub(crate) fn is_known_placeholder(name: &str) -> bool {
54 PLACEHOLDERS.contains(&name)
55}
56
57fn next_placeholder(text: &str) -> Option<(usize, usize, &str)> {
58 let mut search_from = 0;
59 while let Some(offset) = text[search_from..].find('{') {
60 let start = search_from + offset;
61 let rest = &text[start + 1..];
62 if let Some(end) = rest.find('}') {
63 let name = &rest[..end];
64 let is_identifier = !name.is_empty()
65 && name
66 .chars()
67 .all(|character| character.is_ascii_alphanumeric() || character == '_');
68 if is_identifier {
69 return Some((start, start + end + 2, name));
70 }
71 }
72 search_from = start + 1;
73 }
74 None
75}
76
77pub fn placeholders_in(template: &str) -> Vec<String> {
78 let mut names = Vec::new();
79 let mut remaining = template;
80 while let Some((_, end, name)) = next_placeholder(remaining) {
81 names.push(name.to_string());
82 remaining = &remaining[end..];
83 }
84 names
85}
86
87pub fn render(template: &str, values: &Values) -> Result<String, UnknownPlaceholder> {
88 let mut output = String::with_capacity(template.len());
89 let mut remaining = template;
90 while let Some((start, end, name)) = next_placeholder(remaining) {
91 let value = values
92 .get(name)
93 .ok_or_else(|| UnknownPlaceholder(name.to_string()))?;
94 output.push_str(&remaining[..start]);
95 output.push_str(value);
96 remaining = &remaining[end..];
97 }
98 output.push_str(remaining);
99 Ok(output)
100}
101
102pub fn split_command(command: &str) -> Vec<String> {
103 let mut tokens = Vec::new();
104 let mut current = String::new();
105 let mut in_token = false;
106 let mut quote: Option<char> = None;
107 for character in command.chars() {
108 match quote {
109 Some(open) if character == open => quote = None,
110 Some(_) => current.push(character),
111 None if character == '"' || character == '\'' => {
112 quote = Some(character);
113 in_token = true;
114 }
115 None if character.is_whitespace() => {
116 if in_token {
117 tokens.push(std::mem::take(&mut current));
118 in_token = false;
119 }
120 }
121 None => {
122 current.push(character);
123 in_token = true;
124 }
125 }
126 }
127 if in_token {
128 tokens.push(current);
129 }
130 tokens
131}
132
133#[cfg(test)]
134mod tests {
135 use super::*;
136
137 fn values() -> Values {
138 Values {
139 sender: "Ada".to_string(),
140 prompt: "line one\nline two".to_string(),
141 session_id: "abc".to_string(),
142 ..Values::default()
143 }
144 }
145
146 #[test]
147 fn renders_known_placeholders() {
148 let rendered = render("{sender} id={session_id} {extra}!", &values()).unwrap();
149 assert_eq!(rendered, "Ada id=abc !");
150 }
151
152 #[test]
153 fn rejects_unknown_placeholder() {
154 let error = render("hello {nope}", &values()).unwrap_err();
155 assert_eq!(error, UnknownPlaceholder("nope".to_string()));
156 }
157
158 #[test]
159 fn keeps_non_placeholder_braces() {
160 assert_eq!(
161 render("{\"a\": 1} { x }", &values()).unwrap(),
162 "{\"a\": 1} { x }"
163 );
164 }
165
166 #[test]
167 fn does_not_rescan_substituted_values() {
168 let mut substituted = values();
169 substituted.sender = "{prompt}".to_string();
170 assert_eq!(render("{sender}", &substituted).unwrap(), "{prompt}");
171 }
172
173 #[test]
174 fn lists_placeholders() {
175 assert_eq!(
176 placeholders_in("a {message} b {x} {message}"),
177 vec!["message", "x", "message"]
178 );
179 }
180
181 #[test]
182 fn splits_with_quotes() {
183 assert_eq!(
184 split_command(r#"sh -c "echo 'a b'" 'c d' "" e"#),
185 vec!["sh", "-c", "echo 'a b'", "c d", "", "e"]
186 );
187 }
188
189 #[test]
190 fn prompt_stays_one_token() {
191 let tokens = split_command("copilot -p {prompt} --x");
192 let rendered: Vec<String> = tokens
193 .iter()
194 .map(|token| render(token, &values()).unwrap())
195 .collect();
196 assert_eq!(rendered, vec!["copilot", "-p", "line one\nline two", "--x"]);
197 }
198}
crates/agents/tests/fixtures/claude-stream.jsonl added +6 −0
@@ -0,0 +1,6 @@
1 {"type":"system","subtype":"init","session_id":"3f6a2c1e-6f53-4c8e-9a51-7c2b5d0e9a11","cwd":"/home/user/project","model":"claude-opus-5-5"}
2 {"type":"assistant","session_id":"3f6a2c1e-6f53-4c8e-9a51-7c2b5d0e9a11","message":{"role":"assistant","content":[{"type":"tool_use","id":"toolu_015zjuPdfJyvvzouR24h1knd","name":"Read","input":{"file_path":"/etc/hostname"},"caller":{"type":"direct"}}]}}
3 {"type":"user","session_id":"3f6a2c1e-6f53-4c8e-9a51-7c2b5d0e9a11","message":{"role":"user","content":[{"tool_use_id":"toolu_015zjuPdfJyvvzouR24h1knd","type":"tool_result","content":"1\tHOST01\n2\t"}]}}
4 {"type":"assistant","session_id":"3f6a2c1e-6f53-4c8e-9a51-7c2b5d0e9a11","message":{"role":"assistant","content":[{"type":"thinking","thinking":"..."}]}}
5 {"type":"assistant","session_id":"3f6a2c1e-6f53-4c8e-9a51-7c2b5d0e9a11","message":{"role":"assistant","content":[{"type":"text","text":"The first word in `/etc/hostname` is `HOST01`."}]}}
6 {"type":"result","subtype":"success","is_error":false,"duration_ms":19769,"num_turns":2,"result":"The first word in `/etc/hostname` is `HOST01`.","session_id":"3f6a2c1e-6f53-4c8e-9a51-7c2b5d0e9a11","total_cost_usd":0.45020399999999994}
@@ -0,0 +1,6 @@
1{"type":"system","subtype":"init","session_id":"3f6a2c1e-6f53-4c8e-9a51-7c2b5d0e9a11","cwd":"/home/user/project","model":"claude-opus-5-5"}
2{"type":"assistant","session_id":"3f6a2c1e-6f53-4c8e-9a51-7c2b5d0e9a11","message":{"role":"assistant","content":[{"type":"tool_use","id":"toolu_015zjuPdfJyvvzouR24h1knd","name":"Read","input":{"file_path":"/etc/hostname"},"caller":{"type":"direct"}}]}}
3{"type":"user","session_id":"3f6a2c1e-6f53-4c8e-9a51-7c2b5d0e9a11","message":{"role":"user","content":[{"tool_use_id":"toolu_015zjuPdfJyvvzouR24h1knd","type":"tool_result","content":"1\tHOST01\n2\t"}]}}
4{"type":"assistant","session_id":"3f6a2c1e-6f53-4c8e-9a51-7c2b5d0e9a11","message":{"role":"assistant","content":[{"type":"thinking","thinking":"..."}]}}
5{"type":"assistant","session_id":"3f6a2c1e-6f53-4c8e-9a51-7c2b5d0e9a11","message":{"role":"assistant","content":[{"type":"text","text":"The first word in `/etc/hostname` is `HOST01`."}]}}
6{"type":"result","subtype":"success","is_error":false,"duration_ms":19769,"num_turns":2,"result":"The first word in `/etc/hostname` is `HOST01`.","session_id":"3f6a2c1e-6f53-4c8e-9a51-7c2b5d0e9a11","total_cost_usd":0.45020399999999994}
crates/agents/tests/fixtures/copilot.jsonl added +16 −0
@@ -0,0 +1,16 @@
1 {"type":"user.message","data":{"content":"Read the file /etc/hostname and tell me its first word."}}
2 {"type":"assistant.message","data":{"messageId":"4e250083-2155-4889-9ff2-20fda4dd349e","originatingMessageId":"77f559a5-97e8-4a24-bad7-dc93da90e37a","model":"claude-sonnet-5.5","content":"","toolRequests":[{"toolCallId":"toolu_011T3QnmHAVnoqt61ua4UbCf","name":"view","arguments":{"path":"/etc/hostname"},"type":"function","intentionSummary":"view the file at /etc/hostname.","toolTitle":"Viewing file"}],"interactionId":"c0d8cfc7-33f8-4d02-b886-6944e80f6517","turnId":"0","rte":true,"apiCallId":"msg_011Cfw8DPquo2TwEbQnym66c"}}
3 {"type":"tool.execution_start","data":{"toolCallId":"toolu_011T3QnmHAVnoqt61ua4UbCf","toolName":"view","arguments":{"path":"/etc/hostname"},"turnId":"0","model":"claude-sonnet-5.5","toolTitle":"Viewing file"}}
4 {"type":"assistant.message","data":{"messageId":"22076fc9-351d-4215-a28f-4db06b3e2736","originatingMessageId":"77f559a5-97e8-4a24-bad7-dc93da90e37a","model":"claude-sonnet-5.5","content":"","toolRequests":[{"toolCallId":"toolu_013mVYppotmvxqQa2PWLtY3Q","name":"bash","arguments":{"command":"head -n1 /etc/hostname | awk '{print $1}'","description":"Read first word of /etc/hostname"},"type":"function","intentionSummary":"Read first word of /etc/hostname","toolTitle":"Running command"}],"interactionId":"c0d8cfc7-33f8-4d02-b886-6944e80f6517","turnId":"1","rte":true,"apiCallId":"msg_011Cfw8DaYLqgPRknEndrFMG"}}
5 {"type":"tool.execution_start","data":{"toolCallId":"toolu_013mVYppotmvxqQa2PWLtY3Q","toolName":"bash","arguments":{"command":"head -n1 /etc/hostname | awk '{print $1}'","description":"Read first word of /etc/hostname"},"turnId":"1","model":"claude-sonnet-5.5","toolTitle":"Running command","shellToolInfo":{"possiblePaths":["/etc/hostname"],"hasWriteFileRedirection":false}}}
6 {"type":"assistant.message_delta","data":{"messageId":"605afe54-1441-4858-912d-71c5a75cb917","deltaContent":"I couldn't read /et"}}
7 {"type":"assistant.message_delta","data":{"messageId":"605afe54-1441-4858-912d-71c5a75cb917","deltaContent":"c/hostname:"}}
8 {"type":"assistant.message_delta","data":{"messageId":"605afe54-1441-4858-912d-71c5a75cb917","deltaContent":" both the file"}}
9 {"type":"assistant.message_delta","data":{"messageId":"605afe54-1441-4858-912d-71c5a75cb917","deltaContent":" vi"}}
10 {"type":"assistant.message_delta","data":{"messageId":"605afe54-1441-4858-912d-71c5a75cb917","deltaContent":"ewer and a sh"}}
11 {"type":"assistant.message_delta","data":{"messageId":"605afe54-1441-4858-912d-71c5a75cb917","deltaContent":"ell command were denied perm"}}
12 {"type":"assistant.message_delta","data":{"messageId":"605afe54-1441-4858-912d-71c5a75cb917","deltaContent":"ission,"}}
13 {"type":"assistant.message_delta","data":{"messageId":"605afe54-1441-4858-912d-71c5a75cb917","deltaContent":" so I don"}}
14 {"type":"assistant.message_delta","data":{"messageId":"605afe54-1441-4858-912d-71c5a75cb917","deltaContent":"'t have its first word."}}
15 {"type":"assistant.message","data":{"messageId":"605afe54-1441-4858-912d-71c5a75cb917","originatingMessageId":"77f559a5-97e8-4a24-bad7-dc93da90e37a","model":"claude-sonnet-5.5","content":"I couldn't read /etc/hostname: both the file viewer and a shell command were denied permission, so I don't have its first word.","toolRequests":[],"interactionId":"c0d8cfc7-33f8-4d02-b886-6944e80f6517","turnId":"2","rte":true,"apiCallId":"msg_011Cfw8DrCRYusyJVNd765vL"}}
16 {"type":"result","timestamp":"2026-10-11T21:02:18.051Z","sessionId":"7d1e9b2a-3c4f-4a5b-8e6d-1f2a3b4c5d6e","exitCode":0,"usage":{"premiumRequests":1,"totalApiDurationMs":4566,"sessionDurationMs":18400,"codeChanges":{"linesAdded":0,"linesRemoved":0,"filesModified":[]}}}
@@ -0,0 +1,16 @@
1{"type":"user.message","data":{"content":"Read the file /etc/hostname and tell me its first word."}}
2{"type":"assistant.message","data":{"messageId":"4e250083-2155-4889-9ff2-20fda4dd349e","originatingMessageId":"77f559a5-97e8-4a24-bad7-dc93da90e37a","model":"claude-sonnet-5.5","content":"","toolRequests":[{"toolCallId":"toolu_011T3QnmHAVnoqt61ua4UbCf","name":"view","arguments":{"path":"/etc/hostname"},"type":"function","intentionSummary":"view the file at /etc/hostname.","toolTitle":"Viewing file"}],"interactionId":"c0d8cfc7-33f8-4d02-b886-6944e80f6517","turnId":"0","rte":true,"apiCallId":"msg_011Cfw8DPquo2TwEbQnym66c"}}
3{"type":"tool.execution_start","data":{"toolCallId":"toolu_011T3QnmHAVnoqt61ua4UbCf","toolName":"view","arguments":{"path":"/etc/hostname"},"turnId":"0","model":"claude-sonnet-5.5","toolTitle":"Viewing file"}}
4{"type":"assistant.message","data":{"messageId":"22076fc9-351d-4215-a28f-4db06b3e2736","originatingMessageId":"77f559a5-97e8-4a24-bad7-dc93da90e37a","model":"claude-sonnet-5.5","content":"","toolRequests":[{"toolCallId":"toolu_013mVYppotmvxqQa2PWLtY3Q","name":"bash","arguments":{"command":"head -n1 /etc/hostname | awk '{print $1}'","description":"Read first word of /etc/hostname"},"type":"function","intentionSummary":"Read first word of /etc/hostname","toolTitle":"Running command"}],"interactionId":"c0d8cfc7-33f8-4d02-b886-6944e80f6517","turnId":"1","rte":true,"apiCallId":"msg_011Cfw8DaYLqgPRknEndrFMG"}}
5{"type":"tool.execution_start","data":{"toolCallId":"toolu_013mVYppotmvxqQa2PWLtY3Q","toolName":"bash","arguments":{"command":"head -n1 /etc/hostname | awk '{print $1}'","description":"Read first word of /etc/hostname"},"turnId":"1","model":"claude-sonnet-5.5","toolTitle":"Running command","shellToolInfo":{"possiblePaths":["/etc/hostname"],"hasWriteFileRedirection":false}}}
6{"type":"assistant.message_delta","data":{"messageId":"605afe54-1441-4858-912d-71c5a75cb917","deltaContent":"I couldn't read /et"}}
7{"type":"assistant.message_delta","data":{"messageId":"605afe54-1441-4858-912d-71c5a75cb917","deltaContent":"c/hostname:"}}
8{"type":"assistant.message_delta","data":{"messageId":"605afe54-1441-4858-912d-71c5a75cb917","deltaContent":" both the file"}}
9{"type":"assistant.message_delta","data":{"messageId":"605afe54-1441-4858-912d-71c5a75cb917","deltaContent":" vi"}}
10{"type":"assistant.message_delta","data":{"messageId":"605afe54-1441-4858-912d-71c5a75cb917","deltaContent":"ewer and a sh"}}
11{"type":"assistant.message_delta","data":{"messageId":"605afe54-1441-4858-912d-71c5a75cb917","deltaContent":"ell command were denied perm"}}
12{"type":"assistant.message_delta","data":{"messageId":"605afe54-1441-4858-912d-71c5a75cb917","deltaContent":"ission,"}}
13{"type":"assistant.message_delta","data":{"messageId":"605afe54-1441-4858-912d-71c5a75cb917","deltaContent":" so I don"}}
14{"type":"assistant.message_delta","data":{"messageId":"605afe54-1441-4858-912d-71c5a75cb917","deltaContent":"'t have its first word."}}
15{"type":"assistant.message","data":{"messageId":"605afe54-1441-4858-912d-71c5a75cb917","originatingMessageId":"77f559a5-97e8-4a24-bad7-dc93da90e37a","model":"claude-sonnet-5.5","content":"I couldn't read /etc/hostname: both the file viewer and a shell command were denied permission, so I don't have its first word.","toolRequests":[],"interactionId":"c0d8cfc7-33f8-4d02-b886-6944e80f6517","turnId":"2","rte":true,"apiCallId":"msg_011Cfw8DrCRYusyJVNd765vL"}}
16{"type":"result","timestamp":"2026-10-11T21:02:18.051Z","sessionId":"7d1e9b2a-3c4f-4a5b-8e6d-1f2a3b4c5d6e","exitCode":0,"usage":{"premiumRequests":1,"totalApiDurationMs":4566,"sessionDurationMs":18400,"codeChanges":{"linesAdded":0,"linesRemoved":0,"filesModified":[]}}}
crates/agents/tests/parsers.rs added +100 −0
@@ -0,0 +1,100 @@
1 use agents::{OutputFormat, OutputParser, RunEvent, parse_line};
2
3 fn parse_fixture(format: OutputFormat, name: &str) -> Vec<RunEvent> {
4 let path = format!("{}/tests/fixtures/{name}", env!("CARGO_MANIFEST_DIR"));
5 let content = std::fs::read_to_string(path).unwrap();
6 let mut parser = OutputParser::new(format);
7 let mut events: Vec<RunEvent> = content.lines().flat_map(|line| parser.feed(line)).collect();
8 events.extend(parser.finish());
9 events
10 }
11
12 #[test]
13 fn claude_fixture() {
14 let events = parse_fixture(OutputFormat::ClaudeStreamJson, "claude-stream.jsonl");
15 assert!(events.contains(&RunEvent::Step("Reading hostname".to_string())));
16 assert!(events.contains(&RunEvent::SessionId(
17 "3f6a2c1e-6f53-4c8e-9a51-7c2b5d0e9a11".to_string()
18 )));
19 assert_eq!(
20 events.last(),
21 Some(&RunEvent::Final(
22 "The first word in `/etc/hostname` is `HOST01`.".to_string()
23 ))
24 );
25 assert!(events.contains(&RunEvent::Text(
26 "The first word in `/etc/hostname` is `HOST01`.".to_string()
27 )));
28 }
29
30 #[test]
31 fn copilot_fixture() {
32 let events = parse_fixture(OutputFormat::CopilotJsonl, "copilot.jsonl");
33 assert!(events.iter().any(
34 |event| matches!(event, RunEvent::Step(step) if step.contains("Viewing file") && step.contains("/etc/hostname"))
35 ));
36 assert!(events.contains(&RunEvent::SessionId(
37 "7d1e9b2a-3c4f-4a5b-8e6d-1f2a3b4c5d6e".to_string()
38 )));
39 assert!(
40 matches!(events.last(), Some(RunEvent::Final(text)) if text.starts_with("I couldn't read"))
41 );
42 }
43
44 #[test]
45 fn copilot_failure_without_text() {
46 let events = parse_line(
47 OutputFormat::CopilotJsonl,
48 r#"{"type":"result","sessionId":"s","exitCode":1}"#,
49 );
50 assert!(matches!(events.last(), Some(RunEvent::Failed(_))));
51 }
52
53 #[test]
54 fn claude_tool_labels_and_failures() {
55 let label = |name: &str, input: &str| {
56 let line = format!(
57 r#"{{"type":"assistant","message":{{"content":[{{"type":"tool_use","name":"{name}","input":{input}}}]}}}}"#
58 );
59 parse_line(OutputFormat::ClaudeStreamJson, &line)
60 };
61 assert_eq!(
62 label("WebFetch", r#"{"url":"https://example.com/a/b"}"#),
63 vec![RunEvent::Step("Reading example.com".to_string())]
64 );
65 assert_eq!(
66 label("Grep", r#"{"pattern":"foo"}"#),
67 vec![RunEvent::Step("Searching \"foo\"".to_string())]
68 );
69 assert_eq!(
70 label("Bash", r#"{"command":"ls"}"#),
71 vec![RunEvent::Step("Running ls".to_string())]
72 );
73 assert_eq!(
74 label("Mystery", "{}"),
75 vec![RunEvent::Step("Mystery".to_string())]
76 );
77 assert_eq!(
78 parse_line(
79 OutputFormat::ClaudeStreamJson,
80 r#"{"type":"result","subtype":"error_max_turns","is_error":true}"#
81 ),
82 vec![RunEvent::Failed("error_max_turns".to_string())]
83 );
84 assert!(parse_line(OutputFormat::ClaudeStreamJson, "not json").is_empty());
85 }
86
87 #[test]
88 fn text_format_accumulates() {
89 let mut parser = OutputParser::new(OutputFormat::Text);
90 assert_eq!(
91 parser.feed("hello"),
92 vec![RunEvent::Step("hello".to_string())]
93 );
94 assert!(parser.feed("").is_empty());
95 parser.feed("world");
96 assert_eq!(
97 parser.finish(),
98 vec![RunEvent::Final("hello\n\nworld".to_string())]
99 );
100 }
@@ -0,0 +1,100 @@
1use agents::{OutputFormat, OutputParser, RunEvent, parse_line};
2
3fn parse_fixture(format: OutputFormat, name: &str) -> Vec<RunEvent> {
4 let path = format!("{}/tests/fixtures/{name}", env!("CARGO_MANIFEST_DIR"));
5 let content = std::fs::read_to_string(path).unwrap();
6 let mut parser = OutputParser::new(format);
7 let mut events: Vec<RunEvent> = content.lines().flat_map(|line| parser.feed(line)).collect();
8 events.extend(parser.finish());
9 events
10}
11
12#[test]
13fn claude_fixture() {
14 let events = parse_fixture(OutputFormat::ClaudeStreamJson, "claude-stream.jsonl");
15 assert!(events.contains(&RunEvent::Step("Reading hostname".to_string())));
16 assert!(events.contains(&RunEvent::SessionId(
17 "3f6a2c1e-6f53-4c8e-9a51-7c2b5d0e9a11".to_string()
18 )));
19 assert_eq!(
20 events.last(),
21 Some(&RunEvent::Final(
22 "The first word in `/etc/hostname` is `HOST01`.".to_string()
23 ))
24 );
25 assert!(events.contains(&RunEvent::Text(
26 "The first word in `/etc/hostname` is `HOST01`.".to_string()
27 )));
28}
29
30#[test]
31fn copilot_fixture() {
32 let events = parse_fixture(OutputFormat::CopilotJsonl, "copilot.jsonl");
33 assert!(events.iter().any(
34 |event| matches!(event, RunEvent::Step(step) if step.contains("Viewing file") && step.contains("/etc/hostname"))
35 ));
36 assert!(events.contains(&RunEvent::SessionId(
37 "7d1e9b2a-3c4f-4a5b-8e6d-1f2a3b4c5d6e".to_string()
38 )));
39 assert!(
40 matches!(events.last(), Some(RunEvent::Final(text)) if text.starts_with("I couldn't read"))
41 );
42}
43
44#[test]
45fn copilot_failure_without_text() {
46 let events = parse_line(
47 OutputFormat::CopilotJsonl,
48 r#"{"type":"result","sessionId":"s","exitCode":1}"#,
49 );
50 assert!(matches!(events.last(), Some(RunEvent::Failed(_))));
51}
52
53#[test]
54fn claude_tool_labels_and_failures() {
55 let label = |name: &str, input: &str| {
56 let line = format!(
57 r#"{{"type":"assistant","message":{{"content":[{{"type":"tool_use","name":"{name}","input":{input}}}]}}}}"#
58 );
59 parse_line(OutputFormat::ClaudeStreamJson, &line)
60 };
61 assert_eq!(
62 label("WebFetch", r#"{"url":"https://example.com/a/b"}"#),
63 vec![RunEvent::Step("Reading example.com".to_string())]
64 );
65 assert_eq!(
66 label("Grep", r#"{"pattern":"foo"}"#),
67 vec![RunEvent::Step("Searching \"foo\"".to_string())]
68 );
69 assert_eq!(
70 label("Bash", r#"{"command":"ls"}"#),
71 vec![RunEvent::Step("Running ls".to_string())]
72 );
73 assert_eq!(
74 label("Mystery", "{}"),
75 vec![RunEvent::Step("Mystery".to_string())]
76 );
77 assert_eq!(
78 parse_line(
79 OutputFormat::ClaudeStreamJson,
80 r#"{"type":"result","subtype":"error_max_turns","is_error":true}"#
81 ),
82 vec![RunEvent::Failed("error_max_turns".to_string())]
83 );
84 assert!(parse_line(OutputFormat::ClaudeStreamJson, "not json").is_empty());
85}
86
87#[test]
88fn text_format_accumulates() {
89 let mut parser = OutputParser::new(OutputFormat::Text);
90 assert_eq!(
91 parser.feed("hello"),
92 vec![RunEvent::Step("hello".to_string())]
93 );
94 assert!(parser.feed("").is_empty());
95 parser.feed("world");
96 assert_eq!(
97 parser.finish(),
98 vec![RunEvent::Final("hello\n\nworld".to_string())]
99 );
100}
crates/agents/tests/runner.rs added +176 −0
@@ -0,0 +1,176 @@
1 #![cfg(unix)]
2
3 use std::time::{Duration, Instant};
4
5 use agents::{Invocation, OutputFormat, RunEvent, RunPlan, RunStatus, RunUpdate, probe, run};
6 use tokio::sync::{mpsc, oneshot};
7
8 fn plan(program: &str, args: &[&str], stdin: Option<&str>) -> RunPlan {
9 RunPlan {
10 run: Invocation {
11 program: program.to_string(),
12 args: args.iter().map(|arg| arg.to_string()).collect(),
13 cwd: Some("/".into()),
14 stdin: stdin.map(str::to_string),
15 },
16 stop: None,
17 cleanup: Vec::new(),
18 }
19 }
20
21 #[tokio::test]
22 async fn completes_with_claude_final_text() {
23 let fixture = format!(
24 "{}/tests/fixtures/claude-stream.jsonl",
25 env!("CARGO_MANIFEST_DIR")
26 );
27 let (sender, mut receiver) = mpsc::unbounded_channel();
28 let (_keep_alive, stop) = oneshot::channel();
29 let outcome = run(
30 plan("sh", &["-c", &format!("cat '{fixture}'")], Some("prompt")),
31 OutputFormat::ClaudeStreamJson,
32 sender,
33 stop,
34 )
35 .await;
36 assert_eq!(
37 outcome.status,
38 RunStatus::Completed {
39 final_text: "The first word in `/etc/hostname` is `HOST01`.".to_string()
40 }
41 );
42 assert_eq!(outcome.exit_code, Some(0));
43 let mut saw_step = false;
44 while let Ok(update) = receiver.try_recv() {
45 if update == RunUpdate::Event(RunEvent::Step("Reading hostname".to_string())) {
46 saw_step = true;
47 }
48 }
49 assert!(saw_step);
50 }
51
52 #[tokio::test]
53 async fn failing_command_reports_stderr() {
54 let (sender, mut receiver) = mpsc::unbounded_channel();
55 let (_keep_alive, stop) = oneshot::channel();
56 let outcome = run(
57 plan("sh", &["-c", "echo boom >&2; exit 3"], None),
58 OutputFormat::ClaudeStreamJson,
59 sender,
60 stop,
61 )
62 .await;
63 assert_eq!(outcome.exit_code, Some(3));
64 match outcome.status {
65 RunStatus::Failed {
66 message,
67 stderr_tail,
68 } => {
69 assert_eq!(message, "boom");
70 assert_eq!(stderr_tail, vec!["boom".to_string()]);
71 }
72 other => panic!("unexpected status {other:?}"),
73 }
74 assert_eq!(
75 receiver.try_recv().ok(),
76 Some(RunUpdate::Stderr("boom".to_string()))
77 );
78 }
79
80 #[tokio::test]
81 async fn missing_program_fails_readably() {
82 let (sender, _receiver) = mpsc::unbounded_channel();
83 let (_keep_alive, stop) = oneshot::channel();
84 let outcome = run(
85 plan("definitely-not-a-real-program", &[], None),
86 OutputFormat::Text,
87 sender,
88 stop,
89 )
90 .await;
91 assert!(matches!(
92 outcome.status,
93 RunStatus::Failed { message, .. } if message.contains("cannot start definitely-not-a-real-program")
94 ));
95 }
96
97 #[tokio::test]
98 async fn stop_kills_the_process() {
99 let (sender, _receiver) = mpsc::unbounded_channel();
100 let (stop_sender, stop) = oneshot::channel();
101 let started = Instant::now();
102 let handle = tokio::spawn(run(
103 plan("sh", &["-c", "sleep 30"], None),
104 OutputFormat::Text,
105 sender,
106 stop,
107 ));
108 tokio::time::sleep(Duration::from_millis(200)).await;
109 stop_sender.send(()).unwrap();
110 let outcome = handle.await.unwrap();
111 assert_eq!(outcome.status, RunStatus::Stopped);
112 assert!(started.elapsed() < Duration::from_secs(2));
113 }
114
115 #[tokio::test]
116 async fn probe_returns_the_first_output_line() {
117 let invocation = Invocation {
118 program: "sh".to_string(),
119 args: ["-c", "echo '2.1.290 (Claude Code)'; echo more"]
120 .map(String::from)
121 .to_vec(),
122 cwd: None,
123 stdin: None,
124 };
125 assert_eq!(
126 probe(&invocation).await,
127 Ok("2.1.290 (Claude Code)".to_string())
128 );
129 }
130
131 #[tokio::test]
132 async fn probe_reports_stderr_of_a_failing_command() {
133 let invocation = Invocation {
134 program: "sh".to_string(),
135 args: ["-c", "echo 'not logged in' >&2; exit 2"]
136 .map(String::from)
137 .to_vec(),
138 cwd: None,
139 stdin: None,
140 };
141 assert_eq!(probe(&invocation).await, Err("not logged in".to_string()));
142 let missing = Invocation {
143 program: "definitely-not-a-program".to_string(),
144 args: Vec::new(),
145 cwd: None,
146 stdin: None,
147 };
148 assert!(
149 probe(&missing)
150 .await
151 .unwrap_err()
152 .starts_with("cannot start")
153 );
154 }
155
156 #[tokio::test]
157 async fn cleanup_files_are_removed_when_the_run_ends() {
158 let directory = tempfile::tempdir().unwrap();
159 let config = directory.path().join("mcp.json");
160 std::fs::write(&config, "{}").unwrap();
161 let mut finished_plan = plan("sh", &["-c", "exit 0"], None);
162 finished_plan.cleanup = vec![config.clone()];
163 let (sender, _receiver) = mpsc::unbounded_channel();
164 let (_keep_alive, stop) = oneshot::channel();
165 run(finished_plan, OutputFormat::ClaudeStreamJson, sender, stop).await;
166 assert!(!config.exists());
167
168 std::fs::write(&config, "{}").unwrap();
169 let mut stopped_plan = plan("sleep", &["30"], None);
170 stopped_plan.cleanup = vec![config.clone()];
171 let (sender, _receiver) = mpsc::unbounded_channel();
172 let (stop_sender, stop) = oneshot::channel();
173 stop_sender.send(()).unwrap();
174 run(stopped_plan, OutputFormat::ClaudeStreamJson, sender, stop).await;
175 assert!(!config.exists());
176 }
@@ -0,0 +1,176 @@
1#![cfg(unix)]
2
3use std::time::{Duration, Instant};
4
5use agents::{Invocation, OutputFormat, RunEvent, RunPlan, RunStatus, RunUpdate, probe, run};
6use tokio::sync::{mpsc, oneshot};
7
8fn plan(program: &str, args: &[&str], stdin: Option<&str>) -> RunPlan {
9 RunPlan {
10 run: Invocation {
11 program: program.to_string(),
12 args: args.iter().map(|arg| arg.to_string()).collect(),
13 cwd: Some("/".into()),
14 stdin: stdin.map(str::to_string),
15 },
16 stop: None,
17 cleanup: Vec::new(),
18 }
19}
20
21#[tokio::test]
22async fn completes_with_claude_final_text() {
23 let fixture = format!(
24 "{}/tests/fixtures/claude-stream.jsonl",
25 env!("CARGO_MANIFEST_DIR")
26 );
27 let (sender, mut receiver) = mpsc::unbounded_channel();
28 let (_keep_alive, stop) = oneshot::channel();
29 let outcome = run(
30 plan("sh", &["-c", &format!("cat '{fixture}'")], Some("prompt")),
31 OutputFormat::ClaudeStreamJson,
32 sender,
33 stop,
34 )
35 .await;
36 assert_eq!(
37 outcome.status,
38 RunStatus::Completed {
39 final_text: "The first word in `/etc/hostname` is `HOST01`.".to_string()
40 }
41 );
42 assert_eq!(outcome.exit_code, Some(0));
43 let mut saw_step = false;
44 while let Ok(update) = receiver.try_recv() {
45 if update == RunUpdate::Event(RunEvent::Step("Reading hostname".to_string())) {
46 saw_step = true;
47 }
48 }
49 assert!(saw_step);
50}
51
52#[tokio::test]
53async fn failing_command_reports_stderr() {
54 let (sender, mut receiver) = mpsc::unbounded_channel();
55 let (_keep_alive, stop) = oneshot::channel();
56 let outcome = run(
57 plan("sh", &["-c", "echo boom >&2; exit 3"], None),
58 OutputFormat::ClaudeStreamJson,
59 sender,
60 stop,
61 )
62 .await;
63 assert_eq!(outcome.exit_code, Some(3));
64 match outcome.status {
65 RunStatus::Failed {
66 message,
67 stderr_tail,
68 } => {
69 assert_eq!(message, "boom");
70 assert_eq!(stderr_tail, vec!["boom".to_string()]);
71 }
72 other => panic!("unexpected status {other:?}"),
73 }
74 assert_eq!(
75 receiver.try_recv().ok(),
76 Some(RunUpdate::Stderr("boom".to_string()))
77 );
78}
79
80#[tokio::test]
81async fn missing_program_fails_readably() {
82 let (sender, _receiver) = mpsc::unbounded_channel();
83 let (_keep_alive, stop) = oneshot::channel();
84 let outcome = run(
85 plan("definitely-not-a-real-program", &[], None),
86 OutputFormat::Text,
87 sender,
88 stop,
89 )
90 .await;
91 assert!(matches!(
92 outcome.status,
93 RunStatus::Failed { message, .. } if message.contains("cannot start definitely-not-a-real-program")
94 ));
95}
96
97#[tokio::test]
98async fn stop_kills_the_process() {
99 let (sender, _receiver) = mpsc::unbounded_channel();
100 let (stop_sender, stop) = oneshot::channel();
101 let started = Instant::now();
102 let handle = tokio::spawn(run(
103 plan("sh", &["-c", "sleep 30"], None),
104 OutputFormat::Text,
105 sender,
106 stop,
107 ));
108 tokio::time::sleep(Duration::from_millis(200)).await;
109 stop_sender.send(()).unwrap();
110 let outcome = handle.await.unwrap();
111 assert_eq!(outcome.status, RunStatus::Stopped);
112 assert!(started.elapsed() < Duration::from_secs(2));
113}
114
115#[tokio::test]
116async fn probe_returns_the_first_output_line() {
117 let invocation = Invocation {
118 program: "sh".to_string(),
119 args: ["-c", "echo '2.1.290 (Claude Code)'; echo more"]
120 .map(String::from)
121 .to_vec(),
122 cwd: None,
123 stdin: None,
124 };
125 assert_eq!(
126 probe(&invocation).await,
127 Ok("2.1.290 (Claude Code)".to_string())
128 );
129}
130
131#[tokio::test]
132async fn probe_reports_stderr_of_a_failing_command() {
133 let invocation = Invocation {
134 program: "sh".to_string(),
135 args: ["-c", "echo 'not logged in' >&2; exit 2"]
136 .map(String::from)
137 .to_vec(),
138 cwd: None,
139 stdin: None,
140 };
141 assert_eq!(probe(&invocation).await, Err("not logged in".to_string()));
142 let missing = Invocation {
143 program: "definitely-not-a-program".to_string(),
144 args: Vec::new(),
145 cwd: None,
146 stdin: None,
147 };
148 assert!(
149 probe(&missing)
150 .await
151 .unwrap_err()
152 .starts_with("cannot start")
153 );
154}
155
156#[tokio::test]
157async fn cleanup_files_are_removed_when_the_run_ends() {
158 let directory = tempfile::tempdir().unwrap();
159 let config = directory.path().join("mcp.json");
160 std::fs::write(&config, "{}").unwrap();
161 let mut finished_plan = plan("sh", &["-c", "exit 0"], None);
162 finished_plan.cleanup = vec![config.clone()];
163 let (sender, _receiver) = mpsc::unbounded_channel();
164 let (_keep_alive, stop) = oneshot::channel();
165 run(finished_plan, OutputFormat::ClaudeStreamJson, sender, stop).await;
166 assert!(!config.exists());
167
168 std::fs::write(&config, "{}").unwrap();
169 let mut stopped_plan = plan("sleep", &["30"], None);
170 stopped_plan.cleanup = vec![config.clone()];
171 let (sender, _receiver) = mpsc::unbounded_channel();
172 let (stop_sender, stop) = oneshot::channel();
173 stop_sender.send(()).unwrap();
174 run(stopped_plan, OutputFormat::ClaudeStreamJson, sender, stop).await;
175 assert!(!config.exists());
176}
crates/app/Cargo.toml +1 −0
@@ -18,6 +18,7 @@ gpui-kit = { workspace = true, features = ["test-support"] }
18 18 tempfile.workspace = true
19 19
20 20 [dependencies]
21 agents.workspace = true
21 22 calling.workspace = true
22 23 chatsvc.workspace = true
23 24 chrono.workspace = true
@@ -18,6 +18,7 @@ gpui-kit = { workspace = true, features = ["test-support"] }
18tempfile.workspace = true
18tempfile.workspace = true
19
19
20[dependencies]
20[dependencies]
21agents.workspace = true
21calling.workspace = true
22calling.workspace = true
22chatsvc.workspace = true
23chatsvc.workspace = true
23chrono.workspace = true
24chrono.workspace = true
crates/app/assets/symbols/spinner_arc.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="4" stroke-linecap="round"><path d="M12 2a10 10 0 0 1 10 10"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="4" stroke-linecap="round"><path d="M12 2a10 10 0 0 1 10 10"/></svg>
crates/app/assets/symbols/spinner_track.svg added +1 −0
@@ -0,0 +1 @@
1 <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="4"><circle cx="12" cy="12" r="10"/></svg>
@@ -0,0 +1 @@
1<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="4"><circle cx="12" cy="12" r="10"/></svg>
crates/app/src/agents/demo.rs added +101 −0
@@ -0,0 +1,101 @@
1 use std::time::Duration;
2
3 use chrono::{Duration as ChronoDuration, Utc};
4 use store::MessageRecord;
5
6 use super::runs::{AgentRun, RunState};
7 use crate::app_state::{AppState, Selection};
8 use crate::rows::message_text;
9
10 const DEMO_RUN_COUNT: usize = 3;
11
12 fn run_for(
13 id: u64,
14 record: &MessageRecord,
15 label: &str,
16 state: RunState,
17 steps: &[(u64, &str)],
18 elapsed_seconds: i64,
19 ) -> AgentRun {
20 let started_at = Utc::now() - ChronoDuration::seconds(elapsed_seconds);
21 let finished = state != RunState::Running;
22 let current_step = match &state {
23 RunState::Done => "Done - reply proposed".to_owned(),
24 RunState::Failed { message, .. } => message.clone(),
25 _ => steps
26 .last()
27 .map(|(_, text)| (*text).to_owned())
28 .unwrap_or_default(),
29 };
30 AgentRun {
31 id,
32 action_id: label.to_lowercase().replace(' ', "-"),
33 action_label: label.to_owned(),
34 agent_id: "claude".to_owned(),
35 agent_name: "Claude Code (WSL)".to_owned(),
36 conversation_id: record.conversation_id.clone(),
37 message_id: record.message_id.clone(),
38 chat_title: "Release".to_owned(),
39 sender_name: record.sender_name.clone().unwrap_or_default(),
40 session_id: format!("demo-session-{id}"),
41 working_dir: "~".to_owned(),
42 extra: message_text(record),
43 state,
44 current_step,
45 steps: steps
46 .iter()
47 .map(|(seconds, text)| (Duration::from_secs(*seconds), (*text).to_owned()))
48 .collect(),
49 final_text: "Group the shift report by plant, then export it.".to_owned(),
50 started_at,
51 ended_at: finished.then(|| started_at + ChronoDuration::seconds(elapsed_seconds)),
52 expanded: false,
53 dismissed: false,
54 }
55 }
56
57 pub fn runs(app: &AppState) -> Vec<AgentRun> {
58 let (Selection::Chat(conversation_id) | Selection::Channel(conversation_id)) =
59 crate::demo::first_selection();
60 let records = app
61 .store
62 .messages(&conversation_id, None, DEMO_RUN_COUNT)
63 .unwrap_or_default();
64 let [done, failed, running] = records.as_slice() else {
65 return Vec::new();
66 };
67 vec![
68 run_for(
69 1,
70 done,
71 "Answer this",
72 RunState::Done,
73 &[(4, "Read ShiftReport.cs")],
74 118,
75 ),
76 run_for(
77 2,
78 failed,
79 "Build this",
80 RunState::Failed {
81 message: "claude exited 1: Not logged in".to_owned(),
82 log: vec!["Not logged in".to_owned(), "Run claude /login".to_owned()],
83 },
84 &[],
85 3,
86 ),
87 run_for(
88 3,
89 running,
90 "Build this",
91 RunState::Running,
92 &[
93 (4, "Read ShiftReportService.cs"),
94 (72, "Searched \"ExportFormat\""),
95 (190, "Edited ShiftReportExport.cs"),
96 (391, "Running dotnet test --filter ShiftReport"),
97 ],
98 391,
99 ),
100 ]
101 }
@@ -0,0 +1,101 @@
1use std::time::Duration;
2
3use chrono::{Duration as ChronoDuration, Utc};
4use store::MessageRecord;
5
6use super::runs::{AgentRun, RunState};
7use crate::app_state::{AppState, Selection};
8use crate::rows::message_text;
9
10const DEMO_RUN_COUNT: usize = 3;
11
12fn run_for(
13 id: u64,
14 record: &MessageRecord,
15 label: &str,
16 state: RunState,
17 steps: &[(u64, &str)],
18 elapsed_seconds: i64,
19) -> AgentRun {
20 let started_at = Utc::now() - ChronoDuration::seconds(elapsed_seconds);
21 let finished = state != RunState::Running;
22 let current_step = match &state {
23 RunState::Done => "Done - reply proposed".to_owned(),
24 RunState::Failed { message, .. } => message.clone(),
25 _ => steps
26 .last()
27 .map(|(_, text)| (*text).to_owned())
28 .unwrap_or_default(),
29 };
30 AgentRun {
31 id,
32 action_id: label.to_lowercase().replace(' ', "-"),
33 action_label: label.to_owned(),
34 agent_id: "claude".to_owned(),
35 agent_name: "Claude Code (WSL)".to_owned(),
36 conversation_id: record.conversation_id.clone(),
37 message_id: record.message_id.clone(),
38 chat_title: "Release".to_owned(),
39 sender_name: record.sender_name.clone().unwrap_or_default(),
40 session_id: format!("demo-session-{id}"),
41 working_dir: "~".to_owned(),
42 extra: message_text(record),
43 state,
44 current_step,
45 steps: steps
46 .iter()
47 .map(|(seconds, text)| (Duration::from_secs(*seconds), (*text).to_owned()))
48 .collect(),
49 final_text: "Group the shift report by plant, then export it.".to_owned(),
50 started_at,
51 ended_at: finished.then(|| started_at + ChronoDuration::seconds(elapsed_seconds)),
52 expanded: false,
53 dismissed: false,
54 }
55}
56
57pub fn runs(app: &AppState) -> Vec<AgentRun> {
58 let (Selection::Chat(conversation_id) | Selection::Channel(conversation_id)) =
59 crate::demo::first_selection();
60 let records = app
61 .store
62 .messages(&conversation_id, None, DEMO_RUN_COUNT)
63 .unwrap_or_default();
64 let [done, failed, running] = records.as_slice() else {
65 return Vec::new();
66 };
67 vec![
68 run_for(
69 1,
70 done,
71 "Answer this",
72 RunState::Done,
73 &[(4, "Read ShiftReport.cs")],
74 118,
75 ),
76 run_for(
77 2,
78 failed,
79 "Build this",
80 RunState::Failed {
81 message: "claude exited 1: Not logged in".to_owned(),
82 log: vec!["Not logged in".to_owned(), "Run claude /login".to_owned()],
83 },
84 &[],
85 3,
86 ),
87 run_for(
88 3,
89 running,
90 "Build this",
91 RunState::Running,
92 &[
93 (4, "Read ShiftReportService.cs"),
94 (72, "Searched \"ExportFormat\""),
95 (190, "Edited ShiftReportExport.cs"),
96 (391, "Running dotnet test --filter ShiftReport"),
97 ],
98 391,
99 ),
100 ]
101}
crates/app/src/agents/mcp_bridge.rs added +16 −0
@@ -0,0 +1,16 @@
1 use gpui_kit::*;
2
3 pub fn endpoint(cx: &App) -> Option<agents::McpEndpoint> {
4 crate::agent_api::mcp_endpoint(cx).map(|endpoint| agents::McpEndpoint {
5 url: endpoint.url,
6 token: endpoint.token,
7 })
8 }
9
10 pub fn chat_allowed(conversation_id: &str, cx: &App) -> bool {
11 crate::agent_api::chat_allowed(conversation_id, cx)
12 }
13
14 pub fn allow_chat(conversation_id: &str, cx: &mut App) {
15 crate::agent_api::allow_chat(conversation_id, cx);
16 }
@@ -0,0 +1,16 @@
1use gpui_kit::*;
2
3pub fn endpoint(cx: &App) -> Option<agents::McpEndpoint> {
4 crate::agent_api::mcp_endpoint(cx).map(|endpoint| agents::McpEndpoint {
5 url: endpoint.url,
6 token: endpoint.token,
7 })
8}
9
10pub fn chat_allowed(conversation_id: &str, cx: &App) -> bool {
11 crate::agent_api::chat_allowed(conversation_id, cx)
12}
13
14pub fn allow_chat(conversation_id: &str, cx: &mut App) {
15 crate::agent_api::allow_chat(conversation_id, cx);
16}
crates/app/src/agents/message_context.rs added +226 −0
@@ -0,0 +1,226 @@
1 use agents::{AgentAction, MessageContext, ThreadMessage, build_prompt};
2 use chrono::Local;
3 use store::MessageRecord;
4
5 use crate::app_state::{AppState, Selection, selection_title};
6 use crate::notify::selection_for;
7 use crate::people::local_names;
8 use crate::rows::message_text;
9
10 const THREAD_LIMIT: usize = 20;
11 const UNKNOWN_SENDER: &str = "Unknown";
12 const SESSION_PLACEHOLDER: &str = "(session id)";
13 const TIME_FORMAT: &str = "%Y-%m-%d %H:%M";
14
15 fn earlier_records(
16 state: &AppState,
17 selection: Option<&Selection>,
18 record: &MessageRecord,
19 ) -> Vec<MessageRecord> {
20 let conversation_id = record.conversation_id.as_str();
21 let mut earlier = match selection {
22 Some(Selection::Channel(_)) => {
23 let root_id = record
24 .reply_to_id
25 .clone()
26 .unwrap_or_else(|| record.message_id.clone());
27 let mut thread = state
28 .store
29 .thread_messages(conversation_id, &root_id)
30 .unwrap_or_default();
31 thread.retain(|entry| entry.created_at < record.created_at);
32 thread
33 }
34 _ => state
35 .store
36 .messages(conversation_id, Some(record.created_at), THREAD_LIMIT)
37 .unwrap_or_default(),
38 };
39 earlier.retain(|entry| !entry.deleted);
40 let skipped = earlier.len().saturating_sub(THREAD_LIMIT);
41 earlier.split_off(skipped)
42 }
43
44 pub fn build(state: &AppState, conversation_id: &str, message_id: &str) -> Option<MessageContext> {
45 let record = state
46 .store
47 .messages_by_id(conversation_id, &[message_id.to_owned()])
48 .ok()?
49 .remove(message_id)
50 .filter(|record| !record.deleted)?;
51 let names = local_names(state);
52 let sender_of = |entry: &MessageRecord| {
53 entry
54 .sender_name
55 .clone()
56 .filter(|name| !name.trim().is_empty())
57 .or_else(|| {
58 entry
59 .sender_id
60 .as_ref()
61 .and_then(|user_id| names.get(user_id).cloned())
62 })
63 .unwrap_or_else(|| UNKNOWN_SENDER.to_owned())
64 };
65 let selection = selection_for(&state.sidebar, conversation_id);
66 let chat = selection
67 .as_ref()
68 .map(|selection| selection_title(&state.sidebar, selection))
69 .unwrap_or_else(|| "Chat".to_owned());
70 let thread = earlier_records(state, selection.as_ref(), &record)
71 .iter()
72 .map(|entry| ThreadMessage {
73 sender: sender_of(entry),
74 text: message_text(entry),
75 time: entry
76 .created_at
77 .with_timezone(&Local)
78 .format(TIME_FORMAT)
79 .to_string(),
80 })
81 .collect();
82 Some(MessageContext {
83 sender: sender_of(&record),
84 chat,
85 conversation_id: conversation_id.to_owned(),
86 message_id: message_id.to_owned(),
87 message: message_text(&record),
88 thread,
89 })
90 }
91
92 pub fn preview_prompt(
93 state: &AppState,
94 action: &AgentAction,
95 conversation_id: &str,
96 message_id: &str,
97 extra: &str,
98 ) -> Option<String> {
99 let context = build(state, conversation_id, message_id)?;
100 Some(build_prompt(
101 action,
102 &context,
103 extra,
104 SESSION_PLACEHOLDER,
105 &action.agent_id,
106 ))
107 }
108
109 #[cfg(test)]
110 mod tests {
111 use std::sync::Arc;
112
113 use chrono::{TimeZone, Utc};
114 use store::{ChatRecord, Store};
115
116 use super::*;
117 use crate::app_state::Mode;
118
119 fn message(id: &str, reply_to: Option<&str>, minute: u32, sender: &str) -> MessageRecord {
120 MessageRecord {
121 conversation_id: "19:chat".to_owned(),
122 message_id: id.to_owned(),
123 reply_to_id: reply_to.map(str::to_owned),
124 sender_name: Some(sender.to_owned()),
125 created_at: Utc.with_ymd_and_hms(2026, 10, 1, 9, minute, 0).unwrap(),
126 body_html: format!("<p>text {id}</p>"),
127 attachments_json: "[]".to_owned(),
128 reactions_json: "[]".to_owned(),
129 mentions_json: "[]".to_owned(),
130 links_json: "[]".to_owned(),
131 ..MessageRecord::default()
132 }
133 }
134
135 fn state_with(records: &[MessageRecord]) -> AppState {
136 let store = Arc::new(Store::open_in_memory().unwrap());
137 store.upsert_messages(records).unwrap();
138 let mut state = AppState::new(store, Mode::default());
139 state.sidebar.chats.push(ChatRecord {
140 id: "19:chat".to_owned(),
141 kind: "chat".to_owned(),
142 title: "Ops".to_owned(),
143 member_summary: String::new(),
144 last_message_at: None,
145 last_read_at: None,
146 unread: false,
147 muted: false,
148 members: Vec::new(),
149 last_message_preview: None,
150 last_message_sender_id: None,
151 last_message_sender_name: None,
152 last_message_deleted: false,
153 last_event_system: false,
154 });
155 state
156 }
157
158 #[test]
159 fn chat_context_takes_up_to_twenty_earlier_messages_oldest_first() {
160 let records: Vec<MessageRecord> = (0..30)
161 .map(|minute| message(&format!("m{minute}"), None, minute, "Ada"))
162 .collect();
163 let state = state_with(&records);
164 let context = build(&state, "19:chat", "m25").unwrap();
165 assert_eq!(context.chat, "Ops");
166 assert_eq!(context.sender, "Ada");
167 assert_eq!(context.message, "text m25");
168 assert_eq!(context.thread.len(), 20);
169 assert_eq!(context.thread[0].text, "text m5");
170 assert_eq!(context.thread[19].text, "text m24");
171 }
172
173 #[test]
174 fn deleted_and_missing_messages_give_no_context() {
175 let mut deleted = message("m1", None, 1, "Ada");
176 deleted.deleted = true;
177 let state = state_with(&[deleted]);
178 assert!(build(&state, "19:chat", "m1").is_none());
179 assert!(build(&state, "19:chat", "nope").is_none());
180 }
181
182 #[test]
183 fn channel_context_follows_the_thread_root() {
184 let records = [
185 message("root", None, 1, "Ada"),
186 message("other", None, 2, "Bo"),
187 message("reply-1", Some("root"), 3, "Cy"),
188 message("reply-2", Some("root"), 4, "Di"),
189 ];
190 let mut state = state_with(&records);
191 state.sidebar.chats.clear();
192 state.sidebar.teams.push(store::SidebarTeam {
193 team: store::TeamRecord {
194 id: "team".to_owned(),
195 name: "Platform".to_owned(),
196 },
197 channels: vec![store::ChannelRecord {
198 id: "19:chat".to_owned(),
199 team_id: "team".to_owned(),
200 name: "Releases".to_owned(),
201 membership_type: None,
202 last_message_at: None,
203 unread: false,
204 }],
205 hidden: false,
206 hidden_channel_ids: Vec::new(),
207 notifications: Default::default(),
208 });
209 let context = build(&state, "19:chat", "reply-2").unwrap();
210 let texts: Vec<&str> = context
211 .thread
212 .iter()
213 .map(|entry| entry.text.as_str())
214 .collect();
215 assert_eq!(texts, ["text root", "text reply-1"]);
216 }
217
218 #[test]
219 fn preview_renders_the_template_with_a_session_placeholder() {
220 let state = state_with(&[message("m1", None, 1, "Ada")]);
221 let action = AgentAction::answer_this("claude");
222 let prompt = preview_prompt(&state, &action, "19:chat", "m1", "").unwrap();
223 assert!(prompt.starts_with("Ada asked me in the Teams chat \"Ops\""));
224 assert!(prompt.contains("session_id \"(session id)\""));
225 }
226 }
@@ -0,0 +1,226 @@
1use agents::{AgentAction, MessageContext, ThreadMessage, build_prompt};
2use chrono::Local;
3use store::MessageRecord;
4
5use crate::app_state::{AppState, Selection, selection_title};
6use crate::notify::selection_for;
7use crate::people::local_names;
8use crate::rows::message_text;
9
10const THREAD_LIMIT: usize = 20;
11const UNKNOWN_SENDER: &str = "Unknown";
12const SESSION_PLACEHOLDER: &str = "(session id)";
13const TIME_FORMAT: &str = "%Y-%m-%d %H:%M";
14
15fn earlier_records(
16 state: &AppState,
17 selection: Option<&Selection>,
18 record: &MessageRecord,
19) -> Vec<MessageRecord> {
20 let conversation_id = record.conversation_id.as_str();
21 let mut earlier = match selection {
22 Some(Selection::Channel(_)) => {
23 let root_id = record
24 .reply_to_id
25 .clone()
26 .unwrap_or_else(|| record.message_id.clone());
27 let mut thread = state
28 .store
29 .thread_messages(conversation_id, &root_id)
30 .unwrap_or_default();
31 thread.retain(|entry| entry.created_at < record.created_at);
32 thread
33 }
34 _ => state
35 .store
36 .messages(conversation_id, Some(record.created_at), THREAD_LIMIT)
37 .unwrap_or_default(),
38 };
39 earlier.retain(|entry| !entry.deleted);
40 let skipped = earlier.len().saturating_sub(THREAD_LIMIT);
41 earlier.split_off(skipped)
42}
43
44pub fn build(state: &AppState, conversation_id: &str, message_id: &str) -> Option<MessageContext> {
45 let record = state
46 .store
47 .messages_by_id(conversation_id, &[message_id.to_owned()])
48 .ok()?
49 .remove(message_id)
50 .filter(|record| !record.deleted)?;
51 let names = local_names(state);
52 let sender_of = |entry: &MessageRecord| {
53 entry
54 .sender_name
55 .clone()
56 .filter(|name| !name.trim().is_empty())
57 .or_else(|| {
58 entry
59 .sender_id
60 .as_ref()
61 .and_then(|user_id| names.get(user_id).cloned())
62 })
63 .unwrap_or_else(|| UNKNOWN_SENDER.to_owned())
64 };
65 let selection = selection_for(&state.sidebar, conversation_id);
66 let chat = selection
67 .as_ref()
68 .map(|selection| selection_title(&state.sidebar, selection))
69 .unwrap_or_else(|| "Chat".to_owned());
70 let thread = earlier_records(state, selection.as_ref(), &record)
71 .iter()
72 .map(|entry| ThreadMessage {
73 sender: sender_of(entry),
74 text: message_text(entry),
75 time: entry
76 .created_at
77 .with_timezone(&Local)
78 .format(TIME_FORMAT)
79 .to_string(),
80 })
81 .collect();
82 Some(MessageContext {
83 sender: sender_of(&record),
84 chat,
85 conversation_id: conversation_id.to_owned(),
86 message_id: message_id.to_owned(),
87 message: message_text(&record),
88 thread,
89 })
90}
91
92pub fn preview_prompt(
93 state: &AppState,
94 action: &AgentAction,
95 conversation_id: &str,
96 message_id: &str,
97 extra: &str,
98) -> Option<String> {
99 let context = build(state, conversation_id, message_id)?;
100 Some(build_prompt(
101 action,
102 &context,
103 extra,
104 SESSION_PLACEHOLDER,
105 &action.agent_id,
106 ))
107}
108
109#[cfg(test)]
110mod tests {
111 use std::sync::Arc;
112
113 use chrono::{TimeZone, Utc};
114 use store::{ChatRecord, Store};
115
116 use super::*;
117 use crate::app_state::Mode;
118
119 fn message(id: &str, reply_to: Option<&str>, minute: u32, sender: &str) -> MessageRecord {
120 MessageRecord {
121 conversation_id: "19:chat".to_owned(),
122 message_id: id.to_owned(),
123 reply_to_id: reply_to.map(str::to_owned),
124 sender_name: Some(sender.to_owned()),
125 created_at: Utc.with_ymd_and_hms(2026, 10, 1, 9, minute, 0).unwrap(),
126 body_html: format!("<p>text {id}</p>"),
127 attachments_json: "[]".to_owned(),
128 reactions_json: "[]".to_owned(),
129 mentions_json: "[]".to_owned(),
130 links_json: "[]".to_owned(),
131 ..MessageRecord::default()
132 }
133 }
134
135 fn state_with(records: &[MessageRecord]) -> AppState {
136 let store = Arc::new(Store::open_in_memory().unwrap());
137 store.upsert_messages(records).unwrap();
138 let mut state = AppState::new(store, Mode::default());
139 state.sidebar.chats.push(ChatRecord {
140 id: "19:chat".to_owned(),
141 kind: "chat".to_owned(),
142 title: "Ops".to_owned(),
143 member_summary: String::new(),
144 last_message_at: None,
145 last_read_at: None,
146 unread: false,
147 muted: false,
148 members: Vec::new(),
149 last_message_preview: None,
150 last_message_sender_id: None,
151 last_message_sender_name: None,
152 last_message_deleted: false,
153 last_event_system: false,
154 });
155 state
156 }
157
158 #[test]
159 fn chat_context_takes_up_to_twenty_earlier_messages_oldest_first() {
160 let records: Vec<MessageRecord> = (0..30)
161 .map(|minute| message(&format!("m{minute}"), None, minute, "Ada"))
162 .collect();
163 let state = state_with(&records);
164 let context = build(&state, "19:chat", "m25").unwrap();
165 assert_eq!(context.chat, "Ops");
166 assert_eq!(context.sender, "Ada");
167 assert_eq!(context.message, "text m25");
168 assert_eq!(context.thread.len(), 20);
169 assert_eq!(context.thread[0].text, "text m5");
170 assert_eq!(context.thread[19].text, "text m24");
171 }
172
173 #[test]
174 fn deleted_and_missing_messages_give_no_context() {
175 let mut deleted = message("m1", None, 1, "Ada");
176 deleted.deleted = true;
177 let state = state_with(&[deleted]);
178 assert!(build(&state, "19:chat", "m1").is_none());
179 assert!(build(&state, "19:chat", "nope").is_none());
180 }
181
182 #[test]
183 fn channel_context_follows_the_thread_root() {
184 let records = [
185 message("root", None, 1, "Ada"),
186 message("other", None, 2, "Bo"),
187 message("reply-1", Some("root"), 3, "Cy"),
188 message("reply-2", Some("root"), 4, "Di"),
189 ];
190 let mut state = state_with(&records);
191 state.sidebar.chats.clear();
192 state.sidebar.teams.push(store::SidebarTeam {
193 team: store::TeamRecord {
194 id: "team".to_owned(),
195 name: "Platform".to_owned(),
196 },
197 channels: vec![store::ChannelRecord {
198 id: "19:chat".to_owned(),
199 team_id: "team".to_owned(),
200 name: "Releases".to_owned(),
201 membership_type: None,
202 last_message_at: None,
203 unread: false,
204 }],
205 hidden: false,
206 hidden_channel_ids: Vec::new(),
207 notifications: Default::default(),
208 });
209 let context = build(&state, "19:chat", "reply-2").unwrap();
210 let texts: Vec<&str> = context
211 .thread
212 .iter()
213 .map(|entry| entry.text.as_str())
214 .collect();
215 assert_eq!(texts, ["text root", "text reply-1"]);
216 }
217
218 #[test]
219 fn preview_renders_the_template_with_a_session_placeholder() {
220 let state = state_with(&[message("m1", None, 1, "Ada")]);
221 let action = AgentAction::answer_this("claude");
222 let prompt = preview_prompt(&state, &action, "19:chat", "m1", "").unwrap();
223 assert!(prompt.starts_with("Ada asked me in the Teams chat \"Ops\""));
224 assert!(prompt.contains("session_id \"(session id)\""));
225 }
226}
crates/app/src/agents/mod.rs added +201 −0
@@ -0,0 +1,201 @@
1 mod demo;
2 mod mcp_bridge;
3 mod message_context;
4 mod run_chip;
5 mod runs;
6 mod runs_popover;
7 mod settings_controls;
8 mod settings_forms;
9 mod settings_problems;
10 mod settings_section;
11 mod spinner;
12 mod start_dialog;
13 mod store;
14
15 use std::path::PathBuf;
16 use std::time::Duration;
17
18 use agents::{AgentAction, Environment};
19 use directories::ProjectDirs;
20 use gpui_kit::*;
21
22 pub use run_chip::run_chip;
23 pub use runs::{AgentRun, AgentRuns, AgentRunsEvent, AgentRunsHandle, RunState};
24 pub use runs_popover::RunsPopover;
25 pub use settings_section::AgentsSettings;
26 pub use start_dialog::{StartDialog, StartDialogEvent, StartRequest};
27
28 use crate::app_state::{AppHandle, AppState};
29
30 pub fn install(app: Entity<AppState>, cx: &mut App) {
31 let runs = cx.new(|cx| AgentRuns::new(app, cx));
32 cx.set_global(AgentRunsHandle(runs));
33 }
34
35 const MCP_POLL_INTERVAL: Duration = Duration::from_millis(100);
36 const MCP_WAIT_LIMIT: Duration = Duration::from_secs(5);
37 const MCP_CONFIG_FOLDER: &str = "agent-mcp";
38
39 fn mcp_config_directory() -> Option<PathBuf> {
40 ProjectDirs::from("", "", ::store::DATA_DIR_NAME)
41 .map(|directories| directories.data_local_dir().join(MCP_CONFIG_FOLDER))
42 }
43
44 pub fn runs_handle(cx: &App) -> Option<Entity<AgentRuns>> {
45 cx.try_global::<AgentRunsHandle>()
46 .map(|handle| handle.0.clone())
47 }
48
49 fn raise_notice(text: String, cx: &mut App) {
50 let Some(handle) = cx.try_global::<AppHandle>() else {
51 return;
52 };
53 handle
54 .0
55 .clone()
56 .update(cx, |state, cx| state.raise_notice(text, None, cx));
57 }
58
59 pub fn start_run(
60 action_id: &str,
61 conversation_id: &str,
62 message_id: &str,
63 extra: &str,
64 cx: &mut App,
65 ) {
66 let Some(runs) = runs_handle(cx) else {
67 return;
68 };
69 let started = runs.update(cx, |runs, cx| {
70 runs.start(action_id, conversation_id, message_id, extra, cx)
71 });
72 if let Err(error) = started {
73 raise_notice(format!("Agent could not start: {error}"), cx);
74 }
75 }
76
77 pub fn start_run_when_mcp_ready(
78 action_id: String,
79 conversation_id: String,
80 message_id: String,
81 extra: String,
82 cx: &mut App,
83 ) {
84 cx.spawn(async move |cx| {
85 let mut waited = Duration::ZERO;
86 while waited < MCP_WAIT_LIMIT && !cx.update(|cx| mcp_bridge::endpoint(cx).is_some()) {
87 cx.background_executor().timer(MCP_POLL_INTERVAL).await;
88 waited += MCP_POLL_INTERVAL;
89 }
90 cx.update(|cx| {
91 if mcp_bridge::endpoint(cx).is_none() {
92 raise_notice(
93 "MCP server is not running - the agent cannot propose a reply".to_owned(),
94 cx,
95 );
96 }
97 start_run(&action_id, &conversation_id, &message_id, &extra, cx);
98 });
99 })
100 .detach();
101 }
102
103 pub fn retry_run(run_id: u64, cx: &mut App) {
104 let Some(runs) = runs_handle(cx) else {
105 return;
106 };
107 let retried = runs.update(cx, |runs, cx| runs.retry(run_id, cx));
108 if let Err(error) = retried {
109 raise_notice(format!("Agent could not start: {error}"), cx);
110 }
111 }
112
113 pub fn delegate(request: StartRequest, cx: &mut App) {
114 let Some(runs) = runs_handle(cx) else {
115 return;
116 };
117 let action = runs
118 .read(cx)
119 .settings()
120 .actions
121 .iter()
122 .find(|action| action.id == request.action_id)
123 .cloned();
124 let Some(action) = action else {
125 return;
126 };
127 let allowed = mcp_bridge::chat_allowed(&request.conversation_id, cx);
128 if start_dialog::needs_dialog(&action, allowed) {
129 runs.update(cx, |_, cx| cx.emit(AgentRunsEvent::StartRequested(request)));
130 } else {
131 start_run(
132 &request.action_id,
133 &request.conversation_id,
134 &request.message_id,
135 "",
136 cx,
137 );
138 }
139 }
140
141 pub fn open_settings(cx: &mut App) {
142 if let Some(runs) = runs_handle(cx) {
143 runs.update(cx, |_, cx| cx.emit(AgentRunsEvent::OpenSettings));
144 }
145 }
146
147 pub fn has_session(session_id: &str, cx: &App) -> bool {
148 runs_handle(cx).is_some_and(|runs| runs.read(cx).by_session(session_id).is_some())
149 }
150
151 pub fn open_session(session_id: &str, cx: &mut App) {
152 let run = runs_handle(cx).and_then(|runs| runs.read(cx).by_session(session_id).cloned());
153 match run {
154 Some(run) => open_run_session(&run, cx),
155 None => raise_notice(
156 "This session was not started from this app, open it in your terminal".to_owned(),
157 cx,
158 ),
159 }
160 }
161
162 fn open_run_session(run: &AgentRun, cx: &mut App) {
163 let Some(handle) = cx.try_global::<AppHandle>() else {
164 return;
165 };
166 let settings = store::load_settings(&handle.0.read(cx).store);
167 let Some(profile) = settings
168 .agents
169 .iter()
170 .find(|profile| profile.id == run.agent_id)
171 else {
172 raise_notice("The agent of this run no longer exists".to_owned(), cx);
173 return;
174 };
175 let action = AgentAction {
176 working_dir: run.working_dir.clone(),
177 ..AgentAction::default()
178 };
179 let spawned = agents::open_session_invocation(profile, &action, &run.session_id)
180 .map_err(|error| error.to_string())
181 .and_then(|invocation| {
182 std::process::Command::new(&invocation.program)
183 .args(&invocation.args)
184 .spawn()
185 .map(drop)
186 .map_err(|error| error.to_string())
187 });
188 if let Err(error) = spawned {
189 raise_notice(format!("Could not open the session: {error}"), cx);
190 }
191 }
192
193 pub fn environment_label(environment: &Environment) -> String {
194 match environment {
195 Environment::Host => "Windows".to_owned(),
196 Environment::Wsl { distro: None } => "WSL".to_owned(),
197 Environment::Wsl {
198 distro: Some(distro),
199 } => format!("WSL - {distro}"),
200 }
201 }
@@ -0,0 +1,201 @@
1mod demo;
2mod mcp_bridge;
3mod message_context;
4mod run_chip;
5mod runs;
6mod runs_popover;
7mod settings_controls;
8mod settings_forms;
9mod settings_problems;
10mod settings_section;
11mod spinner;
12mod start_dialog;
13mod store;
14
15use std::path::PathBuf;
16use std::time::Duration;
17
18use agents::{AgentAction, Environment};
19use directories::ProjectDirs;
20use gpui_kit::*;
21
22pub use run_chip::run_chip;
23pub use runs::{AgentRun, AgentRuns, AgentRunsEvent, AgentRunsHandle, RunState};
24pub use runs_popover::RunsPopover;
25pub use settings_section::AgentsSettings;
26pub use start_dialog::{StartDialog, StartDialogEvent, StartRequest};
27
28use crate::app_state::{AppHandle, AppState};
29
30pub fn install(app: Entity<AppState>, cx: &mut App) {
31 let runs = cx.new(|cx| AgentRuns::new(app, cx));
32 cx.set_global(AgentRunsHandle(runs));
33}
34
35const MCP_POLL_INTERVAL: Duration = Duration::from_millis(100);
36const MCP_WAIT_LIMIT: Duration = Duration::from_secs(5);
37const MCP_CONFIG_FOLDER: &str = "agent-mcp";
38
39fn mcp_config_directory() -> Option<PathBuf> {
40 ProjectDirs::from("", "", ::store::DATA_DIR_NAME)
41 .map(|directories| directories.data_local_dir().join(MCP_CONFIG_FOLDER))
42}
43
44pub fn runs_handle(cx: &App) -> Option<Entity<AgentRuns>> {
45 cx.try_global::<AgentRunsHandle>()
46 .map(|handle| handle.0.clone())
47}
48
49fn raise_notice(text: String, cx: &mut App) {
50 let Some(handle) = cx.try_global::<AppHandle>() else {
51 return;
52 };
53 handle
54 .0
55 .clone()
56 .update(cx, |state, cx| state.raise_notice(text, None, cx));
57}
58
59pub fn start_run(
60 action_id: &str,
61 conversation_id: &str,
62 message_id: &str,
63 extra: &str,
64 cx: &mut App,
65) {
66 let Some(runs) = runs_handle(cx) else {
67 return;
68 };
69 let started = runs.update(cx, |runs, cx| {
70 runs.start(action_id, conversation_id, message_id, extra, cx)
71 });
72 if let Err(error) = started {
73 raise_notice(format!("Agent could not start: {error}"), cx);
74 }
75}
76
77pub fn start_run_when_mcp_ready(
78 action_id: String,
79 conversation_id: String,
80 message_id: String,
81 extra: String,
82 cx: &mut App,
83) {
84 cx.spawn(async move |cx| {
85 let mut waited = Duration::ZERO;
86 while waited < MCP_WAIT_LIMIT && !cx.update(|cx| mcp_bridge::endpoint(cx).is_some()) {
87 cx.background_executor().timer(MCP_POLL_INTERVAL).await;
88 waited += MCP_POLL_INTERVAL;
89 }
90 cx.update(|cx| {
91 if mcp_bridge::endpoint(cx).is_none() {
92 raise_notice(
93 "MCP server is not running - the agent cannot propose a reply".to_owned(),
94 cx,
95 );
96 }
97 start_run(&action_id, &conversation_id, &message_id, &extra, cx);
98 });
99 })
100 .detach();
101}
102
103pub fn retry_run(run_id: u64, cx: &mut App) {
104 let Some(runs) = runs_handle(cx) else {
105 return;
106 };
107 let retried = runs.update(cx, |runs, cx| runs.retry(run_id, cx));
108 if let Err(error) = retried {
109 raise_notice(format!("Agent could not start: {error}"), cx);
110 }
111}
112
113pub fn delegate(request: StartRequest, cx: &mut App) {
114 let Some(runs) = runs_handle(cx) else {
115 return;
116 };
117 let action = runs
118 .read(cx)
119 .settings()
120 .actions
121 .iter()
122 .find(|action| action.id == request.action_id)
123 .cloned();
124 let Some(action) = action else {
125 return;
126 };
127 let allowed = mcp_bridge::chat_allowed(&request.conversation_id, cx);
128 if start_dialog::needs_dialog(&action, allowed) {
129 runs.update(cx, |_, cx| cx.emit(AgentRunsEvent::StartRequested(request)));
130 } else {
131 start_run(
132 &request.action_id,
133 &request.conversation_id,
134 &request.message_id,
135 "",
136 cx,
137 );
138 }
139}
140
141pub fn open_settings(cx: &mut App) {
142 if let Some(runs) = runs_handle(cx) {
143 runs.update(cx, |_, cx| cx.emit(AgentRunsEvent::OpenSettings));
144 }
145}
146
147pub fn has_session(session_id: &str, cx: &App) -> bool {
148 runs_handle(cx).is_some_and(|runs| runs.read(cx).by_session(session_id).is_some())
149}
150
151pub fn open_session(session_id: &str, cx: &mut App) {
152 let run = runs_handle(cx).and_then(|runs| runs.read(cx).by_session(session_id).cloned());
153 match run {
154 Some(run) => open_run_session(&run, cx),
155 None => raise_notice(
156 "This session was not started from this app, open it in your terminal".to_owned(),
157 cx,
158 ),
159 }
160}
161
162fn open_run_session(run: &AgentRun, cx: &mut App) {
163 let Some(handle) = cx.try_global::<AppHandle>() else {
164 return;
165 };
166 let settings = store::load_settings(&handle.0.read(cx).store);
167 let Some(profile) = settings
168 .agents
169 .iter()
170 .find(|profile| profile.id == run.agent_id)
171 else {
172 raise_notice("The agent of this run no longer exists".to_owned(), cx);
173 return;
174 };
175 let action = AgentAction {
176 working_dir: run.working_dir.clone(),
177 ..AgentAction::default()
178 };
179 let spawned = agents::open_session_invocation(profile, &action, &run.session_id)
180 .map_err(|error| error.to_string())
181 .and_then(|invocation| {
182 std::process::Command::new(&invocation.program)
183 .args(&invocation.args)
184 .spawn()
185 .map(drop)
186 .map_err(|error| error.to_string())
187 });
188 if let Err(error) = spawned {
189 raise_notice(format!("Could not open the session: {error}"), cx);
190 }
191}
192
193pub fn environment_label(environment: &Environment) -> String {
194 match environment {
195 Environment::Host => "Windows".to_owned(),
196 Environment::Wsl { distro: None } => "WSL".to_owned(),
197 Environment::Wsl {
198 distro: Some(distro),
199 } => format!("WSL - {distro}"),
200 }
201}
crates/app/src/agents/run_chip.rs added +269 −0
@@ -0,0 +1,269 @@
1 use gpui_kit::assets::IconName;
2 use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
3 use gpui_kit::prelude::FluentBuilder as _;
4 use gpui_kit::*;
5
6 use super::runs::{AgentRun, AgentRuns, RunState, format_elapsed};
7 use super::spinner::spinner;
8 use super::{AgentRunsHandle, open_session, retry_run};
9 use crate::theme;
10 use crate::views::widgets::icon;
11
12 const CHIP_HEIGHT: f32 = 28.;
13 const CHIP_MAX_WIDTH: f32 = 310.;
14 const BUTTON_HEIGHT: f32 = 22.;
15 const STATUS_ICON: f32 = 12.;
16
17 fn with_runs(cx: &mut App, change: impl FnOnce(&mut AgentRuns, &mut Context<AgentRuns>)) {
18 cx.global::<AgentRunsHandle>().0.clone().update(cx, change);
19 }
20
21 fn chip_button(id: String, label: &'static str, primary: bool) -> Stateful<Div> {
22 div()
23 .id(ElementId::Name(id.into()))
24 .h(px(BUTTON_HEIGHT))
25 .px(px(8.))
26 .flex()
27 .flex_none()
28 .items_center()
29 .rounded(px(6.))
30 .cursor_pointer()
31 .text_color(theme::accent_text())
32 .font_weight(FontWeight::SEMIBOLD)
33 .when(primary, |button| button.bg(theme::surface_raised()))
34 .hover(move |button| {
35 button.bg(if primary {
36 theme::popup_hover()
37 } else {
38 theme::surface_raised()
39 })
40 })
41 .child(label)
42 }
43
44 fn dismiss_button(run_id: u64) -> Stateful<Div> {
45 div()
46 .id(("agent-dismiss", run_id as usize))
47 .size(px(BUTTON_HEIGHT))
48 .flex()
49 .flex_none()
50 .items_center()
51 .justify_center()
52 .rounded(px(6.))
53 .cursor_pointer()
54 .hover(|button| button.bg(theme::surface_raised()))
55 .child(icon(IconName::X, STATUS_ICON, theme::text_faint()))
56 .on_click(move |_, _, cx| {
57 cx.stop_propagation();
58 with_runs(cx, |runs, cx| runs.dismiss(run_id, cx));
59 })
60 }
61
62 fn label(text: String, color: Hsla) -> Div {
63 div().flex_none().text_color(color).child(text)
64 }
65
66 fn step_text(text: String) -> Div {
67 div()
68 .min_w(px(0.))
69 .truncate()
70 .text_color(theme::text_muted())
71 .child(text)
72 }
73
74 fn elapsed_text(run: &AgentRun) -> Div {
75 div()
76 .flex_none()
77 .text_color(theme::text_faint())
78 .child(run.elapsed_text())
79 }
80
81 fn chip_row(run: &AgentRun, fill: Hsla) -> Stateful<Div> {
82 let run_id = run.id;
83 let step = run.current_step.clone();
84 let session_id = run.session_id.clone();
85 let row = h_flex()
86 .id(("agent-chip", run_id as usize))
87 .h(px(CHIP_HEIGHT))
88 .max_w(px(CHIP_MAX_WIDTH))
89 .pl(px(10.))
90 .pr(px(4.))
91 .gap(px(8.))
92 .flex_none()
93 .items_center()
94 .rounded(px(8.))
95 .bg(fill)
96 .cursor_pointer()
97 .text_size(px(12.))
98 .text_color(theme::text_soft())
99 .tooltip(move |window, cx| Tooltip::new(step.clone()).build(window, cx))
100 .on_click(move |_, _, cx| with_runs(cx, |runs, cx| runs.toggle_expanded(run_id, cx)));
101 let action_label = run.action_label.clone();
102 match &run.state {
103 RunState::Running => row
104 .child(spinner(STATUS_ICON))
105 .child(label(action_label, theme::text_soft()))
106 .child(step_text(run.current_step.clone()))
107 .child(elapsed_text(run))
108 .child(
109 div()
110 .size(px(BUTTON_HEIGHT))
111 .flex()
112 .flex_none()
113 .items_center()
114 .justify_center()
115 .child(icon(
116 if run.expanded {
117 IconName::ChevronUp
118 } else {
119 IconName::ChevronDown
120 },
121 STATUS_ICON,
122 theme::text_faint(),
123 )),
124 ),
125 RunState::Done => row
126 .child(icon(IconName::Check, STATUS_ICON, theme::accent_text()))
127 .child(label(action_label, theme::text_soft()))
128 .child(step_text(run.current_step.clone()))
129 .child(elapsed_text(run))
130 .when(!session_id.is_empty(), |row| {
131 row.child(
132 chip_button(format!("agent-open-{run_id}"), "Open session", true).on_click(
133 move |_, _, cx| {
134 cx.stop_propagation();
135 open_session(&session_id, cx);
136 },
137 ),
138 )
139 })
140 .child(dismiss_button(run_id)),
141 RunState::Failed { .. } => {
142 row.child(icon(IconName::X, STATUS_ICON, theme::red_soft()))
143 .child(label("Failed".to_owned(), theme::red_tint()))
144 .child(step_text(run.current_step.clone()))
145 .child(
146 chip_button(format!("agent-log-{run_id}"), "Log", false).on_click(
147 move |_, _, cx| {
148 cx.stop_propagation();
149 with_runs(cx, |runs, cx| runs.toggle_expanded(run_id, cx));
150 },
151 ),
152 )
153 .child(
154 chip_button(format!("agent-retry-{run_id}"), "Retry", false).on_click(
155 move |_, _, cx| {
156 cx.stop_propagation();
157 retry_run(run_id, cx);
158 },
159 ),
160 )
161 .when(!session_id.is_empty(), |row| {
162 row.child(
163 chip_button(format!("agent-open-{run_id}"), "Open session", false)
164 .on_click(move |_, _, cx| {
165 cx.stop_propagation();
166 open_session(&session_id, cx);
167 }),
168 )
169 })
170 .child(dismiss_button(run_id))
171 }
172 RunState::Stopped => row
173 .child(icon(IconName::Square, STATUS_ICON, theme::text_faint()))
174 .child(label(action_label, theme::text_soft()))
175 .child(step_text("Stopped".to_owned()))
176 .child(elapsed_text(run))
177 .child(dismiss_button(run_id)),
178 }
179 }
180
181 fn step_row(elapsed: String, text: String, current: bool) -> Div {
182 h_flex()
183 .gap(px(8.))
184 .items_center()
185 .overflow_hidden()
186 .whitespace_nowrap()
187 .text_color(if current {
188 theme::text_strong()
189 } else {
190 theme::text_muted()
191 })
192 .child(
193 div()
194 .flex_none()
195 .text_color(theme::text_faint())
196 .child(elapsed),
197 )
198 .child(div().min_w(px(0.)).truncate().child(text))
199 }
200
201 fn stop_row(run_id: u64) -> Div {
202 h_flex()
203 .mt(px(2.))
204 .items_center()
205 .justify_between()
206 .child(
207 chip_button(
208 format!("agent-stop-open-{run_id}"),
209 "Stop and open session",
210 false,
211 )
212 .on_click(move |_, _, cx| {
213 cx.stop_propagation();
214 with_runs(cx, |runs, cx| runs.stop_and_open_session(run_id, cx));
215 }),
216 )
217 .child(
218 chip_button(format!("agent-stop-{run_id}"), "Stop", false).on_click(move |_, _, cx| {
219 cx.stop_propagation();
220 with_runs(cx, |runs, cx| runs.stop(run_id, cx));
221 }),
222 )
223 }
224
225 fn detail_panel(run: &AgentRun, fill: Hsla) -> Div {
226 let panel = v_flex()
227 .w(px(CHIP_MAX_WIDTH))
228 .py(px(8.))
229 .px(px(10.))
230 .gap(px(6.))
231 .rounded(px(8.))
232 .bg(fill)
233 .text_size(px(12.))
234 .text_color(theme::text_muted());
235 if matches!(run.state, RunState::Failed { .. }) {
236 let lines = run.log_lines();
237 if lines.is_empty() {
238 return panel.child("No output");
239 }
240 return panel.children(lines.iter().map(|line| {
241 div()
242 .overflow_hidden()
243 .whitespace_nowrap()
244 .text_ellipsis()
245 .child(line.clone())
246 }));
247 }
248 let steps = run.visible_steps();
249 if steps.is_empty() {
250 return panel
251 .child("No steps yet")
252 .when(run.is_running(), |panel| panel.child(stop_row(run.id)));
253 }
254 let last = steps.len() - 1;
255 panel
256 .children(steps.iter().enumerate().map(|(index, (elapsed, text))| {
257 step_row(format_elapsed(*elapsed), text.clone(), index == last)
258 }))
259 .when(run.is_running(), |panel| panel.child(stop_row(run.id)))
260 }
261
262 pub fn run_chip(run: &AgentRun, fill: Hsla) -> AnyElement {
263 v_flex()
264 .gap(px(4.))
265 .items_start()
266 .child(chip_row(run, fill))
267 .when(run.expanded, |column| column.child(detail_panel(run, fill)))
268 .into_any_element()
269 }
@@ -0,0 +1,269 @@
1use gpui_kit::assets::IconName;
2use gpui_kit::component::{h_flex, tooltip::Tooltip, v_flex};
3use gpui_kit::prelude::FluentBuilder as _;
4use gpui_kit::*;
5
6use super::runs::{AgentRun, AgentRuns, RunState, format_elapsed};
7use super::spinner::spinner;
8use super::{AgentRunsHandle, open_session, retry_run};
9use crate::theme;
10use crate::views::widgets::icon;
11
12const CHIP_HEIGHT: f32 = 28.;
13const CHIP_MAX_WIDTH: f32 = 310.;
14const BUTTON_HEIGHT: f32 = 22.;
15const STATUS_ICON: f32 = 12.;
16
17fn with_runs(cx: &mut App, change: impl FnOnce(&mut AgentRuns, &mut Context<AgentRuns>)) {
18 cx.global::<AgentRunsHandle>().0.clone().update(cx, change);
19}
20
21fn chip_button(id: String, label: &'static str, primary: bool) -> Stateful<Div> {
22 div()
23 .id(ElementId::Name(id.into()))
24 .h(px(BUTTON_HEIGHT))
25 .px(px(8.))
26 .flex()
27 .flex_none()
28 .items_center()
29 .rounded(px(6.))
30 .cursor_pointer()
31 .text_color(theme::accent_text())
32 .font_weight(FontWeight::SEMIBOLD)
33 .when(primary, |button| button.bg(theme::surface_raised()))
34 .hover(move |button| {
35 button.bg(if primary {
36 theme::popup_hover()
37 } else {
38 theme::surface_raised()
39 })
40 })
41 .child(label)
42}
43
44fn dismiss_button(run_id: u64) -> Stateful<Div> {
45 div()
46 .id(("agent-dismiss", run_id as usize))
47 .size(px(BUTTON_HEIGHT))
48 .flex()
49 .flex_none()
50 .items_center()
51 .justify_center()
52 .rounded(px(6.))
53 .cursor_pointer()
54 .hover(|button| button.bg(theme::surface_raised()))
55 .child(icon(IconName::X, STATUS_ICON, theme::text_faint()))
56 .on_click(move |_, _, cx| {
57 cx.stop_propagation();
58 with_runs(cx, |runs, cx| runs.dismiss(run_id, cx));
59 })
60}
61
62fn label(text: String, color: Hsla) -> Div {
63 div().flex_none().text_color(color).child(text)
64}
65
66fn step_text(text: String) -> Div {
67 div()
68 .min_w(px(0.))
69 .truncate()
70 .text_color(theme::text_muted())
71 .child(text)
72}
73
74fn elapsed_text(run: &AgentRun) -> Div {
75 div()
76 .flex_none()
77 .text_color(theme::text_faint())
78 .child(run.elapsed_text())
79}
80
81fn chip_row(run: &AgentRun, fill: Hsla) -> Stateful<Div> {
82 let run_id = run.id;
83 let step = run.current_step.clone();
84 let session_id = run.session_id.clone();
85 let row = h_flex()
86 .id(("agent-chip", run_id as usize))
87 .h(px(CHIP_HEIGHT))
88 .max_w(px(CHIP_MAX_WIDTH))
89 .pl(px(10.))
90 .pr(px(4.))
91 .gap(px(8.))
92 .flex_none()
93 .items_center()
94 .rounded(px(8.))
95 .bg(fill)
96 .cursor_pointer()
97 .text_size(px(12.))
98 .text_color(theme::text_soft())
99 .tooltip(move |window, cx| Tooltip::new(step.clone()).build(window, cx))
100 .on_click(move |_, _, cx| with_runs(cx, |runs, cx| runs.toggle_expanded(run_id, cx)));
101 let action_label = run.action_label.clone();
102 match &run.state {
103 RunState::Running => row
104 .child(spinner(STATUS_ICON))
105 .child(label(action_label, theme::text_soft()))
106 .child(step_text(run.current_step.clone()))
107 .child(elapsed_text(run))
108 .child(
109 div()
110 .size(px(BUTTON_HEIGHT))
111 .flex()
112 .flex_none()
113 .items_center()
114 .justify_center()
115 .child(icon(
116 if run.expanded {
117 IconName::ChevronUp
118 } else {
119 IconName::ChevronDown
120 },
121 STATUS_ICON,
122 theme::text_faint(),
123 )),
124 ),
125 RunState::Done => row
126 .child(icon(IconName::Check, STATUS_ICON, theme::accent_text()))
127 .child(label(action_label, theme::text_soft()))
128 .child(step_text(run.current_step.clone()))
129 .child(elapsed_text(run))
130 .when(!session_id.is_empty(), |row| {
131 row.child(
132 chip_button(format!("agent-open-{run_id}"), "Open session", true).on_click(
133 move |_, _, cx| {
134 cx.stop_propagation();
135 open_session(&session_id, cx);
136 },
137 ),
138 )
139 })
140 .child(dismiss_button(run_id)),
141 RunState::Failed { .. } => {
142 row.child(icon(IconName::X, STATUS_ICON, theme::red_soft()))
143 .child(label("Failed".to_owned(), theme::red_tint()))
144 .child(step_text(run.current_step.clone()))
145 .child(
146 chip_button(format!("agent-log-{run_id}"), "Log", false).on_click(
147 move |_, _, cx| {
148 cx.stop_propagation();
149 with_runs(cx, |runs, cx| runs.toggle_expanded(run_id, cx));
150 },
151 ),
152 )
153 .child(
154 chip_button(format!("agent-retry-{run_id}"), "Retry", false).on_click(
155 move |_, _, cx| {
156 cx.stop_propagation();
157 retry_run(run_id, cx);
158 },
159 ),
160 )
161 .when(!session_id.is_empty(), |row| {
162 row.child(
163 chip_button(format!("agent-open-{run_id}"), "Open session", false)
164 .on_click(move |_, _, cx| {
165 cx.stop_propagation();
166 open_session(&session_id, cx);
167 }),
168 )
169 })
170 .child(dismiss_button(run_id))
171 }
172 RunState::Stopped => row
173 .child(icon(IconName::Square, STATUS_ICON, theme::text_faint()))
174 .child(label(action_label, theme::text_soft()))
175 .child(step_text("Stopped".to_owned()))
176 .child(elapsed_text(run))
177 .child(dismiss_button(run_id)),
178 }
179}
180
181fn step_row(elapsed: String, text: String, current: bool) -> Div {
182 h_flex()
183 .gap(px(8.))
184 .items_center()
185 .overflow_hidden()
186 .whitespace_nowrap()
187 .text_color(if current {
188 theme::text_strong()
189 } else {
190 theme::text_muted()
191 })
192 .child(
193 div()
194 .flex_none()
195 .text_color(theme::text_faint())
196 .child(elapsed),
197 )
198 .child(div().min_w(px(0.)).truncate().child(text))
199}
200
201fn stop_row(run_id: u64) -> Div {
202 h_flex()
203 .mt(px(2.))
204 .items_center()
205 .justify_between()
206 .child(
207 chip_button(
208 format!("agent-stop-open-{run_id}"),
209 "Stop and open session",
210 false,
211 )
212 .on_click(move |_, _, cx| {
213 cx.stop_propagation();
214 with_runs(cx, |runs, cx| runs.stop_and_open_session(run_id, cx));
215 }),
216 )
217 .child(
218 chip_button(format!("agent-stop-{run_id}"), "Stop", false).on_click(move |_, _, cx| {
219 cx.stop_propagation();
220 with_runs(cx, |runs, cx| runs.stop(run_id, cx));
221 }),
222 )
223}
224
225fn detail_panel(run: &AgentRun, fill: Hsla) -> Div {
226 let panel = v_flex()
227 .w(px(CHIP_MAX_WIDTH))
228 .py(px(8.))
229 .px(px(10.))
230 .gap(px(6.))
231 .rounded(px(8.))
232 .bg(fill)
233 .text_size(px(12.))
234 .text_color(theme::text_muted());
235 if matches!(run.state, RunState::Failed { .. }) {
236 let lines = run.log_lines();
237 if lines.is_empty() {
238 return panel.child("No output");
239 }
240 return panel.children(lines.iter().map(|line| {
241 div()
242 .overflow_hidden()
243 .whitespace_nowrap()
244 .text_ellipsis()
245 .child(line.clone())
246 }));
247 }
248 let steps = run.visible_steps();
249 if steps.is_empty() {
250 return panel
251 .child("No steps yet")
252 .when(run.is_running(), |panel| panel.child(stop_row(run.id)));
253 }
254 let last = steps.len() - 1;
255 panel
256 .children(steps.iter().enumerate().map(|(index, (elapsed, text))| {
257 step_row(format_elapsed(*elapsed), text.clone(), index == last)
258 }))
259 .when(run.is_running(), |panel| panel.child(stop_row(run.id)))
260}
261
262pub fn run_chip(run: &AgentRun, fill: Hsla) -> AnyElement {
263 v_flex()
264 .gap(px(4.))
265 .items_start()
266 .child(chip_row(run, fill))
267 .when(run.expanded, |column| column.child(detail_panel(run, fill)))
268 .into_any_element()
269}
crates/app/src/agents/runs.rs added +761 −0
@@ -0,0 +1,761 @@
1 use std::collections::{HashMap, HashSet};
2 use std::time::Duration;
3
4 use agents::{AgentSettings, RunEvent, RunOutcome, RunStatus, RunUpdate};
5 use chrono::{DateTime, Utc};
6 use gpui_kit::*;
7 use serde::{Deserialize, Serialize};
8 use tokio::sync::{mpsc, oneshot};
9
10 use super::{
11 StartRequest, demo, mcp_bridge, mcp_config_directory, message_context, open_run_session,
12 store as run_store,
13 };
14 use crate::app_state::AppState;
15 use crate::notice::truncated;
16 use crate::runtime;
17
18 const STEP_LIMIT: usize = 50;
19 const VISIBLE_STEPS: usize = 6;
20 const VISIBLE_LOG_LINES: usize = 20;
21 const TEXT_STEP_CHARS: usize = 80;
22 const DONE_STEP_CHARS: usize = 60;
23 const TICK: Duration = Duration::from_secs(1);
24
25 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
26 pub enum RunState {
27 Running,
28 Done,
29 Failed { message: String, log: Vec<String> },
30 Stopped,
31 }
32
33 #[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
34 pub struct AgentRun {
35 pub id: u64,
36 pub action_id: String,
37 pub action_label: String,
38 pub agent_id: String,
39 pub agent_name: String,
40 pub conversation_id: String,
41 pub message_id: String,
42 pub chat_title: String,
43 pub sender_name: String,
44 pub session_id: String,
45 pub working_dir: String,
46 pub extra: String,
47 pub state: RunState,
48 pub current_step: String,
49 pub steps: Vec<(Duration, String)>,
50 pub final_text: String,
51 pub started_at: DateTime<Utc>,
52 pub ended_at: Option<DateTime<Utc>>,
53 #[serde(skip)]
54 pub expanded: bool,
55 pub dismissed: bool,
56 }
57
58 impl AgentRun {
59 pub fn is_running(&self) -> bool {
60 self.state == RunState::Running
61 }
62
63 pub fn is_finished(&self) -> bool {
64 !self.is_running()
65 }
66
67 pub fn elapsed(&self) -> Duration {
68 let end = self.ended_at.unwrap_or_else(Utc::now);
69 (end - self.started_at).to_std().unwrap_or_default()
70 }
71
72 pub fn elapsed_text(&self) -> String {
73 format_elapsed(self.elapsed())
74 }
75
76 pub fn visible_steps(&self) -> &[(Duration, String)] {
77 let skipped = self.steps.len().saturating_sub(VISIBLE_STEPS);
78 &self.steps[skipped..]
79 }
80
81 pub fn log_lines(&self) -> &[String] {
82 match &self.state {
83 RunState::Failed { log, .. } => {
84 let skipped = log.len().saturating_sub(VISIBLE_LOG_LINES);
85 &log[skipped..]
86 }
87 _ => &[],
88 }
89 }
90
91 pub fn layout_key(&self) -> (usize, bool) {
92 let rows = match (&self.state, self.expanded) {
93 (_, false) => 0,
94 (RunState::Failed { .. }, true) => self.log_lines().len().max(1),
95 (_, true) => self.visible_steps().len().max(1),
96 };
97 (rows, self.is_running())
98 }
99
100 fn mark_interrupted(&mut self) {
101 let message = "Interrupted - the app was closed during the run".to_owned();
102 self.current_step = message.clone();
103 self.state = RunState::Failed {
104 message,
105 log: Vec::new(),
106 };
107 self.ended_at = Some(Utc::now());
108 }
109
110 fn push_step(&mut self, text: String) {
111 let elapsed = (Utc::now() - self.started_at).to_std().unwrap_or_default();
112 self.steps.push((elapsed, text.clone()));
113 if self.steps.len() > STEP_LIMIT {
114 self.steps.remove(0);
115 }
116 self.current_step = text;
117 }
118 }
119
120 fn remove_stale_mcp_configs() {
121 let Some(directory) = mcp_config_directory() else {
122 return;
123 };
124 let Ok(entries) = std::fs::read_dir(directory) else {
125 return;
126 };
127 for entry in entries.flatten() {
128 let _ = std::fs::remove_file(entry.path());
129 }
130 }
131
132 pub fn format_elapsed(duration: Duration) -> String {
133 let seconds = duration.as_secs();
134 format!("{}:{:02}", seconds / 60, seconds % 60)
135 }
136
137 fn first_line(text: &str) -> &str {
138 text.lines()
139 .find(|line| !line.trim().is_empty())
140 .unwrap_or("")
141 .trim()
142 }
143
144 pub struct AgentRunsHandle(pub Entity<AgentRuns>);
145
146 impl Global for AgentRunsHandle {}
147
148 pub enum AgentRunsEvent {
149 Finished(u64),
150 StartRequested(StartRequest),
151 OpenSettings,
152 }
153
154 pub struct AgentRuns {
155 app: Entity<AppState>,
156 settings: AgentSettings,
157 runs: Vec<AgentRun>,
158 stops: HashMap<u64, oneshot::Sender<()>>,
159 open_after_stop: HashSet<u64>,
160 next_id: u64,
161 ticking: bool,
162 }
163
164 impl EventEmitter<AgentRunsEvent> for AgentRuns {}
165
166 impl AgentRuns {
167 pub fn new(app: Entity<AppState>, cx: &mut Context<Self>) -> Self {
168 let store = app.read(cx).store.clone();
169 let mut runs = run_store::load_runs(&store);
170 let interrupted = runs.iter().any(AgentRun::is_running);
171 for run in runs.iter_mut().filter(|run| run.is_running()) {
172 run.mark_interrupted();
173 }
174 if interrupted {
175 run_store::save_runs(&store, &runs);
176 }
177 remove_stale_mcp_configs();
178 if runs.is_empty() && app.read(cx).mode.demo {
179 runs = demo::runs(app.read(cx));
180 }
181 let next_id = runs.iter().map(|run| run.id).max().map_or(1, |id| id + 1);
182 let mut agent_runs = AgentRuns {
183 app,
184 settings: run_store::load_settings(&store),
185 runs,
186 stops: HashMap::new(),
187 open_after_stop: HashSet::new(),
188 next_id,
189 ticking: false,
190 };
191 agent_runs.ensure_ticking(cx);
192 agent_runs
193 }
194
195 pub fn settings(&self) -> &AgentSettings {
196 &self.settings
197 }
198
199 pub fn update_settings(
200 &mut self,
201 change: impl FnOnce(&mut AgentSettings),
202 cx: &mut Context<Self>,
203 ) {
204 change(&mut self.settings);
205 run_store::save_settings(&self.app.read(cx).store, &self.settings);
206 cx.notify();
207 }
208
209 pub fn get(&self, run_id: u64) -> Option<&AgentRun> {
210 self.runs.iter().find(|run| run.id == run_id)
211 }
212
213 pub fn by_session(&self, session_id: &str) -> Option<&AgentRun> {
214 self.runs
215 .iter()
216 .rev()
217 .find(|run| run.session_id == session_id)
218 }
219
220 pub fn for_conversation<'a>(
221 &'a self,
222 conversation_id: &'a str,
223 ) -> impl Iterator<Item = &'a AgentRun> {
224 self.runs
225 .iter()
226 .filter(move |run| run.conversation_id == conversation_id && !run.dismissed)
227 }
228
229 pub fn running_count(&self) -> usize {
230 self.runs.iter().filter(|run| run.is_running()).count()
231 }
232
233 pub fn recent(&self, limit: usize) -> Vec<&AgentRun> {
234 self.runs
235 .iter()
236 .rev()
237 .filter(|run| !run.dismissed)
238 .take(limit)
239 .collect()
240 }
241
242 fn run_mut(&mut self, run_id: u64) -> Option<&mut AgentRun> {
243 self.runs.iter_mut().find(|run| run.id == run_id)
244 }
245
246 fn persist(&self, cx: &App) {
247 run_store::save_runs(&self.app.read(cx).store, &self.runs);
248 }
249
250 pub fn start(
251 &mut self,
252 action_id: &str,
253 conversation_id: &str,
254 message_id: &str,
255 extra: &str,
256 cx: &mut Context<Self>,
257 ) -> Result<u64, String> {
258 let action = self
259 .settings
260 .actions
261 .iter()
262 .find(|action| action.id == action_id)
263 .cloned()
264 .ok_or("This action no longer exists")?;
265 let profile = self
266 .settings
267 .agents
268 .iter()
269 .find(|profile| profile.id == action.agent_id)
270 .cloned()
271 .ok_or("The agent of this action no longer exists")?;
272 let context = message_context::build(self.app.read(cx), conversation_id, message_id)
273 .ok_or("The message is no longer available")?;
274 let session_id = agents::new_session_id();
275 let prompt = agents::build_prompt(&action, &context, extra, &session_id, &profile.id);
276 let endpoint = mcp_bridge::endpoint(cx);
277 let plan = agents::build_invocation(
278 &profile,
279 &action,
280 &prompt,
281 &session_id,
282 endpoint.as_ref(),
283 mcp_config_directory().as_deref(),
284 );
285 let run_id = self.next_id;
286 self.next_id += 1;
287 self.runs.push(AgentRun {
288 id: run_id,
289 action_id: action.id.clone(),
290 action_label: action.label.clone(),
291 agent_id: profile.id.clone(),
292 agent_name: profile.name.clone(),
293 conversation_id: conversation_id.to_owned(),
294 message_id: message_id.to_owned(),
295 chat_title: context.chat.clone(),
296 sender_name: context.sender.clone(),
297 session_id,
298 working_dir: action.working_dir.clone(),
299 extra: extra.to_owned(),
300 state: RunState::Running,
301 current_step: "Starting".to_owned(),
302 steps: Vec::new(),
303 final_text: String::new(),
304 started_at: Utc::now(),
305 ended_at: None,
306 expanded: false,
307 dismissed: false,
308 });
309 if endpoint.is_none()
310 && let Some(run) = self.run_mut(run_id)
311 {
312 run.push_step("MCP server is off - no reply proposal possible".to_owned());
313 }
314 match plan {
315 Ok(plan) => self.spawn(run_id, plan, profile.output, cx),
316 Err(error) => self.finish(
317 run_id,
318 Some(RunOutcome {
319 status: RunStatus::Failed {
320 message: error.to_string(),
321 stderr_tail: Vec::new(),
322 },
323 exit_code: None,
324 }),
325 cx,
326 ),
327 }
328 self.persist(cx);
329 self.ensure_ticking(cx);
330 cx.notify();
331 Ok(run_id)
332 }
333
334 fn spawn(
335 &mut self,
336 run_id: u64,
337 plan: agents::RunPlan,
338 format: agents::OutputFormat,
339 cx: &mut Context<Self>,
340 ) {
341 let (updates_sender, mut updates) = mpsc::unbounded_channel();
342 let (stop_sender, stop_receiver) = oneshot::channel();
343 self.stops.insert(run_id, stop_sender);
344 let outcome = runtime::spawn(agents::run(plan, format, updates_sender, stop_receiver));
345 cx.spawn(async move |this, cx| {
346 while let Some(update) = updates.recv().await {
347 if this
348 .update(cx, |runs, cx| runs.apply_update(run_id, update, cx))
349 .is_err()
350 {
351 return;
352 }
353 }
354 let outcome = outcome.await.ok();
355 this.update(cx, |runs, cx| runs.finish(run_id, outcome, cx))
356 .ok();
357 })
358 .detach();
359 }
360
361 fn apply_update(&mut self, run_id: u64, update: RunUpdate, cx: &mut Context<Self>) {
362 let RunUpdate::Event(event) = update else {
363 return;
364 };
365 let Some(run) = self.run_mut(run_id) else {
366 return;
367 };
368 match event {
369 RunEvent::Step(text) => run.push_step(text),
370 RunEvent::Text(text) => {
371 run.current_step = truncated(first_line(&text), TEXT_STEP_CHARS)
372 }
373 _ => return,
374 }
375 cx.notify();
376 }
377
378 fn finish(&mut self, run_id: u64, outcome: Option<RunOutcome>, cx: &mut Context<Self>) {
379 self.stops.remove(&run_id);
380 let Some(run) = self.run_mut(run_id).filter(|run| run.is_running()) else {
381 return;
382 };
383 run.ended_at = Some(Utc::now());
384 match outcome.map(|outcome| outcome.status) {
385 Some(RunStatus::Completed { final_text }) => {
386 let line = truncated(first_line(&final_text), DONE_STEP_CHARS);
387 run.current_step = if line.is_empty() {
388 "Done".to_owned()
389 } else {
390 format!("Done - {line}")
391 };
392 run.final_text = final_text;
393 run.state = RunState::Done;
394 }
395 Some(RunStatus::Failed {
396 message,
397 stderr_tail,
398 }) => {
399 run.current_step = message.clone();
400 run.state = RunState::Failed {
401 message,
402 log: stderr_tail,
403 };
404 }
405 Some(RunStatus::Stopped) => {
406 run.current_step = "Stopped".to_owned();
407 run.state = RunState::Stopped;
408 }
409 None => {
410 let message = "The run was cancelled".to_owned();
411 run.current_step = message.clone();
412 run.state = RunState::Failed {
413 message,
414 log: Vec::new(),
415 };
416 }
417 }
418 let stopped = run.state == RunState::Stopped;
419 let failed_or_done = !stopped;
420 let snapshot = run.clone();
421 self.prune_finished();
422 self.persist(cx);
423 if failed_or_done {
424 cx.emit(AgentRunsEvent::Finished(run_id));
425 }
426 if self.open_after_stop.remove(&run_id) && stopped {
427 open_run_session(&snapshot, cx);
428 }
429 cx.notify();
430 }
431
432 fn prune_finished(&mut self) {
433 let finished = self.runs.iter().filter(|run| run.is_finished()).count();
434 let mut excess = finished.saturating_sub(run_store::RUNS_HISTORY_LIMIT);
435 self.runs.retain(|run| {
436 if excess > 0 && run.is_finished() {
437 excess -= 1;
438 return false;
439 }
440 true
441 });
442 }
443
444 fn ensure_ticking(&mut self, cx: &mut Context<Self>) {
445 if self.ticking || self.running_count() == 0 {
446 return;
447 }
448 self.ticking = true;
449 cx.spawn(async move |this, cx| {
450 loop {
451 cx.background_executor().timer(TICK).await;
452 let keep_going = this
453 .update(cx, |runs, cx| {
454 runs.ticking = runs.running_count() > 0;
455 if runs.ticking {
456 cx.notify();
457 }
458 runs.ticking
459 })
460 .unwrap_or(false);
461 if !keep_going {
462 break;
463 }
464 }
465 })
466 .detach();
467 }
468
469 pub fn stop(&mut self, run_id: u64, cx: &mut Context<Self>) {
470 if let Some(stop) = self.stops.remove(&run_id) {
471 let _ = stop.send(());
472 if let Some(run) = self.run_mut(run_id) {
473 run.current_step = "Stopping".to_owned();
474 }
475 cx.notify();
476 }
477 }
478
479 pub fn stop_and_open_session(&mut self, run_id: u64, cx: &mut Context<Self>) {
480 self.open_after_stop.insert(run_id);
481 self.stop(run_id, cx);
482 }
483
484 pub fn retry(&mut self, run_id: u64, cx: &mut Context<Self>) -> Result<u64, String> {
485 let run = self
486 .get(run_id)
487 .cloned()
488 .ok_or("This run no longer exists")?;
489 let started = self.start(
490 &run.action_id,
491 &run.conversation_id,
492 &run.message_id,
493 &run.extra,
494 cx,
495 )?;
496 self.dismiss(run_id, cx);
497 Ok(started)
498 }
499
500 pub fn dismiss(&mut self, run_id: u64, cx: &mut Context<Self>) {
501 let Some(run) = self.run_mut(run_id).filter(|run| run.is_finished()) else {
502 return;
503 };
504 run.dismissed = true;
505 self.persist(cx);
506 cx.notify();
507 }
508
509 pub fn toggle_expanded(&mut self, run_id: u64, cx: &mut Context<Self>) {
510 if let Some(run) = self.run_mut(run_id) {
511 run.expanded = !run.expanded;
512 cx.notify();
513 }
514 }
515 }
516
517 #[cfg(test)]
518 pub(super) mod tests {
519 use std::sync::Arc;
520 use std::time::Duration;
521
522 use agents::{AgentAction, AgentProfile, AgentSettings, Environment, OutputFormat};
523 use chrono::TimeZone;
524 use store::{MessageRecord, Store};
525
526 use gpui_kit::{AppContext as _, Entity, TestAppContext};
527
528 use super::{AgentRun, AgentRuns, RunState, Utc, format_elapsed, run_store};
529 use crate::app_state::{AppState, Mode};
530
531 pub fn finished_run(id: u64) -> AgentRun {
532 AgentRun {
533 id,
534 action_id: "answer-this".to_owned(),
535 action_label: "Answer this".to_owned(),
536 agent_id: "claude".to_owned(),
537 agent_name: "Claude Code".to_owned(),
538 conversation_id: "19:chat".to_owned(),
539 message_id: format!("m{id}"),
540 chat_title: "Ops".to_owned(),
541 sender_name: "Ada".to_owned(),
542 session_id: format!("session-{id}"),
543 working_dir: "~".to_owned(),
544 extra: String::new(),
545 state: RunState::Done,
546 current_step: "Done".to_owned(),
547 steps: vec![(Duration::from_secs(3), "Read a.rs".to_owned())],
548 final_text: "ok".to_owned(),
549 started_at: Utc.with_ymd_and_hms(2026, 10, 1, 9, 0, 0).unwrap(),
550 ended_at: Some(Utc.with_ymd_and_hms(2026, 10, 1, 9, 1, 0).unwrap()),
551 expanded: false,
552 dismissed: false,
553 }
554 }
555
556 fn fake_settings(command: &str) -> AgentSettings {
557 let profile = AgentProfile {
558 id: "fake".to_owned(),
559 name: "Fake".to_owned(),
560 environment: Environment::Host,
561 command: command.to_owned(),
562 output: OutputFormat::ClaudeStreamJson,
563 open_session_command: String::new(),
564 mcp_config_flag: String::new(),
565 };
566 let action = AgentAction {
567 id: "ask".to_owned(),
568 label: "Ask".to_owned(),
569 agent_id: "fake".to_owned(),
570 working_dir: std::env::temp_dir().to_string_lossy().into_owned(),
571 prompt_template: "{message}".to_owned(),
572 ask_extra_instructions: false,
573 extra_args: String::new(),
574 };
575 AgentSettings {
576 agents: vec![profile],
577 actions: vec![action],
578 }
579 }
580
581 fn setup(cx: &mut TestAppContext, command: &str) -> (Entity<AppState>, Entity<AgentRuns>) {
582 cx.executor().allow_parking();
583 let store = Arc::new(Store::open_in_memory().unwrap());
584 store
585 .upsert_messages(&[MessageRecord {
586 conversation_id: "19:chat".to_owned(),
587 message_id: "m1".to_owned(),
588 sender_name: Some("Ada".to_owned()),
589 created_at: Utc.with_ymd_and_hms(2026, 10, 1, 9, 0, 0).unwrap(),
590 body_html: "<p>Where is the report?</p>".to_owned(),
591 attachments_json: "[]".to_owned(),
592 reactions_json: "[]".to_owned(),
593 mentions_json: "[]".to_owned(),
594 links_json: "[]".to_owned(),
595 ..MessageRecord::default()
596 }])
597 .unwrap();
598 run_store::save_settings(&store, &fake_settings(command));
599 cx.update(|cx| {
600 let app = cx.new(|_| AppState::new(store, Mode::default()));
601 let runs = cx.new(|cx| AgentRuns::new(app.clone(), cx));
602 (app, runs)
603 })
604 }
605
606 fn wait_until_finished(cx: &mut TestAppContext, runs: &Entity<AgentRuns>, run_id: u64) {
607 for _ in 0..500 {
608 cx.run_until_parked();
609 let finished = cx.update(|cx| {
610 runs.read(cx)
611 .get(run_id)
612 .is_some_and(|run| run.is_finished())
613 });
614 if finished {
615 return;
616 }
617 std::thread::sleep(Duration::from_millis(10));
618 }
619 panic!("the run did not finish");
620 }
621
622 #[cfg(unix)]
623 mod shell_runs {
624 use super::{RunState, TestAppContext, run_store, setup, wait_until_finished};
625
626 #[gpui_kit::test]
627 fn a_stream_json_run_ends_done_and_is_persisted(cx: &mut TestAppContext) {
628 let fixture = concat!(
629 env!("CARGO_MANIFEST_DIR"),
630 "/../agents/tests/fixtures/claude-stream.jsonl"
631 );
632 let (app, runs) = setup(cx, &format!("sh -c 'cat {fixture}'"));
633 let run_id = cx.update(|cx| {
634 runs.update(cx, |runs, cx| runs.start("ask", "19:chat", "m1", "", cx))
635 .unwrap()
636 });
637 wait_until_finished(cx, &runs, run_id);
638 cx.update(|cx| {
639 let run = runs.read(cx).get(run_id).unwrap().clone();
640 assert_eq!(run.state, RunState::Done);
641 assert_eq!(
642 run.current_step,
643 "Done - The first word in `/etc/hostname` is `HOST01`."
644 );
645 assert_eq!(run.steps.len(), 2);
646 assert_eq!(
647 run.steps[0].1,
648 "MCP server is off - no reply proposal possible"
649 );
650 assert_eq!(run.steps[1].1, "Reading hostname");
651 assert_eq!(run.chat_title, "Chat");
652 assert_eq!(run.sender_name, "Ada");
653 let stored = run_store::load_runs(&app.read(cx).store);
654 assert_eq!(stored.len(), 1);
655 assert_eq!(stored[0].state, RunState::Done);
656 assert_eq!(stored[0].session_id, run.session_id);
657 assert_eq!(runs.read(cx).running_count(), 0);
658 });
659 }
660
661 #[gpui_kit::test]
662 fn a_failing_command_ends_failed_with_its_stderr(cx: &mut TestAppContext) {
663 let (app, runs) = setup(cx, "sh -c 'echo boom >&2; exit 3'");
664 let run_id = cx.update(|cx| {
665 runs.update(cx, |runs, cx| runs.start("ask", "19:chat", "m1", "", cx))
666 .unwrap()
667 });
668 wait_until_finished(cx, &runs, run_id);
669 cx.update(|cx| {
670 let run = runs.read(cx).get(run_id).unwrap().clone();
671 assert_eq!(
672 run.state,
673 RunState::Failed {
674 message: "boom".to_owned(),
675 log: vec!["boom".to_owned()],
676 }
677 );
678 assert_eq!(run.current_step, "boom");
679 let stored = run_store::load_runs(&app.read(cx).store);
680 assert_eq!(stored[0].state, run.state);
681 });
682 }
683 }
684
685 #[gpui_kit::test]
686 fn a_missing_action_is_an_error_and_starts_nothing(cx: &mut TestAppContext) {
687 let (_, runs) = setup(cx, "true");
688 cx.update(|cx| {
689 let error = runs
690 .update(cx, |runs, cx| runs.start("ghost", "19:chat", "m1", "", cx))
691 .unwrap_err();
692 assert_eq!(error, "This action no longer exists");
693 let error = runs
694 .update(cx, |runs, cx| runs.start("ask", "19:chat", "gone", "", cx))
695 .unwrap_err();
696 assert_eq!(error, "The message is no longer available");
697 assert_eq!(runs.read(cx).running_count(), 0);
698 });
699 }
700
701 #[gpui_kit::test]
702 fn dismissed_runs_hide_and_stay_dismissed_after_reload(cx: &mut TestAppContext) {
703 let (app, runs) = setup(cx, "true");
704 cx.update(|cx| {
705 runs.update(cx, |runs, cx| {
706 runs.runs.push(finished_run(7));
707 runs.dismiss(7, cx);
708 assert!(runs.for_conversation("19:chat").next().is_none());
709 assert!(runs.recent(10).is_empty());
710 });
711 let reloaded = cx.new(|cx| AgentRuns::new(app.clone(), cx));
712 let reloaded = reloaded.read(cx);
713 assert!(reloaded.get(7).is_some_and(|run| run.dismissed));
714 assert_eq!(reloaded.next_id, 8);
715 });
716 }
717
718 #[gpui_kit::test]
719 fn runs_loaded_as_running_become_interrupted(cx: &mut TestAppContext) {
720 let (app, runs) = setup(cx, "true");
721 cx.update(|cx| {
722 let mut running = finished_run(5);
723 running.state = RunState::Running;
724 running.ended_at = None;
725 runs.update(cx, |runs, cx| {
726 runs.runs.push(running);
727 runs.persist(cx);
728 });
729 let reloaded = cx.new(|cx| AgentRuns::new(app.clone(), cx));
730 let run = reloaded.read(cx).get(5).unwrap().clone();
731 assert!(matches!(
732 run.state,
733 RunState::Failed { ref message, .. } if message == "Interrupted - the app was closed during the run"
734 ));
735 assert!(run.ended_at.is_some());
736 assert_eq!(run.session_id, "session-5");
737 assert_eq!(reloaded.read(cx).running_count(), 0);
738 });
739 }
740
741 #[test]
742 fn layout_key_counts_visible_detail_rows() {
743 let mut run = finished_run(1);
744 assert_eq!(run.layout_key(), (0, false));
745 run.expanded = true;
746 run.steps = (0..9)
747 .map(|index| (Duration::from_secs(index), index.to_string()))
748 .collect();
749 assert_eq!(run.layout_key(), (6, false));
750 assert_eq!(run.visible_steps()[0].1, "3");
751 run.state = RunState::Running;
752 assert_eq!(run.layout_key(), (6, true));
753 }
754
755 #[test]
756 fn elapsed_reads_as_minutes_and_seconds() {
757 assert_eq!(format_elapsed(Duration::from_secs(42)), "0:42");
758 assert_eq!(format_elapsed(Duration::from_secs(631)), "10:31");
759 assert_eq!(finished_run(1).elapsed_text(), "1:00");
760 }
761 }
@@ -0,0 +1,761 @@
1use std::collections::{HashMap, HashSet};
2use std::time::Duration;
3
4use agents::{AgentSettings, RunEvent, RunOutcome, RunStatus, RunUpdate};
5use chrono::{DateTime, Utc};
6use gpui_kit::*;
7use serde::{Deserialize, Serialize};
8use tokio::sync::{mpsc, oneshot};
9
10use super::{
11 StartRequest, demo, mcp_bridge, mcp_config_directory, message_context, open_run_session,
12 store as run_store,
13};
14use crate::app_state::AppState;
15use crate::notice::truncated;
16use crate::runtime;
17
18const STEP_LIMIT: usize = 50;
19const VISIBLE_STEPS: usize = 6;
20const VISIBLE_LOG_LINES: usize = 20;
21const TEXT_STEP_CHARS: usize = 80;
22const DONE_STEP_CHARS: usize = 60;
23const TICK: Duration = Duration::from_secs(1);
24
25#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
26pub enum RunState {
27 Running,
28 Done,
29 Failed { message: String, log: Vec<String> },
30 Stopped,
31}
32
33#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
34pub struct AgentRun {
35 pub id: u64,
36 pub action_id: String,
37 pub action_label: String,
38 pub agent_id: String,
39 pub agent_name: String,
40 pub conversation_id: String,
41 pub message_id: String,
42 pub chat_title: String,
43 pub sender_name: String,
44 pub session_id: String,
45 pub working_dir: String,
46 pub extra: String,
47 pub state: RunState,
48 pub current_step: String,
49 pub steps: Vec<(Duration, String)>,
50 pub final_text: String,
51 pub started_at: DateTime<Utc>,
52 pub ended_at: Option<DateTime<Utc>>,
53 #[serde(skip)]
54 pub expanded: bool,
55 pub dismissed: bool,
56}
57
58impl AgentRun {
59 pub fn is_running(&self) -> bool {
60 self.state == RunState::Running
61 }
62
63 pub fn is_finished(&self) -> bool {
64 !self.is_running()
65 }
66
67 pub fn elapsed(&self) -> Duration {
68 let end = self.ended_at.unwrap_or_else(Utc::now);
69 (end - self.started_at).to_std().unwrap_or_default()
70 }
71
72 pub fn elapsed_text(&self) -> String {
73 format_elapsed(self.elapsed())
74 }
75
76 pub fn visible_steps(&self) -> &[(Duration, String)] {
77 let skipped = self.steps.len().saturating_sub(VISIBLE_STEPS);
78 &self.steps[skipped..]
79 }
80
81 pub fn log_lines(&self) -> &[String] {
82 match &self.state {
83 RunState::Failed { log, .. } => {
84 let skipped = log.len().saturating_sub(VISIBLE_LOG_LINES);
85 &log[skipped..]
86 }
87 _ => &[],
88 }
89 }
90
91 pub fn layout_key(&self) -> (usize, bool) {
92 let rows = match (&self.state, self.expanded) {
93 (_, false) => 0,
94 (RunState::Failed { .. }, true) => self.log_lines().len().max(1),
95 (_, true) => self.visible_steps().len().max(1),
96 };
97 (rows, self.is_running())
98 }
99
100 fn mark_interrupted(&mut self) {
101 let message = "Interrupted - the app was closed during the run".to_owned();
102 self.current_step = message.clone();
103 self.state = RunState::Failed {
104 message,
105 log: Vec::new(),
106 };
107 self.ended_at = Some(Utc::now());
108 }
109
110 fn push_step(&mut self, text: String) {
111 let elapsed = (Utc::now() - self.started_at).to_std().unwrap_or_default();
112 self.steps.push((elapsed, text.clone()));
113 if self.steps.len() > STEP_LIMIT {
114 self.steps.remove(0);
115 }
116 self.current_step = text;
117 }
118}
119
120fn remove_stale_mcp_configs() {
121 let Some(directory) = mcp_config_directory() else {
122 return;
123 };
124 let Ok(entries) = std::fs::read_dir(directory) else {
125 return;
126 };
127 for entry in entries.flatten() {
128 let _ = std::fs::remove_file(entry.path());
129 }
130}
131
132pub fn format_elapsed(duration: Duration) -> String {
133 let seconds = duration.as_secs();
134 format!("{}:{:02}", seconds / 60, seconds % 60)
135}
136
137fn first_line(text: &str) -> &str {
138 text.lines()
139 .find(|line| !line.trim().is_empty())
140 .unwrap_or("")
141 .trim()
142}
143
144pub struct AgentRunsHandle(pub Entity<AgentRuns>);
145
146impl Global for AgentRunsHandle {}
147
148pub enum AgentRunsEvent {
149 Finished(u64),
150 StartRequested(StartRequest),
151 OpenSettings,
152}
153
154pub struct AgentRuns {
155 app: Entity<AppState>,
156 settings: AgentSettings,
157 runs: Vec<AgentRun>,
158 stops: HashMap<u64, oneshot::Sender<()>>,
159 open_after_stop: HashSet<u64>,
160 next_id: u64,
161 ticking: bool,
162}
163
164impl EventEmitter<AgentRunsEvent> for AgentRuns {}
165
166impl AgentRuns {
167 pub fn new(app: Entity<AppState>, cx: &mut Context<Self>) -> Self {
168 let store = app.read(cx).store.clone();
169 let mut runs = run_store::load_runs(&store);
170 let interrupted = runs.iter().any(AgentRun::is_running);
171 for run in runs.iter_mut().filter(|run| run.is_running()) {
172 run.mark_interrupted();
173 }
174 if interrupted {
175 run_store::save_runs(&store, &runs);
176 }
177 remove_stale_mcp_configs();
178 if runs.is_empty() && app.read(cx).mode.demo {
179 runs = demo::runs(app.read(cx));
180 }
181 let next_id = runs.iter().map(|run| run.id).max().map_or(1, |id| id + 1);
182 let mut agent_runs = AgentRuns {
183 app,
184 settings: run_store::load_settings(&store),
185 runs,
186 stops: HashMap::new(),
187 open_after_stop: HashSet::new(),
188 next_id,
189 ticking: false,
190 };
191 agent_runs.ensure_ticking(cx);
192 agent_runs
193 }
194
195 pub fn settings(&self) -> &AgentSettings {
196 &self.settings
197 }
198
199 pub fn update_settings(
200 &mut self,
201 change: impl FnOnce(&mut AgentSettings),
202 cx: &mut Context<Self>,
203 ) {
204 change(&mut self.settings);
205 run_store::save_settings(&self.app.read(cx).store, &self.settings);
206 cx.notify();
207 }
208
209 pub fn get(&self, run_id: u64) -> Option<&AgentRun> {
210 self.runs.iter().find(|run| run.id == run_id)
211 }
212
213 pub fn by_session(&self, session_id: &str) -> Option<&AgentRun> {
214 self.runs
215 .iter()
216 .rev()
217 .find(|run| run.session_id == session_id)
218 }
219
220 pub fn for_conversation<'a>(
221 &'a self,
222 conversation_id: &'a str,
223 ) -> impl Iterator<Item = &'a AgentRun> {
224 self.runs
225 .iter()
226 .filter(move |run| run.conversation_id == conversation_id && !run.dismissed)
227 }
228
229 pub fn running_count(&self) -> usize {
230 self.runs.iter().filter(|run| run.is_running()).count()
231 }
232
233 pub fn recent(&self, limit: usize) -> Vec<&AgentRun> {
234 self.runs
235 .iter()
236 .rev()
237 .filter(|run| !run.dismissed)
238 .take(limit)
239 .collect()
240 }
241
242 fn run_mut(&mut self, run_id: u64) -> Option<&mut AgentRun> {
243 self.runs.iter_mut().find(|run| run.id == run_id)
244 }
245
246 fn persist(&self, cx: &App) {
247 run_store::save_runs(&self.app.read(cx).store, &self.runs);
248 }
249
250 pub fn start(
251 &mut self,
252 action_id: &str,
253 conversation_id: &str,
254 message_id: &str,
255 extra: &str,
256 cx: &mut Context<Self>,
257 ) -> Result<u64, String> {
258 let action = self
259 .settings
260 .actions
261 .iter()
262 .find(|action| action.id == action_id)
263 .cloned()
264 .ok_or("This action no longer exists")?;
265 let profile = self
266 .settings
267 .agents
268 .iter()
269 .find(|profile| profile.id == action.agent_id)
270 .cloned()
271 .ok_or("The agent of this action no longer exists")?;
272 let context = message_context::build(self.app.read(cx), conversation_id, message_id)
273 .ok_or("The message is no longer available")?;
274 let session_id = agents::new_session_id();
275 let prompt = agents::build_prompt(&action, &context, extra, &session_id, &profile.id);
276 let endpoint = mcp_bridge::endpoint(cx);
277 let plan = agents::build_invocation(
278 &profile,
279 &action,
280 &prompt,
281 &session_id,
282 endpoint.as_ref(),
283 mcp_config_directory().as_deref(),
284 );
285 let run_id = self.next_id;
286 self.next_id += 1;
287 self.runs.push(AgentRun {
288 id: run_id,
289 action_id: action.id.clone(),
290 action_label: action.label.clone(),
291 agent_id: profile.id.clone(),
292 agent_name: profile.name.clone(),
293 conversation_id: conversation_id.to_owned(),
294 message_id: message_id.to_owned(),
295 chat_title: context.chat.clone(),
296 sender_name: context.sender.clone(),
297 session_id,
298 working_dir: action.working_dir.clone(),
299 extra: extra.to_owned(),
300 state: RunState::Running,
301 current_step: "Starting".to_owned(),
302 steps: Vec::new(),
303 final_text: String::new(),
304 started_at: Utc::now(),
305 ended_at: None,
306 expanded: false,
307 dismissed: false,
308 });
309 if endpoint.is_none()
310 && let Some(run) = self.run_mut(run_id)
311 {
312 run.push_step("MCP server is off - no reply proposal possible".to_owned());
313 }
314 match plan {
315 Ok(plan) => self.spawn(run_id, plan, profile.output, cx),
316 Err(error) => self.finish(
317 run_id,
318 Some(RunOutcome {
319 status: RunStatus::Failed {
320 message: error.to_string(),
321 stderr_tail: Vec::new(),
322 },
323 exit_code: None,
324 }),
325 cx,
326 ),
327 }
328 self.persist(cx);
329 self.ensure_ticking(cx);
330 cx.notify();
331 Ok(run_id)
332 }
333
334 fn spawn(
335 &mut self,
336 run_id: u64,
337 plan: agents::RunPlan,
338 format: agents::OutputFormat,
339 cx: &mut Context<Self>,
340 ) {
341 let (updates_sender, mut updates) = mpsc::unbounded_channel();
342 let (stop_sender, stop_receiver) = oneshot::channel();
343 self.stops.insert(run_id, stop_sender);
344 let outcome = runtime::spawn(agents::run(plan, format, updates_sender, stop_receiver));
345 cx.spawn(async move |this, cx| {
346 while let Some(update) = updates.recv().await {
347 if this
348 .update(cx, |runs, cx| runs.apply_update(run_id, update, cx))
349 .is_err()
350 {
351 return;
352 }
353 }
354 let outcome = outcome.await.ok();
355 this.update(cx, |runs, cx| runs.finish(run_id, outcome, cx))
356 .ok();
357 })
358 .detach();
359 }
360
361 fn apply_update(&mut self, run_id: u64, update: RunUpdate, cx: &mut Context<Self>) {
362 let RunUpdate::Event(event) = update else {
363 return;
364 };
365 let Some(run) = self.run_mut(run_id) else {
366 return;
367 };
368 match event {
369 RunEvent::Step(text) => run.push_step(text),
370 RunEvent::Text(text) => {
371 run.current_step = truncated(first_line(&text), TEXT_STEP_CHARS)
372 }
373 _ => return,
374 }
375 cx.notify();
376 }
377
378 fn finish(&mut self, run_id: u64, outcome: Option<RunOutcome>, cx: &mut Context<Self>) {
379 self.stops.remove(&run_id);
380 let Some(run) = self.run_mut(run_id).filter(|run| run.is_running()) else {
381 return;
382 };
383 run.ended_at = Some(Utc::now());
384 match outcome.map(|outcome| outcome.status) {
385 Some(RunStatus::Completed { final_text }) => {
386 let line = truncated(first_line(&final_text), DONE_STEP_CHARS);
387 run.current_step = if line.is_empty() {
388 "Done".to_owned()
389 } else {
390 format!("Done - {line}")
391 };
392 run.final_text = final_text;
393 run.state = RunState::Done;
394 }
395 Some(RunStatus::Failed {
396 message,
397 stderr_tail,
398 }) => {
399 run.current_step = message.clone();
400 run.state = RunState::Failed {
401 message,
402 log: stderr_tail,
403 };
404 }
405 Some(RunStatus::Stopped) => {
406 run.current_step = "Stopped".to_owned();
407 run.state = RunState::Stopped;
408 }
409 None => {
410 let message = "The run was cancelled".to_owned();
411 run.current_step = message.clone();
412 run.state = RunState::Failed {
413 message,
414 log: Vec::new(),
415 };
416 }
417 }
418 let stopped = run.state == RunState::Stopped;
419 let failed_or_done = !stopped;
420 let snapshot = run.clone();
421 self.prune_finished();
422 self.persist(cx);
423 if failed_or_done {
424 cx.emit(AgentRunsEvent::Finished(run_id));
425 }
426 if self.open_after_stop.remove(&run_id) && stopped {
427 open_run_session(&snapshot, cx);
428 }
429 cx.notify();
430 }
431
432 fn prune_finished(&mut self) {
433 let finished = self.runs.iter().filter(|run| run.is_finished()).count();
434 let mut excess = finished.saturating_sub(run_store::RUNS_HISTORY_LIMIT);
435 self.runs.retain(|run| {
436 if excess > 0 && run.is_finished() {
437 excess -= 1;
438 return false;
439 }
440 true
441 });
442 }
443
444 fn ensure_ticking(&mut self, cx: &mut Context<Self>) {
445 if self.ticking || self.running_count() == 0 {
446 return;
447 }
448 self.ticking = true;
449 cx.spawn(async move |this, cx| {
450 loop {
451 cx.background_executor().timer(TICK).await;
452 let keep_going = this
453 .update(cx, |runs, cx| {
454 runs.ticking = runs.running_count() > 0;
455 if runs.ticking {
456 cx.notify();
457 }
458 runs.ticking
459 })
460 .unwrap_or(false);
461 if !keep_going {
462 break;
463 }
464 }
465 })
466 .detach();
467 }
468
469 pub fn stop(&mut self, run_id: u64, cx: &mut Context<Self>) {
470 if let Some(stop) = self.stops.remove(&run_id) {
471 let _ = stop.send(());
472 if let Some(run) = self.run_mut(run_id) {
473 run.current_step = "Stopping".to_owned();
474 }
475 cx.notify();
476 }
477 }
478
479 pub fn stop_and_open_session(&mut self, run_id: u64, cx: &mut Context<Self>) {
480 self.open_after_stop.insert(run_id);
481 self.stop(run_id, cx);
482 }
483
484 pub fn retry(&mut self, run_id: u64, cx: &mut Context<Self>) -> Result<u64, String> {
485 let run = self
486 .get(run_id)
487 .cloned()
488 .ok_or("This run no longer exists")?;
489 let started = self.start(
490 &run.action_id,
491 &run.conversation_id,
492 &run.message_id,
493 &run.extra,
494 cx,
495 )?;
496 self.dismiss(run_id, cx);
497 Ok(started)
498 }
499
500 pub fn dismiss(&mut self, run_id: u64, cx: &mut Context<Self>) {
501 let Some(run) = self.run_mut(run_id).filter(|run| run.is_finished()) else {
502 return;
503 };
504 run.dismissed = true;
505 self.persist(cx);
506 cx.notify();
507 }
508
509 pub fn toggle_expanded(&mut self, run_id: u64, cx: &mut Context<Self>) {
510 if let Some(run) = self.run_mut(run_id) {
511 run.expanded = !run.expanded;
512 cx.notify();
513 }
514 }
515}
516
517#[cfg(test)]
518pub(super) mod tests {
519 use std::sync::Arc;
520 use std::time::Duration;
521
522 use agents::{AgentAction, AgentProfile, AgentSettings, Environment, OutputFormat};
523 use chrono::TimeZone;
524 use store::{MessageRecord, Store};
525
526 use gpui_kit::{AppContext as _, Entity, TestAppContext};
527
528 use super::{AgentRun, AgentRuns, RunState, Utc, format_elapsed, run_store};
529 use crate::app_state::{AppState, Mode};
530
531 pub fn finished_run(id: u64) -> AgentRun {
532 AgentRun {
533 id,
534 action_id: "answer-this".to_owned(),
535 action_label: "Answer this".to_owned(),
536 agent_id: "claude".to_owned(),
537 agent_name: "Claude Code".to_owned(),
538 conversation_id: "19:chat".to_owned(),
539 message_id: format!("m{id}"),
540 chat_title: "Ops".to_owned(),
541 sender_name: "Ada".to_owned(),
542 session_id: format!("session-{id}"),
543 working_dir: "~".to_owned(),
544 extra: String::new(),
545 state: RunState::Done,
546 current_step: "Done".to_owned(),
547 steps: vec![(Duration::from_secs(3), "Read a.rs".to_owned())],
548 final_text: "ok".to_owned(),
549 started_at: Utc.with_ymd_and_hms(2026, 10, 1, 9, 0, 0).unwrap(),
550 ended_at: Some(Utc.with_ymd_and_hms(2026, 10, 1, 9, 1, 0).unwrap()),
551 expanded: false,
552 dismissed: false,
553 }
554 }
555
556 fn fake_settings(command: &str) -> AgentSettings {
557 let profile = AgentProfile {
558 id: "fake".to_owned(),
559 name: "Fake".to_owned(),
560 environment: Environment::Host,
561 command: command.to_owned(),
562 output: OutputFormat::ClaudeStreamJson,
563 open_session_command: String::new(),
564 mcp_config_flag: String::new(),
565 };
566 let action = AgentAction {
567 id: "ask".to_owned(),
568 label: "Ask".to_owned(),
569 agent_id: "fake".to_owned(),
570 working_dir: std::env::temp_dir().to_string_lossy().into_owned(),
571 prompt_template: "{message}".to_owned(),
572 ask_extra_instructions: false,
573 extra_args: String::new(),
574 };
575 AgentSettings {
576 agents: vec![profile],
577 actions: vec![action],
578 }
579 }
580
581 fn setup(cx: &mut TestAppContext, command: &str) -> (Entity<AppState>, Entity<AgentRuns>) {
582 cx.executor().allow_parking();
583 let store = Arc::new(Store::open_in_memory().unwrap());
584 store
585 .upsert_messages(&[MessageRecord {
586 conversation_id: "19:chat".to_owned(),
587 message_id: "m1".to_owned(),
588 sender_name: Some("Ada".to_owned()),
589 created_at: Utc.with_ymd_and_hms(2026, 10, 1, 9, 0, 0).unwrap(),
590 body_html: "<p>Where is the report?</p>".to_owned(),
591 attachments_json: "[]".to_owned(),
592 reactions_json: "[]".to_owned(),
593 mentions_json: "[]".to_owned(),
594 links_json: "[]".to_owned(),
595 ..MessageRecord::default()
596 }])
597 .unwrap();
598 run_store::save_settings(&store, &fake_settings(command));
599 cx.update(|cx| {
600 let app = cx.new(|_| AppState::new(store, Mode::default()));
601 let runs = cx.new(|cx| AgentRuns::new(app.clone(), cx));
602 (app, runs)
603 })
604 }
605
606 fn wait_until_finished(cx: &mut TestAppContext, runs: &Entity<AgentRuns>, run_id: u64) {
607 for _ in 0..500 {
608 cx.run_until_parked();
609 let finished = cx.update(|cx| {
610 runs.read(cx)
611 .get(run_id)
612 .is_some_and(|run| run.is_finished())
613 });
614 if finished {
615 return;
616 }
617 std::thread::sleep(Duration::from_millis(10));
618 }
619 panic!("the run did not finish");
620 }
621
622 #[cfg(unix)]
623 mod shell_runs {
624 use super::{RunState, TestAppContext, run_store, setup, wait_until_finished};
625
626 #[gpui_kit::test]
627 fn a_stream_json_run_ends_done_and_is_persisted(cx: &mut TestAppContext) {
628 let fixture = concat!(
629 env!("CARGO_MANIFEST_DIR"),
630 "/../agents/tests/fixtures/claude-stream.jsonl"
631 );
632 let (app, runs) = setup(cx, &format!("sh -c 'cat {fixture}'"));
633 let run_id = cx.update(|cx| {
634 runs.update(cx, |runs, cx| runs.start("ask", "19:chat", "m1", "", cx))
635 .unwrap()
636 });
637 wait_until_finished(cx, &runs, run_id);
638 cx.update(|cx| {
639 let run = runs.read(cx).get(run_id).unwrap().clone();
640 assert_eq!(run.state, RunState::Done);
641 assert_eq!(
642 run.current_step,
643 "Done - The first word in `/etc/hostname` is `HOST01`."
644 );
645 assert_eq!(run.steps.len(), 2);
646 assert_eq!(
647 run.steps[0].1,
648 "MCP server is off - no reply proposal possible"
649 );
650 assert_eq!(run.steps[1].1, "Reading hostname");
651 assert_eq!(run.chat_title, "Chat");
652 assert_eq!(run.sender_name, "Ada");
653 let stored = run_store::load_runs(&app.read(cx).store);
654 assert_eq!(stored.len(), 1);
655 assert_eq!(stored[0].state, RunState::Done);
656 assert_eq!(stored[0].session_id, run.session_id);
657 assert_eq!(runs.read(cx).running_count(), 0);
658 });
659 }
660
661 #[gpui_kit::test]
662 fn a_failing_command_ends_failed_with_its_stderr(cx: &mut TestAppContext) {
663 let (app, runs) = setup(cx, "sh -c 'echo boom >&2; exit 3'");
664 let run_id = cx.update(|cx| {
665 runs.update(cx, |runs, cx| runs.start("ask", "19:chat", "m1", "", cx))
666 .unwrap()
667 });
668 wait_until_finished(cx, &runs, run_id);
669 cx.update(|cx| {
670 let run = runs.read(cx).get(run_id).unwrap().clone();
671 assert_eq!(
672 run.state,
673 RunState::Failed {
674 message: "boom".to_owned(),
675 log: vec!["boom".to_owned()],
676 }
677 );
678 assert_eq!(run.current_step, "boom");
679 let stored = run_store::load_runs(&app.read(cx).store);
680 assert_eq!(stored[0].state, run.state);
681 });
682 }
683 }
684
685 #[gpui_kit::test]
686 fn a_missing_action_is_an_error_and_starts_nothing(cx: &mut TestAppContext) {
687 let (_, runs) = setup(cx, "true");
688 cx.update(|cx| {
689 let error = runs
690 .update(cx, |runs, cx| runs.start("ghost", "19:chat", "m1", "", cx))
691 .unwrap_err();
692 assert_eq!(error, "This action no longer exists");
693 let error = runs
694 .update(cx, |runs, cx| runs.start("ask", "19:chat", "gone", "", cx))
695 .unwrap_err();
696 assert_eq!(error, "The message is no longer available");
697 assert_eq!(runs.read(cx).running_count(), 0);
698 });
699 }
700
701 #[gpui_kit::test]
702 fn dismissed_runs_hide_and_stay_dismissed_after_reload(cx: &mut TestAppContext) {
703 let (app, runs) = setup(cx, "true");
704 cx.update(|cx| {
705 runs.update(cx, |runs, cx| {
706 runs.runs.push(finished_run(7));
707 runs.dismiss(7, cx);
708 assert!(runs.for_conversation("19:chat").next().is_none());
709 assert!(runs.recent(10).is_empty());
710 });
711 let reloaded = cx.new(|cx| AgentRuns::new(app.clone(), cx));
712 let reloaded = reloaded.read(cx);
713 assert!(reloaded.get(7).is_some_and(|run| run.dismissed));
714 assert_eq!(reloaded.next_id, 8);
715 });
716 }
717
718 #[gpui_kit::test]
719 fn runs_loaded_as_running_become_interrupted(cx: &mut TestAppContext) {
720 let (app, runs) = setup(cx, "true");
721 cx.update(|cx| {
722 let mut running = finished_run(5);
723 running.state = RunState::Running;
724 running.ended_at = None;
725 runs.update(cx, |runs, cx| {
726 runs.runs.push(running);
727 runs.persist(cx);
728 });
729 let reloaded = cx.new(|cx| AgentRuns::new(app.clone(), cx));
730 let run = reloaded.read(cx).get(5).unwrap().clone();
731 assert!(matches!(
732 run.state,
733 RunState::Failed { ref message, .. } if message == "Interrupted - the app was closed during the run"
734 ));
735 assert!(run.ended_at.is_some());
736 assert_eq!(run.session_id, "session-5");
737 assert_eq!(reloaded.read(cx).running_count(), 0);
738 });
739 }
740
741 #[test]
742 fn layout_key_counts_visible_detail_rows() {
743 let mut run = finished_run(1);
744 assert_eq!(run.layout_key(), (0, false));
745 run.expanded = true;
746 run.steps = (0..9)
747 .map(|index| (Duration::from_secs(index), index.to_string()))
748 .collect();
749 assert_eq!(run.layout_key(), (6, false));
750 assert_eq!(run.visible_steps()[0].1, "3");
751 run.state = RunState::Running;
752 assert_eq!(run.layout_key(), (6, true));
753 }
754
755 #[test]
756 fn elapsed_reads_as_minutes_and_seconds() {
757 assert_eq!(format_elapsed(Duration::from_secs(42)), "0:42");
758 assert_eq!(format_elapsed(Duration::from_secs(631)), "10:31");
759 assert_eq!(finished_run(1).elapsed_text(), "1:00");
760 }
761}
crates/app/src/agents/runs_popover.rs added +190 −0
@@ -0,0 +1,190 @@
1 use gpui_kit::assets::IconName;
2 use gpui_kit::base::PopoverState;
3 use gpui_kit::component::{h_flex, v_flex};
4 use gpui_kit::prelude::FluentBuilder as _;
5 use gpui_kit::*;
6
7 use super::runs::{AgentRun, AgentRuns, RunState};
8 use super::spinner::spinner;
9 use crate::app_state::AppState;
10 use crate::notify::selection_for;
11 use crate::theme;
12 use crate::views::widgets::icon;
13
14 const POPOVER_WIDTH: f32 = 300.;
15 const DONE_LIMIT: usize = 10;
16 const HISTORY_WINDOW: usize = 60;
17 const STATUS_ICON: f32 = 12.;
18
19 pub struct RunsPopover {
20 app: Entity<AppState>,
21 runs: Entity<AgentRuns>,
22 popover: Option<WeakEntity<PopoverState>>,
23 _subscription: Subscription,
24 }
25
26 impl RunsPopover {
27 pub fn new(app: Entity<AppState>, runs: Entity<AgentRuns>, cx: &mut Context<Self>) -> Self {
28 let subscription = cx.observe(&runs, |_, _, cx| cx.notify());
29 RunsPopover {
30 app,
31 runs,
32 popover: None,
33 _subscription: subscription,
34 }
35 }
36
37 pub fn set_popover(&mut self, popover: WeakEntity<PopoverState>) {
38 self.popover = Some(popover);
39 }
40
41 fn show(&mut self, run: &AgentRun, window: &mut Window, cx: &mut Context<Self>) {
42 let selection = selection_for(&self.app.read(cx).sidebar, &run.conversation_id);
43 if let Some(selection) = selection {
44 let message_id = run.message_id.clone();
45 self.app.update(cx, |state, cx| {
46 state.jump_to_message(selection, message_id, cx)
47 });
48 }
49 if let Some(popover) = &self.popover {
50 popover
51 .update(cx, |state, cx| state.dismiss(window, cx))
52 .ok();
53 }
54 }
55
56 fn row(&self, run: &AgentRun, cx: &mut Context<Self>) -> Stateful<Div> {
57 let shown = run.clone();
58 let status = match &run.state {
59 RunState::Running => div().mt(px(2.)).child(spinner(STATUS_ICON)),
60 RunState::Done => {
61 div()
62 .mt(px(2.))
63 .child(icon(IconName::Check, STATUS_ICON, theme::accent_text()))
64 }
65 RunState::Failed { .. } => {
66 div()
67 .mt(px(2.))
68 .child(icon(IconName::X, STATUS_ICON, theme::red_soft()))
69 }
70 RunState::Stopped => {
71 div()
72 .mt(px(2.))
73 .child(icon(IconName::Square, STATUS_ICON, theme::text_faint()))
74 }
75 };
76 let trailing = if run.is_running() {
77 div()
78 .text_size(px(11.))
79 .text_color(theme::text_faint())
80 .child(run.elapsed_text())
81 } else {
82 div()
83 .text_size(px(12.))
84 .font_weight(FontWeight::SEMIBOLD)
85 .text_color(theme::accent_text())
86 .child("Show")
87 };
88 h_flex()
89 .id(("agent-run-row", run.id as usize))
90 .w_full()
91 .px(px(10.))
92 .py(px(6.))
93 .gap(px(10.))
94 .items_start()
95 .rounded(px(6.))
96 .cursor_pointer()
97 .hover(|row| row.bg(theme::popup_hover()))
98 .child(status.flex_none())
99 .child(
100 v_flex()
101 .flex_1()
102 .min_w(px(0.))
103 .gap(px(2.))
104 .child(
105 div()
106 .truncate()
107 .text_size(px(13.))
108 .text_color(theme::text())
109 .child(format!("{} - {}", run.action_label, run.chat_title)),
110 )
111 .child(
112 div()
113 .truncate()
114 .text_size(px(12.))
115 .text_color(theme::text_muted())
116 .child(run.current_step.clone()),
117 ),
118 )
119 .child(trailing.flex_none())
120 .on_click(cx.listener(move |this, _, window, cx| this.show(&shown, window, cx)))
121 }
122 }
123
124 fn section_header(title: &'static str) -> Div {
125 div()
126 .px(px(10.))
127 .pt(px(6.))
128 .pb(px(4.))
129 .text_size(px(11.))
130 .font_weight(FontWeight::SEMIBOLD)
131 .text_color(theme::text_faint())
132 .child(title)
133 }
134
135 pub fn split_runs(runs: Vec<&AgentRun>) -> (Vec<&AgentRun>, Vec<&AgentRun>) {
136 let (running, finished): (Vec<&AgentRun>, Vec<&AgentRun>) =
137 runs.into_iter().partition(|run| run.is_running());
138 (running, finished.into_iter().take(DONE_LIMIT).collect())
139 }
140
141 impl Render for RunsPopover {
142 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
143 let runs = self.runs.read(cx);
144 let (running, finished) = split_runs(runs.recent(HISTORY_WINDOW));
145 let (running, finished): (Vec<AgentRun>, Vec<AgentRun>) = (
146 running.into_iter().cloned().collect(),
147 finished.into_iter().cloned().collect(),
148 );
149 let empty = running.is_empty() && finished.is_empty();
150 v_flex()
151 .w(px(POPOVER_WIDTH))
152 .when(!running.is_empty(), |list| {
153 list.child(section_header("Running"))
154 .children(running.iter().map(|run| self.row(run, cx)))
155 })
156 .when(!finished.is_empty(), |list| {
157 list.child(section_header("Done"))
158 .children(finished.iter().map(|run| self.row(run, cx)))
159 })
160 .when(empty, |list| {
161 list.child(
162 div()
163 .px(px(10.))
164 .py(px(8.))
165 .text_size(px(12.))
166 .text_color(theme::text_faint())
167 .child("No agent runs yet"),
168 )
169 })
170 }
171 }
172
173 #[cfg(test)]
174 mod tests {
175 use super::split_runs;
176 use crate::agents::runs::RunState;
177 use crate::agents::runs::tests::finished_run;
178
179 #[test]
180 fn running_runs_go_first_and_done_is_capped_at_ten() {
181 let mut runs: Vec<_> = (0..14).map(finished_run).collect();
182 runs[3].state = RunState::Running;
183 let newest_first: Vec<_> = runs.iter().rev().collect();
184 let (running, finished) = split_runs(newest_first);
185 assert_eq!(running.len(), 1);
186 assert_eq!(running[0].id, 3);
187 assert_eq!(finished.len(), 10);
188 assert_eq!(finished[0].id, 13);
189 }
190 }
@@ -0,0 +1,190 @@
1use gpui_kit::assets::IconName;
2use gpui_kit::base::PopoverState;
3use gpui_kit::component::{h_flex, v_flex};
4use gpui_kit::prelude::FluentBuilder as _;
5use gpui_kit::*;
6
7use super::runs::{AgentRun, AgentRuns, RunState};
8use super::spinner::spinner;
9use crate::app_state::AppState;
10use crate::notify::selection_for;
11use crate::theme;
12use crate::views::widgets::icon;
13
14const POPOVER_WIDTH: f32 = 300.;
15const DONE_LIMIT: usize = 10;
16const HISTORY_WINDOW: usize = 60;
17const STATUS_ICON: f32 = 12.;
18
19pub struct RunsPopover {
20 app: Entity<AppState>,
21 runs: Entity<AgentRuns>,
22 popover: Option<WeakEntity<PopoverState>>,
23 _subscription: Subscription,
24}
25
26impl RunsPopover {
27 pub fn new(app: Entity<AppState>, runs: Entity<AgentRuns>, cx: &mut Context<Self>) -> Self {
28 let subscription = cx.observe(&runs, |_, _, cx| cx.notify());
29 RunsPopover {
30 app,
31 runs,
32 popover: None,
33 _subscription: subscription,
34 }
35 }
36
37 pub fn set_popover(&mut self, popover: WeakEntity<PopoverState>) {
38 self.popover = Some(popover);
39 }
40
41 fn show(&mut self, run: &AgentRun, window: &mut Window, cx: &mut Context<Self>) {
42 let selection = selection_for(&self.app.read(cx).sidebar, &run.conversation_id);
43 if let Some(selection) = selection {
44 let message_id = run.message_id.clone();
45 self.app.update(cx, |state, cx| {
46 state.jump_to_message(selection, message_id, cx)
47 });
48 }
49 if let Some(popover) = &self.popover {
50 popover
51 .update(cx, |state, cx| state.dismiss(window, cx))
52 .ok();
53 }
54 }
55
56 fn row(&self, run: &AgentRun, cx: &mut Context<Self>) -> Stateful<Div> {
57 let shown = run.clone();
58 let status = match &run.state {
59 RunState::Running => div().mt(px(2.)).child(spinner(STATUS_ICON)),
60 RunState::Done => {
61 div()
62 .mt(px(2.))
63 .child(icon(IconName::Check, STATUS_ICON, theme::accent_text()))
64 }
65 RunState::Failed { .. } => {
66 div()
67 .mt(px(2.))
68 .child(icon(IconName::X, STATUS_ICON, theme::red_soft()))
69 }
70 RunState::Stopped => {
71 div()
72 .mt(px(2.))
73 .child(icon(IconName::Square, STATUS_ICON, theme::text_faint()))
74 }
75 };
76 let trailing = if run.is_running() {
77 div()
78 .text_size(px(11.))
79 .text_color(theme::text_faint())
80 .child(run.elapsed_text())
81 } else {
82 div()
83 .text_size(px(12.))
84 .font_weight(FontWeight::SEMIBOLD)
85 .text_color(theme::accent_text())
86 .child("Show")
87 };
88 h_flex()
89 .id(("agent-run-row", run.id as usize))
90 .w_full()
91 .px(px(10.))
92 .py(px(6.))
93 .gap(px(10.))
94 .items_start()
95 .rounded(px(6.))
96 .cursor_pointer()
97 .hover(|row| row.bg(theme::popup_hover()))
98 .child(status.flex_none())
99 .child(
100 v_flex()
101 .flex_1()
102 .min_w(px(0.))
103 .gap(px(2.))
104 .child(
105 div()
106 .truncate()
107 .text_size(px(13.))
108 .text_color(theme::text())
109 .child(format!("{} - {}", run.action_label, run.chat_title)),
110 )
111 .child(
112 div()
113 .truncate()
114 .text_size(px(12.))
115 .text_color(theme::text_muted())
116 .child(run.current_step.clone()),
117 ),
118 )
119 .child(trailing.flex_none())
120 .on_click(cx.listener(move |this, _, window, cx| this.show(&shown, window, cx)))
121 }
122}
123
124fn section_header(title: &'static str) -> Div {
125 div()
126 .px(px(10.))
127 .pt(px(6.))
128 .pb(px(4.))
129 .text_size(px(11.))
130 .font_weight(FontWeight::SEMIBOLD)
131 .text_color(theme::text_faint())
132 .child(title)
133}
134
135pub fn split_runs(runs: Vec<&AgentRun>) -> (Vec<&AgentRun>, Vec<&AgentRun>) {
136 let (running, finished): (Vec<&AgentRun>, Vec<&AgentRun>) =
137 runs.into_iter().partition(|run| run.is_running());
138 (running, finished.into_iter().take(DONE_LIMIT).collect())
139}
140
141impl Render for RunsPopover {
142 fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
143 let runs = self.runs.read(cx);
144 let (running, finished) = split_runs(runs.recent(HISTORY_WINDOW));
145 let (running, finished): (Vec<AgentRun>, Vec<AgentRun>) = (
146 running.into_iter().cloned().collect(),
147 finished.into_iter().cloned().collect(),
148 );
149 let empty = running.is_empty() && finished.is_empty();
150 v_flex()
151 .w(px(POPOVER_WIDTH))
152 .when(!running.is_empty(), |list| {
153 list.child(section_header("Running"))
154 .children(running.iter().map(|run| self.row(run, cx)))
155 })
156 .when(!finished.is_empty(), |list| {
157 list.child(section_header("Done"))
158 .children(finished.iter().map(|run| self.row(run, cx)))
159 })
160 .when(empty, |list| {
161 list.child(
162 div()
163 .px(px(10.))
164 .py(px(8.))
165 .text_size(px(12.))
166 .text_color(theme::text_faint())
167 .child("No agent runs yet"),
168 )
169 })
170 }
171}
172
173#[cfg(test)]
174mod tests {
175 use super::split_runs;
176 use crate::agents::runs::RunState;
177 use crate::agents::runs::tests::finished_run;
178
179 #[test]
180 fn running_runs_go_first_and_done_is_capped_at_ten() {
181 let mut runs: Vec<_> = (0..14).map(finished_run).collect();
182 runs[3].state = RunState::Running;
183 let newest_first: Vec<_> = runs.iter().rev().collect();
184 let (running, finished) = split_runs(newest_first);
185 assert_eq!(running.len(), 1);
186 assert_eq!(running[0].id, 3);
187 assert_eq!(finished.len(), 10);
188 assert_eq!(finished[0].id, 13);
189 }
190}
crates/app/src/agents/settings_controls.rs added +169 −0
@@ -0,0 +1,169 @@
1 use std::rc::Rc;
2
3 use gpui_kit::assets::IconName;
4 use gpui_kit::component::{
5 ActiveTheme as _,
6 button::{Button, ButtonVariants as _},
7 h_flex,
8 input::{Input, InputState},
9 menu::{DropdownMenu as _, PopupMenuItem},
10 v_flex,
11 };
12 use gpui_kit::prelude::FluentBuilder as _;
13 use gpui_kit::*;
14
15 use crate::theme;
16
17 pub const PAGE_PADDING: f32 = 20.;
18 const FIELD_HEIGHT: f32 = 32.;
19 const MONO_SIZE: f32 = 11.5;
20
21 pub type Choice = Rc<dyn Fn(&mut Window, &mut App)>;
22
23 pub struct MenuEntry {
24 pub label: String,
25 pub selected: bool,
26 pub choose: Choice,
27 }
28
29 pub fn field(
30 label: &'static str,
31 control: impl IntoElement,
32 hint: Option<AnyElement>,
33 problem: Option<String>,
34 ) -> Div {
35 v_flex()
36 .w_full()
37 .gap(px(6.))
38 .child(
39 div()
40 .text_size(px(12.))
41 .font_weight(FontWeight::SEMIBOLD)
42 .text_color(theme::text_soft())
43 .child(label),
44 )
45 .child(control)
46 .children(hint)
47 .children(problem.map(|problem| {
48 div()
49 .text_size(px(12.))
50 .text_color(theme::red_soft())
51 .child(problem)
52 }))
53 }
54
55 pub fn hint(text: &'static str) -> AnyElement {
56 div()
57 .text_size(px(11.))
58 .text_color(theme::text_faint())
59 .child(text)
60 .into_any_element()
61 }
62
63 pub fn text_field(state: &Entity<InputState>, mono: bool, invalid: bool, cx: &App) -> Div {
64 div()
65 .w_full()
66 .h(px(FIELD_HEIGHT))
67 .px(px(12.))
68 .flex()
69 .items_center()
70 .overflow_hidden()
71 .rounded(px(8.))
72 .bg(theme::surface_raised())
73 .border_1()
74 .border_color(if invalid {
75 theme::red_soft()
76 } else {
77 theme::surface_raised()
78 })
79 .when(mono, |field| {
80 field
81 .font_family(cx.theme().mono_font_family.clone())
82 .text_size(px(MONO_SIZE))
83 })
84 .child(Input::new(state).appearance(false).bordered(false))
85 }
86
87 pub fn boxed(content: impl IntoElement, invalid: bool, cx: &App) -> Div {
88 div()
89 .w_full()
90 .px(px(12.))
91 .py(px(8.))
92 .rounded(px(8.))
93 .bg(theme::surface_raised())
94 .border_1()
95 .border_color(if invalid {
96 theme::red_soft()
97 } else {
98 theme::surface_raised()
99 })
100 .font_family(cx.theme().mono_font_family.clone())
101 .text_size(px(MONO_SIZE))
102 .child(content)
103 }
104
105 pub fn raised_button(id: &'static str, label: &'static str) -> Stateful<Div> {
106 h_flex()
107 .id(id)
108 .h(px(FIELD_HEIGHT))
109 .px(px(12.))
110 .items_center()
111 .rounded(px(8.))
112 .cursor_pointer()
113 .bg(theme::surface_raised())
114 .hover(|button| button.bg(theme::popup_hover()))
115 .text_size(px(13.))
116 .child(label)
117 }
118
119 pub fn dropdown(id: &'static str, label: String, entries: Vec<MenuEntry>) -> impl IntoElement {
120 Button::new(id)
121 .outline()
122 .w_full()
123 .label(label)
124 .icon(IconName::ChevronDown)
125 .dropdown_menu(move |menu, _, _| {
126 entries.iter().fold(menu, |menu, entry| {
127 let choose = entry.choose.clone();
128 menu.item(
129 PopupMenuItem::new(entry.label.clone())
130 .checked(entry.selected)
131 .on_click(move |_, window, cx| choose(window, cx)),
132 )
133 })
134 })
135 }
136
137 pub fn link_dropdown(
138 id: &'static str,
139 label: &'static str,
140 entries: Vec<MenuEntry>,
141 ) -> impl IntoElement {
142 Button::new(id)
143 .link()
144 .label(label)
145 .dropdown_menu(move |menu, _, _| {
146 entries.iter().fold(menu, |menu, entry| {
147 let choose = entry.choose.clone();
148 menu.item(
149 PopupMenuItem::new(entry.label.clone())
150 .on_click(move |_, window, cx| choose(window, cx)),
151 )
152 })
153 })
154 }
155
156 pub fn section_header(title: &'static str, trailing: Option<AnyElement>) -> Div {
157 h_flex()
158 .w_full()
159 .items_center()
160 .justify_between()
161 .px(px(PAGE_PADDING))
162 .pt(px(16.))
163 .pb(px(6.))
164 .text_size(px(11.))
165 .font_weight(FontWeight::SEMIBOLD)
166 .text_color(theme::text_faint())
167 .child(title)
168 .children(trailing)
169 }
@@ -0,0 +1,169 @@
1use std::rc::Rc;
2
3use gpui_kit::assets::IconName;
4use gpui_kit::component::{
5 ActiveTheme as _,
6 button::{Button, ButtonVariants as _},
7 h_flex,
8 input::{Input, InputState},
9 menu::{DropdownMenu as _, PopupMenuItem},
10 v_flex,
11};
12use gpui_kit::prelude::FluentBuilder as _;
13use gpui_kit::*;
14
15use crate::theme;
16
17pub const PAGE_PADDING: f32 = 20.;
18const FIELD_HEIGHT: f32 = 32.;
19const MONO_SIZE: f32 = 11.5;
20
21pub type Choice = Rc<dyn Fn(&mut Window, &mut App)>;
22
23pub struct MenuEntry {
24 pub label: String,
25 pub selected: bool,
26 pub choose: Choice,
27}
28
29pub fn field(
30 label: &'static str,
31 control: impl IntoElement,
32 hint: Option<AnyElement>,
33 problem: Option<String>,
34) -> Div {
35 v_flex()
36 .w_full()
37 .gap(px(6.))
38 .child(
39 div()
40 .text_size(px(12.))
41 .font_weight(FontWeight::SEMIBOLD)
42 .text_color(theme::text_soft())
43 .child(label),
44 )
45 .child(control)
46 .children(hint)
47 .children(problem.map(|problem| {
48 div()
49 .text_size(px(12.))
50 .text_color(theme::red_soft())
51 .child(problem)
52 }))
53}
54
55pub fn hint(text: &'static str) -> AnyElement {
56 div()
57 .text_size(px(11.))
58 .text_color(theme::text_faint())
59 .child(text)
60 .into_any_element()
61}
62
63pub fn text_field(state: &Entity<InputState>, mono: bool, invalid: bool, cx: &App) -> Div {
64 div()
65 .w_full()
66 .h(px(FIELD_HEIGHT))
67 .px(px(12.))
68 .flex()
69 .items_center()
70 .overflow_hidden()
71 .rounded(px(8.))
72 .bg(theme::surface_raised())
73 .border_1()
74 .border_color(if invalid {
75 theme::red_soft()
76 } else {
77 theme::surface_raised()
78 })
79 .when(mono, |field| {
80 field
81 .font_family(cx.theme().mono_font_family.clone())
82 .text_size(px(MONO_SIZE))
83 })
84 .child(Input::new(state).appearance(false).bordered(false))
85}
86
87pub fn boxed(content: impl IntoElement, invalid: bool, cx: &App) -> Div {
88 div()
89 .w_full()
90 .px(px(12.))
91 .py(px(8.))
92 .rounded(px(8.))
93 .bg(theme::surface_raised())
94 .border_1()
95 .border_color(if invalid {
96 theme::red_soft()
97 } else {
98 theme::surface_raised()
99 })
100 .font_family(cx.theme().mono_font_family.clone())
101 .text_size(px(MONO_SIZE))
102 .child(content)
103}
104
105pub fn raised_button(id: &'static str, label: &'static str) -> Stateful<Div> {
106 h_flex()
107 .id(id)
108 .h(px(FIELD_HEIGHT))
109 .px(px(12.))
110 .items_center()
111 .rounded(px(8.))
112 .cursor_pointer()
113 .bg(theme::surface_raised())
114 .hover(|button| button.bg(theme::popup_hover()))
115 .text_size(px(13.))
116 .child(label)
117}
118
119pub fn dropdown(id: &'static str, label: String, entries: Vec<MenuEntry>) -> impl IntoElement {
120 Button::new(id)
121 .outline()
122 .w_full()
123 .label(label)
124 .icon(IconName::ChevronDown)
125 .dropdown_menu(move |menu, _, _| {
126 entries.iter().fold(menu, |menu, entry| {
127 let choose = entry.choose.clone();
128 menu.item(
129 PopupMenuItem::new(entry.label.clone())
130 .checked(entry.selected)
131 .on_click(move |_, window, cx| choose(window, cx)),
132 )
133 })
134 })
135}
136
137pub fn link_dropdown(
138 id: &'static str,
139 label: &'static str,
140 entries: Vec<MenuEntry>,
141) -> impl IntoElement {
142 Button::new(id)
143 .link()
144 .label(label)
145 .dropdown_menu(move |menu, _, _| {
146 entries.iter().fold(menu, |menu, entry| {
147 let choose = entry.choose.clone();
148 menu.item(
149 PopupMenuItem::new(entry.label.clone())
150 .on_click(move |_, window, cx| choose(window, cx)),
151 )
152 })
153 })
154}
155
156pub fn section_header(title: &'static str, trailing: Option<AnyElement>) -> Div {
157 h_flex()
158 .w_full()
159 .items_center()
160 .justify_between()
161 .px(px(PAGE_PADDING))
162 .pt(px(16.))
163 .pb(px(6.))
164 .text_size(px(11.))
165 .font_weight(FontWeight::SEMIBOLD)
166 .text_color(theme::text_faint())
167 .child(title)
168 .children(trailing)
169}
crates/app/src/agents/settings_forms.rs added +440 −0
@@ -0,0 +1,440 @@
1 use std::rc::Rc;
2
3 use agents::{Environment, OutputFormat};
4 use gpui_kit::assets::IconName;
5 use gpui_kit::component::{ActiveTheme as _, h_flex, input::Textarea, v_flex};
6 use gpui_kit::prelude::FluentBuilder as _;
7 use gpui_kit::*;
8
9 use super::settings_controls::{
10 Choice, MenuEntry, PAGE_PADDING, boxed, dropdown, field, hint, raised_button, text_field,
11 };
12 use super::settings_problems::{agent_problem, command_problem, placeholder_problem};
13 use super::settings_section::{AgentsSettings, Probe};
14 use crate::notify::switch;
15 use crate::theme;
16 use crate::views::widgets::icon;
17
18 const PLACEHOLDER_CHIPS: [&str; 9] = [
19 "message",
20 "sender",
21 "chat",
22 "thread",
23 "extra",
24 "conversation_id",
25 "message_id",
26 "session_id",
27 "agent",
28 ];
29
30 fn environment_choices() -> [(&'static str, Environment); 3] {
31 [
32 ("Windows", Environment::Host),
33 ("WSL - default distro", Environment::Wsl { distro: None }),
34 (
35 "WSL - named distro",
36 Environment::Wsl {
37 distro: Some(String::new()),
38 },
39 ),
40 ]
41 }
42
43 fn environment_kind(environment: &Environment) -> u8 {
44 match environment {
45 Environment::Host => 0,
46 Environment::Wsl { distro: None } => 1,
47 Environment::Wsl { distro: Some(_) } => 2,
48 }
49 }
50
51 fn same_environment_kind(left: &Environment, right: &Environment) -> bool {
52 environment_kind(left) == environment_kind(right)
53 }
54
55 fn output_choices() -> [(&'static str, OutputFormat); 3] {
56 [
57 (
58 "Claude stream-json - live steps",
59 OutputFormat::ClaudeStreamJson,
60 ),
61 ("Copilot JSON - live steps", OutputFormat::CopilotJsonl),
62 ("Plain text - time and last line", OutputFormat::Text),
63 ]
64 }
65
66 fn back_row(title: String, cx: &mut Context<AgentsSettings>) -> Stateful<Div> {
67 h_flex()
68 .id("agents-back")
69 .w_full()
70 .px(px(PAGE_PADDING))
71 .pt(px(12.))
72 .pb(px(8.))
73 .gap(px(6.))
74 .items_center()
75 .cursor_pointer()
76 .text_size(px(15.))
77 .font_weight(FontWeight::BOLD)
78 .child(icon(IconName::ArrowLeft, 16., theme::text()))
79 .child(div().truncate().child(title))
80 .on_click(cx.listener(|this, _, _, cx| this.go_back(cx)))
81 }
82
83 fn form(children: impl IntoIterator<Item = AnyElement>) -> Div {
84 v_flex()
85 .w_full()
86 .px(px(PAGE_PADDING))
87 .pb(px(16.))
88 .gap(px(12.))
89 .children(children)
90 }
91
92 impl AgentsSettings {
93 pub(super) fn agent_page(&mut self, _: &mut Window, cx: &mut Context<Self>) -> Div {
94 let (Some(form_state), Some(profile)) = (&self.agent_form, self.current_agent(cx)) else {
95 return div();
96 };
97 let problems = self.runs.read(cx).settings().validate();
98 let this = cx.entity();
99 let environment_entries: Vec<MenuEntry> = environment_choices()
100 .into_iter()
101 .map(|(label, environment)| {
102 let this = this.clone();
103 let selected = same_environment_kind(&environment, &profile.environment);
104 let choose: Choice = Rc::new(move |window, cx| {
105 let environment = environment.clone();
106 this.update(cx, |this, cx| this.set_environment(environment, window, cx))
107 });
108 MenuEntry {
109 label: label.to_owned(),
110 selected,
111 choose,
112 }
113 })
114 .collect();
115 let environment_label = environment_choices()
116 .into_iter()
117 .find(|(_, environment)| same_environment_kind(environment, &profile.environment))
118 .map_or("Windows", |(label, _)| label);
119 let output_entries: Vec<MenuEntry> = output_choices()
120 .into_iter()
121 .map(|(label, output)| {
122 let this = this.clone();
123 let choose: Choice =
124 Rc::new(move |_, cx| this.update(cx, |this, cx| this.set_output(output, cx)));
125 MenuEntry {
126 label: label.to_owned(),
127 selected: output == profile.output,
128 choose,
129 }
130 })
131 .collect();
132 let output_label = output_choices()
133 .into_iter()
134 .find(|(_, output)| *output == profile.output)
135 .map_or("", |(label, _)| label);
136 let command_problem = command_problem(&problems, &profile.id, &profile.command);
137 let open_problem =
138 placeholder_problem(&problems, &profile.id, &profile.open_session_command);
139 let named_distro = matches!(profile.environment, Environment::Wsl { distro: Some(_) });
140 let status = match &self.probe {
141 Probe::Idle => None,
142 Probe::Running => Some(("Testing...".to_owned(), theme::text_muted())),
143 Probe::Found(line) => Some((format!("Found: {line}"), theme::green())),
144 Probe::Missing(error) => Some((error.clone(), theme::red_soft())),
145 };
146 let test_this = this.clone();
147 let delete_this = this.clone();
148 v_flex()
149 .w_full()
150 .child(back_row(profile.name.clone(), cx))
151 .child(form([
152 field(
153 "Name",
154 text_field(&form_state.name, false, false, cx),
155 None,
156 None,
157 )
158 .into_any_element(),
159 field(
160 "Runs in",
161 dropdown(
162 "agent-environment",
163 environment_label.to_owned(),
164 environment_entries,
165 ),
166 Some(hint(
167 "Windows or a WSL distro. Paths below are in that system.",
168 )),
169 None,
170 )
171 .into_any_element(),
172 div()
173 .w_full()
174 .when(named_distro, |slot| {
175 slot.child(field(
176 "Distro name",
177 text_field(&form_state.distro, false, false, cx),
178 None,
179 None,
180 ))
181 })
182 .into_any_element(),
183 field(
184 "Command",
185 text_field(&form_state.command, true, command_problem.is_some(), cx),
186 Some(hint(
187 "The prompt goes to stdin unless the command has {prompt}.",
188 )),
189 command_problem,
190 )
191 .into_any_element(),
192 field(
193 "Output",
194 dropdown("agent-output", output_label.to_owned(), output_entries),
195 Some(hint("Plain text shows only the time and the last line.")),
196 None,
197 )
198 .into_any_element(),
199 field(
200 "MCP config flag",
201 text_field(&form_state.mcp_flag, true, false, cx),
202 Some(hint(
203 "Passes the Teams MCP endpoint to the agent. Empty = none.",
204 )),
205 None,
206 )
207 .into_any_element(),
208 field(
209 "Open session",
210 text_field(&form_state.open_session, true, open_problem.is_some(), cx),
211 Some(hint("Available: {cwd} and {session_id}.")),
212 open_problem,
213 )
214 .into_any_element(),
215 h_flex()
216 .w_full()
217 .gap(px(8.))
218 .items_center()
219 .child(
220 raised_button("agent-test", "Test").on_click(move |_, _, cx| {
221 test_this.update(cx, |this, cx| this.test_agent(cx))
222 }),
223 )
224 .children(status.map(|(text, color)| {
225 div()
226 .flex_1()
227 .min_w(px(0.))
228 .truncate()
229 .text_size(px(12.))
230 .text_color(color)
231 .child(text)
232 }))
233 .child(div().flex_1())
234 .child(
235 div()
236 .id("agent-delete")
237 .cursor_pointer()
238 .text_size(px(13.))
239 .text_color(theme::red_soft())
240 .child("Delete")
241 .on_click(move |_, _, cx| {
242 delete_this.update(cx, |this, cx| this.delete_agent(cx))
243 }),
244 )
245 .into_any_element(),
246 ]))
247 }
248
249 pub(super) fn action_page(&mut self, _: &mut Window, cx: &mut Context<Self>) -> Div {
250 let Some(form_state) = &self.action_form else {
251 return div();
252 };
253 let settings = self.runs.read(cx).settings().clone();
254 let Some(action) = settings
255 .actions
256 .iter()
257 .find(|action| action.id == form_state.id)
258 .cloned()
259 else {
260 return div();
261 };
262 let problems = settings.validate();
263 let this = cx.entity();
264 let agent_entries: Vec<MenuEntry> = settings
265 .agents
266 .iter()
267 .map(|agent| {
268 let (this, agent_id) = (this.clone(), agent.id.clone());
269 let selected = agent.id == action.agent_id;
270 let choose: Choice = Rc::new(move |_, cx| {
271 let agent_id = agent_id.clone();
272 this.update(cx, |this, cx| this.set_action_agent(agent_id, cx))
273 });
274 MenuEntry {
275 label: agent.name.clone(),
276 selected,
277 choose,
278 }
279 })
280 .collect();
281 let agent_label = settings
282 .agents
283 .iter()
284 .find(|agent| agent.id == action.agent_id)
285 .map_or("Choose an agent".to_owned(), |agent| agent.name.clone());
286 let agent_problem = agent_problem(&problems, &action.id);
287 let prompt_problem = placeholder_problem(&problems, &action.id, &action.prompt_template);
288 let args_problem = placeholder_problem(&problems, &action.id, &action.extra_args);
289 let chips =
290 h_flex()
291 .w_full()
292 .flex_wrap()
293 .gap(px(4.))
294 .children(PLACEHOLDER_CHIPS.iter().map(|placeholder| {
295 let this = this.clone();
296 div()
297 .id(*placeholder)
298 .px(px(6.))
299 .py(px(2.))
300 .rounded(px(6.))
301 .cursor_pointer()
302 .bg(theme::row_hover())
303 .hover(|chip| chip.bg(theme::surface_raised()))
304 .font_family(cx.theme().mono_font_family.clone())
305 .text_size(px(11.))
306 .text_color(theme::accent_text())
307 .child(format!("{{{placeholder}}}"))
308 .on_click(move |_, window, cx| {
309 this.update(cx, |this, cx| {
310 this.insert_placeholder(placeholder, window, cx)
311 })
312 })
313 }));
314 let ask = action.ask_extra_instructions;
315 let (ask_this, delete_this) = (this.clone(), this.clone());
316 v_flex()
317 .w_full()
318 .child(back_row(action.label.clone(), cx))
319 .child(form([
320 h_flex()
321 .w_full()
322 .gap(px(8.))
323 .items_start()
324 .child(
325 field(
326 "Label",
327 text_field(&form_state.label, false, false, cx),
328 None,
329 None,
330 )
331 .flex_1()
332 .min_w(px(0.)),
333 )
334 .child(
335 field(
336 "Agent",
337 dropdown("action-agent", agent_label, agent_entries),
338 None,
339 agent_problem,
340 )
341 .flex_1()
342 .min_w(px(0.)),
343 )
344 .into_any_element(),
345 field(
346 "Working dir",
347 text_field(&form_state.working_dir, true, false, cx),
348 Some(hint("A path inside the system the agent runs in.")),
349 None,
350 )
351 .into_any_element(),
352 field(
353 "Prompt",
354 boxed(
355 Textarea::new(&form_state.prompt)
356 .appearance(false)
357 .bordered(false),
358 prompt_problem.is_some(),
359 cx,
360 ),
361 Some(chips.into_any_element()),
362 prompt_problem,
363 )
364 .into_any_element(),
365 h_flex()
366 .id("action-ask-extra")
367 .w_full()
368 .gap(px(12.))
369 .items_center()
370 .cursor_pointer()
371 .child(
372 v_flex()
373 .flex_1()
374 .child(
375 div()
376 .text_size(px(14.))
377 .font_weight(FontWeight::SEMIBOLD)
378 .child("Ask for extra instructions"),
379 )
380 .child(
381 div()
382 .text_size(px(12.))
383 .text_color(theme::text_muted())
384 .child("Dialog before each run"),
385 ),
386 )
387 .child(switch(ask))
388 .on_click(move |_, _, cx| {
389 ask_this.update(cx, |this, cx| this.set_ask_extra(!ask, cx))
390 })
391 .into_any_element(),
392 field(
393 "Extra args",
394 text_field(&form_state.extra_args, true, args_problem.is_some(), cx),
395 Some(hint("Added after the agent command.")),
396 args_problem,
397 )
398 .into_any_element(),
399 h_flex()
400 .w_full()
401 .justify_end()
402 .child(
403 div()
404 .id("action-delete")
405 .cursor_pointer()
406 .text_size(px(13.))
407 .text_color(theme::red_soft())
408 .child("Delete")
409 .on_click(move |_, _, cx| {
410 delete_this.update(cx, |this, cx| this.delete_action(cx))
411 }),
412 )
413 .into_any_element(),
414 ]))
415 }
416 }
417
418 #[cfg(test)]
419 mod tests {
420 use agents::Environment;
421
422 use super::same_environment_kind;
423
424 #[test]
425 fn environments_compare_by_kind_not_distro_name() {
426 let named = |name: &str| Environment::Wsl {
427 distro: Some(name.to_owned()),
428 };
429 assert!(same_environment_kind(&named("Ubuntu"), &named("Debian")));
430 assert!(!same_environment_kind(
431 &named("Ubuntu"),
432 &Environment::Wsl { distro: None }
433 ));
434 assert!(!same_environment_kind(&Environment::Host, &named("Ubuntu")));
435 assert!(same_environment_kind(
436 &Environment::Host,
437 &Environment::Host
438 ));
439 }
440 }
@@ -0,0 +1,440 @@
1use std::rc::Rc;
2
3use agents::{Environment, OutputFormat};
4use gpui_kit::assets::IconName;
5use gpui_kit::component::{ActiveTheme as _, h_flex, input::Textarea, v_flex};
6use gpui_kit::prelude::FluentBuilder as _;
7use gpui_kit::*;
8
9use super::settings_controls::{
10 Choice, MenuEntry, PAGE_PADDING, boxed, dropdown, field, hint, raised_button, text_field,
11};
12use super::settings_problems::{agent_problem, command_problem, placeholder_problem};
13use super::settings_section::{AgentsSettings, Probe};
14use crate::notify::switch;
15use crate::theme;
16use crate::views::widgets::icon;
17
18const PLACEHOLDER_CHIPS: [&str; 9] = [
19 "message",
20 "sender",
21 "chat",
22 "thread",
23 "extra",
24 "conversation_id",
25 "message_id",
26 "session_id",
27 "agent",
28];
29
30fn environment_choices() -> [(&'static str, Environment); 3] {
31 [
32 ("Windows", Environment::Host),
33 ("WSL - default distro", Environment::Wsl { distro: None }),
34 (
35 "WSL - named distro",
36 Environment::Wsl {
37 distro: Some(String::new()),
38 },
39 ),
40 ]
41}
42
43fn environment_kind(environment: &Environment) -> u8 {
44 match environment {
45 Environment::Host => 0,
46 Environment::Wsl { distro: None } => 1,
47 Environment::Wsl { distro: Some(_) } => 2,
48 }
49}
50
51fn same_environment_kind(left: &Environment, right: &Environment) -> bool {
52 environment_kind(left) == environment_kind(right)
53}
54
55fn output_choices() -> [(&'static str, OutputFormat); 3] {
56 [
57 (
58 "Claude stream-json - live steps",
59 OutputFormat::ClaudeStreamJson,
60 ),
61 ("Copilot JSON - live steps", OutputFormat::CopilotJsonl),
62 ("Plain text - time and last line", OutputFormat::Text),
63 ]
64}
65
66fn back_row(title: String, cx: &mut Context<AgentsSettings>) -> Stateful<Div> {
67 h_flex()
68 .id("agents-back")
69 .w_full()
70 .px(px(PAGE_PADDING))
71 .pt(px(12.))
72 .pb(px(8.))
73 .gap(px(6.))
74 .items_center()
75 .cursor_pointer()
76 .text_size(px(15.))
77 .font_weight(FontWeight::BOLD)
78 .child(icon(IconName::ArrowLeft, 16., theme::text()))
79 .child(div().truncate().child(title))
80 .on_click(cx.listener(|this, _, _, cx| this.go_back(cx)))
81}
82
83fn form(children: impl IntoIterator<Item = AnyElement>) -> Div {
84 v_flex()
85 .w_full()
86 .px(px(PAGE_PADDING))
87 .pb(px(16.))
88 .gap(px(12.))
89 .children(children)
90}
91
92impl AgentsSettings {
93 pub(super) fn agent_page(&mut self, _: &mut Window, cx: &mut Context<Self>) -> Div {
94 let (Some(form_state), Some(profile)) = (&self.agent_form, self.current_agent(cx)) else {
95 return div();
96 };
97 let problems = self.runs.read(cx).settings().validate();
98 let this = cx.entity();
99 let environment_entries: Vec<MenuEntry> = environment_choices()
100 .into_iter()
101 .map(|(label, environment)| {
102 let this = this.clone();
103 let selected = same_environment_kind(&environment, &profile.environment);
104 let choose: Choice = Rc::new(move |window, cx| {
105 let environment = environment.clone();
106 this.update(cx, |this, cx| this.set_environment(environment, window, cx))
107 });
108 MenuEntry {
109 label: label.to_owned(),
110 selected,
111 choose,
112 }
113 })
114 .collect();
115 let environment_label = environment_choices()
116 .into_iter()
117 .find(|(_, environment)| same_environment_kind(environment, &profile.environment))
118 .map_or("Windows", |(label, _)| label);
119 let output_entries: Vec<MenuEntry> = output_choices()
120 .into_iter()
121 .map(|(label, output)| {
122 let this = this.clone();
123 let choose: Choice =
124 Rc::new(move |_, cx| this.update(cx, |this, cx| this.set_output(output, cx)));
125 MenuEntry {
126 label: label.to_owned(),
127 selected: output == profile.output,
128 choose,
129 }
130 })
131 .collect();
132 let output_label = output_choices()
133 .into_iter()
134 .find(|(_, output)| *output == profile.output)
135 .map_or("", |(label, _)| label);
136 let command_problem = command_problem(&problems, &profile.id, &profile.command);
137 let open_problem =
138 placeholder_problem(&problems, &profile.id, &profile.open_session_command);
139 let named_distro = matches!(profile.environment, Environment::Wsl { distro: Some(_) });
140 let status = match &self.probe {
141 Probe::Idle => None,
142 Probe::Running => Some(("Testing...".to_owned(), theme::text_muted())),
143 Probe::Found(line) => Some((format!("Found: {line}"), theme::green())),
144 Probe::Missing(error) => Some((error.clone(), theme::red_soft())),
145 };
146 let test_this = this.clone();
147 let delete_this = this.clone();
148 v_flex()
149 .w_full()
150 .child(back_row(profile.name.clone(), cx))
151 .child(form([
152 field(
153 "Name",
154 text_field(&form_state.name, false, false, cx),
155 None,
156 None,
157 )
158 .into_any_element(),
159 field(
160 "Runs in",
161 dropdown(
162 "agent-environment",
163 environment_label.to_owned(),
164 environment_entries,
165 ),
166 Some(hint(
167 "Windows or a WSL distro. Paths below are in that system.",
168 )),
169 None,
170 )
171 .into_any_element(),
172 div()
173 .w_full()
174 .when(named_distro, |slot| {
175 slot.child(field(
176 "Distro name",
177 text_field(&form_state.distro, false, false, cx),
178 None,
179 None,
180 ))
181 })
182 .into_any_element(),
183 field(
184 "Command",
185 text_field(&form_state.command, true, command_problem.is_some(), cx),
186 Some(hint(
187 "The prompt goes to stdin unless the command has {prompt}.",
188 )),
189 command_problem,
190 )
191 .into_any_element(),
192 field(
193 "Output",
194 dropdown("agent-output", output_label.to_owned(), output_entries),
195 Some(hint("Plain text shows only the time and the last line.")),
196 None,
197 )
198 .into_any_element(),
199 field(
200 "MCP config flag",
201 text_field(&form_state.mcp_flag, true, false, cx),
202 Some(hint(
203 "Passes the Teams MCP endpoint to the agent. Empty = none.",
204 )),
205 None,
206 )
207 .into_any_element(),
208 field(
209 "Open session",
210 text_field(&form_state.open_session, true, open_problem.is_some(), cx),
211 Some(hint("Available: {cwd} and {session_id}.")),
212 open_problem,
213 )
214 .into_any_element(),
215 h_flex()
216 .w_full()
217 .gap(px(8.))
218 .items_center()
219 .child(
220 raised_button("agent-test", "Test").on_click(move |_, _, cx| {
221 test_this.update(cx, |this, cx| this.test_agent(cx))
222 }),
223 )
224 .children(status.map(|(text, color)| {
225 div()
226 .flex_1()
227 .min_w(px(0.))
228 .truncate()
229 .text_size(px(12.))
230 .text_color(color)
231 .child(text)
232 }))
233 .child(div().flex_1())
234 .child(
235 div()
236 .id("agent-delete")
237 .cursor_pointer()
238 .text_size(px(13.))
239 .text_color(theme::red_soft())
240 .child("Delete")
241 .on_click(move |_, _, cx| {
242 delete_this.update(cx, |this, cx| this.delete_agent(cx))
243 }),
244 )
245 .into_any_element(),
246 ]))
247 }
248
249 pub(super) fn action_page(&mut self, _: &mut Window, cx: &mut Context<Self>) -> Div {
250 let Some(form_state) = &self.action_form else {
251 return div();
252 };
253 let settings = self.runs.read(cx).settings().clone();
254 let Some(action) = settings
255 .actions
256 .iter()
257 .find(|action| action.id == form_state.id)
258 .cloned()
259 else {
260 return div();
261 };
262 let problems = settings.validate();
263 let this = cx.entity();
264 let agent_entries: Vec<MenuEntry> = settings
265 .agents
266 .iter()
267 .map(|agent| {
268 let (this, agent_id) = (this.clone(), agent.id.clone());
269 let selected = agent.id == action.agent_id;
270 let choose: Choice = Rc::new(move |_, cx| {
271 let agent_id = agent_id.clone();
272 this.update(cx, |this, cx| this.set_action_agent(agent_id, cx))
273 });
274 MenuEntry {
275 label: agent.name.clone(),
276 selected,
277 choose,
278 }
279 })
280 .collect();
281 let agent_label = settings
282 .agents
283 .iter()
284 .find(|agent| agent.id == action.agent_id)
285 .map_or("Choose an agent".to_owned(), |agent| agent.name.clone());
286 let agent_problem = agent_problem(&problems, &action.id);
287 let prompt_problem = placeholder_problem(&problems, &action.id, &action.prompt_template);
288 let args_problem = placeholder_problem(&problems, &action.id, &action.extra_args);
289 let chips =
290 h_flex()
291 .w_full()
292 .flex_wrap()
293 .gap(px(4.))
294 .children(PLACEHOLDER_CHIPS.iter().map(|placeholder| {
295 let this = this.clone();
296 div()
297 .id(*placeholder)
298 .px(px(6.))
299 .py(px(2.))
300 .rounded(px(6.))
301 .cursor_pointer()
302 .bg(theme::row_hover())
303 .hover(|chip| chip.bg(theme::surface_raised()))
304 .font_family(cx.theme().mono_font_family.clone())
305 .text_size(px(11.))
306 .text_color(theme::accent_text())
307 .child(format!("{{{placeholder}}}"))
308 .on_click(move |_, window, cx| {
309 this.update(cx, |this, cx| {
310 this.insert_placeholder(placeholder, window, cx)
311 })
312 })
313 }));
314 let ask = action.ask_extra_instructions;
315 let (ask_this, delete_this) = (this.clone(), this.clone());
316 v_flex()
317 .w_full()
318 .child(back_row(action.label.clone(), cx))
319 .child(form([
320 h_flex()
321 .w_full()
322 .gap(px(8.))
323 .items_start()
324 .child(
325 field(
326 "Label",
327 text_field(&form_state.label, false, false, cx),
328 None,
329 None,
330 )
331 .flex_1()
332 .min_w(px(0.)),
333 )
334 .child(
335 field(
336 "Agent",
337 dropdown("action-agent", agent_label, agent_entries),
338 None,
339 agent_problem,
340 )
341 .flex_1()
342 .min_w(px(0.)),
343 )
344 .into_any_element(),
345 field(
346 "Working dir",
347 text_field(&form_state.working_dir, true, false, cx),
348 Some(hint("A path inside the system the agent runs in.")),
349 None,
350 )
351 .into_any_element(),
352 field(
353 "Prompt",
354 boxed(
355 Textarea::new(&form_state.prompt)
356 .appearance(false)
357 .bordered(false),
358 prompt_problem.is_some(),
359 cx,
360 ),
361 Some(chips.into_any_element()),
362 prompt_problem,
363 )
364 .into_any_element(),
365 h_flex()
366 .id("action-ask-extra")
367 .w_full()
368 .gap(px(12.))
369 .items_center()
370 .cursor_pointer()
371 .child(
372 v_flex()
373 .flex_1()
374 .child(
375 div()
376 .text_size(px(14.))
377 .font_weight(FontWeight::SEMIBOLD)
378 .child("Ask for extra instructions"),
379 )
380 .child(
381 div()
382 .text_size(px(12.))
383 .text_color(theme::text_muted())
384 .child("Dialog before each run"),
385 ),
386 )
387 .child(switch(ask))
388 .on_click(move |_, _, cx| {
389 ask_this.update(cx, |this, cx| this.set_ask_extra(!ask, cx))
390 })
391 .into_any_element(),
392 field(
393 "Extra args",
394 text_field(&form_state.extra_args, true, args_problem.is_some(), cx),
395 Some(hint("Added after the agent command.")),
396 args_problem,
397 )
398 .into_any_element(),
399 h_flex()
400 .w_full()
401 .justify_end()
402 .child(
403 div()
404 .id("action-delete")
405 .cursor_pointer()
406 .text_size(px(13.))
407 .text_color(theme::red_soft())
408 .child("Delete")
409 .on_click(move |_, _, cx| {
410 delete_this.update(cx, |this, cx| this.delete_action(cx))
411 }),
412 )
413 .into_any_element(),
414 ]))
415 }
416}
417
418#[cfg(test)]
419mod tests {
420 use agents::Environment;
421
422 use super::same_environment_kind;
423
424 #[test]
425 fn environments_compare_by_kind_not_distro_name() {
426 let named = |name: &str| Environment::Wsl {
427 distro: Some(name.to_owned()),
428 };
429 assert!(same_environment_kind(&named("Ubuntu"), &named("Debian")));
430 assert!(!same_environment_kind(
431 &named("Ubuntu"),
432 &Environment::Wsl { distro: None }
433 ));
434 assert!(!same_environment_kind(&Environment::Host, &named("Ubuntu")));
435 assert!(same_environment_kind(
436 &Environment::Host,
437 &Environment::Host
438 ));
439 }
440}
crates/app/src/agents/settings_problems.rs added +93 −0
@@ -0,0 +1,93 @@
1 use agents::SettingsProblem;
2
3 pub fn placeholder_problem(
4 problems: &[SettingsProblem],
5 item_id: &str,
6 text: &str,
7 ) -> Option<String> {
8 problems.iter().find_map(|problem| match problem {
9 SettingsProblem::UnknownPlaceholder {
10 item_id: problem_item,
11 placeholder,
12 } if problem_item == item_id && text.contains(&format!("{{{placeholder}}}")) => {
13 Some(format!("Unknown placeholder {{{placeholder}}}"))
14 }
15 _ => None,
16 })
17 }
18
19 pub fn command_problem(problems: &[SettingsProblem], agent_id: &str, text: &str) -> Option<String> {
20 let empty = problems.iter().any(
21 |problem| matches!(problem, SettingsProblem::EmptyCommand { agent_id: id } if id == agent_id),
22 );
23 if empty {
24 return Some("The command is empty".to_owned());
25 }
26 placeholder_problem(problems, agent_id, text)
27 }
28
29 pub fn agent_problem(problems: &[SettingsProblem], action_id: &str) -> Option<String> {
30 problems.iter().find_map(|problem| match problem {
31 SettingsProblem::UnknownAgent {
32 action_id: problem_action,
33 ..
34 } if problem_action == action_id => Some("This agent no longer exists".to_owned()),
35 _ => None,
36 })
37 }
38
39 #[cfg(test)]
40 mod tests {
41 use agents::{AgentSettings, SettingsProblem};
42
43 use super::{agent_problem, command_problem, placeholder_problem};
44
45 fn broken() -> Vec<SettingsProblem> {
46 let mut settings = AgentSettings::default();
47 settings.agents[0].command = " {bogus}".to_owned();
48 settings.agents[1].command.clear();
49 settings.agents[0].open_session_command = "wt.exe {session_id}".to_owned();
50 settings.actions[0].agent_id = "ghost".to_owned();
51 settings.actions[1].extra_args = "--flag {nope}".to_owned();
52 settings.validate()
53 }
54
55 #[test]
56 fn unknown_placeholders_show_under_the_field_that_contains_them() {
57 let problems = broken();
58 assert_eq!(
59 command_problem(&problems, "claude", " {bogus}").as_deref(),
60 Some("Unknown placeholder {bogus}")
61 );
62 assert_eq!(
63 placeholder_problem(&problems, "claude", "wt.exe {session_id}"),
64 None
65 );
66 assert_eq!(
67 placeholder_problem(&problems, "build-this", "--flag {nope}").as_deref(),
68 Some("Unknown placeholder {nope}")
69 );
70 assert_eq!(placeholder_problem(&problems, "build-this", "--flag"), None);
71 }
72
73 #[test]
74 fn an_empty_command_and_a_missing_agent_are_reported() {
75 let problems = broken();
76 assert_eq!(
77 command_problem(&problems, "copilot", "").as_deref(),
78 Some("The command is empty")
79 );
80 assert_eq!(
81 agent_problem(&problems, "answer-this").as_deref(),
82 Some("This agent no longer exists")
83 );
84 assert_eq!(agent_problem(&problems, "build-this"), None);
85 }
86
87 #[test]
88 fn valid_settings_show_nothing() {
89 let problems = AgentSettings::default().validate();
90 assert_eq!(command_problem(&problems, "claude", "claude -p"), None);
91 assert_eq!(agent_problem(&problems, "answer-this"), None);
92 }
93 }
@@ -0,0 +1,93 @@
1use agents::SettingsProblem;
2
3pub fn placeholder_problem(
4 problems: &[SettingsProblem],
5 item_id: &str,
6 text: &str,
7) -> Option<String> {
8 problems.iter().find_map(|problem| match problem {
9 SettingsProblem::UnknownPlaceholder {
10 item_id: problem_item,
11 placeholder,
12 } if problem_item == item_id && text.contains(&format!("{{{placeholder}}}")) => {
13 Some(format!("Unknown placeholder {{{placeholder}}}"))
14 }
15 _ => None,
16 })
17}
18
19pub fn command_problem(problems: &[SettingsProblem], agent_id: &str, text: &str) -> Option<String> {
20 let empty = problems.iter().any(
21 |problem| matches!(problem, SettingsProblem::EmptyCommand { agent_id: id } if id == agent_id),
22 );
23 if empty {
24 return Some("The command is empty".to_owned());
25 }
26 placeholder_problem(problems, agent_id, text)
27}
28
29pub fn agent_problem(problems: &[SettingsProblem], action_id: &str) -> Option<String> {
30 problems.iter().find_map(|problem| match problem {
31 SettingsProblem::UnknownAgent {
32 action_id: problem_action,
33 ..
34 } if problem_action == action_id => Some("This agent no longer exists".to_owned()),
35 _ => None,
36 })
37}
38
39#[cfg(test)]
40mod tests {
41 use agents::{AgentSettings, SettingsProblem};
42
43 use super::{agent_problem, command_problem, placeholder_problem};
44
45 fn broken() -> Vec<SettingsProblem> {
46 let mut settings = AgentSettings::default();
47 settings.agents[0].command = " {bogus}".to_owned();
48 settings.agents[1].command.clear();
49 settings.agents[0].open_session_command = "wt.exe {session_id}".to_owned();
50 settings.actions[0].agent_id = "ghost".to_owned();
51 settings.actions[1].extra_args = "--flag {nope}".to_owned();
52 settings.validate()
53 }
54
55 #[test]
56 fn unknown_placeholders_show_under_the_field_that_contains_them() {
57 let problems = broken();
58 assert_eq!(
59 command_problem(&problems, "claude", " {bogus}").as_deref(),
60 Some("Unknown placeholder {bogus}")
61 );
62 assert_eq!(
63 placeholder_problem(&problems, "claude", "wt.exe {session_id}"),
64 None
65 );
66 assert_eq!(
67 placeholder_problem(&problems, "build-this", "--flag {nope}").as_deref(),
68 Some("Unknown placeholder {nope}")
69 );
70 assert_eq!(placeholder_problem(&problems, "build-this", "--flag"), None);
71 }
72
73 #[test]
74 fn an_empty_command_and_a_missing_agent_are_reported() {
75 let problems = broken();
76 assert_eq!(
77 command_problem(&problems, "copilot", "").as_deref(),
78 Some("The command is empty")
79 );
80 assert_eq!(
81 agent_problem(&problems, "answer-this").as_deref(),
82 Some("This agent no longer exists")
83 );
84 assert_eq!(agent_problem(&problems, "build-this"), None);
85 }
86
87 #[test]
88 fn valid_settings_show_nothing() {
89 let problems = AgentSettings::default().validate();
90 assert_eq!(command_problem(&problems, "claude", "claude -p"), None);
91 assert_eq!(agent_problem(&problems, "answer-this"), None);
92 }
93}
crates/app/src/agents/settings_section.rs added +715 −0
@@ -0,0 +1,715 @@
1 use agents::{AgentAction, AgentProfile, Environment, OutputFormat};
2 use gpui_kit::assets::IconName;
3 use gpui_kit::component::{
4 button::{Button, ButtonVariants as _},
5 h_flex,
6 input::{InputEvent, InputState, TextareaState},
7 v_flex,
8 };
9 use gpui_kit::prelude::FluentBuilder as _;
10 use gpui_kit::*;
11
12 use super::environment_label;
13 use super::runs::AgentRuns;
14 use super::settings_controls::{Choice, MenuEntry, PAGE_PADDING, link_dropdown, section_header};
15 use crate::runtime;
16 use crate::theme;
17 use crate::views::widgets::icon;
18
19 const NOTE: &str = "Agents get the message, its sender and up to 20 earlier messages. Nothing is sent to Teams without you.";
20 const DEFAULT_DISTRO: &str = "Ubuntu";
21 const PROMPT_MIN_ROWS: usize = 4;
22 const PROMPT_MAX_ROWS: usize = 8;
23
24 #[derive(Clone, Copy, PartialEq, Eq)]
25 pub(super) enum Page {
26 List,
27 Agent,
28 Action,
29 }
30
31 #[derive(Clone, PartialEq, Eq)]
32 pub(super) enum Probe {
33 Idle,
34 Running,
35 Found(String),
36 Missing(String),
37 }
38
39 pub(super) struct AgentForm {
40 pub id: String,
41 pub name: Entity<InputState>,
42 pub distro: Entity<InputState>,
43 pub command: Entity<InputState>,
44 pub open_session: Entity<InputState>,
45 pub mcp_flag: Entity<InputState>,
46 }
47
48 pub(super) struct ActionForm {
49 pub id: String,
50 pub label: Entity<InputState>,
51 pub working_dir: Entity<InputState>,
52 pub prompt: Entity<TextareaState>,
53 pub extra_args: Entity<InputState>,
54 }
55
56 pub struct AgentsSettings {
57 pub(super) runs: Entity<AgentRuns>,
58 pub(super) page: Page,
59 pub(super) agent_form: Option<AgentForm>,
60 pub(super) action_form: Option<ActionForm>,
61 pub(super) probe: Probe,
62 form_subscriptions: Vec<Subscription>,
63 _runs_subscription: Subscription,
64 }
65
66 pub fn unique_id(base: &str, taken: impl Fn(&str) -> bool) -> String {
67 if !taken(base) {
68 return base.to_owned();
69 }
70 (2..)
71 .map(|suffix| format!("{base}-{suffix}"))
72 .find(|candidate| !taken(candidate))
73 .unwrap_or_else(|| base.to_owned())
74 }
75
76 pub fn move_item<T>(items: &mut [T], index: usize, up: bool) -> bool {
77 let target = if up {
78 index.checked_sub(1)
79 } else {
80 Some(index + 1).filter(|target| *target < items.len())
81 };
82 match target {
83 Some(target) if index < items.len() => {
84 items.swap(index, target);
85 true
86 }
87 _ => false,
88 }
89 }
90
91 impl AgentsSettings {
92 pub fn new(runs: Entity<AgentRuns>, cx: &mut Context<Self>) -> Self {
93 let subscription = cx.observe(&runs, |_, _, cx| cx.notify());
94 AgentsSettings {
95 runs,
96 page: Page::List,
97 agent_form: None,
98 action_form: None,
99 probe: Probe::Idle,
100 form_subscriptions: Vec::new(),
101 _runs_subscription: subscription,
102 }
103 }
104
105 pub(super) fn go_back(&mut self, cx: &mut Context<Self>) {
106 self.page = Page::List;
107 self.agent_form = None;
108 self.action_form = None;
109 self.form_subscriptions.clear();
110 self.probe = Probe::Idle;
111 cx.notify();
112 }
113
114 fn line_input(
115 &mut self,
116 value: &str,
117 window: &mut Window,
118 cx: &mut Context<Self>,
119 on_change: fn(&mut Self, &mut Context<Self>),
120 ) -> Entity<InputState> {
121 let value = value.to_owned();
122 let input = cx.new(|cx| InputState::new(window, cx).default_value(value));
123 self.form_subscriptions.push(cx.subscribe(
124 &input,
125 move |this, _, event: &InputEvent, cx| {
126 if matches!(event, InputEvent::Change) {
127 on_change(this, cx);
128 }
129 },
130 ));
131 input
132 }
133
134 fn open_agent(&mut self, agent_id: &str, window: &mut Window, cx: &mut Context<Self>) {
135 let Some(profile) = self
136 .runs
137 .read(cx)
138 .settings()
139 .agents
140 .iter()
141 .find(|profile| profile.id == agent_id)
142 .cloned()
143 else {
144 return;
145 };
146 self.go_back(cx);
147 let distro = match &profile.environment {
148 Environment::Wsl {
149 distro: Some(distro),
150 } => distro.clone(),
151 _ => String::new(),
152 };
153 self.agent_form = Some(AgentForm {
154 id: profile.id.clone(),
155 name: self.line_input(&profile.name, window, cx, Self::commit_agent),
156 distro: self.line_input(&distro, window, cx, Self::commit_agent),
157 command: self.line_input(&profile.command, window, cx, Self::commit_agent),
158 open_session: self.line_input(
159 &profile.open_session_command,
160 window,
161 cx,
162 Self::commit_agent,
163 ),
164 mcp_flag: self.line_input(&profile.mcp_config_flag, window, cx, Self::commit_agent),
165 });
166 self.page = Page::Agent;
167 cx.notify();
168 }
169
170 fn open_action(&mut self, action_id: &str, window: &mut Window, cx: &mut Context<Self>) {
171 let Some(action) = self
172 .runs
173 .read(cx)
174 .settings()
175 .actions
176 .iter()
177 .find(|action| action.id == action_id)
178 .cloned()
179 else {
180 return;
181 };
182 self.go_back(cx);
183 let prompt = cx.new(|cx| {
184 TextareaState::new(window, cx)
185 .auto_grow(PROMPT_MIN_ROWS, PROMPT_MAX_ROWS)
186 .default_value(action.prompt_template.clone())
187 });
188 self.form_subscriptions
189 .push(cx.subscribe(&prompt, |this, _, event: &InputEvent, cx| {
190 if matches!(event, InputEvent::Change) {
191 this.commit_action(cx);
192 }
193 }));
194 self.action_form = Some(ActionForm {
195 id: action.id.clone(),
196 label: self.line_input(&action.label, window, cx, Self::commit_action),
197 working_dir: self.line_input(&action.working_dir, window, cx, Self::commit_action),
198 prompt,
199 extra_args: self.line_input(&action.extra_args, window, cx, Self::commit_action),
200 });
201 self.page = Page::Action;
202 cx.notify();
203 }
204
205 pub(super) fn commit_agent(&mut self, cx: &mut Context<Self>) {
206 let Some(form) = &self.agent_form else {
207 return;
208 };
209 let id = form.id.clone();
210 let name = form.name.read(cx).value().to_string();
211 let distro = form.distro.read(cx).value().trim().to_owned();
212 let command = form.command.read(cx).value().to_string();
213 let open_session = form.open_session.read(cx).value().to_string();
214 let mcp_flag = form.mcp_flag.read(cx).value().trim().to_owned();
215 self.runs.update(cx, |runs, cx| {
216 runs.update_settings(
217 |settings| {
218 let Some(agent) = settings.agents.iter_mut().find(|agent| agent.id == id)
219 else {
220 return;
221 };
222 agent.name = name;
223 agent.command = command;
224 agent.open_session_command = open_session;
225 agent.mcp_config_flag = mcp_flag;
226 if let Environment::Wsl {
227 distro: Some(current),
228 } = &mut agent.environment
229 {
230 *current = distro;
231 }
232 },
233 cx,
234 )
235 });
236 self.probe = Probe::Idle;
237 }
238
239 pub(super) fn commit_action(&mut self, cx: &mut Context<Self>) {
240 let Some(form) = &self.action_form else {
241 return;
242 };
243 let id = form.id.clone();
244 let label = form.label.read(cx).value().to_string();
245 let working_dir = form.working_dir.read(cx).value().trim().to_owned();
246 let prompt = form.prompt.read(cx).value().to_string();
247 let extra_args = form.extra_args.read(cx).value().to_string();
248 self.runs.update(cx, |runs, cx| {
249 runs.update_settings(
250 |settings| {
251 let Some(action) = settings.actions.iter_mut().find(|action| action.id == id)
252 else {
253 return;
254 };
255 action.label = label;
256 action.working_dir = working_dir;
257 action.prompt_template = prompt;
258 action.extra_args = extra_args;
259 },
260 cx,
261 )
262 });
263 }
264
265 pub(super) fn set_environment(
266 &mut self,
267 environment: Environment,
268 window: &mut Window,
269 cx: &mut Context<Self>,
270 ) {
271 let Some(form) = &self.agent_form else {
272 return;
273 };
274 let id = form.id.clone();
275 if matches!(environment, Environment::Wsl { distro: Some(_) })
276 && form.distro.read(cx).value().trim().is_empty()
277 {
278 form.distro
279 .update(cx, |input, cx| input.set_value(DEFAULT_DISTRO, window, cx));
280 }
281 let distro = form.distro.read(cx).value().trim().to_owned();
282 let environment = match environment {
283 Environment::Wsl { distro: Some(_) } => Environment::Wsl {
284 distro: Some(distro),
285 },
286 other => other,
287 };
288 self.runs.update(cx, |runs, cx| {
289 runs.update_settings(
290 |settings| {
291 if let Some(agent) = settings.agents.iter_mut().find(|agent| agent.id == id) {
292 agent.environment = environment;
293 }
294 },
295 cx,
296 )
297 });
298 self.probe = Probe::Idle;
299 }
300
301 pub(super) fn set_output(&mut self, output: OutputFormat, cx: &mut Context<Self>) {
302 let Some(id) = self.agent_form.as_ref().map(|form| form.id.clone()) else {
303 return;
304 };
305 self.runs.update(cx, |runs, cx| {
306 runs.update_settings(
307 |settings| {
308 if let Some(agent) = settings.agents.iter_mut().find(|agent| agent.id == id) {
309 agent.output = output;
310 }
311 },
312 cx,
313 )
314 });
315 }
316
317 pub(super) fn set_action_agent(&mut self, agent_id: String, cx: &mut Context<Self>) {
318 self.update_action(cx, move |action| action.agent_id = agent_id);
319 }
320
321 pub(super) fn set_ask_extra(&mut self, ask: bool, cx: &mut Context<Self>) {
322 self.update_action(cx, move |action| action.ask_extra_instructions = ask);
323 }
324
325 fn update_action(&mut self, cx: &mut Context<Self>, change: impl FnOnce(&mut AgentAction)) {
326 let Some(id) = self.action_form.as_ref().map(|form| form.id.clone()) else {
327 return;
328 };
329 self.runs.update(cx, |runs, cx| {
330 runs.update_settings(
331 |settings| {
332 if let Some(action) = settings.actions.iter_mut().find(|action| action.id == id)
333 {
334 change(action);
335 }
336 },
337 cx,
338 )
339 });
340 }
341
342 pub(super) fn insert_placeholder(
343 &mut self,
344 placeholder: &str,
345 window: &mut Window,
346 cx: &mut Context<Self>,
347 ) {
348 let Some(prompt) = self.action_form.as_ref().map(|form| form.prompt.clone()) else {
349 return;
350 };
351 let text = format!("{{{placeholder}}}");
352 prompt.update(cx, |prompt, cx| {
353 prompt.insert(text, window, cx);
354 prompt.focus(window, cx);
355 });
356 self.commit_action(cx);
357 }
358
359 pub(super) fn delete_agent(&mut self, cx: &mut Context<Self>) {
360 let Some(id) = self.agent_form.as_ref().map(|form| form.id.clone()) else {
361 return;
362 };
363 self.go_back(cx);
364 self.runs.update(cx, |runs, cx| {
365 runs.update_settings(
366 |settings| settings.agents.retain(|agent| agent.id != id),
367 cx,
368 )
369 });
370 }
371
372 pub(super) fn delete_action(&mut self, cx: &mut Context<Self>) {
373 let Some(id) = self.action_form.as_ref().map(|form| form.id.clone()) else {
374 return;
375 };
376 self.go_back(cx);
377 self.runs.update(cx, |runs, cx| {
378 runs.update_settings(
379 |settings| settings.actions.retain(|action| action.id != id),
380 cx,
381 )
382 });
383 }
384
385 pub(super) fn test_agent(&mut self, cx: &mut Context<Self>) {
386 let Some(profile) = self.current_agent(cx) else {
387 return;
388 };
389 if profile.command.trim().is_empty() {
390 self.probe = Probe::Missing("The command is empty".to_owned());
391 cx.notify();
392 return;
393 }
394 self.probe = Probe::Running;
395 cx.notify();
396 let invocation = agents::version_check_invocation(&profile);
397 let receiver = runtime::spawn(async move { agents::probe(&invocation).await });
398 cx.spawn(async move |this, cx| {
399 let result = receiver
400 .await
401 .unwrap_or_else(|_| Err("cancelled".to_owned()));
402 this.update(cx, |this, cx| {
403 this.probe = match result {
404 Ok(line) => Probe::Found(line),
405 Err(error) => Probe::Missing(error),
406 };
407 cx.notify();
408 })
409 .ok();
410 })
411 .detach();
412 }
413
414 pub(super) fn current_agent(&self, cx: &App) -> Option<AgentProfile> {
415 let id = &self.agent_form.as_ref()?.id;
416 self.runs
417 .read(cx)
418 .settings()
419 .agents
420 .iter()
421 .find(|agent| &agent.id == id)
422 .cloned()
423 }
424
425 fn add_agent(&mut self, preset: AgentProfile, window: &mut Window, cx: &mut Context<Self>) {
426 let mut profile = preset;
427 let existing: Vec<String> = self
428 .runs
429 .read(cx)
430 .settings()
431 .agents
432 .iter()
433 .map(|agent| agent.id.clone())
434 .collect();
435 profile.id = unique_id(&profile.id, |candidate| {
436 existing.iter().any(|id| id == candidate)
437 });
438 let id = profile.id.clone();
439 self.runs.update(cx, |runs, cx| {
440 runs.update_settings(|settings| settings.agents.push(profile), cx)
441 });
442 self.open_agent(&id, window, cx);
443 }
444
445 fn add_action(&mut self, window: &mut Window, cx: &mut Context<Self>) {
446 let settings = self.runs.read(cx).settings();
447 let agent_id = settings
448 .agents
449 .first()
450 .map(|agent| agent.id.clone())
451 .unwrap_or_default();
452 let mut action = AgentAction::answer_this(&agent_id);
453 action.label = "New action".to_owned();
454 action.id = unique_id("action", |candidate| {
455 settings.actions.iter().any(|action| action.id == candidate)
456 });
457 let id = action.id.clone();
458 self.runs.update(cx, |runs, cx| {
459 runs.update_settings(|settings| settings.actions.push(action), cx)
460 });
461 self.open_action(&id, window, cx);
462 }
463
464 fn move_action(&mut self, index: usize, up: bool, cx: &mut Context<Self>) {
465 self.runs.update(cx, |runs, cx| {
466 runs.update_settings(
467 |settings| {
468 move_item(&mut settings.actions, index, up);
469 },
470 cx,
471 )
472 });
473 }
474 }
475
476 type Preset = (&'static str, fn() -> AgentProfile);
477
478 fn agent_presets() -> [Preset; 4] {
479 fn custom() -> AgentProfile {
480 AgentProfile {
481 id: "custom".to_owned(),
482 name: "Custom agent".to_owned(),
483 environment: Environment::Host,
484 command: String::new(),
485 output: OutputFormat::Text,
486 open_session_command: String::new(),
487 mcp_config_flag: String::new(),
488 }
489 }
490 [
491 ("Claude Code (WSL)", AgentProfile::claude_wsl),
492 ("Claude Code (Windows)", AgentProfile::claude_host),
493 ("Copilot CLI (WSL)", AgentProfile::copilot_wsl),
494 ("Custom", custom),
495 ]
496 }
497
498 fn list_row(
499 id: (&'static str, usize),
500 leading: Option<AnyElement>,
501 title: String,
502 detail: String,
503 mono: Option<String>,
504 ) -> Stateful<Div> {
505 h_flex()
506 .id(id)
507 .w_full()
508 .px(px(12.))
509 .py(px(8.))
510 .gap(px(12.))
511 .items_center()
512 .rounded(px(8.))
513 .cursor_pointer()
514 .hover(|row| row.bg(theme::row_hover()))
515 .children(leading)
516 .child(
517 v_flex()
518 .flex_1()
519 .min_w(px(0.))
520 .gap(px(2.))
521 .child(
522 div()
523 .text_size(px(14.))
524 .font_weight(FontWeight::SEMIBOLD)
525 .child(title),
526 )
527 .child(
528 div()
529 .truncate()
530 .text_size(px(12.))
531 .text_color(theme::text_muted())
532 .child(detail),
533 )
534 .children(mono.map(|command| {
535 div()
536 .truncate()
537 .text_size(px(11.))
538 .text_color(theme::text_faint())
539 .child(command)
540 })),
541 )
542 }
543
544 fn small_button(id: (&'static str, usize), name: IconName, enabled: bool) -> Stateful<Div> {
545 div()
546 .id(id)
547 .size(px(28.))
548 .flex()
549 .flex_none()
550 .items_center()
551 .justify_center()
552 .rounded(px(7.))
553 .when(enabled, |button| {
554 button
555 .cursor_pointer()
556 .hover(|button| button.bg(theme::surface_raised()))
557 })
558 .when(!enabled, |button| button.opacity(0.4))
559 .child(icon(name, 14., theme::text_muted()))
560 }
561
562 impl AgentsSettings {
563 fn list_page(&mut self, cx: &mut Context<Self>) -> Div {
564 let settings = self.runs.read(cx).settings().clone();
565 let this = cx.entity();
566 let preset_entries: Vec<MenuEntry> = agent_presets()
567 .into_iter()
568 .map(|(label, build)| {
569 let this = this.clone();
570 let choose: Choice = std::rc::Rc::new(move |window, cx| {
571 this.update(cx, |this, cx| this.add_agent(build(), window, cx))
572 });
573 MenuEntry {
574 label: label.to_owned(),
575 selected: false,
576 choose,
577 }
578 })
579 .collect();
580 let add_action = {
581 let this = this.clone();
582 Button::new("add-action")
583 .link()
584 .label("+ Add action")
585 .on_click(move |_, window, cx| {
586 this.update(cx, |this, cx| this.add_action(window, cx))
587 })
588 };
589 let action_count = settings.actions.len();
590 let agent_rows = settings.agents.iter().enumerate().map(|(index, agent)| {
591 let (open, id) = (cx.entity(), agent.id.clone());
592 list_row(
593 ("agent-row", index),
594 Some(
595 div()
596 .size(px(28.))
597 .flex()
598 .flex_none()
599 .items_center()
600 .justify_center()
601 .rounded(px(7.))
602 .bg(theme::surface_raised())
603 .child(icon(IconName::Bot, 14., theme::accent_text()))
604 .into_any_element(),
605 ),
606 agent.name.clone(),
607 environment_label(&agent.environment),
608 Some(agent.command.clone()),
609 )
610 .on_click(move |_, window, cx| {
611 open.update(cx, |this, cx| this.open_agent(&id, window, cx))
612 })
613 });
614 let action_rows = settings.actions.iter().enumerate().map(|(index, action)| {
615 let (open, id) = (cx.entity(), action.id.clone());
616 let (up, down) = (cx.entity(), cx.entity());
617 let agent_name = settings
618 .agents
619 .iter()
620 .find(|agent| agent.id == action.agent_id)
621 .map_or("Unknown agent", |agent| agent.name.as_str());
622 list_row(
623 ("action-row", index),
624 None,
625 action.label.clone(),
626 format!("{agent_name} - {}", action.working_dir),
627 None,
628 )
629 .on_click(move |_, window, cx| {
630 open.update(cx, |this, cx| this.open_action(&id, window, cx))
631 })
632 .child(
633 h_flex()
634 .flex_none()
635 .child(
636 small_button(("action-up", index), IconName::ArrowUp, index > 0).on_click(
637 move |_, _, cx| {
638 cx.stop_propagation();
639 up.update(cx, |this, cx| this.move_action(index, true, cx))
640 },
641 ),
642 )
643 .child(
644 small_button(
645 ("action-down", index),
646 IconName::ArrowDown,
647 index + 1 < action_count,
648 )
649 .on_click(move |_, _, cx| {
650 cx.stop_propagation();
651 down.update(cx, |this, cx| this.move_action(index, false, cx))
652 }),
653 ),
654 )
655 });
656 v_flex()
657 .w_full()
658 .child(section_header(
659 "AGENTS",
660 Some(link_dropdown("add-agent", "+ Add agent", preset_entries).into_any_element()),
661 ))
662 .child(v_flex().w_full().px(px(8.)).children(agent_rows))
663 .child(section_header(
664 "ACTIONS - IN THIS ORDER IN THE MENU",
665 Some(add_action.into_any_element()),
666 ))
667 .child(v_flex().w_full().px(px(8.)).children(action_rows))
668 .child(
669 div()
670 .w_full()
671 .px(px(PAGE_PADDING))
672 .pt(px(16.))
673 .pb(px(16.))
674 .text_size(px(12.))
675 .line_height(relative(1.5))
676 .text_color(theme::text_faint())
677 .child(NOTE),
678 )
679 }
680 }
681
682 impl Render for AgentsSettings {
683 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
684 match self.page {
685 Page::List => self.list_page(cx).into_any_element(),
686 Page::Agent => self.agent_page(window, cx).into_any_element(),
687 Page::Action => self.action_page(window, cx).into_any_element(),
688 }
689 }
690 }
691
692 #[cfg(test)]
693 mod tests {
694 use super::{move_item, unique_id};
695
696 #[test]
697 fn ids_get_a_numeric_suffix_when_taken() {
698 let taken = ["claude", "claude-2"];
699 let is_taken = |candidate: &str| taken.contains(&candidate);
700 assert_eq!(unique_id("copilot", is_taken), "copilot");
701 assert_eq!(unique_id("claude", is_taken), "claude-3");
702 }
703
704 #[test]
705 fn moving_swaps_neighbours_and_stops_at_the_ends() {
706 let mut items = vec!["a", "b", "c"];
707 assert!(move_item(&mut items, 1, true));
708 assert_eq!(items, ["b", "a", "c"]);
709 assert!(move_item(&mut items, 1, false));
710 assert_eq!(items, ["b", "c", "a"]);
711 assert!(!move_item(&mut items, 0, true));
712 assert!(!move_item(&mut items, 2, false));
713 assert_eq!(items, ["b", "c", "a"]);
714 }
715 }
@@ -0,0 +1,715 @@
1use agents::{AgentAction, AgentProfile, Environment, OutputFormat};
2use gpui_kit::assets::IconName;
3use gpui_kit::component::{
4 button::{Button, ButtonVariants as _},
5 h_flex,
6 input::{InputEvent, InputState, TextareaState},
7 v_flex,
8};
9use gpui_kit::prelude::FluentBuilder as _;
10use gpui_kit::*;
11
12use super::environment_label;
13use super::runs::AgentRuns;
14use super::settings_controls::{Choice, MenuEntry, PAGE_PADDING, link_dropdown, section_header};
15use crate::runtime;
16use crate::theme;
17use crate::views::widgets::icon;
18
19const NOTE: &str = "Agents get the message, its sender and up to 20 earlier messages. Nothing is sent to Teams without you.";
20const DEFAULT_DISTRO: &str = "Ubuntu";
21const PROMPT_MIN_ROWS: usize = 4;
22const PROMPT_MAX_ROWS: usize = 8;
23
24#[derive(Clone, Copy, PartialEq, Eq)]
25pub(super) enum Page {
26 List,
27 Agent,
28 Action,
29}
30
31#[derive(Clone, PartialEq, Eq)]
32pub(super) enum Probe {
33 Idle,
34 Running,
35 Found(String),
36 Missing(String),
37}
38
39pub(super) struct AgentForm {
40 pub id: String,
41 pub name: Entity<InputState>,
42 pub distro: Entity<InputState>,
43 pub command: Entity<InputState>,
44 pub open_session: Entity<InputState>,
45 pub mcp_flag: Entity<InputState>,
46}
47
48pub(super) struct ActionForm {
49 pub id: String,
50 pub label: Entity<InputState>,
51 pub working_dir: Entity<InputState>,
52 pub prompt: Entity<TextareaState>,
53 pub extra_args: Entity<InputState>,
54}
55
56pub struct AgentsSettings {
57 pub(super) runs: Entity<AgentRuns>,
58 pub(super) page: Page,
59 pub(super) agent_form: Option<AgentForm>,
60 pub(super) action_form: Option<ActionForm>,
61 pub(super) probe: Probe,
62 form_subscriptions: Vec<Subscription>,
63 _runs_subscription: Subscription,
64}
65
66pub fn unique_id(base: &str, taken: impl Fn(&str) -> bool) -> String {
67 if !taken(base) {
68 return base.to_owned();
69 }
70 (2..)
71 .map(|suffix| format!("{base}-{suffix}"))
72 .find(|candidate| !taken(candidate))
73 .unwrap_or_else(|| base.to_owned())
74}
75
76pub fn move_item<T>(items: &mut [T], index: usize, up: bool) -> bool {
77 let target = if up {
78 index.checked_sub(1)
79 } else {
80 Some(index + 1).filter(|target| *target < items.len())
81 };
82 match target {
83 Some(target) if index < items.len() => {
84 items.swap(index, target);
85 true
86 }
87 _ => false,
88 }
89}
90
91impl AgentsSettings {
92 pub fn new(runs: Entity<AgentRuns>, cx: &mut Context<Self>) -> Self {
93 let subscription = cx.observe(&runs, |_, _, cx| cx.notify());
94 AgentsSettings {
95 runs,
96 page: Page::List,
97 agent_form: None,
98 action_form: None,
99 probe: Probe::Idle,
100 form_subscriptions: Vec::new(),
101 _runs_subscription: subscription,
102 }
103 }
104
105 pub(super) fn go_back(&mut self, cx: &mut Context<Self>) {
106 self.page = Page::List;
107 self.agent_form = None;
108 self.action_form = None;
109 self.form_subscriptions.clear();
110 self.probe = Probe::Idle;
111 cx.notify();
112 }
113
114 fn line_input(
115 &mut self,
116 value: &str,
117 window: &mut Window,
118 cx: &mut Context<Self>,
119 on_change: fn(&mut Self, &mut Context<Self>),
120 ) -> Entity<InputState> {
121 let value = value.to_owned();
122 let input = cx.new(|cx| InputState::new(window, cx).default_value(value));
123 self.form_subscriptions.push(cx.subscribe(
124 &input,
125 move |this, _, event: &InputEvent, cx| {
126 if matches!(event, InputEvent::Change) {
127 on_change(this, cx);
128 }
129 },
130 ));
131 input
132 }
133
134 fn open_agent(&mut self, agent_id: &str, window: &mut Window, cx: &mut Context<Self>) {
135 let Some(profile) = self
136 .runs
137 .read(cx)
138 .settings()
139 .agents
140 .iter()
141 .find(|profile| profile.id == agent_id)
142 .cloned()
143 else {
144 return;
145 };
146 self.go_back(cx);
147 let distro = match &profile.environment {
148 Environment::Wsl {
149 distro: Some(distro),
150 } => distro.clone(),
151 _ => String::new(),
152 };
153 self.agent_form = Some(AgentForm {
154 id: profile.id.clone(),
155 name: self.line_input(&profile.name, window, cx, Self::commit_agent),
156 distro: self.line_input(&distro, window, cx, Self::commit_agent),
157 command: self.line_input(&profile.command, window, cx, Self::commit_agent),
158 open_session: self.line_input(
159 &profile.open_session_command,
160 window,
161 cx,
162 Self::commit_agent,
163 ),
164 mcp_flag: self.line_input(&profile.mcp_config_flag, window, cx, Self::commit_agent),
165 });
166 self.page = Page::Agent;
167 cx.notify();
168 }
169
170 fn open_action(&mut self, action_id: &str, window: &mut Window, cx: &mut Context<Self>) {
171 let Some(action) = self
172 .runs
173 .read(cx)
174 .settings()
175 .actions
176 .iter()
177 .find(|action| action.id == action_id)
178 .cloned()
179 else {
180 return;
181 };
182 self.go_back(cx);
183 let prompt = cx.new(|cx| {
184 TextareaState::new(window, cx)
185 .auto_grow(PROMPT_MIN_ROWS, PROMPT_MAX_ROWS)
186 .default_value(action.prompt_template.clone())
187 });
188 self.form_subscriptions
189 .push(cx.subscribe(&prompt, |this, _, event: &InputEvent, cx| {
190 if matches!(event, InputEvent::Change) {
191 this.commit_action(cx);
192 }
193 }));
194 self.action_form = Some(ActionForm {
195 id: action.id.clone(),
196 label: self.line_input(&action.label, window, cx, Self::commit_action),
197 working_dir: self.line_input(&action.working_dir, window, cx, Self::commit_action),
198 prompt,
199 extra_args: self.line_input(&action.extra_args, window, cx, Self::commit_action),
200 });
201 self.page = Page::Action;
202 cx.notify();
203 }
204
205 pub(super) fn commit_agent(&mut self, cx: &mut Context<Self>) {
206 let Some(form) = &self.agent_form else {
207 return;
208 };
209 let id = form.id.clone();
210 let name = form.name.read(cx).value().to_string();
211 let distro = form.distro.read(cx).value().trim().to_owned();
212 let command = form.command.read(cx).value().to_string();
213 let open_session = form.open_session.read(cx).value().to_string();
214 let mcp_flag = form.mcp_flag.read(cx).value().trim().to_owned();
215 self.runs.update(cx, |runs, cx| {
216 runs.update_settings(
217 |settings| {
218 let Some(agent) = settings.agents.iter_mut().find(|agent| agent.id == id)
219 else {
220 return;
221 };
222 agent.name = name;
223 agent.command = command;
224 agent.open_session_command = open_session;
225 agent.mcp_config_flag = mcp_flag;
226 if let Environment::Wsl {
227 distro: Some(current),
228 } = &mut agent.environment
229 {
230 *current = distro;
231 }
232 },
233 cx,
234 )
235 });
236 self.probe = Probe::Idle;
237 }
238
239 pub(super) fn commit_action(&mut self, cx: &mut Context<Self>) {
240 let Some(form) = &self.action_form else {
241 return;
242 };
243 let id = form.id.clone();
244 let label = form.label.read(cx).value().to_string();
245 let working_dir = form.working_dir.read(cx).value().trim().to_owned();
246 let prompt = form.prompt.read(cx).value().to_string();
247 let extra_args = form.extra_args.read(cx).value().to_string();
248 self.runs.update(cx, |runs, cx| {
249 runs.update_settings(
250 |settings| {
251 let Some(action) = settings.actions.iter_mut().find(|action| action.id == id)
252 else {
253 return;
254 };
255 action.label = label;
256 action.working_dir = working_dir;
257 action.prompt_template = prompt;
258 action.extra_args = extra_args;
259 },
260 cx,
261 )
262 });
263 }
264
265 pub(super) fn set_environment(
266 &mut self,
267 environment: Environment,
268 window: &mut Window,
269 cx: &mut Context<Self>,
270 ) {
271 let Some(form) = &self.agent_form else {
272 return;
273 };
274 let id = form.id.clone();
275 if matches!(environment, Environment::Wsl { distro: Some(_) })
276 && form.distro.read(cx).value().trim().is_empty()
277 {
278 form.distro
279 .update(cx, |input, cx| input.set_value(DEFAULT_DISTRO, window, cx));
280 }
281 let distro = form.distro.read(cx).value().trim().to_owned();
282 let environment = match environment {
283 Environment::Wsl { distro: Some(_) } => Environment::Wsl {
284 distro: Some(distro),
285 },
286 other => other,
287 };
288 self.runs.update(cx, |runs, cx| {
289 runs.update_settings(
290 |settings| {
291 if let Some(agent) = settings.agents.iter_mut().find(|agent| agent.id == id) {
292 agent.environment = environment;
293 }
294 },
295 cx,
296 )
297 });
298 self.probe = Probe::Idle;
299 }
300
301 pub(super) fn set_output(&mut self, output: OutputFormat, cx: &mut Context<Self>) {
302 let Some(id) = self.agent_form.as_ref().map(|form| form.id.clone()) else {
303 return;
304 };
305 self.runs.update(cx, |runs, cx| {
306 runs.update_settings(
307 |settings| {
308 if let Some(agent) = settings.agents.iter_mut().find(|agent| agent.id == id) {
309 agent.output = output;
310 }
311 },
312 cx,
313 )
314 });
315 }
316
317 pub(super) fn set_action_agent(&mut self, agent_id: String, cx: &mut Context<Self>) {
318 self.update_action(cx, move |action| action.agent_id = agent_id);
319 }
320
321 pub(super) fn set_ask_extra(&mut self, ask: bool, cx: &mut Context<Self>) {
322 self.update_action(cx, move |action| action.ask_extra_instructions = ask);
323 }
324
325 fn update_action(&mut self, cx: &mut Context<Self>, change: impl FnOnce(&mut AgentAction)) {
326 let Some(id) = self.action_form.as_ref().map(|form| form.id.clone()) else {
327 return;
328 };
329 self.runs.update(cx, |runs, cx| {
330 runs.update_settings(
331 |settings| {
332 if let Some(action) = settings.actions.iter_mut().find(|action| action.id == id)
333 {
334 change(action);
335 }
336 },
337 cx,
338 )
339 });
340 }
341
342 pub(super) fn insert_placeholder(
343 &mut self,
344 placeholder: &str,
345 window: &mut Window,
346 cx: &mut Context<Self>,
347 ) {
348 let Some(prompt) = self.action_form.as_ref().map(|form| form.prompt.clone()) else {
349 return;
350 };
351 let text = format!("{{{placeholder}}}");
352 prompt.update(cx, |prompt, cx| {
353 prompt.insert(text, window, cx);
354 prompt.focus(window, cx);
355 });
356 self.commit_action(cx);
357 }
358
359 pub(super) fn delete_agent(&mut self, cx: &mut Context<Self>) {
360 let Some(id) = self.agent_form.as_ref().map(|form| form.id.clone()) else {
361 return;
362 };
363 self.go_back(cx);
364 self.runs.update(cx, |runs, cx| {
365 runs.update_settings(
366 |settings| settings.agents.retain(|agent| agent.id != id),
367 cx,
368 )
369 });
370 }
371
372 pub(super) fn delete_action(&mut self, cx: &mut Context<Self>) {
373 let Some(id) = self.action_form.as_ref().map(|form| form.id.clone()) else {
374 return;
375 };
376 self.go_back(cx);
377 self.runs.update(cx, |runs, cx| {
378 runs.update_settings(
379 |settings| settings.actions.retain(|action| action.id != id),
380 cx,
381 )
382 });
383 }
384
385 pub(super) fn test_agent(&mut self, cx: &mut Context<Self>) {
386 let Some(profile) = self.current_agent(cx) else {
387 return;
388 };
389 if profile.command.trim().is_empty() {
390 self.probe = Probe::Missing("The command is empty".to_owned());
391 cx.notify();
392 return;
393 }
394 self.probe = Probe::Running;
395 cx.notify();
396 let invocation = agents::version_check_invocation(&profile);
397 let receiver = runtime::spawn(async move { agents::probe(&invocation).await });
398 cx.spawn(async move |this, cx| {
399 let result = receiver
400 .await
401 .unwrap_or_else(|_| Err("cancelled".to_owned()));
402 this.update(cx, |this, cx| {
403 this.probe = match result {
404 Ok(line) => Probe::Found(line),
405 Err(error) => Probe::Missing(error),
406 };
407 cx.notify();
408 })
409 .ok();
410 })
411 .detach();
412 }
413
414 pub(super) fn current_agent(&self, cx: &App) -> Option<AgentProfile> {
415 let id = &self.agent_form.as_ref()?.id;
416 self.runs
417 .read(cx)
418 .settings()
419 .agents
420 .iter()
421 .find(|agent| &agent.id == id)
422 .cloned()
423 }
424
425 fn add_agent(&mut self, preset: AgentProfile, window: &mut Window, cx: &mut Context<Self>) {
426 let mut profile = preset;
427 let existing: Vec<String> = self
428 .runs
429 .read(cx)
430 .settings()
431 .agents
432 .iter()
433 .map(|agent| agent.id.clone())
434 .collect();
435 profile.id = unique_id(&profile.id, |candidate| {
436 existing.iter().any(|id| id == candidate)
437 });
438 let id = profile.id.clone();
439 self.runs.update(cx, |runs, cx| {
440 runs.update_settings(|settings| settings.agents.push(profile), cx)
441 });
442 self.open_agent(&id, window, cx);
443 }
444
445 fn add_action(&mut self, window: &mut Window, cx: &mut Context<Self>) {
446 let settings = self.runs.read(cx).settings();
447 let agent_id = settings
448 .agents
449 .first()
450 .map(|agent| agent.id.clone())
451 .unwrap_or_default();
452 let mut action = AgentAction::answer_this(&agent_id);
453 action.label = "New action".to_owned();
454 action.id = unique_id("action", |candidate| {
455 settings.actions.iter().any(|action| action.id == candidate)
456 });
457 let id = action.id.clone();
458 self.runs.update(cx, |runs, cx| {
459 runs.update_settings(|settings| settings.actions.push(action), cx)
460 });
461 self.open_action(&id, window, cx);
462 }
463
464 fn move_action(&mut self, index: usize, up: bool, cx: &mut Context<Self>) {
465 self.runs.update(cx, |runs, cx| {
466 runs.update_settings(
467 |settings| {
468 move_item(&mut settings.actions, index, up);
469 },
470 cx,
471 )
472 });
473 }
474}
475
476type Preset = (&'static str, fn() -> AgentProfile);
477
478fn agent_presets() -> [Preset; 4] {
479 fn custom() -> AgentProfile {
480 AgentProfile {
481 id: "custom".to_owned(),
482 name: "Custom agent".to_owned(),
483 environment: Environment::Host,
484 command: String::new(),
485 output: OutputFormat::Text,
486 open_session_command: String::new(),
487 mcp_config_flag: String::new(),
488 }
489 }
490 [
491 ("Claude Code (WSL)", AgentProfile::claude_wsl),
492 ("Claude Code (Windows)", AgentProfile::claude_host),
493 ("Copilot CLI (WSL)", AgentProfile::copilot_wsl),
494 ("Custom", custom),
495 ]
496}
497
498fn list_row(
499 id: (&'static str, usize),
500 leading: Option<AnyElement>,
501 title: String,
502 detail: String,
503 mono: Option<String>,
504) -> Stateful<Div> {
505 h_flex()
506 .id(id)
507 .w_full()
508 .px(px(12.))
509 .py(px(8.))
510 .gap(px(12.))
511 .items_center()
512 .rounded(px(8.))
513 .cursor_pointer()
514 .hover(|row| row.bg(theme::row_hover()))
515 .children(leading)
516 .child(
517 v_flex()
518 .flex_1()
519 .min_w(px(0.))
520 .gap(px(2.))
521 .child(
522 div()
523 .text_size(px(14.))
524 .font_weight(FontWeight::SEMIBOLD)
525 .child(title),
526 )
527 .child(
528 div()
529 .truncate()
530 .text_size(px(12.))
531 .text_color(theme::text_muted())
532 .child(detail),
533 )
534 .children(mono.map(|command| {
535 div()
536 .truncate()
537 .text_size(px(11.))
538 .text_color(theme::text_faint())
539 .child(command)
540 })),
541 )
542}
543
544fn small_button(id: (&'static str, usize), name: IconName, enabled: bool) -> Stateful<Div> {
545 div()
546 .id(id)
547 .size(px(28.))
548 .flex()
549 .flex_none()
550 .items_center()
551 .justify_center()
552 .rounded(px(7.))
553 .when(enabled, |button| {
554 button
555 .cursor_pointer()
556 .hover(|button| button.bg(theme::surface_raised()))
557 })
558 .when(!enabled, |button| button.opacity(0.4))
559 .child(icon(name, 14., theme::text_muted()))
560}
561
562impl AgentsSettings {
563 fn list_page(&mut self, cx: &mut Context<Self>) -> Div {
564 let settings = self.runs.read(cx).settings().clone();
565 let this = cx.entity();
566 let preset_entries: Vec<MenuEntry> = agent_presets()
567 .into_iter()
568 .map(|(label, build)| {
569 let this = this.clone();
570 let choose: Choice = std::rc::Rc::new(move |window, cx| {
571 this.update(cx, |this, cx| this.add_agent(build(), window, cx))
572 });
573 MenuEntry {
574 label: label.to_owned(),
575 selected: false,
576 choose,
577 }
578 })
579 .collect();
580 let add_action = {
581 let this = this.clone();
582 Button::new("add-action")
583 .link()
584 .label("+ Add action")
585 .on_click(move |_, window, cx| {
586 this.update(cx, |this, cx| this.add_action(window, cx))
587 })
588 };
589 let action_count = settings.actions.len();
590 let agent_rows = settings.agents.iter().enumerate().map(|(index, agent)| {
591 let (open, id) = (cx.entity(), agent.id.clone());
592 list_row(
593 ("agent-row", index),
594 Some(
595 div()
596 .size(px(28.))
597 .flex()
598 .flex_none()
599 .items_center()
600 .justify_center()
601 .rounded(px(7.))
602 .bg(theme::surface_raised())
603 .child(icon(IconName::Bot, 14., theme::accent_text()))
604 .into_any_element(),
605 ),
606 agent.name.clone(),
607 environment_label(&agent.environment),
608 Some(agent.command.clone()),
609 )
610 .on_click(move |_, window, cx| {
611 open.update(cx, |this, cx| this.open_agent(&id, window, cx))
612 })
613 });
614 let action_rows = settings.actions.iter().enumerate().map(|(index, action)| {
615 let (open, id) = (cx.entity(), action.id.clone());
616 let (up, down) = (cx.entity(), cx.entity());
617 let agent_name = settings
618 .agents
619 .iter()
620 .find(|agent| agent.id == action.agent_id)
621 .map_or("Unknown agent", |agent| agent.name.as_str());
622 list_row(
623 ("action-row", index),
624 None,
625 action.label.clone(),
626 format!("{agent_name} - {}", action.working_dir),
627 None,
628 )
629 .on_click(move |_, window, cx| {
630 open.update(cx, |this, cx| this.open_action(&id, window, cx))
631 })
632 .child(
633 h_flex()
634 .flex_none()
635 .child(
636 small_button(("action-up", index), IconName::ArrowUp, index > 0).on_click(
637 move |_, _, cx| {
638 cx.stop_propagation();
639 up.update(cx, |this, cx| this.move_action(index, true, cx))
640 },
641 ),
642 )
643 .child(
644 small_button(
645 ("action-down", index),
646 IconName::ArrowDown,
647 index + 1 < action_count,
648 )
649 .on_click(move |_, _, cx| {
650 cx.stop_propagation();
651 down.update(cx, |this, cx| this.move_action(index, false, cx))
652 }),
653 ),
654 )
655 });
656 v_flex()
657 .w_full()
658 .child(section_header(
659 "AGENTS",
660 Some(link_dropdown("add-agent", "+ Add agent", preset_entries).into_any_element()),
661 ))
662 .child(v_flex().w_full().px(px(8.)).children(agent_rows))
663 .child(section_header(
664 "ACTIONS - IN THIS ORDER IN THE MENU",
665 Some(add_action.into_any_element()),
666 ))
667 .child(v_flex().w_full().px(px(8.)).children(action_rows))
668 .child(
669 div()
670 .w_full()
671 .px(px(PAGE_PADDING))
672 .pt(px(16.))
673 .pb(px(16.))
674 .text_size(px(12.))
675 .line_height(relative(1.5))
676 .text_color(theme::text_faint())
677 .child(NOTE),
678 )
679 }
680}
681
682impl Render for AgentsSettings {
683 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
684 match self.page {
685 Page::List => self.list_page(cx).into_any_element(),
686 Page::Agent => self.agent_page(window, cx).into_any_element(),
687 Page::Action => self.action_page(window, cx).into_any_element(),
688 }
689 }
690}
691
692#[cfg(test)]
693mod tests {
694 use super::{move_item, unique_id};
695
696 #[test]
697 fn ids_get_a_numeric_suffix_when_taken() {
698 let taken = ["claude", "claude-2"];
699 let is_taken = |candidate: &str| taken.contains(&candidate);
700 assert_eq!(unique_id("copilot", is_taken), "copilot");
701 assert_eq!(unique_id("claude", is_taken), "claude-3");
702 }
703
704 #[test]
705 fn moving_swaps_neighbours_and_stops_at_the_ends() {
706 let mut items = vec!["a", "b", "c"];
707 assert!(move_item(&mut items, 1, true));
708 assert_eq!(items, ["b", "a", "c"]);
709 assert!(move_item(&mut items, 1, false));
710 assert_eq!(items, ["b", "c", "a"]);
711 assert!(!move_item(&mut items, 0, true));
712 assert!(!move_item(&mut items, 2, false));
713 assert_eq!(items, ["b", "c", "a"]);
714 }
715}
crates/app/src/agents/spinner.rs added +29 −0
@@ -0,0 +1,29 @@
1 use std::time::Duration;
2
3 use gpui_kit::component::Icon;
4 use gpui_kit::*;
5
6 use crate::theme;
7
8 const SPIN_PERIOD: Duration = Duration::from_millis(900);
9
10 pub fn spinner(size: f32) -> Div {
11 let layer = |name: &str, color: Hsla| {
12 Icon::empty()
13 .path(format!("symbols/{name}.svg"))
14 .size(px(size))
15 .text_color(color)
16 };
17 div()
18 .relative()
19 .size(px(size))
20 .flex_none()
21 .child(layer("spinner_track", theme::popup_hover()))
22 .child(div().absolute().top_0().left_0().child(
23 layer("spinner_arc", theme::accent()).with_animation(
24 "agent-spinner",
25 Animation::new(SPIN_PERIOD).repeat(),
26 |arc, progress| arc.rotate(percentage(progress)),
27 ),
28 ))
29 }
@@ -0,0 +1,29 @@
1use std::time::Duration;
2
3use gpui_kit::component::Icon;
4use gpui_kit::*;
5
6use crate::theme;
7
8const SPIN_PERIOD: Duration = Duration::from_millis(900);
9
10pub fn spinner(size: f32) -> Div {
11 let layer = |name: &str, color: Hsla| {
12 Icon::empty()
13 .path(format!("symbols/{name}.svg"))
14 .size(px(size))
15 .text_color(color)
16 };
17 div()
18 .relative()
19 .size(px(size))
20 .flex_none()
21 .child(layer("spinner_track", theme::popup_hover()))
22 .child(div().absolute().top_0().left_0().child(
23 layer("spinner_arc", theme::accent()).with_animation(
24 "agent-spinner",
25 Animation::new(SPIN_PERIOD).repeat(),
26 |arc, progress| arc.rotate(percentage(progress)),
27 ),
28 ))
29}
crates/app/src/agents/start_dialog.rs added +376 −0
@@ -0,0 +1,376 @@
1 use agents::AgentAction;
2 use gpui_kit::assets::IconName;
3 use gpui_kit::component::{
4 ActiveTheme as _, h_flex,
5 input::{Textarea, TextareaState},
6 v_flex,
7 };
8 use gpui_kit::prelude::FluentBuilder as _;
9 use gpui_kit::*;
10
11 use super::{mcp_bridge, message_context, start_run, start_run_when_mcp_ready};
12 use crate::app_state::AppState;
13 use crate::theme;
14 use crate::views::widgets::{icon, symbol};
15
16 const CARD_WIDTH: f32 = 520.;
17 const CARD_RADIUS: f32 = 10.;
18 const CARD_PADDING: f32 = 16.;
19 const CARD_MARGIN: f32 = 32.;
20 const SECTION_GAP: f32 = 12.;
21 const BACKDROP_OPACITY: f32 = 0.55;
22 const CLOSE_SIZE: f32 = 28.;
23 const BUTTON_HEIGHT: f32 = 32.;
24 const QUOTE_LINES: usize = 3;
25 const FIELD_MIN_ROWS: usize = 3;
26 const FIELD_MAX_ROWS: usize = 6;
27 const PROMPT_SIZE: f32 = 12.;
28
29 #[derive(Clone, Debug, PartialEq, Eq)]
30 pub struct StartRequest {
31 pub action_id: String,
32 pub conversation_id: String,
33 pub message_id: String,
34 }
35
36 pub enum StartDialogEvent {
37 Close,
38 }
39
40 pub struct StartDialog {
41 app: Entity<AppState>,
42 request: StartRequest,
43 action: AgentAction,
44 subtitle: String,
45 sender: String,
46 quote: String,
47 needs_allow: bool,
48 input: Entity<TextareaState>,
49 show_prompt: bool,
50 }
51
52 impl EventEmitter<StartDialogEvent> for StartDialog {}
53
54 pub fn needs_dialog(action: &AgentAction, chat_allowed: bool) -> bool {
55 action.ask_extra_instructions || !chat_allowed
56 }
57
58 impl StartDialog {
59 pub fn new(
60 app: Entity<AppState>,
61 request: StartRequest,
62 action: AgentAction,
63 agent_name: &str,
64 window: &mut Window,
65 cx: &mut Context<Self>,
66 ) -> Self {
67 let context =
68 message_context::build(app.read(cx), &request.conversation_id, &request.message_id);
69 let (sender, quote) = context
70 .map(|context| (context.sender, context.message))
71 .unwrap_or_default();
72 let input = cx.new(|cx| {
73 TextareaState::new(window, cx)
74 .auto_grow(FIELD_MIN_ROWS, FIELD_MAX_ROWS)
75 .placeholder("e.g. only the backend, open a PR when done")
76 });
77 input.update(cx, |input, cx| input.focus(window, cx));
78 StartDialog {
79 app,
80 subtitle: format!("{agent_name} - {}", action.working_dir),
81 needs_allow: !mcp_bridge::chat_allowed(&request.conversation_id, cx),
82 request,
83 action,
84 sender,
85 quote,
86 input,
87 show_prompt: false,
88 }
89 }
90
91 fn start(&mut self, cx: &mut Context<Self>) {
92 let extra = self.input.read(cx).value().trim().to_owned();
93 if self.needs_allow {
94 mcp_bridge::allow_chat(&self.request.conversation_id, cx);
95 }
96 if self.needs_allow && mcp_bridge::endpoint(cx).is_none() {
97 start_run_when_mcp_ready(
98 self.request.action_id.clone(),
99 self.request.conversation_id.clone(),
100 self.request.message_id.clone(),
101 extra,
102 cx,
103 );
104 } else {
105 start_run(
106 &self.request.action_id,
107 &self.request.conversation_id,
108 &self.request.message_id,
109 &extra,
110 cx,
111 );
112 }
113 cx.emit(StartDialogEvent::Close);
114 }
115
116 fn on_key_down(&mut self, event: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {
117 match event.keystroke.key.as_str() {
118 "escape" => cx.emit(StartDialogEvent::Close),
119 "enter" if event.keystroke.modifiers.control => self.start(cx),
120 _ => return,
121 }
122 cx.stop_propagation();
123 }
124
125 fn header(&self, cx: &mut Context<Self>) -> Div {
126 h_flex()
127 .w_full()
128 .items_start()
129 .gap(px(SECTION_GAP))
130 .child(
131 v_flex()
132 .flex_1()
133 .min_w(px(0.))
134 .child(
135 div()
136 .text_size(px(15.))
137 .font_weight(FontWeight::BOLD)
138 .child(self.action.label.clone()),
139 )
140 .child(
141 div()
142 .truncate()
143 .text_size(px(12.))
144 .text_color(theme::text_muted())
145 .child(self.subtitle.clone()),
146 ),
147 )
148 .child(
149 div()
150 .id("agent-dialog-close")
151 .size(px(CLOSE_SIZE))
152 .flex_none()
153 .flex()
154 .items_center()
155 .justify_center()
156 .rounded_full()
157 .cursor_pointer()
158 .hover(|button| button.bg(theme::popup_hover()))
159 .on_click(cx.listener(|_, _, _, cx| cx.emit(StartDialogEvent::Close)))
160 .child(symbol("close", 16., theme::text_muted())),
161 )
162 }
163
164 fn quote(&self) -> impl IntoElement {
165 let text = format!("{} - {}", self.sender, self.quote);
166 let sender_style = HighlightStyle {
167 color: Some(theme::text()),
168 font_weight: Some(FontWeight::BOLD),
169 ..Default::default()
170 };
171 let sender_range = 0..self.sender.len();
172 div()
173 .w_full()
174 .px(px(12.))
175 .py(px(8.))
176 .rounded(px(8.))
177 .bg(theme::reply_surface())
178 .text_size(px(12.))
179 .line_height(relative(1.4))
180 .text_color(theme::text_soft())
181 .line_clamp(QUOTE_LINES)
182 .child(StyledText::new(text).with_highlights([(sender_range, sender_style)]))
183 }
184
185 fn field(&self, window: &Window, cx: &App) -> Div {
186 let focused = self.input.focus_handle(cx).contains_focused(window, cx);
187 v_flex()
188 .w_full()
189 .gap(px(6.))
190 .child(
191 div()
192 .text_size(px(11.))
193 .font_weight(FontWeight::SEMIBOLD)
194 .text_color(theme::text_faint())
195 .child("Extra instructions (optional)"),
196 )
197 .child(
198 div()
199 .w_full()
200 .px(px(12.))
201 .py(px(8.))
202 .rounded(px(8.))
203 .bg(theme::surface_raised())
204 .border_1()
205 .border_color(if focused {
206 theme::accent()
207 } else {
208 theme::surface_raised()
209 })
210 .child(Textarea::new(&self.input).appearance(false).bordered(false)),
211 )
212 }
213
214 fn prompt_toggle(&self, cx: &mut Context<Self>) -> Stateful<Div> {
215 h_flex()
216 .id("agent-dialog-prompt-toggle")
217 .gap(px(4.))
218 .items_center()
219 .cursor_pointer()
220 .text_size(px(12.))
221 .text_color(theme::text_muted())
222 .hover(|toggle| toggle.text_color(theme::text_soft()))
223 .child(icon(
224 if self.show_prompt {
225 IconName::ChevronDown
226 } else {
227 IconName::ChevronRight
228 },
229 12.,
230 theme::text_muted(),
231 ))
232 .child("Show prompt")
233 .on_click(cx.listener(|this, _, _, cx| {
234 this.show_prompt = !this.show_prompt;
235 cx.notify();
236 }))
237 }
238
239 fn prompt_box(&self, cx: &mut Context<Self>) -> Div {
240 let extra = self.input.read(cx).value().trim().to_owned();
241 let prompt = message_context::preview_prompt(
242 self.app.read(cx),
243 &self.action,
244 &self.request.conversation_id,
245 &self.request.message_id,
246 &extra,
247 )
248 .unwrap_or_default();
249 div()
250 .w_full()
251 .max_h(px(160.))
252 .px(px(12.))
253 .py(px(8.))
254 .rounded(px(8.))
255 .bg(theme::reply_surface())
256 .overflow_hidden()
257 .font_family(cx.theme().mono_font_family.clone())
258 .text_size(px(PROMPT_SIZE))
259 .line_height(relative(1.5))
260 .text_color(theme::text_muted())
261 .child(prompt)
262 }
263
264 fn buttons(&self, cx: &mut Context<Self>) -> Div {
265 let start_label = if self.needs_allow {
266 "Allow and start"
267 } else {
268 "Start"
269 };
270 h_flex()
271 .w_full()
272 .items_center()
273 .gap(px(8.))
274 .child(self.prompt_toggle(cx))
275 .child(div().flex_1())
276 .child(
277 h_flex()
278 .id("agent-dialog-cancel")
279 .h(px(BUTTON_HEIGHT))
280 .px(px(12.))
281 .items_center()
282 .rounded(px(8.))
283 .cursor_pointer()
284 .bg(theme::surface_raised())
285 .hover(|button| button.bg(theme::popup_hover()))
286 .text_size(px(13.))
287 .child("Cancel")
288 .on_click(cx.listener(|_, _, _, cx| cx.emit(StartDialogEvent::Close))),
289 )
290 .child(
291 h_flex()
292 .id("agent-dialog-start")
293 .h(px(BUTTON_HEIGHT))
294 .px(px(12.))
295 .items_center()
296 .rounded(px(8.))
297 .cursor_pointer()
298 .bg(theme::accent())
299 .hover(|button| button.bg(theme::accent_text()))
300 .text_color(theme::on_accent())
301 .text_size(px(13.))
302 .font_weight(FontWeight::SEMIBOLD)
303 .child(start_label)
304 .on_click(cx.listener(|this, _, _, cx| this.start(cx))),
305 )
306 }
307 }
308
309 impl Render for StartDialog {
310 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
311 div()
312 .id("agent-dialog-layer")
313 .absolute()
314 .top_0()
315 .left_0()
316 .size_full()
317 .flex()
318 .items_center()
319 .justify_center()
320 .child(
321 div()
322 .id("agent-dialog-backdrop")
323 .absolute()
324 .top_0()
325 .left_0()
326 .size_full()
327 .bg(black().opacity(BACKDROP_OPACITY))
328 .occlude()
329 .on_click(cx.listener(|_, _, _, cx| cx.emit(StartDialogEvent::Close))),
330 )
331 .child(
332 v_flex()
333 .id("agent-dialog-card")
334 .w(px(CARD_WIDTH))
335 .max_w(relative(1.))
336 .max_h(relative(1.))
337 .m(px(CARD_MARGIN))
338 .p(px(CARD_PADDING))
339 .gap(px(SECTION_GAP))
340 .rounded(px(CARD_RADIUS))
341 .bg(theme::popup())
342 .text_color(theme::text())
343 .occlude()
344 .capture_key_down(cx.listener(Self::on_key_down))
345 .child(self.header(cx))
346 .child(self.quote())
347 .when(self.needs_allow, |card| {
348 card.child(
349 div()
350 .text_size(px(12.))
351 .text_color(theme::text_soft())
352 .child("Agents can't see this chat yet."),
353 )
354 })
355 .child(self.field(window, cx))
356 .when(self.show_prompt, |card| card.child(self.prompt_box(cx)))
357 .child(self.buttons(cx)),
358 )
359 }
360 }
361
362 #[cfg(test)]
363 mod tests {
364 use agents::AgentAction;
365
366 use super::needs_dialog;
367
368 #[test]
369 fn the_dialog_shows_for_extra_instructions_or_a_chat_agents_cannot_see() {
370 let quiet = AgentAction::answer_this("claude");
371 let asking = AgentAction::build_this("claude");
372 assert!(!needs_dialog(&quiet, true));
373 assert!(needs_dialog(&quiet, false));
374 assert!(needs_dialog(&asking, true));
375 }
376 }
@@ -0,0 +1,376 @@
1use agents::AgentAction;
2use gpui_kit::assets::IconName;
3use gpui_kit::component::{
4 ActiveTheme as _, h_flex,
5 input::{Textarea, TextareaState},
6 v_flex,
7};
8use gpui_kit::prelude::FluentBuilder as _;
9use gpui_kit::*;
10
11use super::{mcp_bridge, message_context, start_run, start_run_when_mcp_ready};
12use crate::app_state::AppState;
13use crate::theme;
14use crate::views::widgets::{icon, symbol};
15
16const CARD_WIDTH: f32 = 520.;
17const CARD_RADIUS: f32 = 10.;
18const CARD_PADDING: f32 = 16.;
19const CARD_MARGIN: f32 = 32.;
20const SECTION_GAP: f32 = 12.;
21const BACKDROP_OPACITY: f32 = 0.55;
22const CLOSE_SIZE: f32 = 28.;
23const BUTTON_HEIGHT: f32 = 32.;
24const QUOTE_LINES: usize = 3;
25const FIELD_MIN_ROWS: usize = 3;
26const FIELD_MAX_ROWS: usize = 6;
27const PROMPT_SIZE: f32 = 12.;
28
29#[derive(Clone, Debug, PartialEq, Eq)]
30pub struct StartRequest {
31 pub action_id: String,
32 pub conversation_id: String,
33 pub message_id: String,
34}
35
36pub enum StartDialogEvent {
37 Close,
38}
39
40pub struct StartDialog {
41 app: Entity<AppState>,
42 request: StartRequest,
43 action: AgentAction,
44 subtitle: String,
45 sender: String,
46 quote: String,
47 needs_allow: bool,
48 input: Entity<TextareaState>,
49 show_prompt: bool,
50}
51
52impl EventEmitter<StartDialogEvent> for StartDialog {}
53
54pub fn needs_dialog(action: &AgentAction, chat_allowed: bool) -> bool {
55 action.ask_extra_instructions || !chat_allowed
56}
57
58impl StartDialog {
59 pub fn new(
60 app: Entity<AppState>,
61 request: StartRequest,
62 action: AgentAction,
63 agent_name: &str,
64 window: &mut Window,
65 cx: &mut Context<Self>,
66 ) -> Self {
67 let context =
68 message_context::build(app.read(cx), &request.conversation_id, &request.message_id);
69 let (sender, quote) = context
70 .map(|context| (context.sender, context.message))
71 .unwrap_or_default();
72 let input = cx.new(|cx| {
73 TextareaState::new(window, cx)
74 .auto_grow(FIELD_MIN_ROWS, FIELD_MAX_ROWS)
75 .placeholder("e.g. only the backend, open a PR when done")
76 });
77 input.update(cx, |input, cx| input.focus(window, cx));
78 StartDialog {
79 app,
80 subtitle: format!("{agent_name} - {}", action.working_dir),
81 needs_allow: !mcp_bridge::chat_allowed(&request.conversation_id, cx),
82 request,
83 action,
84 sender,
85 quote,
86 input,
87 show_prompt: false,
88 }
89 }
90
91 fn start(&mut self, cx: &mut Context<Self>) {
92 let extra = self.input.read(cx).value().trim().to_owned();
93 if self.needs_allow {
94 mcp_bridge::allow_chat(&self.request.conversation_id, cx);
95 }
96 if self.needs_allow && mcp_bridge::endpoint(cx).is_none() {
97 start_run_when_mcp_ready(
98 self.request.action_id.clone(),
99 self.request.conversation_id.clone(),
100 self.request.message_id.clone(),
101 extra,
102 cx,
103 );
104 } else {
105 start_run(
106 &self.request.action_id,
107 &self.request.conversation_id,
108 &self.request.message_id,
109 &extra,
110 cx,
111 );
112 }
113 cx.emit(StartDialogEvent::Close);
114 }
115
116 fn on_key_down(&mut self, event: &KeyDownEvent, _: &mut Window, cx: &mut Context<Self>) {
117 match event.keystroke.key.as_str() {
118 "escape" => cx.emit(StartDialogEvent::Close),
119 "enter" if event.keystroke.modifiers.control => self.start(cx),
120 _ => return,
121 }
122 cx.stop_propagation();
123 }
124
125 fn header(&self, cx: &mut Context<Self>) -> Div {
126 h_flex()
127 .w_full()
128 .items_start()
129 .gap(px(SECTION_GAP))
130 .child(
131 v_flex()
132 .flex_1()
133 .min_w(px(0.))
134 .child(
135 div()
136 .text_size(px(15.))
137 .font_weight(FontWeight::BOLD)
138 .child(self.action.label.clone()),
139 )
140 .child(
141 div()
142 .truncate()
143 .text_size(px(12.))
144 .text_color(theme::text_muted())
145 .child(self.subtitle.clone()),
146 ),
147 )
148 .child(
149 div()
150 .id("agent-dialog-close")
151 .size(px(CLOSE_SIZE))
152 .flex_none()
153 .flex()
154 .items_center()
155 .justify_center()
156 .rounded_full()
157 .cursor_pointer()
158 .hover(|button| button.bg(theme::popup_hover()))
159 .on_click(cx.listener(|_, _, _, cx| cx.emit(StartDialogEvent::Close)))
160 .child(symbol("close", 16., theme::text_muted())),
161 )
162 }
163
164 fn quote(&self) -> impl IntoElement {
165 let text = format!("{} - {}", self.sender, self.quote);
166 let sender_style = HighlightStyle {
167 color: Some(theme::text()),
168 font_weight: Some(FontWeight::BOLD),
169 ..Default::default()
170 };
171 let sender_range = 0..self.sender.len();
172 div()
173 .w_full()
174 .px(px(12.))
175 .py(px(8.))
176 .rounded(px(8.))
177 .bg(theme::reply_surface())
178 .text_size(px(12.))
179 .line_height(relative(1.4))
180 .text_color(theme::text_soft())
181 .line_clamp(QUOTE_LINES)
182 .child(StyledText::new(text).with_highlights([(sender_range, sender_style)]))
183 }
184
185 fn field(&self, window: &Window, cx: &App) -> Div {
186 let focused = self.input.focus_handle(cx).contains_focused(window, cx);
187 v_flex()
188 .w_full()
189 .gap(px(6.))
190 .child(
191 div()
192 .text_size(px(11.))
193 .font_weight(FontWeight::SEMIBOLD)
194 .text_color(theme::text_faint())
195 .child("Extra instructions (optional)"),
196 )
197 .child(
198 div()
199 .w_full()
200 .px(px(12.))
201 .py(px(8.))
202 .rounded(px(8.))
203 .bg(theme::surface_raised())
204 .border_1()
205 .border_color(if focused {
206 theme::accent()
207 } else {
208 theme::surface_raised()
209 })
210 .child(Textarea::new(&self.input).appearance(false).bordered(false)),
211 )
212 }
213
214 fn prompt_toggle(&self, cx: &mut Context<Self>) -> Stateful<Div> {
215 h_flex()
216 .id("agent-dialog-prompt-toggle")
217 .gap(px(4.))
218 .items_center()
219 .cursor_pointer()
220 .text_size(px(12.))
221 .text_color(theme::text_muted())
222 .hover(|toggle| toggle.text_color(theme::text_soft()))
223 .child(icon(
224 if self.show_prompt {
225 IconName::ChevronDown
226 } else {
227 IconName::ChevronRight
228 },
229 12.,
230 theme::text_muted(),
231 ))
232 .child("Show prompt")
233 .on_click(cx.listener(|this, _, _, cx| {
234 this.show_prompt = !this.show_prompt;
235 cx.notify();
236 }))
237 }
238
239 fn prompt_box(&self, cx: &mut Context<Self>) -> Div {
240 let extra = self.input.read(cx).value().trim().to_owned();
241 let prompt = message_context::preview_prompt(
242 self.app.read(cx),
243 &self.action,
244 &self.request.conversation_id,
245 &self.request.message_id,
246 &extra,
247 )
248 .unwrap_or_default();
249 div()
250 .w_full()
251 .max_h(px(160.))
252 .px(px(12.))
253 .py(px(8.))
254 .rounded(px(8.))
255 .bg(theme::reply_surface())
256 .overflow_hidden()
257 .font_family(cx.theme().mono_font_family.clone())
258 .text_size(px(PROMPT_SIZE))
259 .line_height(relative(1.5))
260 .text_color(theme::text_muted())
261 .child(prompt)
262 }
263
264 fn buttons(&self, cx: &mut Context<Self>) -> Div {
265 let start_label = if self.needs_allow {
266 "Allow and start"
267 } else {
268 "Start"
269 };
270 h_flex()
271 .w_full()
272 .items_center()
273 .gap(px(8.))
274 .child(self.prompt_toggle(cx))
275 .child(div().flex_1())
276 .child(
277 h_flex()
278 .id("agent-dialog-cancel")
279 .h(px(BUTTON_HEIGHT))
280 .px(px(12.))
281 .items_center()
282 .rounded(px(8.))
283 .cursor_pointer()
284 .bg(theme::surface_raised())
285 .hover(|button| button.bg(theme::popup_hover()))
286 .text_size(px(13.))
287 .child("Cancel")
288 .on_click(cx.listener(|_, _, _, cx| cx.emit(StartDialogEvent::Close))),
289 )
290 .child(
291 h_flex()
292 .id("agent-dialog-start")
293 .h(px(BUTTON_HEIGHT))
294 .px(px(12.))
295 .items_center()
296 .rounded(px(8.))
297 .cursor_pointer()
298 .bg(theme::accent())
299 .hover(|button| button.bg(theme::accent_text()))
300 .text_color(theme::on_accent())
301 .text_size(px(13.))
302 .font_weight(FontWeight::SEMIBOLD)
303 .child(start_label)
304 .on_click(cx.listener(|this, _, _, cx| this.start(cx))),
305 )
306 }
307}
308
309impl Render for StartDialog {
310 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
311 div()
312 .id("agent-dialog-layer")
313 .absolute()
314 .top_0()
315 .left_0()
316 .size_full()
317 .flex()
318 .items_center()
319 .justify_center()
320 .child(
321 div()
322 .id("agent-dialog-backdrop")
323 .absolute()
324 .top_0()
325 .left_0()
326 .size_full()
327 .bg(black().opacity(BACKDROP_OPACITY))
328 .occlude()
329 .on_click(cx.listener(|_, _, _, cx| cx.emit(StartDialogEvent::Close))),
330 )
331 .child(
332 v_flex()
333 .id("agent-dialog-card")
334 .w(px(CARD_WIDTH))
335 .max_w(relative(1.))
336 .max_h(relative(1.))
337 .m(px(CARD_MARGIN))
338 .p(px(CARD_PADDING))
339 .gap(px(SECTION_GAP))
340 .rounded(px(CARD_RADIUS))
341 .bg(theme::popup())
342 .text_color(theme::text())
343 .occlude()
344 .capture_key_down(cx.listener(Self::on_key_down))
345 .child(self.header(cx))
346 .child(self.quote())
347 .when(self.needs_allow, |card| {
348 card.child(
349 div()
350 .text_size(px(12.))
351 .text_color(theme::text_soft())
352 .child("Agents can't see this chat yet."),
353 )
354 })
355 .child(self.field(window, cx))
356 .when(self.show_prompt, |card| card.child(self.prompt_box(cx)))
357 .child(self.buttons(cx)),
358 )
359 }
360}
361
362#[cfg(test)]
363mod tests {
364 use agents::AgentAction;
365
366 use super::needs_dialog;
367
368 #[test]
369 fn the_dialog_shows_for_extra_instructions_or_a_chat_agents_cannot_see() {
370 let quiet = AgentAction::answer_this("claude");
371 let asking = AgentAction::build_this("claude");
372 assert!(!needs_dialog(&quiet, true));
373 assert!(needs_dialog(&quiet, false));
374 assert!(needs_dialog(&asking, true));
375 }
376}
crates/app/src/agents/store.rs added +97 −0
@@ -0,0 +1,97 @@
1 use agents::{AgentSettings, SETTINGS_KEY};
2 use store::Store;
3
4 use super::runs::AgentRun;
5
6 const RUNS_KEY: &str = "agents.runs";
7 pub const RUNS_HISTORY_LIMIT: usize = 50;
8
9 pub fn load_settings(store: &Store) -> AgentSettings {
10 store
11 .meta(SETTINGS_KEY)
12 .ok()
13 .flatten()
14 .and_then(|json| AgentSettings::from_json(&json).ok())
15 .unwrap_or_default()
16 }
17
18 pub fn save_settings(store: &Store, settings: &AgentSettings) {
19 let _ = store.set_meta(SETTINGS_KEY, &settings.to_json());
20 }
21
22 pub fn load_runs(store: &Store) -> Vec<AgentRun> {
23 store
24 .meta(RUNS_KEY)
25 .ok()
26 .flatten()
27 .and_then(|json| serde_json::from_str(&json).ok())
28 .unwrap_or_default()
29 }
30
31 pub fn save_runs(store: &Store, runs: &[AgentRun]) {
32 let finished = runs.iter().filter(|run| run.is_finished()).count();
33 let mut skipped = finished.saturating_sub(RUNS_HISTORY_LIMIT);
34 let kept: Vec<&AgentRun> = runs
35 .iter()
36 .filter(|run| {
37 if skipped > 0 && run.is_finished() {
38 skipped -= 1;
39 return false;
40 }
41 true
42 })
43 .collect();
44 if let Ok(json) = serde_json::to_string(&kept) {
45 let _ = store.set_meta(RUNS_KEY, &json);
46 }
47 }
48
49 #[cfg(test)]
50 mod tests {
51 use agents::AgentAction;
52
53 use super::*;
54 use crate::agents::runs::tests::finished_run;
55
56 #[test]
57 fn settings_round_trip_and_default_when_missing() {
58 let store = Store::open_in_memory().unwrap();
59 assert_eq!(load_settings(&store), AgentSettings::default());
60 let mut settings = AgentSettings::default();
61 settings.actions.push(AgentAction::build_this("copilot"));
62 settings.actions[0].label = "Ask".to_owned();
63 save_settings(&store, &settings);
64 assert_eq!(load_settings(&store), settings);
65 }
66
67 #[test]
68 fn broken_settings_json_falls_back_to_defaults() {
69 let store = Store::open_in_memory().unwrap();
70 store.set_meta(SETTINGS_KEY, "{not json").unwrap();
71 assert_eq!(load_settings(&store), AgentSettings::default());
72 }
73
74 #[test]
75 fn runs_round_trip_and_keep_the_last_fifty_finished() {
76 let store = Store::open_in_memory().unwrap();
77 assert!(load_runs(&store).is_empty());
78 let runs: Vec<AgentRun> = (0..60).map(finished_run).collect();
79 save_runs(&store, &runs);
80 let loaded = load_runs(&store);
81 assert_eq!(loaded.len(), RUNS_HISTORY_LIMIT);
82 assert_eq!(loaded[0].id, 10);
83 assert_eq!(loaded[49], runs[59]);
84 }
85
86 #[test]
87 fn running_runs_are_persisted_and_load_as_interrupted() {
88 let store = Store::open_in_memory().unwrap();
89 let mut running = finished_run(1);
90 running.state = crate::agents::runs::RunState::Running;
91 running.ended_at = None;
92 save_runs(&store, &[running, finished_run(2)]);
93 let stored = load_runs(&store);
94 assert_eq!(stored.len(), 2);
95 assert!(stored[0].is_running());
96 }
97 }
@@ -0,0 +1,97 @@
1use agents::{AgentSettings, SETTINGS_KEY};
2use store::Store;
3
4use super::runs::AgentRun;
5
6const RUNS_KEY: &str = "agents.runs";
7pub const RUNS_HISTORY_LIMIT: usize = 50;
8
9pub fn load_settings(store: &Store) -> AgentSettings {
10 store
11 .meta(SETTINGS_KEY)
12 .ok()
13 .flatten()
14 .and_then(|json| AgentSettings::from_json(&json).ok())
15 .unwrap_or_default()
16}
17
18pub fn save_settings(store: &Store, settings: &AgentSettings) {
19 let _ = store.set_meta(SETTINGS_KEY, &settings.to_json());
20}
21
22pub fn load_runs(store: &Store) -> Vec<AgentRun> {
23 store
24 .meta(RUNS_KEY)
25 .ok()
26 .flatten()
27 .and_then(|json| serde_json::from_str(&json).ok())
28 .unwrap_or_default()
29}
30
31pub fn save_runs(store: &Store, runs: &[AgentRun]) {
32 let finished = runs.iter().filter(|run| run.is_finished()).count();
33 let mut skipped = finished.saturating_sub(RUNS_HISTORY_LIMIT);
34 let kept: Vec<&AgentRun> = runs
35 .iter()
36 .filter(|run| {
37 if skipped > 0 && run.is_finished() {
38 skipped -= 1;
39 return false;
40 }
41 true
42 })
43 .collect();
44 if let Ok(json) = serde_json::to_string(&kept) {
45 let _ = store.set_meta(RUNS_KEY, &json);
46 }
47}
48
49#[cfg(test)]
50mod tests {
51 use agents::AgentAction;
52
53 use super::*;
54 use crate::agents::runs::tests::finished_run;
55
56 #[test]
57 fn settings_round_trip_and_default_when_missing() {
58 let store = Store::open_in_memory().unwrap();
59 assert_eq!(load_settings(&store), AgentSettings::default());
60 let mut settings = AgentSettings::default();
61 settings.actions.push(AgentAction::build_this("copilot"));
62 settings.actions[0].label = "Ask".to_owned();
63 save_settings(&store, &settings);
64 assert_eq!(load_settings(&store), settings);
65 }
66
67 #[test]
68 fn broken_settings_json_falls_back_to_defaults() {
69 let store = Store::open_in_memory().unwrap();
70 store.set_meta(SETTINGS_KEY, "{not json").unwrap();
71 assert_eq!(load_settings(&store), AgentSettings::default());
72 }
73
74 #[test]
75 fn runs_round_trip_and_keep_the_last_fifty_finished() {
76 let store = Store::open_in_memory().unwrap();
77 assert!(load_runs(&store).is_empty());
78 let runs: Vec<AgentRun> = (0..60).map(finished_run).collect();
79 save_runs(&store, &runs);
80 let loaded = load_runs(&store);
81 assert_eq!(loaded.len(), RUNS_HISTORY_LIMIT);
82 assert_eq!(loaded[0].id, 10);
83 assert_eq!(loaded[49], runs[59]);
84 }
85
86 #[test]
87 fn running_runs_are_persisted_and_load_as_interrupted() {
88 let store = Store::open_in_memory().unwrap();
89 let mut running = finished_run(1);
90 running.state = crate::agents::runs::RunState::Running;
91 running.ended_at = None;
92 save_runs(&store, &[running, finished_run(2)]);
93 let stored = load_runs(&store);
94 assert_eq!(stored.len(), 2);
95 assert!(stored[0].is_running());
96 }
97}
crates/app/src/assets.rs +3 −1
@@ -8,7 +8,7 @@ macro_rules! symbols {
8 8 };
9 9 }
10 10
11 const SYMBOLS: [(&str, &[u8]); 40] = symbols![
11 const SYMBOLS: [(&str, &[u8]); 42] = symbols![
12 12 "done",
13 13 "done_all",
14 14 "keyboard_return",
@@ -49,6 +49,8 @@ const SYMBOLS: [(&str, &[u8]); 40] = symbols![
49 49 "chevron_left",
50 50 "chevron_right",
51 51 "fullscreen",
52 "spinner_track",
53 "spinner_arc",
52 54 ];
53 55
54 56 pub struct AppAssets;
@@ -8,7 +8,7 @@ macro_rules! symbols {
8 };
8 };
9}
9}
10
10
11const SYMBOLS: [(&str, &[u8]); 40] = symbols![
11const SYMBOLS: [(&str, &[u8]); 42] = symbols![
12 "done",
12 "done",
13 "done_all",
13 "done_all",
14 "keyboard_return",
14 "keyboard_return",
@@ -49,6 +49,8 @@ const SYMBOLS: [(&str, &[u8]); 40] = symbols![
49 "chevron_left",
49 "chevron_left",
50 "chevron_right",
50 "chevron_right",
51 "fullscreen",
51 "fullscreen",
52 "spinner_track",
53 "spinner_arc",
52];
54];
53
55
54pub struct AppAssets;
56pub struct AppAssets;
crates/app/src/main.rs +2 −0
@@ -5,6 +5,7 @@
5 5
6 6 mod activity;
7 7 mod agent_api;
8 mod agents;
8 9 mod app_state;
9 10 mod assets;
10 11 mod avatar_image;
@@ -253,6 +254,7 @@ fn main() {
253 254 cx.set_global(app_state::AppHandle(state.clone()));
254 255 cx.set_global(views::shell::UserInputHandle(user_input));
255 256 agent_api::init(state.read(cx).store.clone(), arguments.demo, cx);
257 agents::install(state.clone(), cx);
256 258 if arguments.demo {
257 259 state.update(cx, |state, cx| {
258 260 demo::seed_directory(state);
@@ -5,6 +5,7 @@
5
5
6mod activity;
6mod activity;
7mod agent_api;
7mod agent_api;
8mod agents;
8mod app_state;
9mod app_state;
9mod assets;
10mod assets;
10mod avatar_image;
11mod avatar_image;
@@ -253,6 +254,7 @@ fn main() {
253 cx.set_global(app_state::AppHandle(state.clone()));
254 cx.set_global(app_state::AppHandle(state.clone()));
254 cx.set_global(views::shell::UserInputHandle(user_input));
255 cx.set_global(views::shell::UserInputHandle(user_input));
255 agent_api::init(state.read(cx).store.clone(), arguments.demo, cx);
256 agent_api::init(state.read(cx).store.clone(), arguments.demo, cx);
257 agents::install(state.clone(), cx);
256 if arguments.demo {
258 if arguments.demo {
257 state.update(cx, |state, cx| {
259 state.update(cx, |state, cx| {
258 demo::seed_directory(state);
260 demo::seed_directory(state);
crates/app/src/notify/agent_toast.rs added +137 −0
@@ -0,0 +1,137 @@
1 use gpui_kit::assets::IconName;
2 use gpui_kit::component::{h_flex, v_flex};
3 use gpui_kit::prelude::FluentBuilder as _;
4 use gpui_kit::*;
5
6 use super::center::NotificationCenter;
7 use super::layout::{PREVIEW_MAX_LINES, PREVIEW_SIZE};
8 use super::stack::AgentToast;
9 use crate::theme;
10 use crate::views::widgets::{icon, symbol};
11
12 const BUTTON_HEIGHT: f32 = 30.;
13 const CLOSE_SIZE: f32 = 24.;
14
15 fn button(id: &'static str, label: &'static str, primary: bool) -> Stateful<Div> {
16 h_flex()
17 .id(id)
18 .h(px(BUTTON_HEIGHT))
19 .px(px(12.))
20 .items_center()
21 .rounded(px(6.))
22 .cursor_pointer()
23 .text_size(px(12.5))
24 .font_weight(FontWeight::SEMIBOLD)
25 .when(primary, |button| {
26 button
27 .bg(theme::accent())
28 .text_color(theme::on_accent())
29 .hover(|button| button.bg(theme::accent_text()))
30 })
31 .when(!primary, |button| {
32 button
33 .bg(theme::popup())
34 .text_color(theme::text_soft())
35 .hover(|button| button.bg(theme::popup_hover()))
36 })
37 .child(label)
38 }
39
40 pub(super) fn agent_toast_content(
41 center: &Entity<NotificationCenter>,
42 id: u64,
43 agent: &AgentToast,
44 hovered: bool,
45 ) -> Div {
46 let (open_chat_center, follow_up_center, close_center) =
47 (center.clone(), center.clone(), center.clone());
48 let follow_up_label = if agent.failed {
49 "Retry"
50 } else {
51 "Open session"
52 };
53 let tint = if agent.failed {
54 theme::red_soft()
55 } else {
56 theme::accent_text()
57 };
58 v_flex()
59 .w_full()
60 .gap(px(8.))
61 .child(
62 h_flex()
63 .w_full()
64 .h(px(16.))
65 .gap(px(8.))
66 .items_center()
67 .child(icon(IconName::Bot, 14., tint))
68 .child(
69 div()
70 .flex_1()
71 .min_w_0()
72 .truncate()
73 .text_size(px(12.))
74 .text_color(theme::text_muted())
75 .child(agent.header.clone()),
76 )
77 .when(hovered, |row| {
78 row.child(
79 div()
80 .id("agent-toast-close")
81 .size(px(CLOSE_SIZE))
82 .flex_none()
83 .flex()
84 .items_center()
85 .justify_center()
86 .rounded_full()
87 .bg(theme::border_strong())
88 .cursor_pointer()
89 .hover(|button| button.bg(theme::text_faint()))
90 .child(symbol("close", 16., theme::text()))
91 .on_click(move |_, _, cx| {
92 cx.stop_propagation();
93 close_center.update(cx, |center, cx| center.dismiss(id, cx));
94 }),
95 )
96 }),
97 )
98 .child(
99 div()
100 .w_full()
101 .h(px(20.))
102 .truncate()
103 .text_size(px(14.))
104 .line_height(px(20.))
105 .font_weight(FontWeight::SEMIBOLD)
106 .text_color(theme::text())
107 .child(agent.title.clone()),
108 )
109 .child(
110 div()
111 .w_full()
112 .text_size(px(PREVIEW_SIZE))
113 .line_height(px(18.))
114 .text_color(theme::text_soft())
115 .line_clamp(PREVIEW_MAX_LINES)
116 .child(agent.body.clone()),
117 )
118 .child(
119 h_flex()
120 .gap(px(6.))
121 .child(button("agent-toast-open-chat", "Open chat", true).on_click(
122 move |_, _, cx| {
123 cx.stop_propagation();
124 open_chat_center.update(cx, |center, cx| center.activate(id, cx));
125 },
126 ))
127 .child(
128 button("agent-toast-follow-up", follow_up_label, false).on_click(
129 move |_, _, cx| {
130 cx.stop_propagation();
131 follow_up_center
132 .update(cx, |center, cx| center.agent_toast_follow_up(id, cx));
133 },
134 ),
135 ),
136 )
137 }
@@ -0,0 +1,137 @@
1use gpui_kit::assets::IconName;
2use gpui_kit::component::{h_flex, v_flex};
3use gpui_kit::prelude::FluentBuilder as _;
4use gpui_kit::*;
5
6use super::center::NotificationCenter;
7use super::layout::{PREVIEW_MAX_LINES, PREVIEW_SIZE};
8use super::stack::AgentToast;
9use crate::theme;
10use crate::views::widgets::{icon, symbol};
11
12const BUTTON_HEIGHT: f32 = 30.;
13const CLOSE_SIZE: f32 = 24.;
14
15fn button(id: &'static str, label: &'static str, primary: bool) -> Stateful<Div> {
16 h_flex()
17 .id(id)
18 .h(px(BUTTON_HEIGHT))
19 .px(px(12.))
20 .items_center()
21 .rounded(px(6.))
22 .cursor_pointer()
23 .text_size(px(12.5))
24 .font_weight(FontWeight::SEMIBOLD)
25 .when(primary, |button| {
26 button
27 .bg(theme::accent())
28 .text_color(theme::on_accent())
29 .hover(|button| button.bg(theme::accent_text()))
30 })
31 .when(!primary, |button| {
32 button
33 .bg(theme::popup())
34 .text_color(theme::text_soft())
35 .hover(|button| button.bg(theme::popup_hover()))
36 })
37 .child(label)
38}
39
40pub(super) fn agent_toast_content(
41 center: &Entity<NotificationCenter>,
42 id: u64,
43 agent: &AgentToast,
44 hovered: bool,
45) -> Div {
46 let (open_chat_center, follow_up_center, close_center) =
47 (center.clone(), center.clone(), center.clone());
48 let follow_up_label = if agent.failed {
49 "Retry"
50 } else {
51 "Open session"
52 };
53 let tint = if agent.failed {
54 theme::red_soft()
55 } else {
56 theme::accent_text()
57 };
58 v_flex()
59 .w_full()
60 .gap(px(8.))
61 .child(
62 h_flex()
63 .w_full()
64 .h(px(16.))
65 .gap(px(8.))
66 .items_center()
67 .child(icon(IconName::Bot, 14., tint))
68 .child(
69 div()
70 .flex_1()
71 .min_w_0()
72 .truncate()
73 .text_size(px(12.))
74 .text_color(theme::text_muted())
75 .child(agent.header.clone()),
76 )
77 .when(hovered, |row| {
78 row.child(
79 div()
80 .id("agent-toast-close")
81 .size(px(CLOSE_SIZE))
82 .flex_none()
83 .flex()
84 .items_center()
85 .justify_center()
86 .rounded_full()
87 .bg(theme::border_strong())
88 .cursor_pointer()
89 .hover(|button| button.bg(theme::text_faint()))
90 .child(symbol("close", 16., theme::text()))
91 .on_click(move |_, _, cx| {
92 cx.stop_propagation();
93 close_center.update(cx, |center, cx| center.dismiss(id, cx));
94 }),
95 )
96 }),
97 )
98 .child(
99 div()
100 .w_full()
101 .h(px(20.))
102 .truncate()
103 .text_size(px(14.))
104 .line_height(px(20.))
105 .font_weight(FontWeight::SEMIBOLD)
106 .text_color(theme::text())
107 .child(agent.title.clone()),
108 )
109 .child(
110 div()
111 .w_full()
112 .text_size(px(PREVIEW_SIZE))
113 .line_height(px(18.))
114 .text_color(theme::text_soft())
115 .line_clamp(PREVIEW_MAX_LINES)
116 .child(agent.body.clone()),
117 )
118 .child(
119 h_flex()
120 .gap(px(6.))
121 .child(button("agent-toast-open-chat", "Open chat", true).on_click(
122 move |_, _, cx| {
123 cx.stop_propagation();
124 open_chat_center.update(cx, |center, cx| center.activate(id, cx));
125 },
126 ))
127 .child(
128 button("agent-toast-follow-up", follow_up_label, false).on_click(
129 move |_, _, cx| {
130 cx.stop_propagation();
131 follow_up_center
132 .update(cx, |center, cx| center.agent_toast_follow_up(id, cx));
133 },
134 ),
135 ),
136 )
137}
crates/app/src/notify/center.rs +94 −9
@@ -14,13 +14,14 @@ use super::rules::{
14 14 should_flash, should_ringback,
15 15 };
16 16 use super::settings;
17 use super::settings_view::SettingsView;
17 use super::settings_view::{Section, SettingsView};
18 18 use super::stack::{
19 FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE, ToastModel, ToastStack,
19 AgentToast, FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE, ToastModel, ToastStack,
20 20 };
21 21 use super::text::describe;
22 22 use super::ring_view::RingView;
23 23 use super::toast::{PillView, ToastView};
24 use crate::agents::{AgentRun, AgentRunsEvent, RunState};
24 25 use crate::app_state::{AppEvent, AppState, Selection};
25 26 use crate::call::DemoScene;
26 27 use crate::data::{self, Directory, PresenceKind};
@@ -35,6 +36,7 @@ const DEMO_RING_ENV: &str = "TEAMS_DEMO_RING";
35 36 const DEMO_RING_KIND_ENV: &str = "TEAMS_DEMO_RING_KIND";
36 37 const DEMO_CALL_ENV: &str = "TEAMS_DEMO_CALL";
37 38 const DEMO_SCENE_DELAY: Duration = Duration::from_millis(1500);
39 const AGENT_BODY_LINES: usize = 2;
38 40
39 41 struct OpenWindow {
40 42 handle: AnyWindowHandle,
@@ -77,6 +79,7 @@ pub struct NotificationCenter {
77 79 shown_badge: Option<Badge>,
78 80 animations: bool,
79 81 _subscription: Subscription,
82 _agent_subscription: Option<Subscription>,
80 83 }
81 84
82 85 impl NotificationCenter {
@@ -90,6 +93,15 @@ impl NotificationCenter {
90 93 let subscription = cx.subscribe(&app, |this, _, event: &AppEvent, cx| {
91 94 this.on_app_event(event, cx);
92 95 });
96 let agent_subscription = crate::agents::runs_handle(cx).map(|runs| {
97 cx.subscribe(&runs, |this, runs, event: &AgentRunsEvent, cx| {
98 if let AgentRunsEvent::Finished(run_id) = event
99 && let Some(run) = runs.read(cx).get(*run_id).cloned()
100 {
101 this.present_agent_run(&run, cx);
102 }
103 })
104 });
93 105 let center = NotificationCenter {
94 106 main_window: window.window_handle(),
95 107 main_native: platform::native_handle(window),
@@ -115,6 +127,7 @@ impl NotificationCenter {
115 127 animations: platform::animations_enabled(),
116 128 app,
117 129 _subscription: subscription,
130 _agent_subscription: agent_subscription,
118 131 };
119 132 cx.spawn(async move |this, cx| {
120 133 loop {
@@ -321,6 +334,51 @@ impl NotificationCenter {
321 334 self.sync_windows(cx);
322 335 }
323 336
337 pub fn present_agent_run(&mut self, run: &AgentRun, cx: &mut Context<Self>) {
338 let failed = matches!(run.state, RunState::Failed { .. });
339 let verb = if failed { "failed" } else { "finished" };
340 let body = if failed {
341 run.current_step.clone()
342 } else {
343 first_lines(&run.final_text, AGENT_BODY_LINES)
344 };
345 let toast = AgentToast {
346 run_id: run.id,
347 session_id: run.session_id.clone(),
348 header: format!("{} - {} - {}", run.action_label, run.agent_name, run.elapsed_text()),
349 title: format!(
350 "{} {verb}: {} for {}",
351 run.agent_name, run.action_label, run.sender_name
352 ),
353 body: if body.is_empty() { "Done".to_owned() } else { body },
354 failed,
355 };
356 let now = Instant::now();
357 let id = self
358 .stack
359 .push_agent(toast, &run.conversation_id, &run.message_id, now);
360 if let Some(model) = self.stack.get_mut(id) {
361 model.time = chrono::Local::now().format("%H:%M").to_string();
362 }
363 let quiet = self.settings.do_not_disturb || self.app.read(cx).mode.demo;
364 if self.settings.sound && !quiet {
365 platform::play_sound();
366 }
367 self.sync_windows(cx);
368 }
369
370 pub fn agent_toast_follow_up(&mut self, id: u64, cx: &mut Context<Self>) {
371 let Some(agent) = self.stack.get(id).and_then(|toast| toast.agent.clone()) else {
372 return;
373 };
374 self.drop_toast(id, cx);
375 if agent.failed {
376 crate::agents::retry_run(agent.run_id, cx);
377 } else {
378 crate::agents::open_session(&agent.session_id, cx);
379 }
380 }
381
324 382 fn visible_ids(&self) -> Vec<u64> {
325 383 self.stack.visible().iter().map(|toast| toast.id).collect()
326 384 }
@@ -379,7 +437,10 @@ impl NotificationCenter {
379 437 .visible()
380 438 .iter()
381 439 .map(|toast| {
382 let lines = preview_lines(&describe(toast, self.settings.preview).preview, cx);
440 let lines = match &toast.agent {
441 Some(agent) => wrapped_lines(&agent.body, layout::AGENT_BODY_WIDTH, cx),
442 None => preview_lines(&describe(toast, self.settings.preview).preview, cx),
443 };
383 444 layout::toast_height(toast, lines)
384 445 })
385 446 .collect();
@@ -826,11 +887,22 @@ impl NotificationCenter {
826 887 }
827 888
828 889 pub fn open_settings(&mut self, cx: &mut Context<Self>) {
890 self.show_settings(Section::Notifications, false, cx);
891 }
892
893 pub fn open_agent_settings(&mut self, cx: &mut Context<Self>) {
894 self.show_settings(Section::Agents, true, cx);
895 }
896
897 fn show_settings(&mut self, section: Section, switch_open_window: bool, cx: &mut Context<Self>) {
829 898 if let Some(handle) = self.settings_window {
830 if handle
831 .update(cx, |_, window, _| window.activate_window())
832 .is_ok()
833 {
899 let shown = handle.update(cx, |view, window, cx| {
900 window.activate_window();
901 if switch_open_window && let Ok(view) = view.downcast::<SettingsView>() {
902 view.update(cx, |view, cx| view.select_section(section, cx));
903 }
904 });
905 if shown.is_ok() {
834 906 return;
835 907 }
836 908 self.settings_window = None;
@@ -858,7 +930,7 @@ impl NotificationCenter {
858 930 cx.defer(move |cx| {
859 931 let view_center = center.clone();
860 932 let opened = gpui_kit::open_window(options, cx, move |window, cx| {
861 cx.new(|cx| SettingsView::new(view_center, window, cx))
933 cx.new(|cx| SettingsView::new(view_center, section, window, cx))
862 934 });
863 935 center.update(cx, |this, _| {
864 936 this.settings_opening = false;
@@ -945,7 +1017,20 @@ fn demo_ring_delay() -> Option<Duration> {
945 1017 (seconds >= 0.).then(|| Duration::from_secs_f32(seconds))
946 1018 }
947 1019
1020 fn first_lines(text: &str, count: usize) -> String {
1021 text.lines()
1022 .map(str::trim)
1023 .filter(|line| !line.is_empty())
1024 .take(count)
1025 .collect::<Vec<_>>()
1026 .join("\n")
1027 }
1028
948 1029 fn preview_lines(text: &str, cx: &App) -> usize {
1030 wrapped_lines(text, layout::PREVIEW_WIDTH, cx)
1031 }
1032
1033 fn wrapped_lines(text: &str, width: f32, cx: &App) -> usize {
949 1034 let mut wrapper = cx
950 1035 .text_system()
951 1036 .line_wrapper(font(crate::theme::font_family()), px(layout::PREVIEW_SIZE));
@@ -953,7 +1038,7 @@ fn preview_lines(text: &str, cx: &App) -> usize {
953 1038 .map(|line| {
954 1039 let fragments = [LineFragment::text(line)];
955 1040 wrapper
956 .wrap_line(&fragments, px(layout::PREVIEW_WIDTH), IndentAdjustment::NoIndent)
1041 .wrap_line(&fragments, px(width), IndentAdjustment::NoIndent)
957 1042 .count()
958 1043 + 1
959 1044 })
@@ -14,13 +14,14 @@ use super::rules::{
14 should_flash, should_ringback,
14 should_flash, should_ringback,
15};
15};
16use super::settings;
16use super::settings;
17use super::settings_view::SettingsView;
17use super::settings_view::{Section, SettingsView};
18use super::stack::{
18use super::stack::{
19 FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE, ToastModel, ToastStack,
19 AgentToast, FADE_IN, FAST_FADE, ReplyState, SENT_DURATION, SLOW_FADE, ToastModel, ToastStack,
20};
20};
21use super::text::describe;
21use super::text::describe;
22use super::ring_view::RingView;
22use super::ring_view::RingView;
23use super::toast::{PillView, ToastView};
23use super::toast::{PillView, ToastView};
24use crate::agents::{AgentRun, AgentRunsEvent, RunState};
24use crate::app_state::{AppEvent, AppState, Selection};
25use crate::app_state::{AppEvent, AppState, Selection};
25use crate::call::DemoScene;
26use crate::call::DemoScene;
26use crate::data::{self, Directory, PresenceKind};
27use crate::data::{self, Directory, PresenceKind};
@@ -35,6 +36,7 @@ const DEMO_RING_ENV: &str = "TEAMS_DEMO_RING";
35const DEMO_RING_KIND_ENV: &str = "TEAMS_DEMO_RING_KIND";
36const DEMO_RING_KIND_ENV: &str = "TEAMS_DEMO_RING_KIND";
36const DEMO_CALL_ENV: &str = "TEAMS_DEMO_CALL";
37const DEMO_CALL_ENV: &str = "TEAMS_DEMO_CALL";
37const DEMO_SCENE_DELAY: Duration = Duration::from_millis(1500);
38const DEMO_SCENE_DELAY: Duration = Duration::from_millis(1500);
39const AGENT_BODY_LINES: usize = 2;
38
40
39struct OpenWindow {
41struct OpenWindow {
40 handle: AnyWindowHandle,
42 handle: AnyWindowHandle,
@@ -77,6 +79,7 @@ pub struct NotificationCenter {
77 shown_badge: Option<Badge>,
79 shown_badge: Option<Badge>,
78 animations: bool,
80 animations: bool,
79 _subscription: Subscription,
81 _subscription: Subscription,
82 _agent_subscription: Option<Subscription>,
80}
83}
81
84
82impl NotificationCenter {
85impl NotificationCenter {
@@ -90,6 +93,15 @@ impl NotificationCenter {
90 let subscription = cx.subscribe(&app, |this, _, event: &AppEvent, cx| {
93 let subscription = cx.subscribe(&app, |this, _, event: &AppEvent, cx| {
91 this.on_app_event(event, cx);
94 this.on_app_event(event, cx);
92 });
95 });
96 let agent_subscription = crate::agents::runs_handle(cx).map(|runs| {
97 cx.subscribe(&runs, |this, runs, event: &AgentRunsEvent, cx| {
98 if let AgentRunsEvent::Finished(run_id) = event
99 && let Some(run) = runs.read(cx).get(*run_id).cloned()
100 {
101 this.present_agent_run(&run, cx);
102 }
103 })
104 });
93 let center = NotificationCenter {
105 let center = NotificationCenter {
94 main_window: window.window_handle(),
106 main_window: window.window_handle(),
95 main_native: platform::native_handle(window),
107 main_native: platform::native_handle(window),
@@ -115,6 +127,7 @@ impl NotificationCenter {
115 animations: platform::animations_enabled(),
127 animations: platform::animations_enabled(),
116 app,
128 app,
117 _subscription: subscription,
129 _subscription: subscription,
130 _agent_subscription: agent_subscription,
118 };
131 };
119 cx.spawn(async move |this, cx| {
132 cx.spawn(async move |this, cx| {
120 loop {
133 loop {
@@ -321,6 +334,51 @@ impl NotificationCenter {
321 self.sync_windows(cx);
334 self.sync_windows(cx);
322 }
335 }
323
336
337 pub fn present_agent_run(&mut self, run: &AgentRun, cx: &mut Context<Self>) {
338 let failed = matches!(run.state, RunState::Failed { .. });
339 let verb = if failed { "failed" } else { "finished" };
340 let body = if failed {
341 run.current_step.clone()
342 } else {
343 first_lines(&run.final_text, AGENT_BODY_LINES)
344 };
345 let toast = AgentToast {
346 run_id: run.id,
347 session_id: run.session_id.clone(),
348 header: format!("{} - {} - {}", run.action_label, run.agent_name, run.elapsed_text()),
349 title: format!(
350 "{} {verb}: {} for {}",
351 run.agent_name, run.action_label, run.sender_name
352 ),
353 body: if body.is_empty() { "Done".to_owned() } else { body },
354 failed,
355 };
356 let now = Instant::now();
357 let id = self
358 .stack
359 .push_agent(toast, &run.conversation_id, &run.message_id, now);
360 if let Some(model) = self.stack.get_mut(id) {
361 model.time = chrono::Local::now().format("%H:%M").to_string();
362 }
363 let quiet = self.settings.do_not_disturb || self.app.read(cx).mode.demo;
364 if self.settings.sound && !quiet {
365 platform::play_sound();
366 }
367 self.sync_windows(cx);
368 }
369
370 pub fn agent_toast_follow_up(&mut self, id: u64, cx: &mut Context<Self>) {
371 let Some(agent) = self.stack.get(id).and_then(|toast| toast.agent.clone()) else {
372 return;
373 };
374 self.drop_toast(id, cx);
375 if agent.failed {
376 crate::agents::retry_run(agent.run_id, cx);
377 } else {
378 crate::agents::open_session(&agent.session_id, cx);
379 }
380 }
381
324 fn visible_ids(&self) -> Vec<u64> {
382 fn visible_ids(&self) -> Vec<u64> {
325 self.stack.visible().iter().map(|toast| toast.id).collect()
383 self.stack.visible().iter().map(|toast| toast.id).collect()
326 }
384 }
@@ -379,7 +437,10 @@ impl NotificationCenter {
379 .visible()
437 .visible()
380 .iter()
438 .iter()
381 .map(|toast| {
439 .map(|toast| {
382 let lines = preview_lines(&describe(toast, self.settings.preview).preview, cx);
440 let lines = match &toast.agent {
441 Some(agent) => wrapped_lines(&agent.body, layout::AGENT_BODY_WIDTH, cx),
442 None => preview_lines(&describe(toast, self.settings.preview).preview, cx),
443 };
383 layout::toast_height(toast, lines)
444 layout::toast_height(toast, lines)
384 })
445 })
385 .collect();
446 .collect();
@@ -826,11 +887,22 @@ impl NotificationCenter {
826 }
887 }
827
888
828 pub fn open_settings(&mut self, cx: &mut Context<Self>) {
889 pub fn open_settings(&mut self, cx: &mut Context<Self>) {
890 self.show_settings(Section::Notifications, false, cx);
891 }
892
893 pub fn open_agent_settings(&mut self, cx: &mut Context<Self>) {
894 self.show_settings(Section::Agents, true, cx);
895 }
896
897 fn show_settings(&mut self, section: Section, switch_open_window: bool, cx: &mut Context<Self>) {
829 if let Some(handle) = self.settings_window {
898 if let Some(handle) = self.settings_window {
830 if handle
899 let shown = handle.update(cx, |view, window, cx| {
831 .update(cx, |_, window, _| window.activate_window())
900 window.activate_window();
832 .is_ok()
901 if switch_open_window && let Ok(view) = view.downcast::<SettingsView>() {
833 {
902 view.update(cx, |view, cx| view.select_section(section, cx));
903 }
904 });
905 if shown.is_ok() {
834 return;
906 return;
835 }
907 }
836 self.settings_window = None;
908 self.settings_window = None;
@@ -858,7 +930,7 @@ impl NotificationCenter {
858 cx.defer(move |cx| {
930 cx.defer(move |cx| {
859 let view_center = center.clone();
931 let view_center = center.clone();
860 let opened = gpui_kit::open_window(options, cx, move |window, cx| {
932 let opened = gpui_kit::open_window(options, cx, move |window, cx| {
861 cx.new(|cx| SettingsView::new(view_center, window, cx))
933 cx.new(|cx| SettingsView::new(view_center, section, window, cx))
862 });
934 });
863 center.update(cx, |this, _| {
935 center.update(cx, |this, _| {
864 this.settings_opening = false;
936 this.settings_opening = false;
@@ -945,7 +1017,20 @@ fn demo_ring_delay() -> Option<Duration> {
945 (seconds >= 0.).then(|| Duration::from_secs_f32(seconds))
1017 (seconds >= 0.).then(|| Duration::from_secs_f32(seconds))
946}
1018}
947
1019
1020fn first_lines(text: &str, count: usize) -> String {
1021 text.lines()
1022 .map(str::trim)
1023 .filter(|line| !line.is_empty())
1024 .take(count)
1025 .collect::<Vec<_>>()
1026 .join("\n")
1027}
1028
948fn preview_lines(text: &str, cx: &App) -> usize {
1029fn preview_lines(text: &str, cx: &App) -> usize {
1030 wrapped_lines(text, layout::PREVIEW_WIDTH, cx)
1031}
1032
1033fn wrapped_lines(text: &str, width: f32, cx: &App) -> usize {
949 let mut wrapper = cx
1034 let mut wrapper = cx
950 .text_system()
1035 .text_system()
951 .line_wrapper(font(crate::theme::font_family()), px(layout::PREVIEW_SIZE));
1036 .line_wrapper(font(crate::theme::font_family()), px(layout::PREVIEW_SIZE));
@@ -953,7 +1038,7 @@ fn preview_lines(text: &str, cx: &App) -> usize {
953 .map(|line| {
1038 .map(|line| {
954 let fragments = [LineFragment::text(line)];
1039 let fragments = [LineFragment::text(line)];
955 wrapper
1040 wrapper
956 .wrap_line(&fragments, px(layout::PREVIEW_WIDTH), IndentAdjustment::NoIndent)
1041 .wrap_line(&fragments, px(width), IndentAdjustment::NoIndent)
957 .count()
1042 .count()
958 + 1
1043 + 1
959 })
1044 })
crates/app/src/notify/layout.rs +18 −0
@@ -24,6 +24,8 @@ const REPLY_FIELD_FRAME: f32 = 14.;
24 24 const REPLY_HINT_ROW: f32 = 20.;
25 25 const REPLY_SPACING: f32 = 8.;
26 26 const CONFIRM_HEIGHT: f32 = 56.;
27 const AGENT_CHROME_HEIGHT: f32 = 116.;
28 pub const AGENT_BODY_WIDTH: f32 = TOAST_WIDTH - 2. * TOAST_PADDING - 2.;
27 29 const RING_BASE_HEIGHT: f32 = 120.;
28 30 const RING_NOTE_HEIGHT: f32 = 18.;
29 31
@@ -36,6 +38,9 @@ pub struct Slot {
36 38 }
37 39
38 40 pub fn toast_height(model: &ToastModel, preview_lines: usize) -> f32 {
41 if model.agent.is_some() {
42 return AGENT_CHROME_HEIGHT + preview_lines.clamp(1, PREVIEW_MAX_LINES) as f32 * PREVIEW_LINE;
43 }
39 44 let base = BASE_HEIGHT + preview_lines.clamp(1, PREVIEW_MAX_LINES) as f32 * PREVIEW_LINE;
40 45 match model.reply {
41 46 ReplyState::Sent | ReplyState::Failed => CONFIRM_HEIGHT,
@@ -194,10 +199,23 @@ mod tests {
194 199 queued: false,
195 200 dismissed: false,
196 201 fade: super::super::stack::Fade::shown(std::time::Instant::now()),
202 agent: None,
197 203 };
198 204 assert_eq!(toast_height(&model("Hi"), 1), 112.);
199 205 assert_eq!(toast_height(&model("Hi"), 2), 130.);
200 206 assert_eq!(toast_height(&model("Hi"), 5), 130.);
201 207 assert_eq!(toast_height(&model("Hi"), 0), 112.);
208 let mut agent = model("Hi");
209 agent.agent = Some(super::super::stack::AgentToast {
210 run_id: 1,
211 session_id: String::new(),
212 header: String::new(),
213 title: String::new(),
214 body: "Hi".into(),
215 failed: false,
216 });
217 assert_eq!(toast_height(&agent, 1), 134.);
218 assert_eq!(toast_height(&agent, 2), 152.);
219 assert_eq!(toast_height(&agent, 6), 152.);
202 220 }
203 221 }
@@ -24,6 +24,8 @@ const REPLY_FIELD_FRAME: f32 = 14.;
24const REPLY_HINT_ROW: f32 = 20.;
24const REPLY_HINT_ROW: f32 = 20.;
25const REPLY_SPACING: f32 = 8.;
25const REPLY_SPACING: f32 = 8.;
26const CONFIRM_HEIGHT: f32 = 56.;
26const CONFIRM_HEIGHT: f32 = 56.;
27const AGENT_CHROME_HEIGHT: f32 = 116.;
28pub const AGENT_BODY_WIDTH: f32 = TOAST_WIDTH - 2. * TOAST_PADDING - 2.;
27const RING_BASE_HEIGHT: f32 = 120.;
29const RING_BASE_HEIGHT: f32 = 120.;
28const RING_NOTE_HEIGHT: f32 = 18.;
30const RING_NOTE_HEIGHT: f32 = 18.;
29
31
@@ -36,6 +38,9 @@ pub struct Slot {
36}
38}
37
39
38pub fn toast_height(model: &ToastModel, preview_lines: usize) -> f32 {
40pub fn toast_height(model: &ToastModel, preview_lines: usize) -> f32 {
41 if model.agent.is_some() {
42 return AGENT_CHROME_HEIGHT + preview_lines.clamp(1, PREVIEW_MAX_LINES) as f32 * PREVIEW_LINE;
43 }
39 let base = BASE_HEIGHT + preview_lines.clamp(1, PREVIEW_MAX_LINES) as f32 * PREVIEW_LINE;
44 let base = BASE_HEIGHT + preview_lines.clamp(1, PREVIEW_MAX_LINES) as f32 * PREVIEW_LINE;
40 match model.reply {
45 match model.reply {
41 ReplyState::Sent | ReplyState::Failed => CONFIRM_HEIGHT,
46 ReplyState::Sent | ReplyState::Failed => CONFIRM_HEIGHT,
@@ -194,10 +199,23 @@ mod tests {
194 queued: false,
199 queued: false,
195 dismissed: false,
200 dismissed: false,
196 fade: super::super::stack::Fade::shown(std::time::Instant::now()),
201 fade: super::super::stack::Fade::shown(std::time::Instant::now()),
202 agent: None,
197 };
203 };
198 assert_eq!(toast_height(&model("Hi"), 1), 112.);
204 assert_eq!(toast_height(&model("Hi"), 1), 112.);
199 assert_eq!(toast_height(&model("Hi"), 2), 130.);
205 assert_eq!(toast_height(&model("Hi"), 2), 130.);
200 assert_eq!(toast_height(&model("Hi"), 5), 130.);
206 assert_eq!(toast_height(&model("Hi"), 5), 130.);
201 assert_eq!(toast_height(&model("Hi"), 0), 112.);
207 assert_eq!(toast_height(&model("Hi"), 0), 112.);
208 let mut agent = model("Hi");
209 agent.agent = Some(super::super::stack::AgentToast {
210 run_id: 1,
211 session_id: String::new(),
212 header: String::new(),
213 title: String::new(),
214 body: "Hi".into(),
215 failed: false,
216 });
217 assert_eq!(toast_height(&agent, 1), 134.);
218 assert_eq!(toast_height(&agent, 2), 152.);
219 assert_eq!(toast_height(&agent, 6), 152.);
202 }
220 }
203}
221}
crates/app/src/notify/mod.rs +2 −0
@@ -1,3 +1,4 @@
1 mod agent_toast;
1 2 #[cfg_attr(not(windows), allow(dead_code))]
2 3 mod badge;
3 4 mod center;
@@ -18,6 +19,7 @@ mod toast;
18 19
19 20 pub use center::{NotificationCenter, selection_for};
20 21 pub use incoming::{IncomingTracker, preview_of};
22 pub(crate) use settings_view::switch;
21 23 pub use rules::{Incoming, Preview, channel_alerts};
22 24 #[cfg(test)]
23 25 pub use rules::ChatKind;
@@ -1,3 +1,4 @@
1mod agent_toast;
1#[cfg_attr(not(windows), allow(dead_code))]
2#[cfg_attr(not(windows), allow(dead_code))]
2mod badge;
3mod badge;
3mod center;
4mod center;
@@ -18,6 +19,7 @@ mod toast;
18
19
19pub use center::{NotificationCenter, selection_for};
20pub use center::{NotificationCenter, selection_for};
20pub use incoming::{IncomingTracker, preview_of};
21pub use incoming::{IncomingTracker, preview_of};
22pub(crate) use settings_view::switch;
21pub use rules::{Incoming, Preview, channel_alerts};
23pub use rules::{Incoming, Preview, channel_alerts};
22#[cfg(test)]
24#[cfg(test)]
23pub use rules::ChatKind;
25pub use rules::ChatKind;
crates/app/src/notify/settings_view.rs +22 −7
@@ -17,6 +17,7 @@ use super::platform;
17 17 use super::ring_tone::Ringtone;
18 18 use super::rules::Settings;
19 19 use super::settings_mcp::McpView;
20 use crate::agents::AgentsSettings;
20 21 use crate::app_state::AppState;
21 22 use crate::call::{BackgroundPick, CameraPreview, preview_backgrounds};
22 23 use crate::theme;
@@ -33,19 +34,21 @@ fn camera_in_call(state: &AppState) -> bool {
33 34 }
34 35
35 36 #[derive(Clone, Copy, PartialEq, Eq)]
36 enum Section {
37 pub(super) enum Section {
37 38 Notifications,
38 39 Devices,
40 Agents,
39 41 Mcp,
40 42 }
41 43
42 44 impl Section {
43 const ALL: [Section; 3] = [Section::Notifications, Section::Devices, Section::Mcp];
45 const ALL: [Section; 4] = [Section::Notifications, Section::Devices, Section::Agents, Section::Mcp];
44 46
45 47 fn label(self) -> &'static str {
46 48 match self {
47 49 Section::Notifications => "Notifications",
48 50 Section::Devices => "Devices",
51 Section::Agents => "Agents",
49 52 Section::Mcp => "MCP",
50 53 }
51 54 }
@@ -91,6 +94,7 @@ pub struct SettingsView {
91 94 center: Entity<NotificationCenter>,
92 95 section: Section,
93 96 mcp: Entity<McpView>,
97 agents: Option<Entity<AgentsSettings>>,
94 98 preview: CameraPreview,
95 99 cameras: Vec<DeviceEntry>,
96 100 cameras_requested: bool,
@@ -104,10 +108,11 @@ pub struct SettingsView {
104 108
105 109 impl SettingsView {
106 110 pub const WIDTH: f32 = 420.;
107 pub const HEIGHT: f32 = 540.;
111 pub const HEIGHT: f32 = 680.;
108 112
109 113 pub fn new(
110 114 center: Entity<NotificationCenter>,
115 section: Section,
111 116 window: &mut Window,
112 117 cx: &mut Context<Self>,
113 118 ) -> Self {
@@ -140,10 +145,13 @@ impl SettingsView {
140 145 }
141 146 })
142 147 .detach();
148 let agents = crate::agents::runs_handle(cx)
149 .map(|runs| cx.new(|cx| AgentsSettings::new(runs, cx)));
143 150 SettingsView {
144 151 center,
145 section: Section::Notifications,
152 section,
146 153 mcp,
154 agents,
147 155 preview,
148 156 cameras: camera_entries(&[]),
149 157 cameras_requested: false,
@@ -168,7 +176,7 @@ impl SettingsView {
168 176 }
169 177 }
170 178
171 fn select_section(&mut self, section: Section, cx: &mut Context<Self>) {
179 pub(super) fn select_section(&mut self, section: Section, cx: &mut Context<Self>) {
172 180 if self.section == section {
173 181 return;
174 182 }
@@ -180,7 +188,7 @@ impl SettingsView {
180 188 self.preview_blocked = camera_in_call(self.center.read(cx).app().read(cx));
181 189 self.start_preview();
182 190 }
183 Section::Notifications | Section::Mcp => self.preview.stop(cx),
191 Section::Notifications | Section::Agents | Section::Mcp => self.preview.stop(cx),
184 192 }
185 193 cx.notify();
186 194 }
@@ -244,7 +252,7 @@ impl SettingsView {
244 252 }
245 253 }
246 254
247 pub(super) fn switch(on: bool) -> Div {
255 pub(crate) fn switch(on: bool) -> Div {
248 256 div()
249 257 .w(px(36.))
250 258 .h(px(20.))
@@ -489,6 +497,13 @@ impl Render for SettingsView {
489 497 let body = match self.section {
490 498 Section::Notifications => self.notifications_section(cx).into_any_element(),
491 499 Section::Devices => self.devices_section(cx).into_any_element(),
500 Section::Agents => div()
501 .id("agents-scroll")
502 .flex_1()
503 .min_h(px(0.))
504 .overflow_y_scroll()
505 .children(self.agents.clone())
506 .into_any_element(),
492 507 Section::Mcp => self.mcp.clone().into_any_element(),
493 508 };
494 509 v_flex()
@@ -17,6 +17,7 @@ use super::platform;
17use super::ring_tone::Ringtone;
17use super::ring_tone::Ringtone;
18use super::rules::Settings;
18use super::rules::Settings;
19use super::settings_mcp::McpView;
19use super::settings_mcp::McpView;
20use crate::agents::AgentsSettings;
20use crate::app_state::AppState;
21use crate::app_state::AppState;
21use crate::call::{BackgroundPick, CameraPreview, preview_backgrounds};
22use crate::call::{BackgroundPick, CameraPreview, preview_backgrounds};
22use crate::theme;
23use crate::theme;
@@ -33,19 +34,21 @@ fn camera_in_call(state: &AppState) -> bool {
33}
34}
34
35
35#[derive(Clone, Copy, PartialEq, Eq)]
36#[derive(Clone, Copy, PartialEq, Eq)]
36enum Section {
37pub(super) enum Section {
37 Notifications,
38 Notifications,
38 Devices,
39 Devices,
40 Agents,
39 Mcp,
41 Mcp,
40}
42}
41
43
42impl Section {
44impl Section {
43 const ALL: [Section; 3] = [Section::Notifications, Section::Devices, Section::Mcp];
45 const ALL: [Section; 4] = [Section::Notifications, Section::Devices, Section::Agents, Section::Mcp];
44
46
45 fn label(self) -> &'static str {
47 fn label(self) -> &'static str {
46 match self {
48 match self {
47 Section::Notifications => "Notifications",
49 Section::Notifications => "Notifications",
48 Section::Devices => "Devices",
50 Section::Devices => "Devices",
51 Section::Agents => "Agents",
49 Section::Mcp => "MCP",
52 Section::Mcp => "MCP",
50 }
53 }
51 }
54 }
@@ -91,6 +94,7 @@ pub struct SettingsView {
91 center: Entity<NotificationCenter>,
94 center: Entity<NotificationCenter>,
92 section: Section,
95 section: Section,
93 mcp: Entity<McpView>,
96 mcp: Entity<McpView>,
97 agents: Option<Entity<AgentsSettings>>,
94 preview: CameraPreview,
98 preview: CameraPreview,
95 cameras: Vec<DeviceEntry>,
99 cameras: Vec<DeviceEntry>,
96 cameras_requested: bool,
100 cameras_requested: bool,
@@ -104,10 +108,11 @@ pub struct SettingsView {
104
108
105impl SettingsView {
109impl SettingsView {
106 pub const WIDTH: f32 = 420.;
110 pub const WIDTH: f32 = 420.;
107 pub const HEIGHT: f32 = 540.;
111 pub const HEIGHT: f32 = 680.;
108
112
109 pub fn new(
113 pub fn new(
110 center: Entity<NotificationCenter>,
114 center: Entity<NotificationCenter>,
115 section: Section,
111 window: &mut Window,
116 window: &mut Window,
112 cx: &mut Context<Self>,
117 cx: &mut Context<Self>,
113 ) -> Self {
118 ) -> Self {
@@ -140,10 +145,13 @@ impl SettingsView {
140 }
145 }
141 })
146 })
142 .detach();
147 .detach();
148 let agents = crate::agents::runs_handle(cx)
149 .map(|runs| cx.new(|cx| AgentsSettings::new(runs, cx)));
143 SettingsView {
150 SettingsView {
144 center,
151 center,
145 section: Section::Notifications,
152 section,
146 mcp,
153 mcp,
154 agents,
147 preview,
155 preview,
148 cameras: camera_entries(&[]),
156 cameras: camera_entries(&[]),
149 cameras_requested: false,
157 cameras_requested: false,
@@ -168,7 +176,7 @@ impl SettingsView {
168 }
176 }
169 }
177 }
170
178
171 fn select_section(&mut self, section: Section, cx: &mut Context<Self>) {
179 pub(super) fn select_section(&mut self, section: Section, cx: &mut Context<Self>) {
172 if self.section == section {
180 if self.section == section {
173 return;
181 return;
174 }
182 }
@@ -180,7 +188,7 @@ impl SettingsView {
180 self.preview_blocked = camera_in_call(self.center.read(cx).app().read(cx));
188 self.preview_blocked = camera_in_call(self.center.read(cx).app().read(cx));
181 self.start_preview();
189 self.start_preview();
182 }
190 }
183 Section::Notifications | Section::Mcp => self.preview.stop(cx),
191 Section::Notifications | Section::Agents | Section::Mcp => self.preview.stop(cx),
184 }
192 }
185 cx.notify();
193 cx.notify();
186 }
194 }
@@ -244,7 +252,7 @@ impl SettingsView {
244 }
252 }
245}
253}
246
254
247pub(super) fn switch(on: bool) -> Div {
255pub(crate) fn switch(on: bool) -> Div {
248 div()
256 div()
249 .w(px(36.))
257 .w(px(36.))
250 .h(px(20.))
258 .h(px(20.))
@@ -489,6 +497,13 @@ impl Render for SettingsView {
489 let body = match self.section {
497 let body = match self.section {
490 Section::Notifications => self.notifications_section(cx).into_any_element(),
498 Section::Notifications => self.notifications_section(cx).into_any_element(),
491 Section::Devices => self.devices_section(cx).into_any_element(),
499 Section::Devices => self.devices_section(cx).into_any_element(),
500 Section::Agents => div()
501 .id("agents-scroll")
502 .flex_1()
503 .min_h(px(0.))
504 .overflow_y_scroll()
505 .children(self.agents.clone())
506 .into_any_element(),
492 Section::Mcp => self.mcp.clone().into_any_element(),
507 Section::Mcp => self.mcp.clone().into_any_element(),
493 };
508 };
494 v_flex()
509 v_flex()
crates/app/src/notify/stack.rs +83 −4
@@ -140,6 +140,16 @@ pub enum ReplyState {
140 140 Failed,
141 141 }
142 142
143 #[derive(Debug, Clone, PartialEq, Eq)]
144 pub struct AgentToast {
145 pub run_id: u64,
146 pub session_id: String,
147 pub header: String,
148 pub title: String,
149 pub body: String,
150 pub failed: bool,
151 }
152
143 153 #[derive(Debug, Clone)]
144 154 pub struct ToastModel {
145 155 pub id: u64,
@@ -160,6 +170,7 @@ pub struct ToastModel {
160 170 pub queued: bool,
161 171 pub dismissed: bool,
162 172 pub fade: Fade,
173 pub agent: Option<AgentToast>,
163 174 }
164 175
165 176 impl ToastModel {
@@ -200,7 +211,7 @@ impl ToastStack {
200 211 if let Some(existing) = self
201 212 .toasts
202 213 .iter_mut()
203 .find(|toast| toast.conversation_id == incoming.conversation_id)
214 .find(|toast| toast.agent.is_none() && toast.conversation_id == incoming.conversation_id)
204 215 {
205 216 let became_mention = incoming.mentions_me && !existing.mentions_me;
206 217 existing.count += 1;
@@ -238,6 +249,7 @@ impl ToastStack {
238 249 queued,
239 250 dismissed: false,
240 251 fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),
252 agent: None,
241 253 });
242 254 PushOutcome {
243 255 id: self.next_id,
@@ -246,6 +258,39 @@ impl ToastStack {
246 258 }
247 259 }
248 260
261 pub fn push_agent(
262 &mut self,
263 agent: AgentToast,
264 conversation_id: &str,
265 message_id: &str,
266 now: Instant,
267 ) -> u64 {
268 self.next_id += 1;
269 let queued = self.toasts.len() >= MAX_VISIBLE;
270 self.toasts.push(ToastModel {
271 id: self.next_id,
272 conversation_id: conversation_id.to_owned(),
273 message_id: message_id.to_owned(),
274 kind: ChatKind::Direct,
275 chat_title: String::new(),
276 sender_id: None,
277 sender_name: String::new(),
278 preview: Preview::Text(agent.body.clone()),
279 mentions_me: false,
280 count: 1,
281 timer: ToastTimer::new(now, true),
282 reply: ReplyState::Closed,
283 reply_text: String::new(),
284 hovered: false,
285 time: String::new(),
286 queued,
287 dismissed: false,
288 fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),
289 agent: Some(agent),
290 });
291 self.next_id
292 }
293
249 294 pub fn get(&self, id: u64) -> Option<&ToastModel> {
250 295 self.toasts.iter().find(|toast| toast.id == id)
251 296 }
@@ -260,14 +305,16 @@ impl ToastStack {
260 305 }
261 306
262 307 pub fn remove_conversation(&mut self, conversation_id: &str) -> Vec<u64> {
308 let matches = |toast: &ToastModel| {
309 toast.agent.is_none() && toast.conversation_id == conversation_id
310 };
263 311 let ids: Vec<u64> = self
264 312 .toasts
265 313 .iter()
266 .filter(|toast| toast.conversation_id == conversation_id)
314 .filter(|toast| matches(toast))
267 315 .map(|toast| toast.id)
268 316 .collect();
269 self.toasts
270 .retain(|toast| toast.conversation_id != conversation_id);
317 self.toasts.retain(|toast| !matches(toast));
271 318 ids
272 319 }
273 320
@@ -563,4 +610,36 @@ mod tests {
563 610 assert_eq!(stack.remove_conversation("a"), vec![id]);
564 611 assert_eq!(stack.visible().len(), 1);
565 612 }
613
614 fn agent_toast() -> AgentToast {
615 AgentToast {
616 run_id: 7,
617 session_id: "s".into(),
618 header: "Answer this - Claude - 1:02".into(),
619 title: "Claude finished: Answer this for Mara".into(),
620 body: "Done".into(),
621 failed: false,
622 }
623 }
624
625 #[test]
626 fn agent_toasts_never_bundle_with_messages() {
627 let mut stack = ToastStack::default();
628 let now = Instant::now();
629 let agent_id = stack.push_agent(agent_toast(), "a", "m", now);
630 let outcome = stack.push(&incoming("a", false), now);
631 assert!(!outcome.bundled);
632 assert_ne!(outcome.id, agent_id);
633 assert_eq!(stack.visible().len(), 2);
634 }
635
636 #[test]
637 fn opening_the_chat_keeps_the_agent_toast() {
638 let mut stack = ToastStack::default();
639 let now = Instant::now();
640 let agent_id = stack.push_agent(agent_toast(), "a", "m", now);
641 let message_id = stack.push(&incoming("a", false), now).id;
642 assert_eq!(stack.remove_conversation("a"), vec![message_id]);
643 assert!(stack.get(agent_id).is_some());
644 }
566 645 }
@@ -140,6 +140,16 @@ pub enum ReplyState {
140 Failed,
140 Failed,
141}
141}
142
142
143#[derive(Debug, Clone, PartialEq, Eq)]
144pub struct AgentToast {
145 pub run_id: u64,
146 pub session_id: String,
147 pub header: String,
148 pub title: String,
149 pub body: String,
150 pub failed: bool,
151}
152
143#[derive(Debug, Clone)]
153#[derive(Debug, Clone)]
144pub struct ToastModel {
154pub struct ToastModel {
145 pub id: u64,
155 pub id: u64,
@@ -160,6 +170,7 @@ pub struct ToastModel {
160 pub queued: bool,
170 pub queued: bool,
161 pub dismissed: bool,
171 pub dismissed: bool,
162 pub fade: Fade,
172 pub fade: Fade,
173 pub agent: Option<AgentToast>,
163}
174}
164
175
165impl ToastModel {
176impl ToastModel {
@@ -200,7 +211,7 @@ impl ToastStack {
200 if let Some(existing) = self
211 if let Some(existing) = self
201 .toasts
212 .toasts
202 .iter_mut()
213 .iter_mut()
203 .find(|toast| toast.conversation_id == incoming.conversation_id)
214 .find(|toast| toast.agent.is_none() && toast.conversation_id == incoming.conversation_id)
204 {
215 {
205 let became_mention = incoming.mentions_me && !existing.mentions_me;
216 let became_mention = incoming.mentions_me && !existing.mentions_me;
206 existing.count += 1;
217 existing.count += 1;
@@ -238,6 +249,7 @@ impl ToastStack {
238 queued,
249 queued,
239 dismissed: false,
250 dismissed: false,
240 fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),
251 fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),
252 agent: None,
241 });
253 });
242 PushOutcome {
254 PushOutcome {
243 id: self.next_id,
255 id: self.next_id,
@@ -246,6 +258,39 @@ impl ToastStack {
246 }
258 }
247 }
259 }
248
260
261 pub fn push_agent(
262 &mut self,
263 agent: AgentToast,
264 conversation_id: &str,
265 message_id: &str,
266 now: Instant,
267 ) -> u64 {
268 self.next_id += 1;
269 let queued = self.toasts.len() >= MAX_VISIBLE;
270 self.toasts.push(ToastModel {
271 id: self.next_id,
272 conversation_id: conversation_id.to_owned(),
273 message_id: message_id.to_owned(),
274 kind: ChatKind::Direct,
275 chat_title: String::new(),
276 sender_id: None,
277 sender_name: String::new(),
278 preview: Preview::Text(agent.body.clone()),
279 mentions_me: false,
280 count: 1,
281 timer: ToastTimer::new(now, true),
282 reply: ReplyState::Closed,
283 reply_text: String::new(),
284 hovered: false,
285 time: String::new(),
286 queued,
287 dismissed: false,
288 fade: Fade::new(0., 1., now, FADE_IN, Curve::Linear),
289 agent: Some(agent),
290 });
291 self.next_id
292 }
293
249 pub fn get(&self, id: u64) -> Option<&ToastModel> {
294 pub fn get(&self, id: u64) -> Option<&ToastModel> {
250 self.toasts.iter().find(|toast| toast.id == id)
295 self.toasts.iter().find(|toast| toast.id == id)
251 }
296 }
@@ -260,14 +305,16 @@ impl ToastStack {
260 }
305 }
261
306
262 pub fn remove_conversation(&mut self, conversation_id: &str) -> Vec<u64> {
307 pub fn remove_conversation(&mut self, conversation_id: &str) -> Vec<u64> {
308 let matches = |toast: &ToastModel| {
309 toast.agent.is_none() && toast.conversation_id == conversation_id
310 };
263 let ids: Vec<u64> = self
311 let ids: Vec<u64> = self
264 .toasts
312 .toasts
265 .iter()
313 .iter()
266 .filter(|toast| toast.conversation_id == conversation_id)
314 .filter(|toast| matches(toast))
267 .map(|toast| toast.id)
315 .map(|toast| toast.id)
268 .collect();
316 .collect();
269 self.toasts
317 self.toasts.retain(|toast| !matches(toast));
270 .retain(|toast| toast.conversation_id != conversation_id);
271 ids
318 ids
272 }
319 }
273
320
@@ -563,4 +610,36 @@ mod tests {
563 assert_eq!(stack.remove_conversation("a"), vec![id]);
610 assert_eq!(stack.remove_conversation("a"), vec![id]);
564 assert_eq!(stack.visible().len(), 1);
611 assert_eq!(stack.visible().len(), 1);
565 }
612 }
613
614 fn agent_toast() -> AgentToast {
615 AgentToast {
616 run_id: 7,
617 session_id: "s".into(),
618 header: "Answer this - Claude - 1:02".into(),
619 title: "Claude finished: Answer this for Mara".into(),
620 body: "Done".into(),
621 failed: false,
622 }
623 }
624
625 #[test]
626 fn agent_toasts_never_bundle_with_messages() {
627 let mut stack = ToastStack::default();
628 let now = Instant::now();
629 let agent_id = stack.push_agent(agent_toast(), "a", "m", now);
630 let outcome = stack.push(&incoming("a", false), now);
631 assert!(!outcome.bundled);
632 assert_ne!(outcome.id, agent_id);
633 assert_eq!(stack.visible().len(), 2);
634 }
635
636 #[test]
637 fn opening_the_chat_keeps_the_agent_toast() {
638 let mut stack = ToastStack::default();
639 let now = Instant::now();
640 let agent_id = stack.push_agent(agent_toast(), "a", "m", now);
641 let message_id = stack.push(&incoming("a", false), now).id;
642 assert_eq!(stack.remove_conversation("a"), vec![message_id]);
643 assert!(stack.get(agent_id).is_some());
644 }
566}
645}
crates/app/src/notify/text.rs +1 −0
@@ -98,6 +98,7 @@ mod tests {
98 98 queued: false,
99 99 dismissed: false,
100 100 fade: Fade::shown(Instant::now()),
101 agent: None,
101 102 }
102 103 }
103 104
@@ -98,6 +98,7 @@ mod tests {
98 queued: false,
98 queued: false,
99 dismissed: false,
99 dismissed: false,
100 fade: Fade::shown(Instant::now()),
100 fade: Fade::shown(Instant::now()),
101 agent: None,
101 }
102 }
102 }
103 }
103
104
crates/app/src/notify/toast.rs +9 −1
@@ -8,6 +8,7 @@ use gpui_kit::component::{
8 8 use gpui_kit::prelude::FluentBuilder as _;
9 9 use gpui_kit::*;
10 10
11 use super::agent_toast::agent_toast_content;
11 12 use super::center::NotificationCenter;
12 13 use super::layout::{
13 14 ACTION_BUTTON, AVATAR_GAP, AVATAR_SIZE, MENTION_BORDER, PREVIEW_MAX_LINES, PREVIEW_SIZE,
@@ -477,7 +478,10 @@ impl Render for ToastView {
477 478 .into_any_element();
478 479 };
479 480 let text = describe(&model, preview_on);
480 let narration = text.narration();
481 let narration = model
482 .agent
483 .as_ref()
484 .map_or_else(|| text.narration(), |agent| agent.title.clone());
481 485 if narration != self.last_title {
482 486 window.set_window_title(&narration);
483 487 self.last_title = narration;
@@ -496,6 +500,10 @@ impl Render for ToastView {
496 500 let border_width = if mention { MENTION_BORDER } else { 1. };
497 501 let hovered = model.hovered;
498 502 let content = match model.reply {
503 _ if model.agent.is_some() => {
504 let agent = model.agent.as_ref().expect("checked above");
505 agent_toast_content(&self.center, id, agent, hovered)
506 }
499 507 ReplyState::Sent | ReplyState::Failed => self.confirmation(&model, cx),
500 508 ReplyState::Open => v_flex()
501 509 .w_full()
@@ -8,6 +8,7 @@ use gpui_kit::component::{
8use gpui_kit::prelude::FluentBuilder as _;
8use gpui_kit::prelude::FluentBuilder as _;
9use gpui_kit::*;
9use gpui_kit::*;
10
10
11use super::agent_toast::agent_toast_content;
11use super::center::NotificationCenter;
12use super::center::NotificationCenter;
12use super::layout::{
13use super::layout::{
13 ACTION_BUTTON, AVATAR_GAP, AVATAR_SIZE, MENTION_BORDER, PREVIEW_MAX_LINES, PREVIEW_SIZE,
14 ACTION_BUTTON, AVATAR_GAP, AVATAR_SIZE, MENTION_BORDER, PREVIEW_MAX_LINES, PREVIEW_SIZE,
@@ -477,7 +478,10 @@ impl Render for ToastView {
477 .into_any_element();
478 .into_any_element();
478 };
479 };
479 let text = describe(&model, preview_on);
480 let text = describe(&model, preview_on);
480 let narration = text.narration();
481 let narration = model
482 .agent
483 .as_ref()
484 .map_or_else(|| text.narration(), |agent| agent.title.clone());
481 if narration != self.last_title {
485 if narration != self.last_title {
482 window.set_window_title(&narration);
486 window.set_window_title(&narration);
483 self.last_title = narration;
487 self.last_title = narration;
@@ -496,6 +500,10 @@ impl Render for ToastView {
496 let border_width = if mention { MENTION_BORDER } else { 1. };
500 let border_width = if mention { MENTION_BORDER } else { 1. };
497 let hovered = model.hovered;
501 let hovered = model.hovered;
498 let content = match model.reply {
502 let content = match model.reply {
503 _ if model.agent.is_some() => {
504 let agent = model.agent.as_ref().expect("checked above");
505 agent_toast_content(&self.center, id, agent, hovered)
506 }
499 ReplyState::Sent | ReplyState::Failed => self.confirmation(&model, cx),
507 ReplyState::Sent | ReplyState::Failed => self.confirmation(&model, cx),
500 ReplyState::Open => v_flex()
508 ReplyState::Open => v_flex()
501 .w_full()
509 .w_full()
crates/app/src/views/conversation.rs +110 −2
@@ -31,7 +31,7 @@ use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, wit
31 31 use super::call_controls::header_call_controls;
32 32 use super::channel_tabs::ChannelPane;
33 33 use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
34 use super::message_actions::{Action, MessageMenu, QUICK_REACTION_COUNT};
34 use super::message_actions::{Action, DelegateEntry, MessageMenu, QUICK_REACTION_COUNT};
35 35 use super::message_row::{AVATAR_GAP, AVATAR_SIZE, render_message_row, render_skeleton_row};
36 36 use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};
37 37 use super::post_card::render_post;
@@ -40,6 +40,7 @@ use super::profile_card::opens_profile;
40 40 use super::reaction_picker::{PickHandler, ReactionPicker};
41 41 use super::reaction_pills::{ReactionControls, ReactionPopover};
42 42 use super::widgets::{icon, symbol};
43 use crate::agents::{AgentRun, StartRequest};
43 44 use crate::app_state::{AppEvent, AppState, Selection, selection_title};
44 45 use crate::backend::Engine;
45 46 use crate::card_state::CardScope;
@@ -52,6 +53,7 @@ use crate::image_view_gallery::{ViewerRequest, collect_gallery, position_of};
52 53 use crate::notice::short_error;
53 54 use crate::outbox::{deliver, new_outbox_id, outbox_record, outgoing_of};
54 55 use crate::pending_rows::pending_row;
56 use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
55 57 use crate::people::{local_names, resolve_names};
56 58 use crate::reaction_model::UNKNOWN_REACTOR;
57 59 use crate::read_state::{ReadTrigger, plan_read};
@@ -189,6 +191,8 @@ pub struct ConversationView {
189 191 shared: SharedState,
190 192 demo_library: DemoLibrary,
191 193 new_folder_input: Option<Entity<InputState>>,
194 agent_layouts: HashMap<String, (usize, bool)>,
195 agent_runs: Rc<RefCell<HashMap<String, AgentRun>>>,
192 196 _subscriptions: Vec<Subscription>,
193 197 }
194 198
@@ -423,7 +427,7 @@ impl ConversationView {
423 427 let recent = cx.new(|cx| emoji::Recent::load(&app.read(cx).store));
424 428 let picker = cx.new(|cx| ReactionPicker::new(app.clone(), recent.clone(), window, cx));
425 429 let draft = cx.new(|cx| NewChatDraft::new(app.clone(), window, cx));
426 let subscriptions = vec![
430 let mut subscriptions = vec![
427 431 cx.subscribe_in(&app, window, Self::on_app_event),
428 432 cx.observe(&app, |_, _, cx| cx.notify()),
429 433 cx.subscribe_in(&composer, window, Self::on_composer_event),
@@ -441,6 +445,9 @@ impl ConversationView {
441 445 }
442 446 }),
443 447 ];
448 if let Some(runs) = crate::agents::runs_handle(cx) {
449 subscriptions.push(cx.observe(&runs, |this, _, cx| this.sync_agent_chips(cx)));
450 }
444 451 let mut view = ConversationView {
445 452 app,
446 453 pinned: pinned.is_some(),
@@ -488,6 +495,8 @@ impl ConversationView {
488 495 shared: SharedState::default(),
489 496 demo_library: DemoLibrary::default(),
490 497 new_folder_input: None,
498 agent_layouts: HashMap::new(),
499 agent_runs: Rc::new(RefCell::new(HashMap::new())),
491 500 _subscriptions: subscriptions,
492 501 };
493 502 if let Some(selection) = pinned.or_else(|| view.app.read(cx).selection.clone()) {
@@ -763,6 +772,8 @@ impl ConversationView {
763 772 self.toolbar_hovered = None;
764 773 self.toolbar_pinned = None;
765 774 self.toolbar_suppressed = None;
775 self.agent_layouts.clear();
776 self.agent_runs.borrow_mut().clear();
766 777 let title = selection_title(&self.app.read(cx).sidebar, &selection);
767 778 let mode = match selection {
768 779 Selection::Chat(_) => ViewMode::Flat,
@@ -782,6 +793,7 @@ impl ConversationView {
782 793 first_unread,
783 794 sync: SyncProgress::default(),
784 795 });
796 self.refresh_agent_runs(cx);
785 797 self.sync_generation += 1;
786 798 self.reset_channel_tabs(cx);
787 799 self.reload_pending(cx);
@@ -2665,6 +2677,98 @@ impl ConversationView {
2665 2677 .detach();
2666 2678 }
2667 2679
2680 fn delegate_entries(&self, key: &str, cx: &App) -> (Vec<DelegateEntry>, Option<Action>) {
2681 let (Some(conversation_id), Some(runs)) =
2682 (self.conversation_id(), crate::agents::runs_handle(cx))
2683 else {
2684 return (Vec::new(), None);
2685 };
2686 if key.starts_with(PENDING_KEY_PREFIX) || key.starts_with(SCHEDULED_KEY_PREFIX) {
2687 return (Vec::new(), None);
2688 }
2689 let settings = runs.read(cx).settings();
2690 let entries: Vec<DelegateEntry> = settings
2691 .actions
2692 .iter()
2693 .map(|action| {
2694 let request = StartRequest {
2695 action_id: action.id.clone(),
2696 conversation_id: conversation_id.clone(),
2697 message_id: key.to_owned(),
2698 };
2699 let agent_name = settings
2700 .agents
2701 .iter()
2702 .find(|agent| agent.id == action.agent_id)
2703 .map(|agent| agent.name.clone())
2704 .unwrap_or_default();
2705 DelegateEntry {
2706 label: action.label.clone(),
2707 agent_name,
2708 action: Rc::new(move |_, cx| crate::agents::delegate(request.clone(), cx)),
2709 }
2710 })
2711 .collect();
2712 let manage_agents = (!entries.is_empty())
2713 .then(|| Rc::new(|_: &mut Window, cx: &mut App| crate::agents::open_settings(cx)) as Action);
2714 (entries, manage_agents)
2715 }
2716
2717 fn refresh_agent_runs(&mut self, cx: &App) -> (bool, HashSet<String>) {
2718 let Some(conversation_id) = self.conversation_id() else {
2719 return (false, HashSet::new());
2720 };
2721 let Some(runs) = crate::agents::runs_handle(cx) else {
2722 return (false, HashSet::new());
2723 };
2724 let mut snapshot: HashMap<String, AgentRun> = HashMap::new();
2725 for run in runs.read(cx).for_conversation(&conversation_id) {
2726 snapshot.insert(run.message_id.clone(), run.clone());
2727 }
2728 let layouts: HashMap<String, (usize, bool)> = snapshot
2729 .iter()
2730 .map(|(key, run)| (key.clone(), run.layout_key()))
2731 .collect();
2732 let layout_changed: HashSet<String> = layouts
2733 .iter()
2734 .filter(|(key, layout)| self.agent_layouts.get(*key) != Some(layout))
2735 .map(|(key, _)| key.clone())
2736 .chain(
2737 self.agent_layouts
2738 .keys()
2739 .filter(|key| !layouts.contains_key(*key))
2740 .cloned(),
2741 )
2742 .collect();
2743 self.agent_layouts = layouts;
2744 let snapshot_changed = *self.agent_runs.borrow() != snapshot;
2745 *self.agent_runs.borrow_mut() = snapshot;
2746 (snapshot_changed, layout_changed)
2747 }
2748
2749 fn sync_agent_chips(&mut self, cx: &mut Context<Self>) {
2750 let (snapshot_changed, changed) = self.refresh_agent_runs(cx);
2751 let any_running = self.agent_runs.borrow().values().any(AgentRun::is_running);
2752 if !changed.is_empty() {
2753 let indices: Vec<usize> = self
2754 .rows
2755 .borrow()
2756 .iter()
2757 .enumerate()
2758 .filter(|(_, row)| row.messages().any(|message| changed.contains(&message.key)))
2759 .map(|(index, _)| index)
2760 .collect();
2761 self.scroller.update(cx, |scroller, cx| {
2762 for index in indices {
2763 scroller.remeasure_items(index..index + 1, cx);
2764 }
2765 });
2766 }
2767 if snapshot_changed || any_running {
2768 cx.notify();
2769 }
2770 }
2771
2668 2772 fn message_menu(
2669 2773 &self,
2670 2774 message: &MessageRow,
@@ -2729,6 +2833,7 @@ impl ConversationView {
2729 2833 .as_deref()
2730 2834 .is_some_and(|chat_id| state.is_pinned(chat_id, key));
2731 2835 let in_chat = chat_id.is_some();
2836 let (delegate, manage_agents) = self.delegate_entries(key, cx);
2732 2837 MessageMenu {
2733 2838 key: key.to_owned(),
2734 2839 react,
@@ -2749,6 +2854,8 @@ impl ConversationView {
2749 2854 mark_unread: (in_chat && !own)
2750 2855 .then(|| action(|this, key, _, cx| this.mark_unread_from(key, cx))),
2751 2856 refresh_card,
2857 delegate,
2858 manage_agents,
2752 2859 pin,
2753 2860 hover,
2754 2861 picker: self.picker.clone(),
@@ -3101,6 +3208,7 @@ impl Render for ConversationView {
3101 3208 drafting,
3102 3209 reply_editor: self.reply_root.clone().zip(self.reply_composer.clone()),
3103 3210 timeline: self.timeline_bounds.clone(),
3211 agent_runs: self.agent_runs.clone(),
3104 3212 };
3105 3213 let scroller = MessageScroller::new(
3106 3214 "messages",
@@ -31,7 +31,7 @@ use super::avatar::{member_stack, person_avatar, spec_avatar, square_avatar, wit
31use super::call_controls::header_call_controls;
31use super::call_controls::header_call_controls;
32use super::channel_tabs::ChannelPane;
32use super::channel_tabs::ChannelPane;
33use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
33use super::composer::{Composer, ComposerEvent, EditPreview, Outgoing, ReplyPreview};
34use super::message_actions::{Action, MessageMenu, QUICK_REACTION_COUNT};
34use super::message_actions::{Action, DelegateEntry, MessageMenu, QUICK_REACTION_COUNT};
35use super::message_row::{AVATAR_GAP, AVATAR_SIZE, render_message_row, render_skeleton_row};
35use super::message_row::{AVATAR_GAP, AVATAR_SIZE, render_message_row, render_skeleton_row};
36use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};
36use super::new_chat::{NewChatDraft, NewChatEvent, composer_placeholder, existing_one_on_one};
37use super::post_card::render_post;
37use super::post_card::render_post;
@@ -40,6 +40,7 @@ use super::profile_card::opens_profile;
40use super::reaction_picker::{PickHandler, ReactionPicker};
40use super::reaction_picker::{PickHandler, ReactionPicker};
41use super::reaction_pills::{ReactionControls, ReactionPopover};
41use super::reaction_pills::{ReactionControls, ReactionPopover};
42use super::widgets::{icon, symbol};
42use super::widgets::{icon, symbol};
43use crate::agents::{AgentRun, StartRequest};
43use crate::app_state::{AppEvent, AppState, Selection, selection_title};
44use crate::app_state::{AppEvent, AppState, Selection, selection_title};
44use crate::backend::Engine;
45use crate::backend::Engine;
45use crate::card_state::CardScope;
46use crate::card_state::CardScope;
@@ -52,6 +53,7 @@ use crate::image_view_gallery::{ViewerRequest, collect_gallery, position_of};
52use crate::notice::short_error;
53use crate::notice::short_error;
53use crate::outbox::{deliver, new_outbox_id, outbox_record, outgoing_of};
54use crate::outbox::{deliver, new_outbox_id, outbox_record, outgoing_of};
54use crate::pending_rows::pending_row;
55use crate::pending_rows::pending_row;
56use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
55use crate::people::{local_names, resolve_names};
57use crate::people::{local_names, resolve_names};
56use crate::reaction_model::UNKNOWN_REACTOR;
58use crate::reaction_model::UNKNOWN_REACTOR;
57use crate::read_state::{ReadTrigger, plan_read};
59use crate::read_state::{ReadTrigger, plan_read};
@@ -189,6 +191,8 @@ pub struct ConversationView {
189 shared: SharedState,
191 shared: SharedState,
190 demo_library: DemoLibrary,
192 demo_library: DemoLibrary,
191 new_folder_input: Option<Entity<InputState>>,
193 new_folder_input: Option<Entity<InputState>>,
194 agent_layouts: HashMap<String, (usize, bool)>,
195 agent_runs: Rc<RefCell<HashMap<String, AgentRun>>>,
192 _subscriptions: Vec<Subscription>,
196 _subscriptions: Vec<Subscription>,
193}
197}
194
198
@@ -423,7 +427,7 @@ impl ConversationView {
423 let recent = cx.new(|cx| emoji::Recent::load(&app.read(cx).store));
427 let recent = cx.new(|cx| emoji::Recent::load(&app.read(cx).store));
424 let picker = cx.new(|cx| ReactionPicker::new(app.clone(), recent.clone(), window, cx));
428 let picker = cx.new(|cx| ReactionPicker::new(app.clone(), recent.clone(), window, cx));
425 let draft = cx.new(|cx| NewChatDraft::new(app.clone(), window, cx));
429 let draft = cx.new(|cx| NewChatDraft::new(app.clone(), window, cx));
426 let subscriptions = vec![
430 let mut subscriptions = vec![
427 cx.subscribe_in(&app, window, Self::on_app_event),
431 cx.subscribe_in(&app, window, Self::on_app_event),
428 cx.observe(&app, |_, _, cx| cx.notify()),
432 cx.observe(&app, |_, _, cx| cx.notify()),
429 cx.subscribe_in(&composer, window, Self::on_composer_event),
433 cx.subscribe_in(&composer, window, Self::on_composer_event),
@@ -441,6 +445,9 @@ impl ConversationView {
441 }
445 }
442 }),
446 }),
443 ];
447 ];
448 if let Some(runs) = crate::agents::runs_handle(cx) {
449 subscriptions.push(cx.observe(&runs, |this, _, cx| this.sync_agent_chips(cx)));
450 }
444 let mut view = ConversationView {
451 let mut view = ConversationView {
445 app,
452 app,
446 pinned: pinned.is_some(),
453 pinned: pinned.is_some(),
@@ -488,6 +495,8 @@ impl ConversationView {
488 shared: SharedState::default(),
495 shared: SharedState::default(),
489 demo_library: DemoLibrary::default(),
496 demo_library: DemoLibrary::default(),
490 new_folder_input: None,
497 new_folder_input: None,
498 agent_layouts: HashMap::new(),
499 agent_runs: Rc::new(RefCell::new(HashMap::new())),
491 _subscriptions: subscriptions,
500 _subscriptions: subscriptions,
492 };
501 };
493 if let Some(selection) = pinned.or_else(|| view.app.read(cx).selection.clone()) {
502 if let Some(selection) = pinned.or_else(|| view.app.read(cx).selection.clone()) {
@@ -763,6 +772,8 @@ impl ConversationView {
763 self.toolbar_hovered = None;
772 self.toolbar_hovered = None;
764 self.toolbar_pinned = None;
773 self.toolbar_pinned = None;
765 self.toolbar_suppressed = None;
774 self.toolbar_suppressed = None;
775 self.agent_layouts.clear();
776 self.agent_runs.borrow_mut().clear();
766 let title = selection_title(&self.app.read(cx).sidebar, &selection);
777 let title = selection_title(&self.app.read(cx).sidebar, &selection);
767 let mode = match selection {
778 let mode = match selection {
768 Selection::Chat(_) => ViewMode::Flat,
779 Selection::Chat(_) => ViewMode::Flat,
@@ -782,6 +793,7 @@ impl ConversationView {
782 first_unread,
793 first_unread,
783 sync: SyncProgress::default(),
794 sync: SyncProgress::default(),
784 });
795 });
796 self.refresh_agent_runs(cx);
785 self.sync_generation += 1;
797 self.sync_generation += 1;
786 self.reset_channel_tabs(cx);
798 self.reset_channel_tabs(cx);
787 self.reload_pending(cx);
799 self.reload_pending(cx);
@@ -2665,6 +2677,98 @@ impl ConversationView {
2665 .detach();
2677 .detach();
2666 }
2678 }
2667
2679
2680 fn delegate_entries(&self, key: &str, cx: &App) -> (Vec<DelegateEntry>, Option<Action>) {
2681 let (Some(conversation_id), Some(runs)) =
2682 (self.conversation_id(), crate::agents::runs_handle(cx))
2683 else {
2684 return (Vec::new(), None);
2685 };
2686 if key.starts_with(PENDING_KEY_PREFIX) || key.starts_with(SCHEDULED_KEY_PREFIX) {
2687 return (Vec::new(), None);
2688 }
2689 let settings = runs.read(cx).settings();
2690 let entries: Vec<DelegateEntry> = settings
2691 .actions
2692 .iter()
2693 .map(|action| {
2694 let request = StartRequest {
2695 action_id: action.id.clone(),
2696 conversation_id: conversation_id.clone(),
2697 message_id: key.to_owned(),
2698 };
2699 let agent_name = settings
2700 .agents
2701 .iter()
2702 .find(|agent| agent.id == action.agent_id)
2703 .map(|agent| agent.name.clone())
2704 .unwrap_or_default();
2705 DelegateEntry {
2706 label: action.label.clone(),
2707 agent_name,
2708 action: Rc::new(move |_, cx| crate::agents::delegate(request.clone(), cx)),
2709 }
2710 })
2711 .collect();
2712 let manage_agents = (!entries.is_empty())
2713 .then(|| Rc::new(|_: &mut Window, cx: &mut App| crate::agents::open_settings(cx)) as Action);
2714 (entries, manage_agents)
2715 }
2716
2717 fn refresh_agent_runs(&mut self, cx: &App) -> (bool, HashSet<String>) {
2718 let Some(conversation_id) = self.conversation_id() else {
2719 return (false, HashSet::new());
2720 };
2721 let Some(runs) = crate::agents::runs_handle(cx) else {
2722 return (false, HashSet::new());
2723 };
2724 let mut snapshot: HashMap<String, AgentRun> = HashMap::new();
2725 for run in runs.read(cx).for_conversation(&conversation_id) {
2726 snapshot.insert(run.message_id.clone(), run.clone());
2727 }
2728 let layouts: HashMap<String, (usize, bool)> = snapshot
2729 .iter()
2730 .map(|(key, run)| (key.clone(), run.layout_key()))
2731 .collect();
2732 let layout_changed: HashSet<String> = layouts
2733 .iter()
2734 .filter(|(key, layout)| self.agent_layouts.get(*key) != Some(layout))
2735 .map(|(key, _)| key.clone())
2736 .chain(
2737 self.agent_layouts
2738 .keys()
2739 .filter(|key| !layouts.contains_key(*key))
2740 .cloned(),
2741 )
2742 .collect();
2743 self.agent_layouts = layouts;
2744 let snapshot_changed = *self.agent_runs.borrow() != snapshot;
2745 *self.agent_runs.borrow_mut() = snapshot;
2746 (snapshot_changed, layout_changed)
2747 }
2748
2749 fn sync_agent_chips(&mut self, cx: &mut Context<Self>) {
2750 let (snapshot_changed, changed) = self.refresh_agent_runs(cx);
2751 let any_running = self.agent_runs.borrow().values().any(AgentRun::is_running);
2752 if !changed.is_empty() {
2753 let indices: Vec<usize> = self
2754 .rows
2755 .borrow()
2756 .iter()
2757 .enumerate()
2758 .filter(|(_, row)| row.messages().any(|message| changed.contains(&message.key)))
2759 .map(|(index, _)| index)
2760 .collect();
2761 self.scroller.update(cx, |scroller, cx| {
2762 for index in indices {
2763 scroller.remeasure_items(index..index + 1, cx);
2764 }
2765 });
2766 }
2767 if snapshot_changed || any_running {
2768 cx.notify();
2769 }
2770 }
2771
2668 fn message_menu(
2772 fn message_menu(
2669 &self,
2773 &self,
2670 message: &MessageRow,
2774 message: &MessageRow,
@@ -2729,6 +2833,7 @@ impl ConversationView {
2729 .as_deref()
2833 .as_deref()
2730 .is_some_and(|chat_id| state.is_pinned(chat_id, key));
2834 .is_some_and(|chat_id| state.is_pinned(chat_id, key));
2731 let in_chat = chat_id.is_some();
2835 let in_chat = chat_id.is_some();
2836 let (delegate, manage_agents) = self.delegate_entries(key, cx);
2732 MessageMenu {
2837 MessageMenu {
2733 key: key.to_owned(),
2838 key: key.to_owned(),
2734 react,
2839 react,
@@ -2749,6 +2854,8 @@ impl ConversationView {
2749 mark_unread: (in_chat && !own)
2854 mark_unread: (in_chat && !own)
2750 .then(|| action(|this, key, _, cx| this.mark_unread_from(key, cx))),
2855 .then(|| action(|this, key, _, cx| this.mark_unread_from(key, cx))),
2751 refresh_card,
2856 refresh_card,
2857 delegate,
2858 manage_agents,
2752 pin,
2859 pin,
2753 hover,
2860 hover,
2754 picker: self.picker.clone(),
2861 picker: self.picker.clone(),
@@ -3101,6 +3208,7 @@ impl Render for ConversationView {
3101 drafting,
3208 drafting,
3102 reply_editor: self.reply_root.clone().zip(self.reply_composer.clone()),
3209 reply_editor: self.reply_root.clone().zip(self.reply_composer.clone()),
3103 timeline: self.timeline_bounds.clone(),
3210 timeline: self.timeline_bounds.clone(),
3211 agent_runs: self.agent_runs.clone(),
3104 };
3212 };
3105 let scroller = MessageScroller::new(
3213 let scroller = MessageScroller::new(
3106 "messages",
3214 "messages",
crates/app/src/views/conversation/proposal.rs +1 −1
@@ -38,7 +38,7 @@ impl ConversationView {
38 38 edit: action(Self::edit_proposal),
39 39 discard: action(Self::discard_proposal),
40 40 };
41 Some(proposal_card::render(&entry, quote, actions, Utc::now()).into_any_element())
41 Some(proposal_card::render(&entry, quote, actions, Utc::now(), cx).into_any_element())
42 42 }
43 43
44 44 pub(super) fn report_composer_activity(&self, event: &ComposerEvent, cx: &App) {
@@ -38,7 +38,7 @@ impl ConversationView {
38 edit: action(Self::edit_proposal),
38 edit: action(Self::edit_proposal),
39 discard: action(Self::discard_proposal),
39 discard: action(Self::discard_proposal),
40 };
40 };
41 Some(proposal_card::render(&entry, quote, actions, Utc::now()).into_any_element())
41 Some(proposal_card::render(&entry, quote, actions, Utc::now(), cx).into_any_element())
42 }
42 }
43
43
44 pub(super) fn report_composer_activity(&self, event: &ComposerEvent, cx: &App) {
44 pub(super) fn report_composer_activity(&self, event: &ComposerEvent, cx: &App) {
crates/app/src/views/conversation/render_env.rs +8 −0
@@ -1,3 +1,5 @@
1 use std::cell::RefCell;
2 use std::collections::HashMap;
1 3 use std::rc::Rc;
2 4
3 5 use gpui_kit::component::{
@@ -8,6 +10,7 @@ use gpui_kit::*;
8 10 use teams_core::{ImageRef, LinkPreview};
9 11
10 12 use super::{ConversationView, HoverSlot, PENDING_KEY_PREFIX};
13 use crate::agents::AgentRun;
11 14 use crate::app_state::AppState;
12 15 use crate::rows::{Delivery, MessageRow, PostRow};
13 16 use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
@@ -27,6 +30,7 @@ pub(super) struct RenderEnv {
27 30 pub drafting: bool,
28 31 pub reply_editor: Option<(String, Entity<Composer>)>,
29 32 pub timeline: TimelineBounds,
33 pub agent_runs: Rc<RefCell<HashMap<String, AgentRun>>>,
30 34 }
31 35
32 36 fn boxed(action: impl Fn(&mut App) + 'static) -> Box<dyn Fn(&mut App)> {
@@ -204,6 +208,9 @@ impl RenderEnv {
204 208 }) as ImageOpen
205 209 });
206 210 let bot = self.bot_identity(message, cx);
211 let actionable_run = (is_real && !message.deleted)
212 .then(|| self.agent_runs.borrow().get(&message.key).cloned())
213 .flatten();
207 214 let translation = (is_real && !message.deleted)
208 215 .then(|| self.translation_actions(message))
209 216 .flatten();
@@ -240,6 +247,7 @@ impl RenderEnv {
240 247 .is_saved(&message.conversation_id, &message.key),
241 248 translation,
242 249 timeline: self.timeline.clone(),
250 agent_run: actionable_run,
243 251 }
244 252 }
245 253
@@ -1,3 +1,5 @@
1use std::cell::RefCell;
2use std::collections::HashMap;
1use std::rc::Rc;
3use std::rc::Rc;
2
4
3use gpui_kit::component::{
5use gpui_kit::component::{
@@ -8,6 +10,7 @@ use gpui_kit::*;
8use teams_core::{ImageRef, LinkPreview};
10use teams_core::{ImageRef, LinkPreview};
9
11
10use super::{ConversationView, HoverSlot, PENDING_KEY_PREFIX};
12use super::{ConversationView, HoverSlot, PENDING_KEY_PREFIX};
13use crate::agents::AgentRun;
11use crate::app_state::AppState;
14use crate::app_state::AppState;
12use crate::rows::{Delivery, MessageRow, PostRow};
15use crate::rows::{Delivery, MessageRow, PostRow};
13use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
16use crate::scheduled_rows::SCHEDULED_KEY_PREFIX;
@@ -27,6 +30,7 @@ pub(super) struct RenderEnv {
27 pub drafting: bool,
30 pub drafting: bool,
28 pub reply_editor: Option<(String, Entity<Composer>)>,
31 pub reply_editor: Option<(String, Entity<Composer>)>,
29 pub timeline: TimelineBounds,
32 pub timeline: TimelineBounds,
33 pub agent_runs: Rc<RefCell<HashMap<String, AgentRun>>>,
30}
34}
31
35
32fn boxed(action: impl Fn(&mut App) + 'static) -> Box<dyn Fn(&mut App)> {
36fn boxed(action: impl Fn(&mut App) + 'static) -> Box<dyn Fn(&mut App)> {
@@ -204,6 +208,9 @@ impl RenderEnv {
204 }) as ImageOpen
208 }) as ImageOpen
205 });
209 });
206 let bot = self.bot_identity(message, cx);
210 let bot = self.bot_identity(message, cx);
211 let actionable_run = (is_real && !message.deleted)
212 .then(|| self.agent_runs.borrow().get(&message.key).cloned())
213 .flatten();
207 let translation = (is_real && !message.deleted)
214 let translation = (is_real && !message.deleted)
208 .then(|| self.translation_actions(message))
215 .then(|| self.translation_actions(message))
209 .flatten();
216 .flatten();
@@ -240,6 +247,7 @@ impl RenderEnv {
240 .is_saved(&message.conversation_id, &message.key),
247 .is_saved(&message.conversation_id, &message.key),
241 translation,
248 translation,
242 timeline: self.timeline.clone(),
249 timeline: self.timeline.clone(),
250 agent_run: actionable_run,
243 }
251 }
244 }
252 }
245
253
crates/app/src/views/message_actions.rs +81 −4
@@ -20,13 +20,22 @@ use crate::theme;
20 20
21 21 const BAR_BUTTON: f32 = 30.;
22 22 const BAR_PADDING: f32 = 3.;
23 const BAR_GROUP_GAP: f32 = 6.;
23 const BAR_ICON: f32 = 16.;
24 const DELEGATE_ITEM_WIDTH: f32 = 188.;
25 const DELEGATE_AGENT_SIZE: f32 = 11.;
24 26 pub const QUICK_REACTION_COUNT: usize = 4;
25 27
26 28 pub type Action = Rc<dyn Fn(&mut Window, &mut App)>;
27 29 pub type OpenChange = Rc<dyn Fn(bool, &mut Window, &mut App)>;
28 30 pub type HoverChange = Rc<dyn Fn(bool, &mut App)>;
29 31
32 #[derive(Clone)]
33 pub struct DelegateEntry {
34 pub label: String,
35 pub agent_name: String,
36 pub action: Action,
37 }
38
30 39 pub struct MessageMenu {
31 40 pub key: String,
32 41 pub react: PickHandler,
@@ -44,6 +53,8 @@ pub struct MessageMenu {
44 53 pub delete: Option<Action>,
45 54 pub mark_unread: Option<Action>,
46 55 pub refresh_card: Option<Action>,
56 pub delegate: Vec<DelegateEntry>,
57 pub manage_agents: Option<Action>,
47 58 pub pin: OpenChange,
48 59 pub hover: HoverChange,
49 60 pub picker: Entity<ReactionPicker>,
@@ -103,7 +114,7 @@ fn picker_button(menu: &MessageMenu, cx: &App) -> AnyElement {
103 114 .anchor(Anchor::TopRight)
104 115 .trigger(
105 116 Button::new(element_id("add-reaction", &menu.key))
106 .child(icon(IconName::Plus, 16., theme::text_soft()))
117 .child(icon(IconName::Plus, BAR_ICON, theme::text_soft()))
107 118 .custom(bar_variant(cx))
108 119 .rounded(px(7.))
109 120 .size(px(BAR_BUTTON)),
@@ -154,7 +165,7 @@ fn more_button(menu: &MessageMenu, cx: &App) -> AnyElement {
154 165 );
155 166 let (saved, pinned, translate_label) = (menu.saved, menu.pinned, menu.translate_label);
156 167 Button::new(element_id("message-more", &menu.key))
157 .child(icon(IconName::Ellipsis, 16., theme::text_soft()))
168 .child(icon(IconName::Ellipsis, BAR_ICON, theme::text_soft()))
158 169 .custom(bar_variant(cx))
159 170 .rounded(px(7.))
160 171 .size(px(BAR_BUTTON))
@@ -213,6 +224,63 @@ fn more_button(menu: &MessageMenu, cx: &App) -> AnyElement {
213 224 .into_any_element()
214 225 }
215 226
227 fn delegate_item(entry: &DelegateEntry) -> PopupMenuItem {
228 let (label, agent_name, action) = (
229 entry.label.clone(),
230 entry.agent_name.clone(),
231 entry.action.clone(),
232 );
233 PopupMenuItem::element(move |_, _| {
234 h_flex()
235 .w(px(DELEGATE_ITEM_WIDTH))
236 .gap(px(12.))
237 .items_center()
238 .justify_between()
239 .child(div().flex_1().min_w_0().truncate().child(label.clone()))
240 .child(
241 div()
242 .flex_none()
243 .text_size(px(DELEGATE_AGENT_SIZE))
244 .text_color(theme::text_faint())
245 .child(agent_name.clone()),
246 )
247 })
248 .icon(IconName::Bot)
249 .on_click(move |_, window, cx| action(window, cx))
250 }
251
252 fn delegate_button(menu: &MessageMenu, cx: &App) -> AnyElement {
253 let (entries, manage_agents, pin) = (
254 menu.delegate.clone(),
255 menu.manage_agents.clone(),
256 menu.pin.clone(),
257 );
258 Button::new(element_id("message-delegate", &menu.key))
259 .child(icon(IconName::Bot, BAR_ICON, theme::text_soft()))
260 .custom(bar_variant(cx))
261 .rounded(px(7.))
262 .size(px(BAR_BUTTON))
263 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, _, _| {
264 let mut popup = popup;
265 for entry in &entries {
266 popup = popup.item(delegate_item(entry));
267 }
268 if let Some(manage_agents) = manage_agents.clone() {
269 popup = popup.separator().item(
270 PopupMenuItem::element(|_, _| {
271 div()
272 .text_color(theme::text_muted())
273 .child("Manage actions...")
274 })
275 .on_click(move |_, window, cx| manage_agents(window, cx)),
276 );
277 }
278 popup
279 })
280 .on_open_change(move |open, window, cx| pin(*open, window, cx))
281 .into_any_element()
282 }
283
216 284 pub fn message_toolbar(menu: MessageMenu, cx: &App) -> AnyElement {
217 285 let hover = menu.hover.clone();
218 286 let mut children: Vec<AnyElement> = menu
@@ -223,7 +291,13 @@ pub fn message_toolbar(menu: MessageMenu, cx: &App) -> AnyElement {
223 291 .collect();
224 292 children.push(picker_button(&menu, cx));
225 293 children.push(
226 div().w(px(BAR_GROUP_GAP)).into_any_element(),
294 div()
295 .w(px(1.))
296 .h(px(16.))
297 .mx(px(4.))
298 .flex_none()
299 .bg(theme::popup_hover())
300 .into_any_element(),
227 301 );
228 302 if let Some(reply) = menu.reply.clone() {
229 303 children.push(
@@ -236,6 +310,9 @@ pub fn message_toolbar(menu: MessageMenu, cx: &App) -> AnyElement {
236 310 .into_any_element(),
237 311 );
238 312 }
313 if !menu.delegate.is_empty() {
314 children.push(delegate_button(&menu, cx));
315 }
239 316 children.push(more_button(&menu, cx));
240 317 let bar = h_flex()
241 318 .h(px(TOOLBAR_HEIGHT))
@@ -20,13 +20,22 @@ use crate::theme;
20
20
21const BAR_BUTTON: f32 = 30.;
21const BAR_BUTTON: f32 = 30.;
22const BAR_PADDING: f32 = 3.;
22const BAR_PADDING: f32 = 3.;
23const BAR_GROUP_GAP: f32 = 6.;
23const BAR_ICON: f32 = 16.;
24const DELEGATE_ITEM_WIDTH: f32 = 188.;
25const DELEGATE_AGENT_SIZE: f32 = 11.;
24pub const QUICK_REACTION_COUNT: usize = 4;
26pub const QUICK_REACTION_COUNT: usize = 4;
25
27
26pub type Action = Rc<dyn Fn(&mut Window, &mut App)>;
28pub type Action = Rc<dyn Fn(&mut Window, &mut App)>;
27pub type OpenChange = Rc<dyn Fn(bool, &mut Window, &mut App)>;
29pub type OpenChange = Rc<dyn Fn(bool, &mut Window, &mut App)>;
28pub type HoverChange = Rc<dyn Fn(bool, &mut App)>;
30pub type HoverChange = Rc<dyn Fn(bool, &mut App)>;
29
31
32#[derive(Clone)]
33pub struct DelegateEntry {
34 pub label: String,
35 pub agent_name: String,
36 pub action: Action,
37}
38
30pub struct MessageMenu {
39pub struct MessageMenu {
31 pub key: String,
40 pub key: String,
32 pub react: PickHandler,
41 pub react: PickHandler,
@@ -44,6 +53,8 @@ pub struct MessageMenu {
44 pub delete: Option<Action>,
53 pub delete: Option<Action>,
45 pub mark_unread: Option<Action>,
54 pub mark_unread: Option<Action>,
46 pub refresh_card: Option<Action>,
55 pub refresh_card: Option<Action>,
56 pub delegate: Vec<DelegateEntry>,
57 pub manage_agents: Option<Action>,
47 pub pin: OpenChange,
58 pub pin: OpenChange,
48 pub hover: HoverChange,
59 pub hover: HoverChange,
49 pub picker: Entity<ReactionPicker>,
60 pub picker: Entity<ReactionPicker>,
@@ -103,7 +114,7 @@ fn picker_button(menu: &MessageMenu, cx: &App) -> AnyElement {
103 .anchor(Anchor::TopRight)
114 .anchor(Anchor::TopRight)
104 .trigger(
115 .trigger(
105 Button::new(element_id("add-reaction", &menu.key))
116 Button::new(element_id("add-reaction", &menu.key))
106 .child(icon(IconName::Plus, 16., theme::text_soft()))
117 .child(icon(IconName::Plus, BAR_ICON, theme::text_soft()))
107 .custom(bar_variant(cx))
118 .custom(bar_variant(cx))
108 .rounded(px(7.))
119 .rounded(px(7.))
109 .size(px(BAR_BUTTON)),
120 .size(px(BAR_BUTTON)),
@@ -154,7 +165,7 @@ fn more_button(menu: &MessageMenu, cx: &App) -> AnyElement {
154 );
165 );
155 let (saved, pinned, translate_label) = (menu.saved, menu.pinned, menu.translate_label);
166 let (saved, pinned, translate_label) = (menu.saved, menu.pinned, menu.translate_label);
156 Button::new(element_id("message-more", &menu.key))
167 Button::new(element_id("message-more", &menu.key))
157 .child(icon(IconName::Ellipsis, 16., theme::text_soft()))
168 .child(icon(IconName::Ellipsis, BAR_ICON, theme::text_soft()))
158 .custom(bar_variant(cx))
169 .custom(bar_variant(cx))
159 .rounded(px(7.))
170 .rounded(px(7.))
160 .size(px(BAR_BUTTON))
171 .size(px(BAR_BUTTON))
@@ -213,6 +224,63 @@ fn more_button(menu: &MessageMenu, cx: &App) -> AnyElement {
213 .into_any_element()
224 .into_any_element()
214}
225}
215
226
227fn delegate_item(entry: &DelegateEntry) -> PopupMenuItem {
228 let (label, agent_name, action) = (
229 entry.label.clone(),
230 entry.agent_name.clone(),
231 entry.action.clone(),
232 );
233 PopupMenuItem::element(move |_, _| {
234 h_flex()
235 .w(px(DELEGATE_ITEM_WIDTH))
236 .gap(px(12.))
237 .items_center()
238 .justify_between()
239 .child(div().flex_1().min_w_0().truncate().child(label.clone()))
240 .child(
241 div()
242 .flex_none()
243 .text_size(px(DELEGATE_AGENT_SIZE))
244 .text_color(theme::text_faint())
245 .child(agent_name.clone()),
246 )
247 })
248 .icon(IconName::Bot)
249 .on_click(move |_, window, cx| action(window, cx))
250}
251
252fn delegate_button(menu: &MessageMenu, cx: &App) -> AnyElement {
253 let (entries, manage_agents, pin) = (
254 menu.delegate.clone(),
255 menu.manage_agents.clone(),
256 menu.pin.clone(),
257 );
258 Button::new(element_id("message-delegate", &menu.key))
259 .child(icon(IconName::Bot, BAR_ICON, theme::text_soft()))
260 .custom(bar_variant(cx))
261 .rounded(px(7.))
262 .size(px(BAR_BUTTON))
263 .dropdown_menu_with_anchor(Anchor::TopRight, move |popup, _, _| {
264 let mut popup = popup;
265 for entry in &entries {
266 popup = popup.item(delegate_item(entry));
267 }
268 if let Some(manage_agents) = manage_agents.clone() {
269 popup = popup.separator().item(
270 PopupMenuItem::element(|_, _| {
271 div()
272 .text_color(theme::text_muted())
273 .child("Manage actions...")
274 })
275 .on_click(move |_, window, cx| manage_agents(window, cx)),
276 );
277 }
278 popup
279 })
280 .on_open_change(move |open, window, cx| pin(*open, window, cx))
281 .into_any_element()
282}
283
216pub fn message_toolbar(menu: MessageMenu, cx: &App) -> AnyElement {
284pub fn message_toolbar(menu: MessageMenu, cx: &App) -> AnyElement {
217 let hover = menu.hover.clone();
285 let hover = menu.hover.clone();
218 let mut children: Vec<AnyElement> = menu
286 let mut children: Vec<AnyElement> = menu
@@ -223,7 +291,13 @@ pub fn message_toolbar(menu: MessageMenu, cx: &App) -> AnyElement {
223 .collect();
291 .collect();
224 children.push(picker_button(&menu, cx));
292 children.push(picker_button(&menu, cx));
225 children.push(
293 children.push(
226 div().w(px(BAR_GROUP_GAP)).into_any_element(),
294 div()
295 .w(px(1.))
296 .h(px(16.))
297 .mx(px(4.))
298 .flex_none()
299 .bg(theme::popup_hover())
300 .into_any_element(),
227 );
301 );
228 if let Some(reply) = menu.reply.clone() {
302 if let Some(reply) = menu.reply.clone() {
229 children.push(
303 children.push(
@@ -236,6 +310,9 @@ pub fn message_toolbar(menu: MessageMenu, cx: &App) -> AnyElement {
236 .into_any_element(),
310 .into_any_element(),
237 );
311 );
238 }
312 }
313 if !menu.delegate.is_empty() {
314 children.push(delegate_button(&menu, cx));
315 }
239 children.push(more_button(&menu, cx));
316 children.push(more_button(&menu, cx));
240 let bar = h_flex()
317 let bar = h_flex()
241 .h(px(TOOLBAR_HEIGHT))
318 .h(px(TOOLBAR_HEIGHT))
crates/app/src/views/message_row.rs +13 −0
@@ -16,6 +16,7 @@ use super::scheduled_toolbar::{ScheduledMenu, scheduled_toolbar};
16 16 use super::toolbar_placement::{TimelineBounds, placed_toolbar};
17 17 use super::translation_line::{TranslationActions, translation_line};
18 18 use super::widgets::{icon, symbol};
19 use crate::agents::{AgentRun, run_chip};
19 20 use crate::card_state::BotIdentity;
20 21 use crate::data::Directory;
21 22 use crate::render::Block;
@@ -60,6 +61,7 @@ pub struct RowActions {
60 61 pub saved: bool,
61 62 pub translation: Option<TranslationActions>,
62 63 pub timeline: TimelineBounds,
64 pub agent_run: Option<AgentRun>,
63 65 }
64 66
65 67 const TOOLBAR_RIGHT_INSET: f32 = 0.;
@@ -264,6 +266,11 @@ struct BubbleExtras {
264 266 saved: bool,
265 267 translation: Option<TranslationActions>,
266 268 timeline: TimelineBounds,
269 agent_run: Option<AgentRun>,
270 }
271
272 fn agent_chip(run: Option<AgentRun>) -> Option<Div> {
273 run.map(|run| div().pt(px(2.)).child(run_chip(&run, theme::row_hover())))
267 274 }
268 275
269 276 pub(super) fn forwarded_header() -> Div {
@@ -470,6 +477,7 @@ fn others_row(
470 477 cx: &App,
471 478 ) -> Div {
472 479 let translation = extras.translation.take();
480 let agent_run = extras.agent_run.take();
473 481 let first = !row.series.has_prev;
474 482 let author = bot.map_or_else(|| row.author.clone(), |bot| bot.name.clone());
475 483 let profile_user = row.sender_id.as_deref().filter(|_| bot.is_none());
@@ -492,6 +500,7 @@ fn others_row(
492 500 );
493 501 }
494 502 column = column.child(bubble(row, index, false, directory, extras, cx));
503 column = column.children(agent_chip(agent_run));
495 504 column = column.children(translation_line(row, index, translation.as_ref()));
496 505 if let Some(note) = delivery_note(row, delivery, index) {
497 506 column = column.child(note);
@@ -533,12 +542,14 @@ fn own_row(
533 542 cx: &App,
534 543 ) -> Div {
535 544 let translation = extras.translation.take();
545 let agent_run = extras.agent_run.take();
536 546 let mut column = v_flex().w_full().items_end().gap(px(2.));
537 547 column = column.child(
538 548 div()
539 549 .max_w(relative(MAX_WIDTH_RATIO))
540 550 .child(bubble(row, index, true, directory, extras, cx)),
541 551 );
552 column = column.children(agent_chip(agent_run));
542 553 column = column.children(translation_line(row, index, translation.as_ref()));
543 554 if let Some(note) = delivery_note(row, delivery, index) {
544 555 column = column.child(note);
@@ -568,6 +579,7 @@ pub fn render_message_row(
568 579 saved,
569 580 translation,
570 581 timeline,
582 agent_run,
571 583 } = actions;
572 584 let extras = BubbleExtras {
573 585 hover: hovered,
@@ -580,6 +592,7 @@ pub fn render_message_row(
580 592 saved,
581 593 translation,
582 594 timeline,
595 agent_run,
583 596 };
584 597 let own = row.own;
585 598 let spacing = if row.series.has_prev {
@@ -16,6 +16,7 @@ use super::scheduled_toolbar::{ScheduledMenu, scheduled_toolbar};
16use super::toolbar_placement::{TimelineBounds, placed_toolbar};
16use super::toolbar_placement::{TimelineBounds, placed_toolbar};
17use super::translation_line::{TranslationActions, translation_line};
17use super::translation_line::{TranslationActions, translation_line};
18use super::widgets::{icon, symbol};
18use super::widgets::{icon, symbol};
19use crate::agents::{AgentRun, run_chip};
19use crate::card_state::BotIdentity;
20use crate::card_state::BotIdentity;
20use crate::data::Directory;
21use crate::data::Directory;
21use crate::render::Block;
22use crate::render::Block;
@@ -60,6 +61,7 @@ pub struct RowActions {
60 pub saved: bool,
61 pub saved: bool,
61 pub translation: Option<TranslationActions>,
62 pub translation: Option<TranslationActions>,
62 pub timeline: TimelineBounds,
63 pub timeline: TimelineBounds,
64 pub agent_run: Option<AgentRun>,
63}
65}
64
66
65const TOOLBAR_RIGHT_INSET: f32 = 0.;
67const TOOLBAR_RIGHT_INSET: f32 = 0.;
@@ -264,6 +266,11 @@ struct BubbleExtras {
264 saved: bool,
266 saved: bool,
265 translation: Option<TranslationActions>,
267 translation: Option<TranslationActions>,
266 timeline: TimelineBounds,
268 timeline: TimelineBounds,
269 agent_run: Option<AgentRun>,
270}
271
272fn agent_chip(run: Option<AgentRun>) -> Option<Div> {
273 run.map(|run| div().pt(px(2.)).child(run_chip(&run, theme::row_hover())))
267}
274}
268
275
269pub(super) fn forwarded_header() -> Div {
276pub(super) fn forwarded_header() -> Div {
@@ -470,6 +477,7 @@ fn others_row(
470 cx: &App,
477 cx: &App,
471) -> Div {
478) -> Div {
472 let translation = extras.translation.take();
479 let translation = extras.translation.take();
480 let agent_run = extras.agent_run.take();
473 let first = !row.series.has_prev;
481 let first = !row.series.has_prev;
474 let author = bot.map_or_else(|| row.author.clone(), |bot| bot.name.clone());
482 let author = bot.map_or_else(|| row.author.clone(), |bot| bot.name.clone());
475 let profile_user = row.sender_id.as_deref().filter(|_| bot.is_none());
483 let profile_user = row.sender_id.as_deref().filter(|_| bot.is_none());
@@ -492,6 +500,7 @@ fn others_row(
492 );
500 );
493 }
501 }
494 column = column.child(bubble(row, index, false, directory, extras, cx));
502 column = column.child(bubble(row, index, false, directory, extras, cx));
503 column = column.children(agent_chip(agent_run));
495 column = column.children(translation_line(row, index, translation.as_ref()));
504 column = column.children(translation_line(row, index, translation.as_ref()));
496 if let Some(note) = delivery_note(row, delivery, index) {
505 if let Some(note) = delivery_note(row, delivery, index) {
497 column = column.child(note);
506 column = column.child(note);
@@ -533,12 +542,14 @@ fn own_row(
533 cx: &App,
542 cx: &App,
534) -> Div {
543) -> Div {
535 let translation = extras.translation.take();
544 let translation = extras.translation.take();
545 let agent_run = extras.agent_run.take();
536 let mut column = v_flex().w_full().items_end().gap(px(2.));
546 let mut column = v_flex().w_full().items_end().gap(px(2.));
537 column = column.child(
547 column = column.child(
538 div()
548 div()
539 .max_w(relative(MAX_WIDTH_RATIO))
549 .max_w(relative(MAX_WIDTH_RATIO))
540 .child(bubble(row, index, true, directory, extras, cx)),
550 .child(bubble(row, index, true, directory, extras, cx)),
541 );
551 );
552 column = column.children(agent_chip(agent_run));
542 column = column.children(translation_line(row, index, translation.as_ref()));
553 column = column.children(translation_line(row, index, translation.as_ref()));
543 if let Some(note) = delivery_note(row, delivery, index) {
554 if let Some(note) = delivery_note(row, delivery, index) {
544 column = column.child(note);
555 column = column.child(note);
@@ -568,6 +579,7 @@ pub fn render_message_row(
568 saved,
579 saved,
569 translation,
580 translation,
570 timeline,
581 timeline,
582 agent_run,
571 } = actions;
583 } = actions;
572 let extras = BubbleExtras {
584 let extras = BubbleExtras {
573 hover: hovered,
585 hover: hovered,
@@ -580,6 +592,7 @@ pub fn render_message_row(
580 saved,
592 saved,
581 translation,
593 translation,
582 timeline,
594 timeline,
595 agent_run,
583 };
596 };
584 let own = row.own;
597 let own = row.own;
585 let spacing = if row.series.has_prev {
598 let spacing = if row.series.has_prev {
crates/app/src/views/post_card.rs +4 −1
@@ -15,6 +15,7 @@ use super::scheduled_toolbar::scheduled_toolbar;
15 15 use super::toolbar_placement::placed_toolbar;
16 16 use super::translation_line::translation_line;
17 17 use super::widgets::{icon, symbol};
18 use crate::agents::run_chip;
18 19 use crate::data::Directory;
19 20 use crate::rows::{Delivery, MessageRow, PostRow};
20 21 use crate::sidebar_model::DELETED_PREVIEW;
@@ -208,6 +209,7 @@ fn message_block(
208 209 highlighted,
209 210 translation: translation_actions,
210 211 timeline,
212 agent_run,
211 213 ..
212 214 } = actions;
213 215 let note = delivery_note(row, delivery, index);
@@ -231,7 +233,8 @@ fn message_block(
231 233 )
232 234 .child(content)
233 235 .children(translation)
234 .children(note);
236 .children(note)
237 .children(agent_run.map(|run| run_chip(&run, theme::surface_raised())));
235 238 div()
236 239 .id(ElementId::Name(format!("post-message-{index}").into()))
237 240 .relative()
@@ -15,6 +15,7 @@ use super::scheduled_toolbar::scheduled_toolbar;
15use super::toolbar_placement::placed_toolbar;
15use super::toolbar_placement::placed_toolbar;
16use super::translation_line::translation_line;
16use super::translation_line::translation_line;
17use super::widgets::{icon, symbol};
17use super::widgets::{icon, symbol};
18use crate::agents::run_chip;
18use crate::data::Directory;
19use crate::data::Directory;
19use crate::rows::{Delivery, MessageRow, PostRow};
20use crate::rows::{Delivery, MessageRow, PostRow};
20use crate::sidebar_model::DELETED_PREVIEW;
21use crate::sidebar_model::DELETED_PREVIEW;
@@ -208,6 +209,7 @@ fn message_block(
208 highlighted,
209 highlighted,
209 translation: translation_actions,
210 translation: translation_actions,
210 timeline,
211 timeline,
212 agent_run,
211 ..
213 ..
212 } = actions;
214 } = actions;
213 let note = delivery_note(row, delivery, index);
215 let note = delivery_note(row, delivery, index);
@@ -231,7 +233,8 @@ fn message_block(
231 )
233 )
232 .child(content)
234 .child(content)
233 .children(translation)
235 .children(translation)
234 .children(note);
236 .children(note)
237 .children(agent_run.map(|run| run_chip(&run, theme::surface_raised())));
235 div()
238 div()
236 .id(ElementId::Name(format!("post-message-{index}").into()))
239 .id(ElementId::Name(format!("post-message-{index}").into()))
237 .relative()
240 .relative()
crates/app/src/views/proposal_card.rs +7 −4
@@ -30,11 +30,13 @@ pub struct CardActions {
30 30 pub discard: CardAction,
31 31 }
32 32
33 fn open_session_available() -> bool {
34 false
33 fn open_session_available(session_id: &str, cx: &App) -> bool {
34 crate::agents::has_session(session_id, cx)
35 35 }
36 36
37 fn open_session(_session_id: &str, _window: &mut Window, _cx: &mut App) {}
37 fn open_session(session_id: &str, _window: &mut Window, cx: &mut App) {
38 crate::agents::open_session(session_id, cx);
39 }
38 40
39 41 pub fn age_label(created_at: DateTime<Utc>, now: DateTime<Utc>) -> String {
40 42 let minutes = (now - created_at).num_minutes().max(0);
@@ -99,6 +101,7 @@ pub fn render(
99 101 quote: Option<String>,
100 102 actions: CardActions,
101 103 now: DateTime<Utc>,
104 cx: &App,
102 105 ) -> Div {
103 106 let stale = matches!(entry.status, ProposalStatus::Stale { .. });
104 107 let failed = matches!(entry.status, ProposalStatus::Failed { .. });
@@ -167,7 +170,7 @@ pub fn render(
167 170 .proposal
168 171 .session_id
169 172 .clone()
170 .filter(|_| open_session_available());
173 .filter(|session_id| open_session_available(session_id, cx));
171 174 let buttons = h_flex()
172 175 .w_full()
173 176 .items_center()
@@ -30,11 +30,13 @@ pub struct CardActions {
30 pub discard: CardAction,
30 pub discard: CardAction,
31}
31}
32
32
33fn open_session_available() -> bool {
33fn open_session_available(session_id: &str, cx: &App) -> bool {
34 false
34 crate::agents::has_session(session_id, cx)
35}
35}
36
36
37fn open_session(_session_id: &str, _window: &mut Window, _cx: &mut App) {}
37fn open_session(session_id: &str, _window: &mut Window, cx: &mut App) {
38 crate::agents::open_session(session_id, cx);
39}
38
40
39pub fn age_label(created_at: DateTime<Utc>, now: DateTime<Utc>) -> String {
41pub fn age_label(created_at: DateTime<Utc>, now: DateTime<Utc>) -> String {
40 let minutes = (now - created_at).num_minutes().max(0);
42 let minutes = (now - created_at).num_minutes().max(0);
@@ -99,6 +101,7 @@ pub fn render(
99 quote: Option<String>,
101 quote: Option<String>,
100 actions: CardActions,
102 actions: CardActions,
101 now: DateTime<Utc>,
103 now: DateTime<Utc>,
104 cx: &App,
102) -> Div {
105) -> Div {
103 let stale = matches!(entry.status, ProposalStatus::Stale { .. });
106 let stale = matches!(entry.status, ProposalStatus::Stale { .. });
104 let failed = matches!(entry.status, ProposalStatus::Failed { .. });
107 let failed = matches!(entry.status, ProposalStatus::Failed { .. });
@@ -167,7 +170,7 @@ pub fn render(
167 .proposal
170 .proposal
168 .session_id
171 .session_id
169 .clone()
172 .clone()
170 .filter(|_| open_session_available());
173 .filter(|session_id| open_session_available(session_id, cx));
171 let buttons = h_flex()
174 let buttons = h_flex()
172 .w_full()
175 .w_full()
173 .items_center()
176 .items_center()
crates/app/src/views/rail.rs +173 −61
@@ -1,5 +1,6 @@
1 1 use gpui_kit::assets::IconName;
2 use gpui_kit::component::{tooltip::Tooltip, v_flex};
2 use gpui_kit::base::Selectable;
3 use gpui_kit::component::{popover::Popover, tooltip::Tooltip, v_flex};
3 4 use gpui_kit::prelude::FluentBuilder as _;
4 5 use gpui_kit::*;
5 6
@@ -8,6 +9,7 @@ use super::shortcuts::keys_for_label;
8 9 use super::sidebar::{SidebarTab, SidebarView};
9 10 use super::widgets::icon;
10 11 use crate::activity::ActivityCenter;
12 use crate::agents::{AgentRuns, RunsPopover, runs_handle};
11 13 use crate::app_state::AppState;
12 14 use crate::format;
13 15 use crate::sidebar_model::{any_unread_channel, unread_chat_count};
@@ -25,9 +27,15 @@ enum RailBadge {
25 27 Dot,
26 28 }
27 29
30 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
31 enum RailTarget {
32 Tab(SidebarTab),
33 Agents,
34 }
35
28 36 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
29 37 struct RailItem {
30 tab: SidebarTab,
38 target: RailTarget,
31 39 label: &'static str,
32 40 shortcut_label: &'static str,
33 41 icon: IconName,
@@ -41,24 +49,29 @@ fn count_badge_for(count: usize) -> RailBadge {
41 49 }
42 50 }
43 51
44 fn rail_items(activity_unread: usize, unread_chats: usize, channel_dot: bool) -> [RailItem; 5] {
45 [
52 fn rail_items(
53 activity_unread: usize,
54 unread_chats: usize,
55 channel_dot: bool,
56 agents_running: Option<usize>,
57 ) -> Vec<RailItem> {
58 let mut items = vec![
46 59 RailItem {
47 tab: SidebarTab::Activity,
60 target: RailTarget::Tab(SidebarTab::Activity),
48 61 label: "Activity",
49 62 shortcut_label: "Open Activity",
50 63 icon: IconName::Bell,
51 64 badge: count_badge_for(activity_unread),
52 65 },
53 66 RailItem {
54 tab: SidebarTab::Chats,
67 target: RailTarget::Tab(SidebarTab::Chats),
55 68 label: "Chats",
56 69 shortcut_label: "Show Chats",
57 70 icon: IconName::MessageSquare,
58 71 badge: count_badge_for(unread_chats),
59 72 },
60 73 RailItem {
61 tab: SidebarTab::Channels,
74 target: RailTarget::Tab(SidebarTab::Channels),
62 75 label: "Channels",
63 76 shortcut_label: "Show Channels",
64 77 icon: IconName::Users,
@@ -69,20 +82,30 @@ fn rail_items(activity_unread: usize, unread_chats: usize, channel_dot: bool) ->
69 82 },
70 83 },
71 84 RailItem {
72 tab: SidebarTab::Calls,
85 target: RailTarget::Tab(SidebarTab::Calls),
73 86 label: "Calls",
74 87 shortcut_label: "Show Calls",
75 88 icon: IconName::Phone,
76 89 badge: RailBadge::None,
77 90 },
78 91 RailItem {
79 tab: SidebarTab::Saved,
92 target: RailTarget::Tab(SidebarTab::Saved),
80 93 label: "Saved",
81 94 shortcut_label: "Open Saved",
82 95 icon: IconName::Bookmark,
83 96 badge: RailBadge::None,
84 97 },
85 ]
98 ];
99 if let Some(running) = agents_running {
100 items.push(RailItem {
101 target: RailTarget::Agents,
102 label: "Agents",
103 shortcut_label: "Agents",
104 icon: IconName::Bot,
105 badge: count_badge_for(running),
106 });
107 }
108 items
86 109 }
87 110
88 111 fn tooltip_text(item: &RailItem) -> SharedString {
@@ -96,7 +119,67 @@ pub struct RailView {
96 119 state: Entity<AppState>,
97 120 activity: Entity<ActivityCenter>,
98 121 sidebar: Entity<SidebarView>,
99 _observations: [Subscription; 3],
122 runs: Option<Entity<AgentRuns>>,
123 runs_popover: Option<Entity<RunsPopover>>,
124 _observations: Vec<Subscription>,
125 }
126
127 fn item_element(item: &RailItem, active: bool) -> Stateful<Div> {
128 let tooltip = tooltip_text(item);
129 let color = if active {
130 theme::accent_text()
131 } else {
132 theme::text_muted()
133 };
134 div()
135 .id(SharedString::from(format!("rail-{}", item.label)))
136 .relative()
137 .w(px(ITEM_WIDTH))
138 .h(px(ITEM_HEIGHT))
139 .flex()
140 .flex_col()
141 .flex_none()
142 .items_center()
143 .justify_center()
144 .gap(px(4.))
145 .rounded(px(10.))
146 .cursor_pointer()
147 .when(active, |button| button.bg(theme::surface_raised()))
148 .when(!active, |button| button.hover(|button| button.bg(theme::row_hover())))
149 .child(icon(item.icon, ICON_SIZE, color))
150 .child(
151 div()
152 .whitespace_nowrap()
153 .text_size(px(10.))
154 .font_weight(FontWeight::SEMIBOLD)
155 .text_color(color)
156 .child(item.label),
157 )
158 .child(badge(item.badge))
159 .tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx))
160 }
161
162 #[derive(IntoElement)]
163 struct AgentsTrigger {
164 item: RailItem,
165 open: bool,
166 }
167
168 impl Selectable for AgentsTrigger {
169 fn selected(mut self, selected: bool) -> Self {
170 self.open = selected;
171 self
172 }
173
174 fn is_selected(&self) -> bool {
175 self.open
176 }
177 }
178
179 impl RenderOnce for AgentsTrigger {
180 fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
181 item_element(&self.item, self.open)
182 }
100 183 }
101 184
102 185 impl RailView {
@@ -106,57 +189,66 @@ impl RailView {
106 189 sidebar: Entity<SidebarView>,
107 190 cx: &mut Context<Self>,
108 191 ) -> Self {
109 let observations = [
192 let mut observations = vec![
110 193 cx.observe(&state, |_, _, cx| cx.notify()),
111 194 cx.observe(&activity, |_, _, cx| cx.notify()),
112 195 cx.observe(&sidebar, |_, _, cx| cx.notify()),
113 196 ];
197 let runs = runs_handle(cx);
198 if let Some(runs) = &runs {
199 observations.push(cx.observe(runs, |_, _, cx| cx.notify()));
200 }
201 let runs_popover = runs.clone().map(|runs| {
202 let app = state.clone();
203 cx.new(|cx| RunsPopover::new(app, runs, cx))
204 });
114 205 RailView {
115 206 state,
116 207 activity,
117 208 sidebar,
209 runs,
210 runs_popover,
118 211 _observations: observations,
119 212 }
120 213 }
121 214
122 fn item(&self, item: &RailItem, active: bool) -> impl IntoElement {
123 let tab = item.tab;
124 let sidebar = self.sidebar.clone();
125 let tooltip = tooltip_text(item);
126 let color = if active {
127 theme::accent_text()
128 } else {
129 theme::text_muted()
215 fn item(&self, item: &RailItem, active: bool) -> AnyElement {
216 match item.target {
217 RailTarget::Tab(tab) => {
218 let sidebar = self.sidebar.clone();
219 item_element(item, active)
220 .on_click(move |_, _, cx| {
221 sidebar.update(cx, |sidebar, cx| sidebar.open_tab(tab, cx));
222 })
223 .into_any_element()
224 }
225 RailTarget::Agents => self.agents_item(item),
226 }
227 }
228
229 fn agents_item(&self, item: &RailItem) -> AnyElement {
230 let Some(content) = self.runs_popover.clone() else {
231 return div().into_any_element();
130 232 };
131 div()
132 .id(SharedString::from(format!("rail-{}", item.label)))
133 .relative()
134 .w(px(ITEM_WIDTH))
135 .h(px(ITEM_HEIGHT))
136 .flex()
137 .flex_col()
138 .flex_none()
139 .items_center()
140 .justify_center()
141 .gap(px(4.))
142 .rounded(px(10.))
143 .cursor_pointer()
144 .when(active, |button| button.bg(theme::surface_raised()))
145 .when(!active, |button| button.hover(|button| button.bg(theme::row_hover())))
146 .child(icon(item.icon, ICON_SIZE, color))
147 .child(
148 div()
149 .whitespace_nowrap()
150 .text_size(px(10.))
151 .font_weight(FontWeight::SEMIBOLD)
152 .text_color(color)
153 .child(item.label),
154 )
155 .child(badge(item.badge))
156 .tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx))
157 .on_click(move |_, _, cx| {
158 sidebar.update(cx, |sidebar, cx| sidebar.open_tab(tab, cx));
233 Popover::new("rail-agents-popover")
234 .anchor(Anchor::LeftCenter)
235 .offset(px(6.))
236 .p(px(4.))
237 .trigger(AgentsTrigger {
238 item: *item,
239 open: false,
240 })
241 .content(move |_, _, cx| {
242 let popover = cx.entity().downgrade();
243 content.update(cx, |content, _| content.set_popover(popover));
244 content.clone()
159 245 })
246 .into_any_element()
247 }
248
249 fn agents_running(&self, cx: &App) -> Option<usize> {
250 let runs = self.runs.as_ref()?.read(cx);
251 (!runs.settings().actions.is_empty()).then(|| runs.running_count())
160 252 }
161 253 }
162 254
@@ -201,6 +293,12 @@ impl Render for RailView {
201 293 any_unread_channel(&state.sidebar),
202 294 )
203 295 };
296 let items = rail_items(
297 activity_unread,
298 unread_chats as usize,
299 channel_dot,
300 self.agents_running(cx),
301 );
204 302 v_flex()
205 303 .w(px(RAIL_WIDTH))
206 304 .h_full()
@@ -209,49 +307,63 @@ impl Render for RailView {
209 307 .gap(px(2.))
210 308 .pt(px(0.))
211 309 .children(
212 rail_items(activity_unread, unread_chats as usize, channel_dot)
310 items
213 311 .iter()
214 .map(|item| self.item(item, item.tab == active)),
312 .map(|item| self.item(item, item.target == RailTarget::Tab(active))),
215 313 )
216 314 }
217 315 }
218 316
219 317 #[cfg(test)]
220 318 mod tests {
221 use super::{RailBadge, count_badge_for, rail_items, tooltip_text};
319 use super::{RailBadge, RailTarget, count_badge_for, rail_items, tooltip_text};
222 320 use crate::views::sidebar::SidebarTab;
223 321
224 322 #[test]
225 323 fn items_follow_the_spec_order() {
226 let tabs: Vec<SidebarTab> = rail_items(0, 0, false).iter().map(|item| item.tab).collect();
324 let targets: Vec<RailTarget> = rail_items(0, 0, false, None)
325 .iter()
326 .map(|item| item.target)
327 .collect();
227 328 assert_eq!(
228 tabs,
329 targets,
229 330 [
230 SidebarTab::Activity,
231 SidebarTab::Chats,
232 SidebarTab::Channels,
233 SidebarTab::Calls,
234 SidebarTab::Saved
331 RailTarget::Tab(SidebarTab::Activity),
332 RailTarget::Tab(SidebarTab::Chats),
333 RailTarget::Tab(SidebarTab::Channels),
334 RailTarget::Tab(SidebarTab::Calls),
335 RailTarget::Tab(SidebarTab::Saved)
235 336 ]
236 337 );
237 338 }
238 339
340 #[test]
341 fn agents_comes_last_and_only_when_actions_exist() {
342 assert_eq!(rail_items(0, 0, false, None).len(), 5);
343 let with_agents = rail_items(0, 0, false, Some(2));
344 assert_eq!(with_agents.len(), 6);
345 assert_eq!(with_agents[5].target, RailTarget::Agents);
346 assert_eq!(with_agents[5].label, "Agents");
347 assert_eq!(with_agents[5].badge, RailBadge::Count(2));
348 assert_eq!(rail_items(0, 0, false, Some(0))[5].badge, RailBadge::None);
349 }
350
239 351 #[test]
240 352 fn badges_follow_the_unread_inputs() {
241 let items = rail_items(3, 5, true);
353 let items = rail_items(3, 5, true, None);
242 354 assert_eq!(items[0].badge, RailBadge::Count(3));
243 355 assert_eq!(items[1].badge, RailBadge::Count(5));
244 356 assert_eq!(items[2].badge, RailBadge::Dot);
245 357 assert_eq!(items[3].badge, RailBadge::None);
246 358 assert_eq!(items[4].badge, RailBadge::None);
247 let quiet = rail_items(0, 0, false);
359 let quiet = rail_items(0, 0, false, None);
248 360 assert!(quiet.iter().all(|item| item.badge == RailBadge::None));
249 361 assert_eq!(count_badge_for(usize::MAX), RailBadge::Count(u32::MAX));
250 362 }
251 363
252 364 #[test]
253 365 fn every_item_shows_its_shortcut_in_the_tooltip() {
254 let items = rail_items(0, 0, false);
366 let items = rail_items(0, 0, false, None);
255 367 assert_eq!(tooltip_text(&items[0]), "Activity (Ctrl+1)");
256 368 assert!(items.iter().all(|item| tooltip_text(item).ends_with(')')));
257 369 }
@@ -1,5 +1,6 @@
1use gpui_kit::assets::IconName;
1use gpui_kit::assets::IconName;
2use gpui_kit::component::{tooltip::Tooltip, v_flex};
2use gpui_kit::base::Selectable;
3use gpui_kit::component::{popover::Popover, tooltip::Tooltip, v_flex};
3use gpui_kit::prelude::FluentBuilder as _;
4use gpui_kit::prelude::FluentBuilder as _;
4use gpui_kit::*;
5use gpui_kit::*;
5
6
@@ -8,6 +9,7 @@ use super::shortcuts::keys_for_label;
8use super::sidebar::{SidebarTab, SidebarView};
9use super::sidebar::{SidebarTab, SidebarView};
9use super::widgets::icon;
10use super::widgets::icon;
10use crate::activity::ActivityCenter;
11use crate::activity::ActivityCenter;
12use crate::agents::{AgentRuns, RunsPopover, runs_handle};
11use crate::app_state::AppState;
13use crate::app_state::AppState;
12use crate::format;
14use crate::format;
13use crate::sidebar_model::{any_unread_channel, unread_chat_count};
15use crate::sidebar_model::{any_unread_channel, unread_chat_count};
@@ -25,9 +27,15 @@ enum RailBadge {
25 Dot,
27 Dot,
26}
28}
27
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq)]
31enum RailTarget {
32 Tab(SidebarTab),
33 Agents,
34}
35
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29struct RailItem {
37struct RailItem {
30 tab: SidebarTab,
38 target: RailTarget,
31 label: &'static str,
39 label: &'static str,
32 shortcut_label: &'static str,
40 shortcut_label: &'static str,
33 icon: IconName,
41 icon: IconName,
@@ -41,24 +49,29 @@ fn count_badge_for(count: usize) -> RailBadge {
41 }
49 }
42}
50}
43
51
44fn rail_items(activity_unread: usize, unread_chats: usize, channel_dot: bool) -> [RailItem; 5] {
52fn rail_items(
45 [
53 activity_unread: usize,
54 unread_chats: usize,
55 channel_dot: bool,
56 agents_running: Option<usize>,
57) -> Vec<RailItem> {
58 let mut items = vec![
46 RailItem {
59 RailItem {
47 tab: SidebarTab::Activity,
60 target: RailTarget::Tab(SidebarTab::Activity),
48 label: "Activity",
61 label: "Activity",
49 shortcut_label: "Open Activity",
62 shortcut_label: "Open Activity",
50 icon: IconName::Bell,
63 icon: IconName::Bell,
51 badge: count_badge_for(activity_unread),
64 badge: count_badge_for(activity_unread),
52 },
65 },
53 RailItem {
66 RailItem {
54 tab: SidebarTab::Chats,
67 target: RailTarget::Tab(SidebarTab::Chats),
55 label: "Chats",
68 label: "Chats",
56 shortcut_label: "Show Chats",
69 shortcut_label: "Show Chats",
57 icon: IconName::MessageSquare,
70 icon: IconName::MessageSquare,
58 badge: count_badge_for(unread_chats),
71 badge: count_badge_for(unread_chats),
59 },
72 },
60 RailItem {
73 RailItem {
61 tab: SidebarTab::Channels,
74 target: RailTarget::Tab(SidebarTab::Channels),
62 label: "Channels",
75 label: "Channels",
63 shortcut_label: "Show Channels",
76 shortcut_label: "Show Channels",
64 icon: IconName::Users,
77 icon: IconName::Users,
@@ -69,20 +82,30 @@ fn rail_items(activity_unread: usize, unread_chats: usize, channel_dot: bool) ->
69 },
82 },
70 },
83 },
71 RailItem {
84 RailItem {
72 tab: SidebarTab::Calls,
85 target: RailTarget::Tab(SidebarTab::Calls),
73 label: "Calls",
86 label: "Calls",
74 shortcut_label: "Show Calls",
87 shortcut_label: "Show Calls",
75 icon: IconName::Phone,
88 icon: IconName::Phone,
76 badge: RailBadge::None,
89 badge: RailBadge::None,
77 },
90 },
78 RailItem {
91 RailItem {
79 tab: SidebarTab::Saved,
92 target: RailTarget::Tab(SidebarTab::Saved),
80 label: "Saved",
93 label: "Saved",
81 shortcut_label: "Open Saved",
94 shortcut_label: "Open Saved",
82 icon: IconName::Bookmark,
95 icon: IconName::Bookmark,
83 badge: RailBadge::None,
96 badge: RailBadge::None,
84 },
97 },
85 ]
98 ];
99 if let Some(running) = agents_running {
100 items.push(RailItem {
101 target: RailTarget::Agents,
102 label: "Agents",
103 shortcut_label: "Agents",
104 icon: IconName::Bot,
105 badge: count_badge_for(running),
106 });
107 }
108 items
86}
109}
87
110
88fn tooltip_text(item: &RailItem) -> SharedString {
111fn tooltip_text(item: &RailItem) -> SharedString {
@@ -96,7 +119,67 @@ pub struct RailView {
96 state: Entity<AppState>,
119 state: Entity<AppState>,
97 activity: Entity<ActivityCenter>,
120 activity: Entity<ActivityCenter>,
98 sidebar: Entity<SidebarView>,
121 sidebar: Entity<SidebarView>,
99 _observations: [Subscription; 3],
122 runs: Option<Entity<AgentRuns>>,
123 runs_popover: Option<Entity<RunsPopover>>,
124 _observations: Vec<Subscription>,
125}
126
127fn item_element(item: &RailItem, active: bool) -> Stateful<Div> {
128 let tooltip = tooltip_text(item);
129 let color = if active {
130 theme::accent_text()
131 } else {
132 theme::text_muted()
133 };
134 div()
135 .id(SharedString::from(format!("rail-{}", item.label)))
136 .relative()
137 .w(px(ITEM_WIDTH))
138 .h(px(ITEM_HEIGHT))
139 .flex()
140 .flex_col()
141 .flex_none()
142 .items_center()
143 .justify_center()
144 .gap(px(4.))
145 .rounded(px(10.))
146 .cursor_pointer()
147 .when(active, |button| button.bg(theme::surface_raised()))
148 .when(!active, |button| button.hover(|button| button.bg(theme::row_hover())))
149 .child(icon(item.icon, ICON_SIZE, color))
150 .child(
151 div()
152 .whitespace_nowrap()
153 .text_size(px(10.))
154 .font_weight(FontWeight::SEMIBOLD)
155 .text_color(color)
156 .child(item.label),
157 )
158 .child(badge(item.badge))
159 .tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx))
160}
161
162#[derive(IntoElement)]
163struct AgentsTrigger {
164 item: RailItem,
165 open: bool,
166}
167
168impl Selectable for AgentsTrigger {
169 fn selected(mut self, selected: bool) -> Self {
170 self.open = selected;
171 self
172 }
173
174 fn is_selected(&self) -> bool {
175 self.open
176 }
177}
178
179impl RenderOnce for AgentsTrigger {
180 fn render(self, _: &mut Window, _: &mut App) -> impl IntoElement {
181 item_element(&self.item, self.open)
182 }
100}
183}
101
184
102impl RailView {
185impl RailView {
@@ -106,57 +189,66 @@ impl RailView {
106 sidebar: Entity<SidebarView>,
189 sidebar: Entity<SidebarView>,
107 cx: &mut Context<Self>,
190 cx: &mut Context<Self>,
108 ) -> Self {
191 ) -> Self {
109 let observations = [
192 let mut observations = vec![
110 cx.observe(&state, |_, _, cx| cx.notify()),
193 cx.observe(&state, |_, _, cx| cx.notify()),
111 cx.observe(&activity, |_, _, cx| cx.notify()),
194 cx.observe(&activity, |_, _, cx| cx.notify()),
112 cx.observe(&sidebar, |_, _, cx| cx.notify()),
195 cx.observe(&sidebar, |_, _, cx| cx.notify()),
113 ];
196 ];
197 let runs = runs_handle(cx);
198 if let Some(runs) = &runs {
199 observations.push(cx.observe(runs, |_, _, cx| cx.notify()));
200 }
201 let runs_popover = runs.clone().map(|runs| {
202 let app = state.clone();
203 cx.new(|cx| RunsPopover::new(app, runs, cx))
204 });
114 RailView {
205 RailView {
115 state,
206 state,
116 activity,
207 activity,
117 sidebar,
208 sidebar,
209 runs,
210 runs_popover,
118 _observations: observations,
211 _observations: observations,
119 }
212 }
120 }
213 }
121
214
122 fn item(&self, item: &RailItem, active: bool) -> impl IntoElement {
215 fn item(&self, item: &RailItem, active: bool) -> AnyElement {
123 let tab = item.tab;
216 match item.target {
124 let sidebar = self.sidebar.clone();
217 RailTarget::Tab(tab) => {
125 let tooltip = tooltip_text(item);
218 let sidebar = self.sidebar.clone();
126 let color = if active {
219 item_element(item, active)
127 theme::accent_text()
220 .on_click(move |_, _, cx| {
128 } else {
221 sidebar.update(cx, |sidebar, cx| sidebar.open_tab(tab, cx));
129 theme::text_muted()
222 })
223 .into_any_element()
224 }
225 RailTarget::Agents => self.agents_item(item),
226 }
227 }
228
229 fn agents_item(&self, item: &RailItem) -> AnyElement {
230 let Some(content) = self.runs_popover.clone() else {
231 return div().into_any_element();
130 };
232 };
131 div()
233 Popover::new("rail-agents-popover")
132 .id(SharedString::from(format!("rail-{}", item.label)))
234 .anchor(Anchor::LeftCenter)
133 .relative()
235 .offset(px(6.))
134 .w(px(ITEM_WIDTH))
236 .p(px(4.))
135 .h(px(ITEM_HEIGHT))
237 .trigger(AgentsTrigger {
136 .flex()
238 item: *item,
137 .flex_col()
239 open: false,
138 .flex_none()
240 })
139 .items_center()
241 .content(move |_, _, cx| {
140 .justify_center()
242 let popover = cx.entity().downgrade();
141 .gap(px(4.))
243 content.update(cx, |content, _| content.set_popover(popover));
142 .rounded(px(10.))
244 content.clone()
143 .cursor_pointer()
144 .when(active, |button| button.bg(theme::surface_raised()))
145 .when(!active, |button| button.hover(|button| button.bg(theme::row_hover())))
146 .child(icon(item.icon, ICON_SIZE, color))
147 .child(
148 div()
149 .whitespace_nowrap()
150 .text_size(px(10.))
151 .font_weight(FontWeight::SEMIBOLD)
152 .text_color(color)
153 .child(item.label),
154 )
155 .child(badge(item.badge))
156 .tooltip(move |window, cx| Tooltip::new(tooltip.clone()).build(window, cx))
157 .on_click(move |_, _, cx| {
158 sidebar.update(cx, |sidebar, cx| sidebar.open_tab(tab, cx));
159 })
245 })
246 .into_any_element()
247 }
248
249 fn agents_running(&self, cx: &App) -> Option<usize> {
250 let runs = self.runs.as_ref()?.read(cx);
251 (!runs.settings().actions.is_empty()).then(|| runs.running_count())
160 }
252 }
161}
253}
162
254
@@ -201,6 +293,12 @@ impl Render for RailView {
201 any_unread_channel(&state.sidebar),
293 any_unread_channel(&state.sidebar),
202 )
294 )
203 };
295 };
296 let items = rail_items(
297 activity_unread,
298 unread_chats as usize,
299 channel_dot,
300 self.agents_running(cx),
301 );
204 v_flex()
302 v_flex()
205 .w(px(RAIL_WIDTH))
303 .w(px(RAIL_WIDTH))
206 .h_full()
304 .h_full()
@@ -209,49 +307,63 @@ impl Render for RailView {
209 .gap(px(2.))
307 .gap(px(2.))
210 .pt(px(0.))
308 .pt(px(0.))
211 .children(
309 .children(
212 rail_items(activity_unread, unread_chats as usize, channel_dot)
310 items
213 .iter()
311 .iter()
214 .map(|item| self.item(item, item.tab == active)),
312 .map(|item| self.item(item, item.target == RailTarget::Tab(active))),
215 )
313 )
216 }
314 }
217}
315}
218
316
219#[cfg(test)]
317#[cfg(test)]
220mod tests {
318mod tests {
221 use super::{RailBadge, count_badge_for, rail_items, tooltip_text};
319 use super::{RailBadge, RailTarget, count_badge_for, rail_items, tooltip_text};
222 use crate::views::sidebar::SidebarTab;
320 use crate::views::sidebar::SidebarTab;
223
321
224 #[test]
322 #[test]
225 fn items_follow_the_spec_order() {
323 fn items_follow_the_spec_order() {
226 let tabs: Vec<SidebarTab> = rail_items(0, 0, false).iter().map(|item| item.tab).collect();
324 let targets: Vec<RailTarget> = rail_items(0, 0, false, None)
325 .iter()
326 .map(|item| item.target)
327 .collect();
227 assert_eq!(
328 assert_eq!(
228 tabs,
329 targets,
229 [
330 [
230 SidebarTab::Activity,
331 RailTarget::Tab(SidebarTab::Activity),
231 SidebarTab::Chats,
332 RailTarget::Tab(SidebarTab::Chats),
232 SidebarTab::Channels,
333 RailTarget::Tab(SidebarTab::Channels),
233 SidebarTab::Calls,
334 RailTarget::Tab(SidebarTab::Calls),
234 SidebarTab::Saved
335 RailTarget::Tab(SidebarTab::Saved)
235 ]
336 ]
236 );
337 );
237 }
338 }
238
339
340 #[test]
341 fn agents_comes_last_and_only_when_actions_exist() {
342 assert_eq!(rail_items(0, 0, false, None).len(), 5);
343 let with_agents = rail_items(0, 0, false, Some(2));
344 assert_eq!(with_agents.len(), 6);
345 assert_eq!(with_agents[5].target, RailTarget::Agents);
346 assert_eq!(with_agents[5].label, "Agents");
347 assert_eq!(with_agents[5].badge, RailBadge::Count(2));
348 assert_eq!(rail_items(0, 0, false, Some(0))[5].badge, RailBadge::None);
349 }
350
239 #[test]
351 #[test]
240 fn badges_follow_the_unread_inputs() {
352 fn badges_follow_the_unread_inputs() {
241 let items = rail_items(3, 5, true);
353 let items = rail_items(3, 5, true, None);
242 assert_eq!(items[0].badge, RailBadge::Count(3));
354 assert_eq!(items[0].badge, RailBadge::Count(3));
243 assert_eq!(items[1].badge, RailBadge::Count(5));
355 assert_eq!(items[1].badge, RailBadge::Count(5));
244 assert_eq!(items[2].badge, RailBadge::Dot);
356 assert_eq!(items[2].badge, RailBadge::Dot);
245 assert_eq!(items[3].badge, RailBadge::None);
357 assert_eq!(items[3].badge, RailBadge::None);
246 assert_eq!(items[4].badge, RailBadge::None);
358 assert_eq!(items[4].badge, RailBadge::None);
247 let quiet = rail_items(0, 0, false);
359 let quiet = rail_items(0, 0, false, None);
248 assert!(quiet.iter().all(|item| item.badge == RailBadge::None));
360 assert!(quiet.iter().all(|item| item.badge == RailBadge::None));
249 assert_eq!(count_badge_for(usize::MAX), RailBadge::Count(u32::MAX));
361 assert_eq!(count_badge_for(usize::MAX), RailBadge::Count(u32::MAX));
250 }
362 }
251
363
252 #[test]
364 #[test]
253 fn every_item_shows_its_shortcut_in_the_tooltip() {
365 fn every_item_shows_its_shortcut_in_the_tooltip() {
254 let items = rail_items(0, 0, false);
366 let items = rail_items(0, 0, false, None);
255 assert_eq!(tooltip_text(&items[0]), "Activity (Ctrl+1)");
367 assert_eq!(tooltip_text(&items[0]), "Activity (Ctrl+1)");
256 assert!(items.iter().all(|item| tooltip_text(item).ends_with(')')));
368 assert!(items.iter().all(|item| tooltip_text(item).ends_with(')')));
257 }
369 }
crates/app/src/views/shell.rs +56 −0
@@ -27,6 +27,7 @@ use super::status_message_dialog::{StatusMessageDialog, StatusMessageDialogEvent
27 27 use super::switcher::{Switcher, SwitcherEvent, candidates_from};
28 28 use super::title_bar::render_title_bar;
29 29 use crate::activity::ActivityCenter;
30 use crate::agents::{AgentRunsEvent, StartDialog, StartDialogEvent, StartRequest};
30 31 use crate::app_state::{AppEvent, AppState, Selection};
31 32 use crate::call::{CallMedia, CallWindows};
32 33 use crate::notice::NoticeAction;
@@ -75,6 +76,7 @@ pub struct AppShell {
75 76 image_viewer: Option<Entity<ImageViewer>>,
76 77 status_dialog: Option<Entity<StatusMessageDialog>>,
77 78 shortcuts_dialog: Option<Entity<ShortcutsDialog>>,
79 agent_dialog: Option<Entity<StartDialog>>,
78 80 profile_card: Option<Entity<ProfileCard>>,
79 81 focus_handle: FocusHandle,
80 82 open_target: Option<OpenTarget>,
@@ -83,6 +85,7 @@ pub struct AppShell {
83 85 _subscription: Subscription,
84 86 _call_media_observation: Subscription,
85 87 _panel_subscriptions: [Subscription; 2],
88 _agent_subscription: Option<Subscription>,
86 89 _escape_observation: Subscription,
87 90 _activation_observation: Subscription,
88 91 }
@@ -132,6 +135,19 @@ impl AppShell {
132 135 this.open_message(conversation_id, message_id, cx);
133 136 }),
134 137 ];
138 let agent_subscription = crate::agents::runs_handle(cx).map(|runs| {
139 cx.subscribe_in(&runs, window, |this, _, event: &AgentRunsEvent, window, cx| {
140 match event {
141 AgentRunsEvent::StartRequested(request) => {
142 this.open_agent_dialog(request.clone(), window, cx)
143 }
144 AgentRunsEvent::OpenSettings => this
145 .notifications
146 .update(cx, |center, cx| center.open_agent_settings(cx)),
147 AgentRunsEvent::Finished(_) => {}
148 }
149 })
150 });
135 151 let sidebar = cx.new(|cx| SidebarView::new(state.clone(), activity_panel, saved_panel, cx));
136 152 let rail = cx.new(|cx| RailView::new(state.clone(), activity.clone(), sidebar.clone(), cx));
137 153 let conversation = cx.new(|cx| ConversationView::new(state.clone(), window, cx));
@@ -189,6 +205,7 @@ impl AppShell {
189 205 image_viewer: None,
190 206 status_dialog: None,
191 207 shortcuts_dialog: None,
208 agent_dialog: None,
192 209 profile_card: None,
193 210 focus_handle,
194 211 open_target,
@@ -197,6 +214,7 @@ impl AppShell {
197 214 _subscription: subscription,
198 215 _call_media_observation: call_media_observation,
199 216 _panel_subscriptions: panel_subscriptions,
217 _agent_subscription: agent_subscription,
200 218 _escape_observation: escape_observation,
201 219 _activation_observation: activation_observation,
202 220 };
@@ -399,6 +417,43 @@ impl AppShell {
399 417 cx.notify();
400 418 }
401 419
420 fn open_agent_dialog(
421 &mut self,
422 request: StartRequest,
423 window: &mut Window,
424 cx: &mut Context<Self>,
425 ) {
426 let Some(runs) = crate::agents::runs_handle(cx) else {
427 return;
428 };
429 let settings = runs.read(cx).settings();
430 let Some(action) = settings
431 .actions
432 .iter()
433 .find(|action| action.id == request.action_id)
434 .cloned()
435 else {
436 return;
437 };
438 let agent_name = settings
439 .agents
440 .iter()
441 .find(|agent| agent.id == action.agent_id)
442 .map(|agent| agent.name.clone())
443 .unwrap_or_default();
444 self.switcher = None;
445 let app = self.state.clone();
446 let dialog = cx.new(|cx| StartDialog::new(app, request, action, &agent_name, window, cx));
447 cx.subscribe_in(&dialog, window, |this, _, _: &StartDialogEvent, window, cx| {
448 this.agent_dialog = None;
449 window.focus(&this.focus_handle, cx);
450 cx.notify();
451 })
452 .detach();
453 self.agent_dialog = Some(dialog);
454 cx.notify();
455 }
456
402 457 fn toggle_shortcuts_dialog(&mut self, window: &mut Window, cx: &mut Context<Self>) {
403 458 if self.shortcuts_dialog.take().is_some() {
404 459 self.restore_focus(window, cx);
@@ -699,6 +754,7 @@ impl Render for AppShell {
699 754 .children(self.forward_dialog.clone())
700 755 .children(self.status_dialog.clone())
701 756 .children(self.shortcuts_dialog.clone())
757 .children(self.agent_dialog.clone())
702 758 .children(self.profile_card.clone())
703 759 .child(crate::frame_log::probe("last"))
704 760 }
@@ -27,6 +27,7 @@ use super::status_message_dialog::{StatusMessageDialog, StatusMessageDialogEvent
27use super::switcher::{Switcher, SwitcherEvent, candidates_from};
27use super::switcher::{Switcher, SwitcherEvent, candidates_from};
28use super::title_bar::render_title_bar;
28use super::title_bar::render_title_bar;
29use crate::activity::ActivityCenter;
29use crate::activity::ActivityCenter;
30use crate::agents::{AgentRunsEvent, StartDialog, StartDialogEvent, StartRequest};
30use crate::app_state::{AppEvent, AppState, Selection};
31use crate::app_state::{AppEvent, AppState, Selection};
31use crate::call::{CallMedia, CallWindows};
32use crate::call::{CallMedia, CallWindows};
32use crate::notice::NoticeAction;
33use crate::notice::NoticeAction;
@@ -75,6 +76,7 @@ pub struct AppShell {
75 image_viewer: Option<Entity<ImageViewer>>,
76 image_viewer: Option<Entity<ImageViewer>>,
76 status_dialog: Option<Entity<StatusMessageDialog>>,
77 status_dialog: Option<Entity<StatusMessageDialog>>,
77 shortcuts_dialog: Option<Entity<ShortcutsDialog>>,
78 shortcuts_dialog: Option<Entity<ShortcutsDialog>>,
79 agent_dialog: Option<Entity<StartDialog>>,
78 profile_card: Option<Entity<ProfileCard>>,
80 profile_card: Option<Entity<ProfileCard>>,
79 focus_handle: FocusHandle,
81 focus_handle: FocusHandle,
80 open_target: Option<OpenTarget>,
82 open_target: Option<OpenTarget>,
@@ -83,6 +85,7 @@ pub struct AppShell {
83 _subscription: Subscription,
85 _subscription: Subscription,
84 _call_media_observation: Subscription,
86 _call_media_observation: Subscription,
85 _panel_subscriptions: [Subscription; 2],
87 _panel_subscriptions: [Subscription; 2],
88 _agent_subscription: Option<Subscription>,
86 _escape_observation: Subscription,
89 _escape_observation: Subscription,
87 _activation_observation: Subscription,
90 _activation_observation: Subscription,
88}
91}
@@ -132,6 +135,19 @@ impl AppShell {
132 this.open_message(conversation_id, message_id, cx);
135 this.open_message(conversation_id, message_id, cx);
133 }),
136 }),
134 ];
137 ];
138 let agent_subscription = crate::agents::runs_handle(cx).map(|runs| {
139 cx.subscribe_in(&runs, window, |this, _, event: &AgentRunsEvent, window, cx| {
140 match event {
141 AgentRunsEvent::StartRequested(request) => {
142 this.open_agent_dialog(request.clone(), window, cx)
143 }
144 AgentRunsEvent::OpenSettings => this
145 .notifications
146 .update(cx, |center, cx| center.open_agent_settings(cx)),
147 AgentRunsEvent::Finished(_) => {}
148 }
149 })
150 });
135 let sidebar = cx.new(|cx| SidebarView::new(state.clone(), activity_panel, saved_panel, cx));
151 let sidebar = cx.new(|cx| SidebarView::new(state.clone(), activity_panel, saved_panel, cx));
136 let rail = cx.new(|cx| RailView::new(state.clone(), activity.clone(), sidebar.clone(), cx));
152 let rail = cx.new(|cx| RailView::new(state.clone(), activity.clone(), sidebar.clone(), cx));
137 let conversation = cx.new(|cx| ConversationView::new(state.clone(), window, cx));
153 let conversation = cx.new(|cx| ConversationView::new(state.clone(), window, cx));
@@ -189,6 +205,7 @@ impl AppShell {
189 image_viewer: None,
205 image_viewer: None,
190 status_dialog: None,
206 status_dialog: None,
191 shortcuts_dialog: None,
207 shortcuts_dialog: None,
208 agent_dialog: None,
192 profile_card: None,
209 profile_card: None,
193 focus_handle,
210 focus_handle,
194 open_target,
211 open_target,
@@ -197,6 +214,7 @@ impl AppShell {
197 _subscription: subscription,
214 _subscription: subscription,
198 _call_media_observation: call_media_observation,
215 _call_media_observation: call_media_observation,
199 _panel_subscriptions: panel_subscriptions,
216 _panel_subscriptions: panel_subscriptions,
217 _agent_subscription: agent_subscription,
200 _escape_observation: escape_observation,
218 _escape_observation: escape_observation,
201 _activation_observation: activation_observation,
219 _activation_observation: activation_observation,
202 };
220 };
@@ -399,6 +417,43 @@ impl AppShell {
399 cx.notify();
417 cx.notify();
400 }
418 }
401
419
420 fn open_agent_dialog(
421 &mut self,
422 request: StartRequest,
423 window: &mut Window,
424 cx: &mut Context<Self>,
425 ) {
426 let Some(runs) = crate::agents::runs_handle(cx) else {
427 return;
428 };
429 let settings = runs.read(cx).settings();
430 let Some(action) = settings
431 .actions
432 .iter()
433 .find(|action| action.id == request.action_id)
434 .cloned()
435 else {
436 return;
437 };
438 let agent_name = settings
439 .agents
440 .iter()
441 .find(|agent| agent.id == action.agent_id)
442 .map(|agent| agent.name.clone())
443 .unwrap_or_default();
444 self.switcher = None;
445 let app = self.state.clone();
446 let dialog = cx.new(|cx| StartDialog::new(app, request, action, &agent_name, window, cx));
447 cx.subscribe_in(&dialog, window, |this, _, _: &StartDialogEvent, window, cx| {
448 this.agent_dialog = None;
449 window.focus(&this.focus_handle, cx);
450 cx.notify();
451 })
452 .detach();
453 self.agent_dialog = Some(dialog);
454 cx.notify();
455 }
456
402 fn toggle_shortcuts_dialog(&mut self, window: &mut Window, cx: &mut Context<Self>) {
457 fn toggle_shortcuts_dialog(&mut self, window: &mut Window, cx: &mut Context<Self>) {
403 if self.shortcuts_dialog.take().is_some() {
458 if self.shortcuts_dialog.take().is_some() {
404 self.restore_focus(window, cx);
459 self.restore_focus(window, cx);
@@ -699,6 +754,7 @@ impl Render for AppShell {
699 .children(self.forward_dialog.clone())
754 .children(self.forward_dialog.clone())
700 .children(self.status_dialog.clone())
755 .children(self.status_dialog.clone())
701 .children(self.shortcuts_dialog.clone())
756 .children(self.shortcuts_dialog.clone())
757 .children(self.agent_dialog.clone())
702 .children(self.profile_card.clone())
758 .children(self.profile_card.clone())
703 .child(crate::frame_log::probe("last"))
759 .child(crate::frame_log::probe("last"))
704 }
760 }