Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(soup): optimistically populate new folder + children after bulk upload (#3264)
gbirman3a841274f150
diff --git a/js/app/packages/app/util/handleFileUpload.ts b/js/app/packages/app/util/handleFileUpload.tsindex c751ee2cc9..8aa886da0f 100644--- a/js/app/packages/app/util/handleFileUpload.ts+++ b/js/app/packages/app/util/handleFileUpload.ts@@ -34,7 +34,7 @@ export function useHandleFileUpload({upload.projectId.then((createdProjectId) => {if (!createdProjectId) return;- refetchSoupEntity(createdProjectId, 'project');+ refetchSoupEntity(createdProjectId, 'project', { includeRoot: true });refetchHistory();toast.success(`Uploaded ${upload.name}`, undefined, [diff --git a/js/app/packages/queries/soup/normalized-cache/operations.test.ts b/js/app/packages/queries/soup/normalized-cache/operations.test.tsindex 836bff00d3..9784848baf 100644--- a/js/app/packages/queries/soup/normalized-cache/operations.test.ts+++ b/js/app/packages/queries/soup/normalized-cache/operations.test.ts@@ -246,6 +246,18 @@ describe('buildSingleEntityFilter', () => {expect(ids).toEqual([NIL_ID]);}});++ it('project filter defaults include_root to false', () => {+ const filter = buildSingleEntityFilter('project', 'entity-1');+ expect((filter as any).project_filters.include_root).toBe(false);+ });++ it('project filter respects includeRoot option', () => {+ const filter = buildSingleEntityFilter('project', 'entity-1', {+ includeRoot: true,+ });+ expect((filter as any).project_filters.include_root).toBe(true);+ });});describe('insertSoupEntity', () => {diff --git a/js/app/packages/queries/soup/normalized-cache/operations.ts b/js/app/packages/queries/soup/normalized-cache/operations.tsindex 006caf5c10..701c08f221 100644--- a/js/app/packages/queries/soup/normalized-cache/operations.ts+++ b/js/app/packages/queries/soup/normalized-cache/operations.ts@@ -227,11 +227,12 @@ export function removeSearchEntities(entityIds: Set<string>): SoupTransaction {*/export async function refetchSoupEntity(entityId: string,- entityType: SoupEntityTag+ entityType: SoupEntityTag,+ options?: { includeRoot?: boolean }): Promise<void> {const { storageServiceClient } = await import('@service-storage/client');- const filter = buildSingleEntityFilter(entityType, entityId);+ const filter = buildSingleEntityFilter(entityType, entityId, options);const result = await storageServiceClient.getSoupItems({params: {},@@ -249,19 +250,21 @@ export async function refetchSoupEntity(const [, page] = result;if (!page.items.length) return;- const item = page.items[0];-- if (hasSoupEntity(entityId)) {- optimisticUpdateSoupEntity(item);- } else {- insertSoupEntity(item);+ for (const item of page.items) {+ const itemId = getSoupItemId(item);+ if (hasSoupEntity(itemId)) {+ optimisticUpdateSoupEntity(item);+ } else {+ insertSoupEntity(item);+ }}}/** @private */export function buildSingleEntityFilter(entityType: SoupEntityTag,- entityId: string+ entityId: string,+ options?: { includeRoot?: boolean }): PostSoupRequest {const base: PostSoupRequest = {...QUERY_FILTERS_BASE,@@ -279,7 +282,10 @@ export function buildSingleEntityFilter(})).with('project', () => ({...base,- project_filters: { project_ids: [entityId] },+ project_filters: {+ project_ids: [entityId],+ include_root: options?.includeRoot ?? false,+ },})).with('emailThread', () => ({...base,diff --git a/js/app/packages/service-clients/service-search/generated/models/projectFilters.ts b/js/app/packages/service-clients/service-search/generated/models/projectFilters.tsindex 6c0fcdf45b..8092aa4eb8 100644--- a/js/app/packages/service-clients/service-search/generated/models/projectFilters.ts+++ b/js/app/packages/service-clients/service-search/generated/models/projectFilters.ts@@ -14,10 +14,13 @@ import type { ProjectFiltersImportance } from './projectFiltersImportance';export interface ProjectFilters {/** Filter by project importance. None to ignore, true to pass through (no clause), false to short-circuit and return nothing. */importance?: ProjectFiltersImportance;+ /** When true, `project_ids` also matches the projects themselves in addition to their children. */+ include_root?: boolean;/** Filter by project notification state. */notification_filters?: NotificationFilters;/** Filter by project owner. Examples: ['macro|[email protected]'], ['macro|[email protected]', 'macro|[email protected]']. Empty to search all owners. */owners?: string[];- /** Project IDs to search within. Examples: ['project1']. Empty to search all accessible projects. */+ /** Project IDs to search within. Examples: ['project1']. Empty to search all accessible projects.+By default matches children of these projects; set `include_root` to also match the projects themselves. */project_ids?: string[];}diff --git a/js/app/packages/service-clients/service-search/openapi.json b/js/app/packages/service-clients/service-search/openapi.jsonindex 582e8c33ce..07c7aea680 100644--- a/js/app/packages/service-clients/service-search/openapi.json+++ b/js/app/packages/service-clients/service-search/openapi.json@@ -1948,6 +1948,10 @@"type": ["boolean", "null"],"description": "Filter by project importance. None to ignore, true to pass through (no clause), false to short-circuit and return nothing."},+ "include_root": {+ "type": "boolean",+ "description": "When true, `project_ids` also matches the projects themselves in addition to their children."+ },"notification_filters": {"$ref": "#/components/schemas/NotificationFilters","description": "Filter by project notification state."@@ -1964,7 +1968,7 @@"items": {"type": "string"},- "description": "Project IDs to search within. Examples: ['project1']. Empty to search all accessible projects."+ "description": "Project IDs to search within. Examples: ['project1']. Empty to search all accessible projects.\nBy default matches children of these projects; set `include_root` to also match the projects themselves."}}},diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/projectFilters.ts b/js/app/packages/service-clients/service-storage/generated/schemas/projectFilters.tsindex 5a16da65ec..debab5d539 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/projectFilters.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/projectFilters.ts@@ -14,10 +14,13 @@ import type { ProjectFiltersImportance } from './projectFiltersImportance';export interface ProjectFilters {/** Filter by project importance. None to ignore, true to pass through (no clause), false to short-circuit and return nothing. */importance?: ProjectFiltersImportance;+ /** When true, `project_ids` also matches the projects themselves in addition to their children. */+ include_root?: boolean;/** Filter by project notification state. */notification_filters?: NotificationFilters;/** Filter by project owner. Examples: ['macro|[email protected]'], ['macro|[email protected]', 'macro|[email protected]']. Empty to search all owners. */owners?: string[];- /** Project IDs to search within. Examples: ['project1']. Empty to search all accessible projects. */+ /** Project IDs to search within. Examples: ['project1']. Empty to search all accessible projects.+By default matches children of these projects; set `include_root` to also match the projects themselves. */project_ids?: string[];}diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.tsindex 1ded421827..c62c65454f 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -5846,6 +5846,12 @@ export const postItemsSoupBody = zod.describe('Filter by project importance. None to ignore, true to pass through (no clause), false to short-circuit and return nothing.'),+ include_root: zod+ .boolean()+ .optional()+ .describe(+ 'When true, `project_ids` also matches the projects themselves in addition to their children.'+ ),notification_filters: zod.object({done: zod@@ -5873,7 +5879,7 @@ export const postItemsSoupBody = zod.array(zod.string()).optional().describe(- "Project IDs to search within. Examples: ['project1']. Empty to search all accessible projects."+ "Project IDs to search within. Examples: ['project1']. Empty to search all accessible projects.\nBy default matches children of these projects; set `include_root` to also match the projects themselves."),}).optional()diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex d70e597b35..376cd2b000 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -10925,6 +10925,10 @@"type": ["boolean", "null"],"description": "Filter by project importance. None to ignore, true to pass through (no clause), false to short-circuit and return nothing."},+ "include_root": {+ "type": "boolean",+ "description": "When true, `project_ids` also matches the projects themselves in addition to their children."+ },"notification_filters": {"$ref": "#/components/schemas/NotificationFilters","description": "Filter by project notification state."@@ -10941,7 +10945,7 @@"items": {"type": "string"},- "description": "Project IDs to search within. Examples: ['project1']. Empty to search all accessible projects."+ "description": "Project IDs to search within. Examples: ['project1']. Empty to search all accessible projects.\nBy default matches children of these projects; set `include_root` to also match the projects themselves."}}},diff --git a/rust/cloud-storage/frecency/src/outbound/postgres/dynamic.rs b/rust/cloud-storage/frecency/src/outbound/postgres/dynamic.rsindex 59d77f3721..f2ddcaa199 100644--- a/rust/cloud-storage/frecency/src/outbound/postgres/dynamic.rs+++ b/rust/cloud-storage/frecency/src/outbound/postgres/dynamic.rs@@ -310,6 +310,9 @@ fn build_project_filter(ast: Option<&Expr<ProjectLiteral>>) -> String {filter_ast::ExprFrame::Or(a, b) => format!("({a} OR {b})"),filter_ast::ExprFrame::Not(a) => format!("(NOT {a})"),filter_ast::ExprFrame::Literal(ProjectLiteral::ProjectId(p)) => {+ format!(r#"entity_id IN (SELECT id FROM "Project" WHERE "parentId" = '{p}' AND "deletedAt" IS NULL)"#)+ }+ filter_ast::ExprFrame::Literal(ProjectLiteral::ProjectIdSelf(p)) => {format!("entity_id = '{p}'")}filter_ast::ExprFrame::Literal(ProjectLiteral::Owner(o)) => {diff --git a/rust/cloud-storage/frecency/src/outbound/postgres/dynamic_tests.rs b/rust/cloud-storage/frecency/src/outbound/postgres/dynamic_tests.rsindex 4673efb280..bd7c07b207 100644--- a/rust/cloud-storage/frecency/src/outbound/postgres/dynamic_tests.rs+++ b/rust/cloud-storage/frecency/src/outbound/postgres/dynamic_tests.rs@@ -142,13 +142,51 @@ async fn test_dynamic_filter_by_project_ids(pool: PgPool) {let storage = FrecencyPgStorage::new(pool.clone());let test_user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();- let project_id_1 = Uuid::new_v4();- let project_id_2 = Uuid::new_v4();+ let parent_project_id = Uuid::new_v4();+ let child_project_id = Uuid::new_v4();+ let unrelated_project_id = Uuid::new_v4();let doc_id_1 = Uuid::new_v4();+ let macro_user_id = Uuid::new_v4();++ sqlx::query(+ r#"INSERT INTO "macro_user" ("id", "username", "email", "stripe_customer_id") VALUES ($1, $2, $3, $4)"#,+ )+ .bind(macro_user_id)+ .bind("[email protected]")+ .bind("[email protected]")+ .bind("stripe_id")+ .execute(&pool)+ .await+ .unwrap();++ sqlx::query(r#"INSERT INTO "User" ("id", "email", "macro_user_id") VALUES ($1, $2, $3)"#)+ .bind(test_user_id.as_ref())+ .bind("[email protected]")+ .bind(macro_user_id)+ .execute(&pool)+ .await+ .unwrap();++ sqlx::query(+ r#"+ INSERT INTO "Project" ("id", "name", "userId", "parentId") VALUES+ ($1, 'parent', $4, NULL),+ ($2, 'child', $4, $1),+ ($3, 'unrelated', $4, NULL)+ "#,+ )+ .bind(parent_project_id.to_string())+ .bind(child_project_id.to_string())+ .bind(unrelated_project_id.to_string())+ .bind(test_user_id.as_ref())+ .execute(&pool)+ .await+ .unwrap();for (id, entity_type, score) in [- (project_id_1.to_string(), EntityType::Project, 100.0),- (project_id_2.to_string(), EntityType::Project, 80.0),+ (parent_project_id.to_string(), EntityType::Project, 100.0),+ (child_project_id.to_string(), EntityType::Project, 70.0),+ (unrelated_project_id.to_string(), EntityType::Project, 80.0),(doc_id_1.to_string(), EntityType::Document, 90.0),] {storage@@ -170,7 +208,7 @@ async fn test_dynamic_filter_by_project_ids(pool: PgPool) {let filter = item_filters::ast::EntityFilterAst::new_from_filters(EntityFilters {project_filters: ProjectFilters {- project_ids: vec![project_id_1.to_string()],+ project_ids: vec![parent_project_id.to_string()],..Default::default()},..Default::default()@@ -188,12 +226,112 @@ async fn test_dynamic_filter_by_project_ids(pool: PgPool) {.await.unwrap();- // Should return filtered project (project_id_1) + all documents (doc_id_1)+ // Default include_root=false: only the child of parent_project_id matches the project+ // filter; doc_id_1 passes through since document_filters is unconstrained.assert_eq!(results.len(), 2);- assert_eq!(results[0].id.entity.entity_id, project_id_1.to_string());- assert_eq!(results[0].data.frecency_score, 100.0);- assert_eq!(results[1].id.entity.entity_id, doc_id_1.to_string());- assert_eq!(results[1].data.frecency_score, 90.0);+ assert_eq!(results[0].id.entity.entity_id, doc_id_1.to_string());+ assert_eq!(results[0].data.frecency_score, 90.0);+ assert_eq!(results[1].id.entity.entity_id, child_project_id.to_string());+ assert_eq!(results[1].data.frecency_score, 70.0);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn test_dynamic_filter_by_project_ids_include_root(pool: PgPool) {+ let storage = FrecencyPgStorage::new(pool.clone());+ let test_user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();++ let parent_project_id = Uuid::new_v4();+ let child_project_id = Uuid::new_v4();+ let unrelated_project_id = Uuid::new_v4();+ let macro_user_id = Uuid::new_v4();++ sqlx::query(+ r#"INSERT INTO "macro_user" ("id", "username", "email", "stripe_customer_id") VALUES ($1, $2, $3, $4)"#,+ )+ .bind(macro_user_id)+ .bind("[email protected]")+ .bind("[email protected]")+ .bind("stripe_id")+ .execute(&pool)+ .await+ .unwrap();++ sqlx::query(r#"INSERT INTO "User" ("id", "email", "macro_user_id") VALUES ($1, $2, $3)"#)+ .bind(test_user_id.as_ref())+ .bind("[email protected]")+ .bind(macro_user_id)+ .execute(&pool)+ .await+ .unwrap();++ sqlx::query(+ r#"+ INSERT INTO "Project" ("id", "name", "userId", "parentId") VALUES+ ($1, 'parent', $3, NULL),+ ($2, 'child', $3, $1),+ ($4, 'unrelated', $3, NULL)+ "#,+ )+ .bind(parent_project_id.to_string())+ .bind(child_project_id.to_string())+ .bind(test_user_id.as_ref())+ .bind(unrelated_project_id.to_string())+ .execute(&pool)+ .await+ .unwrap();++ for (id, score) in [+ (parent_project_id.to_string(), 100.0),+ (child_project_id.to_string(), 70.0),+ (unrelated_project_id.to_string(), 80.0),+ ] {+ storage+ .set_aggregate(AggregateFrecency {+ id: AggregateId {+ entity: EntityType::Project.with_entity_string(id.clone()),+ user_id: test_user_id.clone(),+ },+ data: FrecencyData {+ event_count: 1,+ frecency_score: score,+ first_event: Utc::now(),+ recent_events: VecDeque::new(),+ },+ })+ .await+ .unwrap();+ }++ let filter = item_filters::ast::EntityFilterAst::new_from_filters(EntityFilters {+ project_filters: ProjectFilters {+ project_ids: vec![parent_project_id.to_string()],+ include_root: true,+ ..Default::default()+ },+ ..Default::default()+ })+ .unwrap()+ .unwrap();++ let results = storage+ .get_top_entities(FrecencyPageRequest {+ user_id: test_user_id.copied(),+ from_score: None,+ limit: 10,+ filters: Some(filter),+ })+ .await+ .unwrap();++ // include_root=true: parent itself + its child match; unrelated_project is filtered out.+ assert_eq!(results.len(), 2);+ let ids: std::collections::HashSet<String> = results+ .iter()+ .map(|r| r.id.entity.entity_id.to_string())+ .collect();+ assert!(ids.contains(&parent_project_id.to_string()));+ assert!(ids.contains(&child_project_id.to_string()));+ assert!(!ids.contains(&unrelated_project_id.to_string()));}#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]diff --git a/rust/cloud-storage/item_filters/src/ast/project.rs b/rust/cloud-storage/item_filters/src/ast/project.rsindex f796cbe9f7..62b21b4b83 100644--- a/rust/cloud-storage/item_filters/src/ast/project.rs+++ b/rust/cloud-storage/item_filters/src/ast/project.rs@@ -11,9 +11,12 @@ use crate::{/// the literal ast types for a project#[derive(Debug, Serialize, Deserialize, Clone)]pub enum ProjectLiteral {- /// the id of the project+ /// matches projects whose parent is this id (i.e. children of this project)#[serde(rename = "pid")]ProjectId(Uuid),+ /// matches the project with this id itself (not its children)+ #[serde(rename = "pids")]+ ProjectIdSelf(Uuid),/// the owner of the project#[serde(rename = "o")]Owner(MacroUserIdStr<'static>),@@ -40,6 +43,7 @@ impl ExpandFrame<ProjectLiteral> for ProjectFilters {fn expand_ast(input: Self) -> Result<Option<filter_ast::Expr<ProjectLiteral>>, Self::Err> {let ProjectFilters {project_ids,+ include_root,owners,importance,notification_filters,@@ -48,7 +52,17 @@ impl ExpandFrame<ProjectLiteral> for ProjectFilters {let project_ids = project_ids.iter().map(|s| Uuid::parse_str(s))- .try_expand(|r| r.map(ProjectLiteral::ProjectId), Expr::or)?;+ .collect::<Result<Vec<_>, _>>()?+ .into_iter()+ .map(|id| {+ let children = Expr::Literal(ProjectLiteral::ProjectId(id));+ if include_root {+ Expr::or(Expr::Literal(ProjectLiteral::ProjectIdSelf(id)), children)+ } else {+ children+ }+ })+ .reduce(Expr::or);let owners = owners.iter()diff --git a/rust/cloud-storage/item_filters/src/lib.rs b/rust/cloud-storage/item_filters/src/lib.rsindex 8965e77fa9..d104584a72 100644--- a/rust/cloud-storage/item_filters/src/lib.rs+++ b/rust/cloud-storage/item_filters/src/lib.rs@@ -415,9 +415,14 @@ impl IsEmpty for PropertyFilter {#[cfg_attr(feature = "schema", derive(utoipa::ToSchema, schemars::JsonSchema))]pub struct ProjectFilters {/// Project IDs to search within. Examples: ['project1']. Empty to search all accessible projects.+ /// By default matches children of these projects; set `include_root` to also match the projects themselves.#[serde(default, skip_serializing_if = "Vec::is_empty")]pub project_ids: Vec<String>,+ /// When true, `project_ids` also matches the projects themselves in addition to their children.+ #[serde(default, skip_serializing_if = "std::ops::Not::not")]+ pub include_root: bool,+/// Filter by project owner. Examples: ['macro|[email protected]'], ['macro|[email protected]', 'macro|[email protected]']. Empty to search all owners.#[serde(default, skip_serializing_if = "Vec::is_empty")]pub owners: Vec<String>,@@ -435,6 +440,7 @@ impl IsEmpty for ProjectFilters {fn is_empty(&self) -> bool {let ProjectFilters {project_ids,+ include_root: _,owners,importance,notification_filters,diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/dynamic.rsindex 61e62846dd..67d8deb291 100644--- a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs@@ -438,6 +438,9 @@ fn build_project_filter(ast: Option<&Expr<ProjectLiteral>>) -> String {filter_ast::ExprFrame::Literal(ProjectLiteral::ProjectId(p)) => {format!(r#"p."parentId" = '{p}'"#)}+ filter_ast::ExprFrame::Literal(ProjectLiteral::ProjectIdSelf(p)) => {+ format!(r#"p.id = '{p}'"#)+ }filter_ast::ExprFrame::Literal(ProjectLiteral::Owner(o)) => {format!(r#"p."userId" = '{o}'"#)}diff --git a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rsindex 53e4d462bf..27f8206657 100644--- a/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs+++ b/rust/cloud-storage/soup/src/outbound/pg_soup_repo/expanded/tests.rs@@ -1188,6 +1188,69 @@ async fn test_filter_by_project_ids(db: PgPool) -> anyhow::Result<()> {Ok(())}+// Test filtering projects by specific project IDs with include_root=true+#[sqlx::test(+ fixtures(+ path = "../../../../../macro_db_client/fixtures",+ scripts("entity_filter_tests")+ ),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn test_filter_by_project_ids_include_root(db: PgPool) -> anyhow::Result<()> {+ use item_filters::{EntityFilters, ProjectFilters};++ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap();++ let entity_filters = EntityFilters {+ project_filters: ProjectFilters {+ project_ids: vec![+ "11111111-1111-1111-1111-111111111111".to_string(),+ "44444444-4444-4444-4444-444444444444".to_string(),+ ],+ include_root: true,+ ..Default::default()+ },+ ..Default::default()+ };++ let filters = EntityFilterAst::new_from_filters(entity_filters)?.unwrap();++ let items = expanded_dynamic_cursor_soup(+ &db,+ ExpandedDynamicCursorArgs {+ user_id: user_id.copied(),+ limit: 20,+ cursor: Query::Sort(SimpleSortMethod::CreatedAt, filters),+ exclude_frecency: false,+ },+ )+ .await?;++ let project_ids: HashSet<Uuid> = items+ .iter()+ .filter_map(|item| match item {+ SoupItem::Project(p) => Some(p.id),+ _ => None,+ })+ .collect();++ let expected_ids: HashSet<Uuid> = [+ "11111111-1111-1111-1111-111111111111", // Project A (self)+ "22222222-2222-2222-2222-222222222222", // Project B (child of A)+ "44444444-4444-4444-4444-444444444444", // Project D (self)+ ]+ .iter()+ .map(|&s| Uuid::parse_str(s).unwrap())+ .collect();++ assert_eq!(+ project_ids, expected_ids,+ "include_root=true should match the projects themselves plus their direct children"+ );++ Ok(())+}+// Test combined filters across multiple entity types#[sqlx::test(fixtures(