Skip to content

Commit 3ffc220

Browse files
committed
feat(gpui): let plugins add thread banners and long host requests
HostLink::sandbox sends a remote workspace request with request_within, waiting 660 s for a start or recovery, 150 s for an end and 30 s for the rest, since a provider may take ten minutes where the client gives up after one. An older host's refusal reads as the "unsupported" code. A ThreadBanners registry lets a compiled-in slice add a note and buttons among a thread's status rows. Each banner is asked with the thread's community, channel and root, so a plugin can show one without changing thread.rs again. Signed-off-by: Tee8z <[email protected]>
1 parent b7bbea2 commit 3ffc220

5 files changed

Lines changed: 364 additions & 0 deletions

File tree

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

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ use super::service::Agents2;
1313
pub use super::working::Working;
1414
use buzz_host::api::{
1515
AppAgentEvent, AppAgentRequest, AppAgentResponse, HostProtocol, Request, Response,
16+
SandboxRequest, SandboxResponse,
1617
};
1718
use buzz_host_rpc::{HostClient, RpcError};
1819
use futures::FutureExt;
@@ -22,6 +23,7 @@ use serde_json::Value;
2223
use std::collections::{HashSet, VecDeque};
2324
use std::sync::atomic::{AtomicBool, Ordering};
2425
use std::sync::{Arc, Mutex};
26+
use std::time::Duration;
2527

2628
/// Why an agent woke.
2729
#[derive(Clone, Debug)]
@@ -189,6 +191,40 @@ impl HostLink {
189191
Err(error) => Err(error.to_string()),
190192
}
191193
}
194+
195+
/// Asks the host's remote workspace backend, waiting as long as the
196+
/// provider may take. A host from before this answers as one without
197+
/// a backend.
198+
pub(crate) async fn sandbox(&self, request: SandboxRequest) -> Result<SandboxResponse, String> {
199+
let client = self.client.clone();
200+
let within = sandbox_timeout(&request);
201+
let response = self
202+
.runtime
203+
.spawn(async move {
204+
client
205+
.request_within(Request::Sandbox(request), within)
206+
.await
207+
})
208+
.await
209+
.map_err(|_| "The request was cancelled".to_string())?;
210+
match response {
211+
Ok(Response::Sandbox(response)) => Ok(response),
212+
Ok(_) => Err("The host answered with something else".into()),
213+
Err(error) if error.is_unsupported() => Ok(SandboxResponse::unsupported()),
214+
Err(RpcError::Failed(message)) => Err(message),
215+
Err(error) => Err(error.to_string()),
216+
}
217+
}
218+
}
219+
220+
/// How long the GUI waits for a sandbox request: a little longer than the
221+
/// provider is given, 10 minutes to start a session and 2 to end one.
222+
fn sandbox_timeout(request: &SandboxRequest) -> Duration {
223+
match request {
224+
SandboxRequest::Start { .. } | SandboxRequest::Recover { .. } => Duration::from_secs(660),
225+
SandboxRequest::End { .. } => Duration::from_secs(150),
226+
SandboxRequest::Providers | SandboxRequest::Lifecycle { .. } => Duration::from_secs(30),
227+
}
192228
}
193229

