Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(ownership): agentsession register sessions in the entity table (#6538)
Will Hutchinsondd40615eb127
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex b88d777cd3..6eb1ab8da9 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -566,6 +566,8 @@"crates/entity_access","crates/entity_access_db_utils","crates/entity_mutation",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/filter_ast","crates/frecency","crates/genai_telemetry",@@ -636,6 +638,8 @@"crates/entity_access","crates/entity_access_db_utils","crates/entity_mutation",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/filter_ast","crates/frecency","crates/genai_telemetry",@@ -707,6 +711,8 @@"crates/entity_access","crates/entity_access_db_utils","crates/entity_mutation",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/filter_ast","crates/frecency","crates/genai_telemetry",@@ -1910,6 +1916,8 @@"crates/entity_access","crates/entity_access_db_utils","crates/entity_mutation",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/filter_ast","crates/frecency","crates/genai_telemetry",@@ -1981,6 +1989,8 @@"crates/entity_access","crates/entity_access_db_utils","crates/entity_mutation",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/filter_ast","crates/frecency","crates/genai_telemetry",@@ -2699,6 +2709,8 @@"crates/entity_access","crates/entity_access_db_utils","crates/entity_mutation",+ "crates/entity_registry/entity_registry_db_utils",+ "crates/entity_registry/shared_entity_registry","crates/filter_ast","crates/frecency","crates/genai_telemetry",diff --git a/.sqlx/query-447cda6d76bc084bf2e77548376992946a5ce9da67bc98ed48a9cd098a471158.json b/.sqlx/query-447cda6d76bc084bf2e77548376992946a5ce9da67bc98ed48a9cd098a471158.jsondeleted file mode 100644index 42b8fcfd95..0000000000--- a/.sqlx/query-447cda6d76bc084bf2e77548376992946a5ce9da67bc98ed48a9cd098a471158.json+++ /dev/null@@ -1,15 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE agent_session\n SET name = $2,\n modified_at = CASE\n WHEN name IS DISTINCT FROM $2 THEN NOW()\n ELSE modified_at\n END\n WHERE id = $1\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Text"- ]- },- "nullable": []- },- "hash": "447cda6d76bc084bf2e77548376992946a5ce9da67bc98ed48a9cd098a471158"-}diff --git a/.sqlx/query-aad539216d5e287af40906ecf02210ad257fb15bb39925716975c228b2a40155.json b/.sqlx/query-aad539216d5e287af40906ecf02210ad257fb15bb39925716975c228b2a40155.jsonnew file mode 100644index 0000000000..fbed5d8033--- /dev/null+++ b/.sqlx/query-aad539216d5e287af40906ecf02210ad257fb15bb39925716975c228b2a40155.json@@ -0,0 +1,29 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH previous AS (\n SELECT modified_at\n FROM agent_session\n WHERE id = $1\n FOR UPDATE\n )\n UPDATE agent_session\n SET name = $2,\n modified_at = CASE\n WHEN name IS DISTINCT FROM $2 THEN NOW()\n ELSE modified_at\n END\n WHERE id = $1\n RETURNING\n modified_at,\n (modified_at IS DISTINCT FROM (SELECT modified_at FROM previous)) AS \"bumped!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "modified_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 1,+ "name": "bumped!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text"+ ]+ },+ "nullable": [+ false,+ null+ ]+ },+ "hash": "aad539216d5e287af40906ecf02210ad257fb15bb39925716975c228b2a40155"+}diff --git a/.sqlx/query-c1da4b8398a6b09b770701c0035013a787782035d100c6b9ef2ba1c12c170e6e.json b/.sqlx/query-c1da4b8398a6b09b770701c0035013a787782035d100c6b9ef2ba1c12c170e6e.jsondeleted file mode 100644index 203d21413e..0000000000--- a/.sqlx/query-c1da4b8398a6b09b770701c0035013a787782035d100c6b9ef2ba1c12c170e6e.json+++ /dev/null@@ -1,16 +0,0 @@-{- "db_name": "PostgreSQL",- "query": "\n UPDATE agent_session\n SET name = $2,\n modified_at = NOW()\n WHERE id = $1\n AND name = $3\n ",- "describe": {- "columns": [],- "parameters": {- "Left": [- "Uuid",- "Text",- "Text"- ]- },- "nullable": []- },- "hash": "c1da4b8398a6b09b770701c0035013a787782035d100c6b9ef2ba1c12c170e6e"-}diff --git a/.sqlx/query-c094414920b4cf99108b21769e8a0804c640610be72cde31ba41b9b5ff58803b.json b/.sqlx/query-de9d4b68675dcede4ac130f3a1791362eb50f79bf650230f62ba7c7ce70a97a5.jsonsimilarity index 53%rename from .sqlx/query-c094414920b4cf99108b21769e8a0804c640610be72cde31ba41b9b5ff58803b.jsonrename to .sqlx/query-de9d4b68675dcede4ac130f3a1791362eb50f79bf650230f62ba7c7ce70a97a5.jsonindex 99cc3dc87b..26288d7dce 100644--- a/.sqlx/query-c094414920b4cf99108b21769e8a0804c640610be72cde31ba41b9b5ff58803b.json+++ b/.sqlx/query-de9d4b68675dcede4ac130f3a1791362eb50f79bf650230f62ba7c7ce70a97a5.json@@ -1,15 +1,23 @@{"db_name": "PostgreSQL",- "query": "\n UPDATE agent_session\n SET model = $2,\n modified_at = NOW()\n WHERE id = $1\n AND model IS DISTINCT FROM $2\n ",+ "query": "\n UPDATE agent_session\n SET model = $2,\n modified_at = NOW()\n WHERE id = $1\n AND model IS DISTINCT FROM $2\n RETURNING modified_at\n ","describe": {- "columns": [],+ "columns": [+ {+ "ordinal": 0,+ "name": "modified_at",+ "type_info": "Timestamptz"+ }+ ],"parameters": {"Left": ["Uuid","Text"]},- "nullable": []+ "nullable": [+ false+ ]},- "hash": "c094414920b4cf99108b21769e8a0804c640610be72cde31ba41b9b5ff58803b"+ "hash": "de9d4b68675dcede4ac130f3a1791362eb50f79bf650230f62ba7c7ce70a97a5"}diff --git a/.sqlx/query-fb724ff2353856afffacad5616ef6672fb044cd48371ca6258ec064060bcedcb.json b/.sqlx/query-fb724ff2353856afffacad5616ef6672fb044cd48371ca6258ec064060bcedcb.jsonnew file mode 100644index 0000000000..4474d2ca36--- /dev/null+++ b/.sqlx/query-fb724ff2353856afffacad5616ef6672fb044cd48371ca6258ec064060bcedcb.json@@ -0,0 +1,24 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE agent_session\n SET name = $2,\n modified_at = NOW()\n WHERE id = $1\n AND name = $3\n RETURNING modified_at\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "modified_at",+ "type_info": "Timestamptz"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "fb724ff2353856afffacad5616ef6672fb044cd48371ca6258ec064060bcedcb"+}diff --git a/Cargo.lock b/Cargo.lockindex 973ac3aa22..2f5c39d3d0 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -468,6 +468,7 @@ dependencies = ["dashmap","entity_access","entity_access_db_utils",+ "entity_registry_db_utils","genai_telemetry","harness_id","lazy-regex",@@ -479,6 +480,7 @@ dependencies = ["macro_uuid","mockall","model-entity",+ "model_owner","model_user","non_empty","opentelemetry",diff --git a/crates/agent_session/Cargo.toml b/crates/agent_session/Cargo.tomlindex 33a4d47928..8ac255d1a6 100644--- a/crates/agent_session/Cargo.toml+++ b/crates/agent_session/Cargo.toml@@ -25,7 +25,9 @@ outbound = ["dep:ai_usage","dep:connection_gateway_client","dep:entity_access_db_utils",+ "dep:entity_registry_db_utils","dep:model-entity",+ "dep:model_owner","dep:sqlx","macro_user_id/sqlx",]@@ -61,8 +63,10 @@ entity_access = { path = "../entity_access", default-features = false, features"ports",] }entity_access_db_utils = { path = "../entity_access_db_utils", optional = true }+entity_registry_db_utils = { path = "../entity_registry/entity_registry_db_utils", optional = true }genai_telemetry = { path = "../genai_telemetry" }model-entity = { path = "../model-entity", optional = true }+model_owner = { path = "../model_owner", optional = true }clap = { workspace = true, optional = true }macro_authorization = { path = "../macro_authorization", default-features = false, optional = true }macro_user_id = { path = "../macro_user_id" }diff --git a/crates/agent_session/src/outbound/postgres.rs b/crates/agent_session/src/outbound/postgres.rsindex c4f55179d0..716e2d127e 100644--- a/crates/agent_session/src/outbound/postgres.rs+++ b/crates/agent_session/src/outbound/postgres.rs@@ -31,8 +31,13 @@ use entity_access_db_utils::{AccessLevel, EntityAccessSourceType, EntityType, delete_entity_access_rows,insert_entity_access_row,};+use entity_registry_db_utils::{+ NewEntityRecord, RegisteredEntityType, WriteOutcome, delete_entity, insert_entity,+ touch_updated,+};use macro_user_id::user_id::MacroUserIdStr;use macro_uuid::Uuid;+use model_owner::Owner;use sqlx::PgPool;use std::num::NonZeroUsize;@@ -153,6 +158,30 @@ async fn upsert_user_history(Ok(())}+fn registry_unknown(+ error: rootcause::Report<entity_registry_db_utils::EntityRegistryError>,+ context: &'static str,+) -> AgentSessionError {+ AgentSessionError::Unknown(anyhow::anyhow!("{error}").context(context))+}++async fn touch_entity_updated(+ tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,+ id: AgentSessionId,+ modified_at: Option<DateTime<Utc>>,+) -> Result<()> {+ let Some(modified_at) = modified_at else {+ return Ok(());+ };+ match touch_updated(tx, id.as_uuid(), modified_at).await {+ Ok(WriteOutcome::Applied | WriteOutcome::NotFound) => Ok(()),+ Err(error) => Err(registry_unknown(+ error,+ "failed to touch agent session entity",+ )),+ }+}+struct AgentSessionRow {id: Uuid,name: String,@@ -319,6 +348,17 @@ impl AgentSessionRepo for PgAgentSessionRepo {.await.context("failed to grant the owner access to the agent session")?;+ insert_entity(+ &mut transaction,+ NewEntityRecord::new(+ id.as_uuid(),+ RegisteredEntityType::AgentSession,+ Owner::User(owner_id.clone()),+ ),+ )+ .await+ .map_err(|error| registry_unknown(error, "failed to register the agent session"))?;+// The channel the bot was invoked in can steer the session: the// invocation was public there, so that audience is. Read from the// message rather than taken from the caller, so the channel is always@@ -702,26 +742,48 @@ impl AgentSessionRepo for PgAgentSessionRepo {}async fn set_model(&self, id: AgentSessionId, model: &str) -> Result<()> {- sqlx::query!(+ let mut transaction = self+ .pool+ .begin()+ .await+ .context("begin agent session set_model")?;+ let modified_at = sqlx::query_scalar!(r#"UPDATE agent_sessionSET model = $2,modified_at = NOW()WHERE id = $1AND model IS DISTINCT FROM $2+ RETURNING modified_at"#,id.as_uuid(),model,)- .execute(&self.pool)+ .fetch_optional(&mut *transaction).await.context("failed to persist agent session model")?;+ touch_entity_updated(&mut transaction, id, modified_at).await?;+ transaction+ .commit()+ .await+ .context("commit agent session set_model")?;Ok(())}async fn set_name(&self, id: AgentSessionId, name: &str) -> Result<()> {- let result = sqlx::query!(+ let mut transaction = self+ .pool+ .begin()+ .await+ .context("begin agent session set_name")?;+ let row = sqlx::query!(r#"+ WITH previous AS (+ SELECT modified_at+ FROM agent_session+ WHERE id = $1+ FOR UPDATE+ )UPDATE agent_sessionSET name = $2,modified_at = CASE@@ -729,37 +791,56 @@ impl AgentSessionRepo for PgAgentSessionRepo {ELSE modified_atENDWHERE id = $1+ RETURNING+ modified_at,+ (modified_at IS DISTINCT FROM (SELECT modified_at FROM previous)) AS "bumped!""#,id.as_uuid(),name,)- .execute(&self.pool)+ .fetch_optional(&mut *transaction).await.context("failed to persist agent session name")?;- if result.rows_affected() == 0 {+ let Some(row) = row else {return Err(anyhow::anyhow!("agent session not found").into());- }+ };+ touch_entity_updated(&mut transaction, id, row.bumped.then_some(row.modified_at)).await?;+ transaction+ .commit()+ .await+ .context("commit agent session set_name")?;Ok(())}async fn set_name_if_default(&self, id: AgentSessionId, name: &str) -> Result<bool> {- let result = sqlx::query!(+ let mut transaction = self+ .pool+ .begin()+ .await+ .context("begin agent session set_name_if_default")?;+ let modified_at = sqlx::query_scalar!(r#"UPDATE agent_sessionSET name = $2,modified_at = NOW()WHERE id = $1AND name = $3+ RETURNING modified_at"#,id.as_uuid(),name,crate::domain::model::DEFAULT_AGENT_SESSION_NAME,)- .execute(&self.pool)+ .fetch_optional(&mut *transaction).await.context("failed to persist generated agent session name")?;- Ok(result.rows_affected() == 1)+ touch_entity_updated(&mut transaction, id, modified_at).await?;+ transaction+ .commit()+ .await+ .context("commit agent session set_name_if_default")?;+ Ok(modified_at.is_some())}async fn set_sandbox_size(&self, id: AgentSessionId, size: SandboxSize) -> Result<()> {@@ -835,6 +916,16 @@ impl AgentSessionRepo for PgAgentSessionRepo {.await.context("failed to delete agent session entity access rows")?;+ match delete_entity(&mut transaction, id.as_uuid()).await {+ Ok(WriteOutcome::Applied | WriteOutcome::NotFound) => {}+ Err(error) => {+ return Err(registry_unknown(+ error,+ "failed to delete the agent session entity",+ ));+ }+ }+// Same story for history: `"UserHistory"."itemId"` is polymorphic// text, so the session's rows in every viewer's history go here.sqlx::query!(diff --git a/crates/agent_session/src/outbound/postgres/test.rs b/crates/agent_session/src/outbound/postgres/test.rsindex e20201d9d8..8e2d17d5bd 100644--- a/crates/agent_session/src/outbound/postgres/test.rs+++ b/crates/agent_session/src/outbound/postgres/test.rs@@ -163,6 +163,49 @@ async fn insert_originating_thread_fixture(pool: &PgPool) -> (Uuid, Uuid, Uuid)(channel_id, thread_id, originating_message_id)}+async fn fetch_session_entity(+ pool: &PgPool,+ id: AgentSessionId,+) -> (String, String, String, Option<DateTime<Utc>>, DateTime<Utc>) {+ let row = sqlx::query!(+ r#"+ SELECT+ entity_type,+ owner_type::text AS "owner_type!",+ owner_id,+ deleted_at,+ updated_at+ FROM entity+ WHERE id = $1+ "#,+ id.as_uuid(),+ )+ .fetch_one(pool)+ .await+ .expect("read the session's entity row");+ (+ row.entity_type,+ row.owner_type,+ row.owner_id,+ row.deleted_at,+ row.updated_at,+ )+}++async fn entity_row_count(pool: &PgPool, id: AgentSessionId) -> i64 {+ sqlx::query_scalar!(+ r#"+ SELECT count(*) AS "count!"+ FROM entity+ WHERE id = $1+ "#,+ id.as_uuid(),+ )+ .fetch_one(pool)+ .await+ .expect("count the session's entity row")+}+fn acp_notification() -> AcpMessage {AcpMessage(RawJsonRpcMessage::notification("test/notify".to_string(), serde_json::json!({}))@@ -329,26 +372,41 @@ async fn set_model_updates_only_the_model(pool: PgPool) {.id;repo.set_model(id, "opus").await.expect("persist model");+ let after_change = AgentSessionRepo::get(&repo, id).await.expect("get session");+ assert_eq!(after_change.model, "opus");+ let (_, _, _, _, entity_updated_at) = fetch_session_entity(&pool, id).await;+ assert_eq!(entity_updated_at, after_change.modified_at);++ let modified_at = after_change.modified_at;+ repo.set_model(id, "opus").await.expect("restate model");assert_eq!(AgentSessionRepo::get(&repo, id).await.expect("get session")- .model,- "opus"+ .modified_at,+ modified_at);+ let (_, _, _, _, restated_entity_updated_at) = fetch_session_entity(&pool, id).await;+ assert_eq!(restated_entity_updated_at, entity_updated_at);- // Idempotent: restating the same model succeeds and changes nothing.- let modified_at = AgentSessionRepo::get(&repo, id)+ sqlx::query!(+ r#"+ DELETE FROM entity WHERE id = $1+ "#,+ id.as_uuid(),+ )+ .execute(&pool)+ .await+ .expect("drop the registry row");+ repo.set_model(id, "haiku").await- .expect("get session")- .modified_at;- repo.set_model(id, "opus").await.expect("restate model");+ .expect("set model without a registry row");assert_eq!(AgentSessionRepo::get(&repo, id).await.expect("get session")- .modified_at,- modified_at+ .model,+ "haiku");}@@ -411,27 +469,43 @@ async fn set_name_updates_only_the_name(pool: PgPool) {repo.set_name(id, "Fix Flaky Tests").await.expect("persist name");+ let after_change = AgentSessionRepo::get(&repo, id).await.expect("get session");+ assert_eq!(after_change.name, "Fix Flaky Tests");+ let (_, _, _, _, entity_updated_at) = fetch_session_entity(&pool, id).await;+ assert_eq!(entity_updated_at, after_change.modified_at);++ let modified_at = after_change.modified_at;+ repo.set_name(id, "Fix Flaky Tests")+ .await+ .expect("restate name");assert_eq!(AgentSessionRepo::get(&repo, id).await.expect("get session")- .name,- "Fix Flaky Tests"+ .modified_at,+ modified_at);+ let (_, _, _, _, restated_entity_updated_at) = fetch_session_entity(&pool, id).await;+ assert_eq!(restated_entity_updated_at, entity_updated_at);- let modified_at = AgentSessionRepo::get(&repo, id)- .await- .expect("get session")- .modified_at;- repo.set_name(id, "Fix Flaky Tests")+ sqlx::query!(+ r#"+ DELETE FROM entity WHERE id = $1+ "#,+ id.as_uuid(),+ )+ .execute(&pool)+ .await+ .expect("drop the registry row");+ repo.set_name(id, "Renamed Without Registry").await- .expect("restate name");+ .expect("rename without a registry row");assert_eq!(AgentSessionRepo::get(&repo, id).await.expect("get session")- .modified_at,- modified_at+ .name,+ "Renamed Without Registry");}@@ -459,21 +533,49 @@ async fn generated_name_only_replaces_the_default(pool: PgPool) {.await.expect("set generated name"));+ let after_generated = AgentSessionRepo::get(&repo, id).await.expect("get session");+ assert_eq!(after_generated.name, "Generated Name");+ let (_, _, _, _, entity_updated_at) = fetch_session_entity(&pool, id).await;+ assert_eq!(entity_updated_at, after_generated.modified_at);+repo.set_name(id, "Manual Name").await.expect("set manual name");+ let after_manual = AgentSessionRepo::get(&repo, id).await.expect("get session");+ let (_, _, _, _, after_manual_entity_updated_at) = fetch_session_entity(&pool, id).await;assert!(!repo.set_name_if_default(id, "Late Generated Name").await.expect("skip generated name"));+ let skipped = AgentSessionRepo::get(&repo, id).await.expect("get session");+ assert_eq!(skipped.name, "Manual Name");+ assert_eq!(skipped.modified_at, after_manual.modified_at);+ let (_, _, _, _, skipped_entity_updated_at) = fetch_session_entity(&pool, id).await;+ assert_eq!(skipped_entity_updated_at, after_manual_entity_updated_at);++ let unregistered = create_session(&repo, new_session(bot_id, None, None)).await;+ sqlx::query!(+ r#"+ DELETE FROM entity WHERE id = $1+ "#,+ unregistered.id.as_uuid(),+ )+ .execute(&pool)+ .await+ .expect("drop the registry row");+ assert!(+ repo.set_name_if_default(unregistered.id, "Generated Without Registry")+ .await+ .expect("generate a name without a registry row")+ );assert_eq!(- AgentSessionRepo::get(&repo, id)+ AgentSessionRepo::get(&repo, unregistered.id).await.expect("get session").name,- "Manual Name"+ "Generated Without Registry");}@@ -869,6 +971,12 @@ async fn create_grants_the_owner_and_the_originating_channel(pool: PgPool) {expected.sort();assert_eq!(grants, expected);++ let (entity_type, owner_type, owner_id, deleted_at, _) = fetch_session_entity(&pool, id).await;+ assert_eq!(entity_type, "agent_session");+ assert_eq!(owner_type, "user");+ assert_eq!(owner_id, OWNER);+ assert_eq!(deleted_at, None);}/// A session created without a mention has no channel to inherit an audience@@ -1090,6 +1198,23 @@ async fn delete_removes_the_session_grants(pool: PgPool) {.expect("count the session's history rows");assert_eq!(remaining_history, 0);++ assert_eq!(entity_row_count(&pool, id).await, 0);++ let unregistered = create_session(&repo, new_session(bot_id, None, None)).await;+ sqlx::query!(+ r#"+ DELETE FROM entity WHERE id = $1+ "#,+ unregistered.id.as_uuid(),+ )+ .execute(&pool)+ .await+ .expect("drop the registry row");+ AgentSessionRepo::delete(&repo, unregistered.id)+ .await+ .expect("delete a session without a registry row");+ assert_eq!(entity_row_count(&pool, unregistered.id).await, 0);}fn cursor_external(agent: &str) -> ExternalSession {