Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

Fix starter guide tag mentions and preserve user edits on retries (#6571)

Peter Chinman6cef9c0fdf80
diff --git a/crates/documents/src/domain.rs b/crates/documents/src/domain.rs
index efa9d28d63..f24c2974ea 100644
--- a/crates/documents/src/domain.rs
+++ b/crates/documents/src/domain.rs
@@ -14,6 +14,9 @@ pub mod markdown_backfill;
#[cfg(feature = "document_create")]
pub mod create;
+#[cfg(feature = "document_create")]
+pub mod starter;
+
#[cfg(feature = "ports")]
pub mod upload_finalize;
diff --git a/crates/documents/src/domain/starter.rs b/crates/documents/src/domain/starter.rs
new file mode 100644
index 0000000000..d1f4ec8d58
--- /dev/null
+++ b/crates/documents/src/domain/starter.rs
@@ -0,0 +1,60 @@
+//! Retry-safe creation and tagging of starter documents.
+
+use std::collections::HashSet;
+use std::future::Future;
+
+use uuid::Uuid;
+
+use super::create::NewMarkdownTextDocument;
+use super::models::DocumentError;
+
+#[cfg(test)]
+mod test;
+
+/// Documents available after a seeding attempt, including prior creations.
+#[derive(Default)]
+pub struct StarterDocumentsOutcome {
+ /// Documents inserted on this attempt, for non-idempotent follow-up work.
+ pub created: HashSet<Uuid>,
+ /// Documents that were created successfully or already existed.
+ pub available: HashSet<Uuid>,
+ /// At least one creation or tag operation failed and needs a retry.
+ pub incomplete: bool,
+}
+
+/// Create documents in order, attempting each one's tag before the next create.
+/// A tag or creation failure does not prevent independent documents from being
+/// created. Conflicts only retry tagging; initial properties remain untouched.
+/// Callers finalize available content before reporting incomplete seeding.
+pub async fn seed_starter_documents<C, T, CF, TF>(
+ documents: Vec<(Uuid, NewMarkdownTextDocument)>,
+ mut create: C,
+ mut tag: T,
+) -> StarterDocumentsOutcome
+where
+ C: FnMut(NewMarkdownTextDocument) -> CF,
+ CF: Future<Output = Result<(), DocumentError>>,
+ T: FnMut(Uuid) -> TF,
+ TF: Future<Output = Result<(), DocumentError>>,
+{
+ let mut outcome = StarterDocumentsOutcome::default();
+ for (id, document) in documents {
+ match create(document).await {
+ Ok(()) => {
+ outcome.created.insert(id);
+ }
+ Err(DocumentError::Conflict(_)) => {}
+ Err(error) => {
+ tracing::error!(error=?error, document_id=%id, "failed to create starter document");
+ outcome.incomplete = true;
+ continue;
+ }
+ }
+ outcome.available.insert(id);
+ if let Err(error) = tag(id).await {
+ tracing::error!(error=?error, document_id=%id, "failed to tag starter document");
+ outcome.incomplete = true;
+ }
+ }
+ outcome
+}
diff --git a/crates/documents/src/domain/starter/test.rs b/crates/documents/src/domain/starter/test.rs
new file mode 100644
index 0000000000..cc3dd91c48
--- /dev/null
+++ b/crates/documents/src/domain/starter/test.rs
@@ -0,0 +1,141 @@
+use std::collections::{HashMap, HashSet};
+use std::future::ready;
+use std::sync::Mutex;
+
+use super::*;
+use crate::domain::create::{MarkdownSubtype, NewDocumentMetadata};
+use crate::domain::models::PropertyInput;
+use models_properties::api::SetPropertyValue;
+const PRIORITY_PROPERTY: Uuid = Uuid::from_u128(100);
+const INITIAL_PRIORITY: Uuid = Uuid::from_u128(101);
+const EDITED_PRIORITY: Uuid = Uuid::from_u128(102);
+
+#[derive(Default)]
+struct FakeStore {
+ priorities: HashMap<Uuid, Uuid>,
+ tags: HashSet<Uuid>,
+ fail_create: HashSet<Uuid>,
+ fail_tag: HashSet<Uuid>,
+ calls: Vec<(Uuid, &'static str)>,
+}
+
+fn documents() -> Vec<(Uuid, NewMarkdownTextDocument)> {
+ (1..=3)
+ .map(|n| {
+ let id = Uuid::from_u128(n);
+ (
+ id,
+ NewMarkdownTextDocument {
+ metadata: NewDocumentMetadata::builder("starter").id(id).build(),
+ markdown: id.to_string(),
+ subtype: MarkdownSubtype::Task {
+ property_values: Some(vec![PropertyInput {
+ property_id: PRIORITY_PROPERTY.to_string(),
+ value: SetPropertyValue::SelectOption {
+ option_id: INITIAL_PRIORITY,
+ },
+ }]),
+ share_with_team: false,
+ team_id: None,
+ },
+ },
+ )
+ })
+ .collect()
+}
+
+async fn seed(store: &Mutex<FakeStore>) -> StarterDocumentsOutcome {
+ seed_starter_documents(
+ documents(),
+ |document| {
+ let mut store = store.lock().unwrap();
+ let id = Uuid::parse_str(&document.markdown).unwrap();
+ store.calls.push((id, "create"));
+ let result = if store.fail_create.contains(&id) {
+ Err(DocumentError::Internal(anyhow::anyhow!(
+ "create unavailable"
+ )))
+ } else if store.priorities.contains_key(&id) {
+ Err(DocumentError::Conflict("already exists".into()))
+ } else {
+ let MarkdownSubtype::Task {
+ property_values: Some(properties),
+ ..
+ } = document.subtype
+ else {
+ panic!("expected task")
+ };
+ let SetPropertyValue::SelectOption { option_id } = properties[0].value else {
+ panic!("expected priority")
+ };
+ store.priorities.insert(id, option_id);
+ Ok(())
+ };
+ ready(result)
+ },
+ |id| {
+ let mut store = store.lock().unwrap();
+ store.calls.push((id, "tag"));
+ let result = if store.fail_tag.contains(&id) {
+ Err(DocumentError::Internal(anyhow::anyhow!("tag unavailable")))
+ } else {
+ store.tags.insert(id);
+ Ok(())
+ };
+ ready(result)
+ },
+ )
+ .await
+}
+
+#[tokio::test]
+async fn tag_failure_does_not_block_content_and_retry_preserves_edited_priority() {
+ let first_id = Uuid::from_u128(1);
+ let store = Mutex::new(FakeStore {
+ fail_tag: HashSet::from([first_id]),
+ ..Default::default()
+ });
+ let first = seed(&store).await;
+ assert!(first.incomplete);
+ assert_eq!(first.available.len(), 3);
+ assert_eq!(first.created.len(), 3);
+ {
+ let mut store = store.lock().unwrap();
+ assert_eq!(
+ store.calls,
+ vec![
+ (first_id, "create"),
+ (first_id, "tag"),
+ (Uuid::from_u128(2), "create"),
+ (Uuid::from_u128(2), "tag"),
+ (Uuid::from_u128(3), "create"),
+ (Uuid::from_u128(3), "tag"),
+ ]
+ );
+ store.priorities.insert(first_id, EDITED_PRIORITY);
+ store.fail_tag.clear();
+ }
+ let retried = seed(&store).await;
+ assert!(!retried.incomplete);
+ assert!(retried.created.is_empty());
+ assert_eq!(retried.available.len(), 3);
+ let store = store.lock().unwrap();
+ assert_eq!(store.tags.len(), 3);
+ assert_eq!(store.priorities[&first_id], EDITED_PRIORITY);
+}
+
+#[tokio::test]
+async fn create_failure_does_not_tag_missing_document_or_block_later_documents() {
+ let first_id = Uuid::from_u128(1);
+ let store = Mutex::new(FakeStore {
+ fail_create: HashSet::from([first_id]),
+ ..Default::default()
+ });
+ let result = seed(&store).await;
+ assert!(result.incomplete);
+ assert_eq!(result.available.len(), 2);
+ assert!(!result.available.contains(&first_id));
+ let store = store.lock().unwrap();
+ assert!(!store.calls.contains(&(first_id, "tag")));
+ assert_eq!(store.tags.len(), 2);
+}
diff --git a/crates/properties/src/domain/model.rs b/crates/properties/src/domain/model.rs
index 80090d1f66..c4fac1b688 100644
--- a/crates/properties/src/domain/model.rs
+++ b/crates/properties/src/domain/model.rs
@@ -190,6 +190,15 @@ impl<'a> PropertyDefinitionOwner<'a> {
}
}
+/// Result of resolving an option by value without changing an existing option.
+#[derive(Debug)]
+pub struct GetOrCreatePropertyOptionResult {
+ /// The newly inserted or existing option.
+ pub option: PropertyOption,
+ /// Whether this call inserted the option.
+ pub created: bool,
+}
+
/// Result of getting or creating an owner's tag definition.
#[derive(Debug, Clone)]
pub struct GetOrCreateTagDefinitionResult {
diff --git a/crates/properties/src/domain/ports.rs b/crates/properties/src/domain/ports.rs
index a1b8252f40..3cb5235956 100644
--- a/crates/properties/src/domain/ports.rs
+++ b/crates/properties/src/domain/ports.rs
@@ -22,10 +22,10 @@ use uuid::Uuid;
use super::model::{
EditReceipt, EntityPropertiesKey, EntityPropertyInfo, EntityPropertyMutationSnapshot,
- EntityPropertyOptionSelection, EntityPropertyOptionUpdate, GetOrCreateTagDefinitionResult,
- PropertyDefinitionOwner, PropertyOptionReplaceOutcome, PropertyOptionReplacePlan,
- TagPromotionOutcome, TagRemapOutcome, TaskAssignedNotification, UpdatePropertyOptionOutcome,
- ViewReceipt,
+ EntityPropertyOptionSelection, EntityPropertyOptionUpdate, GetOrCreatePropertyOptionResult,
+ GetOrCreateTagDefinitionResult, PropertyDefinitionOwner, PropertyOptionReplaceOutcome,
+ PropertyOptionReplacePlan, TagPromotionOutcome, TagRemapOutcome, TaskAssignedNotification,
+ UpdatePropertyOptionOutcome, ViewReceipt,
};
/// Repository trait for property operations.
@@ -121,6 +121,16 @@ pub trait PropertiesRepo: Send + Sync + 'static {
color: Option<String>,
) -> impl Future<Output = Result<PropertyOption, Self::Err>> + Send;
+ /// Resolve by exact value, inserting if absent. Concurrent calls return the
+ /// same option; an existing option's color and display order are preserved.
+ fn get_or_create_property_option(
+ &self,
+ property_definition_id: Uuid,
+ display_order: i32,
+ value: PropertyOptionValue,
+ color: Option<String>,
+ ) -> impl Future<Output = Result<GetOrCreatePropertyOptionResult, Self::Err>> + Send;
+
/// Update a property option's value, color, and display order in place.
/// The option id is preserved, so every entity referencing it reflects the
/// change with no per-entity rewrite.
diff --git a/crates/properties/src/domain/service.rs b/crates/properties/src/domain/service.rs
index c8f8466218..0236cdc653 100644
--- a/crates/properties/src/domain/service.rs
+++ b/crates/properties/src/domain/service.rs
@@ -216,6 +216,16 @@ pub trait PropertiesService: Send + Sync + 'static {
request: &AddPropertyOptionRequest,
) -> impl Future<Output = Result<PropertyOption, PropertiesErr>> + Send;
+ /// Get or create an option by exact value on a property owned by the caller.
+ /// Preserves existing option metadata and tolerates concurrent creation.
+ fn get_or_create_property_option(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ team: Option<&TeamReceipt>,
+ property_definition_id: Uuid,
+ request: &AddPropertyOptionRequest,
+ ) -> impl Future<Output = Result<PropertyOption, PropertiesErr>> + Send;
+
/// Update a property option in place (rename / recolor / reorder) on a
/// property owned by the caller. The option id is preserved, so the change
/// is reflected on every entity that references it.
diff --git a/crates/properties/src/domain/service_impl.rs b/crates/properties/src/domain/service_impl.rs
index d9b39476a9..c0923f5560 100644
--- a/crates/properties/src/domain/service_impl.rs
+++ b/crates/properties/src/domain/service_impl.rs
@@ -1,6 +1,7 @@
//! Service implementation for properties.
mod helpers;
+mod options;
mod task_properties;
use std::collections::{HashMap, HashSet};
@@ -1230,36 +1231,10 @@ where
property_definition_id: Uuid,
request: &AddPropertyOptionRequest,
) -> Result<PropertyOption, PropertiesErr> {
- let definition = self
- .owned_modifiable_definition(
- property_definition_id,
- user_id,
- team_id_from_receipt(team),
- )
+ let (display_order, option_value, color) = self
+ .prepare_property_option(user_id, team, property_definition_id, request)
.await?;
- request
- .validate()
- .map_err(|e| PropertiesErr::Validation(e.to_string()))?;
- request
- .validate_compatibility(&definition.data_type)
- .map_err(|e| PropertiesErr::Validation(e.to_string()))?;
-
- let (display_order, option_value, color) = match request {
- AddPropertyOptionRequest::SelectString { option } => (
- option.display_order,
- PropertyOptionValue::String(option.value.clone()),
- option.color.clone(),
- ),
- AddPropertyOptionRequest::SelectNumber { option } => (
- option.display_order,
- PropertyOptionValue::Number(option.value),
- None,
- ),
- };
-
- validate_option_color(&definition.data_type, color.as_deref(), color.as_deref())?;
-
let option = self
.repository
.create_property_option(property_definition_id, display_order, option_value, color)
@@ -1277,6 +1252,35 @@ where
Ok(option)
}
+ async fn get_or_create_property_option(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ team: Option<&TeamReceipt>,
+ property_definition_id: Uuid,
+ request: &AddPropertyOptionRequest,
+ ) -> Result<PropertyOption, PropertiesErr> {
+ let (display_order, option_value, color) = self
+ .prepare_property_option(user_id, team, property_definition_id, request)
+ .await?;
+ let result = self
+ .repository
+ .get_or_create_property_option(
+ property_definition_id,
+ display_order,
+ option_value,
+ color,
+ )
+ .await
+ .map_err(anyhow::Error::from)?;
+ if result.created {
+ self.publish_property_event(Self::property_option_created_event(
+ &result.option,
+ user_id,
+ ));
+ }
+ Ok(result.option)
+ }
+
#[tracing::instrument(skip(self, team, request), fields(request = ?request), err)]
async fn update_property_option(
&self,
diff --git a/crates/properties/src/domain/service_impl/options.rs b/crates/properties/src/domain/service_impl/options.rs
new file mode 100644
index 0000000000..9b7ef1599d
--- /dev/null
+++ b/crates/properties/src/domain/service_impl/options.rs
@@ -0,0 +1,50 @@
+use super::*;
+
+impl<R, P, N, B> PropertiesServiceImpl<R, P, N, B>
+where
+ R: PropertiesRepo,
+ P: PermissionService,
+ N: NotificationService,
+ B: MacroEventBroker,
+ anyhow::Error: From<R::Err>,
+{
+ pub(super) async fn prepare_property_option(
+ &self,
+ user_id: &MacroUserIdStr<'_>,
+ team: Option<&TeamReceipt>,
+ property_definition_id: Uuid,
+ request: &AddPropertyOptionRequest,
+ ) -> Result<(i32, PropertyOptionValue, Option<String>), PropertiesErr> {
+ let definition = self
+ .owned_modifiable_definition(
+ property_definition_id,
+ user_id,
+ team_id_from_receipt(team),
+ )
+ .await?;
+
+ request
+ .validate()
+ .map_err(|e| PropertiesErr::Validation(e.to_string()))?;
+ request
+ .validate_compatibility(&definition.data_type)
+ .map_err(|e| PropertiesErr::Validation(e.to_string()))?;
+
+ let (display_order, option_value, color) = match request {
+ AddPropertyOptionRequest::SelectString { option } => (
+ option.display_order,
+ PropertyOptionValue::String(option.value.clone()),
+ option.color.clone(),
+ ),
+ AddPropertyOptionRequest::SelectNumber { option } => (
+ option.display_order,
+ PropertyOptionValue::Number(option.value),
+ None,
+ ),
+ };
+
+ validate_option_color(&definition.data_type, color.as_deref(), color.as_deref())?;
+
+ Ok((display_order, option_value, color))
+ }
+}
diff --git a/crates/properties/src/domain/test.rs b/crates/properties/src/domain/test.rs
index 48ed0f1f73..ac4614d0ab 100644
--- a/crates/properties/src/domain/test.rs
+++ b/crates/properties/src/domain/test.rs
@@ -4519,3 +4519,76 @@ async fn merge_tag_rejects_merging_a_label_into_itself() {
.unwrap_err();
assert!(matches!(err, PropertiesErr::Validation(_)));
}
+
+#[tokio::test]
+async fn get_or_create_option_publishes_only_for_new_options() {
+ for created in [true, false] {
+ let definition_id = Uuid::from_u128(0xD0C);
+ let option_id = Uuid::from_u128(0xD0C1);
+ let definition = property_definition_for_event(definition_id, "Tags", DataType::Tag, true);
+ let option = property_option_for_event(
+ option_id,
+ definition_id,
+ 7,
+ PropertyOptionValue::String("docs".into()),
+ Some("#0091FF"),
+ );
+ let mut repo = MockPropertiesRepo::new();
+ expect_owned_modifiable_definition(&mut repo, definition);
+ repo.expect_get_or_create_property_option()
+ .times(1)
+ .return_once(move |_, _, _, _| {
+ Box::pin(async move {
+ Ok(crate::domain::model::GetOrCreatePropertyOptionResult { option, created })
+ })
+ });
+ let broker = RecordingEventBroker::default();
+ let service = service_with_event_broker(repo, broker.clone());
+ let option = service
+ .get_or_create_property_option(
+ &caller_user_id(),
+ None,
+ definition_id,
+ &AddPropertyOptionRequest::SelectString {
+ option: AddStringOptionRequest {
+ display_order: 0,
+ value: "docs".into(),
+ color: Some("#0091FF".into()),
+ },
+ },
+ )
+ .await
+ .unwrap();
+ assert_eq!(option.id, option_id);
+ assert_eq!(option.display_order, 7);
+ assert_eq!(broker.events().len(), usize::from(created));
+ }
+}
+
+#[tokio::test]
+async fn get_or_create_option_rejects_unowned_definition() {
+ let definition_id = Uuid::from_u128(0xD0C);
+ let definition = property_definition_for_event(definition_id, "Tags", DataType::Tag, true);
+ let mut repo = MockPropertiesRepo::new();
+ repo.expect_get_property_definition()
+ .return_once(move |_| Box::pin(async move { Ok(Some(definition)) }));
+ repo.expect_get_property_definition_with_owner()
+ .return_once(|_, _, _| Box::pin(async { Ok(None) }));
+ repo.expect_get_or_create_property_option().never();
+ let service = service_with_event_broker(repo, RecordingEventBroker::default());
+ let result = service
+ .get_or_create_property_option(
+ &caller_user_id(),
+ None,
+ definition_id,
+ &AddPropertyOptionRequest::SelectString {
+ option: AddStringOptionRequest {
+ display_order: 0,
+ value: "docs".into(),
+ color: Some("#0091FF".into()),
+ },
+ },
+ )
+ .await;
+ assert!(matches!(result, Err(PropertiesErr::NotFound)));
+}
diff --git a/crates/properties/src/outbound/options_test.rs b/crates/properties/src/outbound/options_test.rs
index 4007540adb..b1a9c1066a 100644
--- a/crates/properties/src/outbound/options_test.rs
+++ b/crates/properties/src/outbound/options_test.rs
@@ -670,3 +670,70 @@ async fn replace_property_options_rejects_foreign_ids(pool: Pool<Postgres>) -> a
assert_eq!(repo.get_property_options(property_id).await?.len(), 4);
Ok(())
}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../fixtures", scripts("properties"))
+)]
+async fn get_or_create_option_converges_under_concurrency(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let repo = PropertiesPgRepo::new(pool);
+ let property_id = PRIORITY_PROPERTY_ID.parse()?;
+ let create = || {
+ repo.get_or_create_property_option(
+ property_id,
+ 4,
+ PropertyOptionValue::String("docs".into()),
+ Some("#0091FF".into()),
+ )
+ };
+ let (first, second) = tokio::join!(create(), create());
+ let first = first?;
+ let second = second?;
+ assert_eq!(first.option.id, second.option.id);
+ assert_ne!(first.created, second.created);
+ let repeated = repo
+ .get_or_create_property_option(
+ property_id,
+ 99,
+ PropertyOptionValue::String("docs".into()),
+ Some("#FF0000".into()),
+ )
+ .await?;
+ assert!(!repeated.created);
+ assert_eq!(repeated.option.id, first.option.id);
+ assert_eq!(repeated.option.display_order, 4);
+ assert_eq!(repeated.option.color.as_deref(), Some("#0091FF"));
+ assert_eq!(
+ repo.get_property_options(property_id)
+ .await?
+ .iter()
+ .filter(|option| option.value == PropertyOptionValue::String("docs".into()))
+ .count(),
+ 1
+ );
+ Ok(())
+}
+
+#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]
+async fn get_or_create_option_propagates_non_duplicate_errors(pool: Pool<Postgres>) {
+ let repo = PropertiesPgRepo::new(pool);
+ let error = repo
+ .get_or_create_property_option(
+ Uuid::nil(),
+ 0,
+ PropertyOptionValue::String("docs".into()),
+ None,
+ )
+ .await
+ .unwrap_err();
+ assert!(
+ error
+ .downcast_ref::<sqlx::Error>()
+ .unwrap()
+ .as_database_error()
+ .unwrap()
+ .is_foreign_key_violation()
+ );
+}
diff --git a/crates/properties/src/outbound/properties_pg_repo.rs b/crates/properties/src/outbound/properties_pg_repo.rs
index 84078deb09..2c74cf5bc0 100644
--- a/crates/properties/src/outbound/properties_pg_repo.rs
+++ b/crates/properties/src/outbound/properties_pg_repo.rs
@@ -16,8 +16,9 @@ use super::{
};
use crate::domain::model::{
EntityPropertiesKey, EntityPropertyInfo, EntityPropertyMutationSnapshot,
- GetOrCreateTagDefinitionResult, PropertyDefinitionOwner, PropertyOptionReplaceOutcome,
- PropertyOptionReplacePlan, TagPromotionOutcome, TagRemapOutcome, UpdatePropertyOptionOutcome,
+ GetOrCreatePropertyOptionResult, GetOrCreateTagDefinitionResult, PropertyDefinitionOwner,
+ PropertyOptionReplaceOutcome, PropertyOptionReplacePlan, TagPromotionOutcome, TagRemapOutcome,
+ UpdatePropertyOptionOutcome,
};
use crate::domain::ports::PropertiesRepo;
use models_properties::DataType;
@@ -187,6 +188,24 @@ impl PropertiesRepo for PropertiesPgRepo {
.await
}
+ #[tracing::instrument(skip(self), err)]
+ async fn get_or_create_property_option(
+ &self,
+ property_definition_id: Uuid,
+ display_order: i32,
+ value: PropertyOptionValue,
+ color: Option<String>,
+ ) -> Result<GetOrCreatePropertyOptionResult, Self::Err> {
+ property_option_queries::get_or_create_property_option(
+ &self.pool,
+ property_definition_id,
+ display_order,
+ value,
+ color,
+ )
+ .await
+ }
+
#[tracing::instrument(skip(self), err)]
async fn update_property_option(
&self,
diff --git a/crates/properties/src/outbound/property_option_queries.rs b/crates/properties/src/outbound/property_option_queries.rs
index ba3a29a2ff..f84222efcc 100644
--- a/crates/properties/src/outbound/property_option_queries.rs
+++ b/crates/properties/src/outbound/property_option_queries.rs
@@ -8,7 +8,8 @@ use sqlx::{Pool, Postgres};
use uuid::Uuid;
use crate::domain::model::{
- PropertyOptionReplaceOutcome, PropertyOptionReplacePlan, UpdatePropertyOptionOutcome,
+ GetOrCreatePropertyOptionResult, PropertyOptionReplaceOutcome, PropertyOptionReplacePlan,
+ UpdatePropertyOptionOutcome,
};
/// Gets a single property option by ID.
@@ -163,6 +164,74 @@ pub async fn create_property_option(
})
}
+/// Resolve an option without overwriting an existing option's metadata.
+#[tracing::instrument(skip(pool), err)]
+pub async fn get_or_create_property_option(
+ pool: &Pool<Postgres>,
+ property_definition_id: Uuid,
+ display_order: i32,
+ value: PropertyOptionValue,
+ color: Option<String>,
+) -> anyhow::Result<GetOrCreatePropertyOptionResult> {
+ if let Some(option) = get_property_options(pool, property_definition_id)
+ .await?
+ .into_iter()
+ .find(|option| option.value == value)
+ {
+ return Ok(GetOrCreatePropertyOptionResult {
+ option,
+ created: false,
+ });
+ }
+
+ match create_property_option(
+ pool,
+ property_definition_id,
+ display_order,
+ value.clone(),
+ color,
+ )
+ .await
+ {
+ Ok(option) => Ok(GetOrCreatePropertyOptionResult {
+ option,
+ created: true,
+ }),
+ Err(error) => {
+ // Only a collision on the value is recoverable. Do not hide a
+ // missing definition, connection failure, or unrelated constraint.
+ let duplicate_value = error
+ .downcast_ref::<sqlx::Error>()
+ .and_then(sqlx::Error::as_database_error)
+ .is_some_and(|error| {
+ error.is_unique_violation()
+ && matches!(
+ error.constraint(),
+ Some(
+ "unique_property_options_string_value"
+ | "unique_property_options_string_value_sha256"
+ | "unique_property_options_number_value"
+ )
+ )
+ });
+ if !duplicate_value {
+ return Err(error);
+ }
+ // The failed insert waits for the winning transaction to commit.
+ // A fresh read can therefore resolve its option under READ COMMITTED.
+ let option = get_property_options(pool, property_definition_id)
+ .await?
+ .into_iter()
+ .find(|option| option.value == value)
+ .ok_or(error)?;
+ Ok(GetOrCreatePropertyOptionResult {
+ option,
+ created: false,
+ })
+ }
+ }
+}
+
/// Updates a property option's value, color, and display order in place.
///
/// The option id is preserved, so every entity referencing this option by id in its
diff --git a/docs/AGENT_GUIDE/login.md b/docs/AGENT_GUIDE/login.md
index a72e79a035..1b90e90f8e 100644
--- a/docs/AGENT_GUIDE/login.md
+++ b/docs/AGENT_GUIDE/login.md
@@ -13,7 +13,10 @@
the user's inbox (locally: Mailpit).
5. First login auto-creates the user, seeds onboarding content (a "Macro Support x <name>"
channel, a "Macro how to guide" doc favorite, three sample tasks), and lands on
- `/app/component/inbox`.
+ `/app/component/inbox`. The starter documents share a personal `docs` tag; the
+ guide's `#` example is an inline mention of that same tag. A tag attachment
+ failure does not block the remaining content; signup retries repair tags
+ without resetting task priorities. The guide waits until its tag IDs resolve.
## Mailpit (local email)
diff --git a/services/document_storage_service/src/api/documents/initialize_starter_docs.rs b/services/document_storage_service/src/api/documents/initialize_starter_docs.rs
index 105720a373..2a69dc44ab 100644
--- a/services/document_storage_service/src/api/documents/initialize_starter_docs.rs
+++ b/services/document_storage_service/src/api/documents/initialize_starter_docs.rs
@@ -7,7 +7,8 @@ use axum::{
use channels::domain::{models::CreateEntityMentionOptions, ports::ChannelService};
use documents_hex::domain::{
create::{MarkdownSubtype, NewDocumentMetadata, NewMarkdownTextDocument},
- models::DocumentError,
+ models::{DocumentError, PropertyInput},
+ starter::seed_starter_documents,
};
use entity_access::domain::{
models::{BotAccessScope, EditAccessLevel, ViewAccessLevel},
@@ -25,8 +26,7 @@ use models_properties::api::{AddPropertyOptionRequest, AddStringOptionRequest, S
use models_properties::service::property_option::PropertyOptionValue;
use properties::{PropertiesService as _, domain::model::TagScope};
use reqwest::StatusCode;
-use std::collections::HashSet;
-use system_properties::{PriorityOption, SystemPropertyKey};
+use system_properties::{PriorityOption, StatusOption, SystemPropertyKey};
/// Also the name `get_starter_docs` resolves the guide by, so the two stay in
/// sync from one definition.
@@ -44,7 +44,7 @@ struct StarterTask {
template: &'static str,
id_placeholder: &'static str,
name_placeholder: &'static str,
- /// Priority set after creation, so the reading order (High → Low) shows
+ /// Initial priority, so the reading order (High → Low) shows
/// in the default priority-sorted task list.
priority: PriorityOption,
}
@@ -73,9 +73,10 @@ const STARTER_TASKS: [StarterTask; 3] = [
},
];
-/// Gateway push sent once the starter set — the guide favorite included — is
-/// fully seeded. Seeding is fire-and-forget from signup, so a fresh account's
-/// app is often already open with empty Soup and favorites lists cached; the
+/// Gateway push sent after each attempt publishes its available starter content,
+/// including the guide favorite when available. Signup seeding is fire-and-forget,
+/// so a fresh account's app is often already open with empty Soup and favorites
+/// lists cached; the
/// web client invalidates those lists and provisioned properties on this
/// message.
const STARTER_DOCS_INITIALIZED_MESSAGE_TYPE: &str = "starter_docs_initialized";
@@ -132,7 +133,7 @@ async fn resolve_docs_tag(
state
.properties_service
- .add_property_option(
+ .get_or_create_property_option(
user_id,
None,
definition_id,
@@ -184,8 +185,20 @@ pub async fn handler(
.collect();
let guide_id = starter_doc_id(user_id, HOW_TO_GUIDE_NAME).to_string();
+ // The guide needs real tag IDs; independent tasks can still be created
+ // if resolution fails. Report incomplete seeding only after publishing
+ // the content that was successfully created, so the caller can retry.
+ let docs_tag = resolve_docs_tag(&state, user_id).await;
+ let mut incomplete = docs_tag.is_none();
let fill = |template: &str| {
let mut filled = template.to_string();
+ if let Some((tag_definition_id, tag_option_id)) = docs_tag {
+ filled = filled
+ .replace("DOCS_TAG_OPTION_ID", &tag_option_id.to_string())
+ .replace("DOCS_TAG_DEFINITION_ID", &tag_definition_id.to_string())
+ .replace("DOCS_TAG_LABEL", DOCS_TAG_LABEL)
+ .replace("DOCS_TAG_COLOR", DOCS_TAG_COLOR);
+ }
for (task, id) in STARTER_TASKS.iter().zip(&task_ids) {
filled = filled
.replace(task.id_placeholder, id)
@@ -194,67 +207,129 @@ pub async fn handler(
filled
};
- // Ids created by THIS call: backlinks and decorations run once, on the
- // call that created the document.
- let mut created_now: HashSet<String> = HashSet::new();
+ let organization_id = user_context
+ .authorization
+ .user
+ .user_context
+ .organization_id
+ .map(i64::from);
+ // Await each tag attempt before the next create, but do not let a tag
+ // failure prevent the remaining documents from becoming available.
+ let state_ref = &state;
+ let tag_document = |id: uuid::Uuid| async move {
+ let state = state_ref;
+ let document_id = id.to_string();
+ let Some((tag_definition_id, tag_option_id)) = docs_tag else {
+ return Err(DocumentError::Internal(anyhow::anyhow!(
+ "failed to resolve starter doc tag"
+ )));
+ };
+ let receipt = state
+ .entity_access_service
+ .generate_bot_entity_access_receipt::<EditAccessLevel>(
+ bot_id::MACRO_SYSTEM_BOT_ID,
+ BotAccessScope::User {
+ user_id: user_id.clone(),
+ user_org_id: organization_id,
+ },
+ &document_id,
+ EntityType::Document,
+ )
+ .await
+ .map_err(|e| {
+ tracing::error!(error=?e, document_id, "failed to authorize starter doc tag");
+ DocumentError::Internal(anyhow::anyhow!(e))
+ })?;
+ state
+ .properties_service
+ .add_entity_property_option(&receipt, tag_definition_id, tag_option_id)
+ .await
+ .map_err(|e| {
+ tracing::error!(error=?e, document_id, "failed to tag starter doc");
+ DocumentError::Internal(anyhow::anyhow!(e))
+ })
+ };
- for (task, id) in STARTER_TASKS.iter().zip(&task_ids) {
- let created = state
- .documents_state
- .creator
- .create_markdown_text(
- user_id.clone(),
+ let mut documents: Vec<_> = STARTER_TASKS
+ .iter()
+ .map(|task| {
+ let id = starter_doc_id(user_id, task.name);
+ (
+ id,
NewMarkdownTextDocument {
metadata: NewDocumentMetadata::builder(task.name)
- .id(starter_doc_id(user_id, task.name))
+ .id(id)
.attribution(system_for_user.clone())
.build(),
markdown: fill(task.template),
subtype: MarkdownSubtype::Task {
- property_values: None,
+ // Providing properties replaces the task defaults, so include
+ // the normal assignee and status alongside the initial priority.
+ property_values: Some(vec![
+ PropertyInput {
+ property_id: SystemPropertyKey::ASSIGNEES_UUID.to_string(),
+ value: SetPropertyValue::MultiEntityReference {
+ references: vec![models_properties::EntityReference {
+ entity_id: user_id.as_ref().to_string(),
+ entity_type: models_properties::EntityType::User,
+ specific_message_id: None,
+ }],
+ },
+ },
+ PropertyInput {
+ property_id: SystemPropertyKey::STATUS_UUID.to_string(),
+ value: SetPropertyValue::SelectOption {
+ option_id: StatusOption::NotStarted.uuid(),
+ },
+ },
+ PropertyInput {
+ property_id: SystemPropertyKey::PRIORITY_UUID.to_string(),
+ value: SetPropertyValue::SelectOption {
+ option_id: task.priority.uuid(),
+ },
+ },
+ ]),
share_with_team: false,
team_id: None,
},
},
)
- .await;
- match created {
- Ok(_) => {
- created_now.insert(id.clone());
- }
- Err(DocumentError::Conflict(_)) => {}
- Err(e) => {
- tracing::error!(error=?e, task_name=%task.name, "failed to create starter task");
- return Err(internal_error("failed to create starter task"));
- }
- }
- }
-
- let created = state
- .documents_state
- .creator
- .create_markdown_text(
- user_id.clone(),
+ })
+ .collect();
+ let guide_uuid = starter_doc_id(user_id, HOW_TO_GUIDE_NAME);
+ if docs_tag.is_some() {
+ documents.push((
+ guide_uuid,
NewMarkdownTextDocument {
metadata: NewDocumentMetadata::builder(HOW_TO_GUIDE_NAME)
- .id(starter_doc_id(user_id, HOW_TO_GUIDE_NAME))
+ .id(guide_uuid)
.attribution(system_for_user.clone())
.build(),
markdown: fill(HOW_TO_GUIDE_TEMPLATE),
subtype: MarkdownSubtype::Note,
},
- )
- .await;
- match created {
- Ok(_) => {
- created_now.insert(guide_id.clone());
- }
- Err(DocumentError::Conflict(_)) => {}
- Err(e) => {
- tracing::error!(error=?e, "failed to create how to guide document");
- return Err(internal_error("failed to create how to guide document"));
- }
+ ));
}
+ let seeded = seed_starter_documents(
+ documents,
+ |document| async move {
+ state_ref
+ .documents_state
+ .creator
+ .create_markdown_text(user_id.clone(), document)
+ .await
+ .map(|_| ())
+ },
+ tag_document,
+ )
+ .await;
+ incomplete |= seeded.incomplete;
+ let guide_available = seeded.available.contains(&guide_uuid);
+ let created_now: std::collections::HashSet<_> = seeded
+ .created
+ .into_iter()
+ .map(|id| id.to_string())
+ .collect();
// Record mention backlinks (the References panel) for the starter set.
// The mention graph is derived from the templates themselves: a source
@@ -300,115 +375,41 @@ pub async fn handler(
});
}
- // Decorate the documents created by this call: each task's priority,
- // plus the personal "docs" tag. Best-effort like the mention backlinks
- // — a decoration failure on an existing document could never be retried
- // into success, so log and continue instead of failing the request.
- let docs_tag = if created_now.is_empty() {
- None
- } else {
- resolve_docs_tag(&state, user_id).await
- };
- let organization_id = user_context
- .authorization
- .user
- .user_context
- .organization_id
- .map(i64::from);
- let starter_docs = STARTER_TASKS
- .iter()
- .zip(&task_ids)
- .map(|(task, id)| (id.clone(), Some(task.priority)))
- .chain(std::iter::once((guide_id.clone(), None)))
- .filter(|(id, _)| created_now.contains(id));
- for (document_id, priority) in starter_docs {
- // One Edit receipt per doc covers both property writes; the
- // properties service takes its authorization as this typed receipt.
- let receipt = match state
- .entity_access_service
- .generate_bot_entity_access_receipt::<EditAccessLevel>(
- bot_id::MACRO_SYSTEM_BOT_ID,
- BotAccessScope::User {
- user_id: user_context.authorization.user.macro_user_id.clone(),
- user_org_id: organization_id,
- },
- &document_id,
- EntityType::Document,
- )
- .await
- {
- Ok(receipt) => receipt,
- Err(e) => {
- tracing::error!(
- error=?e,
- document_id=%document_id,
- "failed to authorize starter doc decoration"
- );
- continue;
- }
- };
-
- if let Some(priority) = priority {
- let _ = state
- .properties_service
- .set_entity_property(
- &receipt,
- SystemPropertyKey::PRIORITY_UUID,
- Some(SetPropertyValue::SelectOption {
- option_id: priority.uuid(),
- }),
+ // Runs on every call, not just document creation: `add_favorite` is an
+ // upsert, and re-favoriting reconciles a prior attempt that created the
+ // guide but failed before the favorite was written.
+ if guide_available {
+ let favorite_result = async {
+ let how_to_guide_receipt = state
+ .entity_access_service
+ .generate_entity_access_receipt::<ViewAccessLevel>(
+ user_id,
+ organization_id,
+ &guide_id,
+ EntityType::Document,
)
.await
- .inspect_err(|e| {
- tracing::error!(
- error=?e,
- document_id=%document_id,
- "failed to set starter task priority"
- );
- });
- }
+ .map_err(|e| {
+ tracing::error!(error=?e, "failed to authorize how to guide document favorite");
+ internal_error("failed to favorite how to guide document")
+ })?;
- if let Some((tag_definition_id, tag_option_id)) = docs_tag {
- let _ = state
- .properties_service
- .add_entity_property_option(&receipt, tag_definition_id, tag_option_id)
+ state
+ .favorites_service
+ .add_favorite(&how_to_guide_receipt)
.await
- .inspect_err(|e| {
- tracing::error!(
- error=?e,
- document_id=%document_id,
- "failed to tag starter doc"
- );
- });
+ .map_err(|e| {
+ tracing::error!(error=?e, "failed to favorite how to guide document");
+ internal_error("failed to favorite how to guide document")
+ })?;
+ Ok::<(), Response>(())
+ }
+ .await;
+ if favorite_result.is_err() {
+ incomplete = true;
}
}
- // Runs on every call, not just document creation: `add_favorite` is an
- // upsert, and re-favoriting reconciles a prior attempt that created the
- // guide but failed before the favorite was written.
- let how_to_guide_receipt = state
- .entity_access_service
- .generate_entity_access_receipt::<ViewAccessLevel>(
- user_id,
- organization_id,
- &guide_id,
- EntityType::Document,
- )
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "failed to authorize how to guide document favorite");
- internal_error("failed to favorite how to guide document")
- })?;
-
- state
- .favorites_service
- .add_favorite(&how_to_guide_receipt)
- .await
- .map_err(|e| {
- tracing::error!(error=?e, "failed to favorite how to guide document");
- internal_error("failed to favorite how to guide document")
- })?;
-
// Best-effort: a missed push just means the sidebar catches up on the
// next favorites refetch instead of live.
let _ = state
@@ -424,6 +425,12 @@ pub async fn handler(
tracing::warn!(error=?e, "failed to push starter docs initialized");
});
+ if incomplete {
+ return Err(internal_error(
+ "starter document initialization incomplete; retry required",
+ ));
+ }
+
Ok((
StatusCode::OK,
Json(InitializeStarterDocsResponse {
diff --git a/services/document_storage_service/src/api/documents/template/macro_how_to_guide.md b/services/document_storage_service/src/api/documents/template/macro_how_to_guide.md
index 96208f518b..4ae3d5f2b8 100644
--- a/services/document_storage_service/src/api/documents/template/macro_how_to_guide.md
+++ b/services/document_storage_service/src/api/documents/template/macro_how_to_guide.md
@@ -30,7 +30,7 @@ Sometimes mentioning has special powers. For example, if you mention a user in a
Other tools available wherever you are typing:
-1. `#` to add **tags,** e.g. docs
+1. `#` to add **tags,** e.g. <m-tag>{"optionId":"DOCS_TAG_OPTION_ID","propertyDefinitionId":"DOCS_TAG_DEFINITION_ID","scope":"user","name":"DOCS_TAG_LABEL","color":"DOCS_TAG_COLOR"}</m-tag>
2. `/` for text formatting and other tools (try typing `/task`)
3. `:` for emojis 🦋