Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(crm): add linked databases and improved list states (#9059)
dev-rbfc0d6c61bfaa
diff --git a/.sqlx/query-7358d6cac7636a9ba689b9eb205d3bc3feba103fbe638795e6aceb98d5c4b33d.json b/.sqlx/query-6127edc878cb974a9671b6b953e1379bcb4516d3b5b6817aa7b5b2b809a9654b.jsonsimilarity index 60%rename from .sqlx/query-7358d6cac7636a9ba689b9eb205d3bc3feba103fbe638795e6aceb98d5c4b33d.jsonrename to .sqlx/query-6127edc878cb974a9671b6b953e1379bcb4516d3b5b6817aa7b5b2b809a9654b.jsonindex f2797cee2b..cbf2438278 100644--- a/.sqlx/query-7358d6cac7636a9ba689b9eb205d3bc3feba103fbe638795e6aceb98d5c4b33d.json+++ b/.sqlx/query-6127edc878cb974a9671b6b953e1379bcb4516d3b5b6817aa7b5b2b809a9654b.json@@ -1,6 +1,6 @@{"db_name": "PostgreSQL",- "query": "\n SELECT ep.entity_type AS \"entity_type!: EntityType\", ep.entity_id AS \"entity_id!\"\n FROM UNNEST($1::text[]) AS company(id)\n JOIN entity_properties ep\n ON ep.property_definition_id = '00000001-0000-0000-0000-00000000000c'\n AND ep.values->'value' @> jsonb_build_array(jsonb_build_object('entity_id', company.id))\n UNION\n SELECT ep.entity_type, ep.entity_id\n FROM UNNEST($2::text[]) AS contact(id)\n JOIN entity_properties ep\n ON ep.property_definition_id = '00000001-0000-0000-0000-000000000013'\n AND ep.values->'value' @> jsonb_build_array(jsonb_build_object('entity_id', contact.id))\n ",+ "query": "\n SELECT ep.entity_type AS \"entity_type!: EntityType\", ep.entity_id AS \"entity_id!\"\n FROM UNNEST($1::text[]) AS company(id)\n JOIN entity_properties ep\n ON ep.property_definition_id = '00000001-0000-0000-0000-00000000000c'\n AND ep.values->'value' @> jsonb_build_array(jsonb_build_object('entity_id', company.id))\n UNION\n SELECT ep.entity_type, ep.entity_id\n FROM UNNEST($2::text[]) AS contact(id)\n JOIN entity_properties ep\n ON ep.property_definition_id = '00000001-0000-0000-0000-000000000013'\n AND ep.values->'value' @> jsonb_build_array(jsonb_build_object('entity_id', contact.id))\n UNION\n SELECT ep.entity_type, ep.entity_id\n FROM database_columns dc\n JOIN property_definitions pd\n ON pd.id = dc.property_definition_id AND pd.data_type = 'ENTITY'\n JOIN entity_properties ep\n ON ep.property_definition_id = dc.property_definition_id\n AND ep.entity_type = 'DATABASE_ROW'\n JOIN database_rows r\n ON r.id::text = ep.entity_id AND r.table_id = dc.table_id\n WHERE EXISTS (\n SELECT 1\n FROM jsonb_array_elements(\n CASE WHEN jsonb_typeof(ep.values->'value') = 'array'\n THEN ep.values->'value' ELSE '[]'::jsonb END\n ) AS reference\n WHERE (reference->>'entity_type' = 'COMPANY'\n AND reference->>'entity_id' = ANY($1::text[]))\n OR (reference->>'entity_type' = 'CONTACT'\n AND reference->>'entity_id' = ANY($2::text[]))\n )\n ","describe": {"columns": [{@@ -46,5 +46,5 @@null]},- "hash": "7358d6cac7636a9ba689b9eb205d3bc3feba103fbe638795e6aceb98d5c4b33d"+ "hash": "6127edc878cb974a9671b6b953e1379bcb4516d3b5b6817aa7b5b2b809a9654b"}diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex 74d7c097ab..5e86142bc9 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -190,6 +190,7 @@ the user's newest account for that app from the last fifteen minutes.- Share URL recognition with `packages/lexical-core/utils/auto-link.ts`; preserve explicit unlink markers when saving and rendering messages. See `packages/lexical-core/README.md` at the repository root.- Empty human DMs use the shared centered conversations graphic and explain email delivery to nonusers; keep this state out of agent DMs, loading/error states, and populated timelines.+- Keep CRM database discovery row-linked and permission-scoped; use horizontally centered actionable list states raised toward the toolbar and shared skeletons, with separate search-empty and retry states. See `src/features/crm/README.md` and `docs/agent-guide/crm.md` at the repo root.- Main Tasks mounts reusable GraphQL saved views; keep embedded Project/CRM task lists unchanged. Read `src/features/tasks-view/AGENTS.md` for filter, draft, navigation, and browser checks.- Enable persisted email/calendar review controls only for the review’s saved acting account; historical reviews fall back to the session owner. Require session edit access on desktop and mobile.- Email draft reads compare server generations before choosing cached delivery state over a restored working copy; only a definitive first-submission rejection permits local send recovery without server cancellation.diff --git a/apps/web/src/features/crm/README.md b/apps/web/src/features/crm/README.mdindex 9b08c1e9d7..8aa261c39e 100644--- a/apps/web/src/features/crm/README.md+++ b/apps/web/src/features/crm/README.md@@ -75,6 +75,23 @@ links; Notes excludes task, snippet and skill Markdown subtypes. Email matchesvisible company domains/contact addresses in the viewer's own mailbox, withoutteam-scope widening or requiring a property link on the email.+Databases is a row-linked activity view, not a direct database-to-CRM relation.+It opts into database rows with the same server-resolved CRM selector and lists+each containing database once, intersected with authorized database discovery.+A company includes rows linked to its visible contacts; a contact does not inherit+its company's rows. Empty row matches never fall back to all databases. Preserve+Soup pagination and CRM-link invalidation rather than enumerating CRM IDs or table+IDs in the browser. Database creation uses the existing app action; a database+joins the CRM list only after a row has a Companies or Contacts link.++CRM collection and record lists use full-height empty states, horizontally+centered and raised toward the toolbar, with+creation guidance, distinct search-empty actions, retryable error states, and+shared list skeletons. Keep search and available header actions visible in every+state. A failed continuation retains rows and retries that page.+Workspace activity uses the shared single-row desktop header with New and an+expandable Search control; record-detail tabs retain their section toolbar.+Activity rows render stored Companies and Contacts reference properties as inlinepills through the shared Soup row. Pills use the shared property preview and opena record independently of the row; additional values use the shared overflow menu.diff --git a/apps/web/src/features/crm/activity-filters-adapter.tsx b/apps/web/src/features/crm/activity-filters-adapter.tsxindex 9a3c168050..8ccf181436 100644--- a/apps/web/src/features/crm/activity-filters-adapter.tsx+++ b/apps/web/src/features/crm/activity-filters-adapter.tsx@@ -9,11 +9,11 @@ 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';+import type { CrmSoupActivityTab } from './core/navigation';/** Normal Email facets and the applicable Notes/Calls filters, with local intent. */export function createCrmActivityFilters(- tab: CrmActivityTab,+ tab: CrmSoupActivityTab,state: Store<CrmActivityViewState>,setState: SetStoreFunction<CrmActivityViewState>): ActivityFilters {diff --git a/apps/web/src/features/crm/activity-state-adapter.ts b/apps/web/src/features/crm/activity-state-adapter.tsindex f84890a730..436f08684c 100644--- a/apps/web/src/features/crm/activity-state-adapter.ts+++ b/apps/web/src/features/crm/activity-state-adapter.ts@@ -8,7 +8,7 @@ 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';+import type { CrmSoupActivityTab } from './core/navigation';const stateSchema = z.object({search: z.string(),@@ -19,7 +19,7 @@ const stateSchema = z.object({});/** Per-entry, per-activity controls never modify the ordinary app views. */-export function createCrmActivityState(tab: CrmActivityTab) {+export function createCrmActivityState(tab: CrmSoupActivityTab) {const panel = useSplitPanelOrThrow();const key = `crm.activity.${tab}`;const [state, setState] = withSplitPanelOwner(key, () =>diff --git a/apps/web/src/features/crm/activity-tasks-adapter.tsx b/apps/web/src/features/crm/activity-tasks-adapter.tsxindex 6913131128..debac4f8b1 100644--- a/apps/web/src/features/crm/activity-tasks-adapter.tsx+++ b/apps/web/src/features/crm/activity-tasks-adapter.tsx@@ -13,11 +13,18 @@ import {} from '@app/features/tasks-view/tasks-view-context';import { useSplitLayout } from '@components/app/split-layout/layout';import { isTouchDevice } from '@core/mobile/isTouchDevice';+import EmptyStateTasksGraphic from '@design/empty-state-tasks.svg';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 {+ CrmListEmpty,+ CrmListError,+ CrmListSearchEmpty,+ CrmListSkeleton,+} from './components/list-state';import { useCrmContext } from './context/crm-context';/** Production Tasks layouts for the workspace-wide CRM activity scope. */@@ -123,6 +130,30 @@ function ActivityTasksBody(props: {</Show><div class="min-h-0 flex-1"><TasksContent+ loadingContent={<CrmListSkeleton label="Loading tasks" />}+ errorContent={+ <CrmListError+ title="Tasks couldn’t be loaded."+ onRetry={() => source.refresh()}+ />+ }+ emptyContent={+ state.search.trim() && source.hasMore() ? (+ <span>Search more results to find matching tasks.</span>+ ) : state.search.trim() ? (+ <CrmListSearchEmpty+ title="No tasks match this search"+ onClearSearch={() => setState('search', '')}+ />+ ) : (+ <CrmListEmpty+ title="No tasks linked yet"+ graphic={EmptyStateTasksGraphic}+ description="Create a task and choose a company or person to keep your follow-ups here."+ action={{ label: 'New task', onClick: props.onCreateTask }}+ />+ )+ }ref={(element) => {listElement = element;}}diff --git a/apps/web/src/features/crm/components/crm-mobile-tabs.tsx b/apps/web/src/features/crm/components/crm-mobile-tabs.tsxindex 0006fff6a0..65f7c9c84a 100644--- a/apps/web/src/features/crm/components/crm-mobile-tabs.tsx+++ b/apps/web/src/features/crm/components/crm-mobile-tabs.tsx@@ -1,6 +1,9 @@import { useFeatureFlag } from '@app/lib/analytics/posthog';import { type PillTabItem, PillTabs } from '@components/app/mobile/PillTabs';-import { enableCrmActivity } from '@core/constant/featureFlags';+import {+ enableCrmActivity,+ enableDatabases,+} from '@core/constant/featureFlags';import type { JSX } from 'solid-js';import {CRM_ACTIVITY_TABS,@@ -16,10 +19,15 @@ export function CrmMobileTabs(props: {onNavigate(id: string): void;}) {const activityFlag = useFeatureFlag(enableCrmActivity);+ const databasesFlag = useFeatureFlag(enableDatabases);const items = (): PillTabItem[] => [...[...CRM_RECORDS,- ...(activityFlag().enabled ? CRM_ACTIVITY_TABS : []),+ ...(activityFlag().enabled+ ? CRM_ACTIVITY_TABS.filter(+ (tab) => tab.id !== 'databases' || databasesFlag().enabled+ )+ : []),].map((record) => ({value: record.id,label: record.label,diff --git a/apps/web/src/features/crm/components/crm-sidebar.tsx b/apps/web/src/features/crm/components/crm-sidebar.tsxindex d1ac5ab90d..9b8aca61fb 100644--- a/apps/web/src/features/crm/components/crm-sidebar.tsx+++ b/apps/web/src/features/crm/components/crm-sidebar.tsx@@ -1,7 +1,10 @@import { CollapsibleSection, ViewSidebar } from '@app/components/view-shell';import { useFeatureFlag } from '@app/lib/analytics/posthog';import { getIconConfig } from '@core/component/EntityIcon';-import { enableCrmActivity } from '@core/constant/featureFlags';+import {+ enableCrmActivity,+ enableDatabases,+} from '@core/constant/featureFlags';import { isTouchDevice } from '@core/mobile/isTouchDevice';import BuildingsIcon from '@icon/system/regular/buildings.svg';import ExportIcon from '@icon/system/regular/download-simple.svg';@@ -26,6 +29,7 @@ const RECORD_ICONS = {email: getIconConfig('email').icon,notes: getIconConfig('md').icon,calls: getIconConfig('call').icon,+ databases: getIconConfig('database').icon,};export function CrmSidebar(props: {@@ -54,6 +58,7 @@ export function CrmSidebar(props: {searchLabel?: string;}) {const activityFlag = useFeatureFlag(enableCrmActivity);+ const databasesFlag = useFeatureFlag(enableDatabases);const [recordsOpen, setRecordsOpen] = createSignal(true);const [listsOpen, setListsOpen] = createSignal(true);return (@@ -112,7 +117,12 @@ export function CrmSidebar(props: {<Foreach={[...CRM_RECORDS,- ...(activityFlag().enabled ? CRM_ACTIVITY_TABS : []),+ ...(activityFlag().enabled+ ? CRM_ACTIVITY_TABS.filter(+ (tab) =>+ tab.id !== 'databases' || databasesFlag().enabled+ )+ : []),]}>{(record) => (diff --git a/apps/web/src/features/crm/components/list-state.tsx b/apps/web/src/features/crm/components/list-state.tsxnew file mode 100644index 0000000000..f0b8e93a5d--- /dev/null+++ b/apps/web/src/features/crm/components/list-state.tsx@@ -0,0 +1,93 @@+import { ListSkeleton } from '@app/components/view-shell/ListSkeleton';+import { fireAndForget } from '@core/util/fireAndForget';+import EmptyStateCompaniesGraphic from '@design/empty-state-companies.svg';+import EmptyStateNoAccessGraphic from '@design/empty-state-no-access.svg';+import EmptyStateNoFilterMatchGraphic from '@design/empty-state-no-filter-match.svg';+import EmptyStateNoSearchMatchGraphic from '@design/empty-state-no-search-match.svg';+import { EmptyStatePanel } from '@ui';+import { type Component, For, type JSX } from 'solid-js';++/** Presentational states for CRM lists; the caller owns the query and actions. */+export function CrmListEmpty(props: {+ title: string;+ description?: JSX.Element;+ graphic?: Component<{ class?: string }>;+ action?: { label: string; onClick: () => void };+ filtered?: boolean;+}) {+ return (+ <EmptyStatePanel+ centered+ topSpacerClass="grow-[0.5] basis-0 mobile:basis-0"+ graphic={+ props.filtered+ ? EmptyStateNoFilterMatchGraphic+ : (props.graphic ?? EmptyStateCompaniesGraphic)+ }+ title={props.title}+ description={props.description}+ primaryAction={props.action}+ />+ );+}++export function CrmListSearchEmpty(props: {+ title: string;+ description?: string;+ onClearSearch?: () => void;+}) {+ return (+ <EmptyStatePanel+ centered+ topSpacerClass="grow-[0.5] basis-0 mobile:basis-0"+ graphic={EmptyStateNoSearchMatchGraphic}+ title={props.title}+ description={props.description ?? 'Try a different search.'}+ primaryAction={+ props.onClearSearch+ ? { label: 'Clear search', onClick: props.onClearSearch }+ : undefined+ }+ />+ );+}++export function CrmListError(props: {+ title?: string;+ onRetry: () => Promise<unknown>;+}) {+ return (+ <EmptyStatePanel+ centered+ topSpacerClass="grow-[0.5] basis-0 mobile:basis-0"+ graphic={EmptyStateNoAccessGraphic}+ description="Please try again to reload this view."+ title={props.title ?? "Couldn't load this list."}+ primaryAction={{+ label: 'Try again',+ onClick: () => fireAndForget(props.onRetry(), 'crm'),+ }}+ />+ );+}++export function CrmListSkeleton(props: { label?: string; count?: number }) {+ return (+ <ListSkeleton.Root+ label={props.label ?? 'Loading CRM list'}+ class="w-full shrink-0 py-2"+ >+ <For each={Array.from({ length: props.count ?? 6 })}>+ {() => (+ <ListSkeleton.Row class="gap-3 px-4">+ <ListSkeleton.Bar class="size-7 shrink-0 rounded-full" />+ <div class="flex min-w-0 flex-1 flex-col gap-2">+ <ListSkeleton.Bar class="w-1/2" />+ <ListSkeleton.Bar class="h-2 w-2/3 opacity-60" />+ </div>+ </ListSkeleton.Row>+ )}+ </For>+ </ListSkeleton.Root>+ );+}diff --git a/apps/web/src/features/crm/components/record-section.tsx b/apps/web/src/features/crm/components/record-section.tsxindex 6676fe33a3..3984ee2d0c 100644--- a/apps/web/src/features/crm/components/record-section.tsx+++ b/apps/web/src/features/crm/components/record-section.tsx@@ -36,7 +36,7 @@ export function RecordSection(</div></Show></div>- <div class="min-h-0 flex-1 overflow-y-auto px-2 pb-6 touch:pb-[calc(var(--mobile-content-inset-bottom,0px)+1.5rem)] touch:[--mobile-content-inset-top:0px]">+ <div class="flex min-h-0 flex-1 flex-col overflow-y-auto px-2 pb-6 touch:pb-[calc(var(--mobile-content-inset-bottom,0px)+1.5rem)] touch:[--mobile-content-inset-top:0px]">{props.children}</div></section>diff --git a/apps/web/src/features/crm/components/record-tabs.tsx b/apps/web/src/features/crm/components/record-tabs.tsxindex 53c03f2c1f..23c97c6f4a 100644--- a/apps/web/src/features/crm/components/record-tabs.tsx+++ b/apps/web/src/features/crm/components/record-tabs.tsx@@ -1,4 +1,6 @@+import { useFeatureFlag } from '@app/lib/analytics/posthog';import { getIconConfig } from '@core/component/EntityIcon';+import { enableDatabases } from '@core/constant/featureFlags';import SquaresFourIcon from '@icon/system/regular/squares-four.svg';import UsersIcon from '@icon/system/regular/users.svg';import { Tabs } from '@ui';@@ -18,6 +20,7 @@ const SECTION_ICONS: Record<files: getIconConfig('files').icon,tasks: getIconConfig('task').icon,calls: getIconConfig('call').icon,+ databases: getIconConfig('database').icon,};/**@@ -30,16 +33,19 @@ export function RecordTabs<S extends CrmRecordSection>(props: {onChange: (section: S) => void;compact?: boolean;}) {+ const databasesFlag = useFeatureFlag(enableDatabases);return (<Tabsaria-label="Record sections"touch="inset"class="shrink-0"- options={props.sections.map((section) => ({- value: section,- label: CRM_RECORD_SECTION_LABELS[section],- icon: props.compact ? SECTION_ICONS[section] : undefined,- }))}+ options={props.sections+ .filter((section) => section !== 'databases' || databasesFlag().enabled)+ .map((section) => ({+ value: section,+ label: CRM_RECORD_SECTION_LABELS[section],+ icon: props.compact ? SECTION_ICONS[section] : undefined,+ }))}iconOnly={props.compact}value={props.value}onChange={props.onChange}diff --git a/apps/web/src/features/crm/context/crm-context.tsx b/apps/web/src/features/crm/context/crm-context.tsxindex 52dc87c5e0..598fdd98a0 100644--- a/apps/web/src/features/crm/context/crm-context.tsx+++ b/apps/web/src/features/crm/context/crm-context.tsx@@ -22,7 +22,7 @@ import type {CrmDisplayOptions,CrmListColumnId,} from '../core/display-options';-import type { CrmActivityTab } from '../core/navigation';+import type { CrmSoupActivityTab } from '../core/navigation';import type { Pipeline } from '../core/pipeline';import type { CrmRecordScope, CrmTaskRecord } from '../core/record';import type {@@ -96,17 +96,21 @@ export type CrmContext = {): ItemListSource;/** Paged CRM-wide activity, limited to associated records. */createActivity(- tab: Accessor<CrmActivityTab>,+ tab: Accessor<CrmSoupActivityTab>,options?: Accessor<CrmActivityViewState>): ItemListSource;+ /** Databases containing CRM-linked rows; undefined selects the workspace scope. */+ createDatabases(scope: Accessor<CrmRecordScope | undefined>): ItemListSource;+ openCreateItem(kind: 'notes' | 'calls' | 'databases'): void;+ openEmailComposer(recipient?: string): void;createActivityState(- tab: CrmActivityTab+ tab: CrmSoupActivityTab): readonly [Store<CrmActivityViewState>,SetStoreFunction<CrmActivityViewState>,];createActivityFilters(- tab: CrmActivityTab,+ tab: CrmSoupActivityTab,state: Store<CrmActivityViewState>,setState: SetStoreFunction<CrmActivityViewState>): ActivityFilters;diff --git a/apps/web/src/features/crm/core/navigation.ts b/apps/web/src/features/crm/core/navigation.tsindex a1d9a5c858..d8c1fb840a 100644--- a/apps/web/src/features/crm/core/navigation.ts+++ b/apps/web/src/features/crm/core/navigation.ts@@ -10,9 +10,11 @@ export const CRM_ACTIVITY_TABS = [{ id: 'email', label: 'Email' },{ id: 'notes', label: 'Notes' },{ id: 'calls', label: 'Calls' },+ { id: 'databases', label: 'Databases' },] as const;export type CrmActivityTab = (typeof CRM_ACTIVITY_TABS)[number]['id'];+export type CrmSoupActivityTab = Exclude<CrmActivityTab, 'databases'>;export function isCrmActivityTab(value: string): value is CrmActivityTab {return CRM_ACTIVITY_TABS.some((tab) => tab.id === value);diff --git a/apps/web/src/features/crm/core/record.ts b/apps/web/src/features/crm/core/record.tsindex 2f5694dbbe..70afe7aa9c 100644--- a/apps/web/src/features/crm/core/record.ts+++ b/apps/web/src/features/crm/core/record.ts@@ -42,6 +42,7 @@ export const COMPANY_SECTIONS = ['files','tasks','calls',+ 'databases',] as const;export const CONTACT_SECTIONS = ['overview',@@ -49,6 +50,7 @@ export const CONTACT_SECTIONS = ['files','tasks','calls',+ 'databases',] as const;export type CompanySection = (typeof COMPANY_SECTIONS)[number];@@ -62,4 +64,5 @@ export const CRM_RECORD_SECTION_LABELS: Record<CrmRecordSection, string> = {files: 'Files',tasks: 'Tasks',calls: 'Calls',+ databases: 'Databases',};diff --git a/apps/web/src/features/crm/crm-adapter.ts b/apps/web/src/features/crm/crm-adapter.tsindex 6745ca2335..d12fa54405 100644--- a/apps/web/src/features/crm/crm-adapter.ts+++ b/apps/web/src/features/crm/crm-adapter.ts@@ -1,5 +1,6 @@import { useCreateContext } from '@app/features/command/context/create-context';import { useQuickAccessCrmCompaniesQuery } from '@app/features/crm/crm-search';+import { composeEmail } from '@app/features/email-view/compose-email';import { withEntityNotifications } from '@app/features/soup/entity-notifications';import { useFeatureFlag } from '@app/lib/analytics/posthog';import { useGlobalNotificationSource } from '@components/app/GlobalAppState';@@ -10,21 +11,29 @@ import {enableCrmActivity,enableCrmLists,enableCrmPipelines,+ enableDatabases,} from '@core/constant/featureFlags';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 { fireAndForget } from '@core/util/fireAndForget';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';+import { createSoupLiveQuery } from '@queries/soup/graphql/create-soup-live-query';import {type SoupAstItemsQuery,useSoupAstItemsQuery,} from '@queries/soup/items';import { getSoupEntityById } from '@queries/soup/normalized-cache';+import {+ onDatabaseBatchCommitted,+ onDatabaseTableAdvanced,+ useDatabasesQuery,+} from '@queries/storage/databases';import {invalidateUserTeams,useCurrentTeamQuery,@@ -33,6 +42,7 @@ import {import { patchTeamCrmSettings } from '@service-auth/crm';import { storageServiceClient } from '@service-storage/client';import { getGraphqlSoupClient } from '@service-storage/graphql-soup';+import { useNavigate } from '@solidjs/router';import { useQueryClient } from '@tanstack/solid-query';import { createMemo, lazy } from 'solid-js';import { createTagFacetContext } from '../soup';@@ -73,6 +83,7 @@ import {useSetContactHiddenMutation,useSetContactNameMutation,} from './queries/contacts';+import { createCrmDatabasesSource } from './queries/databases';import { fetchCrmExportCompanies } from './queries/export';import { useCrmLists } from './queries/lists';import { createPipelineTransfer } from './queries/pipeline-transfer';@@ -191,6 +202,20 @@ export function createAppCrmContext(): CrmContext {const panel = useSplitPanel();const createContext = useCreateContext();const activityFlag = useFeatureFlag(enableCrmActivity);+ const databasesFlag = useFeatureFlag(enableDatabases);+ const navigate = useNavigate();+ const openCreateItem = async (kind: 'notes' | 'calls' | 'databases') => {+ if (kind === 'calls') {+ navigate('/meet/new');+ return;+ }+ const { runCreateAction } = await import('@app/features/command/Launcher');+ const type = {+ notes: 'md',+ databases: 'database',+ } as const;+ runCreateAction(type[kind], { source: 'crm' });+ };const createSettings = () => useTeamCrmConfig(deps);return {registerTaskComposerRecord(source) {@@ -234,6 +259,24 @@ export function createAppCrmContext(): CrmContext {withRowNotifications(useContactEmailsQuery(useSoupAstItemsQuery, ...args)),+ createDatabases: (scope) =>+ createCrmDatabasesSource(+ {+ createRows: createSoupLiveQuery,+ createListing: useDatabasesQuery,+ onCommitted: onDatabaseBatchCommitted,+ onTableAdvanced: onDatabaseTableAdvanced,+ },+ scope,+ () => !!userId() && databasesFlag().enabled+ ),+ openCreateItem: (kind) => fireAndForget(openCreateItem(kind), 'crm'),+ openEmailComposer: (recipient) =>+ composeEmail(+ layout.openWithSplit,+ undefined,+ recipient ? [recipient] : undefined+ ),createActivity: (tab, options) => {const tags = useTagSets();const tagsReady = useTagSetsReady();diff --git a/apps/web/src/features/crm/pipeline-adapter.tsx b/apps/web/src/features/crm/pipeline-adapter.tsxindex 3f213e3df0..c5c09bdd35 100644--- a/apps/web/src/features/crm/pipeline-adapter.tsx+++ b/apps/web/src/features/crm/pipeline-adapter.tsx@@ -44,6 +44,7 @@ import {import type { BoardPositions } from '../database/views/database-board-view';import { DatabaseRecords } from '../database/views/database-records';import type { DatabaseRecordsActions } from '../database/views/database-records-view';+import { CrmListSkeleton } from './components/list-state';import type { Pipeline } from './core/pipeline';import { createPipelineApi } from './queries/pipeline-data';import {@@ -88,11 +89,7 @@ export function PipelineDatabaseEditor(props: {class="@container/database flex min-h-0 min-w-0 flex-1 flex-col overflow-hidden bg-canvas-base text-ink"style={{ '--database-title-column-width': '18rem' }}>- <Suspense- fallback={- <div class="p-4 text-sm text-ink-muted">Loading pipeline…</div>- }- >+ <Suspense fallback={<CrmListSkeleton label="Loading pipeline" />}><Show when={props.pipeline.id} keyed>{(_id) => (<PipelineRecordsdiff --git a/apps/web/src/features/crm/queries/activity-filter.ts b/apps/web/src/features/crm/queries/activity-filter.tsindex 03d16f2b11..5c9403d12d 100644--- a/apps/web/src/features/crm/queries/activity-filter.ts+++ b/apps/web/src/features/crm/queries/activity-filter.ts@@ -1,7 +1,7 @@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';+import type { CrmSoupActivityTab } from '../core/navigation';const NO_CRM_ACTIVITY = {calf: { l: { id: NIL_UUID } },@@ -18,7 +18,7 @@ const NO_CRM_ACTIVITY = {/** The server resolves all visible CRM records before filtering and pagination. */export function crmActivityBody(- tab: CrmActivityTab+ tab: CrmSoupActivityTab): BackendAstMap & Pick<SoupAstBody, 'crma' | 'emailView'> {const base = { ...NO_CRM_ACTIVITY, crma: 'activity' as const };if (tab === 'email') {diff --git a/apps/web/src/features/crm/queries/activity-options.ts b/apps/web/src/features/crm/queries/activity-options.tsindex ff2cf738dd..62dbd28f80 100644--- a/apps/web/src/features/crm/queries/activity-options.ts+++ b/apps/web/src/features/crm/queries/activity-options.ts@@ -14,12 +14,12 @@ import {testFacets,} from '../../soup';import type { CrmActivityViewState } from '../core/activity-view';-import type { CrmActivityTab } from '../core/navigation';+import type { CrmSoupActivityTab } from '../core/navigation';import { crmActivityBody } from './activity-filter';/** Refine, never replace, the fixed CRM and entity-type predicates. */export function buildCrmActivityQuery(- tab: CrmActivityTab,+ tab: CrmSoupActivityTab,options?: CrmActivityViewState,facetContext: TagFacetContext = EMPTY_TAG_FACET_CONTEXT): SoupAstItemsQueryArgs {@@ -42,7 +42,7 @@ export function buildCrmActivityQuery(/** Attachment and audience predicates mirror the ordinary Email and Calls lists. */export function crmActivityItemMatches(entity: EntityData,- tab: CrmActivityTab,+ tab: CrmSoupActivityTab,options: CrmActivityViewState,facetContext: TagFacetContext): boolean {diff --git a/apps/web/src/features/crm/queries/activity.test.ts b/apps/web/src/features/crm/queries/activity.test.tsindex eb8328afc5..f91471b6da 100644--- a/apps/web/src/features/crm/queries/activity.test.ts+++ b/apps/web/src/features/crm/queries/activity.test.ts@@ -7,7 +7,7 @@ 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 type { CrmSoupActivityTab } from '../core/navigation';import { useCrmActivityQuery } from './activity';import { crmActivityBody } from './activity-filter';import {@@ -15,7 +15,7 @@ import {crmActivityItemMatches,} from './activity-options';-const tabs: CrmActivityTab[] = ['tasks', 'notes', 'calls', 'email'];+const tabs: CrmSoupActivityTab[] = ['tasks', 'notes', 'calls', 'email'];describe('CRM activity queries', () => {it.each(tabs)(@@ -58,7 +58,7 @@ describe('CRM activity queries', () => {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 [tab, setTab] = createSignal<CrmSoupActivityTab>('tasks');const query: SoupAstItemsQuery = {data: undefined,error: new Error('Request failed'),diff --git a/apps/web/src/features/crm/queries/activity.ts b/apps/web/src/features/crm/queries/activity.tsindex ecb0764625..5ed3fe63e9 100644--- a/apps/web/src/features/crm/queries/activity.ts+++ b/apps/web/src/features/crm/queries/activity.ts@@ -6,13 +6,13 @@ import {tagFacetReady,} from '../../soup';import type { CrmActivityViewState } from '../core/activity-view';-import type { CrmActivityTab } from '../core/navigation';+import type { CrmSoupActivityTab } from '../core/navigation';import { buildCrmActivityQuery } from './activity-options';/** A bounded query for the complete authorized CRM activity feed. */export function useCrmActivityQuery(createQuery: typeof useSoupAstItemsQuery,- tab: Accessor<CrmActivityTab>,+ tab: Accessor<CrmSoupActivityTab>,userId: Accessor<string | undefined>,options?: Accessor<CrmActivityViewState>,facetContext: Accessor<TagFacetContext> = () => EMPTY_TAG_FACET_CONTEXT,diff --git a/apps/web/src/features/crm/queries/databases.ts b/apps/web/src/features/crm/queries/databases.tsnew file mode 100644index 0000000000..647189ff36--- /dev/null+++ b/apps/web/src/features/crm/queries/databases.ts@@ -0,0 +1,143 @@+import { fireAndForget } from '@core/util/fireAndForget';+import type { DatabaseEntity } from '@entity';+import { registerActiveGraphqlSoupQuery } from '@queries/soup/graphql/active-queries';+import type {+ createSoupLiveQuery,+ SoupLiveQueryInput,+} from '@queries/soup/graphql/create-soup-live-query';+import { buildGraphqlEntitySoupInput } from '@queries/soup/graphql/entity-input';+import type {+ onDatabaseBatchCommitted,+ onDatabaseTableAdvanced,+ useDatabasesQuery,+} from '@queries/storage/databases';+import type { ListedDatabase } from '@service-storage/generated/schemas/listedDatabase';+import type { Accessor } from 'solid-js';+import { createMemo, onCleanup } from 'solid-js';+import { NIL as NIL_UUID } from 'uuid';+import type { ItemListSource } from '../context/crm-sources';+import type { CrmRecordScope } from '../core/record';+import { crmAssociation } from './record-items';++/** Opt into database rows while excluding every other Soup source. */+export function crmDatabasesInput(+ scope?: CrmRecordScope+): SoupLiveQueryInput | undefined {+ const input = buildGraphqlEntitySoupInput('DATABASE_ROW', NIL_UUID)?.initial;+ if (!input) return undefined;+ return {+ ...input,+ limit: 100,+ filters: {+ ...input.filters,+ databaseRowFilter: { literal: { include: true } },+ crmAssociation: scope ? crmAssociation(scope) : { activity: true },+ },+ };+}++/** A database appears once, only after an authorized associated row names it. */+export function selectCrmDatabases(+ rows: readonly { databaseId: string }[],+ listed: readonly ListedDatabase[]+): DatabaseEntity[] {+ const databases = new Map(listed.map((entry) => [entry.database.id, entry]));+ return [...new Set(rows.map((row) => row.databaseId))].flatMap((id) => {+ const entry = databases.get(id);+ if (!entry || entry.database.trashed_at) return [];+ return [+ {+ type: 'database',+ id,+ name: entry.database.name,+ ownerId: entry.database.owner_id,+ createdAt: entry.database.created_at,+ grant: entry.grant,+ },+ ];+ });+}++/** Reuse Soup's authorization, cursor chain, and CRM-link invalidation. */+export function createCrmDatabasesSource(+ sources: {+ createRows: typeof createSoupLiveQuery;+ createListing: typeof useDatabasesQuery;+ onCommitted: typeof onDatabaseBatchCommitted;+ onTableAdvanced: typeof onDatabaseTableAdvanced;+ },+ scope: Accessor<CrmRecordScope | undefined>,+ enabled: Accessor<boolean>+): ItemListSource {+ const rows = sources.createRows(+ () => crmDatabasesInput(scope()),+ () => ({+ enabled: enabled(),+ keepPreviousData: false,+ })+ );+ const listing = sources.createListing();+ const refresh = async () => {+ await Promise.all([+ rows.refresh(),+ listing.refetch({ throwOnError: true }),+ ]);+ };+ onCleanup(+ registerActiveGraphqlSoupQuery({+ isEnabled: enabled,+ body: () => {+ const current = scope();+ return { crma: current ? crmAssociation(current) : 'activity' };+ },+ refresh,+ })+ );+ const refreshAfterWrite = () => {+ if (enabled()) fireAndForget(refresh(), 'crm');+ };+ onCleanup(sources.onCommitted(refreshAfterWrite));+ onCleanup(sources.onTableAdvanced(refreshAfterWrite));+ const data = createMemo(() => {+ const items = rows.data();+ if (listing.isPending || !items) return undefined;+ return {+ entities: selectCrmDatabases(+ items.flatMap((item) =>+ item.__typename === 'GraphqlSoupDatabaseRow' ? [item] : []+ ),+ listing.data ?? []+ ),+ };+ });+ return {+ get data() {+ return data();+ },+ get isPending() {+ return !listing.isError && !rows.error() && data() === undefined;+ },+ get isEnabled() {+ return enabled();+ },+ get isLoading() {+ return rows.isLoading() || listing.isLoading;+ },+ get isError() {+ return (+ listing.isError || (!!rows.error() && !rows.isFetchNextPageError())+ );+ },+ get isFetchNextPageError() {+ return rows.isFetchNextPageError();+ },+ get hasNextPage() {+ return rows.hasNextPage();+ },+ get isFetchingNextPage() {+ return rows.isFetchingNextPage();+ },+ fetchNextPage: () => rows.fetchNextPage(),+ refetch: refresh,+ };+}diff --git a/apps/web/src/features/crm/record-tasks-adapter.tsx b/apps/web/src/features/crm/record-tasks-adapter.tsxindex c3127ddfbb..d563181439 100644--- a/apps/web/src/features/crm/record-tasks-adapter.tsx+++ b/apps/web/src/features/crm/record-tasks-adapter.tsx@@ -10,10 +10,17 @@ import {enableCrmActivity,isFeatureEnabled,} from '@core/constant/featureFlags';+import EmptyStateTasksGraphic from '@design/empty-state-tasks.svg';import PlusIcon from '@icon/system/regular/plus.svg';import { TagSetsQueryProvider } from '@property/tags/tag-sets-context';import { Button } from '@ui';import { Show } from 'solid-js';+import {+ CrmListEmpty,+ CrmListError,+ CrmListSearchEmpty,+ CrmListSkeleton,+} from './components/list-state';import { RecordSection } from './components/record-section';import type { CrmRecordScope } from './core/record';import { crmTaskComposerContext } from './task-composer';@@ -58,7 +65,7 @@ export function CrmRecordTasks(props: { scope: CrmRecordScope }) {}function RecordTasksBody(props: { scope: CrmRecordScope }) {- const { state, setState } = useTasksView();+ const { state, setState, source } = useTasksView();const layout = useSplitLayout();let listElement: HTMLDivElement | undefined;@@ -95,6 +102,30 @@ function RecordTasksBody(props: { scope: CrmRecordScope }) {}><TaskList+ loadingContent={<CrmListSkeleton label="Loading tasks" />}+ errorContent={+ <CrmListError+ title="Tasks couldn’t be loaded."+ onRetry={() => source.refresh()}+ />+ }+ emptyContent={+ state.search.trim() && source.hasMore() ? (+ <span>Search more results to find matching tasks.</span>+ ) : state.search.trim() ? (+ <CrmListSearchEmpty+ title="No tasks match this search"+ onClearSearch={() => setState('search', '')}+ />+ ) : (+ <CrmListEmpty+ title="No tasks yet"+ graphic={EmptyStateTasksGraphic}+ description="Tasks associated with this record will appear here."+ action={{ label: 'New task', onClick: composeTask }}+ />+ )+ }ref={(element) => {listElement = element;}}diff --git a/apps/web/src/features/crm/views/activity-section.tsx b/apps/web/src/features/crm/views/activity-section.tsxnew file mode 100644index 0000000000..3ce488a6c6--- /dev/null+++ b/apps/web/src/features/crm/views/activity-section.tsx@@ -0,0 +1,98 @@+import {+ SearchBar,+ useViewControlHotkeys,+ ViewShell,+} from '@app/components/view-shell';+import {+ ListHeader,+ ListHeaderSearch,+} from '@app/components/view-shell/ListHeader';+import { ViewCreateButton } from '@app/components/view-shell/ViewCreateButton';+import { isTouchDevice } from '@core/mobile/isTouchDevice';+import PlusIcon from '@icon/system/regular/plus.svg';+import { Button } from '@ui';+import { type JSX, type ParentProps, Show } from 'solid-js';+import { useCrmWorkspace } from '../context/workspace-context';++/** Workspace lists share the app header; record tabs keep their own toolbar. */+export function ActivitySection(+ props: ParentProps<{+ label: string;+ title?: JSX.Element;+ search: string;+ onSearchChange: (value: string) => void;+ createLabel: string;+ onCreate: () => void;+ controls?: JSX.Element;+ }>+) {+ const view = useCrmWorkspace();+ let focusSearch: (() => void) | undefined;+ const searchLabel = () => `Search ${props.label.toLowerCase()}`;+ useViewControlHotkeys({+ scopeId: view.host.scopeId,+ enabled: view.host.isActive,+ search: {+ description: searchLabel(),+ run: () => {+ focusSearch?.();+ return true;+ },+ },+ });++ return (+ <section+ aria-label={props.label}+ class="@container/record flex min-h-0 min-w-0 flex-1 flex-col"+ >+ <Show+ when={!isTouchDevice()}+ fallback={+ <ViewShell.Header class="py-2">+ <div class="flex min-w-0 items-center gap-3">+ {props.controls}+ <SearchBar+ ref={(element) => {+ focusSearch = () => {+ element.focus();+ element.select();+ };+ }}+ size="sm"+ label={searchLabel()}+ value={props.search}+ onValueChange={props.onSearchChange}+ onEscape={view.host.focus}+ class="min-w-0 flex-1"+ />+ <Button variant="secondary" onClick={props.onCreate}>+ <PlusIcon class="size-4" />+ {props.createLabel}+ </Button>+ </div>+ </ViewShell.Header>+ }+ >+ <ListHeader title={props.title ?? props.label}>+ {props.controls}+ <ViewCreateButton+ aria-label={props.createLabel}+ tooltip={props.createLabel}+ onClick={props.onCreate}+ />+ <ListHeaderSearch+ label={searchLabel()}+ value={props.search}+ onValueChange={props.onSearchChange}+ onEscape={view.host.focus}+ registerFocus={(focus) => (focusSearch = focus)}+ />+ </ListHeader>+ </Show>+ <div class="flex min-h-0 flex-1 flex-col overflow-y-auto px-2 pb-6 touch:pb-[calc(var(--mobile-content-inset-bottom,0px)+1.5rem)] touch:[--mobile-content-inset-top:0px]">+ {props.children}+ </div>+ </section>+ );+}diff --git a/apps/web/src/features/crm/views/activity.tsx b/apps/web/src/features/crm/views/activity.tsxindex e651bbf0e5..7575affa0a 100644--- a/apps/web/src/features/crm/views/activity.tsx+++ b/apps/web/src/features/crm/views/activity.tsx@@ -1,39 +1,75 @@-import { SearchBar, ViewShell } from '@app/components/view-shell';-import {- ListHeader,- ListHeaderSearch,-} from '@app/components/view-shell/ListHeader';-import { isTouchDevice } from '@core/mobile/isTouchDevice';+import EmptyStateCallsGraphic from '@design/empty-state-calls.svg';+import EmptyStateDocGraphic from '@design/empty-state-doc.svg';+import EmptyStateEmailGraphic from '@design/empty-state-email.svg';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 { CrmListEmpty } from '../components/list-state';import { useCrmContext } from '../context/crm-context';-import type { CrmActivityTab } from '../core/navigation';+import type { CrmActivityTab, CrmSoupActivityTab } from '../core/navigation';+import { ActivitySection } from './activity-section';+import { CrmDatabasesView } from './databases';import { RecordItemList } from './record-item-list';-/** Embedded activity uses normal view controls around an immutable CRM scope. */+const CONTENT = {+ email: {+ title: 'Email',+ graphic: EmptyStateEmailGraphic,+ action: 'New email',+ description:+ 'Email your CRM companies and people to see those conversations here.',+ },+ notes: {+ title: 'Notes',+ graphic: EmptyStateDocGraphic,+ action: 'New note',+ description:+ 'Create a note and link a company or person through its Companies or Contacts property.',+ },+ calls: {+ title: 'Calls',+ graphic: EmptyStateCallsGraphic,+ action: 'New call',+ description:+ 'Start a call with your CRM contacts, or link a company or person to an existing call.',+ },+};++/** Workspace activity combines normal view controls with the fixed CRM scope. */export function CrmActivityView(props: {tab: CrmActivityTab;title?: JSX.Element;}) {const crm = useCrmContext();+ const tab = () => (props.tab === 'databases' ? undefined : props.tab);return (<Show- when={props.tab !== 'tasks' ? props.tab : undefined}+ when={tab()}keyed- fallback={<crm.ActivityTasks title={props.title} />}+ fallback={<CrmDatabasesView title={props.title} />}>- {(tab) => (- <TagSetsQueryProvider>- <ActivityList tab={tab} title={props.title} />- </TagSetsQueryProvider>+ {(current) => (+ <Show+ when={current !== 'tasks' ? current : undefined}+ keyed+ fallback={<crm.ActivityTasks title={props.title} />}+ >+ {(activity) => (+ <TagSetsQueryProvider>+ <ActivityList tab={activity} title={props.title} />+ </TagSetsQueryProvider>+ )}+ </Show>)}</Show>);}-function ActivityList(props: { tab: CrmActivityTab; title?: JSX.Element }) {+function ActivityList(props: {+ tab: Exclude<CrmSoupActivityTab, 'tasks'>;+ title?: JSX.Element;+}) {const crm = useCrmContext();const [state, setState] = crm.createActivityState(props.tab);const filters = crm.createActivityFilters(props.tab, state, setState);@@ -41,58 +77,60 @@ function ActivityList(props: { tab: CrmActivityTab; title?: JSX.Element }) {() => 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)}- />- );+ const content = () => CONTENT[props.tab];+ const create = () => {+ if (props.tab === 'email') return crm.openEmailComposer();+ return crm.openCreateItem(props.tab);+ };return (- <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"+ <ActivitySection+ label={content().title}+ title={props.title}+ search={state.search}+ onSearchChange={(search) => setState('search', search)}+ createLabel={content().action}+ onCreate={create}+ controls={+ <ActivityControls+ label={props.tab}+ state={state}+ filters={filters}+ setSort={(sort) => setState('sort', sort)}+ setDirection={(direction) => setState('direction', direction)}+ setGroupBy={(groupBy) => setState('groupBy', groupBy)}+ />+ }+ >+ <RecordItemList+ source={source}+ search={state.search}+ onClearSearch={() => setState('search', '')}+ groupByDate={state.groupBy === 'date'}+ dateField={state.sort}+ referencePropertyIds={[+ SYSTEM_PROPERTY_IDS.COMPANIES,+ SYSTEM_PROPERTY_IDS.CONTACTS,+ ]}+ emptyContent={+ <Show+ when={filters.activeCount() === 0}+ fallback={+ <CrmListEmpty+ title={`No ${props.tab} match these filters`}+ description="Clear your filters to see all CRM-linked items."+ action={{ label: 'Clear filters', onClick: filters.clear }}/>- </div>- </ViewShell.Header>+ }+ >+ <CrmListEmpty+ graphic={content().graphic}+ title={`No ${props.tab} linked yet`}+ description={content().description}+ action={{ label: content().action, onClick: create }}+ />+ </Show>}- >- <ListHeader title={props.title ?? props.tab}>- {controls()}- <ListHeaderSearch- label={`Search ${props.tab}`}- value={state.search}- onValueChange={(search) => setState('search', search)}- registerFocus={() => {}}- />- </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>+ />+ </ActivitySection>);}diff --git a/apps/web/src/features/crm/views/companies.tsx b/apps/web/src/features/crm/views/companies.tsxindex 6c33967685..f9b6752a07 100644--- a/apps/web/src/features/crm/views/companies.tsx+++ b/apps/web/src/features/crm/views/companies.tsx@@ -1,6 +1,7 @@import { isTouchDevice } from '@core/mobile/isTouchDevice';import { Show, Suspense } from 'solid-js';import { SoupViewList } from '../../next-soup/soup-view/soup-view';+import { CrmListError, CrmListSkeleton } from '../components/list-state';import { useCrmWorkspace } from '../context/workspace-context';import { CompanyGroupHeader } from './company-group-header';import { ResponsiveCompanyListHeader } from './company-list-header';@@ -21,12 +22,23 @@ export function Companies() {data-list-view="companies"><div class="relative grow min-h-1 flex max-sm:flex-col flex-row size-full">- <Suspense>+ <Suspense fallback={<CrmListSkeleton />}><Showwhen={people()}fallback={<SoupViewList- emptyContent={<CrmEmptyState />}+ emptyState={(state) => (+ <CrmEmptyState+ filtered={state.filtered}+ onClearFilters={state.clearFilters}+ onClearPeopleSearch={options.clearPeopleSearch}+ onEditList={options.editList}+ />+ )}+ loadingContent={<CrmListSkeleton />}+ errorContent={(retry) => (+ <CrmListError onRetry={async () => retry()} />+ )}onOpenEntity={options.onOpenEntity}rowEntry={{ component: CompanyListEntity, family: 'row' }}groupHeader={CompanyGroupHeader}@@ -39,7 +51,18 @@ export function Companies() {}><SoupViewList- emptyContent={<CrmEmptyState />}+ emptyState={(state) => (+ <CrmEmptyState+ filtered={state.filtered}+ onClearFilters={state.clearFilters}+ onClearPeopleSearch={options.clearPeopleSearch}+ onEditList={options.editList}+ />+ )}+ loadingContent={<CrmListSkeleton />}+ errorContent={(retry) => (+ <CrmListError onRetry={async () => retry()} />+ )}onOpenEntity={options.onOpenEntity}rowEntry={{ component: ContactListEntity, family: 'row' }}listHeader={diff --git a/apps/web/src/features/crm/views/company-contacts-section.test.tsx b/apps/web/src/features/crm/views/company-contacts-section.test.tsxindex e3c24c4f96..772f6d787e 100644--- a/apps/web/src/features/crm/views/company-contacts-section.test.tsx+++ b/apps/web/src/features/crm/views/company-contacts-section.test.tsx@@ -21,7 +21,22 @@ vi.mock('@entity', () => ({ListEntityMetadataQueryProvider: (props: ParentProps) => props.children,ListLayoutProvider: (props: ParentProps) => props.children,}));-vi.mock('@ui', async () => import('../../../components/ui/components/Avatar'));+vi.mock('@ui', async () => ({+ ...(await import('../../../components/ui/components/Avatar')),+ EmptyStatePanel: (props: {+ title?: string;+ primaryAction?: { label: string; onClick: () => void };+ }) => (+ <div>+ {props.title}+ {props.primaryAction && (+ <button type="button" onClick={props.primaryAction.onClick}>+ {props.primaryAction.label}+ </button>+ )}+ </div>+ ),+}));vi.mock('@app/components/view-shell', () => ({SearchBar: (props: {label: string;@@ -98,5 +113,7 @@ it('filters by email and keeps the search available with no results', () => {screen.getByRole('button', { name: /[email protected]/ });fireEvent.input(search, { target: { value: 'missing' } });screen.getByText('No matching contacts.');+ fireEvent.click(screen.getByRole('button', { name: 'Clear search' }));+ screen.getByRole('button', { name: /Avery Chen/ });expect(screen.getByRole('textbox', { name: 'Search team' })).toBe(search);});diff --git a/apps/web/src/features/crm/views/company-contacts-section.tsx b/apps/web/src/features/crm/views/company-contacts-section.tsxindex 13fbfd438f..3a4cdb9d52 100644--- a/apps/web/src/features/crm/views/company-contacts-section.tsx+++ b/apps/web/src/features/crm/views/company-contacts-section.tsx@@ -7,6 +7,11 @@ import {} from '@entity';import { Avatar } from '@ui';import { createMemo, createSignal, For, type JSX, Show } from 'solid-js';+import {+ CrmListEmpty,+ CrmListSearchEmpty,+ CrmListSkeleton,+} from '../components/list-state';import { RecordSection } from '../components/record-section';import { useCrmContext } from '../context/crm-context';import type { CrmContact } from '../core/contact';@@ -63,7 +68,8 @@ export function CompanyContactsSection(props: {onOpenContact?: (contact: CrmContact) => void;actions?: JSX.Element;}) {- const { openWithSplit } = useCrmContext().createNavigation();+ const context = useCrmContext();+ const { openWithSplit } = context.createNavigation();const [search, setSearch] = createSignal('');const [listRef, setListRef] = createSignal<HTMLElement>();const filtered = createMemo(() => {@@ -82,20 +88,45 @@ export function CompanyContactsSection(props: {search={search()}onSearchChange={setSearch}searchPlaceholder="Search contacts…"+ onSearchEscape={() => setSearch('')}actions={props.actions}><Showwhen={props.company}- fallback={- <div class="p-6 text-center text-sm text-ink-muted">Loading…</div>- }+ fallback={<CrmListSkeleton label="Loading contacts" />}><Showwhen={filtered().length}fallback={- <div class="p-6 text-center text-sm text-ink-muted">- {search().trim() ? 'No matching contacts.' : 'No contacts yet.'}- </div>+ <Show+ when={search().trim()}+ fallback={+ <CrmListEmpty+ title="No contacts yet"+ description="Add a contact to this company to see them here."+ action={+ props.company?.domains?.[0]+ ? {+ label: 'Add contact',+ onClick: () => {+ const domain = props.company?.domains?.[0]?.domain;+ if (domain && props.company)+ context.openCreateContact({+ companyId: props.company.id,+ domain,+ });+ },+ }+ : undefined+ }+ />+ }+ >+ <CrmListSearchEmpty+ title="No matching contacts."+ onClearSearch={() => setSearch('')}+ />+ </Show>}><ListEntityMetadataQueryProvider>diff --git a/apps/web/src/features/crm/views/company-detail.tsx b/apps/web/src/features/crm/views/company-detail.tsxindex 2973c406e6..acf83fe9fd 100644--- a/apps/web/src/features/crm/views/company-detail.tsx+++ b/apps/web/src/features/crm/views/company-detail.tsx@@ -2,6 +2,7 @@ import { SidePanel } from '@components/app/side-panel';import PlusIcon from '@icon/system/regular/plus.svg';import { Button } from '@ui';import { createMemo, Match, onCleanup, Show, Suspense, Switch } from 'solid-js';+import { CrmListSkeleton } from '../components/list-state';import { RecordOverview } from '../components/record-overview';import { useCrmContext } from '../context/crm-context';import type { CrmContact as CompanyContact } from '../core/contact';@@ -19,6 +20,7 @@ import { CompanyPropertiesSection } from './company-properties-section';import { CompanySharingSection } from './company-sharing-section';import {RecordCallsSection,+ RecordDatabasesSection,RecordFilesSection,RecordReferencesSection,} from './record-associations';@@ -119,25 +121,18 @@ export function Company(props: {<RecordFilesSection scope={scope()} /></Match><Match when={section() === 'tasks'}>- <Suspense- fallback={- <div class="p-6 text-center text-sm text-ink-muted touch:pt-[calc(var(--mobile-content-inset-top,0px)+1.5rem)]">- Loading…- </div>- }- >+ <Suspense fallback={<CrmListSkeleton label="Loading tasks" />}><Showwhen={scope()}- fallback={- <div class="p-6 text-center text-sm text-ink-muted touch:pt-[calc(var(--mobile-content-inset-top,0px)+1.5rem)]">- Loading…- </div>- }+ fallback={<CrmListSkeleton label="Loading tasks" />}>{(current) => <context.RecordTasks scope={current()} />}</Show></Suspense></Match>+ <Match when={section() === 'databases'}>+ <RecordDatabasesSection scope={scope()} />+ </Match><Match when={section() === 'calls'}><RecordCallsSection scope={scope()} /></Match>diff --git a/apps/web/src/features/crm/views/company-emails-section.tsx b/apps/web/src/features/crm/views/company-emails-section.tsxindex c85de9c327..db1fcd1ab8 100644--- a/apps/web/src/features/crm/views/company-emails-section.tsx+++ b/apps/web/src/features/crm/views/company-emails-section.tsx@@ -1,7 +1,10 @@+import EmptyStateEmailGraphic from '@design/empty-state-email.svg';import type { CrmCompanyEntity } from '@entity';import { Tabs } from '@ui';import { createMemo, createSignal } from 'solid-js';+import { CrmListEmpty } from '../components/list-state';import { RecordSection } from '../components/record-section';+import { useCrmContext } from '../context/crm-context';import type {CrmEmailSignal as EmailSignalView,CrmEmailScope as EmailView,@@ -14,6 +17,7 @@ export function CompanyEmailsSection(props: { company?: CrmCompanyEntity }) {() => props.company?.domains.map((domain) => domain.domain) ?? []);const [search, setSearch] = createSignal('');+ const crm = useCrmContext();const [view, setView] = createSignal<EmailView>('team');const [signalView, setSignalView] = createSignal<EmailSignalView>('all');const emailsQuery = useCompanyEmailsQuery(domains, view, signalView);@@ -63,7 +67,22 @@ export function CompanyEmailsSection(props: { company?: CrmCompanyEntity }) {source={emailsQuery}search={search()}pending={!props.company}- empty={emptyMessage()}+ onClearSearch={() => setSearch('')}+ emptyContent={+ <CrmListEmpty+ graphic={EmptyStateEmailGraphic}+ title={emptyMessage()}+ description="Conversations with this company's email domains will appear here."+ action={+ props.company?.emailSync === false+ ? undefined+ : {+ label: 'New email',+ onClick: () => crm.openEmailComposer(),+ }+ }+ />+ }/></RecordSection>);diff --git a/apps/web/src/features/crm/views/company-header.tsx b/apps/web/src/features/crm/views/company-header.tsxindex b94067056e..c81eb654b2 100644--- a/apps/web/src/features/crm/views/company-header.tsx+++ b/apps/web/src/features/crm/views/company-header.tsx@@ -1,3 +1,4 @@+import { ListSkeleton } from '@app/components/view-shell/ListSkeleton';import { EntityIcon } from '@core/component/EntityIcon';import { InlineTitleEditor } from '@core/component/InlineTitleEditor';import {@@ -82,7 +83,10 @@ export function CompanyHeader(props: { company?: CrmCompanyEntity }) {<EntityIcon targetType="crm_company" size="fill" /></div><h1 class="min-w-0 flex-1 text-2xl font-semibold">- <Show when={props.company} fallback={'Loading company…'}>+ <Show+ when={props.company}+ fallback={<ListSkeleton.Bar class="h-6 w-48" />}+ >{(company) => <TitleEditor company={company()} />}</Show></h1>diff --git a/apps/web/src/features/crm/views/contact-detail.tsx b/apps/web/src/features/crm/views/contact-detail.tsxindex a8bef4e140..ce990b4e73 100644--- a/apps/web/src/features/crm/views/contact-detail.tsx+++ b/apps/web/src/features/crm/views/contact-detail.tsx@@ -1,5 +1,6 @@import { SidePanel } from '@components/app/side-panel';import { createMemo, Match, onCleanup, Show, Suspense, Switch } from 'solid-js';+import { CrmListSkeleton } from '../components/list-state';import { RecordOverview } from '../components/record-overview';import { useCrmContext } from '../context/crm-context';import {@@ -13,6 +14,7 @@ import { ContactHeader } from './contact-header';import { ContactSharingSection } from './contact-sharing-section';import {RecordCallsSection,+ RecordDatabasesSection,RecordFilesSection,RecordReferencesSection,} from './record-associations';@@ -90,25 +92,18 @@ export function Contact(props: {<RecordFilesSection scope={scope()} /></Match><Match when={section() === 'tasks'}>- <Suspense- fallback={- <div class="p-6 text-center text-sm text-ink-muted touch:pt-[calc(var(--mobile-content-inset-top,0px)+1.5rem)]">- Loading…- </div>- }- >+ <Suspense fallback={<CrmListSkeleton label="Loading tasks" />}><Showwhen={scope()}- fallback={- <div class="p-6 text-center text-sm text-ink-muted touch:pt-[calc(var(--mobile-content-inset-top,0px)+1.5rem)]">- Loading…- </div>- }+ fallback={<CrmListSkeleton label="Loading tasks" />}>{(current) => <context.RecordTasks scope={current()} />}</Show></Suspense></Match>+ <Match when={section() === 'databases'}>+ <RecordDatabasesSection scope={scope()} />+ </Match><Match when={section() === 'calls'}><RecordCallsSection scope={scope()} /></Match>diff --git a/apps/web/src/features/crm/views/contact-emails-section.tsx b/apps/web/src/features/crm/views/contact-emails-section.tsxindex a118d6d89f..3dc2790236 100644--- a/apps/web/src/features/crm/views/contact-emails-section.tsx+++ b/apps/web/src/features/crm/views/contact-emails-section.tsx@@ -1,6 +1,9 @@+import EmptyStateEmailGraphic from '@design/empty-state-email.svg';import { Tabs } from '@ui';import { createSignal } from 'solid-js';+import { CrmListEmpty } from '../components/list-state';import { RecordSection } from '../components/record-section';+import { useCrmContext } from '../context/crm-context';import type {CrmEmailSignal as EmailSignalView,CrmEmailScope as EmailView,@@ -12,6 +15,7 @@ import { useContactEmailsQuery } from './use-crm';export function ContactEmailsSection(props: { contact?: CrmContactResponse }) {const email = () => props.contact?.email;const [search, setSearch] = createSignal('');+ const crm = useCrmContext();const [view, setView] = createSignal<EmailView>('team');const [signalView, setSignalView] = createSignal<EmailSignalView>('all');const emailsQuery = useContactEmailsQuery(email, view, signalView);@@ -52,7 +56,18 @@ export function ContactEmailsSection(props: { contact?: CrmContactResponse }) {source={emailsQuery}search={search()}pending={!props.contact}- empty={`No ${signalView() === 'signal' ? 'signal emails' : 'emails'} with this contact ${view() === 'me' ? 'in your inbox' : 'yet'}.`}+ onClearSearch={() => setSearch('')}+ emptyContent={+ <CrmListEmpty+ graphic={EmptyStateEmailGraphic}+ title={`No ${signalView() === 'signal' ? 'signal emails' : 'emails'} with this contact ${view() === 'me' ? 'in your inbox' : 'yet'}.`}+ description="Email this contact to start a conversation."+ action={{+ label: 'New email',+ onClick: () => crm.openEmailComposer(props.contact?.email),+ }}+ />+ }/></RecordSection>);diff --git a/apps/web/src/features/crm/views/contact-header.tsx b/apps/web/src/features/crm/views/contact-header.tsxindex 8ea8dc151f..40df9e529c 100644--- a/apps/web/src/features/crm/views/contact-header.tsx+++ b/apps/web/src/features/crm/views/contact-header.tsx@@ -1,3 +1,4 @@+import { ListSkeleton } from '@app/components/view-shell/ListSkeleton';import { EntityIcon } from '@core/component/EntityIcon';import { InlineTitleEditor } from '@core/component/InlineTitleEditor';import { formatDateAndTime, formatRelativeTimestamp } from '@entity';@@ -95,7 +96,10 @@ export function ContactHeader(props: {</Show></Avatar><h1 class="min-w-0 flex-1 text-2xl font-semibold">- <Show when={props.contact} fallback={'Loading contact…'}>+ <Show+ when={props.contact}+ fallback={<ListSkeleton.Bar class="h-6 w-48" />}+ >{(contact) => <TitleEditor contact={contact()} />}</Show></h1>diff --git a/apps/web/src/features/crm/views/crm-workspace.test.tsx b/apps/web/src/features/crm/views/crm-workspace.test.tsxindex eb87da4eec..b2e3aeb54f 100644--- a/apps/web/src/features/crm/views/crm-workspace.test.tsx+++ b/apps/web/src/features/crm/views/crm-workspace.test.tsx@@ -362,13 +362,21 @@ it('omits pipelines and lists when those features are disabled', () => {const tabs = within(screen.getByRole('navigation', { name: 'CRM views' }));expect(tabs.getAllByRole('button').map((button) => button.textContent)- ).toEqual(['Companies', 'People', 'Tasks', 'Email', 'Notes', 'Calls']);+ ).toEqual([+ 'Companies',+ 'People',+ 'Tasks',+ 'Email',+ 'Notes',+ 'Calls',+ 'Databases',+ ]);});it('opens each CRM activity feed instead of the company list', () => {const { activeTab } = setup();const tabs = within(screen.getByRole('navigation', { name: 'CRM views' }));- for (const label of ['Tasks', 'Email', 'Notes', 'Calls']) {+ for (const label of ['Tasks', 'Email', 'Notes', 'Calls', 'Databases']) {fireEvent.click(tabs.getByRole('button', { name: label }));expect(activeTab()).toBe(label.toLowerCase());expect(screen.getByText(`${label.toLowerCase()} feed`)).toBeTruthy();@@ -384,7 +392,9 @@ it('waits for the rollout before resolving a cold activity link', () => {loading: true,});expect(activeTab()).toBe('tasks');- expect(screen.getByText('Loading CRM activity…')).toBeTruthy();+ expect(+ screen.getByRole('status', { name: 'Loading CRM activity' })+ ).toBeTruthy();expect(screen.queryByText('tasks feed')).toBeNull();expect(screen.queryByText('Record list')).toBeNull();setActivityFlag({ enabled: true, loading: false });diff --git a/apps/web/src/features/crm/views/crm-workspace.tsx b/apps/web/src/features/crm/views/crm-workspace.tsxindex 12d0f1b97b..037bc5e524 100644--- a/apps/web/src/features/crm/views/crm-workspace.tsx+++ b/apps/web/src/features/crm/views/crm-workspace.tsx@@ -24,7 +24,10 @@ import { useFeatureFlag } from '@app/lib/analytics/posthog';import { usePreference } from '@app/preferences/use-preference';import { HeaderActionGroup } from '@components/app/HeaderActionGroup';import { SplitPanel } from '@components/app/split-panel';-import { enableCrmActivity } from '@core/constant/featureFlags';+import {+ enableCrmActivity,+ enableDatabases,+} from '@core/constant/featureFlags';import { isTouchDevice } from '@core/mobile/isTouchDevice';import { debounce } from '@core/util/debounce';import { fireAndForget } from '@core/util/fireAndForget';@@ -53,6 +56,7 @@ import { CrmListDialog } from '../components/company-list-dialog';import { CrmCreateMenu } from '../components/crm-create-menu';import { CrmMobileTabs } from '../components/crm-mobile-tabs';import { CrmSidebar } from '../components/crm-sidebar';+import { CrmListError, CrmListSkeleton } from '../components/list-state';import { PipelineDialog } from '../components/pipeline-dialog';import { PipelineSidebar } from '../components/pipeline-sidebar';import { useCrmContext } from '../context/crm-context';@@ -245,9 +249,12 @@ function CrmFilterChips(props: { onReset: () => void }) {export function CrmWorkspaceView(props: {children: (options: {onOpenEntity?: (entity: EntityData) => boolean;+ clearPeopleSearch: () => void;+ editList?: () => void;}) => JSX.Element;}) {const activityFlag = useFeatureFlag(enableCrmActivity);+ const databasesFlag = useFeatureFlag(enableDatabases);const {openCreateCompany: openCreateCompanyModal,openCreateContact: openCreateContactModal,@@ -271,6 +278,11 @@ export function CrmWorkspaceView(props: {setPeopleSearch(value);applyPeopleSearch(value);};+ const clearPeopleSearch = () => {+ applyPeopleSearch.clear();+ setPeopleSearch('');+ view.queryFilters.set({ include: { crmContactSearch: undefined } });+ };const settings = view.host.settings;const { openWithSplit } = useCrmContext().createNavigation();@@ -339,13 +351,28 @@ export function CrmWorkspaceView(props: {const peopleActive = () => active() === 'people';const activityTab = () => {const tab = active();- return activityFlag().enabled && isCrmActivityTab(tab) ? tab : undefined;+ return activityFlag().enabled &&+ (tab !== 'databases' || databasesFlag().enabled) &&+ isCrmActivityTab(tab)+ ? tab+ : undefined;};const activityPending = () =>- isCrmActivityTab(active()) && activityFlag().loading;+ isCrmActivityTab(active()) &&+ (activityFlag().loading ||+ (active() === 'databases' && databasesFlag().loading));const [exporting, setExporting] = createSignal(false);const activeList = () =>lists.lists().find((list) => `list:${list.id}` === active());+ const editActiveList = () => {+ const list = activeList();+ if (list)+ setEditing({+ id: list.id,+ name: list.name,+ companyIds: [...list.config.companyIds],+ });+ };// A list tab from the URL has no preset, so apply its company filter once the list loads.createEffect(() => {const list = activeList();@@ -385,6 +412,7 @@ export function CrmWorkspaceView(props: {settings.close();if (!listsEnabled() && id.startsWith('list:')) id = 'active';if (!activityFlag().enabled && isCrmActivityTab(id)) id = 'active';+ if (id === 'databases' && !databasesFlag().enabled) id = 'active';if (id !== 'people' && !id.startsWith('list:') && !isCrmActivityTab(id))id = 'active';if (id === active()) view.host.record.close();@@ -443,9 +471,20 @@ export function CrmWorkspaceView(props: {// Keep cold activity links intact until PostHog resolves; off falls back to Companies.createEffect(on(- () => [activityFlag().loading, activityFlag().enabled, active()] as const,- ([loading, enabled, tab]) => {- if (!loading && !enabled && isCrmActivityTab(tab)) navigate('active');+ () =>+ [+ activityPending(),+ activityFlag().enabled,+ databasesFlag().enabled,+ active(),+ ] as const,+ ([loading, activityEnabled, databasesEnabled, tab]) => {+ if (+ !loading &&+ isCrmActivityTab(tab) &&+ (!activityEnabled || (tab === 'databases' && !databasesEnabled))+ )+ navigate('active');}));@@ -520,9 +559,7 @@ export function CrmWorkspaceView(props: {return (<ViewShell.Root aside={collapsed() ? false : {}} main={{ min: 320 }}><ViewShell.Aside>- <Suspense- fallback={<div class="p-4 text-sm text-ink-muted">Loading CRM…</div>}- >+ <Suspense fallback={<CrmListSkeleton label="Loading CRM" />}>{sidebar(() => setCollapsed(true))}</Suspense></ViewShell.Aside>@@ -632,31 +669,31 @@ export function CrmWorkspaceView(props: {</Show>)}</Show>- <Show when={pipelineId() && !activePipeline()}>- <div class="flex flex-col items-start gap-3 p-6 text-sm text-ink-muted">- <p>- {pipelines.loading()- ? 'Loading pipeline…'- : pipelines.error()+ <Show when={!recordOpen() && pipelineId() && !activePipeline()}>+ <Show+ when={!pipelines.loading()}+ fallback={<CrmListSkeleton label="Loading pipeline" />}+ >+ <CrmListError+ title={+ pipelines.error()? 'Could not load this pipeline.'- : 'This pipeline is unavailable or you no longer have access.'}- </p>+ : 'This pipeline is unavailable or you no longer have access.'+ }+ onRetry={() => pipelines.refresh()}+ /><Button variant="ghost" onClick={() => navigate('active')}>Back to companies</Button>- </div>+ </Show></Show><Show when={!recordOpen() && !pipelineId() && activityPending()}>- <div class="p-4 text-sm text-ink-muted">Loading CRM activity…</div>+ <CrmListSkeleton label="Loading CRM activity" /></Show><Show when={!recordOpen() && !pipelineId() && activityTab()} keyed>{(tab) => (<Suspense- fallback={- <div class="p-4 text-sm text-ink-muted">- Loading CRM activity…- </div>- }+ fallback={<CrmListSkeleton label="Loading CRM activity" />}><CrmActivityViewtab={tab}@@ -729,20 +766,12 @@ export function CrmWorkspaceView(props: {<CompanyViewsMenu grouped hideLabel /></Suspense><Show when={listsEnabled() && activeList()}>- {(list) => (- <ButtonGroup.Button- variant="ghost"- onClick={() =>- setEditing({- id: list().id,- name: list().name,- companyIds: [...list().config.companyIds],- })- }- >- Edit list- </ButtonGroup.Button>- )}+ <ButtonGroup.Button+ variant="ghost"+ onClick={editActiveList}+ >+ Edit list+ </ButtonGroup.Button></Show></HeaderActionGroup></Show>@@ -767,6 +796,8 @@ export function CrmWorkspaceView(props: {<div class="flex min-h-0 min-w-0 flex-1 flex-col [--mobile-content-inset-top:0px]">{props.children({onOpenEntity: isTouchDevice() ? undefined : openRecord,+ clearPeopleSearch,+ editList: activeList() ? editActiveList : undefined,})}</div></Show>diff --git a/apps/web/src/features/crm/views/databases.tsx b/apps/web/src/features/crm/views/databases.tsxnew file mode 100644index 0000000000..df18fead15--- /dev/null+++ b/apps/web/src/features/crm/views/databases.tsx@@ -0,0 +1,105 @@+import { ListHeader } from '@app/components/view-shell/ListHeader';+import { useFeatureFlag } from '@app/lib/analytics/posthog';+import { enableDatabases } from '@core/constant/featureFlags';+import { isTouchDevice } from '@core/mobile/isTouchDevice';+import EmptyStateDatabaseGraphic from '@design/empty-state-folder.svg';+import PlusIcon from '@icon/system/regular/plus.svg';+import { Button } from '@ui';+import { createSignal, type JSX, Show } from 'solid-js';+import { CrmListEmpty, CrmListSkeleton } from '../components/list-state';+import { RecordSection } from '../components/record-section';+import { useCrmContext } from '../context/crm-context';+import type { CrmRecordScope } from '../core/record';+import { ActivitySection } from './activity-section';+import { RecordItemList } from './record-item-list';++/** Lists whole databases discovered through their authorized CRM-linked rows. */+export function CrmDatabasesView(props: {+ scope?: CrmRecordScope;+ title?: JSX.Element;+}) {+ const flag = useFeatureFlag(enableDatabases);+ return (+ <Show+ when={flag().enabled}+ fallback={+ <div class="flex min-h-0 min-w-0 flex-1 flex-col">+ <Show when={!props.scope && !isTouchDevice()}>+ <ListHeader title={props.title ?? 'Databases'} />+ </Show>+ <Show+ when={flag().loading}+ fallback={+ <CrmListEmpty+ graphic={EmptyStateDatabaseGraphic}+ title="Databases are unavailable"+ description="Database access is not enabled for this account."+ />+ }+ >+ <CrmListSkeleton label="Loading databases" />+ </Show>+ </div>+ }+ >+ <DatabasesList scope={props.scope} title={props.title} />+ </Show>+ );+}++function DatabasesList(props: { scope?: CrmRecordScope; title?: JSX.Element }) {+ const crm = useCrmContext();+ const source = crm.createDatabases(() => props.scope);+ const [search, setSearch] = createSignal('');+ const create = () => crm.openCreateItem('databases');+ const list = () => (+ <RecordItemList+ source={source}+ search={search()}+ onClearSearch={() => setSearch('')}+ emptyContent={+ <CrmListEmpty+ graphic={EmptyStateDatabaseGraphic}+ title="No linked databases yet"+ description={+ props.scope+ ? `Databases appear here when a row links to this ${props.scope.type}. Add a company or contact reference to a row to get started.`+ : 'Databases appear here when a row links to a CRM company or person. Add a company or contact reference to a row to get started.'+ }+ action={{ label: 'New database', onClick: create }}+ />+ }+ />+ );+ return (+ <Show+ when={props.scope}+ fallback={+ <ActivitySection+ label="Databases"+ title={props.title}+ search={search()}+ onSearchChange={setSearch}+ createLabel="New database"+ onCreate={create}+ >+ {list()}+ </ActivitySection>+ }+ >+ <RecordSection+ title="Databases"+ search={search()}+ onSearchChange={setSearch}+ actions={+ <Button variant="outline" onClick={create}>+ <PlusIcon class="size-4" />+ New database+ </Button>+ }+ >+ {list()}+ </RecordSection>+ </Show>+ );+}diff --git a/apps/web/src/features/crm/views/empty-state.tsx b/apps/web/src/features/crm/views/empty-state.tsxindex f4ccf0009f..7032182393 100644--- a/apps/web/src/features/crm/views/empty-state.tsx+++ b/apps/web/src/features/crm/views/empty-state.tsx@@ -1,11 +1,34 @@import EmptyStateCompaniesGraphic from '@design/empty-state-companies.svg';import { EmptyStatePanel } from '@ui';import { Match, Switch } from 'solid-js';+import {+ CrmListEmpty,+ CrmListError,+ CrmListSearchEmpty,+ CrmListSkeleton,+} from '../components/list-state';+import { useCrmContext } from '../context/crm-context';import { useCrmWorkspace } from '../context/workspace-context';import { useCurrentTeamQuery, useIsTeamAdmin } from './use-crm';-export function CrmEmptyState() {- const { host, activeTab, queryFilters } = useCrmWorkspace();+export function CrmEmptyState(+ props: {+ filtered?: boolean;+ onClearFilters?: () => void;+ onClearPeopleSearch?: () => void;+ onEditList?: () => void;+ } = {}+) {+ const {+ host,+ activeTab,+ queryFilters,+ searchText,+ setSearchText,+ stageFilter,+ ownerFilter,+ } = useCrmWorkspace();+ const { openCreateCompany, openCreateContact } = useCrmContext();const peopleSearch = () => queryFilters.state.include.crmContactSearch;const teamQuery = useCurrentTeamQuery();const isTeamAdmin = useIsTeamAdmin();@@ -14,12 +37,19 @@ export function CrmEmptyState() {const hasNoTeam = () => teamQuery.data === null;return (<Switch>- {/* Render nothing until the team query resolves — showing a wrong- panel for a moment is worse than a brief blank. */}- <Match when={!teamResolved()}>{null}</Match>+ <Match when={teamQuery.isError && !teamResolved()}>+ <CrmListError+ title="Couldn't load CRM settings."+ onRetry={() => teamQuery.refetch()}+ />+ </Match>+ <Match when={!teamResolved()}>+ <CrmListSkeleton label="Loading CRM" />+ </Match><Match when={hasNoTeam()}><EmptyStatePanelcentered+ topSpacerClass="grow-[0.5] basis-0 mobile:basis-0"graphic={EmptyStateCompaniesGraphic}title="Join a team to enable CRM"description="Create or join a team in Settings > Team."@@ -32,6 +62,7 @@ export function CrmEmptyState() {<Match when={!crmEnabled()}><EmptyStatePanelcentered+ topSpacerClass="grow-[0.5] basis-0 mobile:basis-0"graphic={EmptyStateCompaniesGraphic}title="CRM is disabled"description={@@ -49,20 +80,58 @@ export function CrmEmptyState() {}/></Match>+ <Match when={activeTab() === 'people' && !!peopleSearch()}>+ <CrmListSearchEmpty+ title="No matching people"+ description="Try a different name or email address."+ onClearSearch={props.onClearPeopleSearch}+ />+ </Match>+ <Match when={activeTab() === 'people' && props.filtered}>+ <CrmListEmpty+ filtered+ title="No people match these filters"+ description="Try adjusting or clearing your filters."+ action={+ props.onClearFilters+ ? { label: 'Clear filters', onClick: props.onClearFilters }+ : undefined+ }+ />+ </Match><Match when={activeTab() === 'people'}>- <EmptyStatePanel- graphic={EmptyStateCompaniesGraphic}- title={peopleSearch() ? 'No matching people' : 'No people yet'}- description={- peopleSearch()- ? 'Try a name or email address.'- : 'People connected to your CRM companies will appear here.'+ <CrmListEmpty+ title="No people yet"+ description="People connected to your CRM companies will appear here."+ action={{ label: 'Add person', onClick: () => openCreateContact() }}+ />+ </Match>+ <Match when={!!searchText().trim()}>+ <CrmListSearchEmpty+ title="No matching companies"+ onClearSearch={() => setSearchText('')}+ />+ </Match>+ <Match+ when={+ (props.filtered && !activeTab()?.startsWith('list:')) ||+ stageFilter().length > 0 ||+ ownerFilter().length > 0+ }+ >+ <CrmListEmpty+ filtered+ title="No companies match these filters"+ description="Try adjusting the stage or owner filters."+ action={+ props.onClearFilters+ ? { label: 'Clear filters', onClick: props.onClearFilters }+ : undefined}/></Match><Match when={true}>- <EmptyStatePanel- graphic={EmptyStateCompaniesGraphic}+ <CrmListEmptytitle={!activeTab() || activeTab() === 'active'? 'No customers yet'@@ -77,6 +146,13 @@ export function CrmEmptyState() {? 'Use Edit list to add companies to this collection.': 'Companies that match this view will appear here.'}+ action={+ !activeTab() || activeTab() === 'active'+ ? { label: 'Add company', onClick: openCreateCompany }+ : props.onEditList+ ? { label: 'Edit list', onClick: props.onEditList }+ : undefined+ }/></Match></Switch>diff --git a/apps/web/src/features/crm/views/record-associations.tsx b/apps/web/src/features/crm/views/record-associations.tsxindex 9a542c28ad..3f26a77952 100644--- a/apps/web/src/features/crm/views/record-associations.tsx+++ b/apps/web/src/features/crm/views/record-associations.tsx@@ -1,7 +1,11 @@-import { createSignal } from 'solid-js';+import EmptyStateCallsGraphic from '@design/empty-state-calls.svg';+import EmptyStateDocGraphic from '@design/empty-state-doc.svg';+import { createSignal, Show } from 'solid-js';+import { CrmListEmpty, CrmListSkeleton } from '../components/list-state';import { RecordSection } from '../components/record-section';import { useCrmContext } from '../context/crm-context';import type { CrmRecordScope } from '../core/record';+import { CrmDatabasesView } from './databases';import { RecordItemList } from './record-item-list';/**@@ -10,14 +14,26 @@ import { RecordItemList } from './record-item-list';*/export function RecordFilesSection(props: { scope?: CrmRecordScope }) {const [search, setSearch] = createSignal('');- const files = useCrmContext().createRecordFiles(() => props.scope);+ const crm = useCrmContext();+ const files = crm.createRecordFiles(() => props.scope);return (<RecordSection title="Files" search={search()} onSearchChange={setSearch}><RecordItemListsource={files}search={search()}pending={!props.scope}- empty={`No files with this ${props.scope?.type ?? 'record'} yet.`}+ onClearSearch={() => setSearch('')}+ emptyContent={+ <CrmListEmpty+ graphic={EmptyStateDocGraphic}+ title="No files linked yet"+ description={`Create a note and link it to this ${props.scope?.type ?? 'record'} through its Companies or Contacts property.`}+ action={{+ label: 'New note',+ onClick: () => crm.openCreateItem('notes'),+ }}+ />+ }/></RecordSection>);@@ -29,19 +45,43 @@ export function RecordFilesSection(props: { scope?: CrmRecordScope }) {*/export function RecordCallsSection(props: { scope?: CrmRecordScope }) {const [search, setSearch] = createSignal('');- const calls = useCrmContext().createRecordCalls(() => props.scope);+ const crm = useCrmContext();+ const calls = crm.createRecordCalls(() => props.scope);return (<RecordSection title="Calls" search={search()} onSearchChange={setSearch}><RecordItemListsource={calls}search={search()}pending={!props.scope}- empty={`No calls with this ${props.scope?.type ?? 'record'} yet.`}+ onClearSearch={() => setSearch('')}+ emptyContent={+ <CrmListEmpty+ graphic={EmptyStateCallsGraphic}+ title="No calls linked yet"+ description={`Calls with a Companies or Contacts link to this ${props.scope?.type ?? 'record'} will appear here.`}+ action={{+ label: 'New call',+ onClick: () => crm.openCreateItem('calls'),+ }}+ />+ }/></RecordSection>);}+/** Databases require a loaded record so pending details never request workspace scope. */+export function RecordDatabasesSection(props: { scope?: CrmRecordScope }) {+ return (+ <Show+ when={props.scope}+ fallback={<CrmListSkeleton label="Loading databases" />}+ >+ {(scope) => <CrmDatabasesView scope={scope()} />}+ </Show>+ );+}+/*** Items of any type associated with the record: what names it in a* Companies or Contacts property and what references it, including through adiff --git a/apps/web/src/features/crm/views/record-detail.tsx b/apps/web/src/features/crm/views/record-detail.tsxindex d3e62dba26..7dd5540de7 100644--- a/apps/web/src/features/crm/views/record-detail.tsx+++ b/apps/web/src/features/crm/views/record-detail.tsx@@ -9,7 +9,6 @@ import {import { COMMENT_LINK_PARAM } from '@core/messages/comment-link';import { isTouchDevice } from '@core/mobile/isTouchDevice';import { fireAndForget } from '@core/util/fireAndForget';-import SpinnerIcon from '@icon/system/regular/spinner.svg';import { createElementSize } from '@solid-primitives/resize-observer';import { Button, Tooltip } from '@ui';import {@@ -25,6 +24,7 @@ import {Suspense,untrack,} from 'solid-js';+import { CrmListSkeleton } from '../components/list-state';import { RecordTabs } from '../components/record-tabs';import { useCrmContext } from '../context/crm-context';import type { CrmCommentTarget } from '../context/workspace-context';@@ -311,15 +311,7 @@ function RecordContent(props: {fallback={error(() => fireAndForget(query.refetch(), 'crm'))}><Suspense- fallback={- <div class="grid size-full place-items-center text-ink-muted">- <SpinnerIcon- aria-hidden={false}- aria-label={`Loading ${props.record.type}`}- class="size-5 animate-spin"- />- </div>- }+ fallback={<CrmListSkeleton label={`Loading ${props.record.type}`} />}><ParamsProvider state={params}>{props.children}</ParamsProvider></Suspense>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.tsxindex a0e624e969..0645d406e1 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@@ -23,6 +23,22 @@ vi.mock('@entity', () => ({ListLayoutProvider: (props: ParentProps) => props.children,}));vi.mock('@ui', () => ({+ cn: (...classes: (string | undefined)[]) => classes.filter(Boolean).join(' '),+ EmptyStatePanel: (props: {+ title?: string;+ description?: string;+ primaryAction?: { label: string; onClick: () => void };+ }) => (+ <div>+ <h2>{props.title}</h2>+ <p>{props.description}</p>+ {props.primaryAction && (+ <button type="button" onClick={props.primaryAction.onClick}>+ {props.primaryAction.label}+ </button>+ )}+ </div>+ ),Button: (props: ParentProps<{ onClick: () => void }>) => (<button type="button" onClick={props.onClick}>{props.children}@@ -67,7 +83,7 @@ it('replaces cached rows and retries the query after a failed refetch', () => {expect(screen.queryByText('Kickoff notes')).toBeNull();screen.getByText("Couldn't load this list.");- fireEvent.click(screen.getByText('Retry'));+ fireEvent.click(screen.getByText('Try again'));expect(failed.refetch).toHaveBeenCalledTimes(1);expect(failed.fetchNextPage).not.toHaveBeenCalled();});@@ -114,10 +130,34 @@ it('only declares no search results after the final page', () => {empty="Nothing"/>));- screen.getByText('Searching more…');+ screen.getByRole('status', { name: 'Searching more items' });expect(screen.queryByText('No matching items.')).toBeNull();});+it('clears a finished search without hiding loaded rows', () => {+ const clear = vi.fn();+ render(() => (+ <RecordItemList+ source={source({ hasNextPage: false })}+ search="missing"+ onClearSearch={clear}+ />+ ));+ fireEvent.click(screen.getByText('Clear search'));+ expect(clear).toHaveBeenCalledTimes(1);+});++it('keeps an empty first page pageable until more results arrive', () => {+ render(() => (+ <RecordItemList+ source={source({ data: { entities: [] }, hasNextPage: true })}+ search="missing"+ empty="Nothing"+ />+ ));+ screen.getByRole('status', { name: 'Searching more items' });+ expect(screen.queryByText('Nothing')).toBeNull();+});it('keeps the paging marker mounted when a local filter removes an entire page', () => {const view = render(() => (<RecordItemList@@ -125,7 +165,7 @@ it('keeps the paging marker mounted when a local filter removes an entire page',empty="Nothing"/>));- screen.getByText('Searching more…');+ screen.getByRole('status', { name: 'Searching more items' });expect(screen.queryByText('Nothing')).toBeNull();expect(view.container.querySelector('.h-px')).not.toBeNull();});diff --git a/apps/web/src/features/crm/views/record-item-list.tsx b/apps/web/src/features/crm/views/record-item-list.tsxindex 269d94a8d5..3054761e5f 100644--- a/apps/web/src/features/crm/views/record-item-list.tsx+++ b/apps/web/src/features/crm/views/record-item-list.tsx@@ -19,6 +19,12 @@ import {Switch,} from 'solid-js';import { useInfiniteScrollSentinel } from '../../../lib/primitives/infinite-scroll-sentinel';+import {+ CrmListEmpty,+ CrmListError,+ CrmListSearchEmpty,+ CrmListSkeleton,+} from '../components/list-state';import { useCrmContext } from '../context/crm-context';import type { ItemListSource } from '../context/crm-sources';import { recordItemMatchesSearch } from '../core/record-search';@@ -32,7 +38,11 @@ export function RecordItemList(props: {source: ItemListSource;/** Hold the loading state, e.g. while the record itself loads. */pending?: boolean;- empty: JSX.Element;+ empty?: JSX.Element;+ /** A complete empty panel; `empty` remains a short description. */+ emptyContent?: JSX.Element;+ /** Clear the search when this list has its own search control. */+ onClearSearch?: () => void;search?: string;/** Row layout when the list is narrow, e.g. in the information panel. */narrowLayout?: NarrowLayoutVariant;@@ -89,77 +99,150 @@ export function RecordItemList(props: {props.pending || (props.source.isPending && props.source.isEnabled);return (- <Switch>- <Match when={loading()}>- <div class="p-6 text-center text-sm text-ink-muted">Loading…</div>- </Match>- <Match when={props.source.isError}>- <RetryNotice- message="Couldn't load this list."- onRetry={() => props.source.refetch()}- />- </Match>- <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 || props.source.hasNextPage}>- <ListEntityMetadataQueryProvider>- <ListLayoutProvider ref={listRef} narrowLayout={props.narrowLayout}>- <div ref={setListRef} class="flex flex-col">- <Show when={filteredItems().length === 0}>- <div class="p-6 text-center text-sm text-ink-muted">- {props.source.hasNextPage &&- !props.source.isFetchNextPageError- ? 'Searching more…'- : 'No matching items.'}- </div>+ <div class="flex min-h-0 w-full flex-1 flex-col">+ <Switch>+ <Match when={loading()}>+ <CrmListSkeleton+ count={props.narrowLayout === 'condensed' ? 2 : undefined}+ />+ </Match>+ <Match when={props.source.isError}>+ <Show+ when={props.narrowLayout !== 'condensed'}+ fallback={+ <RetryNotice+ message="Couldn't load this list."+ onRetry={() => props.source.refetch()}+ />+ }+ >+ <CrmListError onRetry={() => props.source.refetch()} />+ </Show>+ </Match>+ <Match when={items().length === 0}>+ <Show+ when={+ props.source.hasNextPage ||+ props.source.isFetchingNextPage ||+ props.source.isFetchNextPageError+ }+ fallback={+ <Show+ when={props.search?.trim()}+ fallback={+ <Show+ when={props.narrowLayout !== 'condensed'}+ fallback={+ <div class="p-3 text-xs text-ink-muted">+ {props.empty ?? 'No items yet.'}+ </div>+ }+ >+ {props.emptyContent ?? (+ <CrmListEmpty+ title="No items yet"+ description={props.empty}+ />+ )}+ </Show>+ }+ >+ <CrmListSearchEmpty+ title="No matching items"+ onClearSearch={props.onClearSearch}+ /></Show>- <For each={filteredItems()}>- {(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>- </ListLayoutProvider>- </ListEntityMetadataQueryProvider>- <Show- when={!props.source.isFetchNextPageError}- fallback={- <RetryNotice- message="Couldn't load more."- onRetry={() => props.source.fetchNextPage()}- />- }- >- <Show when={props.source.hasNextPage}>- <div ref={setSentinelRef} class="h-px" />+ }+ >+ <Show+ when={props.source.isFetchNextPageError}+ fallback={+ <CrmListSkeleton label="Searching more items" count={2} />+ }+ >+ <RetryNotice+ message="Couldn't load more."+ onRetry={() => props.source.fetchNextPage()}+ />+ </Show>+ <Show+ when={+ props.source.hasNextPage && !props.source.isFetchNextPageError+ }+ >+ <div ref={setSentinelRef} class="h-px" />+ </Show></Show>- <Show when={props.source.isFetchingNextPage}>- <div class="p-3 text-center text-xs text-ink-muted">- Loading more…- </div>+ </Match>+ <Match when={items().length > 0}>+ <ListEntityMetadataQueryProvider>+ <ListLayoutProvider ref={listRef} narrowLayout={props.narrowLayout}>+ <div+ ref={setListRef}+ class="flex flex-col"+ classList={{ 'min-h-0 flex-1': filteredItems().length === 0 }}+ >+ <Show when={filteredItems().length === 0}>+ <Show+ when={+ props.source.hasNextPage ||+ props.source.isFetchingNextPage+ }+ fallback={+ <CrmListSearchEmpty+ title="No matching items."+ onClearSearch={props.onClearSearch}+ />+ }+ >+ <Show when={!props.source.isFetchNextPageError}>+ <CrmListSkeleton label="Searching more items" count={2} />+ </Show>+ </Show>+ </Show>+ <For each={filteredItems()}>+ {(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>+ </ListLayoutProvider>+ </ListEntityMetadataQueryProvider>+ <Show+ when={!props.source.isFetchNextPageError}+ fallback={+ <RetryNotice+ message="Couldn't load more."+ onRetry={() => props.source.fetchNextPage()}+ />+ }+ >+ <Show when={props.source.hasNextPage}>+ <div ref={setSentinelRef} class="h-px" />+ </Show>+ <Show when={props.source.isFetchingNextPage}>+ <CrmListSkeleton label="Loading more items" count={2} />+ </Show></Show>- </Show>- </Match>- </Switch>+ </Match>+ </Switch>+ </div>);}diff --git a/apps/web/src/features/email-view/compose-email.ts b/apps/web/src/features/email-view/compose-email.tsindex 2489fce508..af85831858 100644--- a/apps/web/src/features/email-view/compose-email.ts+++ b/apps/web/src/features/email-view/compose-email.ts@@ -2,10 +2,11 @@ import { EMAIL_COMPOSE_TO_INPUT_ID } from '@app/features/email-compose/core/consimport type { useSplitLayout } from '@components/app/split-layout/layout';import { triggerFocusInput } from '@core/directive/focusInput';-/** Opens a new email from the current inbox scope, focusing the To field. */+/** Opens a new email from an inbox scope, optionally addressed to known recipients. */export function composeEmail(openWithSplit: ReturnType<typeof useSplitLayout>['openWithSplit'],- inboxIds?: string[]+ inboxIds?: string[],+ recipients?: string[]) {triggerFocusInput(() => document.getElementById(EMAIL_COMPOSE_TO_INPUT_ID));openWithSplit(@@ -14,9 +15,12 @@ export function composeEmail(id: 'email-compose',params: {initialInboxId: inboxIds?.length === 1 ? inboxIds[0] : undefined,+ ...(recipients?.length ? { initialTo: recipients } : {}),},preserveParams: true,},- { preferNewSplit: false }+ recipients?.length+ ? { preferNewSplit: true, allowDuplicate: true }+ : { preferNewSplit: false });}diff --git a/apps/web/src/features/next-soup/soup-view/soup-view.tsx b/apps/web/src/features/next-soup/soup-view/soup-view.tsxindex afc06971ea..2708a547b3 100644--- a/apps/web/src/features/next-soup/soup-view/soup-view.tsx+++ b/apps/web/src/features/next-soup/soup-view/soup-view.tsx@@ -545,7 +545,12 @@ interface SoupViewListProps {groupHeader?: import('solid-js').Component<GroupHeaderProps & { highlighted?: boolean }>;- emptyState?: () => JSX.Element;+ emptyState?: (state: {+ filtered: boolean;+ clearFilters: () => void;+ }) => JSX.Element;+ loadingContent?: JSX.Element;+ errorContent?: (retry: () => void) => JSX.Element;emptyContent?: JSX.Element;timestamp?: (entity: EntityData) => DateValue | null | undefined;navigationKey?: string;@@ -581,6 +586,8 @@ export const SoupViewList = (props: SoupViewListProps) => (timestamp={props.timestamp}navigationKey={props.navigationKey}emptyState={props.emptyState}+ loadingContent={props.loadingContent}+ errorContent={props.errorContent}emptyContent={props.emptyContent}/></SoupRowMetadataProvider>@@ -1124,7 +1131,11 @@ const SoupViewListContent = (props: SoupViewListProps) => {ref={setEmptyStateRef}class="flex-1 min-h-0 flex flex-col touch:pb-(--mobile-content-inset-bottom)">- <LoadErrorPanel onRetry={retryLoad} />+ {props.errorContent ? (+ props.errorContent(retryLoad)+ ) : (+ <LoadErrorPanel onRetry={retryLoad} />+ )}</div></Match><Match@@ -1136,7 +1147,7 @@ const SoupViewListContent = (props: SoupViewListProps) => {panel leaves list views unpadded so rows canunder-scroll the status bar. */}<div class="flex-1 min-h-0 flex flex-col touch:pt-(--mobile-content-inset-top) touch:pb-(--mobile-content-inset-bottom)">- <LoadingBlock />+ {props.loadingContent ?? <LoadingBlock />}</div></Match><Match@@ -1157,7 +1168,7 @@ const SoupViewListContent = (props: SoupViewListProps) => {class="flex-1 min-h-0 flex flex-col touch:pb-(--mobile-content-inset-bottom)"><Show- when={!searchText() && props.emptyState}+ when={props.emptyState}fallback={<EmptyStatecontent={props.emptyContent}@@ -1169,7 +1180,12 @@ const SoupViewListContent = (props: SoupViewListProps) => {/>}>- {(emptyState) => emptyState()()}+ {(emptyState) =>+ emptyState()({+ filtered: hasActiveRefinements(),+ clearFilters: resetToTabDefaults,+ })+ }</Show></div></Match>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.tsxindex fc9b6f6016..dff11abab3 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@@ -43,6 +43,7 @@ import {createEffect,createMemo,createSignal,+ type JSX,Match,type Setter,Show,@@ -92,6 +93,10 @@ const getStatusProperty = (task: TaskEntityWithProperties) => {export type TaskListProps = {/** The focusable list root, for callers that hand keyboard focus back. */ref?: (element: HTMLDivElement) => void;+ /** Optional list-state content; defaults remain unchanged for other callers. */+ emptyContent?: JSX.Element;+ loadingContent?: JSX.Element;+ errorContent?: JSX.Element;referencePropertyIds?: readonly string[];};@@ -435,29 +440,48 @@ export function TaskList(props: TaskListProps) {><Switch><Match when={!forceEmptyState() && source.isLoading()}>- <div class="grid min-h-0 flex-1 place-items-center text-ink-muted">- <SpinnerIcon class="size-5 animate-spin" />- </div>+ <Show+ when={props.loadingContent !== undefined}+ fallback={+ <div class="grid min-h-0 flex-1 place-items-center text-ink-muted">+ <SpinnerIcon class="size-5 animate-spin" />+ </div>+ }+ >+ {props.loadingContent}+ </Show></Match><Match when={!forceEmptyState() && source.error()}>- <div class="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 text-sm text-ink-muted">- <span>Tasks couldn’t be loaded.</span>- <Button- variant="secondary"- size="sm"- onClick={() =>- fireAndForget(source.refresh(), 'tasks-view')- }- >- Try again- </Button>- </div>+ <Show+ when={props.errorContent !== undefined}+ fallback={+ <div class="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 text-sm text-ink-muted">+ <span>Tasks couldn’t be loaded.</span>+ <Button+ variant="secondary"+ size="sm"+ onClick={() =>+ fireAndForget(source.refresh(), 'tasks-view')+ }+ >+ Try again+ </Button>+ </div>+ }+ >+ {props.errorContent}+ </Show></Match><Match when={forceEmptyState() || visibleRows().length === 0}><div class="flex min-h-0 flex-1 flex-col items-center justify-center gap-3 text-sm text-ink-muted">- <span>{emptyMessage()}</span>+ <Show+ when={props.emptyContent !== undefined}+ fallback={<span>{emptyMessage()}</span>}+ >+ {props.emptyContent}+ </Show><Show when={!forceEmptyState() && source.hasMore()}><Buttonvariant="secondary"diff --git a/apps/web/src/features/tasks-view/tasks-content.tsx b/apps/web/src/features/tasks-view/tasks-content.tsxindex 4c8426634a..5d654ad984 100644--- a/apps/web/src/features/tasks-view/tasks-content.tsx+++ b/apps/web/src/features/tasks-view/tasks-content.tsx@@ -1,6 +1,6 @@import SpinnerIcon from '@icon/system/regular/spinner.svg';import { Match, Suspense, Switch } from 'solid-js';-import { TaskList } from './components/task-list/TaskList';+import { TaskList, type TaskListProps } from './components/task-list/TaskList';import { TasksBoard } from './tasks-board';import { TasksGantt } from './tasks-gantt';import { useTasksView } from './tasks-view-context';@@ -18,14 +18,11 @@ 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[];-}) {+export function TasksContent(props: TaskListProps) {const { state } = useTasksView();return (- <Suspense fallback={<TasksLoading />}>+ <Suspense fallback={props.loadingContent ?? <TasksLoading />}><Switch><Match when={state.layout === 'board'}><TasksBoard ref={props.ref} />@@ -37,6 +34,9 @@ export function TasksContent(props: {<TaskListref={props.ref}referencePropertyIds={props.referencePropertyIds}+ emptyContent={props.emptyContent}+ loadingContent={props.loadingContent}+ errorContent={props.errorContent}/></Match></Switch>diff --git a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.tsindex 470863bc27..2f1d2c2426 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@@ -939,8 +939,10 @@ export type GraphqlDatabaseRowExpr =/** GraphQL input for selecting database rows through Soup. */export type GraphqlDatabaseRowLiteral ={ /** Match one row. */- id: string | number; tableId?: never; }- | { id?: never; /** Match the rows of a table. */+ id: string | number; include?: never; tableId?: never; }+ | { id?: never; /** Include accessible rows of every table; must be true. */+ include: boolean; tableId?: never; }+ | { id?: never; include?: never; /** Match the rows of a table. */tableId: string | number; };/** GraphQL input representing the date literal. */diff --git a/crates/databases_sql/src/test_support.rs b/crates/databases_sql/src/test_support.rsindex 4b045284f1..b00ca4aa38 100644--- a/crates/databases_sql/src/test_support.rs+++ b/crates/databases_sql/src/test_support.rs@@ -495,6 +495,7 @@ fn row_matches(expr: &Expr<DatabaseRowLiteral>, row: &StoredRow) -> bool {Expr::And(a, b) => row_matches(a, row) && row_matches(b, row),Expr::Or(a, b) => row_matches(a, row) || row_matches(b, row),Expr::Not(a) => !row_matches(a, row),+ Expr::Literal(DatabaseRowLiteral::Include) => true,Expr::Literal(DatabaseRowLiteral::TableId(table)) => {row.table_id == TableId::from_uuid(*table)}diff --git a/crates/graphql_soup_filter_input/src/lib.rs b/crates/graphql_soup_filter_input/src/lib.rsindex e2a674619d..fd34fc70e3 100644--- a/crates/graphql_soup_filter_input/src/lib.rs+++ b/crates/graphql_soup_filter_input/src/lib.rs@@ -1483,6 +1483,8 @@ filter_expr_input!(#[derive(Serialize, Deserialize)]#[serde(rename_all = "camelCase")]enum GraphqlDatabaseRowLiteral {+ /// Include accessible rows of every table; must be true.+ Include(bool),/// Match the rows of a table.TableId(ID),/// Match one row.@@ -1492,6 +1494,12 @@ enum GraphqlDatabaseRowLiteral {impl IntoFilterExpr<DatabaseRowLiteral> for GraphqlDatabaseRowLiteral {fn into_expr(self) -> InputResult<Expr<DatabaseRowLiteral>> {Ok(Expr::val(match self {+ Self::Include(false) => {+ return Err(InputError::new(+ "database row `include` must be true; omit the filter to exclude rows",+ ));+ }+ Self::Include(true) => DatabaseRowLiteral::Include,Self::TableId(id) => DatabaseRowLiteral::TableId(parse_id(id, "tableId")?),Self::Id(id) => DatabaseRowLiteral::Id(parse_id(id, "id")?),}))diff --git a/crates/graphql_soup_filter_input/src/test.rs b/crates/graphql_soup_filter_input/src/test.rsindex 56f3ebc459..535f174132 100644--- a/crates/graphql_soup_filter_input/src/test.rs+++ b/crates/graphql_soup_filter_input/src/test.rs@@ -189,6 +189,33 @@ fn initiative_property_filters_preserve_entity_scope() {));}+#[test]+fn database_row_include_materializes_and_false_is_rejected() {+ let input = json!({"databaseRowFilter": {"literal": {"include": true}}});+ let ast = materialize_graphql_filter(input.clone()).unwrap();+ assert_eq!(+ ast.database_row_filter.as_deref(),+ Some(&Expr::val(DatabaseRowLiteral::Include))+ );+ let graphql: GraphqlEntityFilterAst = serde_json::from_value(input).unwrap();+ assert_eq!(+ serde_json::to_value(ast).unwrap(),+ serde_json::to_value(graphql.into_ast().unwrap()).unwrap()+ );+ assert!(+ materialize_graphql_filter(json!({+ "databaseRowFilter": {"literal": {"include": false}}+ }))+ .is_err()+ );+ assert!(+ materialize_graphql_filter(json!({}))+ .unwrap()+ .database_row_filter+ .is_none()+ );+}+#[test]fn a_database_row_filter_names_a_table_or_a_row() {use item_filters::ast::database_row::DatabaseRowLiteral;diff --git a/crates/item_filter_index/src/lib.rs b/crates/item_filter_index/src/lib.rsindex c9ac409458..ce52aae405 100644--- a/crates/item_filter_index/src/lib.rs+++ b/crates/item_filter_index/src/lib.rs@@ -827,6 +827,7 @@ fn compile_chat_literal(literal: &ChatLiteral) -> Result<PredicateExpr, CompileEfn compile_database_row_literal(literal: &DatabaseRowLiteral) -> PredicateExpr {match literal {+ DatabaseRowLiteral::Include => PredicateExpr::All,DatabaseRowLiteral::TableId(id) => exact_uuid(vocabulary::table_id(), id),DatabaseRowLiteral::Id(id) => exact_uuid(vocabulary::id(), id),}diff --git a/crates/item_filter_index/src/test.rs b/crates/item_filter_index/src/test.rsindex 9957a3f803..7f44ac84b9 100644--- a/crates/item_filter_index/src/test.rs+++ b/crates/item_filter_index/src/test.rs@@ -505,6 +505,14 @@ fn a_tables_rows_compile_to_the_database_row_partition() {));+ let mut all_rows = excluded_deferred_partitions();+ all_rows.database_row_filter = Some(Arc::new(Expr::val(DatabaseRowLiteral::Include)));+ assert_eq!(rows_partition(&all_rows), PredicateExpr::All);+ assert_eq!(+ check_soup_flat_v3(&all_rows, request()),+ Eligibility::Unsupported(UnsupportedReason::Partition("database_row"))+ );+let without_rows = excluded_deferred_partitions();assert_eq!(rows_partition(&without_rows), PredicateExpr::None);diff --git a/crates/item_filters/src/ast/database_row.rs b/crates/item_filters/src/ast/database_row.rsindex 5ab4afc017..3fac042ac4 100644--- a/crates/item_filters/src/ast/database_row.rs+++ b/crates/item_filters/src/ast/database_row.rs@@ -2,10 +2,13 @@ use filter_ast::Expr;use serde::{Deserialize, Serialize};use uuid::Uuid;-/// A database row filter literal. Rows are off by default: only naming a-/// table or a row opts a query into them, so Home, Search and Recent never list them.+/// A database row filter literal. Rows are off by default: only an explicit+/// include or naming a table or row opts a query into them.#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)]pub enum DatabaseRowLiteral {+ /// Opt into accessible rows of every table.+ #[serde(rename = "inc")]+ Include,/// Rows of this table.#[serde(rename = "t")]TableId(Uuid),@@ -14,7 +17,7 @@ pub enum DatabaseRowLiteral {Id(Uuid),}-/// Whether the expression asks for rows at all: some table or row is named+/// Whether the expression asks for rows at all: an include, table or row/// outside a `NOT`. A missing filter or a solely negative one keeps rows out.pub fn database_rows_requested(filter: Option<&Expr<DatabaseRowLiteral>>) -> bool {match filter {diff --git a/crates/item_filters/src/ast/tests.rs b/crates/item_filters/src/ast/tests.rsindex 614681b936..98eaf1f1bc 100644--- a/crates/item_filters/src/ast/tests.rs+++ b/crates/item_filters/src/ast/tests.rs@@ -1683,12 +1683,22 @@ fn initiatives_expand_with_properties_without_enabling_legacy_queries() {}#[test]-fn database_rows_are_requested_by_naming_a_table_or_a_row_outside_a_not() {+fn database_rows_are_requested_by_include_or_id_outside_a_not() {use database_row::{DatabaseRowLiteral, database_rows_requested};let table = Uuid::from_u128(0x7ab1e);let row = Uuid::from_u128(0x0001);assert!(!database_rows_requested(None));+ assert!(database_rows_requested(Some(&Expr::val(+ DatabaseRowLiteral::Include+ ))));+ assert!(!database_rows_requested(Some(&Expr::is_not(Expr::val(+ DatabaseRowLiteral::Include+ )))));+ assert_eq!(+ serde_json::to_value(DatabaseRowLiteral::Include).unwrap(),+ json!("inc")+ );assert!(database_rows_requested(Some(&Expr::val(DatabaseRowLiteral::TableId(table)))));diff --git a/crates/soup/src/outbound/pg_soup_repo/crm_association.rs b/crates/soup/src/outbound/pg_soup_repo/crm_association.rsindex 3b5feab3b7..28c342e759 100644--- a/crates/soup/src/outbound/pg_soup_repo/crm_association.rs+++ b/crates/soup/src/outbound/pg_soup_repo/crm_association.rs@@ -9,8 +9,8 @@ use crate::domain::models::CrmPropertyEdge;#[cfg(test)]mod test;-/// Entities whose Companies property names a company in `company_ids`, or-/// whose Contacts property names a contact in `contact_ids`.+/// Entities whose Companies or Contacts properties name the requested CRM records,+/// including typed references in entity columns currently bound to database rows.////// The property definition ids are literals rather than binds so the planner/// can match the partial `idx_ep_companies_value_gin` and@@ -39,6 +39,27 @@ pub(super) async fn property_edges(JOIN entity_properties epON ep.property_definition_id = '00000001-0000-0000-0000-000000000013'AND ep.values->'value' @> jsonb_build_array(jsonb_build_object('entity_id', contact.id))+ UNION+ SELECT ep.entity_type, ep.entity_id+ FROM database_columns dc+ JOIN property_definitions pd+ ON pd.id = dc.property_definition_id AND pd.data_type = 'ENTITY'+ JOIN entity_properties ep+ ON ep.property_definition_id = dc.property_definition_id+ AND ep.entity_type = 'DATABASE_ROW'+ JOIN database_rows r+ ON r.id::text = ep.entity_id AND r.table_id = dc.table_id+ WHERE EXISTS (+ SELECT 1+ FROM jsonb_array_elements(+ CASE WHEN jsonb_typeof(ep.values->'value') = 'array'+ THEN ep.values->'value' ELSE '[]'::jsonb END+ ) AS reference+ WHERE (reference->>'entity_type' = 'COMPANY'+ AND reference->>'entity_id' = ANY($1::text[]))+ OR (reference->>'entity_type' = 'CONTACT'+ AND reference->>'entity_id' = ANY($2::text[]))+ )"#,&company_ids,&contact_ids,diff --git a/crates/soup/src/outbound/pg_soup_repo/database_row/test.rs b/crates/soup/src/outbound/pg_soup_repo/database_row/test.rsindex 74351f7a46..fc70bc3dac 100644--- a/crates/soup/src/outbound/pg_soup_repo/database_row/test.rs+++ b/crates/soup/src/outbound/pg_soup_repo/database_row/test.rs@@ -159,6 +159,15 @@ async fn naming_a_table_reads_only_that_tables_rows(pool: PgPool) {#[sqlx::test(fixtures("test/database_rows.sql"), migrator = "MACRO_DB_MIGRATIONS")]async fn rows_stay_out_of_queries_that_name_no_table(pool: PgPool) {assert!(page(&pool, viewer(), rows_of(None)).await.is_empty());+ assert!(+ page(+ &pool,+ viewer(),+ rows_of(Some(Expr::is_not(Expr::val(DatabaseRowLiteral::Include))))+ )+ .await+ .is_empty()+ );assert!(page(&pool,@@ -172,6 +181,47 @@ async fn rows_stay_out_of_queries_that_name_no_table(pool: PgPool) {);}+#[sqlx::test(fixtures("test/database_rows.sql"), migrator = "MACRO_DB_MIGRATIONS")]+async fn include_reads_all_accessible_tables_but_not_private_rows(pool: PgPool) {+ let include = Some(Expr::val(DatabaseRowLiteral::Include));+ assert_eq!(+ page(&pool, viewer(), rows_of(include.clone()))+ .await+ .iter()+ .map(Identify::id)+ .collect::<Vec<_>>(),+ vec![+ Uuid::from_u128(0x70000000_0000_0000_0000_000000000004),+ DEAL_3,+ DEAL_2,+ DEAL_1,+ ]+ );+ assert_eq!(+ page(&pool, stranger(), rows_of(include))+ .await+ .iter()+ .map(Identify::id)+ .collect::<Vec<_>>(),+ vec![NOTE]+ );+ assert_eq!(+ page(+ &pool,+ viewer(),+ rows_of(Some(Expr::and(+ Expr::val(DatabaseRowLiteral::Include),+ Expr::is_not(Expr::val(DatabaseRowLiteral::TableId(CONTACTS))),+ ))),+ )+ .await+ .iter()+ .map(Identify::id)+ .collect::<Vec<_>>(),+ vec![DEAL_3, DEAL_2, DEAL_1]+ );+}+#[sqlx::test(fixtures("test/database_rows.sql"), migrator = "MACRO_DB_MIGRATIONS")]async fn a_stranger_reads_no_rows_of_a_database_not_shared_with_them(pool: PgPool) {assert!(diff --git a/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic/database_row.rs b/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic/database_row.rsindex 8856538566..dfe3ddf6ac 100644--- a/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic/database_row.rs+++ b/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic/database_row.rs@@ -18,6 +18,7 @@ pub(in crate::outbound::pg_soup_repo) fn build_database_row_filter(Expr::And(a, b) => format!("({} AND {})", fold(a), fold(b)),Expr::Or(a, b) => format!("({} OR {})", fold(a), fold(b)),Expr::Not(a) => format!("NOT ({})", fold(a)),+ Expr::Literal(DatabaseRowLiteral::Include) => "TRUE".to_owned(),Expr::Literal(DatabaseRowLiteral::TableId(id)) => format!("r.table_id = '{id}'"),Expr::Literal(DatabaseRowLiteral::Id(id)) => format!("r.id = '{id}'"),}diff --git a/docs/agent-guide/crm.md b/docs/agent-guide/crm.mdindex 3fa27d98e8..67813e76ba 100644--- a/docs/agent-guide/crm.md+++ b/docs/agent-guide/crm.md@@ -6,12 +6,12 @@ On desktop, the local sidebar uses the same navigation primitives as Email and TIts **New** menu creates a **Company**, a **Contact**, or a **Pipeline** (Pipelineonly when pipelines are enabled; disabled until the team's CRM is enabled). The**Records** section lists **Companies**, **People**, **Tasks**, **Email**, **Notes**,-and **Calls**, in that order; Pipelines and Lists follow.+**Calls**, and **Databases**, in that order; Pipelines and Lists follow.There are no built-in company views or Board/List layout. Companies and Peopleare plain soup lists with the shared pagination. Existing personal/team savedviews stay in the toolbar's Views menu.-**Rollout:** Tasks, Email, Notes and Calls require PostHog `enable-crm-activity`+**Rollout:** Tasks, Email, Notes, Calls and Databases require PostHog `enable-crm-activity`(off by default; local override: `VITE_ENABLE_CRM_ACTIVITY=true`). CRM also usesthis flag to decide whether to supply its task-composer preset; the sharedcomposer itself is not feature-flagged. With it off, only Companies and People@@ -19,6 +19,9 @@ appear in Records, activity queries do not run, and activity deep links return tCompanies after flags finish loading. Global task creation uses the standardcomposer; record-level New task still associates the new task with that record.With it on, the activity and contextual composer behavior below applies.+Databases additionally requires `enable-databases`, including record tabs and direct tab links.+Database flag loading and unavailable states keep the desktop title and navigation+toggle visible, without mounting the list query or creation controls.Task creation opens immediately from the focused pane's registered preset,without fetching record details. Contact company prefills use already-loadeddetails. If CRM's flag is still loading, CRM supplies no preset. Later flag,@@ -27,7 +30,7 @@ context. If an embedded record shows a loading error, global task creation stilltargets the selected record until you close its details.The selected Customers list is stored on the pane as `sN.crm.tab`. People uses-`people`, activity tabs use `tasks`, `email`, `notes`, or `calls`, a list uses+`people`, activity tabs use `tasks`, `email`, `notes`, `calls`, or `databases`, a list uses`list:<uuid>`, and hidden companies use `hidden`. Companies is the default andomits the key. A pipeline has its own path, `/app/companies/pipeline/<uuid>`;older `sN.crm.tab=pipeline:<uuid>` URLs and shared `crmView` links that show a@@ -38,7 +41,7 @@ captured entry state within the current account session, including an openpipeline or record. Direct links and new-split actions keep their requesteddestination; reload and account changes clear the remembered location.-The four activity tabs show CRM-linked content, not the whole app: Tasks and+The activity tabs show CRM-linked content, not the whole app: Tasks andCalls require a Companies or Contacts reference; Notes are linked Markdowndocuments (excluding tasks, snippets, and skills); Email is your own mailbox'sthreads with CRM company domains or contact addresses. Lists page as you scroll.@@ -52,6 +55,26 @@ same preset. With an embedded company or contact detail open, global Createprefills the current breadcrumb record; a contact also includes its company.Closing the detail returns global Create to the unassociated CRM preset.+**Databases** lists each accessible database that contains a CRM-linked row once.+A company's tab includes rows linked to that company or its visible contacts; a+contact's tab matches that contact only. The sidebar view matches all visible CRM+records. Unlinked databases, trashed databases, and databases without access stay+out. These are row associations, not whole-database associations or new sharing+grants. **New database** opens the existing creation flow. Add a Companies or+Contacts column and link a row before the database appears in CRM.++Empty collection and record lists fill the available height with a horizontally+centered illustration, guidance, and a relevant creation action, raised toward+the toolbar rather than vertically centered. Search-empty states use a+different illustration and **Clear search**, not a creation prompt. Initial list+failures offer **Try again**; failed continuation pages retain existing rows.+Loading uses list skeletons while search and header actions remain available.+On desktop, each workspace activity view keeps its title, **New**, and expandable+**Search** in one header row, including when empty or loading. Command-F expands+and focuses Search; Escape clears and closes it. Phone activity views keep the+search field and creation action below the CRM navigation tabs. Record-detail+tabs retain their own section toolbar.+Activity rows show stored Companies and Contacts reference pills in the sharedSoup row. Click a pill to open its record; Shift-click opens a new split withoutopening the parent item. The first two references appear inline; **+N** opens@@ -111,7 +134,7 @@ and expand into the shared Email/Tasks search bar. Command-F expands and focusesthe field; Close or Escape clears the query and returns to the icon.On touch devices, CRM uses the same scrollable pill tabs as Tasks in the top-header: Companies, People, Tasks, Email, Notes, Calls, available pipelines, and+header: Companies, People, Tasks, Email, Notes, Calls, Databases, available pipelines, andenabled lists. Swipe thestrip horizontally to reach every destination; the selected tab stays visible.The tabs remain available inside pipelines, with no hamburger button. Company@@ -126,7 +149,7 @@ row navigates in place.Verify touch spacing with a nonzero top safe area (for example 47px): the CRMtab strip clears the status bar, while standalone company/contact Overview and-Team, Emails, Files, Tasks, and Calls clear both the status bar and floating+Team, Emails, Files, Tasks, Calls, and Databases clear both the status bar and floatingrecord navigation. Switch tabs and check the first title/search control isvisible and tappable. Scroll to the end to check content clears the dock. Repeatat tablet width; desktop retains its usual spacing. An embedded record header@@ -171,7 +194,7 @@ the toggle to dismiss it; the open state is not restored on a later visit.It copies the record's direct URL and shows a confirmation toast; this is alsoavailable in the embedded company and contact breadcrumb header.-The Team, Emails, Files, Tasks, and Calls tabs share a compact toolbar: search on+The Team, Emails, Files, Tasks, Calls, and Databases tabs share a compact toolbar: search onthe left, with available filters and actions on the right. Search remains visiblefor empty lists. `Add contact` and `New task` match the project task list'screation button: a rounded outline, standard height, and leading plus icon.@@ -187,7 +210,7 @@ Emails, Files, Calls, and References rows open their items without selectioncheckboxes, including on touch devices.A company is laid out like a project. Its split header or embedded breadcrumb-header shows rounded view tabs for `Overview`, `Team`, `Emails`, `Files`, `Tasks`, and `Calls`+header shows rounded view tabs for `Overview`, `Team`, `Emails`, `Files`, `Tasks`, `Calls`, and `Databases`tabs, collapsing to icons when narrow. Overview shows the name, pillsfor each domain and `Last interacted`, the generated description, a**Pipelines** section and the Discussion. Pipelines stacks one full-width card@@ -224,10 +247,10 @@ Discussion message makes its document the item. Initiatives and database rowsare not listed.When a record list fails to refresh (for example, the record becameinaccessible), it replaces its rows with `Couldn't load this list.` and-`Retry` reloads it; a failed later page keeps the rows and shows `Couldn't+`Try again` reloads it; a failed later page keeps the rows and shows `Couldn'tload more.`-A contact has the same layout with `Overview`, `Emails`, `Files`, `Tasks` and-`Calls`: Overview pills show the email, the company (opens it) and `Last+A contact has the same layout with `Overview`, `Emails`, `Files`, `Tasks`, `Calls`, and+`Databases`: Overview pills show the email, the company (opens it) and `Lastinteracted`, followed by the contact's Pipelines cards. Its Files, Tasks, Calls,and References show items associated with the contact itself (its `Contacts`property or an @mention of it), not everything associated with its company;@@ -240,6 +263,9 @@ focused row) opens the task detail view at `/app/tasks/<task-id>`, including onmobile. Shift-click opens it in a separate split. Verify that the task's statusand properties appear, rather than the regular Drive markdown editor.+Verify the real CRM routes separately with accessible and inaccessible databases,+multiple matching rows per database, empty matches, and a second page of results.+Mentioning a company or contact with `@` in a document or task records it as areference of that record (removing the chip removes it) without sharing thedocument, inviting anyone, or notifying the contact; channel and Discussiondiff --git a/static_assets/schema.graphql b/static_assets/schema.graphqlindex 038c0fbffd..60bd74be12 100644--- a/static_assets/schema.graphql+++ b/static_assets/schema.graphql@@ -3618,6 +3618,10 @@ input GraphqlDatabaseRowExpr @oneOf {GraphQL input for selecting database rows through Soup."""input GraphqlDatabaseRowLiteral @oneOf {+ """+ Include accessible rows of every table; must be true.+ """+ include: Boolean"""Match the rows of a table."""