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
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/jcode-app-core/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ chrono = { version = "0.4", features = ["serde"] }
regex = "1"
urlencoding = "2" # URL encoding for web search
uuid = { version = "1", features = ["v4", "v5"] }
unicode-width = "0.2" # display-cell width for compact UI limits
jcode-applet-types = { path = "../jcode-applet-types" }

# Embeddings (local inference) live in jcode-base; this crate forwards the
Expand Down
41 changes: 38 additions & 3 deletions crates/jcode-app-core/src/agent/elicitation.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
//! Session UI capability changes invalidate the provider's locked tool surface.
//! Session UI capability changes register form tools and invalidate the locked
//! provider tool surface.
use super::*;
impl Agent {
pub(crate) async fn set_form_capabilities(&mut self, desktop: bool, applet: bool) {
self.register_ask_user().await;
if self.ui_capabilities == (desktop, applet) {
return;
}
Expand All @@ -16,8 +18,13 @@ impl Agent {
.await;
}
let mut allowed = self.allowed_tools.clone();
if applet && let Some(allowed) = allowed.as_mut() {
allowed.insert("applet".into());
if let Some(allowed) = allowed.as_mut() {
if applet {
allowed.insert("applet".into());
}
if desktop {
allowed.insert("user_response".into());
}
}
self._tool_policy_registration = crate::tool::register_session_tool_policy(
&self.session.id,
Expand All @@ -26,4 +33,32 @@ impl Agent {
);
self.invalidate_sdk_tools();
}

/// Register `ask_user` once any form-capable client attaches, before the
/// `(desktop, applet)` early return: a TUI reports `(false, false)`.
///
/// The registry is the source of truth, so `Agent` needs no extra field and
/// detaching never unregisters the tool. Registration invalidates the locked
/// surface once, because the first request may already have locked it.
async fn register_ask_user(&mut self) {
if !crate::elicitation::global().forms(&self.session.id) {
return;
}
if self
.registry
.tool_names()
.await
.iter()
.any(|name| name == "ask_user")
{
return;
}
self.registry
.register(
"ask_user".into(),
Arc::new(crate::elicitation::ask_user::AskUserTool),
)
.await;
self.invalidate_sdk_tools();
}
}
7 changes: 7 additions & 0 deletions crates/jcode-app-core/src/agent/turn_execution.rs
Original file line number Diff line number Diff line change
Expand Up @@ -677,6 +677,12 @@ impl Agent {
{
allowed.insert("applet".into());
}
if self.ui_capabilities.0
&& enabled.is_none()
&& let Some(allowed) = allowed.as_mut()
{
allowed.insert("user_response".into());
}
let mut tools = self.registry.definitions(allowed.as_ref()).await;
if enabled.is_none() && !self.disabled_tools.is_empty() {
tools.retain(|tool| {
Expand Down Expand Up @@ -1156,6 +1162,7 @@ impl Agent {
if let Some(allowed) = self.allowed_tools.as_ref()
&& !self.registry.tool_is_allowed(allowed, name)
&& !(name == "applet" && self.ui_capabilities.1)
&& !(name == "user_response" && self.ui_capabilities.0)
{
return Err(anyhow::anyhow!("Tool '{}' is not allowed", name));
}
Expand Down
138 changes: 138 additions & 0 deletions crates/jcode-app-core/src/agent_tests/elicitation.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
use super::*;

fn attach_form_client(
session: &str,
connection: &str,
) -> tokio::sync::mpsc::UnboundedReceiver<crate::protocol::ServerEvent> {
let (tx, rx) = tokio::sync::mpsc::unbounded_channel();
crate::elicitation::global().attach(connection, session, true, false, false, tx);
rx
}

#[tokio::test]
async fn applet_elicitation_capability_updates_locked_tool_surface() {
let mut agent = Agent::new(Arc::new(BoundSavedAccountProvider), Registry::empty());
Expand Down Expand Up @@ -45,3 +55,131 @@ async fn applet_elicitation_capability_updates_locked_tool_surface() {
assert!(agent.locked_tools.is_none());
assert!(!agent.tool_names().await.iter().any(|n| n == "applet"));
}

#[tokio::test]
async fn ask_user_registers_for_a_form_capable_client_and_survives_detach() {
let mut agent = Agent::new(Arc::new(BoundSavedAccountProvider), Registry::empty());
let session = agent.session_id().to_string();
assert!(agent.locked_tools.is_none());
let _ = agent.tool_definitions().await;
assert!(agent.locked_tools.is_some());

// Headless: no form-capable attachment, so the tool stays unregistered.
agent.set_form_capabilities(false, false).await;
assert!(
!agent
.tool_names()
.await
.iter()
.any(|name| name == "ask_user")
);

let _rx = attach_form_client(&session, "ask-user-capability-connection");
agent.set_form_capabilities(false, false).await;
assert!(
agent.locked_tools.is_none(),
"first registration must unlock the frozen surface"
);
assert!(
agent
.tool_names()
.await
.iter()
.any(|name| name == "ask_user")
);

// Already registered: a later capability change must not unlock again.
let _ = agent.tool_definitions().await;
assert!(agent.locked_tools.is_some());
agent.set_form_capabilities(false, false).await;
assert!(agent.locked_tools.is_some());

// Detach keeps the registry entry: no unregister, no cache churn.
crate::elicitation::global().detach("ask-user-capability-connection");
agent.set_form_capabilities(false, true).await;
assert!(
agent
.tool_names()
.await
.iter()
.any(|name| name == "ask_user")
);
agent.set_form_capabilities(false, false).await;
assert!(
agent
.tool_names()
.await
.iter()
.any(|name| name == "ask_user")
);
}

#[tokio::test]
async fn ask_user_is_offered_on_the_next_request_after_a_late_attach() {
let mut agent = Agent::new(Arc::new(BoundSavedAccountProvider), Registry::empty());
let session = agent.session_id().to_string();
let first = agent.tool_definitions().await;
assert!(!first.iter().any(|tool| tool.name == "ask_user"));
assert!(agent.locked_tools.is_some());

let _rx = attach_form_client(&session, "ask-user-late-connection");
agent.set_form_capabilities(false, false).await;
let next = agent.tool_definitions().await;
assert!(next.iter().any(|tool| tool.name == "ask_user"));
}

#[tokio::test]
async fn ask_user_is_not_forced_into_an_explicit_allowlist() {
let mut agent = Agent::new(Arc::new(BoundSavedAccountProvider), Registry::empty());
agent.allowed_tools = Some(["bash".to_string()].into_iter().collect());
let session = agent.session_id().to_string();
let _rx = attach_form_client(&session, "ask-user-allowlist-connection");
agent.set_form_capabilities(false, false).await;
assert!(
agent
.registry
.tool_names()
.await
.iter()
.any(|name| name == "ask_user"),
"the tool is registered"
);
assert!(
!agent
.tool_definitions()
.await
.iter()
.any(|tool| tool.name == "ask_user"),
"an explicit allowlist is respected"
);
}

#[tokio::test]
async fn hibernation_wake_keeps_registry_and_offered_tools_in_agreement() {
let _env = crate::storage::lock_test_env();
let mut agent = Agent::new(Arc::new(BoundSavedAccountProvider), Registry::empty());
let session = agent.session_id().to_string();
let _rx = attach_form_client(&session, "ask-user-hibernation-connection");
agent.set_form_capabilities(false, false).await;
let frozen = agent.tool_definitions().await;
assert!(frozen.iter().any(|tool| tool.name == "ask_user"));

crate::elicitation::global().detach("ask-user-hibernation-connection");
let _ = agent.hibernate_idle_caches();
let registered = agent
.registry
.tool_names()
.await
.iter()
.any(|name| name == "ask_user");
let offered = agent
.tool_definitions()
.await
.iter()
.any(|tool| tool.name == "ask_user");
assert_eq!(
offered, registered,
"the frozen surface and the registry must agree after an idle wake"
);
assert!(offered);
}
67 changes: 67 additions & 0 deletions crates/jcode-app-core/src/elicitation.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
//! Session-scoped form broker. A single mutex makes validation and winning atomic.
pub mod ask_user;

use crate::protocol::{
ServerEvent,
elicitation::{ElicitationResolution, ElicitationResponse, FormElicitation, FormSchema},
Expand Down Expand Up @@ -75,6 +77,14 @@ impl Broker {
ServerEvent::ElicitationRequest(pending.request.clone()),
);
}
// Mark the end of replay even when nothing was pending. Reconcile
// drafts against this boundary, never against a quiet interval.
send(
&events,
ServerEvent::ElicitationReplayComplete {
session_id: session.into(),
},
);
}
state.connections.insert(
connection.into(),
Expand Down Expand Up @@ -102,6 +112,14 @@ impl Broker {
.filter(|c| c.session == session)
.fold((false, false), |(d, a), c| (d || c.desktop, a || c.applet))
}
/// True when at least one live, form-capable connection is attached to the session.
pub fn forms(&self, session: &str) -> bool {
let state = self.state.lock().unwrap_or_else(|p| p.into_inner());
state
.connections
.values()
.any(|c| c.session == session && c.forms && !c.events.is_closed())
}
pub fn start(
self: &Arc<Self>,
session: &str,
Expand Down Expand Up @@ -292,11 +310,21 @@ mod tests {
broker.attach(id, "s", true, true, false, tx);
rx
}
fn expect_replay_complete(event: Option<ServerEvent>, session: &str) {
match event {
Some(ServerEvent::ElicitationReplayComplete { session_id }) => {
assert_eq!(session_id, session);
}
other => panic!("expected replay completion for {session}, got {other:?}"),
}
}
#[tokio::test]
async fn fanout_first_valid_reply_wins_and_invalid_reply_stays_pending() {
let broker = Arc::new(Broker::default());
let mut a = attach(&broker, "a");
let mut b = attach(&broker, "b");
expect_replay_complete(a.recv().await, "s");
expect_replay_complete(b.recv().await, "s");
let ticket = broker
.start("s", None, "Question".into(), schema())
.unwrap()
Expand Down Expand Up @@ -353,6 +381,7 @@ mod tests {
async fn reconnect_catches_up_and_turn_cancel_withdraws() {
let broker = Arc::new(Broker::default());
let mut a = attach(&broker, "a");
expect_replay_complete(a.recv().await, "s");
let ticket = broker
.start("s", None, "Question".into(), schema())
.unwrap()
Expand All @@ -364,6 +393,7 @@ mod tests {
b.recv().await,
Some(ServerEvent::ElicitationRequest(_))
));
expect_replay_complete(b.recv().await, "s");
assert_eq!(
ticket.wait(async {}, Duration::from_secs(1)).await,
ElicitOutcome::Cancelled
Expand All @@ -386,6 +416,7 @@ mod tests {
.is_none()
);
let mut a = attach(&broker, "a");
expect_replay_complete(a.recv().await, "s");
let ticket = broker
.start("s", None, "Question".into(), schema())
.unwrap()
Expand Down Expand Up @@ -417,4 +448,40 @@ mod tests {
));
assert!(broker.state.lock().unwrap().pending.is_empty());
}
#[tokio::test]
async fn replay_requests_precede_replay_complete() {
let broker = Arc::new(Broker::default());
let mut a = attach(&broker, "a");
expect_replay_complete(a.recv().await, "s");
let ticket = broker
.start("s", None, "Question".into(), schema())
.unwrap()
.unwrap();
assert!(matches!(
a.recv().await,
Some(ServerEvent::ElicitationRequest(_))
));
broker.detach("a");
let mut b = attach(&broker, "b");
match b.recv().await {
Some(ServerEvent::ElicitationRequest(request)) => {
assert_eq!(request.session_id, "s");
}
other => panic!("expected replayed request first, got {other:?}"),
}
expect_replay_complete(b.recv().await, "s");
assert!(b.try_recv().is_err());
drop(ticket);
}
#[tokio::test]
async fn empty_replay_completes_and_non_form_attach_does_not() {
let broker = Arc::new(Broker::default());
let mut a = attach(&broker, "a");
expect_replay_complete(a.recv().await, "s");
assert!(a.try_recv().is_err());

let (tx, mut plain) = mpsc::unbounded_channel();
broker.attach("plain", "s", false, true, false, tx);
assert!(plain.try_recv().is_err());
}
}
Loading
Loading