Skip to content

Commit fa66500

Browse files
committed
fix(agents): wake remote workspaces from owner direct messages
Signed-off-by: Tee8z <[email protected]>
1 parent ac44fae commit fa66500

15 files changed

Lines changed: 480 additions & 111 deletions

File tree

‎apps/buzz-gpui/crates/app/src/agent_plugins/remote_workspace/mod.rs‎

Lines changed: 42 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ impl AgentType for RemoteWorkspace {
6565

6666
fn description(&self) -> Option<SharedString> {
6767
Some(
68-
"Each thread runs in its own Kubernetes Sandbox, started by the agent's host or the Sandbox manager."
68+
"Each channel thread or direct-message conversation runs in its own Kubernetes Sandbox."
6969
.into(),
7070
)
7171
}
@@ -122,19 +122,32 @@ impl AgentType for RemoteWorkspace {
122122
}
123123

124124
fn run(&self, delivery: Delivery, cx: &mut App) -> Task<Result<(), String>> {
125-
let relay = Agents2::global(cx).and_then(|agents| {
126-
agents
127-
.read(cx)
125+
let route = Agents2::global(cx).and_then(|agents| {
126+
let agents = agents.read(cx);
127+
let agent = agents
128128
.running()
129129
.iter()
130-
.find(|agent| agent.pubkey == delivery.agent.pubkey)
131-
.map(|agent| agent.relay.clone())
130+
.find(|agent| agent.pubkey == delivery.agent.pubkey)?;
131+
let community = agents.relay(&agent.pubkey)?;
132+
let channel = delivery.channel.as_deref()?;
133+
let direct_message = community
134+
.read(cx)
135+
.snapshot
136+
.channels
137+
.iter()
138+
.find(|item| item.id == channel)?
139+
.channel_type
140+
== Some(buzz_relay_client::ChannelType::Dm);
141+
Some((agent.relay.clone(), direct_message))
132142
});
133-
let Some(relay) = relay else {
134-
return Task::ready(Err("The agent is not running in a community".into()));
143+
let Some((relay, direct_message)) = route else {
144+
return Task::ready(Err(
145+
"Open the conversation before starting its remote agent.".into(),
146+
));
135147
};
136148
let name = delivery.agent.name.clone();
137-
let started = crate::runtime::Runtime::handle(cx).spawn(deliver(delivery, relay));
149+
let started =
150+
crate::runtime::Runtime::handle(cx).spawn(deliver(delivery, relay, direct_message));
138151
cx.spawn(async move |cx| {
139152
let sent = started
140153
.await
@@ -155,8 +168,12 @@ impl AgentType for RemoteWorkspace {
155168
/// The session a mention starts, and how its start ended. Watches, timers
156169
/// and mentions from anyone but the owner start nothing; a mention that
157170
/// cannot start one fails before anything is sent.
158-
pub(crate) async fn deliver(delivery: Delivery, relay: String) -> Result<Option<Sent>, String> {
159-
let Some(start) = start_of(&delivery, relay) else {
171+
pub(crate) async fn deliver(
172+
delivery: Delivery,
173+
relay: String,
174+
direct_message: bool,
175+
) -> Result<Option<Sent>, String> {
176+
let Some(start) = start_of(&delivery, relay, direct_message) else {
160177
return Ok(None);
161178
};
162179
let (session, replay_floor) = start?;
@@ -192,7 +209,11 @@ pub(crate) struct Sent {
192209

193210
/// The mention's thread session and the time the harness replays from,
194211
/// for a mention by the owner or an agent it attested.
195-
fn start_of(delivery: &Delivery, relay: String) -> Option<Result<(SandboxSession, u64), String>> {
212+
fn start_of(
213+
delivery: &Delivery,
214+
relay: String,
215+
direct_message: bool,
216+
) -> Option<Result<(SandboxSession, u64), String>> {
196217
let Trigger::Mention { event } = &delivery.trigger else {
197218
return None;
198219
};
@@ -213,9 +234,15 @@ fn start_of(delivery: &Delivery, relay: String) -> Option<Result<(SandboxSession
213234
relay,
214235
signer: agent.owner.clone(),
215236
},
216-
scope: SandboxScope {
217-
channel_id: channel,
218-
thread_root: crate::agents2::working::thread_root(event),
237+
scope: if direct_message {
238+
SandboxScope::DirectMessage {
239+
dm_channel_id: channel,
240+
}
241+
} else {
242+
SandboxScope::Thread {
243+
channel_id: channel,
244+
thread_root: crate::agents2::working::thread_root(event),
245+
}
219246
},
220247
spec: config.spec(&agent.name, delivery.team.as_deref()),
221248
};

‎apps/buzz-gpui/crates/app/src/agent_plugins/remote_workspace/recovery.rs‎

Lines changed: 50 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
use super::{Sent, send};
88
use crate::agents2::Agents2;
99
use crate::ui::thread_banners::{self, Banner, BannerButton, BannerThread, ThreadBanner};
10+
use buzz_host::api::SandboxScope;
1011
use buzz_host::api::{EndState, RecoveryMode, SandboxRequest, SandboxResponse, SandboxSession};
1112
use buzz_remote_sessions::{
1213
RecoveryKind, RecoveryPrompt, RecoveryPromptKey, RecoveryPrompts, SessionError, SessionScope,
@@ -152,11 +153,15 @@ pub struct Prompts {
152153
impl Global for Prompts {}
153154

154155
fn key_of(session: &SandboxSession) -> Option<(RecoveryPromptKey, SessionScope)> {
155-
let scope = SessionScope::new(
156-
session.scope.channel_id.parse().ok()?,
157-
session.scope.thread_root.clone(),
158-
)
159-
.ok()?;
156+
let scope = match &session.scope {
157+
SandboxScope::Thread {
158+
channel_id,
159+
thread_root,
160+
} => SessionScope::new(channel_id.parse().ok()?, thread_root.clone()).ok()?,
161+
SandboxScope::DirectMessage { dm_channel_id } => SessionScope::DirectMessage {
162+
dm_channel_id: dm_channel_id.parse().ok()?,
163+
},
164+
};
160165
let key = RecoveryPromptKey::new(
161166
&session.tenant.relay,
162167
&session.tenant.signer,
@@ -237,8 +242,15 @@ impl Prompts {
237242
let Ok(channel) = thread.channel.parse() else {
238243
return Vec::new();
239244
};
240-
let Ok(scope) = SessionScope::new(channel, thread.root.clone()) else {
241-
return Vec::new();
245+
let scope = if thread.root.is_empty() {
246+
SessionScope::DirectMessage {
247+
dm_channel_id: channel,
248+
}
249+
} else {
250+
let Ok(scope) = SessionScope::new(channel, thread.root.clone()) else {
251+
return Vec::new();
252+
};
253+
scope
242254
};
243255
let relay = |url: &str| url.trim().trim_end_matches('/').to_owned();
244256
self.prompts
@@ -386,7 +398,7 @@ mod tests {
386398
relay: "wss://relay.example".into(),
387399
signer: "a".repeat(64),
388400
},
389-
scope: SandboxScope {
401+
scope: SandboxScope::Thread {
390402
channel_id: "f9ee507e-d03c-4570-baa6-02951c38e1cd".into(),
391403
thread_root: root.to_string().repeat(64),
392404
},
@@ -464,7 +476,7 @@ mod tests {
464476
panic!("expected recovery request")
465477
};
466478
assert_eq!(requested, mode);
467-
assert_eq!(session.scope.thread_root, "c".repeat(64));
479+
assert_eq!(session.scope, self::session('c').scope);
468480
assert_eq!(replay_floor, Some(1_700_000_123));
469481
}
470482
}
@@ -491,6 +503,35 @@ mod tests {
491503
assert!(prompts.for_thread(&thread('c')).is_empty());
492504
}
493505

506+
#[test]
507+
fn a_dm_recovery_is_visible_in_its_conversation_and_replays_the_request() {
508+
let mut sent = sent('c', Err(coded("session_ended")));
509+
sent.session.scope = SandboxScope::DirectMessage {
510+
dm_channel_id: thread('c').channel,
511+
};
512+
let mut prompts = Prompts::default();
513+
assert!(prompts.started(&sent, "Ada"));
514+
let mut conversation = thread('c');
515+
conversation.root.clear();
516+
let shown = prompts.for_thread(&conversation);
517+
assert_eq!(shown.len(), 1);
518+
let Some(SandboxRequest::Recover {
519+
session,
520+
replay_floor,
521+
..
522+
}) = shown[0]
523+
.1
524+
.request(Action::Recover(RecoveryMode::Checkpoint))
525+
else {
526+
panic!("expected recover");
527+
};
528+
assert_eq!(session.scope, sent.session.scope);
529+
assert_eq!(replay_floor, Some(sent.replay_floor));
530+
assert!(prompts.for_thread(&thread('c')).is_empty());
531+
conversation.channel = uuid::Uuid::new_v4().to_string();
532+
assert!(prompts.for_thread(&conversation).is_empty());
533+
}
534+
494535
#[test]
495536
fn an_end_reply_picks_the_next_banner() {
496537
let mut prompts = Prompts::default();

‎apps/buzz-gpui/crates/app/src/agent_plugins/remote_workspace/tests.rs‎

Lines changed: 53 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -149,6 +149,7 @@ async fn a_mention_starts_its_threads_session() {
149149
link,
150150
),
151151
RELAY.into(),
152+
false,
152153
)
153154
.await
154155
.unwrap();
@@ -175,8 +176,13 @@ async fn a_mention_starts_its_threads_session() {
175176
};
176177
assert_eq!(replay_floor, Some(1_700_000_123));
177178
assert_eq!(session.pubkey, "b".repeat(64));
178-
assert_eq!(session.scope.channel_id, CHANNEL);
179-
assert_eq!(session.scope.thread_root, root);
179+
assert_eq!(
180+
session.scope,
181+
SandboxScope::Thread {
182+
channel_id: CHANNEL.into(),
183+
thread_root: root
184+
}
185+
);
180186
assert_eq!(session.tenant.relay, RELAY);
181187
assert_eq!(session.tenant.signer, OWNER);
182188
let config: serde_json::Value =
@@ -229,7 +235,7 @@ async fn watches_timers_and_strangers_start_nothing() {
229235
event: Arc::new(stranger),
230236
};
231237
for trigger in [watch, timer, stranger] {
232-
let started = deliver(delivery(trigger, link.clone()), RELAY.into()).await;
238+
let started = deliver(delivery(trigger, link.clone()), RELAY.into(), false).await;
233239
assert!(matches!(started, Ok(None)), "{started:?}");
234240
}
235241
assert!(sent.lock().unwrap().is_empty());
@@ -359,7 +365,7 @@ async fn a_relay_mention_starts_its_session_through_the_host() {
359365
"provider": "relay",
360366
"provider_config": {"relay_url": RELAY, "manager_pubkey": MANAGER},
361367
});
362-
let started = deliver(delivery, RELAY.into()).await.unwrap();
368+
let started = deliver(delivery, RELAY.into(), false).await.unwrap();
363369
assert!(
364370
matches!(
365371
started,
@@ -462,3 +468,46 @@ fn agents_run_through_the_sandbox_manager() {
462468
assert_eq!(other.provider, "relay");
463469
assert!(other.validate().is_err(), "the relay takes no namespace");
464470
}
471+
472+
#[tokio::test]
473+
async fn plain_owner_messages_in_one_dm_start_the_same_conversation_scope() {
474+
let (link, sent) = host().await;
475+
for id in ["a".repeat(64), "b".repeat(64)] {
476+
let mut event = (*mention(&"c".repeat(64))).clone();
477+
event.id = id;
478+
event
479+
.tags
480+
.retain(|tag| tag.first().map(String::as_str) == Some("h"));
481+
let started = deliver(
482+
delivery(
483+
Trigger::Mention {
484+
event: Arc::new(event),
485+
},
486+
link.clone(),
487+
),
488+
RELAY.into(),
489+
true,
490+
)
491+
.await
492+
.unwrap()
493+
.unwrap();
494+
assert!(started.result.is_ok());
495+
}
496+
for request in sent.lock().unwrap().iter() {
497+
let SandboxRequest::Start {
498+
session,
499+
replay_floor,
500+
} = request
501+
else {
502+
panic!("expected start");
503+
};
504+
assert_eq!(
505+
session.scope,
506+
SandboxScope::DirectMessage {
507+
dm_channel_id: CHANNEL.into()
508+
}
509+
);
510+
assert_eq!(*replay_floor, Some(1_700_000_123));
511+
}
512+
assert_eq!(sent.lock().unwrap().len(), 2);
513+
}

‎apps/buzz-gpui/crates/app/src/agents2/service.rs‎

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@ use crate::runtime::Runtime;
3636
use buzz_host::api::{AppAgentRequest, AppAgentResponse, AppAgentSummary, PortableAgent};
3737
use buzz_host_rpc::ConnectionState;
3838
use buzz_identity::Identity;
39-
use buzz_relay_client::{LiveBatch, RelayOrigin, Session, SessionStatus};
39+
use buzz_relay_client::{ChannelType, LiveBatch, RelayOrigin, Session, SessionStatus};
4040
use futures::FutureExt as _;
4141
use gpui_kit::{App, AppContext, Context, Entity, EntityId, Global, Subscription, Task};
4242
use serde_json::Value;
@@ -516,6 +516,7 @@ pub(crate) fn heard(
516516
event: &Arc<EventData>,
517517
wrote: &dyn Fn(&str) -> bool,
518518
watches: &[CompiledWatch],
519+
direct_message: bool,
519520
) -> Vec<Trigger> {
520521
let mention = || {
521522
vec![Trigger::Mention {
@@ -533,7 +534,7 @@ pub(crate) fn heard(
533534
Vec::new()
534535
};
535536
}
536-
if addressed_to(event, agent, wrote) {
537+
if (direct_message && event.pubkey == owner) || addressed_to(event, agent, wrote) {
537538
return if CHAT_KINDS.contains(&event.kind) {
538539
mention()
539540
} else {
@@ -1715,6 +1716,15 @@ impl Agents2 {
17151716
.attention_enabled
17161717
.then(|| self.relay(&agent.pubkey))
17171718
.flatten();
1719+
let direct_message = self.relay(&agent.pubkey).is_some_and(|community| {
1720+
batch.channel.as_deref().is_some_and(|id| {
1721+
community.read(cx).snapshot.channels.iter().any(|channel| {
1722+
channel.id == id
1723+
&& channel.channel_type == Some(ChannelType::Dm)
1724+
&& channel.members.contains(&agent.pubkey)
1725+
})
1726+
})
1727+
});
17181728
let Some(runner) = self.runners.get_mut(&agent.pubkey) else {
17191729
continue;
17201730
};
@@ -1753,7 +1763,14 @@ impl Agents2 {
17531763
.as_ref()
17541764
.is_some_and(|community| member(community, &agent.pubkey, event, cx));
17551765
let watches: &[CompiledWatch] = if watching { &watches } else { &[] };
1756-
for trigger in heard(&agent.pubkey, &agent.owner, event, &wrote, watches) {
1766+
for trigger in heard(
1767+
&agent.pubkey,
1768+
&agent.owner,
1769+
event,
1770+
&wrote,
1771+
watches,
1772+
direct_message,
1773+
) {
17571774
let matched = match &trigger {
17581775
Trigger::Watch { slug, .. } => agent
17591776
.attention

0 commit comments

Comments
 (0)