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(tasks): add a Customer / Contact property to task creation (#9635)
teob4e9b4e1f52b
diff --git a/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx b/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsxindex c45c8ec57b..05e4304a3b 100644--- a/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx+++ b/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx@@ -573,10 +573,13 @@ describe('pane create context registration', () => {it('isolates snapshots from mutable provider values', () => {const context = mountCreateContext(() => 'pane');- const preset = crmTaskComposerContext({ type: 'company', id: 'acme' });+ const preset = {+ ...crmTaskComposerContext({ type: 'company', id: 'acme' }),+ visiblePropertyIds: ['existing-property'],+ };state.unregister.push(context.register('pane', () => ({ task: preset })));const snapshot = context.snapshot('task');- preset.visiblePropertyIds?.push('new-property');+ preset.visiblePropertyIds.push('new-property');expect(snapshot?.visiblePropertyIds).not.toContain('new-property');});diff --git a/apps/web/src/features/block-md/util/taskComposerProperties.ts b/apps/web/src/features/block-md/util/taskComposerProperties.tsindex c750db9425..c6b5dadeb0 100644--- a/apps/web/src/features/block-md/util/taskComposerProperties.ts+++ b/apps/web/src/features/block-md/util/taskComposerProperties.ts@@ -262,6 +262,8 @@ export function createTaskComposerProperties(args: {values?: Accessor<Record<string, PropertyApiValues>>;additionalPropertyIds?: Accessor<string[]>;initialVisiblePropertyIds?: string[];+ /** Properties a host edits with its own control: no pill, not addable. */+ hiddenPropertyIds?: readonly string[];allDefinitions?: boolean;}) {const [propertyValues, setPropertyValues] = createStore<@@ -351,7 +353,7 @@ export function createTaskComposerProperties(args: {],availableDefinitions(),projects().enabled- );+ ).filter((id) => !args.hiddenPropertyIds?.includes(id));const addableDefinitions = () =>availableDefinitions().filter((definition) =>@@ -376,7 +378,9 @@ export function createTaskComposerProperties(args: {availableDefinitions().filter((definition) =>- definition.id !== SYSTEM_PROPERTY_IDS.PROJECT || projects().enabled+ (definition.id !== SYSTEM_PROPERTY_IDS.PROJECT ||+ projects().enabled) &&+ !args.hiddenPropertyIds?.includes(definition.id)).map((definition) =>toPropertyDefinitionDomain(definition, options().get(definition.id))diff --git a/apps/web/src/features/crm/README.md b/apps/web/src/features/crm/README.mdindex 297c84a5db..ca2cff83ba 100644--- a/apps/web/src/features/crm/README.md+++ b/apps/web/src/features/crm/README.md@@ -116,9 +116,9 @@ the dependent query refreshes before the mutation stops being pending.`crm.people_visibility` measures the display choice through the next paint;Soup retains its existing query/loading instrumentation.-`task-composer.ts` owns the CRM task preset: Companies/Contacts are visible,-Status remains a task default but is not initially shown. CRM registers live-`{ task: TaskComposerContext }` values with the provider in+`task-composer.ts` owns the CRM task preset: the records a new task starts+associated with. The Customer / Contact pill belongs to the shared task composer,+not this preset. CRM registers live `{ task: TaskComposerContext }` values with the provider in`command/context/create-context.tsx`, scoped to its pane. The app shell owns theprovider and supplies the layout's focus accessor; no global registry or managerkey is involved. The workspace registers the unassociated preset; nested record@@ -129,13 +129,15 @@ The selected-record fallback survives detail query errors until the record closeGlobal task creation snapshots the focused pane's getter before opening, withoutfetching details or capturing navigation history. Record contexts isolate drafts.-`enable-crm-activity` gates workspace activity tabs and whether CRM supplies its-composer context. It defaults off everywhere and can be overridden locally with+`enable-crm-activity` gates workspace activity tabs, whether CRM supplies its+composer context, and, with `enable-crm`, the Customer / Contact pill in the task+composer and Universal Input's task mode. Those two read both flags through+`customerContactEnabled`. It defaults off everywhere and can be overridden locally with`VITE_ENABLE_CRM_ACTIVITY=true`. Off hides activity navigation and skips activityqueries; saved activity links wait for flag loading, then fall back to Companies.The standard record task action still associates the task with its record.-The shared composer, registry and launcher never read this flag. With no supplied-context, the standard composer opens immediately. Each opening snapshots its+The registry and launcher never read this flag. With no supplied context, the+standard composer opens immediately. Each opening snapshots itscontext; later flag, focus or record changes leave the open draft unchanged.The Soup and email SQL optimizations are independent of this frontend gate.diff --git a/apps/web/src/features/crm/record-tasks-adapter.test.tsx b/apps/web/src/features/crm/record-tasks-adapter.test.tsxindex 8622ec319a..62cfb0a789 100644--- a/apps/web/src/features/crm/record-tasks-adapter.test.tsx+++ b/apps/web/src/features/crm/record-tasks-adapter.test.tsx@@ -9,14 +9,12 @@ import { CrmRecordTasks } from './record-tasks-adapter';const {openWithSplit,popoverSplit,- adaptive,openTaskComposer,openItem,workspacePresent,} = vi.hoisted(() => ({openWithSplit: vi.fn(),popoverSplit: vi.fn(),- adaptive: vi.fn(() => false),openTaskComposer: vi.fn(),openItem: vi.fn(() => false),workspacePresent: vi.fn(() => true),@@ -36,10 +34,6 @@ vi.mock('@app/features/tasks-view/tasks-content', () => ({vi.mock('@components/app/split-layout/layout', () => ({useSplitLayout: () => ({ openWithSplit, popoverSplit }),}));-vi.mock('@core/constant/featureFlags', () => ({- enableCrmActivity: 'crm',- isFeatureEnabled: adaptive,-}));vi.mock('@property/tags/tag-sets-context', () => ({TagSetsQueryProvider: (props: ParentProps) => props.children,}));@@ -112,29 +106,25 @@ const scopes: CrmRecordScope[] = [{ type: 'company', id: 'company-1', domains: ['example.com'] },];-it.each([false, true])(- 'persists the original CRM context and associations with adaptive=%s',- (enabled) => {- adaptive.mockReturnValue(enabled);- render(() => <CrmRecordTasks scope={scopes[0]} />);- fireEvent.click(screen.getByRole('button', { name: 'New task' }));- const params = popoverSplit.mock.calls[0][0].params;- expect(params.composerContext.key).toBe('crm:contact:contact-1');- expect(Object.values(params.composerContext.initialPropertyValues)).toEqual(- expect.arrayContaining([- {- valueType: 'ENTITY',- refs: [{ entity_id: 'contact-1', entity_type: 'CONTACT' }],- },- {- valueType: 'ENTITY',- refs: [{ entity_id: 'company-1', entity_type: 'COMPANY' }],- },- ])- );- expect(params.createTask).toBeUndefined();- }-);+it('persists the original CRM context and associations', () => {+ render(() => <CrmRecordTasks scope={scopes[0]} />);+ fireEvent.click(screen.getByRole('button', { name: 'New task' }));+ const params = popoverSplit.mock.calls[0][0].params;+ expect(params.composerContext.key).toBe('crm:contact:contact-1');+ expect(Object.values(params.composerContext.initialPropertyValues)).toEqual(+ expect.arrayContaining([+ {+ valueType: 'ENTITY',+ refs: [{ entity_id: 'contact-1', entity_type: 'CONTACT' }],+ },+ {+ valueType: 'ENTITY',+ refs: [{ entity_id: 'company-1', entity_type: 'COMPANY' }],+ },+ ])+ );+ expect(params.createTask).toBeUndefined();+});it.each(scopes)('opens a task from a $type in the task view', (scope) => {render(() => <CrmRecordTasks scope={scope} />);diff --git a/apps/web/src/features/crm/record-tasks-adapter.tsx b/apps/web/src/features/crm/record-tasks-adapter.tsxindex 605097865f..999e204b45 100644--- a/apps/web/src/features/crm/record-tasks-adapter.tsx+++ b/apps/web/src/features/crm/record-tasks-adapter.tsx@@ -6,10 +6,6 @@ import {useTasksView,} from '@app/features/tasks-view/tasks-view-context';import { useSplitLayout } from '@components/app/split-layout/layout';-import {- enableCrmActivity,- isFeatureEnabled,-} from '@core/constant/featureFlags';import EmptyStateTasksGraphic from '@design/empty-state-tasks.svg';import { TagSetsQueryProvider } from '@property/tags/tag-sets-context';import { Show } from 'solid-js';@@ -83,17 +79,13 @@ function RecordTasksBody(props: { scope: CrmRecordScope }) {let listElement: HTMLDivElement | undefined;const composeTask = () => {- const context = crmTaskComposerContext(props.scope);- const adaptive = isFeatureEnabled(enableCrmActivity);layout.popoverSplit({type: 'component',id: 'task-compose',params: {- // Record identity/associations must survive a restart even with the- // standard property row; they cannot live only in a create callback.- composerContext: adaptive- ? context- : { ...context, visiblePropertyIds: undefined },+ // Record identity/associations must survive a restart; they cannot+ // live only in a create callback.+ composerContext: crmTaskComposerContext(props.scope),},});};diff --git a/apps/web/src/features/crm/task-composer.ts b/apps/web/src/features/crm/task-composer.tsindex fbf60d799e..b539f892c8 100644--- a/apps/web/src/features/crm/task-composer.ts+++ b/apps/web/src/features/crm/task-composer.ts@@ -35,13 +35,6 @@ export function crmTaskComposerContext(}return {key: record ? `crm:${record.type}:${record.id}` : 'crm',- visiblePropertyIds: [- SYSTEM_PROPERTY_IDS.COMPANIES,- SYSTEM_PROPERTY_IDS.CONTACTS,- SYSTEM_PROPERTY_IDS.ASSIGNEES,- SYSTEM_PROPERTY_IDS.DUE_DATE,- SYSTEM_PROPERTY_IDS.PRIORITY,- ],initialPropertyValues,};}diff --git a/apps/web/src/features/property/editors/popover/EntityEditor.tsx b/apps/web/src/features/property/editors/popover/EntityEditor.tsxindex beb066a50b..f0fb614d91 100644--- a/apps/web/src/features/property/editors/popover/EntityEditor.tsx+++ b/apps/web/src/features/property/editors/popover/EntityEditor.tsx@@ -16,6 +16,7 @@ import { useAgentAssignees } from '../../queries/agent-assignees';import type { EntityProperty, PropertyApiValues } from '../../types';import { isEntityProperty } from '../../utils';import { PropertyEntitySelector } from '../selectors/PropertyEntitySelector';+import type { EntityPickerOptions } from '../selectors/types';import { EditorPopover } from './EditorPopover';type EntityEditorProps = {@@ -25,6 +26,8 @@ type EntityEditorProps = {* is needed (e.g. composer with no entity yet).*/selfFilter?: { entityType: EntityType; blockId?: string };+ /** Set when one control edits several properties. */+ entityPicker?: EntityPickerOptions;};/**@@ -35,7 +38,10 @@ export function EntityEditor(props: EntityEditorProps) {const ctx = useProperty();return (<Show when={ctx.editorOpen() && isEntityProperty(ctx.property())}>- <EntityEditorBody selfFilter={props.selfFilter} />+ <EntityEditorBody+ selfFilter={props.selfFilter}+ entityPicker={props.entityPicker}+ /></Show>);}@@ -135,8 +141,12 @@ function EntityEditorSelector(<PropertyEntitySelectorconfig={{isMultiSelect: property.isMultiSelect,- placeholder: `${property.isMultiSelect ? 'Add' : 'Change'} ${property.displayName.toLowerCase()}...`,- specificEntityType: property.specificEntityType,+ placeholder:+ props.entityPicker?.placeholder ??+ `${property.isMultiSelect ? 'Add' : 'Change'} ${property.displayName.toLowerCase()}...`,+ emptyMessage: props.entityPicker?.emptyMessage,+ specificEntityType:+ props.entityPicker?.entityTypes ?? property.specificEntityType,selfFilter: props.selfFilter,users: isCompanyOwner ? teamMembers : undefined,additionalUsers: agents,@@ -179,7 +189,11 @@ function EntityEditorBody(props: EntityEditorProps) {const draft = createEntityEditorDraft();return (<EditorPopover onClose={draft.closeAndSave}>- <EntityEditorSelector selfFilter={props.selfFilter} draft={draft} />+ <EntityEditorSelector+ selfFilter={props.selfFilter}+ entityPicker={props.entityPicker}+ draft={draft}+ /></EditorPopover>);}@@ -194,7 +208,10 @@ export function EntitySheetEditor(props: EntityEditorProps) {return (<Show when={isEntityProperty(ctx.property())}><PickerSheet.Root open={ctx.editorOpen()} onCancel={ctx.closeEditor}>- <EntitySheetBody selfFilter={props.selfFilter} />+ <EntitySheetBody+ selfFilter={props.selfFilter}+ entityPicker={props.entityPicker}+ /></PickerSheet.Root></Show>);@@ -212,6 +229,7 @@ function EntitySheetBody(props: EntityEditorProps) {<PickerSheet.Body><EntityEditorSelectorselfFilter={props.selfFilter}+ entityPicker={props.entityPicker}draft={draft}fillHeightonCancel={ctx.closeEditor}diff --git a/apps/web/src/features/property/editors/popover/PopoverEditor.tsx b/apps/web/src/features/property/editors/popover/PopoverEditor.tsxindex 94e62e72c6..1d409a0bf6 100644--- a/apps/web/src/features/property/editors/popover/PopoverEditor.tsx+++ b/apps/web/src/features/property/editors/popover/PopoverEditor.tsx@@ -1,6 +1,7 @@import type { EntityType } from '@service-properties/generated/schemas/entityType';import { Match, Switch } from 'solid-js';import { useProperty } from '../../core/context';+import type { EntityPickerOptions } from '../selectors/types';import { DateEditor, DateSheetEditor } from './DateEditor';import { DateRangeEditor } from './DateRangeEditor';import { EntityEditor, EntitySheetEditor } from './EntityEditor';@@ -12,6 +13,8 @@ type PopoverEditorProps = {* Has no effect for non-entity properties.*/entitySelfFilter?: { entityType: EntityType; blockId?: string };+ /** Forwarded to EntityEditor; has no effect for non-entity properties. */+ entityPicker?: EntityPickerOptions;};/**@@ -35,7 +38,10 @@ export function PopoverEditor(props: PopoverEditorProps) {<SelectEditor /></Match><Match when={type() === 'ENTITY'}>- <EntityEditor selfFilter={props.entitySelfFilter} />+ <EntityEditor+ selfFilter={props.entitySelfFilter}+ entityPicker={props.entityPicker}+ /></Match></Switch>);@@ -51,10 +57,18 @@ export function SheetEditor(props: PopoverEditorProps) {const type = () => ctx.property().valueType;return (<Switch- fallback={<PopoverEditor entitySelfFilter={props.entitySelfFilter} />}+ fallback={+ <PopoverEditor+ entitySelfFilter={props.entitySelfFilter}+ entityPicker={props.entityPicker}+ />+ }><Match when={type() === 'ENTITY'}>- <EntitySheetEditor selfFilter={props.entitySelfFilter} />+ <EntitySheetEditor+ selfFilter={props.entitySelfFilter}+ entityPicker={props.entityPicker}+ /></Match><Match when={type() === 'DATE'}><DateSheetEditor />diff --git a/apps/web/src/features/property/editors/selectors/PropertyEntitySelector.tsx b/apps/web/src/features/property/editors/selectors/PropertyEntitySelector.tsxindex 163ee39834..5461ef0621 100644--- a/apps/web/src/features/property/editors/selectors/PropertyEntitySelector.tsx+++ b/apps/web/src/features/property/editors/selectors/PropertyEntitySelector.tsx@@ -58,9 +58,9 @@ type EntityInputProps = {};function getEntityTypePluralLabel(- entityType: EntityType | null | undefined+ entityType: EntityType | EntityType[] | null | undefined): string {- if (!entityType) return 'entities';+ if (!entityType || Array.isArray(entityType)) return 'entities';switch (entityType) {case 'USER':return 'users';@@ -229,10 +229,12 @@ export function PropertyEntitySelector(props: EntityInputProps) {} else {const entity = quickAccessItemToEntity(item);const entityType = getEntityType(entity);- if (- entityType &&- (!specificEntityType || entityType === specificEntityType)- ) {+ const matches =+ !specificEntityType ||+ (Array.isArray(specificEntityType)+ ? entityType && specificEntityType.includes(entityType)+ : entityType === specificEntityType);+ if (entityType && matches) {converted.push(entity);}}@@ -626,7 +628,8 @@ export function PropertyEntitySelector(props: EntityInputProps) {<Show when={totalCount() === 0}><div class="text-center py-4 text-ink-muted text-sm"><Show when={!isLoadingEntities()} fallback={<span>Loading...</span>}>- No {getEntityTypePluralLabel(props.config.specificEntityType)} found+ {props.config.emptyMessage ??+ `No ${getEntityTypePluralLabel(props.config.specificEntityType)} found`}</Show></div></Show>diff --git a/apps/web/src/features/property/editors/selectors/types.ts b/apps/web/src/features/property/editors/selectors/types.tsindex 867968bf5d..4fc5842e3d 100644--- a/apps/web/src/features/property/editors/selectors/types.ts+++ b/apps/web/src/features/property/editors/selectors/types.ts@@ -11,10 +11,19 @@ export type OptionSelectorConfig = {canAddOption?: (query: string) => boolean;};+/** One picker over several entity types, in its own wording. */+export type EntityPickerOptions = {+ entityTypes: EntityType[];+ placeholder: string;+ emptyMessage: string;+};+export type EntitySelectorConfig = {isMultiSelect: boolean;placeholder: string;- specificEntityType?: EntityType | null;+ /** Replaces "No {entity type} found". */+ emptyMessage?: string;+ specificEntityType?: EntityType | EntityType[] | null;selfFilter?: { entityType: EntityType; blockId?: string };/** Entities already linked to the destination are not selectable again. */excludedIds?: Accessor<ReadonlySet<string>>;diff --git a/apps/web/src/features/task-composer/components/customer-contact-pill.tsx b/apps/web/src/features/task-composer/components/customer-contact-pill.tsxnew file mode 100644index 0000000000..57fff00814--- /dev/null+++ b/apps/web/src/features/task-composer/components/customer-contact-pill.tsx@@ -0,0 +1,93 @@+import { t } from '@app/lib/i18n';+import { useQuickAccess } from '@core/context/quickAccess';+import { Property } from '@property';+import type { EntityProperty, PropertyApiValues } from '@property/types';+import type { EntityType } from '@service-properties/generated/schemas/entityType';+import { createMemo } from 'solid-js';+import { Dynamic } from 'solid-js/web';+import {+ customerContactReferences,+ customerContactSelection,+ customerContactValues,+} from '../customer-contact';++const ENTITY_TYPES: EntityType[] = ['COMPANY', 'CONTACT'];++/**+ * One dropdown over the Companies and Contacts properties. It edits a single+ * pick, shown as the contact when there is one, and writes both properties.+ */+export function CustomerContactPill(props: {+ values: Record<string, PropertyApiValues>;+ onChange: (values: Record<string, PropertyApiValues>) => void;+ disabled?: boolean;+ /** The editor the pill opens; `Property.SheetEditor` inside a touch sheet. */+ editor: typeof Property.PopoverEditor;+}) {+ const contacts = useQuickAccess().useList('crm_contact').items;++ const property = createMemo(+ (): EntityProperty => ({+ propertyId: 'compose-customer-contact',+ propertyDefinitionId: 'customer-contact',+ displayName: t('crm.customerContact'),+ isMultiSelect: false,+ owner: { scope: 'system' },+ updatedAt: new Date(0),+ createdAt: new Date(0),+ valueType: 'ENTITY',+ value: customerContactSelection(props.values),+ })+ );++ const save = async (_: unknown, value: PropertyApiValues) => {+ const picked = value.valueType === 'ENTITY' ? value.refs?.[0] : undefined;+ const contact = contacts().find((item) => item.id === picked?.entity_id);+ props.onChange(customerContactValues(picked, contact?.data.companyId));+ };++ return (+ <Property.Root+ property={property()}+ canEdit={!props.disabled}+ onSave={save}+ >+ {(shown) => (+ <>+ {/* The hover card names both records, as the pill shows only one. */}+ <Property.Tooltip+ property={{+ ...property(),+ isMultiSelect: true,+ value: customerContactReferences(props.values),+ }}+ >+ <Property.Pill variant="secondary" size="xs">+ <Property.Text+ property={shown()}+ resolveSingleEntity+ class="min-w-0 max-w-60"+ fallback={+ <Property.Empty+ propertyDefinitionId={shown().propertyDefinitionId}+ label={shown().displayName}+ iconClass="size-3 touch:size-4 shrink-0"+ />+ }+ />+ <Property.Caret />+ </Property.Pill>+ </Property.Tooltip>+ <Dynamic+ component={props.editor}+ entityPicker={{+ entityTypes: ENTITY_TYPES,+ placeholder: t('crm.searchCustomerContact'),+ emptyMessage: t('crm.noCustomerContactFound'),+ }}+ />+ </>+ )}+ </Property.Root>+ );+}diff --git a/apps/web/src/features/task-composer/customer-contact.test.ts b/apps/web/src/features/task-composer/customer-contact.test.tsnew file mode 100644index 0000000000..614d3b58e2--- /dev/null+++ b/apps/web/src/features/task-composer/customer-contact.test.ts@@ -0,0 +1,90 @@+import { SYSTEM_PROPERTY_IDS } from '@property/identifiers';+import type { PropertyApiValues } from '@property/types';+import { createMemo, createRoot } from 'solid-js';+import { createStore, reconcile } from 'solid-js/store';+import { describe, expect, it, vi } from 'vitest';+import {+ customerContactSelection,+ customerContactValues,+} from './customer-contact';++const COMPANIES = SYSTEM_PROPERTY_IDS.COMPANIES;+const CONTACTS = SYSTEM_PROPERTY_IDS.CONTACTS;+const company = { entity_id: 'company-1', entity_type: 'COMPANY' as const };+const contact = { entity_id: 'contact-1', entity_type: 'CONTACT' as const };++describe('customerContactValues', () => {+ it('leaves the contact unset when a company is picked', () => {+ expect(customerContactValues(company, undefined)).toEqual({+ [COMPANIES]: { valueType: 'ENTITY', refs: [company] },+ [CONTACTS]: { valueType: 'ENTITY', refs: null },+ });+ });++ it('sets both when a contact is picked', () => {+ expect(customerContactValues(contact, 'company-1')).toEqual({+ [COMPANIES]: { valueType: 'ENTITY', refs: [company] },+ [CONTACTS]: { valueType: 'ENTITY', refs: [contact] },+ });+ });++ it('clears an earlier company when the picked contact has none', () => {+ expect(customerContactValues(contact, null)).toEqual({+ [COMPANIES]: { valueType: 'ENTITY', refs: null },+ [CONTACTS]: { valueType: 'ENTITY', refs: [contact] },+ });+ });++ it('clears both when the pick is removed', () => {+ expect(customerContactValues(undefined, undefined)).toEqual({+ [COMPANIES]: { valueType: 'ENTITY', refs: null },+ [CONTACTS]: { valueType: 'ENTITY', refs: null },+ });+ });+});++describe('customerContactSelection', () => {+ it('selects the contact when both are set', () => {+ expect(+ customerContactSelection({+ [COMPANIES]: { valueType: 'ENTITY', refs: [company] },+ [CONTACTS]: { valueType: 'ENTITY', refs: [contact] },+ })+ ).toEqual([contact]);+ });++ it('selects the company when no contact is set', () => {+ expect(+ customerContactSelection({+ [COMPANIES]: { valueType: 'ENTITY', refs: [company] },+ [CONTACTS]: { valueType: 'ENTITY', refs: null },+ })+ ).toEqual([company]);+ });++ it('re-evaluates when a reset rewrites the same-length list in place', () => {+ const picked: Record<string, PropertyApiValues> = {+ [COMPANIES]: { valueType: 'ENTITY', refs: [company] },+ [CONTACTS]: { valueType: 'ENTITY', refs: [contact] },+ };+ const other = { entity_id: 'contact-2', entity_type: 'CONTACT' as const };+ const [values, setValues] = createStore(picked);++ createRoot((dispose) => {+ const evaluate = vi.fn(() => customerContactSelection(values));+ const selection = createMemo(evaluate);+ expect(selection()).toEqual([contact]);++ setValues(+ reconcile({+ [COMPANIES]: { valueType: 'ENTITY', refs: [company] },+ [CONTACTS]: { valueType: 'ENTITY', refs: [other] },+ })+ );++ expect(evaluate).toHaveBeenCalledTimes(2);+ expect(selection()).toEqual([other]);+ dispose();+ });+ });+});diff --git a/apps/web/src/features/task-composer/customer-contact.ts b/apps/web/src/features/task-composer/customer-contact.tsnew file mode 100644index 0000000000..9d2bcb36b1--- /dev/null+++ b/apps/web/src/features/task-composer/customer-contact.ts@@ -0,0 +1,75 @@+import {+ enableCrm,+ enableCrmActivity,+ isFeatureEnabled,+} from '@core/constant/featureFlags';+import { SYSTEM_PROPERTY_IDS } from '@property/identifiers';+import type { PropertyApiValues } from '@property/types';+import type { EntityReference } from '@service-properties/generated/schemas/entityReference';++/** The properties the Customer / Contact pill writes, replacing their own pills. */+export const CUSTOMER_CONTACT_PROPERTY_IDS: readonly string[] = [+ SYSTEM_PROPERTY_IDS.COMPANIES,+ SYSTEM_PROPERTY_IDS.CONTACTS,+];++/** Whether task creation shows the pill. Read once per opening of a form. */+export function customerContactEnabled(): boolean {+ return isFeatureEnabled(enableCrm) && isFeatureEnabled(enableCrmActivity);+}++function entityReferences(value: PropertyApiValues | undefined) {+ return value?.valueType === 'ENTITY' ? (value.refs ?? []) : [];+}++/** The company and contact held by a composer's property values. */+export function customerContactReferences(+ values: Record<string, PropertyApiValues>+): EntityReference[] {+ return [+ ...entityReferences(values[SYSTEM_PROPERTY_IDS.COMPANIES]),+ ...entityReferences(values[SYSTEM_PROPERTY_IDS.CONTACTS]),+ ];+}++/**+ * The one reference the pill selects: the contact when there is one. Returns+ * copies so a caller tracks the IDs: `reconcile` rewrites a same-length list in+ * place, which a caller holding only the list would never see.+ */+export function customerContactSelection(+ values: Record<string, PropertyApiValues>+): EntityReference[] {+ const contacts = entityReferences(values[SYSTEM_PROPERTY_IDS.CONTACTS]);+ const selected =+ contacts.length > 0+ ? contacts+ : entityReferences(values[SYSTEM_PROPERTY_IDS.COMPANIES]);+ return selected.map((reference) => ({ ...reference }));+}++/**+ * Both property values for a pick. A company leaves the contact unset, and a+ * contact also sets the company it belongs to.+ */+export function customerContactValues(+ picked: EntityReference | undefined,+ contactCompanyId: string | null | undefined+): Record<string, PropertyApiValues> {+ const contact = picked?.entity_type === 'CONTACT' ? picked : undefined;+ const contactCompany: EntityReference | undefined = contactCompanyId+ ? { entity_id: contactCompanyId, entity_type: 'COMPANY' }+ : undefined;+ const company = contact ? contactCompany : picked;++ return {+ [SYSTEM_PROPERTY_IDS.COMPANIES]: {+ valueType: 'ENTITY',+ refs: company ? [company] : null,+ },+ [SYSTEM_PROPERTY_IDS.CONTACTS]: {+ valueType: 'ENTITY',+ refs: contact ? [contact] : null,+ },+ };+}diff --git a/apps/web/src/features/task-composer/primitives/task-composer.ts b/apps/web/src/features/task-composer/primitives/task-composer.tsindex 2edd2bb98d..b1cd5df4cc 100644--- a/apps/web/src/features/task-composer/primitives/task-composer.ts+++ b/apps/web/src/features/task-composer/primitives/task-composer.ts@@ -49,6 +49,10 @@ import {import { reconcile, unwrap } from 'solid-js/store';import { tabbable } from 'tabbable';import type { ComposeTaskProps, ComposeTaskSuccess } from '../core/types';+import {+ CUSTOMER_CONTACT_PROPERTY_IDS,+ customerContactEnabled,+} from '../customer-contact';import { showTaskCreatedToast } from './taskCreatedToast';type ComposerTagLayoutMode = 'bottom' | 'title';@@ -219,6 +223,9 @@ export function createTaskComposer(}};+ // Read once per opening, so a flag change leaves an open draft's row alone.+ const showCustomerContact = customerContactEnabled();+const {propertyValues,setPropertyValues,@@ -234,6 +241,9 @@ export function createTaskComposer(} = createTaskComposerProperties({initialValues: initialState.propertyValues,initialVisiblePropertyIds: initialState.visiblePropertyIds,+ hiddenPropertyIds: showCustomerContact+ ? CUSTOMER_CONTACT_PROPERTY_IDS+ : undefined,allDefinitions: true,});let baselinePropertyValues = JSON.stringify(initialState.propertyValues);@@ -631,6 +641,8 @@ export function createTaskComposer(handleTitleTagPickerActive,deleteTitleTagsAtStart,properties,+ showCustomerContact,+ propertyValues,setPropertyValues,availableProperties,addProperty,diff --git a/apps/web/src/features/task-composer/views/task-composer-parts.tsx b/apps/web/src/features/task-composer/views/task-composer-parts.tsxindex 6f3f7d99c2..764be4c4ff 100644--- a/apps/web/src/features/task-composer/views/task-composer-parts.tsx+++ b/apps/web/src/features/task-composer/views/task-composer-parts.tsx@@ -23,6 +23,7 @@ import {} from 'solid-js';import { Dynamic } from 'solid-js/web';import { tabbable } from 'tabbable';+import { CustomerContactPill } from '../components/customer-contact-pill';import {ComposeTaskTitleEditor,TaskTitleAccessory,@@ -310,6 +311,13 @@ function Properties(props: { class?: string }) {/>)}</For>+ <Show when={composer.showCustomerContact}>+ <CustomerContactPill+ values={composer.propertyValues}+ onChange={composer.setPropertyValues}+ editor={pickers.propertyEditor}+ />+ </Show><Show when={composer.tagLayoutMode() === 'bottom'}><Dynamiccomponent={pickers.tagsPill}diff --git a/apps/web/src/features/universal-input/queries/task-field-source.test.ts b/apps/web/src/features/universal-input/queries/task-field-source.test.tsindex c3ea27ff3a..33b6ae7554 100644--- a/apps/web/src/features/universal-input/queries/task-field-source.test.ts+++ b/apps/web/src/features/universal-input/queries/task-field-source.test.ts@@ -82,6 +82,47 @@ it('loads a cold catalog through the shared query before supplying inference and});});+it('creates with Companies and Contacts without offering them to extraction', async () => {+ await createRoot(async (dispose) => {+ try {+ const definition = (id: string, display_name: string) => ({+ definition: {+ id,+ display_name,+ data_type: 'ENTITY',+ is_multi_select: true,+ specific_entity_type: 'COMPANY',+ is_metadata: false,+ is_system: true,+ owner: { scope: 'system' },+ created_at: '',+ updated_at: '',+ },+ property_options: [],+ });+ query.isSuccess = false;+ query.refetch.mockResolvedValue({+ isSuccess: true,+ data: [+ definition(SYSTEM_PROPERTY_IDS.COMPANIES, 'Companies'),+ definition(SYSTEM_PROPERTY_IDS.CONTACTS, 'Contacts'),+ ],+ });+ const source = createTaskFieldSource('me');+ expect(await source.definitions()).toEqual([]);+ const definitions = await source.createDefinitions();+ expect(+ definitions.get(SYSTEM_PROPERTY_IDS.COMPANIES)?.is_multi_select+ ).toBe(true);+ expect(+ definitions.get(SYSTEM_PROPERTY_IDS.CONTACTS)?.is_multi_select+ ).toBe(true);+ } finally {+ dispose();+ }+ });+});+it('rejects impossible inferred due dates and permits a manual correction', () => {createRoot((dispose) => {try {diff --git a/apps/web/src/features/universal-input/queries/task-field-source.ts b/apps/web/src/features/universal-input/queries/task-field-source.tsindex 1925f87370..7fdb830e5a 100644--- a/apps/web/src/features/universal-input/queries/task-field-source.ts+++ b/apps/web/src/features/universal-input/queries/task-field-source.ts@@ -6,6 +6,7 @@ import {} from '@property/constants';import { useListPropertiesQuery } from '@queries/properties/definitions';import type { PropertyDefinitionResponse } from '@service-properties/generated/schemas/propertyDefinitionResponse';+import { CUSTOMER_CONTACT_PROPERTY_IDS } from '../../task-composer/customer-contact';import type { InputFields } from '../core/input';import {parseTaskDate,@@ -20,10 +21,12 @@ export function createTaskFieldSource(userId: string) {scope: 'system',includeOptions: true,}));+ // What extraction may suggest; Customer / Contact is only ever picked by hand.const allowed = new Set([...getBuiltinPropertyIds('task'),SYSTEM_PROPERTY_IDS.PROJECT,]);+ const creatable = new Set([...allowed, ...CUSTOMER_CONTACT_PROPERTY_IDS]);const items = useQuickAccess().useList('person','initiative',@@ -31,12 +34,13 @@ export function createTaskFieldSource(userId: string) {'document');const fromRows = (- rows: PropertyDefinitionResponse[]+ rows: PropertyDefinitionResponse[],+ ids: ReadonlySet<string> = allowed): TaskFieldDefinition[] =>rows.flatMap((property) => {const definition ='definition' in property ? property.definition : property;- if (!allowed.has(definition.id)) return [];+ if (!ids.has(definition.id)) return [];return [{definition,@@ -46,12 +50,12 @@ export function createTaskFieldSource(userId: string) {];});const definitions = () => (query.isSuccess ? fromRows(query.data) : []);- const loadDefinitions = async () => {- if (query.isSuccess) return definitions();+ const loadRows = async () => {+ if (query.isSuccess) return query.data;const result = await query.refetch({ cancelRefetch: false });if (!result.isSuccess)throw result.error ?? new Error('Could not load task fields');- return fromRows(result.data);+ return result.data;};const references = (): TaskReference[] =>items.items().map((item) =>@@ -78,7 +82,7 @@ export function createTaskFieldSource(userId: string) {);return {definitions: async () =>- (await loadDefinitions())+ fromRows(await loadRows()).filter(({ definition }) => definition.id !== SYSTEM_PROPERTY_IDS.DUE_DATE)@@ -88,7 +92,7 @@ export function createTaskFieldSource(userId: string) {})),createDefinitions: async () =>new Map(- (await loadDefinitions()).map(({ definition }) => [+ fromRows(await loadRows(), creatable).map(({ definition }) => [definition.id,definition,])diff --git a/apps/web/src/features/universal-input/task-fields.tsx b/apps/web/src/features/universal-input/task-fields.tsxindex fa53d5c753..19551888b6 100644--- a/apps/web/src/features/universal-input/task-fields.tsx+++ b/apps/web/src/features/universal-input/task-fields.tsx@@ -1,10 +1,16 @@import { InlinePropertyValue } from '@app/features/block-md/component/InlinePropertyValue';import { createTaskComposerProperties } from '@app/features/block-md/util/taskComposerProperties';+import { Property } from '@property';import { Modals } from '@property/component/modal';import { PropertiesProvider } from '@property/context/PropertiesContext';import type { PropertyApiValues } from '@property/types';import { EntityComposer } from '@ui';-import { For } from 'solid-js';+import { For, Show } from 'solid-js';+import { CustomerContactPill } from '../task-composer/components/customer-contact-pill';+import {+ CUSTOMER_CONTACT_PROPERTY_IDS,+ customerContactEnabled,+} from '../task-composer/customer-contact';import { parseTaskProperties } from './queries/task-properties';export function TaskFields(props: {@@ -13,10 +19,14 @@ export function TaskFields(props: {values: Record<string, PropertyApiValues>;onChange: (value: string) => void;}) {+ const showCustomerContact = customerContactEnabled();const state = createTaskComposerProperties({initialValues: {},values: () => props.values,additionalPropertyIds: () => Object.keys(props.values),+ hiddenPropertyIds: showCustomerContact+ ? CUSTOMER_CONTACT_PROPERTY_IDS+ : undefined,});const saveHandler: typeof state.saveHandler = {async saveProperty(property, value) {@@ -55,6 +65,21 @@ export function TaskFields(props: {/>)}</For>+ <Show when={showCustomerContact}>+ <CustomerContactPill+ values={props.values}+ disabled={props.disabled}+ onChange={(values) =>+ props.onChange(+ JSON.stringify({+ ...parseTaskProperties(props.value),+ ...values,+ })+ )+ }+ editor={Property.PopoverEditor}+ />+ </Show></EntityComposer.Properties><Modals /></PropertiesProvider>diff --git a/apps/web/src/lib/i18n/locales/en/crm.ts b/apps/web/src/lib/i18n/locales/en/crm.tsindex 1afff1658f..5d58cfa7a0 100644--- a/apps/web/src/lib/i18n/locales/en/crm.ts+++ b/apps/web/src/lib/i18n/locales/en/crm.ts@@ -1,4 +1,7 @@export default {+ customerContact: 'Customer / Contact',+ searchCustomerContact: 'Search customers and contacts...',+ noCustomerContactFound: 'No customers or contacts found',stageRequirements: 'Stage requirements',stageRequirementsDescription:'Choose fields that must be filled before a deal enters a stage.',diff --git a/docs/agent-guide/crm.md b/docs/agent-guide/crm.mdindex 948459194f..3688a606b1 100644--- a/docs/agent-guide/crm.md+++ b/docs/agent-guide/crm.md@@ -18,8 +18,8 @@ it again can retry. Marking read does not mark the notification done.**Rollout:** Tasks, Email, Notes, Calls and Databases require PostHog `enable-crm-activity`(off by default; local override: `VITE_ENABLE_CRM_ACTIVITY=true`). CRM also uses-this flag to decide whether to supply its task-composer preset; the shared-composer itself is not feature-flagged. With it off, only Companies and People+this flag to decide whether to supply its task-composer preset, and with+`enable-crm` to show the Customer / Contact pill when creating any task. With it off, only Companies and Peopleappear in Records, activity queries do not run, and activity deep links return toCompanies after flags finish loading. Global task creation uses the standardcomposer; record-level New task still associates the new task with that record.@@ -53,8 +53,8 @@ threads with CRM company domains or contact addresses. Lists page as you scroll.Empty CRM scope never falls back to all content. Activity loads directly with aserver-resolved scope; it does not fetch every company and contact first. Hiddencompanies and contacts stay excluded even for admins. A loading failure offers-**Try again**. Tasks has **New task**, with Companies and Contacts visible in-place of Status. Choose a CRM association when creating a task from this feed.+**Try again**. Tasks has **New task**, which opens the task composer. Choose a CRM+association with its **Customer / Contact** pill when creating a task from this feed.Opening Task through the global Create menu while Customers is focused uses thesame preset. With an embedded company or contact detail open, global Createprefills the current breadcrumb record; a contact also includes its company.diff --git a/docs/agent-guide/navigation.md b/docs/agent-guide/navigation.mdindex e9d2185961..20d507a6f5 100644--- a/docs/agent-guide/navigation.md+++ b/docs/agent-guide/navigation.md@@ -825,7 +825,9 @@ while inference is pending. Email and message modes show their outgoing bodyand resolved recipients. Email uses the Email Composer's inbox picker, recipientchips with address completion, separate Cc/Bcc controls, subject control, rich Markdown editor, and HTMLpreparation for delivery. Task creation uses the task composer's rich title,-Markdown description, and editable property pills, including Due date.+Markdown description, and editable property pills, including Due date, and the+same **Customer / Contact** pill as the task composer when its flags are on (see+[tasks](tasks.md)). Extraction never fills that pill.Calendar uses the event composer's date/time popovers and calendar, guest, andlocation and recurrence pills, including the shared custom recurrence builder.Manual recurrence choices, including Does not repeat, survive later predictions.diff --git a/docs/agent-guide/tasks.md b/docs/agent-guide/tasks.mdindex 14204e876a..c16995a62c 100644--- a/docs/agent-guide/tasks.md+++ b/docs/agent-guide/tasks.md@@ -848,15 +848,22 @@ The app shell's creation-context provider snapshots the focused pane's presetbefore the composer opens. It reads the layout's existing focus accessor, not aglobal context registry; no detail fetch or navigation-state capture is needed.Without a preset, the standard property row and draft are used. The shared-composer is not feature-flagged. Create-menu actions, shortcuts, and pane buttons+composer's only flag gate is the Customer / Contact pill below. Create-menu actions, shortcuts, and pane buttonscapture the provider during setup and read the preset when invoked.-Customers supplies its preset when PostHog `enable-crm-activity` is enabled:-**Companies** and **Contacts** replace Status in the initial row; Status still-starts as Not Started on the saved task. Record-level task creation prefills the-company or contact, including the contact's company when already loaded. With the-CRM flag off or loading, record-level creation uses the standard property row-while retaining its record-scoped draft and associations. **Add property** opens the same property+With PostHog `enable-crm` and `enable-crm-activity` both on, every opening of the+composer, and Universal Input's task mode, shows one **Customer / Contact** pill, a single-choice picker of companies+and contacts that writes the Companies and Contacts properties. Picking a company+leaves the contact unset; picking a contact also sets its company, and the pill+shows the contact with both named on hover. A team with no CRM records sees the+pill with "No customers or contacts found". Neither property is offered separately+under **Add property** while the pill shows. With either flag off, there is no pill+and both stay under **Add property**.++Customers supplies its preset when `enable-crm-activity` is on. Record-level task+creation prefills the company or contact, including the contact's company when+already loaded. With the CRM flag off or loading, record-level creation uses the+standard property row while retaining its record-scoped draft and associations. **Add property** opens the same propertyeditor as the document/task side panel: search by name or type, select a propertyand enter its value, or create a property from an unmatched search. Assignmentsand values stay in the task draft until creation; opening or closing the editor