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(activity): batch sync editors and debounce in DSS (#6690)

teo3352073c84c3
diff --git a/Cargo.lock b/Cargo.lock
index ec5adf3ee5..41a3bdad6e 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5842,6 +5842,7 @@ dependencies = [
"models_properties",
"non_empty",
"rdkafka",
+ "redis",
"reqwest 0.13.4",
"rootcause",
"s3_key",
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/documentSyncContentUpdatedMetadata.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/documentSyncContentUpdatedMetadata.ts
index 3d7ab4cde2..2653cf75f3 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/documentSyncContentUpdatedMetadata.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/documentSyncContentUpdatedMetadata.ts
@@ -7,19 +7,21 @@
import type { DocumentSyncContentUpdatedMetadataActor } from './documentSyncContentUpdatedMetadataActor';
import type { DocumentSyncContentUpdatedMetadataDocumentVersionId } from './documentSyncContentUpdatedMetadataDocumentVersionId';
import type { DocumentSyncContentUpdatedMetadataOnBehalfOf } from './documentSyncContentUpdatedMetadataOnBehalfOf';
+import type { DocumentSyncEditor } from './documentSyncEditor';
import type { FileType } from './fileType';
/**
* Metadata for [`DocumentTopicEvent::SyncContentUpdated`].
*/
export interface DocumentSyncContentUpdatedMetadata {
- /** Who mechanically changed the content. Absent on events published
-before attribution, and on human-only collab sessions. */
+ /** Legacy single-editor attribution; newer Sync callers send `editors`. */
actor?: DocumentSyncContentUpdatedMetadataActor;
/** The id of the live-collab document whose content changed. */
document_id: string;
/** Version marker for the sync snapshot, when the caller supplies one. */
document_version_id?: DocumentSyncContentUpdatedMetadataDocumentVersionId;
+ /** Distinct editors since the preceding snapshot notification. */
+ editors?: DocumentSyncEditor[];
/** File type of the sync document, resolved by the document backend. */
file_type: FileType;
on_behalf_of?: DocumentSyncContentUpdatedMetadataOnBehalfOf;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/documentSyncContentUpdatedMetadataActor.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/documentSyncContentUpdatedMetadataActor.ts
index 987d8ea2d5..acf35cd0a1 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/documentSyncContentUpdatedMetadataActor.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/documentSyncContentUpdatedMetadataActor.ts
@@ -6,7 +6,6 @@
*/
/**
- * Who mechanically changed the content. Absent on events published
-before attribution, and on human-only collab sessions.
+ * Legacy single-editor attribution; newer Sync callers send `editors`.
*/
export type DocumentSyncContentUpdatedMetadataActor = string | null;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/documentSyncEditor.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/documentSyncEditor.ts
new file mode 100644
index 0000000000..310e5b80ab
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/documentSyncEditor.ts
@@ -0,0 +1,16 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { DocumentSyncEditorOnBehalfOf } from './documentSyncEditorOnBehalfOf';
+
+/**
+ * An editor reported by Sync from an authenticated session.
+ */
+export interface DocumentSyncEditor {
+ /** User or bot that performed the edit. */
+ actor: string;
+ on_behalf_of?: DocumentSyncEditorOnBehalfOf;
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/documentSyncEditorOnBehalfOf.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/documentSyncEditorOnBehalfOf.ts
new file mode 100644
index 0000000000..ebdb10dd5d
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/documentSyncEditorOnBehalfOf.ts
@@ -0,0 +1,9 @@
+/**
+ * Generated by orval v7.21.0 🍺
+ * Do not edit manually.
+ * document_storage_service
+ * OpenAPI spec version: 0.1.0
+ */
+import type { MacroUserIdStr } from './macroUserIdStr';
+
+export type DocumentSyncEditorOnBehalfOf = null | MacroUserIdStr;
diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
index 01cedf9a32..037e51e511 100644
--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/index.ts
@@ -630,6 +630,8 @@ export * from './documentSyncContentUpdatedMetadata';
export * from './documentSyncContentUpdatedMetadataActor';
export * from './documentSyncContentUpdatedMetadataDocumentVersionId';
export * from './documentSyncContentUpdatedMetadataOnBehalfOf';
+export * from './documentSyncEditor';
+export * from './documentSyncEditorOnBehalfOf';
export * from './documentTeamShareResponse';
export * from './documentTeamShareResponseTeamId';
export * from './editAnchorRequest';
diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.json
index 3f5978a42c..cf75b9ea5b 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -21822,7 +21822,7 @@
"properties": {
"actor": {
"type": ["string", "null"],
- "description": "Who mechanically changed the content. Absent on events published\nbefore attribution, and on human-only collab sessions."
+ "description": "Legacy single-editor attribution; newer Sync callers send `editors`."
},
"document_id": {
"type": "string",
@@ -21832,6 +21832,13 @@
"type": ["string", "null"],
"description": "Version marker for the sync snapshot, when the caller supplies one."
},
+ "editors": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/DocumentSyncEditor"
+ },
+ "description": "Distinct editors since the preceding snapshot notification."
+ },
"file_type": {
"$ref": "#/components/schemas/FileType",
"description": "File type of the sync document, resolved by the document backend."
@@ -21849,6 +21856,28 @@
}
}
},
+ "DocumentSyncEditor": {
+ "type": "object",
+ "description": "An editor reported by Sync from an authenticated session.",
+ "required": ["actor"],
+ "properties": {
+ "actor": {
+ "type": "string",
+ "description": "User or bot that performed the edit."
+ },
+ "on_behalf_of": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/MacroUserIdStr",
+ "description": "User represented by an agent, if any."
+ }
+ ]
+ }
+ }
+ },
"DocumentTeamShareResponse": {
"type": "object",
"description": "The team-share state of a document. The team is resolved from the document\nowner's team membership.",
diff --git a/crates/activity/src/inbound/kafka_consumer.rs b/crates/activity/src/inbound/kafka_consumer.rs
index c44fe7b8b3..3cce3c25e6 100644
--- a/crates/activity/src/inbound/kafka_consumer.rs
+++ b/crates/activity/src/inbound/kafka_consumer.rs
@@ -1,7 +1,8 @@
//! Generic Kafka consumer that materializes activities from domain events.
//!
//! This machinery knows **zero domains**: it is generic over a declared
-//! event collection `C` and a host-supplied dispatcher `Fn(&C) -> Ingest`.
+//! event collection `C` and a host-supplied asynchronous dispatcher
+//! `Fn(C) -> impl Future<Output = Ingest>`.
//! The composition root (the hosting service) declares the topics and maps
//! each decoded event to the owning domain's ingest function.
//!
@@ -45,11 +46,12 @@ pub struct ActivityConsumer<R, C, F, P> {
_events: PhantomData<fn() -> C>,
}
-impl<R, C, F, P> ActivityConsumer<R, C, F, P>
+impl<R, C, F, P, Fut> ActivityConsumer<R, C, F, P>
where
R: ActivityRepo,
C: MacroEventCollection + 'static,
- F: Fn(&C) -> Ingest + Send + Sync,
+ F: Fn(C) -> Fut + Send + Sync,
+ Fut: Future<Output = Ingest> + Send,
P: ActivityRealtimePublisher,
{
/// Builds the consumer over an activity store, an event dispatcher, and
@@ -69,8 +71,8 @@ where
/// offset replays the source event, the deterministic ids no-op the
/// insert, and the announcement is published again; duplicates are
/// idempotent for subscribers (records keyed by id).
- async fn apply(&self, event: &C) -> Result<(), R::Err> {
- self.materializer.apply((self.ingest)(event)).await
+ async fn apply(&self, event: C) -> Result<(), R::Err> {
+ self.materializer.apply((self.ingest)(event).await).await
}
/// Runs the consumer until `shutdown` resolves.
@@ -135,7 +137,7 @@ where
// the replay idempotent.
tokio::select! {
_ = &mut shutdown => break,
- result = self.apply(&event).instrument(span) => {
+ result = self.apply(event).instrument(span) => {
result.context("failed to store activities")?;
}
}
diff --git a/crates/documents/Cargo.toml b/crates/documents/Cargo.toml
index 491f0d5d4b..804d2275e1 100644
--- a/crates/documents/Cargo.toml
+++ b/crates/documents/Cargo.toml
@@ -70,6 +70,7 @@ outbound = [
"dep:entity_access_db_utils",
"dep:entity_registry_db_utils",
"dep:hex",
+ "dep:redis",
"dep:share_permission_db_utils",
"dep:sqlx",
"ports",
@@ -149,6 +150,7 @@ model_owner = { path = "../model_owner" }
futures = { workspace = true }
share_permission_db_utils = { path = "../share_permission_db_utils", optional = true }
hex = { workspace = true, optional = true }
+redis = { workspace = true, optional = true, features = ["aio", "tokio-rustls-comp"] }
sqlx = { workspace = true, optional = true }
sync_service_client = { path = "../sync_service_client" }
task_dedup = { path = "../task_dedup", optional = true }
diff --git a/crates/documents/src/domain/activity.rs b/crates/documents/src/domain/activity.rs
index 09cea6b06e..f72994aad4 100644
--- a/crates/documents/src/domain/activity.rs
+++ b/crates/documents/src/domain/activity.rs
@@ -12,7 +12,7 @@ use ::activity::{
use chrono::{DateTime, Utc};
use uuid::Uuid;
-use super::events::DocumentTopicEvent;
+use super::events::{DocumentSyncEditor, DocumentTopicEvent};
use macro_user_id::user_id::MacroUserIdStr;
use model_owner::Owner;
@@ -121,19 +121,84 @@ impl ActivitySource for DocumentTopicEvent {
}
// Extraction-pipeline noise, not user activity.
DocumentTopicEvent::ContentUploaded(_) => Ingest::Ignore,
- // Only AI-attributed sessions carry an actor; human-only collab
- // sessions stay unattributed.
- DocumentTopicEvent::SyncContentUpdated(metadata) => match metadata.actor.clone() {
- Some(actor) => single(
- Attribution::new(actor, metadata.on_behalf_of.clone()),
- CommonAction::Edited,
- &metadata.document_id,
- event_time(event_id),
- ),
- None => Ingest::Ignore,
- },
+ DocumentTopicEvent::SyncContentUpdated(metadata) => {
+ let legacy = metadata.actor.clone().map(|actor| DocumentSyncEditor {
+ actor,
+ on_behalf_of: metadata.on_behalf_of.clone(),
+ });
+ let mut editors: Vec<_> = metadata.editors.iter().cloned().chain(legacy).collect();
+ // A stable order keeps ordinals, and so activity ids, identical on replay.
+ editors.sort_by(|a, b| editor_key(a).cmp(&editor_key(b)));
+ editors.dedup();
+ let activities: Vec<_> = editors
+ .into_iter()
+ .enumerate()
+ .map(|(ordinal, editor)| {
+ Activity::attributed(
+ event_id,
+ ordinal as u32,
+ Attribution::new(editor.actor, editor.on_behalf_of),
+ EntityType::Document,
+ &metadata.document_id,
+ CommonAction::Edited,
+ event_time(event_id),
+ )
+ })
+ .collect();
+ if activities.is_empty() {
+ Ingest::Ignore
+ } else {
+ Ingest::Insert(activities)
+ }
+ }
// Session lifecycle (first join / last leave), no actor.
DocumentTopicEvent::Interaction(_) => Ingest::Ignore,
}
}
}
+
+fn editor_key(editor: &DocumentSyncEditor) -> (&str, Option<&str>) {
+ (
+ editor.actor.as_ref(),
+ editor.on_behalf_of.as_ref().map(|user| user.as_ref()),
+ )
+}
+
+/// Classify document activity and debounce Sync edits in the Activity consumer.
+/// Search consumes the same source event independently and never waits on this work.
+#[cfg(feature = "ports")]
+pub async fn ingest_with_editing_sessions(
+ event: &DocumentTopicEvent,
+ event_id: Uuid,
+ store: &impl super::ports::EditingActivityStore,
+) -> Ingest {
+ const EDITING_IDLE: std::time::Duration = std::time::Duration::from_secs(5 * 60);
+ const STORE_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(100);
+
+ let rows = match (event, event.ingest(event_id)) {
+ (DocumentTopicEvent::SyncContentUpdated(_), Ingest::Insert(rows)) => rows,
+ (_, ingest) => return ingest,
+ };
+ // Redis may apply a refresh before its response times out. Losing that
+ // session's Activity is acceptable here: delivery is best effort, and
+ // emitting on uncertainty would turn cache failures into noisy edit feeds.
+ let refresh = store.refresh_editing_sessions(&rows, event_id, EDITING_IDLE);
+ let admitted = match tokio::time::timeout(STORE_TIMEOUT, refresh).await {
+ Ok(Ok(admitted)) => admitted,
+ result => {
+ tracing::warn!(?result, "skipping best-effort editing activity");
+ return Ingest::Ignore;
+ }
+ };
+ // Assign ordinals before filtering so retries keep the same activity ids.
+ let rows: Vec<_> = rows
+ .into_iter()
+ .zip(admitted)
+ .filter_map(|(row, admitted)| admitted.then_some(row))
+ .collect();
+ if rows.is_empty() {
+ Ingest::Ignore
+ } else {
+ Ingest::Insert(rows)
+ }
+}
diff --git a/crates/documents/src/domain/activity/test.rs b/crates/documents/src/domain/activity/test.rs
index ccb7250e46..4205802653 100644
--- a/crates/documents/src/domain/activity/test.rs
+++ b/crates/documents/src/domain/activity/test.rs
@@ -321,6 +321,7 @@ fn purge_requests_entity_deletion() {
fn pipeline_and_session_events_are_ignored() {
let sync = envelope(DocumentTopicEvent::SyncContentUpdated(
DocumentSyncContentUpdatedMetadata {
+ editors: Vec::new(),
document_id: DOCUMENT_ID.to_string(),
file_type: FileType::Md,
document_version_id: None,
@@ -346,6 +347,7 @@ fn pipeline_and_session_events_are_ignored() {
fn attributed_sync_content_is_an_edited_activity() {
let event = envelope(DocumentTopicEvent::SyncContentUpdated(
DocumentSyncContentUpdatedMetadata {
+ editors: Vec::new(),
document_id: DOCUMENT_ID.to_string(),
file_type: FileType::Md,
document_version_id: None,
@@ -376,3 +378,157 @@ fn replaying_an_event_derives_identical_activity_ids() {
let second = single_activity(event.event.ingest(event.event_id));
assert_eq!(first.id, second.id);
}
+
+#[test]
+fn human_sync_content_is_an_edit_by_the_authenticated_user() {
+ let actor = user("macro|[email protected]");
+ let event = envelope(DocumentTopicEvent::SyncContentUpdated(
+ DocumentSyncContentUpdatedMetadata {
+ editors: Vec::new(),
+ document_id: DOCUMENT_ID.to_string(),
+ file_type: FileType::Md,
+ document_version_id: None,
+ actor: Some(Actor::new_from_user(actor.clone())),
+ on_behalf_of: None,
+ },
+ ));
+ let activity = single_activity(event.event.ingest(event.event_id));
+ assert_eq!(activity.action, Action::Edited);
+ assert_eq!(activity.actor.as_ref(), actor.as_ref());
+ assert_eq!(activity.subject_id, actor.as_ref());
+ assert_eq!(activity.entity_id, DOCUMENT_ID);
+}
+
+fn editor_event(editors: &[(&str, Option<&str>)]) -> DocumentTopicEvent {
+ let mut metadata = DocumentSyncContentUpdatedMetadata::from_extract(
+ DOCUMENT_ID.to_owned(),
+ FileType::Md,
+ None,
+ None,
+ None,
+ );
+ metadata.editors = editors
+ .iter()
+ .map(
+ |(actor, subject)| crate::domain::events::DocumentSyncEditor {
+ actor: Actor::try_from((*actor).to_owned()).unwrap(),
+ on_behalf_of: subject.map(user),
+ },
+ )
+ .collect();
+ DocumentTopicEvent::SyncContentUpdated(metadata)
+}
+
+#[test]
+fn batched_editors_are_distinct_and_keep_agent_attribution() {
+ let event = editor_event(&[
+ ("macro|[email protected]", None),
+ ("macro|[email protected]", None),
+ (
+ "bot|00000000-0000-0000-0000-00000000a1a1",
+ Some("macro|[email protected]"),
+ ),
+ ("macro|[email protected]", None),
+ ]);
+ let id = Uuid::now_v7();
+ let Ingest::Insert(rows) = event.ingest(id) else {
+ panic!("expected editors");
+ };
+ assert_eq!(rows.len(), 3);
+ assert_eq!(
+ rows[0].actor.as_ref(),
+ "bot|00000000-0000-0000-0000-00000000a1a1"
+ );
+ assert_eq!(rows[0].subject_id, "macro|[email protected]");
+ assert_eq!(rows[1].actor.as_ref(), "macro|[email protected]");
+ assert_eq!(rows[2].actor.as_ref(), "macro|[email protected]");
+ assert_eq!(event.ingest(id), Ingest::Insert(rows));
+}
+
+#[cfg(feature = "ports")]
+struct Decisions(Vec<bool>);
+
+#[cfg(feature = "ports")]
+impl crate::domain::ports::EditingActivityStore for Decisions {
+ async fn refresh_editing_sessions(
+ &self,
+ activities: &[Activity],
+ _source_event_id: Uuid,
+ idle: std::time::Duration,
+ ) -> Result<Vec<bool>, rootcause::Report> {
+ assert_eq!(idle, std::time::Duration::from_secs(300));
+ assert_eq!(activities.len(), self.0.len());
+ Ok(self.0.clone())
+ }
+}
+
+#[cfg(feature = "ports")]
+#[tokio::test]
+async fn debounce_preserves_ordinals_and_ignores_empty_batches() {
+ let event = editor_event(&[
+ ("macro|[email protected]", None),
+ ("macro|[email protected]", None),
+ ]);
+ let id = Uuid::now_v7();
+ let row = single_activity(
+ ingest_with_editing_sessions(&event, id, &Decisions(vec![false, true])).await,
+ );
+ assert_eq!(row.actor.as_ref(), "macro|[email protected]");
+ assert_eq!(row.id, activity_id(id, 1));
+ assert_eq!(
+ ingest_with_editing_sessions(&event, id, &Decisions(vec![false, false])).await,
+ Ingest::Ignore
+ );
+ assert_eq!(
+ ingest_with_editing_sessions(&editor_event(&[]), id, &Decisions(vec![true])).await,
+ Ingest::Ignore
+ );
+}
+
+#[cfg(feature = "ports")]
+struct UnavailableStore {
+ stalled: bool,
+}
+
+#[cfg(feature = "ports")]
+impl crate::domain::ports::EditingActivityStore for UnavailableStore {
+ async fn refresh_editing_sessions(
+ &self,
+ _activities: &[Activity],
+ _source_event_id: Uuid,
+ _idle: std::time::Duration,
+ ) -> Result<Vec<bool>, rootcause::Report> {
+ if self.stalled {
+ std::future::pending::<()>().await;
+ }
+ Err(rootcause::report!("unavailable"))
+ }
+}
+
+#[cfg(feature = "ports")]
+#[tokio::test]
+async fn unavailable_debounce_is_best_effort_and_does_not_stall_other_activity() {
+ let event = editor_event(&[("macro|[email protected]", None)]);
+ let id = Uuid::now_v7();
+ for stalled in [false, true] {
+ let store = UnavailableStore { stalled };
+ let result = tokio::time::timeout(
+ std::time::Duration::from_secs(1),
+ ingest_with_editing_sessions(&event, id, &store),
+ )
+ .await
+ .unwrap();
+ assert_eq!(result, Ingest::Ignore);
+ let deleted = DocumentTopicEvent::Deleted(DocumentDeletedMetadata {
+ document_id: DOCUMENT_ID.to_owned(),
+ actor_user_id: Some(user("macro|[email protected]")),
+ actor: None,
+ on_behalf_of: None,
+ project_id: None,
+ });
+ assert_eq!(
+ ingest_with_editing_sessions(&deleted, id, &store).await,
+ deleted.ingest(id)
+ );
+ }
+}
diff --git a/crates/documents/src/domain/events.rs b/crates/documents/src/domain/events.rs
index 1dbd17475c..e92589d44e 100644
--- a/crates/documents/src/domain/events.rs
+++ b/crates/documents/src/domain/events.rs
@@ -125,6 +125,17 @@ pub struct DocumentContentUploadedMetadata {
pub document_version_id: Option<String>,
}
+/// An editor reported by Sync from an authenticated session.
+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
+pub struct DocumentSyncEditor {
+ /// User or bot that performed the edit.
+ #[cfg_attr(feature = "schema", schema(value_type = String))]
+ pub actor: Actor<'static>,
+ /// User represented by an agent, if any.
+ pub on_behalf_of: Option<MacroUserIdStr<'static>>,
+}
+
/// Metadata for [`DocumentTopicEvent::SyncContentUpdated`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]
@@ -135,8 +146,7 @@ pub struct DocumentSyncContentUpdatedMetadata {
pub file_type: FileType,
/// Version marker for the sync snapshot, when the caller supplies one.
pub document_version_id: Option<String>,
- /// Who mechanically changed the content. Absent on events published
- /// before attribution, and on human-only collab sessions.
+ /// Legacy single-editor attribution; newer Sync callers send `editors`.
#[serde(default, skip_serializing_if = "Option::is_none")]
#[cfg_attr(feature = "schema", schema(value_type = Option<String>))]
pub actor: Option<Actor<'static>>,
@@ -144,6 +154,9 @@ pub struct DocumentSyncContentUpdatedMetadata {
/// [`Self::actor`].
#[serde(default, skip_serializing_if = "Option::is_none")]
pub on_behalf_of: Option<MacroUserIdStr<'static>>,
+ /// Distinct editors since the preceding snapshot notification.
+ #[serde(default, skip_serializing_if = "Vec::is_empty")]
+ pub editors: Vec<DocumentSyncEditor>,
}
impl DocumentSyncContentUpdatedMetadata {
@@ -162,6 +175,7 @@ impl DocumentSyncContentUpdatedMetadata {
document_version_id,
actor: actor.and_then(|id| Actor::try_from(id).ok()),
on_behalf_of: on_behalf_of.and_then(|id| MacroUserIdStr::try_from(id).ok()),
+ editors: Vec::new(),
}
}
}
diff --git a/crates/documents/src/domain/events/test.rs b/crates/documents/src/domain/events/test.rs
index c5db749a78..337d029ade 100644
--- a/crates/documents/src/domain/events/test.rs
+++ b/crates/documents/src/domain/events/test.rs
@@ -123,6 +123,7 @@ fn sync_content_updated_serializes_to_the_exact_envelope() {
let event = Event::with_event_id(
Uuid::from_u128(2),
DocumentTopicEvent::SyncContentUpdated(DocumentSyncContentUpdatedMetadata {
+ editors: Vec::new(),
document_id: DOCUMENT_ID.to_string(),
file_type: FileType::Md,
document_version_id: None,
@@ -178,6 +179,7 @@ fn optional_document_versions_support_present_and_absent_values() {
document_version_id: None,
}),
DocumentTopicEvent::SyncContentUpdated(DocumentSyncContentUpdatedMetadata {
+ editors: Vec::new(),
document_id: DOCUMENT_ID.to_string(),
file_type: FileType::Md,
document_version_id: Some("snapshot-7".to_string()),
@@ -226,6 +228,7 @@ fn search_event_constructors_use_the_document_key_and_schema_v1() {
);
let sync_metadata = DocumentSyncContentUpdatedMetadata {
+ editors: Vec::new(),
document_id: DOCUMENT_ID.to_string(),
file_type: FileType::Md,
document_version_id: None,
diff --git a/crates/documents/src/domain/ports.rs b/crates/documents/src/domain/ports.rs
index b99df5a15d..039140457a 100644
--- a/crates/documents/src/domain/ports.rs
+++ b/crates/documents/src/domain/ports.rs
@@ -408,12 +408,11 @@ pub trait DocumentContentEventService: Send + Sync + 'static {
) -> impl Future<Output = Result<(), DocumentError>> + Send;
/// Resolve the stored file type and publish a sync-content event. Sync callers
- /// supply document identity and attribution without interpreting the content.
+ /// supply document identity and editors without interpreting the content.
fn publish_sync_content_updated(
&self,
document_id: &str,
- actor: Option<String>,
- on_behalf_of: Option<String>,
+ editors: Vec<crate::domain::events::DocumentSyncEditor>,
) -> impl Future<Output = Result<(), DocumentError>> + Send;
}
@@ -589,3 +588,18 @@ pub trait DocumentService: Send + Sync + 'static {
share: bool,
) -> impl Future<Output = Result<DocumentTeamShareResponse, DocumentError>> + Send;
}
+
+/// Shared editing-session timestamps, independent of document synchronization.
+pub trait EditingActivityStore: Send + Sync {
+ /// Atomically refresh each actor's session for the supplied inactivity window.
+ ///
+ /// Returns one admission flag per activity, in input order. A new session or
+ /// replay of its admitted source event is allowed; subsequent edits refresh
+ /// the inactivity window without producing another activity.
+ fn refresh_editing_sessions(
+ &self,
+ activities: &[activity::Activity],
+ source_event_id: uuid::Uuid,
+ idle: std::time::Duration,
+ ) -> impl Future<Output = Result<Vec<bool>, rootcause::Report>> + Send;
+}
diff --git a/crates/documents/src/domain/service/content_events.rs b/crates/documents/src/domain/service/content_events.rs
index ecac378c37..f902155092 100644
--- a/crates/documents/src/domain/service/content_events.rs
+++ b/crates/documents/src/domain/service/content_events.rs
@@ -45,8 +45,7 @@ impl<
async fn publish_sync_content_updated(
&self,
document_id: &str,
- actor: Option<String>,
- on_behalf_of: Option<String>,
+ editors: Vec<crate::domain::events::DocumentSyncEditor>,
) -> Result<(), DocumentError> {
let document = self
.repo
@@ -59,16 +58,18 @@ impl<
.and_then(|value| FileType::from_str(value).ok())
.ok_or_else(|| DocumentError::BadRequest("Unknown document file type".to_string()))?;
+ let mut metadata = DocumentSyncContentUpdatedMetadata::from_extract(
+ document_id.to_string(),
+ file_type,
+ None,
+ None,
+ None,
+ );
+ metadata.editors = editors;
self.macro_event_broker
.send_event(&DocumentMacroEvent::sync_content_updated(
document_id,
- DocumentSyncContentUpdatedMetadata::from_extract(
- document_id.to_string(),
- file_type,
- None,
- actor,
- on_behalf_of,
- ),
+ metadata,
))
.map(|_| ())
.map_err(|error| DocumentError::Internal(error.into()))
diff --git a/crates/documents/src/domain/service/tests/sync_content.rs b/crates/documents/src/domain/service/tests/sync_content.rs
index 2868e65418..b310101e5c 100644
--- a/crates/documents/src/domain/service/tests/sync_content.rs
+++ b/crates/documents/src/domain/service/tests/sync_content.rs
@@ -16,7 +16,15 @@ async fn notifications_resolve_the_stored_type_and_preserve_attribution() {
let user = "macro|[email protected]";
service
- .publish_sync_content_updated("doc-1", Some(actor.into()), Some(user.into()))
+ .publish_sync_content_updated(
+ "doc-1",
+ vec![crate::domain::events::DocumentSyncEditor {
+ actor: activity::Actor::try_from(actor.to_owned()).unwrap(),
+ on_behalf_of: Some(
+ macro_user_id::user_id::MacroUserIdStr::try_from(user.to_owned()).unwrap(),
+ ),
+ }],
+ )
.await
.unwrap();
@@ -29,8 +37,9 @@ async fn notifications_resolve_the_stored_type_and_preserve_attribution() {
"document.sync_content_updated"
);
assert_eq!(events[0].payload["metadata"]["file_type"], file_type);
- assert_eq!(events[0].payload["metadata"]["actor"], actor);
- assert_eq!(events[0].payload["metadata"]["on_behalf_of"], user);
+ let editor = &events[0].payload["metadata"]["editors"][0];
+ assert_eq!(editor["actor"], actor);
+ assert_eq!(editor["on_behalf_of"], user);
}
}
@@ -44,7 +53,7 @@ async fn missing_documents_do_not_publish_events() {
});
let (service, broker) = make_test_service_with_event_broker(repo);
let result = service
- .publish_sync_content_updated("missing", None, None)
+ .publish_sync_content_updated("missing", Vec::new())
.await;
assert!(matches!(result, Err(DocumentError::NotFound(_))));
assert!(broker.published().lock().unwrap().is_empty());
@@ -58,8 +67,37 @@ async fn notifications_surface_broker_failures() {
let (service, broker) =
make_test_service_with_configured_event_broker(repo, TestEventBroker::failing());
let result = service
- .publish_sync_content_updated("doc-1", None, None)
+ .publish_sync_content_updated("doc-1", Vec::new())
.await;
assert!(matches!(result, Err(DocumentError::Internal(_))));
assert!(broker.published().lock().unwrap().is_empty());
}
+
+#[tokio::test]
+async fn a_batch_of_editors_still_publishes_only_one_search_event() {
+ let mut repo = make_mock_repo();
+ repo.expect_get_basic_document()
+ .return_once(|_| Box::pin(std::future::ready(Ok(task_document_context("doc-1")))));
+ let (service, broker) = make_test_service_with_event_broker(repo);
+ let editors = ["macro|[email protected]", "macro|[email protected]"]
+ .into_iter()
+ .map(|actor| crate::domain::events::DocumentSyncEditor {
+ actor: activity::Actor::try_from(actor.to_owned()).unwrap(),
+ on_behalf_of: None,
+ })
+ .collect();
+ service
+ .publish_sync_content_updated("doc-1", editors)
+ .await
+ .unwrap();
+ let published = broker.published();
+ let events = published.lock().unwrap();
+ assert_eq!(events.len(), 1);
+ assert_eq!(
+ events[0].payload["metadata"]["editors"]
+ .as_array()
+ .unwrap()
+ .len(),
+ 2
+ );
+}
diff --git a/crates/documents/src/inbound/axum_router/sync_content_updated.rs b/crates/documents/src/inbound/axum_router/sync_content_updated.rs
index 5f10684c35..bcabb332a8 100644
--- a/crates/documents/src/inbound/axum_router/sync_content_updated.rs
+++ b/crates/documents/src/inbound/axum_router/sync_content_updated.rs
@@ -1,5 +1,6 @@
//! Handler for sync-content notifications from the synchronization service.
+use activity::Actor;
use axum::{
Json,
extract::{Path, State},
@@ -7,19 +8,25 @@ use axum::{
};
use entity_access::domain::ports::EntityAccessService;
use macro_authorization::{InternalOnly, MacroAuthorizationExtractor, MacroAuthorizationService};
+use macro_user_id::user_id::MacroUserIdStr;
use serde::Deserialize;
use super::{DocumentRouterState, Params};
-use crate::domain::{models::DocumentError, ports::DocumentContentEventService};
+use crate::domain::{
+ events::DocumentSyncEditor, models::DocumentError, ports::DocumentContentEventService,
+};
/// Attribution from the sync service's verified document token.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SyncContentUpdatedRequest {
- /// Actor that performed the edit, if any.
+ /// Legacy single agent actor from older Sync releases.
pub actor: Option<String>,
- /// User represented by the actor, if any.
+ /// User represented by the legacy actor, if any.
pub on_behalf_of: Option<String>,
+ /// Editors accumulated by Sync since its last snapshot notification.
+ #[serde(default)]
+ pub editors: Vec<DocumentSyncEditor>,
}
/// Publish an event using the document's stored metadata.
@@ -34,9 +41,20 @@ pub async fn sync_content_updated_handler<
Path(Params { document_id }): Path<Params>,
Json(request): Json<SyncContentUpdatedRequest>,
) -> Result<StatusCode, DocumentError> {
+ let mut editors = request.editors;
+ // Sync releases before batched editors sent a single agent actor. Invalid
+ // legacy ids are dropped, as they always were, so search still extracts.
+ if let Some(actor) = request.actor.and_then(|actor| Actor::try_from(actor).ok()) {
+ editors.push(DocumentSyncEditor {
+ actor,
+ on_behalf_of: request
+ .on_behalf_of
+ .and_then(|user| MacroUserIdStr::try_from(user).ok()),
+ });
+ }
state
.service
- .publish_sync_content_updated(&document_id, request.actor, request.on_behalf_of)
+ .publish_sync_content_updated(&document_id, editors)
.await?;
Ok(StatusCode::OK)
}
diff --git a/crates/documents/src/inbound/axum_router/tests.rs b/crates/documents/src/inbound/axum_router/tests.rs
index e5fdaebd7e..a5ed7be916 100644
--- a/crates/documents/src/inbound/axum_router/tests.rs
+++ b/crates/documents/src/inbound/axum_router/tests.rs
@@ -107,8 +107,7 @@ struct ContentUploadedCall {
#[derive(Clone, Debug, Eq, PartialEq)]
struct SyncContentCall {
document_id: String,
- actor: Option<String>,
- on_behalf_of: Option<String>,
+ editors: Vec<crate::domain::events::DocumentSyncEditor>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
@@ -445,16 +444,14 @@ impl DocumentContentEventService for FakeDocumentService {
async fn publish_sync_content_updated(
&self,
document_id: &str,
- actor: Option<String>,
- on_behalf_of: Option<String>,
+ editors: Vec<crate::domain::events::DocumentSyncEditor>,
) -> Result<(), DocumentError> {
self.sync_content_calls
.lock()
.unwrap()
.push(SyncContentCall {
document_id: document_id.to_string(),
- actor,
- on_behalf_of,
+ editors,
});
Ok(())
}
diff --git a/crates/documents/src/inbound/axum_router/tests/sync_content.rs b/crates/documents/src/inbound/axum_router/tests/sync_content.rs
index 43f3f49ec4..e737c97af9 100644
--- a/crates/documents/src/inbound/axum_router/tests/sync_content.rs
+++ b/crates/documents/src/inbound/axum_router/tests/sync_content.rs
@@ -3,7 +3,11 @@ use super::*;
#[tokio::test]
async fn sync_notifications_require_internal_auth_and_forward_only_identity_and_attribution() {
let (router, service, _, _) = test_router();
- let body = || Body::from(r#"{"actor":"bot|agent","on_behalf_of":"macro|[email protected]"}"#);
+ let body = || {
+ Body::from(
+ r#"{"actor":"bot|00000000-0000-0000-0000-00000000a1a1","on_behalf_of":"macro|[email protected]"}"#,
+ )
+ };
let user_request = Request::post("/doc-1/sync-content-updated")
.header("authorization", format!("Bearer {JWT_TOKEN}"))
.header("content-type", "application/json")
@@ -25,8 +29,18 @@ async fn sync_notifications_require_internal_auth_and_forward_only_identity_and_
*service.sync_content_calls.lock().unwrap(),
[SyncContentCall {
document_id: "doc-1".into(),
- actor: Some("bot|agent".into()),
- on_behalf_of: Some("macro|[email protected]".into()),
+ editors: vec![crate::domain::events::DocumentSyncEditor {
+ actor: activity::Actor::try_from(
+ "bot|00000000-0000-0000-0000-00000000a1a1".to_owned()
+ )
+ .unwrap(),
+ on_behalf_of: Some(
+ macro_user_id::user_id::MacroUserIdStr::try_from(
+ "macro|[email protected]".to_owned()
+ )
+ .unwrap()
+ ),
+ }],
}]
);
@@ -41,3 +55,53 @@ async fn sync_notifications_require_internal_auth_and_forward_only_identity_and_
);
assert_eq!(service.sync_content_calls.lock().unwrap().len(), 1);
}
+
+#[tokio::test]
+async fn sync_notifications_forward_batched_editors() {
+ let (router, service, _, _) = test_router();
+ let request = Request::post("/doc-1/sync-content-updated")
+ .header(INTERNAL_API_KEY_HEADER, STANDARD_INTERNAL_KEY)
+ .header("content-type", "application/json")
+ .body(Body::from(
+ r#"{"editors":[{"actor":"macro|[email protected]","on_behalf_of":null}]}"#,
+ ))
+ .unwrap();
+ assert_eq!(send_status(&router, request).await, StatusCode::OK);
+ let calls = service.sync_content_calls.lock().unwrap();
+ assert_eq!(calls.len(), 1);
+ assert_eq!(calls[0].editors.len(), 1);
+ assert_eq!(
+ calls[0].editors[0].actor.as_ref(),
+ );
+}
+
+#[tokio::test]
+async fn sync_notifications_reject_invalid_editors_and_drop_invalid_legacy_actors() {
+ let (router, service, _, _) = test_router();
+ let send = |body: &'static str| {
+ Request::post("/doc-1/sync-content-updated")
+ .header(INTERNAL_API_KEY_HEADER, STANDARD_INTERNAL_KEY)
+ .header("content-type", "application/json")
+ .body(Body::from(body))
+ .unwrap()
+ };
+ // Sync retries a rejected notification without editors, so search still runs.
+ assert_eq!(
+ send_status(
+ &router,
+ send(r#"{"editors":[{"actor":"not-a-principal","on_behalf_of":null}]}"#)
+ )
+ .await,
+ StatusCode::UNPROCESSABLE_ENTITY
+ );
+ assert!(service.sync_content_calls.lock().unwrap().is_empty());
+
+ assert_eq!(
+ send_status(&router, send(r#"{"actor":"not-a-principal"}"#)).await,
+ StatusCode::OK
+ );
+ let calls = service.sync_content_calls.lock().unwrap();
+ assert_eq!(calls.len(), 1);
+ assert!(calls[0].editors.is_empty());
+}
diff --git a/crates/documents/src/outbound.rs b/crates/documents/src/outbound.rs
index 889b3e3240..746295113d 100644
--- a/crates/documents/src/outbound.rs
+++ b/crates/documents/src/outbound.rs
@@ -5,6 +5,8 @@ pub mod document_sync;
#[cfg(feature = "document_create_adapters")]
pub mod document_bytes_upload;
+#[cfg(feature = "outbound")]
+pub mod editing_activity;
#[cfg(feature = "ai_tools")]
pub mod editing_worker_client;
#[cfg(feature = "ai_tools")]
diff --git a/crates/documents/src/outbound/editing_activity.rs b/crates/documents/src/outbound/editing_activity.rs
new file mode 100644
index 0000000000..9eea25f066
--- /dev/null
+++ b/crates/documents/src/outbound/editing_activity.rs
@@ -0,0 +1,76 @@
+//! Redis storage for shared document editing-session inactivity windows.
+
+use std::time::Duration;
+
+use activity::Activity;
+use redis::{ExistenceCheck, SetExpiry, SetOptions};
+use rootcause::Report;
+use uuid::Uuid;
+
+use crate::domain::ports::EditingActivityStore;
+
+/// Refreshes editing sessions atomically across document-service instances.
+/// This is a best-effort debounce; cache loss starts a new session.
+#[derive(Clone)]
+pub struct RedisEditingActivityStore {
+ client: redis::Client,
+}
+
+impl RedisEditingActivityStore {
+ /// Reuse the hosting service's Redis configuration.
+ pub fn new(client: redis::Client) -> Self {
+ Self { client }
+ }
+}
+
+fn session_key(activity: &Activity) -> Result<String, Report> {
+ // Encoding a tuple keeps separators within identifiers unambiguous.
+ let identity = serde_json::to_string(&(
+ activity.actor.as_ref(),
+ &activity.subject_id,
+ &activity.entity_id,
+ ))?;
+ Ok(format!("documents:editing:{identity}"))
+}
+
+impl EditingActivityStore for RedisEditingActivityStore {
+ async fn refresh_editing_sessions(
+ &self,
+ activities: &[Activity],
+ source_event_id: Uuid,
+ idle: Duration,
+ ) -> Result<Vec<bool>, Report> {
+ if activities.is_empty() {
+ return Ok(Vec::new());
+ }
+
+ // `SET NX GET` starts a session owned by this event, or returns the
+ // event that owns the current one; `EXPIRE` extends either window.
+ // Requires Redis 7.0+ for `NX` with `GET`.
+ let event_id = source_event_id.to_string();
+ let start_session = SetOptions::default()
+ .conditional_set(ExistenceCheck::NX)
+ .get(true)
+ .with_expiration(SetExpiry::EX(idle.as_secs()));
+ let mut pipeline = redis::pipe();
+ pipeline.atomic();
+ for activity in activities {
+ let key = session_key(activity)?;
+ pipeline
+ .set_options(&key, &event_id, start_session.clone())
+ .expire(&key, idle.as_secs() as i64)
+ .ignore();
+ }
+
+ let mut connection = self.client.get_multiplexed_async_connection().await?;
+ let owners: Vec<Option<String>> = pipeline.query_async(&mut connection).await?;
+ // A new session, or a replay of the event that opened it, is admitted.
+ Ok(owners
+ .into_iter()
+ .map(|owner| owner.is_none_or(|owner| owner == event_id))
+ .collect())
+ }
+}
+
+#[cfg(test)]
+mod test;
diff --git a/crates/documents/src/outbound/editing_activity/test.rs b/crates/documents/src/outbound/editing_activity/test.rs
new file mode 100644
index 0000000000..d0b629f378
--- /dev/null
+++ b/crates/documents/src/outbound/editing_activity/test.rs
@@ -0,0 +1,171 @@
+use super::*;
+use activity::{Actor, Attribution, CommonAction, EntityType};
+use chrono::Utc;
+use macro_user_id::user_id::MacroUserIdStr;
+
+macro_env_var::maybe_env_var! {
+ struct RedisUrl;
+}
+
+const TEST_IDLE: Duration = Duration::from_secs(30);
+
+fn store() -> RedisEditingActivityStore {
+ let redis_url = RedisUrl::new();
+ let url = redis_url
+ .as_ref()
+ .and_then(RedisUrl::value)
+ .unwrap_or("redis://127.0.0.1:6379");
+ RedisEditingActivityStore::new(redis::Client::open(url).unwrap())
+}
+
+fn edit(document_id: &str, actor: &str, subject: Option<&str>) -> Activity {
+ Activity::attributed(
+ Uuid::now_v7(),
+ 0,
+ Attribution::new(
+ Actor::try_from(actor.to_owned()).unwrap(),
+ subject.map(|user| MacroUserIdStr::try_from(user.to_owned()).unwrap()),
+ ),
+ EntityType::Document,
+ document_id,
+ CommonAction::Edited,
+ Utc::now(),
+ )
+}
+
+#[tokio::test]
+async fn replay_keeps_the_original_admission_decision_after_later_edits() {
+ let store = store();
+ let activities = [edit(
+ &Uuid::now_v7().to_string(),
+ None,
+ )];
+ let first = Uuid::now_v7();
+ let later = Uuid::now_v7();
+ for (event_id, expected) in [
+ (first, true),
+ (first, true),
+ (later, false),
+ (later, false),
+ (first, true),
+ ] {
+ assert_eq!(
+ store
+ .refresh_editing_sessions(&activities, event_id, TEST_IDLE)
+ .await
+ .unwrap(),
+ vec![expected],
+ );
+ }
+}
+
+#[tokio::test]
+async fn actor_subject_and_document_have_independent_sessions_in_input_order() {
+ let store = store();
+ let document = Uuid::now_v7().to_string();
+ let other_document = Uuid::now_v7().to_string();
+ let agent = format!("bot|{}", Uuid::now_v7());
+ let other_agent = format!("bot|{}", Uuid::now_v7());
+ let alice = "macro|[email protected]";
+ let bob = "macro|[email protected]";
+ let first = edit(&document, &agent, Some(alice));
+ assert_eq!(
+ store
+ .refresh_editing_sessions(std::slice::from_ref(&first), Uuid::now_v7(), TEST_IDLE)
+ .await
+ .unwrap(),
+ vec![true],
+ );
+
+ let activities = [
+ edit(&document, &other_agent, Some(alice)),
+ first,
+ edit(&document, &agent, Some(bob)),
+ edit(&other_document, &agent, Some(alice)),
+ edit(&document, alice, None),
+ ];
+ assert_eq!(
+ store
+ .refresh_editing_sessions(&activities, Uuid::now_v7(), TEST_IDLE)
+ .await
+ .unwrap(),
+ vec![true, false, true, true, true],
+ );
+}
+
+#[tokio::test]
+async fn concurrent_distinct_events_admit_only_one_session_start() {
+ let store = store();
+ let activities = [edit(
+ &Uuid::now_v7().to_string(),
+ None,
+ )];
+ let results = futures::future::join_all(
+ (0..16).map(|_| store.refresh_editing_sessions(&activities, Uuid::now_v7(), TEST_IDLE)),
+ )
+ .await;
+ assert_eq!(
+ results
+ .into_iter()
+ .filter(|result| result.as_ref().unwrap()[0])
+ .count(),
+ 1,
+ );
+}
+
+#[tokio::test]
+async fn suppressed_edits_extend_expiry_until_a_full_inactivity_window() {
+ let store = store();
+ let activities = [edit(
+ &Uuid::now_v7().to_string(),
+ None,
+ )];
+ let idle = Duration::from_secs(3);
+ assert_eq!(
+ store
+ .refresh_editing_sessions(&activities, Uuid::now_v7(), idle)
+ .await
+ .unwrap(),
+ vec![true],
+ );
+ tokio::time::sleep(Duration::from_millis(1500)).await;
+ assert_eq!(
+ store
+ .refresh_editing_sessions(&activities, Uuid::now_v7(), idle)
+ .await
+ .unwrap(),
+ vec![false],
+ );
+ // The original expiry has elapsed, but the suppressed edit extended it.
+ tokio::time::sleep(Duration::from_millis(1800)).await;
+ assert_eq!(
+ store
+ .refresh_editing_sessions(&activities, Uuid::now_v7(), idle)
+ .await
+ .unwrap(),
+ vec![false],
+ );
+ tokio::time::sleep(idle + Duration::from_millis(200)).await;
+ assert_eq!(
+ store
+ .refresh_editing_sessions(&activities, Uuid::now_v7(), idle)
+ .await
+ .unwrap(),
+ vec![true],
+ );
+}
+
+#[tokio::test]
+async fn an_empty_batch_does_not_connect_to_redis() {
+ let store = RedisEditingActivityStore::new(redis::Client::open("redis://127.0.0.1:1").unwrap());
+ assert!(
+ store
+ .refresh_editing_sessions(&[], Uuid::now_v7(), TEST_IDLE)
+ .await
+ .unwrap()
+ .is_empty()
+ );
+}
diff --git a/crates/soup_realtime/src/inbound/kafka_consumer/test.rs b/crates/soup_realtime/src/inbound/kafka_consumer/test.rs
index f9a50c62d6..077943ddc4 100644
--- a/crates/soup_realtime/src/inbound/kafka_consumer/test.rs
+++ b/crates/soup_realtime/src/inbound/kafka_consumer/test.rs
@@ -206,6 +206,7 @@ fn search_only_document_events_do_not_emit_patches() {
document_version_id: Some("convert".to_string()),
}),
DocumentTopicEvent::SyncContentUpdated(DocumentSyncContentUpdatedMetadata {
+ editors: Vec::new(),
document_id: DOCUMENT_ID.to_string(),
file_type: "md".parse().expect("valid file type"),
document_version_id: None,
diff --git a/crates/webhook/src/domain/ingestion/test.rs b/crates/webhook/src/domain/ingestion/test.rs
index 965ff73a63..f2a9960385 100644
--- a/crates/webhook/src/domain/ingestion/test.rs
+++ b/crates/webhook/src/domain/ingestion/test.rs
@@ -547,6 +547,7 @@ fn search_only_document_event_cases() -> Vec<(&'static str, Event<DocumentTopicE
"document.sync_content_updated",
Event::new(DocumentTopicEvent::SyncContentUpdated(
DocumentSyncContentUpdatedMetadata {
+ editors: Vec::new(),
document_id: DOCUMENT_ID.to_string(),
file_type: "md".parse().expect("valid file type"),
document_version_id: None,
diff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.md
index b73e8dd6b4..5a55dc363c 100644
--- a/docs/AGENT_GUIDE/documents.md
+++ b/docs/AGENT_GUIDE/documents.md
@@ -559,6 +559,9 @@ Right side of a doc (toggle with `Hide/Show Side Panel`):
three newest, a `View all activities` toggle row (dotted connector, caret glyph), and the
oldest fetched entry (usually `created this`) pinned last; the toggle flips to `Show less`
once expanded.
+ Human content edits appear after the next sync flush. Continued editing creates
+ one Activity event until that editor has been inactive for five minutes; their
+ next edit then starts another event. Opening a document alone creates no edit.
- Header: `Share`, `Copy Share Link`, overflow menu — use `Share` to inspect or change the
doc's visibility/permissions. Documents, AI chats, and folders have a `Team access`
control (None / View / Comment / Edit) for sharing directly with the owner's team.
diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.md
index 70946aa0ed..12ef7cff21 100644
--- a/docs/AGENT_GUIDE/surfaces.md
+++ b/docs/AGENT_GUIDE/surfaces.md
@@ -221,8 +221,8 @@ insert older history above already displayed rows. Live actions and refreshes
can still reorder rows. Short or fully filtered pages continue loading until the list
fills or there are no more results. A failed
source shows a retry notice while the other source stays usable. Document typing
-alone is not yet attributed by Activity; Home reflects the actions the existing
-Activity system records.
+starts an Edited activity for that editing session. Human edits
+are attributed to the signed-in editor; agent edits retain their agent attribution.
Calendar reminder rows use the reminder delivery time for Home's date section,
including on a cold GraphQL load with notification sorting disabled. Verify that
@@ -786,6 +786,13 @@ quoted fields, original date timestamps and spreadsheet formula escaping.
## Activity — `/app/component/activity`
+To verify document content activity, keep Activity open in one tab and edit an
+existing document's body in another, without renaming it. The editor's Edited
+entry should arrive for the first edit. Keep typing across multiple saves: the
+activity count must stay unchanged. After five minutes without editing, the next
+edit should add one new event. Reconnecting within that window and opening or
+closing a document without edits must not add an event.
+
Requires authentication and the `enable-activity-feed` flag. Direct navigation and
restored splits wait for flags to load; when disabled, they redirect to Home
(`/app/component/inbox`) without loading the activity feed.
diff --git a/packages/sdk/generated/storage/index.ts b/packages/sdk/generated/storage/index.ts
index e1f76334d6..97a100a9f4 100644
--- a/packages/sdk/generated/storage/index.ts
+++ b/packages/sdk/generated/storage/index.ts
@@ -1,4 +1,4 @@
// This file is auto-generated by @hey-api/openapi-ts
export { type Options, Sdk } from './sdk.gen';
-export type { AccessLevel, ActiveCallsResponse, ActiveCallSummary, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Agent, AgentActionId, AgentChannelScope, AgentMcpServer, AgentMcpServers, AgentPullRequestState, AgentSessionFilters, AgentSessionLifecycleEvent, Anchor, AnchorId, AnchorRequest, AnchorResponse, AnnotationIncrementalUpdate, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelContextMessage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelMessage, ApiChannelMessageKind, ApiChannelMessagesPage, ApiChannelParticipant, ApiChannelWithLatest, ApiCountedReaction, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiMessageAttachment, ApiMessageSender, ApiMessageSenderType, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, ApiResolvedChannelMessage, ApiThreadInfo, ApiThreadReply, ApproveHarnessPairingData, ApproveHarnessPairingError, ApproveHarnessPairingErrors, ApproveHarnessPairingResponse, ApproveHarnessPairingResponses, ApprovePairingRequest, AssignInitiativeTasksData, AssignInitiativeTasksError, AssignInitiativeTasksErrors, AssignInitiativeTasksResponse, AssignInitiativeTasksResponses, AssignTasksRequest, AssignTasksResponse, AssignTasksResult, AssignTaskStatus, AttachmentChange, AttendeeResponseStatus, BasicDocument, BasicDocumentSubType, BomPart, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotSenderProfile, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarEventSourceContent, CalendarMentionEvent, CalendarMentionPreviewItem, CalendarMentionPreviewKind, CalendarMentionPreviewRequest, CalendarMentionPreviewRequestItem, CalendarMentionPreviewResponse, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallRecord, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelEventAttachment, ChannelFilters, ChannelJoinCodeResponse, ChannelLabel, ChannelLabelRule, ChannelLabelsList, ChannelMentionedMetadata, ChannelMessage, ChannelMessageAttachmentCreatedMetadata, ChannelMessageAttachmentRemovedMetadata, ChannelMessageDeletedMetadata, ChannelMessageFilters, ChannelMessagePatchedMetadata, ChannelMessagePostedMetadata, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClaimedPairing, ClaimHarnessPairingData, ClaimHarnessPairingError, ClaimHarnessPairingErrors, ClaimHarnessPairingResponse, ClaimHarnessPairingResponses, ClaimPairingRequest, ClientOptions, CloudStorageItemType, CollabSurfaceResponse, CollabSurfaceTokenResponse, Comment, CommentThread, ConferenceProvider, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CountedReaction, CreateAgentData, CreateAgentError, CreateAgentErrors, CreateAgentRequest, CreateAgentResponse, CreateAgentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelLabelData, CreateChannelLabelError, CreateChannelLabelErrors, CreateChannelLabelRequest, CreateChannelLabelResponse, CreateChannelLabelResponses, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenError, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponse, CreateCollabSurfaceTokenResponses, CreateCommentData, CreateCommentError, CreateCommentErrors, CreateCommentRequest, CreateCommentResponse, CreateCommentResponse2, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentError, CreateCrmCommentErrors, CreateCrmCommentRequest, CreateCrmCommentResponse, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreatedPairing, CreatedUserApiKey, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateHarnessPairingData, CreateHarnessPairingError, CreateHarnessPairingErrors, CreateHarnessPairingResponse, CreateHarnessPairingResponses, CreateInitiativeData, CreateInitiativeError, CreateInitiativeErrors, CreateInitiativeRequest, CreateInitiativeResponse, CreateInitiativeResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreatePairingRequest, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateReminderData, CreateReminderError, CreateReminderErrors, CreateReminderRequest, CreateReminderResponse, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateUserApiKeyData, CreateUserApiKeyError, CreateUserApiKeyErrors, CreateUserApiKeyRequest, CreateUserApiKeyResponse, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmComment, CrmCommentEntityType, CrmCommentThread, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmStageInput, CrmStageResponse, CrmStagesResponse, CrmTeamSettingsResponse, CrmThread, CustomSpeakerAssignment, DataType, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorInfo, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelError, DeleteChannelLabelErrors, DeleteChannelLabelResponse, DeleteChannelLabelResponses, DeleteChannelResponse, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceError, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponse, DeleteCollabSurfaceResponses, DeleteCommentData, DeleteCommentError, DeleteCommentErrors, DeleteCommentRequest, DeleteCommentResponse, DeleteCommentResponse2, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentError, DeleteCrmCommentErrors, DeleteCrmCommentResponse, DeleteCrmCommentResponses, DeleteCrmCommentResult, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessError, DeleteHarnessErrors, DeleteHarnessResponse, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteInitiativeData, DeleteInitiativeError, DeleteInitiativeErrors, DeleteInitiativeResponse, DeleteInitiativeResponses, DeleteMessageData, DeleteMessageError, DeleteMessageErrors, DeleteMessageQuery, DeleteMessageResponse, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderError, DeleteReminderErrors, DeleteReminderResponse, DeleteReminderResponses, DeleteSelfHarnessData, DeleteSelfHarnessError, DeleteSelfHarnessErrors, DeleteSelfHarnessResponse, DeleteSelfHarnessResponses, DeleteThreadInfo, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserApiKeyData, DeleteUserApiKeyError, DeleteUserApiKeyErrors, DeleteUserApiKeyResponse, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DescriptionDocumentId, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentId, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentTeamShareResponse, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditCommentData, EditCommentError, EditCommentErrors, EditCommentRequest, EditCommentResponse, EditCommentResponse2, EditCommentResponses, EditCrmCommentData, EditCrmCommentError, EditCrmCommentErrors, EditCrmCommentRequest, EditCrmCommentResponse, EditCrmCommentResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmptyResponse, EnsureCollabSurfaceData, EnsureCollabSurfaceError, EnsureCollabSurfaceErrors, EnsureCollabSurfaceRequest, EnsureCollabSurfaceResponse, EnsureCollabSurfaceResponses, EntityFilters, EntityMessageCreateData, EntityMessageCreateResponse, EntityMessageCreateResponses, EntityMessageDeleteMessageData, EntityMessageDeleteMessageResponse, EntityMessageDeleteMessageResponses, EntityMessageDeleteThreadData, EntityMessageDeleteThreadResponse, EntityMessageDeleteThreadResponses, EntityMessageEditData, EntityMessageEditResponse, EntityMessageEditResponses, EntityMessageGetMessageData, EntityMessageGetMessageResponse, EntityMessageGetMessageResponses, EntityMessageGetThreadData, EntityMessageGetThreadResponse, EntityMessageGetThreadResponses, EntityMessageLegacyData, EntityMessageLegacyResponse, EntityMessageLegacyResponses, EntityMessagePatchThreadData, EntityMessagePatchThreadResponse, EntityMessagePatchThreadResponses, EntityMessageReactData, EntityMessageReactResponse, EntityMessageReactResponses, EntityMessageTypingData, EntityMessageTypingResponse, EntityMessageTypingResponses, EntityPermission, EntityPermissionResponse, EntityReference, EntityType, ErrorResponse, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileSystemNodeWithIds, FileType, FileTypeUpdate, FolderItem, ForeignEntity, ForeignEntityFilters, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActiveCallsData, GetActiveCallsError, GetActiveCallsErrors, GetActiveCallsResponse, GetActiveCallsResponses, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelMessagesCatchUpData, GetChannelMessagesCatchUpError, GetChannelMessagesCatchUpErrors, GetChannelMessagesCatchUpResponse, GetChannelMessagesCatchUpResponses, GetChannelMessagesData, GetChannelMessagesError, GetChannelMessagesErrors, GetChannelMessagesResponse, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceError, GetCollabSurfaceErrors, GetCollabSurfaceResponse, GetCollabSurfaceResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactByEmailData, GetContactByEmailError, GetContactByEmailErrors, GetContactByEmailResponse, GetContactByEmailResponse2, GetContactByEmailResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsError, GetDocumentCommentsErrors, GetDocumentCommentsResponse, GetDocumentCommentsResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceError, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponse, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetHarnessPairingData, GetHarnessPairingError, GetHarnessPairingErrors, GetHarnessPairingResponse, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInitiativeData, GetInitiativeError, GetInitiativeErrors, GetInitiativeResponse, GetInitiativeResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextError, GetMessageWithContextErrors, GetMessageWithContextResponse, GetMessageWithContextResponse2, GetMessageWithContextResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetReminderData, GetReminderError, GetReminderErrors, GetReminderResponse, GetReminderResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessError, GetSelfHarnessErrors, GetSelfHarnessResponse, GetSelfHarnessResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesError, GetThreadRepliesErrors, GetThreadRepliesResponse, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubPullRequest, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestsResponse, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, Harness, HarnessAgent, HarnessId, HarnessOwner, HarnessSession, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, ImportedAuthor, InFlightTurnSummary, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InitiativeDetail, InitiativeId, InitiativeList, InitiativeSummary, InputReceivedMetadata, InstallSyncData, InstallSyncErrors, InteractionReason, Item, ItemWithUserAccessLevel, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, LatestMessage, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkShare, ListAgentsData, ListAgentsError, ListAgentsErrors, ListAgentsResponse, ListAgentsResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListChannelLabelsData, ListChannelLabelsError, ListChannelLabelsErrors, ListChannelLabelsResponse, ListChannelLabelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsError, ListCrmCommentsErrors, ListCrmCommentsResponse, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListHarnessAgentsData, ListHarnessAgentsError, ListHarnessAgentsErrors, ListHarnessAgentsResponse, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesError, ListHarnessesErrors, ListHarnessesResponse, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsError, ListHarnessSessionsErrors, ListHarnessSessionsResponse, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesError, ListInitiativesErrors, ListInitiativesResponse, ListInitiativesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListRemindersData, ListRemindersError, ListRemindersErrors, ListRemindersResponse, ListRemindersResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponse, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Mentions, Message, MessageAttachment, MessageChange, MessageCursor, MessageDirection, MessageEvent, MessageListItem, MessagePage, MessageParent, MessagePatch, MessageThread, MessageThreadPreview, MessageTimelineData, MessageTimelineQuery, MessageTimelineResponse, MessageTimelineResponses, NewAttachment, NewChannelAttachment, NewThreadAnchor, NotificationFilters, NotificationState, PairingDetails, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageData, PatchMessageError, PatchMessageErrors, PatchMessageNotificationPolicy, PatchMessageRequest, PatchMessageResponse, PatchMessageResponses, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfAnchorRequest, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PdfPlaceableCommentAnchorRequest, PendingClaimResponse, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesError, PostChannelMessagesErrors, PostChannelMessagesResponse, PostChannelMessagesResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessage, PostMessageData, PostMessageError, PostMessageErrors, PostMessageNotificationPolicy, PostMessageRequest, PostMessageResponse, PostMessageResponse2, PostMessageResponses, PostReactionData, PostReactionError, PostReactionErrors, PostReactionRequest, PostReactionResponse, PostReactionResponses, PostSoupAstRequest, PostSoupRequest, PostTypingData, PostTypingError, PostTypingErrors, PostTypingRequest, PostTypingResponse, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresignedUrl, PreviewSmartTagData, PreviewSmartTagError, PreviewSmartTagErrors, PreviewSmartTagResponse, PreviewSmartTagResponses, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyFilter, PropertyInput, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesError, PutCrmTeamStagesErrors, PutCrmTeamStagesResponse, PutCrmTeamStagesResponses, ReactionAction, ReactionInput, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, Reminder, ReminderFilters, ReminderSchedule, RemindersList, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, RenameChannelLabelData, RenameChannelLabelError, RenameChannelLabelErrors, RenameChannelLabelRequest, RenameChannelLabelResponse, RenameChannelLabelResponses, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ReplaceCrmStagesRequest, RequestedHarnessScope, ResetCrmTeamStagesData, ResetCrmTeamStagesError, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponse, ResetCrmTeamStagesResponses, ResolveChannelMessageData, ResolveChannelMessageError, ResolveChannelMessageErrors, ResolveChannelMessageResponse, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, S3ObjectInfo, SaveBomPart, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SessionDeletedMetadata, SessionIdentity, SessionMentionedMetadata, SessionOpenedMetadata, SessionRenamedMetadata, SessionSettledMetadata, SessionStoppedMetadata, SetChannelLabelData, SetChannelLabelError, SetChannelLabelErrors, SetChannelLabelRequest, SetChannelLabelResponse, SetChannelLabelResponses, SetChannelPictureData, SetChannelPictureError, SetChannelPictureErrors, SetChannelPictureRequest, SetChannelPictureResponse, SetChannelPictureResponses, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetPropertyValue, SharedEmailFilter, SharePermissionV2, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SmartTagChannelMatch, SmartTagPreview, SoupAgentSessionSoupPropertiesField, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmDomain, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupReminderReference, SoupReminderSchedule, SoupReminderSoupPropertiesField, SoupThreadInfo, SoupThreadReply, StarterDocumentsResponse, StreamEventsData, StreamEventsError, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, String, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, TagFilterMode, TaskFilters, TeamOutOfOfficeItem, TeamOutOfOfficeResponse, TeamRole, Thread, ThreadAnchor, ThreadOrigin, ThreadPatch, ThreadResponse, ThreadState, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TranscribeDictationData, TranscribeDictationError, TranscribeDictationErrors, TranscribeDictationResponse, TranscribeDictationResponses, TranscribeResponse, TranscriptSegmentRequest, TurnEndedMetadata, TurnStartedMetadata, TurnSummary, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingAction, TypingInput, UnassignInitiativeTaskData, UnassignInitiativeTaskError, UnassignInitiativeTaskErrors, UnassignInitiativeTaskResponse, UnassignInitiativeTaskResponses, UnthreadedPdfUuidRequest, UpdateAgentData, UpdateAgentError, UpdateAgentErrors, UpdateAgentRequest, UpdateAgentResponse, UpdateAgentResponses, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateInitiativeData, UpdateInitiativeError, UpdateInitiativeErrors, UpdateInitiativeRequest, UpdateInitiativeResponse, UpdateInitiativeResponses, UpdateOperation, UpdateReminderData, UpdateReminderError, UpdateReminderErrors, UpdateReminderRequest, UpdateReminderResponse, UpdateReminderResponses, UpdateSharePermissionRequestV2, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserApiKeyId, UserApiKeyInfo, UserApiKeysList, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, View, ViewPatch, ViewsResponse, WaitingForInputMetadata, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';
+export type { AccessLevel, ActiveCallsResponse, ActiveCallSummary, ActivityType, AddFavoriteData, AddFavoriteError, AddFavoriteErrors, AddFavoriteRequest, AddFavoriteResponse, AddFavoriteResponses, AddParticipantsData, AddParticipantsError, AddParticipantsErrors, AddParticipantsRequest, AddParticipantsResponses, AddPinHandlerData, AddPinHandlerError, AddPinHandlerErrors, AddPinHandlerResponse, AddPinHandlerResponses, AddPinRequest, Agent, AgentActionId, AgentChannelScope, AgentMcpServer, AgentMcpServers, AgentPullRequestState, AgentSessionFilters, AgentSessionLifecycleEvent, Anchor, AnchorId, AnchorRequest, AnchorResponse, AnnotationIncrementalUpdate, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelContextMessage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelMessage, ApiChannelMessageKind, ApiChannelMessagesPage, ApiChannelParticipant, ApiChannelWithLatest, ApiCountedReaction, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiMessageAttachment, ApiMessageSender, ApiMessageSenderType, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, ApiResolvedChannelMessage, ApiThreadInfo, ApiThreadReply, ApproveHarnessPairingData, ApproveHarnessPairingError, ApproveHarnessPairingErrors, ApproveHarnessPairingResponse, ApproveHarnessPairingResponses, ApprovePairingRequest, AssignInitiativeTasksData, AssignInitiativeTasksError, AssignInitiativeTasksErrors, AssignInitiativeTasksResponse, AssignInitiativeTasksResponses, AssignTasksRequest, AssignTasksResponse, AssignTasksResult, AssignTaskStatus, AttachmentChange, AttendeeResponseStatus, BasicDocument, BasicDocumentSubType, BomPart, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotSenderProfile, BotToken, BranchNameResponse, BTreeMap, BulkWakeupRequest, BulkWakeupResponse, BulkWakeupSyncServiceDocumentsData, BulkWakeupSyncServiceDocumentsErrors, BulkWakeupSyncServiceDocumentsResponse, BulkWakeupSyncServiceDocumentsResponses, CalendarAttendee, CalendarEvent, CalendarEventFilters, CalendarEventSourceContent, CalendarMentionEvent, CalendarMentionPreviewItem, CalendarMentionPreviewKind, CalendarMentionPreviewRequest, CalendarMentionPreviewRequestItem, CalendarMentionPreviewResponse, CalendarOccurrence, CalendarOccurrenceItem, CalendarOccurrenceResponse, CalendarSyncStatus, CallActiveResponse, CallFilters, CallRecord, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelEventAttachment, ChannelFilters, ChannelJoinCodeResponse, ChannelLabel, ChannelLabelRule, ChannelLabelsList, ChannelMentionedMetadata, ChannelMessage, ChannelMessageAttachmentCreatedMetadata, ChannelMessageAttachmentRemovedMetadata, ChannelMessageDeletedMetadata, ChannelMessageFilters, ChannelMessagePatchedMetadata, ChannelMessagePostedMetadata, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPreview, ChannelPreviewData, ChannelSender, ChannelSharePermission, ChannelThreadFilters, ChannelTopicEvent, ChannelType, ChannelUpdatedMetadata, ChannelWebhookRequest, ChannelWebhookResponse, ChannelWithParticipants, Chat, ChatFilters, CheckActiveCallData, CheckActiveCallError, CheckActiveCallErrors, CheckActiveCallResponse, CheckActiveCallResponses, ClaimedPairing, ClaimHarnessPairingData, ClaimHarnessPairingError, ClaimHarnessPairingErrors, ClaimHarnessPairingResponse, ClaimHarnessPairingResponses, ClaimPairingRequest, ClientOptions, CloudStorageItemType, CollabSurfaceResponse, CollabSurfaceTokenResponse, Comment, CommentThread, ConferenceProvider, CopyDocumentData, CopyDocumentError, CopyDocumentErrors, CopyDocumentQueryParams, CopyDocumentRequest, CopyDocumentResponse, CopyDocumentResponse2, CopyDocumentResponses, CountedReaction, CreateAgentData, CreateAgentError, CreateAgentErrors, CreateAgentRequest, CreateAgentResponse, CreateAgentResponses, CreateAnchorData, CreateAnchorError, CreateAnchorErrors, CreateAnchorResponse, CreateAnchorResponses, CreateBotRequest, CreateBulkDocumentResponse, CreateBulkDocumentResponseData, CreateChannelData, CreateChannelError, CreateChannelErrors, CreateChannelLabelData, CreateChannelLabelError, CreateChannelLabelErrors, CreateChannelLabelRequest, CreateChannelLabelResponse, CreateChannelLabelResponses, CreateChannelRequest, CreateChannelResponse, CreateChannelResponse2, CreateChannelResponses, CreateChannelScopedBotData, CreateChannelScopedBotError, CreateChannelScopedBotErrors, CreateChannelScopedBotRequest, CreateChannelScopedBotResponse, CreateChannelScopedBotResponse2, CreateChannelScopedBotResponses, CreateCollabSurfaceTokenData, CreateCollabSurfaceTokenError, CreateCollabSurfaceTokenErrors, CreateCollabSurfaceTokenResponse, CreateCollabSurfaceTokenResponses, CreateCommentData, CreateCommentError, CreateCommentErrors, CreateCommentRequest, CreateCommentResponse, CreateCommentResponse2, CreateCommentResponses, CreateCrmCommentData, CreateCrmCommentError, CreateCrmCommentErrors, CreateCrmCommentRequest, CreateCrmCommentResponse, CreateCrmCommentResponses, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreatedPairing, CreatedUserApiKey, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateHarnessPairingData, CreateHarnessPairingError, CreateHarnessPairingErrors, CreateHarnessPairingResponse, CreateHarnessPairingResponses, CreateInitiativeData, CreateInitiativeError, CreateInitiativeErrors, CreateInitiativeRequest, CreateInitiativeResponse, CreateInitiativeResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreatePairingRequest, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateReminderData, CreateReminderError, CreateReminderErrors, CreateReminderRequest, CreateReminderResponse, CreateReminderResponses, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateUserApiKeyData, CreateUserApiKeyError, CreateUserApiKeyErrors, CreateUserApiKeyRequest, CreateUserApiKeyResponse, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmComment, CrmCommentEntityType, CrmCommentThread, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmStageInput, CrmStageResponse, CrmStagesResponse, CrmTeamSettingsResponse, CrmThread, CustomSpeakerAssignment, DataType, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorInfo, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelError, DeleteChannelLabelErrors, DeleteChannelLabelResponse, DeleteChannelLabelResponses, DeleteChannelResponse, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceError, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponse, DeleteCollabSurfaceResponses, DeleteCommentData, DeleteCommentError, DeleteCommentErrors, DeleteCommentRequest, DeleteCommentResponse, DeleteCommentResponse2, DeleteCommentResponses, DeleteCrmCommentData, DeleteCrmCommentError, DeleteCrmCommentErrors, DeleteCrmCommentResponse, DeleteCrmCommentResponses, DeleteCrmCommentResult, DeleteDocumentData, DeleteDocumentError, DeleteDocumentErrors, DeleteDocumentResponse, DeleteDocumentResponses, DeleteEntityMentionData, DeleteEntityMentionError, DeleteEntityMentionErrors, DeleteEntityMentionResponse, DeleteEntityMentionResponse2, DeleteEntityMentionResponses, DeleteHarnessData, DeleteHarnessError, DeleteHarnessErrors, DeleteHarnessResponse, DeleteHarnessResponses, DeleteHistoryHandlerData, DeleteHistoryHandlerError, DeleteHistoryHandlerErrors, DeleteHistoryHandlerResponse, DeleteHistoryHandlerResponses, DeleteInitiativeData, DeleteInitiativeError, DeleteInitiativeErrors, DeleteInitiativeResponse, DeleteInitiativeResponses, DeleteMessageData, DeleteMessageError, DeleteMessageErrors, DeleteMessageQuery, DeleteMessageResponse, DeleteMessageResponses, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteReminderData, DeleteReminderError, DeleteReminderErrors, DeleteReminderResponse, DeleteReminderResponses, DeleteSelfHarnessData, DeleteSelfHarnessError, DeleteSelfHarnessErrors, DeleteSelfHarnessResponse, DeleteSelfHarnessResponses, DeleteThreadInfo, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserApiKeyData, DeleteUserApiKeyError, DeleteUserApiKeyErrors, DeleteUserApiKeyResponse, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DescriptionDocumentId, DocumentBasic, DocumentContent, DocumentContentLocation, DocumentContentState, DocumentContentUploadedMetadata, DocumentCopiedMetadata, DocumentCreatedMetadata, DocumentDeletedMetadata, DocumentFilters, DocumentId, DocumentInteractionMetadata, DocumentMetadata, DocumentMetadataWithContent, DocumentPermissionsToken, DocumentPermissionsTokenRequest, DocumentPermissionsTokenResponse, DocumentPreview, DocumentPreviewData, DocumentPreviewDataSubType, DocumentPurgedMetadata, DocumentResponse, DocumentResponseMetadata, DocumentResponseMetadataWithContent, DocumentStorageServiceApiVersion, DocumentSubType, DocumentSyncContentUpdatedMetadata, DocumentSyncEditor, DocumentTeamShareResponse, DocumentTopicEvent, DocumentUpdatedMetadata, EditAnchorData, EditAnchorError, EditAnchorErrors, EditAnchorRequest, EditAnchorResponse, EditAnchorResponse2, EditAnchorResponses, EditCallRecordData, EditCallRecordError, EditCallRecordErrors, EditCallRecordRequest, EditCallRecordResponse, EditCallRecordResponses, EditCallTranscriptData, EditCallTranscriptError, EditCallTranscriptErrors, EditCallTranscriptRequest, EditCallTranscriptResponse, EditCallTranscriptResponses, EditCommentData, EditCommentError, EditCommentErrors, EditCommentRequest, EditCommentResponse, EditCommentResponse2, EditCommentResponses, EditCrmCommentData, EditCrmCommentError, EditCrmCommentErrors, EditCrmCommentRequest, EditCrmCommentResponse, EditCrmCommentResponses, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmptyResponse, EnsureCollabSurfaceData, EnsureCollabSurfaceError, EnsureCollabSurfaceErrors, EnsureCollabSurfaceRequest, EnsureCollabSurfaceResponse, EnsureCollabSurfaceResponses, EntityFilters, EntityMessageCreateData, EntityMessageCreateResponse, EntityMessageCreateResponses, EntityMessageDeleteMessageData, EntityMessageDeleteMessageResponse, EntityMessageDeleteMessageResponses, EntityMessageDeleteThreadData, EntityMessageDeleteThreadResponse, EntityMessageDeleteThreadResponses, EntityMessageEditData, EntityMessageEditResponse, EntityMessageEditResponses, EntityMessageGetMessageData, EntityMessageGetMessageResponse, EntityMessageGetMessageResponses, EntityMessageGetThreadData, EntityMessageGetThreadResponse, EntityMessageGetThreadResponses, EntityMessageLegacyData, EntityMessageLegacyResponse, EntityMessageLegacyResponses, EntityMessagePatchThreadData, EntityMessagePatchThreadResponse, EntityMessagePatchThreadResponses, EntityMessageReactData, EntityMessageReactResponse, EntityMessageReactResponses, EntityMessageTypingData, EntityMessageTypingResponse, EntityMessageTypingResponses, EntityPermission, EntityPermissionResponse, EntityReference, EntityType, ErrorResponse, EventReminderOverride, EventReminders, EventStatus, EventTime, EventTransparency, EventType, EventVisibility, ExcludedDefaultView, ExcludeDefaultViewHandlerData, ExcludeDefaultViewHandlerError, ExcludeDefaultViewHandlerErrors, ExcludeDefaultViewHandlerResponses, ExcludeDefaultViewRequest, ExportDocumentData, ExportDocumentError, ExportDocumentErrors, ExportDocumentResponse, ExportDocumentResponse2, ExportDocumentResponses, Favorite, FavoriteEntityRef, FavoritesList, FileSystemNodeWithIds, FileType, FileTypeUpdate, FolderItem, ForeignEntity, ForeignEntityFilters, GenericErrorResponse, GenericResponse, GenericSuccessResponse, GetActiveCallsData, GetActiveCallsError, GetActiveCallsErrors, GetActiveCallsResponse, GetActiveCallsResponses, GetActivityData, GetActivityError, GetActivityErrors, GetActivityResponse, GetActivityResponses, GetAttachmentReferencesData, GetAttachmentReferencesError, GetAttachmentReferencesErrors, GetAttachmentReferencesResponse, GetAttachmentReferencesResponse2, GetAttachmentReferencesResponses, GetBatchCallRecordPreviewData, GetBatchCallRecordPreviewError, GetBatchCallRecordPreviewErrors, GetBatchCallRecordPreviewRequest, GetBatchCallRecordPreviewResponse, GetBatchCallRecordPreviewResponse2, GetBatchCallRecordPreviewResponses, GetBatchChannelPreviewData, GetBatchChannelPreviewError, GetBatchChannelPreviewErrors, GetBatchChannelPreviewRequest, GetBatchChannelPreviewResponse, GetBatchChannelPreviewResponse2, GetBatchChannelPreviewResponses, GetBatchPreviewHandlerData, GetBatchPreviewHandlerError, GetBatchPreviewHandlerErrors, GetBatchPreviewHandlerResponse, GetBatchPreviewHandlerResponses, GetBatchPreviewRequest, GetBatchPreviewResponse, GetBatchProjectPreviewData, GetBatchProjectPreviewError, GetBatchProjectPreviewErrors, GetBatchProjectPreviewRequest, GetBatchProjectPreviewResponse, GetBatchProjectPreviewResponse2, GetBatchProjectPreviewResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, GetChannelMessagesCatchUpData, GetChannelMessagesCatchUpError, GetChannelMessagesCatchUpErrors, GetChannelMessagesCatchUpResponse, GetChannelMessagesCatchUpResponses, GetChannelMessagesData, GetChannelMessagesError, GetChannelMessagesErrors, GetChannelMessagesResponse, GetChannelMessagesResponses, GetChannelParticipantsData, GetChannelParticipantsError, GetChannelParticipantsErrors, GetChannelParticipantsResponse, GetChannelParticipantsResponses, GetChannelResponse, GetChannelResponses, GetChannelsData, GetChannelsError, GetChannelsErrors, GetChannelsResponse, GetChannelsResponses, GetCollabSurfaceData, GetCollabSurfaceError, GetCollabSurfaceErrors, GetCollabSurfaceResponse, GetCollabSurfaceResponses, GetCompanyData, GetCompanyError, GetCompanyErrors, GetCompanyResponse, GetCompanyResponses, GetContactByEmailData, GetContactByEmailError, GetContactByEmailErrors, GetContactByEmailResponse, GetContactByEmailResponse2, GetContactByEmailResponses, GetContactData, GetContactError, GetContactErrors, GetContactResponse, GetContactResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, GetDocumentCommentsData, GetDocumentCommentsError, GetDocumentCommentsErrors, GetDocumentCommentsResponse, GetDocumentCommentsResponses, GetDocumentData, GetDocumentError, GetDocumentErrors, GetDocumentGithubPullRequestsData, GetDocumentGithubPullRequestsError, GetDocumentGithubPullRequestsErrors, GetDocumentGithubPullRequestsResponse, GetDocumentGithubPullRequestsResponses, GetDocumentKeyResponse, GetDocumentKeyResponseData, GetDocumentListHandlerData, GetDocumentListHandlerError, GetDocumentListHandlerErrors, GetDocumentListHandlerResponse, GetDocumentListHandlerResponses, GetDocumentListResult, GetDocumentLocationV3Data, GetDocumentLocationV3Error, GetDocumentLocationV3Errors, GetDocumentLocationV3Response, GetDocumentLocationV3Responses, GetDocumentPermissionsResponseDataV2, GetDocumentPermissionsTokenData, GetDocumentPermissionsTokenError, GetDocumentPermissionsTokenErrors, GetDocumentPermissionsTokenResponse, GetDocumentPermissionsTokenResponses, GetDocumentPermissionsV2Data, GetDocumentPermissionsV2Error, GetDocumentPermissionsV2Errors, GetDocumentPermissionsV2Response, GetDocumentPermissionsV2Responses, GetDocumentProcessingResult, GetDocumentProcessingResultData, GetDocumentProcessingResultError, GetDocumentProcessingResultErrors, GetDocumentProcessingResultResponse, GetDocumentProcessingResultResponse2, GetDocumentProcessingResultResponses, GetDocumentResponse, GetDocumentResponse2, GetDocumentResponseData, GetDocumentResponses, GetDocumentSearchResponse, GetDocumentShortIdData, GetDocumentShortIdError, GetDocumentShortIdErrors, GetDocumentShortIdResponse, GetDocumentShortIdResponses, GetDocumentsResponse, GetDocumentTeamShareData, GetDocumentTeamShareError, GetDocumentTeamShareErrors, GetDocumentTeamShareResponse, GetDocumentTeamShareResponses, GetDocumentUserAccessLevelResponse, GetDocumentVersionData, GetDocumentVersionError, GetDocumentVersionErrors, GetDocumentVersionResponse, GetDocumentVersionResponses, GetDocumentViewsHandlerData, GetDocumentViewsHandlerError, GetDocumentViewsHandlerErrors, GetDocumentViewsHandlerResponse, GetDocumentViewsHandlerResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceError, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponse, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetHarnessPairingData, GetHarnessPairingError, GetHarnessPairingErrors, GetHarnessPairingResponse, GetHarnessPairingResponses, GetHistoryHandlerData, GetHistoryHandlerError, GetHistoryHandlerErrors, GetHistoryHandlerResponse, GetHistoryHandlerResponses, GetInitiativeData, GetInitiativeError, GetInitiativeErrors, GetInitiativeResponse, GetInitiativeResponses, GetInstructionsDocumentResponse, GetInstructionsHandlerData, GetInstructionsHandlerError, GetInstructionsHandlerErrors, GetInstructionsHandlerResponse, GetInstructionsHandlerResponses, GetItemsSoupData, GetItemsSoupError, GetItemsSoupErrors, GetItemsSoupResponse, GetItemsSoupResponses, GetLocationHandlerData, GetLocationHandlerError, GetLocationHandlerErrors, GetLocationHandlerResponse, GetLocationHandlerResponses, GetMessageWithContextData, GetMessageWithContextError, GetMessageWithContextErrors, GetMessageWithContextResponse, GetMessageWithContextResponse2, GetMessageWithContextResponses, GetOrCreateAction, GetOrCreateCallData, GetOrCreateCallError, GetOrCreateCallErrors, GetOrCreateCallResponse, GetOrCreateCallResponses, GetOrCreateChannelResponse, GetOrCreateDmData, GetOrCreateDmError, GetOrCreateDmErrors, GetOrCreateDmRequest, GetOrCreateDmResponse, GetOrCreateDmResponses, GetOrCreatePrivateData, GetOrCreatePrivateError, GetOrCreatePrivateErrors, GetOrCreatePrivateRequest, GetOrCreatePrivateResponse, GetOrCreatePrivateResponses, GetPendingProjectsHandlerData, GetPendingProjectsHandlerError, GetPendingProjectsHandlerErrors, GetPendingProjectsHandlerResponse, GetPendingProjectsHandlerResponses, GetPinsHandlerData, GetPinsHandlerError, GetPinsHandlerErrors, GetPinsHandlerResponse, GetPinsHandlerResponses, GetPinsResponse, GetProjectContentHandlerData, GetProjectContentHandlerError, GetProjectContentHandlerErrors, GetProjectContentHandlerResponse, GetProjectContentHandlerResponses, GetProjectContentResponse, GetProjectHandlerData, GetProjectHandlerError, GetProjectHandlerErrors, GetProjectHandlerResponse, GetProjectHandlerResponses, GetProjectPermissionsV2Data, GetProjectPermissionsV2Error, GetProjectPermissionsV2Errors, GetProjectPermissionsV2Response, GetProjectPermissionsV2Responses, GetProjectResponse, GetProjectResponseData, GetProjectsHandlerData, GetProjectsHandlerError, GetProjectsHandlerErrors, GetProjectsHandlerResponse, GetProjectsHandlerResponses, GetProjectsResponse, GetProjectUserAccessLevelData, GetProjectUserAccessLevelError, GetProjectUserAccessLevelErrors, GetProjectUserAccessLevelResponse, GetProjectUserAccessLevelResponses, GetReminderData, GetReminderError, GetReminderErrors, GetReminderResponse, GetReminderResponses, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessError, GetSelfHarnessErrors, GetSelfHarnessResponse, GetSelfHarnessResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetThreadRepliesData, GetThreadRepliesError, GetThreadRepliesErrors, GetThreadRepliesResponse, GetThreadRepliesResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubPullRequest, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestsResponse, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, Harness, HarnessAgent, HarnessId, HarnessOwner, HarnessSession, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, ImportedAuthor, InFlightTurnSummary, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InitiativeDetail, InitiativeId, InitiativeList, InitiativeSummary, InputReceivedMetadata, InstallSyncData, InstallSyncErrors, InteractionReason, Item, ItemWithUserAccessLevel, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, LatestMessage, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkShare, ListAgentsData, ListAgentsError, ListAgentsErrors, ListAgentsResponse, ListAgentsResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListChannelLabelsData, ListChannelLabelsError, ListChannelLabelsErrors, ListChannelLabelsResponse, ListChannelLabelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmCommentsData, ListCrmCommentsError, ListCrmCommentsErrors, ListCrmCommentsResponse, ListCrmCommentsResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListHarnessAgentsData, ListHarnessAgentsError, ListHarnessAgentsErrors, ListHarnessAgentsResponse, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesError, ListHarnessesErrors, ListHarnessesResponse, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsError, ListHarnessSessionsErrors, ListHarnessSessionsResponse, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesError, ListInitiativesErrors, ListInitiativesResponse, ListInitiativesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListRemindersData, ListRemindersError, ListRemindersErrors, ListRemindersResponse, ListRemindersResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponse, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Mentions, Message, MessageAttachment, MessageChange, MessageCursor, MessageDirection, MessageEvent, MessageListItem, MessagePage, MessageParent, MessagePatch, MessageThread, MessageThreadPreview, MessageTimelineData, MessageTimelineQuery, MessageTimelineResponse, MessageTimelineResponses, NewAttachment, NewChannelAttachment, NewThreadAnchor, NotificationFilters, NotificationState, PairingDetails, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageData, PatchMessageError, PatchMessageErrors, PatchMessageNotificationPolicy, PatchMessageRequest, PatchMessageResponse, PatchMessageResponses, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfAnchorRequest, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PdfPlaceableCommentAnchorRequest, PendingClaimResponse, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostChannelMessagesData, PostChannelMessagesError, PostChannelMessagesErrors, PostChannelMessagesResponse, PostChannelMessagesResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessage, PostMessageData, PostMessageError, PostMessageErrors, PostMessageNotificationPolicy, PostMessageRequest, PostMessageResponse, PostMessageResponse2, PostMessageResponses, PostReactionData, PostReactionError, PostReactionErrors, PostReactionRequest, PostReactionResponse, PostReactionResponses, PostSoupAstRequest, PostSoupRequest, PostTypingData, PostTypingError, PostTypingErrors, PostTypingRequest, PostTypingResponse, PostTypingResponses, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresignedUrl, PreviewSmartTagData, PreviewSmartTagError, PreviewSmartTagErrors, PreviewSmartTagResponse, PreviewSmartTagResponses, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyFilter, PropertyInput, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesError, PutCrmTeamStagesErrors, PutCrmTeamStagesResponse, PutCrmTeamStagesResponses, ReactionAction, ReactionInput, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, Reminder, ReminderFilters, ReminderSchedule, RemindersList, RemoveBotFromChannelByBotData, RemoveBotFromChannelByBotError, RemoveBotFromChannelByBotErrors, RemoveBotFromChannelByBotResponse, RemoveBotFromChannelByBotResponses, RemoveFavoriteByEntityData, RemoveFavoriteByEntityError, RemoveFavoriteByEntityErrors, RemoveFavoriteByEntityResponses, RemoveParticipantsData, RemoveParticipantsError, RemoveParticipantsErrors, RemoveParticipantsRequest, RemoveParticipantsResponses, RemovePinHandlerData, RemovePinHandlerError, RemovePinHandlerErrors, RemovePinHandlerResponse, RemovePinHandlerResponses, RenameChannelLabelData, RenameChannelLabelError, RenameChannelLabelErrors, RenameChannelLabelRequest, RenameChannelLabelResponse, RenameChannelLabelResponses, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ReplaceCrmStagesRequest, RequestedHarnessScope, ResetCrmTeamStagesData, ResetCrmTeamStagesError, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponse, ResetCrmTeamStagesResponses, ResolveChannelMessageData, ResolveChannelMessageError, ResolveChannelMessageErrors, ResolveChannelMessageResponse, ResolveChannelMessageResponses, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, S3ObjectInfo, SaveBomPart, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SessionDeletedMetadata, SessionIdentity, SessionMentionedMetadata, SessionOpenedMetadata, SessionRenamedMetadata, SessionSettledMetadata, SessionStoppedMetadata, SetChannelLabelData, SetChannelLabelError, SetChannelLabelErrors, SetChannelLabelRequest, SetChannelLabelResponse, SetChannelLabelResponses, SetChannelPictureData, SetChannelPictureError, SetChannelPictureErrors, SetChannelPictureRequest, SetChannelPictureResponse, SetChannelPictureResponses, SetCompanyHiddenData, SetCompanyHiddenError, SetCompanyHiddenErrors, SetCompanyHiddenRequest, SetCompanyHiddenResponse, SetCompanyHiddenResponses, SetCompanyNameRequest, SetContactHiddenData, SetContactHiddenError, SetContactHiddenErrors, SetContactHiddenRequest, SetContactHiddenResponse, SetContactHiddenResponses, SetContactNameRequest, SetCrmCompanyNameData, SetCrmCompanyNameError, SetCrmCompanyNameErrors, SetCrmCompanyNameResponse, SetCrmCompanyNameResponses, SetCrmContactNameData, SetCrmContactNameError, SetCrmContactNameErrors, SetCrmContactNameResponse, SetCrmContactNameResponses, SetDocumentTeamShareData, SetDocumentTeamShareError, SetDocumentTeamShareErrors, SetDocumentTeamShareRequest, SetDocumentTeamShareResponse, SetDocumentTeamShareResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetPropertyValue, SharedEmailFilter, SharePermissionV2, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SmartTagChannelMatch, SmartTagPreview, SoupAgentSessionSoupPropertiesField, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmDomain, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupReminderReference, SoupReminderSchedule, SoupReminderSoupPropertiesField, SoupThreadInfo, SoupThreadReply, StarterDocumentsResponse, StreamEventsData, StreamEventsError, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, String, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, TagFilterMode, TaskFilters, TeamOutOfOfficeItem, TeamOutOfOfficeResponse, TeamRole, Thread, ThreadAnchor, ThreadOrigin, ThreadPatch, ThreadResponse, ThreadState, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TranscribeDictationData, TranscribeDictationError, TranscribeDictationErrors, TranscribeDictationResponse, TranscribeDictationResponses, TranscribeResponse, TranscriptSegmentRequest, TurnEndedMetadata, TurnStartedMetadata, TurnSummary, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingAction, TypingInput, UnassignInitiativeTaskData, UnassignInitiativeTaskError, UnassignInitiativeTaskErrors, UnassignInitiativeTaskResponse, UnassignInitiativeTaskResponses, UnthreadedPdfUuidRequest, UpdateAgentData, UpdateAgentError, UpdateAgentErrors, UpdateAgentRequest, UpdateAgentResponse, UpdateAgentResponses, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateInitiativeData, UpdateInitiativeError, UpdateInitiativeErrors, UpdateInitiativeRequest, UpdateInitiativeResponse, UpdateInitiativeResponses, UpdateOperation, UpdateReminderData, UpdateReminderError, UpdateReminderErrors, UpdateReminderRequest, UpdateReminderResponse, UpdateReminderResponses, UpdateSharePermissionRequestV2, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UpsertHistoryHandlerData, UpsertHistoryHandlerError, UpsertHistoryHandlerErrors, UpsertHistoryHandlerResponse, UpsertHistoryHandlerResponses, UpsertUserDocumentViewLocationData, UpsertUserDocumentViewLocationError, UpsertUserDocumentViewLocationErrors, UpsertUserDocumentViewLocationRequest, UpsertUserDocumentViewLocationResponse, UpsertUserDocumentViewLocationResponses, UserApiKeyId, UserApiKeyInfo, UserApiKeysList, UserDocumentsResponse, UserDocumentViewLocation, UserDocumentViewLocationResponse, UserPinsResponse, UserViewsResponse, ValidateDocumentPermissionsTokenData, ValidateDocumentPermissionsTokenError, ValidateDocumentPermissionsTokenErrors, ValidateDocumentPermissionsTokenResponse, ValidateDocumentPermissionsTokenResponses, ValidateWebhookData, ValidateWebhookError, ValidateWebhookErrors, ValidateWebhookResponse, ValidateWebhookResponse2, ValidateWebhookResponses, Vec, View, ViewPatch, ViewsResponse, WaitingForInputMetadata, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';
diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.ts
index f2447ad591..747b8eeea8 100644
--- a/packages/sdk/generated/storage/types.gen.ts
+++ b/packages/sdk/generated/storage/types.gen.ts
@@ -4968,8 +4968,7 @@ export type DocumentSubType = 'task' | 'snippet' | 'skill' | 'initiative_descrip
*/
export type DocumentSyncContentUpdatedMetadata = {
/**
- * Who mechanically changed the content. Absent on events published
- * before attribution, and on human-only collab sessions.
+ * Legacy single-editor attribution; newer Sync callers send `editors`.
*/
actor?: string | null;
/**
@@ -4980,6 +4979,10 @@ export type DocumentSyncContentUpdatedMetadata = {
* Version marker for the sync snapshot, when the caller supplies one.
*/
document_version_id?: string | null;
+ /**
+ * Distinct editors since the preceding snapshot notification.
+ */
+ editors?: Array<DocumentSyncEditor>;
/**
* File type of the sync document, resolved by the document backend.
*/
@@ -4987,6 +4990,17 @@ export type DocumentSyncContentUpdatedMetadata = {
on_behalf_of?: null | MacroUserIdStr;
};
+/**
+ * An editor reported by Sync from an authenticated session.
+ */
+export type DocumentSyncEditor = {
+ /**
+ * User or bot that performed the edit.
+ */
+ actor: string;
+ on_behalf_of?: null | MacroUserIdStr;
+};
+
/**
* The team-share state of a document. The team is resolved from the document
* owner's team membership.
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index 3f5978a42c..cf75b9ea5b 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -21822,7 +21822,7 @@
"properties": {
"actor": {
"type": ["string", "null"],
- "description": "Who mechanically changed the content. Absent on events published\nbefore attribution, and on human-only collab sessions."
+ "description": "Legacy single-editor attribution; newer Sync callers send `editors`."
},
"document_id": {
"type": "string",
@@ -21832,6 +21832,13 @@
"type": ["string", "null"],
"description": "Version marker for the sync snapshot, when the caller supplies one."
},
+ "editors": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/DocumentSyncEditor"
+ },
+ "description": "Distinct editors since the preceding snapshot notification."
+ },
"file_type": {
"$ref": "#/components/schemas/FileType",
"description": "File type of the sync document, resolved by the document backend."
@@ -21849,6 +21856,28 @@
}
}
},
+ "DocumentSyncEditor": {
+ "type": "object",
+ "description": "An editor reported by Sync from an authenticated session.",
+ "required": ["actor"],
+ "properties": {
+ "actor": {
+ "type": "string",
+ "description": "User or bot that performed the edit."
+ },
+ "on_behalf_of": {
+ "oneOf": [
+ {
+ "type": "null"
+ },
+ {
+ "$ref": "#/components/schemas/MacroUserIdStr",
+ "description": "User represented by an agent, if any."
+ }
+ ]
+ }
+ }
+ },
"DocumentTeamShareResponse": {
"type": "object",
"description": "The team-share state of a document. The team is resolved from the document\nowner's team membership.",
diff --git a/services/document_storage_service/src/main.rs b/services/document_storage_service/src/main.rs
index 39ec992b2c..b9b35e6f50 100644
--- a/services/document_storage_service/src/main.rs
+++ b/services/document_storage_service/src/main.rs
@@ -876,6 +876,11 @@ async fn run() -> anyhow::Result<()> {
});
let activity_consumer_brokers = config.kafka_brokers.as_ref().to_string();
+ let editing_activity = Arc::new(
+ documents_hex::outbound::editing_activity::RedisEditingActivityStore::new(
+ redis_client.clone(),
+ ),
+ );
consumer_tracker.spawn({
let cancellation_token = consumer_cancellation_token.clone();
let activity_repo = activity::outbound::pg_activity_repo::PgActivityRepo::new(db.clone());
@@ -893,7 +898,12 @@ async fn run() -> anyhow::Result<()> {
_,
>::new(
activity_repo,
- crate::service::activity::ingest,
+ move |event| {
+ let editing_activity = editing_activity.clone();
+ async move {
+ crate::service::activity::ingest(event, editing_activity.as_ref()).await
+ }
+ },
activity_realtime,
);
loop {
diff --git a/services/document_storage_service/src/service/activity.rs b/services/document_storage_service/src/service/activity.rs
index 11cec64c48..33820215b8 100644
--- a/services/document_storage_service/src/service/activity.rs
+++ b/services/document_storage_service/src/service/activity.rs
@@ -32,16 +32,27 @@ mod source {
}
pub(crate) use source::ActivitySourceEvent;
-/// Dispatches one decoded event to its domain's [`ActivitySource`] impl —
-/// every arm is the identical expression; all semantics live with the
-/// domains.
-pub(crate) fn ingest(event: &ActivitySourceEvent) -> Ingest {
+/// Dispatches each event to its owning domain. Document editing sessions use
+/// the shared inactivity store; all classification and debounce policy stays
+/// in the documents domain.
+pub(crate) async fn ingest(
+ event: ActivitySourceEvent,
+ editing_activity: &impl documents_hex::domain::ports::EditingActivityStore,
+) -> Ingest {
fn arm<E: activity::ActivitySource>(envelope: &macro_event_broker::Event<E>) -> Ingest {
envelope.event.ingest(envelope.event_id)
}
match event {
- ActivitySourceEvent::DocumentMacroEvent(e) => arm(e.event()),
+ ActivitySourceEvent::DocumentMacroEvent(e) => {
+ let envelope = e.event();
+ documents_hex::domain::activity::ingest_with_editing_sessions(
+ &envelope.event,
+ envelope.event_id,
+ editing_activity,
+ )
+ .await
+ }
ActivitySourceEvent::ChannelMacroEvent(e) => arm(e.event()),
ActivitySourceEvent::ChatMacroEvent(e) => arm(e.event()),
ActivitySourceEvent::ProjectMacroEvent(e) => arm(e.event()),
diff --git a/services/search_processing_service/src/api/internal/extract_sync/test.rs b/services/search_processing_service/src/api/internal/extract_sync/test.rs
index 6c1c237b48..8d6cd9c7ac 100644
--- a/services/search_processing_service/src/api/internal/extract_sync/test.rs
+++ b/services/search_processing_service/src/api/internal/extract_sync/test.rs
@@ -28,6 +28,7 @@ fn documents_map_to_events_with_matching_keys_and_exact_metadata() {
assert_eq!(
events[0].event().event,
DocumentTopicEvent::SyncContentUpdated(DocumentSyncContentUpdatedMetadata {
+ editors: Vec::new(),
document_id: "document-a".to_string(),
file_type: FileType::Md,
document_version_id: Some("version-42".to_string()),
@@ -39,6 +40,7 @@ fn documents_map_to_events_with_matching_keys_and_exact_metadata() {
assert_eq!(
events[1].event().event,
DocumentTopicEvent::SyncContentUpdated(DocumentSyncContentUpdatedMetadata {
+ editors: Vec::new(),
document_id: "document-b".to_string(),
file_type: FileType::Pdf,
document_version_id: None,
diff --git a/services/search_processing_service/src/inbound/kafka_consumer/test.rs b/services/search_processing_service/src/inbound/kafka_consumer/test.rs
index 3cf15ebc61..0423370f6c 100644
--- a/services/search_processing_service/src/inbound/kafka_consumer/test.rs
+++ b/services/search_processing_service/src/inbound/kafka_consumer/test.rs
@@ -919,6 +919,7 @@ fn document_event_cases() -> Vec<(DocumentTopicEvent, DocumentEventDescription)>
),
(
DocumentTopicEvent::SyncContentUpdated(DocumentSyncContentUpdatedMetadata {
+ editors: Vec::new(),
document_id: DOCUMENT_ID.to_string(),
file_type: FileType::Md,
document_version_id: None,
@@ -1423,6 +1424,7 @@ fn document_extraction_actions_preserve_optional_versions() {
let sync_content_updated =
DocumentTopicEvent::SyncContentUpdated(DocumentSyncContentUpdatedMetadata {
+ editors: Vec::new(),
document_id: DOCUMENT_ID.to_string(),
file_type: FileType::Md,
document_version_id: Some("snapshot-7".to_string()),
@@ -1785,6 +1787,7 @@ fn exact_macro_documents_envelopes_decode_into_document_events() {
Event::with_event_id(
Uuid::from_u128(2),
DocumentTopicEvent::SyncContentUpdated(DocumentSyncContentUpdatedMetadata {
+ editors: Vec::new(),
document_id: DOCUMENT_ID.to_string(),
file_type: FileType::Md,
document_version_id: None,
diff --git a/services/sync-service/README.md b/services/sync-service/README.md
index eb8ac6c3b9..7429fae497 100644
--- a/services/sync-service/README.md
+++ b/services/sync-service/README.md
@@ -154,3 +154,22 @@ CRDT roots or labels updates as Markdown. The `search-service` feature continues
to control these notifications for compatibility with existing build commands.
Deploy DSS first, then roll out Sync and the AI editing worker together.
+
+Content edits collect the editing socket's verified actor, or its user ID for
+human editors, in an in-memory list. Existing snapshot/search notifications
+flush distinct editors to DSS; collecting an editor adds no storage writes,
+network requests, background tasks, or timers to Sync. Anonymous edits,
+duplicate updates, and idle peers do not add editors.
+
+DSS's independent Activity consumer records one event at the start of editing
+and refreshes a shared five-minute inactivity window on each subsequent batch.
+An edit after five quiet minutes starts another session. Timing follows the
+existing snapshot notification cadence. Redis or notification failures may drop
+Activity hints; they never block document saving or search extraction. If Redis
+applies a session refresh before timing out, that session can remain suppressed
+without an Activity row until five minutes of inactivity. This is an accepted
+best-effort delivery limit, rather than a reason to retry or emit on every batch.
+
+Deploy DSS before Sync to enable Activity hints immediately. If an older DSS
+rejects the optional `editors` field, Sync retries once without it so search
+continues working. Old Sync requests and old Kafka events remain supported.
diff --git a/services/sync-service/src/domain/document.rs b/services/sync-service/src/domain/document.rs
index d86d21f5a1..e1c56cc2bd 100644
--- a/services/sync-service/src/domain/document.rs
+++ b/services/sync-service/src/domain/document.rs
@@ -63,13 +63,36 @@ pub struct PreparedUpdate {
}
/// Signed-token attribution stored alongside the existing operation log.
-#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
+#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, serde::Serialize)]
pub struct DocumentAttribution {
pub actor: String,
pub on_behalf_of: Option<String>,
}
impl DocumentAttribution {
+ /// Resolve only verified session claims. Human edits are direct actions;
+ /// an explicit agent actor retains the user it is acting on behalf of.
+ pub fn from_session_claims(
+ actor: Option<String>,
+ user_id: Option<String>,
+ ) -> Result<Option<Self>, DocumentError> {
+ match (actor, user_id) {
+ (Some(actor), user_id) => Self::from_signed_claims(actor, user_id).map(Some),
+ (None, Some(user_id)) => {
+ // Human identities retain the user-claim bound; long valid
+ // email addresses can exceed the explicit agent-actor bound.
+ if user_id.len() > 1024 {
+ return Err(DocumentError::Invalid("Invalid signed attribution."));
+ }
+ Ok(Some(Self {
+ actor: user_id,
+ on_behalf_of: None,
+ }))
+ }
+ (None, None) => Ok(None),
+ }
+ }
+
pub fn from_signed_claims(
actor: String,
on_behalf_of: Option<String>,
diff --git a/services/sync-service/src/domain/document/test.rs b/services/sync-service/src/domain/document/test.rs
index 00a2719567..d9830b2c9c 100644
--- a/services/sync-service/src/domain/document/test.rs
+++ b/services/sync-service/src/domain/document/test.rs
@@ -272,3 +272,44 @@ fn notification_failure_preserves_durable_update_and_allows_idempotent_retry() {
assert!(!retried.applied);
assert_eq!(*port.calls.borrow(), ["persist", "broadcast", "keep_alive"]);
}
+
+#[test]
+fn session_attribution_uses_the_verified_human_or_agent_identity() {
+ let long_user = format!(
+ "macro|{}@{}.{}.{}",
+ "a".repeat(64),
+ "b".repeat(63),
+ "c".repeat(63),
+ "d".repeat(61)
+ );
+ assert_eq!(long_user.len(), 260);
+ assert_eq!(
+ DocumentAttribution::from_session_claims(None, Some(long_user.clone()))
+ .unwrap()
+ .unwrap()
+ .actor,
+ long_user
+ );
+
+ let user = "macro|[email protected]".to_string();
+ assert_eq!(
+ DocumentAttribution::from_session_claims(None, Some(user.clone())).unwrap(),
+ Some(DocumentAttribution {
+ actor: user.clone(),
+ on_behalf_of: None
+ })
+ );
+ assert_eq!(
+ DocumentAttribution::from_session_claims(Some("bot|agent".into()), Some(user.clone()))
+ .unwrap(),
+ Some(DocumentAttribution {
+ actor: "bot|agent".into(),
+ on_behalf_of: Some(user)
+ })
+ );
+ assert_eq!(
+ DocumentAttribution::from_session_claims(None, None).unwrap(),
+ None
+ );
+ assert!(DocumentAttribution::from_session_claims(None, Some("x".repeat(1025))).is_err());
+}
diff --git a/services/sync-service/src/dss_internal.rs b/services/sync-service/src/dss_internal.rs
index 6e7ed62334..a0d78f1601 100644
--- a/services/sync-service/src/dss_internal.rs
+++ b/services/sync-service/src/dss_internal.rs
@@ -41,7 +41,7 @@ pub trait DssInternal {
async fn publish_sync_content_updated(
&self,
document_id: &str,
- attribution: Option<DocumentAttribution>,
+ editors: Vec<DocumentAttribution>,
) -> worker::Result<()>;
}
@@ -74,37 +74,46 @@ impl DssInternal for DssInternalClient<'_> {
async fn publish_sync_content_updated(
&self,
document_id: &str,
- attribution: Option<DocumentAttribution>,
+ editors: Vec<DocumentAttribution>,
) -> worker::Result<()> {
let url = format!(
"{}/internal/documents/{document_id}/sync-content-updated",
self.dss_url()?,
);
- let body = serde_json::json!({
- "actor": attribution.as_ref().map(|value| &value.actor),
- "on_behalf_of": attribution.as_ref().and_then(|value| value.on_behalf_of.as_ref()),
- });
- let mut request = Request::new_with_init(
- &url,
- RequestInit::new()
- .with_method(Method::Post)
- .with_body(Some(body.to_string().into())),
- )?;
- request.headers_mut()?.set(
- MACRO_DOCUMENT_STORAGE_SERVICE_AUTH_HEADER_KEY,
- &self.internal_auth_key()?,
- )?;
- request
- .headers_mut()?
- .set("Content-Type", "application/json")?;
- let response = Fetch::Request(request).send().await?;
- if response.status_code() != 200 {
- return Err(worker::Error::from(format!(
- "DSS sync-content notification returned {}",
- response.status_code()
- )));
+ let mut body = if editors.is_empty() {
+ serde_json::json!({})
+ } else {
+ serde_json::json!({ "editors": editors })
+ };
+ loop {
+ let mut request = Request::new_with_init(
+ &url,
+ RequestInit::new()
+ .with_method(Method::Post)
+ .with_body(Some(body.to_string().into())),
+ )?;
+ request.headers_mut()?.set(
+ MACRO_DOCUMENT_STORAGE_SERVICE_AUTH_HEADER_KEY,
+ &self.internal_auth_key()?,
+ )?;
+ request
+ .headers_mut()?
+ .set("Content-Type", "application/json")?;
+ let response = Fetch::Request(request).send().await?;
+ match response.status_code() {
+ 200 => return Ok(()),
+ 422 if body.get("editors").is_some() => {
+ // Older DSS rejects unknown fields. Preserve search during
+ // mixed-version deployments by dropping optional activity hints.
+ body = serde_json::json!({});
+ }
+ status => {
+ return Err(worker::Error::from(format!(
+ "DSS sync-content notification returned {status}",
+ )));
+ }
+ }
}
- Ok(())
}
async fn publish_shallow_snapshot(
diff --git a/services/sync-service/src/durable_object.rs b/services/sync-service/src/durable_object.rs
index 4ab6d9635a..ba0e2db0fd 100644
--- a/services/sync-service/src/durable_object.rs
+++ b/services/sync-service/src/durable_object.rs
@@ -53,7 +53,7 @@ mod document_effects;
mod surface_api;
pub(crate) mod surface_migration;
-use document_effects::{CloseFlush, report_interaction, report_new_doc_state};
+use document_effects::{report_interaction, report_new_doc_state};
use surface_api::{SurfaceLifecycle, session_kind_from_storage_key};
mod path {
@@ -123,22 +123,6 @@ pub struct WebSocketMetadata {
pub type WsMetaMap = BTreeMap<String, WebSocketMetadata>;
-/// Attribution from currently-connected websocket metadata only.
-///
-/// Closed sockets must not contribute an `actor`: the isolate stays warm while
-/// anyone is connected, so a disconnected AI peer would otherwise keep
-/// attributing later human edits.
-fn edit_attribution_from_meta<'a>(
- metas: impl IntoIterator<Item = &'a WebSocketMetadata>,
-) -> Option<DocumentAttribution> {
- metas.into_iter().find_map(|meta| {
- meta.actor.clone().map(|actor| DocumentAttribution {
- actor,
- on_behalf_of: meta.user_id.clone(),
- })
- })
-}
-
#[durable_object]
pub struct DocumentSyncSession {
state: State,
@@ -155,6 +139,8 @@ pub struct DocumentSyncSession {
msg_buffer: Arc<Mutex<Vec<u8>>>,
/// Buffered blame events. Flushed via D1 batch on each alarm tick.
pending_blame: Arc<Mutex<Vec<crate::d1::BlameEvent>>>,
+ /// Distinct editors since the last snapshot notification.
+ pending_editors: Arc<Mutex<BTreeSet<DocumentAttribution>>>,
surface_lifecycle: Mutex<Option<SurfaceLifecycle>>,
source_migration: Mutex<Option<surface_migration::SourceState>>,
// Serialize whole callbacks, including persistence awaits. A freeze must
@@ -203,73 +189,6 @@ mod u64_serde_strings {
}
}
-#[cfg(test)]
-mod actor_attribution_test {
- use super::{
- AccessLevel, CloseFlush, DocumentAttribution, SessionKind, WebSocketMetadata,
- edit_attribution_from_meta,
- };
-
- fn meta(actor: Option<&str>, user_id: Option<&str>) -> WebSocketMetadata {
- WebSocketMetadata {
- user_id: user_id.map(str::to_string),
- access_level: AccessLevel::Edit,
- actor: actor.map(str::to_string),
- peer_ids: Default::default(),
- session_kind: SessionKind::Document,
- expires_at: None,
- }
- }
-
- #[test]
- fn ignores_sockets_without_an_actor() {
- let human = meta(None, Some("macro|[email protected]"));
- assert_eq!(edit_attribution_from_meta([&human]), None);
- }
-
- #[test]
- fn uses_the_connected_actor_and_its_user() {
- let stale = meta(Some("bot|stale"), Some("macro|[email protected]"));
- let human = meta(None, Some("macro|[email protected]"));
- assert_eq!(
- edit_attribution_from_meta([&human]),
- None,
- "closed AI metadata must not be consulted"
- );
- assert_eq!(
- edit_attribution_from_meta([&stale, &human]),
- Some(DocumentAttribution {
- actor: "bot|stale".to_string(),
- on_behalf_of: Some("macro|[email protected]".to_string()),
- })
- );
- }
-
- #[test]
- fn close_flushes_on_last_leave_or_when_the_actor_leaves_with_pending_edits() {
- assert_eq!(
- CloseFlush::decide(false, true, true),
- Some(CloseFlush::ActorLeft),
- "AI leave while a human stays must flush pending edits"
- );
- assert_eq!(
- CloseFlush::decide(false, false, true),
- None,
- "human leave while the AI stays must not flush"
- );
- assert_eq!(
- CloseFlush::decide(true, true, true),
- Some(CloseFlush::LastLeave),
- "last-leave publishes one attributed snapshot"
- );
- assert_eq!(
- CloseFlush::decide(true, false, false),
- Some(CloseFlush::LastLeave)
- );
- assert_eq!(CloseFlush::decide(false, true, false), None);
- }
-}
-
pub struct Wsm<'a> {
dss: &'a DocumentSyncSession,
ws: &'a WebSocket,
@@ -328,6 +247,15 @@ impl<'a> Wsm<'a> {
.collect())
}
+ pub async fn edit_attribution(&mut self) -> Result<Option<DocumentAttribution>> {
+ self.maybe_update_ws_meta_map().await?;
+ let ws_id = self.get_ws_id()?.to_string();
+ let map = self.dss.ws_meta_map.lock("Wsm::edit_attribution");
+ let meta = map.get(&ws_id).context("missing ws metadata")?;
+ DocumentAttribution::from_session_claims(meta.actor.clone(), meta.user_id.clone())
+ .context("invalid signed websocket attribution")
+ }
+
pub async fn can_edit(&mut self) -> Result<bool> {
self.maybe_update_ws_meta_map().await?;
let ws_id = self.get_ws_id()?.to_string();
@@ -388,32 +316,23 @@ async fn bump_alarm(state: &State) -> Result<()> {
Ok(())
}
+fn take_editors(editors: &Mutex<BTreeSet<DocumentAttribution>>) -> Vec<DocumentAttribution> {
+ std::mem::take(&mut *editors.lock("take document editors"))
+ .into_iter()
+ .collect()
+}
+
impl DocumentSyncSession {
pub fn get_websockets(&self) -> Vec<WebSocket> {
self.active_websockets()
}
- fn edit_attribution(&self) -> Option<DocumentAttribution> {
- let connected: BTreeSet<String> = self
- .state
- .get_websockets()
- .iter()
- .filter_map(|ws| get_ws_id(&self.state, ws).ok())
- .collect();
- let map = self
- .ws_meta_map
- .lock("DocumentSyncSession::edit_attribution");
- edit_attribution_from_meta(connected.iter().filter_map(|ws_id| map.get(ws_id)))
- }
-
- fn websocket_has_actor(&self, ws: &WebSocket) -> bool {
- let Ok(ws_id) = get_ws_id(&self.state, ws) else {
- return false;
- };
- self.ws_meta_map
- .lock("DocumentSyncSession::websocket_has_actor")
- .get(&ws_id)
- .is_some_and(|meta| meta.actor.is_some())
+ pub(crate) fn record_editor(&self, attribution: Option<&DocumentAttribution>) {
+ if let Some(attribution) = attribution {
+ self.pending_editors
+ .lock("record document editor")
+ .insert(attribution.clone());
+ }
}
async fn forget_websocket_metadata(&self, ws: &WebSocket) {
@@ -607,9 +526,8 @@ impl DocumentSyncSession {
}
let document_id_owned = document_id.to_string();
let env = self.env.clone();
- let attribution = self.edit_attribution();
self.state.wait_until(async move {
- report_new_doc_state(&document_id_owned, &snapshot, &env, attribution).await;
+ report_new_doc_state(&document_id_owned, &snapshot, &env, Vec::new()).await;
});
}
@@ -1075,6 +993,7 @@ impl DurableObject for DocumentSyncSession {
ws_meta_map: Arc::new(Mutex::new(Default::default())),
msg_buffer: Arc::new(Mutex::new(vec![])),
pending_blame: Arc::new(Mutex::new(Vec::new())),
+ pending_editors: Arc::new(Mutex::new(Default::default())),
surface_lifecycle: Mutex::new(None),
source_migration: Mutex::new(None),
mutation_barrier: futures::lock::Mutex::new(()),
@@ -1258,13 +1177,14 @@ impl DurableObject for DocumentSyncSession {
state.mark_exported();
let document_id = self.document_id().await.ok();
+ let pending_editors = self.pending_editors.clone();
let env = self.env.clone();
- let attribution = self.edit_attribution();
self.state.wait_until(async move {
if let Some(document_id) = document_id
&& let Ok(snapshot) = doc_state.export_shallow_snapshot()
{
- report_new_doc_state(&document_id, &snapshot, &env, attribution).await;
+ let editors = take_editors(&pending_editors);
+ report_new_doc_state(&document_id, &snapshot, &env, editors).await;
report_interaction(&document_id, &env, InteractionReason::Edited).await;
}
});
@@ -1320,27 +1240,16 @@ impl DurableObject for DocumentSyncSession {
.context("failed to broadcast awareness")?;
}
- // The closing socket still counts as connected here, so its actor
- // is still part of the attribution.
- let state = self.document_state().await.ok();
- let flush = CloseFlush::decide(
- self.state.get_websockets().len() == 1,
- self.websocket_has_actor(&ws),
- state.as_ref().is_some_and(|s| s.should_save()),
- );
- if let Some(flush) = flush
- && let Some(state) = state
+ if self.state.get_websockets().len() == 1
+ && let Ok(state) = self.document_state().await
&& let Ok(document_id) = self.document_id().await
&& let Ok(snapshot) = state.export_shallow_snapshot()
{
- if flush == CloseFlush::ActorLeft {
- state.mark_exported();
- }
- let attribution = self.edit_attribution();
+ let editors = take_editors(&self.pending_editors);
let env = self.env.clone();
self.state.wait_until(async move {
- report_new_doc_state(&document_id, &snapshot, &env, attribution).await;
- report_interaction(&document_id, &env, flush.interaction_reason()).await;
+ report_new_doc_state(&document_id, &snapshot, &env, editors).await;
+ report_interaction(&document_id, &env, InteractionReason::LastLeave).await;
});
}
self.forget_websocket_metadata(&ws).await;
diff --git a/services/sync-service/src/durable_object/document_api.rs b/services/sync-service/src/durable_object/document_api.rs
index b0160d2194..4d2c5a60bd 100644
--- a/services/sync-service/src/durable_object/document_api.rs
+++ b/services/sync-service/src/durable_object/document_api.rs
@@ -112,30 +112,26 @@ impl DocumentSyncSession {
};
let state = self.document_state().await?;
let storage = self.session_storage().await?;
- let attribution = match claims
- .actor
- .as_ref()
- .map(|actor| {
- document::DocumentAttribution::from_signed_claims(
- actor.clone(),
- claims.user_id.clone(),
- )
- })
- .transpose()
- {
- Ok(attribution) => attribution,
+ // Only agent actors are stored with the operation; humans are still editors.
+ let is_agent = claims.actor.is_some();
+ let editor = match document::DocumentAttribution::from_session_claims(
+ claims.actor,
+ claims.user_id,
+ ) {
+ Ok(editor) => editor,
Err(error) => return error_response(error),
};
+ let stored_attribution = if is_agent { editor.as_ref() } else { None };
let port = DocumentUpdateStorage {
document_state: &state,
storage: &storage,
- attribution: attribution.as_ref(),
+ attribution: stored_attribution,
};
let effects = WorkerDocumentEffects {
session: self,
document_state: &state,
document_id,
- attribution: attribution.as_ref(),
+ attribution: editor.as_ref(),
};
// The service synchronously compares + validates + imports before its
// first storage await, just like a websocket update in this isolate.
diff --git a/services/sync-service/src/durable_object/document_effects.rs b/services/sync-service/src/durable_object/document_effects.rs
index 84d338ad22..6e5fa2b54c 100644
--- a/services/sync-service/src/durable_object/document_effects.rs
+++ b/services/sync-service/src/durable_object/document_effects.rs
@@ -5,49 +5,15 @@ use macro_sync_service_jwt::session::SessionKind;
use tracing::{error, warn};
use worker::Env;
-use super::{DocumentSyncSession, bump_alarm, surface_api::session_kind_from_storage_key};
+use super::{
+ DocumentSyncSession, bump_alarm, surface_api::session_kind_from_storage_key, take_editors,
+};
use crate::{
domain::document::{DocumentAttribution, DocumentError, DocumentUpdateEffects},
dss_internal::{DssInternal, DssInternalClient, InteractionReason},
state::DocumentState,
};
-/// Why a snapshot is published from `websocket_close`.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub(super) enum CloseFlush {
- /// The last peer left; the pre-attribution snapshot-on-idle behaviour.
- LastLeave,
- /// The attributed peer left while humans stay. Publish pending edits while
- /// its metadata still supplies the actor, before the next unattributed alarm.
- ActorLeft,
-}
-
-impl CloseFlush {
- /// A human leaving while the actor stays never flushes: the next alarm
- /// still has the actor, and flushing here would `mark_exported` and then
- /// republish the same content on last-leave.
- pub(super) fn decide(
- is_last_leave: bool,
- leaving_socket_has_actor: bool,
- should_save: bool,
- ) -> Option<Self> {
- if is_last_leave {
- Some(Self::LastLeave)
- } else if leaving_socket_has_actor && should_save {
- Some(Self::ActorLeft)
- } else {
- None
- }
- }
-
- pub(super) fn interaction_reason(self) -> InteractionReason {
- match self {
- Self::LastLeave => InteractionReason::LastLeave,
- Self::ActorLeft => InteractionReason::Edited,
- }
- }
-}
-
/// All document-only effects pass through this boundary, including socket joins,
/// initialization, alarms, HTTP updates and disconnects. The persisted storage key
/// is a kind-discriminated identity; surface keys never reach document consumers.
@@ -55,7 +21,7 @@ pub(super) async fn report_new_doc_state(
session_key: &str,
snapshot: &[u8],
env: &Env,
- attribution: Option<DocumentAttribution>,
+ editors: Vec<DocumentAttribution>,
) {
if session_kind_from_storage_key(session_key) != SessionKind::Document {
return;
@@ -68,7 +34,7 @@ pub(super) async fn report_new_doc_state(
}
#[cfg(feature = "search-service")]
if let Err(error) = DssInternalClient::new(env)
- .publish_sync_content_updated(session_key, attribution)
+ .publish_sync_content_updated(session_key, editors)
.await
{
warn!(error = ?error, "failed to publish document content change");
@@ -117,15 +83,16 @@ impl DocumentUpdateEffects for WorkerDocumentEffects<'_> {
}
fn publish_changed_document(&self) -> Result<(), DocumentError> {
- let attribution = self.attribution.cloned();
+ self.session.record_editor(self.attribution);
let snapshot = self
.document_state
.export_shallow_snapshot()
.map_err(notification_error)?;
+ let editors = take_editors(&self.session.pending_editors);
let env = self.session.env.clone();
let document_id = self.document_id.to_owned();
self.session.state.wait_until(async move {
- report_new_doc_state(&document_id, &snapshot, &env, attribution).await;
+ report_new_doc_state(&document_id, &snapshot, &env, editors).await;
report_interaction(&document_id, &env, InteractionReason::Edited).await;
});
Ok(())
diff --git a/services/sync-service/src/state.rs b/services/sync-service/src/state.rs
index 9e4933bd68..da75cc86f3 100644
--- a/services/sync-service/src/state.rs
+++ b/services/sync-service/src/state.rs
@@ -16,6 +16,14 @@ const FROM_CLIENT_TAG: &str = "from_client";
const FROM_SERVICE_TAG: &str = "from_service";
const FRONTIERS_ID_SEPERATOR: &str = "|";
+/// Result of applying an update, before any persistence awaits.
+pub struct ImportedUpdate {
+ /// Whether the operation log gained new operations.
+ pub changed: bool,
+ /// Lexical node IDs used by the existing blame tracking.
+ pub touched_nodes: Vec<String>,
+}
+
#[derive(Debug)]
pub struct DocumentState {
pub loro_doc: LoroDoc,
@@ -89,9 +97,9 @@ impl DocumentState {
.unwrap_context("last_export mutex poisoned") = Some(Instant::now());
}
- /// Import an update into the document. Returns the set of Lexical node IDs
- /// whose backing Loro containers were touched, deduplicated.
- pub fn import(&self, update: &[u8]) -> Result<Vec<String>> {
+ /// Import an update and report whether it changed the operation log plus
+ /// the deduplicated Lexical node IDs used by blame tracking.
+ pub fn import(&self, update: &[u8]) -> Result<ImportedUpdate> {
let before = self.loro_doc.oplog_frontiers();
self.loro_doc
.import_with(update, FROM_CLIENT_TAG)
@@ -103,7 +111,10 @@ impl DocumentState {
.lock()
.unwrap_context("last_update mutex poisoned") = Some(Instant::now());
- Ok(self.touched_lexical_ids(&before, &after))
+ Ok(ImportedUpdate {
+ changed: before != after,
+ touched_nodes: self.touched_lexical_ids(&before, &after),
+ })
}
/// Diff the two frontiers and return the Lexical node IDs whose backing
@@ -237,7 +248,13 @@ mod tests {
})
.unwrap();
- state.import(update.as_slice()).unwrap();
+ let imported = state.import(update.as_slice()).unwrap();
+ assert!(imported.changed);
+ assert!(
+ imported.touched_nodes.is_empty(),
+ "plain text has no Lexical IDs"
+ );
+ assert!(!state.import(update.as_slice()).unwrap().changed);
let text = state.loro_doc.get_text("content");
assert_eq!(text.to_string(), "01234");
diff --git a/services/sync-service/src/storage.rs b/services/sync-service/src/storage.rs
index c910627320..e1fc6d7b07 100644
--- a/services/sync-service/src/storage.rs
+++ b/services/sync-service/src/storage.rs
@@ -5,7 +5,9 @@ use tracing::trace;
use worker::{Env, Error, Result, State};
use crate::{
- state::DocumentState, storage::backends::durable_kv::DurableKVStorage, timeit, timeit_log,
+ state::{DocumentState, ImportedUpdate},
+ storage::backends::durable_kv::DurableKVStorage,
+ timeit, timeit_log,
};
pub mod backends;
@@ -119,13 +121,12 @@ impl SessionStorage {
Ok(res)
}
- /// Append a new pending operation to the operation log and return the
- /// Lexical node IDs that were touched (for blame tracking).
+ /// Persist an update and return its change status and touched Lexical nodes.
pub async fn append_pending_operation(
&self,
operation: &[u8],
document_state: &DocumentState,
- ) -> Result<Vec<String>> {
+ ) -> Result<ImportedUpdate> {
self.oplog.apply_op(document_state, operation).await
}
diff --git a/services/sync-service/src/storage/backends/durable_kv.rs b/services/sync-service/src/storage/backends/durable_kv.rs
index 025c532c60..469244fbe3 100644
--- a/services/sync-service/src/storage/backends/durable_kv.rs
+++ b/services/sync-service/src/storage/backends/durable_kv.rs
@@ -14,7 +14,10 @@ use worker::{
wasm_bindgen::JsCast,
};
-use crate::{error::ResultExt, state::DocumentState};
+use crate::{
+ error::ResultExt,
+ state::{DocumentState, ImportedUpdate},
+};
/// When saving snapshot, we also write the version vector to durable object KV
/// When we read a snapshot from Worker KV, we check it's version vector is >= version vector in LAST_VERSION_VECTOR.
@@ -97,7 +100,7 @@ impl DurableKVStorage {
&self,
document_state: &DocumentState,
op_update: &[u8],
- ) -> Result<Vec<String>> {
+ ) -> Result<ImportedUpdate> {
self.apply_op_with_attribution(document_state, op_update, None)
.await
}
@@ -109,10 +112,10 @@ impl DurableKVStorage {
document_state: &DocumentState,
op_update: &[u8],
attribution: Option<&crate::domain::document::DocumentAttribution>,
- ) -> Result<Vec<String>> {
+ ) -> Result<ImportedUpdate> {
let op_id = self.ids.id();
let op_key = pending_op_key(&op_id);
- let touched_nodes = document_state.import(op_update)?;
+ let imported = document_state.import(op_update)?;
self.inner.put(&op_key, op_update).await?;
self.applied_keys
.write()
@@ -124,7 +127,7 @@ impl DurableKVStorage {
.context("failed to serialize signed document attribution")?;
self.inner.put(&format!("actor/{op_id}"), metadata).await?;
}
- Ok(touched_nodes)
+ Ok(imported)
}
pub async fn apply_pending_ops(&self, snapshot: &DocumentState) -> Result<()> {
diff --git a/services/sync-service/src/websocket.rs b/services/sync-service/src/websocket.rs
index aec4f53fc4..09fba2757b 100644
--- a/services/sync-service/src/websocket.rs
+++ b/services/sync-service/src/websocket.rs
@@ -225,6 +225,13 @@ pub async fn process_message(
return Ok(());
}
+ let attribution = match Wsm::new(dss, ws).edit_attribution().await {
+ Ok(attribution) => attribution,
+ Err(error) => {
+ tracing::warn!(error = ?error, "failed to resolve optional edit attribution");
+ None
+ }
+ };
let peer_ids = Wsm::new(dss, ws).get_peer_ids().await.unwrap_or_default();
let peer_id = peer_ids.first().copied();
telemetry.peer_id = peer_id;
@@ -233,14 +240,18 @@ pub async fn process_message(
.map(|d| d.as_millis() as i64)
.unwrap_or(0);
for update in &updates {
- let touched_nodes = session_storage
+ let imported = session_storage
.append_pending_operation(update, document_state)
.await?;
- if !touched_nodes.is_empty()
+ if imported.changed {
+ dss.record_editor(attribution.as_ref());
+ }
+ if !imported.touched_nodes.is_empty()
&& let Some(peer_id) = peer_id
{
dss.push_blame_events(
- touched_nodes
+ imported
+ .touched_nodes
.into_iter()
.map(|node_id| crate::d1::BlameEvent {
document_id: document_id.to_string(),
diff --git a/services/sync-service/tests/activity.test.ts b/services/sync-service/tests/activity.test.ts
new file mode 100644
index 0000000000..66a68551a1
--- /dev/null
+++ b/services/sync-service/tests/activity.test.ts
@@ -0,0 +1,324 @@
+import { mkdtempSync, rmSync } from 'node:fs';
+import { createServer, type Server, type ServerResponse } from 'node:http';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import jwt from 'jsonwebtoken';
+import { LoroDoc } from 'loro-crdt';
+import type { Miniflare } from 'miniflare';
+import { afterAll, afterEach, beforeAll, expect, it } from 'vitest';
+import { FromPeer, FromRemote, InitializeFromSnapshotRequest } from '../bebop/generated/schema';
+import { createTestWebSocket, setupMiniflare } from './utils';
+
+type Editor = { actor: string; on_behalf_of: string | null };
+type Notification = { editors: Editor[] };
+type DssMode = 'hold_snapshot' | 'hold_notification' | 'fail_notification' | 'legacy';
+type HeldRequest = { documentId: string; response: ServerResponse };
+type Client = Awaited<ReturnType<typeof connect>>;
+let mf: Miniflare;
+let server: Server;
+const notifications = new Map<string, Notification[]>();
+const rawNotifications = new Map<string, Partial<Notification>[]>();
+const snapshots = new Map<string, Uint8Array[]>();
+const modes = new Map<string, DssMode>();
+const heldRequests: HeldRequest[] = [];
+const clients: Client[] = [];
+const persistPath = mkdtempSync(join(tmpdir(), 'sync-activity-'));
+
+beforeAll(async () => {
+ server = createServer(async (req, res) => {
+ const chunks: Buffer[] = [];
+ try {
+ for await (const chunk of req) chunks.push(Buffer.from(chunk));
+ } catch (error) {
+ // Disposing Miniflare can cancel an in-flight lifecycle notification.
+ if (req.aborted) return;
+ throw error;
+ }
+ const match = req.url?.match(/\/documents\/([^/]+)\/(snapshot|sync-content-updated)$/);
+ if (match) {
+ const documentId = match[1];
+ const kind = match[2] === 'snapshot' ? 'snapshot' : 'notification';
+ const body = Buffer.concat(chunks);
+ const mode = modes.get(documentId);
+ if (kind === 'snapshot') {
+ const records = snapshots.get(documentId) ?? [];
+ records.push(body);
+ snapshots.set(documentId, records);
+ } else {
+ const parsed = JSON.parse(body.toString()) as Partial<Notification>;
+ const rawRecords = rawNotifications.get(documentId) ?? [];
+ rawRecords.push(parsed);
+ rawNotifications.set(documentId, rawRecords);
+ const records = notifications.get(documentId) ?? [];
+ records.push({ editors: parsed.editors ?? [] });
+ notifications.set(documentId, records);
+ if (mode === 'legacy' && 'editors' in parsed) {
+ res.writeHead(422).end();
+ return;
+ }
+ }
+ if (mode === `hold_${kind}`) {
+ heldRequests.push({ documentId, response: res });
+ return;
+ }
+ if (kind === 'notification' && mode === 'fail_notification') {
+ res.writeHead(503).end();
+ return;
+ }
+ }
+ res.writeHead(200).end();
+ });
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve));
+ const address = server.address();
+ if (!address || typeof address === 'string') throw new Error('Missing mock DSS address');
+ mf = await setupMiniflare({ persistPath, dssUrl: `http://127.0.0.1:${address.port}` });
+}, 60_000);
+
+afterEach(() => {
+ for (const { documentId } of heldRequests) modes.set(documentId, 'fail_notification');
+ for (const { response } of heldRequests.splice(0)) response.writeHead(503).end();
+ for (const client of clients.splice(0)) {
+ if (client.getWebSocket().readyState === 1) client.getWebSocket().close();
+ client.doc.free();
+ }
+});
+
+afterAll(async () => {
+ await mf?.dispose();
+ await new Promise<void>((resolve, reject) => server?.close((error) => error ? reject(error) : resolve()));
+ rmSync(persistPath, { recursive: true, force: true });
+});
+
+async function seed() {
+ const id = crypto.randomUUID();
+ const doc = new LoroDoc();
+ doc.getText('content').insert(0, 'Original content');
+ const response = await mf.dispatchFetch(`http://localhost/document/${id}/initialize`, {
+ method: 'POST',
+ headers: { 'x-internal-auth-key': 'local' },
+ body: InitializeFromSnapshotRequest.encode({ snapshot: doc.export({ mode: 'snapshot' }) }),
+ });
+ expect(response.status).toBe(200);
+ doc.free();
+ await expect.poll(() => notifications.get(id), { timeout: 10_000 }).toEqual([{ editors: [] }]);
+ return id;
+}
+
+function tokenFor(id: string, userId: string | null, actor?: string, access = 'edit') {
+ return jwt.sign({ document_id: id, user_id: userId, actor, access_level: access,
+ exp: Math.floor(Date.now() / 1000) + 120 }, 'local');
+}
+
+async function connect(id: string, userId: string | null, actor?: string, access = 'edit') {
+ const token = tokenFor(id, userId, actor, access);
+ const response = await mf.dispatchFetch(`http://localhost/document/${id}/connect?token=${token}`, {
+ headers: { Upgrade: 'websocket' },
+ });
+ if (!response.webSocket) throw new Error('Expected a websocket');
+ const socket = createTestWebSocket(response.webSocket);
+ response.webSocket.accept();
+ const initial = FromRemote.decode(new Uint8Array(await socket.waitForNextMessage() as ArrayBuffer));
+ if (!initial.isRemoteInitialSync()) throw new Error('Expected initial snapshot');
+ const doc = new LoroDoc();
+ doc.import(initial.value.snapshot);
+ const client = { ...socket, doc };
+ clients.push(client);
+ return client;
+}
+
+async function send(client: Client, updates: Uint8Array[]) {
+ const id = crypto.randomUUID();
+ client.send(FromPeer.fromPeerUpdate({ updates, id }).encode());
+ for (;;) {
+ const message = FromRemote.decode(new Uint8Array(await client.waitForNextMessage(2000) as ArrayBuffer));
+ if (message.isRemoteUpdateAck() && message.value.id === id) return;
+ }
+}
+
+function change(client: Client, text = ' Accepted body edit') {
+ const from = client.doc.version();
+ client.doc.getText('content').push(text);
+ client.doc.commit();
+ return client.doc.export({ mode: 'update', from });
+}
+
+async function edit(client: Client) {
+ const update = change(client);
+ await send(client, [update]);
+ return update;
+}
+
+async function receiveUpdate(client: Client) {
+ for (;;) {
+ const message = FromRemote.decode(new Uint8Array(await client.waitForNextMessage(2000) as ArrayBuffer));
+ if (message.isRemoteUpdate()) {
+ client.doc.import(message.value.update);
+ return;
+ }
+ }
+}
+
+function releaseHeld(documentId: string, status: number) {
+ for (let i = heldRequests.length - 1; i >= 0; i--) {
+ if (heldRequests[i].documentId === documentId) {
+ heldRequests.splice(i, 1)[0].response.writeHead(status).end();
+ }
+ }
+}
+
+function snapshotText(snapshot: Uint8Array) {
+ const doc = new LoroDoc();
+ try {
+ doc.import(snapshot);
+ return doc.getText('content').toString();
+ } finally {
+ doc.free();
+ }
+}
+
+const batches = (id: string) => (notifications.get(id) ?? []).filter((item) => item.editors.length > 0);
+const waitForBatches = (id: string, count: number) => expect.poll(() => batches(id).length, {
+ timeout: 12_000, interval: 100,
+}).toBe(count);
+const human = (actor: string): Editor => ({ actor, on_behalf_of: null });
+
+it('attaches unique accepted editors to the existing snapshot notification', async () => {
+ const id = await seed();
+ await connect(id, 'macro|[email protected]', 'bot|idle-agent');
+ const viewer = await connect(id, 'macro|[email protected]', undefined, 'view');
+ const alice = await connect(id, 'macro|[email protected]');
+ const bob = await connect(id, 'macro|[email protected]');
+ modes.set(id, 'hold_snapshot');
+ await send(alice, [change(alice), change(alice)]);
+ await edit(bob);
+ viewer.send(FromPeer.fromPeerUpdate({ updates: [change(viewer, ' Forbidden')], id: crypto.randomUUID() }).encode());
+ await expect.poll(() => heldRequests.some((request) => request.documentId === id), {
+ timeout: 12_000,
+ }).toBe(true);
+ // No separate per-edit POST: the editor batch follows the existing snapshot upload.
+ expect(notifications.get(id)).toEqual([{ editors: [] }]);
+ modes.delete(id);
+ releaseHeld(id, 200);
+ await waitForBatches(id, 1);
+ expect(batches(id)[0].editors).toHaveLength(2);
+ expect(batches(id)[0].editors).toEqual(expect.arrayContaining([
+ human('macro|[email protected]'), human('macro|[email protected]'),
+ ]));
+ expect(snapshotText(snapshots.get(id)!.at(-1)!)).not.toContain('Forbidden');
+}, 20_000);
+
+it('reports ongoing editors in later snapshots but excludes replayed operations', async () => {
+ const id = await seed();
+ const alice = await connect(id, 'macro|[email protected]');
+ const anonymous = await connect(id, null);
+ const replay = await edit(alice);
+ await waitForBatches(id, 1);
+ const beforeReplay = notifications.get(id)!.length;
+ await send(alice, [replay]);
+ // Force another save with an accepted anonymous edit; the replay adds no editor.
+ await edit(anonymous);
+ await expect.poll(() => notifications.get(id)!.length, { timeout: 12_000 }).toBeGreaterThan(beforeReplay);
+ expect(notifications.get(id)!.at(-1)).toEqual({ editors: [] });
+ await edit(alice);
+ await waitForBatches(id, 2);
+ expect(batches(id)).toEqual([
+ { editors: [human('macro|[email protected]')] },
+ { editors: [human('macro|[email protected]')] },
+ ]);
+}, 30_000);
+
+it('preserves agent subjects and excludes anonymous editors on last leave', async () => {
+ const id = await seed();
+ const aliceAgent = await connect(id, 'macro|[email protected]', 'bot|document-agent');
+ const bobAgent = await connect(id, 'macro|[email protected]', 'bot|document-agent');
+ const anonymous = await connect(id, null);
+ await edit(aliceAgent);
+ await edit(bobAgent);
+ await edit(anonymous);
+ for (const client of [aliceAgent, bobAgent, anonymous]) client.getWebSocket().close();
+ await waitForBatches(id, 1);
+ expect(batches(id)[0].editors).toHaveLength(2);
+ expect(batches(id)[0].editors).toEqual(expect.arrayContaining([
+ { actor: 'bot|document-agent', on_behalf_of: 'macro|[email protected]' },
+ { actor: 'bot|document-agent', on_behalf_of: 'macro|[email protected]' },
+ ]));
+}, 20_000);
+
+it('keeps lifecycle notifications empty when opening and closing without edits', async () => {
+ const id = await seed();
+ const viewer = await connect(id, 'macro|[email protected]', undefined, 'view');
+ viewer.getWebSocket().close();
+ await expect.poll(() => notifications.get(id)!.length, { timeout: 12_000 }).toBeGreaterThan(1);
+ expect(notifications.get(id)!.every(({ editors }) => editors.length === 0)).toBe(true);
+}, 20_000);
+
+it.each([
+ { user: 'macro|[email protected]', actor: undefined },
+ { user: 'macro|[email protected]', actor: 'bot|http-agent' },
+])('includes $user attribution in both HTTP and websocket snapshot notifications', async ({ user, actor }) => {
+ const id = await seed();
+ const token = tokenFor(id, user, actor);
+ const headers = { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' };
+ const response = await mf.dispatchFetch(`http://localhost/document/${id}/state`, { headers });
+ expect(response.status).toBe(200);
+ const source = await response.json() as { snapshot: string; revision: string };
+ const doc = new LoroDoc();
+ doc.import(Buffer.from(source.snapshot, 'base64'));
+ const from = doc.version();
+ doc.getText('content').push(' HTTP edit');
+ doc.commit();
+ const updated = await mf.dispatchFetch(`http://localhost/document/${id}/update`, {
+ method: 'POST', headers,
+ body: JSON.stringify({ expectedRevision: source.revision,
+ update: Buffer.from(doc.export({ mode: 'update', from })).toString('base64') }),
+ });
+ expect(updated.status).toBe(200);
+ doc.free();
+ const expected = actor ? { actor, on_behalf_of: user } : human(user);
+ await waitForBatches(id, 1);
+ expect(batches(id)[0]).toEqual({ editors: [expected] });
+ const websocket = await connect(id, user, actor);
+ await edit(websocket);
+ await waitForBatches(id, 2);
+ expect(batches(id)[1]).toEqual({ editors: [expected] });
+}, 20_000);
+
+it('keeps ACKs, broadcasts, and snapshot saves working while DSS notifications stall or fail', async () => {
+ const id = await seed();
+ const editor = await connect(id, 'macro|[email protected]');
+ const observer = await connect(id, 'macro|[email protected]', undefined, 'view');
+ modes.set(id, 'hold_notification');
+ await edit(editor);
+ await receiveUpdate(observer);
+ await expect.poll(() => heldRequests.some((request) => request.documentId === id), {
+ timeout: 12_000,
+ }).toBe(true);
+ const beforeStalledEdit = snapshots.get(id)!.length;
+ await edit(editor);
+ await receiveUpdate(observer);
+ expect(observer.doc.getText('content').toString()).toBe(editor.doc.getText('content').toString());
+ await expect.poll(() => snapshots.get(id)!.length, { timeout: 12_000 }).toBeGreaterThan(beforeStalledEdit);
+ expect(snapshotText(snapshots.get(id)!.at(-1)!)).toBe(editor.doc.getText('content').toString());
+ modes.set(id, 'fail_notification');
+ releaseHeld(id, 503);
+ const beforeFailedEdit = snapshots.get(id)!.length;
+ await edit(editor);
+ await receiveUpdate(observer);
+ expect(observer.doc.getText('content').toString()).toBe(editor.doc.getText('content').toString());
+ await expect.poll(() => snapshots.get(id)!.length, { timeout: 12_000 }).toBeGreaterThan(beforeFailedEdit);
+ expect(snapshotText(snapshots.get(id)!.at(-1)!)).toBe(editor.doc.getText('content').toString());
+ // A 503 must not trigger the legacy empty-body fallback for the failed batch.
+ expect(rawNotifications.get(id)!.slice(1).every(({ editors }) => editors?.length === 1)).toBe(true);
+}, 35_000);
+
+it('retries with the legacy empty body only when older DSS rejects editor fields', async () => {
+ const id = await seed();
+ const editor = await connect(id, 'macro|[email protected]');
+ modes.set(id, 'legacy');
+ await edit(editor);
+ await expect.poll(() => rawNotifications.get(id)!.length, { timeout: 12_000 }).toBe(3);
+ expect(rawNotifications.get(id)!.slice(1)).toEqual([
+ { editors: [human('macro|[email protected]')] },
+ {},
+ ]);
+}, 20_000);
diff --git a/services/sync-service/tests/awareness.test.ts b/services/sync-service/tests/awareness.test.ts
index 7ecaca6dda..8aa88fe8a0 100644
--- a/services/sync-service/tests/awareness.test.ts
+++ b/services/sync-service/tests/awareness.test.ts
@@ -15,7 +15,9 @@ beforeAll(async () => {
describe("awareness sync tests", () => {
test("should include awareness on connection if available", async () => {
- const userA = await createTestUser(mf, "1234");
+ const documentId = crypto.randomUUID();
+ const userA = await createTestUser(mf, documentId);
+ const observer = await createTestUser(mf, documentId);
// Initialize with some text
userA.doc.getText("content").push("hello world");
const cursor = userA.doc.getText("content").getCursor(5);
@@ -27,15 +29,22 @@ describe("awareness sync tests", () => {
let awarenessUpdate = userA.awareness.encode(userA.doc.peerIdStr);
const update = userA.doc.export({ mode: "update" });
- userA.connection.send(FromPeer.fromPeerUpdate({ update}).encode());
+ userA.connection.send(FromPeer.fromPeerUpdate({ updates: [update], id: crypto.randomUUID() }).encode());
userA.connection.send(FromPeer.fromPeerAwareness({ awareness: awarenessUpdate }).encode());
- const userB = await createTestUser(mf, "1234");
+ // Observe server delivery before checking a new connection's initial state.
+ for (;;) {
+ const message = await observer.readNextMessage();
+ if (message.isRemoteAwareness()) break;
+ }
+ const userB = await createTestUser(mf, documentId);
expect(userB.awareness.getAllStates()[userA.doc.peerIdStr]).toBeDefined();
});
test("should broadcast awareness when one client disconnects", async () => {
- const userA = await createTestUser(mf, "1234");
+ const documentId = crypto.randomUUID();
+ const userA = await createTestUser(mf, documentId);
+ const observer = await createTestUser(mf, documentId);
// Initialize with some text
userA.doc.getText("content").push("hello world");
const cursor = userA.doc.getText("content").getCursor(5);
@@ -47,10 +56,15 @@ describe("awareness sync tests", () => {
let awarenessUpdate = userA.awareness.encode(userA.doc.peerIdStr);
const update = userA.doc.export({ mode: "update" });
- userA.connection.send(FromPeer.fromPeerUpdate({ update}).encode());
+ userA.connection.send(FromPeer.fromPeerUpdate({ updates: [update], id: crypto.randomUUID() }).encode());
userA.connection.send(FromPeer.fromPeerAwareness({ awareness: awarenessUpdate }).encode());
- const userB = await createTestUser(mf, "1234");
+ // Observe server delivery before checking a new connection's initial state.
+ for (;;) {
+ const message = await observer.readNextMessage();
+ if (message.isRemoteAwareness()) break;
+ }
+ const userB = await createTestUser(mf, documentId);
expect(userB.awareness.getAllStates()[userA.doc.peerIdStr]).toBeDefined();
// When userA disconnects, the service should broadcast an undefined awareness update
diff --git a/services/sync-service/tests/document_sync.test.ts b/services/sync-service/tests/document_sync.test.ts
index 822ee24b6a..5cff86bf50 100644
--- a/services/sync-service/tests/document_sync.test.ts
+++ b/services/sync-service/tests/document_sync.test.ts
@@ -61,7 +61,8 @@ describe("document sync tests", () => {
wsA.send(
FromPeer.fromPeerUpdate({
- update: update,
+ updates: [update],
+ id: crypto.randomUUID(),
}).encode(),
);
@@ -101,6 +102,8 @@ describe("document sync tests", () => {
expect(userC.getState()).toBe("hello world goodbye world");
userB.makeChange(" hello again world");
+ // Wait for the accepted update before racing a new connection against it.
+ userA.import(await userA.readSyncMessage());
const userD = await createTestUser(mf, "1234");
expect(userD.getState()).toBe(
@@ -139,7 +142,7 @@ describe("document sync tests", () => {
const docB = new LoroDoc();
const connectionB = await connectToDocumentForTesting(mf, "12347");
- connectionB.waitForNextMessage();
+ await connectionB.waitForNextMessage();
let tree = docA.getTree("tree");
@@ -151,7 +154,8 @@ describe("document sync tests", () => {
docA.commit();
connectionA.send(
FromPeer.fromPeerUpdate({
- update: docA.export({ mode: "update" }),
+ updates: [docA.export({ mode: "update" })],
+ id: crypto.randomUUID(),
}).encode(),
);
diff --git a/services/sync-service/tests/utils.ts b/services/sync-service/tests/utils.ts
index 9733da437b..bc139269f8 100644
--- a/services/sync-service/tests/utils.ts
+++ b/services/sync-service/tests/utils.ts
@@ -27,7 +27,14 @@ async function migrateDatabase(mf: Miniflare) {
}
}
-export async function setupMiniflare(options: { persistPath?: string; migrate?: boolean; fetchMock?: MiniflareOptions['fetchMock'] } = {}) {
+export async function setupMiniflare(
+ options: {
+ persistPath?: string;
+ migrate?: boolean;
+ dssUrl?: string;
+ fetchMock?: MiniflareOptions['fetchMock'];
+ } = {},
+) {
const persist = (name: string) => options.persistPath ? `${options.persistPath}/${name}` : false;
const mf = new Miniflare({
d1Databases: {
@@ -64,6 +71,7 @@ export async function setupMiniflare(options: { persistPath?: string; migrate?:
SPS_API_SECRET_KEY: "local",
SPS_URL: "http://localhost:8092",
local:true,
+ ...(options.dssUrl ? { DSS_URL: options.dssUrl, DSS_INTERNAL_AUTH_KEY: "local" } : {}),
},
compatibilityDate: '2025-03-05'
});