feat(acp): filter session/list by client tags (#13173)
Signed-off-by: Salman Mohammed <smohammed@squareup.com> Co-authored-by: piper <2c910ba970d83c8e7ce8d7d7c72b8f0f229e8a3d18cda630c633393205e76aa2@buzz> Co-authored-by: Jack Amadeo <jackamadeo@squareup.com>
This commit is contained in:
@@ -359,6 +359,50 @@ fn meta_string(
|
||||
Ok(Some(value.to_string()))
|
||||
}
|
||||
|
||||
const MAX_SESSION_TAGS: usize = 16;
|
||||
const MAX_SESSION_TAG_KEY_BYTES: usize = 128;
|
||||
const MAX_SESSION_TAG_VALUE_BYTES: usize = 1024;
|
||||
|
||||
/// Client-owned `key -> value` string labels from `_meta.tags`, sorted by key.
|
||||
fn meta_tags(meta: Option<&Meta>) -> Result<Vec<(String, String)>, agent_client_protocol::Error> {
|
||||
let invalid = |message: String| agent_client_protocol::Error::invalid_params().data(message);
|
||||
let Some(value) = meta.and_then(|m| m.get("tags")) else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
if value.is_null() {
|
||||
return Ok(Vec::new());
|
||||
}
|
||||
let Some(tags) = value.as_object() else {
|
||||
return Err(invalid("tags must be an object".to_string()));
|
||||
};
|
||||
if tags.len() > MAX_SESSION_TAGS {
|
||||
return Err(invalid(format!(
|
||||
"tags may have at most {MAX_SESSION_TAGS} entries"
|
||||
)));
|
||||
}
|
||||
let mut parsed = tags
|
||||
.iter()
|
||||
.map(|(key, value)| {
|
||||
if key.is_empty() || key.len() > MAX_SESSION_TAG_KEY_BYTES {
|
||||
return Err(invalid(format!(
|
||||
"tag keys must be 1-{MAX_SESSION_TAG_KEY_BYTES} bytes"
|
||||
)));
|
||||
}
|
||||
let Some(value) = value.as_str() else {
|
||||
return Err(invalid(format!("tag {key} must be a string")));
|
||||
};
|
||||
if value.len() > MAX_SESSION_TAG_VALUE_BYTES {
|
||||
return Err(invalid(format!(
|
||||
"tag {key} must be at most {MAX_SESSION_TAG_VALUE_BYTES} bytes"
|
||||
)));
|
||||
}
|
||||
Ok((key.clone(), value.to_string()))
|
||||
})
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
parsed.sort();
|
||||
Ok(parsed)
|
||||
}
|
||||
|
||||
fn agent_capabilities_meta() -> Option<Meta> {
|
||||
let mut goose = serde_json::Map::new();
|
||||
goose.insert("recipeParameterScopes".to_string(), serde_json::json!({}));
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::{
|
||||
build_session_info, is_acp_visible_session_type, meta_string, AcpConnection, ResultExt,
|
||||
ACP_VISIBLE_SESSION_TYPES,
|
||||
build_session_info, is_acp_visible_session_type, meta_string, meta_tags, AcpConnection,
|
||||
ResultExt, ACP_VISIBLE_SESSION_TYPES,
|
||||
};
|
||||
use crate::session::session_manager::{
|
||||
SessionListCursor, SessionListFilters, SessionListPageQuery, SessionType,
|
||||
@@ -26,10 +26,13 @@ struct SessionListCursorToken {
|
||||
|
||||
#[derive(Debug, Serialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct SessionListCursorFilters {
|
||||
struct SessionListCursorFilters<'a> {
|
||||
cwd: Option<String>,
|
||||
session_types: Vec<String>,
|
||||
keyword: Option<String>,
|
||||
// Omitted when empty so cursors issued before tags existed stay valid.
|
||||
#[serde(skip_serializing_if = "<[_]>::is_empty")]
|
||||
tags: &'a [(String, String)],
|
||||
only_sessions_with_messages: bool,
|
||||
}
|
||||
|
||||
@@ -105,6 +108,7 @@ fn session_list_filter_hash(
|
||||
cwd: Option<&std::path::Path>,
|
||||
session_types: &[SessionType],
|
||||
keyword: Option<&str>,
|
||||
tags: &[(String, String)],
|
||||
) -> Result<String, agent_client_protocol::Error> {
|
||||
let mut session_type_names = session_types
|
||||
.iter()
|
||||
@@ -115,6 +119,7 @@ fn session_list_filter_hash(
|
||||
cwd: cwd.map(|path| path.to_string_lossy().to_string()),
|
||||
session_types: session_type_names,
|
||||
keyword: keyword.map(ToString::to_string),
|
||||
tags,
|
||||
only_sessions_with_messages: true,
|
||||
};
|
||||
let bytes =
|
||||
@@ -127,6 +132,7 @@ fn decode_session_list_cursor(
|
||||
cwd: Option<&std::path::Path>,
|
||||
session_types: &[SessionType],
|
||||
keyword: Option<&str>,
|
||||
tags: &[(String, String)],
|
||||
) -> Result<Option<SessionListCursor>, agent_client_protocol::Error> {
|
||||
let Some(cursor) = cursor else {
|
||||
return Ok(None);
|
||||
@@ -142,7 +148,7 @@ fn decode_session_list_cursor(
|
||||
return Err(invalid_session_list_cursor("malformed session list cursor"));
|
||||
}
|
||||
|
||||
let expected_filter_hash = session_list_filter_hash(cwd, session_types, keyword)?;
|
||||
let expected_filter_hash = session_list_filter_hash(cwd, session_types, keyword, tags)?;
|
||||
if token.filter_hash != expected_filter_hash {
|
||||
return Err(invalid_session_list_cursor(
|
||||
"session list cursor does not match filters",
|
||||
@@ -160,11 +166,12 @@ fn encode_session_list_cursor(
|
||||
cwd: Option<&std::path::Path>,
|
||||
session_types: &[SessionType],
|
||||
keyword: Option<&str>,
|
||||
tags: &[(String, String)],
|
||||
) -> Result<String, agent_client_protocol::Error> {
|
||||
let token = SessionListCursorToken {
|
||||
sort_at: cursor.sort_at,
|
||||
session_id: cursor.session_id.clone(),
|
||||
filter_hash: session_list_filter_hash(cwd, session_types, keyword)?,
|
||||
filter_hash: session_list_filter_hash(cwd, session_types, keyword, tags)?,
|
||||
};
|
||||
let bytes =
|
||||
serde_json::to_vec(&token).internal_err_ctx("Failed to encode session list cursor")?;
|
||||
@@ -186,6 +193,7 @@ impl AcpConnection {
|
||||
let cwd = req.cwd.as_deref();
|
||||
let keyword = session_keyword_from_meta(req.meta.as_ref())?;
|
||||
let session_types = session_types_from_meta(req.meta.as_ref())?;
|
||||
let tags = meta_tags(req.meta.as_ref())?;
|
||||
let include_last_message_snippet =
|
||||
include_last_message_snippet_from_meta(req.meta.as_ref())?;
|
||||
let cursor = decode_session_list_cursor(
|
||||
@@ -193,6 +201,7 @@ impl AcpConnection {
|
||||
cwd,
|
||||
&session_types,
|
||||
keyword.as_deref(),
|
||||
&tags,
|
||||
)?;
|
||||
|
||||
// ACP clients see their own (Acp) sessions plus legacy User/Scheduled ones.
|
||||
@@ -204,6 +213,7 @@ impl AcpConnection {
|
||||
types: Some(&session_types),
|
||||
working_dir: cwd,
|
||||
keyword: keyword.as_deref(),
|
||||
tags: &tags,
|
||||
only_sessions_with_messages: true,
|
||||
},
|
||||
cursor: cursor.as_ref(),
|
||||
@@ -219,7 +229,7 @@ impl AcpConnection {
|
||||
.next_cursor
|
||||
.as_ref()
|
||||
.map(|cursor| {
|
||||
encode_session_list_cursor(cursor, cwd, &session_types, keyword.as_deref())
|
||||
encode_session_list_cursor(cursor, cwd, &session_types, keyword.as_deref(), &tags)
|
||||
})
|
||||
.transpose()?;
|
||||
Ok(ListSessionsResponse::new(session_infos).next_cursor(next_cursor))
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use crate::acp::custom_requests::GooseExtension;
|
||||
use crate::acp::server::{meta_string, validate_absolute_cwd, ResultExt};
|
||||
use crate::acp::server::{meta_string, meta_tags, validate_absolute_cwd, ResultExt};
|
||||
use crate::agents::ExtensionLoadResult;
|
||||
use crate::config::{Config, GooseMode};
|
||||
use crate::model_config::resolve_provider_and_model_config;
|
||||
@@ -32,6 +32,8 @@ struct NewSessionMetaFields {
|
||||
/// Client-supplied title, recorded as user-set so goose's own name
|
||||
/// generation leaves it alone. `None` when a recipe title took precedence.
|
||||
client_title: Option<String>,
|
||||
/// Client-owned labels that `session/list` can filter on via an index.
|
||||
tags: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
impl AcpConnection {
|
||||
@@ -212,6 +214,13 @@ impl AcpConnection {
|
||||
.apply()
|
||||
.await
|
||||
.internal_err_ctx("Failed to update session")?;
|
||||
if !config.meta.tags.is_empty() {
|
||||
self.services
|
||||
.session_manager
|
||||
.set_session_tags(session_id, &config.meta.tags)
|
||||
.await
|
||||
.internal_err_ctx("Failed to save session tags")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -278,6 +287,7 @@ fn new_session_meta_fields(
|
||||
// precedence it has today and a client title only replaces the
|
||||
// "New Chat" fallback.
|
||||
client_title: session_title.filter(|_| recipe_title(recipe).is_none()),
|
||||
tags: meta_tags(meta)?,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, LazyLock};
|
||||
use tracing::{info, warn};
|
||||
|
||||
pub const CURRENT_SCHEMA_VERSION: i32 = 17;
|
||||
pub const CURRENT_SCHEMA_VERSION: i32 = 18;
|
||||
pub const SESSIONS_FOLDER: &str = "sessions";
|
||||
pub const DB_NAME: &str = "sessions.db";
|
||||
const MILLISECOND_TIMESTAMP_THRESHOLD: i64 = 10_000_000_000;
|
||||
@@ -376,6 +376,7 @@ pub(crate) struct SessionListFilters<'a> {
|
||||
pub(crate) types: Option<&'a [SessionType]>,
|
||||
pub(crate) working_dir: Option<&'a Path>,
|
||||
pub(crate) keyword: Option<&'a str>,
|
||||
pub(crate) tags: &'a [(String, String)],
|
||||
pub(crate) only_sessions_with_messages: bool,
|
||||
}
|
||||
|
||||
@@ -553,6 +554,14 @@ impl SessionManager {
|
||||
self.storage.list_sessions_paged(query).await
|
||||
}
|
||||
|
||||
pub async fn set_session_tags(
|
||||
&self,
|
||||
session_id: &str,
|
||||
tags: &[(String, String)],
|
||||
) -> Result<()> {
|
||||
self.storage.set_session_tags(session_id, tags).await
|
||||
}
|
||||
|
||||
pub async fn list_all_sessions(&self) -> Result<Vec<Session>> {
|
||||
self.storage.list_sessions_by_types(None).await
|
||||
}
|
||||
@@ -1269,6 +1278,7 @@ impl SessionStorage {
|
||||
)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
Self::create_session_tags_table(&mut tx).await?;
|
||||
|
||||
// Create the inventory tables inside the same transaction so that a
|
||||
// second SessionStorage opening the same DB file never observes a
|
||||
@@ -1770,6 +1780,9 @@ impl SessionStorage {
|
||||
}
|
||||
}
|
||||
}
|
||||
18 => {
|
||||
Self::create_session_tags_table(tx).await?;
|
||||
}
|
||||
_ => {
|
||||
anyhow::bail!("Unknown migration version: {}", version);
|
||||
}
|
||||
@@ -1778,6 +1791,44 @@ impl SessionStorage {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn create_session_tags_table(tx: &mut sqlx::Transaction<'_, Sqlite>) -> Result<()> {
|
||||
sqlx::query(
|
||||
r#"
|
||||
CREATE TABLE IF NOT EXISTS session_tags (
|
||||
session_id TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
|
||||
key TEXT NOT NULL,
|
||||
value TEXT NOT NULL,
|
||||
PRIMARY KEY (session_id, key)
|
||||
)
|
||||
"#,
|
||||
)
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"CREATE INDEX IF NOT EXISTS idx_session_tags_key_value ON session_tags(key, value, session_id)",
|
||||
)
|
||||
.execute(&mut **tx)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn set_session_tags(&self, session_id: &str, tags: &[(String, String)]) -> Result<()> {
|
||||
let pool = self.pool().await?;
|
||||
let mut tx = pool.begin_with("BEGIN IMMEDIATE").await?;
|
||||
for (key, value) in tags {
|
||||
sqlx::query(
|
||||
"INSERT INTO session_tags (session_id, key, value) VALUES (?, ?, ?) ON CONFLICT(session_id, key) DO UPDATE SET value = excluded.value",
|
||||
)
|
||||
.bind(session_id)
|
||||
.bind(key)
|
||||
.bind(value)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
}
|
||||
tx.commit().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn create_session(
|
||||
&self,
|
||||
id: Option<&str>,
|
||||
@@ -2323,6 +2374,12 @@ impl SessionStorage {
|
||||
if filters.working_dir.is_some() {
|
||||
where_clauses.push("s.working_dir = ?".to_string());
|
||||
}
|
||||
for _ in filters.tags {
|
||||
where_clauses.push(
|
||||
"s.id IN (SELECT session_id FROM session_tags WHERE key = ? AND value = ?)"
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
if !keywords.is_empty() {
|
||||
where_clauses.push(message_keyword_clause(keywords.len()));
|
||||
}
|
||||
@@ -2406,6 +2463,9 @@ impl SessionStorage {
|
||||
if let Some(working_dir) = filters.working_dir {
|
||||
q = q.bind(working_dir.to_string_lossy().to_string());
|
||||
}
|
||||
for (key, value) in filters.tags {
|
||||
q = q.bind(key).bind(value);
|
||||
}
|
||||
for term in keywords {
|
||||
q = q.bind(term);
|
||||
}
|
||||
@@ -2550,6 +2610,11 @@ impl SessionStorage {
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
|
||||
sqlx::query("DELETE FROM session_tags WHERE session_id = ?")
|
||||
.bind(session_id)
|
||||
.execute(&mut *tx)
|
||||
.await?;
|
||||
|
||||
sqlx::query("DELETE FROM sessions WHERE id = ?")
|
||||
.bind(session_id)
|
||||
.execute(&mut *tx)
|
||||
@@ -4378,6 +4443,187 @@ mod tests {
|
||||
assert!(page.next_cursor.is_none());
|
||||
}
|
||||
|
||||
fn tags(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
|
||||
pairs
|
||||
.iter()
|
||||
.map(|(key, value)| (key.to_string(), value.to_string()))
|
||||
.collect()
|
||||
}
|
||||
|
||||
async fn list_ids_with_tags(sm: &SessionManager, filter: &[(String, String)]) -> Vec<String> {
|
||||
let types = [SessionType::User];
|
||||
let mut ids = sm
|
||||
.list_sessions_paged(SessionListPageQuery {
|
||||
filters: SessionListFilters {
|
||||
types: Some(&types),
|
||||
tags: filter,
|
||||
only_sessions_with_messages: true,
|
||||
..Default::default()
|
||||
},
|
||||
cursor: None,
|
||||
page_size: 10,
|
||||
include_last_message_snippet: false,
|
||||
})
|
||||
.await
|
||||
.unwrap()
|
||||
.sessions
|
||||
.into_iter()
|
||||
.map(|session| session.id)
|
||||
.collect::<Vec<_>>();
|
||||
ids.sort();
|
||||
ids
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_session_list_paged_filters_by_tags() {
|
||||
let temp_dir = TempDir::new().unwrap();
|
||||
let sm = SessionManager::new(temp_dir.path().to_path_buf());
|
||||
let thread_one =
|
||||
create_session_for_list_with_message(&sm, "/tmp/session-list", "first").await;
|
||||
let thread_two =
|
||||
create_session_for_list_with_message(&sm, "/tmp/session-list", "second").await;
|
||||
create_session_for_list_with_message(&sm, "/tmp/session-list", "untagged").await;
|
||||
sm.set_session_tags(
|
||||
&thread_one,
|
||||
&tags(&[("buzz.channel", "c1"), ("buzz.thread", "t1")]),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
sm.set_session_tags(
|
||||
&thread_two,
|
||||
&tags(&[("buzz.channel", "c1"), ("buzz.thread", "t2")]),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
list_ids_with_tags(&sm, &tags(&[("buzz.thread", "t1")])).await,
|
||||
vec![thread_one.clone()]
|
||||
);
|
||||
let mut channel = vec![thread_one.clone(), thread_two.clone()];
|
||||
channel.sort();
|
||||
assert_eq!(
|
||||
list_ids_with_tags(&sm, &tags(&[("buzz.channel", "c1")])).await,
|
||||
channel
|
||||
);
|
||||
assert_eq!(
|
||||
list_ids_with_tags(&sm, &tags(&[("buzz.channel", "c1"), ("buzz.thread", "t2")])).await,
|
||||
vec![thread_two.clone()]
|
||||
);
|
||||
assert!(
|
||||
list_ids_with_tags(&sm, &tags(&[("buzz.channel", "t1")]))
|
||||
.await
|
||||
.is_empty(),
|
||||
"a value must match under its own key"
|
||||
);
|
||||
assert_eq!(list_ids_with_tags(&sm, &[]).await.len(), 3);
|
||||
|
||||
sm.set_session_tags(&thread_two, &tags(&[("buzz.thread", "t1")]))
|
||||
.await
|
||||
.unwrap();
|
||||
let mut retagged = vec![thread_one, thread_two];
|
||||
retagged.sort();
|
||||
assert_eq!(
|
||||
list_ids_with_tags(&sm, &tags(&[("buzz.thread", "t1")])).await,
|
||||
retagged
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_delete_session_removes_tags() {
|
||||
let temp_dir = TempDir::new().unwrap();
|
||||
let sm = SessionManager::new(temp_dir.path().to_path_buf());
|
||||
let session_id =
|
||||
create_session_for_list_with_message(&sm, "/tmp/session-list", "tagged").await;
|
||||
sm.set_session_tags(&session_id, &tags(&[("buzz.thread", "t1")]))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
sm.delete_session(&session_id).await.unwrap();
|
||||
|
||||
let pool = sm.storage().pool().await.unwrap();
|
||||
let remaining: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM session_tags")
|
||||
.fetch_one(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(remaining, 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_session_tag_filter_seeks_tag_index() {
|
||||
use sqlx::Row;
|
||||
|
||||
let temp_dir = TempDir::new().unwrap();
|
||||
let sm = SessionManager::new(temp_dir.path().to_path_buf());
|
||||
let pool = sm.storage().pool().await.unwrap();
|
||||
|
||||
let plan_rows = sqlx::query(
|
||||
"EXPLAIN QUERY PLAN \
|
||||
SELECT s.id FROM sessions s JOIN messages m ON s.id = m.session_id \
|
||||
WHERE s.session_type IN (?) AND s.working_dir = ? \
|
||||
AND s.id IN (SELECT session_id FROM session_tags WHERE key = ? AND value = ?) \
|
||||
GROUP BY s.id",
|
||||
)
|
||||
.bind("acp")
|
||||
.bind("/tmp")
|
||||
.bind("buzz.thread")
|
||||
.bind("t1")
|
||||
.fetch_all(pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let plan_text = plan_rows
|
||||
.iter()
|
||||
.map(|row| row.try_get::<String, _>("detail").unwrap_or_default())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
|
||||
assert!(
|
||||
plan_text.contains("idx_session_tags_key_value"),
|
||||
"tag filters should seek idx_session_tags_key_value, got: {plan_text}"
|
||||
);
|
||||
assert!(
|
||||
!plan_text.contains("SCAN s"),
|
||||
"tag filters must not scan every session, got: {plan_text}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_session_tags_migration() {
|
||||
let temp_dir = TempDir::new().unwrap();
|
||||
let db_path = temp_dir.path().join(SESSIONS_FOLDER).join(DB_NAME);
|
||||
std::fs::create_dir_all(db_path.parent().unwrap()).unwrap();
|
||||
let pool = SqlitePoolOptions::new()
|
||||
.connect_with(
|
||||
SqliteConnectOptions::new()
|
||||
.filename(&db_path)
|
||||
.create_if_missing(true),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
SessionStorage::create_schema(&pool).await.unwrap();
|
||||
sqlx::query("DROP TABLE session_tags")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
sqlx::query("UPDATE schema_version SET version = 17")
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
pool.close().await;
|
||||
|
||||
let sm = SessionManager::new(temp_dir.path().to_path_buf());
|
||||
let session_id =
|
||||
create_session_for_list_with_message(&sm, "/tmp/session-list", "migrated").await;
|
||||
sm.set_session_tags(&session_id, &tags(&[("buzz.thread", "t1")]))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(
|
||||
list_ids_with_tags(&sm, &tags(&[("buzz.thread", "t1")])).await,
|
||||
vec![session_id]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_session_list_paged_keyword_uses_or_terms() {
|
||||
let temp_dir = TempDir::new().unwrap();
|
||||
@@ -4534,6 +4780,7 @@ mod tests {
|
||||
working_dir: Some(Path::new("/tmp/session-list/a")),
|
||||
keyword: Some("postgres"),
|
||||
only_sessions_with_messages: true,
|
||||
..Default::default()
|
||||
};
|
||||
let cursor = sm
|
||||
.list_sessions_paged(SessionListPageQuery {
|
||||
|
||||
@@ -1156,6 +1156,160 @@ fn test_new_session_rejects_non_string_meta_session_title() {
|
||||
});
|
||||
}
|
||||
|
||||
fn tags_meta(value: serde_json::Value) -> serde_json::Map<String, serde_json::Value> {
|
||||
let mut meta = serde_json::Map::new();
|
||||
meta.insert("tags".to_string(), value);
|
||||
meta
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_list_sessions_filters_by_tags_from_new_session() {
|
||||
run_test(async {
|
||||
let data_root = tempfile::tempdir().unwrap();
|
||||
let conn = new_connection(data_root.path()).await;
|
||||
let work_dir = tempfile::tempdir().unwrap();
|
||||
let mut session_ids = Vec::new();
|
||||
for (thread, message) in [("t1", "first thread"), ("t2", "second thread")] {
|
||||
let session_id = new_session_with_meta(
|
||||
&conn,
|
||||
work_dir.path(),
|
||||
tags_meta(serde_json::json!({ "buzz.channel": "c1", "buzz.thread": thread })),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
SessionManager::new(data_root.path().to_path_buf())
|
||||
.add_message(&session_id, &Message::user().with_text(message))
|
||||
.await
|
||||
.unwrap();
|
||||
session_ids.push(session_id);
|
||||
}
|
||||
|
||||
let thread_one = list_sessions_request(
|
||||
&conn,
|
||||
ListSessionsRequest::new()
|
||||
.cwd(work_dir.path())
|
||||
.meta(tags_meta(serde_json::json!({ "buzz.thread": "t1" }))),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
thread_one
|
||||
.sessions
|
||||
.iter()
|
||||
.map(|session| session.session_id.0.to_string())
|
||||
.collect::<Vec<_>>(),
|
||||
vec![session_ids[0].clone()]
|
||||
);
|
||||
|
||||
let channel = list_sessions_request(
|
||||
&conn,
|
||||
ListSessionsRequest::new()
|
||||
.cwd(work_dir.path())
|
||||
.meta(tags_meta(serde_json::json!({ "buzz.channel": "c1" }))),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(channel.sessions.len(), 2);
|
||||
|
||||
let missing = list_sessions_request(
|
||||
&conn,
|
||||
ListSessionsRequest::new()
|
||||
.cwd(work_dir.path())
|
||||
.meta(tags_meta(serde_json::json!({ "buzz.thread": "t3" }))),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(missing.sessions.is_empty());
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_list_sessions_tag_cursor_is_bound_to_tags() {
|
||||
run_test(async {
|
||||
let data_root = tempfile::tempdir().unwrap();
|
||||
let cwd = tempfile::tempdir().unwrap();
|
||||
seed_list_sessions(data_root.path(), cwd.path(), 51).await;
|
||||
let session_manager = SessionManager::new(data_root.path().to_path_buf());
|
||||
for session in session_manager.list_all_sessions().await.unwrap() {
|
||||
session_manager
|
||||
.set_session_tags(&session.id, &[("buzz.channel".into(), "c1".into())])
|
||||
.await
|
||||
.unwrap();
|
||||
}
|
||||
let conn = new_connection(data_root.path()).await;
|
||||
|
||||
let first = list_sessions_request(
|
||||
&conn,
|
||||
ListSessionsRequest::new()
|
||||
.cwd(cwd.path())
|
||||
.meta(tags_meta(serde_json::json!({ "buzz.channel": "c1" }))),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(first.sessions.len(), 50);
|
||||
let cursor = first.next_cursor.unwrap();
|
||||
|
||||
let second = list_sessions_request(
|
||||
&conn,
|
||||
ListSessionsRequest::new()
|
||||
.cwd(cwd.path())
|
||||
.cursor(cursor.clone())
|
||||
.meta(tags_meta(serde_json::json!({ "buzz.channel": "c1" }))),
|
||||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(second.sessions.len(), 1);
|
||||
assert!(second.next_cursor.is_none());
|
||||
|
||||
let error = list_sessions_request(
|
||||
&conn,
|
||||
ListSessionsRequest::new().cwd(cwd.path()).cursor(cursor),
|
||||
)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_invalid_params(error);
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_new_session_and_list_sessions_reject_invalid_tags() {
|
||||
run_test(async {
|
||||
let data_root = tempfile::tempdir().unwrap();
|
||||
let conn = new_connection(data_root.path()).await;
|
||||
let work_dir = tempfile::tempdir().unwrap();
|
||||
let too_many = (0..17)
|
||||
.map(|index| (format!("key{index}"), serde_json::json!("value")))
|
||||
.collect::<serde_json::Map<_, _>>();
|
||||
|
||||
for tags in [
|
||||
serde_json::json!("buzz.thread"),
|
||||
serde_json::json!(["buzz.thread", "t1"]),
|
||||
serde_json::json!({ "buzz.thread": 1 }),
|
||||
serde_json::json!({ "": "t1" }),
|
||||
serde_json::json!({ "k".repeat(129): "t1" }),
|
||||
serde_json::json!({ "buzz.thread": "v".repeat(1025) }),
|
||||
serde_json::Value::Object(too_many),
|
||||
] {
|
||||
let error = new_session_with_meta(&conn, work_dir.path(), tags_meta(tags.clone()))
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_invalid_params(error);
|
||||
|
||||
let error =
|
||||
list_sessions_request(&conn, ListSessionsRequest::new().meta(tags_meta(tags)))
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert_invalid_params(error);
|
||||
}
|
||||
|
||||
let sessions = SessionManager::new(data_root.path().to_path_buf())
|
||||
.list_all_sessions()
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(sessions.is_empty());
|
||||
});
|
||||
}
|
||||
|
||||
/// Drives one naming-enabled turn and returns the session's title once name
|
||||
/// generation has had a chance to run.
|
||||
async fn title_after_naming_turn(
|
||||
|
||||
Reference in New Issue
Block a user