194230
/// The 2,048 most recent ids, as the spec asks for at least.
@@ -461,3 +497,6 @@ impl AgentHandle {
461497
}
462498
}
463499
}
500+
501+
#[cfg(test)]
502+
mod tests;
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
use super::*;
2+
use buzz_host::api::{
3+
HostAnswer, HostAsk, HostEvent, LaunchSpec, SANDBOX_UNSUPPORTED, SandboxSession,
4+
};
5+
use buzz_host_rpc::{
6+
ClientHandler, ConnectionState, EventSource, HostClientOptions, HostHandler, HostInfo, Peer,
7+
ServerOptions, serve, transport,
8+
};
9+
use futures::future::BoxFuture;
10+
use tokio::sync::broadcast;
11+
12+
/// A host whose backend takes 90 seconds to start a session, and that
13+
/// predates every other sandbox request.
14+
struct SlowHost(broadcast::Sender<(u64, HostEvent)>);
15+
16+
impl HostHandler<HostProtocol> for SlowHost {
17+
fn info(&self) -> HostInfo {
18+
HostInfo {
19+
id: "devbox".into(),
20+
name: "Devbox".into(),
21+
platform: "linux".into(),
22+
version: "test".into(),
23+
}
24+
}
25+
26+
fn events(&self) -> EventSource<HostProtocol> {
27+
self.0.subscribe()
28+
}
29+
30+
fn handle(
31+
&self,
32+
_: Peer<HostProtocol>,
33+
request: Request,
34+
) -> BoxFuture<'static, Result<Response, RpcError>> {
35+
Box::pin(async move {
36+
match request {
37+
Request::Sandbox(SandboxRequest::Start { .. }) => {
38+
tokio::time::sleep(Duration::from_secs(90)).await;
39+
Ok(Response::Sandbox(SandboxResponse::Started))
40+
}
41+
// What a host answers for a request it cannot read.
42+
_ => Err(RpcError::Failed(
43+
"The other side does not support this request; update it.".into(),
44+
)),
45+
}
46+
})
47+
}
48+
}
49+
50+
struct NoAsks;
51+
52+
impl ClientHandler<HostProtocol> for NoAsks {
53+
fn handle(&self, _: HostAsk) -> BoxFuture<'static, Result<HostAnswer, RpcError>> {
54+
Box::pin(async { Err(RpcError::Failed("unexpected ask".into())) })
55+
}
56+
}
57+
58+
#[tokio::test(start_paused = true)]
59+
async fn a_start_may_take_longer_than_the_default_wait() {
60+
let (connector, listener) = transport::memory();
61+
let (events, _) = broadcast::channel(1);
62+
tokio::spawn(serve(
63+
listener,
64+
Arc::new(SlowHost(events)),
65+
ServerOptions::default(),
66+
));
67+
let client = Arc::new(HostClient::<HostProtocol>::spawn(
68+
&tokio::runtime::Handle::current(),
69+
Arc::new(connector),
70+
Arc::new(NoAsks),
71+
HostClientOptions::default(),
72+
));
73+
client
74+
.state()
75+
.wait_for(|state| matches!(state, ConnectionState::Connected { .. }))
76+
.await
77+
.unwrap();
78+
let start = SandboxRequest::Start {
79+
session: SandboxSession {
80+
pubkey: "a".repeat(64),
81+
tenant: Default::default(),
82+
scope: Default::default(),
83+
spec: LaunchSpec::default(),
84+
},
85+
replay_floor: None,
86+
};
87+
assert_eq!(
88+
client
89+
.request(Request::Sandbox(start.clone()))
90+
.await
91+
.unwrap_err(),
92+
RpcError::TimedOut,
93+
"the default wait is a minute"
94+
);
95+
96+
let link = HostLink {
97+
client,
98+
runtime: tokio::runtime::Handle::current(),
99+
};
100+
assert!(matches!(
101+
link.sandbox(start).await,
102+
Ok(SandboxResponse::Started)
103+
));
104+
match link.sandbox(SandboxRequest::Providers).await {
105+
Ok(SandboxResponse::Failed { code, .. }) => {
106+
assert_eq!(code.as_deref(), Some(SANDBOX_UNSUPPORTED))
107+
}
108+
other => panic!("expected an older host to be unsupported, got {other:?}"),
109+
}
110+
}

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,6 +74,7 @@ mod status;
7474
mod tab_drag;
7575
pub mod terminal;
7676
pub mod thread;
77+
pub mod thread_banners;
7778
pub(crate) mod time;
7879
pub mod toasts;
7980
mod typing;

‎apps/buzz-gpui/crates/app/src/ui/thread.rs‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -297,6 +297,7 @@ impl ThreadPanel {
297297
];
298298
// A selected message is revealed once its thread has loaded.
299299
subscriptions.push(cx.observe_self(|this, cx| this.reveal_target(cx)));
300+
subscriptions.push(super::thread_banners::observe(cx));
300301
let weak = cx.entity().downgrade();
301302
list.set_scroll_handler(move |event, _, cx| {
302303
if event.visible_range.start < LOAD_OLDER_WITHIN && event.is_scrolled {
@@ -1435,6 +1436,40 @@ impl Render for ThreadPanel {
14351436
);
14361437
}
14371438

1439+
let thread = super::thread_banners::BannerThread {
1440+
relay: self.community.read(cx).origin.websocket().to_owned(),
1441+
channel: self.channel.clone(),
1442+
root: self.root_id.to_hex(),
1443+
};
1444+
for (index, banner) in super::thread_banners::for_thread(&thread, cx)
1445+
.into_iter()
1446+
.enumerate()
1447+
{
1448+
status.push(note(banner.text).into_any_element());
1449+
if banner.buttons.is_empty() {
1450+
continue;
1451+
}
1452+
let buttons = banner.buttons.into_iter().enumerate().map(|(at, button)| {
1453+
let action = button.action;
1454+
Button::new(
1455+
ElementId::Name(format!("thread-banner-{index}-{at}").into()),
1456+
button.label,
1457+
)
1458+
.size(ButtonSize::Sm)
1459+
.loading(button.loading)
1460+
.on_click(move |_, window, cx| action(window, cx))
1461+
});
1462+
status.push(
1463+
div()
1464+
.px(px(16.))
1465+
.pb(px(12.))
1466+
.flex()
1467+
.gap(px(8.))
1468+
.children(buttons)
1469+
.into_any_element(),
1470+
);
1471+
}
1472+
14381473
let typing = typing::overlay(
14391474
&activity.humans,
14401475
Some(self.activity.clone()),

0 commit comments

Comments
 (0)