Skip to content
Open
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
60 changes: 59 additions & 1 deletion crates/assistant/src/relay.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
//! token is checked, and every read and write wait are bounded. A command whose reply does not
//! come in time is cancelled before the app can run it. Stopping the relay, or dropping its last
//! owner, closes the listener and every client and removes the token file.
use std::collections::{HashMap, VecDeque};
use std::collections::{BTreeMap, HashMap, VecDeque};
use std::io::{Read, Write};
use std::net::{Shutdown, SocketAddr, TcpListener, TcpStream};
use std::path::PathBuf;
Expand Down Expand Up @@ -159,6 +159,8 @@ struct Shared {
preauth: AtomicUsize,
/// Authenticated connections.
attached: AtomicUsize,
/// What the attached clients call themselves (MCP's `clientInfo.name`), by connection id.
clients: Mutex<BTreeMap<u64, String>>,
/// How long a request waits for the app before it is cancelled, unless its client asked for
/// another time.
reply_wait: Duration,
Expand Down Expand Up @@ -589,6 +591,7 @@ impl Relay {
next_id: AtomicU64::new(0),
preauth: AtomicUsize::new(0),
attached: AtomicUsize::new(0),
clients: Mutex::new(BTreeMap::new()),
reply_wait,
busy_after,
last_poll: Mutex::new(Instant::now()),
Expand Down Expand Up @@ -633,6 +636,13 @@ impl Relay {
self.owner.shared.attached.load(SeqCst)
}

/// The names the attached clients gave in their `initialize`, oldest connection first. One
/// that hasn't sent it isn't listed. A client's own word, for the user to read, never to
/// decide anything by.
pub fn client_names(&self) -> Vec<String> {
lock(&self.owner.shared.clients).values().cloned().collect()
}

/// Writes a request and how it went to the audit log, if there is one.
fn audit(&self, line: &str, reply: Option<&str>, took: Duration) {
// Out of the lock first, so changing the folder never waits on the disk.
Expand Down Expand Up @@ -1183,6 +1193,30 @@ fn asks_for_skills(line: &str) -> bool {
}
}

/// The most characters of a client's name kept.
const MAX_CLIENT_NAME: usize = 60;

/// What an `initialize` message calls its client: one line, without control or invisible formatting characters, cut to
/// [`MAX_CLIENT_NAME`].
fn client_name(msg: &Value) -> Option<String> {
if msg.get("method").and_then(Value::as_str) != Some("initialize") {
return None;
}
let name = msg.pointer("/params/clientInfo/name").and_then(Value::as_str)?;
let name: String = name
.chars()
.filter(|c| {
!c.is_control()
&& !matches!(
c,
'\u{AD}' | '\u{061C}' | '\u{200B}'..='\u{200F}' | '\u{2028}'..='\u{202E}' | '\u{2060}'..='\u{2069}' | '\u{FEFF}'
)
})
.take(MAX_CLIENT_NAME)
.collect();
Some(name.trim().to_string()).filter(|n| !n.is_empty())
}

/// Accepts connections until the relay is stopped, then closes the listener.
fn accept_loop(listener: TcpListener, shared: Arc<Shared>) {
while !shared.stopped.load(SeqCst) {
Expand Down Expand Up @@ -1212,6 +1246,7 @@ impl Drop for Slot {
fn drop(&mut self) {
lock(&self.shared.streams).remove(&self.id);
lock(&self.shared.granted).remove(&self.id);
lock(&self.shared.clients).remove(&self.id);
if self.preauth {
self.shared.preauth.fetch_sub(1, SeqCst);
}
Expand Down Expand Up @@ -1376,6 +1411,9 @@ fn connection(stream: TcpStream, slot: &mut Slot) {
if shared.access(&token, asked).is_none() {
return;
}
if let Some(name) = msg.as_ref().and_then(client_name) {
lock(&shared.clients).insert(slot.id, name);
}
let expects = expects_reply(&line);
let id = msg.as_ref().map_or(Value::Null, request_id);
let state = Arc::new(AtomicU8::new(PENDING));
Expand Down Expand Up @@ -2680,6 +2718,26 @@ mod tests {
relay.stop();
}

/// An attached client is named by its `initialize`, in one clipped line, until it leaves.
#[test]
fn relay_names_its_clients_while_they_stay() {
let relay = Relay::start(0).unwrap();
let mut client = TcpStream::connect(("127.0.0.1", relay.port())).unwrap();
attach(&mut client, &relay, false);
wait_until("the attach", || relay.attached_clients() == 1);
assert!(relay.client_names().is_empty(), "no name before initialize");
let name = format!("claude-code\n\u{7}\u{061C}\u{200B}\u{200D}\u{2028}\u{202E}\u{2066}\u{2069}\u{FEFF}{}", "x".repeat(200));
let hello = json!({"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"clientInfo": {"name": name}}});
writeln!(client, "{hello}").unwrap();
// The app answers it, and the connection reads on.
settle(&relay, &mut Session::new(Project::default()));
assert_eq!(relay.client_names(), vec![format!("claude-code{}", "x".repeat(49))]);
drop(client);
wait_until("the disconnect", || relay.attached_clients() == 0);
assert!(relay.client_names().is_empty());
relay.stop();
}

/// Stopping closes the listener and every client, removes the token, and drops the
/// attached count; a temporary clone that drops first does not stop the relay.
#[test]
Expand Down
17 changes: 12 additions & 5 deletions crates/ui-egui/src/agentthreads.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
//!
//! Threads end with a new conversation, when the user closes them, or after half an hour idle.

use std::path::PathBuf;
use std::path::{Path, PathBuf};
use std::time::Duration;

use egui::{Align, Layout, RichText, Ui, vec2};
Expand Down Expand Up @@ -101,10 +101,17 @@ impl Drop for Threads {
}
}

/// `rustgis-cli` beside the app.
fn cli() -> Option<PathBuf> {
let name = if cfg!(windows) { "rustgis-cli.exe" } else { "rustgis-cli" };
std::env::current_exe().ok().map(|p| p.with_file_name(name)).filter(|p| p.is_file())
pub(crate) const CLI_NAME: &str = if cfg!(windows) { "rustgis-cli.exe" } else { "rustgis-cli" };

/// The CLI shipped beside the app.
pub(crate) fn cli_beside(app_exe: &Path) -> Option<PathBuf> {
let cli = app_exe.with_file_name(CLI_NAME);
cli.is_file().then_some(cli)
}

/// The CLI shipped beside the running app.
pub(crate) fn cli() -> Option<PathBuf> {
std::env::current_exe().ok().as_deref().and_then(cli_beside)
}

/// Starts the tasks the assistant handed out, passes on what threads did, asked and reported,
Expand Down
18 changes: 9 additions & 9 deletions crates/ui-egui/src/approvalcard.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,15 @@ pub(crate) fn show(ui: &mut Ui, registry: &Registry, review: &Review) {
count => crate::i18n::fmt("{actions} · {count} project edits", &[("actions", &actions), ("count", &count.to_string())]),
};
ui.add(egui::Label::new(RichText::new(title).strong()).wrap());
// What a query does is its text, so it isn't left under Details.
for (_, query) in &queries {
ui.add(egui::Label::new(RichText::new(query).monospace().small()).wrap().selectable(true));
}
// Secrets are left out of what is shown (a CREATE SECRET's options, a key): said, so the
// text isn't taken for the whole query.
if review.sql_hidden {
ui.label(RichText::new(tl!("Secret values are hidden here, but the request runs with them.")).small().italics());
}
// These are starting defaults, not an exhaustive target list for a composite request.
if let Some((active, selected)) = &review.defaults {
ui.add(
Expand All @@ -52,15 +61,6 @@ pub(crate) fn show(ui: &mut Ui, registry: &Registry, review: &Review) {
);
}
ui.add(egui::Label::new(RichText::new(reason(review)).small()).wrap());
// What a query does is its text, so it isn't left under Details.
for (_, query) in &queries {
ui.add(egui::Label::new(RichText::new(query).monospace().small()).wrap().selectable(true));
}
// Secrets are left out of what is shown (a CREATE SECRET's options, a key): said, so the
// text isn't taken for the whole query.
if review.sql_hidden {
ui.label(RichText::new(tl!("Secret values are hidden here, but the request runs with them.")).small().italics());
}
for detail in &review.details {
let name = operation(registry, &detail.operation);
if !detail.targets.is_empty() {
Expand Down
10 changes: 10 additions & 0 deletions crates/ui-egui/src/assistant.rs
Original file line number Diff line number Diff line change
Expand Up @@ -438,6 +438,12 @@ pub(crate) fn toggle_settings(app: &mut RustGisApp) {
#[cfg(not(target_arch = "wasm32"))]
{
app.assistant.settings_pending = None;
// Asked for from the connect view: the settings show, whether or not they were open
// under it.
if std::mem::take(&mut app.connect.view) {
app.assistant.settings = true;
return;
}
}
app.assistant.settings = !app.assistant.settings;
}
Expand Down Expand Up @@ -1435,6 +1441,10 @@ fn to_box(state: &mut AssistantState, text: &str) {
/// be sent ([`AssistantState::sending_when_ready`]) isn't sent into the new one: it stays in the
/// box.
pub fn new_conversation(app: &mut RustGisApp) {
#[cfg(not(target_arch = "wasm32"))]
{
app.connect.view = false;
}
if let Some(a) = app.assistant.agent.as_mut() {
a.clear();
}
Expand Down
Loading
Loading