Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions crates/agent-chat/src/seat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@ pub trait ChatWorkspace: 'static {
/// Foreground and background terminals; none once the workspace closed.
fn terminals(&self, cx: &App) -> Option<Vec<TerminalEntry>>;
fn connections(&self, cx: &App) -> Vec<ConnectionSummary>;
/// Metadata of this seat's original live workspace, independent of visible tabs.
fn workspace_description(&self, _cx: &App) -> Option<nocterm_ai::context::WorkspaceDescriptor> {
None
}
/// Whether saved connections can be opened in this window.
fn opens_connections(&self, cx: &App) -> bool;
/// Calls `changed` whenever the workspace's membership or placement
Expand Down
4 changes: 3 additions & 1 deletion crates/agent-chat/src/thread.rs
Original file line number Diff line number Diff line change
Expand Up @@ -201,8 +201,10 @@ impl AgentThread {
pub fn context(&mut self, cx: &App) -> String {
self.offer_tools(cx);
let input = self::tool_runtime::resolution::Resolution::observe(self.deps.seat(), cx);
let attachments = self.composer.default_attachments();
let workspace = self.deps.seat().workspace_description(cx);
self.tools
.context(&input, self.composer.default_attachments(), cx)
.context(&input, attachments, workspace.as_ref(), cx)
}

pub fn offline_servers(&mut self, cx: &App) -> Vec<(ServerDescriptor, ConnectionSummary)> {
Expand Down
90 changes: 57 additions & 33 deletions crates/agent-chat/src/thread/connection_wait.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,6 @@ pub(super) enum ConnectionWaitError {
ConnectFailed,
#[error("Connecting to the server timed out.")]
Timeout,
#[error(
"The server is waiting for the user to sign in; ask them to finish signing in, then call list_terminals."
)]
VisiblePromptTimeout,
#[error(
"The server is waiting for the user to sign in from the chat or unlock the vault; ask them to, then call open_terminal again."
)]
HiddenPromptTimeout,
}
impl ConnectionWaitError {
pub(super) fn into_failure(self) -> nocterm_ai::ToolFailure {
Expand Down Expand Up @@ -135,31 +127,68 @@ impl WaitTarget {
}
}

/// One finite waiter owns timing and promotion decisions for its original receipt.
/// One waiter owns timing and promotion decisions for its original receipt.
/// Machine work has a finite deadline; an outstanding human sign-in question does not.
pub(in crate::thread) struct ConnectionWaitOperation {
target: WaitTarget,
started: Instant,
shown: bool,
waiting: bool,
}

const CONNECT_LIMIT: Duration = Duration::from_secs(60);
const CONNECT_POLL: Duration = Duration::from_millis(150);
const SIGN_IN_POLL: Duration = Duration::from_millis(500);

/// The current stretch of machine work. Each human answer starts a fresh stretch.
enum WaitPhase {
Connecting { deadline: Instant },
SigningIn,
}

impl WaitPhase {
fn connecting(now: Instant) -> Self {
Self::Connecting {
deadline: now + CONNECT_LIMIT,
}
}

fn poll_interval(&self) -> Duration {
match self {
Self::Connecting { .. } => CONNECT_POLL,
Self::SigningIn => SIGN_IN_POLL,
}
}

fn observe(&mut self, status: TerminalStatus, now: Instant) {
match status {
TerminalStatus::AwaitingVault | TerminalStatus::AwaitingUser => {
*self = Self::SigningIn;
}
TerminalStatus::Connecting if matches!(self, Self::SigningIn) => {
*self = Self::connecting(now);
}
_ => {}
}
}

fn expired(&self, now: Instant) -> bool {
matches!(self, Self::Connecting { deadline } if now >= *deadline)
}
}
impl ConnectionWaitOperation {
pub(in crate::thread) fn new(target: WaitTarget) -> Self {
Self {
target,
started: Instant::now(),
shown: false,
waiting: false,
}
}
pub(in crate::thread) async fn run(
mut self,
thread: &WeakEntity<AgentThread>,
cx: &mut AsyncApp,
) -> Result<serde_json::Value, ConnectionWaitError> {
let mut phase = WaitPhase::connecting(cx.background_executor().now());
let result = loop {
cx.background_executor()
.timer(Duration::from_millis(150))
.await;
cx.background_executor().timer(phase.poll_interval()).await;
let step = thread.update(cx, |thread, cx| {
thread.poll_connection_wait(&self.target, cx)
});
Expand All @@ -168,7 +197,7 @@ impl ConnectionWaitOperation {
Ok(Err(error)) => break Err(error),
Err(_) => break Err(ConnectionWaitError::ChatClosed),
};
if let Some(result) = self.advance(step, cx) {
if let Some(result) = self.advance(step, &mut phase, cx) {
break result;
}
};
Expand All @@ -184,14 +213,20 @@ impl ConnectionWaitOperation {
bool,
nocterm_ai::context::TerminalDescriptor,
),
phase: &mut WaitPhase,
cx: &mut AsyncApp,
) -> Option<Result<serde_json::Value, ConnectionWaitError>> {
let now = cx.background_executor().now();
if let Some(status) = step.0 {
phase.observe(status, now);
}
match step {
(Some(TerminalStatus::Connected), _, descriptor) => {
return Some(Ok(serde_json::json!({ "terminal": descriptor })));
}
(_, true, _) => self.waiting = true,
(Some(TerminalStatus::AwaitingUser), false, _) if !self.shown => {
(Some(TerminalStatus::AwaitingUser | TerminalStatus::AwaitingVault), false, _)
if !self.shown =>
{
self.shown = true;
let seat = self.target.seat.clone();
let item = self.target.expected.item();
Expand All @@ -204,19 +239,8 @@ impl ConnectionWaitOperation {
}
_ => {}
}
let limit = if self.shown || self.waiting {
Duration::from_secs(180)
} else {
Duration::from_secs(60)
};
(self.started.elapsed() >= limit).then(|| {
Err(if self.shown {
ConnectionWaitError::VisiblePromptTimeout
} else if self.waiting {
ConnectionWaitError::HiddenPromptTimeout
} else {
ConnectionWaitError::Timeout
})
})
phase
.expired(now)
.then_some(Err(ConnectionWaitError::Timeout))
}
}
1 change: 1 addition & 0 deletions crates/agent-chat/src/thread/queue.rs
Original file line number Diff line number Diff line change
Expand Up @@ -336,6 +336,7 @@ impl AgentThread {
if self.deps.seat().id() != target.seat().id()
|| self.registration().as_ref().map(|value| value.id) != target.registration()
|| !self.session.session_current(target.ticket())
|| self.session.stopped()
|| !self.session.accepts_updates()
|| !self.deps.enabled(cx)
{
Expand Down
3 changes: 2 additions & 1 deletion crates/agent-chat/src/thread/tool_runtime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -270,9 +270,10 @@ impl ToolRuntime {
&mut self,
input: &resolution::Resolution,
defaults: &[Attachment],
workspace: Option<&nocterm_ai::context::WorkspaceDescriptor>,
cx: &gpui::App,
) -> String {
self.turn.context(input, defaults, cx)
self.turn.context(input, defaults, workspace, cx)
}
/// Tells the chat's bridge what it offers the agent: the file tools only while an attached
/// terminal takes them. The bridge tells a connected agent when that changes.
Expand Down
3 changes: 2 additions & 1 deletion crates/agent-chat/src/thread/tool_runtime/turn_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,7 @@ impl TurnContext {
&mut self,
input: &super::resolution::Resolution,
defaults: &[Attachment],
workspace: Option<&nocterm_ai::context::WorkspaceDescriptor>,
cx: &App,
) -> String {
let terminals: Vec<_> = self
Expand All @@ -209,7 +210,7 @@ impl TurnContext {
.into_iter()
.map(|(server, _)| server)
.collect();
nocterm_ai::context::context_block(&terminals, &servers)
nocterm_ai::context::context_block_with_workspace(&terminals, &servers, workspace)
}
/// A human description of what `call` acts on, for its approval card.
pub(super) fn describe_target(
Expand Down
11 changes: 9 additions & 2 deletions crates/agent/src/panel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -528,21 +528,28 @@ impl AgentPanel {
impl AgentPanel {
pub(super) fn render_menu(&mut self, window: &Window, cx: &mut Context<Self>) -> AnyElement {
let kind = self.menus.current().cloned();
let value = self.menus.query(cx);
let query = if kind == Some(MenuKind::Context) {
value.trim().to_lowercase()
} else {
value.to_lowercase()
};
let attachment = matches!(kind, Some(MenuKind::Context)).then(|| match self.current() {
Some(thread) if chat_servers::takes_servers(thread.read(cx)) => {
chat_servers::ChatServersRenderer::render_menu(&thread, cx)
chat_servers::ChatServersRenderer::render_menu(&thread, &query, cx)
}
thread => attach::AttachmentMenuRenderer::render_attach_menu(
thread,
self.host.workspace().clone(),
&query,
cx,
),
});
let frame = menu::MenuFrame::new(
kind,
self.current(),
self.menus.query_input(),
self.menus.query(cx).to_lowercase(),
query,
self.host.window_agents(cx),
self.last_agent(cx),
self.focus.clone(),
Expand Down
35 changes: 22 additions & 13 deletions crates/agent/src/panel/attach.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,7 @@ impl AttachmentMenuRenderer {
pub(super) fn render_attach_menu(
thread: Option<Entity<AgentThread>>,
workspace: gpui_kit::WeakEntity<nocterm_workspace::Workspace>,
query: &str,
cx: &mut Context<AgentPanel>,
) -> AnyElement {
let (Some(thread), Some(workspace)) = (thread, workspace.upgrade()) else {
Expand All @@ -89,7 +90,7 @@ impl AttachmentMenuRenderer {
seat.opens_connections(cx)
.then(|| SavedServerOpen::Workspace(seat.clone()))
};
let rows = Self::active_rows(&terminals, &summaries, &thread, cx);
let rows = Self::active_rows(&terminals, &summaries, &thread, query, cx);
let mut sessions: HashMap<SharedString, Vec<&TerminalEntry>> = HashMap::new();
for entry in &terminals {
if let Some(profile) = entry
Expand All @@ -101,21 +102,26 @@ impl AttachmentMenuRenderer {
sessions.entry(profile).or_default().push(entry);
}
}
let mut menu =
v_flex()
.w_full()
.gap(px(2.))
.child(super::local_attachment::LocalAttachment::render(
&thread,
workspace.downgrade(),
cx,
));
let local = servers::matches_query("Local terminal", query);
let saved_rows = servers::server_rows(&summaries, query);
let empty = !local && rows.is_empty() && saved_rows.is_empty();
let mut menu = v_flex().w_full().gap(px(2.));
if local {
menu = menu.child(super::local_attachment::LocalAttachment::render(
&thread,
workspace.downgrade(),
cx,
));
}
if empty {
menu = menu.child(heading("No matching servers or terminals", cx));
}
if !rows.is_empty() {
menu = menu.child(heading("Active sessions", cx)).children(rows);
}
if !summaries.is_empty() {
if !saved_rows.is_empty() {
menu = menu.child(heading("Saved servers", cx));
for row in servers::server_rows(&summaries) {
for row in saved_rows {
menu = menu.child(match row {
servers::ServerRow::Folder(group) => Self::folder_row(group, &thread, cx),
servers::ServerRow::Server { summary, nested } => Self::server_row(
Expand All @@ -138,6 +144,7 @@ impl AttachmentMenuRenderer {
terminals: &[TerminalEntry],
summaries: &[ConnectionSummary],
thread: &Entity<AgentThread>,
query: &str,
cx: &mut Context<AgentPanel>,
) -> Vec<AnyElement> {
let seat = thread.read(cx).workspace_seat().clone();
Expand All @@ -159,7 +166,9 @@ impl AttachmentMenuRenderer {
continue;
}
}
rows.push(Self::terminal_row(entry, thread, seat.clone(), cx));
if servers::matches_query(&entry.title, query) {
rows.push(Self::terminal_row(entry, thread, seat.clone(), cx));
}
}
rows
}
Expand Down
26 changes: 25 additions & 1 deletion crates/agent/src/panel/chat_servers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ impl ChatServersRenderer {
/// The attach menu of a chat whose agent takes servers.
pub(super) fn render_menu(
thread: &Entity<AgentThread>,
query: &str,
cx: &mut Context<AgentPanel>,
) -> AnyElement {
let servers = offered(thread.read(cx));
Expand All @@ -95,7 +96,30 @@ impl ChatServersRenderer {
),
);
}
for (index, server) in servers.into_iter().enumerate() {
let had_servers = !servers.is_empty();
let mut matches = servers
.into_iter()
.enumerate()
.filter(|(_, server)| {
super::servers::matches_query(&server.option.name, query)
|| server
.option
.description
.as_deref()
.is_some_and(|address| super::servers::matches_query(address, query))
})
.peekable();
if had_servers && matches.peek().is_none() {
menu = menu.child(
div()
.px_2()
.py_1()
.text_xs()
.text_color(cx.theme().muted_foreground)
.child("No matching servers"),
);
}
for (index, server) in matches {
menu = menu.child(Self::row(thread, index, server, busy, cx));
}
menu.into_any_element()
Expand Down
7 changes: 4 additions & 3 deletions crates/agent/src/panel/composer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -409,12 +409,13 @@ impl AgentPanel {
&mut self,
kind: MenuKind,
open: bool,
window: &mut Window,
cx: &mut Context<Self>,
) {
if open {
self.menus.open(kind);
} else {
self.menus.close_if_same(&kind);
self.menus.open_with_window(kind, window, cx);
} else if self.menus.close_if_same(&kind) && kind == MenuKind::Context {
self.focus_composer(window, cx);
}
cx.notify();
}
Expand Down
2 changes: 2 additions & 0 deletions crates/agent/src/panel/local_attachment.rs
Original file line number Diff line number Diff line change
Expand Up @@ -114,13 +114,15 @@ impl LocalAttachment {
if let Some(entry) = Self::terminal(original.read(cx), cx) {
owner.update(cx, |panel, cx| {
panel.on_attachment_selected(origin, Attachment::Terminal(entry.item), cx);
panel.focus_composer(window, cx);
});
} else {
owner.update(cx, |panel, cx| {
panel.notices.set_error(Some(
"Could not open a local terminal. Try opening it from the terminal menu."
.into(),
));
panel.focus_composer(window, cx);
cx.notify();
});
}
Expand Down
Loading
Loading