Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(crm): activity tabs improvments (#8545)

dev-rb3812769b914a
diff --git a/.sqlx/query-fdbf830ebfdd4c90b0fa8d7f90d578b173e88d9c30b919e2563003cf6259fa7d.json b/.sqlx/query-fdbf830ebfdd4c90b0fa8d7f90d578b173e88d9c30b919e2563003cf6259fa7d.json
new file mode 100644
index 0000000000..662687b1ff
--- /dev/null
+++ b/.sqlx/query-fdbf830ebfdd4c90b0fa8d7f90d578b173e88d9c30b919e2563003cf6259fa7d.json
@@ -0,0 +1,41 @@
+{
+ "db_name": "PostgreSQL",
+ "query": "\n SELECT co.id AS \"company_id!\", ct.id AS \"contact_id?\",\n LOWER(BTRIM(d.domain)) AS \"domain?\", LOWER(BTRIM(ct.email)) AS \"email?\"\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 team_user tu ON tu.team_id = co.team_id AND tu.user_id = $1\n LEFT JOIN crm_contacts ct ON ct.company_id = co.id AND NOT ct.hidden\n LEFT JOIN crm_domains d ON d.company_id = co.id\n WHERE NOT co.hidden\n AND (($1::text IS NOT NULL AND tu.user_id IS NOT NULL)\n OR ($2::uuid IS NOT NULL AND co.team_id = $2))\n ",
+ "describe": {
+ "columns": [
+ {
+ "ordinal": 0,
+ "name": "company_id!",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 1,
+ "name": "contact_id?",
+ "type_info": "Uuid"
+ },
+ {
+ "ordinal": 2,
+ "name": "domain?",
+ "type_info": "Text"
+ },
+ {
+ "ordinal": 3,
+ "name": "email?",
+ "type_info": "Text"
+ }
+ ],
+ "parameters": {
+ "Left": [
+ "Text",
+ "Uuid"
+ ]
+ },
+ "nullable": [
+ false,
+ false,
+ null,
+ null
+ ]
+ },
+ "hash": "fdbf830ebfdd4c90b0fa8d7f90d578b173e88d9c30b919e2563003cf6259fa7d"
+}
diff --git a/apps/web/src/features/crm/README.md b/apps/web/src/features/crm/README.md
index c88677b26d..d7715674c5 100644
--- a/apps/web/src/features/crm/README.md
+++ b/apps/web/src/features/crm/README.md
@@ -65,18 +65,21 @@ context; later flag, focus or record changes leave the open draft unchanged.
The Soup and email SQL optimizations are independent of this frontend gate.
The workspace activity feeds are CRM-linked, not unfiltered app shortcuts.
-`queries/activity.ts` loads all authorized companies and contacts before
-building the feed filters; the capped Quick Access suggestions are not a
-complete scope. Notes means Markdown documents excluding task, snippet, and
-skill subtypes. Email uses the viewer's mailbox, without team-scope widening.
-This reuses existing endpoints without a schema change. Keep the scope complete:
-never cap association IDs or fall back to an unfiltered feed. The activity query
-memoizes its large filter AST between scope/tab changes. SQL generation batches
-OR-ed references into set-membership predicates rather than emitting thousands
-of separate subqueries. Email similarly batches participant lists with identical
-sender/recipient roles in both candidate and message queries, and omits exact
-addresses already covered by a company domain. These backend optimizations must
-be deployed to resolve large-scope request stalls.
+`queries/activity.ts` sends a constant-size `crma: 'activity'` association
+selector. CRM resolves every visible company and contact on the server before
+Soup filters and paginates the result; the browser does not prefetch the full
+CRM or enumerate record IDs in filter trees. The scope excludes hidden records,
+including for administrators, and keeps distinct contact IDs even when their
+email addresses match. Tasks, Notes and Calls match Companies/Contacts property
+links; Notes excludes task, snippet and skill Markdown subtypes. Email matches
+visible company domains/contact addresses in the viewer's own mailbox, without
+team-scope widening or requiring a property link on the email.
+
+Activity extends the existing authorized CRM association path rather than
+splitting the feed into independent client queries. This preserves one sorted
+cursor and a complete scope without raising GraphQL's filter safety limits.
+SQL batching remains useful after resolution, but cannot fix oversized ingress
+filters. Deploy the backend association variant before the updated frontend.
When changing behavior, test the responsible primitive or pure function. When
moving behavior, retain query keys, persistence keys, mutation ordering, loading
diff --git a/apps/web/src/features/crm/crm-adapter.ts b/apps/web/src/features/crm/crm-adapter.ts
index cff3050a0e..8b95b0c0c2 100644
--- a/apps/web/src/features/crm/crm-adapter.ts
+++ b/apps/web/src/features/crm/crm-adapter.ts
@@ -221,7 +221,7 @@ export function createAppCrmContext(): CrmContext {
),
createActivity: (tab) =>
withRowNotifications(
- useCrmActivityQuery(deps, useSoupAstItemsQuery, tab, userId)
+ useCrmActivityQuery(useSoupAstItemsQuery, tab, userId)
),
openTaskComposer: () =>
layout.popoverSplit({
diff --git a/apps/web/src/features/crm/queries/activity-filter.ts b/apps/web/src/features/crm/queries/activity-filter.ts
index 777e999ad1..2f4b263053 100644
--- a/apps/web/src/features/crm/queries/activity-filter.ts
+++ b/apps/web/src/features/crm/queries/activity-filter.ts
@@ -1,77 +1,48 @@
-import { SYSTEM_PROPERTY_IDS } from '@property/identifiers';
+import type { SoupAstBody } from '@queries/soup/items';
import { NIL_UUID } from '../../next-soup/filters/filter-store';
import type { CrmActivityTab } from '../core/navigation';
-import { emailFilterForAddress, emailFilterForDomains } from './email-filter';
-export type CrmActivityScope = {
- companyIds: string[];
- contactIds: string[];
- domains: string[];
- emails: string[];
+const NO_CRM_ACTIVITY = {
+ calf: { l: { id: NIL_UUID } },
+ df: { l: { id: NIL_UUID } },
+ chanf: { l: { ChannelId: NIL_UUID } },
+ cthf: { l: { ThreadId: NIL_UUID } },
+ cf: { l: { cid: NIL_UUID } },
+ pf: { l: { pid: NIL_UUID } },
+ callf: { l: { CallId: NIL_UUID } },
+ ccf: { l: { id: NIL_UUID } },
+ fef: { l: { id: NIL_UUID } },
+ ef: { l: { ThreadId: NIL_UUID } },
};
-type AstNode = Record<string, unknown>;
-const leaf = (value: AstNode): AstNode => ({ l: value });
-export const NO_CRM_ACTIVITY = {
- calf: leaf({ id: NIL_UUID }),
- df: leaf({ id: NIL_UUID }),
- chanf: leaf({ ChannelId: NIL_UUID }),
- cthf: leaf({ ThreadId: NIL_UUID }),
- cf: leaf({ cid: NIL_UUID }),
- pf: leaf({ pid: NIL_UUID }),
- callf: leaf({ CallId: NIL_UUID }),
- ccf: leaf({ id: NIL_UUID }),
- fef: leaf({ id: NIL_UUID }),
- ef: leaf({ ThreadId: NIL_UUID }),
-};
-
-// A balanced expression avoids excessive recursion for large CRMs.
-function anyOf(nodes: unknown[]): unknown {
- if (nodes.length === 0) return undefined;
- if (nodes.length === 1) return nodes[0];
- const middle = Math.floor(nodes.length / 2);
- return { '|': [anyOf(nodes.slice(0, middle)), anyOf(nodes.slice(middle))] };
-}
-
-/** Never use an omitted scope as an unfiltered query. */
-export function crmActivityBody(tab: CrmActivityTab, scope: CrmActivityScope) {
+/** The server resolves all visible CRM records before filtering and pagination. */
+export function crmActivityBody(tab: CrmActivityTab): SoupAstBody {
+ const base = { ...NO_CRM_ACTIVITY, crma: 'activity' as const };
if (tab === 'email') {
- const emails = anyOf(
- [
- ...scope.domains.map((domain) => emailFilterForDomains([domain])),
- ...scope.emails.map(emailFilterForAddress),
- ].filter((value) => value !== undefined)
- );
- return emails
- ? { ...NO_CRM_ACTIVITY, ef: emails, emailView: 'all' }
- : NO_CRM_ACTIVITY;
+ const { ef: _email, ...others } = base;
+ return { ...others, emailView: 'all' };
}
- const associations = anyOf([
- ...scope.companyIds.map((id) =>
- leaf({ pd: SYSTEM_PROPERTY_IDS.COMPANIES, v: { er: id } })
- ),
- ...scope.contactIds.map((id) =>
- leaf({ pd: SYSTEM_PROPERTY_IDS.CONTACTS, v: { er: id } })
- ),
- ]);
- if (!associations) return NO_CRM_ACTIVITY;
if (tab === 'calls') {
- const { callf: _calls, ...others } = NO_CRM_ACTIVITY;
- return { ...others, propf: associations };
+ const { callf: _calls, ...others } = base;
+ return others;
}
return {
- ...NO_CRM_ACTIVITY,
- propf: associations,
+ ...base,
df:
tab === 'tasks'
- ? leaf({ dst: 'task' })
+ ? { l: { dst: 'task' } }
: {
'&': [
- leaf({ ft: 'md' }),
+ { l: { ft: 'md' } },
{
- '!': anyOf(
- ['task', 'snippet', 'skill'].map((dst) => leaf({ dst }))
- ),
+ '!': {
+ '|': [
+ { l: { dst: 'task' } },
+ {
+ '|': [{ l: { dst: 'snippet' } }, { l: { dst: 'skill' } }],
+ },
+ ],
+ },
},
],
},
diff --git a/apps/web/src/features/crm/queries/activity-scope.ts b/apps/web/src/features/crm/queries/activity-scope.ts
deleted file mode 100644
index 029e586fad..0000000000
--- a/apps/web/src/features/crm/queries/activity-scope.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import type { CrmActivityScope } from './activity-filter';
-
-type Company = { id: string; domains: { domain: string }[] };
-type Contact = { id: string; email: string };
-type ContactPage = { contacts: Contact[]; nextCursor: string | null };
-
-/** Read every authorized record before constructing an association filter. */
-export async function loadCrmActivityScope(
- sources: {
- companies(): Promise<Company[]>;
- contacts(cursor: string | null): Promise<ContactPage>;
- },
- signal: AbortSignal
-): Promise<CrmActivityScope> {
- async function contacts() {
- const records = new Map<string, Contact>();
- const cursors: string[] = [];
- let cursor: string | null = null;
- do {
- signal.throwIfAborted();
- const page = await sources.contacts(cursor);
- signal.throwIfAborted();
- for (const contact of page.contacts) records.set(contact.id, contact);
- cursor = page.nextCursor;
- if (cursor && cursors.includes(cursor)) {
- throw new Error('CRM pagination did not advance.');
- }
- if (cursor) cursors.push(cursor);
- } while (cursor);
- return [...records.values()];
- }
- const [companies, people] = await Promise.all([
- sources.companies(),
- contacts(),
- ]);
- signal.throwIfAborted();
- const domains = [
- ...new Set(
- companies.flatMap((company) =>
- company.domains.map(({ domain }) => domain.toLowerCase())
- )
- ),
- ];
- const domainSet = new Set(domains);
- // A domain already matches every contact at that domain in every direction.
- // Omitting those redundant addresses keeps the email AST much smaller.
- const emails = [
- ...new Set(people.map(({ email }) => email.toLowerCase())),
- ].filter((email) => !domainSet.has(email.slice(email.lastIndexOf('@') + 1)));
- return {
- companyIds: companies.map((company) => company.id),
- contactIds: people.map((contact) => contact.id),
- domains,
- emails,
- };
-}
diff --git a/apps/web/src/features/crm/queries/activity.test.ts b/apps/web/src/features/crm/queries/activity.test.ts
new file mode 100644
index 0000000000..1efc73dbf6
--- /dev/null
+++ b/apps/web/src/features/crm/queries/activity.test.ts
@@ -0,0 +1,89 @@
+import { makeGraphqlSoupInput } from '@queries/soup/graphql/ast';
+import type {
+ SoupAstItemsQuery,
+ useSoupAstItemsQuery,
+} from '@queries/soup/items';
+import { createRoot, createSignal } from 'solid-js';
+import { describe, expect, it, vi } from 'vitest';
+import type { CrmActivityTab } from '../core/navigation';
+import { useCrmActivityQuery } from './activity';
+import { crmActivityBody } from './activity-filter';
+
+const tabs: CrmActivityTab[] = ['tasks', 'notes', 'calls', 'email'];
+
+describe('CRM activity queries', () => {
+ it.each(tabs)(
+ 'keeps %s within the GraphQL ingress budget without enumerating records',
+ (tab) => {
+ const input = makeGraphqlSoupInput({
+ params: { limit: 100, sort_method: 'updated_at' },
+ body: crmActivityBody(tab),
+ });
+ const pending: unknown[] = [input];
+ let nodes = 0;
+ while (pending.length) {
+ const value = pending.pop();
+ nodes++;
+ if (value !== null && typeof value === 'object')
+ pending.push(...Object.values(value));
+ }
+ expect(nodes).toBeLessThan(100);
+ expect(input).toMatchObject({
+ initial: { filters: { crmAssociation: { activity: true } } },
+ });
+ }
+ );
+
+ it('uses the authorized activity scope without a generic property filter for calls', () => {
+ const body = crmActivityBody('calls');
+ expect(body.crma).toBe('activity');
+ expect(body).not.toHaveProperty('callf');
+ expect(body).not.toHaveProperty('propf');
+ });
+
+ it('keeps email in the viewer mailbox without excluding unlinked matching threads', () => {
+ const body = crmActivityBody('email');
+ expect(body).not.toHaveProperty('ef');
+ expect(body).not.toHaveProperty('ecd');
+ expect(body).not.toHaveProperty('eca');
+ expect(body.emailView).toBe('all');
+ });
+
+ it('starts with the authenticated viewer and delegates errors, retries, and paging to Soup', () => {
+ createRoot((dispose) => {
+ const [userId, setUserId] = createSignal<string>();
+ const [tab, setTab] = createSignal<CrmActivityTab>('tasks');
+ const query: SoupAstItemsQuery = {
+ data: undefined,
+ error: new Error('Request failed'),
+ isPending: false,
+ isLoading: false,
+ isFetching: false,
+ isPlaceholderData: false,
+ isFetchingNextPage: false,
+ isFetchNextPageError: false,
+ isEnabled: true,
+ hasNextPage: false,
+ transport: 'graphql',
+ fetchNextPage: vi.fn(async () => {}),
+ refetch: vi.fn(async () => {}),
+ resetToInitialPage: vi.fn(),
+ refresh: vi.fn(async () => {}),
+ };
+ const createQuery = vi.fn<typeof useSoupAstItemsQuery>(() => query);
+ const source = useCrmActivityQuery(createQuery, tab, userId);
+ const [args, options] = createQuery.mock.calls[0];
+ expect(options?.().enabled).toBe(false);
+ setUserId('macro|[email protected]');
+ expect(options?.().enabled).toBe(true);
+ expect(args().body).toEqual(crmActivityBody('tasks'));
+ setTab('calls');
+ expect(args().body).toEqual(crmActivityBody('calls'));
+ expect(source).toBe(query);
+ expect(source.error).toBe(query.error);
+ expect(source.refetch).toBe(query.refetch);
+ expect(source.fetchNextPage).toBe(query.fetchNextPage);
+ dispose();
+ });
+ });
+});
diff --git a/apps/web/src/features/crm/queries/activity.ts b/apps/web/src/features/crm/queries/activity.ts
index 5e5f0ae746..4f7d9359f1 100644
--- a/apps/web/src/features/crm/queries/activity.ts
+++ b/apps/web/src/features/crm/queries/activity.ts
@@ -1,90 +1,20 @@
-import { queryReadyGate } from '@queries/gate';
-import type {
- SoupAstItemsQuery,
- useSoupAstItemsQuery,
-} from '@queries/soup/items';
-import { soupKeys } from '@queries/soup/keys';
-import { fetchCrmContacts } from '@service-storage/crm-contacts';
-import { queryOptions, useQuery } from '@tanstack/solid-query';
-import { type Accessor, createMemo, mergeProps } from 'solid-js';
+import type { useSoupAstItemsQuery } from '@queries/soup/items';
+import { type Accessor, createMemo } from 'solid-js';
import type { CrmActivityTab } from '../core/navigation';
-import { crmActivityBody, NO_CRM_ACTIVITY } from './activity-filter';
-import { loadCrmActivityScope } from './activity-scope';
-import type { CrmRecordDependencies } from './dependencies';
-import { fetchCrmExportCompanies } from './export';
-import { crmKeys } from './keys';
+import { crmActivityBody } from './activity-filter';
-function activityScopeOptions(
- deps: CrmRecordDependencies,
- userId: string | undefined
-) {
- return queryOptions({
- // Company/contact mutations invalidate Soup, so rebuild this scope with it.
- queryKey: [...soupKeys._def, ...crmKeys.activityScope(userId).queryKey],
- enabled: !!userId,
- staleTime: 60_000,
- queryFn: ({ signal }) =>
- loadCrmActivityScope(
- {
- companies: () =>
- fetchCrmExportCompanies(deps.storage, signal, () => {}),
- contacts: (cursor) =>
- fetchCrmContacts({ cursor, limit: 500, signal }),
- },
- signal
- ),
- });
-}
-
-/** Load the complete authorized CRM scope, not the capped Quick Access cache. */
+/** A bounded query for the complete authorized CRM activity feed. */
export function useCrmActivityQuery(
- deps: CrmRecordDependencies,
createQuery: typeof useSoupAstItemsQuery,
tab: Accessor<CrmActivityTab>,
userId: Accessor<string | undefined>
-): SoupAstItemsQuery {
- const scope = useQuery(
- () => activityScopeOptions(deps, userId()),
- () => deps.client
- );
- // The scope can contain thousands of records. Build the AST once per scope
- // or tab change, not on every read by the Soup transport and query observers.
- const body = createMemo(() =>
- queryReadyGate(scope) ? crmActivityBody(tab(), scope.data) : NO_CRM_ACTIVITY
- );
- const query = createQuery(
+) {
+ const body = createMemo(() => crmActivityBody(tab()));
+ return createQuery(
() => ({
params: { limit: 100, sort_method: 'updated_at' },
body: body(),
}),
- () => ({ enabled: scope.isSuccess })
+ () => ({ enabled: !!userId() })
);
- return mergeProps(query, {
- get isPending() {
- return scope.isPending || query.isPending;
- },
- get isEnabled() {
- return !!userId();
- },
- get isLoading() {
- return scope.isLoading || query.isLoading;
- },
- get isFetching() {
- return scope.isFetching || query.isFetching;
- },
- get isFetchNextPageError() {
- return !scope.error && query.isFetchNextPageError;
- },
- get error() {
- return scope.error ?? query.error;
- },
- async refetch() {
- await scope.refetch({ throwOnError: true });
- await query.refetch();
- },
- async refresh() {
- await scope.refetch({ throwOnError: true });
- await query.refresh();
- },
- });
}
diff --git a/apps/web/src/features/crm/queries/keys.ts b/apps/web/src/features/crm/queries/keys.ts
index 5b729daf53..03f2e1f38e 100644
--- a/apps/web/src/features/crm/queries/keys.ts
+++ b/apps/web/src/features/crm/queries/keys.ts
@@ -2,7 +2,6 @@ import { createQueryKeys } from '@lukemorales/query-key-factory';
export const crmKeys = createQueryKeys('crm', {
lists: null,
- activityScope: (userId: string | undefined) => [userId],
pipelines: (teamId: string | undefined) => [teamId],
pipelineTable: (id: string) => [id],
pipelineRows: (id: string) => [id],
diff --git a/apps/web/src/lib/queries/soup/graphql/ast.ts b/apps/web/src/lib/queries/soup/graphql/ast.ts
index d2337735d7..ed6ff2ae54 100644
--- a/apps/web/src/lib/queries/soup/graphql/ast.ts
+++ b/apps/web/src/lib/queries/soup/graphql/ast.ts
@@ -398,6 +398,7 @@ function mapDocumentLiteral(literal: unknown): GraphqlDocumentLiteralInput {
}
function mapCrmAssociation(value: unknown): GraphqlCrmAssociation {
+ if (value === 'activity') return { activity: true };
const [field, id] = singleLiteralField(value);
if (field === 'company') return { company: mapString(id, 'company') };
if (field === 'contact') return { contact: mapString(id, 'contact') };
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.ts
index cc2a44aab5..7ff83cab54 100644
--- 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.ts
@@ -10,4 +10,7 @@ import type { CrmAssociationOneOfTwo } from './crmAssociationOneOfTwo';
/**
* The CRM record an association filter names.
*/
-export type CrmAssociation = CrmAssociationOneOf | CrmAssociationOneOfTwo;
+export type CrmAssociation =
+ | CrmAssociationOneOf
+ | CrmAssociationOneOfTwo
+ | 'activity';
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.ts
index b384820702..ef061d109b 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
@@ -33158,6 +33158,11 @@ export const postItemsSoupAstBody = zod
.describe('Items associated with the contact.'),
})
.describe('Items associated with the contact.'),
+ zod
+ .enum(['activity'])
+ .describe(
+ 'Activity across visible CRM-enabled teams, excluding hidden records.'
+ ),
])
.describe('The CRM record an association filter names.'),
])
@@ -37293,6 +37298,11 @@ export const postItemsSoupAstGroupedBody = zod
.describe('Items associated with the contact.'),
})
.describe('Items associated with the contact.'),
+ zod
+ .enum(['activity'])
+ .describe(
+ 'Activity across visible CRM-enabled teams, excluding hidden records.'
+ ),
])
.describe('The CRM record an association filter names.'),
])
@@ -37500,6 +37510,11 @@ export const postItemsSoupAstGroupedBody = zod
.describe('Items associated with the contact.'),
})
.describe('Items associated with the contact.'),
+ zod
+ .enum(['activity'])
+ .describe(
+ 'Activity across visible CRM-enabled teams, excluding hidden records.'
+ ),
])
.describe('The CRM record an association filter names.'),
])
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.ts
index a86f1bbbd6..90da5358a5 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
@@ -805,9 +805,11 @@ export type GraphqlChatRole =
/** GraphQL input naming the CRM record an association filter restricts to. */
export type GraphqlCrmAssociation =
- { /** Items associated with the company or any of its contacts. */
+ { /** Activity across visible CRM-enabled teams; only true is valid. */
+ activity: boolean; company?: never; contact?: never; }
+ | { activity?: never; /** Items associated with the company or any of its contacts. */
company: string | number; contact?: never; }
- | { company?: never; /** Items associated with the contact. */
+ | { activity?: never; company?: never; /** Items associated with the contact. */
contact: string | number; };
/** The two operands of a recursive `CrmCompanyFilterExpr` binary expression. */
@@ -1125,7 +1127,8 @@ export type GraphqlEntityFilterAst = {
/** The chat filter to apply. */
chatFilter?: GraphqlChatExpr | null | undefined;
/**
- * Restrict every entity type to items associated with this CRM record.
+ * Restrict every entity type to items associated with this CRM record,
+ * or to activity across visible CRM-enabled teams.
* Requires an expanded, timestamp-sorted query.
*/
crmAssociation?: GraphqlCrmAssociation | 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.json
index 98b444366c..b3c3690902 100644
--- a/apps/web/src/lib/service-clients/service-storage/openapi.json
+++ b/apps/web/src/lib/service-clients/service-storage/openapi.json
@@ -26426,6 +26426,11 @@
"description": "Items associated with the contact."
}
}
+ },
+ {
+ "type": "string",
+ "description": "Activity across visible CRM-enabled teams, excluding hidden records.",
+ "enum": ["activity"]
}
],
"description": "The CRM record an association filter names."
diff --git a/crates/crm/AGENTS.md b/crates/crm/AGENTS.md
index 37ab297d4c..00eb08eba0 100644
--- a/crates/crm/AGENTS.md
+++ b/crates/crm/AGENTS.md
@@ -57,6 +57,11 @@ tools/HTTP/GraphQL surfaces over them.
## Gotchas
+- `resolve_association` also accepts `CrmAssociation::Activity`: all records in
+ CRM-enabled teams within the viewer/verified-bot scope, excluding hidden rows
+ even for admins. Preserve distinct contact IDs that share an email; returned
+ domains and addresses constrain the viewer's mailbox, not team email access.
+
- Company names/logos live in the global `crm_domain_directory`. Only the
email pubsub workers carry a real `CompanyMetadataResolver`; every other
binary uses `NoOpCompanyMetadataResolver`, which leaves a pending entry
diff --git a/crates/crm/src/domain/association.rs b/crates/crm/src/domain/association.rs
index 4938eb0132..0cdf610a8e 100644
--- a/crates/crm/src/domain/association.rs
+++ b/crates/crm/src/domain/association.rs
@@ -16,6 +16,10 @@ pub struct CrmRecordAssociation {
pub company_ids: Vec<Uuid>,
/// Contacts matched through the Contacts property or a reference.
pub contact_ids: Vec<Uuid>,
+ /// Normalized domains of visible companies, for activity email matching.
+ pub domains: Vec<String>,
+ /// Normalized addresses of visible contacts, for activity email matching.
+ pub addresses: Vec<String>,
}
impl CrmRecordAssociation {
@@ -24,6 +28,8 @@ impl CrmRecordAssociation {
Self {
company_ids: vec![company_id],
contact_ids,
+ domains: Vec::new(),
+ addresses: Vec::new(),
}
}
@@ -32,6 +38,8 @@ impl CrmRecordAssociation {
Self {
company_ids: Vec::new(),
contact_ids: vec![contact_id],
+ domains: Vec::new(),
+ addresses: Vec::new(),
}
}
}
diff --git a/crates/crm/src/domain/companies_repo.rs b/crates/crm/src/domain/companies_repo.rs
index c3805535a4..ac5d4740dc 100644
--- a/crates/crm/src/domain/companies_repo.rs
+++ b/crates/crm/src/domain/companies_repo.rs
@@ -66,6 +66,13 @@ pub trait CompaniesRepository: Clone + Send + Sync + 'static {
record: super::association::CrmAssociation,
) -> impl Future<Output = Result<Option<super::association::CrmRecordAssociation>, CrmError>> + Send;
+ /// Resolve the complete activity scope with no contact email deduplication.
+ /// Membership and CRM settings gate rows; hidden records never participate.
+ fn resolve_activity(
+ &self,
+ scope: super::contact_listing::CrmContactListScope<'_>,
+ ) -> impl Future<Output = Result<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 single
diff --git a/crates/crm/src/domain/service.rs b/crates/crm/src/domain/service.rs
index 48f8f1bf98..14193eebb4 100644
--- a/crates/crm/src/domain/service.rs
+++ b/crates/crm/src/domain/service.rs
@@ -32,7 +32,9 @@ pub trait CrmService: Clone + Send + Sync + 'static {
/// 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.
+ /// is reported as not found. Activity resolves all visible records across
+ /// CRM-enabled teams without hidden rows or contact-email deduplication;
+ /// team-scoped bot receipts limit it to their verified team.
fn resolve_association(
&self,
user_id: &str,
@@ -957,12 +959,18 @@ where
) -> Result<super::association::CrmRecordAssociation, CrmError> {
use super::association::CrmAssociation;
let scope = viewer_scope(user_id, access)?;
+ if record == CrmAssociation::Activity {
+ return self.companies_repository.resolve_activity(scope).await;
+ }
self.companies_repository
.resolve_association(scope, record)
.await?
.ok_or(match record {
CrmAssociation::Company(_) => CrmError::CompanyNotFoundForTeam,
CrmAssociation::Contact(_) => CrmError::ContactNotFoundForTeam,
+ CrmAssociation::Activity => {
+ CrmError::InvalidRequest("activity scope unavailable".into())
+ }
})
}
@@ -1140,6 +1148,9 @@ impl CrmService for NoOpCrmService {
Err(match record {
CrmAssociation::Company(_) => CrmError::CompanyNotFoundForTeam,
CrmAssociation::Contact(_) => CrmError::ContactNotFoundForTeam,
+ CrmAssociation::Activity => {
+ CrmError::InvalidRequest("activity scope unavailable".into())
+ }
})
}
diff --git a/crates/crm/src/domain/service/test.rs b/crates/crm/src/domain/service/test.rs
index ae86b89009..661a100344 100644
--- a/crates/crm/src/domain/service/test.rs
+++ b/crates/crm/src/domain/service/test.rs
@@ -54,6 +54,15 @@ impl CompaniesRepository for StubRepo {
Ok(vec![])
}
+ async fn resolve_activity(
+ &self,
+ scope: CrmContactListScope<'_>,
+ ) -> Result<crate::domain::association::CrmRecordAssociation, CrmError> {
+ self.resolve_association(scope, crate::domain::association::CrmAssociation::Activity)
+ .await
+ .map(Option::unwrap_or_default)
+ }
+
async fn resolve_association(
&self,
scope: CrmContactListScope<'_>,
diff --git a/crates/crm/src/outbound/companies_repo.rs b/crates/crm/src/outbound/companies_repo.rs
index 661655301c..c086a24364 100644
--- a/crates/crm/src/outbound/companies_repo.rs
+++ b/crates/crm/src/outbound/companies_repo.rs
@@ -269,6 +269,13 @@ impl CompaniesRepository for CompaniesRepositoryImpl {
self.query_association(scope, record).await
}
+ async fn resolve_activity(
+ &self,
+ scope: crate::domain::contact_listing::CrmContactListScope<'_>,
+ ) -> Result<crate::domain::association::CrmRecordAssociation, CrmError> {
+ self.query_activity(scope).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.rs
index d1654e7973..429001c806 100644
--- a/crates/crm/src/outbound/companies_repo/association.rs
+++ b/crates/crm/src/outbound/companies_repo/association.rs
@@ -1,9 +1,8 @@
-//! Resolve a CRM record to the records its associated items match.
+//! Resolve CRM records and activity scope to the records their 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).
+//! Record visibility mirrors viewer-scoped contact listing, including hidden
+//! rows for admins and owners. Activity always excludes hidden companies and
+//! contacts. Both require CRM-enabled teams and membership or a team receipt.
use uuid::Uuid;
@@ -34,6 +33,7 @@ impl CompaniesRepositoryImpl {
rows.into_iter().flatten().collect(),
)))
}
+ CrmAssociation::Activity => Ok(None),
CrmAssociation::Contact(contact_id) => Ok(self
.contact_visible(scope, contact_id)
.await?
@@ -41,6 +41,52 @@ impl CompaniesRepositoryImpl {
}
}
+ #[tracing::instrument(name = "crm.activity_scope", skip_all, err)]
+ pub(super) async fn query_activity(
+ &self,
+ scope: CrmContactListScope<'_>,
+ ) -> Result<CrmRecordAssociation, CrmError> {
+ let (viewer, team_id) = match scope {
+ CrmContactListScope::Viewer(user_id) => (Some(user_id), None),
+ CrmContactListScope::Team { team_id, .. } => (None, Some(team_id)),
+ };
+ let rows = sqlx::query!(
+ r#"
+ SELECT co.id AS "company_id!", ct.id AS "contact_id?",
+ LOWER(BTRIM(d.domain)) AS "domain?", LOWER(BTRIM(ct.email)) AS "email?"
+ FROM crm_companies co
+ JOIN team_crm_settings tcs ON tcs.team_id = co.team_id AND tcs.crm_enabled
+ LEFT 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
+ LEFT JOIN crm_domains d ON d.company_id = co.id
+ WHERE NOT co.hidden
+ AND (($1::text IS NOT NULL AND tu.user_id IS NOT NULL)
+ OR ($2::uuid IS NOT NULL AND co.team_id = $2))
+ "#,
+ viewer,
+ team_id,
+ )
+ .fetch_all(&self.pool)
+ .await
+ .map_err(|error| CrmError::StorageLayerError(error.into()))?;
+ let mut company_ids = std::collections::BTreeSet::new();
+ let mut contact_ids = std::collections::BTreeSet::new();
+ let mut domains = std::collections::BTreeSet::new();
+ let mut addresses = std::collections::BTreeSet::new();
+ for row in rows {
+ company_ids.insert(row.company_id);
+ contact_ids.extend(row.contact_id);
+ domains.extend(row.domain);
+ addresses.extend(row.email);
+ }
+ Ok(CrmRecordAssociation {
+ company_ids: company_ids.into_iter().collect(),
+ contact_ids: contact_ids.into_iter().collect(),
+ domains: domains.into_iter().collect(),
+ addresses: addresses.into_iter().collect(),
+ })
+ }
+
async fn company_contacts(
&self,
scope: CrmContactListScope<'_>,
diff --git a/crates/crm/src/outbound/companies_repo/test/resolve_association.rs b/crates/crm/src/outbound/companies_repo/test/resolve_association.rs
index bdc5ac2176..6e4c1d776c 100644
--- a/crates/crm/src/outbound/companies_repo/test/resolve_association.rs
+++ b/crates/crm/src/outbound/companies_repo/test/resolve_association.rs
@@ -147,3 +147,72 @@ async fn team_scope_is_restricted_to_its_team(pool: PgPool) {
None
);
}
+
+#[sqlx::test(
+ migrator = "MACRO_DB_MIGRATIONS",
+ fixtures("fixtures/contact_listing.sql")
+)]
+async fn activity_preserves_duplicate_contacts_and_excludes_hidden_and_disabled(pool: PgPool) {
+ let repo = CompaniesRepositoryImpl::new(pool.clone());
+ sqlx::query!(
+ "INSERT INTO crm_domains (company_id, team_id, domain) VALUES ($1, $2, 'EXAMPLE.com')",
+ id(101),
+ id(11)
+ )
+ .execute(&pool)
+ .await
+ .unwrap();
+ let scope = repo
+ .resolve_activity(CrmContactListScope::Viewer(VIEWER))
+ .await
+ .unwrap();
+ assert_eq!(scope.company_ids, vec![id(101), id(102)]);
+ assert_eq!(
+ scope.contact_ids,
+ [1001, 1002, 1004, 1005, 1010, 1011].map(id)
+ );
+ assert_eq!(scope.domains, vec!["example.com"]);
+ assert!(scope.addresses.contains(&"[email protected]".to_string()));
+ assert!(
+ !scope
+ .addresses
+ .contains(&"[email protected]".to_string())
+ );
+ assert!(
+ !scope
+ .addresses
+ .contains(&"[email protected]".to_string())
+ );
+ assert!(
+ !scope
+ .addresses
+ .contains(&"[email protected]".to_string())
+ );
+
+ let team = repo
+ .resolve_activity(CrmContactListScope::Team {
+ team_id: id(12),
+ include_hidden: true,
+ })
+ .await
+ .unwrap();
+ assert_eq!(team.company_ids, vec![id(102)]);
+ assert_eq!(team.contact_ids, [1002, 1005].map(id));
+ assert!(
+ repo.resolve_activity(CrmContactListScope::Viewer("macro|[email protected]"))
+ .await
+ .unwrap()
+ .company_ids
+ .is_empty()
+ );
+ assert!(
+ repo.resolve_activity(CrmContactListScope::Team {
+ team_id: id(13),
+ include_hidden: true,
+ })
+ .await
+ .unwrap()
+ .company_ids
+ .is_empty()
+ );
+}
diff --git a/crates/graphql_soup_filter_input/src/lib.rs b/crates/graphql_soup_filter_input/src/lib.rs
index e4d3cebd94..e2a674619d 100644
--- a/crates/graphql_soup_filter_input/src/lib.rs
+++ b/crates/graphql_soup_filter_input/src/lib.rs
@@ -364,7 +364,8 @@ 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.
+ /// Restrict every entity type to items associated with this CRM record,
+ /// or to activity across visible CRM-enabled teams.
/// Requires an expanded, timestamp-sorted query.
crm_association: Option<GraphqlCrmAssociation>,
/// The calendar event filter to apply.
@@ -718,6 +719,8 @@ enum GraphqlCrmAssociation {
Company(ID),
/// Items associated with the contact.
Contact(ID),
+ /// Activity across visible CRM-enabled teams; only true is valid.
+ Activity(bool),
}
impl GraphqlCrmAssociation {
@@ -726,6 +729,8 @@ impl GraphqlCrmAssociation {
Ok(match self {
Self::Company(id) => CrmAssociation::Company(parse_id(id, "company")?),
Self::Contact(id) => CrmAssociation::Contact(parse_id(id, "contact")?),
+ Self::Activity(true) => CrmAssociation::Activity,
+ Self::Activity(false) => return Err(InputError::new("activity must be true")),
})
}
}
diff --git a/crates/graphql_soup_filter_input/src/test.rs b/crates/graphql_soup_filter_input/src/test.rs
index 6ef26f9c87..56f3ebc459 100644
--- a/crates/graphql_soup_filter_input/src/test.rs
+++ b/crates/graphql_soup_filter_input/src/test.rs
@@ -348,3 +348,14 @@ fn contacts_are_opt_in_and_normalize_full_email_filters() {
.is_err()
);
}
+
+#[test]
+fn activity_association_accepts_only_true() {
+ let ast = materialize_graphql_filter(json!({"crmAssociation": {"activity": true}})).unwrap();
+ assert_eq!(ast.crm_association, Some(CrmAssociation::Activity));
+ assert_eq!(
+ serde_json::to_value(CrmAssociation::Activity).unwrap(),
+ json!("activity")
+ );
+ assert!(materialize_graphql_filter(json!({"crmAssociation": {"activity": false}})).is_err());
+}
diff --git a/crates/item_filters/AGENTS.md b/crates/item_filters/AGENTS.md
index 80e255e39b..2c9adc990c 100644
--- a/crates/item_filters/AGENTS.md
+++ b/crates/item_filters/AGENTS.md
@@ -52,6 +52,9 @@ logically-combinable query form.
## Gotchas
+- CRM associations serialize company/contact IDs or the unit string `activity`.
+ The CRM service resolves activity scope; clients do not enumerate record IDs.
+
- Several entity types (initiatives, agent sessions) are opt-in: `include:
false` by default, and asking for specific ids/owners also implicitly opts
in — don't assume an empty `include` flag means "show everything".
diff --git a/crates/item_filters/src/ast/crm_association.rs b/crates/item_filters/src/ast/crm_association.rs
index 99a350a5ee..41757c21c4 100644
--- a/crates/item_filters/src/ast/crm_association.rs
+++ b/crates/item_filters/src/ast/crm_association.rs
@@ -4,7 +4,9 @@
//! 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
+//! or it references the contact. Activity instead matches properties across
+//! visible, CRM-enabled teams and email participants from their domains and
+//! addresses. The Soup domain authorizes the record and
//! resolves that membership before any source query runs; renderers never
//! evaluate these values themselves.
@@ -23,6 +25,8 @@ pub enum CrmAssociation {
Company(Uuid),
/// Items associated with the contact.
Contact(Uuid),
+ /// Activity across visible CRM-enabled teams, excluding hidden records.
+ Activity,
}
/// Every distinct CRM record a document tree names through
diff --git a/crates/soup/AGENTS.md b/crates/soup/AGENTS.md
index 575d279cb2..dfe17fae74 100644
--- a/crates/soup/AGENTS.md
+++ b/crates/soup/AGENTS.md
@@ -66,6 +66,11 @@ rows, initiatives, ...) and get back a single unified, paginated result.
## Gotchas
+- `crm_association.rs` resolves CRM scope before filtering, sorting, and paging.
+ Activity uses property edges rather than references and matches email within
+ the caller's mailbox. Keep browser requests bounded; never expand every CRM
+ record into client-side filters or raise ingress limits to fit them.
+
- `expanded/` vs `unexpanded/` queries exist because hydrating full entities
is expensive — don't widen `unexpanded` to return hydrated data; add a new
`expanded` path instead.
diff --git a/crates/soup/src/domain/service/crm_association.rs b/crates/soup/src/domain/service/crm_association.rs
index 96a9dc8697..f98b594b86 100644
--- a/crates/soup/src/domain/service/crm_association.rs
+++ b/crates/soup/src/domain/service/crm_association.rs
@@ -4,7 +4,8 @@
//! 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.
+//! references the contact. Activity matches properties only, and email
+//! participants from visible CRM domains and addresses in the user's own mailbox.
//!
//! The CRM service authorizes the record and expands a company to the
//! contacts the viewer may see. The property and reference edges of those
@@ -21,11 +22,13 @@ use crm::domain::{
auth::CrmTeamReceipt,
model::CrmError,
};
+use item_filters::ast::email::Email;
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 macro_user_id::email::EmailStr;
use models_properties::EntityType as PropertyEntityType;
use std::collections::BTreeSet;
@@ -56,7 +59,7 @@ pub(super) struct AssociatedEntities {
}
impl AssociatedEntities {
- /// Group the property and reference edges of `scope` by source.
+ /// Group property and (for record associations) reference edges by source.
pub(super) fn from_edges(
record: CrmAssociation,
property_edges: Vec<CrmPropertyEdge>,
@@ -128,9 +131,14 @@ impl AssociatedEntities {
}
// 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),
- };
+ CrmAssociation::Company(id) => {
+ entities.crm_companies.remove(&id);
+ }
+ CrmAssociation::Contact(id) => {
+ entities.crm_contacts.remove(&id);
+ }
+ CrmAssociation::Activity => {}
+ }
entities
}
}
@@ -156,12 +164,15 @@ fn reference_targets(association: &CrmRecordAssociation) -> Vec<ReferenceTarget>
/// Every CRM association a request names, resolved to its entities.
#[derive(Debug, Default)]
-pub(super) struct ResolvedAssociations(HashMap<CrmAssociation, AssociatedEntities>);
+pub(super) struct ResolvedAssociations {
+ entities: HashMap<CrmAssociation, AssociatedEntities>,
+ activity_email: Option<Arc<Expr<EmailLiteral>>>,
+}
impl ResolvedAssociations {
/// The entities of a record resolved for this request.
pub(super) fn get(&self, record: &CrmAssociation) -> Option<&AssociatedEntities> {
- self.0.get(record)
+ self.entities.get(record)
}
/// Restrict `ast` to the resolved associations: every source to the
@@ -175,6 +186,13 @@ impl ResolvedAssociations {
let Some(record) = ast.crm_association.take() else {
return ast;
};
+ if record == CrmAssociation::Activity {
+ let email = self
+ .activity_email
+ .clone()
+ .unwrap_or_else(|| Arc::new(Expr::val(EmailLiteral::ThreadId(Uuid::nil()))));
+ ast.email_filter.tree = Some(with_id_tree(email, ast.email_filter.tree.as_ref()));
+ }
let Some(entities) = self.get(&record) else {
return ast;
};
@@ -189,11 +207,13 @@ impl ResolvedAssociations {
&entities.projects,
ProjectLiteral::ProjectIdSelf,
);
- constrain(
- &mut ast.email_filter.tree,
- &entities.email_threads,
- EmailLiteral::ThreadId,
- );
+ if record != CrmAssociation::Activity {
+ constrain(
+ &mut ast.email_filter.tree,
+ &entities.email_threads,
+ EmailLiteral::ThreadId,
+ );
+ }
constrain(
&mut ast.channel_filter,
&entities.channels,
@@ -331,6 +351,7 @@ where
F: GithubPullRequestListing,
{
/// Authorize and resolve every CRM record `ast` restricts to.
+ #[tracing::instrument(name = "soup.crm_associations", skip_all, err)]
pub(super) async fn resolve_crm_associations(
&self,
user: &MacroUserIdStr<'_>,
@@ -354,6 +375,7 @@ where
.transpose()
.map_err(crm_error)?;
let mut resolved = HashMap::with_capacity(records.len());
+ let mut activity_email = None;
for record in records {
let association = self
.crm_service
@@ -370,6 +392,9 @@ where
.map_err(SoupErr::from)
},
async {
+ if record == CrmAssociation::Activity {
+ return Ok(Vec::new());
+ }
self.comms_service
.get_reference_sources(&targets)
.await
@@ -379,6 +404,34 @@ where
.map_err(|_| SoupErr::CommsErr)
},
);
+ if record == CrmAssociation::Activity {
+ let values = association
+ .domains
+ .iter()
+ .cloned()
+ .map(Email::Domain)
+ .chain(association.addresses.iter().filter_map(|address| {
+ EmailStr::parse_from_str(address)
+ .ok()
+ .map(|email| Email::Complete(email.into_owned()))
+ }));
+ activity_email = balanced_or_tree(
+ values
+ .map(|email| {
+ Expr::or(
+ Expr::or(
+ Expr::val(EmailLiteral::Sender(email.clone())),
+ Expr::val(EmailLiteral::Recipient(email.clone())),
+ ),
+ Expr::or(
+ Expr::val(EmailLiteral::Cc(email.clone())),
+ Expr::val(EmailLiteral::Bcc(email)),
+ ),
+ )
+ })
+ .collect(),
+ );
+ }
let entities =
AssociatedEntities::from_edges(record, property_edges?, reference_sources?);
tracing::debug!(
@@ -390,6 +443,9 @@ where
);
resolved.insert(record, entities);
}
- Ok(Some(ResolvedAssociations(resolved)))
+ Ok(Some(ResolvedAssociations {
+ entities: resolved,
+ activity_email,
+ }))
}
}
diff --git a/crates/soup/src/domain/service/crm_association/test.rs b/crates/soup/src/domain/service/crm_association/test.rs
index 73f45b31fa..bbe250fa16 100644
--- a/crates/soup/src/domain/service/crm_association/test.rs
+++ b/crates/soup/src/domain/service/crm_association/test.rs
@@ -101,10 +101,10 @@ fn edges_group_by_source_and_deduplicate() {
}
fn resolved(entities: AssociatedEntities) -> ResolvedAssociations {
- ResolvedAssociations(HashMap::from([(
- CrmAssociation::Company(COMPANY),
- entities,
- )]))
+ ResolvedAssociations {
+ entities: HashMap::from([(CrmAssociation::Company(COMPANY), entities)]),
+ activity_email: None,
+ }
}
fn id_set<T: std::fmt::Debug>(
@@ -190,13 +190,16 @@ fn top_level_scope_constrains_every_source_before_its_own_filter() {
#[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 resolved = ResolvedAssociations {
+ entities: HashMap::from([(
+ contact,
+ AssociatedEntities {
+ documents: ids(&[7, 8]),
+ ..AssociatedEntities::default()
+ },
+ )]),
+ activity_email: None,
+ };
let ast = resolved.apply(EntityFilterAst {
document_filter: Some(Arc::new(Expr::or(
Expr::val(DocumentLiteral::CrmAssociated(contact)),
@@ -265,3 +268,59 @@ fn requested_opt_in_sources_are_constrained() {
let mut other = request(vec![id(11)]);
assert!(!intersect_crm_companies(&mut other, &entities));
}
+
+#[test]
+fn activity_uses_property_edges_only_and_matches_email_in_every_direction() {
+ let entities = AssociatedEntities::from_edges(
+ CrmAssociation::Activity,
+ vec![
+ edge(PropertyEntityType::Document, 1),
+ edge(PropertyEntityType::CallRecord, 2),
+ edge(PropertyEntityType::Thread, 3),
+ ],
+ vec![],
+ );
+ assert_eq!(entities.documents, ids(&[1]));
+ assert_eq!(entities.calls, ids(&[2]));
+ let email = Email::Domain("example.com".into());
+ let email_tree = Arc::new(Expr::or(
+ Expr::or(
+ Expr::val(EmailLiteral::Sender(email.clone())),
+ Expr::val(EmailLiteral::Recipient(email.clone())),
+ ),
+ Expr::or(
+ Expr::val(EmailLiteral::Cc(email.clone())),
+ Expr::val(EmailLiteral::Bcc(email)),
+ ),
+ ));
+ let resolved = ResolvedAssociations {
+ entities: HashMap::from([(CrmAssociation::Activity, entities)]),
+ activity_email: Some(email_tree.clone()),
+ };
+ let ast = resolved.apply(EntityFilterAst {
+ crm_association: Some(CrmAssociation::Activity),
+ ..EntityFilterAst::default()
+ });
+ assert_eq!(ast.email_filter.crm_scope, None);
+ assert_eq!(
+ serde_json::to_value(&ast.email_filter.tree).unwrap(),
+ serde_json::to_value(&Some(email_tree)).unwrap()
+ );
+ assert_matches!(ast.call_filter.as_deref(), Some(Expr::Literal(CallLiteral::CallId(id))) if *id == Uuid::from_u128(2));
+ assert!(
+ !serde_json::to_string(&ast.email_filter.tree)
+ .unwrap()
+ .contains(&Uuid::from_u128(3).to_string())
+ );
+
+ let empty = ResolvedAssociations {
+ entities: HashMap::from([(CrmAssociation::Activity, AssociatedEntities::default())]),
+ activity_email: None,
+ }
+ .apply(EntityFilterAst {
+ crm_association: Some(CrmAssociation::Activity),
+ ..EntityFilterAst::default()
+ });
+ assert_matches!(empty.email_filter.tree.as_deref(), Some(Expr::Literal(EmailLiteral::ThreadId(nil))) if nil.is_nil());
+ assert_matches!(empty.call_filter.as_deref(), Some(Expr::Literal(CallLiteral::CallId(nil))) if nil.is_nil());
+}
diff --git a/crates/soup/src/domain/service/tests/crm_association.rs b/crates/soup/src/domain/service/tests/crm_association.rs
index c00cd3912e..1a1de961d8 100644
--- a/crates/soup/src/domain/service/tests/crm_association.rs
+++ b/crates/soup/src/domain/service/tests/crm_association.rs
@@ -42,6 +42,7 @@ impl CrmService for FakeCrm {
vec![CONTACT, SIBLING_CONTACT],
)),
CrmAssociation::Contact(CONTACT) => Ok(CrmRecordAssociation::contact(CONTACT)),
+ CrmAssociation::Activity => Ok(CrmRecordAssociation::default()),
CrmAssociation::Company(_) => Err(CrmError::CompanyNotFoundForTeam),
CrmAssociation::Contact(_) => Err(CrmError::ContactNotFoundForTeam),
}
diff --git a/docs/agent-guide/crm.md b/docs/agent-guide/crm.md
index 7492a44db0..02093e951a 100644
--- a/docs/agent-guide/crm.md
+++ b/docs/agent-guide/crm.md
@@ -42,7 +42,9 @@ The four activity tabs show CRM-linked content, not the whole app: Tasks and
Calls require a Companies or Contacts reference; Notes are linked Markdown
documents (excluding tasks, snippets, and skills); Email is your own mailbox's
threads with CRM company domains or contact addresses. Lists page as you scroll.
-Empty CRM scope never falls back to all content. A loading failure offers
+Empty CRM scope never falls back to all content. Activity loads directly with a
+server-resolved scope; it does not fetch every company and contact first. Hidden
+companies and contacts stay excluded even for admins. A loading failure offers
**Try again**. Tasks has **New task**, with Companies and Contacts visible in
place of Status. Choose a CRM association when creating a task from this feed.
Opening Task through the global Create menu while Customers is focused uses the
diff --git a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/CrmAssociation.md b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/CrmAssociation.md
index dd836d26b6..6ea9383c17 100644
--- a/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/CrmAssociation.md
+++ b/packages/sdk-docs/reference/generated/storage/types.gen/type-aliases/CrmAssociation.md
@@ -1,6 +1,6 @@
# Type Alias: CrmAssociation
-> **CrmAssociation** = \{ `company`: `string`; \} \| \{ `contact`: `string`; \}
+> **CrmAssociation** = \{ `company`: `string`; \} \| \{ `contact`: `string`; \} \| `"activity"`
The CRM record an association filter names.
@@ -23,3 +23,7 @@ The CRM record an association filter names.
| Name | Type | Description |
| ------ | ------ | ------ |
| `contact` | `string` | Items associated with the contact. |
+
+***
+
+`"activity"`
diff --git a/packages/sdk/generated/storage/types.gen.ts b/packages/sdk/generated/storage/types.gen.ts
index 0b942717a3..6a8b6389c0 100644
--- a/packages/sdk/generated/storage/types.gen.ts
+++ b/packages/sdk/generated/storage/types.gen.ts
@@ -4772,7 +4772,7 @@ export type CrmAssociation = {
* Items associated with the contact.
*/
contact: string;
-};
+} | 'activity';
/**
* The crm company filters used to narrow which CRM companies appear in soup.
diff --git a/packages/sdk/specs/storage.json b/packages/sdk/specs/storage.json
index 98b444366c..b3c3690902 100644
--- a/packages/sdk/specs/storage.json
+++ b/packages/sdk/specs/storage.json
@@ -26426,6 +26426,11 @@
"description": "Items associated with the contact."
}
}
+ },
+ {
+ "type": "string",
+ "description": "Activity across visible CRM-enabled teams, excluding hidden records.",
+ "enum": ["activity"]
}
],
"description": "The CRM record an association filter names."
diff --git a/static_assets/schema.graphql b/static_assets/schema.graphql
index 1a520fa932..2256894a0e 100644
--- a/static_assets/schema.graphql
+++ b/static_assets/schema.graphql
@@ -3203,6 +3203,10 @@ input GraphqlCrmAssociation @oneOf {
Items associated with the contact.
"""
contact: ID
+ """
+ Activity across visible CRM-enabled teams; only true is valid.
+ """
+ activity: Boolean
}
"""
@@ -4200,7 +4204,8 @@ input GraphqlEntityFilterAst {
"""
favoritesOnly: Boolean
"""
- Restrict every entity type to items associated with this CRM record.
+ Restrict every entity type to items associated with this CRM record,
+ or to activity across visible CRM-enabled teams.
Requires an expanded, timestamp-sorted query.
"""
crmAssociation: GraphqlCrmAssociation