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
refactor(chat): typed owner in chat models and access (#6688)
Will Hutchinsonb5d088feffbc
diff --git a/.github/workspace-dep-closures.json b/.github/workspace-dep-closures.jsonindex b158881030..da892df875 100644--- a/.github/workspace-dep-closures.json+++ b/.github/workspace-dep-closures.json@@ -1715,6 +1715,7 @@"crates/model-error-response","crates/model_file_type","crates/model_notifications",+ "crates/model_owner","crates/model_user","crates/models_bulk_upload","crates/models_email",@@ -4764,6 +4765,7 @@"crates/model-entity","crates/model-error-response","crates/model_file_type",+ "crates/model_owner","crates/model_user","crates/models_bulk_upload","crates/models_pagination",diff --git a/crates/chat/Cargo.toml b/crates/chat/Cargo.tomlindex 63e557db0e..d7322ee703 100644--- a/crates/chat/Cargo.toml+++ b/crates/chat/Cargo.toml@@ -22,7 +22,6 @@ outbound = ["dep:entity_access_db_utils","dep:entity_registry_db_utils","dep:macro_uuid",- "dep:model_owner","dep:share_permission_db_utils","dep:sqlx","ports",@@ -50,7 +49,7 @@ macro_user_id = { path = "../macro_user_id" }model = { path = "../model" }non_empty = { path = "../non_empty" }model-entity = { path = "../model-entity" }-model_owner = { path = "../model_owner", optional = true }+model_owner = { path = "../model_owner" }models_entity_access_management = { path = "../models_entity_access_management", default-features = false }models_permissions = { path = "../models_permissions" }rootcause = { workspace = true }diff --git a/crates/chat/src/domain/models/chat.rs b/crates/chat/src/domain/models/chat.rsindex f9a3f6fe76..52f843d959 100644--- a/crates/chat/src/domain/models/chat.rs+++ b/crates/chat/src/domain/models/chat.rs@@ -1,4 +1,5 @@use model::chat::ChatMessageWithAttachments;+use model_owner::Owner;use models_permissions::share_permission::access_level::AccessLevel;use models_permissions::share_permission::team_share::AuthorizedTeamShareCommand;use serde::{Deserialize, Serialize};@@ -69,7 +70,8 @@ pub struct ChatResponse {/// The chat uuid.pub id: String,/// Who the chat belongs to.- pub user_id: String,+ #[schema(value_type = String)]+ pub user_id: Owner,/// The project id the chat belongs to.pub project_id: Option<String>,/// The name of the chat.diff --git a/crates/chat/src/domain/service/chat/test.rs b/crates/chat/src/domain/service/chat/test.rsindex ec5fc6990d..56c8214294 100644--- a/crates/chat/src/domain/service/chat/test.rs+++ b/crates/chat/src/domain/service/chat/test.rs@@ -8,6 +8,7 @@ use attachment::FormattedParts;use entity_access_management::domain::models::EntityAccessManagementError;use macro_event_broker::{EventBrokerError, MacroEvent};use model::chat::Chat;+use model_owner::Owner;use super::*;use crate::domain::models::{ChatResponse, PatchChatMessageArgs};@@ -136,7 +137,7 @@ impl ChatRepo for StubChatRepo {Ok(Chat {id: chat_id.to_string(),name: "Source Chat".to_string(),- user_id: OWNER.to_string(),+ user_id: Owner::from_principal_str(OWNER).unwrap(),model: None,project_id: self.metadata_project_id.clone(),created_at: None,diff --git a/crates/chat/src/inbound/test.rs b/crates/chat/src/inbound/test.rsindex 4b30f7d1dd..46171f30ae 100644--- a/crates/chat/src/inbound/test.rs+++ b/crates/chat/src/inbound/test.rs@@ -12,6 +12,7 @@ use macro_user_id::user_id::MacroUserIdStr;use model::chat::ChatBasic;use model::response::StringIDResponse;use model::user::UserContext;+use model_owner::Owner;use rootcause::Report;use std::sync::Arc;use tower::util::ServiceExt;@@ -52,7 +53,7 @@ impl ChatService for MockService {Ok(GetChatResponse {chat: ChatResponse {id: chat_id,- user_id: "macro|[email protected]".to_string(),+ user_id: Owner::from_principal_str("macro|[email protected]").unwrap(),project_id: None,name: "Mock Chat".to_string(),messages: Vec::new(),@@ -593,10 +594,7 @@ fn chat_basic_extension() -> Extension<ChatBasic> {Extension(ChatBasic {id: "some-chat-id".to_string(),name: "Mock Chat".to_string(),- user_id: macro_user_id::user_id::MacroUserIdStr::try_from(- "macro|[email protected]".to_string(),- )- .unwrap(),+ user_id: Owner::from_principal_str("macro|[email protected]").unwrap(),project_id: None,deleted_at: None,})diff --git a/crates/chat/src/inbound/toolset/test.rs b/crates/chat/src/inbound/toolset/test.rsindex 1bd5674076..15bf179955 100644--- a/crates/chat/src/inbound/toolset/test.rs+++ b/crates/chat/src/inbound/toolset/test.rs@@ -297,7 +297,7 @@ mod self_read_guard {Ok(model::chat::Chat {id: chat_id.to_string(),name: "Other Chat".to_string(),- user_id: "macro|[email protected]".to_string(),+ user_id: model_owner::Owner::from_principal_str("macro|[email protected]").unwrap(),model: None,project_id: None,created_at: None,@@ -319,7 +319,8 @@ mod self_read_guard {Ok(GetChatResponse {chat: ChatResponse {id: chat_id,- user_id: "macro|[email protected]".to_string(),+ user_id: model_owner::Owner::from_principal_str("macro|[email protected]")+ .unwrap(),project_id: None,name: "Other Chat".to_string(),messages: Vec::new(),diff --git a/crates/chat/src/outbound/postgres/queries/get_chat.rs b/crates/chat/src/outbound/postgres/queries/get_chat.rsindex fbfa343567..8538133fa3 100644--- a/crates/chat/src/outbound/postgres/queries/get_chat.rs+++ b/crates/chat/src/outbound/postgres/queries/get_chat.rs@@ -1,13 +1,13 @@//! Fetch a chat by ID.use model::chat::Chat;+use model_owner::Owner;use sqlx::PgPool;/// Fetch a single chat row by its ID.#[tracing::instrument(err, skip(pool))]pub(crate) async fn get_chat(pool: &PgPool, chat_id: &str) -> anyhow::Result<Chat> {- let chat = sqlx::query_as!(- Chat,+ let chat = sqlx::query!(r#"SELECTid,@@ -25,6 +25,21 @@ pub(crate) async fn get_chat(pool: &PgPool, chat_id: &str) -> anyhow::Result<Cha"#,chat_id,)+ .try_map(|row| {+ Ok(Chat {+ id: row.id,+ name: row.name,+ user_id: Owner::from_principal_str(&row.user_id)+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?,+ model: Some(row.model),+ project_id: row.project_id,+ created_at: row.created_at,+ updated_at: row.updated_at,+ token_count: row.token_count,+ is_persistent: row.is_persistent,+ deleted_at: row.deleted_at,+ })+ }).fetch_one(pool).await?;diff --git a/crates/chat/src/outbound/postgres/queries/revert_delete_chat.rs b/crates/chat/src/outbound/postgres/queries/revert_delete_chat.rsindex 59e81551c7..b100ad74a4 100644--- a/crates/chat/src/outbound/postgres/queries/revert_delete_chat.rs+++ b/crates/chat/src/outbound/postgres/queries/revert_delete_chat.rs@@ -1,4 +1,5 @@use anyhow::Context;+use model_owner::Owner;#[tracing::instrument(err, skip(tx))]pub(crate) async fn revert_delete_chat(@@ -19,24 +20,28 @@ pub(crate) async fn revert_delete_chat(.fetch_one(&mut **tx).await.context("unable to update chat")?;+ let chat_owner = Owner::from_principal_str(&chat_owner).context("invalid chat owner")?;let chat_uuid = macro_uuid::string_to_uuid(chat_id)?;entity_registry_db_utils::clear_deleted(tx, chat_uuid).await?;- sqlx::query!(- r#"+ // Only a user has a history feed; bot- and team-owned chats leave it alone.+ if let Owner::User(owner_user_id) = &chat_owner {+ sqlx::query!(+ r#"INSERT INTO "UserHistory" ("userId", "itemId", "itemType", "createdAt", "updatedAt")VALUES ($1, $2, $3, NOW(), NOW())ON CONFLICT ("userId", "itemId", "itemType") DO UPDATESET "updatedAt" = NOW();"#,- chat_owner,- chat_id,- "chat",- )- .execute(&mut **tx)- .await- .context("unable to add chat to history")?;+ owner_user_id.as_ref(),+ chat_id,+ "chat",+ )+ .execute(&mut **tx)+ .await+ .context("unable to add chat to history")?;+ }if let Some(project_id) = project_id {let is_deleted = sqlx::query!(diff --git a/crates/chat/src/outbound/postgres/test.rs b/crates/chat/src/outbound/postgres/test.rsindex 0b7aa88431..2b81b00833 100644--- a/crates/chat/src/outbound/postgres/test.rs+++ b/crates/chat/src/outbound/postgres/test.rs@@ -6,6 +6,7 @@ use macro_db_migrator::MACRO_DB_MIGRATIONS;use macro_user_id::cowlike::CowLike;use macro_user_id::user_id::MacroUserIdStr;use model::chat::NewChatMessage;+use model_owner::Owner;use models_permissions::share_permission::access_level::AccessLevel;use models_permissions::share_permission::{LinkShare, SharePermissionV2, UpdateSharePermissionRequestV2,@@ -23,6 +24,55 @@ fn default_share_permission() -> SharePermissionV2 {SharePermissionV2::new_chat_share_permission(None)}+const BOT_OWNER: &str = "bot|00000000-0000-0000-0000-00000000a1a1";+const TEAM_OWNER: &str = "00000000-0000-0000-0000-00000000a2a2";++/// Registers a non-user principal in `"User"` so the `Chat."userId"` foreign+/// key accepts it as an owner.+async fn insert_owner_principal(pool: &Pool<Postgres>, principal: &str, macro_user_id: &str) {+ let macro_user_id = uuid::Uuid::parse_str(macro_user_id).unwrap();+ sqlx::query(+ r#"+ INSERT INTO "macro_user" ("id", "username", "email", "stripe_customer_id")+ VALUES ($1, $2, $3, $4)+ "#,+ )+ .bind(macro_user_id)+ .bind(principal)+ .bind(format!("{macro_user_id}@example.com"))+ .bind(format!("stripe_{macro_user_id}"))+ .execute(pool)+ .await+ .unwrap();+ sqlx::query(r#"INSERT INTO "User" ("id", "email", "macro_user_id") VALUES ($1, $2, $3)"#)+ .bind(principal)+ .bind(format!("{macro_user_id}@example.com"))+ .bind(macro_user_id)+ .execute(pool)+ .await+ .unwrap();+}++async fn set_chat_owner(pool: &Pool<Postgres>, chat_id: &str, owner: &str) {+ sqlx::query(r#"UPDATE "Chat" SET "userId" = $1 WHERE id = $2"#)+ .bind(owner)+ .bind(chat_id)+ .execute(pool)+ .await+ .unwrap();+}++async fn chat_history_count(pool: &Pool<Postgres>, chat_id: &str) -> i64 {+ let count: (i64,) = sqlx::query_as(+ r#"SELECT COUNT(*) FROM "UserHistory" WHERE "itemId" = $1 AND "itemType" = 'chat'"#,+ )+ .bind(chat_id)+ .fetch_one(pool)+ .await+ .unwrap();+ count.0+}+#[derive(Debug, Eq, PartialEq)]struct StoredSharePermission {id: String,@@ -706,12 +756,36 @@ async fn get_chat_returns_chat(pool: Pool<Postgres>) {assert_eq!(chat.id, chat_id);assert_eq!(chat.name, "Get Me");- assert_eq!(chat.user_id, "macro|[email protected]");+ assert_eq!(+ chat.user_id,+ Owner::from_principal_str("macro|[email protected]").unwrap()+ );assert!(chat.created_at.is_some());assert!(chat.updated_at.is_some());assert!(chat.deleted_at.is_none());}+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "fixtures", scripts("users"))+)]+async fn get_chat_decodes_bot_and_team_owners(pool: Pool<Postgres>) {+ let repo = PgChatRepo::new(pool.clone());+ let chat_id = create_test_chat(&repo, "Owned Elsewhere").await;+ insert_owner_principal(&pool, BOT_OWNER, "b1111111-1111-1111-1111-111111111111").await;+ insert_owner_principal(&pool, TEAM_OWNER, "b2222222-2222-2222-2222-222222222222").await;++ set_chat_owner(&pool, &chat_id, BOT_OWNER).await;+ let chat = repo.get_metadata(&chat_id).await.unwrap();+ assert_eq!(chat.user_id, Owner::from_principal_str(BOT_OWNER).unwrap());+ assert!(matches!(chat.user_id, Owner::Bot(_)));++ set_chat_owner(&pool, &chat_id, TEAM_OWNER).await;+ let chat = repo.get_metadata(&chat_id).await.unwrap();+ assert_eq!(chat.user_id, Owner::from_principal_str(TEAM_OWNER).unwrap());+ assert!(matches!(chat.user_id, Owner::Team(_)));+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "fixtures", scripts("users"))@@ -1060,7 +1134,10 @@ async fn get_chat_returns_full_response(pool: Pool<Postgres>) {assert_eq!(response.id, chat_id);assert_eq!(response.name, "Full Chat");- assert_eq!(response.user_id, "macro|[email protected]");+ assert_eq!(+ response.user_id,+ Owner::from_principal_str("macro|[email protected]").unwrap()+ );assert!(response.model.is_some());assert!(response.messages.is_empty());}@@ -1186,6 +1263,32 @@ async fn revert_delete_restores_chat(pool: Pool<Postgres>) {assert_eq!(count.0, 1);}+#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "fixtures", scripts("users"))+)]+async fn revert_delete_skips_user_history_for_non_user_owner(pool: Pool<Postgres>) {+ let repo = PgChatRepo::new(pool.clone());+ let chat_id = create_test_chat(&repo, "Bot Chat").await;+ insert_owner_principal(&pool, BOT_OWNER, "b1111111-1111-1111-1111-111111111111").await;+ set_chat_owner(&pool, &chat_id, BOT_OWNER).await;+ // `create` recorded history for the creating user; clear it so only+ // `revert_delete` can put rows back.+ sqlx::query(r#"DELETE FROM "UserHistory" WHERE "itemId" = $1"#)+ .bind(&chat_id)+ .execute(&pool)+ .await+ .unwrap();+ repo.delete(&chat_id).await.unwrap();++ repo.revert_delete(&chat_id, None).await.unwrap();++ let chat = repo.get_metadata(&chat_id).await.unwrap();+ assert!(chat.deleted_at.is_none());+ assert_eq!(chat.user_id, Owner::from_principal_str(BOT_OWNER).unwrap());+ assert_eq!(chat_history_count(&pool, &chat_id).await, 0);+}+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS",fixtures(path = "fixtures", scripts("users"))diff --git a/crates/entity_access/src/inbound/axum_extractors/chat.rs b/crates/entity_access/src/inbound/axum_extractors/chat.rsindex 21cb2babdd..513ebf9fa8 100644--- a/crates/entity_access/src/inbound/axum_extractors/chat.rs+++ b/crates/entity_access/src/inbound/axum_extractors/chat.rs@@ -124,7 +124,7 @@ where// Bots always resolve ownership through the scoped domain policy.if let Some(ref user_id) = macro_user_id- && chat_context.user_id == *user_id+ && chat_context.user_id.is_user(user_id){return Ok(Self {entity_access_receipt: EntityAccessReceipt {diff --git a/crates/entity_access/src/inbound/axum_extractors/chat/test.rs b/crates/entity_access/src/inbound/axum_extractors/chat/test.rsindex 7af6475a74..d79a27ba52 100644--- a/crates/entity_access/src/inbound/axum_extractors/chat/test.rs+++ b/crates/entity_access/src/inbound/axum_extractors/chat/test.rs@@ -11,8 +11,8 @@ use macro_authorization::{INTERNAL_API_KEY_HEADER, INTERNAL_MACRO_USER_ID_HEADER, InternalIdentityClaims,MacroAuthorizationError, MacroAuthorizationService, MacroAuthorizationState,};-use macro_user_id::user_id::MacroUserIdStr;use model::chat::ChatBasic;+use model_owner::Owner;use model_user::UserContext;use rootcause::Report;@@ -146,7 +146,7 @@ fn chat_owned_by(owner_id: &str, deleted: bool) -> ChatBasic {ChatBasic {id: CHAT_ID.to_string(),name: "Test chat".to_string(),- user_id: MacroUserIdStr::try_from(owner_id.to_string()).expect("owner id should be valid"),+ user_id: Owner::from_principal_str(owner_id).expect("owner id should be valid"),project_id: None,deleted_at: deleted.then(|| {"2026-01-01T00:00:00Z"@@ -239,6 +239,66 @@ async fn authenticated_owner_bypasses_access_lookup() {assert!(state.entity_access.calls().is_empty());}+#[tokio::test]+async fn bot_owner_does_not_take_user_owner_fast_path() {+ let state = TestState::new(Some(AccessLevel::Edit));+ let chat = chat_owned_by("bot|00000000-0000-0000-0000-00000000a1a1", false);++ let extracted = extract::<EditAccessLevel>(request(Some("valid"), chat), &state)+ .await+ .expect("non-owner should fall through to entity_access");++ assert!(matches!(+ extracted.entity_access_receipt.entity_permission(),+ EntityPermission::AccessLevel {+ access_level: AccessLevel::Edit+ }+ ));+ assert_eq!(state.entity_access.calls().len(), 1);+ assert_eq!(+ state.entity_access.calls()[0].user_id.as_deref(),+ Some(USER_ID)+ );+}++#[tokio::test]+async fn team_owner_does_not_take_user_owner_fast_path() {+ let state = TestState::new(Some(AccessLevel::View));+ let chat = chat_owned_by("01234567-89ab-cdef-0123-456789abcdef", false);++ let extracted = extract::<ViewAccessLevel>(request(Some("valid"), chat), &state)+ .await+ .expect("non-owner should fall through to entity_access");++ assert!(matches!(+ extracted.entity_access_receipt.entity_permission(),+ EntityPermission::AccessLevel {+ access_level: AccessLevel::View+ }+ ));+ assert_eq!(state.entity_access.calls().len(), 1);+ assert_eq!(+ state.entity_access.calls()[0].user_id.as_deref(),+ Some(USER_ID)+ );+}++#[tokio::test]+async fn deleted_chat_with_non_user_owner_rejects_authenticated_user() {+ let state = TestState::new(Some(AccessLevel::Owner));+ let chat = chat_owned_by("bot|00000000-0000-0000-0000-00000000a1a1", true);++ let result = extract::<ViewAccessLevel>(request(Some("valid"), chat), &state).await;++ assert!(matches!(+ result,+ Err(ExtractorError::UnauthorizedWithMessage(+ "only owner can access deleted resource"+ ))+ ));+ assert!(state.entity_access.calls().is_empty());+}+#[tokio::test]async fn insufficient_access_is_rejected() {let state = TestState::new(Some(AccessLevel::View));diff --git a/crates/macro_db_client/src/chat.rs b/crates/macro_db_client/src/chat.rsindex 7e262ccbbb..889bc8d61f 100644--- a/crates/macro_db_client/src/chat.rs+++ b/crates/macro_db_client/src/chat.rs@@ -1,5 +1,5 @@-use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};use model::chat::ChatBasic;+use model_owner::Owner;use sqlx::{Pool, Postgres};use std::collections::HashSet;@@ -30,9 +30,8 @@ pub async fn get_basic_chat(db: &Pool<Postgres>, chat_id: &str) -> Result<ChatBaOk(ChatBasic {id: r.id,name: r.name,- user_id: MacroUserIdStr::parse_from_str(&r.user_id)- .map_err(|e| sqlx::Error::Decode(Box::new(e)))?- .into_owned(),+ user_id: Owner::from_principal_str(&r.user_id)+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?,project_id: r.project_id,deleted_at: r.deleted_at,})diff --git a/crates/macro_db_client/src/dcs/get_chat.rs b/crates/macro_db_client/src/dcs/get_chat.rsindex f611d9d991..d4e7157104 100644--- a/crates/macro_db_client/src/dcs/get_chat.rs+++ b/crates/macro_db_client/src/dcs/get_chat.rs@@ -4,6 +4,7 @@ use agent::types::Role;use anyhow::{Error, Result};use model::chat::{AttachmentType, Chat, ChatAttachment, ChatMessageWithAttachments};use model_entity::{Entity, EntityType};+use model_owner::Owner;use sqlx::{Executor, Pool, Postgres};use std::collections::HashMap;@@ -34,8 +35,7 @@ pub async fn get_chat_db<'e, T>(db: T, chat_id: &str) -> Result<Chat>whereT: Executor<'e, Database = Postgres>,{- sqlx::query_as!(- Chat,+ sqlx::query!(r#"SELECTc.id,@@ -52,6 +52,21 @@ where"#,chat_id,)+ .try_map(|row| {+ Ok(Chat {+ id: row.id,+ name: row.name,+ user_id: Owner::from_principal_str(&row.user_id)+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?,+ model: Some(row.model),+ project_id: row.project_id,+ created_at: row.created_at,+ updated_at: row.updated_at,+ token_count: row.token_count,+ is_persistent: row.is_persistent,+ deleted_at: row.deleted_at,+ })+ }).fetch_one(db).await.map_err(Error::from)diff --git a/crates/macro_db_client/src/dcs/get_chats.rs b/crates/macro_db_client/src/dcs/get_chats.rsindex 13d49d5102..c26bdb1e8c 100644--- a/crates/macro_db_client/src/dcs/get_chats.rs+++ b/crates/macro_db_client/src/dcs/get_chats.rs@@ -1,12 +1,12 @@use model::chat::Chat;+use model_owner::Owner;use sqlx::{Pool, Postgres};#[tracing::instrument(skip(db))]pub async fn get_chats(db: &Pool<Postgres>, user_id: &str) -> anyhow::Result<Vec<Chat>> {let mut chats: Vec<Chat> = Vec::new();chats.extend(- sqlx::query_as!(- Chat,+ sqlx::query!(r#"SELECTc.id,@@ -24,6 +24,21 @@ pub async fn get_chats(db: &Pool<Postgres>, user_id: &str) -> anyhow::Result<Vec"#,user_id,)+ .try_map(|row| {+ Ok(Chat {+ id: row.id,+ name: row.name,+ user_id: Owner::from_principal_str(&row.user_id)+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?,+ model: Some(row.model),+ project_id: row.project_id,+ created_at: row.created_at,+ updated_at: row.updated_at,+ token_count: row.token_count,+ is_persistent: row.is_persistent,+ deleted_at: row.deleted_at,+ })+ }).fetch_all(db).await?,);diff --git a/crates/macro_db_client/src/dcs/get_chats_for_attachment.rs b/crates/macro_db_client/src/dcs/get_chats_for_attachment.rsindex 681386a80e..94dfbdaa79 100644--- a/crates/macro_db_client/src/dcs/get_chats_for_attachment.rs+++ b/crates/macro_db_client/src/dcs/get_chats_for_attachment.rs@@ -1,5 +1,6 @@use anyhow::Result;use model::chat::Chat;+use model_owner::Owner;use sqlx::Postgres;pub async fn get_latest_single_attachment_chat(@@ -7,8 +8,7 @@ pub async fn get_latest_single_attachment_chat(attachment_id: &str,user_id: &str,) -> Result<Option<Chat>, sqlx::Error> {- sqlx::query_as!(- Chat,+ sqlx::query!(r#"WITH SingleAttachmentChats AS (SELECT@@ -43,6 +43,21 @@ pub async fn get_latest_single_attachment_chat(attachment_id,user_id,)+ .try_map(|row| {+ Ok(Chat {+ id: row.id,+ name: row.name,+ user_id: Owner::from_principal_str(&row.user_id)+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?,+ model: Some(row.model),+ project_id: row.project_id,+ created_at: row.created_at,+ updated_at: row.updated_at,+ token_count: row.token_count,+ is_persistent: row.is_persistent,+ deleted_at: row.deleted_at,+ })+ }).fetch_optional(transaction.as_mut()).await}@@ -52,8 +67,7 @@ pub async fn get_multi_attachment_chat(attachment_id: &str,user_id: &str,) -> Result<Vec<Chat>, sqlx::Error> {- sqlx::query_as!(- Chat,+ sqlx::query!(r#"WITH MultiAttachmentChats AS (SELECT@@ -85,6 +99,21 @@ pub async fn get_multi_attachment_chat(attachment_id,user_id,)+ .try_map(|row| {+ Ok(Chat {+ id: row.id,+ name: row.name,+ user_id: Owner::from_principal_str(&row.user_id)+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?,+ model: Some(row.model),+ project_id: row.project_id,+ created_at: row.created_at,+ updated_at: row.updated_at,+ token_count: row.token_count,+ is_persistent: row.is_persistent,+ deleted_at: row.deleted_at,+ })+ }).fetch_all(transaction.as_mut()).await}diff --git a/crates/macro_db_client/src/history.rs b/crates/macro_db_client/src/history.rsindex 3bfdc8b721..7d9661489d 100644--- a/crates/macro_db_client/src/history.rs+++ b/crates/macro_db_client/src/history.rs@@ -161,16 +161,22 @@ pub async fn get_user_history(db: &Pool<Postgres>, user_id: &str) -> anyhow::Res})?;Ok(Item::Document(document))}- "chat" => Ok(Item::Chat(map_chat_item(- r.id,- r.user_id,- r.name,- r.created_at,- r.updated_at,- r.deleted_at,- r.project_id,- r.is_persistent,- ))),+ "chat" => {+ let chat = map_chat_item(+ r.id,+ r.user_id,+ r.name,+ r.created_at,+ r.updated_at,+ r.deleted_at,+ r.project_id,+ r.is_persistent,+ )+ .map_err(|e| sqlx::Error::TypeNotFound {+ type_name: e.to_string(),+ })?;+ Ok(Item::Chat(chat))+ }"project" => Ok(Item::Project(map_project_item(r.id,r.user_id,diff --git a/crates/macro_db_client/src/notification.rs b/crates/macro_db_client/src/notification.rsindex a7cdf26927..9221697e79 100644--- a/crates/macro_db_client/src/notification.rs+++ b/crates/macro_db_client/src/notification.rs@@ -1,6 +1,7 @@use anyhow::Context;use document_sub_type::DocumentSubType;use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};+use model_owner::Owner;use crate::{chat::get_basic_chat, projects::get_project::get_basic_project::get_basic_project};@@ -65,11 +66,15 @@ pub async fn get_basic_cloud_storage_item_metadata(let basic_chat_metadata = get_basic_chat(db, item_id).await.context("unable to get chat metadata")?;+ // Notifications address a user; bot- and team-owned chats have none.+ let Owner::User(owner) = basic_chat_metadata.user_id else {+ anyhow::bail!("chat owner is not a user");+ };Ok(BasicCloudStorageItemMetadata {item_id: basic_chat_metadata.id,item_name: basic_chat_metadata.name,- item_owner: basic_chat_metadata.user_id,+ item_owner: owner,file_type: None,sub_type: None,})diff --git a/crates/macro_db_client/src/pins.rs b/crates/macro_db_client/src/pins.rsindex b3e3c80a7d..f537f78776 100644--- a/crates/macro_db_client/src/pins.rs+++ b/crates/macro_db_client/src/pins.rs@@ -221,7 +221,10 @@ pub async fn get_pins(db: Pool<Postgres>, user_id: &str) -> anyhow::Result<Vec<Pr.updated_at,r.project_id,r.is_persistent,- );+ )+ .map_err(|e| sqlx::Error::TypeNotFound {+ type_name: e.to_string(),+ })?;Ok(PinnedItem {pin_index,item: Item::Chat(chat.clone()),diff --git a/crates/macro_db_client/src/recents/deleted.rs b/crates/macro_db_client/src/recents/deleted.rsindex 6477bbf010..6125a75d86 100644--- a/crates/macro_db_client/src/recents/deleted.rs+++ b/crates/macro_db_client/src/recents/deleted.rs@@ -133,16 +133,22 @@ pub async fn get_recently_deleted(})?;Ok(Item::Document(document))}- "chat" => Ok(Item::Chat(map_chat_item(- r.id,- r.user_id,- r.name,- r.created_at,- r.updated_at,- r.deleted_at,- r.project_id,- r.is_persistent,- ))),+ "chat" => {+ let chat = map_chat_item(+ r.id,+ r.user_id,+ r.name,+ r.created_at,+ r.updated_at,+ r.deleted_at,+ r.project_id,+ r.is_persistent,+ )+ .map_err(|e| sqlx::Error::TypeNotFound {+ type_name: e.to_string(),+ })?;+ Ok(Item::Chat(chat))+ }"project" => Ok(Item::Project(map_project_item(r.id,r.user_id,diff --git a/crates/model/src/activity/map_item.rs b/crates/model/src/activity/map_item.rsindex 1f26d64ac9..58dd920506 100644--- a/crates/model/src/activity/map_item.rs+++ b/crates/model/src/activity/map_item.rs@@ -52,10 +52,10 @@ pub fn map_chat_item(updated_at: Option<chrono::DateTime<chrono::Utc>>,project_id: Option<String>,is_persistent: Option<bool>,-) -> Chat {- Chat {+) -> anyhow::Result<Chat> {+ Ok(Chat {id,- user_id,+ user_id: Owner::from_principal_str(&user_id)?,name,// Don't care about the model in user historymodel: None,@@ -65,5 +65,5 @@ pub fn map_chat_item(project_id,token_count: None,is_persistent: is_persistent.unwrap_or(false),- }+ })}diff --git a/crates/model/src/chat.rs b/crates/model/src/chat.rsindex 82be5de7c7..62ca9c488e 100644--- a/crates/model/src/chat.rs+++ b/crates/model/src/chat.rs@@ -1,9 +1,11 @@mod message;pub mod preview;+#[cfg(test)]+mod test;pub mod utils;-use macro_user_id::user_id::MacroUserIdStr;pub use message::{ChatMessage, ChatMessageWithAttachments, NewChatMessage};+use model_owner::Owner;use serde::{Deserialize, Serialize};use strum::Display;use utoipa::ToSchema;@@ -18,7 +20,9 @@ pub struct Chat {/// The name of the chatpub name: String,/// Who the chat belongs to- pub user_id: String,+ #[schema(value_type = String)]+ #[sqlx(try_from = "String")]+ pub user_id: Owner,/// The model used to generate the chatpub model: Option<String>,/// The project id of the chat@@ -41,7 +45,8 @@ pub struct Chat {pub struct ChatBasic {pub id: String,pub name: String,- pub user_id: MacroUserIdStr<'static>,+ /// Who the chat belongs to+ pub user_id: Owner,pub project_id: Option<String>,pub deleted_at: Option<chrono::DateTime<chrono::Utc>>,}diff --git a/crates/model/src/chat/test.rs b/crates/model/src/chat/test.rsnew file mode 100644index 0000000000..26116b2bf1--- /dev/null+++ b/crates/model/src/chat/test.rs@@ -0,0 +1,97 @@+use model_owner::Owner;+use serde_json::json;++use super::{Chat, ChatBasic};++const USER_OWNER: &str = "macro|[email protected]";+const BOT_OWNER: &str = "bot|00000000-0000-0000-0000-00000000a1a1";+const TEAM_OWNER: &str = "01234567-89ab-cdef-0123-456789abcdef";++fn owner(principal: &str) -> Owner {+ Owner::from_principal_str(principal).unwrap()+}++fn chat(principal: &str) -> Chat {+ Chat {+ id: "chat-1".to_string(),+ name: "Test Chat".to_string(),+ user_id: owner(principal),+ model: Some("anthropic/claude".to_string()),+ project_id: None,+ created_at: None,+ updated_at: None,+ token_count: Some(10),+ is_persistent: true,+ deleted_at: None,+ }+}++#[test]+fn chat_serializes_owner_as_user_id_string() {+ let serialized = serde_json::to_value(chat(USER_OWNER)).unwrap();++ assert_eq!(serialized["userId"], USER_OWNER);+ assert!(serialized.get("user_id").is_none());+}++#[test]+fn chat_round_trips_every_owner_kind() {+ for principal in [USER_OWNER, BOT_OWNER, TEAM_OWNER] {+ let original = chat(principal);+ let serialized = serde_json::to_value(&original).unwrap();+ assert_eq!(serialized["userId"], principal);++ let deserialized: Chat = serde_json::from_value(serialized).unwrap();+ assert_eq!(deserialized, original);+ }+}++fn chat_from_wire(principal: &str) -> Chat {+ serde_json::from_value(json!({+ "id": "chat-1",+ "name": "Test Chat",+ "userId": principal,+ "isPersistent": false,+ }))+ .unwrap()+}++#[test]+fn chat_deserializes_bot_and_team_owner_principals() {+ let bot = chat_from_wire(BOT_OWNER);+ assert_eq!(bot.user_id, owner(BOT_OWNER));+ assert!(matches!(bot.user_id, Owner::Bot(_)));++ let team = chat_from_wire(TEAM_OWNER);+ assert_eq!(team.user_id, owner(TEAM_OWNER));+ assert!(matches!(team.user_id, Owner::Team(_)));+}++#[test]+fn chat_rejects_malformed_owner_principal() {+ let result = serde_json::from_value::<Chat>(json!({+ "id": "chat-1",+ "name": "Test Chat",+ "userId": "user1",+ "isPersistent": false,+ }));++ assert!(result.is_err());+}++#[test]+fn chat_basic_round_trips_non_user_owner() {+ let original = ChatBasic {+ id: "chat-1".to_string(),+ name: "Test Chat".to_string(),+ user_id: owner(BOT_OWNER),+ project_id: Some("project-1".to_string()),+ deleted_at: None,+ };++ let serialized = serde_json::to_value(&original).unwrap();+ assert_eq!(serialized["user_id"], BOT_OWNER);++ let deserialized: ChatBasic = serde_json::from_value(serialized).unwrap();+ assert_eq!(deserialized, original);+}diff --git a/crates/model/src/item/map_item.rs b/crates/model/src/item/map_item.rsindex a7a45ad903..fd34a1b8c4 100644--- a/crates/model/src/item/map_item.rs+++ b/crates/model/src/item/map_item.rs@@ -59,10 +59,10 @@ pub fn map_chat_item(deleted_at: Option<chrono::DateTime<chrono::Utc>>,project_id: Option<String>,is_persistent: Option<bool>,-) -> Chat {- Chat {+) -> anyhow::Result<Chat> {+ Ok(Chat {id,- user_id,+ user_id: Owner::from_principal_str(&user_id)?,name,// Don't care about the model in user historymodel: None,@@ -72,7 +72,7 @@ pub fn map_chat_item(project_id,token_count: None,is_persistent: is_persistent.unwrap_or(false),- }+ })}pub fn map_project_item(diff --git a/crates/model/src/item/tests.rs b/crates/model/src/item/tests.rsindex 70ab649e56..b394d2c7df 100644--- a/crates/model/src/item/tests.rs+++ b/crates/model/src/item/tests.rs@@ -145,7 +145,7 @@ fn test_chat_serde() {let chat = Chat {id: "chat123".to_string(),name: "Test Chat".to_string(),- user_id: "user1".to_string(),+ user_id: Owner::from_principal_str("macro|[email protected]").unwrap(),model: Some("claude-3".to_string()),project_id: None,created_at: Some(chrono::Utc::now()),diff --git a/crates/projects/src/domain/service.rs b/crates/projects/src/domain/service.rsindex bd73927be9..a41d730a01 100644--- a/crates/projects/src/domain/service.rs+++ b/crates/projects/src/domain/service.rs@@ -873,7 +873,7 @@ fn owns(item: &Item, actor: &str) -> bool {match item {Item::Project(project) => project.user_id == actor,Item::Document(document) => document.owner.principal_id() == actor,- Item::Chat(chat) => chat.user_id == actor,+ Item::Chat(chat) => chat.user_id.principal_id() == actor,}}diff --git a/crates/projects/src/outbound/pg_project_repo/content.rs b/crates/projects/src/outbound/pg_project_repo/content.rsindex b3a307cbc1..ea4a367880 100644--- a/crates/projects/src/outbound/pg_project_repo/content.rs+++ b/crates/projects/src/outbound/pg_project_repo/content.rs@@ -122,8 +122,7 @@ async fn get_sub_documents(}async fn get_sub_chats(pool: &PgPool, project_id: &str) -> Result<Vec<Chat>, sqlx::Error> {- sqlx::query_as!(- Chat,+ sqlx::query!(r#"SELECTc.id,@@ -142,6 +141,21 @@ async fn get_sub_chats(pool: &PgPool, project_id: &str) -> Result<Vec<Chat>, sql"#,project_id,)+ .try_map(|row| {+ Ok(Chat {+ id: row.id,+ name: row.name,+ user_id: Owner::from_principal_str(&row.user_id)+ .map_err(|e| sqlx::Error::Decode(Box::new(e)))?,+ model: row.model,+ project_id: row.project_id,+ created_at: row.created_at,+ updated_at: row.updated_at,+ token_count: row.token_count,+ is_persistent: row.is_persistent,+ deleted_at: row.deleted_at,+ })+ }).fetch_all(pool).await}diff --git a/services/document_cognition_service/src/service/get_chat.rs b/services/document_cognition_service/src/service/get_chat.rsindex ed9f990d45..342e6776ed 100644--- a/services/document_cognition_service/src/service/get_chat.rs+++ b/services/document_cognition_service/src/service/get_chat.rs@@ -42,7 +42,7 @@ pub async fn get_chat(#[allow(deprecated)]Ok(ChatResponse {id: chat.id,- user_id: chat.user_id,+ user_id: chat.user_id.principal_id(),name: chat.name,model: chat.model,messages,