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): add inline associations and activity view controls (#8937)

dev-rbf68af549e348
diff --git a/apps/web/src/features/crm/README.md b/apps/web/src/features/crm/README.md
index d7715674c5..9b08c1e9d7 100644
--- a/apps/web/src/features/crm/README.md
+++ b/apps/web/src/features/crm/README.md
@@ -75,6 +75,24 @@ 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 rows render stored Companies and Contacts reference properties as inline
+pills through the shared Soup row. Pills use the shared property preview and open
+a record independently of the row; additional values use the shared overflow menu.
+Email still matches visible company domains and contact addresses for feed
+membership, but the row displays only stored properties, not inferred matches.
+No separate CRM association metadata lookup or row footer runs during paging.
+Record-detail lists and activity membership remain unchanged.
+Sidebar Tasks reuse the production Tasks filters, sort, grouping, and list/board/Gantt
+layouts (subject to the normal feature flags and touch fallback). They use a separate
+CRM persistence scope, and every query, including search and grouped continuation,
+retains the mandatory CRM association. Record-detail Tasks stay unchanged.
+Email reuses the shared read/done/attachment/calendar/tag facets. Notes expose creator
+and tag filters; Calls expose audience and tag filters. These lists have independent
+per-entry search, sort direction, and date/none grouping settings. Date headings follow
+the selected sort field in viewer-local time. Email defaults to last-update date groups;
+Notes and Calls default to no grouping. Local-only filters continue paging through
+empty pages; clearing filters never clears the CRM scope.
+
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.
diff --git a/apps/web/src/features/crm/activity-filters-adapter.tsx b/apps/web/src/features/crm/activity-filters-adapter.tsx
new file mode 100644
index 0000000000..9a3c168050
--- /dev/null
+++ b/apps/web/src/features/crm/activity-filters-adapter.tsx
@@ -0,0 +1,87 @@
+import type { ListFilterGroup } from '@app/components/view-shell';
+import { useUserId } from '@core/context/user';
+import { idToDisplayName } from '@core/user/util';
+import { useTagFilterGroup } from '@property/tags/use-tag-filter-group';
+import { useContacts } from '@queries/contacts/contacts';
+import { createMemo } from 'solid-js';
+import { reconcile, type SetStoreFunction, type Store } from 'solid-js/store';
+import { CALL_AUDIENCES } from '../calls-view/core/call-filters';
+import { createEmailFilters } from '../email-view/filters/use-email-filters';
+import type { ActivityFilters } from './context/crm-context';
+import type { CrmActivityViewState } from './core/activity-view';
+import type { CrmActivityTab } from './core/navigation';
+
+/** Normal Email facets and the applicable Notes/Calls filters, with local intent. */
+export function createCrmActivityFilters(
+ tab: CrmActivityTab,
+ state: Store<CrmActivityViewState>,
+ setState: SetStoreFunction<CrmActivityViewState>
+): ActivityFilters {
+ if (tab === 'email') {
+ return createEmailFilters(
+ () => state.facets,
+ (facets) => setState('facets', reconcile(facets))
+ );
+ }
+ const tags = useTagFilterGroup();
+ const contacts = tab === 'notes' ? useContacts() : () => [];
+ const userId = useUserId();
+ const peopleOptions = createMemo(() => {
+ const people = contacts().map((person) => ({
+ id: person.id,
+ label: person.name || person.id,
+ }));
+ const me = userId();
+ if (me && !people.some((person) => person.id === me)) {
+ people.unshift({ id: me, label: `${idToDisplayName(me)} (me)` });
+ }
+ return people;
+ });
+ const groups = createMemo((): ListFilterGroup<string, string>[] => [
+ ...(tab === 'notes'
+ ? [
+ {
+ id: 'created-by',
+ label: 'Created by',
+ searchPlaceholder: 'Search creators...',
+ options: peopleOptions(),
+ },
+ ]
+ : []),
+ ...(tab === 'calls'
+ ? [
+ {
+ id: 'audience',
+ label: 'Audience',
+ selectionMode: 'single' as const,
+ defaultOptionId: 'all',
+ options: [{ id: 'all', label: 'All' }, ...CALL_AUDIENCES],
+ },
+ ]
+ : []),
+ ...(tags().options.length ? [tags()] : []),
+ ]);
+ return {
+ groups,
+ activeCount: () =>
+ Object.values(state.facets).reduce((count, ids) => count + ids.length, 0),
+ selectedIds: (group) => state.facets[group] ?? [],
+ isSelected: (group, option) =>
+ option === 'all'
+ ? !state.facets[group]?.length
+ : (state.facets[group] ?? []).includes(option),
+ setSelected: (group, option, selected) => {
+ const previous = state.facets[group] ?? [];
+ const next =
+ group === 'audience'
+ ? option === 'all' || !selected
+ ? []
+ : [option]
+ : selected
+ ? [...previous.filter((id) => id !== option), option]
+ : previous.filter((id) => id !== option);
+ setState('facets', { ...state.facets, [group]: next });
+ },
+ clear: () => setState('facets', reconcile({})),
+ };
+}
diff --git a/apps/web/src/features/crm/activity-state-adapter.ts b/apps/web/src/features/crm/activity-state-adapter.ts
new file mode 100644
index 0000000000..f84890a730
--- /dev/null
+++ b/apps/web/src/features/crm/activity-state-adapter.ts
@@ -0,0 +1,56 @@
+import { makePersistedState } from '@app/lib/persistence';
+import { createEntryPersistenceStorage } from '@components/app/split-layout/entry-persistence';
+import {
+ useSplitPanelOrThrow,
+ withSplitPanelOwner,
+} from '@components/app/split-layout/layoutUtils';
+import { createStore } from 'solid-js/store';
+import { z } from 'zod';
+import { normalizeFacetSelection } from '../soup';
+import type { CrmActivityViewState } from './core/activity-view';
+import type { CrmActivityTab } from './core/navigation';
+
+const stateSchema = z.object({
+ search: z.string(),
+ facets: z.record(z.string(), z.array(z.string())),
+ sort: z.enum(['updated_at', 'created_at', 'viewed_at']),
+ direction: z.enum(['desc', 'asc']),
+ groupBy: z.enum(['none', 'date']),
+});
+
+/** Per-entry, per-activity controls never modify the ordinary app views. */
+export function createCrmActivityState(tab: CrmActivityTab) {
+ const panel = useSplitPanelOrThrow();
+ const key = `crm.activity.${tab}`;
+ const [state, setState] = withSplitPanelOwner(key, () =>
+ makePersistedState(
+ createStore<CrmActivityViewState>({
+ search: '',
+ facets: {},
+ sort: 'updated_at',
+ direction: 'desc',
+ groupBy: tab === 'email' || tab === 'tasks' ? 'date' : 'none',
+ }),
+ {
+ storages: [
+ createEntryPersistenceStorage<
+ CrmActivityViewState,
+ CrmActivityViewState
+ >({
+ handle: panel.handle,
+ key,
+ restore: (_current, stored) => {
+ const result = stateSchema.safeParse(stored);
+ return result.success ? result.data : undefined;
+ },
+ select: (state) => ({
+ ...state,
+ facets: normalizeFacetSelection(state.facets),
+ }),
+ }),
+ ],
+ }
+ )
+ );
+ return [state, setState] as const;
+}
diff --git a/apps/web/src/features/crm/activity-tasks-adapter.tsx b/apps/web/src/features/crm/activity-tasks-adapter.tsx
new file mode 100644
index 0000000000..ca54188559
--- /dev/null
+++ b/apps/web/src/features/crm/activity-tasks-adapter.tsx
@@ -0,0 +1,137 @@
+import { SearchBar, ViewShell } from '@app/components/view-shell';
+import {
+ ListHeader,
+ ListHeaderSearch,
+} from '@app/components/view-shell/ListHeader';
+import { ViewCreateButton } from '@app/components/view-shell/ViewCreateButton';
+import { TasksControls } from '@app/features/tasks-view/components/TasksControls';
+import { useTasksDataSource } from '@app/features/tasks-view/queries/use-tasks-query';
+import { TasksContent } from '@app/features/tasks-view/tasks-content';
+import {
+ TasksViewProvider,
+ useTasksView,
+} from '@app/features/tasks-view/tasks-view-context';
+import { useSplitLayout } from '@components/app/split-layout/layout';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
+import PlusIcon from '@icon/system/regular/plus.svg';
+import { SYSTEM_PROPERTY_IDS } from '@property/identifiers';
+import { TagSetsQueryProvider } from '@property/tags/tag-sets-context';
+import { Button } from '@ui';
+import { type JSX, Show } from 'solid-js';
+import { useCrmContext } from './context/crm-context';
+
+/** Production Tasks layouts for the workspace-wide CRM activity scope. */
+export function CrmActivityTasks(props: { title?: JSX.Element }) {
+ const crm = useCrmContext();
+ const layout = useSplitLayout();
+ return (
+ <TagSetsQueryProvider>
+ <TasksViewProvider
+ initialState={{ tab: 'team-tasks', groupBy: 'date' }}
+ restoreEntryState
+ scopeKey="crm:activity:tasks"
+ onOpenTask={(task, options) => {
+ layout.openWithSplit(
+ { type: 'task', id: task.id },
+ { preferNewSplit: options?.event?.shiftKey }
+ );
+ return true;
+ }}
+ onCloseTask={() => {}}
+ onCreateTask={(options) => crm.openTaskComposer(options)}
+ sourceFactory={(state, options) =>
+ useTasksDataSource(state, {
+ ...options,
+ crm: () => ({ type: 'activity' }),
+ })
+ }
+ >
+ <ActivityTasksBody
+ title={props.title}
+ onCreateTask={crm.openTaskComposer}
+ />
+ </TasksViewProvider>
+ </TagSetsQueryProvider>
+ );
+}
+
+function ActivityTasksBody(props: {
+ title?: JSX.Element;
+ onCreateTask: () => void;
+}) {
+ const { state, setState, source } = useTasksView();
+ let listElement: HTMLDivElement | undefined;
+ const controls = () => (
+ <>
+ <TasksControls />
+ <Show
+ when={!isTouchDevice()}
+ fallback={
+ <Button variant="outline" onClick={() => props.onCreateTask()}>
+ <PlusIcon class="size-4" />
+ New task
+ </Button>
+ }
+ >
+ <ViewCreateButton
+ label="New task"
+ onClick={() => props.onCreateTask()}
+ />
+ </Show>
+ </>
+ );
+ return (
+ <div class="flex size-full min-h-0 flex-col">
+ <Show
+ when={!isTouchDevice()}
+ fallback={
+ <ViewShell.Header>
+ <div class="flex min-w-0 items-center gap-2 px-4 py-2">
+ {controls()}
+ <SearchBar
+ label="Search tasks"
+ placeholder="Search tasks"
+ value={state.search}
+ onValueChange={(search) => setState('search', search)}
+ class="min-w-0 flex-1"
+ />
+ </div>
+ </ViewShell.Header>
+ }
+ >
+ <ListHeader title={props.title ?? 'Tasks'}>
+ {controls()}
+ <ListHeaderSearch
+ label="Search tasks"
+ value={state.search}
+ onValueChange={(search) => setState('search', search)}
+ onEscape={() => listElement?.focus()}
+ registerFocus={() => {}}
+ />
+ </ListHeader>
+ </Show>
+ <Show when={source.paginationError?.()}>
+ <div
+ role="alert"
+ class="flex items-center gap-3 px-3 py-2 text-sm text-ink-muted"
+ >
+ Some tasks could not be loaded.
+ <Button size="sm" onClick={() => source.retryPagination?.()}>
+ Try again
+ </Button>
+ </div>
+ </Show>
+ <div class="min-h-0 flex-1">
+ <TasksContent
+ ref={(element) => {
+ listElement = element;
+ }}
+ referencePropertyIds={[
+ SYSTEM_PROPERTY_IDS.COMPANIES,
+ SYSTEM_PROPERTY_IDS.CONTACTS,
+ ]}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/crm/components/activity-controls.tsx b/apps/web/src/features/crm/components/activity-controls.tsx
new file mode 100644
index 0000000000..f76e5fef16
--- /dev/null
+++ b/apps/web/src/features/crm/components/activity-controls.tsx
@@ -0,0 +1,169 @@
+import {
+ ListFilterDropdown,
+ ListGroupDropdown,
+ ListSortDropdown,
+} from '@app/components/view-shell';
+import { MobileFilterDrawer } from '@app/components/view-shell/MobileFilterDrawer';
+import { HeaderActionGroup } from '@components/app/HeaderActionGroup';
+import { MobileDrawer } from '@components/app/mobile/MobileDrawer';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
+import { Accordion } from '@kobalte/core/accordion';
+import { For, Show } from 'solid-js';
+import type { ActivityFilters } from '../context/crm-context';
+import type { CrmActivityViewState } from '../core/activity-view';
+
+const SORT_OPTIONS = [
+ { id: 'updated_at', label: 'Last updated' },
+ { id: 'created_at', label: 'Date created' },
+ { id: 'viewed_at', label: 'Last viewed' },
+] satisfies { id: CrmActivityViewState['sort']; label: string }[];
+const GROUP_OPTIONS = [
+ { id: 'date', label: 'Date' },
+ { id: 'none', label: 'None' },
+] satisfies { id: CrmActivityViewState['groupBy']; label: string }[];
+const DIRECTION_OPTIONS = [
+ { id: 'desc', label: 'Newest first' },
+ { id: 'asc', label: 'Oldest first' },
+] satisfies { id: CrmActivityViewState['direction']; label: string }[];
+
+export function ActivityControls(props: {
+ label: string;
+ state: CrmActivityViewState;
+ filters: ActivityFilters;
+ setSort(value: CrmActivityViewState['sort']): void;
+ setDirection(value: CrmActivityViewState['direction']): void;
+ setGroupBy(value: CrmActivityViewState['groupBy']): void;
+}) {
+ return (
+ <Show
+ when={!isTouchDevice()}
+ fallback={
+ <MobileFilterDrawer
+ triggerLabel={`Open ${props.label} filters`}
+ label={`${props.label} list controls`}
+ activeCount={props.filters.activeCount()}
+ onClear={props.filters.clear}
+ >
+ <MobileDrawer.Label class="pt-4">Sort</MobileDrawer.Label>
+ <MobileDrawer.Section role="radiogroup" aria-label="Sort">
+ <For each={SORT_OPTIONS}>
+ {(option) => (
+ <MobileFilterDrawer.Option
+ selectionMode="single"
+ checked={props.state.sort === option.id}
+ onChange={() => props.setSort(option.id)}
+ >
+ {option.label}
+ </MobileFilterDrawer.Option>
+ )}
+ </For>
+ </MobileDrawer.Section>
+ <MobileDrawer.Section role="radiogroup" aria-label="Direction">
+ <For each={DIRECTION_OPTIONS}>
+ {(option) => (
+ <MobileFilterDrawer.Option
+ selectionMode="single"
+ checked={props.state.direction === option.id}
+ onChange={() => props.setDirection(option.id)}
+ >
+ {option.label}
+ </MobileFilterDrawer.Option>
+ )}
+ </For>
+ </MobileDrawer.Section>
+ <MobileDrawer.Label class="pt-4">Group</MobileDrawer.Label>
+ <MobileDrawer.Section role="radiogroup" aria-label="Group">
+ <For each={GROUP_OPTIONS}>
+ {(option) => (
+ <MobileFilterDrawer.Option
+ selectionMode="single"
+ checked={props.state.groupBy === option.id}
+ onChange={() => props.setGroupBy(option.id)}
+ >
+ {option.label}
+ </MobileFilterDrawer.Option>
+ )}
+ </For>
+ </MobileDrawer.Section>
+ <MobileDrawer.Label class="pt-4">Filters</MobileDrawer.Label>
+ <Accordion
+ multiple
+ collapsible
+ defaultValue={[props.filters.groups()[0]?.id ?? 'tags']}
+ >
+ <For each={props.filters.groups()}>
+ {(group) => (
+ <MobileFilterDrawer.Section
+ value={group.id}
+ label={group.label}
+ activeCount={props.filters.selectedIds(group.id).length}
+ >
+ <div
+ role={
+ group.selectionMode === 'single' ? 'radiogroup' : 'group'
+ }
+ aria-label={group.label}
+ >
+ <For each={group.options}>
+ {(option) => (
+ <MobileFilterDrawer.Option
+ selectionMode={group.selectionMode}
+ checked={props.filters.isSelected(
+ group.id,
+ option.id
+ )}
+ onChange={(checked) =>
+ props.filters.setSelected(
+ group.id,
+ option.id,
+ checked
+ )
+ }
+ icon={option.icon?.()}
+ >
+ {option.label}
+ </MobileFilterDrawer.Option>
+ )}
+ </For>
+ </div>
+ </MobileFilterDrawer.Section>
+ )}
+ </For>
+ </Accordion>
+ </MobileFilterDrawer>
+ }
+ >
+ <HeaderActionGroup label={`${props.label} filters`}>
+ <ListFilterDropdown
+ label={`Filter ${props.label}`}
+ activeCount={props.filters.activeCount()}
+ groups={props.filters.groups()}
+ isSelected={props.filters.isSelected}
+ selectedIds={props.filters.selectedIds}
+ onSelectionChange={props.filters.setSelected}
+ onClear={props.filters.clear}
+ />
+ </HeaderActionGroup>
+ <HeaderActionGroup label={`${props.label} view options`}>
+ <ListSortDropdown
+ label={`Sort ${props.label}`}
+ value={props.state.sort}
+ options={SORT_OPTIONS}
+ onChange={props.setSort}
+ />
+ <ListSortDropdown
+ label="Sort direction"
+ value={props.state.direction}
+ options={DIRECTION_OPTIONS}
+ onChange={props.setDirection}
+ />
+ <ListGroupDropdown
+ label="Group by"
+ value={props.state.groupBy}
+ options={GROUP_OPTIONS}
+ onChange={props.setGroupBy}
+ />
+ </HeaderActionGroup>
+ </Show>
+ );
+}
diff --git a/apps/web/src/features/crm/context/crm-context.tsx b/apps/web/src/features/crm/context/crm-context.tsx
index ce547a1cf1..52dc87c5e0 100644
--- a/apps/web/src/features/crm/context/crm-context.tsx
+++ b/apps/web/src/features/crm/context/crm-context.tsx
@@ -1,3 +1,4 @@
+import type { ListFilterGroup } from '@app/components/view-shell';
import type { CrmCompanyEntity } from '@entity';
import {
type Accessor,
@@ -5,6 +6,18 @@ import {
createContext,
useContext,
} from 'solid-js';
+import type { SetStoreFunction, Store } from 'solid-js/store';
+import type { CrmActivityViewState } from '../core/activity-view';
+
+export type ActivityFilters = {
+ groups: Accessor<ListFilterGroup<string, string>[]>;
+ activeCount: Accessor<number>;
+ isSelected(group: string, option: string): boolean;
+ selectedIds(group: string): string[];
+ setSelected(group: string, option: string, selected: boolean): void;
+ clear(): void;
+};
+
import type {
CrmDisplayOptions,
CrmListColumnId,
@@ -82,8 +95,25 @@ export type CrmContext = {
signal: Accessor<CrmEmailSignal>
): ItemListSource;
/** Paged CRM-wide activity, limited to associated records. */
- createActivity(tab: Accessor<CrmActivityTab>): ItemListSource;
- openTaskComposer(): void;
+ createActivity(
+ tab: Accessor<CrmActivityTab>,
+ options?: Accessor<CrmActivityViewState>
+ ): ItemListSource;
+ createActivityState(
+ tab: CrmActivityTab
+ ): readonly [
+ Store<CrmActivityViewState>,
+ SetStoreFunction<CrmActivityViewState>,
+ ];
+ createActivityFilters(
+ tab: CrmActivityTab,
+ state: Store<CrmActivityViewState>,
+ setState: SetStoreFunction<CrmActivityViewState>
+ ): ActivityFilters;
+ ActivityTasks: Component<{ title?: import('solid-js').JSX.Element }>;
+ openTaskComposer(
+ options?: import('../../tasks-view/types').TaskCreateOptions
+ ): void;
/** Newest mounted record source wins; cleanup restores the parent record source. */
registerTaskComposerRecord(
source: Accessor<CrmTaskRecord | undefined>
diff --git a/apps/web/src/features/crm/core/activity-view.ts b/apps/web/src/features/crm/core/activity-view.ts
new file mode 100644
index 0000000000..f874aeef05
--- /dev/null
+++ b/apps/web/src/features/crm/core/activity-view.ts
@@ -0,0 +1,10 @@
+import type { FacetSelection } from '../../soup';
+
+/** User-controlled refinements; the CRM association scope is never editable. */
+export type CrmActivityViewState = {
+ search: string;
+ facets: FacetSelection;
+ sort: 'updated_at' | 'created_at' | 'viewed_at';
+ direction: 'desc' | 'asc';
+ groupBy: 'none' | 'date';
+};
diff --git a/apps/web/src/features/crm/crm-adapter.ts b/apps/web/src/features/crm/crm-adapter.ts
index 8b95b0c0c2..6745ca2335 100644
--- a/apps/web/src/features/crm/crm-adapter.ts
+++ b/apps/web/src/features/crm/crm-adapter.ts
@@ -15,6 +15,8 @@ import { useUserId } from '@core/context/user';
import { useProfilePictureUrl } from '@core/signal/profilePicture';
import { emailToMacroId, getInitialsFromName } from '@core/user';
import { idToEmail } from '@core/user/util';
+import type { EntityData } from '@entity';
+import { useTagSets, useTagSetsReady } from '@property/tags/tag-sets-context';
import { queryReadyGate } from '@queries/gate';
import { useListPropertiesQuery } from '@queries/properties/definitions';
import { useBulkSaveEntityPropertiesMutation } from '@queries/properties/entity';
@@ -33,6 +35,9 @@ import { storageServiceClient } from '@service-storage/client';
import { getGraphqlSoupClient } from '@service-storage/graphql-soup';
import { useQueryClient } from '@tanstack/solid-query';
import { createMemo, lazy } from 'solid-js';
+import { createTagFacetContext } from '../soup';
+import { createCrmActivityFilters } from './activity-filters-adapter';
+import { createCrmActivityState } from './activity-state-adapter';
import type { CrmContext } from './context/crm-context';
import type { CrmQuery, ItemListSource } from './context/crm-sources';
import {
@@ -51,6 +56,7 @@ import { PipelineDatabaseEditor, PipelineShare } from './pipeline-adapter';
import { createCrmPipelineEntries } from './pipeline-entries-adapter';
import { createCrmPermissions } from './primitives/team-config';
import { useCrmActivityQuery } from './queries/activity';
+import { crmActivityItemMatches } from './queries/activity-options';
import {
createCompanyImporter,
useCompanyQuery,
@@ -93,19 +99,28 @@ const CrmRecordTasks = lazy(async () => ({
default: (await import('./record-tasks-adapter')).CrmRecordTasks,
}));
+const CrmActivityTasks = lazy(async () => ({
+ default: (await import('./activity-tasks-adapter')).CrmActivityTasks,
+}));
+
/**
* 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: SoupAstItemsQuery): ItemListSource {
+function withRowNotifications(
+ source: SoupAstItemsQuery,
+ matches?: (entity: EntityData) => boolean
+): ItemListSource {
const notificationSource = useGlobalNotificationSource();
// Reading `data` before the first page resolves would suspend the tab.
const data = createMemo(() =>
queryReadyGate(source)
? {
- entities: source.data.entities.map((entity) =>
- withEntityNotifications(entity, notificationSource)
- ),
+ entities: source.data.entities
+ .filter((entity) => !matches || matches(entity))
+ .map((entity) =>
+ withEntityNotifications(entity, notificationSource)
+ ),
}
: undefined
);
@@ -219,18 +234,39 @@ export function createAppCrmContext(): CrmContext {
withRowNotifications(
useContactEmailsQuery(useSoupAstItemsQuery, ...args)
),
- createActivity: (tab) =>
- withRowNotifications(
- useCrmActivityQuery(useSoupAstItemsQuery, tab, userId)
- ),
- openTaskComposer: () =>
+ createActivity: (tab, options) => {
+ const tags = useTagSets();
+ const tagsReady = useTagSetsReady();
+ const facetContext = createMemo(() => createTagFacetContext(tags()));
+ return withRowNotifications(
+ useCrmActivityQuery(
+ useSoupAstItemsQuery,
+ tab,
+ userId,
+ options,
+ facetContext,
+ tagsReady
+ ),
+ options
+ ? (entity) =>
+ crmActivityItemMatches(entity, tab(), options(), facetContext())
+ : undefined
+ );
+ },
+ createActivityState: createCrmActivityState,
+ createActivityFilters: createCrmActivityFilters,
+ ActivityTasks: CrmActivityTasks,
+ openTaskComposer: (options) =>
layout.popoverSplit({
type: 'component',
id: 'task-compose',
params: {
- composerContext: panel
- ? createContext.snapshot('task', panel.handle.id)
- : undefined,
+ initialDueDate: options?.dueDate,
+ composerContext:
+ options?.composerContext ??
+ (panel
+ ? createContext.snapshot('task', panel.handle.id)
+ : undefined),
},
}),
createRecordFiles: (scope) =>
diff --git a/apps/web/src/features/crm/queries/activity-filter.ts b/apps/web/src/features/crm/queries/activity-filter.ts
index 2f4b263053..03d16f2b11 100644
--- a/apps/web/src/features/crm/queries/activity-filter.ts
+++ b/apps/web/src/features/crm/queries/activity-filter.ts
@@ -1,5 +1,6 @@
import type { SoupAstBody } from '@queries/soup/items';
import { NIL_UUID } from '../../next-soup/filters/filter-store';
+import type { BackendAstMap } from '../../soup';
import type { CrmActivityTab } from '../core/navigation';
const NO_CRM_ACTIVITY = {
@@ -16,7 +17,9 @@ const NO_CRM_ACTIVITY = {
};
/** The server resolves all visible CRM records before filtering and pagination. */
-export function crmActivityBody(tab: CrmActivityTab): SoupAstBody {
+export function crmActivityBody(
+ tab: CrmActivityTab
+): BackendAstMap & Pick<SoupAstBody, 'crma' | 'emailView'> {
const base = { ...NO_CRM_ACTIVITY, crma: 'activity' as const };
if (tab === 'email') {
const { ef: _email, ...others } = base;
diff --git a/apps/web/src/features/crm/queries/activity-options.ts b/apps/web/src/features/crm/queries/activity-options.ts
new file mode 100644
index 0000000000..ff2cf738dd
--- /dev/null
+++ b/apps/web/src/features/crm/queries/activity-options.ts
@@ -0,0 +1,62 @@
+import type { EntityData } from '@entity';
+import type { SoupAstItemsQueryArgs } from '@queries/soup/items';
+import { DRIVE_FACETS } from '../../drive-view/filters/drive-facets';
+import { EMAIL_FACETS } from '../../email-view/filters/email-facets';
+import {
+ externalCallFilter,
+ internalCallFilter,
+} from '../../next-soup/filters/call-audience';
+import {
+ compileFacets,
+ EMPTY_TAG_FACET_CONTEXT,
+ mergeAst,
+ type TagFacetContext,
+ testFacets,
+} from '../../soup';
+import type { CrmActivityViewState } from '../core/activity-view';
+import type { CrmActivityTab } from '../core/navigation';
+import { crmActivityBody } from './activity-filter';
+
+/** Refine, never replace, the fixed CRM and entity-type predicates. */
+export function buildCrmActivityQuery(
+ tab: CrmActivityTab,
+ options?: CrmActivityViewState,
+ facetContext: TagFacetContext = EMPTY_TAG_FACET_CONTEXT
+): SoupAstItemsQueryArgs {
+ const base = crmActivityBody(tab);
+ const facets = options?.facets ?? {};
+ const refinements =
+ tab === 'email'
+ ? compileFacets(facets, EMAIL_FACETS, facetContext)
+ : compileFacets(facets, DRIVE_FACETS, facetContext);
+ return {
+ params: {
+ limit: 100,
+ sort_method: options?.sort ?? 'updated_at',
+ sort_direction: options?.direction ?? 'desc',
+ },
+ body: { ...base, ...mergeAst(base, refinements) },
+ };
+}
+
+/** Attachment and audience predicates mirror the ordinary Email and Calls lists. */
+export function crmActivityItemMatches(
+ entity: EntityData,
+ tab: CrmActivityTab,
+ options: CrmActivityViewState,
+ facetContext: TagFacetContext
+): boolean {
+ if (tab === 'email') {
+ return (
+ entity.type === 'email' &&
+ testFacets(options.facets, EMAIL_FACETS, entity, facetContext)
+ );
+ }
+ if (!testFacets(options.facets, DRIVE_FACETS, entity, facetContext))
+ return false;
+ if (tab !== 'calls') return true;
+ const audience = options.facets.audience?.[0];
+ if (audience === 'call-external') return externalCallFilter(entity);
+ if (audience === 'call-internal') return internalCallFilter(entity);
+ return true;
+}
diff --git a/apps/web/src/features/crm/queries/activity.test.ts b/apps/web/src/features/crm/queries/activity.test.ts
index 1efc73dbf6..eb8328afc5 100644
--- a/apps/web/src/features/crm/queries/activity.test.ts
+++ b/apps/web/src/features/crm/queries/activity.test.ts
@@ -5,9 +5,15 @@ import type {
} from '@queries/soup/items';
import { createRoot, createSignal } from 'solid-js';
import { describe, expect, it, vi } from 'vitest';
+import { EMPTY_TAG_FACET_CONTEXT } from '../../soup';
+import type { CrmActivityViewState } from '../core/activity-view';
import type { CrmActivityTab } from '../core/navigation';
import { useCrmActivityQuery } from './activity';
import { crmActivityBody } from './activity-filter';
+import {
+ buildCrmActivityQuery,
+ crmActivityItemMatches,
+} from './activity-options';
const tabs: CrmActivityTab[] = ['tasks', 'notes', 'calls', 'email'];
@@ -86,4 +92,90 @@ describe('CRM activity queries', () => {
dispose();
});
});
+ it('conjoins email filters without widening CRM scope or mailbox visibility', () => {
+ const query = buildCrmActivityQuery('email', {
+ search: '',
+ facets: { read: ['unread'], done: ['not-done'] },
+ sort: 'created_at',
+ direction: 'asc',
+ groupBy: 'none',
+ });
+ expect(query.body).toMatchObject({ crma: 'activity', emailView: 'all' });
+ expect(query.body?.ef).toEqual({
+ '&': [{ l: { Read: false } }, { l: { InboxVisible: true } }],
+ });
+ expect(query.body?.df).toEqual(crmActivityBody('email').df);
+ expect(query.body).not.toHaveProperty('ecd');
+ expect(query.body).not.toHaveProperty('eca');
+ expect(query.params).toMatchObject({
+ sort_method: 'created_at',
+ sort_direction: 'asc',
+ });
+ const cleared = buildCrmActivityQuery('email', {
+ search: '',
+ facets: {},
+ sort: 'updated_at',
+ direction: 'desc',
+ groupBy: 'date',
+ });
+ expect(cleared.body).toEqual(crmActivityBody('email'));
+ });
+
+ it('keeps the Notes subtype restriction when filtering by creator and tags', () => {
+ const query = buildCrmActivityQuery(
+ 'notes',
+ {
+ search: '',
+ facets: { 'created-by': ['macro|[email protected]'], tags: ['tag'] },
+ sort: 'updated_at',
+ direction: 'desc',
+ groupBy: 'date',
+ },
+ { tagPropertyDefinitionByOptionId: new Map([['tag', 'definition']]) }
+ );
+ expect(query.body).toMatchObject({ crma: 'activity' });
+ expect(query.body?.df).toEqual({
+ '&': [
+ crmActivityBody('notes').df,
+ { l: { o: 'macro|[email protected]' } },
+ ],
+ });
+ expect(query.body?.propf).toEqual({
+ l: { pd: 'definition', v: { so: 'tag' } },
+ });
+ });
+
+ it('applies attachment filters locally without changing the server scope', () => {
+ const options: CrmActivityViewState = {
+ search: '',
+ facets: { attachments: ['attachment-pdf'] },
+ sort: 'updated_at',
+ direction: 'desc',
+ groupBy: 'date',
+ };
+ expect(
+ crmActivityItemMatches(
+ {
+ id: 'email',
+ type: 'email',
+ name: 'Message',
+ ownerId: '',
+ createdAt: '2026-01-01',
+ updatedAt: '2026-01-01',
+ isRead: false,
+ isDraft: false,
+ isImportant: false,
+ done: false,
+ senderEmail: '[email protected]',
+ participants: [],
+ },
+ 'email',
+ options,
+ EMPTY_TAG_FACET_CONTEXT
+ )
+ ).toBe(false);
+ expect(buildCrmActivityQuery('email', options).body).toEqual(
+ crmActivityBody('email')
+ );
+ });
});
diff --git a/apps/web/src/features/crm/queries/activity.ts b/apps/web/src/features/crm/queries/activity.ts
index 4f7d9359f1..ecb0764625 100644
--- a/apps/web/src/features/crm/queries/activity.ts
+++ b/apps/web/src/features/crm/queries/activity.ts
@@ -1,20 +1,28 @@
import type { useSoupAstItemsQuery } from '@queries/soup/items';
-import { type Accessor, createMemo } from 'solid-js';
+import type { Accessor } from 'solid-js';
+import {
+ EMPTY_TAG_FACET_CONTEXT,
+ type TagFacetContext,
+ tagFacetReady,
+} from '../../soup';
+import type { CrmActivityViewState } from '../core/activity-view';
import type { CrmActivityTab } from '../core/navigation';
-import { crmActivityBody } from './activity-filter';
+import { buildCrmActivityQuery } from './activity-options';
/** A bounded query for the complete authorized CRM activity feed. */
export function useCrmActivityQuery(
createQuery: typeof useSoupAstItemsQuery,
tab: Accessor<CrmActivityTab>,
- userId: Accessor<string | undefined>
+ userId: Accessor<string | undefined>,
+ options?: Accessor<CrmActivityViewState>,
+ facetContext: Accessor<TagFacetContext> = () => EMPTY_TAG_FACET_CONTEXT,
+ tagsReady: Accessor<boolean> = () => true
) {
- const body = createMemo(() => crmActivityBody(tab()));
return createQuery(
+ () => buildCrmActivityQuery(tab(), options?.(), facetContext()),
() => ({
- params: { limit: 100, sort_method: 'updated_at' },
- body: body(),
- }),
- () => ({ enabled: !!userId() })
+ enabled:
+ !!userId() && tagFacetReady(options?.().facets ?? {}, tagsReady()),
+ })
);
}
diff --git a/apps/web/src/features/crm/record-tasks-adapter.test.tsx b/apps/web/src/features/crm/record-tasks-adapter.test.tsx
index 3b3fd8b59b..047f60b11a 100644
--- a/apps/web/src/features/crm/record-tasks-adapter.test.tsx
+++ b/apps/web/src/features/crm/record-tasks-adapter.test.tsx
@@ -2,10 +2,20 @@ import type { TasksViewProviderProps } from '@app/features/tasks-view/tasks-view
import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
import type { ParentProps } from 'solid-js';
import { afterEach, expect, it, vi } from 'vitest';
+import { CrmActivityTasks } from './activity-tasks-adapter';
import type { CrmRecordScope } from './core/record';
import { CrmRecordTasks } from './record-tasks-adapter';
-const { openWithSplit } = vi.hoisted(() => ({ openWithSplit: vi.fn() }));
+const { openWithSplit, openTaskComposer } = vi.hoisted(() => ({
+ openWithSplit: vi.fn(),
+ openTaskComposer: vi.fn(),
+}));
+vi.mock('./context/crm-context', () => ({
+ useCrmContext: () => ({ openTaskComposer }),
+}));
+vi.mock('@app/features/tasks-view/tasks-content', () => ({
+ TasksContent: () => null,
+}));
vi.mock('@components/app/split-layout/layout', () => ({
useSplitLayout: () => ({ openWithSplit }),
@@ -15,12 +25,25 @@ vi.mock('@property/tags/tag-sets-context', () => ({
}));
vi.mock('@app/features/tasks-view/tasks-view-context', () => ({
TasksViewProvider: (props: TasksViewProviderProps) => (
- <button
- type="button"
- onClick={(event) => props.onOpenTask?.({ id: 'task-1' }, { event })}
- >
- Open task
- </button>
+ <>
+ <button
+ type="button"
+ onClick={(event) => props.onOpenTask?.({ id: 'task-1' }, { event })}
+ >
+ Open task
+ </button>
+ <button
+ type="button"
+ onClick={() =>
+ props.onCreateTask?.({
+ dueDate: new Date('2026-10-01T12:00:00Z'),
+ composerContext: { key: 'crm-board', initialPropertyValues: {} },
+ })
+ }
+ >
+ Create scoped task
+ </button>
+ </>
),
}));
vi.mock('@app/features/tasks-view/components/TasksControls', () => ({
@@ -72,3 +95,12 @@ it('preserves the request to open a task in a new split', () => {
{ preferNewSplit: true }
);
});
+
+it('forwards board and Gantt creation defaults through the CRM composer', () => {
+ render(() => <CrmActivityTasks />);
+ fireEvent.click(screen.getByRole('button', { name: 'Create scoped task' }));
+ expect(openTaskComposer).toHaveBeenCalledWith({
+ dueDate: new Date('2026-10-01T12:00:00Z'),
+ composerContext: { key: 'crm-board', initialPropertyValues: {} },
+ });
+});
diff --git a/apps/web/src/features/crm/views/activity.tsx b/apps/web/src/features/crm/views/activity.tsx
index 6f3b225d30..e651bbf0e5 100644
--- a/apps/web/src/features/crm/views/activity.tsx
+++ b/apps/web/src/features/crm/views/activity.tsx
@@ -1,70 +1,97 @@
-import { fireAndForget } from '@core/util/fireAndForget';
-import PlusIcon from '@icon/system/regular/plus.svg';
-import { Button } from '@ui';
-import { createSignal, Show } from 'solid-js';
+import { SearchBar, ViewShell } from '@app/components/view-shell';
+import {
+ ListHeader,
+ ListHeaderSearch,
+} from '@app/components/view-shell/ListHeader';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
+import { SYSTEM_PROPERTY_IDS } from '@property/identifiers';
+import { TagSetsQueryProvider } from '@property/tags/tag-sets-context';
+import { type JSX, Show } from 'solid-js';
+import { ActivityControls } from '../components/activity-controls';
import { useCrmContext } from '../context/crm-context';
import type { CrmActivityTab } from '../core/navigation';
import { RecordItemList } from './record-item-list';
-const DESCRIPTIONS: Record<CrmActivityTab, string> = {
- tasks: 'Tasks linked to your CRM companies and people.',
- email: 'Email in your mailbox exchanged with your CRM companies and people.',
- notes: 'Notes linked to your CRM companies and people.',
- calls: 'Calls linked to your CRM companies and people.',
-};
+/** Embedded activity uses normal view controls around an immutable CRM scope. */
+export function CrmActivityView(props: {
+ tab: CrmActivityTab;
+ title?: JSX.Element;
+}) {
+ const crm = useCrmContext();
+ return (
+ <Show
+ when={props.tab !== 'tasks' ? props.tab : undefined}
+ keyed
+ fallback={<crm.ActivityTasks title={props.title} />}
+ >
+ {(tab) => (
+ <TagSetsQueryProvider>
+ <ActivityList tab={tab} title={props.title} />
+ </TagSetsQueryProvider>
+ )}
+ </Show>
+ );
+}
-/** The workspace-wide feed uses the same paged rows as a record's activity. */
-export function CrmActivityView(props: { tab: CrmActivityTab }) {
+function ActivityList(props: { tab: CrmActivityTab; title?: JSX.Element }) {
const crm = useCrmContext();
- const source = crm.createActivity(() => props.tab);
- const [retrying, setRetrying] = createSignal(false);
- const retry = async () => {
- if (!source.refetch || retrying()) return;
- setRetrying(true);
- try {
- await source.refetch();
- } catch {
- // Keep the source's error state and retry action visible.
- } finally {
- setRetrying(false);
- }
- };
+ const [state, setState] = crm.createActivityState(props.tab);
+ const filters = crm.createActivityFilters(props.tab, state, setState);
+ const source = crm.createActivity(
+ () => props.tab,
+ () => state
+ );
+ const controls = () => (
+ <ActivityControls
+ label={props.tab}
+ state={state}
+ filters={filters}
+ setSort={(sort) => setState('sort', sort)}
+ setDirection={(direction) => setState('direction', direction)}
+ setGroupBy={(groupBy) => setState('groupBy', groupBy)}
+ />
+ );
return (
- <div class="flex min-h-0 flex-1 flex-col">
- <div class="flex items-center justify-between gap-3 border-b border-edge-muted px-4 py-3">
- <p class="text-sm text-ink-muted">{DESCRIPTIONS[props.tab]}</p>
- <Show when={props.tab === 'tasks'}>
- <Button
- variant="outline"
- class="shrink-0"
- onClick={crm.openTaskComposer}
- >
- <PlusIcon class="size-4" />
- New task
- </Button>
- </Show>
- </div>
- <div class="min-h-0 flex-1 overflow-y-auto p-4">
- <Show
- when={!source.isError}
- fallback={
- <div class="flex flex-col items-start gap-3 text-sm text-ink-muted">
- <p>Could not load CRM {props.tab}.</p>
- <Button
- variant="outline"
- disabled={retrying()}
- onClick={() => fireAndForget(retry(), 'crm')}
- >
- {retrying() ? 'Retrying…' : 'Try again'}
- </Button>
+ <div class="flex min-h-0 min-w-0 flex-1 flex-col">
+ <Show
+ when={!isTouchDevice()}
+ fallback={
+ <ViewShell.Header>
+ <div class="flex min-w-0 items-center gap-2 px-4 py-2">
+ {controls()}
+ <SearchBar
+ label={`Search ${props.tab}`}
+ placeholder={`Search ${props.tab}`}
+ value={state.search}
+ onValueChange={(search) => setState('search', search)}
+ class="min-w-0 flex-1"
+ />
</div>
- }
- >
- <RecordItemList
- source={source}
- empty={`No ${props.tab} linked to your CRM companies or people yet.`}
+ </ViewShell.Header>
+ }
+ >
+ <ListHeader title={props.title ?? props.tab}>
+ {controls()}
+ <ListHeaderSearch
+ label={`Search ${props.tab}`}
+ value={state.search}
+ onValueChange={(search) => setState('search', search)}
+ registerFocus={() => {}}
/>
- </Show>
+ </ListHeader>
+ </Show>
+ <div class="min-h-0 flex-1 overflow-y-auto p-4">
+ <RecordItemList
+ source={source}
+ empty={`No ${props.tab} match these CRM filters.`}
+ search={state.search}
+ groupByDate={state.groupBy === 'date'}
+ dateField={state.sort}
+ referencePropertyIds={[
+ SYSTEM_PROPERTY_IDS.COMPANIES,
+ SYSTEM_PROPERTY_IDS.CONTACTS,
+ ]}
+ />
</div>
</div>
);
diff --git a/apps/web/src/features/crm/views/crm-workspace.tsx b/apps/web/src/features/crm/views/crm-workspace.tsx
index ab4aaa6dc7..8e1d2b89d6 100644
--- a/apps/web/src/features/crm/views/crm-workspace.tsx
+++ b/apps/web/src/features/crm/views/crm-workspace.tsx
@@ -648,34 +648,30 @@ export function CrmWorkspaceView(props: {
</Show>
<Show when={!recordOpen() && !pipelineId() && activityTab()} keyed>
{(tab) => (
- <>
- <Show when={!isTouchDevice()}>
- <ListHeader
- title={
- <div class="flex min-w-0 items-center gap-3">
- <NavigationToggle onExpand={() => setCollapsed(false)}>
- <Suspense>{sidebar()}</Suspense>
- </NavigationToggle>
- <h1
- class="min-w-0 truncate text-sm font-semibold"
- title={title()}
- >
- {title()}
- </h1>
- </div>
- }
- />
- </Show>
- <Suspense
- fallback={
- <div class="p-4 text-sm text-ink-muted">
- Loading CRM activity…
+ <Suspense
+ fallback={
+ <div class="p-4 text-sm text-ink-muted">
+ Loading CRM activity…
+ </div>
+ }
+ >
+ <CrmActivityView
+ tab={tab}
+ title={
+ <div class="flex min-w-0 items-center gap-3">
+ <NavigationToggle onExpand={() => setCollapsed(false)}>
+ <Suspense>{sidebar()}</Suspense>
+ </NavigationToggle>
+ <h1
+ class="min-w-0 truncate text-sm font-semibold"
+ title={title()}
+ >
+ {title()}
+ </h1>
</div>
}
- >
- <CrmActivityView tab={tab} />
- </Suspense>
- </>
+ />
+ </Suspense>
)}
</Show>
<Show
diff --git a/apps/web/src/features/crm/views/infinite-scroll-sentinel.test.ts b/apps/web/src/features/crm/views/infinite-scroll-sentinel.test.ts
new file mode 100644
index 0000000000..2e972af8ff
--- /dev/null
+++ b/apps/web/src/features/crm/views/infinite-scroll-sentinel.test.ts
@@ -0,0 +1,65 @@
+// @vitest-environment jsdom
+import { createRoot, createSignal } from 'solid-js';
+import { beforeEach, expect, it, vi } from 'vitest';
+import { useInfiniteScrollSentinel } from '../../../lib/primitives/infinite-scroll-sentinel';
+
+const observers: {
+ trigger: () => void;
+ disconnect: ReturnType<typeof vi.fn>;
+}[] = [];
+
+beforeEach(() => {
+ observers.length = 0;
+ vi.stubGlobal(
+ 'IntersectionObserver',
+ class {
+ disconnect = vi.fn();
+ constructor(private callback: IntersectionObserverCallback) {
+ observers.push({
+ trigger: () =>
+ this.callback(
+ [{ isIntersecting: true } as IntersectionObserverEntry],
+ this as never
+ ),
+ disconnect: this.disconnect,
+ });
+ }
+ observe() {}
+ }
+ );
+});
+
+it('fetches again when a completed page leaves the sentinel visible', () => {
+ const node = document.createElement('div');
+ document.body.append(node);
+ const fetch = vi.fn();
+ let setFetching!: (value: boolean) => void;
+ let setHasNext!: (value: boolean) => void;
+ const dispose = createRoot((stop) => {
+ const [fetching, updateFetching] = createSignal(false);
+ const [hasNext, updateHasNext] = createSignal(true);
+ setFetching = updateFetching;
+ setHasNext = updateHasNext;
+ useInfiniteScrollSentinel({
+ sentinel: () => node,
+ hasNextPage: hasNext,
+ isFetchingNextPage: fetching,
+ fetchNextPage: fetch,
+ });
+ return stop;
+ });
+ expect(observers).toHaveLength(1);
+ observers[0].trigger();
+ expect(fetch).toHaveBeenCalledTimes(1);
+ setFetching(true);
+ observers.at(-1)?.trigger();
+ expect(fetch).toHaveBeenCalledTimes(1);
+ setFetching(false);
+ expect(observers).toHaveLength(2);
+ observers[1].trigger();
+ expect(fetch).toHaveBeenCalledTimes(2);
+ setHasNext(false);
+ expect(observers[1].disconnect).toHaveBeenCalled();
+ dispose();
+ node.remove();
+});
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.tsx
index fa2c5cf2c0..a0e624e969 100644
--- a/apps/web/src/features/crm/views/record-item-list.test.tsx
+++ b/apps/web/src/features/crm/views/record-item-list.test.tsx
@@ -1,13 +1,24 @@
import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
-import type { ParentProps } from 'solid-js';
+import { createSignal, 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>
+const mounted = vi.hoisted(() => vi.fn());
+
+vi.mock('@app/features/next-soup/soup-view/date-group-heading', () => ({
+ DateGroupHeading: (props: { label: string }) => (
+ <header>{props.label}</header>
),
+}));
+vi.mock('@entity', () => ({
+ ListEntity: (props: {
+ entity: { name: string };
+ referencePropertyIds?: readonly string[];
+ }) => {
+ mounted(props.referencePropertyIds);
+ return <div>{props.entity.name}</div>;
+ },
ListEntityMetadataQueryProvider: (props: ParentProps) => props.children,
ListLayoutProvider: (props: ParentProps) => props.children,
}));
@@ -27,7 +38,10 @@ vi.mock('../context/crm-context', () => ({
}),
}));
-afterEach(cleanup);
+afterEach(() => {
+ cleanup();
+ vi.useRealTimers();
+});
function source(overrides: Partial<ItemListSource>): ItemListSource {
return {
@@ -103,3 +117,71 @@ it('only declares no search results after the final page', () => {
screen.getByText('Searching more…');
expect(screen.queryByText('No matching items.')).toBeNull();
});
+
+it('keeps the paging marker mounted when a local filter removes an entire page', () => {
+ const view = render(() => (
+ <RecordItemList
+ source={source({ data: { entities: [] }, hasNextPage: true })}
+ empty="Nothing"
+ />
+ ));
+ screen.getByText('Searching more…');
+ expect(screen.queryByText('Nothing')).toBeNull();
+ expect(view.container.querySelector('.h-px')).not.toBeNull();
+});
+
+it('continues date groups across pages without remounting earlier rows', () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date(2026, 9, 27, 12));
+ mounted.mockClear();
+ const [entities, setEntities] = createSignal([
+ {
+ id: 'doc-1',
+ type: 'document',
+ name: 'First page',
+ updatedAt: new Date(2026, 9, 27, 10),
+ },
+ ]);
+ const list = source({ hasNextPage: true });
+ Object.defineProperty(list, 'data', {
+ get: () => ({ entities: entities() }),
+ });
+ const view = render(() => (
+ <RecordItemList
+ source={list}
+ empty="Nothing"
+ groupByDate
+ referencePropertyIds={['reference-id']}
+ />
+ ));
+ const first = screen.getByText('First page');
+ expect(screen.getAllByText('Today')).toHaveLength(1);
+ setEntities([
+ {
+ id: 'doc-1',
+ type: 'document',
+ name: 'First page updated',
+ updatedAt: new Date(2026, 9, 27, 10),
+ },
+ {
+ id: 'doc-2',
+ type: 'document',
+ name: 'Same date, next page',
+ updatedAt: new Date(2026, 9, 27, 9),
+ },
+ {
+ id: 'doc-3',
+ type: 'document',
+ name: 'Older page',
+ updatedAt: new Date(2026, 9, 26, 9),
+ },
+ ]);
+ expect(screen.getByText('First page updated')).toBe(first);
+ screen.getByText('Same date, next page');
+ screen.getByText('Older page');
+ expect(screen.getAllByText('Today')).toHaveLength(1);
+ expect(screen.getAllByText('Yesterday')).toHaveLength(1);
+ expect(mounted).toHaveBeenCalledTimes(3);
+ expect(mounted).toHaveBeenCalledWith(['reference-id']);
+ view.unmount();
+});
diff --git a/apps/web/src/features/crm/views/record-item-list.tsx b/apps/web/src/features/crm/views/record-item-list.tsx
index faee5c2269..269d94a8d5 100644
--- a/apps/web/src/features/crm/views/record-item-list.tsx
+++ b/apps/web/src/features/crm/views/record-item-list.tsx
@@ -1,3 +1,6 @@
+import { DateGroupHeading } from '@app/features/next-soup/soup-view/date-group-heading';
+import { dateBucket } from '@app/features/soup/collection/date-buckets';
+import { createKeyedProjection } from '@app/lib/queries/soup/create-keyed-projection';
import { fireAndForget } from '@core/util/fireAndForget';
import {
ListEntity,
@@ -33,14 +36,42 @@ export function RecordItemList(props: {
search?: string;
/** Row layout when the list is narrow, e.g. in the information panel. */
narrowLayout?: NarrowLayoutVariant;
+ /** Property IDs to display as inline reference pills when needed. */
+ referencePropertyIds?: readonly string[];
+ /** Group the existing newest-first list by its last-updated date. */
+ groupByDate?: boolean;
+ /** Date field matching the list's server-side ordering. */
+ dateField?: 'updated_at' | 'created_at' | 'viewed_at';
}) {
const { openEntity } = useCrmContext().createNavigation();
// Reading `data` before the first page resolves would suspend the tab.
const items = () =>
props.source.isPending ? [] : (props.source.data?.entities ?? []);
+ const rows = createKeyedProjection(
+ items,
+ (item) => `${item.type}:${item.id}`,
+ (item) => item
+ );
const filteredItems = createMemo(() =>
- items().filter((item) => recordItemMatchesSearch(item, props.search ?? ''))
+ rows().filter((item) => recordItemMatchesSearch(item, props.search ?? ''))
);
+ const dateHeadings = createMemo(() => {
+ if (!props.groupByDate) return [];
+ const now = new Date();
+ let previous: string | undefined;
+ return filteredItems().map((entity) => {
+ const date =
+ props.dateField === 'created_at'
+ ? entity.createdAt
+ : props.dateField === 'viewed_at'
+ ? entity.viewedAt
+ : entity.updatedAt;
+ const bucket = dateBucket(date ?? entity.createdAt, now);
+ const label = bucket.key !== previous ? bucket.label : undefined;
+ previous = bucket.key;
+ return label;
+ });
+ });
const [listRef, setListRef] = createSignal<HTMLElement>();
const [sentinelRef, setSentinelRef] = createSignal<HTMLDivElement>();
@@ -68,12 +99,12 @@ export function RecordItemList(props: {
onRetry={() => props.source.refetch()}
/>
</Match>
- <Match when={items().length === 0}>
+ <Match when={items().length === 0 && !props.source.hasNextPage}>
<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}>
+ <Match when={items().length > 0 || props.source.hasNextPage}>
<ListEntityMetadataQueryProvider>
<ListLayoutProvider ref={listRef} narrowLayout={props.narrowLayout}>
<div ref={setListRef} class="flex flex-col">
@@ -86,13 +117,24 @@ export function RecordItemList(props: {
</div>
</Show>
<For each={filteredItems()}>
- {(entity) => (
- <ListEntity
- entity={entity}
- hideCheckbox
- timestamp={entity.updatedAt}
- onClick={() => openEntity(entity)}
- />
+ {(entity, index) => (
+ <>
+ <Show when={dateHeadings()[index()]}>
+ {(label) => (
+ <DateGroupHeading
+ label={label()}
+ isFirst={index() === 0}
+ />
+ )}
+ </Show>
+ <ListEntity
+ entity={entity}
+ hideCheckbox
+ timestamp={entity.updatedAt}
+ onClick={() => openEntity(entity)}
+ referencePropertyIds={props.referencePropertyIds}
+ />
+ </>
)}
</For>
</div>
diff --git a/apps/web/src/features/email-view/filters/use-email-filters.tsx b/apps/web/src/features/email-view/filters/use-email-filters.tsx
index be1ddf6f57..9c2e2847be 100644
--- a/apps/web/src/features/email-view/filters/use-email-filters.tsx
+++ b/apps/web/src/features/email-view/filters/use-email-filters.tsx
@@ -1,8 +1,9 @@
import type { ListFilterGroup } from '@app/components/view-shell';
+import type { FacetSelection } from '@app/features/soup';
import { addUnique, removeValue } from '@app/lib/signals/store-array-updaters';
import { EntityIcon } from '@core/component/EntityIcon';
import { useTagFilterGroup } from '@property/tags/use-tag-filter-group';
-import { createMemo } from 'solid-js';
+import { type Accessor, createMemo } from 'solid-js';
import { useEmailView } from '../email-view-context';
import type { EmailFilterGroupId } from '../types';
import { EMAIL_FILTER_GROUPS } from './email-facets';
@@ -24,24 +25,32 @@ const STATIC_FILTER_GROUPS: EmailFilterGroup[] = EMAIL_FILTER_GROUPS.map(
/** Shared selection semantics for the desktop menu and mobile drawer. */
export function useEmailFilters() {
const { state, setFacets } = useEmailView();
+ return createEmailFilters(() => state.facets, setFacets);
+}
+
+/** Shared Email filters without coupling an embedded list to the Email host. */
+export function createEmailFilters(
+ facets: Accessor<FacetSelection>,
+ setFacets: (facets: FacetSelection) => void
+) {
const tagGroup = useTagFilterGroup();
// Tags come last: the static groups are short, the tag list grows with use.
const groups = createMemo((): EmailFilterGroup[] => [
...STATIC_FILTER_GROUPS,
...(tagGroup().options.length > 0 ? [tagGroup()] : []),
]);
- const groupFor = (groupId: EmailFilterGroupId) =>
+ const groupFor = (groupId: string) =>
groups().find((group) => group.id === groupId);
const activeFilterCount = createMemo(() =>
- Object.values(state.facets).reduce(
+ Object.values(facets()).reduce(
(count, optionIds) => count + optionIds.length,
0
)
);
// Single-select groups carry an "All" option that stands for no selection.
- const isSelected = (groupId: EmailFilterGroupId, optionId: string) => {
- const selected = state.facets[groupId] ?? [];
+ const isSelected = (groupId: string, optionId: string) => {
+ const selected = facets()[groupId] ?? [];
const group = groupFor(groupId);
if (
group?.selectionMode === 'single' &&
@@ -54,7 +63,7 @@ export function useEmailFilters() {
};
const setSelected = (
- groupId: EmailFilterGroupId,
+ groupId: string,
optionId: string,
selected: boolean
) => {
@@ -63,7 +72,7 @@ export function useEmailFilters() {
if (!selected) return;
setFacets({
- ...state.facets,
+ ...facets(),
[groupId]: optionId === group.defaultOptionId ? [] : [optionId],
});
return;
@@ -74,8 +83,8 @@ export function useEmailFilters() {
? addUnique<string>(optionId)
: removeValue<string>(optionId);
setFacets({
- ...state.facets,
- [groupId]: update(state.facets[groupId]),
+ ...facets(),
+ [groupId]: update(facets()[groupId]),
});
};
@@ -83,7 +92,7 @@ export function useEmailFilters() {
groups,
activeCount: activeFilterCount,
isSelected,
- selectedIds: (groupId: EmailFilterGroupId) => state.facets[groupId] ?? [],
+ selectedIds: (groupId: string) => facets()[groupId] ?? [],
setSelected,
clear: () => setFacets({}),
};
diff --git a/apps/web/src/features/entity/README.md b/apps/web/src/features/entity/README.md
index c35159245e..fcab9689fc 100644
--- a/apps/web/src/features/entity/README.md
+++ b/apps/web/src/features/entity/README.md
@@ -4,3 +4,8 @@ App-local entity feature code, including composable entity rendering,
domain-specific extractors, editing surfaces, query and mutation adapters, and
search/notification adapters. The `@entity` alias is the feature's public
app-local entry point.
+
+`ListEntity.referencePropertyIds` opts stored reference properties into the
+existing inline metadata area. Names and icons use the shared property preview
+cache; the row does not search for related entities. Narrow rows compact these
+pills to icons, with full names available in tooltips and the overflow menu.
diff --git a/apps/web/src/features/entity/composed/ListEntity.tsx b/apps/web/src/features/entity/composed/ListEntity.tsx
index cbe264f73a..401b7541f5 100644
--- a/apps/web/src/features/entity/composed/ListEntity.tsx
+++ b/apps/web/src/features/entity/composed/ListEntity.tsx
@@ -33,6 +33,7 @@ import {
} from 'solid-js';
import { Entity } from '../entity';
import type { EntityRowConfig } from '../extractors-notification';
+import { EntityReferenceProperties } from '../extractors-property/entity-reference-properties';
import {
isHitSnippetComplete,
isHitSnippetEntity,
@@ -72,6 +73,8 @@ interface ListEntityProps extends BaseListEntityProps {
showUnrollNotifications?: boolean;
/** Collection-owned schedule metadata for the original entity row. */
scheduleStatus?: JSX.Element;
+ /** Stored reference properties to show beside the row's other properties. */
+ referencePropertyIds?: readonly string[];
}
export function MaybeEntityRow(props: {
@@ -167,6 +170,7 @@ export function ListEntity(props: ListEntityProps) {
titleTrailing: titleTrailing(),
meta: meta(),
scheduleStatus: scheduleStatus(),
+ referenceProperties: referenceProperties(),
authorDisplayName: props.authorDisplayName,
checked: props.checked,
hideCheckbox: props.hideCheckbox,
@@ -193,6 +197,17 @@ export function ListEntity(props: ListEntityProps) {
const listLayout = useListLayout();
const isWide = listLayout?.isWide ?? (() => true);
+ const referenceProperties = children(() => (
+ <Show when={props.referencePropertyIds}>
+ {(ids) => (
+ <EntityReferenceProperties
+ entity={props.entity}
+ propertyIds={ids()}
+ compact={!isWide()}
+ />
+ )}
+ </Show>
+ ));
const isCondensedVariant = () => listLayout?.narrowLayout() === 'condensed';
const usesCondensedNarrowLayout = () => !isWide() && isCondensedVariant();
const isSingleLineVariant = () =>
diff --git a/apps/web/src/features/entity/composed/list-entity/narrow-condensed-layout.tsx b/apps/web/src/features/entity/composed/list-entity/narrow-condensed-layout.tsx
index 5dc80ce282..f6681f16e1 100644
--- a/apps/web/src/features/entity/composed/list-entity/narrow-condensed-layout.tsx
+++ b/apps/web/src/features/entity/composed/list-entity/narrow-condensed-layout.tsx
@@ -67,7 +67,10 @@ export function NarrowCondensedLayout(props: LayoutProps) {
)}
</Show>
</Entity.Slot>
- <Entity.Slot placement="timestamp">{props.scheduleStatus}</Entity.Slot>
+ <Entity.Slot placement="timestamp" class="flex items-center gap-1">
+ {props.referenceProperties}
+ {props.scheduleStatus}
+ </Entity.Slot>
</Entity.Layout>
);
}
diff --git a/apps/web/src/features/entity/composed/list-entity/narrow-email-layout.tsx b/apps/web/src/features/entity/composed/list-entity/narrow-email-layout.tsx
index d905b33cd4..8c26f0fc80 100644
--- a/apps/web/src/features/entity/composed/list-entity/narrow-email-layout.tsx
+++ b/apps/web/src/features/entity/composed/list-entity/narrow-email-layout.tsx
@@ -81,6 +81,7 @@ export function NarrowEmailLayout(
>
<RowEnd actions={props.actions} leadingAction={props.leadingAction}>
<span class="flex items-center gap-1">
+ {props.referenceProperties}
{props.scheduleStatus}
<Show when={!props.hasNotifications}>
<Entity.Timestamp entity={props.entity} />
diff --git a/apps/web/src/features/entity/composed/list-entity/narrow-inbox-layout.tsx b/apps/web/src/features/entity/composed/list-entity/narrow-inbox-layout.tsx
index a0e910493c..39f6af8a6c 100644
--- a/apps/web/src/features/entity/composed/list-entity/narrow-inbox-layout.tsx
+++ b/apps/web/src/features/entity/composed/list-entity/narrow-inbox-layout.tsx
@@ -43,6 +43,7 @@ export function NarrowInboxLayout(props: LayoutProps) {
style={{
// A scheduled send's badge is wider than a date, so it sizes its column.
'grid-template-columns':
+ props.referenceProperties ||
props.scheduleStatus ||
(isEmailEntity(props.entity) && props.entity.scheduledSendTime)
? 'auto 1fr auto'
@@ -129,6 +130,7 @@ export function NarrowInboxLayout(props: LayoutProps) {
placement="timestamp"
class="flex items-center justify-end gap-1 text-xs text-right text-ink-extra-muted font-light pt-3 pr-4"
>
+ {props.referenceProperties}
{props.scheduleStatus}
<Show
when={
diff --git a/apps/web/src/features/entity/composed/list-entity/narrow-layout.tsx b/apps/web/src/features/entity/composed/list-entity/narrow-layout.tsx
index 13c73133c1..d2a08ced3c 100644
--- a/apps/web/src/features/entity/composed/list-entity/narrow-layout.tsx
+++ b/apps/web/src/features/entity/composed/list-entity/narrow-layout.tsx
@@ -113,6 +113,7 @@ export function NarrowLayout(props: LayoutProps) {
<Show
when={
+ props.referenceProperties ||
props.scheduleStatus ||
(!props.hasNotifications &&
!(isChannelEntity(props.entity) && isSearchEntity(props.entity)))
@@ -122,6 +123,7 @@ export function NarrowLayout(props: LayoutProps) {
placement="timestamp"
class="flex items-center justify-end gap-1 text-xs text-right text-ink-extra-muted font-light"
>
+ {props.referenceProperties}
{props.scheduleStatus}
<Show when={!props.hasNotifications}>
<RowEnd actions={props.actions} leadingAction={props.leadingAction}>
diff --git a/apps/web/src/features/entity/composed/list-entity/narrow-single-line-layout.tsx b/apps/web/src/features/entity/composed/list-entity/narrow-single-line-layout.tsx
index 39b8278a8f..d5a12d7250 100644
--- a/apps/web/src/features/entity/composed/list-entity/narrow-single-line-layout.tsx
+++ b/apps/web/src/features/entity/composed/list-entity/narrow-single-line-layout.tsx
@@ -114,6 +114,7 @@ export function NarrowSingleLineLayout(props: LayoutProps) {
<Show
when={
+ props.referenceProperties ||
props.scheduleStatus ||
(!props.hasNotifications &&
!(isChannelEntity(props.entity) && isSearchEntity(props.entity)))
@@ -123,6 +124,7 @@ export function NarrowSingleLineLayout(props: LayoutProps) {
placement="timestamp"
class="flex items-center justify-end gap-1 text-xs text-right text-ink-extra-muted font-light"
>
+ {props.referenceProperties}
{props.scheduleStatus}
<Show when={!props.hasNotifications}>
<Switch fallback={<Entity.Timestamp entity={props.entity} />}>
diff --git a/apps/web/src/features/entity/composed/list-entity/shared.tsx b/apps/web/src/features/entity/composed/list-entity/shared.tsx
index 89ec9e924a..43a8fdcf65 100644
--- a/apps/web/src/features/entity/composed/list-entity/shared.tsx
+++ b/apps/web/src/features/entity/composed/list-entity/shared.tsx
@@ -86,6 +86,8 @@ export interface LayoutProps {
/** Supporting text after the title in the standard content slot. */
titleTrailing?: JSX.Element;
meta?: JSX.Element;
+ /** Stored reference values alongside the existing property pills. */
+ referenceProperties?: JSX.Element;
checked?: boolean;
authorDisplayName?: string;
hideCheckbox?: boolean;
diff --git a/apps/web/src/features/entity/composed/list-entity/wide-layout.tsx b/apps/web/src/features/entity/composed/list-entity/wide-layout.tsx
index 1354c9f6f4..5a3f8fc383 100644
--- a/apps/web/src/features/entity/composed/list-entity/wide-layout.tsx
+++ b/apps/web/src/features/entity/composed/list-entity/wide-layout.tsx
@@ -221,6 +221,7 @@ export function WideLayout(props: LayoutProps) {
</CompactingPills>
)}
</Show>
+ {props.referenceProperties}
<Show when={isProjectEntity(props.entity) && props.entity}>
{(entity) => (
<RowTags
diff --git a/apps/web/src/features/entity/extractors-property/entity-reference-properties.tsx b/apps/web/src/features/entity/extractors-property/entity-reference-properties.tsx
new file mode 100644
index 0000000000..bf88a35095
--- /dev/null
+++ b/apps/web/src/features/entity/extractors-property/entity-reference-properties.tsx
@@ -0,0 +1,146 @@
+import { openDocument } from '@core/component/LexicalMarkdown/component/core/BlockLink';
+import { propertyPillClasses } from '@property/extractors/property-pill-classes';
+import { usePropertyEntityDisplay } from '@property/hooks/usePropertyEntityDisplay';
+import type { EntityReference } from '@service-properties/generated/schemas/entityReference';
+import { createCallback } from '@solid-primitives/rootless';
+import { Dropdown, Tooltip } from '@ui';
+import { createMemo, For, mapArray, Show } from 'solid-js';
+import type { EntityData } from '../types/entity';
+import { soupPropertyToProperty } from './property-helpers';
+
+/** Stored reference values, rendered with the shared property preview cache. */
+export function EntityReferenceProperties(props: {
+ entity: EntityData;
+ propertyIds: readonly string[];
+ compact: boolean;
+}) {
+ const references = createMemo(() => {
+ const properties =
+ 'properties' in props.entity ? props.entity.properties : [];
+ return (properties ?? []).flatMap((property) => {
+ if (!props.propertyIds.includes(property.definition.id)) return [];
+ const value = soupPropertyToProperty(property);
+ if (value.valueType !== 'ENTITY') return [];
+ return (value.value ?? []).map((reference) => ({
+ reference,
+ label: value.displayName,
+ }));
+ });
+ });
+
+ const displays = mapArray(references, (value) => ({
+ ...value,
+ display: usePropertyEntityDisplay(
+ () => value.reference.entity_id,
+ () => value.reference.entity_type
+ ),
+ }));
+ const accessible = () =>
+ displays().filter((value) => value.display.hasPreviewAccess());
+
+ return (
+ <Show when={accessible().length > 0}>
+ <div
+ class="flex min-w-0 shrink-0 items-center gap-1 text-xs font-normal"
+ onPointerDown={(event) => event.stopPropagation()}
+ onMouseDown={(event) => event.stopPropagation()}
+ onClick={(event) => event.stopPropagation()}
+ onKeyDown={(event) => event.stopPropagation()}
+ >
+ <For each={accessible().slice(0, 2)}>
+ {(value) => (
+ <ReferencePill
+ reference={value.reference}
+ label={value.label}
+ display={value.display}
+ compact={props.compact}
+ />
+ )}
+ </For>
+ <Show when={accessible().length > 2}>
+ <Dropdown placement="bottom-start">
+ <Dropdown.Trigger
+ variant="ghost"
+ size="xs"
+ aria-label={`Show ${accessible().length - 2} more property values`}
+ >
+ +{accessible().length - 2}
+ </Dropdown.Trigger>
+ <Dropdown.Content>
+ <For each={accessible().slice(2)}>
+ {(value) => (
+ <ReferencePill
+ reference={value.reference}
+ label={value.label}
+ display={value.display}
+ compact={false}
+ menu
+ />
+ )}
+ </For>
+ </Dropdown.Content>
+ </Dropdown>
+ </Show>
+ </div>
+ </Show>
+ );
+}
+
+function ReferencePill(props: {
+ reference: EntityReference;
+ label: string;
+ display: ReturnType<typeof usePropertyEntityDisplay>;
+ compact: boolean;
+ menu?: boolean;
+}) {
+ const display = props.display;
+ const open = createCallback((event?: MouseEvent) => {
+ event?.stopPropagation();
+ const type = display.blockOrFileType();
+ if (!type || !display.hasPreviewAccess()) return;
+ openDocument(
+ type,
+ props.reference.entity_id,
+ display.linkParams(),
+ event?.shiftKey
+ );
+ });
+ const content = () => (
+ <>
+ <span class="flex size-3.5 shrink-0 items-center justify-center [&_svg]:size-3.5">
+ {display.icon()}
+ </span>
+ <Show when={!props.compact}>
+ <span class="min-w-0 truncate">{display.name()}</span>
+ </Show>
+ </>
+ );
+ return (
+ <Show when={display.hasPreviewAccess()}>
+ <Show
+ when={!props.menu}
+ fallback={
+ <Dropdown.Item disabled={display.isLoading()} onSelect={() => open()}>
+ {content()}
+ </Dropdown.Item>
+ }
+ >
+ <Tooltip label={`${props.label}: ${display.name()}`}>
+ <button
+ type="button"
+ class={propertyPillClasses({
+ variant: 'outline',
+ size: 'sm',
+ class: 'max-w-32',
+ })}
+ aria-label={`${props.label}: ${display.name()}`}
+ disabled={display.isLoading()}
+ onClick={open}
+ >
+ {content()}
+ </button>
+ </Tooltip>
+ </Show>
+ </Show>
+ );
+}
diff --git a/apps/web/src/features/property/hooks/usePropertyEntityDisplay.test.tsx b/apps/web/src/features/property/hooks/usePropertyEntityDisplay.test.tsx
index 70eb21b051..51f9cd555a 100644
--- a/apps/web/src/features/property/hooks/usePropertyEntityDisplay.test.tsx
+++ b/apps/web/src/features/property/hooks/usePropertyEntityDisplay.test.tsx
@@ -252,6 +252,24 @@ describe('usePropertyEntityDisplay subscription ownership', () => {
});
describe('usePropertyEntityDisplay CRM references', () => {
+ it.each(['COMPANY', 'CONTACT'] as const)(
+ 'tracks authorized preview access for %s without resubscribing',
+ (type) => {
+ const [preview, setPreview] = createSignal<unknown>({ loading: true });
+ fixture.preview = preview;
+ const display = setup(type);
+ expect(display.hasPreviewAccess()).toBe(false);
+ setPreview({ loading: false, access: 'access', name: 'Example record' });
+ expect(display.hasPreviewAccess()).toBe(true);
+ setPreview({ loading: false, access: 'no_access' });
+ expect(display.hasPreviewAccess()).toBe(false);
+ setPreview({ loading: false, access: 'does_not_exist' });
+ expect(display.hasPreviewAccess()).toBe(false);
+ setPreview({ loading: false, access: 'access', name: 'Restored record' });
+ expect(display.hasPreviewAccess()).toBe(true);
+ expect(fixture.previewMounts).toBe(1);
+ }
+ );
it.each([
['COMPANY', 'Acme', 'company'],
['CONTACT', 'Ada Lovelace', 'contact'],
diff --git a/apps/web/src/features/property/hooks/usePropertyEntityDisplay.tsx b/apps/web/src/features/property/hooks/usePropertyEntityDisplay.tsx
index 11ff3d32ac..416e71d251 100644
--- a/apps/web/src/features/property/hooks/usePropertyEntityDisplay.tsx
+++ b/apps/web/src/features/property/hooks/usePropertyEntityDisplay.tsx
@@ -45,6 +45,8 @@ type PropertyEntityDisplayResult = {
icon: Accessor<JSX.Element>;
/** Whether preview data is still loading */
isLoading: Accessor<boolean>;
+ /** Whether the current preview confirms access to the referenced entity. */
+ hasPreviewAccess: Accessor<boolean>;
/** Block or file type for linking (null if not linkable) */
blockOrFileType: Accessor<string | null>;
/** URL params for navigation (e.g., message ID for threads) */
@@ -103,6 +105,10 @@ export function usePropertyEntityDisplay(
// Keep subscription ownership separate from its value: a live result must
// not dispose and reacquire the preview that produced it.
const preview = () => previewSource()?.();
+ const hasPreviewAccess = () => {
+ const item = preview();
+ return !!item && isAccessiblePreviewItem(item);
+ };
const channelNameSource = createMemo(() => {
const eType = entityType();
@@ -217,6 +223,7 @@ export function usePropertyEntityDisplay(
name,
icon,
isLoading,
+ hasPreviewAccess,
blockOrFileType,
nativeProjectId,
linkParams,
diff --git a/apps/web/src/features/tasks-view/components/task-list/TaskGridLayout.tsx b/apps/web/src/features/tasks-view/components/task-list/TaskGridLayout.tsx
index 1645e7b275..a7af3d88fc 100644
--- a/apps/web/src/features/tasks-view/components/task-list/TaskGridLayout.tsx
+++ b/apps/web/src/features/tasks-view/components/task-list/TaskGridLayout.tsx
@@ -13,6 +13,7 @@ import {
} from '@entity/components/Badges';
import type { LayoutProps } from '@entity/composed/list-entity/shared';
import { soupPropertyToProperty } from '@entity/extractors-property';
+import { EntityReferenceProperties } from '@entity/extractors-property/entity-reference-properties';
import { ListPropertyValue } from '@property/component/ListPropertyValue';
import { Modals } from '@property/component/modal';
import {
@@ -61,6 +62,7 @@ function buildStubProperty(col: TaskGridColumn): Property {
type TaskGridLayoutProps = Omit<LayoutProps, 'entity'> & {
entity: TaskEntityWithProperties;
onFilterByTag?: (optionId: string) => void;
+ referencePropertyIds?: readonly string[];
};
export function TaskGridLayout(props: TaskGridLayoutProps) {
@@ -174,6 +176,15 @@ export function TaskGridLayout(props: TaskGridLayoutProps) {
<CreatedByBadgeSmall ownerId={props.entity.ownerId} />
</span>
</Show>
+ <Show when={props.referencePropertyIds}>
+ {(ids) => (
+ <EntityReferenceProperties
+ entity={props.entity}
+ propertyIds={ids()}
+ compact={false}
+ />
+ )}
+ </Show>
<EntityRowTags
entityId={props.entity.id}
entityType={EntityType.TASK}
diff --git a/apps/web/src/features/tasks-view/components/task-list/TaskList.tsx b/apps/web/src/features/tasks-view/components/task-list/TaskList.tsx
index 6faa4acd74..56b37c7d96 100644
--- a/apps/web/src/features/tasks-view/components/task-list/TaskList.tsx
+++ b/apps/web/src/features/tasks-view/components/task-list/TaskList.tsx
@@ -92,6 +92,7 @@ const getStatusProperty = (task: TaskEntityWithProperties) => {
export type TaskListProps = {
/** The focusable list root, for callers that hand keyboard focus back. */
ref?: (element: HTMLDivElement) => void;
+ referencePropertyIds?: readonly string[];
};
export function TaskList(props: TaskListProps) {
@@ -528,6 +529,7 @@ export function TaskList(props: TaskListProps) {
}}
>
<TaskListEntity
+ referencePropertyIds={props.referencePropertyIds}
showProject={projectsEnabled()}
rowId={entityRow().id}
entity={entityRow().entity}
diff --git a/apps/web/src/features/tasks-view/components/task-list/TaskListEntity.tsx b/apps/web/src/features/tasks-view/components/task-list/TaskListEntity.tsx
index cf4da1e751..4110980823 100644
--- a/apps/web/src/features/tasks-view/components/task-list/TaskListEntity.tsx
+++ b/apps/web/src/features/tasks-view/components/task-list/TaskListEntity.tsx
@@ -25,6 +25,7 @@ import {
useListLayout,
} from '@entity/composed/list-entity/shared';
import type { EntityRowConfig } from '@entity/extractors-notification';
+import { EntityReferenceProperties } from '@entity/extractors-property/entity-reference-properties';
import {
BULK_DOCUMENT_WAKEUP_FEATURE_FLAG,
enqueueDocumentWakeup,
@@ -53,6 +54,7 @@ type TaskListEntityProps = Omit<BaseListEntityProps, 'entity'> & {
showUnrollNotifications?: boolean;
/** Show the Project column (Projects enabled). */
showProject?: boolean;
+ referencePropertyIds?: readonly string[];
/** Called when "filter by tag" is clicked on an entity row tag. */
onFilterByTag?: (optionId: string) => void;
};
@@ -131,6 +133,7 @@ export function TaskListEntity(props: TaskListEntityProps) {
chars: chars(),
onProjectClick: props.onProjectClick,
showProject: props.showProject,
+ referencePropertyIds: props.referencePropertyIds,
onFilterByTag: props.onFilterByTag,
});
@@ -186,6 +189,17 @@ export function TaskListEntity(props: TaskListEntityProps) {
config={props.entityRowConfig}
>
<NarrowLayout {...layoutProps()} />
+ <Show when={props.referencePropertyIds}>
+ {(ids) => (
+ <div class="px-3 pb-1">
+ <EntityReferenceProperties
+ entity={props.entity}
+ propertyIds={ids()}
+ compact
+ />
+ </div>
+ )}
+ </Show>
</MaybeEntityRow>
</Match>
</Switch>
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.ts
index 9972ac9477..53e8b52de6 100644
--- 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.ts
@@ -5,7 +5,8 @@ const fixture = vi.hoisted(() => ({
calls: [] as { args: () => unknown; options: () => unknown }[],
query: {} as Record<string, unknown>,
}));
-vi.mock('@core/util/debounce', () => ({
+vi.mock('@core/util/debounce', async (importOriginal) => ({
+ ...((await importOriginal()) as typeof import('@core/util/debounce')),
debouncedDependent: (value: () => string) => value,
}));
vi.mock('@queries/soup/items', () => ({
@@ -19,6 +20,7 @@ import {
createScopedTaskSearch,
scopedTaskSearchText,
} from './scoped-task-search';
+import { buildTaskQuery } from './task-query';
it('matches quoted phrases without their quotes', () => {
expect(scopedTaskSearchText(' "renewal call" ')).toBe('renewal call');
@@ -71,3 +73,53 @@ it('pages the scoped list query by name and stays off without text', () => {
}
});
});
+
+it('keeps CRM activity membership on every scoped search page', () => {
+ fixture.calls = [];
+ fixture.query = {
+ isPending: false,
+ isPlaceholderData: false,
+ isFetching: false,
+ hasNextPage: true,
+ isFetchingNextPage: false,
+ error: null,
+ data: { entities: [] },
+ fetchNextPage: vi.fn(),
+ };
+ createRoot((dispose) => {
+ try {
+ const [text, setText] = createSignal('renewal');
+ const search = createScopedTaskSearch({
+ text,
+ enabled: () => true,
+ args: (nameContains) =>
+ buildTaskQuery({
+ tab: 'team-tasks',
+ userId: 'viewer',
+ facets: {},
+ sort: [],
+ groupBy: 'date',
+ crm: { type: 'activity' },
+ nameContains,
+ }),
+ });
+ const args = fixture.calls[0]?.args() as {
+ body: { crma: unknown; df: unknown };
+ groupBy?: unknown;
+ };
+ expect(args.body.crma).toBe('activity');
+ expect(args.body.df).toEqual({
+ '&': [{ l: { dst: 'task' } }, { l: { nc: 'renewal' } }],
+ });
+ expect(args.groupBy).toBeUndefined();
+ setText('call');
+ expect(
+ (fixture.calls[0]?.args() as { body: { crma: unknown } } | undefined)
+ ?.body.crma
+ ).toBe('activity');
+ expect(search.hasNextPage()).toBe(true);
+ } finally {
+ dispose();
+ }
+ });
+});
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.ts
index d59280cb05..56a8197a13 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
@@ -61,6 +61,47 @@ describe('task reference scope', () => {
});
describe('task CRM scope', () => {
+ it('preserves activity membership in list, search, board and Gantt queries', () => {
+ const list = buildTaskQuery({
+ ...options,
+ crm: { type: 'activity' },
+ groupBy: 'date',
+ });
+ const search = buildTaskQuery({
+ ...options,
+ crm: { type: 'activity' },
+ groupBy: 'date',
+ nameContains: 'renewal',
+ });
+ const board = buildTaskQuery({
+ ...options,
+ crm: { type: 'activity' },
+ groupBy: 'project',
+ board: true,
+ });
+ const gantt = buildTaskQuery({
+ ...options,
+ crm: { type: 'activity' },
+ groupBy: 'status',
+ });
+ for (const query of [list, search, board, gantt]) {
+ expect(query.body.crma).toBe('activity');
+ expect(JSON.stringify(query.body)).not.toContain('company-1');
+ }
+ expect(list.groupBy).toEqual({ type: 'date' });
+ expect(search.body.df).toEqual({
+ '&': [{ l: { dst: 'task' } }, { l: { nc: 'renewal' } }],
+ });
+ expect(board.groupBy).toEqual({
+ type: 'property',
+ propertyDefinitionId: '00000001-0000-0000-0000-000000000014',
+ });
+ expect(gantt.groupBy).toEqual({
+ type: 'property',
+ propertyDefinitionId: '00000001-0000-0000-0000-000000000002',
+ });
+ });
+
it('scopes the list to the record without a property-only filter', () => {
const query = 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.ts
index c3249e9f75..bd85266910 100644
--- a/apps/web/src/features/tasks-view/queries/task-query.ts
+++ b/apps/web/src/features/tasks-view/queries/task-query.ts
@@ -10,6 +10,7 @@ import {
import { SYSTEM_PROPERTY_IDS } from '@property/constants';
import type { GroupByField } from '@queries/soup/grouped/types';
import type { SoupAstBody, SoupAstItemsQueryArgs } from '@queries/soup/items';
+import { match } from 'ts-pattern';
import {
EMPTY_TASK_FACET_CONTEXT,
TASK_FACETS,
@@ -124,7 +125,13 @@ export type BuildTaskQueryOptions = {
/** The Soup CRM association naming the record. */
export const taskCrmAssociation = (crm: TaskCrmScope) =>
- crm.type === 'company' ? { company: crm.id } : { contact: crm.id };
+ match(crm)
+ .with({ type: 'activity' }, () => 'activity' as const)
+ .with({ type: 'company' }, ({ id }) => ({ company: id }))
+ .with({ type: 'contact' }, ({ id }) => ({ contact: id }))
+ .exhaustive(() => {
+ throw new Error('Unsupported CRM task scope');
+ });
/** Builds the concrete Soup AST used only by the production Tasks view. */
export function buildTaskQuery(
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.ts
index 4f066e9b04..cf8c35b95c 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
@@ -604,3 +604,47 @@ it('admits only optimistic CRM tasks that name the record', () => {
}
});
});
+
+it('keeps activity membership in list and grouped paging and excludes optimistic rows', () => {
+ fixture.calls = [];
+ fixture.query = {
+ isLoading: false,
+ isPending: false,
+ isPlaceholderData: false,
+ data: { entities: [] },
+ };
+ createRoot((dispose) => {
+ try {
+ useTasksDataSource(
+ {
+ tab: 'team-tasks',
+ search: '',
+ facets: {},
+ groupBy: 'date',
+ sort: [],
+ },
+ {
+ userId: () => 'viewer',
+ tagSets: () => [],
+ tagSetsReady: () => true,
+ isGroupExpanded: () => true,
+ crm: () => ({ type: 'activity' }),
+ board: () => true,
+ }
+ );
+ const call = fixture.calls[0];
+ expect(
+ (call?.args() as { body: { crma: unknown } } | undefined)?.body.crma
+ ).toBe('activity');
+ expect(fixture.groupArgs?.soupBody().crma).toBe('activity');
+ const meta = call?.options?.() as {
+ meta: { insertFilter: (item: unknown) => boolean };
+ };
+ fixture.mapItem.mockReturnValueOnce(crmTask('linked', ['acme']));
+ expect(meta.meta.insertFilter({})).toBe(false);
+ expect(fixture.searchState).not.toHaveBeenCalled();
+ } 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.ts
index 37ff4ba3cc..4b52eaaa08 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
@@ -105,6 +105,7 @@ function referencesEntity(
* are known only to the server and arrive with the next fetch.
*/
function namesCrmRecord(task: TaskEntityWithProperties, crm: TaskCrmScope) {
+ if (crm.type === 'activity') return false;
return getTaskReferencedEntityIds(
task,
crm.type === 'company'
diff --git a/apps/web/src/features/tasks-view/tasks-content.tsx b/apps/web/src/features/tasks-view/tasks-content.tsx
index c87b7e43d8..4c8426634a 100644
--- a/apps/web/src/features/tasks-view/tasks-content.tsx
+++ b/apps/web/src/features/tasks-view/tasks-content.tsx
@@ -20,6 +20,7 @@ export function TasksLoading() {
/** Renders the selected layout from the host's task scope and navigation capabilities. */
export function TasksContent(props: {
ref?: (element: HTMLDivElement) => void;
+ referencePropertyIds?: readonly string[];
}) {
const { state } = useTasksView();
@@ -33,7 +34,10 @@ export function TasksContent(props: {
<TasksGantt ref={props.ref} />
</Match>
<Match when={state.layout === 'list'}>
- <TaskList ref={props.ref} />
+ <TaskList
+ ref={props.ref}
+ referencePropertyIds={props.referencePropertyIds}
+ />
</Match>
</Switch>
</Suspense>
diff --git a/apps/web/src/features/tasks-view/types.ts b/apps/web/src/features/tasks-view/types.ts
index 3f3b037cc9..09e8a73a1b 100644
--- a/apps/web/src/features/tasks-view/types.ts
+++ b/apps/web/src/features/tasks-view/types.ts
@@ -30,10 +30,9 @@ export type TaskReferenceScope = {
* 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 TaskCrmScope =
+ | { type: 'company' | 'contact'; id: string }
+ | { type: 'activity' };
export type TaskDetailTarget = {
id: string;
diff --git a/apps/web/src/lib/primitives/infinite-scroll-sentinel.ts b/apps/web/src/lib/primitives/infinite-scroll-sentinel.ts
index 85d00c1a34..fa802810ad 100644
--- a/apps/web/src/lib/primitives/infinite-scroll-sentinel.ts
+++ b/apps/web/src/lib/primitives/infinite-scroll-sentinel.ts
@@ -32,15 +32,15 @@ function findScrollableParent(el: HTMLElement | null): HTMLElement | null {
/**
* Fires `fetchNextPage` whenever the sentinel scrolls into (or close to)
* view, gated by `hasNextPage` + `isFetchingNextPage`. The observer is
- * torn down and re-created whenever the sentinel ref or `hasNextPage`
- * changes — when there are no more pages, no observer runs.
+ * torn down during a fetch and re-created when it completes. Re-observing
+ * triggers the next page if the sentinel remains visible after the append.
*/
export function useInfiniteScrollSentinel(
opts: UseInfiniteScrollSentinelOptions
) {
createEffect(() => {
const node = opts.sentinel();
- if (!node || !opts.hasNextPage()) return;
+ if (!node || !opts.hasNextPage() || opts.isFetchingNextPage()) return;
const observer = new IntersectionObserver(
(entries) => {
diff --git a/docs/agent-guide/crm.md b/docs/agent-guide/crm.md
index 02093e951a..3fa27d98e8 100644
--- a/docs/agent-guide/crm.md
+++ b/docs/agent-guide/crm.md
@@ -52,6 +52,29 @@ same preset. With an embedded company or contact detail open, global Create
prefills the current breadcrumb record; a contact also includes its company.
Closing the detail returns global Create to the unassociated CRM preset.
+Activity rows show stored Companies and Contacts reference pills in the shared
+Soup row. Click a pill to open its record; Shift-click opens a new split without
+opening the parent item. The first two references appear inline; **+N** opens
+the remainder. Email matches still determine feed membership, but an address
+or domain match without a stored property does not add a display pill. The row
+uses shared property previews rather than a separate association lookup.
+Verify these interactions at desktop and phone widths.
+Sidebar Tasks use the normal Tasks filters (status, priority, assignee, creator,
+and tags), sorting and grouping, with list/board/Gantt layouts when enabled. Touch
+uses the normal list and filter drawer. The default is open tasks grouped by date.
+Email exposes the normal read/done, attachment, calendar and tag filters. Notes has
+creator/tag filters and Calls has audience/tag filters. Email, Notes and Calls support
+last-updated/created/viewed sorting, newest/oldest direction, and date/none grouping.
+Email defaults to last-update date groups; Notes and Calls start ungrouped. Date
+headings use the selected sort field and viewer-local time. Filter controls share one
+desktop header; touch puts filters, sorting and grouping in a drawer beside search.
+Each activity keeps its own settings, independent of the normal app views.
+Clear filters removes only refinements, never the fixed CRM restriction. Verify
+switching away and back preserves the filter, sorting and grouping choices, that
+changing a filter starts a fresh query, and that local-only attachment/audience
+filters continue through pages with no visible rows. Stored association pills remain
+inline, and record-detail controls remain unchanged.
+
Verify activity loading with a CRM containing thousands of companies and
contacts, not only an empty fixture. Opening a tab must settle without repeated
requests; switching tabs must preserve filtering and scrolling must load older