use std::time::Duration;
use gadk_session::{CreateRequest, InMemorySessionService, SessionService};
use crate::context::builder::test_support::{TestSession, session};
use crate::context::{ContextDelta, InvocationContext};
#[tokio::test]
async fn test_identity_from_context_recovers_identity() {
let s = InMemorySessionService::new()
.create(CreateRequest {
app_name: "app-1".into(),
user_id: "user-42".into(),
session_id: None,
state: None,
})
.await
.unwrap();
let session_id = s.id().to_string();
let ic = InvocationContext::builder().session(s).build_invocation();
let ctx = ic.clone().into_context();
let (cancel_ctx, _g1) = ctx.with_agent_cancel();
let (timeout_ctx, _g2) = ctx.with_agent_timeout(Duration::from_secs(60));
let tool_ctx = ctx.with_delta(ContextDelta {
function_call_id: Some("fc-1".into()),
..Default::default()
});
for c in [
ic,
ctx.as_invocation().clone(),
cancel_ctx.as_invocation().clone(),
timeout_ctx.as_invocation().clone(),
tool_ctx.as_invocation().clone(),
] {
assert_eq!(
(c.user_id(), c.app_name(), c.session_id()),
("user-42", "app-1", session_id.as_str())
);
}
}
#[test]
fn test_identity_from_context_session_shapes() {
for (name, s) in [
("pointer", session("app-1", "user-42", "sid-1")),
(
"struct value",
TestSession::shared("app-1", "user-42", "sid-1"),
),
] {
let ic = InvocationContext::builder().session(s).build_invocation();
let promoted = ic.clone().into_context();
let tool = promoted.with_delta(ContextDelta {
function_call_id: Some("fc-1".into()),
..Default::default()
});
for (ctx_name, c) in [
("invocation context", ic),
("promoted common context", promoted.as_invocation().clone()),
("tool context", tool.as_invocation().clone()),
] {
assert_eq!(
(c.user_id(), c.app_name(), c.session_id()),
("user-42", "app-1", "sid-1"),
"{name}/{ctx_name}"
);
}
}
}
#[test]
fn test_identity_does_not_inherit_enclosing_invocation() {
let outer = InvocationContext::builder()
.session(session("app-1", "alice", "s1"))
.build_invocation();
let inner = InvocationContext::builder()
.session(session("app-1", "inner", "s2"))
.cancellation_token(outer.cancellation_token().child_token())
.build_invocation();
let promoted = inner.clone().into_context();
let tool = promoted.with_delta(ContextDelta {
function_call_id: Some("fc-1".into()),
..Default::default()
});
for (name, c) in [
("inner", inner),
("promoted", promoted.as_invocation().clone()),
("tool context", tool.as_invocation().clone()),
] {
assert_eq!(
(c.user_id(), c.app_name(), c.session_id()),
("inner", "app-1", "s2"),
"{name}"
);
}
assert_eq!(outer.user_id(), "alice");
}