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.

feat: ensure updated_at is always updated when you modify an entity (#5215)

Will Hutchinsonf60c993d36b6
diff --git a/.sqlx/query-0876e7623feb7c8f77b58716cbe3e43456fefad97ac0ba38daf2e5e6880bb51b.json b/.sqlx/query-0876e7623feb7c8f77b58716cbe3e43456fefad97ac0ba38daf2e5e6880bb51b.json
deleted file mode 100644
index 10cdcda76b..0000000000
--- a/.sqlx/query-0876e7623feb7c8f77b58716cbe3e43456fefad97ac0ba38daf2e5e6880bb51b.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "UPDATE \"Project\" SET \"parentId\"=$2 WHERE \"id\"=$1",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Text",
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "0876e7623feb7c8f77b58716cbe3e43456fefad97ac0ba38daf2e5e6880bb51b"
-}
diff --git a/.sqlx/query-679af359cf0fccd5b687fe58ece3b1052fe8c636b986fb6f59f67fcfd08fce38.json b/.sqlx/query-679af359cf0fccd5b687fe58ece3b1052fe8c636b986fb6f59f67fcfd08fce38.json
deleted file mode 100644
index 02e4d8a7ad..0000000000
--- a/.sqlx/query-679af359cf0fccd5b687fe58ece3b1052fe8c636b986fb6f59f67fcfd08fce38.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "UPDATE \"Chat\" SET \"projectId\"=$2 WHERE \"id\"=$1",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Text",
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "679af359cf0fccd5b687fe58ece3b1052fe8c636b986fb6f59f67fcfd08fce38"
-}
diff --git a/.sqlx/query-2c77b982d340967465a952f918b3ebd357faa0b3edc9a8bf325ffafe4b90d3ca.json b/.sqlx/query-87ea1f2739ad994c53e2694b4c1c82fcb58d02e4f94b909ddeb40d880320d889.json
similarity index 86%
rename from .sqlx/query-2c77b982d340967465a952f918b3ebd357faa0b3edc9a8bf325ffafe4b90d3ca.json
rename to .sqlx/query-87ea1f2739ad994c53e2694b4c1c82fcb58d02e4f94b909ddeb40d880320d889.json
index c9b636d8b7..4856e3b2a5 100644
--- a/.sqlx/query-2c77b982d340967465a952f918b3ebd357faa0b3edc9a8bf325ffafe4b90d3ca.json
+++ b/.sqlx/query-87ea1f2739ad994c53e2694b4c1c82fcb58d02e4f94b909ddeb40d880320d889.json
@@ -1,6 +1,6 @@
{
"db_name": "PostgreSQL",
- "query": "\n UPDATE comms_channels\n SET name = COALESCE($2, name),\n channel_type = CASE\n WHEN $3 IS TRUE THEN 'team'::comms_channel_type\n WHEN $3 IS FALSE AND channel_type = 'team'::comms_channel_type\n THEN 'private'::comms_channel_type\n ELSE channel_type\n END,\n team_id = CASE\n WHEN $3 IS TRUE THEN $4\n WHEN $3 IS FALSE AND channel_type = 'team'::comms_channel_type THEN NULL\n ELSE team_id\n END,\n auto_join_team = CASE\n WHEN $3 IS FALSE AND channel_type = 'team'::comms_channel_type THEN FALSE\n ELSE COALESCE($5, auto_join_team)\n END\n WHERE id = $1\n ",
+ "query": "\n UPDATE comms_channels\n SET name = COALESCE($2, name),\n channel_type = CASE\n WHEN $3 IS TRUE THEN 'team'::comms_channel_type\n WHEN $3 IS FALSE AND channel_type = 'team'::comms_channel_type\n THEN 'private'::comms_channel_type\n ELSE channel_type\n END,\n team_id = CASE\n WHEN $3 IS TRUE THEN $4\n WHEN $3 IS FALSE AND channel_type = 'team'::comms_channel_type THEN NULL\n ELSE team_id\n END,\n auto_join_team = CASE\n WHEN $3 IS FALSE AND channel_type = 'team'::comms_channel_type THEN FALSE\n ELSE COALESCE($5, auto_join_team)\n END,\n updated_at = NOW()\n WHERE id = $1\n ",
"describe": {
"columns": [],
"parameters": {
@@ -14,5 +14,5 @@
},
"nullable": []
},
- "hash": "2c77b982d340967465a952f918b3ebd357faa0b3edc9a8bf325ffafe4b90d3ca"
+ "hash": "87ea1f2739ad994c53e2694b4c1c82fcb58d02e4f94b909ddeb40d880320d889"
}
diff --git a/.sqlx/query-9bb89d78cff9b84ca91fa891dd3e61c04906fa841a9d21c29127d03797e98186.json b/.sqlx/query-9bb89d78cff9b84ca91fa891dd3e61c04906fa841a9d21c29127d03797e98186.json
deleted file mode 100644
index 50d679e8f6..0000000000
--- a/.sqlx/query-9bb89d78cff9b84ca91fa891dd3e61c04906fa841a9d21c29127d03797e98186.json
+++ /dev/null
@@ -1,15 +0,0 @@
-{
- "db_name": "PostgreSQL",
- "query": "UPDATE \"Document\" SET \"projectId\"=$2 WHERE \"id\"=$1",
- "describe": {
- "columns": [],
- "parameters": {
- "Left": [
- "Text",
- "Text"
- ]
- },
- "nullable": []
- },
- "hash": "9bb89d78cff9b84ca91fa891dd3e61c04906fa841a9d21c29127d03797e98186"
-}
diff --git a/crates/channels/src/domain/service.rs b/crates/channels/src/domain/service.rs
index 03d6f17b61..c0c5466af6 100644
--- a/crates/channels/src/domain/service.rs
+++ b/crates/channels/src/domain/service.rs
@@ -463,6 +463,13 @@ where
channel_id: Uuid,
mut req: PatchChannelRequest,
) -> Result<(), ChannelMutationErr> {
+ if req.channel_name.is_none()
+ && req.convert_to_team_channel.is_none()
+ && req.auto_join_team.is_none()
+ {
+ return Ok(());
+ }
+
let actor = require_user_actor(&actor)?;
let info = self
.repo
@@ -850,6 +857,13 @@ where
tracing::error!(error=?err, "unable to upsert activity for attachment patch");
}
+ if attachments_changed || content.is_some() {
+ self.repo
+ .touch_channel_updated_at(channel_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+ }
+
Ok(())
}
@@ -1002,11 +1016,20 @@ where
));
}
+ let mut membership_changed = false;
for participant in &req.participants {
- self.repo
+ let participant_changed = self
+ .repo
.add_participant(channel_id, participant.copied(), ParticipantRole::Member)
.await
.map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+ membership_changed |= participant_changed;
+ }
+ if membership_changed {
+ self.repo
+ .touch_channel_updated_at(channel_id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
}
let active_participants = self
@@ -1170,6 +1193,11 @@ where
return Ok(());
}
+ self.repo
+ .touch_channel_updated_at(info.id)
+ .await
+ .map_err(|e| ChannelMutationErr::Repo(e.into()))?;
+
active_participant_user_ids.push(actor_user.clone());
self.events.dispatch(ChannelEvent::ParticipantJoined {
channel_id: info.id,
diff --git a/crates/channels/src/domain/service/test.rs b/crates/channels/src/domain/service/test.rs
index f1a66fd24b..4328dbce67 100644
--- a/crates/channels/src/domain/service/test.rs
+++ b/crates/channels/src/domain/service/test.rs
@@ -298,6 +298,8 @@ struct FakeMutationRepoState {
attachments: Vec<MutatedAttachment>,
patched_content: Option<String>,
activity_upserts: usize,
+ touched_channel_ids: Vec<Uuid>,
+ fail_channel_touches: bool,
removed_participants: Vec<String>,
channel_patches: Vec<(PatchChannelRequest, Option<Uuid>)>,
created_mentions: Vec<SimpleMention>,
@@ -353,6 +355,8 @@ impl FakeMutationRepo {
attachments: vec![],
patched_content: None,
activity_upserts: 0,
+ touched_channel_ids: vec![],
+ fail_channel_touches: false,
removed_participants: vec![],
channel_patches: vec![],
created_mentions: vec![],
@@ -684,7 +688,12 @@ impl ChannelRepo for FakeMutationRepo {
Ok(state.message.clone())
}
- async fn touch_channel_updated_at(&self, _channel_id: Uuid) -> Result<(), Self::Err> {
+ async fn touch_channel_updated_at(&self, channel_id: Uuid) -> Result<(), Self::Err> {
+ let mut state = self.state.lock().unwrap();
+ state.touched_channel_ids.push(channel_id);
+ if state.fail_channel_touches {
+ anyhow::bail!("channel touch failed");
+ }
Ok(())
}
@@ -1037,6 +1046,44 @@ async fn post_message_emits_message_posted_event_and_updates_share_permissions()
"doc-1",
ReferencedShareItemType::Document
)));
+ assert_eq!(
+ repo.state.lock().unwrap().touched_channel_ids,
+ vec![channel_id]
+ );
+}
+
+#[tokio::test]
+async fn post_message_ignores_channel_touch_errors() {
+ let channel_id = Uuid::new_v4();
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ repo.state.lock().unwrap().fail_channel_touches = true;
+ let svc = mutation_service(
+ repo.clone(),
+ FakeEvents::default(),
+ FakeReferenceSharing::default(),
+ );
+
+ let result = svc
+ .post_message(
+ sender("macro|[email protected]"),
+ channel_id,
+ PostMessageRequest {
+ content: "hello world".to_string(),
+ mentions: vec![],
+ thread_id: None,
+ attachments: vec![],
+ nonce: None,
+ notification_policy: Default::default(),
+ triggered_by: None,
+ },
+ )
+ .await;
+
+ assert!(result.is_ok());
+ assert_eq!(
+ repo.state.lock().unwrap().touched_channel_ids,
+ vec![channel_id]
+ );
}
#[tokio::test]
@@ -1304,6 +1351,155 @@ async fn patch_message_content_emits_message_changed_event_to_thread_participant
assert_eq!(nonce.as_deref(), Some("edit-nonce"));
assert_eq!(recipients.len(), 1);
assert_eq!(recipients[0].as_ref(), "macro|[email protected]");
+ assert_eq!(
+ repo.state.lock().unwrap().touched_channel_ids,
+ vec![channel_id]
+ );
+}
+
+#[tokio::test]
+async fn patch_message_attachment_only_touches_channel_once() {
+ let channel_id = Uuid::new_v4();
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ let message_id = repo.state.lock().unwrap().message.id;
+ let svc = mutation_service(
+ repo.clone(),
+ FakeEvents::default(),
+ FakeReferenceSharing::default(),
+ );
+
+ svc.patch_message(
+ sender("macro|[email protected]"),
+ ParticipantRole::Member,
+ channel_id,
+ message_id,
+ PatchMessageRequest {
+ content: None,
+ mentions: None,
+ attachment_ids_to_delete: None,
+ attachments_to_add: Some(vec![NewChannelAttachment {
+ entity_type: "document".to_string(),
+ entity_id: "doc-1".to_string(),
+ width: None,
+ height: None,
+ }]),
+ nonce: None,
+ notification_policy: Default::default(),
+ },
+ )
+ .await
+ .unwrap();
+
+ let state = repo.state.lock().unwrap();
+ assert_eq!(state.touched_channel_ids, vec![channel_id]);
+ assert!(state.patched_content.is_none());
+}
+
+#[tokio::test]
+async fn patch_message_content_and_attachments_touch_channel_once() {
+ let channel_id = Uuid::new_v4();
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ let message_id = repo.state.lock().unwrap().message.id;
+ let svc = mutation_service(
+ repo.clone(),
+ FakeEvents::default(),
+ FakeReferenceSharing::default(),
+ );
+
+ svc.patch_message(
+ sender("macro|[email protected]"),
+ ParticipantRole::Member,
+ channel_id,
+ message_id,
+ PatchMessageRequest {
+ content: Some("edited".to_string()),
+ mentions: None,
+ attachment_ids_to_delete: None,
+ attachments_to_add: Some(vec![NewChannelAttachment {
+ entity_type: "document".to_string(),
+ entity_id: "doc-1".to_string(),
+ width: None,
+ height: None,
+ }]),
+ nonce: None,
+ notification_policy: Default::default(),
+ },
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ repo.state.lock().unwrap().touched_channel_ids,
+ vec![channel_id]
+ );
+}
+
+#[tokio::test]
+async fn patch_message_without_content_or_attachment_changes_does_not_touch_channel() {
+ let channel_id = Uuid::new_v4();
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ let message_id = repo.state.lock().unwrap().message.id;
+ let svc = mutation_service(
+ repo.clone(),
+ FakeEvents::default(),
+ FakeReferenceSharing::default(),
+ );
+
+ svc.patch_message(
+ sender("macro|[email protected]"),
+ ParticipantRole::Member,
+ channel_id,
+ message_id,
+ PatchMessageRequest {
+ content: None,
+ mentions: None,
+ attachment_ids_to_delete: None,
+ attachments_to_add: None,
+ nonce: None,
+ notification_policy: Default::default(),
+ },
+ )
+ .await
+ .unwrap();
+
+ assert!(repo.state.lock().unwrap().touched_channel_ids.is_empty());
+}
+
+#[tokio::test]
+async fn patch_message_propagates_channel_touch_errors() {
+ let channel_id = Uuid::new_v4();
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ let message_id = repo.state.lock().unwrap().message.id;
+ repo.state.lock().unwrap().fail_channel_touches = true;
+ let svc = mutation_service(
+ repo.clone(),
+ FakeEvents::default(),
+ FakeReferenceSharing::default(),
+ );
+
+ let error = svc
+ .patch_message(
+ sender("macro|[email protected]"),
+ ParticipantRole::Member,
+ channel_id,
+ message_id,
+ PatchMessageRequest {
+ content: Some("edited".to_string()),
+ mentions: None,
+ attachment_ids_to_delete: None,
+ attachments_to_add: None,
+ nonce: None,
+ notification_policy: Default::default(),
+ },
+ )
+ .await
+ .unwrap_err();
+
+ assert!(matches!(error, ChannelMutationErr::Repo(_)));
+ assert_eq!(
+ repo.state.lock().unwrap().touched_channel_ids,
+ vec![channel_id]
+ );
}
#[tokio::test]
@@ -1428,6 +1624,7 @@ async fn member_can_delete_bot_authored_message() {
let emitted = events.events.lock().unwrap();
assert_eq!(emitted.len(), 1);
assert!(matches!(&emitted[0], ChannelEvent::MessageDeleted { .. }));
+ assert!(repo.state.lock().unwrap().touched_channel_ids.is_empty());
}
#[tokio::test]
@@ -1868,6 +2065,91 @@ async fn thread_replies_resolve_and_hydrate() {
assert_eq!(replies[1].attachments.len(), 1);
}
+#[tokio::test]
+async fn add_participants_touches_channel_once_when_any_membership_changes() {
+ let channel_id = Uuid::new_v4();
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ let svc = mutation_service(
+ repo.clone(),
+ FakeEvents::default(),
+ FakeReferenceSharing::default(),
+ );
+
+ svc.add_participants(
+ sender("macro|[email protected]"),
+ channel_id,
+ AddParticipantsRequest {
+ participants: HashSet::from([
+ macro_id("macro|[email protected]"),
+ macro_id("macro|[email protected]"),
+ ]),
+ },
+ )
+ .await
+ .unwrap();
+
+ let state = repo.state.lock().unwrap();
+ assert_eq!(state.participant_additions, 1);
+ assert_eq!(state.touched_channel_ids, vec![channel_id]);
+}
+
+#[tokio::test]
+async fn add_participants_does_not_touch_channel_when_memberships_are_already_active() {
+ let channel_id = Uuid::new_v4();
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ let svc = mutation_service(
+ repo.clone(),
+ FakeEvents::default(),
+ FakeReferenceSharing::default(),
+ );
+
+ svc.add_participants(
+ sender("macro|[email protected]"),
+ channel_id,
+ AddParticipantsRequest {
+ participants: HashSet::from([
+ macro_id("macro|[email protected]"),
+ macro_id("macro|[email protected]"),
+ ]),
+ },
+ )
+ .await
+ .unwrap();
+
+ let state = repo.state.lock().unwrap();
+ assert_eq!(state.participant_additions, 0);
+ assert!(state.touched_channel_ids.is_empty());
+}
+
+#[tokio::test]
+async fn add_participants_propagates_channel_touch_errors() {
+ let channel_id = Uuid::new_v4();
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ repo.state.lock().unwrap().fail_channel_touches = true;
+ let svc = mutation_service(
+ repo.clone(),
+ FakeEvents::default(),
+ FakeReferenceSharing::default(),
+ );
+
+ let error = svc
+ .add_participants(
+ sender("macro|[email protected]"),
+ channel_id,
+ AddParticipantsRequest {
+ participants: HashSet::from([macro_id("macro|[email protected]")]),
+ },
+ )
+ .await
+ .unwrap_err();
+
+ assert!(matches!(error, ChannelMutationErr::Repo(_)));
+ assert_eq!(
+ repo.state.lock().unwrap().touched_channel_ids,
+ vec![channel_id]
+ );
+}
+
#[tokio::test]
async fn remove_participants_rejects_removing_channel_owner() {
let channel_id = Uuid::new_v4();
@@ -1916,10 +2198,12 @@ async fn remove_participants_allows_removing_non_owner() {
.await
.unwrap();
+ let state = repo.state.lock().unwrap();
assert_eq!(
- repo.state.lock().unwrap().removed_participants,
+ state.removed_participants,
vec!["macro|[email protected]".to_string()]
);
+ assert!(state.touched_channel_ids.is_empty());
}
#[tokio::test]
@@ -2047,6 +2331,23 @@ async fn create_channel_rejects_auto_join_for_non_team_channel() {
assert!(matches!(err, ChannelMutationErr::BadRequest(_)));
}
+#[tokio::test]
+async fn auto_join_by_team_id_does_not_touch_channel_recency() {
+ let channel_id = Uuid::new_v4();
+ let team_id = Uuid::new_v4();
+ let user_id = macro_id("macro|[email protected]");
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ let svc = mutation_service(
+ repo.clone(),
+ FakeEvents::default(),
+ FakeReferenceSharing::default(),
+ );
+
+ svc.auto_join_by_team_id(&team_id, &user_id).await.unwrap();
+
+ assert!(repo.state.lock().unwrap().touched_channel_ids.is_empty());
+}
+
#[tokio::test]
async fn team_membership_operations_delegate_to_repo() {
let team_id = Uuid::new_v4();
@@ -2162,7 +2463,11 @@ async fn noop_patch_channel_dispatches_nothing() {
let channel_id = Uuid::new_v4();
let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
let events = FakeEvents::default();
- let svc = mutation_service(repo, events.clone(), FakeReferenceSharing::default());
+ let svc = mutation_service(
+ repo.clone(),
+ events.clone(),
+ FakeReferenceSharing::default(),
+ );
svc.patch_channel(
sender("macro|[email protected]"),
@@ -2177,6 +2482,9 @@ async fn noop_patch_channel_dispatches_nothing() {
.unwrap();
assert!(events.events.lock().unwrap().is_empty());
+ let state = repo.state.lock().unwrap();
+ assert!(state.channel_patches.is_empty());
+ assert!(state.touched_channel_ids.is_empty());
}
#[tokio::test]
@@ -2515,6 +2823,57 @@ async fn patch_message_attachments_event_carries_deltas() {
}
}
+#[tokio::test]
+async fn join_channel_touches_channel_when_membership_changes() {
+ let channel_id = Uuid::new_v4();
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ let events = FakeEvents::default();
+ let svc = mutation_service(
+ repo.clone(),
+ events.clone(),
+ FakeReferenceSharing::default(),
+ );
+
+ svc.join_channel(sender("macro|[email protected]"), channel_id)
+ .await
+ .unwrap();
+
+ assert_eq!(
+ repo.state.lock().unwrap().touched_channel_ids,
+ vec![channel_id]
+ );
+ assert!(matches!(
+ events.events.lock().unwrap().as_slice(),
+ [ChannelEvent::ParticipantJoined { channel_id: event_channel_id, .. }]
+ if event_channel_id == &channel_id
+ ));
+}
+
+#[tokio::test]
+async fn join_channel_propagates_channel_touch_errors() {
+ let channel_id = Uuid::new_v4();
+ let repo = FakeMutationRepo::new(channel_id, "macro|[email protected]");
+ repo.state.lock().unwrap().fail_channel_touches = true;
+ let events = FakeEvents::default();
+ let svc = mutation_service(
+ repo.clone(),
+ events.clone(),
+ FakeReferenceSharing::default(),
+ );
+
+ let error = svc
+ .join_channel(sender("macro|[email protected]"), channel_id)
+ .await
+ .unwrap_err();
+
+ assert!(matches!(error, ChannelMutationErr::Repo(_)));
+ assert_eq!(
+ repo.state.lock().unwrap().touched_channel_ids,
+ vec![channel_id]
+ );
+ assert!(events.events.lock().unwrap().is_empty());
+}
+
#[tokio::test]
async fn private_channel_join_code_is_reused() {
let channel_id = Uuid::new_v4();
@@ -2603,6 +2962,7 @@ async fn join_by_code_adds_participant_and_dispatches_event() {
let state = repo.state.lock().unwrap();
assert_eq!(state.participant_additions, 1);
+ assert_eq!(state.touched_channel_ids, vec![channel_id]);
assert!(
state
.participants
@@ -2634,6 +2994,8 @@ async fn join_by_code_is_idempotent_for_active_participant() {
.await
.unwrap();
- assert_eq!(repo.state.lock().unwrap().participant_additions, 0);
+ let state = repo.state.lock().unwrap();
+ assert_eq!(state.participant_additions, 0);
+ assert!(state.touched_channel_ids.is_empty());
assert!(events.events.lock().unwrap().is_empty());
}
diff --git a/crates/channels/src/outbound/pg_channels_repo.rs b/crates/channels/src/outbound/pg_channels_repo.rs
index bfe27bfcfe..478ebd5d50 100644
--- a/crates/channels/src/outbound/pg_channels_repo.rs
+++ b/crates/channels/src/outbound/pg_channels_repo.rs
@@ -3071,7 +3071,8 @@ impl ChannelRepo for PgChannelsRepo {
auto_join_team = CASE
WHEN $3 IS FALSE AND channel_type = 'team'::comms_channel_type THEN FALSE
ELSE COALESCE($5, auto_join_team)
- END
+ END,
+ updated_at = NOW()
WHERE id = $1
"#,
channel_id,
diff --git a/crates/channels/src/outbound/pg_channels_repo/tests.rs b/crates/channels/src/outbound/pg_channels_repo/tests.rs
index f86d648b1d..c10d0374f9 100644
--- a/crates/channels/src/outbound/pg_channels_repo/tests.rs
+++ b/crates/channels/src/outbound/pg_channels_repo/tests.rs
@@ -334,6 +334,45 @@ async fn create_channel_persists_auto_join_team_and_adds_current_members(pool: P
);
}
+#[sqlx::test(
+ fixtures(path = "../../../fixtures", scripts("channels_repo")),
+ migrator = "MACRO_DB_MIGRATIONS"
+)]
+async fn patch_channel_rename_advances_updated_at(pool: Pool<Postgres>) {
+ let repo = repo(pool.clone());
+ let before = sqlx::query!(
+ "SELECT name, updated_at FROM comms_channels WHERE id = $1",
+ CH1,
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+
+ repo.patch_channel(
+ CH1,
+ USER_A.to_string(),
+ None,
+ PatchChannelRequest {
+ channel_name: Some("renamed-channel".to_string()),
+ convert_to_team_channel: None,
+ auto_join_team: None,
+ },
+ )
+ .await
+ .unwrap();
+
+ let after = sqlx::query!(
+ "SELECT name, updated_at FROM comms_channels WHERE id = $1",
+ CH1,
+ )
+ .fetch_one(&pool)
+ .await
+ .unwrap();
+
+ assert_eq!(after.name.as_deref(), Some("renamed-channel"));
+ assert!(after.updated_at > before.updated_at);
+}
+
#[sqlx::test(
fixtures(path = "../../../fixtures", scripts("channels_repo")),
migrator = "MACRO_DB_MIGRATIONS"
diff --git a/crates/chat/src/domain/ports/chat.rs b/crates/chat/src/domain/ports/chat.rs
index c6bfdbc67d..0a9a464952 100644
--- a/crates/chat/src/domain/ports/chat.rs
+++ b/crates/chat/src/domain/ports/chat.rs
@@ -97,7 +97,7 @@ pub trait ChatRepo: Send + Sync + 'static {
message_id: &str,
) -> impl std::future::Future<Output = Result<ChatMessageContent>> + Send;
- /// Update the content of a specific message.
+ /// Update a specific message's final content and chat recency.
fn update_message_content(
&self,
chat_id: &str,
@@ -105,6 +105,14 @@ pub trait ChatRepo: Send + Sync + 'static {
content: &ChatMessageContent,
) -> impl std::future::Future<Output = Result<()>> + Send;
+ /// Persist interim message content without updating chat recency.
+ fn update_interim_message_content(
+ &self,
+ chat_id: &str,
+ message_id: &str,
+ content: &ChatMessageContent,
+ ) -> impl std::future::Future<Output = Result<()>> + Send;
+
/// Store the resolved (AI-facing) representation of a user message.
fn store_resolved_message(
&self,
diff --git a/crates/chat/src/domain/service/chat.rs b/crates/chat/src/domain/service/chat.rs
index 868b9613a4..be2348340f 100644
--- a/crates/chat/src/domain/service/chat.rs
+++ b/crates/chat/src/domain/service/chat.rs
@@ -448,7 +448,7 @@ where
let content = ChatMessageContent::AssistantMessageParts(parts);
self.repo
- .update_message_content(chat_id, message_id, &content)
+ .update_interim_message_content(chat_id, message_id, &content)
.await
}
diff --git a/crates/chat/src/domain/service/chat/test.rs b/crates/chat/src/domain/service/chat/test.rs
index 423d791db1..7224394528 100644
--- a/crates/chat/src/domain/service/chat/test.rs
+++ b/crates/chat/src/domain/service/chat/test.rs
@@ -1,6 +1,7 @@
use std::sync::Mutex;
-use agent::types::ChatMessageContent;
+use agent::types::{AssistantMessagePart, ChatMessageContent};
+use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolResult};
use attachment::FormattedParts;
use entity_access_management::domain::models::EntityAccessManagementError;
use macro_event_broker::{EventBrokerError, MacroEvent};
@@ -13,12 +14,28 @@ const CHAT_ID: &str = "3f6f8b0a-6f9f-4a3f-9c3a-2b1e5d4c7a90";
const NEW_CHAT_ID: &str = "0197f776-6e7b-7c69-a251-780ae754d3e4";
const PROJECT_ID: &str = "c1a2b3d4-e5f6-4a7b-8c9d-0e1f2a3b4c5d";
const OWNER: &str = "macro|[email protected]";
+const MESSAGE_ID: &str = "message-id";
+const TOOL_CALL_ID: &str = "tool-call-id";
+const TOOL_NAME: &str = "test_tool";
// -- Stub ChatRepo --
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+enum MessageContentUpdate {
+ Final,
+ Interim,
+}
+
+#[derive(Default)]
+struct MessagePersistence {
+ content: Option<ChatMessageContent>,
+ updates: Vec<MessageContentUpdate>,
+}
+
#[derive(Clone, Default)]
struct StubChatRepo {
metadata_project_id: Option<String>,
+ message_persistence: Arc<Mutex<MessagePersistence>>,
fail_create: bool,
fail_copy_chat: bool,
fail_delete: bool,
@@ -35,6 +52,26 @@ impl StubChatRepo {
}
}
+ fn with_tool_message() -> Self {
+ Self {
+ message_persistence: Arc::new(Mutex::new(MessagePersistence {
+ content: Some(tool_message_content()),
+ updates: Vec::new(),
+ })),
+ ..Self::default()
+ }
+ }
+
+ fn content_updates(&self) -> Vec<MessageContentUpdate> {
+ self.message_persistence.lock().unwrap().updates.clone()
+ }
+
+ fn record_content_update(&self, content: &ChatMessageContent, update: MessageContentUpdate) {
+ let mut persistence = self.message_persistence.lock().unwrap();
+ persistence.content = Some(content.clone());
+ persistence.updates.push(update);
+ }
+
fn repo_err() -> ChatErr {
ChatErr::Unknown(anyhow::anyhow!("intentional repo failure"))
}
@@ -141,16 +178,32 @@ impl ChatRepo for StubChatRepo {
_chat_id: &str,
_message_id: &str,
) -> Result<ChatMessageContent> {
- unimplemented!("not exercised")
+ self.message_persistence
+ .lock()
+ .unwrap()
+ .content
+ .clone()
+ .ok_or(ChatErr::NotFound)
}
async fn update_message_content(
&self,
_chat_id: &str,
_message_id: &str,
- _content: &ChatMessageContent,
+ content: &ChatMessageContent,
) -> Result<()> {
- unimplemented!("not exercised")
+ self.record_content_update(content, MessageContentUpdate::Final);
+ Ok(())
+ }
+
+ async fn update_interim_message_content(
+ &self,
+ _chat_id: &str,
+ _message_id: &str,
+ content: &ChatMessageContent,
+ ) -> Result<()> {
+ self.record_content_update(content, MessageContentUpdate::Interim);
+ Ok(())
}
async fn store_resolved_message(
@@ -252,8 +305,45 @@ impl MacroEventBroker for RecordingEventBroker {
}
}
+// -- Test tool --
+
+#[derive(serde::Deserialize, schemars::JsonSchema)]
+#[schemars(title = "test_tool", description = "A tool used by chat service tests")]
+struct TestTool {
+ value: String,
+}
+
+#[async_trait::async_trait]
+impl AsyncTool<()> for TestTool {
+ type Output = serde_json::Value;
+
+ async fn call(
+ &self,
+ _service_context: ServiceContext<()>,
+ _request_context: RequestContext,
+ ) -> ToolResult<Self::Output> {
+ Ok(serde_json::json!({ "value": self.value }))
+ }
+}
+
// -- Helpers --
+fn tool_message_content() -> ChatMessageContent {
+ ChatMessageContent::AssistantMessageParts(vec![
+ AssistantMessagePart::ToolCall {
+ name: TOOL_NAME.to_string(),
+ json: serde_json::json!({ "value": "initial" }),
+ id: TOOL_CALL_ID.to_string(),
+ },
+ AssistantMessagePart::ToolCallResponseJson {
+ name: TOOL_NAME.to_string(),
+ json: serde_json::to_value(UserToolResponse::<serde_json::Value>::PendingUserExecution)
+ .unwrap(),
+ id: TOOL_CALL_ID.to_string(),
+ },
+ ])
+}
+
fn owner() -> MacroUserIdStr<'static> {
MacroUserIdStr::try_from(OWNER.to_string()).expect("valid user id")
}
@@ -279,6 +369,17 @@ fn build_service<B: MacroEventBroker>(
.with_event_broker(event_broker)
}
+fn build_service_with_tools(
+ repo: StubChatRepo,
+) -> ChatServiceImpl<StubChatRepo, (), StubEntityAccessManagement> {
+ ChatServiceImpl::new(
+ repo,
+ Arc::new(AsyncToolCollection::new().add_user_tool::<TestTool, ()>()),
+ (),
+ StubEntityAccessManagement,
+ )
+}
+
fn patch_args(share_permission_updated: bool) -> PatchChatArgs {
let share_permission = share_permission_updated.then_some(
models_permissions::share_permission::UpdateSharePermissionRequestV2 {
@@ -297,6 +398,76 @@ fn patch_args(share_permission_updated: bool) -> PatchChatArgs {
// -- Tests --
+#[tokio::test]
+async fn update_tool_call_uses_interim_content_persistence() {
+ let repo = StubChatRepo::with_tool_message();
+ let service = build_service_with_tools(repo.clone());
+
+ service
+ .update_tool_call(
+ owner_receipt(CHAT_ID),
+ MESSAGE_ID,
+ TOOL_CALL_ID,
+ serde_json::json!({ "value": "updated" }),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(repo.content_updates(), vec![MessageContentUpdate::Interim]);
+}
+
+#[tokio::test]
+async fn update_tool_response_uses_final_content_persistence() {
+ let repo = StubChatRepo::with_tool_message();
+ let service = build_service(repo.clone(), RecordingEventBroker::default());
+
+ service
+ .update_tool_response(
+ owner_receipt(CHAT_ID),
+ MESSAGE_ID,
+ TOOL_CALL_ID,
+ UserToolResponse::UserAction(serde_json::json!({ "result": "done" })),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(repo.content_updates(), vec![MessageContentUpdate::Final]);
+}
+
+#[tokio::test]
+async fn call_tool_uses_interim_persistence_for_args_and_final_persistence_for_response() {
+ let repo = StubChatRepo::with_tool_message();
+ let service = build_service_with_tools(repo.clone());
+
+ service
+ .call_tool(
+ owner_receipt(CHAT_ID),
+ MESSAGE_ID,
+ TOOL_CALL_ID,
+ Some(serde_json::json!({ "value": "updated" })),
+ )
+ .await
+ .unwrap();
+
+ assert_eq!(
+ repo.content_updates(),
+ vec![MessageContentUpdate::Interim, MessageContentUpdate::Final]
+ );
+}
+
+#[tokio::test]
+async fn reject_tool_call_uses_final_content_persistence() {
+ let repo = StubChatRepo::with_tool_message();
+ let service = build_service(repo.clone(), RecordingEventBroker::default());
+
+ service
+ .reject_tool_call(owner_receipt(CHAT_ID), MESSAGE_ID, TOOL_CALL_ID)
+ .await
+ .unwrap();
+
+ assert_eq!(repo.content_updates(), vec![MessageContentUpdate::Final]);
+}
+
#[tokio::test]
async fn create_publishes_chat_created() {
let broker = RecordingEventBroker::default();
diff --git a/crates/chat/src/outbound/postgres/mod.rs b/crates/chat/src/outbound/postgres/mod.rs
index 8e7fa6d4d9..f260912169 100644
--- a/crates/chat/src/outbound/postgres/mod.rs
+++ b/crates/chat/src/outbound/postgres/mod.rs
@@ -46,6 +46,24 @@ impl PgChatRepo {
queries::get_messages::get_messages(&self.pool, chat_id).await
}
+ async fn persist_message_content(
+ &self,
+ chat_id: &str,
+ message_id: &str,
+ content: &ChatMessageContent,
+ bump_chat_recency: bool,
+ ) -> Result<()> {
+ queries::update_message_content::update_message_content(
+ &self.pool,
+ chat_id,
+ message_id,
+ content,
+ bump_chat_recency,
+ )
+ .await
+ .map_err(to_chat_err)
+ }
+
/// Store a resolved message without going through the trait.
pub async fn store_resolved_message_static(
&self,
@@ -306,14 +324,8 @@ impl ChatRepo for PgChatRepo {
#[tracing::instrument(err, skip(self))]
async fn patch_message(&self, chat_id: &str, args: PatchChatMessageArgs) -> Result<()> {
- queries::update_message_content::update_message_content(
- &self.pool,
- chat_id,
- &args.message_id,
- &args.content,
- )
- .await
- .map_err(to_chat_err)
+ self.persist_message_content(chat_id, &args.message_id, &args.content, true)
+ .await
}
#[tracing::instrument(err, skip(self))]
@@ -334,11 +346,19 @@ impl ChatRepo for PgChatRepo {
message_id: &str,
content: &ChatMessageContent,
) -> Result<()> {
- queries::update_message_content::update_message_content(
- &self.pool, chat_id, message_id, content,
- )
- .await
- .map_err(to_chat_err)
+ self.persist_message_content(chat_id, message_id, content, true)
+ .await
+ }
+
+ #[tracing::instrument(err, skip(self, content))]
+ async fn update_interim_message_content(
+ &self,
+ chat_id: &str,
+ message_id: &str,
+ content: &ChatMessageContent,
+ ) -> Result<()> {
+ self.persist_message_content(chat_id, message_id, content, false)
+ .await
}
#[tracing::instrument(err, skip(self, parts))]
@@ -396,23 +416,14 @@ impl MessageRepo for PgChatRepo {
message_id: &str,
content: &ChatMessageContent,
) -> Result<()> {
- queries::update_message_content::update_message_content(
- &self.pool, chat_id, message_id, content,
- )
- .await
- .map_err(to_chat_err)
+ self.persist_message_content(chat_id, message_id, content, true)
+ .await
}
#[tracing::instrument(err, skip(self))]
async fn patch_message(&self, chat_id: &str, args: PatchChatMessageArgs) -> Result<()> {
- queries::update_message_content::update_message_content(
- &self.pool,
- chat_id,
- &args.message_id,
- &args.content,
- )
- .await
- .map_err(to_chat_err)
+ self.persist_message_content(chat_id, &args.message_id, &args.content, true)
+ .await
}
#[tracing::instrument(err, skip(self))]
diff --git a/crates/chat/src/outbound/postgres/queries/create_message.rs b/crates/chat/src/outbound/postgres/queries/create_message.rs
index 9f6f412e26..6bcab49543 100644
--- a/crates/chat/src/outbound/postgres/queries/create_message.rs
+++ b/crates/chat/src/outbound/postgres/queries/create_message.rs
@@ -17,7 +17,9 @@ fn attachment_type_to_entity_type(at: &AttachmentType) -> EntityType {
/// Insert a message into a chat, returning the message ID.
///
-/// User messages also insert their attachments in the same transaction.
+/// User messages also insert their attachments in the same transaction. Both
+/// `MessageService::create` and `MessageService::store` use this path through
+/// `MessageRepo::create`.
#[tracing::instrument(err, skip(pool, message))]
pub(crate) async fn create_message(
pool: &PgPool,
@@ -79,6 +81,8 @@ pub(crate) async fn create_message(
}
}
+ super::patch_chat::patch_chat(&mut tx, chat_id, None, None).await?;
+
tx.commit().await?;
Ok(message_id)
}
diff --git a/crates/chat/src/outbound/postgres/queries/update_message_content.rs b/crates/chat/src/outbound/postgres/queries/update_message_content.rs
index 5c7ba63d00..6dd4627edc 100644
--- a/crates/chat/src/outbound/postgres/queries/update_message_content.rs
+++ b/crates/chat/src/outbound/postgres/queries/update_message_content.rs
@@ -3,17 +3,19 @@
use agent::types::ChatMessageContent;
use sqlx::PgPool;
-/// Update the content of a specific message, scoped to the chat.
+/// Update a message and optionally bump its chat when the message exists.
#[tracing::instrument(err, skip(pool, content))]
pub(crate) async fn update_message_content(
pool: &PgPool,
chat_id: &str,
message_id: &str,
content: &ChatMessageContent,
+ bump_chat_recency: bool,
) -> anyhow::Result<()> {
let content_json = serde_json::to_value(content)?;
+ let mut tx = pool.begin().await?;
- sqlx::query!(
+ let result = sqlx::query!(
r#"
UPDATE "ChatMessage"
SET "content" = $1, "updatedAt" = NOW()
@@ -23,8 +25,13 @@ pub(crate) async fn update_message_content(
message_id,
chat_id
)
- .execute(pool)
+ .execute(tx.as_mut())
.await?;
+ if bump_chat_recency && result.rows_affected() > 0 {
+ super::patch_chat::patch_chat(&mut tx, chat_id, None, None).await?;
+ }
+
+ tx.commit().await?;
Ok(())
}
diff --git a/crates/chat/src/outbound/postgres/test.rs b/crates/chat/src/outbound/postgres/test.rs
index f498e9064d..0568560703 100644
--- a/crates/chat/src/outbound/postgres/test.rs
+++ b/crates/chat/src/outbound/postgres/test.rs
@@ -1,12 +1,51 @@
+use std::time::Duration;
+
+use agent::types::{ChatMessageContent, Role};
+use chrono::Utc;
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 sqlx::{Pool, Postgres, Row};
use super::PgChatRepo;
use crate::domain::models::{ChatErr, CopyChatArgs, CreateChatArgs, PatchChatArgs};
use crate::domain::ports::ChatRepo;
+async fn create_chat_with_message(repo: &PgChatRepo) -> (String, String) {
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned();
+ let chat_id = repo
+ .create(
+ user_id,
+ CreateChatArgs {
+ name: "Message update test".to_string(),
+ project_id: None,
+ },
+ )
+ .await
+ .unwrap();
+ let now = Utc::now();
+ let message_id = crate::domain::ports::MessageRepo::create(
+ repo,
+ &chat_id,
+ NewChatMessage {
+ id: None,
+ content: ChatMessageContent::Text("initial content".to_string()),
+ role: Role::User,
+ attachments: None,
+ model: "test-model".to_string(),
+ created_at: now,
+ updated_at: now,
+ },
+ )
+ .await
+ .unwrap();
+
+ (chat_id, message_id)
+}
+
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "fixtures", scripts("users"))
@@ -41,6 +80,156 @@ async fn create_chat_returns_id(pool: Pool<Postgres>) {
assert_eq!(row.get::<String, _>("userId"), "macro|[email protected]");
}
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "fixtures", scripts("users"))
+)]
+async fn create_message_bumps_chat_updated_at(pool: Pool<Postgres>) {
+ let repo = PgChatRepo::new(pool);
+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")
+ .unwrap()
+ .into_owned();
+
+ let chat_id = repo
+ .create(
+ user_id,
+ CreateChatArgs {
+ name: "Active Chat".to_string(),
+ project_id: None,
+ },
+ )
+ .await
+ .unwrap();
+ let original_updated_at = repo
+ .get_metadata(&chat_id)
+ .await
+ .unwrap()
+ .updated_at
+ .unwrap();
+
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ let now = Utc::now();
+ crate::domain::ports::MessageRepo::create(
+ &repo,
+ &chat_id,
+ NewChatMessage {
+ id: None,
+ content: ChatMessageContent::Text("hello".to_string()),
+ role: Role::User,
+ attachments: None,
+ model: "test-model".to_string(),
+ created_at: now,
+ updated_at: now,
+ },
+ )
+ .await
+ .unwrap();
+
+ let updated_at = repo
+ .get_metadata(&chat_id)
+ .await
+ .unwrap()
+ .updated_at
+ .unwrap();
+ assert!(updated_at > original_updated_at);
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "fixtures", scripts("users"))
+)]
+async fn update_message_content_bumps_chat_updated_at(pool: Pool<Postgres>) {
+ let repo = PgChatRepo::new(pool);
+ let (chat_id, message_id) = create_chat_with_message(&repo).await;
+ let original_updated_at = repo
+ .get_metadata(&chat_id)
+ .await
+ .unwrap()
+ .updated_at
+ .unwrap();
+
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ repo.update_message_content(
+ &chat_id,
+ &message_id,
+ &ChatMessageContent::Text("final content".to_string()),
+ )
+ .await
+ .unwrap();
+
+ let updated_at = repo
+ .get_metadata(&chat_id)
+ .await
+ .unwrap()
+ .updated_at
+ .unwrap();
+ assert!(updated_at > original_updated_at);
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "fixtures", scripts("users"))
+)]
+async fn update_interim_message_content_does_not_bump_chat(pool: Pool<Postgres>) {
+ let repo = PgChatRepo::new(pool);
+ let (chat_id, message_id) = create_chat_with_message(&repo).await;
+ let original_updated_at = repo
+ .get_metadata(&chat_id)
+ .await
+ .unwrap()
+ .updated_at
+ .unwrap();
+
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ repo.update_interim_message_content(
+ &chat_id,
+ &message_id,
+ &ChatMessageContent::Text("interim content".to_string()),
+ )
+ .await
+ .unwrap();
+
+ let updated_at = repo
+ .get_metadata(&chat_id)
+ .await
+ .unwrap()
+ .updated_at
+ .unwrap();
+ assert_eq!(updated_at, original_updated_at);
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "fixtures", scripts("users"))
+)]
+async fn nonexistent_message_does_not_bump_chat(pool: Pool<Postgres>) {
+ let repo = PgChatRepo::new(pool);
+ let (chat_id, _) = create_chat_with_message(&repo).await;
+ let original_updated_at = repo
+ .get_metadata(&chat_id)
+ .await
+ .unwrap()
+ .updated_at
+ .unwrap();
+
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ repo.update_message_content(
+ &chat_id,
+ "nonexistent-message",
+ &ChatMessageContent::Text("final content".to_string()),
+ )
+ .await
+ .unwrap();
+
+ let updated_at = repo
+ .get_metadata(&chat_id)
+ .await
+ .unwrap()
+ .updated_at
+ .unwrap();
+ assert_eq!(updated_at, original_updated_at);
+}
+
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "fixtures", scripts("users"))
diff --git a/crates/documents/src/domain/ports/mod.rs b/crates/documents/src/domain/ports/mod.rs
index fd024e76c4..1ef214706a 100644
--- a/crates/documents/src/domain/ports/mod.rs
+++ b/crates/documents/src/domain/ports/mod.rs
@@ -151,6 +151,12 @@ pub trait DocumentRepo: Send + Sync + 'static {
args: EditDocumentRepoArgs,
) -> impl Future<Output = Result<(), Self::Err>> + Send;
+ /// Update a document's `updatedAt` timestamp.
+ fn update_document_modified(
+ &self,
+ document_id: &str,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
/// Update a project's `updatedAt` timestamp.
fn update_project_modified(
&self,
diff --git a/crates/documents/src/domain/service.rs b/crates/documents/src/domain/service.rs
index 97482c0f31..531a2600c3 100644
--- a/crates/documents/src/domain/service.rs
+++ b/crates/documents/src/domain/service.rs
@@ -1544,6 +1544,12 @@ impl<
return Err(DocumentError::Internal(e.into()));
}
+ if let Some(project_id) = &new_metadata.project_id {
+ let _ = self.repo.update_project_modified(project_id).await.inspect_err(
+ |e| tracing::error!(error=?e, project_id=?project_id, "unable to update project modified date"),
+ );
+ }
+
let document_response_metadata =
DocumentResponseMetadata::from_document_metadata(&new_metadata).map_err(|e| {
tracing::error!(error=?e, "unable to convert document metadata");
@@ -1622,6 +1628,13 @@ impl<
document_id: &str,
reason: InteractionReason,
) -> anyhow::Result<()> {
+ if reason == InteractionReason::Edited {
+ self.repo
+ .update_document_modified(document_id)
+ .await
+ .map_err(Into::into)?;
+ }
+
self.publish_document_event(&DocumentMacroEvent::interaction(
document_id,
DocumentInteractionMetadata {
diff --git a/crates/documents/src/domain/service/tests.rs b/crates/documents/src/domain/service/tests.rs
index 2b4f3a3cba..ad7cfaac59 100644
--- a/crates/documents/src/domain/service/tests.rs
+++ b/crates/documents/src/domain/service/tests.rs
@@ -1777,7 +1777,7 @@ async fn test_edit_document_project_change_moves_project_access() {
}
#[tokio::test]
-async fn test_copy_document_publishes_document_copied_event() {
+async fn copy_document_best_effort_bumps_inherited_project_and_publishes_event() {
let mut repo = make_mock_repo();
let original_metadata = make_test_metadata();
let original_for_lookup = original_metadata.clone();
@@ -1804,6 +1804,10 @@ async fn test_copy_document_publishes_document_copied_event() {
.returning(|_| Box::pin(std::future::ready(Ok((1, true)))));
repo.expect_set_document_content()
.returning(|_, _| Box::pin(std::future::ready(Ok(()))));
+ repo.expect_update_project_modified()
+ .withf(|project_id| project_id == "project-1")
+ .times(1)
+ .returning(|_| Box::pin(std::future::ready(Err(anyhow!("db is down")))));
repo.expect_get_team_task_metadata()
.returning(|_| Box::pin(std::future::ready(Ok(None))));
@@ -1839,3 +1843,67 @@ async fn test_copy_document_publishes_document_copied_event() {
assert_eq!(event.payload["metadata"]["document_name"], "copied doc");
assert_eq!(event.payload["metadata"]["owner"], "macro|[email protected]");
}
+
+#[tokio::test]
+async fn edited_interaction_bumps_document_before_publishing() {
+ let mut repo = make_mock_repo();
+ repo.expect_update_document_modified()
+ .withf(|document_id| document_id == "doc-1")
+ .times(1)
+ .returning(|_| Box::pin(std::future::ready(Ok(()))));
+
+ let (service, event_broker) = make_test_service_with_event_broker(repo);
+
+ service
+ .record_interaction("doc-1", InteractionReason::Edited)
+ .await
+ .unwrap();
+
+ let published = event_broker.published();
+ let published = published.lock().unwrap();
+ assert_eq!(published.len(), 1);
+ assert_eq!(published[0].topic, "macro.documents");
+ assert_eq!(published[0].key, "doc-1");
+ assert_eq!(published[0].payload["event_type"], "document.interaction");
+ assert_eq!(published[0].payload["metadata"]["document_id"], "doc-1");
+ assert_eq!(published[0].payload["metadata"]["reason"], "edited");
+}
+
+#[tokio::test]
+async fn edited_interaction_does_not_publish_when_document_bump_fails() {
+ let mut repo = make_mock_repo();
+ repo.expect_update_document_modified()
+ .withf(|document_id| document_id == "doc-1")
+ .times(1)
+ .returning(|_| Box::pin(std::future::ready(Err(anyhow!("db is down")))));
+
+ let (service, event_broker) = make_test_service_with_event_broker(repo);
+
+ let result = service
+ .record_interaction("doc-1", InteractionReason::Edited)
+ .await;
+
+ assert_eq!(result.unwrap_err().to_string(), "db is down");
+ assert!(event_broker.published().lock().unwrap().is_empty());
+}
+
+#[tokio::test]
+async fn join_and_leave_interactions_publish_without_bumping_document() {
+ for (reason, expected_reason) in [
+ (InteractionReason::FirstJoin, "first_join"),
+ (InteractionReason::LastLeave, "last_leave"),
+ ] {
+ let mut repo = make_mock_repo();
+ repo.expect_update_document_modified().times(0);
+
+ let (service, event_broker) = make_test_service_with_event_broker(repo);
+
+ service.record_interaction("doc-1", reason).await.unwrap();
+
+ let published = event_broker.published();
+ let published = published.lock().unwrap();
+ assert_eq!(published.len(), 1);
+ assert_eq!(published[0].payload["event_type"], "document.interaction");
+ assert_eq!(published[0].payload["metadata"]["reason"], expected_reason);
+ }
+}
diff --git a/crates/documents/src/outbound/pg_document_repo.rs b/crates/documents/src/outbound/pg_document_repo.rs
index 0b12f75d1b..63d86ffb70 100644
--- a/crates/documents/src/outbound/pg_document_repo.rs
+++ b/crates/documents/src/outbound/pg_document_repo.rs
@@ -39,6 +39,21 @@ impl PgDocumentRepo {
}
}
+async fn update_document_modified(pool: &PgPool, document_id: &str) -> Result<(), sqlx::Error> {
+ sqlx::query!(
+ r#"
+ UPDATE "Document"
+ SET "updatedAt" = NOW()
+ WHERE id = $1
+ "#,
+ document_id,
+ )
+ .execute(pool)
+ .await?;
+
+ Ok(())
+}
+
impl DocumentRepo for PgDocumentRepo {
type Err = sqlx::Error;
@@ -581,6 +596,11 @@ impl DocumentRepo for PgDocumentRepo {
Ok(())
}
+ #[tracing::instrument(err, skip(self))]
+ async fn update_document_modified(&self, document_id: &str) -> Result<(), Self::Err> {
+ update_document_modified(&self.pool, document_id).await
+ }
+
#[tracing::instrument(err, skip(self))]
async fn update_project_modified(&self, project_id: &str) -> Result<(), Self::Err> {
sqlx::query!(
diff --git a/crates/documents/src/outbound/pg_document_repo/tests.rs b/crates/documents/src/outbound/pg_document_repo/tests.rs
index 0f968cd4a7..0e96faa952 100644
--- a/crates/documents/src/outbound/pg_document_repo/tests.rs
+++ b/crates/documents/src/outbound/pg_document_repo/tests.rs
@@ -214,6 +214,43 @@ async fn test_soft_delete_document(pool: Pool<Postgres>) {
assert!(row.deleted_at.is_some());
}
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))
+)]
+async fn test_update_document_modified(pool: Pool<Postgres>) {
+ let document_id = "d0000000-0000-0000-0000-000000000001";
+ sqlx::query!(
+ r#"
+ UPDATE "Document"
+ SET "updatedAt" = '2000-01-01 00:00:00'
+ WHERE id = $1
+ "#,
+ document_id,
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+
+ let repo = PgDocumentRepo::new(pool);
+ let before = repo
+ .get_document_metadata(document_id)
+ .await
+ .unwrap()
+ .updated_at
+ .unwrap();
+
+ repo.update_document_modified(document_id).await.unwrap();
+
+ let after = repo
+ .get_document_metadata(document_id)
+ .await
+ .unwrap()
+ .updated_at
+ .unwrap();
+ assert!(after > before);
+}
+
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../fixtures", scripts("documents_test_data"))
diff --git a/crates/email/src/domain/ports.rs b/crates/email/src/domain/ports.rs
index 4ae92ca1f0..8960ea8875 100644
--- a/crates/email/src/domain/ports.rs
+++ b/crates/email/src/domain/ports.rs
@@ -296,6 +296,12 @@ pub trait EmailRepo: Send + Sync + 'static {
thread_id: Uuid,
) -> impl Future<Output = Result<Option<String>, Self::Err>> + Send;
+ /// Advance a project's activity timestamp.
+ fn touch_project_updated_at(
+ &self,
+ project_id: &str,
+ ) -> impl Future<Output = Result<(), Self::Err>> + Send;
+
/// Upsert an email filter (by address or domain) for a link.
fn upsert_email_filter(
&self,
diff --git a/crates/email/src/domain/service/mod.rs b/crates/email/src/domain/service/mod.rs
index db33ee1edd..70c2dd4713 100644
--- a/crates/email/src/domain/service/mod.rs
+++ b/crates/email/src/domain/service/mod.rs
@@ -5,6 +5,9 @@ mod signature;
mod thread;
mod thread_labels;
+#[cfg(test)]
+mod test;
+
/// Unified entity-mutation capability impls.
mod entity_mutation;
@@ -26,9 +29,25 @@ use frecency::domain::ports::FrecencyQueryService;
use macro_event_broker::{MacroEventBroker, NoopMacroEventBroker};
use model_entity::EntityType;
use models_pagination::{PaginatedCursor, SimpleSortMethod};
-use std::collections::HashMap;
+use std::collections::{HashMap, HashSet};
use uuid::Uuid;
+fn changed_project_ids<'a>(
+ old_project_id: Option<&'a str>,
+ new_project_id: Option<&'a str>,
+) -> Vec<&'a str> {
+ if old_project_id == new_project_id {
+ return Vec::new();
+ }
+
+ let mut seen = HashSet::new();
+ [old_project_id, new_project_id]
+ .into_iter()
+ .flatten()
+ .filter(|project_id| !project_id.is_empty() && seen.insert(*project_id))
+ .collect()
+}
+
#[derive(Clone)]
pub struct EmailServiceImpl<T, U, E, CS, Eam, B = NoopMacroEventBroker> {
pub(crate) email_repo: T,
@@ -317,6 +336,21 @@ where
// Sync denormalized entity_access rows for the containing project.
// Best-effort: the project assignment itself already succeeded.
if old_project_id.as_deref() != project_id {
+ for affected_project_id in changed_project_ids(old_project_id.as_deref(), project_id) {
+ let _ = self
+ .email_repo
+ .touch_project_updated_at(affected_project_id)
+ .await
+ .map_err(anyhow::Error::from)
+ .inspect_err(|error| {
+ tracing::error!(
+ error=?error,
+ project_id=affected_project_id,
+ "unable to update project modified date"
+ );
+ });
+ }
+
if let Some(old) = old_project_id
.as_deref()
.and_then(|p| Uuid::parse_str(p).ok())
diff --git a/crates/email/src/domain/service/test.rs b/crates/email/src/domain/service/test.rs
new file mode 100644
index 0000000000..53838b61e7
--- /dev/null
+++ b/crates/email/src/domain/service/test.rs
@@ -0,0 +1,33 @@
+use super::changed_project_ids;
+
+#[test]
+fn changed_project_ids_include_old_and_new_projects() {
+ assert_eq!(
+ changed_project_ids(Some("old-project"), Some("new-project")),
+ vec!["old-project", "new-project"]
+ );
+}
+
+#[test]
+fn changed_project_ids_include_only_the_project_for_root_transitions() {
+ assert_eq!(
+ changed_project_ids(None, Some("new-project")),
+ vec!["new-project"]
+ );
+ assert_eq!(
+ changed_project_ids(Some("old-project"), None),
+ vec!["old-project"]
+ );
+}
+
+#[test]
+fn changed_project_ids_are_empty_for_unchanged_assignments() {
+ assert!(changed_project_ids(None, None).is_empty());
+ assert!(changed_project_ids(Some("project"), Some("project")).is_empty());
+}
+
+#[test]
+fn changed_project_ids_ignore_empty_and_duplicate_ids() {
+ assert!(changed_project_ids(Some(""), None).is_empty());
+ assert!(changed_project_ids(Some("project"), Some("project")).is_empty());
+}
diff --git a/crates/email/src/outbound/email_pg_repo/mod.rs b/crates/email/src/outbound/email_pg_repo/mod.rs
index 541dedd620..6a0e35fc95 100644
--- a/crates/email/src/outbound/email_pg_repo/mod.rs
+++ b/crates/email/src/outbound/email_pg_repo/mod.rs
@@ -23,6 +23,7 @@ mod link;
mod message;
mod preview;
mod preview_views;
+mod project;
mod thread;
#[cfg(test)]
@@ -332,6 +333,10 @@ impl EmailRepo for EmailPgRepo {
thread::get_thread_project_id(&self.pool, thread_id).await
}
+ async fn touch_project_updated_at(&self, project_id: &str) -> Result<(), Self::Err> {
+ project::touch_project_updated_at(&self.pool, project_id).await
+ }
+
async fn upsert_email_filter(
&self,
link_id: Uuid,
diff --git a/crates/email/src/outbound/email_pg_repo/project.rs b/crates/email/src/outbound/email_pg_repo/project.rs
new file mode 100644
index 0000000000..024b5fe655
--- /dev/null
+++ b/crates/email/src/outbound/email_pg_repo/project.rs
@@ -0,0 +1,16 @@
+use sqlx::PgPool;
+
+#[tracing::instrument(err, skip(pool))]
+pub(super) async fn touch_project_updated_at(
+ pool: &PgPool,
+ project_id: &str,
+) -> Result<(), sqlx::Error> {
+ sqlx::query!(
+ r#"UPDATE "Project" SET "updatedAt" = NOW() WHERE id = $1"#,
+ project_id,
+ )
+ .execute(pool)
+ .await?;
+
+ Ok(())
+}
diff --git a/crates/email/src/outbound/email_pg_repo/test/draft.rs b/crates/email/src/outbound/email_pg_repo/test/draft.rs
index ac56a5c721..770e58ac6d 100644
--- a/crates/email/src/outbound/email_pg_repo/test/draft.rs
+++ b/crates/email/src/outbound/email_pg_repo/test/draft.rs
@@ -5,6 +5,7 @@ use crate::domain::models::{
};
use chrono::Utc;
use sqlx::Row;
+use std::time::Duration;
// ── get_simple_message ────────────────────────────────────────────
@@ -693,6 +694,12 @@ async fn test_insert_draft_message_upsert_existing(pool: Pool<Postgres>) -> anyh
let thread_db_id = Uuid::parse_str("11111111-1111-1111-1111-111111111111")?;
// Re-use the existing draft message ID (msg2)
let message_db_id = Uuid::parse_str("ee000002-0000-0000-0000-000000000002")?;
+ let thread_before = repo
+ .thread_by_id(thread_db_id)
+ .await?
+ .expect("draft thread should exist");
+
+ tokio::time::sleep(Duration::from_millis(10)).await;
let input = ResolvedDraftInput {
db_id: message_db_id,
@@ -734,6 +741,15 @@ async fn test_insert_draft_message_upsert_existing(pool: Pool<Postgres>) -> anyh
Some("Updated body")
);
+ let thread_after = repo
+ .thread_by_id(thread_db_id)
+ .await?
+ .expect("draft thread should still exist");
+ assert!(
+ thread_after.updated_at > thread_before.updated_at,
+ "editing an existing draft should advance its thread timestamp"
+ );
+
Ok(())
}
diff --git a/crates/email/src/outbound/email_pg_repo/test/mod.rs b/crates/email/src/outbound/email_pg_repo/test/mod.rs
index d4497a2450..494e981480 100644
--- a/crates/email/src/outbound/email_pg_repo/test/mod.rs
+++ b/crates/email/src/outbound/email_pg_repo/test/mod.rs
@@ -6,6 +6,7 @@ mod labels;
mod link;
mod message;
mod preview;
+mod project;
mod project_scope_dynamic_query;
mod signal_flag;
mod thread;
diff --git a/crates/email/src/outbound/email_pg_repo/test/project.rs b/crates/email/src/outbound/email_pg_repo/test/project.rs
new file mode 100644
index 0000000000..7895762579
--- /dev/null
+++ b/crates/email/src/outbound/email_pg_repo/test/project.rs
@@ -0,0 +1,36 @@
+use std::time::Duration;
+
+use super::*;
+
+async fn project_updated_at(
+ pool: &Pool<Postgres>,
+ project_id: &str,
+) -> anyhow::Result<chrono::DateTime<Utc>> {
+ Ok(sqlx::query_scalar!(
+ r#"SELECT "updatedAt"::timestamptz AS "updated_at!" FROM "Project" WHERE id = $1"#,
+ project_id,
+ )
+ .fetch_one(pool)
+ .await?)
+}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_dynamic_query"))
+)]
+async fn touch_project_updated_at_advances_stored_timestamp(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let project_id = "proj-aaaa-aaaa-aaaa-aaaaaaaaaaaa";
+ let original_updated_at = project_updated_at(&pool, project_id).await?;
+
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ EmailPgRepo::new(pool.clone())
+ .touch_project_updated_at(project_id)
+ .await?;
+
+ let updated_at = project_updated_at(&pool, project_id).await?;
+ assert!(updated_at > original_updated_at);
+
+ Ok(())
+}
diff --git a/crates/email/src/outbound/email_pg_repo/test/thread.rs b/crates/email/src/outbound/email_pg_repo/test/thread.rs
index 164536bca2..a35a4fb6cb 100644
--- a/crates/email/src/outbound/email_pg_repo/test/thread.rs
+++ b/crates/email/src/outbound/email_pg_repo/test/thread.rs
@@ -1,3 +1,5 @@
+use std::time::Duration;
+
use super::*;
#[sqlx::test(
@@ -42,6 +44,31 @@ async fn test_thread_by_id_not_found(pool: Pool<Postgres>) -> anyhow::Result<()>
Ok(())
}
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../../fixtures", scripts("email_dynamic_query"))
+)]
+async fn moving_thread_to_project_advances_thread_timestamp(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let thread_id = Uuid::parse_str("20000001-0000-0000-0000-000000000001")?;
+ let new_project_id = "proj-bbbb-bbbb-bbbb-bbbbbbbbbbbb";
+ let repo = EmailPgRepo::new(pool);
+ let original_updated_at = repo.thread_by_id(thread_id).await?.unwrap().updated_at;
+
+ tokio::time::sleep(Duration::from_millis(10)).await;
+ assert!(
+ repo.update_thread_project(thread_id, Some(new_project_id))
+ .await?
+ );
+
+ let updated_thread = repo.thread_by_id(thread_id).await?.unwrap();
+ assert_eq!(updated_thread.project_id.as_deref(), Some(new_project_id));
+ assert!(updated_thread.updated_at > original_updated_at);
+
+ Ok(())
+}
+
#[sqlx::test(
migrator = "MACRO_DB_MIGRATIONS",
fixtures(path = "../../../../fixtures", scripts("email_thread"))
diff --git a/crates/email_db_client/src/threads/insert.rs b/crates/email_db_client/src/threads/insert.rs
index c23780df5a..8c3b05aa6c 100644
--- a/crates/email_db_client/src/threads/insert.rs
+++ b/crates/email_db_client/src/threads/insert.rs
@@ -1,3 +1,6 @@
+#[cfg(test)]
+mod test;
+
use crate::messages::replying_to_id::update_thread_messages_replying_to;
use crate::parse::service_to_db::addresses_from_message;
use crate::{contacts, messages, parse};
diff --git a/crates/email_db_client/src/threads/insert/test.rs b/crates/email_db_client/src/threads/insert/test.rs
new file mode 100644
index 0000000000..f40b5f4198
--- /dev/null
+++ b/crates/email_db_client/src/threads/insert/test.rs
@@ -0,0 +1,39 @@
+use super::*;
+use crate::threads::get::get_thread_by_id_and_link_id;
+use chrono::Utc;
+use macro_db_migrator::MACRO_DB_MIGRATIONS;
+use sqlx::{Pool, Postgres};
+use std::time::Duration;
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures(path = "../../../fixtures", scripts("links", "threads"))
+)]
+async fn provider_thread_upsert_advances_existing_thread_timestamp(
+ pool: Pool<Postgres>,
+) -> anyhow::Result<()> {
+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000001")?;
+ let existing_thread_id = Uuid::parse_str("10000000-0000-0000-0000-000000000001")?;
+ let mut conflicting_thread = get_thread_by_id_and_link_id(&pool, existing_thread_id, link_id)
+ .await?
+ .expect("provider thread should exist");
+ let updated_at_before = conflicting_thread.updated_at;
+
+ tokio::time::sleep(Duration::from_millis(10)).await;
+
+ conflicting_thread.db_id = Uuid::parse_str("20000000-0000-0000-0000-000000000001")?;
+ conflicting_thread.latest_inbound_message_ts = Some(Utc::now());
+
+ let upserted_thread_id = insert_thread(&pool, &conflicting_thread, link_id).await?;
+
+ assert_eq!(upserted_thread_id, existing_thread_id);
+ let thread_after = get_thread_by_id_and_link_id(&pool, existing_thread_id, link_id)
+ .await?
+ .expect("provider thread should still exist");
+ assert!(
+ thread_after.updated_at > updated_at_before,
+ "provider thread upsert should advance the existing thread timestamp"
+ );
+
+ Ok(())
+}
diff --git a/crates/email_db_client/src/threads/update/test.rs b/crates/email_db_client/src/threads/update/test.rs
index adc5afddbe..a041985b15 100644
--- a/crates/email_db_client/src/threads/update/test.rs
+++ b/crates/email_db_client/src/threads/update/test.rs
@@ -1,6 +1,8 @@
use super::*;
+use crate::threads::get::get_thread_by_id_and_link_id;
use macro_db_migrator::MACRO_DB_MIGRATIONS;
use sqlx::{Pool, Postgres};
+use std::time::Duration;
const THREAD_WITH_ICS: &str = "00000000-0000-0000-0000-00000000b201";
const THREAD_STALE_TRUE_PDF_ONLY: &str = "00000000-0000-0000-0000-00000000b202";
@@ -237,16 +239,26 @@ async fn draft_discard_without_metadata_recompute_syncs_signal_flag(
fixtures(path = "../../../fixtures", scripts("sync_thread_signal_flag"))
)]
async fn update_thread_metadata_syncs_signal_flag(pool: Pool<Postgres>) -> anyhow::Result<()> {
+ let thread_id = Uuid::parse_str(SIG_THREAD_STALE_PROMO)?;
+ let link_id = Uuid::parse_str("00000000-0000-0000-0000-000000000d01")?;
+
assert!(fetch_signal(&pool, SIG_THREAD_STALE_PROMO).await?);
+ let thread_before = get_thread_by_id_and_link_id(&pool, thread_id, link_id)
+ .await?
+ .expect("thread should exist");
+
+ tokio::time::sleep(Duration::from_millis(10)).await;
let mut conn = pool.acquire().await?;
- update_thread_metadata(
- &mut conn,
- Uuid::parse_str(SIG_THREAD_STALE_PROMO)?,
- Uuid::parse_str("00000000-0000-0000-0000-000000000d01")?,
- )
- .await?;
+ update_thread_metadata(&mut conn, thread_id, link_id).await?;
assert!(!fetch_signal(&pool, SIG_THREAD_STALE_PROMO).await?);
+ let thread_after = get_thread_by_id_and_link_id(&pool, thread_id, link_id)
+ .await?
+ .expect("thread should still exist");
+ assert!(
+ thread_after.updated_at > thread_before.updated_at,
+ "metadata recomputation should advance the thread timestamp"
+ );
Ok(())
}
diff --git a/crates/macro_db_client/src/document/mod.rs b/crates/macro_db_client/src/document/mod.rs
index 6416b6e98e..530c898e07 100644
--- a/crates/macro_db_client/src/document/mod.rs
+++ b/crates/macro_db_client/src/document/mod.rs
@@ -36,4 +36,3 @@ pub mod initialize_onboarding_documents;
pub mod preview;
pub mod revert_delete;
pub mod track_document;
-pub mod update;
diff --git a/crates/macro_db_client/src/document/update.rs b/crates/macro_db_client/src/document/update.rs
deleted file mode 100644
index 5d36cebafb..0000000000
--- a/crates/macro_db_client/src/document/update.rs
+++ /dev/null
@@ -1,17 +0,0 @@
-use sqlx::{Pool, Postgres};
-
-#[tracing::instrument(skip(db))]
-pub async fn update_document(db: &Pool<Postgres>, document_id: &str) -> anyhow::Result<()> {
- sqlx::query!(
- r#"
- UPDATE "Document"
- SET "updatedAt" = NOW()
- WHERE id = $1
- "#,
- document_id
- )
- .execute(db)
- .await?;
-
- Ok(())
-}
diff --git a/crates/macro_db_client/src/projects/mod.rs b/crates/macro_db_client/src/projects/mod.rs
index fc83688760..dec5da97e6 100644
--- a/crates/macro_db_client/src/projects/mod.rs
+++ b/crates/macro_db_client/src/projects/mod.rs
@@ -7,4 +7,3 @@ pub use get_projects::{
};
pub mod delete;
pub mod get_project_history;
-pub mod move_item;
diff --git a/crates/macro_db_client/src/projects/move_item.rs b/crates/macro_db_client/src/projects/move_item.rs
deleted file mode 100644
index 8377e976a8..0000000000
--- a/crates/macro_db_client/src/projects/move_item.rs
+++ /dev/null
@@ -1,65 +0,0 @@
-use sqlx::{Postgres, Transaction};
-
-#[tracing::instrument(skip(transaction))]
-pub async fn move_item_to_project(
- transaction: &mut Transaction<'_, Postgres>,
- project_id: &str,
- item_id: &str,
- item_type: &str,
-) -> anyhow::Result<()> {
- let project_id = if project_id.is_empty() {
- None
- } else {
- Some(project_id)
- };
-
- match item_type {
- "document" => {
- sqlx::query!(
- r#"UPDATE "Document" SET "projectId"=$2 WHERE "id"=$1"#,
- item_id,
- project_id
- )
- .execute(transaction.as_mut())
- .await?;
- }
- "chat" => {
- sqlx::query!(
- r#"UPDATE "Chat" SET "projectId"=$2 WHERE "id"=$1"#,
- item_id,
- project_id
- )
- .execute(transaction.as_mut())
- .await?;
- }
- "project" => {
- sqlx::query!(
- r#"UPDATE "Project" SET "parentId"=$2 WHERE "id"=$1"#,
- item_id,
- project_id
- )
- .execute(transaction.as_mut())
- .await?;
- }
- _ => {
- anyhow::bail!("Invalid item type");
- }
- }
-
- Ok(())
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
- use sqlx::{Pool, Postgres};
-
- #[sqlx::test(fixtures(path = "../../fixtures", scripts("basic_user_with_lots_of_documents")))]
- async fn test_move_item_to_project(pool: Pool<Postgres>) -> anyhow::Result<()> {
- let mut transaction = pool.begin().await?;
- move_item_to_project(&mut transaction, "", "document-one", "document").await?;
- transaction.commit().await?;
-
- Ok(())
- }
-}
diff --git a/crates/models_soup/src/call_record/test.rs b/crates/models_soup/src/call_record/test.rs
index 28108bbdbe..8de1b8434d 100644
--- a/crates/models_soup/src/call_record/test.rs
+++ b/crates/models_soup/src/call_record/test.rs
@@ -1,7 +1,9 @@
use super::*;
+use crate::item::SoupItem;
use call::domain::models::{CallRecord, CallRecordParticipant};
-use chrono::Utc;
+use chrono::{DateTime, Duration, Utc};
use item_filters::CallStatus;
+use models_pagination::{SimpleSortMethod, SortOn};
use uuid::Uuid;
fn record_with_participants(user_ids: &[&str]) -> CallRecord {
@@ -45,6 +47,45 @@ fn record_with_status(status: CallStatus, user_ids: &[&str]) -> CallRecord {
record
}
+fn assert_call_recency(item: &SoupItem, expected: DateTime<Utc>) {
+ assert_eq!(item.updated_at(), expected);
+
+ for sort_method in [
+ SimpleSortMethod::ViewedAt,
+ SimpleSortMethod::UpdatedAt,
+ SimpleSortMethod::ViewedUpdated,
+ ] {
+ let mut sort_on = <SoupItem as SortOn<SimpleSortMethod>>::sort_on(sort_method);
+ assert_eq!(sort_on(item).last_val, expected, "sort: {sort_method:?}");
+ }
+}
+
+#[test]
+fn active_call_recency_uses_started_at() {
+ let record = record_with_participants(&["macro|[email protected]"]);
+ let started_at = record.started_at;
+ let item = SoupItem::Call(SoupCallRecord::from_record_for_user(
+ record,
+ ));
+
+ assert_call_recency(&item, started_at);
+}
+
+#[test]
+fn finished_call_recency_uses_ended_at() {
+ let mut record = record_with_participants(&["macro|[email protected]"]);
+ let ended_at = record.started_at + Duration::minutes(30);
+ record.ended_at = Some(ended_at);
+ record.is_active = false;
+ let item = SoupItem::Call(SoupCallRecord::from_record_for_user(
+ record,
+ ));
+
+ assert_call_recency(&item, ended_at);
+}
+
#[test]
fn call_record_status_uses_record_status_when_present() {
let record = record_with_status(CallStatus::Missed, &["macro|[email protected]"]);
diff --git a/crates/models_soup/src/item.rs b/crates/models_soup/src/item.rs
index 5cd58b747b..4dfa9bafff 100644
--- a/crates/models_soup/src/item.rs
+++ b/crates/models_soup/src/item.rs
@@ -86,6 +86,7 @@ impl<T> SoupItem<T> {
SoupItem::EmailThread(soup_thread) => soup_thread.thread.updated_at,
SoupItem::Channel(soup_channel) => soup_channel.channel.channel.updated_at,
SoupItem::ChannelThread(thread) => thread.effective_updated_at(),
+ // Calls intentionally lack `updated_at`; recency follows their lifecycle timestamps.
SoupItem::Call(record) => record.ended_at.unwrap_or(record.started_at),
SoupItem::CrmCompany(company) => company.updated_at,
SoupItem::ForeignEntity(foreign_entity) => foreign_entity.updated_at,
@@ -146,6 +147,7 @@ impl<T> SoupItem<T> {
.unwrap_or(soup_channel.channel.channel.updated_at),
(SoupItem::ChannelThread(thread), SimpleSortMethod::CreatedAt) => thread.created_at,
(SoupItem::ChannelThread(thread), _) => thread.effective_updated_at(),
+ // Calls intentionally lack `updated_at`; recency follows their lifecycle timestamps.
(SoupItem::Call(record), SimpleSortMethod::CreatedAt) => record.started_at,
(SoupItem::Call(record), _) => record.ended_at.unwrap_or(record.started_at),
(SoupItem::CrmCompany(company), SimpleSortMethod::CreatedAt) => company.created_at,
diff --git a/services/document_storage_service/src/api/documents/mod.rs b/services/document_storage_service/src/api/documents/mod.rs
index 0d6b49880b..11455850dd 100644
--- a/services/document_storage_service/src/api/documents/mod.rs
+++ b/services/document_storage_service/src/api/documents/mod.rs
@@ -28,7 +28,6 @@ pub(in crate::api) mod list_documents_with_access;
pub(in crate::api) mod location;
pub(in crate::api) mod permissions_token;
pub(in crate::api) mod pre_save;
-pub(in crate::api) mod put_document_update;
pub(in crate::api) mod revert_delete_document;
pub(in crate::api) mod save_document;
pub(in crate::api) mod simple_save;
diff --git a/services/document_storage_service/src/api/documents/put_document_update.rs b/services/document_storage_service/src/api/documents/put_document_update.rs
deleted file mode 100644
index d951a487f1..0000000000
--- a/services/document_storage_service/src/api/documents/put_document_update.rs
+++ /dev/null
@@ -1,45 +0,0 @@
-use crate::api::context::{ApiContext, AuthorizationService};
-use axum::{
- extract::{Path, State},
- http::StatusCode,
- response::IntoResponse,
-};
-use macro_authorization::{InternalOnly, MacroAuthorizationExtractor};
-use model::response::{EmptyResponse, GenericErrorResponse};
-
-#[derive(serde::Deserialize)]
-pub struct Params {
- pub document_id: String,
-}
-
-/// Updates a particular document by its id.
-#[utoipa::path(
- tag = "document",
- put,
- path = "/internal/documents/{document_id}/update",
- operation_id = "put_document_update",
- params(
- ("document_id" = String, Path, description = "Document ID")
- ),
- responses(
- (status = 200, body=EmptyResponse),
- (status = 401, body=GenericErrorResponse),
- (status = 404, body=GenericErrorResponse),
- (status = 500, body=GenericErrorResponse),
- )
- )]
-#[tracing::instrument(skip(ctx, _auth))]
-pub async fn handler(
- State(ctx): State<ApiContext>,
- _auth: MacroAuthorizationExtractor<AuthorizationService, InternalOnly>,
- Path(Params { document_id }): Path<Params>,
-) -> impl IntoResponse {
- let res = macro_db_client::document::update::update_document(&ctx.db, &document_id).await;
-
- if res.is_err() {
- tracing::error!("unable to update document");
- return StatusCode::INTERNAL_SERVER_ERROR;
- }
-
- StatusCode::OK
-}
diff --git a/services/document_storage_service/src/api/internal/mod.rs b/services/document_storage_service/src/api/internal/mod.rs
index 90078a0777..8a962a7905 100644
--- a/services/document_storage_service/src/api/internal/mod.rs
+++ b/services/document_storage_service/src/api/internal/mod.rs
@@ -9,7 +9,7 @@ use super::{
documents::{
get_document, get_document_key, get_document_permissions, get_document_text,
get_full_pdf_modification_data, initialize_how_to_guide, list_documents_with_access,
- location, put_document_update,
+ location,
},
user::populate_items,
};
@@ -122,10 +122,6 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {
"/documents/{document_id}/{document_version_id}/key",
get(get_document_key::get_document_key_handler),
)
- .route(
- "/documents/{document_id}/update",
- put(put_document_update::handler),
- )
.route(
"/documents/{document_id}/snapshot",
put(