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
feat(crm): populate company and contact references (#8020)
gbirmana50c2821173a
diff --git a/.sqlx/query-0e5c42e814545530f52fc27eeb9b0e06fb87a9035bc8c0f3af875dc46a5f02f7.json b/.sqlx/query-0e5c42e814545530f52fc27eeb9b0e06fb87a9035bc8c0f3af875dc46a5f02f7.jsonnew file mode 100644index 0000000000..4e21ebee79--- /dev/null+++ b/.sqlx/query-0e5c42e814545530f52fc27eeb9b0e06fb87a9035bc8c0f3af875dc46a5f02f7.json@@ -0,0 +1,53 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH targets AS (\n SELECT * FROM UNNEST($1::text[], $2::text[]) AS t(entity_type, entity_id)\n ),\n edges AS (\n SELECT em.source_entity_type::text AS source_type,\n em.source_entity_id AS source_id\n FROM comms_entity_mentions em\n JOIN targets t\n ON em.entity_type = t.entity_type AND em.entity_id = t.entity_id\n WHERE em.source_entity_type IN ('document', 'message')\n UNION\n SELECT 'message', a.message_id::text\n FROM comms_attachments a\n JOIN targets t\n ON a.entity_type = t.entity_type AND a.entity_id = t.entity_id\n )\n SELECT\n e.source_type AS \"source_type!\",\n e.source_id AS \"source_id!\",\n m.id AS \"message_id?\",\n m.thread_id AS \"thread_id?\",\n m.parent_entity_type AS \"parent_entity_type?\",\n m.parent_entity_id AS \"parent_entity_id?\"\n FROM edges e\n LEFT JOIN comms_messages m\n ON m.id = CASE WHEN e.source_type = 'message' THEN e.source_id::uuid END\n AND m.deleted_at IS NULL\n WHERE e.source_type = 'document' OR m.id IS NOT NULL\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "source_type!",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "source_id!",+ "type_info": "Varchar"+ },+ {+ "ordinal": 2,+ "name": "message_id?",+ "type_info": "Uuid"+ },+ {+ "ordinal": 3,+ "name": "thread_id?",+ "type_info": "Uuid"+ },+ {+ "ordinal": 4,+ "name": "parent_entity_type?",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "parent_entity_id?",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "TextArray",+ "TextArray"+ ]+ },+ "nullable": [+ true,+ true,+ false,+ true,+ false,+ false+ ]+ },+ "hash": "0e5c42e814545530f52fc27eeb9b0e06fb87a9035bc8c0f3af875dc46a5f02f7"+}diff --git a/.sqlx/query-e1ebe683de73f15ff6895e08b71c93ef2134b40434bab28c7e497869165cb76a.json b/.sqlx/query-1de43e6d6d7d68c1d7b5df8839afcac615c9c43b14d5853dd48f847ae24b25c0.jsonsimilarity index 94%rename from .sqlx/query-e1ebe683de73f15ff6895e08b71c93ef2134b40434bab28c7e497869165cb76a.jsonrename to .sqlx/query-1de43e6d6d7d68c1d7b5df8839afcac615c9c43b14d5853dd48f847ae24b25c0.jsonindex dad6bb5ddd..47afde9a82 100644--- a/.sqlx/query-e1ebe683de73f15ff6895e08b71c93ef2134b40434bab28c7e497869165cb76a.json+++ b/.sqlx/query-1de43e6d6d7d68c1d7b5df8839afcac615c9c43b14d5853dd48f847ae24b25c0.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n WITH user_source_ids AS (\n SELECT cp.channel_id::text AS source_id\n FROM comms_channel_participants cp\n WHERE cp.user_id = $1 AND cp.left_at IS NULL\n UNION ALL\n SELECT t.team_id::text AS source_id\n FROM team_user t\n WHERE t.user_id = $1\n UNION ALL\n SELECT $1 AS source_id\n ),\n visible_calls AS (\n SELECT\n c.id AS call_id,\n c.channel_id,\n c.room_name,\n c.created_by,\n c.created_at AS started_at,\n NULL::timestamptz AS ended_at,\n NULL::bigint AS duration_ms,\n c.egress_id,\n c.recording_key,\n c.preview_url,\n c.recording_started_at,\n (SELECT title FROM call_meetings WHERE id = c.meeting_id) AS custom_name,\n NULL::text AS summary,\n c.share_with_team,\n sp.team_share_access_level,\n true AS is_active,\n CASE\n WHEN EXISTS (\n SELECT 1 FROM call_participants cp\n WHERE cp.call_id = c.id AND cp.user_id = $1\n ) THEN 'ATTENDED'::text\n WHEN EXISTS (\n SELECT 1 FROM comms_channel_participants ccp\n WHERE ccp.channel_id = c.channel_id\n AND ccp.user_id = $1\n AND ccp.left_at IS NULL\n ) THEN 'MISSED'::text\n ELSE 'UNATTENDED'::text\n END AS status\n FROM calls c\n JOIN \"SharePermission\" sp ON sp.id = c.share_permission_id\n WHERE EXISTS (\n SELECT 1 FROM entity_access ea\n JOIN user_source_ids u ON u.source_id = ea.source_id\n WHERE ea.entity_id = c.id\n AND ea.entity_type = 'call'\n AND (c.channel_id IS NOT NULL OR (ea.source_type = 'user' AND ea.source_id = $1))\n )\n AND ($3::bool IS FALSE OR c.channel_id = ANY($4))\n AND ($5::bool IS FALSE OR c.id = ANY($6))\n -- Property conditions in conjunctive normal form: every\n -- clause needs a term the call satisfies. Tags (no\n -- definition) match any property value; entity references\n -- match their definition's value.\n AND NOT EXISTS (\n SELECT 1\n FROM generate_series(0, $9::int - 1) AS clause(idx)\n WHERE NOT EXISTS (\n SELECT 1\n FROM UNNEST($10::int[], $11::bool[], $12::uuid[], $13::text[])\n AS term(clause_idx, negated, definition_id, value)\n WHERE term.clause_idx = clause.idx\n AND term.negated <> EXISTS (\n SELECT 1 FROM entity_properties ep\n WHERE ep.entity_id = c.id::text\n AND ep.entity_type = 'CALL_RECORD'\n AND jsonb_typeof(ep.values -> 'value') = 'array'\n AND CASE\n WHEN term.definition_id IS NULL\n THEN jsonb_exists(ep.values -> 'value', term.value)\n ELSE ep.property_definition_id = term.definition_id\n AND ep.values -> 'value' @> jsonb_build_array(\n jsonb_build_object('entity_id', term.value)\n )\n END\n )\n )\n )\n UNION ALL\n SELECT\n cr.id AS call_id,\n cr.channel_id,\n cr.room_name,\n cr.created_by,\n cr.started_at,\n cr.ended_at,\n cr.duration_ms,\n cr.egress_id,\n cr.recording_key,\n cr.preview_url,\n cr.recording_started_at,\n cr.custom_name,\n cr.summary,\n (sp.team_share_access_level IS NOT NULL) AS share_with_team,\n sp.team_share_access_level,\n false AS is_active,\n CASE\n WHEN EXISTS (\n SELECT 1 FROM call_record_participants crp\n WHERE crp.call_record_id = cr.id AND crp.user_id = $1\n ) THEN 'ATTENDED'::text\n WHEN EXISTS (\n SELECT 1 FROM comms_channel_participants ccp\n WHERE ccp.channel_id = cr.channel_id\n AND ccp.user_id = $1\n AND ccp.left_at IS NULL\n ) THEN 'MISSED'::text\n ELSE 'UNATTENDED'::text\n END AS status\n FROM call_records cr\n JOIN \"SharePermission\" sp ON sp.id = cr.share_permission_id\n WHERE EXISTS (\n SELECT 1 FROM entity_access ea\n JOIN user_source_ids u ON u.source_id = ea.source_id\n WHERE ea.entity_id = cr.id\n AND ea.entity_type = 'call'\n AND (cr.channel_id IS NOT NULL OR (ea.source_type = 'user' AND ea.source_id = $1))\n )\n AND ($3::bool IS FALSE OR cr.channel_id = ANY($4))\n AND ($5::bool IS FALSE OR cr.id = ANY($6))\n -- Property conditions in conjunctive normal form: every\n -- clause needs a term the call satisfies. Tags (no\n -- definition) match any property value; entity references\n -- match their definition's value.\n AND NOT EXISTS (\n SELECT 1\n FROM generate_series(0, $9::int - 1) AS clause(idx)\n WHERE NOT EXISTS (\n SELECT 1\n FROM UNNEST($10::int[], $11::bool[], $12::uuid[], $13::text[])\n AS term(clause_idx, negated, definition_id, value)\n WHERE term.clause_idx = clause.idx\n AND term.negated <> EXISTS (\n SELECT 1 FROM entity_properties ep\n WHERE ep.entity_id = cr.id::text\n AND ep.entity_type = 'CALL_RECORD'\n AND jsonb_typeof(ep.values -> 'value') = 'array'\n AND CASE\n WHEN term.definition_id IS NULL\n THEN jsonb_exists(ep.values -> 'value', term.value)\n ELSE ep.property_definition_id = term.definition_id\n AND ep.values -> 'value' @> jsonb_build_array(\n jsonb_build_object('entity_id', term.value)\n )\n END\n )\n )\n )\n )\n SELECT\n call_id as \"call_id!\",\n channel_id as \"channel_id?\",\n room_name as \"room_name!\",\n created_by as \"created_by!\",\n started_at as \"started_at!\",\n ended_at,\n duration_ms,\n egress_id,\n recording_key,\n preview_url,\n recording_started_at,\n custom_name,\n summary,\n share_with_team as \"share_with_team!\",\n team_share_access_level as \"team_share_access_level?: AccessLevel\",\n is_active as \"is_active!\",\n status as \"status!\"\n FROM visible_calls\n WHERE ($7::bool IS FALSE OR status = ANY($8::text[]))\n ORDER BY \"started_at!\" DESC\n LIMIT $2\n ",+ "query": "\n WITH user_source_ids AS (\n SELECT cp.channel_id::text AS source_id\n FROM comms_channel_participants cp\n WHERE cp.user_id = $1 AND cp.left_at IS NULL\n UNION ALL\n SELECT t.team_id::text AS source_id\n FROM team_user t\n WHERE t.user_id = $1\n UNION ALL\n SELECT $1 AS source_id\n ),\n visible_calls AS (\n SELECT\n c.id AS call_id,\n c.channel_id,\n c.room_name,\n c.created_by,\n c.created_at AS started_at,\n NULL::timestamptz AS ended_at,\n NULL::bigint AS duration_ms,\n c.egress_id,\n c.recording_key,\n c.preview_url,\n c.recording_started_at,\n (SELECT title FROM call_meetings WHERE id = c.meeting_id) AS custom_name,\n NULL::text AS summary,\n c.share_with_team,\n sp.team_share_access_level,\n true AS is_active,\n CASE\n WHEN EXISTS (\n SELECT 1 FROM call_participants cp\n WHERE cp.call_id = c.id AND cp.user_id = $1\n ) THEN 'ATTENDED'::text\n WHEN EXISTS (\n SELECT 1 FROM comms_channel_participants ccp\n WHERE ccp.channel_id = c.channel_id\n AND ccp.user_id = $1\n AND ccp.left_at IS NULL\n ) THEN 'MISSED'::text\n ELSE 'UNATTENDED'::text\n END AS status\n FROM calls c\n JOIN \"SharePermission\" sp ON sp.id = c.share_permission_id\n WHERE EXISTS (\n SELECT 1 FROM entity_access ea\n JOIN user_source_ids u ON u.source_id = ea.source_id\n WHERE ea.entity_id = c.id\n AND ea.entity_type = 'call'\n AND (c.channel_id IS NOT NULL OR (ea.source_type = 'user' AND ea.source_id = $1))\n )\n AND ($3::bool IS FALSE OR c.channel_id = ANY($4))\n AND ($5::bool IS FALSE OR c.id = ANY($6))\n -- Property conditions in conjunctive normal form: every\n -- clause needs a term the call satisfies. Tags (no\n -- definition) match any property value; entity references\n -- match their definition's value.\n AND NOT EXISTS (\n SELECT 1\n FROM generate_series(0, $9::int - 1) AS clause(idx)\n WHERE NOT EXISTS (\n SELECT 1\n FROM UNNEST($10::int[], $11::bool[], $12::uuid[], $13::text[])\n AS term(clause_idx, negated, definition_id, value)\n WHERE term.clause_idx = clause.idx\n AND term.negated <> EXISTS (\n SELECT 1 FROM entity_properties ep\n WHERE ep.entity_id = c.id::text\n AND ep.entity_type = 'CALL_RECORD'\n AND jsonb_typeof(ep.values -> 'value') = 'array'\n AND CASE\n WHEN term.definition_id IS NULL\n THEN jsonb_exists(ep.values -> 'value', term.value)\n ELSE ep.property_definition_id = term.definition_id\n AND ep.values -> 'value' @> jsonb_build_array(\n jsonb_build_object('entity_id', term.value)\n )\n END\n )\n )\n )\n UNION ALL\n SELECT\n cr.id AS call_id,\n cr.channel_id,\n cr.room_name,\n cr.created_by,\n cr.started_at,\n cr.ended_at,\n cr.duration_ms,\n cr.egress_id,\n cr.recording_key,\n cr.preview_url,\n cr.recording_started_at,\n cr.custom_name,\n cr.summary,\n (sp.team_share_access_level IS NOT NULL) AS share_with_team,\n sp.team_share_access_level,\n false AS is_active,\n CASE\n WHEN EXISTS (\n SELECT 1 FROM call_record_participants crp\n WHERE crp.call_record_id = cr.id AND crp.user_id = $1\n ) THEN 'ATTENDED'::text\n WHEN EXISTS (\n SELECT 1 FROM comms_channel_participants ccp\n WHERE ccp.channel_id = cr.channel_id\n AND ccp.user_id = $1\n AND ccp.left_at IS NULL\n ) THEN 'MISSED'::text\n ELSE 'UNATTENDED'::text\n END AS status\n FROM call_records cr\n JOIN \"SharePermission\" sp ON sp.id = cr.share_permission_id\n WHERE EXISTS (\n SELECT 1 FROM entity_access ea\n JOIN user_source_ids u ON u.source_id = ea.source_id\n WHERE ea.entity_id = cr.id\n AND ea.entity_type = 'call'\n AND (cr.channel_id IS NOT NULL OR (ea.source_type = 'user' AND ea.source_id = $1))\n )\n AND ($3::bool IS FALSE OR cr.channel_id = ANY($4))\n AND ($5::bool IS FALSE OR cr.id = ANY($6))\n -- Property conditions in conjunctive normal form: every\n -- clause needs a term the call satisfies. Tags (no\n -- definition) match any property value; entity references\n -- match their definition's value.\n AND NOT EXISTS (\n SELECT 1\n FROM generate_series(0, $9::int - 1) AS clause(idx)\n WHERE NOT EXISTS (\n SELECT 1\n FROM UNNEST($10::int[], $11::bool[], $12::uuid[], $13::text[])\n AS term(clause_idx, negated, definition_id, value)\n WHERE term.clause_idx = clause.idx\n AND term.negated <> EXISTS (\n SELECT 1 FROM entity_properties ep\n WHERE ep.entity_id = cr.id::text\n AND ep.entity_type = 'CALL_RECORD'\n AND jsonb_typeof(ep.values -> 'value') = 'array'\n AND CASE\n WHEN term.definition_id IS NULL\n THEN jsonb_exists(ep.values -> 'value', term.value)\n ELSE ep.property_definition_id = term.definition_id\n AND ep.values -> 'value' @> jsonb_build_array(\n jsonb_build_object('entity_id', term.value)\n )\n END\n )\n )\n )\n )\n SELECT\n call_id as \"call_id!\",\n channel_id as \"channel_id?\",\n room_name as \"room_name!\",\n created_by as \"created_by!\",\n started_at as \"started_at!\",\n ended_at,\n duration_ms,\n egress_id,\n recording_key,\n preview_url,\n recording_started_at,\n custom_name,\n summary,\n share_with_team as \"share_with_team!\",\n team_share_access_level as \"team_share_access_level?: AccessLevel\",\n is_active as \"is_active!\",\n status as \"status!\"\n FROM visible_calls\n WHERE ($7::bool IS FALSE OR status = ANY($8::text[]))\n -- Soup's keyset: calls sort by start, or by last activity.\n AND (\n $15::timestamptz IS NULL\n OR (\n CASE WHEN $14 THEN started_at ELSE COALESCE(ended_at, started_at) END,\n call_id::text\n ) < ($15, $16::text)\n )\n ORDER BY\n CASE WHEN $14 THEN started_at ELSE COALESCE(ended_at, started_at) END DESC,\n call_id::text DESC\n LIMIT $2\n ","describe": {"columns": [{@@ -115,7 +115,10 @@"Int4Array","BoolArray","UuidArray",- "TextArray"+ "TextArray",+ "Bool",+ "Timestamptz",+ "Text"]},"nullable": [@@ -138,5 +141,5 @@null]},- "hash": "e1ebe683de73f15ff6895e08b71c93ef2134b40434bab28c7e497869165cb76a"+ "hash": "1de43e6d6d7d68c1d7b5df8839afcac615c9c43b14d5853dd48f847ae24b25c0"}diff --git a/.sqlx/query-35b545b69ee0d3cfa9035243e7594ff395821ffb6d00e3e8326eab095ce23abe.json b/.sqlx/query-35b545b69ee0d3cfa9035243e7594ff395821ffb6d00e3e8326eab095ce23abe.jsonnew file mode 100644index 0000000000..34ec4e9864--- /dev/null+++ b/.sqlx/query-35b545b69ee0d3cfa9035243e7594ff395821ffb6d00e3e8326eab095ce23abe.json@@ -0,0 +1,18 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO comms_entity_mentions\n (id, source_entity_type, source_entity_id, entity_type, entity_id)\n VALUES ($1, $2, $3, $4, $5)",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Varchar",+ "Varchar",+ "Varchar",+ "Varchar"+ ]+ },+ "nullable": []+ },+ "hash": "35b545b69ee0d3cfa9035243e7594ff395821ffb6d00e3e8326eab095ce23abe"+}diff --git a/.sqlx/query-3a72f0730f9d9d40191f3cdf8f94e0ad7001e6d5ae729e349c226df1cf702921.json b/.sqlx/query-3a72f0730f9d9d40191f3cdf8f94e0ad7001e6d5ae729e349c226df1cf702921.jsonnew file mode 100644index 0000000000..9f1869a99a--- /dev/null+++ b/.sqlx/query-3a72f0730f9d9d40191f3cdf8f94e0ad7001e6d5ae729e349c226df1cf702921.json@@ -0,0 +1,24 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT EXISTS (\n SELECT 1\n FROM crm_contacts ct\n JOIN crm_companies co ON co.id = ct.company_id\n JOIN team_crm_settings tcs ON tcs.team_id = co.team_id AND tcs.crm_enabled\n WHERE ct.id = $1\n AND co.team_id = $2\n AND (NOT (ct.hidden OR co.hidden) OR $3)\n ) AS \"visible!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "visible!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Bool"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "3a72f0730f9d9d40191f3cdf8f94e0ad7001e6d5ae729e349c226df1cf702921"+}diff --git a/.sqlx/query-576f08c3b00a619dcfb753de1ff1f4b4a18a80b0582428971b9a9e320ab684b4.json b/.sqlx/query-576f08c3b00a619dcfb753de1ff1f4b4a18a80b0582428971b9a9e320ab684b4.jsonnew file mode 100644index 0000000000..fe7bbbcbab--- /dev/null+++ b/.sqlx/query-576f08c3b00a619dcfb753de1ff1f4b4a18a80b0582428971b9a9e320ab684b4.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT ct.id AS \"contact_id?\"\n FROM crm_companies co\n JOIN team_crm_settings tcs ON tcs.team_id = co.team_id AND tcs.crm_enabled\n JOIN team_user tu ON tu.team_id = co.team_id AND tu.user_id = $1\n LEFT JOIN crm_contacts ct\n ON ct.company_id = co.id\n AND (NOT ct.hidden OR tu.team_role <> 'member')\n WHERE co.id = $2\n AND (NOT co.hidden OR tu.team_role <> 'member')\n ORDER BY ct.id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "contact_id?",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Uuid"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "576f08c3b00a619dcfb753de1ff1f4b4a18a80b0582428971b9a9e320ab684b4"+}diff --git a/.sqlx/query-72f5be5d184ee20a2a47724ca3554f9aa413f239e2c72bac17a9c03b433aaa23.json b/.sqlx/query-72f5be5d184ee20a2a47724ca3554f9aa413f239e2c72bac17a9c03b433aaa23.jsonnew file mode 100644index 0000000000..db1abcb61e--- /dev/null+++ b/.sqlx/query-72f5be5d184ee20a2a47724ca3554f9aa413f239e2c72bac17a9c03b433aaa23.json@@ -0,0 +1,24 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT ct.id AS \"contact_id?\"\n FROM crm_companies co\n JOIN team_crm_settings tcs ON tcs.team_id = co.team_id AND tcs.crm_enabled\n LEFT JOIN crm_contacts ct\n ON ct.company_id = co.id AND (NOT ct.hidden OR $3)\n WHERE co.id = $1\n AND co.team_id = $2\n AND (NOT co.hidden OR $3)\n ORDER BY ct.id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "contact_id?",+ "type_info": "Uuid"+ }+ ],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Bool"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "72f5be5d184ee20a2a47724ca3554f9aa413f239e2c72bac17a9c03b433aaa23"+}diff --git a/.sqlx/query-7358d6cac7636a9ba689b9eb205d3bc3feba103fbe638795e6aceb98d5c4b33d.json b/.sqlx/query-7358d6cac7636a9ba689b9eb205d3bc3feba103fbe638795e6aceb98d5c4b33d.jsonnew file mode 100644index 0000000000..f2797cee2b--- /dev/null+++ b/.sqlx/query-7358d6cac7636a9ba689b9eb205d3bc3feba103fbe638795e6aceb98d5c4b33d.json@@ -0,0 +1,50 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT ep.entity_type AS \"entity_type!: EntityType\", ep.entity_id AS \"entity_id!\"\n FROM UNNEST($1::text[]) AS company(id)\n JOIN entity_properties ep\n ON ep.property_definition_id = '00000001-0000-0000-0000-00000000000c'\n AND ep.values->'value' @> jsonb_build_array(jsonb_build_object('entity_id', company.id))\n UNION\n SELECT ep.entity_type, ep.entity_id\n FROM UNNEST($2::text[]) AS contact(id)\n JOIN entity_properties ep\n ON ep.property_definition_id = '00000001-0000-0000-0000-000000000013'\n AND ep.values->'value' @> jsonb_build_array(jsonb_build_object('entity_id', contact.id))\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "entity_type!: EntityType",+ "type_info": {+ "Custom": {+ "name": "property_entity_type",+ "kind": {+ "Enum": [+ "CHANNEL",+ "CHAT",+ "DOCUMENT",+ "PROJECT",+ "THREAD",+ "USER",+ "COMPANY",+ "TASK",+ "CALL_RECORD",+ "CALENDAR_EVENT",+ "INITIATIVE",+ "CONTACT",+ "DATABASE_ROW"+ ]+ }+ }+ }+ },+ {+ "ordinal": 1,+ "name": "entity_id!",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "TextArray",+ "TextArray"+ ]+ },+ "nullable": [+ null,+ null+ ]+ },+ "hash": "7358d6cac7636a9ba689b9eb205d3bc3feba103fbe638795e6aceb98d5c4b33d"+}diff --git a/.sqlx/query-8f261b220f11eb34a1ddacd71d17232dc6d9abff75cafceb7629f1cd713c3ef4.json b/.sqlx/query-8f261b220f11eb34a1ddacd71d17232dc6d9abff75cafceb7629f1cd713c3ef4.jsonnew file mode 100644index 0000000000..da4527b500--- /dev/null+++ b/.sqlx/query-8f261b220f11eb34a1ddacd71d17232dc6d9abff75cafceb7629f1cd713c3ef4.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT EXISTS (\n SELECT 1\n FROM crm_contacts ct\n JOIN crm_companies co ON co.id = ct.company_id\n JOIN team_crm_settings tcs ON tcs.team_id = co.team_id AND tcs.crm_enabled\n JOIN team_user tu ON tu.team_id = co.team_id AND tu.user_id = $1\n WHERE ct.id = $2\n AND (NOT (ct.hidden OR co.hidden) OR tu.team_role <> 'member')\n ) AS \"visible!\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "visible!",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Uuid"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "8f261b220f11eb34a1ddacd71d17232dc6d9abff75cafceb7629f1cd713c3ef4"+}diff --git a/.sqlx/query-936ddff3d066fb4319e4781cd2b18920cb0254242556702b5798286cc1b6df3c.json b/.sqlx/query-936ddff3d066fb4319e4781cd2b18920cb0254242556702b5798286cc1b6df3c.jsonnew file mode 100644index 0000000000..42feba15b5--- /dev/null+++ b/.sqlx/query-936ddff3d066fb4319e4781cd2b18920cb0254242556702b5798286cc1b6df3c.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO comms_attachments (id, message_id, entity_type, entity_id)\n VALUES ($1, $2, 'crm_company', $3)",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Uuid",+ "Varchar"+ ]+ },+ "nullable": []+ },+ "hash": "936ddff3d066fb4319e4781cd2b18920cb0254242556702b5798286cc1b6df3c"+}diff --git a/.sqlx/query-d4acdd029935389e603e8ccb57e4490f2cbd478479778c9abd42ed6c1c4da784.json b/.sqlx/query-d4acdd029935389e603e8ccb57e4490f2cbd478479778c9abd42ed6c1c4da784.jsonnew file mode 100644index 0000000000..36d3cfd300--- /dev/null+++ b/.sqlx/query-d4acdd029935389e603e8ccb57e4490f2cbd478479778c9abd42ed6c1c4da784.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "INSERT INTO comms_messages\n (id, parent_entity_type, parent_entity_id, sender_id, content)\n VALUES ($1, 'document', 'doc-with-discussion', 'macro|[email protected]', 'discussion')",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid"+ ]+ },+ "nullable": []+ },+ "hash": "d4acdd029935389e603e8ccb57e4490f2cbd478479778c9abd42ed6c1c4da784"+}diff --git a/apps/web/src/features/crm/context/crm-context.tsx b/apps/web/src/features/crm/context/crm-context.tsxindex 6ff4703b17..d94b7ca2b8 100644--- a/apps/web/src/features/crm/context/crm-context.tsx+++ b/apps/web/src/features/crm/context/crm-context.tsx@@ -81,6 +81,10 @@ export type CrmContext = {createRecordCalls(scope: Accessor<CrmRecordScope | undefined>): ItemListSource;+ /** Items associated with the record through properties or references. */+ createRecordReferences(+ scope: Accessor<CrmRecordScope | undefined>+ ): ItemListSource;/** The record's Tasks tab, scoped to tasks associated with it. */RecordTasks: Component<{ scope: CrmRecordScope }>;createPropertyCommands(): PropertyCommands;diff --git a/apps/web/src/features/crm/context/crm-sources.ts b/apps/web/src/features/crm/context/crm-sources.tsindex 98319b8d58..193474d0b5 100644--- a/apps/web/src/features/crm/context/crm-sources.ts+++ b/apps/web/src/features/crm/context/crm-sources.ts@@ -116,7 +116,7 @@ export type ListsSource = {export type CrmEmailScope = 'team' | 'me';export type CrmEmailSignal = 'signal' | 'all';-/** A paged soup list: email threads, files or calls of a CRM record. */+/** A paged soup list: email threads, files, calls or references of a CRM record. */export type ItemListSource = {/** True until the first page is readable (including disabled queries). */readonly isPending: boolean;@@ -126,7 +126,15 @@ export type ItemListSource = {readonly data: { entities: import('@entity').EntityData[] } | undefined;readonly hasNextPage: boolean;readonly isFetchingNextPage: boolean;+ /**+ * The query failed, on its first page or on a refetch; distinct from an+ * empty list, and any loaded rows are no longer current.+ */+ readonly isError: boolean;+ /** A continuation page failed; the loaded pages remain current. */+ readonly isFetchNextPageError: boolean;fetchNextPage(): Promise<unknown>;+ refetch(): Promise<unknown>;};export type CompanyPropertySave = {properties: {diff --git a/apps/web/src/features/crm/crm-adapter.ts b/apps/web/src/features/crm/crm-adapter.tsindex 40fab89e28..e1678a0131 100644--- a/apps/web/src/features/crm/crm-adapter.ts+++ b/apps/web/src/features/crm/crm-adapter.ts@@ -13,7 +13,10 @@ import { idToEmail } from '@core/user/util';import { queryReadyGate } from '@queries/gate';import { useListPropertiesQuery } from '@queries/properties/definitions';import { useBulkSaveEntityPropertiesMutation } from '@queries/properties/entity';-import { useSoupAstItemsQuery } from '@queries/soup/items';+import {+ type SoupAstItemsQuery,+ useSoupAstItemsQuery,+} from '@queries/soup/items';import { getSoupEntityById } from '@queries/soup/normalized-cache';import {invalidateUserTeams,@@ -63,8 +66,10 @@ import { fetchCrmExportCompanies } from './queries/export';import { useCrmLists } from './queries/lists';import { createPipelinesSource } from './queries/pipelines';import {+ recordListFailure,useRecordCallsQuery,useRecordFilesQuery,+ useRecordReferencesQuery,} from './queries/record-items';import { usePersonalCrmViews, useTeamCrmViews } from './queries/saved-views';import { usePatchTeamCrmSettingsMutation } from './queries/settings-commands';@@ -84,7 +89,7 @@ const CrmRecordTasks = lazy(async () => ({* Soup rows carry raw notification arrays; `ListEntity` reads them through* an accessor bound to the app's notification source, as other lists do.*/-function withRowNotifications(source: ItemListSource): ItemListSource {+function withRowNotifications(source: SoupAstItemsQuery): ItemListSource {const notificationSource = useGlobalNotificationSource();// Reading `data` before the first page resolves would suspend the tab.const data = createMemo(() =>@@ -115,7 +120,14 @@ function withRowNotifications(source: ItemListSource): ItemListSource {get isFetchingNextPage() {return source.isFetchingNextPage;},+ get isError() {+ return recordListFailure(source).isError;+ },+ get isFetchNextPageError() {+ return recordListFailure(source).isFetchNextPageError;+ },fetchNextPage: () => source.fetchNextPage(),+ refetch: () => source.refetch(),};}@@ -188,6 +200,10 @@ export function createAppCrmContext(): CrmContext {withRowNotifications(useRecordFilesQuery(useSoupAstItemsQuery, scope)),createRecordCalls: (scope) =>withRowNotifications(useRecordCallsQuery(useSoupAstItemsQuery, scope)),+ createRecordReferences: (scope) =>+ withRowNotifications(+ useRecordReferencesQuery(useSoupAstItemsQuery, scope)+ ),RecordTasks: CrmRecordTasks,createPropertyCommands: useBulkSaveEntityPropertiesMutation,createSettingsCommands: () =>diff --git a/apps/web/src/features/crm/queries/record-items.test.ts b/apps/web/src/features/crm/queries/record-items.test.tsindex c21a6dadfd..d5c08ff763 100644--- a/apps/web/src/features/crm/queries/record-items.test.ts+++ b/apps/web/src/features/crm/queries/record-items.test.ts@@ -1,9 +1,11 @@import { NIL_UUID } from '@app/features/next-soup/filters/filter-store';import { describe, expect, it } from 'vitest';-import { recordCallsBody, recordFilesBody } from './record-items';--const COMPANIES = '00000001-0000-0000-0000-00000000000c';-const CONTACTS = '00000001-0000-0000-0000-000000000013';+import {+ recordCallsBody,+ recordFilesBody,+ recordListFailure,+ recordReferencesBody,+} from './record-items';describe('CRM record item queries', () => {it('lists non-task files associated with a company or attached to emails with its domains', () => {@@ -20,7 +22,7 @@ describe('CRM record item queries', () => {'|': [{'|': [- { l: { prop: { pd: COMPANIES, v: { er: 'company-1' } } } },+ { l: { crm: { company: 'company-1' } } },{ l: { eap: { Domain: 'acme.com' } } },],},@@ -29,11 +31,12 @@ describe('CRM record item queries', () => {},],});+ expect(body).not.toHaveProperty('crma');expect(body.callf).toEqual({ l: { CallId: NIL_UUID } });expect(body.ef).toEqual({ l: { ThreadId: NIL_UUID } });});- it('matches a contact by its exact address', () => {+ it('matches a contact through its association or its exact address', () => {const body = recordFilesBody({type: 'contact',id: 'contact-1',@@ -43,13 +46,13 @@ describe('CRM record item queries', () => {expect(body.df['&'][1]).toEqual({'|': [- { l: { prop: { pd: CONTACTS, v: { er: 'contact-1' } } } },+ { l: { crm: { contact: 'contact-1' } } },{ l: { eap: { Complete: '[email protected]' } } },],});});- it('lists only calls, through the record property', () => {+ it('lists only calls associated with the record', () => {const body = recordCallsBody({type: 'company',id: 'company-1',@@ -57,10 +60,39 @@ describe('CRM record item queries', () => {});expect(body).not.toHaveProperty('callf');- expect(body.propf).toEqual({- l: { pd: COMPANIES, v: { er: 'company-1' } },- });+ expect(body).not.toHaveProperty('propf');+ expect(body.crma).toEqual({ company: 'company-1' });expect(body.df).toEqual({ l: { id: NIL_UUID } });expect(body.ef).toEqual({ l: { ThreadId: NIL_UUID } });});++ it('lists every associated item for references, including other CRM records', () => {+ expect(+ recordReferencesBody({+ type: 'contact',+ id: 'contact-1',+ email: '[email protected]',+ companyId: 'company-1',+ })+ ).toEqual({+ crma: { contact: 'contact-1' },+ crmf: { l: 'include' },+ emailView: 'all',+ });+ });++ it('keeps loaded rows only when a continuation page failed', () => {+ const error = new Error('CRM record not found');+ expect(recordListFailure({ error, isFetchNextPageError: false })).toEqual({+ isError: true,+ isFetchNextPageError: false,+ });+ expect(recordListFailure({ error, isFetchNextPageError: true })).toEqual({+ isError: false,+ isFetchNextPageError: true,+ });+ expect(+ recordListFailure({ error: null, isFetchNextPageError: false })+ ).toEqual({ isError: false, isFetchNextPageError: false });+ });});diff --git a/apps/web/src/features/crm/queries/record-items.ts b/apps/web/src/features/crm/queries/record-items.tsindex 88ac194d3a..5566ae9fe2 100644--- a/apps/web/src/features/crm/queries/record-items.ts+++ b/apps/web/src/features/crm/queries/record-items.ts@@ -1,21 +1,15 @@import { NIL_UUID } from '@app/features/next-soup/filters/filter-store';-import { SYSTEM_PROPERTY_IDS } from '@property/identifiers';-import type { useSoupAstItemsQuery } from '@queries/soup/items';+import type {+ SoupAstItemsQuery,+ useSoupAstItemsQuery,+} from '@queries/soup/items';import type { Accessor } from 'solid-js';import { match } from 'ts-pattern';import type { CrmRecordScope } from '../core/record';-/** The system property that associates entities with this kind of record. */-export function crmRecordPropertyId(scope: CrmRecordScope): string {- return match(scope.type)- .with('company', () => SYSTEM_PROPERTY_IDS.COMPANIES)- .with('contact', () => SYSTEM_PROPERTY_IDS.CONTACTS)- .exhaustive();-}-type AstNode = Record<string, unknown>;-const leaf = (literal: AstNode): AstNode => ({ l: literal });+const leaf = (literal: AstNode | string): AstNode => ({ l: literal });const or = (nodes: AstNode[]): AstNode =>nodes.reduce((acc, node) => ({ '|': [acc, node] }));@@ -33,11 +27,17 @@ const NO_ITEMS = {ef: leaf({ ThreadId: NIL_UUID }),};-/** The record's Companies/Contacts reference, as a property literal. */-const associatedLiteral = (scope: CrmRecordScope): AstNode => ({- pd: crmRecordPropertyId(scope),- v: { er: scope.id },-});+/**+ * The record as a Soup CRM association: items whose Companies or Contacts+ * property names it, or that reference it. A company also matches through+ * every one of its contacts; the server expands and authorizes the record.+ */+export function crmAssociation(scope: CrmRecordScope) {+ return match(scope)+ .with({ type: 'company' }, ({ id }) => ({ company: id }))+ .with({ type: 'contact' }, ({ id }) => ({ contact: id }))+ .exhaustive();+}/** Email addresses or domains of the people at the record. */const participants = (scope: CrmRecordScope): AstNode[] =>@@ -51,8 +51,8 @@ const participants = (scope: CrmRecordScope): AstNode[] =>.exhaustive();/**- * Non-task documents associated with the record through its Companies or- * Contacts property, plus attachments of emails exchanged with its people.+ * Non-task documents associated with the record, plus attachments of emails+ * exchanged with its people.*/export function recordFilesBody(scope: CrmRecordScope) {return {@@ -60,7 +60,7 @@ export function recordFilesBody(scope: CrmRecordScope) {df: {'&': [{ '!': leaf({ dst: 'task' }) },- or([leaf({ prop: associatedLiteral(scope) }), ...participants(scope)]),+ or([leaf({ crm: crmAssociation(scope) }), ...participants(scope)]),],},};@@ -68,11 +68,41 @@ export function recordFilesBody(scope: CrmRecordScope) {/*** Calls associated with the record. Calls are linked to the CRM records of- * their participants when they end, so the property alone covers both.+ * their participants when they end, and call threads can mention the record.*/export function recordCallsBody(scope: CrmRecordScope) {const { callf: _calls, ...others } = NO_ITEMS;- return { ...others, propf: leaf(associatedLiteral(scope)) };+ return { ...others, crma: crmAssociation(scope) };+}++/**+ * Items of any type associated with the record: files, tasks, chats,+ * projects, email threads, channels, channel messages, calls, events, and+ * other CRM records whose discussions reference it. Initiatives and database+ * rows are opt-in Soup sources this body does not request.+ */+export function recordReferencesBody(scope: CrmRecordScope) {+ return {+ crma: crmAssociation(scope),+ crmf: leaf('include'),+ emailView: 'all' as const,+ };+}++/**+ * How a failed record list presents. A failed continuation page keeps the+ * loaded rows and retries that page. Any other failure, including a refetch+ * after the record became inaccessible, means the loaded rows are no longer+ * current: the list shows the failure and retries the query.+ */+export function recordListFailure(+ source: Pick<SoupAstItemsQuery, 'error' | 'isFetchNextPageError'>+) {+ const failed = source.error != null;+ return {+ isError: failed && !source.isFetchNextPageError,+ isFetchNextPageError: failed && source.isFetchNextPageError,+ };}const PARAMS = { limit: 100, sort_method: 'updated_at' } as const;@@ -94,6 +124,23 @@ export function useRecordFilesQuery();}+/** Items of any type associated with a CRM record, via `/soup/ast`. */+export function useRecordReferencesQuery(+ createQuery: typeof useSoupAstItemsQuery,+ scope: Accessor<CrmRecordScope | undefined>+) {+ return createQuery(+ () => {+ const current = scope();+ return {+ params: PARAMS,+ body: current ? recordReferencesBody(current) : NO_ITEMS,+ };+ },+ () => ({ enabled: !!scope() })+ );+}+/** Calls associated with a CRM record, via `/soup/ast`. */export function useRecordCallsQuery(createQuery: typeof useSoupAstItemsQuery,diff --git a/apps/web/src/features/crm/record-tasks-adapter.tsx b/apps/web/src/features/crm/record-tasks-adapter.tsxindex 7ff10055eb..155cf1a349 100644--- a/apps/web/src/features/crm/record-tasks-adapter.tsx+++ b/apps/web/src/features/crm/record-tasks-adapter.tsx@@ -16,12 +16,12 @@ import { Show } from 'solid-js';import { match } from 'ts-pattern';import { RecordSection } from './components/record-section';import type { CrmRecordScope } from './core/record';-import { crmRecordPropertyId } from './queries/record-items';/**- * The record's Tasks tab: the production Tasks list, scoped to tasks whose- * Companies or Contacts property references the record. It owns its tag- * sets because a standalone record has no list provider above it.+ * The record's Tasks tab: the production Tasks list, scoped to tasks+ * associated with the record through its Companies or Contacts property or a+ * reference (for a company, also through any of its contacts). It owns its+ * tag sets because a standalone record has no list provider above it.*/export function CrmRecordTasks(props: { scope: CrmRecordScope }) {const layout = useSplitLayout();@@ -44,10 +44,7 @@ export function CrmRecordTasks(props: { scope: CrmRecordScope }) {sourceFactory={(state, options) =>useTasksDataSource(state, {...options,- reference: () => ({- propertyDefinitionId: crmRecordPropertyId(scope),- entityId: scope.id,- }),+ crm: () => ({ type: scope.type, id: scope.id }),})}>diff --git a/apps/web/src/features/crm/views/company-detail.tsx b/apps/web/src/features/crm/views/company-detail.tsxindex 4d3f182cfb..29bd38bee9 100644--- a/apps/web/src/features/crm/views/company-detail.tsx+++ b/apps/web/src/features/crm/views/company-detail.tsx@@ -17,14 +17,19 @@ import { CompanyHeader } from './company-header';import { CompanyListsSection } from './company-list-membership';import { CompanyPropertiesSection } from './company-properties-section';import { CompanySharingSection } from './company-sharing-section';-import { RecordCallsSection, RecordFilesSection } from './record-associations';+import {+ RecordCallsSection,+ RecordFilesSection,+ RecordReferencesSection,+} from './record-associations';import { useCompanyQuery } from './use-crm';/*** Root of the company detail view, laid out like a project: the host's top* tab row picks the section, Overview shows the company with its description and* discussion, and the other sections list its team, emails, files, tasks and- * calls. Properties and sharing open in the floating information panel.+ * calls. Properties, sharing, and references open in the floating+ * information panel.*/export function Company(props: {companyId: string;@@ -159,8 +164,9 @@ export function Company(props: {<SidePanel.Section id="company-sharing" title="Sharing" order={25}><CompanySharingSection company={company()} onHidden={props.onHidden} /></SidePanel.Section>- {/* TODO: add a References section (inbound channel messages + documents)- once the references backend supports the crm_company entity type. */}+ <SidePanel.Section id="company-references" title="References" order={30}>+ <RecordReferencesSection scope={scope()} />+ </SidePanel.Section></SidePanel.Layout>);}diff --git a/apps/web/src/features/crm/views/contact-detail.tsx b/apps/web/src/features/crm/views/contact-detail.tsxindex 7f1a2d53e0..72c4b46926 100644--- a/apps/web/src/features/crm/views/contact-detail.tsx+++ b/apps/web/src/features/crm/views/contact-detail.tsx@@ -10,14 +10,18 @@ import { ContactDiscussionSection } from './contact-discussion-section';import { ContactEmailsSection } from './contact-emails-section';import { ContactHeader } from './contact-header';import { ContactSharingSection } from './contact-sharing-section';-import { RecordCallsSection, RecordFilesSection } from './record-associations';+import {+ RecordCallsSection,+ RecordFilesSection,+ RecordReferencesSection,+} from './record-associations';import { useContactQuery, useIsTeamAdmin } from './use-crm';/*** Root of the contact detail view, laid out like a project: the host's top* bar picks the section, Overview shows the contact and its discussion, and- * the other sections list its emails, files, tasks and calls. Sharing stays- * in the floating information panel.+ * the other sections list its emails, files, tasks and calls. Sharing and+ * references stay in the floating information panel.*/export function Contact(props: {contactId: string;@@ -113,8 +117,9 @@ export function Contact(props: {<ContactSharingSection contact={contact()} /></SidePanel.Section></Show>- {/* TODO: add a References section (inbound channel messages + documents)- once the references backend supports the crm_contact entity type. */}+ <SidePanel.Section id="contact-references" title="References" order={30}>+ <RecordReferencesSection scope={scope()} />+ </SidePanel.Section></SidePanel.Layout>);}diff --git a/apps/web/src/features/crm/views/record-associations.tsx b/apps/web/src/features/crm/views/record-associations.tsxindex 15db8fedc3..0303ece0aa 100644--- a/apps/web/src/features/crm/views/record-associations.tsx+++ b/apps/web/src/features/crm/views/record-associations.tsx@@ -4,8 +4,8 @@ import type { CrmRecordScope } from '../core/record';import { RecordItemList } from './record-item-list';/**- * Documents associated with the record, plus attachments of emails- * exchanged with its people.+ * Documents associated with the record through its properties or references,+ * plus attachments of emails exchanged with its people.*/export function RecordFilesSection(props: { scope?: CrmRecordScope }) {const files = useCrmContext().createRecordFiles(() => props.scope);@@ -20,7 +20,10 @@ export function RecordFilesSection(props: { scope?: CrmRecordScope }) {);}-/** Calls associated with the record, including calls with its people. */+/**+ * Calls associated with the record: linked to it or (for a company) to one of+ * its contacts when the call ended, or referencing it in the call thread.+ */export function RecordCallsSection(props: { scope?: CrmRecordScope }) {const calls = useCrmContext().createRecordCalls(() => props.scope);return (@@ -33,3 +36,20 @@ export function RecordCallsSection(props: { scope?: CrmRecordScope }) {</RecordSection>);}++/**+ * Items of any type associated with the record: what names it in a+ * Companies or Contacts property and what references it, including through a+ * company's contacts. Lives in the floating information panel.+ */+export function RecordReferencesSection(props: { scope?: CrmRecordScope }) {+ const references = useCrmContext().createRecordReferences(() => props.scope);+ return (+ <RecordItemList+ source={references}+ pending={!props.scope}+ empty={`Nothing references this ${props.scope?.type ?? 'record'} yet.`}+ narrowLayout="condensed"+ />+ );+}diff --git a/apps/web/src/features/crm/views/record-item-list.test.tsx b/apps/web/src/features/crm/views/record-item-list.test.tsxnew file mode 100644index 0000000000..c47c817044--- /dev/null+++ b/apps/web/src/features/crm/views/record-item-list.test.tsx@@ -0,0 +1,70 @@+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';+import type { ParentProps } from 'solid-js';+import { afterEach, expect, it, vi } from 'vitest';+import type { ItemListSource } from '../context/crm-sources';+import { RecordItemList } from './record-item-list';++vi.mock('@entity', () => ({+ ListEntity: (props: { entity: { name: string } }) => (+ <div>{props.entity.name}</div>+ ),+ ListEntityMetadataQueryProvider: (props: ParentProps) => props.children,+ ListLayoutProvider: (props: ParentProps) => props.children,+}));+vi.mock('@ui', () => ({+ Button: (props: ParentProps<{ onClick: () => void }>) => (+ <button type="button" onClick={props.onClick}>+ {props.children}+ </button>+ ),+}));+vi.mock('../../../lib/primitives/infinite-scroll-sentinel', () => ({+ useInfiniteScrollSentinel: vi.fn(),+}));+vi.mock('../context/crm-context', () => ({+ useCrmContext: () => ({+ createNavigation: () => ({ openEntity: vi.fn() }),+ }),+}));++afterEach(cleanup);++function source(overrides: Partial<ItemListSource>): ItemListSource {+ return {+ isPending: false,+ isEnabled: true,+ isLoading: false,+ data: {+ entities: [{ id: 'doc-1', name: 'Kickoff notes' }] as never,+ },+ hasNextPage: false,+ isFetchingNextPage: false,+ isError: false,+ isFetchNextPageError: false,+ fetchNextPage: vi.fn(async () => undefined),+ refetch: vi.fn(async () => undefined),+ ...overrides,+ };+}++it('replaces cached rows and retries the query after a failed refetch', () => {+ const failed = source({ isError: true });+ render(() => <RecordItemList source={failed} empty="Nothing" />);++ expect(screen.queryByText('Kickoff notes')).toBeNull();+ screen.getByText("Couldn't load this list.");+ fireEvent.click(screen.getByText('Retry'));+ expect(failed.refetch).toHaveBeenCalledTimes(1);+ expect(failed.fetchNextPage).not.toHaveBeenCalled();+});++it('keeps loaded rows and retries the page after a failed continuation', () => {+ const failed = source({ isFetchNextPageError: true, hasNextPage: true });+ render(() => <RecordItemList source={failed} empty="Nothing" />);++ screen.getByText('Kickoff notes');+ screen.getByText("Couldn't load more.");+ fireEvent.click(screen.getByText('Retry'));+ expect(failed.fetchNextPage).toHaveBeenCalledTimes(1);+ expect(failed.refetch).not.toHaveBeenCalled();+});diff --git a/apps/web/src/features/crm/views/record-item-list.tsx b/apps/web/src/features/crm/views/record-item-list.tsxindex cc4f01aa33..6b434d628b 100644--- a/apps/web/src/features/crm/views/record-item-list.tsx+++ b/apps/web/src/features/crm/views/record-item-list.tsx@@ -2,21 +2,26 @@ import {ListEntity,ListEntityMetadataQueryProvider,ListLayoutProvider,+ type NarrowLayoutVariant,} from '@entity';-import { createSignal, For, type JSX, Show } from 'solid-js';+import { Button } from '@ui';+import { createSignal, For, type JSX, Match, Show, Switch } from 'solid-js';import { useInfiniteScrollSentinel } from '../../../lib/primitives/infinite-scroll-sentinel';import { useCrmContext } from '../context/crm-context';import type { ItemListSource } from '../context/crm-sources';/**- * One of a CRM record's soup lists (emails, files or calls): unified-list- * rows that open in a split, paging in as the end scrolls into view.+ * One of a CRM record's soup lists (emails, files, calls or references):+ * unified-list rows that open in a split, paging in as the end scrolls into+ * view. A failed request shows a retry instead of the empty state.*/export function RecordItemList(props: {source: ItemListSource;/** Hold the loading state, e.g. while the record itself loads. */pending?: boolean;empty: JSX.Element;+ /** Row layout when the list is narrow, e.g. in the information panel. */+ narrowLayout?: NarrowLayoutVariant;}) {const { openEntity } = useCrmContext().createNavigation();// Reading `data` before the first page resolves would suspend the tab.@@ -27,7 +32,8 @@ export function RecordItemList(props: {useInfiniteScrollSentinel({sentinel: sentinelRef,- hasNextPage: () => props.source.hasNextPage ?? false,+ hasNextPage: () =>+ (props.source.hasNextPage ?? false) && !props.source.isFetchNextPageError,isFetchingNextPage: () => props.source.isFetchingNextPage,fetchNextPage: () => props.source.fetchNextPage(),});@@ -38,22 +44,24 @@ export function RecordItemList(props: {props.pending || (props.source.isPending && props.source.isEnabled);return (- <Show- when={!loading()}- fallback={+ <Switch>+ <Match when={loading()}><div class="p-6 text-center text-sm text-ink-muted">Loading…</div>- }- >- <Show- when={items().length > 0}- fallback={- <div class="rounded-lg border border-dashed border-edge-muted p-6 text-center text-sm text-ink-muted">- {props.empty}- </div>- }- >+ </Match>+ <Match when={props.source.isError}>+ <RetryNotice+ message="Couldn't load this list."+ onRetry={() => props.source.refetch()}+ />+ </Match>+ <Match when={items().length === 0}>+ <div class="rounded-lg border border-dashed border-edge-muted p-6 text-center text-sm text-ink-muted">+ {props.empty}+ </div>+ </Match>+ <Match when={items().length > 0}><ListEntityMetadataQueryProvider>- <ListLayoutProvider ref={listRef}>+ <ListLayoutProvider ref={listRef} narrowLayout={props.narrowLayout}><div ref={setListRef} class="flex flex-col"><For each={items()}>{(entity) => (@@ -67,15 +75,40 @@ export function RecordItemList(props: {</div></ListLayoutProvider></ListEntityMetadataQueryProvider>- <Show when={props.source.hasNextPage}>- <div ref={setSentinelRef} class="h-px" />- </Show>- <Show when={props.source.isFetchingNextPage}>- <div class="p-3 text-center text-xs text-ink-muted">- Loading more…- </div>+ <Show+ when={!props.source.isFetchNextPageError}+ fallback={+ <RetryNotice+ message="Couldn't load more."+ onRetry={() => props.source.fetchNextPage()}+ />+ }+ >+ <Show when={props.source.hasNextPage}>+ <div ref={setSentinelRef} class="h-px" />+ </Show>+ <Show when={props.source.isFetchingNextPage}>+ <div class="p-3 text-center text-xs text-ink-muted">+ Loading more…+ </div>+ </Show></Show>- </Show>- </Show>+ </Match>+ </Switch>+ );+}++/** A failed request, kept distinct from an empty list, with a retry. */+function RetryNotice(props: {+ message: string;+ onRetry: () => Promise<unknown>;+}) {+ return (+ <div class="flex items-center justify-center gap-2 p-3 text-center text-xs text-ink-muted">+ <span>{props.message}</span>+ <Button variant="ghost" size="sm" onClick={() => void props.onRetry()}>+ Retry+ </Button>+ </div>);}diff --git a/apps/web/src/features/email-view/queries/use-email-query.test.ts b/apps/web/src/features/email-view/queries/use-email-query.test.tsindex be07b8ca14..738383b4ab 100644--- a/apps/web/src/features/email-view/queries/use-email-query.test.ts+++ b/apps/web/src/features/email-view/queries/use-email-query.test.ts@@ -203,6 +203,7 @@ function mount(search = '') {error: null,hasNextPage: true,isFetchingNextPage: false,+ isFetchNextPageError: false,isEnabled: true,transport: 'graphql',fetchNextPage: vi.fn(async () => {}),@@ -218,6 +219,7 @@ function mount(search = '') {error: null,hasNextPage: false,isFetchingNextPage: false,+ isFetchNextPageError: false,isEnabled: true,transport: 'graphql',fetchNextPage: vi.fn(async () => {}),diff --git a/apps/web/src/features/home/queries/use-home-query.test.ts b/apps/web/src/features/home/queries/use-home-query.test.tsindex 4fc489a320..a0ffeb127b 100644--- a/apps/web/src/features/home/queries/use-home-query.test.ts+++ b/apps/web/src/features/home/queries/use-home-query.test.ts@@ -132,6 +132,7 @@ function makeQuery(initial: EntityData[], hasMore = true) {},isFetching: false,isFetchingNextPage: false,+ isFetchNextPageError: false,isPlaceholderData: false,isEnabled: true,transport: 'rest',diff --git a/apps/web/src/features/tasks-view/queries/scoped-task-search.test.ts b/apps/web/src/features/tasks-view/queries/scoped-task-search.test.tsnew file mode 100644index 0000000000..9972ac9477--- /dev/null+++ b/apps/web/src/features/tasks-view/queries/scoped-task-search.test.ts@@ -0,0 +1,73 @@+import { createRoot, createSignal } from 'solid-js';+import { expect, it, vi } from 'vitest';++const fixture = vi.hoisted(() => ({+ calls: [] as { args: () => unknown; options: () => unknown }[],+ query: {} as Record<string, unknown>,+}));+vi.mock('@core/util/debounce', () => ({+ debouncedDependent: (value: () => string) => value,+}));+vi.mock('@queries/soup/items', () => ({+ useSoupAstItemsQuery: (args: () => unknown, options: () => unknown) => {+ fixture.calls.push({ args, options });+ return fixture.query;+ },+}));++import {+ createScopedTaskSearch,+ scopedTaskSearchText,+} from './scoped-task-search';++it('matches quoted phrases without their quotes', () => {+ expect(scopedTaskSearchText(' "renewal call" ')).toBe('renewal call');+ expect(scopedTaskSearchText(' renewal ')).toBe('renewal');+ expect(scopedTaskSearchText('"')).toBe('"');+});++it('pages the scoped list query by name and stays off without text', () => {+ fixture.calls = [];+ fixture.query = {+ isPending: false,+ isPlaceholderData: false,+ isFetching: false,+ hasNextPage: true,+ isFetchingNextPage: false,+ error: null,+ data: { entities: [{ id: 'task' }] },+ fetchNextPage: vi.fn(),+ };+ createRoot((dispose) => {+ try {+ const [text, setText] = createSignal('');+ const search = createScopedTaskSearch({+ text,+ enabled: () => true,+ args: (nameContains) => ({+ params: { limit: 100 },+ body: { crma: { company: 'acme' }, nc: nameContains },+ groupBy: { type: 'date' },+ }),+ });+ const call = fixture.calls[0];+ expect(search.isSearching()).toBe(false);+ expect(call?.options()).toEqual({ enabled: false });+ expect(search.data()).toEqual([]);+ expect(search.hasNextPage()).toBe(false);++ setText('renewal');+ expect(call?.options()).toEqual({ enabled: true });+ // Search pages flat through the scoped query's own cursor.+ expect(call?.args()).toEqual({+ params: { limit: 100 },+ body: { crma: { company: 'acme' }, nc: 'renewal' },+ });+ expect(search.usesServiceSearch()).toBe(true);+ expect(search.data()).toEqual([{ id: 'task' }]);+ expect(search.hasNextPage()).toBe(true);+ } finally {+ dispose();+ }+ });+});diff --git a/apps/web/src/features/tasks-view/queries/scoped-task-search.ts b/apps/web/src/features/tasks-view/queries/scoped-task-search.tsnew file mode 100644index 0000000000..f2dae18cdb--- /dev/null+++ b/apps/web/src/features/tasks-view/queries/scoped-task-search.ts@@ -0,0 +1,75 @@+import { debouncedDependent } from '@core/util/debounce';+import type { EntityData } from '@entity';+import { queryReadyGate } from '@queries/gate';+import {+ type SoupAstItemsQueryArgs,+ useSoupAstItemsQuery,+} from '@queries/soup/items';+import { type Accessor, createMemo } from 'solid-js';++const SCOPED_SEARCH_DEBOUNCE_MS = 300;++/** Text a task name must contain; a quoted phrase matches without quotes. */+export function scopedTaskSearchText(text: string): string {+ const trimmed = text.trim();+ const quoted =+ trimmed.length >= 2 && trimmed.startsWith('"') && trimmed.endsWith('"');+ return quoted ? trimmed.slice(1, -1).trim() : trimmed;+}++/**+ * Task search for a list whose membership only the server can resolve, such+ * as tasks associated with a CRM record. The search service cannot express+ * that scope, so the list's own Soup query runs again with a name filter and+ * pages through its cursor; matches never come from unscoped results.+ */+export function createScopedTaskSearch(options: {+ text: Accessor<string>;+ args: (nameContains: string) => SoupAstItemsQueryArgs;+ enabled: Accessor<boolean>;+}) {+ const text = createMemo(() => scopedTaskSearchText(options.text()));+ const debouncedText = debouncedDependent(text, SCOPED_SEARCH_DEBOUNCE_MS);+ const isSearching = () => text().length > 0;+ const isSettled = () => text() === debouncedText();+ const queryEnabled = () =>+ options.enabled() && isSearching() && debouncedText().length > 0;++ const query = useSoupAstItemsQuery(+ () => {+ const { groupBy: _flat, ...args } = options.args(debouncedText());+ return args;+ },+ () => ({ enabled: queryEnabled() })+ );++ const isQueryLoading = () =>+ isSearching() &&+ (!isSettled() ||+ (queryEnabled() && (query.isPending || query.isPlaceholderData)));+ // Results for an earlier term are never shown for the current one.+ const data = createMemo<EntityData[]>(() =>+ queryEnabled() &&+ isSettled() &&+ !query.isPlaceholderData &&+ queryReadyGate(query)+ ? query.data.entities+ : []+ );++ return {+ isSearching,+ data,+ // Results are only shown once the debounced query settles.+ isLocalSearchSettling: () => isSearching() && !isSettled(),+ isSettling: () => isQueryLoading(),+ usesServiceSearch: isSearching,+ isLoading: () => isQueryLoading() && data().length === 0,+ isFetching: () => isQueryLoading() || (queryEnabled() && query.isFetching),+ error: () => (queryEnabled() ? (query.error ?? undefined) : undefined),+ hasNextPage: () => queryEnabled() && query.hasNextPage,+ isFetchingNextPage: () => queryEnabled() && query.isFetchingNextPage,+ fetchNextPage: () => query.fetchNextPage(),+ refetch: () => query.refetch(),+ };+}diff --git a/apps/web/src/features/tasks-view/queries/task-query.test.ts b/apps/web/src/features/tasks-view/queries/task-query.test.tsindex d54f4063c2..3bade61edb 100644--- a/apps/web/src/features/tasks-view/queries/task-query.test.ts+++ b/apps/web/src/features/tasks-view/queries/task-query.test.ts@@ -54,6 +54,37 @@ describe('task reference scope', () => {});});+describe('task CRM scope', () => {+ it('scopes the list to the record without a property-only filter', () => {+ const query = buildTaskQuery({+ ...options,+ facets: {},+ crm: { type: 'company', id: 'company-1' },+ });+ expect(query.body.crma).toEqual({ company: 'company-1' });+ expect(query.body.propf).toBeUndefined();+ expect(query.body.df).toEqual({ l: { dst: 'task' } });+ // Grouping and sort still apply to the scoped list.+ expect(query.groupBy).toEqual({+ type: 'property',+ propertyDefinitionId: '00000001-0000-0000-0000-000000000002',+ });+ });++ it('searches by name inside the same scope', () => {+ const query = buildTaskQuery({+ ...options,+ facets: {},+ crm: { type: 'contact', id: 'contact-1' },+ nameContains: 'renewal',+ });+ expect(query.body.crma).toEqual({ contact: 'contact-1' });+ expect(query.body.df).toEqual({+ '&': [{ l: { dst: 'task' } }, { l: { nc: 'renewal' } }],+ });+ });+});+it('uses the initiative Project property for board columns without changing legacy list grouping', () => {const boardQuery = buildTaskQuery({...options,diff --git a/apps/web/src/features/tasks-view/queries/task-query.ts b/apps/web/src/features/tasks-view/queries/task-query.tsindex 035cd292f5..3bb6b06fb0 100644--- a/apps/web/src/features/tasks-view/queries/task-query.ts+++ b/apps/web/src/features/tasks-view/queries/task-query.ts@@ -16,6 +16,7 @@ import {type TaskFacetContext,} from '../filters/task-facets';import type {+ TaskCrmScope,TaskGroupBy,TaskReferenceScope,TaskSortId,@@ -113,10 +114,18 @@ export type BuildTaskQueryOptions = {sort: SortSelection<TaskSortId>[];/** Only tasks whose property references this entity. */reference?: TaskReferenceScope;+ /** Only tasks associated with this CRM record, resolved by the server. */+ crm?: TaskCrmScope;+ /** Only tasks whose name contains this text, case-insensitively. */+ nameContains?: string;/** Board Project columns use the initiative property, not legacy folders. */board?: boolean;};+/** The Soup CRM association naming the record. */+export const taskCrmAssociation = (crm: TaskCrmScope) =>+ crm.type === 'company' ? { company: crm.id } : { contact: crm.id };+/** Builds the concrete Soup AST used only by the production Tasks view. */export function buildTaskQuery(options: BuildTaskQueryOptions@@ -143,9 +152,15 @@ export function buildTaskQuery(const taskDocuments = documentScope(options.tab, options.userId);- const documents: TaskAst = compiledFacets.df- ? { '&': [taskDocuments, compiledFacets.df] }- : taskDocuments;+ const documents =+ combine(+ '&',+ [+ taskDocuments,+ compiledFacets.df,+ options.nameContains ? literal('nc', options.nameContains) : undefined,+ ].filter((node): node is TaskAst => node !== undefined)+ ) ?? taskDocuments;const body: SoupAstBody = {...nonTaskTargets,@@ -153,6 +168,7 @@ export function buildTaskQuery(};if (properties) body.propf = properties;+ if (options.crm) body.crma = taskCrmAssociation(options.crm);return {params: {diff --git a/apps/web/src/features/tasks-view/queries/use-tasks-query.test.ts b/apps/web/src/features/tasks-view/queries/use-tasks-query.test.tsindex e08af089c8..d1c5794abc 100644--- a/apps/web/src/features/tasks-view/queries/use-tasks-query.test.ts+++ b/apps/web/src/features/tasks-view/queries/use-tasks-query.test.ts@@ -5,6 +5,9 @@ import { expect, it, vi } from 'vitest';const fixture = vi.hoisted(() => ({query: {} as Record<string, unknown>,groupQueries: new Map<string, unknown>(),+ calls: [] as { args: () => unknown; options?: () => unknown }[],+ searchState: vi.fn(),+ mapItem: vi.fn(),}));vi.mock('@app/features/soup', async () => ({...(await import('@app/features/soup/filters')),@@ -12,11 +15,14 @@ vi.mock('@app/features/soup', async () => ({...(await import('@app/features/soup/collection/row-store')),...(await import('@app/features/soup/collection/transforms')),useSearchContext: () => ({ entityPool: () => [] }),- createSearchState: () => ({- isSearching: () => false,- usesServiceSearch: () => false,- isSettling: () => false,- }),+ createSearchState: () => {+ fixture.searchState();+ return {+ isSearching: () => false,+ usesServiceSearch: () => false,+ isSettling: () => false,+ };+ },}));vi.mock('@entity', async () => ({...(await import('@entity/types/entity')),@@ -26,10 +32,13 @@ vi.mock('@components/app/GlobalAppState', () => ({useGlobalNotificationSource: () => ({ notificationsByEntity: () => ({}) }),}));vi.mock('@queries/soup/transform-utils', () => ({- mapApiSoupItemToEntity: vi.fn(),+ mapApiSoupItemToEntity: fixture.mapItem,}));vi.mock('@queries/soup/items', () => ({- useSoupAstItemsQuery: () => fixture.query,+ useSoupAstItemsQuery: (args: () => unknown, options?: () => unknown) => {+ fixture.calls.push({ args, options });+ return fixture.query;+ },}));vi.mock('@queries/soup/grouped/create-grouped-soup-queries', () => ({createGroupedSoupQueries: () => ({ map: () => fixture.groupQueries }),@@ -354,3 +363,148 @@ it('exposes uncollapsed board rows and hides stale groups during query changes',}});});++const COMPANIES = '00000001-0000-0000-0000-00000000000c';++function crmTask(id: string, companyIds: string[] = []) {+ return {+ type: 'document',+ fileType: 'md',+ id,+ name: id,+ ownerId: 'viewer',+ createdAt: new Date(),+ updatedAt: new Date(),+ subType: { type: 'task', is_completed: false },+ properties: companyIds.length+ ? [+ {+ definition: { id: COMPANIES },+ value: {+ type: 'EntityReference',+ value: companyIds.map((entity_id) => ({+ entity_type: 'COMPANY',+ entity_id,+ })),+ },+ },+ ]+ : [],+ } as unknown as TaskEntityWithProperties;+}++function crmSource(groupBy: 'none' | 'status' = 'none') {+ return useTasksDataSource(+ { tab: 'team-tasks', search: '', facets: {}, groupBy, sort: [] },+ {+ userId: () => 'viewer',+ tagSets: () => [],+ tagSetsReady: () => true,+ isGroupExpanded: () => true,+ crm: () => ({ type: 'company', id: 'acme' }),+ }+ );+}++it('keeps server-matched CRM tasks that only mention the record', () => {+ fixture.calls = [];+ fixture.query = {+ isLoading: false,+ isPending: false,+ isPlaceholderData: false,+ data: { entities: [crmTask('mention-only'), crmTask('linked', ['acme'])] },+ };+ createRoot((dispose) => {+ try {+ const source = crmSource();+ expect(+ source+ .items()+ .flatMap((row) => (row.kind === 'entity' ? [row.entity.id] : []))+ ).toEqual(['mention-only', 'linked']);+ const query = fixture.calls[0]?.args() as {+ body: Record<string, unknown>;+ };+ expect(query.body.crma).toEqual({ company: 'acme' });+ expect(query.body.propf).toBeUndefined();+ // The search service cannot express the scope, so it is not used.+ expect(fixture.searchState).not.toHaveBeenCalled();+ } finally {+ dispose();+ }+ });+});++it('keeps CRM continuation rows the server returned for a group', () => {+ fixture.query = {+ isLoading: false,+ isPending: false,+ isPlaceholderData: false,+ data: {+ entities: [],+ itemsById: {},+ groups: [+ {+ key: 'todo',+ label: 'To do',+ displayOrder: 0,+ totalCount: 2,+ itemIds: [],+ nextCursor: 'next',+ },+ ],+ },+ };+ fixture.groupQueries = new Map([+ [+ 'todo',+ {+ data: () => ({+ entities: [crmTask('contact-mention'), crmTask('linked', ['acme'])],+ }),+ hasNextPage: () => false,+ isFetchingNextPage: () => false,+ fetchNextPage: async () => {},+ },+ ],+ ]);+ createRoot((dispose) => {+ try {+ const source = crmSource('status');+ expect(+ source+ .items()+ .flatMap((row) => (row.kind === 'entity' ? [row.entity.id] : []))+ ).toEqual(['contact-mention', 'linked']);+ } finally {+ dispose();+ fixture.groupQueries = new Map();+ }+ });+});++it('admits only optimistic CRM tasks that name the record', () => {+ fixture.calls = [];+ fixture.query = {+ isLoading: false,+ isPending: false,+ isPlaceholderData: false,+ data: { entities: [] },+ };+ createRoot((dispose) => {+ try {+ crmSource();+ const options = fixture.calls[0]?.options?.() as {+ meta: { insertFilter: (item: unknown) => boolean };+ };+ fixture.mapItem.mockReturnValueOnce(crmTask('created', ['acme']));+ expect(options.meta.insertFilter({})).toBe(true);+ fixture.mapItem.mockReturnValueOnce(crmTask('unrelated', ['globex']));+ expect(options.meta.insertFilter({})).toBe(false);+ fixture.mapItem.mockReturnValueOnce(crmTask('cached'));+ expect(options.meta.insertFilter({})).toBe(false);+ } finally {+ dispose();+ }+ });+});diff --git a/apps/web/src/features/tasks-view/queries/use-tasks-query.ts b/apps/web/src/features/tasks-view/queries/use-tasks-query.tsindex b07b9496a0..f8ba622bcd 100644--- a/apps/web/src/features/tasks-view/queries/use-tasks-query.ts+++ b/apps/web/src/features/tasks-view/queries/use-tasks-query.ts@@ -21,6 +21,7 @@ import {isTaskEntity,type TaskEntityWithProperties,} from '@entity';+import { SYSTEM_PROPERTY_IDS } from '@property/constants';import { createGroupedSoupQueries } from '@queries/soup/grouped/create-grouped-soup-queries';import { useSoupAstItemsQuery } from '@queries/soup/items';import { mapApiSoupItemToEntity } from '@queries/soup/transform-utils';@@ -32,8 +33,13 @@ import {type TaskViewContext,taskMatchesView,} from '../filters/task-predicates';-import type { TaskReferenceScope, TasksViewState } from '../types';+import type {+ TaskCrmScope,+ TaskReferenceScope,+ TasksViewState,+} from '../types';import { createAutomaticTaskPagination } from './automatic-task-pagination';+import { createScopedTaskSearch } from './scoped-task-search';import { buildTaskQuery } from './task-query';import { buildTaskSearchRequest } from './task-search';@@ -49,6 +55,11 @@ export type UseTasksDataSourceOptions = {isGroupExpanded: (groupId: string) => boolean;/** Only tasks whose property references this entity. */reference?: Accessor<TaskReferenceScope>;+ /**+ * Only tasks associated with this CRM record. The server resolves the+ * membership, so fetched rows are not re-filtered by their properties.+ */+ crm?: Accessor<TaskCrmScope>;enabled?: Accessor<boolean>;networkPaused?: Accessor<boolean>;/** Project lists drain all cursors instead of requiring per-group Load More. */@@ -86,6 +97,20 @@ function referencesEntity().includes(reference.entityId);}+/**+ * Whether a task known only locally (an optimistic insert) is associated with+ * the record through its own property. Mention and contact-company matches+ * are known only to the server and arrive with the next fetch.+ */+function namesCrmRecord(task: TaskEntityWithProperties, crm: TaskCrmScope) {+ return getTaskReferencedEntityIds(+ task,+ crm.type === 'company'+ ? SYSTEM_PROPERTY_IDS.COMPANIES+ : SYSTEM_PROPERTY_IDS.CONTACTS+ ).includes(crm.id);+}+/** Query, service search, and row assembly owned by the production Tasks view. */export function useTasksDataSource(state: TasksDataSourceInput,@@ -103,7 +128,7 @@ export function useTasksDataSource(state.tab !== 'projects' &&tagFacetReady(state.facets, options.tagSetsReady());- const queryArgs = () =>+ const queryArgsFor = (nameContains?: string) =>buildTaskQuery({tab: state.tab,userId: options.userId(),@@ -112,10 +137,13 @@ export function useTasksDataSource(groupBy: state.groupBy,sort: state.sort,reference: options.reference?.(),+ crm: options.crm?.(),+ nameContains,board: options.board?.(),});+ const queryArgs = () => queryArgsFor();- const scoped = Boolean(options.reference);+ const scoped = Boolean(options.reference || options.crm);const query = useSoupAstItemsQuery(queryArgs, () => ({enabled: facetOptionsReady(),networkPaused: options.networkPaused?.(),@@ -126,10 +154,12 @@ export function useTasksDataSource(insertFilter: (item) => {const entity = mapApiSoupItemToEntity(item);const reference = options.reference?.();+ const crm = options.crm?.();return (isTaskEntity(entity) &&taskMatchesView(entity, viewContext()) &&- (!reference || referencesEntity(entity, reference))+ (!reference || referencesEntity(entity, reference)) &&+ (!crm || namesCrmRecord(entity, crm)));},}@@ -180,21 +210,29 @@ export function useTasksDataSource(return pool.filter((item) => matchingIds.has(item.data.id));});- const search = createSearchState({- text: () => state.search,- localPool,- enabled: facetOptionsReady,- buildRequest: ({ query, matchType }) =>- buildTaskSearchRequest({- query,- matchType,- tab: state.tab,- userId: options.userId(),- facets: state.facets,- facetContext: facetContext(),- reference: options.reference?.(),- }),- });+ // CRM membership includes references and a company's contacts, which the+ // search service cannot express: search the scoped Soup query by name.+ const search = options.crm+ ? createScopedTaskSearch({+ text: () => state.search,+ args: queryArgsFor,+ enabled: facetOptionsReady,+ })+ : createSearchState({+ text: () => state.search,+ localPool,+ enabled: facetOptionsReady,+ buildRequest: ({ query, matchType }) =>+ buildTaskSearchRequest({+ query,+ matchType,+ tab: state.tab,+ userId: options.userId(),+ facets: state.facets,+ facetContext: facetContext(),+ reference: options.reference?.(),+ }),+ });const groupedQueries = createGroupedSoupQueries({initialPage: createMemo(() => {diff --git a/apps/web/src/features/tasks-view/types.ts b/apps/web/src/features/tasks-view/types.tsindex c596e61932..0c6d54a114 100644--- a/apps/web/src/features/tasks-view/types.ts+++ b/apps/web/src/features/tasks-view/types.ts@@ -19,6 +19,16 @@ export type TaskReferenceScope = {entityId: string;};+/**+ * Scopes a task list to tasks associated with a CRM record. The server+ * resolves the membership: the record's Companies or Contacts property, a+ * reference to the record, or (for a company) either for any of its contacts.+ */+export type TaskCrmScope = {+ type: 'company' | 'contact';+ id: string;+};+export type TaskDetailTarget = {id: string;fallbackName?: string;diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.test.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.test.tsxindex b1b0d639b0..657169626f 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.test.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.test.tsx@@ -1,11 +1,12 @@import type { IUser } from '@core/user';import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';-import { createEditor } from 'lexical';+import { createEditor, type LexicalEditor } from 'lexical';import { createSignal, type ParentProps } from 'solid-js';import { afterEach, expect, it, vi } from 'vitest';import { createMenuOperations } from '../../../shared/inlineMenu';import { useEmailSearchMention } from './hooks/useEmailSearchMention';import { MentionsMenu } from './MentionsMenu';+import { createItemHandler } from './utils/mentionHandlers';import * as mobileSort from './utils/mobileSort';const mocks = vi.hoisted(() => ({@@ -297,3 +298,28 @@ it('opens cell pickers without replaying the menu entrance animation', () => {expect(screen.getByText('No results')).toBeTruthy();expect(container.querySelector('.menu-open-animation')).toBeNull();});++it('records mentions against the editing source outside a legacy block', () => {+ vi.mocked(useEmailSearchMention).mockReturnValue({+ emails: () => [],+ totalCount: () => 0,+ hasMore: () => false,+ isLoadingMore: () => false,+ loadMore: async () => {},+ } as unknown as ReturnType<typeof useEmailSearchMention>);+ const editor = {+ dispatchCommand: vi.fn(),+ getRootElement: () => null,+ } as unknown as LexicalEditor;+ render(() => (+ <MentionsMenu+ menu={createMenuOperations()}+ users={() => []}+ editor={editor}+ sourceDocumentId="doc-1"+ />+ ));+ expect(createItemHandler).toHaveBeenCalledWith(+ expect.objectContaining({ blockId: 'doc-1' })+ );+});diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsxindex 757429c46c..a9d7e403c3 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx@@ -93,6 +93,11 @@ type MentionsMenuProps = {onDocumentMention?: (item: Item | ChannelWithParticipants) => void;onEmailMention?: (item: EmailEntity) => void;disableMentionTracking?: boolean;+ /**+ * The document hosting the editor, which records inserted mentions.+ * Defaults to the enclosing legacy block, which routed documents lack.+ */+ sourceDocumentId?: string;/** whether to show open tabs as a bucket in the menu */showOpenTabs?: boolean;/** restrict which mention source buckets to show (e.g. ['users'] for user-only mentions) */@@ -145,7 +150,8 @@ function MentionsMenuInner(props: MentionsMenuProps) {const { isKeypressActive } = useIsKeyPressActive();- const blockId = useMaybeBlockId();+ const legacyBlockId = useMaybeBlockId();+ const blockId = props.sourceDocumentId ?? legacyBlockId;const { usersAndGroups, groups, availableUsers } = useUsersMention({users: props.users,@@ -253,8 +259,6 @@ function MentionsMenuInner(props: MentionsMenuProps) {);});- const currentBlockId = useMaybeBlockId();-const openTabs = createLazyMemo(() => {const splitManager = globalSplitManager();if (!splitManager) return [];@@ -274,7 +278,7 @@ function MentionsMenuInner(props: MentionsMenuProps) {continue;}- if (split.content.id === currentBlockId) continue;+ if (split.content.id === blockId) continue;const key = `${split.content.type}:${split.content.id}`;if (seenKeys.has(key)) continue;@@ -480,7 +484,7 @@ function MentionsMenuInner(props: MentionsMenuProps) {? createItemHandler({editor: props.editor,blockName: useMaybeBlockName(),- blockId: useMaybeBlockId(),+ blockId,onUserMention: props.onUserMention,onDocumentMention: props.onDocumentMention,onEmailMention: props.onEmailMention,diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/crm-selection.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/crm-selection.test.tsnew file mode 100644index 0000000000..83394aa590--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/crm-selection.test.ts@@ -0,0 +1,108 @@+import type { EntityItem } from '@core/context/quickAccess';+import type { CrmCompanyEntity, CrmContactEntity } from '@entity';+import type { LexicalEditor } from 'lexical';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const { trackMention } = vi.hoisted(() => ({ trackMention: vi.fn() }));+vi.mock('@core/signal/mention', () => ({ trackMention }));+// The block table loads every block module; entities here never need it.+vi.mock('@core/constant/allBlocks', () => ({ fileTypeToBlockName: vi.fn() }));+vi.mock('../../../../plugins', () => ({+ REMOVE_INLINE_SEARCH_COMMAND: 'remove-search',+}));+vi.mock('../../../../plugins/mentions', () => ({+ INSERT_AGENT_SESSION_MENTION_COMMAND: 'insert-session',+ INSERT_DOCUMENT_MENTION_COMMAND: 'insert-document',+ INSERT_DATE_MENTION_COMMAND: 'insert-date',+ INSERT_GROUP_MENTION_COMMAND: 'insert-group',+}));+vi.mock('../../../../utils/mentionsUtils', () => ({+ handleUserMention: vi.fn(),+}));++import { createItemHandler } from './mentionHandlers';++const company = {+ kind: 'entity',+ bucket: 'crm_company',+ id: 'company-1',+ searchText: 'Acme',+ sortTimestamp: 0,+ timestamps: {},+ data: { type: 'crm_company', id: 'company-1', name: 'Acme' },+} as unknown as EntityItem<CrmCompanyEntity>;++const contact = {+ kind: 'entity',+ bucket: 'crm_contact',+ id: 'contact-1',+ searchText: 'Ada',+ sortTimestamp: 0,+ timestamps: {},+ data: {+ type: 'crm_contact',+ id: 'contact-1',+ name: '',+ email: '[email protected]',+ },+} as unknown as EntityItem<CrmContactEntity>;++function handlerFor(+ blockName: Parameters<typeof createItemHandler>[0]['blockName']+) {+ const dispatchCommand = vi.fn();+ const onDocumentMention = vi.fn();+ const onEmailMention = vi.fn();+ const handler = createItemHandler({+ editor: { dispatchCommand } as unknown as LexicalEditor,+ blockId: 'doc-1',+ blockName,+ onDocumentMention,+ onEmailMention,+ });+ return { handler, dispatchCommand, onDocumentMention, onEmailMention };+}++describe('CRM mention selection', () => {+ beforeEach(() => {+ trackMention.mockReset();+ });++ it.each([+ [company, 'crm_company', 'company', 'Acme'],+ [contact, 'crm_contact', 'contact', '[email protected]'],+ ] as const)(+ 'records a %s chip as a reference of the CRM record without sharing anything',+ async (item, trackedType, blockName, documentName) => {+ trackMention.mockResolvedValue('mention-uuid');+ const { handler, dispatchCommand, onDocumentMention, onEmailMention } =+ handlerFor('md');+ await handler(item);++ expect(trackMention).toHaveBeenCalledWith(+ 'doc-1',+ trackedType,+ item.data.id+ );+ expect(dispatchCommand).toHaveBeenNthCalledWith(2, 'insert-document', {+ documentId: item.data.id,+ documentName,+ blockName,+ mentionUuid: 'mention-uuid',+ });+ expect(onDocumentMention).not.toHaveBeenCalled();+ expect(onEmailMention).not.toHaveBeenCalled();+ }+ );++ it('leaves message editors to record CRM references when the message sends', async () => {+ const { handler, dispatchCommand } = handlerFor('channel');+ await handler(company);+ expect(trackMention).not.toHaveBeenCalled();+ expect(dispatchCommand).toHaveBeenNthCalledWith(2, 'insert-document', {+ documentId: 'company-1',+ documentName: 'Acme',+ blockName: 'company',+ });+ });+});diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/database-mention.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/database-mention.test.tsindex 7c2e3264e1..b10a66fb92 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/database-mention.test.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/database-mention.test.ts@@ -76,7 +76,7 @@ describe('mentioning a database', () => {});});-it('inserts a CRM contact reference without sharing, inviting, or notification tracking', async () => {+it('records a CRM contact reference without sharing, inviting, or notifying', async () => {trackMention.mockClear();const dispatchCommand = vi.fn();const onUserMention = vi.fn();@@ -110,8 +110,14 @@ it('inserts a CRM contact reference without sharing, inviting, or notification tdocumentId: 'contact-1',documentName: 'Pat',blockName: 'contact',+ mentionUuid: 'mention-1',});- expect(trackMention).not.toHaveBeenCalled();+ // Recorded as a reference of the contact, which is not a notification.+ expect(trackMention).toHaveBeenCalledWith(+ 'doc-1',+ 'crm_contact',+ 'contact-1'+ );expect(onUserMention).not.toHaveBeenCalled();expect(onDocumentMention).not.toHaveBeenCalled();expect(onEmailMention).not.toHaveBeenCalled();diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mentionHandlers.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mentionHandlers.tsindex 0ce276ea17..64fc953f46 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mentionHandlers.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mentionHandlers.ts@@ -65,6 +65,33 @@ async function handleAgentSessionMention(});}+/**+ * Insert a CRM company or contact chip and record it as a reference of the+ * CRM record, so the record's References list includes this document. A CRM+ * reference does not share a file, invite a user, or notify the contact.+ */+async function handleCrmMention(+ item: EntityItem,+ dependencies: HandlerDependencies+): Promise<void> {+ const { editor, blockId } = dependencies;+ const entity = item.data;+ if (entity.type !== 'crm_contact' && entity.type !== 'crm_company') return;+ const mentionUuid =+ blockId && tracksMentions(dependencies)+ ? await trackMention(blockId, entity.type, entity.id)+ : undefined;+ editor.dispatchCommand(INSERT_DOCUMENT_MENTION_COMMAND, {+ documentId: entity.id,+ documentName:+ entity.type === 'crm_contact'+ ? entity.name || entity.email+ : entityDisplayName(item),+ blockName: entity.type === 'crm_contact' ? 'contact' : 'company',+ ...(mentionUuid ? { mentionUuid } : {}),+ });+}+/*** Handle entity mention (documents, channels, emails, etc.).*/@@ -79,14 +106,8 @@ async function handleEntityMention(return await handleAgentSessionMention(entity, dependencies);}- if (entity.type === 'crm_contact') {- // A CRM reference does not share a file, invite a user, or notify the contact.- editor.dispatchCommand(INSERT_DOCUMENT_MENTION_COMMAND, {- documentId: entity.id,- documentName: entity.name || entity.email,- blockName: 'contact',- });- return;+ if (entity.type === 'crm_contact' || entity.type === 'crm_company') {+ return await handleCrmMention(item, dependencies);}const blockNameForMention = getBlockNameFromEntity(item);diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/editing/MarkdownEditingOverlays.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/editing/MarkdownEditingOverlays.tsxindex 75cfcf12dc..fa3e38d17f 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/editing/MarkdownEditingOverlays.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/editing/MarkdownEditingOverlays.tsx@@ -74,6 +74,7 @@ export function MarkdownEditingOverlays(props: {useBlockBoundary={props.useBlockBoundary}showOpenTabs={props.showOpenTabs}disableMentionTracking={!props.source.trackMentions}+ sourceDocumentId={props.source.id}/><SnippetsMenudiff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.test.tsindex ceca820af8..891c869f6d 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.test.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.test.ts@@ -149,7 +149,8 @@ describe('mentionsPlugin', () => {discrete(editor, () => $getRoot().clear());expect(untrackMention).toHaveBeenCalledExactlyOnceWith('doc-1',- 'reference-1'+ 'reference-1',+ 'database');});it('sends an inline form mention as a form reference, and drops it when the mention is removed', () => {diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.tsindex e84e092c4a..5d86756f44 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts@@ -318,7 +318,11 @@ function $deleteSelectedMentions(sourceDocumentId?: string) {if (!$isGroupMentionNode(node)) {const mentionUuid = node.getMentionUuid();if (mentionUuid && sourceDocumentId) {- untrackMention(sourceDocumentId, mentionUuid);+ untrackMention(+ sourceDocumentId,+ mentionUuid,+ $mentionItemFromNode(node).itemType+ );}}node.remove();@@ -477,7 +481,7 @@ function registerMentionsPlugin(sourceDocumentId &&!databaseReferenceRemains(uuid))- void untrackMention(sourceDocumentId, uuid);+ void untrackMention(sourceDocumentId, uuid, 'database');onRemoveMention?.({ itemType: card.itemType, itemId: card.itemId });}}@@ -655,7 +659,7 @@ function registerMentionsPlugin(if (mutation === 'destroyed') {const mentionUuid = node.getMentionUuid();if (mentionUuid && sourceDocumentId) {- untrackMention(sourceDocumentId, mentionUuid);+ untrackMention(sourceDocumentId, mentionUuid, 'agent_session');}onRemoveMention?.($mentionItemFromNode(node));}@@ -916,7 +920,7 @@ function registerMentionsPlugin((node.getBlockName() !== 'database' ||!databaseReferenceRemains(mentionUuid))) {- untrackMention(sourceDocumentId, mentionUuid);+ untrackMention(sourceDocumentId, mentionUuid, itemType);}if (onRemoveMention) {onRemoveMention({@@ -954,7 +958,7 @@ function registerMentionsPlugin(if (node) {const mentionUuid = node.getMentionUuid();if (mentionUuid && sourceDocumentId) {- untrackMention(sourceDocumentId, mentionUuid);+ untrackMention(sourceDocumentId, mentionUuid, 'user');}if (onRemoveMention) {onRemoveMention({@@ -992,7 +996,7 @@ function registerMentionsPlugin(if (node) {const mentionUuid = node.getMentionUuid();if (mentionUuid && sourceDocumentId) {- untrackMention(sourceDocumentId, mentionUuid);+ untrackMention(sourceDocumentId, mentionUuid, 'contact');}if (onRemoveMention) {onRemoveMention({@@ -1027,7 +1031,7 @@ function registerMentionsPlugin(if (node) {const mentionUuid = node.getMentionUuid();if (mentionUuid && sourceDocumentId) {- untrackMention(sourceDocumentId, mentionUuid);+ untrackMention(sourceDocumentId, mentionUuid, 'date');}if (onRemoveMention) {onRemoveMention({@@ -1092,7 +1096,7 @@ function registerMentionsPlugin(if (mutation === 'destroyed') {const mentionUuid = node.getMentionUuid();if (mentionUuid && sourceDocumentId) {- untrackMention(sourceDocumentId, mentionUuid);+ untrackMention(sourceDocumentId, mentionUuid, 'foreign');}onRemoveMention?.($mentionItemFromNode(node));} else if (mutation === 'created') {diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/tests/mentionCallbacks.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/tests/mentionCallbacks.test.tsindex 9e383a750e..8fbd844362 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/tests/mentionCallbacks.test.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/tests/mentionCallbacks.test.ts@@ -397,7 +397,11 @@ describe('mentionsPlugin callbacks', () => {itemId: 'session-1',}));- expect(untrackMention).toHaveBeenCalledWith('doc-1', 'uuid-session');+ expect(untrackMention).toHaveBeenCalledWith(+ 'doc-1',+ 'uuid-session',+ 'agent_session'+ );cleanup();});diff --git a/apps/web/src/lib/core/signal/mention.ts b/apps/web/src/lib/core/signal/mention.tsindex 9672aa4030..3e3bbaa65e 100644--- a/apps/web/src/lib/core/signal/mention.ts+++ b/apps/web/src/lib/core/signal/mention.ts@@ -1,5 +1,6 @@import { ENABLE_MENTION_TRACKING } from '@core/constant/featureFlags';import { queryClient } from '@queries/client';+import { refreshCrmAssociatedSoupQueries } from '@queries/soup/crm-association';import { attachmentReferencesKeys } from '@queries/storage/keys';import { type ItemType, storageServiceClient } from '@service-storage/client';@@ -7,6 +8,12 @@ import { getPermissionToken } from './token';type MentionId = string;+/** CRM records whose associated-item lists include what references them. */+const isCrmTarget = (targetType: string | undefined) =>+ targetType === undefined ||+ targetType === 'crm_company' ||+ targetType === 'crm_contact';+export async function trackMention(sourceId: string,targetType: ItemType | 'user',@@ -34,12 +41,18 @@ export async function trackMention(queryClient.invalidateQueries({queryKey: attachmentReferencesKeys.list(targetType, targetId).queryKey,});+ if (isCrmTarget(targetType)) void refreshCrmAssociatedSoupQueries();return response.value?.id;}+/**+ * Remove a recorded mention. Pass the target type when known so only+ * removals that can change a CRM record's associated items refresh them.+ */export async function untrackMention(sourceId: string,- mentionId: MentionId+ mentionId: MentionId,+ targetType?: string): Promise<void> {if (!ENABLE_MENTION_TRACKING) return;const token = await getPermissionToken('document', sourceId);@@ -59,4 +72,5 @@ export async function untrackMention(queryClient.invalidateQueries({queryKey: attachmentReferencesKeys.list._def,});+ if (isCrmTarget(targetType)) void refreshCrmAssociatedSoupQueries();}diff --git a/apps/web/src/lib/queries/messages/mutations.ts b/apps/web/src/lib/queries/messages/mutations.tsindex dc320abc56..1f92d6e66b 100644--- a/apps/web/src/lib/queries/messages/mutations.ts+++ b/apps/web/src/lib/queries/messages/mutations.ts@@ -3,6 +3,10 @@ import type { OptimisticPostMessageAttachment } from '@channel/Input/message-payimport { toast } from '@core/component/Toast/Toast';import type { DateValue } from '@core/util/date';import { markMessageSent } from '@core/util/message-send-motion';+import {+ messageReferencesCrmRecord,+ refreshCrmAssociatedSoupQueries,+} from '@queries/soup/crm-association';import {bumpSoupEntityTouchedAt,invalidateSoupEntity,@@ -500,6 +504,10 @@ export function useSendMessageMutation(invalidateSoupEntity(variables.parent.id);}+ // CRM record lists include messages that mention or attach the record.+ if (messageReferencesCrmRecord(variables.message))+ void refreshCrmAssociatedSoupQueries();+if (variables.parent.type === 'channel')analytics.track('channel_message_sent', {contentLength: variables.message.content?.length ?? 0,@@ -587,6 +595,8 @@ export function useDeleteMessageMutation(},onSuccess(data, _vars, context) {applyRootDeletion(data, context?.threadState);+ // The deleted message may have referenced a CRM record.+ void refreshCrmAssociatedSoupQueries();},onError(error, vars, context) {console.error('failed to delete message', error);@@ -677,6 +687,8 @@ export function usePatchMessageMutation(},onSuccess(data) {applyMessage(data, 'edited');+ // An edit can add or remove a CRM record reference.+ void refreshCrmAssociatedSoupQueries();},onError(error, vars, context) {console.error('failed to update message', error);diff --git a/apps/web/src/lib/queries/messages/tests/mutations.test.tsx b/apps/web/src/lib/queries/messages/tests/mutations.test.tsxindex 7c8994c3d6..93a201c56c 100644--- a/apps/web/src/lib/queries/messages/tests/mutations.test.tsx+++ b/apps/web/src/lib/queries/messages/tests/mutations.test.tsx@@ -3,6 +3,7 @@ import type {MessageListItem,MessageParent,MessageThread,+ PostMessage,} from '@service-storage/messages';import { cleanup, fireEvent, render, waitFor } from '@solidjs/testing-library';import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';@@ -13,6 +14,7 @@ const mocks = vi.hoisted(() => ({delete: vi.fn(),patchThread: vi.fn(),post: vi.fn(),+ refreshCrmLists: vi.fn(async () => {}),}));vi.mock('../../client', () => ({get queryClient() {@@ -24,6 +26,10 @@ vi.mock('@core/component/Toast/Toast', () => ({}));vi.mock('@service-storage/messages', () => ({ entityMessagesClient: mocks }));vi.mock('../subscription', () => ({ useMessageSubscription: () => {} }));+vi.mock('@queries/soup/crm-association', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@queries/soup/crm-association')>()),+ refreshCrmAssociatedSoupQueries: mocks.refreshCrmLists,+}));vi.mock('@app/lib/analytics/analytics-context', () => ({useAnalytics: () => ({ track: vi.fn() }),}));@@ -68,6 +74,7 @@ beforeEach(() => {mocks.delete.mockReset();mocks.patchThread.mockReset();mocks.post.mockReset();+ mocks.refreshCrmLists.mockClear();testQueryClient = new QueryClient({defaultOptions: { queries: { retry: false }, mutations: { retry: false } },});@@ -723,6 +730,46 @@ describe('sending', () => {).toEqual(anchor ?? null);});+ it.each<[string, Pick<PostMessage, 'mentions' | 'attachments'>, boolean]>([+ [+ 'a CRM attachment',+ { attachments: [{ entity_type: 'crm_company', entity_id: 'company' }] },+ true,+ ],+ [+ 'a CRM mention',+ { mentions: [{ entity_type: 'crm_contact', entity_id: 'contact' }] },+ true,+ ],+ [+ 'a non-CRM attachment',+ { attachments: [{ entity_type: 'document', entity_id: 'doc-2' }] },+ false,+ ],+ ])(+ 'refreshes CRM record lists only after sending %s',+ async (_name, references, refreshes) => {+ const parent: MessageParent = { type: 'document', id: 'doc' };+ testQueryClient.setQueryData<MessageTimelineData>(+ getMessageTimelineQueryKey(parent),+ {+ pageParams: [null],+ pages: [{ entries: [], next_cursor: null, previous_cursor: null }],+ }+ );+ mocks.post.mockResolvedValue(message(parent, 'sent'));++ await mountSend().mutateAsync({+ parent,+ message: { content: 'Hello', ...references },+ senderId: 'macro|[email protected]',+ optimisticId: newMessageId(),+ });++ expect(mocks.refreshCrmLists).toHaveBeenCalledTimes(refreshes ? 1 : 0);+ }+ );+it('adopts the server id when the server ignores the client id', async () => {const parent: MessageParent = { type: 'document', id: 'doc' };const timelineKey = getMessageTimelineQueryKey(parent);diff --git a/apps/web/src/lib/queries/properties/entity.ts b/apps/web/src/lib/queries/properties/entity.tsindex 282e119fa2..67b494894d 100644--- a/apps/web/src/lib/queries/properties/entity.ts+++ b/apps/web/src/lib/queries/properties/entity.ts@@ -18,6 +18,7 @@ import type {PropertyDefinitionDomain,} from '@property/types';import { isInstantiatedProperty } from '@property/utils';+import { refreshCrmAssociatedSoupQueries } from '@queries/soup/crm-association';import { ownTouchStamp } from '@queries/soup/normalized-cache/own-touch';import { DeleteEntityPropertyDocument } from '@service-storage/graphql/generated/graphql';import { getGraphqlSoupClient } from '@service-storage/graphql-soup';@@ -430,11 +431,14 @@ export function useDeleteEntityPropertyMutation(},...withCallbacks<void, Error, DeleteEntityPropertyParams>({- onSuccess: (_data, variables) =>- invalidatePropertiesForEntity(+ onSuccess: (_data, variables) => {+ // The removed row may have been a Companies or Contacts value.+ void refreshCrmAssociatedSoupQueries();+ return invalidatePropertiesForEntity(variables.entityType,variables.entityId- ),+ );+ },onError(error, variables) {console.error('Failed to delete property', error);toast.failure('Failed to delete property');@@ -929,11 +933,25 @@ class BulkSaveEntityPropertiesError extends Error {}}+/** Properties whose values decide which items a CRM record lists. */+const CRM_ASSOCIATION_PROPERTY_IDS: readonly string[] = [+ SYSTEM_PROPERTY_IDS.COMPANIES,+ SYSTEM_PROPERTY_IDS.CONTACTS,+];+function invalidatePropertySaveCaches(item: BulkSaveEntityPropertiesParams['properties'][number]): void {void invalidatePropertiesForEntity(item.entityType, item.entityId);invalidateSoupEntity(item.entityId);+ // CRM record lists resolve membership on the server, not from these rows.+ if (+ CRM_ASSOCIATION_PROPERTY_IDS.includes(+ getPropertyDefinitionId(item.property)+ )+ ) {+ void refreshCrmAssociatedSoupQueries();+ }}function handleCommittedPropertySave(diff --git a/apps/web/src/lib/queries/soup/crm-association.test.ts b/apps/web/src/lib/queries/soup/crm-association.test.tsnew file mode 100644index 0000000000..1064ab8aeb--- /dev/null+++ b/apps/web/src/lib/queries/soup/crm-association.test.ts@@ -0,0 +1,106 @@+import { QueryClient } from '@tanstack/solid-query';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const { client, refreshActiveGraphqlSoupQueries } = vi.hoisted(() => ({+ client: { current: undefined as unknown as QueryClient },+ refreshActiveGraphqlSoupQueries: vi.fn(async () => {}),+}));+vi.mock('@queries/client', () => ({+ get queryClient() {+ return client.current;+ },+}));+vi.mock('./graphql/active-queries', () => ({+ refreshActiveGraphqlSoupQueries,+}));++import {+ hasCrmAssociation,+ messageReferencesCrmRecord,+ refreshCrmAssociatedSoupQueries,+} from './crm-association';+import { soupKeys } from './keys';++const filesBody = {+ df: {+ '&': [+ { '!': { l: { dst: 'task' } } },+ { '|': [{ l: { crm: { company: 'c' } } }, { l: { eap: '[email protected]' } }] },+ ],+ },+};++const listKey = (body: unknown) =>+ soupKeys.astItems({ params: { limit: 100 }, body: body as never }).queryKey;++describe('CRM-associated Soup lists', () => {+ beforeEach(() => {+ client.current = new QueryClient();+ refreshActiveGraphqlSoupQueries.mockClear();+ });++ it('recognizes the scope and document literals', () => {+ expect(hasCrmAssociation({ crma: { contact: 'c' } })).toBe(true);+ expect(hasCrmAssociation(filesBody)).toBe(true);+ expect(hasCrmAssociation({ df: { l: { dst: 'task' } } })).toBe(false);+ expect(hasCrmAssociation({ propf: { l: { crm: {} } } })).toBe(false);+ expect(hasCrmAssociation(undefined)).toBe(false);+ });++ it('recognizes CRM message references', () => {+ expect(+ messageReferencesCrmRecord({+ mentions: [{ entity_type: 'user' }, { entity_type: 'crm_contact' }],+ })+ ).toBe(true);+ expect(+ messageReferencesCrmRecord({+ attachments: [{ entity_type: 'crm_company' }],+ })+ ).toBe(true);+ expect(+ messageReferencesCrmRecord({+ mentions: [{ entity_type: 'document' }],+ attachments: [{ entity_type: 'document' }],+ })+ ).toBe(false);+ expect(messageReferencesCrmRecord({})).toBe(false);+ });++ it('refetches only associated lists on both transports', async () => {+ const lists = {+ files: listKey(filesBody),+ tasks: listKey({ df: { l: { dst: 'task' } } }),+ search: soupKeys.search({+ params: {},+ body: { crma: { company: 'c' } } as never,+ }).queryKey,+ };+ for (const queryKey of Object.values(lists)) {+ client.current.setQueryData(queryKey, { items: [] });+ }++ await refreshCrmAssociatedSoupQueries();++ const invalidated = (queryKey: readonly unknown[]) =>+ client.current.getQueryState(queryKey)?.isInvalidated;+ expect(invalidated(lists.files)).toBe(true);+ expect(invalidated(lists.tasks)).toBe(false);+ expect(invalidated(lists.search)).toBe(false);+ expect(refreshActiveGraphqlSoupQueries).toHaveBeenCalledWith({+ where: hasCrmAssociation,+ });+ });++ it('skips REST invalidation when no associated list is cached', async () => {+ client.current.setQueryData(listKey({ df: { l: { dst: 'task' } } }), {+ items: [],+ });+ const invalidate = vi.spyOn(client.current, 'invalidateQueries');++ await refreshCrmAssociatedSoupQueries();++ expect(invalidate).not.toHaveBeenCalled();+ expect(refreshActiveGraphqlSoupQueries).toHaveBeenCalled();+ });+});diff --git a/apps/web/src/lib/queries/soup/crm-association.ts b/apps/web/src/lib/queries/soup/crm-association.tsnew file mode 100644index 0000000000..5e0e1b3b42--- /dev/null+++ b/apps/web/src/lib/queries/soup/crm-association.ts@@ -0,0 +1,70 @@+import { queryClient } from '@queries/client';+import { partialMatchKey, type Query } from '@tanstack/solid-query';+import { refreshActiveGraphqlSoupQueries } from './graphql/active-queries';+import { soupKeys } from './keys';++function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++/** Whether a REST AST names a CRM association literal anywhere in its tree. */+function treeNamesCrmAssociation(ast: unknown): boolean {+ if (!isRecord(ast)) return false;+ if ('l' in ast) return isRecord(ast.l) && 'crm' in ast.l;+ if (Array.isArray(ast['&'])) return ast['&'].some(treeNamesCrmAssociation);+ if (Array.isArray(ast['|'])) return ast['|'].some(treeNamesCrmAssociation);+ return treeNamesCrmAssociation(ast['!']);+}++/**+ * Whether a Soup AST body is restricted to items associated with a CRM+ * record, through the top-level scope or a document literal. Membership is+ * resolved by the server, so such lists refetch when associations change.+ */+export function hasCrmAssociation(body: unknown): boolean {+ if (!isRecord(body)) return false;+ return body.crma !== undefined || treeNamesCrmAssociation(body.df);+}++type EntityRef = { entity_type: string };++const isCrmRecord = ({ entity_type }: EntityRef) =>+ entity_type === 'crm_company' || entity_type === 'crm_contact';++/**+ * Whether a message mentions or attaches a CRM company or contact; either+ * makes the message an associated item of that record.+ */+export function messageReferencesCrmRecord(message: {+ mentions?: readonly EntityRef[];+ attachments?: readonly EntityRef[];+}): boolean {+ return (+ (message.mentions ?? []).some(isCrmRecord) ||+ (message.attachments ?? []).some(isCrmRecord)+ );+}++/** The filter body in a Soup list query key, which holds it after params. */+function keyBody(queryKey: readonly unknown[]): unknown {+ return queryKey.find(+ (part) => isRecord(part) && ('crma' in part || 'df' in part)+ );+}++/**+ * Refetch every mounted list restricted to a CRM association, on both+ * transports. Call after a CRM reference or a Companies/Contacts property+ * changes; lists without an association are left alone.+ */+export async function refreshCrmAssociatedSoupQueries(): Promise<void> {+ const prefixes = [soupKeys.astItems._def, soupKeys.groupedGroup._def];+ const predicate = (query: Query) =>+ prefixes.some((prefix) => partialMatchKey(query.queryKey, prefix)) &&+ hasCrmAssociation(keyBody(query.queryKey));+ const cached = queryClient.getQueryCache().findAll({ predicate });+ await Promise.all([+ cached.length > 0 ? queryClient.invalidateQueries({ predicate }) : null,+ refreshActiveGraphqlSoupQueries({ where: hasCrmAssociation }),+ ]);+}diff --git a/apps/web/src/lib/queries/soup/graphql/active-queries.test.ts b/apps/web/src/lib/queries/soup/graphql/active-queries.test.tsindex 6ebc6416b3..212abcd194 100644--- a/apps/web/src/lib/queries/soup/graphql/active-queries.test.ts+++ b/apps/web/src/lib/queries/soup/graphql/active-queries.test.ts@@ -250,4 +250,24 @@ describe('active GraphQL Soup queries', () => {unregisterSuccess();consoleError.mockRestore();});+ it('limits a scoped refresh to readers whose filter body matches', async () => {+ const scoped = vi.fn(async () => {});+ const other = vi.fn(async () => {});+ const unbodied = vi.fn(async () => {});+ register({+ isEnabled: () => true,+ refresh: scoped,+ body: () => ({ crma: { company: 'c' } }),+ });+ register({ isEnabled: () => true, refresh: other, body: () => ({}) });+ register({ isEnabled: () => true, refresh: unbodied });++ await refreshActiveGraphqlSoupQueries({+ where: (body) =>+ typeof body === 'object' && body !== null && 'crma' in body,+ });+ expect(scoped).toHaveBeenCalledOnce();+ expect(other).not.toHaveBeenCalled();+ expect(unbodied).not.toHaveBeenCalled();+ });});diff --git a/apps/web/src/lib/queries/soup/graphql/active-queries.ts b/apps/web/src/lib/queries/soup/graphql/active-queries.tsindex 0cd50548f5..874aa10e74 100644--- a/apps/web/src/lib/queries/soup/graphql/active-queries.ts+++ b/apps/web/src/lib/queries/soup/graphql/active-queries.ts@@ -12,6 +12,8 @@ type ActiveGraphqlSoupQuery = {refresh: () => Promise<void>;/** Only refresh this reader for its matching mutation, never for broad Soup work. */target?: () => GraphqlSoupRefreshTarget;+ /** The REST-shaped filter body, for refreshes scoped to matching lists. */+ body?: () => unknown;};const activeQueries = new Set<ActiveGraphqlSoupQuery>();@@ -57,10 +59,16 @@ export function registerActiveGraphqlSoupQuery(* succeeded. Other callers retain the existing best-effort behavior.*/export async function refreshActiveGraphqlSoupQueries(- options: { throwOnError?: boolean; target?: GraphqlSoupRefreshTarget } = {}+ options: {+ throwOnError?: boolean;+ target?: GraphqlSoupRefreshTarget;+ /** Only refresh list readers whose filter body matches. */+ where?: (body: unknown) => boolean;+ } = {}): Promise<void> {const applicable = (query: ActiveGraphqlSoupQuery) => {if (!query.isEnabled()) return false;+ if (options.where && !options.where(query.body?.())) return false;if (!query.target) return true;const target = query.target();return (diff --git a/apps/web/src/lib/queries/soup/graphql/ast.test.ts b/apps/web/src/lib/queries/soup/graphql/ast.test.tsindex 7d53cb3e8c..5670d96b46 100644--- a/apps/web/src/lib/queries/soup/graphql/ast.test.ts+++ b/apps/web/src/lib/queries/soup/graphql/ast.test.ts@@ -329,6 +329,51 @@ describe('makeGraphqlSoupInput', () => {});});+ it('translates the CRM record scope, record literals, and name search', () => {+ const company = '0198a1b2-c3d4-7e5f-8061-728394a5b700';+ const contact = '0198a1b2-c3d4-7e5f-8061-728394a5b701';+ const body = {+ crma: { company },+ df: {+ '&': [{ l: { crm: { contact } } }, { l: { nc: 'Renewal' } }],+ },+ };+ expect(+ makeGraphqlSoupInput({+ params: { limit: 100, sort_method: 'updated_at' },+ body: body as never,+ })+ ).toMatchObject({+ initial: {+ filters: {+ crmAssociation: { company },+ documentFilter: {+ and: {+ left: { literal: { crmAssociated: { contact } } },+ right: { literal: { nameContains: 'Renewal' } },+ },+ },+ },+ },+ });+ // Grouped CRM Tasks keep the scope on the grouped transport too.+ expect(+ makeGraphqlGroupedSoupInput({+ params: { limit: 100, sort_method: 'updated_at' },+ body: { crma: { contact }, df: { l: { dst: 'task' } } } as never,+ groupBy: { type: 'property', propertyDefinitionId: 'status' },+ })+ ).toMatchObject({+ initial: { filters: { crmAssociation: { contact } } },+ });+ expect(() =>+ makeGraphqlSoupInput({+ params: { limit: 100, sort_method: 'updated_at' },+ body: { crma: { team: company } } as never,+ })+ ).toThrow('Unsupported GraphQL Soup AST');+ });+it('throws for unsupported calendar literals so callers can fall back', () => {expect(() =>makeGraphqlSoupInput({diff --git a/apps/web/src/lib/queries/soup/graphql/ast.ts b/apps/web/src/lib/queries/soup/graphql/ast.tsindex 0d53529db5..5681977c0d 100644--- a/apps/web/src/lib/queries/soup/graphql/ast.ts+++ b/apps/web/src/lib/queries/soup/graphql/ast.ts@@ -7,6 +7,7 @@ import type {GraphqlChannelLiteral as GraphqlChannelLiteralInput,GraphqlChannelThreadLiteral as GraphqlChannelThreadLiteralInput,GraphqlChatLiteral as GraphqlChatLiteralInput,+ GraphqlCrmAssociation,GraphqlCrmCompanyLiteral as GraphqlCrmCompanyLiteralInput,GraphqlCrmContactLiteral,GraphqlDateLiteral as GraphqlDateLiteralInput,@@ -71,6 +72,7 @@ type TargetAstKey =type AstBody = Partial<Record<TargetAstKey, RestAst>> & {favorites_only?: SoupAstBody['favorites_only'];+ crma?: SoupAstBody['crma'];/** CRM-address and CRM-domain filters are REST-only today. */eca?: string[];ecd?: string[];@@ -307,11 +309,22 @@ function mapDocumentLiteral(literal: unknown): GraphqlDocumentLiteralInput {return { property: mapPropertiesLiteral(value) };case 'eap':return { emailAttachmentParticipant: mapEmailValue(value) };+ case 'crm':+ return { crmAssociated: mapCrmAssociation(value) };+ case 'nc':+ return { nameContains: mapString(value, 'nameContains') };default:unsupported(`document literal ${field}`);}}+function mapCrmAssociation(value: unknown): GraphqlCrmAssociation {+ const [field, id] = singleLiteralField(value);+ if (field === 'company') return { company: mapString(id, 'company') };+ if (field === 'contact') return { contact: mapString(id, 'contact') };+ unsupported(`CRM association ${field}`);+}+function mapProjectLiteral(literal: unknown): GraphqlProjectLiteralInput {const [field, value] = singleLiteralField(literal);switch (field) {@@ -690,6 +703,7 @@ function makeGraphqlFilters(body: AstBody): GraphqlEntityFilterAstInput {const filters: GraphqlEntityFilterAstInput = {};if (body.favorites_only !== undefined)filters.favoritesOnly = body.favorites_only;+ if (body.crma) filters.crmAssociation = mapCrmAssociation(body.crma);if (body.calf) {filters.calendarEventFilter = compileExpr(diff --git a/apps/web/src/lib/queries/soup/graphql/create-soup-live-query.ts b/apps/web/src/lib/queries/soup/graphql/create-soup-live-query.tsindex 37f8092db2..aa894d902f 100644--- a/apps/web/src/lib/queries/soup/graphql/create-soup-live-query.ts+++ b/apps/web/src/lib/queries/soup/graphql/create-soup-live-query.ts@@ -833,6 +833,7 @@ export function createSoupLiveQuery(isLoading: () => query.isLoading && displayLocalProjection() === undefined,isFetching: () => query.isFetching,isFetchingNextPage: () => fetchingMailPage() || query.isFetchingNextPage,+ isFetchNextPageError: () => query.isFetchNextPageError,// Current-query cache results are usable data, not previous-tab// placeholders. In particular, local recomputation must not animate the// mobile tab-loading bar or make the view report that it has no data.diff --git a/apps/web/src/lib/queries/soup/graphql/grouped-items.ts b/apps/web/src/lib/queries/soup/graphql/grouped-items.tsindex 7e2e60a585..8d37437259 100644--- a/apps/web/src/lib/queries/soup/graphql/grouped-items.ts+++ b/apps/web/src/lib/queries/soup/graphql/grouped-items.ts@@ -257,6 +257,7 @@ export function createGraphqlGroupedSoupAstItemsQuery(isLoading: () => !cachedMail() && query.isLoading,isFetching: () => query.isFetching,isFetchingNextPage: () => !!cachedMail() && local.isFetchingNextPage(),+ isFetchNextPageError: () => !!cachedMail() && local.isFetchNextPageError(),isPlaceholderData: () => false,hasNextPage: () => !!cachedMail() && local.hasNextPage(),fetchNextPage: async () => {diff --git a/apps/web/src/lib/queries/soup/graphql/items.ts b/apps/web/src/lib/queries/soup/graphql/items.tsindex dfb0ed754f..195ef311a4 100644--- a/apps/web/src/lib/queries/soup/graphql/items.ts+++ b/apps/web/src/lib/queries/soup/graphql/items.ts@@ -47,6 +47,8 @@ export type GraphqlSoupAstItemsQuery = {isLoading: Accessor<boolean>;isFetching: Accessor<boolean>;isFetchingNextPage: Accessor<boolean>;+ /** The current error came from loading a continuation page. */+ isFetchNextPageError: Accessor<boolean>;isPlaceholderData: Accessor<boolean>;hasNextPage: Accessor<boolean>;fetchNextPage: () => Promise<void>;diff --git a/apps/web/src/lib/queries/soup/items.transport-refetch.test.ts b/apps/web/src/lib/queries/soup/items.transport-refetch.test.tsindex b0e18f7209..a3a7e6894d 100644--- a/apps/web/src/lib/queries/soup/items.transport-refetch.test.ts+++ b/apps/web/src/lib/queries/soup/items.transport-refetch.test.ts@@ -5,6 +5,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';const testState = vi.hoisted(() => ({graphqlEnabled: false,restPending: false,+ restNextPageError: false,}));const restRefetch = vi.hoisted(() => vi.fn(async () => undefined));const fetchSoup = vi.hoisted(() => vi.fn());@@ -20,6 +21,7 @@ function makeGraphqlQuery(enabled: boolean) {isLoading: vi.fn(() => false),isFetching: vi.fn(() => false),isFetchingNextPage: vi.fn(() => false),+ isFetchNextPageError: vi.fn(() => false),isPlaceholderData: vi.fn(() => false),hasNextPage: vi.fn(() => false),fetchNextPage: vi.fn(async () => undefined),@@ -80,6 +82,9 @@ vi.mock('@tanstack/solid-query', () => ({isFetching: false,isPlaceholderData: false,isFetchingNextPage: false,+ get isFetchNextPageError() {+ return testState.restNextPageError;+ },isEnabled: true,hasNextPage: false,fetchNextPage: vi.fn(async () => undefined),@@ -133,6 +138,7 @@ describe('Soup refetch transport selection', () => {beforeEach(() => {testState.graphqlEnabled = false;testState.restPending = false;+ testState.restNextPageError = false;vi.clearAllMocks();});@@ -148,6 +154,21 @@ describe('Soup refetch transport selection', () => {expect(query.isPending).toBe(true);});+ it('reports continuation-page failures from the selected transport', () => {+ const rest = mountAutoTransportQuery();+ expect(rest.isFetchNextPageError).toBe(false);+ testState.restNextPageError = true;+ expect(rest.isFetchNextPageError).toBe(true);+ disposeRoot?.();++ testState.graphqlEnabled = true;+ const graphql = mountAutoTransportQuery();+ expect(graphql.transport).toBe('graphql');+ groupedQuery.isFetchNextPageError.mockReturnValueOnce(true);+ expect(graphql.isFetchNextPageError).toBe(true);+ expect(graphql.isFetchNextPageError).toBe(false);+ });+it('keeps paused GraphQL requests pending until data or an error arrives, unless disabled', () => {testState.graphqlEnabled = true;const query = mountAutoTransportQuery(true);diff --git a/apps/web/src/lib/queries/soup/items.ts b/apps/web/src/lib/queries/soup/items.tsindex 6f6223b2ab..b259df3378 100644--- a/apps/web/src/lib/queries/soup/items.ts+++ b/apps/web/src/lib/queries/soup/items.ts@@ -375,6 +375,11 @@ export type SoupAstItemsQuery = {readonly isFetching: boolean;readonly isPlaceholderData: boolean;readonly isFetchingNextPage: boolean;+ /**+ * The current error came from loading a continuation page; the loaded pages+ * are still current. Any other error means the query itself failed.+ */+ readonly isFetchNextPageError: boolean;readonly isEnabled: boolean;readonly hasNextPage: boolean;readonly transport: SoupAstItemsQueryTransport;@@ -457,6 +462,7 @@ export function useSoupAstItemsQuery(options?.().onBeforeGraphqlRefresh?.();await activeGraphqlQuery().refresh();},+ body: () => args().body,}));@@ -512,6 +518,11 @@ export function useSoupAstItemsQuery(? activeGraphqlQuery().isFetchingNextPage(): restQuery.isFetchingNextPage;},+ get isFetchNextPageError() {+ return usesGraphql()+ ? activeGraphqlQuery().isFetchNextPageError()+ : restQuery.isFetchNextPageError;+ },get isEnabled() {return usesGraphql()? activeGraphqlQuery().isEnabled()diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/apiEntityFilterAst.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/apiEntityFilterAst.tsindex a21e3254db..d79fb45ca9 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/schemas/apiEntityFilterAst.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/apiEntityFilterAst.ts@@ -4,6 +4,7 @@* document_storage_service* OpenAPI spec version: 0.1.0*/+import type { ApiEntityFilterAstCrma } from './apiEntityFilterAstCrma';import type { ApiEntityFilterAstFavoritesOnly } from './apiEntityFilterAstFavoritesOnly';/**@@ -25,6 +26,7 @@ Empty/omitted = team's full visible list. */cf?: unknown;/** the filters that should be applied to the channel entity */chanf?: unknown;+ crma?: ApiEntityFilterAstCrma;/** Opt-in filters for viewer-accessible CRM contacts (wire key `crmf`). */crmf?: unknown;/** the filters that should be applied to the channel-thread entity */diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/apiEntityFilterAstCrma.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/apiEntityFilterAstCrma.tsnew file mode 100644index 0000000000..9c2ceb36ea--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/apiEntityFilterAstCrma.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 { CrmAssociation } from './crmAssociation';++export type ApiEntityFilterAstCrma = null | CrmAssociation;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/crmAssociation.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/crmAssociation.tsnew file mode 100644index 0000000000..cc2a44aab5--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/crmAssociation.ts@@ -0,0 +1,13 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { CrmAssociationOneOf } from './crmAssociationOneOf';+import type { CrmAssociationOneOfTwo } from './crmAssociationOneOfTwo';++/**+ * The CRM record an association filter names.+ */+export type CrmAssociation = CrmAssociationOneOf | CrmAssociationOneOfTwo;diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/crmAssociationOneOf.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/crmAssociationOneOf.tsnew file mode 100644index 0000000000..d163de50dc--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/crmAssociationOneOf.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Items associated with the company or with any of its contacts.+ */+export type CrmAssociationOneOf = {+ /** Items associated with the company or with any of its contacts. */+ company: string;+};diff --git a/apps/web/src/lib/service-clients/service-storage/generated/schemas/crmAssociationOneOfTwo.ts b/apps/web/src/lib/service-clients/service-storage/generated/schemas/crmAssociationOneOfTwo.tsnew file mode 100644index 0000000000..a8224fb065--- /dev/null+++ b/apps/web/src/lib/service-clients/service-storage/generated/schemas/crmAssociationOneOfTwo.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Items associated with the contact.+ */+export type CrmAssociationOneOfTwo = {+ /** Items associated with the contact. */+ contact: string;+};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.tsindex f5ab48ac03..76578c033d 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@@ -111,6 +111,7 @@ export * from './apiChannelWithLatestOrgId';export * from './apiChannelWithLatestTeamId';export * from './apiChannelWithLatestViewedAt';export * from './apiEntityFilterAst';+export * from './apiEntityFilterAstCrma';export * from './apiEntityFilterAstFavoritesOnly';export * from './apiGroupByField';export * from './apiGroupByFieldOneOf';@@ -585,6 +586,9 @@ export * from './createWebhookRequest';export * from './createWebhookRequestHeaders';export * from './createWebhookResponse';export * from './createWebhookResponseDeletedAt';+export * from './crmAssociation';+export * from './crmAssociationOneOf';+export * from './crmAssociationOneOfTwo';export * from './crmCompanyFilters';export * from './crmCompanyFiltersHidden';export * from './crmCompanyResponse';diff --git a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts b/apps/web/src/lib/service-clients/service-storage/generated/zod.tsindex 6d1793f5db..7018f3ab89 100644--- a/apps/web/src/lib/service-clients/service-storage/generated/zod.ts+++ b/apps/web/src/lib/service-clients/service-storage/generated/zod.ts@@ -31748,6 +31748,33 @@ export const postItemsSoupAstBody = zod.unknown().optional().describe('the filters that should be applied to the channel entity'),+ crma: zod+ .union([+ zod.null(),+ zod+ .union([+ zod+ .object({+ company: zod+ .uuid()+ .describe(+ 'Items associated with the company or with any of its contacts.'+ ),+ })+ .describe(+ 'Items associated with the company or with any of its contacts.'+ ),+ zod+ .object({+ contact: zod+ .uuid()+ .describe('Items associated with the contact.'),+ })+ .describe('Items associated with the contact.'),+ ])+ .describe('The CRM record an association filter names.'),+ ])+ .optional(),crmf: zod.unknown().optional()@@ -35844,6 +35871,33 @@ export const postItemsSoupAstGroupedBody = zod.unknown().optional().describe('the filters that should be applied to the channel entity'),+ crma: zod+ .union([+ zod.null(),+ zod+ .union([+ zod+ .object({+ company: zod+ .uuid()+ .describe(+ 'Items associated with the company or with any of its contacts.'+ ),+ })+ .describe(+ 'Items associated with the company or with any of its contacts.'+ ),+ zod+ .object({+ contact: zod+ .uuid()+ .describe('Items associated with the contact.'),+ })+ .describe('Items associated with the contact.'),+ ])+ .describe('The CRM record an association filter names.'),+ ])+ .optional(),crmf: zod.unknown().optional()@@ -36024,6 +36078,33 @@ export const postItemsSoupAstGroupedBody = zod.unknown().optional().describe('the filters that should be applied to the channel entity'),+ crma: zod+ .union([+ zod.null(),+ zod+ .union([+ zod+ .object({+ company: zod+ .uuid()+ .describe(+ 'Items associated with the company or with any of its contacts.'+ ),+ })+ .describe(+ 'Items associated with the company or with any of its contacts.'+ ),+ zod+ .object({+ contact: zod+ .uuid()+ .describe('Items associated with the contact.'),+ })+ .describe('Items associated with the contact.'),+ ])+ .describe('The CRM record an association filter names.'),+ ])+ .optional(),crmf: zod.unknown().optional()diff --git a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.tsindex 6220c4fbc0..7a24bf435e 100644--- a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts+++ b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts@@ -641,6 +641,13 @@ export type GraphqlChatRole =/** The user option. */| 'USER';+/** GraphQL input naming the CRM record an association filter restricts to. */+export type GraphqlCrmAssociation =+ { /** Items associated with the company or any of its contacts. */+ company: string | number; contact?: never; }+ | { company?: never; /** Items associated with the contact. */+ contact: string | number; };+/** The two operands of a recursive `CrmCompanyFilterExpr` binary expression. */export type GraphqlCrmCompanyBinaryExpr = {/** Left expression. */@@ -785,35 +792,43 @@ export type GraphqlDocumentExpr =/** GraphQL input representing the document literal. */export type GraphqlDocumentLiteral ={ /** The created at option. */- createdAt: GraphqlDateLiteral; emailAttachmentParticipant?: never; fileAssoc?: never; fileType?: never; id?: never; importance?: never; includeCbmAtmNc?: never; isEmailAttachment?: never; notificationState?: never; owner?: never; projectId?: never; property?: never; subType?: never; updatedAt?: never; }- | { createdAt?: never; /** Uploaded from an email attachment sent by, or to, a matching address. */- emailAttachmentParticipant: GraphqlEmailValue; fileAssoc?: never; fileType?: never; id?: never; importance?: never; includeCbmAtmNc?: never; isEmailAttachment?: never; notificationState?: never; owner?: never; projectId?: never; property?: never; subType?: never; updatedAt?: never; }- | { createdAt?: never; emailAttachmentParticipant?: never; /** The file assoc option. */- fileAssoc: string; fileType?: never; id?: never; importance?: never; includeCbmAtmNc?: never; isEmailAttachment?: never; notificationState?: never; owner?: never; projectId?: never; property?: never; subType?: never; updatedAt?: never; }- | { createdAt?: never; emailAttachmentParticipant?: never; fileAssoc?: never; /** The file type option. */- fileType: string; id?: never; importance?: never; includeCbmAtmNc?: never; isEmailAttachment?: never; notificationState?: never; owner?: never; projectId?: never; property?: never; subType?: never; updatedAt?: never; }- | { createdAt?: never; emailAttachmentParticipant?: never; fileAssoc?: never; fileType?: never; /** The id option. */- id: string | number; importance?: never; includeCbmAtmNc?: never; isEmailAttachment?: never; notificationState?: never; owner?: never; projectId?: never; property?: never; subType?: never; updatedAt?: never; }- | { createdAt?: never; emailAttachmentParticipant?: never; fileAssoc?: never; fileType?: never; id?: never; /** The importance option. */- importance: boolean; includeCbmAtmNc?: never; isEmailAttachment?: never; notificationState?: never; owner?: never; projectId?: never; property?: never; subType?: never; updatedAt?: never; }- | { createdAt?: never; emailAttachmentParticipant?: never; fileAssoc?: never; fileType?: never; id?: never; importance?: never; /** The include cbm atm nc option. */- includeCbmAtmNc: boolean; isEmailAttachment?: never; notificationState?: never; owner?: never; projectId?: never; property?: never; subType?: never; updatedAt?: never; }- | { createdAt?: never; emailAttachmentParticipant?: never; fileAssoc?: never; fileType?: never; id?: never; importance?: never; includeCbmAtmNc?: never; /** The is email attachment option. */- isEmailAttachment: boolean; notificationState?: never; owner?: never; projectId?: never; property?: never; subType?: never; updatedAt?: never; }- | { createdAt?: never; emailAttachmentParticipant?: never; fileAssoc?: never; fileType?: never; id?: never; importance?: never; includeCbmAtmNc?: never; isEmailAttachment?: never; /** Exact notification state for the requester. */+ createdAt: GraphqlDateLiteral; crmAssociated?: never; emailAttachmentParticipant?: never; fileAssoc?: never; fileType?: never; id?: never; importance?: never; includeCbmAtmNc?: never; isEmailAttachment?: never; nameContains?: never; notificationState?: never; owner?: never; projectId?: never; property?: never; subType?: never; updatedAt?: never; }+ | { createdAt?: never; /**+ * Associated with a CRM record through its Companies or Contacts+ * property or a reference to the record. Requires an expanded,+ * timestamp-sorted query.+ */+ crmAssociated: GraphqlCrmAssociation; emailAttachmentParticipant?: never; fileAssoc?: never; fileType?: never; id?: never; importance?: never; includeCbmAtmNc?: never; isEmailAttachment?: never; nameContains?: never; notificationState?: never; owner?: never; projectId?: never; property?: never; subType?: never; updatedAt?: never; }+ | { createdAt?: never; crmAssociated?: never; /** Uploaded from an email attachment sent by, or to, a matching address. */+ emailAttachmentParticipant: GraphqlEmailValue; fileAssoc?: never; fileType?: never; id?: never; importance?: never; includeCbmAtmNc?: never; isEmailAttachment?: never; nameContains?: never; notificationState?: never; owner?: never; projectId?: never; property?: never; subType?: never; updatedAt?: never; }+ | { createdAt?: never; crmAssociated?: never; emailAttachmentParticipant?: never; /** The file assoc option. */+ fileAssoc: string; fileType?: never; id?: never; importance?: never; includeCbmAtmNc?: never; isEmailAttachment?: never; nameContains?: never; notificationState?: never; owner?: never; projectId?: never; property?: never; subType?: never; updatedAt?: never; }+ | { createdAt?: never; crmAssociated?: never; emailAttachmentParticipant?: never; fileAssoc?: never; /** The file type option. */+ fileType: string; id?: never; importance?: never; includeCbmAtmNc?: never; isEmailAttachment?: never; nameContains?: never; notificationState?: never; owner?: never; projectId?: never; property?: never; subType?: never; updatedAt?: never; }+ | { createdAt?: never; crmAssociated?: never; emailAttachmentParticipant?: never; fileAssoc?: never; fileType?: never; /** The id option. */+ id: string | number; importance?: never; includeCbmAtmNc?: never; isEmailAttachment?: never; nameContains?: never; notificationState?: never; owner?: never; projectId?: never; property?: never; subType?: never; updatedAt?: never; }+ | { createdAt?: never; crmAssociated?: never; emailAttachmentParticipant?: never; fileAssoc?: never; fileType?: never; id?: never; /** The importance option. */+ importance: boolean; includeCbmAtmNc?: never; isEmailAttachment?: never; nameContains?: never; notificationState?: never; owner?: never; projectId?: never; property?: never; subType?: never; updatedAt?: never; }+ | { createdAt?: never; crmAssociated?: never; emailAttachmentParticipant?: never; fileAssoc?: never; fileType?: never; id?: never; importance?: never; /** The include cbm atm nc option. */+ includeCbmAtmNc: boolean; isEmailAttachment?: never; nameContains?: never; notificationState?: never; owner?: never; projectId?: never; property?: never; subType?: never; updatedAt?: never; }+ | { createdAt?: never; crmAssociated?: never; emailAttachmentParticipant?: never; fileAssoc?: never; fileType?: never; id?: never; importance?: never; includeCbmAtmNc?: never; /** The is email attachment option. */+ isEmailAttachment: boolean; nameContains?: never; notificationState?: never; owner?: never; projectId?: never; property?: never; subType?: never; updatedAt?: never; }+ | { createdAt?: never; crmAssociated?: never; emailAttachmentParticipant?: never; fileAssoc?: never; fileType?: never; id?: never; importance?: never; includeCbmAtmNc?: never; isEmailAttachment?: never; /** Case-insensitive substring of the document name. */+ nameContains: string; notificationState?: never; owner?: never; projectId?: never; property?: never; subType?: never; updatedAt?: never; }+ | { createdAt?: never; crmAssociated?: never; emailAttachmentParticipant?: never; fileAssoc?: never; fileType?: never; id?: never; importance?: never; includeCbmAtmNc?: never; isEmailAttachment?: never; nameContains?: never; /** Exact notification state for the requester. */notificationState: NotificationState; owner?: never; projectId?: never; property?: never; subType?: never; updatedAt?: never; }- | { createdAt?: never; emailAttachmentParticipant?: never; fileAssoc?: never; fileType?: never; id?: never; importance?: never; includeCbmAtmNc?: never; isEmailAttachment?: never; notificationState?: never; /**+ | { createdAt?: never; crmAssociated?: never; emailAttachmentParticipant?: never; fileAssoc?: never; fileType?: never; id?: never; importance?: never; includeCbmAtmNc?: never; isEmailAttachment?: never; nameContains?: never; notificationState?: never; /*** The owner principal option — a user (`macro|<email>`), a bot* (`bot|<uuid>`), or a team (a bare hyphenated uuid).*/owner: string; projectId?: never; property?: never; subType?: never; updatedAt?: never; }- | { createdAt?: never; emailAttachmentParticipant?: never; fileAssoc?: never; fileType?: never; id?: never; importance?: never; includeCbmAtmNc?: never; isEmailAttachment?: never; notificationState?: never; owner?: never; /** The project id option. */+ | { createdAt?: never; crmAssociated?: never; emailAttachmentParticipant?: never; fileAssoc?: never; fileType?: never; id?: never; importance?: never; includeCbmAtmNc?: never; isEmailAttachment?: never; nameContains?: never; notificationState?: never; owner?: never; /** The project id option. */projectId: string | number; property?: never; subType?: never; updatedAt?: never; }- | { createdAt?: never; emailAttachmentParticipant?: never; fileAssoc?: never; fileType?: never; id?: never; importance?: never; includeCbmAtmNc?: never; isEmailAttachment?: never; notificationState?: never; owner?: never; projectId?: never; /** An entity-property condition on the document or task. */+ | { createdAt?: never; crmAssociated?: never; emailAttachmentParticipant?: never; fileAssoc?: never; fileType?: never; id?: never; importance?: never; includeCbmAtmNc?: never; isEmailAttachment?: never; nameContains?: never; notificationState?: never; owner?: never; projectId?: never; /** An entity-property condition on the document or task. */property: GraphqlFilterPropertiesLiteral; subType?: never; updatedAt?: never; }- | { createdAt?: never; emailAttachmentParticipant?: never; fileAssoc?: never; fileType?: never; id?: never; importance?: never; includeCbmAtmNc?: never; isEmailAttachment?: never; notificationState?: never; owner?: never; projectId?: never; property?: never; /** The sub type option. */+ | { createdAt?: never; crmAssociated?: never; emailAttachmentParticipant?: never; fileAssoc?: never; fileType?: never; id?: never; importance?: never; includeCbmAtmNc?: never; isEmailAttachment?: never; nameContains?: never; notificationState?: never; owner?: never; projectId?: never; property?: never; /** The sub type option. */subType: GraphqlDocumentSubType; updatedAt?: never; }- | { createdAt?: never; emailAttachmentParticipant?: never; fileAssoc?: never; fileType?: never; id?: never; importance?: never; includeCbmAtmNc?: never; isEmailAttachment?: never; notificationState?: never; owner?: never; projectId?: never; property?: never; subType?: never; /** The updated at option. */+ | { createdAt?: never; crmAssociated?: never; emailAttachmentParticipant?: never; fileAssoc?: never; fileType?: never; id?: never; importance?: never; includeCbmAtmNc?: never; isEmailAttachment?: never; nameContains?: never; notificationState?: never; owner?: never; projectId?: never; property?: never; subType?: never; /** The updated at option. */updatedAt: GraphqlDateLiteral; };/** GraphQL input representing the document sub type. */@@ -940,6 +955,11 @@ export type GraphqlEntityFilterAst = {channelThreadFilter?: GraphqlChannelThreadExpr | null | undefined;/** The chat filter to apply. */chatFilter?: GraphqlChatExpr | null | undefined;+ /**+ * Restrict every entity type to items associated with this CRM record.+ * Requires an expanded, timestamp-sorted query.+ */+ crmAssociation?: GraphqlCrmAssociation | null | undefined;/** The crm company filter to apply. */crmCompanyFilter?: GraphqlCrmCompanyExpr | null | undefined;/**diff --git a/apps/web/src/lib/service-clients/service-storage/openapi.json b/apps/web/src/lib/service-clients/service-storage/openapi.jsonindex 282dc27034..9e50281d7c 100644--- a/apps/web/src/lib/service-clients/service-storage/openapi.json+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json@@ -14338,6 +14338,16 @@}}},+ "404": {+ "description": "The CRM record named by `crma` or a document `crm` literal is not visible to the caller",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },"500": {"description": "","content": {@@ -14398,6 +14408,16 @@}}},+ "404": {+ "description": "The CRM record named by `crma` or a document `crm` literal is not visible to the caller",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },"500": {"description": "","content": {@@ -18984,6 +19004,17 @@"chanf": {"description": "the filters that should be applied to the channel entity"},+ "crma": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/CrmAssociation",+ "description": "Restrict every entity type to items associated with this CRM record\n(wire key `crma`): its Companies or Contacts property names the\nrecord, or it references the record. A company also matches through\nits contacts. Unknown or inaccessible records answer 404; requests\nthat are not expanded or not timestamp-sorted answer 400."+ }+ ]+ },"crmf": {"description": "Opt-in filters for viewer-accessible CRM contacts (wire key `crmf`)."},@@ -24229,6 +24260,35 @@}}},+ "CrmAssociation": {+ "oneOf": [+ {+ "type": "object",+ "description": "Items associated with the company or with any of its contacts.",+ "required": ["company"],+ "properties": {+ "company": {+ "type": "string",+ "format": "uuid",+ "description": "Items associated with the company or with any of its contacts."+ }+ }+ },+ {+ "type": "object",+ "description": "Items associated with the contact.",+ "required": ["contact"],+ "properties": {+ "contact": {+ "type": "string",+ "format": "uuid",+ "description": "Items associated with the contact."+ }+ }+ }+ ],+ "description": "The CRM record an association filter names."+ },"CrmCompanyFilters": {"type": "object","description": "The crm company filters used to narrow which CRM companies appear in soup.",diff --git a/crates/call/src/domain/models.rs b/crates/call/src/domain/models.rsindex 804ed70e0a..4900b2d0fc 100644--- a/crates/call/src/domain/models.rs+++ b/crates/call/src/domain/models.rs@@ -631,6 +631,28 @@ pub struct GetCallRecordsRequest {pub query: Query<Uuid, SimpleSortMethod, LiteralTree<CallLiteral>>,}+/// The order and keyset position of one page of a user's call records.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub struct CallRecordPage {+ /// Order by start time; otherwise by last activity (end time, or start+ /// time for a call that has not ended), the way Soup sorts calls.+ pub by_start: bool,+ /// Resume strictly after this sort timestamp and call id.+ pub after: Option<(DateTime<Utc>, Uuid)>,+}++impl CallRecordPage {+ /// The page a Soup query asks for.+ pub fn from_query<F>(query: &Query<Uuid, SimpleSortMethod, F>) -> Self {+ let by_start = matches!(query.sort_method(), SimpleSortMethod::CreatedAt);+ let after = match query {+ Query::Sort(..) => None,+ Query::Cursor(cursor) => Some((cursor.val.last_val, cursor.id)),+ };+ Self { by_start, after }+ }+}+/// Errors that can occur when adding a participant to a call at the/// repository boundary. Splitting the "already-active-elsewhere" case into/// a typed variant lets the service handle it without looking at thediff --git a/crates/call/src/domain/ports.rs b/crates/call/src/domain/ports.rsindex c1786605de..7f6df20843 100644--- a/crates/call/src/domain/ports.rs+++ b/crates/call/src/domain/ports.rs@@ -18,8 +18,8 @@ use notification::domain::models::apple::VoipPushPayload;use models_permissions::share_permission::team_share::TeamShareFacts;use crate::domain::models::{- CallPeople, CustomSpeakerAssignment, DeletedCallRecordStorageKeys, EditCallRecordRepoArgs,- EditCallRecordRequest, EditCallTranscriptRequest,+ CallPeople, CallRecordPage, CustomSpeakerAssignment, DeletedCallRecordStorageKeys,+ EditCallRecordRepoArgs, EditCallRecordRequest, EditCallTranscriptRequest,};use super::meetings::{@@ -436,12 +436,14 @@ pub trait CallRepository: Send + Sync + 'static {/// Fetch visible active and archived records, without transcripts. Status/// reflects the user's participation and current channel membership./// Standalone calls require an individual user grant, never a group grant.- /// Apply `filter`, order by start time descending, and return at most `limit`.+ /// Apply `filter`, order descending by `page`'s sort timestamp and call id,+ /// seek past `page.after`, and return at most `limit`.fn get_call_records_by_user<'a>(&self,user_id: MacroUserIdStr<'a>,limit: u32,filter: &LiteralTree<CallLiteral>,+ page: CallRecordPage,) -> impl Future<Output = Result<Vec<CallRecord>, Self::Err>> + Send;/// Resolve the display name for a single channel.diff --git a/crates/call/src/domain/service.rs b/crates/call/src/domain/service.rsindex 9052461650..ec57e4130f 100644--- a/crates/call/src/domain/service.rs+++ b/crates/call/src/domain/service.rs@@ -42,7 +42,7 @@ use crate::domain::events::{CallStartedMetadata,};use crate::domain::models::{- EditCallRecordRepoArgs, EditCallRecordRequest, EditCallTranscriptRequest,+ CallRecordPage, EditCallRecordRepoArgs, EditCallRecordRequest, EditCallTranscriptRequest,VoipPushPayloadRequest,};@@ -2422,8 +2422,9 @@ impl<R: CallRepository> CallRecordQueryService for CallRecordQueryServiceImpl<R>req: GetCallRecordsRequest,) -> Result<Vec<CallRecord>, CallError> {let filter = req.query.filter();+ let page = CallRecordPage::from_query(&req.query);self.repo- .get_call_records_by_user(req.user_id.copied(), req.limit, filter)+ .get_call_records_by_user(req.user_id.copied(), req.limit, filter, page).await.map_err(|e| CallError::Internal(e.into()))}diff --git a/crates/call/src/outbound/pg_call_repo.rs b/crates/call/src/outbound/pg_call_repo.rsindex 6d31f383bb..295b47721e 100644--- a/crates/call/src/outbound/pg_call_repo.rs+++ b/crates/call/src/outbound/pg_call_repo.rs@@ -32,8 +32,8 @@ use crate::domain::meetings::{};use crate::domain::models::{ActiveCallSummary, AddParticipantError, ArchivedCall, Call, CallError, CallParticipant,- CallPeople, CallRecord, CallRecordGuest, CallRecordParticipant, CallRecordPreview,- CallRecordPreviewData, CallRecordTranscriptSegment, CustomSpeakerAssignment,+ CallPeople, CallRecord, CallRecordGuest, CallRecordPage, CallRecordParticipant,+ CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CustomSpeakerAssignment,DeletedCallRecordStorageKeys, EditCallRecordRepoArgs, EnrichedCallTranscript,TranscriptSegmentRequest, WithCallId,};@@ -1585,6 +1585,7 @@ impl CallRepository for PgCallRepo {user_id: MacroUserIdStr<'a>,limit: u32,filter: &LiteralTree<CallLiteral>,+ page: CallRecordPage,) -> Result<Vec<CallRecord>, Self::Err> {// Fetch active and archived headers without transcripts. Channel calls// accept matching user, channel, or team grants; standalone calls require@@ -1779,7 +1780,17 @@ impl CallRepository for PgCallRepo {status as "status!"FROM visible_callsWHERE ($7::bool IS FALSE OR status = ANY($8::text[]))- ORDER BY "started_at!" DESC+ -- Soup's keyset: calls sort by start, or by last activity.+ AND (+ $15::timestamptz IS NULL+ OR (+ CASE WHEN $14 THEN started_at ELSE COALESCE(ended_at, started_at) END,+ call_id::text+ ) < ($15, $16::text)+ )+ ORDER BY+ CASE WHEN $14 THEN started_at ELSE COALESCE(ended_at, started_at) END DESC,+ call_id::text DESCLIMIT $2"#,user_id.as_ref(),@@ -1795,6 +1806,9 @@ impl CallRepository for PgCallRepo {&property.negated,&property.definition_ids as &[Option<Uuid>],&property.values,+ page.by_start,+ page.after.map(|(sort_ts, _)| sort_ts),+ page.after.map(|(_, call_id)| call_id.to_string()),).fetch_all(&self.pool).await?;diff --git a/crates/call/src/outbound/pg_call_repo/team_share/test.rs b/crates/call/src/outbound/pg_call_repo/team_share/test.rsindex fed9da5f97..216301ee27 100644--- a/crates/call/src/outbound/pg_call_repo/team_share/test.rs+++ b/crates/call/src/outbound/pg_call_repo/team_share/test.rs@@ -19,7 +19,7 @@ use uuid::Uuid;use super::super::test::{CALL_ARCHIVED, CALL1, CH1, CH2, USER_A, give_user_a_team, repo, team_entity_access_count,};-use crate::domain::models::{CallError, EditCallRecordRepoArgs};+use crate::domain::models::{CallError, CallRecordPage, EditCallRecordRepoArgs};use crate::domain::ports::CallRepository;use crate::outbound::pg_call_repo::PgCallRepo;@@ -851,7 +851,15 @@ async fn list_read_reports_live_toggle_and_canonical_state(set_team_share(&repo, CALL_ARCHIVED, Some(AccessLevel::View)).await?;let records = repo- .get_call_records_by_user(USER_A.deref().copied(), 10, &None)+ .get_call_records_by_user(+ USER_A.deref().copied(),+ 10,+ &None,+ CallRecordPage {+ by_start: false,+ after: None,+ },+ ).await?;// Live: the pending toggle (now off), no canonical level yet.diff --git a/crates/call/src/outbound/pg_call_repo/test.rs b/crates/call/src/outbound/pg_call_repo/test.rsindex 93aafb7543..fbb8af3de1 100644--- a/crates/call/src/outbound/pg_call_repo/test.rs+++ b/crates/call/src/outbound/pg_call_repo/test.rs@@ -2,7 +2,7 @@ use std::{ops::Deref, sync::Arc, sync::LazyLock};use crate::domain::meetings::GuestId;use crate::domain::models::{- AddParticipantError, CallRecord, CallRecordPreview, CustomSpeakerAssignment,+ AddParticipantError, CallRecord, CallRecordPage, CallRecordPreview, CustomSpeakerAssignment,EditCallRecordRepoArgs, TranscriptSegmentRequest,};use crate::domain::ports::CallRepository;@@ -58,6 +58,10 @@ pub(super) const CH1: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000pub(super) const CH2: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000c02);pub(super) const CALL1: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_0000000ca110);const CALL2: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_0000000ca220);+const LATEST_FIRST: CallRecordPage = CallRecordPage {+ by_start: false,+ after: None,+};pub(super) const CALL_ARCHIVED: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_0000000ca2ed);const MACRO_USER_A: Uuid = Uuid::from_u128(0xaaaaaaaa_aaaa_aaaa_aaaa_aaaaaaaaaaa1);const MACRO_USER_B: Uuid = Uuid::from_u128(0xbbbbbbbb_bbbb_bbbb_bbbb_bbbbbbbbbbb2);@@ -1635,6 +1639,51 @@ async fn batch_get_call_record_previews_empty_input_returns_empty(Ok(())}+#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("call_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn get_call_records_by_user_seeks_past_the_soup_cursor(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = repo(pool);+ let all = repo+ .get_call_records_by_user(USER_C.deref().copied(), 10, &None, LATEST_FIRST)+ .await?;+ assert_eq!(all.len(), 2);++ // Each page resumes strictly after the previous page's last call, so a+ // feed never serves the same call twice and reaches every call.+ for by_start in [false, true] {+ let sort_ts = |record: &CallRecord| {+ if by_start {+ record.started_at+ } else {+ record.ended_at.unwrap_or(record.started_at)+ }+ };+ let mut seen = Vec::new();+ let mut page = CallRecordPage {+ by_start,+ after: None,+ };+ loop {+ let records = repo+ .get_call_records_by_user(USER_C.deref().copied(), 1, &None, page)+ .await?;+ let Some(last) = records.last() else { break };+ seen.push(last.call_id);+ page.after = Some((sort_ts(last), last.call_id));+ assert!(seen.len() <= all.len(), "a call repeated: {seen:?}");+ }+ let mut expected: Vec<_> = all.iter().map(|record| record.call_id).collect();+ expected.sort();+ seen.sort();+ assert_eq!(seen, expected);+ }+ Ok(())+}+#[sqlx::test(fixtures(path = "../../../fixtures", scripts("call_repo")),migrator = "MACRO_DB_MIGRATIONS"@@ -1648,7 +1697,7 @@ async fn get_call_records_by_user_includes_channel_member_not_in_call(// for CALL1 or call_record_participants for CALL_ARCHIVED. Visibility// should now come from channel membership, so both calls should appear.let records = repo- .get_call_records_by_user(USER_C.deref().copied(), 10, &None)+ .get_call_records_by_user(USER_C.deref().copied(), 10, &None, LATEST_FIRST).await?;assert_eq!(@@ -1675,7 +1724,7 @@ async fn get_call_records_by_user_status_attended_for_participant(let repo = repo(pool);let records = repo- .get_call_records_by_user(USER_A.deref().copied(), 10, &None)+ .get_call_records_by_user(USER_A.deref().copied(), 10, &None, LATEST_FIRST).await?;assert_eq!(records.len(), 2);@@ -1697,7 +1746,7 @@ async fn get_call_records_by_user_status_missed_for_channel_nonparticipant(let repo = repo(pool);let records = repo- .get_call_records_by_user(USER_C.deref().copied(), 10, &None)+ .get_call_records_by_user(USER_C.deref().copied(), 10, &None, LATEST_FIRST).await?;assert_eq!(records.len(), 2);@@ -1719,7 +1768,7 @@ async fn get_call_records_by_user_status_unattended_for_accessible_non_channel_nlet repo = repo(pool);let records = repo- .get_call_records_by_user(USER_D.deref().copied(), 10, &None)+ .get_call_records_by_user(USER_D.deref().copied(), 10, &None, LATEST_FIRST).await?;assert_eq!(records.len(), 2);@@ -1742,27 +1791,27 @@ async fn get_call_records_by_user_status_filters_return_exact_matches(let attended = status_filter(CallStatus::Attended);let attended_records = repo- .get_call_records_by_user(USER_A.deref().copied(), 10, &attended)+ .get_call_records_by_user(USER_A.deref().copied(), 10, &attended, LATEST_FIRST).await?;assert_eq!(attended_records.len(), 2);assert_records_have_status(&attended_records, CallStatus::Attended);let missed = status_filter(CallStatus::Missed);let missed_records = repo- .get_call_records_by_user(USER_C.deref().copied(), 10, &missed)+ .get_call_records_by_user(USER_C.deref().copied(), 10, &missed, LATEST_FIRST).await?;assert_eq!(missed_records.len(), 2);assert_records_have_status(&missed_records, CallStatus::Missed);let unattended = status_filter(CallStatus::Unattended);let unattended_records = repo- .get_call_records_by_user(USER_D.deref().copied(), 10, &unattended)+ .get_call_records_by_user(USER_D.deref().copied(), 10, &unattended, LATEST_FIRST).await?;assert_eq!(unattended_records.len(), 2);assert_records_have_status(&unattended_records, CallStatus::Unattended);let no_unattended_for_channel_member = repo- .get_call_records_by_user(USER_C.deref().copied(), 10, &unattended)+ .get_call_records_by_user(USER_C.deref().copied(), 10, &unattended, LATEST_FIRST).await?;assert!(no_unattended_for_channel_member.is_empty());Ok(())@@ -1779,13 +1828,13 @@ async fn get_call_records_by_user_status_legacy_attended_false_returns_not_partilet filter = attended_filter(false);let missed_records = repo- .get_call_records_by_user(USER_C.deref().copied(), 10, &filter)+ .get_call_records_by_user(USER_C.deref().copied(), 10, &filter, LATEST_FIRST).await?;assert_eq!(missed_records.len(), 2);assert_records_have_status(&missed_records, CallStatus::Missed);let unattended_records = repo- .get_call_records_by_user(USER_D.deref().copied(), 10, &filter)+ .get_call_records_by_user(USER_D.deref().copied(), 10, &filter, LATEST_FIRST).await?;assert_eq!(unattended_records.len(), 2);assert_records_have_status(&unattended_records, CallStatus::Unattended);@@ -1803,12 +1852,12 @@ async fn get_call_records_by_user_status_not_filter_complements_status(let not_attended = not_status_filter(CallStatus::Attended);let participant_records = repo- .get_call_records_by_user(USER_A.deref().copied(), 10, ¬_attended)+ .get_call_records_by_user(USER_A.deref().copied(), 10, ¬_attended, LATEST_FIRST).await?;assert!(participant_records.is_empty());let missed_records = repo- .get_call_records_by_user(USER_C.deref().copied(), 10, ¬_attended)+ .get_call_records_by_user(USER_C.deref().copied(), 10, ¬_attended, LATEST_FIRST).await?;assert_eq!(missed_records.len(), 2);assert_records_have_status(&missed_records, CallStatus::Missed);@@ -1827,7 +1876,7 @@ async fn get_call_records_by_user_attended_true_returns_only_joined(// user-a is a participant in both CALL1 and CALL_ARCHIVED.let user_a_records = repo- .get_call_records_by_user(USER_A.deref().copied(), 10, &filter)+ .get_call_records_by_user(USER_A.deref().copied(), 10, &filter, LATEST_FIRST).await?;assert_eq!(user_a_records.len(), 2);assert!(user_a_records.iter().any(|r| r.call_id == CALL1));@@ -1835,7 +1884,7 @@ async fn get_call_records_by_user_attended_true_returns_only_joined(// user-c is a channel member but did not join any call.let user_c_records = repo- .get_call_records_by_user(USER_C.deref().copied(), 10, &filter)+ .get_call_records_by_user(USER_C.deref().copied(), 10, &filter, LATEST_FIRST).await?;assert!(user_c_records.is_empty(),@@ -1856,7 +1905,7 @@ async fn get_call_records_by_user_attended_false_returns_only_not_joined(// user-a joined every call, so attended=false should return nothing.let user_a_records = repo- .get_call_records_by_user(USER_A.deref().copied(), 10, &filter)+ .get_call_records_by_user(USER_A.deref().copied(), 10, &filter, LATEST_FIRST).await?;assert!(user_a_records.is_empty(),@@ -1865,7 +1914,7 @@ async fn get_call_records_by_user_attended_false_returns_only_not_joined(// user-c joined none of the calls, so both should appear.let user_c_records = repo- .get_call_records_by_user(USER_C.deref().copied(), 10, &filter)+ .get_call_records_by_user(USER_C.deref().copied(), 10, &filter, LATEST_FIRST).await?;assert_eq!(user_c_records.len(), 2);assert!(user_c_records.iter().any(|r| r.call_id == CALL1));@@ -1885,7 +1934,7 @@ async fn get_call_records_by_user_attended_none_returns_all(// Sanity-check the default path: without the attended filter, the query// still returns every call the channel member can see.let records = repo- .get_call_records_by_user(USER_A.deref().copied(), 10, &None)+ .get_call_records_by_user(USER_A.deref().copied(), 10, &None, LATEST_FIRST).await?;assert_eq!(records.len(), 2);Ok(())@@ -1902,20 +1951,20 @@ async fn get_call_records_by_user_call_ids_filter_narrows_results(let filter = call_ids_filter(&[CALL_ARCHIVED]);let records = repo- .get_call_records_by_user(USER_A.deref().copied(), 10, &filter)+ .get_call_records_by_user(USER_A.deref().copied(), 10, &filter, LATEST_FIRST).await?;assert_eq!(records.len(), 1);assert_eq!(records[0].call_id, CALL_ARCHIVED);let filter = call_ids_filter(&[CALL1, CALL_ARCHIVED]);let records = repo- .get_call_records_by_user(USER_A.deref().copied(), 10, &filter)+ .get_call_records_by_user(USER_A.deref().copied(), 10, &filter, LATEST_FIRST).await?;assert_eq!(records.len(), 2);let filter = call_ids_filter(&[Uuid::nil()]);let records = repo- .get_call_records_by_user(USER_A.deref().copied(), 10, &filter)+ .get_call_records_by_user(USER_A.deref().copied(), 10, &filter, LATEST_FIRST).await?;assert!(records.is_empty(),@@ -1962,7 +2011,7 @@ async fn get_call_records_by_user_entity_ref_filter_matches_referencing_calls(entity_ref_property_literal(companies, acme),)));let records = repo- .get_call_records_by_user(USER_A.deref().copied(), 10, &filter)+ .get_call_records_by_user(USER_A.deref().copied(), 10, &filter, LATEST_FIRST).await?;assert_eq!(records.iter().map(|r| r.call_id).collect::<Vec<_>>(),@@ -1975,7 +2024,7 @@ async fn get_call_records_by_user_entity_ref_filter_matches_referencing_calls(Expr::Literal(entity_ref_property_literal(companies, acme)),)));let records = repo- .get_call_records_by_user(USER_A.deref().copied(), 10, &filter)+ .get_call_records_by_user(USER_A.deref().copied(), 10, &filter, LATEST_FIRST).await?;assert_eq!(records.len(), 1);@@ -1985,7 +2034,7 @@ async fn get_call_records_by_user_entity_ref_filter_matches_referencing_calls(] {let filter: LiteralTree<CallLiteral> = Some(Arc::new(Expr::Literal(literal)));let records = repo- .get_call_records_by_user(USER_A.deref().copied(), 10, &filter)+ .get_call_records_by_user(USER_A.deref().copied(), 10, &filter, LATEST_FIRST).await?;assert!(records.is_empty(), "unexpected match: {records:?}");}@@ -1993,9 +2042,14 @@ async fn get_call_records_by_user_entity_ref_filter_matches_referencing_calls(let matching = |filter: Expr<CallLiteral>| {let repo = &repo;async move {- repo.get_call_records_by_user(USER_A.deref().copied(), 10, &Some(Arc::new(filter)))- .await- .map(|records| records.iter().map(|r| r.call_id).collect::<Vec<_>>())+ repo.get_call_records_by_user(+ USER_A.deref().copied(),+ 10,+ &Some(Arc::new(filter)),+ LATEST_FIRST,+ )+ .await+ .map(|records| records.iter().map(|r| r.call_id).collect::<Vec<_>>())}};let acme_ref = || Expr::Literal(entity_ref_property_literal(companies, acme));@@ -2050,7 +2104,7 @@ async fn get_call_records_by_user_returns_archived_summary(.await?;let records = repo- .get_call_records_by_user(USER_A.deref().copied(), 10, &None)+ .get_call_records_by_user(USER_A.deref().copied(), 10, &None, LATEST_FIRST).await?;let active = records@@ -3613,7 +3667,7 @@ async fn standalone_call_list_requires_individual_grants_live_and_archived((USER_D.deref(), true),] {let records = repo- .get_call_records_by_user(user.copied(), 10, &None)+ .get_call_records_by_user(user.copied(), 10, &None, LATEST_FIRST).await?;assert_eq!(records.iter().any(|record| record.call_id == call.id),diff --git a/crates/channels/src/domain/list_service.rs b/crates/channels/src/domain/list_service.rsindex 23d8f4d0f6..3778bdeb5b 100644--- a/crates/channels/src/domain/list_service.rs+++ b/crates/channels/src/domain/list_service.rs@@ -28,7 +28,8 @@ async fn get_channel_frecency<'a, Frec: AggregateFrecencyStorage>(use crate::domain::{models::{Activity, ChannelMessage, ChannelType, ChannelWithLatest, GetChannelsRequest,- GetThreadReplyRowsRequest, NameLookup, UserName, fallback_user_name,+ GetThreadReplyRowsRequest, NameLookup, ReferenceSource, ReferenceTarget, UserName,+ fallback_user_name,},ports::{ChannelListRepo, ChannelListService, ChannelListUserRepo},};@@ -182,6 +183,13 @@ whereself.channels.get_thread_messages(req.into_params())}+ fn get_reference_sources(+ &self,+ targets: &[ReferenceTarget],+ ) -> impl Future<Output = Result<Vec<ReferenceSource>, rootcause::Report>> + Send {+ self.channels.get_reference_sources(targets)+ }+fn get_names(&self,names: std::collections::HashSet<MacroUserIdStr<'_>>,diff --git a/crates/channels/src/domain/models.rs b/crates/channels/src/domain/models.rsindex 89ea81ddc9..9579286790 100644--- a/crates/channels/src/domain/models.rs+++ b/crates/channels/src/domain/models.rs@@ -965,6 +965,83 @@ pub struct GetChannelsParams {query: Query<Uuid, SimpleSortMethod, LiteralTree<ChannelLiteral>>,}+/// An entity whose references are looked up, as stored on reference edges+/// (for example `crm_company` and the company id).+#[cfg(feature = "list")]+#[derive(Debug, Clone, PartialEq, Eq, Hash)]+pub struct ReferenceTarget {+ /// Stored entity type of the referenced entity.+ pub entity_type: String,+ /// Referenced entity id.+ pub entity_id: String,+}++/// What a live reference to a target belongs to.+#[cfg(feature = "list")]+#[derive(Debug, Clone, PartialEq, Eq, Hash)]+pub enum ReferenceSource {+ /// A document or task whose content references the target.+ Document(String),+ /// An undeleted message that references the target.+ Message(ReferencingMessage),+}++/// An undeleted message that mentions or attaches a reference target.+#[cfg(feature = "list")]+#[derive(Debug, Clone, PartialEq, Eq, Hash)]+pub struct ReferencingMessage {+ /// The message id.+ pub message_id: Uuid,+ /// The root of the message's thread, or `None` for a top-level message.+ pub thread_id: Option<Uuid>,+ /// The channel or discussion the message belongs to.+ pub parent: MessageParent,+}++#[cfg(feature = "list")]+impl ReferencingMessage {+ /// The top-level message the reference appears under: the thread root+ /// for a reply, otherwise the message itself.+ pub fn root_id(&self) -> Uuid {+ self.thread_id.unwrap_or(self.message_id)+ }+}++/// The channel or discussion a message belongs to.+#[cfg(feature = "list")]+#[derive(Debug, Clone, PartialEq, Eq, Hash)]+pub enum MessageParent {+ /// A channel message.+ Channel(Uuid),+ /// A discussion message on a document.+ Document(String),+ /// A discussion message on an initiative.+ Initiative(Uuid),+ /// A discussion message on a CRM company.+ CrmCompany(Uuid),+ /// A discussion message on a CRM contact.+ CrmContact(Uuid),+ /// A message in a call's thread.+ Call(Uuid),+}++#[cfg(feature = "list")]+impl MessageParent {+ /// Parse a stored parent, or `None` for an unknown parent type or id.+ pub fn from_stored(parent_type: &str, parent_id: &str) -> Option<Self> {+ let uuid = || Uuid::parse_str(parent_id).ok();+ Some(match parent_type {+ "channel" => Self::Channel(uuid()?),+ "document" => Self::Document(parent_id.to_owned()),+ "initiative" => Self::Initiative(uuid()?),+ "crm_company" => Self::CrmCompany(uuid()?),+ "crm_contact" => Self::CrmContact(uuid()?),+ "call" => Self::Call(uuid()?),+ _ => return None,+ })+ }+}+/// Channel thread reply rows request.#[cfg(feature = "list")]#[derive(Debug)]diff --git a/crates/channels/src/domain/ports.rs b/crates/channels/src/domain/ports.rsindex 15bf76e5b7..9e9e1a1c95 100644--- a/crates/channels/src/domain/ports.rs+++ b/crates/channels/src/domain/ports.rs@@ -13,7 +13,7 @@ use crate::domain::models::{use crate::domain::models::{ChannelMessage, ChannelWithLatest, ChannelWithParticipants, GetChannelsParams,GetChannelsRequest, GetThreadReplyRowsParams, GetThreadReplyRowsRequest, LatestMessage,- UserName,+ ReferenceSource, ReferenceTarget, UserName,};use crate::domain::side_effects::{ChannelDocumentMention, ChannelNotificationEffect, ChannelRealtimeEffect,@@ -63,6 +63,14 @@ pub trait ChannelListRepo: Send + Sync + 'static {&self,req: GetThreadReplyRowsParams,) -> impl Future<Output = Result<Vec<ChannelMessage>, rootcause::Report>> + Send;++ /// Distinct documents and undeleted messages that currently mention or+ /// attach any of `targets`. Unauthorized: callers must apply the reading+ /// user's access to every returned source.+ fn get_reference_sources(+ &self,+ targets: &[ReferenceTarget],+ ) -> impl Future<Output = Result<Vec<ReferenceSource>, rootcause::Report>> + Send;}/// Repository for user display names needed by channel list rendering.@@ -96,6 +104,15 @@ pub trait ChannelListService: Send + Sync + 'static {req: GetThreadReplyRowsRequest,) -> impl Future<Output = Result<Vec<ChannelMessage>, rootcause::Report>> + Send;+ /// Distinct documents and undeleted messages that currently mention or+ /// attach any of `targets`. The result is not authorized for any user:+ /// callers must apply the reader's access to each source before+ /// exposing it.+ fn get_reference_sources(+ &self,+ targets: &[ReferenceTarget],+ ) -> impl Future<Output = Result<Vec<ReferenceSource>, rootcause::Report>> + Send;+/// Fetch names for user ids.fn get_names(&self,diff --git a/crates/channels/src/inbound/list_router/test.rs b/crates/channels/src/inbound/list_router/test.rsindex 30ae5bb52e..b8b44d1330 100644--- a/crates/channels/src/inbound/list_router/test.rs+++ b/crates/channels/src/inbound/list_router/test.rs@@ -92,6 +92,13 @@ impl ChannelListService for FakeChannelListService {Ok(Vec::new())}+ async fn get_reference_sources(+ &self,+ _targets: &[crate::domain::models::ReferenceTarget],+ ) -> Result<Vec<crate::domain::models::ReferenceSource>, Report> {+ Ok(Vec::new())+ }+async fn get_names(&self,_names: HashSet<MacroUserIdStr<'_>>,diff --git a/crates/channels/src/outbound/pg_channels_repo.rs b/crates/channels/src/outbound/pg_channels_repo.rsindex bf27c5b0ce..2977240275 100644--- a/crates/channels/src/outbound/pg_channels_repo.rs+++ b/crates/channels/src/outbound/pg_channels_repo.rs@@ -1,5 +1,7 @@/// Silent historical persistence and transaction-aware activity updates.pub mod historical;+#[cfg(feature = "list")]+mod references;#[cfg(test)]mod tests;@@ -1198,6 +1200,13 @@ impl PgChannelsRepo {#[cfg(feature = "list")]impl ChannelListRepo for PgChannelsRepo {+ async fn get_reference_sources(+ &self,+ targets: &[crate::domain::models::ReferenceTarget],+ ) -> Result<Vec<crate::domain::models::ReferenceSource>, rootcause::Report> {+ self.query_reference_sources(targets).await+ }+async fn get_user_channels_with_participants(&self,params: GetChannelsParams,diff --git a/crates/channels/src/outbound/pg_channels_repo/references.rs b/crates/channels/src/outbound/pg_channels_repo/references.rsnew file mode 100644index 0000000000..66fc10849c--- /dev/null+++ b/crates/channels/src/outbound/pg_channels_repo/references.rs@@ -0,0 +1,96 @@+//! Reference edges for associated-item queries: documents and undeleted+//! messages that mention or attach a target entity.++use std::collections::HashSet;++use crate::domain::models::{MessageParent, ReferenceSource, ReferenceTarget, ReferencingMessage};++use super::PgChannelsRepo;++#[cfg(test)]+mod test;++impl PgChannelsRepo {+ pub(super) async fn query_reference_sources(+ &self,+ targets: &[ReferenceTarget],+ ) -> Result<Vec<ReferenceSource>, rootcause::Report> {+ if targets.is_empty() {+ return Ok(Vec::new());+ }+ let (entity_types, entity_ids): (Vec<String>, Vec<String>) = targets+ .iter()+ .map(|target| (target.entity_type.clone(), target.entity_id.clone()))+ .unzip();+ // Message sources resolve to their live message so deleted messages+ // stop matching; the CASE keeps document ids out of the uuid cast.+ let rows = sqlx::query!(+ r#"+ WITH targets AS (+ SELECT * FROM UNNEST($1::text[], $2::text[]) AS t(entity_type, entity_id)+ ),+ edges AS (+ SELECT em.source_entity_type::text AS source_type,+ em.source_entity_id AS source_id+ FROM comms_entity_mentions em+ JOIN targets t+ ON em.entity_type = t.entity_type AND em.entity_id = t.entity_id+ WHERE em.source_entity_type IN ('document', 'message')+ UNION+ SELECT 'message', a.message_id::text+ FROM comms_attachments a+ JOIN targets t+ ON a.entity_type = t.entity_type AND a.entity_id = t.entity_id+ )+ SELECT+ e.source_type AS "source_type!",+ e.source_id AS "source_id!",+ m.id AS "message_id?",+ m.thread_id AS "thread_id?",+ m.parent_entity_type AS "parent_entity_type?",+ m.parent_entity_id AS "parent_entity_id?"+ FROM edges e+ LEFT JOIN comms_messages m+ ON m.id = CASE WHEN e.source_type = 'message' THEN e.source_id::uuid END+ AND m.deleted_at IS NULL+ WHERE e.source_type = 'document' OR m.id IS NOT NULL+ "#,+ &entity_types,+ &entity_ids,+ )+ .fetch_all(&self.pool)+ .await?;++ let mut seen = HashSet::new();+ let mut sources = Vec::with_capacity(rows.len());+ for row in rows {+ let source = match (+ row.source_type.as_str(),+ row.message_id,+ row.parent_entity_type.as_deref(),+ row.parent_entity_id.as_deref(),+ ) {+ ("document", ..) => ReferenceSource::Document(row.source_id),+ ("message", Some(message_id), Some(parent_type), Some(parent_id)) => {+ let Some(parent) = MessageParent::from_stored(parent_type, parent_id) else {+ tracing::warn!(+ parent_type,+ "referencing message has an unknown parent; skipping"+ );+ continue;+ };+ ReferenceSource::Message(ReferencingMessage {+ message_id,+ thread_id: row.thread_id,+ parent,+ })+ }+ _ => continue,+ };+ if seen.insert(source.clone()) {+ sources.push(source);+ }+ }+ Ok(sources)+ }+}diff --git a/crates/channels/src/outbound/pg_channels_repo/references/test.rs b/crates/channels/src/outbound/pg_channels_repo/references/test.rsnew file mode 100644index 0000000000..ea7221ae33--- /dev/null+++ b/crates/channels/src/outbound/pg_channels_repo/references/test.rs@@ -0,0 +1,146 @@+use crate::domain::models::{MessageParent, ReferenceSource, ReferenceTarget, ReferencingMessage};+use crate::outbound::pg_channels_repo::PgChannelsRepo;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::{Pool, Postgres};+use uuid::Uuid;++const CH1: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000c01);+const MSG1: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000001);+const MSG3: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000003);+const DELETED_MSG: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_000000000004);+const REPLY1: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_00000000b001);+const DISCUSSION_MSG: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_00000000d001);+const COMPANY: &str = "00000000-0000-0000-0000-00000000c0c0";+const CONTACT: &str = "00000000-0000-0000-0000-00000000c0c1";+const OTHER_CONTACT: &str = "00000000-0000-0000-0000-00000000c0c2";++fn target(entity_type: &str, entity_id: &str) -> ReferenceTarget {+ ReferenceTarget {+ entity_type: entity_type.to_owned(),+ entity_id: entity_id.to_owned(),+ }+}++async fn mention(+ pool: &Pool<Postgres>,+ source_type: &str,+ source_id: &str,+ entity_type: &str,+ entity_id: &str,+) {+ sqlx::query!(+ r#"INSERT INTO comms_entity_mentions+ (id, source_entity_type, source_entity_id, entity_type, entity_id)+ VALUES ($1, $2, $3, $4, $5)"#,+ Uuid::now_v7(),+ source_type,+ source_id,+ entity_type,+ entity_id,+ )+ .execute(pool)+ .await+ .unwrap();+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../../fixtures", scripts("channels_repo"))+)]+async fn resolves_live_documents_and_messages_once(pool: Pool<Postgres>) {+ sqlx::query!(+ r#"INSERT INTO comms_messages+ (id, parent_entity_type, parent_entity_id, sender_id, content)+ VALUES ($1, 'document', 'doc-with-discussion', 'macro|[email protected]', 'discussion')"#,+ DISCUSSION_MSG,+ )+ .execute(&pool)+ .await+ .unwrap();+ // A document referencing both targets, twice, is one source.+ mention(&pool, "document", "doc-1", "crm_company", COMPANY).await;+ mention(&pool, "document", "doc-1", "crm_contact", CONTACT).await;+ mention(&pool, "document", "doc-1", "crm_contact", CONTACT).await;+ // A top-level message, a reply, and a document discussion message.+ mention(&pool, "message", &MSG3.to_string(), "crm_contact", CONTACT).await;+ mention(+ &pool,+ "message",+ &REPLY1.to_string(),+ "crm_company",+ COMPANY,+ )+ .await;+ mention(+ &pool,+ "message",+ &DISCUSSION_MSG.to_string(),+ "crm_company",+ COMPANY,+ )+ .await;+ // Deleted messages, other targets, and other source types never match.+ mention(+ &pool,+ "message",+ &DELETED_MSG.to_string(),+ "crm_company",+ COMPANY,+ )+ .await;+ mention(&pool, "document", "doc-2", "crm_contact", OTHER_CONTACT).await;+ mention(&pool, "document", "doc-3", "document", COMPANY).await;+ mention(&pool, "chat", "chat-1", "crm_company", COMPANY).await;+ // An attachment of the company on a message counts as a reference.+ sqlx::query!(+ r#"INSERT INTO comms_attachments (id, message_id, entity_type, entity_id)+ VALUES ($1, $2, 'crm_company', $3)"#,+ Uuid::now_v7(),+ MSG1,+ COMPANY,+ )+ .execute(&pool)+ .await+ .unwrap();++ let mut sources = PgChannelsRepo::new(pool)+ .query_reference_sources(&[+ target("crm_company", COMPANY),+ target("crm_contact", CONTACT),+ ])+ .await+ .unwrap();+ sources.sort_by_key(|source| format!("{source:?}"));++ let message = |message_id, thread_id, parent| {+ ReferenceSource::Message(ReferencingMessage {+ message_id,+ thread_id,+ parent,+ })+ };+ let mut expected = vec![+ ReferenceSource::Document("doc-1".to_owned()),+ message(MSG1, None, MessageParent::Channel(CH1)),+ message(MSG3, None, MessageParent::Channel(CH1)),+ message(REPLY1, Some(MSG1), MessageParent::Channel(CH1)),+ message(+ DISCUSSION_MSG,+ None,+ MessageParent::Document("doc-with-discussion".to_owned()),+ ),+ ];+ expected.sort_by_key(|source| format!("{source:?}"));+ assert_eq!(sources, expected);+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn no_targets_reads_nothing(pool: Pool<Postgres>) {+ assert!(+ PgChannelsRepo::new(pool)+ .query_reference_sources(&[])+ .await+ .unwrap()+ .is_empty()+ );+}diff --git a/crates/complete_graph/src/sdl_test.rs b/crates/complete_graph/src/sdl_test.rsindex eff94f9215..35c166c357 100644--- a/crates/complete_graph/src/sdl_test.rs+++ b/crates/complete_graph/src/sdl_test.rs@@ -556,6 +556,30 @@ fn crm_records_carry_their_pipeline_entries() {assert_sdl_line(&pipeline, "canEdit: Boolean!");}+#[test]+fn crm_associations_scope_soup_and_compose_in_document_trees() {+ let sdl = crate::build_schema().sdl();+ let block = |declaration: &str| {+ sdl.split_once(declaration)+ .unwrap_or_else(|| panic!("schema has no `{declaration}`"))+ .1+ .split_once("\n}")+ .unwrap()+ .0+ .to_owned()+ };+ assert_sdl_line(+ &block("input GraphqlEntityFilterAst {"),+ "crmAssociation: GraphqlCrmAssociation",+ );+ let document = block("input GraphqlDocumentLiteral @oneOf {");+ assert_sdl_line(&document, "crmAssociated: GraphqlCrmAssociation");+ assert_sdl_line(&document, "nameContains: String");+ let association = block("input GraphqlCrmAssociation @oneOf {");+ assert_sdl_line(&association, "company: ID");+ assert_sdl_line(&association, "contact: ID");+}+#[test]fn scheduled_actions_hang_off_the_authenticated_user() {use apollo_compiler::schema::ExtendedType;diff --git a/crates/crm/src/domain.rs b/crates/crm/src/domain.rsindex 9d724ee4d7..239f25f638 100644--- a/crates/crm/src/domain.rs+++ b/crates/crm/src/domain.rs@@ -34,6 +34,9 @@ pub mod search_repo;#[cfg(feature = "search")]pub mod search_service;+/// The CRM records an associated-items query matches against.+#[cfg(feature = "ports")]+pub mod association;/// Contact listing models shared by Soup and the CRM service.#[cfg(feature = "ports")]pub mod contact_listing;diff --git a/crates/crm/src/domain/association.rs b/crates/crm/src/domain/association.rsnew file mode 100644index 0000000000..4938eb0132--- /dev/null+++ b/crates/crm/src/domain/association.rs@@ -0,0 +1,37 @@+//! The CRM records an associated-items query matches against.++use uuid::Uuid;++pub use item_filters::ast::crm_association::CrmAssociation;++/// The records whose Companies and Contacts property values, and whose+/// references, make an item associated with an authorized CRM record.+///+/// A company covers itself and every contact of the company that the viewer+/// may see. A contact covers only itself: it does not inherit the items+/// associated with its company.+#[derive(Debug, Clone, Default, PartialEq, Eq)]+pub struct CrmRecordAssociation {+ /// Companies matched through the Companies property or a reference.+ pub company_ids: Vec<Uuid>,+ /// Contacts matched through the Contacts property or a reference.+ pub contact_ids: Vec<Uuid>,+}++impl CrmRecordAssociation {+ /// The association of a company and its visible contacts.+ pub fn company(company_id: Uuid, contact_ids: Vec<Uuid>) -> Self {+ Self {+ company_ids: vec![company_id],+ contact_ids,+ }+ }++ /// The association of one contact.+ pub fn contact(contact_id: Uuid) -> Self {+ Self {+ company_ids: Vec::new(),+ contact_ids: vec![contact_id],+ }+ }+}diff --git a/crates/crm/src/domain/companies_repo.rs b/crates/crm/src/domain/companies_repo.rsindex 182404c77b..c789c8ee47 100644--- a/crates/crm/src/domain/companies_repo.rs+++ b/crates/crm/src/domain/companies_repo.rs@@ -56,6 +56,16 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {query: &super::contact_listing::CrmContactListQuery,) -> impl Future<Output = Result<Vec<super::contact_listing::CrmContactForSoup>, CrmError>> + Send;+ /// Resolve `record` to the records its associated items match, under the+ /// same visibility as the scope's contact listings: CRM-enabled teams+ /// only, and hidden companies and contacts are visible only to the owning+ /// team's admins and owners. `None` when the record is not visible.+ fn resolve_association(+ &self,+ scope: super::contact_listing::CrmContactListScope<'_>,+ record: super::association::CrmAssociation,+ ) -> impl Future<Output = Result<Option<super::association::CrmRecordAssociation>, CrmError>> + Send;+/// Idempotently records that `email` (which lives on `domain`) was seen/// from the mailbox identified by `link_id`, for the team `team_id`./// Performs the company/domain/contact/contact_source upserts in a singlediff --git a/crates/crm/src/domain/service.rs b/crates/crm/src/domain/service.rsindex 462c4b87cc..53e76c2026 100644--- a/crates/crm/src/domain/service.rs+++ b/crates/crm/src/domain/service.rs@@ -28,6 +28,18 @@ pub trait CrmService: Clone + Send + Sync + 'static {query: super::contact_listing::CrmContactListQuery,) -> impl Future<Output = Result<Vec<super::contact_listing::CrmContactForSoup>, CrmError>> + Send;+ /// Authorize `record` for the viewer and resolve the records whose+ /// properties and references make an item associated with it: a company+ /// with every contact the viewer may see, or a single contact. Scoped+ /// like [`Self::list_contacts_for_soup`]; a record the viewer cannot see+ /// is reported as not found.+ fn resolve_association(+ &self,+ user_id: &str,+ access: Option<&CrmTeamReceipt<MemberTeamRole>>,+ record: super::association::CrmAssociation,+ ) -> impl Future<Output = Result<super::association::CrmRecordAssociation, CrmError>> + Send;+/// Idempotently records that `email` was seen from the mailbox/// identified by `link_id`, for the team `team_id`. Upserts/// `crm_companies` (+ `crm_domains`), `crm_contacts`, and@@ -398,6 +410,37 @@ const MAX_EMAIL_CHARS: usize = 320;/// enough for the Quick Access feed of a team's recent contacts.pub const MAX_CONTACT_SEARCH_LIMIT: u16 = 500;+/// The records a viewer-scoped CRM read covers: every enabled team the+/// viewer belongs to, or the single team of a verified team-scoped bot+/// receipt. A receipt for another viewer is rejected.+fn viewer_scope<'a>(+ user_id: &'a str,+ access: Option<&CrmTeamReceipt<MemberTeamRole>>,+) -> Result<super::contact_listing::CrmContactListScope<'a>, CrmError> {+ use super::contact_listing::CrmContactListScope;+ use entity_access::domain::models::{BotReceiptScope, EntityAccessAuth};+ match access.map(|access| (access, access.receipt().auth())) {+ Some((access, EntityAccessAuth::Bot(bot))) => match bot.scope() {+ BotReceiptScope::Team { team_id } if *team_id == access.team_id() => {+ Ok(CrmContactListScope::Team {+ team_id: *team_id,+ include_hidden: access.include_hidden(),+ })+ }+ BotReceiptScope::User { acting_user } if acting_user.as_ref() == user_id => {+ Ok(CrmContactListScope::Viewer(user_id))+ }+ _ => Err(CrmError::InvalidRequest(+ "contact listing scope mismatch".into(),+ )),+ },+ Some((_, EntityAccessAuth::Authenticated(user))) if user.as_ref() != user_id => Err(+ CrmError::InvalidRequest("contact listing viewer mismatch".into()),+ ),+ _ => Ok(CrmContactListScope::Viewer(user_id)),+ }+}+/// Validates a user-supplied display name: trims whitespace; must be/// non-blank and within [`MAX_DISPLAY_NAME_CHARS`].fn validate_display_name(raw: &str) -> Result<&str, CrmError> {@@ -819,38 +862,31 @@ whereaccess: Option<&CrmTeamReceipt<MemberTeamRole>>,mut query: super::contact_listing::CrmContactListQuery,) -> Result<Vec<super::contact_listing::CrmContactForSoup>, CrmError> {- use super::contact_listing::CrmContactListScope;- use entity_access::domain::models::{BotReceiptScope, EntityAccessAuth};- let scope = match access.map(|access| (access, access.receipt().auth())) {- Some((access, EntityAccessAuth::Bot(bot))) => match bot.scope() {- BotReceiptScope::Team { team_id } if *team_id == access.team_id() => {- CrmContactListScope::Team {- team_id: *team_id,- include_hidden: access.include_hidden(),- }- }- BotReceiptScope::User { acting_user } if acting_user.as_ref() == user_id => {- CrmContactListScope::Viewer(user_id)- }- _ => {- return Err(CrmError::InvalidRequest(- "contact listing scope mismatch".into(),- ));- }- },- Some((_, EntityAccessAuth::Authenticated(user))) if user.as_ref() != user_id => {- return Err(CrmError::InvalidRequest(- "contact listing viewer mismatch".into(),- ));- }- _ => CrmContactListScope::Viewer(user_id),- };+ let scope = viewer_scope(user_id, access)?;query.limit = query.limit.clamp(1, MAX_CONTACT_SEARCH_LIMIT);self.companies_repository.list_contacts_for_soup(scope, user_id, &query).await}+ #[tracing::instrument(skip(self, access), err)]+ async fn resolve_association(+ &self,+ user_id: &str,+ access: Option<&CrmTeamReceipt<MemberTeamRole>>,+ record: super::association::CrmAssociation,+ ) -> Result<super::association::CrmRecordAssociation, CrmError> {+ use super::association::CrmAssociation;+ let scope = viewer_scope(user_id, access)?;+ self.companies_repository+ .resolve_association(scope, record)+ .await?+ .ok_or(match record {+ CrmAssociation::Company(_) => CrmError::CompanyNotFoundForTeam,+ CrmAssociation::Contact(_) => CrmError::ContactNotFoundForTeam,+ })+ }+#[tracing::instrument(skip(self, access), err)]#[allow(clippy::too_many_arguments)]async fn list_companies_for_soup(@@ -1015,6 +1051,19 @@ impl CrmService for NoOpCrmService {Ok(vec![])}+ async fn resolve_association(+ &self,+ _user_id: &str,+ _access: Option<&CrmTeamReceipt<MemberTeamRole>>,+ record: super::association::CrmAssociation,+ ) -> Result<super::association::CrmRecordAssociation, CrmError> {+ use super::association::CrmAssociation;+ Err(match record {+ CrmAssociation::Company(_) => CrmError::CompanyNotFoundForTeam,+ CrmAssociation::Contact(_) => CrmError::ContactNotFoundForTeam,+ })+ }+async fn populate_contact(&self,_team_id: &uuid::Uuid,diff --git a/crates/crm/src/domain/service/test.rs b/crates/crm/src/domain/service/test.rsindex 9df3ae61e9..7e5f7a8efc 100644--- a/crates/crm/src/domain/service/test.rs+++ b/crates/crm/src/domain/service/test.rs@@ -18,6 +18,8 @@ use std::sync::{Arc, Mutex};#[derive(Clone, Default)]struct StubRepo {contact_calls: Arc<Mutex<Vec<ContactListCall>>>,+ association_calls: Arc<Mutex<Vec<Option<(uuid::Uuid, bool)>>>>,+ association: Option<crate::domain::association::CrmRecordAssociation>,}#[derive(Debug, PartialEq)]@@ -52,6 +54,21 @@ impl CompaniesRepository for StubRepo {Ok(vec![])}+ async fn resolve_association(+ &self,+ scope: CrmContactListScope<'_>,+ _record: crate::domain::association::CrmAssociation,+ ) -> Result<Option<crate::domain::association::CrmRecordAssociation>, CrmError> {+ self.association_calls.lock().unwrap().push(match scope {+ CrmContactListScope::Viewer(_) => None,+ CrmContactListScope::Team {+ team_id,+ include_hidden,+ } => Some((team_id, include_hidden)),+ });+ Ok(self.association.clone())+ }+async fn populate_contact(&self,_team_id: &uuid::Uuid,@@ -459,6 +476,64 @@ async fn contact_listing_requires_a_user_bot_to_match_its_acting_user() {);}+#[tokio::test]+async fn association_uses_the_viewer_scope_and_reports_invisible_records() {+ use crate::domain::association::{CrmAssociation, CrmRecordAssociation};+ let company = uuid::Uuid::from_u128(7);+ let contact = uuid::Uuid::from_u128(8);+ let viewer = "macro|[email protected]";+ let resolved = CrmRecordAssociation::company(company, vec![contact]);+ let found = CrmServiceImpl::new(+ StubRepo {+ association: Some(resolved.clone()),+ ..StubRepo::default()+ },+ NoOpCompanyMetadataResolver,+ );+ assert_eq!(+ found+ .resolve_association(viewer, None, CrmAssociation::Company(company))+ .await+ .unwrap(),+ resolved+ );+ let team_id = uuid::Uuid::from_u128(42);+ let bot = bot_receipt(team_id, BotReceiptScope::Team { team_id }, TeamRole::Member);+ found+ .resolve_association("bot-viewer", Some(&bot), CrmAssociation::Company(company))+ .await+ .unwrap();+ assert_eq!(+ *found.companies_repository.association_calls.lock().unwrap(),+ vec![None, Some((team_id, false))]+ );+ let member = receipt_with_role(TeamRole::Member);+ assert!(matches!(+ found+ .resolve_association(+ "macro|[email protected]",+ Some(&member),+ CrmAssociation::Company(company)+ )+ .await,+ Err(CrmError::InvalidRequest(_))+ ));++ let missing = service();+ assert!(matches!(+ missing+ .resolve_association(viewer, None, CrmAssociation::Company(company))+ .await,+ Err(CrmError::CompanyNotFoundForTeam)+ ));+ assert!(matches!(+ missing+ .resolve_association(viewer, None, CrmAssociation::Contact(contact))+ .await,+ Err(CrmError::ContactNotFoundForTeam)+ ));+}+#[tokio::test]async fn member_can_update_team_views_and_default() {let access = receipt_with_role(TeamRole::Member);diff --git a/crates/crm/src/inbound/axum_extractors/test.rs b/crates/crm/src/inbound/axum_extractors/test.rsindex dba2b7caf0..ad18e39e79 100644--- a/crates/crm/src/inbound/axum_extractors/test.rs+++ b/crates/crm/src/inbound/axum_extractors/test.rs@@ -238,6 +238,17 @@ impl CrmService for FakeCrmService {Ok(vec![])}+ async fn resolve_association(+ &self,+ _user_id: &str,+ _access: Option<+ &crate::domain::auth::CrmTeamReceipt<entity_access::domain::models::MemberTeamRole>,+ >,+ _record: crate::domain::association::CrmAssociation,+ ) -> Result<crate::domain::association::CrmRecordAssociation, CrmError> {+ panic!("unexpected resolve_association call")+ }+async fn populate_contact(&self,_team_id: &Uuid,diff --git a/crates/crm/src/outbound/companies_repo.rs b/crates/crm/src/outbound/companies_repo.rsindex 90e4e44113..7f0144a2ed 100644--- a/crates/crm/src/outbound/companies_repo.rs+++ b/crates/crm/src/outbound/companies_repo.rs@@ -3,6 +3,7 @@#[cfg(test)]pub(crate) mod test;+mod association;mod contact_listing;use crate::domain::{@@ -259,6 +260,15 @@ impl CompaniesRepository for CompaniesRepositoryImpl {self.query_contacts_for_soup(scope, viewer_id, query).await}+ #[tracing::instrument(skip(self), err)]+ async fn resolve_association(+ &self,+ scope: crate::domain::contact_listing::CrmContactListScope<'_>,+ record: crate::domain::association::CrmAssociation,+ ) -> Result<Option<crate::domain::association::CrmRecordAssociation>, CrmError> {+ self.query_association(scope, record).await+ }+#[tracing::instrument(skip(self), err)]#[allow(clippy::too_many_arguments)]async fn populate_contact(diff --git a/crates/crm/src/outbound/companies_repo/association.rs b/crates/crm/src/outbound/companies_repo/association.rsnew file mode 100644index 0000000000..d1654e7973--- /dev/null+++ b/crates/crm/src/outbound/companies_repo/association.rs@@ -0,0 +1,148 @@+//! Resolve a CRM record to the records its associated items match.+//!+//! Visibility mirrors the viewer-scoped contact listing: the owning team must+//! have CRM enabled, a viewer must belong to it, and hidden companies and+//! contacts are visible only to its admins and owners (or a team-scoped bot+//! receipt that permits hidden rows).++use uuid::Uuid;++use super::CompaniesRepositoryImpl;+use crate::domain::{+ association::{CrmAssociation, CrmRecordAssociation},+ contact_listing::CrmContactListScope,+ model::CrmError,+};++impl CompaniesRepositoryImpl {+ pub(super) async fn query_association(+ &self,+ scope: CrmContactListScope<'_>,+ record: CrmAssociation,+ ) -> Result<Option<CrmRecordAssociation>, CrmError> {+ match record {+ CrmAssociation::Company(company_id) => {+ let rows = self.company_contacts(scope, company_id).await?;+ // One row per visible contact, or a single NULL-contact row+ // for a visible company without any; no rows means the+ // company itself is not visible.+ if rows.is_empty() {+ return Ok(None);+ }+ Ok(Some(CrmRecordAssociation::company(+ company_id,+ rows.into_iter().flatten().collect(),+ )))+ }+ CrmAssociation::Contact(contact_id) => Ok(self+ .contact_visible(scope, contact_id)+ .await?+ .then(|| CrmRecordAssociation::contact(contact_id))),+ }+ }++ async fn company_contacts(+ &self,+ scope: CrmContactListScope<'_>,+ company_id: Uuid,+ ) -> Result<Vec<Option<Uuid>>, CrmError> {+ let rows = match scope {+ CrmContactListScope::Viewer(user_id) => {+ sqlx::query_scalar!(+ r#"+ SELECT ct.id AS "contact_id?"+ FROM crm_companies co+ JOIN team_crm_settings tcs ON tcs.team_id = co.team_id AND tcs.crm_enabled+ JOIN team_user tu ON tu.team_id = co.team_id AND tu.user_id = $1+ LEFT JOIN crm_contacts ct+ ON ct.company_id = co.id+ AND (NOT ct.hidden OR tu.team_role <> 'member')+ WHERE co.id = $2+ AND (NOT co.hidden OR tu.team_role <> 'member')+ ORDER BY ct.id+ "#,+ user_id,+ company_id,+ )+ .fetch_all(&self.pool)+ .await+ }+ CrmContactListScope::Team {+ team_id,+ include_hidden,+ } => {+ sqlx::query_scalar!(+ r#"+ SELECT ct.id AS "contact_id?"+ FROM crm_companies co+ JOIN team_crm_settings tcs ON tcs.team_id = co.team_id AND tcs.crm_enabled+ LEFT JOIN crm_contacts ct+ ON ct.company_id = co.id AND (NOT ct.hidden OR $3)+ WHERE co.id = $1+ AND co.team_id = $2+ AND (NOT co.hidden OR $3)+ ORDER BY ct.id+ "#,+ company_id,+ team_id,+ include_hidden,+ )+ .fetch_all(&self.pool)+ .await+ }+ };+ rows.map_err(|error| CrmError::StorageLayerError(error.into()))+ }++ async fn contact_visible(+ &self,+ scope: CrmContactListScope<'_>,+ contact_id: Uuid,+ ) -> Result<bool, CrmError> {+ let visible = match scope {+ CrmContactListScope::Viewer(user_id) => {+ sqlx::query_scalar!(+ r#"+ SELECT EXISTS (+ SELECT 1+ FROM crm_contacts ct+ JOIN crm_companies co ON co.id = ct.company_id+ JOIN team_crm_settings tcs ON tcs.team_id = co.team_id AND tcs.crm_enabled+ JOIN team_user tu ON tu.team_id = co.team_id AND tu.user_id = $1+ WHERE ct.id = $2+ AND (NOT (ct.hidden OR co.hidden) OR tu.team_role <> 'member')+ ) AS "visible!"+ "#,+ user_id,+ contact_id,+ )+ .fetch_one(&self.pool)+ .await+ }+ CrmContactListScope::Team {+ team_id,+ include_hidden,+ } => {+ sqlx::query_scalar!(+ r#"+ SELECT EXISTS (+ SELECT 1+ FROM crm_contacts ct+ JOIN crm_companies co ON co.id = ct.company_id+ JOIN team_crm_settings tcs ON tcs.team_id = co.team_id AND tcs.crm_enabled+ WHERE ct.id = $1+ AND co.team_id = $2+ AND (NOT (ct.hidden OR co.hidden) OR $3)+ ) AS "visible!"+ "#,+ contact_id,+ team_id,+ include_hidden,+ )+ .fetch_one(&self.pool)+ .await+ }+ };+ visible.map_err(|error| CrmError::StorageLayerError(error.into()))+ }+}diff --git a/crates/crm/src/outbound/companies_repo/test.rs b/crates/crm/src/outbound/companies_repo/test.rsindex 8d13ea1bc5..2cf612b1b8 100644--- a/crates/crm/src/outbound/companies_repo/test.rs+++ b/crates/crm/src/outbound/companies_repo/test.rs@@ -16,6 +16,7 @@ mod list_companies_for_soup;mod list_contacts_for_company;mod list_contacts_for_soup;mod populate_contact;+mod resolve_association;mod search_contacts_for_team;mod set_company_hidden;mod set_company_name;diff --git a/crates/crm/src/outbound/companies_repo/test/resolve_association.rs b/crates/crm/src/outbound/companies_repo/test/resolve_association.rsnew file mode 100644index 0000000000..bdc5ac2176--- /dev/null+++ b/crates/crm/src/outbound/companies_repo/test/resolve_association.rs@@ -0,0 +1,149 @@+use crate::domain::{+ association::{CrmAssociation, CrmRecordAssociation},+ companies_repo::CompaniesRepository,+ contact_listing::CrmContactListScope,+};+use crate::outbound::companies_repo::CompaniesRepositoryImpl;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use sqlx::PgPool;+use uuid::Uuid;++const VIEWER: &str = "macro|[email protected]";+fn id(value: u128) -> Uuid {+ Uuid::from_u128(value)+}+async fn resolve(+ repo: &CompaniesRepositoryImpl,+ scope: CrmContactListScope<'_>,+ record: CrmAssociation,+) -> Option<CrmRecordAssociation> {+ repo.resolve_association(scope, record).await.unwrap()+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures("fixtures/contact_listing.sql")+)]+async fn company_covers_every_contact_the_viewer_may_see(pool: PgPool) {+ let repo = CompaniesRepositoryImpl::new(pool);+ let viewer = || CrmContactListScope::Viewer(VIEWER);+ // Admin of team 11 sees the hidden contact 1008.+ assert_eq!(+ resolve(&repo, viewer(), CrmAssociation::Company(id(101))).await,+ Some(CrmRecordAssociation::company(+ id(101),+ [1001, 1004, 1008, 1010, 1011].map(id).to_vec()+ ))+ );+ // A plain member of team 12 does not see hidden contact 1007.+ assert_eq!(+ resolve(&repo, viewer(), CrmAssociation::Company(id(102))).await,+ Some(CrmRecordAssociation::company(+ id(102),+ [1002, 1005].map(id).to_vec()+ ))+ );+ // An admin may target a hidden company.+ assert_eq!(+ resolve(&repo, viewer(), CrmAssociation::Company(id(105))).await,+ Some(CrmRecordAssociation::company(id(105), vec![id(1006)]))+ );+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures("fixtures/contact_listing.sql")+)]+async fn invisible_records_do_not_resolve(pool: PgPool) {+ let repo = CompaniesRepositoryImpl::new(pool);+ let viewer = || CrmContactListScope::Viewer(VIEWER);+ for record in [+ // The viewer is not in team 14.+ CrmAssociation::Company(id(104)),+ CrmAssociation::Contact(id(1003)),+ // Hidden from a plain member of team 12.+ CrmAssociation::Contact(id(1007)),+ // Team 13 has CRM disabled.+ CrmAssociation::Company(id(103)),+ CrmAssociation::Contact(id(1009)),+ // Unknown ids.+ CrmAssociation::Company(id(999)),+ CrmAssociation::Contact(id(9999)),+ ] {+ assert_eq!(resolve(&repo, viewer(), record).await, None, "{record:?}");+ }+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures("fixtures/contact_listing.sql")+)]+async fn contact_covers_only_itself(pool: PgPool) {+ let repo = CompaniesRepositoryImpl::new(pool);+ assert_eq!(+ resolve(+ &repo,+ CrmContactListScope::Viewer(VIEWER),+ CrmAssociation::Contact(id(1002))+ )+ .await,+ Some(CrmRecordAssociation::contact(id(1002)))+ );+ // Admins see a contact under a hidden company.+ assert_eq!(+ resolve(+ &repo,+ CrmContactListScope::Viewer(VIEWER),+ CrmAssociation::Contact(id(1006))+ )+ .await,+ Some(CrmRecordAssociation::contact(id(1006)))+ );+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures("fixtures/contact_listing.sql")+)]+async fn team_scope_is_restricted_to_its_team(pool: PgPool) {+ let repo = CompaniesRepositoryImpl::new(pool);+ let team = |include_hidden| CrmContactListScope::Team {+ team_id: id(12),+ include_hidden,+ };+ assert_eq!(+ resolve(&repo, team(false), CrmAssociation::Company(id(102))).await,+ Some(CrmRecordAssociation::company(+ id(102),+ [1002, 1005].map(id).to_vec()+ ))+ );+ assert_eq!(+ resolve(&repo, team(true), CrmAssociation::Company(id(102))).await,+ Some(CrmRecordAssociation::company(+ id(102),+ [1002, 1005, 1007].map(id).to_vec()+ ))+ );+ assert_eq!(+ resolve(&repo, team(false), CrmAssociation::Contact(id(1007))).await,+ None+ );+ assert_eq!(+ resolve(&repo, team(true), CrmAssociation::Company(id(101))).await,+ None+ );+ // A CRM-disabled team's own records do not resolve either.+ let disabled = || CrmContactListScope::Team {+ team_id: id(13),+ include_hidden: true,+ };+ assert_eq!(+ resolve(&repo, disabled(), CrmAssociation::Company(id(103))).await,+ None+ );+ assert_eq!(+ resolve(&repo, disabled(), CrmAssociation::Contact(id(1009))).await,+ None+ );+}diff --git a/crates/databases/src/outbound/pg_databases_repo/test/entity_split.rs b/crates/databases/src/outbound/pg_databases_repo/test/entity_split.rsindex 667014f86b..502f9938d5 100644--- a/crates/databases/src/outbound/pg_databases_repo/test/entity_split.rs+++ b/crates/databases/src/outbound/pg_databases_repo/test/entity_split.rs@@ -14,6 +14,10 @@ const SPLIT_DOWN: &str = include_str!(concat!(env!("CARGO_MANIFEST_DIR"),"/../macro_db_client/migrations/20261005183743_separate_database_entity.down.sql"));+const WEBHOOKS_DOWN: &str = include_str!(concat!(+ env!("CARGO_MANIFEST_DIR"),+ "/../macro_db_client/migrations/20261014153433_database_webhooks.down.sql"+));fn batch(database_id: DatabaseId, writes: Vec<Write>) -> Writes {Writes {@@ -183,6 +187,11 @@ async fn schema_cutover_discards_database_content_and_allows_a_fresh_start(pool:let store = PgCellStore::new(pool.clone(), PropertiesPgRepo::new(pool.clone()));store.create_storage().await.unwrap();let mut transaction = pool.begin().await.unwrap();+ // Roll back the newer foreign key dependency before the historical cutover.+ sqlx::raw_sql(WEBHOOKS_DOWN)+ .execute(&mut *transaction)+ .await+ .unwrap();// Down also resets populated app and core storage, without a preservation guard.sqlx::raw_sql(SPLIT_DOWN).execute(&mut *transaction)diff --git a/crates/databases_sql/src/row_source.rs b/crates/databases_sql/src/row_source.rsindex 9ed00b252f..1b06bd2321 100644--- a/crates/databases_sql/src/row_source.rs+++ b/crates/databases_sql/src/row_source.rs@@ -366,6 +366,7 @@ fn rows_filter(}EntityFilterAst {favorites_only: None,+ crm_association: None,calendar_event_filter: Some(Arc::new(Expr::val(CalendarEventLiteral::Id(Uuid::nil())))),document_filter: Some(Arc::new(Expr::val(DocumentLiteral::Id(Uuid::nil())))),project_filter: Some(Arc::new(Expr::val(ProjectLiteral::ProjectIdSelf(diff --git a/crates/frecency/src/outbound/postgres/dynamic.rs b/crates/frecency/src/outbound/postgres/dynamic.rsindex 795ce0ebe8..f047b1c8a4 100644--- a/crates/frecency/src/outbound/postgres/dynamic.rs+++ b/crates/frecency/src/outbound/postgres/dynamic.rs@@ -217,6 +217,13 @@ fn build_document_filter(ast: Option<&Expr<DocumentLiteral>>) -> String {filter_ast::ExprFrame::Literal(DocumentLiteral::EmailAttachmentParticipant(email)) => {email_attachment_participant_predicate(&email)}+ filter_ast::ExprFrame::Literal(DocumentLiteral::NameContains(name)) => format!(+ r#"entity_id IN (SELECT id FROM "Document" WHERE STRPOS(LOWER(name), {}) > 0 AND "deletedAt" IS NULL)"#,+ sql_string_literal(&name.to_lowercase())+ ),+ // Soup resolves CRM associations before querying and rejects them on+ // frecency sorts, so an unresolved one matches nothing.+ filter_ast::ExprFrame::Literal(DocumentLiteral::CrmAssociated(_)) => "FALSE".to_string(),});if formatting.is_empty() {String::new()diff --git a/crates/frecency/src/outbound/postgres/dynamic_tests.rs b/crates/frecency/src/outbound/postgres/dynamic_tests.rsindex 0de55a1111..603794bd67 100644--- a/crates/frecency/src/outbound/postgres/dynamic_tests.rs+++ b/crates/frecency/src/outbound/postgres/dynamic_tests.rs@@ -978,6 +978,7 @@ async fn test_dynamic_filter_document_date_created_at_gt(pool: PgPool) {.into();let filter = EntityFilterAst {favorites_only: None,+ crm_association: None,document_filter: Some(Arc::new(Expr::Literal(DocumentLiteral::CreatedAt(DateLiteral::GreaterThan(cutoff),)))),@@ -1079,6 +1080,7 @@ async fn test_dynamic_filter_document_date_created_at_lt(pool: PgPool) {.into();let filter = EntityFilterAst {favorites_only: None,+ crm_association: None,document_filter: Some(Arc::new(Expr::Literal(DocumentLiteral::CreatedAt(DateLiteral::LessThan(cutoff),)))),@@ -1176,6 +1178,7 @@ async fn test_dynamic_filter_document_date_updated_at_gt(pool: PgPool) {.into();let filter = EntityFilterAst {favorites_only: None,+ crm_association: None,document_filter: Some(Arc::new(Expr::Literal(DocumentLiteral::UpdatedAt(DateLiteral::GreaterThan(cutoff),)))),@@ -1278,6 +1281,7 @@ async fn test_dynamic_filter_document_date_updated_at_lt(pool: PgPool) {.into();let filter = EntityFilterAst {favorites_only: None,+ crm_association: None,document_filter: Some(Arc::new(Expr::Literal(DocumentLiteral::UpdatedAt(DateLiteral::LessThan(cutoff),)))),diff --git a/crates/graphql_soup/src/loaders.rs b/crates/graphql_soup/src/loaders.rsindex f0045f633c..35f6eb6289 100644--- a/crates/graphql_soup/src/loaders.rs+++ b/crates/graphql_soup/src/loaders.rs@@ -488,6 +488,7 @@ fn entity_filter_ast(entities: &[Entity<'static>]) -> Result<EntityFilterAst, Solet nil = Uuid::nil();Ok(EntityFilterAst {favorites_only: None,+ crm_association: None,calendar_event_filter: Some(literal_tree(calendar_events, CalendarEventLiteral::Id(nil))),document_filter: Some(literal_tree(documents, DocumentLiteral::Id(nil))),project_filter: Some(literal_tree(projects, ProjectLiteral::ProjectIdSelf(nil))),diff --git a/crates/graphql_soup_filter_input/src/lib.rs b/crates/graphql_soup_filter_input/src/lib.rsindex 7d19daab3e..c307ae3e76 100644--- a/crates/graphql_soup_filter_input/src/lib.rs+++ b/crates/graphql_soup_filter_input/src/lib.rs@@ -25,6 +25,7 @@ use item_filters::{call::CallLiteral,channel::{ChannelLiteral, ChannelThreadLiteral, ChannelTypeFilter},chat::{ChatLiteral, ChatRole},+ crm_association::CrmAssociation,crm_company::CrmCompanyLiteral,crm_contact::CrmContactLiteral,database_row::DatabaseRowLiteral,@@ -360,6 +361,9 @@ impl TryFrom<GraphqlPropertyEntityType> for PropertyEntityType {pub struct GraphqlEntityFilterAst {/// Restrict results to the authenticated viewer's favorites when true.favorites_only: Option<bool>,+ /// Restrict every entity type to items associated with this CRM record.+ /// Requires an expanded, timestamp-sorted query.+ crm_association: Option<GraphqlCrmAssociation>,/// The calendar event filter to apply.calendar_event_filter: Option<GraphqlCalendarEventExpr>,/// The document filter to apply.@@ -409,6 +413,10 @@ impl GraphqlEntityFilterAst {fn into_ast_unchecked(self) -> InputResult<EntityFilterAst> {Ok(EntityFilterAst {favorites_only: self.favorites_only,+ crm_association: self+ .crm_association+ .map(GraphqlCrmAssociation::into_ast)+ .transpose()?,calendar_event_filter: optional_tree(self.calendar_event_filter)?,document_filter: optional_tree(self.document_filter)?,project_filter: optional_tree(self.project_filter)?,@@ -682,6 +690,33 @@ enum GraphqlDocumentLiteral {Property(GraphqlFilterPropertiesLiteral),/// Uploaded from an email attachment sent by, or to, a matching address.EmailAttachmentParticipant(GraphqlEmailValue),+ /// Associated with a CRM record through its Companies or Contacts+ /// property or a reference to the record. Requires an expanded,+ /// timestamp-sorted query.+ CrmAssociated(GraphqlCrmAssociation),+ /// Case-insensitive substring of the document name.+ NameContains(String),+}++/// GraphQL input naming the CRM record an association filter restricts to.+#[cfg_attr(feature = "server", derive(async_graphql::OneofObject))]+#[derive(Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+enum GraphqlCrmAssociation {+ /// Items associated with the company or any of its contacts.+ Company(ID),+ /// Items associated with the contact.+ Contact(ID),+}++impl GraphqlCrmAssociation {+ /// Convert this value into the ast representation.+ fn into_ast(self) -> InputResult<CrmAssociation> {+ Ok(match self {+ Self::Company(id) => CrmAssociation::Company(parse_id(id, "company")?),+ Self::Contact(id) => CrmAssociation::Contact(parse_id(id, "contact")?),+ })+ }}impl IntoFilterExpr<DocumentLiteral> for GraphqlDocumentLiteral {@@ -714,6 +749,8 @@ impl IntoFilterExpr<DocumentLiteral> for GraphqlDocumentLiteral {Self::EmailAttachmentParticipant(value) => {DocumentLiteral::EmailAttachmentParticipant(value.into_ast()?)}+ Self::CrmAssociated(record) => DocumentLiteral::CrmAssociated(record.into_ast()?),+ Self::NameContains(name) => DocumentLiteral::NameContains(name),};Ok(Expr::val(literal))}diff --git a/crates/graphql_soup_filter_input/src/test.rs b/crates/graphql_soup_filter_input/src/test.rsindex 2b445732d2..6ef26f9c87 100644--- a/crates/graphql_soup_filter_input/src/test.rs+++ b/crates/graphql_soup_filter_input/src/test.rs@@ -283,6 +283,47 @@ fn crm_document_literals_materialize_for_browser_and_server() {));}+#[test]+fn crm_association_materializes_for_browser_and_server() {+ let company_id = "0198a1b2-c3d4-7e5f-8061-728394a5b700";+ let contact_id = "0198a1b2-c3d4-7e5f-8061-728394a5b701";+ let value = json!({+ "crmAssociation": {"company": company_id},+ "documentFilter": {"or": {+ "left": {"literal": {"crmAssociated": {"contact": contact_id}}},+ "right": {"literal": {"nameContains": "Renewal"}}+ }}+ });+ let ast = materialize_graphql_filter(value.clone()).unwrap();+ let input: GraphqlEntityFilterAst = serde_json::from_value(value).unwrap();+ assert_eq!(+ serde_json::to_value(&ast).unwrap(),+ serde_json::to_value(input.into_ast().unwrap()).unwrap()+ );++ assert_eq!(+ ast.crm_association,+ Some(CrmAssociation::Company(+ Uuid::parse_str(company_id).unwrap()+ ))+ );+ let Some(Expr::Or(left, right)) = ast.document_filter.as_deref() else {+ panic!("expected an OR of the association and the name literal")+ };+ assert!(matches!(+ left.as_ref(),+ Expr::Literal(DocumentLiteral::CrmAssociated(CrmAssociation::Contact(id)))+ if id.to_string() == contact_id+ ));+ assert!(matches!(+ right.as_ref(),+ Expr::Literal(DocumentLiteral::NameContains(name)) if name == "Renewal"+ ));+ assert!(+ materialize_graphql_filter(json!({"crmAssociation": {"company": "not-a-uuid"}})).is_err()+ );+}+#[test]fn contacts_are_opt_in_and_normalize_full_email_filters() {assert!(diff --git a/crates/item_filter_index/src/lib.rs b/crates/item_filter_index/src/lib.rsindex 2377732b51..c9ac409458 100644--- a/crates/item_filter_index/src/lib.rs+++ b/crates/item_filter_index/src/lib.rs@@ -294,6 +294,11 @@ fn check_soup_flat(if ast.favorites_only == Some(true) {return Eligibility::Unsupported(UnsupportedReason::Literal("favorites"));}+ // Association membership is resolved by the server from CRM records,+ // properties, and references that no local row carries.+ if ast.crm_association.is_some() {+ return Eligibility::Unsupported(UnsupportedReason::Literal("crm_association"));+ }if request.has_cursor {return Eligibility::Unsupported(UnsupportedReason::Cursor);}diff --git a/crates/item_filter_index/src/test.rs b/crates/item_filter_index/src/test.rsindex f77a301800..9957a3f803 100644--- a/crates/item_filter_index/src/test.rs+++ b/crates/item_filter_index/src/test.rs@@ -531,3 +531,27 @@ fn contact_queries_require_server_authorization_and_deduplication() {ast.crm_contact_filter = Some(Arc::new(Expr::val(CrmContactLiteral::Id(Uuid::nil()))));assert_eq!(check_soup_flat_v3(&ast, request()), Eligibility::Supported);}++#[test]+fn crm_associations_use_server_membership() {+ use item_filters::ast::crm_association::CrmAssociation;+ let record = CrmAssociation::Company(Uuid::from_u128(0xc0));+ let mut ast = excluded_deferred_partitions();+ ast.crm_association = Some(record);+ assert_eq!(+ check_soup_flat_v3(&ast, request()),+ Eligibility::Unsupported(UnsupportedReason::Literal("crm_association"))+ );++ for literal in [+ DocumentLiteral::CrmAssociated(record),+ DocumentLiteral::NameContains("renewal".into()),+ ] {+ let mut ast = excluded_deferred_partitions();+ ast.document_filter = Some(Arc::new(Expr::val(literal)));+ assert_eq!(+ check_soup_flat_v3(&ast, request()),+ Eligibility::Unsupported(UnsupportedReason::Literal("document"))+ );+ }+}diff --git a/crates/item_filters/src/ast.rs b/crates/item_filters/src/ast.rsindex 031b50427a..ab4b886eaa 100644--- a/crates/item_filters/src/ast.rs+++ b/crates/item_filters/src/ast.rs@@ -11,6 +11,7 @@ use crate::{call::CallLiteral,channel::{ChannelLiteral, ChannelThreadLiteral, ChannelTypeFilter},chat::{ChatLiteral, ChatRole},+ crm_association::{CrmAssociation, document_crm_associations},crm_company::CrmCompanyLiteral,crm_contact::CrmContactLiteral,database_row::DatabaseRowLiteral,@@ -39,6 +40,8 @@ pub mod call;pub mod channel;/// contains the ast literal value for chatpub mod chat;+/// CRM record association scope for associated-item queries.+pub mod crm_association;/// contains the ast literal value for crm companiespub mod crm_company;/// CRM contact filter literals. Contacts are opt-in.@@ -200,6 +203,10 @@ pub struct EntityFilterAst {/// Restrict to the authenticated viewer's favorites before pagination when true.#[serde(default, skip_serializing_if = "Option::is_none")]pub favorites_only: Option<bool>,+ /// Restrict every entity type to items associated with this CRM record+ /// before pagination. Soup authorizes and resolves the record first.+ #[serde(default, rename = "crma", skip_serializing_if = "Option::is_none")]+ pub crm_association: Option<CrmAssociation>,/// filters applied to canonical calendar events#[serde(default, rename = "calf")]#[cfg_attr(feature = "schema", schema(value_type = serde_json::Value))]@@ -285,6 +292,7 @@ impl EntityFilterAst {let email_tree = EmailFilters::expand_ast(entity_filter.email_filters)?.map(Arc::new);Ok(Some(EntityFilterAst {favorites_only: entity_filter.favorites_only,+ crm_association: None,calendar_event_filter: CalendarEventFilters::expand_ast(entity_filter.calendar_event_filters,)?@@ -345,11 +353,26 @@ impl EntityFilterAst {.is_some_and(crm_company_requests_admin)}+ /// Every distinct CRM record this filter restricts to, from the top-level+ /// scope and from document [`document::DocumentLiteral::CrmAssociated`]+ /// literals, in first-seen order.+ pub fn crm_associations(&self) -> Vec<CrmAssociation> {+ let mut records = Vec::new();+ if let Some(record) = self.crm_association {+ records.push(record);+ }+ if let Some(tree) = self.document_filter.as_deref() {+ document_crm_associations(tree, &mut records);+ }+ records+ }+/// mock function to create the an empty ast#[cfg(feature = "mock")]pub fn mock_empty() -> Self {Self {favorites_only: None,+ crm_association: None,calendar_event_filter: None,document_filter: None,project_filter: None,@@ -389,6 +412,7 @@ impl IsEmpty for EntityFilterAst {fn is_empty(&self) -> bool {let EntityFilterAst {favorites_only,+ crm_association,calendar_event_filter,document_filter,project_filter,@@ -407,6 +431,7 @@ impl IsEmpty for EntityFilterAst {properties_filter,} = self;favorites_only != &Some(true)+ && crm_association.is_none()&& calendar_event_filter.is_none()&& document_filter.is_none()&& project_filter.is_none()diff --git a/crates/item_filters/src/ast/crm_association.rs b/crates/item_filters/src/ast/crm_association.rsnew file mode 100644index 0000000000..99a350a5ee--- /dev/null+++ b/crates/item_filters/src/ast/crm_association.rs@@ -0,0 +1,44 @@+//! A CRM record whose associated items a query is restricted to.+//!+//! An item is associated with a company when its Companies property names+//! the company, its Contacts property names one of the company's contacts,+//! or it references the company or one of those contacts. An item is+//! associated with a contact when its Contacts property names the contact+//! or it references the contact. The Soup domain authorizes the record and+//! resolves that membership before any source query runs; renderers never+//! evaluate these values themselves.++use filter_ast::Expr;+use serde::{Deserialize, Serialize};+use uuid::Uuid;++use crate::ast::document::DocumentLiteral;++/// The CRM record an association filter names.+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]+#[cfg_attr(feature = "schema", derive(utoipa::ToSchema))]+#[serde(rename_all = "snake_case")]+pub enum CrmAssociation {+ /// Items associated with the company or with any of its contacts.+ Company(Uuid),+ /// Items associated with the contact.+ Contact(Uuid),+}++/// Every distinct CRM record a document tree names through+/// [`DocumentLiteral::CrmAssociated`], in first-seen order.+pub fn document_crm_associations(expr: &Expr<DocumentLiteral>, out: &mut Vec<CrmAssociation>) {+ match expr {+ Expr::Literal(DocumentLiteral::CrmAssociated(record)) => {+ if !out.contains(record) {+ out.push(*record);+ }+ }+ Expr::Literal(_) => {}+ Expr::And(a, b) | Expr::Or(a, b) => {+ document_crm_associations(a, out);+ document_crm_associations(b, out);+ }+ Expr::Not(a) => document_crm_associations(a, out),+ }+}diff --git a/crates/item_filters/src/ast/document.rs b/crates/item_filters/src/ast/document.rsindex c0e03fdbcd..4852c7e3e3 100644--- a/crates/item_filters/src/ast/document.rs+++ b/crates/item_filters/src/ast/document.rs@@ -1,6 +1,9 @@use crate::{DocumentFilters,- ast::{ExpandErr, date::DateLiteral, email::Email, properties::PropertiesLiteral},+ ast::{+ ExpandErr, crm_association::CrmAssociation, date::DateLiteral, email::Email,+ properties::PropertiesLiteral,+ },};use document_sub_type::DocumentSubType;use either::Either;@@ -65,6 +68,16 @@ pub enum DocumentLiteral {/// sent by, or addressed to, a matching email address or domain#[serde(rename = "eap")]EmailAttachmentParticipant(Email),+ /// the document or task is associated with a CRM record through its+ /// Companies or Contacts property or a reference to the record. Soup+ /// resolves the record before querying; it composes with the other+ /// document literals the way [`DocumentLiteral::Property`] does. Only+ /// expanded, timestamp-sorted queries accept it.+ #[serde(rename = "crm")]+ CrmAssociated(CrmAssociation),+ /// case-insensitive substring of the document name+ #[serde(rename = "nc")]+ NameContains(String),}fn prefix(s: &str) -> IResult<&str, &str> {diff --git a/crates/item_filters/src/ast/tests.rs b/crates/item_filters/src/ast/tests.rsindex f5002d519d..37e3f1f61d 100644--- a/crates/item_filters/src/ast/tests.rs+++ b/crates/item_filters/src/ast/tests.rs@@ -1749,3 +1749,51 @@ fn crm_document_literals_round_trip_through_the_rest_ast() {);assert_eq!(serde_json::to_value(&expr).unwrap(), tree);}++#[test]+fn crm_association_round_trips_through_the_rest_ast() {+ let company = Uuid::from_u128(0x0198a1b2_c3d4_7e5f_8061_728394a5b700);+ let contact = Uuid::from_u128(0x0198a1b2_c3d4_7e5f_8061_728394a5b701);+ let body = json!({+ "crma": { "company": company },+ "df": {+ "&": [+ { "!": { "l": { "dst": "task" } } },+ { "|": [+ { "l": { "crm": { "contact": contact } } },+ { "l": { "nc": "Renewal" } }+ ] }+ ]+ }+ });+ let ast: EntityFilterAst = serde_json::from_value(body.clone()).unwrap();++ assert_eq!(ast.crm_association, Some(CrmAssociation::Company(company)));+ assert_eq!(+ ast.crm_associations(),+ vec![+ CrmAssociation::Company(company),+ CrmAssociation::Contact(contact)+ ]+ );+ assert!(!ast.is_empty());+ let value = serde_json::to_value(&ast).unwrap();+ assert_eq!(value["crma"], body["crma"]);+ assert_eq!(value["df"], body["df"]);+}++#[test]+fn crm_associations_deduplicate_repeated_records() {+ let company = CrmAssociation::Company(Uuid::from_u128(1));+ let ast = EntityFilterAst {+ crm_association: Some(company),+ document_filter: Some(Arc::new(Expr::or(+ Expr::val(document::DocumentLiteral::CrmAssociated(company)),+ Expr::is_not(Expr::val(document::DocumentLiteral::CrmAssociated(company))),+ ))),+ ..EntityFilterAst::default()+ };++ assert_eq!(ast.crm_associations(), vec![company]);+ assert!(EntityFilterAst::default().crm_associations().is_empty());+}diff --git a/crates/macro_db_client/migrations/20261013225158_crm_companies_value_gin.down.sql b/crates/macro_db_client/migrations/20261013225158_crm_companies_value_gin.down.sqlnew file mode 100644index 0000000000..eb98f23df7--- /dev/null+++ b/crates/macro_db_client/migrations/20261013225158_crm_companies_value_gin.down.sql@@ -0,0 +1,2 @@+-- no-transaction+DROP INDEX CONCURRENTLY IF EXISTS idx_ep_companies_value_gin;diff --git a/crates/macro_db_client/migrations/20261013225158_crm_companies_value_gin.up.sql b/crates/macro_db_client/migrations/20261013225158_crm_companies_value_gin.up.sqlnew file mode 100644index 0000000000..57c47dc5b5--- /dev/null+++ b/crates/macro_db_client/migrations/20261013225158_crm_companies_value_gin.up.sql@@ -0,0 +1,13 @@+-- no-transaction+-- CRM associated-item queries find every entity whose Companies property+-- references a company with `values->'value' @> [{"entity_id": ...}]`. Like+-- the assignee, status, and project indexes, this partial expression index+-- lets that containment jump to matching rows instead of scanning every+-- Companies row. Must stay a single statement: sqlx sends no-transaction+-- migrations as one batch, and CONCURRENTLY cannot run inside a transaction.+-- IF NOT EXISTS does not repair an INVALID index from an interrupted build;+-- drop it concurrently before retrying.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_ep_companies_value_gin+ON entity_properties+USING gin ((values->'value') jsonb_path_ops)+WHERE property_definition_id = '00000001-0000-0000-0000-00000000000c';diff --git a/crates/macro_db_client/migrations/20261013225205_crm_contacts_value_gin.down.sql b/crates/macro_db_client/migrations/20261013225205_crm_contacts_value_gin.down.sqlnew file mode 100644index 0000000000..705ea0f3f5--- /dev/null+++ b/crates/macro_db_client/migrations/20261013225205_crm_contacts_value_gin.down.sql@@ -0,0 +1,2 @@+-- no-transaction+DROP INDEX CONCURRENTLY IF EXISTS idx_ep_contacts_value_gin;diff --git a/crates/macro_db_client/migrations/20261013225205_crm_contacts_value_gin.up.sql b/crates/macro_db_client/migrations/20261013225205_crm_contacts_value_gin.up.sqlnew file mode 100644index 0000000000..ecde593fae--- /dev/null+++ b/crates/macro_db_client/migrations/20261013225205_crm_contacts_value_gin.up.sql@@ -0,0 +1,10 @@+-- no-transaction+-- The Contacts counterpart of idx_ep_companies_value_gin: CRM associated-item+-- queries match entities whose Contacts property references a contact. Must+-- stay a single statement (see the Companies migration). IF NOT EXISTS does+-- not repair an INVALID index from an interrupted build; drop it concurrently+-- before retrying.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_ep_contacts_value_gin+ON entity_properties+USING gin ((values->'value') jsonb_path_ops)+WHERE property_definition_id = '00000001-0000-0000-0000-000000000013';diff --git a/crates/skills/src/outbound/soup_skill_lister.rs b/crates/skills/src/outbound/soup_skill_lister.rsindex d3007efc77..0d9d944642 100644--- a/crates/skills/src/outbound/soup_skill_lister.rs+++ b/crates/skills/src/outbound/soup_skill_lister.rs@@ -51,6 +51,7 @@ impl<S> Clone for SoupSkillLister<S> {fn skill_only_filter() -> EntityFilterAst {EntityFilterAst {favorites_only: None,+ crm_association: None,document_filter: Some(Arc::new(Expr::val(DocumentLiteral::SubType(DocumentSubType::Skill,)))),diff --git a/crates/soup/src/domain/models.rs b/crates/soup/src/domain/models.rsindex f5efdec328..b26fed6336 100644--- a/crates/soup/src/domain/models.rs+++ b/crates/soup/src/domain/models.rs@@ -344,7 +344,7 @@ pub struct SoupRequest<T> {pub email_preview_view: PreviewView,/// Every inbox the caller can read (own + delegated via macro_user_links)./// Empty when the caller has no inboxes — `build_email_request` returns- /// `None` so the email branch is skipped.+ /// `None` so the email branch is skipped, unless the request is CRM-scoped.pub link_ids: Vec<Uuid>,}@@ -424,7 +424,9 @@ impl SoupRequest<Option<EntityFilterAst>> {let entity_ast = self.entity_ast();let crm_scope = entity_ast.and_then(|a| a.email_filter.crm_scope.clone());- if self.link_ids.is_empty() {+ // A CRM scope reads teammates' threads, which email authorizes against+ // the scope, so a viewer without a mailbox of their own still sees them.+ if self.link_ids.is_empty() && crm_scope.is_none() {return None;}// CRM-scoped requests must still reach email's authorization precheck,@@ -1093,6 +1095,15 @@ fn map_properties_to_call(expr: &Expr<PropertiesLiteral>) -> Expr<CallLiteral> {}}+/// An entity whose Companies or Contacts property names a CRM record.+#[derive(Debug, Clone, PartialEq, Eq)]+pub struct CrmPropertyEdge {+ /// The entity type the property row is stored under.+ pub entity_type: models_properties::EntityType,+ /// The entity id the property row is stored under.+ pub entity_id: String,+}+/// Parameters for fetching CRM companies to fold into the soup feed.#[derive(Debug)]pub struct GetCrmCompaniesRequest {@@ -1305,6 +1316,9 @@ pub enum SoupErr {/// role is below admin/owner.#[error("Querying hidden CRM companies requires admin/owner team role")]CrmAdminRequired,+ /// The filter is restricted to a CRM record the caller cannot see.+ #[error("CRM record not found")]+ CrmRecordNotFound,/// GitHub pull request listing failed.#[error(transparent)]GithubPullRequestErr(#[from] GithubPullRequestError),diff --git a/crates/soup/src/domain/models/test/exclusions.rs b/crates/soup/src/domain/models/test/exclusions.rsindex 23fe480942..6e32e23f21 100644--- a/crates/soup/src/domain/models/test/exclusions.rs+++ b/crates/soup/src/domain/models/test/exclusions.rs@@ -170,6 +170,27 @@ fn crm_scoped_email_exclusions_preserve_authorization_prechecks() {}}+#[test]+fn crm_scoped_email_reaches_viewers_without_a_mailbox() {+ let mut req = request(Some(EntityFilterAst::default()), false);+ req.link_ids.clear();+ assert!(req.build_email_request(None).is_none());++ let mut filter = EntityFilterAst::default();+ filter.email_filter.crm_scope = Some(item_filters::ast::CrmScope::Domains(vec![+ "example.com".to_string(),+ ]));+ for follow_up in [false, true] {+ let mut req = request(Some(filter.clone()), follow_up);+ req.link_ids.clear();+ let email = req+ .build_email_request(None)+ .expect("team-contributed CRM email does not need the viewer's mailbox");+ assert!(email.link_ids.is_empty());+ assert!(email.crm_scope.is_some());+ }+}+#[test]fn exclusion_only_skips_the_targeted_entity_type() {for excluded_leg in LEGS {diff --git a/crates/soup/src/domain/ports.rs b/crates/soup/src/domain/ports.rsindex 5d72827290..2847634232 100644--- a/crates/soup/src/domain/ports.rs+++ b/crates/soup/src/domain/ports.rs@@ -1,10 +1,10 @@use std::sync::Arc;use crate::domain::models::{- AdvancedSortParams, EnrichedSoupItem, GroupedSortRequest, IntoSoupReqAst, NotifiedEntity,- NotifiedSoupRequest, SimpleSortRequest, SoupErr, SoupProjectionHydration, SoupPropertiesField,- SoupRequest, TouchedEntity, TouchedSoupRequest, WorkFeedCandidate, WorkFeedCandidateRequest,- WorkFeedSoupPage, WorkFeedSoupRequest, grouping::ItemGroupingInfo,+ AdvancedSortParams, CrmPropertyEdge, EnrichedSoupItem, GroupedSortRequest, IntoSoupReqAst,+ NotifiedEntity, NotifiedSoupRequest, SimpleSortRequest, SoupErr, SoupProjectionHydration,+ SoupPropertiesField, SoupRequest, TouchedEntity, TouchedSoupRequest, WorkFeedCandidate,+ WorkFeedCandidateRequest, WorkFeedSoupPage, WorkFeedSoupRequest, grouping::ItemGroupingInfo,};use entity_access::domain::models::{EntityAccessReceipt, MemberTeamRole};use macro_user_id::user_id::MacroUserIdStr;@@ -97,6 +97,15 @@ pub trait SoupRepo: Send + Sync + 'static {req: TouchedSoupRequest<'a>,) -> impl Future<Output = Result<Vec<TouchedEntity>, Self::Err>> + Send;+ /// Every entity whose Companies property names one of `company_ids` or+ /// whose Contacts property names one of `contact_ids`. Not authorized:+ /// each entity reaches the caller only through its own source query.+ fn crm_property_edges<'a>(+ &self,+ company_ids: &'a [uuid::Uuid],+ contact_ids: &'a [uuid::Uuid],+ ) -> impl Future<Output = Result<Vec<CrmPropertyEdge>, Self::Err>> + Send;+/// Fetch one page of notified-at candidates: entities the user holds a/// live notification for, newest notification first, already gated on/// existence, deletion and access, and on the request's entity filtersdiff --git a/crates/soup/src/domain/service.rs b/crates/soup/src/domain/service.rsindex 1fecf17a1c..1872a36297 100644--- a/crates/soup/src/domain/service.rs+++ b/crates/soup/src/domain/service.rs@@ -67,6 +67,7 @@ use std::sync::Arc;use uuid::Uuid;mod agent_metadata;+mod crm_association;mod favorites;#[cfg(test)]@@ -878,6 +879,13 @@ whereif !calendar_filter_supported_by_notified(req.filter.calendar_event_filter.as_deref()) {return Err(SoupErr::NotifiedUnsupportedFilter("calendar_event"));}+ // CRM associations resolve to complete entity sets only for timestamp+ // sorts; the candidate query would otherwise ignore the scope.+ if !req.filter.crm_associations().is_empty() {+ return Err(SoupErr::AstErr(item_filters::ast::ExpandErr::ApiAst(+ "CRM associations require a timestamp sort".into(),+ )));+ }let limit = req.limit.clamp(1, 500);let legs_request = SoupRequest {soup_type: SoupType::Expanded,@@ -1660,6 +1668,39 @@ where.cursor.map(|ast| ast.map(|ast| favorites::apply(ast, entities)));}+ // CRM associations resolve to complete entity sets, so they only+ // compose with the timestamp-sorted sources that take those sets.+ let crm_record = req.entity_ast().and_then(|ast| ast.crm_association);+ // Read the filter of every query kind: `entity_ast` hides frecency+ // filters, which must be rejected rather than silently unscoped.+ let crm_associations = if req+ .cursor+ .filter()+ .as_ref()+ .is_some_and(|ast| !ast.crm_associations().is_empty())+ {+ if !matches!(&req.cursor, SoupQuery::Simple(_)) {+ return Err(SoupErr::AstErr(item_filters::ast::ExpandErr::ApiAst(+ "CRM associations require a timestamp sort".into(),+ )));+ }+ // Unexpanded candidate queries cannot apply filter trees, so the+ // resolved entity sets would have nowhere to go.+ if matches!(req.soup_type, SoupType::UnExpanded) {+ return Err(SoupErr::AstErr(item_filters::ast::ExpandErr::ApiAst(+ "CRM associations require an expanded query".into(),+ )));+ }+ let resolved = self+ .resolve_crm_associations(&req.user, team_receipt.as_ref(), req.entity_ast())+ .await?;+ if let Some(resolved) = &resolved {+ req.cursor = req.cursor.map(|ast| ast.map(|ast| resolved.apply(ast)));+ }+ resolved+ } else {+ None+ };let limit = req.limit.clamp(1, 500);// CRM-scoped visibility (team-wide email scope or hidden CRM@@ -1696,6 +1737,15 @@ where.then_some(request)});}+ if let Some(entities) = crm_record.and_then(|record| {+ crm_associations+ .as_ref()+ .and_then(|resolved| resolved.get(&record))+ }) {+ crm_company_request = crm_company_request.and_then(|mut request| {+ crm_association::intersect_crm_companies(&mut request, entities).then_some(request)+ });+ }let sort_direction = req.sort_direction;let output: Result<SoupOutput<R, SoupCandidate>, SoupErr> = match req.cursor {@@ -1988,6 +2038,14 @@ where.cursor.map_filter(|ast| favorites::apply(ast, &entities));}+ // Grouped queries carry no team receipt, so associations resolve+ // under the viewer's own CRM teams.+ if let Some(resolved) = self+ .resolve_crm_associations(&user_id, None, Some(req.cursor.filter()))+ .await?+ {+ req.cursor = req.cursor.map_filter(|ast| resolved.apply(ast));+ }let items = self.handle_grouped_soup_request(req).await?;self.populate_grouped_items(user_id, items).await}diff --git a/crates/soup/src/domain/service/crm_association.rs b/crates/soup/src/domain/service/crm_association.rsnew file mode 100644index 0000000000..96a9dc8697--- /dev/null+++ b/crates/soup/src/domain/service/crm_association.rs@@ -0,0 +1,395 @@+//! Restrict Soup to the items associated with a CRM record.+//!+//! An item is associated with a company when its Companies property names+//! the company, its Contacts property names one of the company's contacts, or+//! it references the company or one of those contacts. An item is associated+//! with a contact when its Contacts property names the contact or it+//! references the contact.+//!+//! The CRM service authorizes the record and expands a company to the+//! contacts the viewer may see. The property and reference edges of those+//! records are then read as complete sets and every source query is+//! constrained to the matching entity ids, before its own access checks,+//! filters, sort, limit, grouping, and cursor apply. Nothing here grants+//! access: an edge only narrows a source query that already enforces the+//! viewer's access to each item.+use super::*;+use crate::domain::models::CrmPropertyEdge;+use channels::domain::models::{MessageParent, ReferenceSource, ReferenceTarget};+use crm::domain::{+ association::{CrmAssociation, CrmRecordAssociation},+ auth::CrmTeamReceipt,+ model::CrmError,+};+use item_filters::ast::{+ agent_session::AgentSessionLiteral, calendar_event::CalendarEventLiteral, call::CallLiteral,+ chat::ChatLiteral, crm_contact::CrmContactLiteral, database_row::DatabaseRowLiteral,+ document::DocumentLiteral, initiative::InitiativeLiteral, project::ProjectLiteral,+};+use models_properties::EntityType as PropertyEntityType;+use std::collections::BTreeSet;++#[cfg(test)]+mod test;++/// Upper bound on distinct CRM records one request may restrict to; each+/// costs an authorization read and an edge read.+const MAX_CRM_ASSOCIATIONS: usize = 8;++/// The entities associated with one CRM record, per Soup source.+#[derive(Debug, Default, Clone, PartialEq, Eq)]+pub(super) struct AssociatedEntities {+ pub documents: BTreeSet<Uuid>,+ pub chats: BTreeSet<Uuid>,+ pub projects: BTreeSet<Uuid>,+ pub initiatives: BTreeSet<Uuid>,+ pub database_rows: BTreeSet<Uuid>,+ pub calendar_events: BTreeSet<Uuid>,+ pub email_threads: BTreeSet<Uuid>,+ pub calls: BTreeSet<Uuid>,+ pub channels: BTreeSet<Uuid>,+ /// Top-level channel messages: a referencing message, or the root of+ /// the thread a referencing reply belongs to.+ pub channel_threads: BTreeSet<Uuid>,+ pub crm_companies: BTreeSet<Uuid>,+ pub crm_contacts: BTreeSet<Uuid>,+}++impl AssociatedEntities {+ /// Group the property and reference edges of `scope` by source.+ pub(super) fn from_edges(+ record: CrmAssociation,+ property_edges: Vec<CrmPropertyEdge>,+ reference_sources: Vec<ReferenceSource>,+ ) -> Self {+ let mut entities = Self::default();+ for edge in property_edges {+ let Ok(id) = Uuid::parse_str(&edge.entity_id) else {+ tracing::warn!(entity_type = ?edge.entity_type, "associated entity id is not a uuid; skipping");+ continue;+ };+ let set = match edge.entity_type {+ PropertyEntityType::Document | PropertyEntityType::Task => &mut entities.documents,+ PropertyEntityType::Chat => &mut entities.chats,+ PropertyEntityType::Project => &mut entities.projects,+ PropertyEntityType::Initiative => &mut entities.initiatives,+ PropertyEntityType::DatabaseRow => &mut entities.database_rows,+ PropertyEntityType::CalendarEvent => &mut entities.calendar_events,+ PropertyEntityType::Thread => &mut entities.email_threads,+ PropertyEntityType::CallRecord => &mut entities.calls,+ PropertyEntityType::Channel => &mut entities.channels,+ // A CRM record's own Companies or Contacts property can name+ // another record, which the CRM sources list like any item.+ PropertyEntityType::Company => &mut entities.crm_companies,+ PropertyEntityType::Contact => &mut entities.crm_contacts,+ // Users are not a Soup source.+ PropertyEntityType::User => continue,+ };+ set.insert(id);+ }+ for source in reference_sources {+ match source {+ ReferenceSource::Document(id) => match Uuid::parse_str(&id) {+ Ok(id) => {+ entities.documents.insert(id);+ }+ Err(_) => tracing::warn!("referencing document id is not a uuid; skipping"),+ },+ ReferenceSource::Message(message) => {+ match message.parent {+ MessageParent::Channel(_) => {+ entities.channel_threads.insert(message.root_id());+ }+ // Discussion messages make their parent the+ // associated item; they are never channel rows.+ MessageParent::Document(id) => match Uuid::parse_str(&id) {+ Ok(id) => {+ entities.documents.insert(id);+ }+ Err(_) => tracing::warn!(+ "discussion parent document id is not a uuid; skipping"+ ),+ },+ MessageParent::Initiative(id) => {+ entities.initiatives.insert(id);+ }+ MessageParent::Call(id) => {+ entities.calls.insert(id);+ }+ MessageParent::CrmCompany(id) => {+ entities.crm_companies.insert(id);+ }+ MessageParent::CrmContact(id) => {+ entities.crm_contacts.insert(id);+ }+ }+ }+ }+ }+ // A record's own discussion does not make it associated with itself.+ match record {+ CrmAssociation::Company(id) => entities.crm_companies.remove(&id),+ CrmAssociation::Contact(id) => entities.crm_contacts.remove(&id),+ };+ entities+ }+}++/// The reference targets a resolved association matches.+fn reference_targets(association: &CrmRecordAssociation) -> Vec<ReferenceTarget> {+ let target = |entity_type: &str, id: &Uuid| ReferenceTarget {+ entity_type: entity_type.to_owned(),+ entity_id: id.to_string(),+ };+ association+ .company_ids+ .iter()+ .map(|id| target("crm_company", id))+ .chain(+ association+ .contact_ids+ .iter()+ .map(|id| target("crm_contact", id)),+ )+ .collect()+}++/// Every CRM association a request names, resolved to its entities.+#[derive(Debug, Default)]+pub(super) struct ResolvedAssociations(HashMap<CrmAssociation, AssociatedEntities>);++impl ResolvedAssociations {+ /// The entities of a record resolved for this request.+ pub(super) fn get(&self, record: &CrmAssociation) -> Option<&AssociatedEntities> {+ self.0.get(record)+ }++ /// Restrict `ast` to the resolved associations: every source to the+ /// top-level record's entities, and each document association literal+ /// to its record's documents. The top-level scope is cleared so no+ /// renderer sees it.+ pub(super) fn apply(&self, mut ast: EntityFilterAst) -> EntityFilterAst {+ if let Some(tree) = ast.document_filter.take() {+ ast.document_filter = Some(Arc::new(replace_document_associations(&tree, self)));+ }+ let Some(record) = ast.crm_association.take() else {+ return ast;+ };+ let Some(entities) = self.get(&record) else {+ return ast;+ };+ constrain(+ &mut ast.document_filter,+ &entities.documents,+ DocumentLiteral::Id,+ );+ constrain(&mut ast.chat_filter, &entities.chats, ChatLiteral::ChatId);+ constrain(+ &mut ast.project_filter,+ &entities.projects,+ ProjectLiteral::ProjectIdSelf,+ );+ constrain(+ &mut ast.email_filter.tree,+ &entities.email_threads,+ EmailLiteral::ThreadId,+ );+ constrain(+ &mut ast.channel_filter,+ &entities.channels,+ ChannelLiteral::ChannelId,+ );+ constrain(+ &mut ast.channel_thread_filter,+ &entities.channel_threads,+ ChannelThreadLiteral::ThreadId,+ );+ constrain(&mut ast.call_filter, &entities.calls, CallLiteral::CallId);+ constrain(+ &mut ast.calendar_event_filter,+ &entities.calendar_events,+ CalendarEventLiteral::Id,+ );+ // Foreign entities and agent sessions carry no CRM association.+ constrain(+ &mut ast.foreign_entity_filter,+ &BTreeSet::new(),+ ForeignEntityLiteral::Id,+ );+ // Agent sessions, initiatives, rows, and contacts are opt-in:+ // constrain them only when requested so the association never opts+ // a query into them.+ if ast.agent_session_filter.is_some() {+ constrain(+ &mut ast.agent_session_filter,+ &BTreeSet::new(),+ AgentSessionLiteral::Id,+ );+ }+ if item_filters::ast::initiative::initiatives_requested(ast.initiative_filter.as_deref()) {+ constrain(+ &mut ast.initiative_filter,+ &entities.initiatives,+ InitiativeLiteral::Id,+ );+ }+ if item_filters::ast::database_row::database_rows_requested(+ ast.database_row_filter.as_deref(),+ ) {+ constrain(+ &mut ast.database_row_filter,+ &entities.database_rows,+ DatabaseRowLiteral::Id,+ );+ }+ if ast.crm_contact_filter.is_some() {+ constrain(+ &mut ast.crm_contact_filter,+ &entities.crm_contacts,+ CrmContactLiteral::Id,+ );+ }+ // CRM companies take an id list, intersected where the request is+ // built (see `intersect_crm_companies`).+ ast+ }+}++/// AND `tree` with membership in `ids`; an empty set matches nothing.+fn constrain<T: Clone>(+ tree: &mut Option<Arc<Expr<T>>>,+ ids: &BTreeSet<Uuid>,+ literal: impl Fn(Uuid) -> T,+) {+ *tree = Some(with_id_tree(id_tree(ids, literal), tree.as_ref()));+}++/// A balanced OR over `ids`, or a nil id when there are none.+fn id_tree<T>(ids: &BTreeSet<Uuid>, literal: impl Fn(Uuid) -> T) -> Arc<Expr<T>> {+ balanced_or_tree(ids.iter().map(|id| Expr::val(literal(*id))).collect())+ .unwrap_or_else(|| Arc::new(Expr::val(literal(Uuid::nil()))))+}++fn replace_document_associations(+ expr: &Expr<DocumentLiteral>,+ resolved: &ResolvedAssociations,+) -> Expr<DocumentLiteral> {+ match expr {+ Expr::Literal(DocumentLiteral::CrmAssociated(record)) => {+ let empty = BTreeSet::new();+ let documents = resolved+ .get(record)+ .map_or(&empty, |entities| &entities.documents);+ Arc::unwrap_or_clone(id_tree(documents, DocumentLiteral::Id))+ }+ Expr::Literal(literal) => Expr::val(literal.clone()),+ Expr::And(a, b) => Expr::and(+ replace_document_associations(a, resolved),+ replace_document_associations(b, resolved),+ ),+ Expr::Or(a, b) => Expr::or(+ replace_document_associations(a, resolved),+ replace_document_associations(b, resolved),+ ),+ Expr::Not(a) => Expr::is_not(replace_document_associations(a, resolved)),+ }+}++/// Restrict a CRM company request to the companies associated with the+/// top-level record. `false` when none remain and the source is skipped.+pub(super) fn intersect_crm_companies(+ request: &mut GetCrmCompaniesRequest,+ entities: &AssociatedEntities,+) -> bool {+ super::favorites::intersect(+ &mut request.company_ids,+ entities.crm_companies.iter().copied().collect(),+ )+}++fn crm_error(error: CrmError) -> SoupErr {+ match error {+ CrmError::CompanyNotFoundForTeam | CrmError::ContactNotFoundForTeam => {+ SoupErr::CrmRecordNotFound+ }+ error => {+ tracing::error!(error = ?error, "failed to resolve a CRM association");+ SoupErr::CrmErr+ }+ }+}++impl<T, U, V, C, K, Crm, F> SoupImpl<T, U, V, C, K, Crm, F>+where+ T: SoupRepo,+ anyhow::Error: From<T::Err>,+ U: FrecencyQueryService,+ V: EmailPreviewServiceReadOnly,+ C: ChannelListService,+ K: CallRecordQueryService,+ Crm: CrmService,+ F: GithubPullRequestListing,+{+ /// Authorize and resolve every CRM record `ast` restricts to.+ pub(super) async fn resolve_crm_associations(+ &self,+ user: &MacroUserIdStr<'_>,+ team_receipt: Option<&EntityAccessReceipt<MemberTeamRole>>,+ ast: Option<&EntityFilterAst>,+ ) -> Result<Option<ResolvedAssociations>, SoupErr> {+ let records = ast+ .map(EntityFilterAst::crm_associations)+ .unwrap_or_default();+ if records.is_empty() {+ return Ok(None);+ }+ if records.len() > MAX_CRM_ASSOCIATIONS {+ return Err(SoupErr::AstErr(item_filters::ast::ExpandErr::ApiAst(+ format!("at most {MAX_CRM_ASSOCIATIONS} CRM associations per query"),+ )));+ }+ let access = team_receipt+ .cloned()+ .map(CrmTeamReceipt::from_team_receipt)+ .transpose()+ .map_err(crm_error)?;+ let mut resolved = HashMap::with_capacity(records.len());+ for record in records {+ let association = self+ .crm_service+ .resolve_association(user.as_ref(), access.as_ref(), record)+ .await+ .map_err(crm_error)?;+ let targets = reference_targets(&association);+ let (property_edges, reference_sources) = tokio::join!(+ async {+ self.soup_storage+ .crm_property_edges(&association.company_ids, &association.contact_ids)+ .await+ .map_err(anyhow::Error::from)+ .map_err(SoupErr::from)+ },+ async {+ self.comms_service+ .get_reference_sources(&targets)+ .await+ .inspect_err(+ |error| tracing::error!(error = ?error, "failed to read CRM references"),+ )+ .map_err(|_| SoupErr::CommsErr)+ },+ );+ let entities =+ AssociatedEntities::from_edges(record, property_edges?, reference_sources?);+ tracing::debug!(+ contacts = association.contact_ids.len(),+ documents = entities.documents.len(),+ channel_threads = entities.channel_threads.len(),+ calls = entities.calls.len(),+ "resolved CRM association"+ );+ resolved.insert(record, entities);+ }+ Ok(Some(ResolvedAssociations(resolved)))+ }+}diff --git a/crates/soup/src/domain/service/crm_association/test.rs b/crates/soup/src/domain/service/crm_association/test.rsnew file mode 100644index 0000000000..73f45b31fa--- /dev/null+++ b/crates/soup/src/domain/service/crm_association/test.rs@@ -0,0 +1,267 @@+use super::*;+use channels::domain::models::ReferencingMessage;+use cool_asserts::assert_matches;++const COMPANY: Uuid = Uuid::from_u128(0xc0);+const CONTACT: Uuid = Uuid::from_u128(0xc1);+const CHANNEL: Uuid = Uuid::from_u128(0xc4a);++fn id(value: u128) -> Uuid {+ Uuid::from_u128(value)+}++fn edge(entity_type: PropertyEntityType, value: u128) -> CrmPropertyEdge {+ CrmPropertyEdge {+ entity_type,+ entity_id: id(value).to_string(),+ }+}++fn message(message_id: u128, thread_id: Option<u128>, parent: MessageParent) -> ReferenceSource {+ ReferenceSource::Message(ReferencingMessage {+ message_id: id(message_id),+ thread_id: thread_id.map(id),+ parent,+ })+}++fn ids(values: &[u128]) -> BTreeSet<Uuid> {+ values.iter().copied().map(id).collect()+}++#[test]+fn edges_group_by_source_and_deduplicate() {+ let entities = AssociatedEntities::from_edges(+ CrmAssociation::Company(COMPANY),+ vec![+ edge(PropertyEntityType::Task, 1),+ edge(PropertyEntityType::Document, 2),+ edge(PropertyEntityType::CallRecord, 3),+ edge(PropertyEntityType::Thread, 4),+ edge(PropertyEntityType::Channel, 5),+ edge(PropertyEntityType::Chat, 6),+ edge(PropertyEntityType::Project, 7),+ edge(PropertyEntityType::CalendarEvent, 8),+ edge(PropertyEntityType::Initiative, 9),+ edge(PropertyEntityType::DatabaseRow, 10),+ // CRM records' own properties: one company also references it+ // from its discussion, and the record naming itself is dropped.+ edge(PropertyEntityType::Company, 11),+ edge(PropertyEntityType::Company, 17),+ edge(PropertyEntityType::Company, 0xc0),+ edge(PropertyEntityType::Contact, 18),+ edge(PropertyEntityType::User, 19),+ CrmPropertyEdge {+ entity_type: PropertyEntityType::Document,+ entity_id: "not-a-uuid".into(),+ },+ ],+ vec![+ // Mentioned by a property-linked task too: still one document.+ ReferenceSource::Document(id(1).to_string()),+ ReferenceSource::Document(id(12).to_string()),+ // A top-level message is its own row; a reply surfaces its root.+ message(20, None, MessageParent::Channel(CHANNEL)),+ message(21, Some(20), MessageParent::Channel(CHANNEL)),+ message(22, Some(23), MessageParent::Channel(CHANNEL)),+ // Discussions make their parent the associated item.+ message(30, None, MessageParent::Document(id(13).to_string())),+ message(31, None, MessageParent::Initiative(id(14))),+ message(32, None, MessageParent::Call(id(15))),+ message(33, None, MessageParent::CrmContact(id(16))),+ message(34, None, MessageParent::CrmCompany(id(17))),+ // The record's own discussion is not an association.+ message(35, None, MessageParent::CrmCompany(COMPANY)),+ ],+ );+ assert_eq!(+ entities,+ AssociatedEntities {+ documents: ids(&[1, 2, 12, 13]),+ chats: ids(&[6]),+ projects: ids(&[7]),+ initiatives: ids(&[9, 14]),+ database_rows: ids(&[10]),+ calendar_events: ids(&[8]),+ email_threads: ids(&[4]),+ calls: ids(&[3, 15]),+ channels: ids(&[5]),+ channel_threads: ids(&[20, 23]),+ crm_companies: ids(&[11, 17]),+ crm_contacts: ids(&[16, 18]),+ }+ );++ let contact = AssociatedEntities::from_edges(+ CrmAssociation::Contact(CONTACT),+ vec![edge(PropertyEntityType::Contact, 0xc1)],+ vec![message(40, None, MessageParent::CrmContact(CONTACT))],+ );+ assert!(contact.crm_contacts.is_empty());+}++fn resolved(entities: AssociatedEntities) -> ResolvedAssociations {+ ResolvedAssociations(HashMap::from([(+ CrmAssociation::Company(COMPANY),+ entities,+ )]))+}++fn id_set<T: std::fmt::Debug>(+ expr: &Expr<T>,+ literal_id: impl Fn(&T) -> Option<Uuid> + Copy,+) -> BTreeSet<Uuid> {+ match expr {+ Expr::Literal(literal) => literal_id(literal).into_iter().collect(),+ Expr::Or(a, b) => {+ let mut ids = id_set(a, literal_id);+ ids.extend(id_set(b, literal_id));+ ids+ }+ other => panic!("expected an OR of ids, got {other:?}"),+ }+}++fn document_id(literal: &DocumentLiteral) -> Option<Uuid> {+ match literal {+ DocumentLiteral::Id(id) => Some(*id),+ other => panic!("expected a document id, got {other:?}"),+ }+}++#[test]+fn top_level_scope_constrains_every_source_before_its_own_filter() {+ let entities = AssociatedEntities {+ documents: ids(&[1, 2, 3]),+ calls: ids(&[4]),+ channel_threads: ids(&[5]),+ ..AssociatedEntities::default()+ };+ let ast = resolved(entities).apply(EntityFilterAst {+ crm_association: Some(CrmAssociation::Company(COMPANY)),+ document_filter: Some(Arc::new(Expr::val(DocumentLiteral::SubType(+ document_sub_type::DocumentSubType::Task,+ )))),+ ..EntityFilterAst::default()+ });++ assert_eq!(ast.crm_association, None);+ assert_matches!(ast.document_filter.as_deref(), Some(Expr::And(ids_tree, task)) => {+ assert_eq!(id_set(ids_tree, document_id), ids(&[1, 2, 3]));+ assert_matches!(task.as_ref(), Expr::Literal(DocumentLiteral::SubType(_)));+ });+ assert_matches!(+ ast.call_filter.as_deref(),+ Some(Expr::Literal(CallLiteral::CallId(call))) if *call == id(4)+ );+ assert_matches!(+ ast.channel_thread_filter.as_deref(),+ Some(Expr::Literal(ChannelThreadLiteral::ThreadId(thread))) if *thread == id(5)+ );+ // Sources without associated entities are pinned to the nil id, which+ // Soup prunes before calling their domains.+ for (tree, what) in [+ (serde_json::to_value(&ast.chat_filter).unwrap(), "chat"),+ (+ serde_json::to_value(&ast.email_filter.tree).unwrap(),+ "email",+ ),+ (+ serde_json::to_value(&ast.channel_filter).unwrap(),+ "channel",+ ),+ (+ serde_json::to_value(&ast.foreign_entity_filter).unwrap(),+ "foreign",+ ),+ ] {+ assert!(+ tree.to_string().contains(&Uuid::nil().to_string()),+ "{what}: {tree}"+ );+ }+ // Opt-in sources stay off.+ assert!(ast.agent_session_filter.is_none());+ assert!(ast.initiative_filter.is_none());+ assert!(ast.database_row_filter.is_none());+ assert!(ast.crm_contact_filter.is_none());+}++#[test]+fn document_literals_resolve_inside_their_tree() {+ let contact = CrmAssociation::Contact(CONTACT);+ let resolved = ResolvedAssociations(HashMap::from([(+ contact,+ AssociatedEntities {+ documents: ids(&[7, 8]),+ ..AssociatedEntities::default()+ },+ )]));+ let ast = resolved.apply(EntityFilterAst {+ document_filter: Some(Arc::new(Expr::or(+ Expr::val(DocumentLiteral::CrmAssociated(contact)),+ Expr::val(DocumentLiteral::IsEmailAttachment(true)),+ ))),+ ..EntityFilterAst::default()+ });+ assert_matches!(ast.document_filter.as_deref(), Some(Expr::Or(ids_tree, attachment)) => {+ assert_eq!(id_set(ids_tree, document_id), ids(&[7, 8]));+ assert_matches!(attachment.as_ref(), Expr::Literal(DocumentLiteral::IsEmailAttachment(true)));+ });+ // The other sources are untouched without a top-level scope.+ assert!(ast.call_filter.is_none());++ let empty = ResolvedAssociations::default().apply(EntityFilterAst {+ document_filter: Some(Arc::new(Expr::val(DocumentLiteral::CrmAssociated(contact)))),+ ..EntityFilterAst::default()+ });+ assert_matches!(+ empty.document_filter.as_deref(),+ Some(Expr::Literal(DocumentLiteral::Id(nil))) if nil.is_nil()+ );+}++#[test]+fn requested_opt_in_sources_are_constrained() {+ let entities = AssociatedEntities {+ crm_contacts: ids(&[9]),+ crm_companies: ids(&[10]),+ ..AssociatedEntities::default()+ };+ let ast = resolved(entities.clone()).apply(EntityFilterAst {+ crm_association: Some(CrmAssociation::Company(COMPANY)),+ crm_contact_filter: Some(Arc::new(Expr::val(CrmContactLiteral::Include))),+ agent_session_filter: Some(Arc::new(Expr::val(AgentSessionLiteral::Include))),+ ..EntityFilterAst::default()+ });+ assert_matches!(ast.crm_contact_filter.as_deref(), Some(Expr::And(contact, include)) => {+ assert_matches!(contact.as_ref(), Expr::Literal(CrmContactLiteral::Id(contact)) if *contact == id(9));+ assert_matches!(include.as_ref(), Expr::Literal(CrmContactLiteral::Include));+ });+ assert_matches!(ast.agent_session_filter.as_deref(), Some(Expr::And(session, _)) => {+ assert_matches!(session.as_ref(), Expr::Literal(AgentSessionLiteral::Id(nil)) if nil.is_nil());+ });++ let request = |company_ids: Vec<Uuid>| GetCrmCompaniesRequest {+ access: CrmTeamReceipt::from_team_receipt(+ EntityAccessReceipt::dangerously_assert_internal_user(+ &Uuid::from_u128(1).to_string(),+ entity_access::domain::models::EntityType::Team,+ ),+ )+ .unwrap(),+ user_id: MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned(),+ company_ids,+ hidden: None,+ sort: crm::domain::companies_repo::CrmCompanyListSort::UpdatedAt,+ cursor: None,+ limit: 20,+ };+ let mut open = request(Vec::new());+ assert!(intersect_crm_companies(&mut open, &entities));+ assert_eq!(open.company_ids, vec![id(10)]);+ let mut other = request(vec![id(11)]);+ assert!(!intersect_crm_companies(&mut other, &entities));+}diff --git a/crates/soup/src/domain/service/tests.rs b/crates/soup/src/domain/service/tests.rsindex 326ca88936..71e887211c 100644--- a/crates/soup/src/domain/service/tests.rs+++ b/crates/soup/src/domain/service/tests.rs@@ -45,6 +45,7 @@ use uuid::Uuid;use super::*;mod agent_metadata;+mod crm_association;mod exclusions;mod favorites;mod work_feed;@@ -92,6 +93,13 @@ impl ChannelListService for NoopCommsService {Ok(Vec::new())}+ async fn get_reference_sources(+ &self,+ _targets: &[channels::domain::models::ReferenceTarget],+ ) -> Result<Vec<channels::domain::models::ReferenceSource>, Report> {+ Ok(Vec::new())+ }+async fn get_names(&self,_names: std::collections::HashSet<MacroUserIdStr<'_>>,@@ -163,6 +171,13 @@ impl ChannelListService for RecordingCommsService {Ok(self.rows.clone())}+ async fn get_reference_sources(+ &self,+ _targets: &[channels::domain::models::ReferenceTarget],+ ) -> Result<Vec<channels::domain::models::ReferenceSource>, Report> {+ Ok(Vec::new())+ }+async fn get_names(&self,_names: std::collections::HashSet<MacroUserIdStr<'_>>,diff --git a/crates/soup/src/domain/service/tests/crm_association.rs b/crates/soup/src/domain/service/tests/crm_association.rsnew file mode 100644index 0000000000..c00cd3912e--- /dev/null+++ b/crates/soup/src/domain/service/tests/crm_association.rs@@ -0,0 +1,547 @@+//! CRM associations through the Soup service: authorization, the resolved+//! source constraints, and the cursor contract.+use super::*;+use crate::domain::models::CrmPropertyEdge;+use channels::domain::models::{+ MessageParent, ReferenceSource, ReferenceTarget, ReferencingMessage,+};+use crm::domain::{+ association::{CrmAssociation, CrmRecordAssociation},+ auth::{CrmCompanyReceipt, CrmContactReceipt, CrmTeamReceipt},+ companies_repo::{CrmCompanyListSort, CrmCompanySoupCursor},+ model::{+ CrmCompanyForSoup, CrmCompanyWithContacts, CrmContact, CrmError, CrmScopePrecheck,+ CrmTeamSettings, CrmTeamSettingsPatch, DepopulateContactOutcome,+ },+};+use entity_access::domain::models::{EditAccessLevel, ViewAccessLevel};+use item_filters::ast::{crm_association::CrmAssociation as Record, document::DocumentLiteral};+use models_properties::EntityType as PropertyEntityType;++const USER: &str = "macro|[email protected]";+const COMPANY: Uuid = Uuid::from_u128(0xc0);+const CONTACT: Uuid = Uuid::from_u128(0xc1);+const SIBLING_CONTACT: Uuid = Uuid::from_u128(0xc2);+const CHANNEL: Uuid = Uuid::from_u128(0xc4a);++/// Resolves the company to its two contacts; any other record is not visible.+#[derive(Clone)]+struct FakeCrm;++impl CrmService for FakeCrm {+ async fn resolve_association(+ &self,+ user_id: &str,+ _access: Option<&CrmTeamReceipt<MemberTeamRole>>,+ record: CrmAssociation,+ ) -> Result<CrmRecordAssociation, CrmError> {+ assert_eq!(user_id, USER);+ match record {+ CrmAssociation::Company(COMPANY) => Ok(CrmRecordAssociation::company(+ COMPANY,+ vec![CONTACT, SIBLING_CONTACT],+ )),+ CrmAssociation::Contact(CONTACT) => Ok(CrmRecordAssociation::contact(CONTACT)),+ CrmAssociation::Company(_) => Err(CrmError::CompanyNotFoundForTeam),+ CrmAssociation::Contact(_) => Err(CrmError::ContactNotFoundForTeam),+ }+ }++ async fn list_contacts_for_soup(+ &self,+ _user_id: &str,+ _access: Option<&CrmTeamReceipt<MemberTeamRole>>,+ _query: crm::domain::contact_listing::CrmContactListQuery,+ ) -> Result<Vec<crm::domain::contact_listing::CrmContactForSoup>, CrmError> {+ unimplemented!("FakeCrm.list_contacts_for_soup")+ }++ async fn populate_contact(+ &self,+ _team_id: &uuid::Uuid,+ _link_id: &uuid::Uuid,+ _user_email: &str,+ _email: &str,+ _name: Option<&str>,+ _first_at: DateTime<Utc>,+ _last_at: DateTime<Utc>,+ _is_sent: bool,+ ) -> Result<(), CrmError> {+ unimplemented!("FakeCrm.populate_contact")+ }++ async fn depopulate_contact(+ &self,+ _team_id: &uuid::Uuid,+ _link_id: &uuid::Uuid,+ _email: &str,+ ) -> Result<DepopulateContactOutcome, CrmError> {+ unimplemented!("FakeCrm.depopulate_contact")+ }++ async fn link_contact_pairs_with_sources(+ &self,+ _pairs: &[(uuid::Uuid, String)],+ ) -> Result<Vec<(uuid::Uuid, String)>, CrmError> {+ unimplemented!("FakeCrm.link_contact_pairs_with_sources")+ }++ async fn depopulate_link_in_team(+ &self,+ _team_id: &uuid::Uuid,+ _link_id: &uuid::Uuid,+ ) -> Result<(), CrmError> {+ unimplemented!("FakeCrm.depopulate_link_in_team")+ }++ async fn get_team_id_for_user(&self, _macro_id: &str) -> Result<Option<uuid::Uuid>, CrmError> {+ unimplemented!("FakeCrm.get_team_id_for_user")+ }++ async fn create_company(+ &self,+ _access: &CrmTeamReceipt<MemberTeamRole>,+ _name: &str,+ _domain: &str,+ ) -> Result<CrmCompanyWithContacts, CrmError> {+ unimplemented!("FakeCrm.create_company")+ }++ async fn create_contact(+ &self,+ _access: &CrmCompanyReceipt<ViewAccessLevel>,+ _name: &str,+ _email: &str,+ ) -> Result<CrmContact, CrmError> {+ unimplemented!("FakeCrm.create_contact")+ }++ async fn set_email_sync(+ &self,+ _access: &CrmCompanyReceipt<EditAccessLevel>,+ _email_sync: bool,+ ) -> Result<(), CrmError> {+ unimplemented!("FakeCrm.set_email_sync")+ }++ async fn set_company_hidden(+ &self,+ _access: &CrmCompanyReceipt<EditAccessLevel>,+ _hidden: bool,+ ) -> Result<(), CrmError> {+ unimplemented!("FakeCrm.set_company_hidden")+ }++ async fn set_company_name(+ &self,+ _access: &CrmCompanyReceipt<ViewAccessLevel>,+ _name: &str,+ ) -> Result<(), CrmError> {+ unimplemented!("FakeCrm.set_company_name")+ }++ async fn set_contact_hidden(+ &self,+ _access: &CrmContactReceipt<EditAccessLevel>,+ _hidden: bool,+ ) -> Result<(), CrmError> {+ unimplemented!("FakeCrm.set_contact_hidden")+ }++ async fn set_contact_name(+ &self,+ _access: &CrmContactReceipt<ViewAccessLevel>,+ _name: &str,+ ) -> Result<(), CrmError> {+ unimplemented!("FakeCrm.set_contact_name")+ }++ async fn crm_scope_precheck(+ &self,+ _team_id: &uuid::Uuid,+ _domains: &[String],+ _addresses: &[String],+ ) -> Result<CrmScopePrecheck, CrmError> {+ unimplemented!("FakeCrm.crm_scope_precheck")+ }++ async fn list_companies_for_soup(+ &self,+ _access: &CrmTeamReceipt<MemberTeamRole>,+ _user_id: &str,+ _company_ids: &[uuid::Uuid],+ _hidden: Option<bool>,+ _sort: CrmCompanyListSort,+ _cursor: Option<CrmCompanySoupCursor>,+ _limit: i64,+ ) -> Result<Vec<CrmCompanyForSoup>, CrmError> {+ unimplemented!("FakeCrm.list_companies_for_soup")+ }++ async fn list_contacts_for_company(+ &self,+ _access: &CrmCompanyReceipt<ViewAccessLevel>,+ ) -> Result<Vec<CrmContact>, CrmError> {+ unimplemented!("FakeCrm.list_contacts_for_company")+ }++ async fn get_contact_for_team(+ &self,+ _access: &CrmContactReceipt<ViewAccessLevel>,+ ) -> Result<Option<CrmContact>, CrmError> {+ unimplemented!("FakeCrm.get_contact_for_team")+ }++ async fn search_contacts(+ &self,+ _access: &CrmTeamReceipt<MemberTeamRole>,+ _query: &str,+ _limit: u16,+ ) -> Result<Vec<CrmContact>, CrmError> {+ unimplemented!("FakeCrm.search_contacts")+ }++ async fn get_contact_by_email(+ &self,+ _access: &CrmTeamReceipt<MemberTeamRole>,+ _email: &str,+ ) -> Result<Option<CrmContact>, CrmError> {+ unimplemented!("FakeCrm.get_contact_by_email")+ }++ async fn get_company_for_team(+ &self,+ _access: &CrmCompanyReceipt<ViewAccessLevel>,+ ) -> Result<Option<CrmCompanyWithContacts>, CrmError> {+ unimplemented!("FakeCrm.get_company_for_team")+ }++ async fn get_team_settings(+ &self,+ _access: &CrmTeamReceipt<MemberTeamRole>,+ ) -> Result<CrmTeamSettings, CrmError> {+ unimplemented!("FakeCrm.get_team_settings")+ }++ async fn update_team_settings(+ &self,+ _access: &CrmTeamReceipt<MemberTeamRole>,+ _patch: CrmTeamSettingsPatch,+ ) -> Result<CrmTeamSettings, CrmError> {+ unimplemented!("FakeCrm.update_team_settings")+ }+}++/// Reference edges keyed by target: a document mentioning the sibling+/// contact, a channel reply mentioning the contact, and a document+/// mentioning the company.+#[derive(Clone, Default)]+struct ReferencingComms {+ targets: Arc<Mutex<Vec<Vec<ReferenceTarget>>>>,+ thread_filters: Arc<Mutex<Vec<String>>>,+}++impl ChannelListService for ReferencingComms {+ async fn get_channels(+ &self,+ _req: GetChannelsRequest,+ ) -> Result<Vec<channels::domain::models::ChannelWithLatest>, Report> {+ Ok(Vec::new())+ }++ async fn get_activities(+ &self,+ _user: MacroUserIdStr<'_>,+ ) -> Result<Vec<channels::domain::models::Activity>, Report> {+ Ok(Vec::new())+ }++ async fn get_thread_messages(+ &self,+ req: GetThreadReplyRowsRequest,+ ) -> Result<Vec<ChannelMessage>, Report> {+ self.thread_filters+ .lock()+ .unwrap()+ .push(serde_json::to_string(req.query.filter()).unwrap());+ Ok(Vec::new())+ }++ async fn get_reference_sources(+ &self,+ targets: &[ReferenceTarget],+ ) -> Result<Vec<ReferenceSource>, Report> {+ self.targets.lock().unwrap().push(targets.to_vec());+ Ok(targets+ .iter()+ .flat_map(+ |target| match (target.entity_type.as_str(), target.entity_id.as_str()) {+ ("crm_company", id) if id == COMPANY.to_string() => {+ vec![ReferenceSource::Document(Uuid::from_u128(1).to_string())]+ }+ ("crm_contact", id) if id == CONTACT.to_string() => {+ vec![ReferenceSource::Message(ReferencingMessage {+ message_id: Uuid::from_u128(0x51),+ thread_id: Some(Uuid::from_u128(0x50)),+ parent: MessageParent::Channel(CHANNEL),+ })]+ }+ ("crm_contact", id) if id == SIBLING_CONTACT.to_string() => {+ vec![ReferenceSource::Document(Uuid::from_u128(2).to_string())]+ }+ _ => Vec::new(),+ },+ )+ .collect())+ }++ async fn get_names(+ &self,+ _names: std::collections::HashSet<MacroUserIdStr<'_>>,+ ) -> Result<Vec<channels::domain::models::UserName>, Report> {+ Ok(Vec::new())+ }+}++fn request(filters: EntityFilterAst) -> SoupRequest<EntityFilterAst> {+ SoupRequest {+ soup_type: SoupType::Expanded,+ limit: 1,+ cursor: SoupQuery::new_sort_simple(SimpleSortMethod::UpdatedAt, filters),+ sort_direction: SoupSortDirection::Desc,+ user: MacroUserIdStr::parse_from_str(USER).unwrap(),+ email_preview_view: PreviewView::default(),+ link_ids: vec![],+ }+}++fn service(+ repo: MockSoupRepo,+ comms: ReferencingComms,+) -> SoupImpl<+ MockSoupRepo,+ FrecencyQueryServiceImpl<MockFrecencyStorage>,+ NoopEmailPreviewService,+ ReferencingComms,+ NoopCallRecordQueryService,+ FakeCrm,+ NoopPullRequestListing,+> {+ SoupImpl::new(+ repo,+ FrecencyQueryServiceImpl::new(MockFrecencyStorage::new()),+ NoopEmailPreviewService,+ comms,+ NoopCallRecordQueryService,+ FakeCrm,+ NoopPullRequestListing,+ )+}++fn document_ids(expr: &Expr<DocumentLiteral>) -> Vec<Uuid> {+ match expr {+ Expr::Literal(DocumentLiteral::Id(id)) => vec![*id],+ Expr::Or(a, b) => [document_ids(a), document_ids(b)].concat(),+ Expr::And(a, _) => document_ids(a),+ other => panic!("unexpected document filter {other:?}"),+ }+}++#[tokio::test]+async fn company_scope_matches_properties_and_references_of_its_contacts() {+ let comms = ReferencingComms::default();+ let mut repo = MockSoupRepo::new();+ repo.expect_crm_property_edges()+ .times(1)+ .returning(|companies, contacts| {+ assert_eq!(companies, [COMPANY]);+ assert_eq!(contacts, [CONTACT, SIBLING_CONTACT]);+ // A contact-only task: Contacts property without Companies.+ Box::pin(async {+ Ok(vec![+ CrmPropertyEdge {+ entity_type: PropertyEntityType::Task,+ entity_id: Uuid::from_u128(3).to_string(),+ },+ CrmPropertyEdge {+ entity_type: PropertyEntityType::Document,+ entity_id: Uuid::from_u128(1).to_string(),+ },+ ])+ })+ });+ repo.expect_expanded_generic_cursor_soup()+ .times(1)+ .returning(|request| {+ let SimpleSortQuery::ItemsFilter(query) = request.cursor else {+ panic!("filtered query")+ };+ let filter = query.filter();+ assert_eq!(filter.crm_association, None);+ let mut documents = document_ids(filter.document_filter.as_deref().unwrap());+ documents.sort();+ // Property-linked, company-mentioning, and contact-mentioning+ // documents, once each.+ assert_eq!(documents, [1, 2, 3].map(Uuid::from_u128));+ Box::pin(async {+ Ok(vec![SoupItem::Document(soup_document_uuid_with_updated(+ Uuid::from_u128(3),+ DateTime::default(),+ ))])+ })+ });+ let filters = EntityFilterAst {+ crm_association: Some(Record::Company(COMPANY)),+ ..Default::default()+ };+ let page = service(repo, comms.clone())+ .get_user_soup(request(filters.clone()), None)+ .await+ .unwrap()+ .into_simple()+ .unwrap();++ assert_eq!(page.items.len(), 1);+ // The reply's thread root is the channel row; channels and calls with no+ // association are pruned before their domains are asked.+ assert_eq!(+ *comms.thread_filters.lock().unwrap(),+ vec![format!(+ r#"{{"l":{{"ThreadId":"{}"}}}}"#,+ Uuid::from_u128(0x50)+ )]+ );+ assert_eq!(comms.targets.lock().unwrap()[0].len(), 3);+ // The cursor carries the record, not the resolved ids, so the next page+ // re-authorizes it.+ let cursor: CursorWithValAndFilter<String, SimpleSortMethod, EntityFilterAst> =+ page.next_cursor.unwrap().decode_json().unwrap();+ assert_eq!(+ serde_json::to_value(cursor.filter).unwrap(),+ serde_json::to_value(filters).unwrap()+ );+}++#[tokio::test]+async fn contact_scope_excludes_company_only_and_sibling_items() {+ let comms = ReferencingComms::default();+ let mut repo = MockSoupRepo::new();+ repo.expect_crm_property_edges()+ .times(1)+ .returning(|companies, contacts| {+ assert!(companies.is_empty());+ assert_eq!(contacts, [CONTACT]);+ Box::pin(async { Ok(Vec::new()) })+ });+ repo.expect_expanded_generic_cursor_soup()+ .times(1)+ .returning(|request| {+ let SimpleSortQuery::ItemsFilter(query) = request.cursor else {+ panic!("filtered query")+ };+ // Only a channel reply mentions the contact, so the document+ // source is pinned to nothing.+ assert_eq!(+ document_ids(query.filter().document_filter.as_deref().unwrap()),+ [Uuid::nil()]+ );+ Box::pin(async { Ok(Vec::new()) })+ });+ service(repo, comms.clone())+ .get_user_soup(+ request(EntityFilterAst {+ crm_association: Some(Record::Contact(CONTACT)),+ ..Default::default()+ }),+ None,+ )+ .await+ .unwrap();+ assert_eq!(+ *comms.targets.lock().unwrap(),+ vec![vec![ReferenceTarget {+ entity_type: "crm_contact".into(),+ entity_id: CONTACT.to_string(),+ }]]+ );+}++#[tokio::test]+async fn invisible_records_fail_before_any_source_query() {+ let comms = ReferencingComms::default();+ for record in [+ Record::Company(Uuid::from_u128(0xdead)),+ Record::Contact(Uuid::from_u128(0xbeef)),+ ] {+ // The repo has no expectations: touching it would panic.+ let result = service(MockSoupRepo::new(), comms.clone())+ .get_user_soup(+ request(EntityFilterAst {+ crm_association: Some(record),+ ..Default::default()+ }),+ None,+ )+ .await;+ assert_matches!(result, Err(SoupErr::CrmRecordNotFound));+ }+ // A document literal naming an invisible record is denied the same way.+ let result = service(MockSoupRepo::new(), comms.clone())+ .get_user_soup(+ request(EntityFilterAst {+ document_filter: Some(Arc::new(Expr::val(DocumentLiteral::CrmAssociated(+ Record::Company(Uuid::from_u128(0xdead)),+ )))),+ ..Default::default()+ }),+ None,+ )+ .await;+ assert_matches!(result, Err(SoupErr::CrmRecordNotFound));+ assert!(comms.targets.lock().unwrap().is_empty());+}++#[tokio::test]+async fn associations_require_a_timestamp_sort() {+ let filters = EntityFilterAst {+ crm_association: Some(Record::Company(COMPANY)),+ ..Default::default()+ };+ for cursor in [+ SoupQuery::new_sort_frecency(Frecency, filters.clone()),+ SoupQuery::new_sort_touched(filters.clone()),+ SoupQuery::new_sort_notified(filters.clone()),+ ] {+ let mut request = request(filters.clone());+ request.cursor = cursor;+ let result = service(MockSoupRepo::new(), ReferencingComms::default())+ .get_user_soup(request, None)+ .await;+ assert_matches!(result, Err(SoupErr::AstErr(_)));+ }+}++#[tokio::test]+async fn associations_require_an_expanded_query() {+ let company = Record::Company(COMPANY);+ let comms = ReferencingComms::default();+ for filters in [+ EntityFilterAst {+ crm_association: Some(company),+ ..Default::default()+ },+ EntityFilterAst {+ document_filter: Some(Arc::new(Expr::val(DocumentLiteral::CrmAssociated(company)))),+ ..Default::default()+ },+ ] {+ let mut request = request(filters);+ request.soup_type = SoupType::UnExpanded;+ // The repo has no expectations, so an edge or candidate read panics.+ let result = service(MockSoupRepo::new(), comms.clone())+ .get_user_soup(request, None)+ .await;+ assert_matches!(result, Err(SoupErr::AstErr(_)));+ }+ assert!(comms.targets.lock().unwrap().is_empty());+}diff --git a/crates/soup/src/domain/service/tests/work_feed.rs b/crates/soup/src/domain/service/tests/work_feed.rsindex 6c6cfbb803..fe5aab1b7b 100644--- a/crates/soup/src/domain/service/tests/work_feed.rs+++ b/crates/soup/src/domain/service/tests/work_feed.rs@@ -213,3 +213,26 @@ async fn work_feed_rejects_calendar_filters_it_cannot_fold() {.unwrap_err();assert_matches!(error, SoupErr::NotifiedUnsupportedFilter("calendar_event"));}++/// The work feed cannot resolve CRM associations, so a scoped request fails+/// before reading candidates rather than returning an unscoped feed.+#[tokio::test]+async fn work_feed_rejects_crm_associations() {+ use item_filters::ast::{crm_association::CrmAssociation, document::DocumentLiteral};+ let company = CrmAssociation::Company(Uuid::from_u128(0xc0));+ let mut scoped = work_feed_request(2);+ scoped.filter.crm_association = Some(company);+ let mut literal = work_feed_request(2);+ literal.filter.document_filter =+ Some(Arc::new(Expr::val(DocumentLiteral::CrmAssociated(company))));++ for request in [scoped, literal] {+ let mut soup_mock = MockSoupRepo::new();+ soup_mock.expect_work_feed_soup_page().times(0);+ let error = service(soup_mock)+ .get_work_feed_page(request, None)+ .await+ .unwrap_err();+ assert_matches!(error, SoupErr::AstErr(_));+ }+}diff --git a/crates/soup/src/inbound/axum_router.rs b/crates/soup/src/inbound/axum_router.rsindex f4ebff6383..958b0a0117 100644--- a/crates/soup/src/inbound/axum_router.rs+++ b/crates/soup/src/inbound/axum_router.rs@@ -798,6 +798,9 @@ pub enum SoupHandlerErr {/// Hidden CRM company query was requested without admin privileges.#[error("Querying hidden CRM companies requires admin/owner team role")]CrmAdminRequired,+ /// The filter is restricted to a CRM record the caller cannot see.+ #[error("CRM record not found")]+ CrmRecordNotFound,/// Ascending order was requested for a frecency-sorted query.#[error("sort_direction=asc is not supported with sort_method=frecency")]AscendingFrecencyUnsupported,@@ -821,6 +824,7 @@ impl From<SoupErr> for SoupHandlerErr {SoupErr::AstErr(expand_err) => SoupHandlerErr::ExpandErr(expand_err),SoupErr::CrmTeamRequired => SoupHandlerErr::CrmScopeForbidden,SoupErr::CrmAdminRequired => SoupHandlerErr::CrmAdminRequired,+ SoupErr::CrmRecordNotFound => SoupHandlerErr::CrmRecordNotFound,SoupErr::TouchedUnsupportedFilter(kind) => {SoupHandlerErr::TouchedUnsupportedFilter(kind)}@@ -845,6 +849,7 @@ impl IntoResponse for SoupHandlerErr {SoupHandlerErr::CrmScopeForbidden | SoupHandlerErr::CrmAdminRequired => {StatusCode::FORBIDDEN}+ SoupHandlerErr::CrmRecordNotFound => StatusCode::NOT_FOUND,_ => StatusCode::INTERNAL_SERVER_ERROR,};(@@ -1037,6 +1042,7 @@ pub struct PostSoupAstRequest {responses((status = 200, body=SoupPage),(status = 403, description = "CRM-scoped queries require team membership, or requesting hidden CRM companies requires admin/owner team role", body=ErrorResponse),+ (status = 404, description = "The CRM record named by `crma` or a document `crm` literal is not visible to the caller", body=ErrorResponse),(status = 500, body=ErrorResponse),))]@@ -1129,6 +1135,7 @@ enum GroupedSoupRequestMode {responses((status = 200, body=GroupedSoupPage),(status = 403, description = "CRM-scoped queries require team membership, or requesting hidden CRM companies requires admin/owner team role", body=ErrorResponse),+ (status = 404, description = "The CRM record named by `crma` or a document `crm` literal is not visible to the caller", body=ErrorResponse),(status = 500, body=ErrorResponse),))]@@ -1190,6 +1197,13 @@ pub struct ApiEntityFilterAst {/// Restrict to the authenticated viewer's favorites before pagination when true.#[serde(default, skip_serializing_if = "Option::is_none")]pub favorites_only: Option<bool>,+ /// Restrict every entity type to items associated with this CRM record+ /// (wire key `crma`): its Companies or Contacts property names the+ /// record, or it references the record. A company also matches through+ /// its contacts. Unknown or inaccessible records answer 404; requests+ /// that are not expanded or not timestamp-sorted answer 400.+ #[serde(default, rename = "crma", skip_serializing_if = "Option::is_none")]+ pub crm_association: Option<item_filters::ast::crm_association::CrmAssociation>,/// filters applied to canonical calendar events#[serde(default, rename = "calf")]#[schema(value_type = serde_json::Value)]@@ -1339,6 +1353,7 @@ impl ApiEntityFilterAst {fn into_entity_ast(self) -> Result<EntityFilterAst, Report> {let ApiEntityFilterAst {favorites_only,+ crm_association,calendar_event_filter,document_filter,project_filter,@@ -1407,6 +1422,7 @@ impl ApiEntityFilterAst {Ok(EntityFilterAst {favorites_only,+ crm_association,calendar_event_filter,document_filter,project_filter,diff --git a/crates/soup/src/inbound/toolset/list_entities.rs b/crates/soup/src/inbound/toolset/list_entities.rsindex 7038bd5292..2a02e7b852 100644--- a/crates/soup/src/inbound/toolset/list_entities.rs+++ b/crates/soup/src/inbound/toolset/list_entities.rs@@ -558,6 +558,7 @@ impl ListEntities {let ast = EntityFilterAst {favorites_only: self.favorites_only.then_some(true),+ crm_association: None,calendar_event_filter: None,document_filter: self.document_filter.clone(),project_filter: self.project_filter.clone(),@@ -605,6 +606,7 @@ impl ListEntities {EntityFilterAst {favorites_only: ast.favorites_only,+ crm_association: ast.crm_association,calendar_event_filter: if include_types.contains(&ItemType::CalendarEvent) {ast.calendar_event_filter} else {diff --git a/crates/soup/src/outbound/pg_soup_repo.rs b/crates/soup/src/outbound/pg_soup_repo.rsindex c93e55d237..37c2a98f9b 100644--- a/crates/soup/src/outbound/pg_soup_repo.rs+++ b/crates/soup/src/outbound/pg_soup_repo.rs@@ -1,10 +1,10 @@use crate::{domain::{models::{- AdvancedSortParams, GroupedSortRequest, NotifiedEntity, NotifiedSoupRequest,- SimpleSortQuery, SimpleSortRequest, SoupProjectionHydration, SoupPropertiesField,- TouchedEntity, TouchedSoupRequest, WorkFeedCandidate, WorkFeedCandidateRequest,- grouping::ItemGroupingInfo,+ AdvancedSortParams, CrmPropertyEdge, GroupedSortRequest, NotifiedEntity,+ NotifiedSoupRequest, SimpleSortQuery, SimpleSortRequest, SoupProjectionHydration,+ SoupPropertiesField, TouchedEntity, TouchedSoupRequest, WorkFeedCandidate,+ WorkFeedCandidateRequest, grouping::ItemGroupingInfo,},ports::SoupRepo,},@@ -23,6 +23,7 @@ use system_properties::SystemPropertyKey;mod agent_session;mod calendar_event;mod candidate_gates;+mod crm_association;mod database_row;mod expanded;pub mod grouping;@@ -306,6 +307,14 @@ impl SoupRepo for PgSoupRepo {.await}+ async fn crm_property_edges<'a>(+ &self,+ company_ids: &'a [uuid::Uuid],+ contact_ids: &'a [uuid::Uuid],+ ) -> Result<Vec<CrmPropertyEdge>, Self::Err> {+ crm_association::property_edges(&self.pool.0, company_ids, contact_ids).await+ }+async fn touched_soup_page<'a>(&self,req: TouchedSoupRequest<'a>,diff --git a/crates/soup/src/outbound/pg_soup_repo/candidate_gates.rs b/crates/soup/src/outbound/pg_soup_repo/candidate_gates.rsindex 9cae546987..503cbcc6cf 100644--- a/crates/soup/src/outbound/pg_soup_repo/candidate_gates.rs+++ b/crates/soup/src/outbound/pg_soup_repo/candidate_gates.rs@@ -110,7 +110,7 @@ pub(super) fn document_gate(id_sql: &str, filter: Option<&EntityFilterAst>) -> S{PER_CANDIDATE})"#,access = access_semi_join("d.id", "document"),- doc_fold = build_document_filter(doc_filter),+ doc_fold = build_document_filter(doc_filter, None),props_fold = build_properties_filter(props_filter, "d.id"),)}diff --git a/crates/soup/src/outbound/pg_soup_repo/crm_association.rs b/crates/soup/src/outbound/pg_soup_repo/crm_association.rsnew file mode 100644index 0000000000..3b5feab3b7--- /dev/null+++ b/crates/soup/src/outbound/pg_soup_repo/crm_association.rs@@ -0,0 +1,55 @@+//! Property edges for CRM associated-item queries.++use models_properties::EntityType;+use sqlx::PgPool;+use uuid::Uuid;++use crate::domain::models::CrmPropertyEdge;++#[cfg(test)]+mod test;++/// Entities whose Companies property names a company in `company_ids`, or+/// whose Contacts property names a contact in `contact_ids`.+///+/// The property definition ids are literals rather than binds so the planner+/// can match the partial `idx_ep_companies_value_gin` and+/// `idx_ep_contacts_value_gin` indexes; `test` pins them to+/// `SystemPropertyKey`.+pub(super) async fn property_edges(+ pool: &PgPool,+ company_ids: &[Uuid],+ contact_ids: &[Uuid],+) -> Result<Vec<CrmPropertyEdge>, sqlx::Error> {+ if company_ids.is_empty() && contact_ids.is_empty() {+ return Ok(Vec::new());+ }+ let company_ids: Vec<String> = company_ids.iter().map(Uuid::to_string).collect();+ let contact_ids: Vec<String> = contact_ids.iter().map(Uuid::to_string).collect();+ let rows = sqlx::query!(+ r#"+ SELECT ep.entity_type AS "entity_type!: EntityType", ep.entity_id AS "entity_id!"+ FROM UNNEST($1::text[]) AS company(id)+ JOIN entity_properties ep+ ON ep.property_definition_id = '00000001-0000-0000-0000-00000000000c'+ AND ep.values->'value' @> jsonb_build_array(jsonb_build_object('entity_id', company.id))+ UNION+ SELECT ep.entity_type, ep.entity_id+ FROM UNNEST($2::text[]) AS contact(id)+ JOIN entity_properties ep+ ON ep.property_definition_id = '00000001-0000-0000-0000-000000000013'+ AND ep.values->'value' @> jsonb_build_array(jsonb_build_object('entity_id', contact.id))+ "#,+ &company_ids,+ &contact_ids,+ )+ .fetch_all(pool)+ .await?;+ Ok(rows+ .into_iter()+ .map(|row| CrmPropertyEdge {+ entity_type: row.entity_type,+ entity_id: row.entity_id,+ })+ .collect())+}diff --git a/crates/soup/src/outbound/pg_soup_repo/crm_association/test.rs b/crates/soup/src/outbound/pg_soup_repo/crm_association/test.rsnew file mode 100644index 0000000000..2d4629d4f9--- /dev/null+++ b/crates/soup/src/outbound/pg_soup_repo/crm_association/test.rs@@ -0,0 +1,79 @@+use super::*;+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use system_properties::SystemPropertyKey;++const COMPANY: Uuid = Uuid::from_u128(0xc0);+const CONTACT: Uuid = Uuid::from_u128(0xc1);+const OTHER: Uuid = Uuid::from_u128(0xc2);++async fn link(pool: &PgPool, entity_id: &str, entity_type: &str, definition: Uuid, ids: &[Uuid]) {+ let refs: Vec<serde_json::Value> = ids+ .iter()+ .map(|id| serde_json::json!({ "entity_id": id.to_string(), "entity_type": "COMPANY" }))+ .collect();+ sqlx::query(+ r#"INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)+ VALUES ($1, $2, $3::property_entity_type, $4, $5)"#,+ )+ .bind(Uuid::now_v7())+ .bind(entity_id)+ .bind(entity_type)+ .bind(definition)+ .bind(serde_json::json!({ "type": "EntityReference", "value": refs }))+ .execute(pool)+ .await+ .unwrap();+}++#[test]+fn literal_property_ids_are_the_system_properties() {+ let sql = include_str!("../crm_association.rs");+ assert!(sql.contains(&SystemPropertyKey::COMPANIES_UUID.to_string()));+ assert!(sql.contains(&SystemPropertyKey::CONTACTS_UUID.to_string()));+}++#[sqlx::test(migrator = "MACRO_DB_MIGRATIONS")]+async fn matches_companies_and_contacts_once(pool: PgPool) {+ let companies = SystemPropertyKey::COMPANIES_UUID;+ let contacts = SystemPropertyKey::CONTACTS_UUID;+ link(&pool, "task-company", "TASK", companies, &[OTHER, COMPANY]).await;+ link(&pool, "call-contact", "CALL_RECORD", contacts, &[CONTACT]).await;+ // Both properties on one entity still produce one edge.+ link(&pool, "doc-both", "DOCUMENT", companies, &[COMPANY]).await;+ link(&pool, "doc-both", "DOCUMENT", contacts, &[CONTACT]).await;+ // A contact id in the Companies property, or another record, never matches.+ link(+ &pool,+ "doc-wrong-property",+ "DOCUMENT",+ companies,+ &[CONTACT],+ )+ .await;+ link(&pool, "doc-other", "DOCUMENT", contacts, &[OTHER]).await;++ let mut edges = property_edges(&pool, &[COMPANY], &[CONTACT]).await.unwrap();+ edges.sort_by(|a, b| a.entity_id.cmp(&b.entity_id));+ assert_eq!(+ edges,+ vec![+ CrmPropertyEdge {+ entity_type: EntityType::CallRecord,+ entity_id: "call-contact".into()+ },+ CrmPropertyEdge {+ entity_type: EntityType::Document,+ entity_id: "doc-both".into()+ },+ CrmPropertyEdge {+ entity_type: EntityType::Task,+ entity_id: "task-company".into()+ },+ ]+ );+ assert!(property_edges(&pool, &[], &[]).await.unwrap().is_empty());+ assert_eq!(+ property_edges(&pool, &[], &[CONTACT]).await.unwrap().len(),+ 2+ );+}diff --git a/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs b/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic.rsindex ac70bfca49..8c22943075 100644--- a/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs+++ b/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs@@ -5,9 +5,11 @@mod test;mod database_row;+mod document_ids;mod initiative;use database_row::{build_database_row_filter, database_row_opted_in, database_row_top_clause};+pub(in crate::outbound::pg_soup_repo) use document_ids::DocumentIdArrays;use initiative::initiative_top_clause;pub(in crate::outbound::pg_soup_repo) use initiative::{build_initiative_filter, initiative_access_clause, initiative_opted_in,@@ -828,28 +830,45 @@ fn date_predicate(col: &str, lit: &DateLiteral) -> String {}}+/// Renders the document filter as ` AND ...` against the `d` alias.+/// `id_arrays` binds its runs of document ids as arrays (see+/// [`document_ids`]); without it every id renders inline, for queries with no+/// free parameter slots.pub(in crate::outbound::pg_soup_repo) fn build_document_filter(ast: Option<&Expr<DocumentLiteral>>,+ id_arrays: Option<&mut DocumentIdArrays>,) -> String {let Some(expr) = ast else {return String::new();};let expr = push_not_inward(expr, false);- let formatting = expr.collapse_frames(|frame| match frame {- filter_ast::ExprFrame::And(a, b) => format!("({a} AND {b})"),- filter_ast::ExprFrame::Or(a, b) => format!("({a} OR {b})"),- filter_ast::ExprFrame::Not(a) => format!("(NOT {a})"),- filter_ast::ExprFrame::Literal(DocumentLiteral::FileType(f)) => {+ let formatting = match id_arrays {+ Some(id_arrays) => document_ids::render(&expr, id_arrays, document_literal_sql),+ None => expr.collapse_frames(|frame| match frame {+ filter_ast::ExprFrame::And(a, b) => format!("({a} AND {b})"),+ filter_ast::ExprFrame::Or(a, b) => format!("({a} OR {b})"),+ filter_ast::ExprFrame::Not(a) => format!("(NOT {a})"),+ filter_ast::ExprFrame::Literal(literal) => document_literal_sql(literal),+ }),+ };+ if formatting.is_empty() {+ String::new()+ } else {+ format!(" AND {}", formatting)+ }+}++fn document_literal_sql(literal: DocumentLiteral) -> String {+ match literal {+ DocumentLiteral::FileType(f) => {format!(r#"d."fileType" = '{f}'"#)}- filter_ast::ExprFrame::Literal(DocumentLiteral::Id(i)) => format!("d.id = '{i}'"),- filter_ast::ExprFrame::Literal(DocumentLiteral::ProjectId(p)) => {- nullable_eq(r#"d."projectId""#, p)- }- filter_ast::ExprFrame::Literal(DocumentLiteral::Owner(o)) => {+ DocumentLiteral::Id(i) => format!("d.id = '{i}'"),+ DocumentLiteral::ProjectId(p) => nullable_eq(r#"d."projectId""#, p),+ DocumentLiteral::Owner(o) => {format!("d.owner = {}", sql_string_literal(&o.principal_id()))}- filter_ast::ExprFrame::Literal(DocumentLiteral::Importance(true)) => {+ DocumentLiteral::Importance(true) => {// "Important" documents: non-tasks OR tasks where user is an assigneer#"(dt.sub_type IS NULL@@ -858,8 +877,8 @@ pub(in crate::outbound::pg_soup_repo) fn build_document_filter()"#.to_string()}- // filter_ast::ExprFrame::Literal(DocumentLiteral::Importance(false)) => String::new()- filter_ast::ExprFrame::Literal(DocumentLiteral::Importance(false)) => {+ // DocumentLiteral::Importance(false) => String::new()+ DocumentLiteral::Importance(false) => {// "Unimportant" documents: tasks where user is NOT an assigneer#"(dt.sub_type = 'task'@@ -869,55 +888,45 @@ pub(in crate::outbound::pg_soup_repo) fn build_document_filter()"#.to_string()}- filter_ast::ExprFrame::Literal(DocumentLiteral::NotificationState(state)) => {+ DocumentLiteral::NotificationState(state) => {build_notification_state_clause("d.id", "document", state)}- filter_ast::ExprFrame::Literal(DocumentLiteral::IncludeCbmAtmNc(true)) => {- build_task_include_cbm_atm_nc_clause()- }+ DocumentLiteral::IncludeCbmAtmNc(true) => build_task_include_cbm_atm_nc_clause(),// false is equivalent to disabled/no-op. Rendered as TRUE (not an// empty string): an empty operand inside And/Or/Not produces invalid// SQL like `( AND x)` or `(NOT )`, and TRUE also gives NOT the right// meaning (a disabled predicate matches everything, its negation// nothing).- filter_ast::ExprFrame::Literal(DocumentLiteral::IncludeCbmAtmNc(false)) => {- "TRUE".to_string()- }+ DocumentLiteral::IncludeCbmAtmNc(false) => "TRUE".to_string(),// EXISTS instead of a predicate on the LEFT-JOINed `dt` alias: this// keeps the top clause free of the join when only SubType literals// are present, and `NOT (EXISTS ...)` becomes a plannable anti-join// (the old `(dt.sub_type IS NOT NULL AND ...)` OR-shape collapsed row// estimates to ~1 on broad arms, picking pathological nested loops).- filter_ast::ExprFrame::Literal(DocumentLiteral::SubType(st)) => {+ DocumentLiteral::SubType(st) => {format!("EXISTS (SELECT 1 FROM document_sub_type dst_f WHERE dst_f.document_id = d.id AND dst_f.sub_type = '{st}')")}- filter_ast::ExprFrame::Literal(DocumentLiteral::IsEmailAttachment(true)) => {- r#"EXISTS(SELECT 1 FROM document_email WHERE document_id = d.id)"#- .to_string()- }- filter_ast::ExprFrame::Literal(DocumentLiteral::IsEmailAttachment(false)) => {- r#"NOT EXISTS(SELECT 1 FROM document_email WHERE document_id = d.id)"#- .to_string()+ DocumentLiteral::IsEmailAttachment(true) => {+ r#"EXISTS(SELECT 1 FROM document_email WHERE document_id = d.id)"#.to_string()}- filter_ast::ExprFrame::Literal(DocumentLiteral::CreatedAt(lit)) => {- date_predicate(r#"d."createdAt""#, &lit)+ DocumentLiteral::IsEmailAttachment(false) => {+ r#"NOT EXISTS(SELECT 1 FROM document_email WHERE document_id = d.id)"#.to_string()}- filter_ast::ExprFrame::Literal(DocumentLiteral::UpdatedAt(lit)) => {- date_predicate(r#"d."updatedAt""#, &lit)- }- filter_ast::ExprFrame::Literal(DocumentLiteral::Property(lit)) => {- property_literal_predicate(&lit, "d.id")- }- filter_ast::ExprFrame::Literal(DocumentLiteral::EmailAttachmentParticipant(email)) => {+ DocumentLiteral::CreatedAt(lit) => date_predicate(r#"d."createdAt""#, &lit),+ DocumentLiteral::UpdatedAt(lit) => date_predicate(r#"d."updatedAt""#, &lit),+ DocumentLiteral::Property(lit) => property_literal_predicate(&lit, "d.id"),+ DocumentLiteral::EmailAttachmentParticipant(email) => {email_attachment_participant_predicate(&email, "d.id")}- });- if formatting.is_empty() {- String::new()- } else {- format!(" AND {}", formatting)+ DocumentLiteral::NameContains(name) => format!(+ "STRPOS(LOWER(d.name), {}) > 0",+ sql_string_literal(&name.to_lowercase())+ ),+ // The Soup domain replaces CRM associations with the associated+ // document ids before querying, so an unresolved one matches nothing.+ DocumentLiteral::CrmAssociated(_) => "FALSE".to_string(),}}@@ -965,11 +974,10 @@ fn sql_string_literal(value: &str) -> String {format!("'{}'", value.replace('\'', "''"))}-/// Renders the calendar-event filter bind-free, like every other arm of the-/// hand-numbered grouped query: `push_bind` placeholders would start at `$1`-/// and collide with the positionally-bound user id. The notification clauses-/// reference `$1` as the requesting user, which both this query and-/// `cursor_soup` guarantee.+/// Renders the calendar-event filter bind-free: in the hand-numbered grouped+/// query, `push_bind` placeholders would start at `$1` and collide with the+/// positionally-bound user id. The notification clauses reference `$1` as the+/// requesting user, which both this query and `cursor_soup` guarantee.fn build_calendar_event_filter(ast: Option<&Expr<CalendarEventLiteral>>) -> String {let Some(expr) = ast else {return String::new();@@ -1396,11 +1404,12 @@ fn project_top_where_clause() -> String {)}-fn build_query(- filter_ast: &EntityFilterAst,+fn build_query<'a>(+ filter_ast: &'a EntityFilterAst,exclude_frecency: bool,sort_method: SimpleSortMethod,-) -> QueryBuilder<'_, Postgres> {+ document_ids: &mut DocumentIdArrays,+) -> QueryBuilder<'a, Postgres> {let mut builder = sqlx::QueryBuilder::new(PREFIX);let include_initiatives = initiative_opted_in(filter_ast.initiative_filter.as_deref())@@ -1521,7 +1530,7 @@ fn build_query(builder.push(DOCUMENT_TASK_PROPERTY_JOINS);}builder.push(document_top_where_clause(sort_method));- builder.push(build_document_filter(document_filter));+ builder.push(build_document_filter(document_filter, Some(document_ids)));builder.push(build_properties_filter(filter_ast.properties_filter.as_deref(),"d.id",@@ -1980,7 +1989,15 @@ async fn expanded_dynamic_cursor_soup_hydrated(let assignees_property_id = SystemPropertyKey::ASSIGNEES_UUID;let completed_option_id = StatusOption::COMPLETED_UUID.to_string();- let items = build_query(cursor.filter(), exclude_frecency, *cursor.sort_method())+ // Document id arrays follow the eight fixed binds.+ let mut document_ids = DocumentIdArrays::starting_at(9);+ let mut builder = build_query(+ cursor.filter(),+ exclude_frecency,+ *cursor.sort_method(),+ &mut document_ids,+ );+ let mut query = builder.build().bind(user_id.as_ref()).bind(sort_method_str)@@ -1989,7 +2006,11 @@ async fn expanded_dynamic_cursor_soup_hydrated(.bind(cursor_id_str).bind(completed_option_id).bind(status_property_id)- .bind(assignees_property_id)+ .bind(assignees_property_id);+ for ids in document_ids.into_binds() {+ query = query.bind(ids);+ }+ let items = query// Unnamed statement: the SQL text varies per filter shape and per// interpolated literal (dates change daily), so a cached prepared// statement is rarely reused but flips to a generic plan after five@@ -2123,6 +2144,7 @@ fn build_grouped_query<'a>(exclude_frecency: bool,grouping: &'a GroupingConfig,sort_method: SimpleSortMethod,+ document_ids: &mut DocumentIdArrays,) -> (QueryBuilder<'a, Postgres>, Option<String>) {let mut builder = sqlx::QueryBuilder::new(PREFIX);@@ -2177,7 +2199,10 @@ fn build_grouped_query<'a>(builder.push(DOCUMENT_TASK_PROPERTY_JOINS);}builder.push(document_top_where_clause(sort_method));- builder.push(build_document_filter(filter_ast.document_filter.as_deref()));+ builder.push(build_document_filter(+ filter_ast.document_filter.as_deref(),+ Some(document_ids),+ ));builder.push(build_properties_filter(filter_ast.properties_filter.as_deref(),"d.id",@@ -2384,15 +2409,19 @@ pub async fn expanded_dynamic_cursor_soup_grouped(let assignees_property_id = SystemPropertyKey::ASSIGNEES_UUID;let completed_option_id = StatusOption::COMPLETED_UUID.to_string();+ // Document id arrays follow the ten fixed binds.+ let mut document_ids = DocumentIdArrays::starting_at(11);let (mut query_builder, entity_type_bind) = build_grouped_query(cursor.filter(),exclude_frecency,&grouping,*cursor.sort_method(),+ &mut document_ids,);// Keep the reserved $2 sort slot even though candidates now specialize it away.- // $9 is bound unconditionally (NULL when not in single-group mode) so $10 stays aligned.+ // $9 and $10 are bound unconditionally (NULL when unused) so the document+ // id arrays after them keep their slots.let mut query = query_builder.build_query_as::<'_, GroupedSoupRow>().bind(user_id.as_ref())@@ -2403,11 +2432,11 @@ pub async fn expanded_dynamic_cursor_soup_grouped(.bind(completed_option_id).bind(status_property_id).bind(assignees_property_id)- .bind(grouping.group_key.clone());-- // Bind entity_type as $10 when property grouping with entity_type filter- if let Some(ref et) = entity_type_bind {- query = query.bind(et.clone());+ .bind(grouping.group_key.clone())+ // The entity type of property grouping with an entity type filter.+ .bind(entity_type_bind);+ for ids in document_ids.into_binds() {+ query = query.bind(ids);}let rows: Vec<GroupedSoupRow> = querydiff --git a/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic/document_ids.rs b/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic/document_ids.rsnew file mode 100644index 0000000000..e2106a9436--- /dev/null+++ b/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic/document_ids.rs@@ -0,0 +1,99 @@+//! Bound id sets for the expanded document filter.+//!+//! A resolved CRM association constrains documents to an OR over every+//! associated id, and its negation to an AND over every excluded id; either+//! can name thousands of documents. Rendered one equality per id, the SQL+//! text grows with the set. Instead, each run of two or more ids of the same+//! polarity becomes one `d.id = ANY($n::text[])` over a bound array, so the+//! SQL keeps a fixed size and the indexed column stays uncast.+//! Document ids are never NULL and neither are the bound elements, so `= ANY`+//! and its negation agree with the equalities they replace.++use filter_ast::{Expr, ExprFrame};+use item_filters::ast::document::DocumentLiteral;+use recursion::CollapsibleExt;+use uuid::Uuid;++#[cfg(test)]+mod test;++/// The id arrays a query binds after its fixed positional parameters.+#[derive(Debug)]+pub(in crate::outbound::pg_soup_repo) struct DocumentIdArrays {+ first_slot: usize,+ arrays: Vec<Vec<String>>,+}++impl DocumentIdArrays {+ /// Number the arrays from `$first_slot`, the slot after the query's+ /// fixed binds.+ pub(in crate::outbound::pg_soup_repo) fn starting_at(first_slot: usize) -> Self {+ Self {+ first_slot,+ arrays: Vec::new(),+ }+ }++ /// The arrays to bind, in slot order.+ pub(in crate::outbound::pg_soup_repo) fn into_binds(self) -> Vec<Vec<String>> {+ self.arrays+ }++ fn bind(&mut self, ids: &[Uuid]) -> String {+ let slot = self.first_slot + self.arrays.len();+ self.arrays.push(ids.iter().map(Uuid::to_string).collect());+ format!("d.id = ANY(${slot}::text[])")+ }+}++/// A rendered subtree, with an id run kept open so its parent can extend it.+enum Fragment {+ /// The document is one of these ids.+ AnyOf(Vec<Uuid>),+ /// The document is none of these ids.+ NoneOf(Vec<Uuid>),+ Sql(String),+}++/// Renders `expr`, whose negations must already sit on its literals, binding+/// its id runs into `arrays`. `literal_sql` renders every other literal and+/// any lone id.+pub(super) fn render(+ expr: &Expr<DocumentLiteral>,+ arrays: &mut DocumentIdArrays,+ literal_sql: impl Fn(DocumentLiteral) -> String,+) -> String {+ let mut sql = |fragment: Fragment| match fragment {+ Fragment::AnyOf(ids) => any_of(&ids, arrays, &literal_sql),+ Fragment::NoneOf(ids) => format!("(NOT {})", any_of(&ids, arrays, &literal_sql)),+ Fragment::Sql(sql) => sql,+ };+ let root = expr.collapse_frames(|frame| match frame {+ ExprFrame::Literal(DocumentLiteral::Id(id)) => Fragment::AnyOf(vec![id]),+ ExprFrame::Literal(literal) => Fragment::Sql(literal_sql(literal)),+ ExprFrame::Or(Fragment::AnyOf(mut a), Fragment::AnyOf(b)) => {+ a.extend(b);+ Fragment::AnyOf(a)+ }+ ExprFrame::And(Fragment::NoneOf(mut a), Fragment::NoneOf(b)) => {+ a.extend(b);+ Fragment::NoneOf(a)+ }+ ExprFrame::Not(Fragment::AnyOf(ids)) => Fragment::NoneOf(ids),+ ExprFrame::And(a, b) => Fragment::Sql(format!("({} AND {})", sql(a), sql(b))),+ ExprFrame::Or(a, b) => Fragment::Sql(format!("({} OR {})", sql(a), sql(b))),+ ExprFrame::Not(a) => Fragment::Sql(format!("(NOT {})", sql(a))),+ });+ sql(root)+}++fn any_of(+ ids: &[Uuid],+ arrays: &mut DocumentIdArrays,+ literal_sql: &impl Fn(DocumentLiteral) -> String,+) -> String {+ match ids {+ [id] => literal_sql(DocumentLiteral::Id(*id)),+ ids => arrays.bind(ids),+ }+}diff --git a/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic/document_ids/test.rs b/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic/document_ids/test.rsnew file mode 100644index 0000000000..22d7b73de1--- /dev/null+++ b/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic/document_ids/test.rs@@ -0,0 +1,513 @@+use super::DocumentIdArrays;+use crate::domain::models::grouping::ItemGroupingInfo;+use crate::outbound::pg_soup_repo::expanded::dynamic::{+ ExpandedDynamicCursorArgs, GroupedDynamicCursorArgs, build_document_filter,+ build_grouped_query, build_query, expanded_dynamic_cursor_soup,+ expanded_dynamic_cursor_soup_grouped,+};+use document_sub_type::DocumentSubType;+use filter_ast::Expr;+use item_filters::ast::{+ EntityFilterAst, calendar_event::CalendarEventLiteral, chat::ChatLiteral,+ document::DocumentLiteral, project::ProjectLiteral,+};+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use macro_user_id::user_id::MacroUserIdStr;+use models_grouping::{GroupByField, GroupingConfig};+use models_pagination::{CursorWithValAndFilter, Identify, Query, SimpleSortMethod, SortOn};+use models_soup::item::SoupItem;+use sqlx::PgPool;+use std::sync::Arc;+use system_properties::SystemPropertyKey;+use uuid::{Uuid, uuid};++const IN_A: Uuid = uuid!("11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa");+const IN_B: Uuid = uuid!("11111111-bbbb-bbbb-bbbb-bbbbbbbbbbbb");+const IN_C: Uuid = uuid!("11111111-cccc-cccc-cccc-cccccccccccc");+const IN_D: Uuid = uuid!("11111111-dddd-dddd-dddd-dddddddddddd");+const STANDALONE: Uuid = uuid!("11111111-0000-0000-0000-000000000000");+/// Exists, but the user has no access to it.+const ISOLATED: Uuid = uuid!("11111111-9999-9999-9999-999999999999");+const IN_PROGRESS: &str = "00000001-0000-0000-0002-000000000002";++/// `count` ids that name no document.+fn absent(tag: u128, count: u128) -> Vec<Uuid> {+ (0..count)+ .map(|i| Uuid::from_u128((tag << 64) | i))+ .collect()+}++/// `ids` among thousands that name no document.+fn among_absent(ids: &[Uuid], tag: u128) -> Vec<Uuid> {+ [ids, &absent(tag, 5_000)].concat()+}++/// A balanced OR over `ids`, as the domain builds an association; no ids is+/// the nil id an empty association becomes.+fn any_of(ids: &[Uuid]) -> Expr<DocumentLiteral> {+ match ids {+ [] => Expr::val(DocumentLiteral::Id(Uuid::nil())),+ [id] => Expr::val(DocumentLiteral::Id(*id)),+ ids => {+ let (a, b) = ids.split_at(ids.len() / 2);+ Expr::or(any_of(a), any_of(b))+ }+ }+}++fn strings(ids: &[Uuid]) -> Vec<String> {+ ids.iter().map(Uuid::to_string).collect()+}++fn render(expr: &Expr<DocumentLiteral>) -> (String, Vec<Vec<String>>) {+ let mut arrays = DocumentIdArrays::starting_at(9);+ let sql = build_document_filter(Some(expr), Some(&mut arrays));+ (sql, arrays.into_binds())+}++/// Soup restricted to the documents `filter` matches.+fn documents(filter: Expr<DocumentLiteral>) -> EntityFilterAst {+ EntityFilterAst {+ document_filter: Some(Arc::new(filter)),+ chat_filter: Some(Arc::new(Expr::val(ChatLiteral::Importance(false)))),+ project_filter: Some(Arc::new(Expr::val(ProjectLiteral::Importance(false)))),+ calendar_event_filter: Some(Arc::new(Expr::val(CalendarEventLiteral::Id(Uuid::nil())))),+ ..Default::default()+ }+}++fn tasks(filter: Expr<DocumentLiteral>) -> EntityFilterAst {+ documents(Expr::and(+ Expr::val(DocumentLiteral::SubType(DocumentSubType::Task)),+ filter,+ ))+}++fn status(entity_type: Option<&str>) -> GroupByField {+ GroupByField::Property {+ property_definition_id: SystemPropertyKey::STATUS_UUID,+ entity_type: entity_type.map(str::to_owned),+ }+}++fn user() -> MacroUserIdStr<'static> {+ MacroUserIdStr::parse_from_str("macro|[email protected]").unwrap()+}++#[test]+fn id_runs_bind_as_arrays_whatever_their_size() {+ let name = || Expr::val(DocumentLiteral::NameContains("acme".into()));+ for count in [2, 100, 5_000] {+ let (a, b) = (absent(1, count), absent(2, count));+ let both = [a.clone(), b.clone()].concat();+ for (expr, sql, binds) in [+ (any_of(&a), " AND d.id = ANY($9::text[])", vec![strings(&a)]),+ (+ Expr::is_not(any_of(&a)),+ " AND (NOT d.id = ANY($9::text[]))",+ vec![strings(&a)],+ ),+ (+ Expr::or(any_of(&a), any_of(&b)),+ " AND d.id = ANY($9::text[])",+ vec![strings(&both)],+ ),+ (+ Expr::and(any_of(&a), any_of(&b)),+ " AND (d.id = ANY($9::text[]) AND d.id = ANY($10::text[]))",+ vec![strings(&a), strings(&b)],+ ),+ (+ Expr::is_not(Expr::or(any_of(&a), any_of(&b))),+ " AND (NOT d.id = ANY($9::text[]))",+ vec![strings(&both)],+ ),+ (+ Expr::is_not(Expr::and(any_of(&a), any_of(&b))),+ " AND ((NOT d.id = ANY($9::text[])) OR (NOT d.id = ANY($10::text[])))",+ vec![strings(&a), strings(&b)],+ ),+ (+ Expr::and(Expr::or(any_of(&a), name()), Expr::is_not(any_of(&b))),+ " AND ((d.id = ANY($9::text[]) OR STRPOS(LOWER(d.name), 'acme') > 0) AND (NOT d.id = ANY($10::text[])))",+ vec![strings(&a), strings(&b)],+ ),+ ] {+ assert_eq!(render(&expr), (sql.to_owned(), binds), "{count} ids");+ }+ }+}++#[test]+fn lone_ids_render_inline() {+ let id = |id| Expr::val(DocumentLiteral::Id(id));+ for (expr, sql) in [+ (id(IN_A), format!(" AND d.id = '{IN_A}'")),+ (+ Expr::is_not(id(IN_A)),+ format!(" AND (NOT d.id = '{IN_A}')"),+ ),+ (any_of(&[]), format!(" AND d.id = '{}'", Uuid::nil())),+ (+ Expr::and(id(IN_A), id(IN_B)),+ format!(" AND (d.id = '{IN_A}' AND d.id = '{IN_B}')"),+ ),+ (+ Expr::and(Expr::is_not(id(IN_A)), id(IN_B)),+ format!(" AND ((NOT d.id = '{IN_A}') AND d.id = '{IN_B}')"),+ ),+ ] {+ assert_eq!(render(&expr), (sql, Vec::new()));+ }+}++#[test]+fn bind_free_rendering_keeps_every_id_inline() {+ let expr = Expr::is_not(any_of(&[IN_A, IN_B, IN_C]));+ assert_eq!(+ build_document_filter(Some(&expr), None),+ format!(+ " AND ((NOT d.id = '{IN_A}') AND ((NOT d.id = '{IN_B}') AND (NOT d.id = '{IN_C}')))"+ )+ );+}++#[test]+fn arrays_follow_each_querys_fixed_binds() {+ let render = |count| {+ let filter = tasks(Expr::and(+ any_of(&absent(1, count)),+ Expr::is_not(any_of(&absent(2, count))),+ ));+ let mut flat_ids = DocumentIdArrays::starting_at(9);+ let flat = build_query(&filter, false, SimpleSortMethod::UpdatedAt, &mut flat_ids)+ .sql()+ .to_owned();+ let grouping = GroupingConfig {+ field: status(Some("TASK")),+ group_key: None,+ per_group_limit: None,+ };+ let mut grouped_ids = DocumentIdArrays::starting_at(11);+ let (grouped, _) = build_grouped_query(+ &filter,+ false,+ &grouping,+ SimpleSortMethod::UpdatedAt,+ &mut grouped_ids,+ );+ (+ flat,+ flat_ids.into_binds().len(),+ grouped.sql().to_owned(),+ grouped_ids.into_binds().len(),+ )+ };+ let few = render(2);+ assert_eq!(few, render(5_000));+ let (flat, flat_arrays, grouped, grouped_arrays) = few;+ assert_eq!((flat_arrays, grouped_arrays), (2, 2));+ assert!(flat.contains("(d.id = ANY($9::text[]) AND (NOT d.id = ANY($10::text[])))"));+ assert!(!flat.contains("$11"));+ assert!(grouped.contains("ep.entity_type = $10::property_entity_type"));+ assert!(grouped.contains("(d.id = ANY($11::text[]) AND (NOT d.id = ANY($12::text[])))"));+}++async fn flat_page(+ pool: &PgPool,+ cursor: Query<Uuid, SimpleSortMethod, EntityFilterAst>,+ limit: u16,+) -> anyhow::Result<Vec<SoupItem<()>>> {+ Ok(expanded_dynamic_cursor_soup(+ pool,+ ExpandedDynamicCursorArgs {+ user_id: user(),+ limit,+ cursor,+ exclude_frecency: false,+ },+ )+ .await?)+}++fn ids(items: &[SoupItem<()>]) -> Vec<Uuid> {+ items.iter().map(Identify::id).collect()+}++#[sqlx::test(+ fixtures("../../../../../../../macro_db_client/fixtures/mixed_items_expanded.sql"),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn flat_pages_match_bound_id_sets(pool: PgPool) -> anyhow::Result<()> {+ let set = |ids: &[Uuid], tag| any_of(&among_absent(ids, tag));+ let name = |name: &str| Expr::val(DocumentLiteral::NameContains(name.into()));+ for (label, filter, expected) in [+ // Membership never grants access: the isolated document stays out.+ (+ "association",+ set(&[IN_A, IN_B, IN_C, ISOLATED], 1),+ vec![IN_C, IN_B, IN_A],+ ),+ (+ "negated association",+ Expr::is_not(set(&[IN_A, IN_B], 1)),+ vec![STANDALONE, IN_D, IN_C],+ ),+ (+ "association minus another",+ Expr::and(set(&[IN_A, IN_B, IN_C], 1), Expr::is_not(set(&[IN_B], 2))),+ vec![IN_C, IN_A],+ ),+ (+ "either association",+ Expr::or(set(&[IN_A], 1), set(&[IN_D], 2)),+ vec![IN_D, IN_A],+ ),+ (+ "neither association",+ Expr::is_not(Expr::or(set(&[IN_A], 1), set(&[IN_D], 2))),+ vec![STANDALONE, IN_C, IN_B],+ ),+ (+ "not both associations",+ Expr::is_not(Expr::and(set(&[IN_A, IN_B], 1), set(&[IN_B, IN_C], 2))),+ vec![STANDALONE, IN_D, IN_C, IN_A],+ ),+ (+ "negated association or a name",+ Expr::or(+ Expr::is_not(set(&[IN_A, IN_B, IN_C, IN_D], 1)),+ name("document in b"),+ ),+ vec![STANDALONE, IN_B],+ ),+ (+ "association or a name, minus another",+ Expr::and(+ Expr::or(set(&[IN_A, IN_B], 1), name("standalone")),+ Expr::is_not(set(&[IN_A], 2)),+ ),+ vec![STANDALONE, IN_B],+ ),+ ("empty association", any_of(&[]), vec![]),+ (+ "negated empty association",+ Expr::is_not(any_of(&[])),+ vec![STANDALONE, IN_D, IN_C, IN_B, IN_A],+ ),+ ] {+ let cursor = Query::Sort(SimpleSortMethod::UpdatedAt, documents(filter));+ assert_eq!(+ ids(&flat_page(&pool, cursor, 50).await?),+ expected,+ "{label}"+ );+ }+ Ok(())+}++#[sqlx::test(+ fixtures("../../../../../../../macro_db_client/fixtures/mixed_items_expanded.sql"),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn flat_continuations_keep_bound_id_sets(pool: PgPool) -> anyhow::Result<()> {+ let filter = || {+ documents(Expr::and(+ any_of(&among_absent(&[STANDALONE, IN_D, IN_C, IN_B, IN_A], 1)),+ Expr::is_not(any_of(&among_absent(&[IN_C], 2))),+ ))+ };+ let mut cursor = Query::Sort(SimpleSortMethod::UpdatedAt, filter());+ let mut pages = Vec::new();+ for _ in 0..4 {+ let page = flat_page(&pool, cursor, 2).await?;+ let Some(last) = page.last() else {+ break;+ };+ cursor = Query::Cursor(CursorWithValAndFilter {+ id: last.id(),+ limit: 2,+ val: SoupItem::sort_on(SimpleSortMethod::UpdatedAt)(last),+ filter: filter(),+ });+ pages.push(ids(&page));+ }+ assert_eq!(pages, [vec![STANDALONE, IN_D], vec![IN_B, IN_A]]);+ Ok(())+}++async fn grouped_page(+ pool: &PgPool,+ cursor: Query<Uuid, SimpleSortMethod, EntityFilterAst>,+ grouping: GroupingConfig,+ limit: u16,+) -> anyhow::Result<Vec<ItemGroupingInfo>> {+ Ok(expanded_dynamic_cursor_soup_grouped(+ pool,+ GroupedDynamicCursorArgs {+ user_id: user(),+ limit,+ cursor,+ exclude_frecency: false,+ grouping,+ },+ )+ .await?+ .collect())+}++#[sqlx::test(+ fixtures(+ "../../../../../../../macro_db_client/fixtures/mixed_items_expanded.sql",+ "test/tasks.sql"+ ),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn grouped_pages_match_bound_id_sets(pool: PgPool) -> anyhow::Result<()> {+ // Of the associated tasks A, C, and D, every one but D.+ let associated = || {+ Expr::and(+ any_of(&among_absent(&[IN_A, IN_B, IN_C, IN_D, ISOLATED], 1)),+ Expr::is_not(any_of(&among_absent(&[IN_D], 2))),+ )+ };+ let by_status = vec![("", IN_A), (IN_PROGRESS, IN_C)];+ for (label, field, filter, arrays, expected) in [+ // The entity type takes `$10`, the arrays `$11` and `$12`.+ (+ "status of tasks",+ status(Some("TASK")),+ associated(),+ 2,+ by_status.clone(),+ ),+ // `$10` is NULL and unreferenced before the arrays.+ ("status", status(None), associated(), 2, by_status.clone()),+ (+ "entity type",+ GroupByField::EntityType,+ associated(),+ 2,+ vec![("document", IN_C), ("document", IN_A)],+ ),+ // `$10` is NULL, unreferenced, and the last bind.+ (+ "status without arrays",+ status(None),+ Expr::is_not(Expr::val(DocumentLiteral::Id(IN_D))),+ 0,+ by_status,+ ),+ (+ "empty association",+ GroupByField::EntityType,+ any_of(&[]),+ 0,+ vec![],+ ),+ ] {+ let filter = tasks(filter);+ let grouping = GroupingConfig {+ field,+ group_key: None,+ per_group_limit: None,+ };+ let mut document_ids = DocumentIdArrays::starting_at(11);+ build_grouped_query(+ &filter,+ false,+ &grouping,+ SimpleSortMethod::UpdatedAt,+ &mut document_ids,+ );+ assert_eq!(document_ids.into_binds().len(), arrays, "{label}");+ let cursor = Query::Sort(SimpleSortMethod::UpdatedAt, filter);+ let items = grouped_page(&pool, cursor, grouping, 50).await?;+ assert_eq!(+ items+ .iter()+ .map(|item| (item.key.as_str(), item.item.id()))+ .collect::<Vec<_>>(),+ expected,+ "{label}"+ );+ }+ Ok(())+}++/// The tasks of `task_pages.sql`, newest first.+fn task_pages() -> Vec<Uuid> {+ (1..=12)+ .rev()+ .map(|n: u32| Uuid::parse_str(&format!("33333333-0000-0000-0000-{n:012}")).unwrap())+ .collect()+}++#[sqlx::test(+ fixtures(+ "../../../../../../../macro_db_client/fixtures/mixed_items_expanded.sql",+ "test/task_pages.sql"+ ),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn grouped_continuations_keep_bound_id_sets(pool: PgPool) -> anyhow::Result<()> {+ let all_tasks = task_pages();+ let excluded = all_tasks[3];+ let expected = all_tasks+ .iter()+ .copied()+ .filter(|id| *id != excluded)+ .collect::<Vec<_>>();+ let filter = || {+ tasks(Expr::and(+ any_of(&among_absent(&all_tasks, 1)),+ Expr::is_not(any_of(&among_absent(&[excluded], 2))),+ ))+ };+ let grouping = |group_key| GroupingConfig {+ field: GroupByField::EntityType,+ group_key,+ per_group_limit: None,+ };+ let initial = grouped_page(+ &pool,+ Query::Sort(SimpleSortMethod::UpdatedAt, filter()),+ grouping(None),+ 10,+ )+ .await?;+ // The initial page holds ten of the group's eleven tasks.+ assert_eq!(+ initial+ .iter()+ .map(|item| (item.item.id(), item.total_group_count, item.index_in_group))+ .collect::<Vec<_>>(),+ expected[..10]+ .iter()+ .zip(1..)+ .map(|(id, index)| (*id, 11, index))+ .collect::<Vec<_>>()+ );+ // Loading more of the group binds its key at `$9`.+ let mut seen = initial+ .iter()+ .map(|item| item.item.id())+ .collect::<Vec<_>>();+ let mut last = initial.into_iter().last().unwrap();+ for _ in 0..4 {+ let cursor = Query::Cursor(CursorWithValAndFilter {+ id: last.item.id(),+ limit: 10,+ val: SoupItem::sort_on(SimpleSortMethod::UpdatedAt)(&last.item),+ filter: filter(),+ });+ let page = grouped_page(&pool, cursor, grouping(Some("document".to_owned())), 10).await?;+ seen.extend(page.iter().map(|item| item.item.id()));+ let Some(item) = page.into_iter().last() else {+ break;+ };+ last = item;+ }+ assert_eq!(seen, expected);+ Ok(())+}diff --git a/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic/document_ids/test/task_pages.sql b/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic/document_ids/test/task_pages.sqlnew file mode 100644index 0000000000..c950260b94--- /dev/null+++ b/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic/document_ids/test/task_pages.sql@@ -0,0 +1,22 @@+-- Applied after mixed_items_expanded: twelve accessible tasks, an hour apart,+-- more than one grouped page holds.+INSERT INTO public."Document" (id, name, owner, "createdAt", "updatedAt")+SELECT format('33333333-0000-0000-0000-%s', lpad(n::text, 12, '0')),+ format('Task %s', n),+ 'macro|[email protected]',+ '2023-02-01 00:00:00+00'::timestamptz + n * interval '1 hour',+ '2023-02-01 00:00:00+00'::timestamptz + n * interval '1 hour'+FROM generate_series(1, 12) n;++INSERT INTO public."DocumentInstance" (id, "documentId", sha)+SELECT 1000 + n, format('33333333-0000-0000-0000-%s', lpad(n::text, 12, '0')), 'sha_task'+FROM generate_series(1, 12) n;++INSERT INTO public.document_sub_type (document_id, sub_type)+SELECT format('33333333-0000-0000-0000-%s', lpad(n::text, 12, '0')), 'task'+FROM generate_series(1, 12) n;++INSERT INTO public.entity_access (entity_id, entity_type, source_id, source_type, access_level)+SELECT format('33333333-0000-0000-0000-%s', lpad(n::text, 12, '0'))::uuid, 'document',+ 'macro|[email protected]', 'user', 'view'+FROM generate_series(1, 12) n;diff --git a/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic/document_ids/test/tasks.sql b/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic/document_ids/test/tasks.sqlnew file mode 100644index 0000000000..53870f54dd--- /dev/null+++ b/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic/document_ids/test/tasks.sql@@ -0,0 +1,11 @@+-- Applied after mixed_items_expanded: its documents in A, C, and D are tasks,+-- and the task in C is in progress.+INSERT INTO public.document_sub_type (document_id, sub_type)+VALUES ('11111111-aaaa-aaaa-aaaa-aaaaaaaaaaaa', 'task'),+ ('11111111-cccc-cccc-cccc-cccccccccccc', 'task'),+ ('11111111-dddd-dddd-dddd-dddddddddddd', 'task');++INSERT INTO public.entity_properties (id, entity_id, entity_type, property_definition_id, values)+VALUES ('e0000000-0000-0000-0000-0000000000c1', '11111111-cccc-cccc-cccc-cccccccccccc', 'TASK',+ '00000001-0000-0000-0000-000000000002',+ '{"type": "SelectOption", "value": ["00000001-0000-0000-0002-000000000002"]}');diff --git a/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic/test.rs b/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic/test.rsindex fae97c6f88..f0baf24d5b 100644--- a/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic/test.rs+++ b/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic/test.rs@@ -10,8 +10,13 @@ fn grouped_access_shape() {group_key: None,per_group_limit: None,};- let (builder, _) =- build_grouped_query(&filter, false, &grouping, SimpleSortMethod::ViewedUpdated);+ let (builder, _) = build_grouped_query(+ &filter,+ false,+ &grouping,+ SimpleSortMethod::ViewedUpdated,+ &mut DocumentIdArrays::starting_at(11),+ );let candidates = builder.sql().split("GroupedItems AS").next().unwrap();assert!(!candidates.contains("AccessibleItems"));for (id, entity_type) in [("d.id", "document"), ("c.id", "chat"), ("p.id", "project")] {@@ -42,7 +47,13 @@ fn grouped_candidate_sort_shape() {group_key,per_group_limit: None,};- let (builder, entity_type) = build_grouped_query(&filter, true, &grouping, sort);+ let (builder, entity_type) = build_grouped_query(+ &filter,+ true,+ &grouping,+ sort,+ &mut DocumentIdArrays::starting_at(11),+ );let sql = builder.sql();let (candidates, rest) = sql.split_once("GroupedItems AS").unwrap();assert_eq!(entity_type.as_deref(), Some("TASK"));@@ -166,7 +177,13 @@ async fn grouped_query_explain_local(pool: PgPool) -> anyhow::Result<()> {.as_ref().map(|_| "2026-01-02T00:00:00Z".parse::<DateTime<Utc>>().unwrap());let cursor_id = grouping.group_key.as_ref().map(|_| ids[60].clone());- let (builder, entity_type) = build_grouped_query(&filter, false, &grouping, sort);+ let (builder, entity_type) = build_grouped_query(+ &filter,+ false,+ &grouping,+ sort,+ &mut DocumentIdArrays::starting_at(11),+ );// Dynamic AST/grouping SQL cannot use a compile-time macro. Mirror// production's positional binds, including unused reserved slots.let sql = format!(@@ -174,7 +191,7 @@ async fn grouped_query_explain_local(pool: PgPool) -> anyhow::Result<()> {builder.sql());for repetition in 1..=3 {- let mut query = sqlx::query_scalar::<_, serde_json::Value>(&sql)+ let query = sqlx::query_scalar::<_, serde_json::Value>(&sql).bind("macro|[email protected]").bind(sort.to_string()).bind(50_i64)@@ -183,10 +200,8 @@ async fn grouped_query_explain_local(pool: PgPool) -> anyhow::Result<()> {.bind(StatusOption::COMPLETED_UUID.to_string()).bind(SystemPropertyKey::STATUS_UUID).bind(SystemPropertyKey::ASSIGNEES_UUID)- .bind(grouping.group_key.clone());- if let Some(ref entity_type) = entity_type {- query = query.bind(entity_type);- }+ .bind(grouping.group_key.clone())+ .bind(entity_type.clone());let plan = query.persistent(false).fetch_one(&pool).await?;println!("EXPLAIN {label} {sort} repetition={repetition}: {plan}");}@@ -199,20 +214,35 @@ async fn grouped_query_explain_local(pool: PgPool) -> anyhow::Result<()> {fn initiatives_are_opt_in_and_share_the_existing_sql_pagination() {let mut filter = EntityFilterAst::default();assert!(- !build_query(&filter, false, SimpleSortMethod::UpdatedAt)- .sql()- .contains("FROM initiative")+ !build_query(+ &filter,+ false,+ SimpleSortMethod::UpdatedAt,+ &mut DocumentIdArrays::starting_at(9),+ )+ .sql()+ .contains("FROM initiative"));filter.initiative_filter = Some(Arc::new(Expr::is_not(Expr::val(InitiativeLiteral::Include,))));assert!(- !build_query(&filter, false, SimpleSortMethod::UpdatedAt)- .sql()- .contains("FROM initiative")+ !build_query(+ &filter,+ false,+ SimpleSortMethod::UpdatedAt,+ &mut DocumentIdArrays::starting_at(9),+ )+ .sql()+ .contains("FROM initiative"));filter.initiative_filter = Some(Arc::new(Expr::val(InitiativeLiteral::Include)));- let query = build_query(&filter, false, SimpleSortMethod::UpdatedAt);+ let query = build_query(+ &filter,+ false,+ SimpleSortMethod::UpdatedAt,+ &mut DocumentIdArrays::starting_at(9),+ );let (candidates, details) = query.sql().split_once("Combined AS").unwrap();assert!(candidates.contains("FROM initiative i"));assert!(candidates.contains("LIMIT $3"));diff --git a/crates/soup/src/outbound/pg_soup_repo/expanded/tests.rs b/crates/soup/src/outbound/pg_soup_repo/expanded/tests.rsindex 0fafb694c0..7e8b4458f4 100644--- a/crates/soup/src/outbound/pg_soup_repo/expanded/tests.rs+++ b/crates/soup/src/outbound/pg_soup_repo/expanded/tests.rs@@ -5898,6 +5898,7 @@ async fn test_dyn_filter_by_not_document_sub_type_task(db: PgPool) -> anyhow::Refn mock_empty_ast() -> EntityFilterAst {EntityFilterAst {+ crm_association: None,document_filter: None,calendar_event_filter: None,project_filter: None,diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.mdindex 3d23d2011e..b457ced11a 100644--- a/docs/AGENT_GUIDE/surfaces.md+++ b/docs/AGENT_GUIDE/surfaces.md@@ -2037,18 +2037,48 @@ four fields sit side by side, label over value, and the rest wait behindpipeline. Inside Customers, the header's `Open <pipeline>` button opens it. The`Pipelines` caret header collapses and expands the cards, like the Discussionheader; both start expanded on each visit. The-section is absent when the record is in no pipeline. Team lists the contacts with `Add contact`. Emails keeps the-`Signal`/`All` and `Team`/`Me` toggles. Files lists non-task documents whose-`Companies` property references the company, plus attachments of emails with-its domains. Tasks is the Tasks list scoped to the `Companies` property; its-`New task` composer pre-fills the company. Calls lists calls linked to the-company, including those linked automatically from their participants. The side-panel keeps Properties and Sharing.+section is absent when the record is in no pipeline.+Team lists the contacts with `Add contact`. Emails keeps the+`Signal`/`All` and `Team`/`Me` toggles; `Team` shows teammates' threads even to+a viewer with no connected mailbox. Files, Tasks, and Calls list items+*associated* with the company: its `Companies` property names the company, its+`Contacts` property names one of the company's contacts, or it @mentions (or a+message attaches) the company or one of those contacts. Contacts beyond the Team+tab's first page count, hidden contacts count only for team admins and owners,+and an item matching several ways appears once. Files lists non-task documents+plus attachments of emails with the company's domains. Tasks is the Tasks list+with that scope, grouping, and Load more; `Search tasks` matches task names+within the scope (not content). Its `New task` composer pre-fills the company.+Calls includes calls linked automatically from their participants and calls+whose thread mentions the company. The side panel keeps Properties and Sharing,+and adds **References**: associated items of any type (documents, tasks,+channel messages, email threads and calls with the property, events, chats,+projects, and companies or contacts whose properties or Discussion name the+company) as compact icon-and-name rows, paged as it scrolls. A channel message+row opens its thread; a reply surfaces as its thread's row. A document+Discussion message makes its document the item. Initiatives and database rows+are not listed.+When a record list fails to refresh (for example, the record became+inaccessible), it replaces its rows with `Couldn't load this list.` and+`Retry` reloads it; a failed later page keeps the rows and shows `Couldn't+load more.`A contact has the same layout with `Overview`, `Emails`, `Files`, `Tasks` and`Calls`: Overview pills show the email, the company (opens it) and `Last-interacted`, followed by the contact's Pipelines cards. Files and Calls match on the contact's `Contacts` property and, for-files, attachments of emails with its address. Tasks created from a contact also-reference its company. The side panel keeps Sharing (admins only).+interacted`, followed by the contact's Pipelines cards. Its Files, Tasks, Calls,+and References show items associated with the contact itself (its `Contacts`+property or an @mention of it), not everything associated with its company;+Files also includes attachments of emails with its address. Tasks created from a+contact also reference its company. The side panel keeps Sharing (admins only)+and adds References.++Mentioning a company or contact with `@` in a document or task records it as a+reference of that record (removing the chip removes it) without sharing the+document, inviting anyone, or notifying the contact; channel and Discussion+messages record their CRM mentions when sent or edited. Open record lists+refresh after a CRM mention or a `Companies`/`Contacts` property changes. To+verify, mention a contact in a document, then check the contact's and its+company's References and Files without reloading; remove the chip and confirm it+drops out.Company and contact pages have a **Discussion** section built from the samemessage conversation as a document's Discussion: threaded replies, reactions,diff --git a/docs/CRM_REFERENCES_SCOPE.md b/docs/CRM_REFERENCES_SCOPE.mdnew file mode 100644index 0000000000..7f7e019fb2--- /dev/null+++ b/docs/CRM_REFERENCES_SCOPE.md@@ -0,0 +1,278 @@+# CRM company and contact references scope++Implement the References section and complete associated-item membership for+CRM companies and contacts. This spans reference recording, authorized Soup filtering, both query transports,+and CRM presentation. Adding the existing References component alone will not+satisfy the task.++The code observations below were made at `9af01f1155` on October 7, 2026.++## Required membership++All alternatives below are OR conditions, evaluated before pagination. Other+view filters and source permissions still apply.++| Record | Include an accessible source item when |+| --- | --- |+| Company | Its Companies property contains the company; its Contacts property contains a contact belonging to the company; it references the company; or it references a contact belonging to the company. |+| Contact | Its Contacts property contains the contact, or it references the contact. |++Use the owning CRM record IDs and company membership. A contact query does not+inherit every item associated with its company. Do not equate contacts across+teams using email addresses or use a partially loaded Team tab as the complete+set of company contacts.++Deduplicate associated items by their canonical source entity identity. Matching+both properties, several contacts, or several mentions must not produce repeated+items or consume multiple page slots. References may retain individual message+destinations for navigation, but repeated occurrences in the same source should+not produce duplicate rows.++Preserve the existing email participant scopes and the additional email-attachment+behavior in Files. Those are separate existing inclusion rules, not replacements+for the task's property/reference union.++## Existing implementation and gaps++| Area | Evidence and implication |+| --- | --- |+| Record UI | `features/crm/views/company-detail.tsx` and `contact-detail.tsx` have References TODOs in their floating information panels. Reuse that placement for this task, including embedded and standalone records. |+| Files and Calls | `features/crm/queries/record-items.ts` matches the current record's one system property; Files also includes email attachments. There is no company-contact expansion or incoming-reference predicate. |+| Tasks | `features/crm/record-tasks-adapter.tsx` passes a single `TaskReferenceScope`. `features/tasks-view/queries/use-tasks-query.ts` filters fetched, local-search, continuation, and optimistic rows through property-only membership. A server-only fix would still lose mention-only tasks. `task-query.ts` and `task-search.ts` also encode the single property constraint. |+| References UI | `lib/core/component/References.tsx` reads an unpaginated attachment-reference endpoint. Its generic-reference navigation only opens documents. It cannot represent the complete associated-item contract as-is. |+| Existing reference reads | `crates/channels/src/outbound/pg_channels_repo.rs::get_attachment_references` reads `comms_attachments` and `comms_entity_mentions`. Channel rows check active membership and deleted messages. The generic-source SQL has no viewer/source ACL predicate; the service currently forwards its results. Do not expose that raw result as an authorized CRM feed. |+| CRM mention vocabulary | `packages/lexical-core/utils/mentions.ts`, the editor mention plugin, and `crates/messages/src/domain/mentions.rs` already recognize `crm_company` and `crm_contact`. The reference lookup passes unknown type strings through, so a blanket claim that the backend cannot accept CRM targets is inaccurate. |+| Document mention recording | In `MentionsMenu/utils/mentionHandlers.ts`, CRM contacts return after inserting a chip without calling `trackMention`; company selection falls through to tracking the target as `document`. These are concrete gaps in this insertion path. The backend document-creation tracker can separately extract canonical CRM types, so audit creation, editing, paste, and removal instead of assuming every path fails identically. |+| Soup architecture | `crates/item_filters/src/ast.rs` has property filters but no cross-entity incoming-reference/CRM-association selector. Soup fans out to other domain services; its SQL is not the only candidate source. Property-based pruning can skip sources that have references but no matching property rows. |+| Transport and cache | Additions must reach REST `ApiEntityFilterAst`, `graphql_soup_filter_input`, the shared frontend GraphQL AST compiler, grouped queries, cursors, and generated schemas. `useSoupAstItemsQuery` can choose either transport. |++Frontend paths in this table are relative to `apps/web/src`.++## Implementation slices++### 1. Define and authorize the association query++Add a typed association/reference filter to the existing Soup query contract.+The exact type and wire name are implementation choices, but callers must be+able to express the required OR union and compose it with document subtype,+status, grouping, sorting, and other existing constraints.++Keep CRM record visibility, owning-team checks, hidden-record rules, and CRM+enablement policy in CRM/domain services. Use their authorized capability to+expand a company to its eligible contacts. Apply the current policy for hidden+contacts rather than silently widening access for ordinary members.++The hexagonal boundary was checked for this scope: inbound adapters should parse+requests and forward identity/receipts, domain services should authorize and+orchestrate, and outbound adapters should implement set-based reads behind+domain ports. Reference edge reads belong behind an owning-domain contract;+Soup composes the result. Do not import another domain's outbound adapter or+add per-contact HTTP calls. A server-side join or equivalent set-based read must+cover contacts beyond any frontend page limit.++### 2. Filter all relevant Soup candidate sources before limits++Reuse `entity_properties`, `comms_entity_mentions`, and applicable attachment+edges. No new relationship store is indicated. Existing mention indexes cover+target type/ID and source type/ID; assess query plans before adding indexes.++Implement property-or-reference matching inside the authorized candidate query,+before sorting, per-source limits, grouping, counts, and cursor construction.+Preserve the predicate in continuation cursors. Deduplicate with semi-joins or+equivalent set semantics, not by concatenating independently limited lists in+the browser.++Audit every participating source, including document/task, channel message or+thread, call, and other property/reference-bearing Soup types. The task says+any entity: do not silently hard-code a documents-and-calls-only result. Audit+`SoupRequest` sub-request builders and property-less exclusion logic so mention+matches are not pruned, and excluded entity types cannot become unfiltered feeds.++For message sources, retain the actual message, thread, and parent identities.+Channel replies need the correct deep link; discussion messages with another+parent type must not be interpreted as channels. Use the appropriate source+authorization and lifecycle checks. Access to a company or contact never grants+access to the document, message, channel, or other source that mentions it.++Key entry points:++- `crates/item_filters/src/ast.rs` and the affected literal modules.+- `crates/soup/src/domain/models.rs`, `domain/service.rs`, and domain ports.+- `crates/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs`, grouped/unexpanded+ equivalents where the new selector is supported, and delegated source queries.+- CRM directory/access ports and the owning reference read adapter.+- `crates/soup/src/inbound/axum_router.rs` and+ `crates/graphql_soup_filter_input/src/lib.rs`.++### 3. Record CRM references correctly++Correct the verified mention-insertion gaps using the canonical CRM target types.+Preserve reference occurrence IDs so deletion removes the correct edge. Recording+a CRM reference must not invoke file sharing, invite the contact, or notify an+external person. Cover document and task editors and channel/discussion creation,+editing, and removal. Check paste/card and server-created markdown paths that+already extract CRM references; avoid double recording them.++The current insertion behavior means older documents may have missing or wrongly+typed CRM edges. Determine whether historical repair is needed and report the+coverage limitation separately from the new-write fix. Do not infer CRM edges+from every `document`-typed row with a coincidentally matching ID. Any backfill+needs source-content verification and a bounded, resumable design; it is a+separate rollout decision, not an automatic production mutation in this task.++### 4. Wire the CRM sections and shared clients++Add References to the existing floating information panel in both detail views.+Inject the production source/navigation through `crm-adapter.ts` and+`context/crm-context.tsx`; keep views independent of concrete service clients.+Reuse shared reference rows and item navigation where suitable, but use an+authorized, paginated source. Show loading, empty, failure/retry, and load-more+states without treating a failed query as an empty list.++Expose the full property-or-reference association union, and use its relevant+type-restricted subset for the existing Files, Tasks, and Calls sections. Keep+the full associated-item feed able to represent types without their own record+tab. The References section should make those items reachable; do not drop them+because they are not files, tasks, or calls.++Extend the Tasks source contract so server-authorized mention matches survive+row assembly and grouped continuation. Scope local search and optimistic inserts+without admitting unrelated cached tasks. Preserve task creation's current+Companies/Contacts defaults. Task search must retain the same association scope;+do not silently fall back to property-only results. If the current OpenSearch+path cannot express it, use an explicit server-backed scoped path or implement+the missing scope support, with complete pagination rather than searching only+one loaded page.++Extend `lib/queries/soup/graphql/ast.ts` and transport tests. Regenerate REST+models as needed, export the GraphQL SDL with the documented command, then run+`bun gen-graphql` in `apps/web`. Preserve normalized entity identities; query+membership is not a new global entity fact. Verify refresh after property and+mention changes, contact/company switching, and permission changes.++### 5. Verify the contract and update the app guide++| Regression case | Required result |+| --- | --- |+| Four company rules independently | Each produces a match; contact-only links work without a Companies property. |+| Two contact rules independently | Both match; company-only and sibling-contact-only items do not. |+| Several paths or repeated references | One associated item per source identity; stable page boundaries. |+| Large company and small page size | Contacts beyond the first UI page and items beyond the first result page remain discoverable. |+| Unauthorized source or target | No source content, identifiers, previews, or counts leak; disabled/hidden CRM and other-team cases honor policy. |+| Deleted/removed data | Deleted source messages/documents and removed mentions stop matching; revoked access is respected. |+| Message references | Root/reply destinations navigate correctly; non-channel discussion parents are handled explicitly. |+| Both transports and grouped Tasks | Membership, sort, grouping/counts, and continuation agree; mention-only rows survive frontend filters. |+| Editing and refresh | Creating/removing CRM mentions and changing properties refresh the relevant lists without a reload. |+| Existing record behavior | Emails, email attachments in Files, task creation defaults, call links, and embedded/standalone navigation continue to work. |++Run meaningful domain allow/deny tests, SQLx integration tests for the joins and+cursor behavior, and focused CRM/Tasks/mention/GraphQL compiler tests. Run Rust+package tests from the root with `SQLX_OFFLINE` unset; read package names from+their manifests. Generate SQLx metadata through the documented workspace+workflow rather than editing cache files. Run TypeScript checking, affected+package tests, and `just check`.++Exercise the resulting UI against the changed backend in an isolated local+stack, including company/contact References, Files, Tasks, Calls, and message+navigation. A frontend talking only to the deployed dev backend cannot verify+new query behavior. Update the CRM section in `docs/AGENT_GUIDE/surfaces.md` and+any changed mention/navigation guide. Report blocked checks precisely.++## Delivery boundary++This is one feature with five reviewable slices, with the largest work in the+authorized query and reference-recording paths. It does not require a CRM+pipeline/database redesign or a new service. The proposed UI placement uses the+existing References placeholders and preserves the current top-level tabs.++## Implementation decisions++Recorded after implementation.++**Contract.** `EntityFilterAst` gained `crma` (`CrmAssociation`: `{ company }` or+`{ contact }`), an AND scope over every Soup source, and the document literal+`crm` with the same value, which composes inside a document tree. Files uses the+literal so it can OR the association with the email-attachment participant rule;+Calls, Tasks, and References use the scope. Both reach REST (`ApiEntityFilterAst`),+GraphQL (`crmAssociation`, `crmAssociated`), and the frontend GraphQL compiler. A+document `nc` (name contains) literal was added for scoped task search.++**Resolution.** `SoupImpl` resolves every named record before any source query:+`CrmService::resolve_association` authorizes the record with the viewer-scoped+contact-listing policy (membership of a CRM-enabled team; hidden companies and+contacts only for admins and owners; team-scoped bots restricted to their team)+and returns the company with all of its visible contacts, or the single contact.+An invisible record is `404` (`SoupErr::CrmRecordNotFound`), never an empty+page. Edges are then read as complete sets: `SoupRepo::crm_property_edges`+(Companies/Contacts values, backed by two new partial GIN indexes like the+assignee/status/project ones) and `ChannelListService::get_reference_sources` in+the channels domain, which owns `comms_entity_mentions`; it returns documents+and undeleted messages that mention or attach a target, with message thread and+parent identity. Soup groups the edges per source and ANDs an id set into each+source tree (the favorites precedent), so each source's own access checks,+filters, sort, limit, grouping, counts, and cursor apply after the association.+Cursors keep the unresolved record, so every page re-authorizes. Frecency,+touched, and notified sorts, unexpanded (`expand=false`) requests, and the work+feed reject associations with a 400. Grouped queries resolve without a team+receipt (viewer scope).++**Source mapping.** Property rows map by entity type (document/task, chat,+project, initiative, database row, calendar event, email thread, call, channel,+CRM company, CRM contact); users are not a Soup source. A document mention maps+to the document. A channel message maps to its top-level thread row (a reply to+its root), so it navigates to the thread. A discussion message maps to its+parent document, initiative, call, CRM company, or CRM contact; a record's own+discussion or property is not its association. Foreign entities and agent+sessions carry no association.++**Reference recording.** Document and task editors now record CRM company and+contact chips as `crm_company` / `crm_contact` mentions with a mention id, so+removal deletes the edge; companies no longer call the document share/attach+callback. Message editors already record CRM mentions on send and edit. Routed+documents (`/app/drive/md/...`) previously recorded no mentions of any type: the+mentions menu read its source from the legacy block context, which those routes+lack. The menu now takes the source from the editing surface. Recording+publishes the existing `mention.created` event only; nothing is shared, invited,+or notified. Mentions, CRM property saves, message edits and deletes, and sends+that mention or attach a CRM record refresh the mounted CRM-associated lists on+both transports.++**Frontend.** Files, Calls, and Tasks use the association. Tasks pass a `crm`+scope to the Tasks source: server rows and grouped continuations are not+re-filtered by property; optimistic inserts are admitted only when the task's+own property names the record; search runs the scoped Soup query with the `nc`+literal (names only, complete cursor pagination) instead of the search service.+Both detail views add a References section to the floating information panel,+listing the full union (all sources plus CRM contacts) with loading, empty,+error/retry, and load-more states, through `createRecordReferences` in the CRM+context. Its rows use the shared list's condensed narrow layout (icon and name)+so task properties do not crowd the panel; the full-width tabs are unchanged.++**Sources References cannot list.** Initiatives and database rows are opt-in+Soup sources, like agent sessions and CRM contacts: the association constrains+them only when a request asks for them. `ApiEntityFilterAst` has no initiative+or database-row field, and the References body asks for neither on GraphQL, so+an initiative or database row that names or references the record is not+listed. This affects only References; Files, Tasks, and Calls never include+those types.++**List failures.** The Soup facade exposes `isFetchNextPageError` from both+transports. A failed continuation page keeps the loaded rows and retries that+page; any other failure, including a refetch after the record became+inaccessible (`404`), replaces the rows with the list error, and Retry+refetches the query. A GraphQL transport failure with current cached results+still keeps them, as before.++**Email without a mailbox.** A CRM-scoped email query reads teammates'+mailboxes, but `SoupRequest::build_email_request` skipped email for any caller+without a linked mailbox, so such a teammate's company and contact Emails `Team`+tabs were always empty. It now skips only requests without a CRM scope;+CRM-scoped requests still go through email's CRM scope authorization.++**Historical data.** Existing documents can lack CRM edges: contact chips were+never tracked, and company chips were stored as `document` mentions. Soup only+matches `crm_company` and `crm_contact` edges, so mistyped rows are ignored+rather than guessed. Repairing them needs a separate, resumable backfill that+re-extracts mentions from document content (the lexical extractor already+emits canonical CRM types) and replaces only verified rows; it is not part of+this change.diff --git a/packages/sdk/generated/storage/index.ts b/packages/sdk/generated/storage/index.tsindex 8d64b3834f..920b4dd31b 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-tsexport { type Options, Sdk } from './sdk.gen';-export type { AccessiblePipeline, AccessLevel, ActiveCallsResponse, ActiveCallSummary, ActiveMeeting, ActiveMeetingsResponse, 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, AnchorResponse, AnnotationIncrementalUpdate, Answer, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelParticipant, ApiChannelWithLatest, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, AppliedOps, ApplyCrmPipelineOpsData, ApplyCrmPipelineOpsResponse, ApplyCrmPipelineOpsResponses, ApplyDatabaseOpsData, ApplyDatabaseOpsError, ApplyDatabaseOpsErrors, ApplyDatabaseOpsResponse, ApplyDatabaseOpsResponses, ApplyOpsRequest, ApplyOpsResponse, ApproveHarnessPairingData, ApproveHarnessPairingError, ApproveHarnessPairingErrors, ApproveHarnessPairingResponse, ApproveHarnessPairingResponses, ApprovePairingRequest, AttachmentChange, AttendeeResponseStatus, Audience, Awareness, AwarenessRelay, BasicDocument, BasicDocumentSubType, BomPart, BookingTarget, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotOwnerProfile, 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, CallRecordGuest, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, CancelSlackImportData, CancelSlackImportErrors, CancelSlackImportResponse, CancelSlackImportResponses, CardPosition, CastVerdict, CellValue, CellWrite, ChangedFileDto, ChangesetDto, ChangesetSourceDto, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelFilters, ChannelJoinCodeResponse, ChannelLabel, ChannelLabelRule, ChannelLabelsList, ChannelMessage, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPictureChangedMetadata, 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, CollaborateFormData, CollaborateFormError, CollaborateFormErrors, CollaborateFormResponse, CollaborateFormResponses, CollabSurfaceResponse, CollabSurfaceTokenResponse, Column, ColumnCast, ColumnChange, ColumnChangeKind, ColumnConfig, ColumnConversion, ColumnConversionRequest, ColumnDetail, ColumnKind, ColumnProtection, ColumnResult, CommandFailure, CommandRejectedMetadata, CommittedChange, CompleteSlackImportUploadsData, CompleteSlackImportUploadsErrors, CompleteSlackImportUploadsResponse, CompleteSlackImportUploadsResponses, CompleteUploads, ConferenceProvider, Conjunction, ConversationId, ConversationKind, ConversationMetadata, ConversationProgress, ConversationSeal, ConversationStatus, ConvertDatabaseColumnData, ConvertDatabaseColumnError, ConvertDatabaseColumnErrors, ConvertDatabaseColumnResponse, ConvertDatabaseColumnResponses, ConvertedCell, 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, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateCrmPipelineData, CreateCrmPipelineResponse, CreateCrmPipelineResponses, CreateDatabaseData, CreateDatabaseError, CreateDatabaseErrors, CreateDatabaseRequest, CreateDatabaseResponse, CreateDatabaseResponses, CreateDatabaseWebhookData, CreateDatabaseWebhookError, CreateDatabaseWebhookErrors, CreateDatabaseWebhookRequest, CreateDatabaseWebhookResponse, CreateDatabaseWebhookResponses, CreatedDatabaseWebhookResponse, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreatedPairing, CreatedUserApiKey, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateForm, CreateFormData, CreateFormError, CreateFormErrors, CreateFormResponse, CreateFormResponses, CreateHarnessPairingData, CreateHarnessPairingError, CreateHarnessPairingErrors, CreateHarnessPairingResponse, CreateHarnessPairingResponses, CreateImport, CreateInitiativeData, CreateInitiativeError, CreateInitiativeErrors, CreateInitiativeRequest, CreateInitiativeResponse, CreateInitiativeResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateMeetingRequest, CreatePairingRequest, CreatePipeline, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSlackImportData, CreateSlackImportErrors, CreateSlackImportResponse, CreateSlackImportResponses, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateToken, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateUserApiKeyData, CreateUserApiKeyError, CreateUserApiKeyErrors, CreateUserApiKeyRequest, CreateUserApiKeyResponse, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmStageInput, CrmStageResponse, CrmStagesResponse, CrmTeamSettingsResponse, CustomSpeakerAssignment, Database, DatabaseDetail, DatabaseOp, DatabaseView, DatabaseWebhookDeliveryResponse, DatabaseWebhookPayloadProblem, DatabaseWebhookResponse, DataType, DateOperator, DeclineCallData, DeclineCallError, DeclineCallErrors, DeclineCallResponse, DeclineCallResponses, DeclineRingData, DeclineRingError, DeclineRingErrors, DeclineRingResponse, DeclineRingResponses, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelError, DeleteChannelLabelErrors, DeleteChannelLabelResponse, DeleteChannelLabelResponses, DeleteChannelResponse, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceError, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponse, DeleteCollabSurfaceResponses, DeleteDatabaseWebhookData, DeleteDatabaseWebhookError, DeleteDatabaseWebhookErrors, DeleteDatabaseWebhookResponse, DeleteDatabaseWebhookResponses, 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, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteSelfHarnessData, DeleteSelfHarnessError, DeleteSelfHarnessErrors, DeleteSelfHarnessResponse, DeleteSelfHarnessResponses, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserApiKeyData, DeleteUserApiKeyError, DeleteUserApiKeyErrors, DeleteUserApiKeyResponse, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DeliverDatabaseWebhookData, DeliverDatabaseWebhookError, DeliverDatabaseWebhookErrors, DeliverDatabaseWebhookResponse, DeliverDatabaseWebhookResponses, 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, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditMyFormResponseData, EditMyFormResponseError, EditMyFormResponseErrors, EditMyFormResponseResponse, EditMyFormResponseResponses, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmailFollowup, EmailFollowupCommand, EmailFollowupResponse, EmailReminderCondition, EmailReminderPage, EmailReminderSummary, EmptyResponse, EnsureCollabSurfaceData, EnsureCollabSurfaceError, EnsureCollabSurfaceErrors, EnsureCollabSurfaceRequest, EnsureCollabSurfaceResponse, EnsureCollabSurfaceResponses, EnsureStarterHandlerData, EnsureStarterHandlerErrors, EnsureStarterHandlerResponse, EnsureStarterHandlerResponses, EntityFilters, EntityKind, 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, EntityRef, 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, FileChangeKindDto, FileSystemNodeWithIds, FileType, FileTypeUpdate, FilterCondition, FilterGroup, FilterNode, FilterTest, FinalizeSlackImportData, FinalizeSlackImportErrors, FinalizeSlackImportResponse, FinalizeSlackImportResponses, FolderItem, FollowupState, ForeignEntity, ForeignEntityFilters, Form, FormAccess, FormCollaboration, FormDetail, FormErrorCode, FormErrorResponse, FormLayout, FormPublicationProblem, FormQuestionDetail, FormResponse, FormSection, FormSectionDetail, FormSource, FormStatus, FormTally, Formula, 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, GetBotOwnerProfilesData, GetBotOwnerProfilesError, GetBotOwnerProfilesErrors, GetBotOwnerProfilesResponse, GetBotOwnerProfilesResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, 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, GetCrmPipelineData, GetCrmPipelineResponse, GetCrmPipelineResponses, GetCrmPipelineRowsData, GetCrmPipelineRowsResponse, GetCrmPipelineRowsResponses, GetCrmPipelineTableData, GetCrmPipelineTableResponse, GetCrmPipelineTableResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDatabaseData, GetDatabaseError, GetDatabaseErrors, GetDatabasePermissionsData, GetDatabasePermissionsError, GetDatabasePermissionsErrors, GetDatabasePermissionsResponse, GetDatabasePermissionsResponses, GetDatabaseQueryData, GetDatabaseQueryError, GetDatabaseQueryErrors, GetDatabaseQueryResponse, GetDatabaseQueryResponses, GetDatabaseResponse, GetDatabaseResponses, GetDatabaseRowHistoryData, GetDatabaseRowHistoryError, GetDatabaseRowHistoryErrors, GetDatabaseRowHistoryResponse, GetDatabaseRowHistoryResponses, GetDatabaseTableChangesData, GetDatabaseTableChangesError, GetDatabaseTableChangesErrors, GetDatabaseTableChangesResponse, GetDatabaseTableChangesResponses, GetDatabaseViewPositionsData, GetDatabaseViewPositionsError, GetDatabaseViewPositionsErrors, GetDatabaseViewPositionsResponse, GetDatabaseViewPositionsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, 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, GetEmailFollowupData, GetEmailFollowupError, GetEmailFollowupErrors, GetEmailFollowupResponse, GetEmailFollowupResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceError, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponse, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetFormData, GetFormError, GetFormErrors, GetFormPermissionsData, GetFormPermissionsError, GetFormPermissionsErrors, GetFormPermissionsResponse, GetFormPermissionsResponses, GetFormResponse, GetFormResponses, GetFormResponseSummaryData, GetFormResponseSummaryError, GetFormResponseSummaryErrors, GetFormResponseSummaryResponse, GetFormResponseSummaryResponses, GetFormTallyData, GetFormTallyError, GetFormTallyErrors, GetFormTallyResponse, GetFormTallyResponses, GetGithubPullRequestChangesData, GetGithubPullRequestChangesError, GetGithubPullRequestChangesErrors, GetGithubPullRequestChangesPatchData, GetGithubPullRequestChangesPatchError, GetGithubPullRequestChangesPatchErrors, GetGithubPullRequestChangesPatchResponse, GetGithubPullRequestChangesPatchResponses, GetGithubPullRequestChangesResponse, GetGithubPullRequestChangesResponses, GetGithubPullRequestData, GetGithubPullRequestError, GetGithubPullRequestErrors, GetGithubPullRequestFacetsData, GetGithubPullRequestFacetsError, GetGithubPullRequestFacetsErrors, GetGithubPullRequestFacetsResponse, GetGithubPullRequestFacetsResponses, GetGithubPullRequestResponse, GetGithubPullRequestResponses, GetGithubPullRequestTasksData, GetGithubPullRequestTasksError, GetGithubPullRequestTasksErrors, GetGithubPullRequestTasksResponse, GetGithubPullRequestTasksResponses, 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, GetMyFormResponseData, GetMyFormResponseError, GetMyFormResponseErrors, GetMyFormResponseResponse, GetMyFormResponseResponses, 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, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessError, GetSelfHarnessErrors, GetSelfHarnessResponse, GetSelfHarnessResponses, GetSlackImportData, GetSlackImportErrors, GetSlackImportResponse, GetSlackImportResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubLabelFacet, GithubPullRequest, GithubPullRequestChangesPatchResponse, GithubPullRequestChangesResponse, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestFacets, GithubPullRequestLabel, GithubPullRequestReview, GithubPullRequestReviewDecision, GithubPullRequestReviewState, GithubPullRequestsResponse, GithubPullRequestTasks, GithubPullRequestTasksRequest, GithubPullRequestTasksResponse, GithubPullRequestUser, GithubRepositoryFacet, GithubUserFacet, GitRefDto, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, GuestId, GuestJoinRequest, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, Harness, HarnessAgent, HarnessId, HarnessOwner, HarnessSession, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, ImportCounters, ImportDatabaseTableData, ImportDatabaseTableError, ImportDatabaseTableErrors, ImportDatabaseTableResponse, ImportDatabaseTableResponses, ImportedAuthor, ImportError, ImportLimits, ImportPage, ImportProgress, ImportTable, ImportWarning, InferColumnTypeOutcome, InferColumnTypeRequest, InferDatabaseColumnTypeData, InferDatabaseColumnTypeError, InferDatabaseColumnTypeErrors, InferDatabaseColumnTypeResponse, InferDatabaseColumnTypeResponses, InFlightTurnSummary, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InitialPropertyValue, InitiativeDetail, InitiativeFilters, InitiativeId, InitiativeList, InitiativeSummary, InputReceivedMetadata, InstallSyncData, InstallSyncErrors, InteractionReason, InvalidDatabaseWebhookPayloadResponse, InviteMeetingRequest, InviteMeetingUsersRequest, Item, ItemWithUserAccessLevel, JobId, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JobStatus, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, KeySegment, Lane, LaneKey, LatestMessage, LayoutProblem, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkShare, ListAccessibleFormsData, ListAccessibleFormsError, ListAccessibleFormsErrors, ListAccessibleFormsResponse, ListAccessibleFormsResponses, ListAgentsData, ListAgentsError, ListAgentsErrors, ListAgentsResponse, ListAgentsResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListChannelLabelsData, ListChannelLabelsError, ListChannelLabelsErrors, ListChannelLabelsResponse, ListChannelLabelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmPipelinesData, ListCrmPipelinesResponse, ListCrmPipelinesResponses, ListDatabaseColumnCastsData, ListDatabaseColumnCastsError, ListDatabaseColumnCastsErrors, ListDatabaseColumnCastsResponse, ListDatabaseColumnCastsResponses, ListDatabasesData, ListDatabasesError, ListDatabasesErrors, ListDatabasesResponse, ListDatabasesResponses, ListDatabaseWebhooksData, ListDatabaseWebhooksError, ListDatabaseWebhooksErrors, ListDatabaseWebhooksResponse, ListDatabaseWebhooksResponse2, ListDatabaseWebhooksResponses, ListedDatabase, ListedForm, ListEmailRemindersData, ListEmailRemindersError, ListEmailRemindersErrors, ListEmailRemindersResponse, ListEmailRemindersResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListFormsData, ListFormsError, ListFormsErrors, ListFormsResponse, ListFormsResponses, ListHarnessAgentsData, ListHarnessAgentsError, ListHarnessAgentsErrors, ListHarnessAgentsResponse, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesError, ListHarnessesErrors, ListHarnessesResponse, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsError, ListHarnessSessionsErrors, ListHarnessSessionsResponse, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesError, ListInitiativesErrors, ListInitiativesResponse, ListInitiativesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListSlackImportsData, ListSlackImportsResponse, ListSlackImportsResponses, ListTeamCalendarData, ListTeamCalendarResponse, ListTeamCalendarResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponse, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, Meeting, MeetingCancelData, MeetingCancelError, MeetingCancelErrors, MeetingCancelPreparationData, MeetingCancelPreparationError, MeetingCancelPreparationErrors, MeetingCancelPreparationResponse, MeetingCancelPreparationResponses, MeetingCancelResponse, MeetingCancelResponses, MeetingCreateData, MeetingCreateError, MeetingCreateErrors, MeetingCreateResponse, MeetingCreateResponses, MeetingGuestJoinData, MeetingGuestJoinError, MeetingGuestJoinErrors, MeetingGuestJoinResponse, MeetingGuestJoinResponses, MeetingGuestParticipantsData, MeetingGuestParticipantsError, MeetingGuestParticipantsErrors, MeetingGuestParticipantsResponse, MeetingGuestParticipantsResponses, MeetingInviteData, MeetingInviteError, MeetingInviteErrors, MeetingInvitePermissions, MeetingInvitePermissionsData, MeetingInvitePermissionsError, MeetingInvitePermissionsErrors, MeetingInvitePermissionsResponse, MeetingInvitePermissionsResponses, MeetingInviteResponse, MeetingInviteResponses, MeetingInviteUsersData, MeetingInviteUsersError, MeetingInviteUsersErrors, MeetingInviteUsersResponse, MeetingInviteUsersResponses, MeetingJoinData, MeetingJoinError, MeetingJoinErrors, MeetingJoinResponse, MeetingJoinResponses, MeetingLeaveData, MeetingLeaveError, MeetingLeaveErrors, MeetingLeaveResponse, MeetingLeaveResponses, MeetingListActiveData, MeetingListActiveError, MeetingListActiveErrors, MeetingListActiveResponse, MeetingListActiveResponses, MeetingListData, MeetingListError, MeetingListErrors, MeetingListResponse, MeetingListResponses, MeetingLookupData, MeetingLookupError, MeetingLookupErrors, MeetingLookupResponse, MeetingLookupResponses, MeetingParticipant, MeetingParticipants, MeetingParticipantsData, MeetingParticipantsError, MeetingParticipantsErrors, MeetingParticipantsResponse, MeetingParticipantsResponses, MeetingPreparation, MeetingPrepareData, MeetingPrepareError, MeetingPrepareErrors, MeetingPrepareResponse, MeetingPrepareResponses, MeetingShareData, MeetingShareError, MeetingShareErrors, MeetingShareResponse, MeetingShareResponses, MeetingsResponse, MeetingToken, MeetingUpdateData, MeetingUpdateError, MeetingUpdateErrors, MeetingUpdateResponse, MeetingUpdateResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Message, MessageAttachment, MessageAttachmentCreatedMetadata, MessageAttachmentRemovedMetadata, MessageChange, MessageCursor, MessageDeletedMetadata, MessageDirection, MessageEvent, MessageEventAttachment, MessageListItem, MessageMentionedMetadata, MessagePage, MessageParent, MessagePatch, MessagePatchedMetadata, MessagePostedMetadata, MessageThread, MessageThreadPreview, MessageTimelineData, MessageTimelineEntriesData, MessageTimelineEntriesResponse, MessageTimelineEntriesResponses, MessageTimelineEntry, MessageTimelinePage, MessageTimelineQuery, MessageTimelineResponse, MessageTimelineResponses, MessageTopicEvent, MyResponse, NewAttachment, NewColumn, NewOption, NewThreadAnchor, NewView, NotificationFilters, NotificationState, NumberOperator, OpBatch, Operator, OpRefusalResponse, OpResult, OptionRef, PairingDetails, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageNotificationPolicy, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PendingClaimResponse, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, Pipeline, PipelineRecordType, PipelineSharing, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessage, PostMessageNotificationPolicy, PostSoupAstRequest, PostSoupRequest, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresenceOperator, PresignedUrl, PreviewSmartTagData, PreviewSmartTagError, PreviewSmartTagErrors, PreviewSmartTagResponse, PreviewSmartTagResponses, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyDefinitionWithOptions, PropertyFilter, PropertyInput, PropertyOption, PropertyOptionValue, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesError, PutCrmTeamStagesErrors, PutCrmTeamStagesResponse, PutCrmTeamStagesResponses, PutFormLayoutData, PutFormLayoutError, PutFormLayoutErrors, PutFormLayoutResponse, PutFormLayoutResponses, QueryCrmPipelineRowsData, QueryCrmPipelineRowsResponse, QueryCrmPipelineRowsResponses, QueryDefinition, QuestionLayout, QuestionOption, QuestionTally, ReactionInput, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, RegisterSlackImportUploadsData, RegisterSlackImportUploadsErrors, RegisterSlackImportUploadsResponse, RegisterSlackImportUploadsResponses, RegisterUploads, 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, RenameCrmPipelineData, RenameCrmPipelineResponse, RenameCrmPipelineResponses, RenamePipeline, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ReplaceCrmStagesRequest, RequestedHarnessScope, RequestedLayout, ResetCrmTeamStagesData, ResetCrmTeamStagesError, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponse, ResetCrmTeamStagesResponses, ResponseStatus, ResponseSummary, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, RowChange, RowChangeKind, RowChanges, RowHistoryEntry, RowHistoryResponse, RowId, RowsChange, RowsResult, S3ObjectInfo, SaveBomPart, SaveDatabaseQueryData, SaveDatabaseQueryError, SaveDatabaseQueryErrors, SaveDatabaseQueryResponse, SaveDatabaseQueryResponses, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SavedQuery, SaveQueryRequest, SearchContactsData, SearchContactsError, SearchContactsErrors, SearchContactsResponse, SearchContactsResponse2, SearchContactsResponses, SearchState, SectionCount, 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, SetEmailFollowupData, SetEmailFollowupError, SetEmailFollowupErrors, SetEmailFollowupResponse, SetEmailFollowupResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetOperator, SetPropertyValue, Sha256Digest, ShareCrmPipelineData, ShareCrmPipelineResponse, ShareCrmPipelineResponses, ShareDatabaseAwarenessData, ShareDatabaseAwarenessError, ShareDatabaseAwarenessErrors, ShareDatabaseAwarenessResponse, ShareDatabaseAwarenessResponses, SharedEmailFilter, SharePermissionV2, SharePipeline, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SkippedCell, SlackCompleteRequest, SlackCreateRequest, SlackRegisterRequest, SlackTimestamp, SlackUserId, SmartTagChannelMatch, SmartTagPreview, SortDirection, SortKey, SoupAgentSessionSoupPropertiesField, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordGuest, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmContactSoupPropertiesField, SoupCrmDomain, SoupDatabaseRowSoupPropertiesField, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupInitiativeSoupPropertiesField, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupThreadInfo, SoupThreadReply, SourceBinding, SourceId, SourceIdentity, StarterDatabase, StarterDocumentsResponse, StorageRow, StorageRows, StorageRowsQuery, StoredGithubPullRequest, StreamEventsData, StreamEventsError, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, String, Submission, SubmissionOutcome, SubmitFormResponseData, SubmitFormResponseError, SubmitFormResponseErrors, SubmitFormResponseResponse, SubmitFormResponseResponses, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, Table, TableChange, TableChanged, TableChanges, TableDetail, TableResult, TableVersion, TagFilterMode, TakenId, TallyBucket, TallyValue, TaskFilters, TeamCalendarContent, TeamCalendarCoverage, TeamCalendarDetails, TeamCalendarItem, TeamCalendarMember, TeamCalendarPage, TeamCalendarSharing, TeamOutOfOfficeItem, TeamOutOfOfficeResponse, TeamRole, TextOperator, ThreadAnchor, ThreadOrigin, ThreadPatch, ThreadState, TimelineActivity, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TouchedColumn, TouchedRow, TranscribeDictationData, TranscribeDictationError, TranscribeDictationErrors, TranscribeDictationResponse, TranscribeDictationResponses, TranscribeResponse, TranscriptSegmentRequest, TrashCrmPipelineData, TrashCrmPipelineResponse, TrashCrmPipelineResponses, TrashPipeline, TurnEndedMetadata, TurnStartedMetadata, TurnSummary, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingInput, UndoChangeResponse, UndoDatabaseChangeData, UndoDatabaseChangeError, UndoDatabaseChangeErrors, UndoDatabaseChangeResponse, UndoDatabaseChangeResponses, UndoOutcome, UndoRefusal, UnlockedBooking, UpdateAgentData, UpdateAgentError, UpdateAgentErrors, UpdateAgentRequest, UpdateAgentResponse, UpdateAgentResponses, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateDatabasePermissionsData, UpdateDatabasePermissionsError, UpdateDatabasePermissionsErrors, UpdateDatabasePermissionsResponse, UpdateDatabasePermissionsResponses, UpdateForm, UpdateFormData, UpdateFormError, UpdateFormErrors, UpdateFormPermissionsData, UpdateFormPermissionsError, UpdateFormPermissionsErrors, UpdateFormPermissionsResponse, UpdateFormPermissionsResponses, UpdateFormResponse, UpdateFormResponses, UpdateInitiativeData, UpdateInitiativeError, UpdateInitiativeErrors, UpdateInitiativeRequest, UpdateInitiativeResponse, UpdateInitiativeResponses, UpdateMeetingRequest, UpdateOperation, UpdateSharePermissionRequestV2, UploadDescriptor, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UploadGrant, UploadId, 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, VersionedTable, View, ViewChange, ViewColumn, ViewLayout, ViewPatch, ViewPosition, ViewPositionsResponse, ViewQuery, ViewResult, ViewsResponse, WaitingForInputMetadata, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, Widget, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';+export type { AccessiblePipeline, AccessLevel, ActiveCallsResponse, ActiveCallSummary, ActiveMeeting, ActiveMeetingsResponse, 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, AnchorResponse, AnnotationIncrementalUpdate, Answer, ApiActivity, ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference, ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelDetail, ApiChannelListMessage, ApiChannelListPage, ApiChannelListParticipant, ApiChannelListType, ApiChannelParticipant, ApiChannelWithLatest, ApiEntityFilterAst, ApiGroupByField, ApiGroupMeta, ApiParticipantListRole, ApiParticipantRole, ApiPropertyEntityType, AppliedOps, ApplyCrmPipelineOpsData, ApplyCrmPipelineOpsResponse, ApplyCrmPipelineOpsResponses, ApplyDatabaseOpsData, ApplyDatabaseOpsError, ApplyDatabaseOpsErrors, ApplyDatabaseOpsResponse, ApplyDatabaseOpsResponses, ApplyOpsRequest, ApplyOpsResponse, ApproveHarnessPairingData, ApproveHarnessPairingError, ApproveHarnessPairingErrors, ApproveHarnessPairingResponse, ApproveHarnessPairingResponses, ApprovePairingRequest, AttachmentChange, AttendeeResponseStatus, Audience, Awareness, AwarenessRelay, BasicDocument, BasicDocumentSubType, BomPart, BookingTarget, Bot, BotChannel, BotChannelType, BotId, BotKind, BotOwner, BotOwnerProfile, 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, CallRecordGuest, CallRecordParticipant, CallRecordPreview, CallRecordPreviewData, CallRecordTranscriptSegment, CallStatus, CallTokenResponse, CallWebhookData, CallWebhookError, CallWebhookErrors, CallWebhookResponses, CancelSlackImportData, CancelSlackImportErrors, CancelSlackImportResponse, CancelSlackImportResponses, CardPosition, CastVerdict, CellValue, CellWrite, ChangedFileDto, ChangesetDto, ChangesetSourceDto, Channel, ChannelCreatedMetadata, ChannelDeletedMetadata, ChannelFilters, ChannelJoinCodeResponse, ChannelLabel, ChannelLabelRule, ChannelLabelsList, ChannelMessage, ChannelParticipant, ChannelParticipantAddedMetadata, ChannelParticipantRemovedMetadata, ChannelPictureChangedMetadata, 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, CollaborateFormData, CollaborateFormError, CollaborateFormErrors, CollaborateFormResponse, CollaborateFormResponses, CollabSurfaceResponse, CollabSurfaceTokenResponse, Column, ColumnCast, ColumnChange, ColumnChangeKind, ColumnConfig, ColumnConversion, ColumnConversionRequest, ColumnDetail, ColumnKind, ColumnProtection, ColumnResult, CommandFailure, CommandRejectedMetadata, CommittedChange, CompleteSlackImportUploadsData, CompleteSlackImportUploadsErrors, CompleteSlackImportUploadsResponse, CompleteSlackImportUploadsResponses, CompleteUploads, ConferenceProvider, Conjunction, ConversationId, ConversationKind, ConversationMetadata, ConversationProgress, ConversationSeal, ConversationStatus, ConvertDatabaseColumnData, ConvertDatabaseColumnError, ConvertDatabaseColumnErrors, ConvertDatabaseColumnResponse, ConvertDatabaseColumnResponses, ConvertedCell, 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, CreateCrmCompanyData, CreateCrmCompanyError, CreateCrmCompanyErrors, CreateCrmCompanyRequest, CreateCrmCompanyResponse, CreateCrmCompanyResponses, CreateCrmContactData, CreateCrmContactError, CreateCrmContactErrors, CreateCrmContactRequest, CreateCrmContactResponse, CreateCrmContactResponses, CreateCrmPipelineData, CreateCrmPipelineResponse, CreateCrmPipelineResponses, CreateDatabaseData, CreateDatabaseError, CreateDatabaseErrors, CreateDatabaseRequest, CreateDatabaseResponse, CreateDatabaseResponses, CreateDatabaseWebhookData, CreateDatabaseWebhookError, CreateDatabaseWebhookErrors, CreateDatabaseWebhookRequest, CreateDatabaseWebhookResponse, CreateDatabaseWebhookResponses, CreatedDatabaseWebhookResponse, CreateDocumentData, CreateDocumentError, CreateDocumentErrors, CreateDocumentRequest, CreateDocumentResponse, CreateDocumentResponseData, CreateDocumentResponses, CreatedPairing, CreatedUserApiKey, CreateEntityMentionData, CreateEntityMentionError, CreateEntityMentionErrors, CreateEntityMentionRequest, CreateEntityMentionResponse, CreateEntityMentionResponse2, CreateEntityMentionResponses, CreateForm, CreateFormData, CreateFormError, CreateFormErrors, CreateFormResponse, CreateFormResponses, CreateHarnessPairingData, CreateHarnessPairingError, CreateHarnessPairingErrors, CreateHarnessPairingResponse, CreateHarnessPairingResponses, CreateImport, CreateInitiativeData, CreateInitiativeError, CreateInitiativeErrors, CreateInitiativeRequest, CreateInitiativeResponse, CreateInitiativeResponses, CreateInstructionsDocumentResponse, CreateInstructionsHandlerData, CreateInstructionsHandlerError, CreateInstructionsHandlerErrors, CreateInstructionsHandlerResponse, CreateInstructionsHandlerResponses, CreateMarkdownDocumentRequest, CreateMarkdownDocumentResponse, CreateMarkdownHandlerData, CreateMarkdownHandlerError, CreateMarkdownHandlerErrors, CreateMarkdownHandlerResponse, CreateMarkdownHandlerResponses, CreateMeetingRequest, CreatePairingRequest, CreatePipeline, CreateProjectHandlerData, CreateProjectHandlerError, CreateProjectHandlerErrors, CreateProjectHandlerResponse, CreateProjectHandlerResponses, CreateProjectRequest, CreateProjectResponse, CreateSkillHandlerData, CreateSkillHandlerError, CreateSkillHandlerErrors, CreateSkillHandlerResponse, CreateSkillHandlerResponses, CreateSkillRequest, CreateSkillResponse, CreateSlackImportData, CreateSlackImportErrors, CreateSlackImportResponse, CreateSlackImportResponses, CreateSnippetHandlerData, CreateSnippetHandlerError, CreateSnippetHandlerErrors, CreateSnippetHandlerResponse, CreateSnippetHandlerResponses, CreateSnippetRequest, CreateSnippetResponse, CreateTaskHandlerData, CreateTaskHandlerError, CreateTaskHandlerErrors, CreateTaskHandlerResponse, CreateTaskHandlerResponses, CreateTaskRequest, CreateTaskResponse, CreateToken, CreateUnthreadedAnchorRequest, CreateUnthreadedAnchorResponse, CreateUnthreadedPdfAnchorRequest, CreateUserApiKeyData, CreateUserApiKeyError, CreateUserApiKeyErrors, CreateUserApiKeyRequest, CreateUserApiKeyResponse, CreateUserApiKeyResponses, CreateViewHandlerData, CreateViewHandlerError, CreateViewHandlerErrors, CreateViewHandlerResponse, CreateViewHandlerResponses, CreateViewRequest, CreateWebhookData, CreateWebhookError, CreateWebhookErrors, CreateWebhookRequest, CreateWebhookResponse, CreateWebhookResponse2, CreateWebhookResponses, CrmAssociation, CrmCompanyFilters, CrmCompanyResponse, CrmContactResponse, CrmDomainResponse, CrmPermissionRole, CrmStageInput, CrmStageResponse, CrmStagesResponse, CrmTeamSettingsResponse, CustomSpeakerAssignment, Database, DatabaseDetail, DatabaseOp, DatabaseView, DatabaseWebhookDeliveryResponse, DatabaseWebhookPayloadProblem, DatabaseWebhookResponse, DataType, DateOperator, DeclineCallData, DeclineCallError, DeclineCallErrors, DeclineCallResponse, DeclineCallResponses, DeclineRingData, DeclineRingError, DeclineRingErrors, DeclineRingResponse, DeclineRingResponses, DeleteAnchorData, DeleteAnchorError, DeleteAnchorErrors, DeleteAnchorResponse, DeleteAnchorResponses, DeleteCallRecordData, DeleteCallRecordError, DeleteCallRecordErrors, DeleteCallRecordResponse, DeleteCallRecordResponses, DeleteChannelData, DeleteChannelError, DeleteChannelErrors, DeleteChannelLabelData, DeleteChannelLabelError, DeleteChannelLabelErrors, DeleteChannelLabelResponse, DeleteChannelLabelResponses, DeleteChannelResponse, DeleteChannelResponses, DeleteCollabSurfaceData, DeleteCollabSurfaceError, DeleteCollabSurfaceErrors, DeleteCollabSurfaceResponse, DeleteCollabSurfaceResponses, DeleteDatabaseWebhookData, DeleteDatabaseWebhookError, DeleteDatabaseWebhookErrors, DeleteDatabaseWebhookResponse, DeleteDatabaseWebhookResponses, 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, DeleteProjectHandlerData, DeleteProjectHandlerError, DeleteProjectHandlerErrors, DeleteProjectHandlerResponse, DeleteProjectHandlerResponses, DeleteSelfHarnessData, DeleteSelfHarnessError, DeleteSelfHarnessErrors, DeleteSelfHarnessResponse, DeleteSelfHarnessResponses, DeleteUnthreadedAnchorRequest, DeleteUnthreadedAnchorResponse, DeleteUnthreadedPdfAnchorRequest, DeleteUserApiKeyData, DeleteUserApiKeyError, DeleteUserApiKeyErrors, DeleteUserApiKeyResponse, DeleteUserApiKeyResponses, DeleteUserDocumentViewLocationData, DeleteUserDocumentViewLocationError, DeleteUserDocumentViewLocationErrors, DeleteUserDocumentViewLocationResponse, DeleteUserDocumentViewLocationResponses, DeleteViewHandlerData, DeleteViewHandlerError, DeleteViewHandlerErrors, DeleteViewHandlerResponses, DeleteWebhookData, DeleteWebhookError, DeleteWebhookErrors, DeleteWebhookResponse, DeleteWebhookResponses, DeliverDatabaseWebhookData, DeliverDatabaseWebhookError, DeliverDatabaseWebhookErrors, DeliverDatabaseWebhookResponse, DeliverDatabaseWebhookResponses, 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, EditDocumentData, EditDocumentError, EditDocumentErrors, EditDocumentResponse, EditDocumentResponse2, EditDocumentResponses, EditDocumentServiceArgs, EditMyFormResponseData, EditMyFormResponseError, EditMyFormResponseErrors, EditMyFormResponseResponse, EditMyFormResponseResponses, EditPdfAnchorRequest, EditPdfPlaceableCommentAnchorRequest, EditProjectV2Data, EditProjectV2Error, EditProjectV2Errors, EditProjectV2Response, EditProjectV2Responses, EditThreadV2Data, EditThreadV2Error, EditThreadV2Errors, EditThreadV2Response, EditThreadV2Responses, EmailFilters, EmailFollowup, EmailFollowupCommand, EmailFollowupResponse, EmailReminderCondition, EmailReminderPage, EmailReminderSummary, EmptyResponse, EnsureCollabSurfaceData, EnsureCollabSurfaceError, EnsureCollabSurfaceErrors, EnsureCollabSurfaceRequest, EnsureCollabSurfaceResponse, EnsureCollabSurfaceResponses, EnsureStarterHandlerData, EnsureStarterHandlerErrors, EnsureStarterHandlerResponse, EnsureStarterHandlerResponses, EntityFilters, EntityKind, 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, EntityRef, 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, FileChangeKindDto, FileSystemNodeWithIds, FileType, FileTypeUpdate, FilterCondition, FilterGroup, FilterNode, FilterTest, FinalizeSlackImportData, FinalizeSlackImportErrors, FinalizeSlackImportResponse, FinalizeSlackImportResponses, FolderItem, FollowupState, ForeignEntity, ForeignEntityFilters, Form, FormAccess, FormCollaboration, FormDetail, FormErrorCode, FormErrorResponse, FormLayout, FormPublicationProblem, FormQuestionDetail, FormResponse, FormSection, FormSectionDetail, FormSource, FormStatus, FormTally, Formula, 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, GetBotOwnerProfilesData, GetBotOwnerProfilesError, GetBotOwnerProfilesErrors, GetBotOwnerProfilesResponse, GetBotOwnerProfilesResponses, GetCallRecordData, GetCallRecordError, GetCallRecordErrors, GetCallRecordResponse, GetCallRecordResponses, GetChannelAttachmentsData, GetChannelAttachmentsError, GetChannelAttachmentsErrors, GetChannelAttachmentsResponse, GetChannelAttachmentsResponses, GetChannelData, GetChannelError, GetChannelErrors, GetChannelJoinLinkData, GetChannelJoinLinkError, GetChannelJoinLinkErrors, GetChannelJoinLinkResponse, GetChannelJoinLinkResponses, 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, GetCrmPipelineData, GetCrmPipelineResponse, GetCrmPipelineResponses, GetCrmPipelineRowsData, GetCrmPipelineRowsResponse, GetCrmPipelineRowsResponses, GetCrmPipelineTableData, GetCrmPipelineTableResponse, GetCrmPipelineTableResponses, GetCrmTeamSettingsData, GetCrmTeamSettingsError, GetCrmTeamSettingsErrors, GetCrmTeamSettingsResponse, GetCrmTeamSettingsResponses, GetDatabaseData, GetDatabaseError, GetDatabaseErrors, GetDatabasePermissionsData, GetDatabasePermissionsError, GetDatabasePermissionsErrors, GetDatabasePermissionsResponse, GetDatabasePermissionsResponses, GetDatabaseQueryData, GetDatabaseQueryError, GetDatabaseQueryErrors, GetDatabaseQueryResponse, GetDatabaseQueryResponses, GetDatabaseResponse, GetDatabaseResponses, GetDatabaseRowHistoryData, GetDatabaseRowHistoryError, GetDatabaseRowHistoryErrors, GetDatabaseRowHistoryResponse, GetDatabaseRowHistoryResponses, GetDatabaseTableChangesData, GetDatabaseTableChangesError, GetDatabaseTableChangesErrors, GetDatabaseTableChangesResponse, GetDatabaseTableChangesResponses, GetDatabaseViewPositionsData, GetDatabaseViewPositionsError, GetDatabaseViewPositionsErrors, GetDatabaseViewPositionsResponse, GetDatabaseViewPositionsResponses, GetDocumentAnchorsData, GetDocumentAnchorsError, GetDocumentAnchorsErrors, GetDocumentAnchorsResponse, GetDocumentAnchorsResponses, GetDocumentBranchNameData, GetDocumentBranchNameError, GetDocumentBranchNameErrors, GetDocumentBranchNameResponse, GetDocumentBranchNameResponses, GetDocumentByTeamSlugData, GetDocumentByTeamSlugError, GetDocumentByTeamSlugErrors, GetDocumentByTeamSlugResponse, GetDocumentByTeamSlugResponses, 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, GetEmailFollowupData, GetEmailFollowupError, GetEmailFollowupErrors, GetEmailFollowupResponse, GetEmailFollowupResponses, GetEntityPermissionData, GetEntityPermissionErrors, GetEntityPermissionResponse, GetEntityPermissionResponses, GetForeignEntityBySourceData, GetForeignEntityBySourceError, GetForeignEntityBySourceErrors, GetForeignEntityBySourceResponse, GetForeignEntityBySourceResponses, GetForeignEntityData, GetForeignEntityError, GetForeignEntityErrors, GetForeignEntityResponse, GetForeignEntityResponses, GetFormData, GetFormError, GetFormErrors, GetFormPermissionsData, GetFormPermissionsError, GetFormPermissionsErrors, GetFormPermissionsResponse, GetFormPermissionsResponses, GetFormResponse, GetFormResponses, GetFormResponseSummaryData, GetFormResponseSummaryError, GetFormResponseSummaryErrors, GetFormResponseSummaryResponse, GetFormResponseSummaryResponses, GetFormTallyData, GetFormTallyError, GetFormTallyErrors, GetFormTallyResponse, GetFormTallyResponses, GetGithubPullRequestChangesData, GetGithubPullRequestChangesError, GetGithubPullRequestChangesErrors, GetGithubPullRequestChangesPatchData, GetGithubPullRequestChangesPatchError, GetGithubPullRequestChangesPatchErrors, GetGithubPullRequestChangesPatchResponse, GetGithubPullRequestChangesPatchResponses, GetGithubPullRequestChangesResponse, GetGithubPullRequestChangesResponses, GetGithubPullRequestData, GetGithubPullRequestError, GetGithubPullRequestErrors, GetGithubPullRequestFacetsData, GetGithubPullRequestFacetsError, GetGithubPullRequestFacetsErrors, GetGithubPullRequestFacetsResponse, GetGithubPullRequestFacetsResponses, GetGithubPullRequestResponse, GetGithubPullRequestResponses, GetGithubPullRequestTasksData, GetGithubPullRequestTasksError, GetGithubPullRequestTasksErrors, GetGithubPullRequestTasksResponse, GetGithubPullRequestTasksResponses, 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, GetMyFormResponseData, GetMyFormResponseError, GetMyFormResponseErrors, GetMyFormResponseResponse, GetMyFormResponseResponses, 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, GetRingStatusData, GetRingStatusError, GetRingStatusErrors, GetRingStatusResponse, GetRingStatusResponses, GetSelfBotData, GetSelfBotError, GetSelfBotErrors, GetSelfBotResponse, GetSelfBotResponses, GetSelfHarnessData, GetSelfHarnessError, GetSelfHarnessErrors, GetSelfHarnessResponse, GetSelfHarnessResponses, GetSlackImportData, GetSlackImportErrors, GetSlackImportResponse, GetSlackImportResponses, GetSystemSkillsHandlerData, GetSystemSkillsHandlerError, GetSystemSkillsHandlerErrors, GetSystemSkillsHandlerResponse, GetSystemSkillsHandlerResponses, GetUserDocumentsHandlerData, GetUserDocumentsHandlerError, GetUserDocumentsHandlerErrors, GetUserDocumentsHandlerResponse, GetUserDocumentsHandlerResponses, GetUserDocumentViewLocationData, GetUserDocumentViewLocationError, GetUserDocumentViewLocationErrors, GetUserDocumentViewLocationResponse, GetUserDocumentViewLocationResponses, GetUserHistoryResponse, GetViewsHandlerData, GetViewsHandlerError, GetViewsHandlerErrors, GetViewsHandlerResponse, GetViewsHandlerResponses, GetWebhookData, GetWebhookError, GetWebhookErrors, GetWebhookResponse, GetWebhookResponses, GithubLabelFacet, GithubPullRequest, GithubPullRequestChangesPatchResponse, GithubPullRequestChangesResponse, GithubPullRequestCheckRun, GithubPullRequestComment, GithubPullRequestFacets, GithubPullRequestLabel, GithubPullRequestReview, GithubPullRequestReviewDecision, GithubPullRequestReviewState, GithubPullRequestsResponse, GithubPullRequestTasks, GithubPullRequestTasksRequest, GithubPullRequestTasksResponse, GithubPullRequestUser, GithubRepositoryFacet, GithubUserFacet, GitRefDto, GroupedInitialParams, GroupedPageParams, GroupedSoupGroupPage, GroupedSoupInitialPage, GroupedSoupPage, GroupedSoupSort, GuestId, GuestJoinRequest, HandlerData, HandlerError, HandlerErrors, HandlerResponse, HandlerResponses, Harness, HarnessAgent, HarnessId, HarnessOwner, HarnessSession, HashMap, HealthHandlerData, HealthHandlerResponse, HealthHandlerResponses, HighlightType, ImportCounters, ImportDatabaseTableData, ImportDatabaseTableError, ImportDatabaseTableErrors, ImportDatabaseTableResponse, ImportDatabaseTableResponses, ImportedAuthor, ImportError, ImportLimits, ImportPage, ImportProgress, ImportTable, ImportWarning, InferColumnTypeOutcome, InferColumnTypeRequest, InferDatabaseColumnTypeData, InferDatabaseColumnTypeError, InferDatabaseColumnTypeErrors, InferDatabaseColumnTypeResponse, InferDatabaseColumnTypeResponses, InFlightTurnSummary, IngestTranscriptData, IngestTranscriptError, IngestTranscriptErrors, IngestTranscriptResponses, InitializeUserDocumentsData, InitializeUserDocumentsError, InitializeUserDocumentsErrors, InitializeUserDocumentsResponse, InitializeUserDocumentsResponses, InitialPropertyValue, InitiativeDetail, InitiativeFilters, InitiativeId, InitiativeList, InitiativeSummary, InputReceivedMetadata, InstallSyncData, InstallSyncErrors, InteractionReason, InvalidDatabaseWebhookPayloadResponse, InviteMeetingRequest, InviteMeetingUsersRequest, Item, ItemWithUserAccessLevel, JobId, JobProcessingResultHandlerData, JobProcessingResultHandlerError, JobProcessingResultHandlerErrors, JobProcessingResultHandlerResponse, JobProcessingResultHandlerResponses, JobStatus, JoinChannelByCodeData, JoinChannelByCodeError, JoinChannelByCodeErrors, JoinChannelByCodeResponses, JoinChannelData, JoinChannelError, JoinChannelErrors, JoinChannelResponses, KeySegment, Lane, LaneKey, LatestMessage, LayoutProblem, LeaveCallResponse, LeaveChannelData, LeaveChannelError, LeaveChannelErrors, LeaveChannelResponses, LeaveOrEndCallData, LeaveOrEndCallError, LeaveOrEndCallErrors, LeaveOrEndCallResponse, LeaveOrEndCallResponses, LinkShare, ListAccessibleFormsData, ListAccessibleFormsError, ListAccessibleFormsErrors, ListAccessibleFormsResponse, ListAccessibleFormsResponses, ListAgentsData, ListAgentsError, ListAgentsErrors, ListAgentsResponse, ListAgentsResponses, ListBotChannelsData, ListBotChannelsError, ListBotChannelsErrors, ListBotChannelsResponse, ListBotChannelsResponses, ListChannelLabelsData, ListChannelLabelsError, ListChannelLabelsErrors, ListChannelLabelsResponse, ListChannelLabelsResponses, ListCompanyContactsData, ListCompanyContactsError, ListCompanyContactsErrors, ListCompanyContactsResponse, ListCompanyContactsResponses, ListCrmPipelinesData, ListCrmPipelinesResponse, ListCrmPipelinesResponses, ListDatabaseColumnCastsData, ListDatabaseColumnCastsError, ListDatabaseColumnCastsErrors, ListDatabaseColumnCastsResponse, ListDatabaseColumnCastsResponses, ListDatabasesData, ListDatabasesError, ListDatabasesErrors, ListDatabasesResponse, ListDatabasesResponses, ListDatabaseWebhooksData, ListDatabaseWebhooksError, ListDatabaseWebhooksErrors, ListDatabaseWebhooksResponse, ListDatabaseWebhooksResponse2, ListDatabaseWebhooksResponses, ListedDatabase, ListedForm, ListEmailRemindersData, ListEmailRemindersError, ListEmailRemindersErrors, ListEmailRemindersResponse, ListEmailRemindersResponses, ListFavoritesData, ListFavoritesError, ListFavoritesErrors, ListFavoritesResponse, ListFavoritesResponses, ListFormsData, ListFormsError, ListFormsErrors, ListFormsResponse, ListFormsResponses, ListHarnessAgentsData, ListHarnessAgentsError, ListHarnessAgentsErrors, ListHarnessAgentsResponse, ListHarnessAgentsResponses, ListHarnessesData, ListHarnessesError, ListHarnessesErrors, ListHarnessesResponse, ListHarnessesResponses, ListHarnessSessionsData, ListHarnessSessionsError, ListHarnessSessionsErrors, ListHarnessSessionsResponse, ListHarnessSessionsResponses, ListInitiativesData, ListInitiativesError, ListInitiativesErrors, ListInitiativesResponse, ListInitiativesResponses, ListOccurrencesData, ListOccurrencesErrors, ListOccurrencesResponse, ListOccurrencesResponses, ListSlackImportsData, ListSlackImportsResponse, ListSlackImportsResponses, ListTeamCalendarData, ListTeamCalendarResponse, ListTeamCalendarResponses, ListTeamOutOfOfficeData, ListTeamOutOfOfficeErrors, ListTeamOutOfOfficeResponse, ListTeamOutOfOfficeResponses, ListUserApiKeysData, ListUserApiKeysError, ListUserApiKeysErrors, ListUserApiKeysResponse, ListUserApiKeysResponses, ListWebhooksData, ListWebhooksError, ListWebhooksErrors, ListWebhooksResponse, ListWebhooksResponse2, ListWebhooksResponses, LocationResponseData, LocationResponseV3, MacroUserIdStr, Meeting, MeetingCancelData, MeetingCancelError, MeetingCancelErrors, MeetingCancelPreparationData, MeetingCancelPreparationError, MeetingCancelPreparationErrors, MeetingCancelPreparationResponse, MeetingCancelPreparationResponses, MeetingCancelResponse, MeetingCancelResponses, MeetingCreateData, MeetingCreateError, MeetingCreateErrors, MeetingCreateResponse, MeetingCreateResponses, MeetingGuestJoinData, MeetingGuestJoinError, MeetingGuestJoinErrors, MeetingGuestJoinResponse, MeetingGuestJoinResponses, MeetingGuestParticipantsData, MeetingGuestParticipantsError, MeetingGuestParticipantsErrors, MeetingGuestParticipantsResponse, MeetingGuestParticipantsResponses, MeetingInviteData, MeetingInviteError, MeetingInviteErrors, MeetingInvitePermissions, MeetingInvitePermissionsData, MeetingInvitePermissionsError, MeetingInvitePermissionsErrors, MeetingInvitePermissionsResponse, MeetingInvitePermissionsResponses, MeetingInviteResponse, MeetingInviteResponses, MeetingInviteUsersData, MeetingInviteUsersError, MeetingInviteUsersErrors, MeetingInviteUsersResponse, MeetingInviteUsersResponses, MeetingJoinData, MeetingJoinError, MeetingJoinErrors, MeetingJoinResponse, MeetingJoinResponses, MeetingLeaveData, MeetingLeaveError, MeetingLeaveErrors, MeetingLeaveResponse, MeetingLeaveResponses, MeetingListActiveData, MeetingListActiveError, MeetingListActiveErrors, MeetingListActiveResponse, MeetingListActiveResponses, MeetingListData, MeetingListError, MeetingListErrors, MeetingListResponse, MeetingListResponses, MeetingLookupData, MeetingLookupError, MeetingLookupErrors, MeetingLookupResponse, MeetingLookupResponses, MeetingParticipant, MeetingParticipants, MeetingParticipantsData, MeetingParticipantsError, MeetingParticipantsErrors, MeetingParticipantsResponse, MeetingParticipantsResponses, MeetingPreparation, MeetingPrepareData, MeetingPrepareError, MeetingPrepareErrors, MeetingPrepareResponse, MeetingPrepareResponses, MeetingShareData, MeetingShareError, MeetingShareErrors, MeetingShareResponse, MeetingShareResponses, MeetingsResponse, MeetingToken, MeetingUpdateData, MeetingUpdateError, MeetingUpdateErrors, MeetingUpdateResponse, MeetingUpdateResponses, MentionPreviewsData, MentionPreviewsErrors, MentionPreviewsResponse, MentionPreviewsResponses, Message, MessageAttachment, MessageAttachmentCreatedMetadata, MessageAttachmentRemovedMetadata, MessageChange, MessageCursor, MessageDeletedMetadata, MessageDirection, MessageEvent, MessageEventAttachment, MessageListItem, MessageMentionedMetadata, MessagePage, MessageParent, MessagePatch, MessagePatchedMetadata, MessagePostedMetadata, MessageThread, MessageThreadPreview, MessageTimelineData, MessageTimelineEntriesData, MessageTimelineEntriesResponse, MessageTimelineEntriesResponses, MessageTimelineEntry, MessageTimelinePage, MessageTimelineQuery, MessageTimelineResponse, MessageTimelineResponses, MessageTopicEvent, MyResponse, NewAttachment, NewColumn, NewOption, NewThreadAnchor, NewView, NotificationFilters, NotificationState, NumberOperator, OpBatch, Operator, OpRefusalResponse, OpResult, OptionRef, PairingDetails, Params, ParticipantRole, PatchBotRequest, PatchChannelData, PatchChannelError, PatchChannelErrors, PatchChannelRequest, PatchChannelResponse, PatchChannelResponses, PatchMessageNotificationPolicy, PatchProjectRequestV2, PatchThreadRequestV2, PatchViewHandlerData, PatchViewHandlerError, PatchViewHandlerErrors, PatchViewHandlerResponses, PatchWebhookData, PatchWebhookError, PatchWebhookErrors, PatchWebhookRequest, PatchWebhookResponse, PatchWebhookResponses, PdfAnchor, PdfAnchorId, PdfHighlightAnchor, PdfHighlightAnchorRequest, PdfHighlightRect, PdfHighlightRectAnchorRequest, PdfPlaceableCommentAnchor, PendingClaimResponse, PermanentlyDeleteDocumentData, PermanentlyDeleteDocumentError, PermanentlyDeleteDocumentErrors, PermanentlyDeleteDocumentResponse, PermanentlyDeleteDocumentResponses, PermanentlyDeleteProjectData, PermanentlyDeleteProjectError, PermanentlyDeleteProjectErrors, PermanentlyDeleteProjectResponse, PermanentlyDeleteProjectResponses, PinnedItem, PinRequest, Pipeline, PipelineRecordType, PipelineSharing, PostActivityData, PostActivityError, PostActivityErrors, PostActivityRequest, PostActivityResponse, PostActivityResponses, PostChannelBotWebhookData, PostChannelBotWebhookError, PostChannelBotWebhookErrors, PostChannelBotWebhookResponse, PostChannelBotWebhookResponses, PostGroupedSoupAstGroupPageRequest, PostGroupedSoupAstInitialRequest, PostGroupedSoupAstRequest, PostItemsSoupAstData, PostItemsSoupAstError, PostItemsSoupAstErrors, PostItemsSoupAstGroupedData, PostItemsSoupAstGroupedError, PostItemsSoupAstGroupedErrors, PostItemsSoupAstGroupedResponse, PostItemsSoupAstGroupedResponses, PostItemsSoupAstResponse, PostItemsSoupAstResponses, PostItemsSoupData, PostItemsSoupError, PostItemsSoupErrors, PostItemsSoupResponse, PostItemsSoupResponses, PostMessage, PostMessageNotificationPolicy, PostSoupAstRequest, PostSoupRequest, PresaveDocumentHandlerData, PresaveDocumentHandlerError, PresaveDocumentHandlerErrors, PresaveDocumentHandlerResponse, PresaveDocumentHandlerResponses, PreSaveDocumentRequest, PreSaveDocumentResponse, PreSaveDocumentResponseData, PresenceOperator, PresignedUrl, PreviewSmartTagData, PreviewSmartTagError, PreviewSmartTagErrors, PreviewSmartTagResponse, PreviewSmartTagResponses, Project, ProjectDeleteResponseData, ProjectDocumentStatus, ProjectFilters, ProjectPreview, ProjectPreviewData, PropertyDefinition, PropertyDefinitionWithOptions, PropertyFilter, PropertyInput, PropertyOption, PropertyOptionValue, PropertyOwner, PropertyValue, PutCrmTeamSettingsData, PutCrmTeamSettingsError, PutCrmTeamSettingsErrors, PutCrmTeamSettingsResponse, PutCrmTeamSettingsResponses, PutCrmTeamStagesData, PutCrmTeamStagesError, PutCrmTeamStagesErrors, PutCrmTeamStagesResponse, PutCrmTeamStagesResponses, PutFormLayoutData, PutFormLayoutError, PutFormLayoutErrors, PutFormLayoutResponse, PutFormLayoutResponses, QueryCrmPipelineRowsData, QueryCrmPipelineRowsResponse, QueryCrmPipelineRowsResponses, QueryDefinition, QuestionLayout, QuestionOption, QuestionTally, ReactionInput, RecentlyDeletedData, RecentlyDeletedError, RecentlyDeletedErrors, RecentlyDeletedResponse, RecentlyDeletedResponseData, RecentlyDeletedResponses, RegisterSlackImportUploadsData, RegisterSlackImportUploadsErrors, RegisterSlackImportUploadsResponse, RegisterSlackImportUploadsResponses, RegisterUploads, 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, RenameCrmPipelineData, RenameCrmPipelineResponse, RenameCrmPipelineResponses, RenamePipeline, ReorderFavoritesData, ReorderFavoritesError, ReorderFavoritesErrors, ReorderFavoritesRequest, ReorderFavoritesResponses, ReorderPinRequest, ReorderPinsHandlerData, ReorderPinsHandlerError, ReorderPinsHandlerErrors, ReorderPinsHandlerResponse, ReorderPinsHandlerResponses, ReplaceCrmStagesRequest, RequestedHarnessScope, RequestedLayout, ResetCrmTeamStagesData, ResetCrmTeamStagesError, ResetCrmTeamStagesErrors, ResetCrmTeamStagesResponse, ResetCrmTeamStagesResponses, ResponseStatus, ResponseSummary, RevertDeleteDocumentData, RevertDeleteDocumentError, RevertDeleteDocumentErrors, RevertDeleteDocumentResponse, RevertDeleteDocumentResponses, RevertDeleteProjectData, RevertDeleteProjectError, RevertDeleteProjectErrors, RevertDeleteProjectResponse, RevertDeleteProjectResponses, RingStatus, RingStatusResponse, RowChange, RowChangeKind, RowChanges, RowHistoryEntry, RowHistoryResponse, RowId, RowsChange, RowsResult, S3ObjectInfo, SaveBomPart, SaveDatabaseQueryData, SaveDatabaseQueryError, SaveDatabaseQueryErrors, SaveDatabaseQueryResponse, SaveDatabaseQueryResponses, SaveDocumentHandlerData, SaveDocumentHandlerError, SaveDocumentHandlerErrors, SaveDocumentHandlerResponse, SaveDocumentHandlerResponses, SaveDocumentRequest, SaveDocumentResponse, SaveDocumentResponseData, SavedQuery, SaveQueryRequest, SearchContactsData, SearchContactsError, SearchContactsErrors, SearchContactsResponse, SearchContactsResponse2, SearchContactsResponses, SearchState, SectionCount, 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, SetEmailFollowupData, SetEmailFollowupError, SetEmailFollowupErrors, SetEmailFollowupResponse, SetEmailFollowupResponses, SetEmailSyncData, SetEmailSyncError, SetEmailSyncErrors, SetEmailSyncRequest, SetEmailSyncResponse, SetEmailSyncResponses, SetOperator, SetPropertyValue, Sha256Digest, ShareCrmPipelineData, ShareCrmPipelineResponse, ShareCrmPipelineResponses, ShareDatabaseAwarenessData, ShareDatabaseAwarenessError, ShareDatabaseAwarenessErrors, ShareDatabaseAwarenessResponse, ShareDatabaseAwarenessResponses, SharedEmailFilter, SharePermissionV2, SharePipeline, ShortIdResponse, SimpleMention, SimpleSaveData, SimpleSaveError, SimpleSaveErrors, SimpleSaveResponse, SimpleSaveResponses, SkippedCell, SlackCompleteRequest, SlackCreateRequest, SlackRegisterRequest, SlackTimestamp, SlackUserId, SmartTagChannelMatch, SmartTagPreview, SortDirection, SortKey, SoupAgentSessionSoupPropertiesField, SoupApiItem, SoupApiSort, SoupApiSortDirection, SoupAttachment, SoupCalendarEventSoupPropertiesField, SoupCalendarEventTime, SoupCallRecordGuest, SoupCallRecordParticipant, SoupCallRecordSoupPropertiesField, SoupChannel, SoupChannelThread, SoupChatSoupPropertiesField, SoupContact, SoupCountedReaction, SoupCrmCompanySoupPropertiesField, SoupCrmContactSoupPropertiesField, SoupCrmDomain, SoupDatabaseRowSoupPropertiesField, SoupDocumentSoupPropertiesField, SoupDocumentSubType, SoupEmailThreadPreview, SoupEnrichedEmailThreadPreviewSoupPropertiesField, SoupForeignEntity, SoupInitiativeSoupPropertiesField, SoupItem, SoupLabel, SoupLabelListVisibility, SoupLabelType, SoupMessageAttachment, SoupMessageListVisibility, SoupMessageSender, SoupMessageSenderType, SoupPage, SoupProjectSoupPropertiesField, SoupPropertiesField, SoupProperty, SoupThreadInfo, SoupThreadReply, SourceBinding, SourceId, SourceIdentity, StarterDatabase, StarterDocumentsResponse, StorageRow, StorageRows, StorageRowsQuery, StoredGithubPullRequest, StreamEventsData, StreamEventsError, StreamEventsErrors, StreamEventsResponse, StreamEventsResponses, String, Submission, SubmissionOutcome, SubmitFormResponseData, SubmitFormResponseError, SubmitFormResponseErrors, SubmitFormResponseResponse, SubmitFormResponseResponses, SuccessResponse, SurfaceState, SyncServiceVersionId, SystemSkillSummary, Table, TableChange, TableChanged, TableChanges, TableDetail, TableResult, TableVersion, TagFilterMode, TakenId, TallyBucket, TallyValue, TaskFilters, TeamCalendarContent, TeamCalendarCoverage, TeamCalendarDetails, TeamCalendarItem, TeamCalendarMember, TeamCalendarPage, TeamCalendarSharing, TeamOutOfOfficeItem, TeamOutOfOfficeResponse, TeamRole, TextOperator, ThreadAnchor, ThreadOrigin, ThreadPatch, ThreadState, TimelineActivity, ToggleShareWithTeamData, ToggleShareWithTeamError, ToggleShareWithTeamErrors, ToggleShareWithTeamResponse, ToggleShareWithTeamResponses, TouchedColumn, TouchedRow, TranscribeDictationData, TranscribeDictationError, TranscribeDictationErrors, TranscribeDictationResponse, TranscribeDictationResponses, TranscribeResponse, TranscriptSegmentRequest, TrashCrmPipelineData, TrashCrmPipelineResponse, TrashCrmPipelineResponses, TrashPipeline, TurnEndedMetadata, TurnStartedMetadata, TurnSummary, TypedSuccessResponse, TypedSuccessResponseGetDocumentResponseData, TypingInput, UndoChangeResponse, UndoDatabaseChangeData, UndoDatabaseChangeError, UndoDatabaseChangeErrors, UndoDatabaseChangeResponse, UndoDatabaseChangeResponses, UndoOutcome, UndoRefusal, UnlockedBooking, UpdateAgentData, UpdateAgentError, UpdateAgentErrors, UpdateAgentRequest, UpdateAgentResponse, UpdateAgentResponses, UpdateChannelSharePermission, UpdateCrmTeamSettingsRequest, UpdateDatabasePermissionsData, UpdateDatabasePermissionsError, UpdateDatabasePermissionsErrors, UpdateDatabasePermissionsResponse, UpdateDatabasePermissionsResponses, UpdateForm, UpdateFormData, UpdateFormError, UpdateFormErrors, UpdateFormPermissionsData, UpdateFormPermissionsError, UpdateFormPermissionsErrors, UpdateFormPermissionsResponse, UpdateFormPermissionsResponses, UpdateFormResponse, UpdateFormResponses, UpdateInitiativeData, UpdateInitiativeError, UpdateInitiativeErrors, UpdateInitiativeRequest, UpdateInitiativeResponse, UpdateInitiativeResponses, UpdateMeetingRequest, UpdateOperation, UpdateSharePermissionRequestV2, UploadDescriptor, UploadDocumentStatus, UploadExtractFolderHandlerData, UploadExtractFolderHandlerError, UploadExtractFolderHandlerErrors, UploadExtractFolderHandlerResponse, UploadExtractFolderHandlerResponses, UploadExtractFolderRequest, UploadFolderHandlerData, UploadFolderHandlerError, UploadFolderHandlerErrors, UploadFolderHandlerResponse, UploadFolderHandlerResponses, UploadFolderRequest, UploadGrant, UploadId, 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, VersionedTable, View, ViewChange, ViewColumn, ViewLayout, ViewPatch, ViewPosition, ViewPositionsResponse, ViewQuery, ViewResult, ViewsResponse, WaitingForInputMetadata, Webhook, WebhookEvent, WebhookFilter, WebhookScope, WebhookStatus, WebhookValidationTestEvent, Widget, WithCallId, WithChannelId, WithDocumentId, WithProjectId } from './types.gen';diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.tsindex 641a5f0113..26fb8c6726 100644--- a/packages/sdk/generated/storage/types.gen.ts+++ b/packages/sdk/generated/storage/types.gen.ts@@ -759,6 +759,7 @@ export type ApiEntityFilterAst = {* the filters that should be applied to the channel entity*/chanf?: unknown;+ crma?: null | CrmAssociation;/*** Opt-in filters for viewer-accessible CRM contacts (wire key `crmf`).*/@@ -4431,6 +4432,21 @@ export type CreatedUserApiKey = {name: string;};+/**+ * The CRM record an association filter names.+ */+export type CrmAssociation = {+ /**+ * Items associated with the company or with any of its contacts.+ */+ company: string;+} | {+ /**+ * Items associated with the contact.+ */+ contact: string;+};+/*** The crm company filters used to narrow which CRM companies appear in soup.*/@@ -20568,6 +20584,10 @@ export type PostItemsSoupAstErrors = {* CRM-scoped queries require team membership, or requesting hidden CRM companies requires admin/owner team role*/403: ErrorResponse;+ /**+ * The CRM record named by `crma` or a document `crm` literal is not visible to the caller+ */+ 404: ErrorResponse;500: ErrorResponse;};@@ -20596,6 +20616,10 @@ export type PostItemsSoupAstGroupedErrors = {* CRM-scoped queries require team membership, or requesting hidden CRM companies requires admin/owner team role*/403: ErrorResponse;+ /**+ * The CRM record named by `crma` or a document `crm` literal is not visible to the caller+ */+ 404: ErrorResponse;500: ErrorResponse;};diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.jsonindex 282dc27034..9e50281d7c 100644--- a/packages/sdk/specs/storage.json+++ b/packages/sdk/specs/storage.json@@ -14338,6 +14338,16 @@}}},+ "404": {+ "description": "The CRM record named by `crma` or a document `crm` literal is not visible to the caller",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },"500": {"description": "","content": {@@ -14398,6 +14408,16 @@}}},+ "404": {+ "description": "The CRM record named by `crma` or a document `crm` literal is not visible to the caller",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },"500": {"description": "","content": {@@ -18984,6 +19004,17 @@"chanf": {"description": "the filters that should be applied to the channel entity"},+ "crma": {+ "oneOf": [+ {+ "type": "null"+ },+ {+ "$ref": "#/components/schemas/CrmAssociation",+ "description": "Restrict every entity type to items associated with this CRM record\n(wire key `crma`): its Companies or Contacts property names the\nrecord, or it references the record. A company also matches through\nits contacts. Unknown or inaccessible records answer 404; requests\nthat are not expanded or not timestamp-sorted answer 400."+ }+ ]+ },"crmf": {"description": "Opt-in filters for viewer-accessible CRM contacts (wire key `crmf`)."},@@ -24229,6 +24260,35 @@}}},+ "CrmAssociation": {+ "oneOf": [+ {+ "type": "object",+ "description": "Items associated with the company or with any of its contacts.",+ "required": ["company"],+ "properties": {+ "company": {+ "type": "string",+ "format": "uuid",+ "description": "Items associated with the company or with any of its contacts."+ }+ }+ },+ {+ "type": "object",+ "description": "Items associated with the contact.",+ "required": ["contact"],+ "properties": {+ "contact": {+ "type": "string",+ "format": "uuid",+ "description": "Items associated with the contact."+ }+ }+ }+ ],+ "description": "The CRM record an association filter names."+ },"CrmCompanyFilters": {"type": "object","description": "The crm company filters used to narrow which CRM companies appear in soup.",diff --git a/static_assets/schema.graphql b/static_assets/schema.graphqlindex ac0573a79b..a31c6f17f9 100644--- a/static_assets/schema.graphql+++ b/static_assets/schema.graphql@@ -2665,6 +2665,20 @@ type GraphqlCommentedOnDocumentMetadata {senderDisplayName: String}+"""+GraphQL input naming the CRM record an association filter restricts to.+"""+input GraphqlCrmAssociation @oneOf {+ """+ Items associated with the company or any of its contacts.+ """+ company: ID+ """+ Items associated with the contact.+ """+ contact: ID+}+"""The two operands of a recursive `CrmCompanyFilterExpr` binary expression."""@@ -3159,6 +3173,16 @@ input GraphqlDocumentLiteral @oneOf {Uploaded from an email attachment sent by, or to, a matching address."""emailAttachmentParticipant: GraphqlEmailValue+ """+ Associated with a CRM record through its Companies or Contacts+ property or a reference to the record. Requires an expanded,+ timestamp-sorted query.+ """+ crmAssociated: GraphqlCrmAssociation+ """+ Case-insensitive substring of the document name.+ """+ nameContains: String}"""@@ -3574,6 +3598,11 @@ input GraphqlEntityFilterAst {"""favoritesOnly: Boolean"""+ Restrict every entity type to items associated with this CRM record.+ Requires an expanded, timestamp-sorted query.+ """+ crmAssociation: GraphqlCrmAssociation+ """The calendar event filter to apply."""calendarEventFilter: GraphqlCalendarEventExpr