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
fix (model): Item type can't be deserialized (#545)
Eric Hayes84d39d6eb7c7
diff --git a/rust/cloud-storage/.gitignore b/rust/cloud-storage/.gitignoreindex 2517c3140d..e4c8272eb0 100644--- a/rust/cloud-storage/.gitignore+++ b/rust/cloud-storage/.gitignore@@ -14,3 +14,4 @@# Jetbrains IDE files**/.idea/**/.helix/+**/.zed/diff --git a/rust/cloud-storage/model/src/chat/mod.rs b/rust/cloud-storage/model/src/chat/mod.rsindex 6c3fbb37fb..41d2e97676 100644--- a/rust/cloud-storage/model/src/chat/mod.rs+++ b/rust/cloud-storage/model/src/chat/mod.rs@@ -40,7 +40,7 @@ pub struct Chat {// whether the chat is persistent or notpub is_persistent: bool,/// The time the chat was deleted- #[serde(skip_serializing_if = "Option::is_none", with = "ts_seconds_option")]+ #[serde(with = "ts_seconds_option")]#[schema(value_type = i64, nullable=true)]pub deleted_at: Option<chrono::DateTime<chrono::Utc>>,}diff --git a/rust/cloud-storage/model/src/document/mod.rs b/rust/cloud-storage/model/src/document/mod.rsindex e52d32cf94..e627067c03 100644--- a/rust/cloud-storage/model/src/document/mod.rs+++ b/rust/cloud-storage/model/src/document/mod.rs@@ -82,7 +82,7 @@ pub struct BasicDocument {pub updated_at: Option<chrono::DateTime<chrono::Utc>>,/// The time the document was deleted- #[serde(skip_serializing_if = "Option::is_none", with = "ts_seconds_option")]+ #[serde(with = "ts_seconds_option")]#[schema(value_type = i64, nullable=true)]pub deleted_at: Option<chrono::DateTime<chrono::Utc>>,diff --git a/rust/cloud-storage/model/src/item/mod.rs b/rust/cloud-storage/model/src/item/mod.rsindex cfc4db5b7b..ce2032ab29 100644--- a/rust/cloud-storage/model/src/item/mod.rs+++ b/rust/cloud-storage/model/src/item/mod.rs@@ -2,12 +2,15 @@ use super::{chat::Chat, document::BasicDocument};use crate::project::Project;use models_pagination::Identify;use models_permissions::share_permission::access_level::AccessLevel;-use serde::{Deserialize, Serialize, Serializer};+use serde::{Deserialize, Serialize};use std::cmp::Ordering;use strum::EnumString;-use utoipa::ToSchema;+use utoipa::openapi::Discriminator;+use utoipa::{PartialSchema, ToSchema};pub mod map_item;+#[cfg(test)]+mod tests;#[derive(Debug, Clone, Eq, PartialEq, ToSchema, EnumString, Deserialize, Serialize)]#[strum(serialize_all = "snake_case")]@@ -18,65 +21,59 @@ pub enum CloudStorageItemType {Project,}-#[derive(Deserialize, Eq, PartialEq, Debug, Clone, ToSchema)]-#[serde(untagged)]-#[schema(discriminator(property_name = "type", mapping(- ("document" = "#/components/schemas/BasicDocument"),- ("chat" = "#/components/schemas/Chat"),- ("project" = "#/components/schemas/Project"),-)))]+#[derive(Deserialize, Serialize, Eq, PartialEq, Debug, Clone)]+#[serde(tag = "type", rename_all = "snake_case")]pub enum Item {Document(BasicDocument),Chat(Chat),Project(Project),}-impl Serialize for Item {- fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>- where- S: Serializer,- {- macro_rules! flatten_variant {- ($tag:expr, $tag_ty:ty, $inner_ty:ty, $inner_val:expr) => {{- #[derive(Serialize)]- struct Inline<'a> {- #[serde(rename = "type")]- tag: &'a $tag_ty,- #[serde(flatten)]- data: &'a $inner_ty,- }- let tmp = Inline {- tag: $tag,- data: $inner_val,- };- tmp.serialize(serializer)- }};- }+// manually implemented ToSchema+// - gen better frontend types by referencing subschemas+// - can deserialize / serialize in rust+impl ToSchema for Item {+ fn name() -> std::borrow::Cow<'static, str> {+ std::borrow::Cow::from("Item")+ }- match self {- Item::Document(doc) => {- flatten_variant!(- &CloudStorageItemType::Document,- CloudStorageItemType,- BasicDocument,- doc- )- }- Item::Chat(chat) => flatten_variant!(- &CloudStorageItemType::Chat,- CloudStorageItemType,- Chat,- chat- ),- Item::Project(project) => {- flatten_variant!(- &CloudStorageItemType::Project,- CloudStorageItemType,- Project,- project- )- }- }+ fn schemas(+ schemas: &mut Vec<(+ String,+ utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>,+ )>,+ ) {+ schemas.push((BasicDocument::name().into(), BasicDocument::schema()));+ schemas.push((Chat::name().into(), Chat::schema()));+ schemas.push((Project::name().into(), Project::schema()));+ <BasicDocument as ToSchema>::schemas(schemas);+ <Chat as ToSchema>::schemas(schemas);+ <Project as ToSchema>::schemas(schemas);+ }+}++impl PartialSchema for Item {+ fn schema() -> utoipa::openapi::RefOr<utoipa::openapi::schema::Schema> {+ utoipa::openapi::Schema::OneOf(+ utoipa::openapi::OneOfBuilder::new()+ .discriminator(Some(Discriminator {+ extensions: None,+ property_name: "type".into(),+ mapping: [+ ("document", "#/components/schemas/BasicDocument"),+ ("chat", "#/components/schemas/Chat"),+ ("project", "#/components/schemas/Project"),+ ]+ .into_iter()+ .map(|(k, v)| (k.to_string(), v.to_string()))+ .collect(),+ }))+ .item(utoipa::openapi::Ref::from_schema_name("BasicDocument"))+ .item(utoipa::openapi::Ref::from_schema_name("Chat"))+ .item(utoipa::openapi::Ref::from_schema_name("Project"))+ .build(),+ )+ .into()}}diff --git a/rust/cloud-storage/model/src/item/tests.rs b/rust/cloud-storage/model/src/item/tests.rsnew file mode 100644index 0000000000..736e34966c--- /dev/null+++ b/rust/cloud-storage/model/src/item/tests.rs@@ -0,0 +1,199 @@+/**+ * Item type needs to generate good types for the frontend+ * using reference schemas.+ *+ * It is imortant that it references schemas _and_ can be used+ * as a normal rust type.+ */+use super::*;+use utoipa::ToSchema;+#[test]+fn test_expected_schema() {+ // very good schema ok yes!+ #[derive(Serialize, Deserialize, ToSchema)]+ #[serde(untagged)]+ #[schema(+ discriminator(property_name = "type", mapping(+ ("document" = "#/components/schemas/BasicDocument"),+ ("chat" = "#/components/schemas/Chat"),+ ("project" = "#/components/schemas/Project"),+ )))]+ enum ItemDerivedSchema {+ Document(BasicDocument),+ Chat(Chat),+ Project(Project),+ }++ let expected_schema = serde_json::to_string_pretty(&ItemDerivedSchema::schema()).unwrap();+ let mut expected_schemas = Vec::new();+ ItemDerivedSchema::schemas(&mut expected_schemas);++ let actual_schema = serde_json::to_string_pretty(&Item::schema()).unwrap();+ let mut actual_schemas = Vec::new();+ Item::schemas(&mut actual_schemas);++ expected_schemas.sort_by(|a, b| a.0.cmp(&b.0));+ actual_schemas.sort_by(|a, b| a.0.cmp(&b.0));+ let expected_schemas = expected_schemas+ .iter()+ .map(|e| serde_json::to_string_pretty(e).unwrap())+ .collect::<Vec<_>>()+ .join("\n");++ let actual_schemas = actual_schemas+ .iter()+ .map(|e| serde_json::to_string_pretty(e).unwrap())+ .collect::<Vec<_>>()+ .join("\n");++ assert_eq!(expected_schemas, actual_schemas, "all");+ assert_eq!(expected_schema, actual_schema, "single");+}++#[test]+fn test_reference() {+ let schema = Item::schema();++ match schema {+ utoipa::openapi::RefOr::T(utoipa::openapi::Schema::OneOf(one_of)) => {+ let discriminator = one_of+ .discriminator+ .as_ref()+ .expect("Discriminator should exist");+ assert_eq!(discriminator.property_name, "type");++ assert_eq!(discriminator.mapping.len(), 3);+ assert_eq!(+ discriminator.mapping.get("document"),+ Some(&"#/components/schemas/BasicDocument".to_string())+ );+ assert_eq!(+ discriminator.mapping.get("chat"),+ Some(&"#/components/schemas/Chat".to_string())+ );+ assert_eq!(+ discriminator.mapping.get("project"),+ Some(&"#/components/schemas/Project".to_string())+ );++ // Check that we have exactly 3 items in the OneOf+ assert_eq!(one_of.items.len(), 3);++ let refs: Vec<String> = one_of+ .items+ .iter()+ .filter_map(|item| match item {+ utoipa::openapi::RefOr::Ref(r) => Some(r.ref_location.clone()),+ _ => None,+ })+ .collect();++ assert!(refs.contains(&"#/components/schemas/BasicDocument".to_string()));+ assert!(refs.contains(&"#/components/schemas/Chat".to_string()));+ assert!(refs.contains(&"#/components/schemas/Project".to_string()));+ }+ _ => panic!("Expected OneOf schema"),+ }++ // Verify that schemas() includes all subschemas+ let mut schemas = Vec::new();+ Item::schemas(&mut schemas);++ let schema_names: Vec<String> = schemas.iter().map(|(name, _)| name.clone()).collect();+ assert!(schema_names.contains(&"BasicDocument".to_string()));+ assert!(schema_names.contains(&"Chat".to_string()));+ assert!(schema_names.contains(&"Project".to_string()));+}++#[test]+fn test_document_serde() {+ let doc = BasicDocument {+ document_id: "doc123".to_string(),+ document_version_id: 1,+ owner: "user1".to_string(),+ document_name: "Test Document".to_string(),+ file_type: Some("pdf".to_string()),+ sha: Some("abc123".to_string()),+ project_id: None,+ branched_from_id: None,+ branched_from_version_id: None,+ document_family_id: None,+ created_at: Some(chrono::Utc::now()),+ updated_at: Some(chrono::Utc::now()),+ deleted_at: None,+ sub_type: None,+ };++ let item = Item::Document(doc.clone());++ let json = serde_json::to_string(&item).expect("Serialization should succeed");++ let deserialized: Item = serde_json::from_str(&json).expect("Deserialization should succeed");++ match deserialized {+ Item::Document(d) => {+ assert_eq!(doc.document_id, d.document_id);+ assert_eq!(doc.document_name, d.document_name);+ }+ _ => panic!("expected document"),+ }+}++#[test]+fn test_chat_serde() {+ let chat = Chat {+ id: "chat123".to_string(),+ name: "Test Chat".to_string(),+ user_id: "user1".to_string(),+ model: Some("claude-3".to_string()),+ project_id: None,+ created_at: Some(chrono::Utc::now()),+ updated_at: Some(chrono::Utc::now()),+ token_count: Some(100),+ is_persistent: true,+ deleted_at: None,+ };++ let item = Item::Chat(chat.clone());+ let json = serde_json::to_string(&item).expect("Serialization should succeed");++ assert!(json.contains("\"type\":\"chat\""));++ let deserialized: Item = serde_json::from_str(&json).expect("Deserialization should succeed");++ match deserialized {+ Item::Chat(c) => {+ assert_eq!(chat.id, c.id);+ assert_eq!(chat.name, c.name);+ }+ _ => panic!("expected chat"),+ }+}++#[test]+fn test_project_serde() {+ // Create a sample Project+ let project = Project {+ id: "proj123".to_string(),+ name: "Test Project".to_string(),+ user_id: "user1".to_string(),+ parent_id: None,+ created_at: Some(chrono::Utc::now()),+ updated_at: Some(chrono::Utc::now()),+ deleted_at: None,+ };++ let item = Item::Project(project.clone());+ let json = serde_json::to_string(&item).expect("Serialization should succeed");++ println!("{}", json);+ let deserialized: Item = serde_json::from_str(&json).expect("Deserialization should succeed");++ match deserialized {+ Item::Project(p) => {+ assert_eq!(project.id, p.id);+ assert_eq!(project.name, p.name);+ }+ _ => panic!("expecte project"),+ }+}diff --git a/rust/cloud-storage/model/src/project/mod.rs b/rust/cloud-storage/model/src/project/mod.rsindex 4faea4dea3..be80be549f 100644--- a/rust/cloud-storage/model/src/project/mod.rs+++ b/rust/cloud-storage/model/src/project/mod.rs@@ -27,8 +27,7 @@ pub struct Project {#[schema(value_type = i64, nullable=false)]pub updated_at: Option<chrono::DateTime<chrono::Utc>>,- /// The time the project was deleted- #[serde(skip_serializing_if = "Option::is_none", with = "ts_seconds_option")]+ #[serde(with = "ts_seconds_option")]#[schema(value_type = i64, nullable=true)]pub deleted_at: Option<chrono::DateTime<chrono::Utc>>,}