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): records sidebar, soup-backed people, and database-styled pipelines (#7787)
teo028698d8fccb
diff --git a/apps/web/src/features/crm/browser-test/pipelines.tsx b/apps/web/src/features/crm/browser-test/pipelines.tsxindex 02ae24a721..e88e8d1fb1 100644--- a/apps/web/src/features/crm/browser-test/pipelines.tsx+++ b/apps/web/src/features/crm/browser-test/pipelines.tsx@@ -142,7 +142,7 @@ function Fixture() {Editor={Editor}Sharing={() => null}onCopyLink={() => {}}- onBack={() => setSelected(undefined)}+ onTrashed={() => setSelected(undefined)}/>)}</Show>diff --git a/apps/web/src/features/crm/collection-filters.ts b/apps/web/src/features/crm/collection-filters.tsindex ff3892f97c..c0182eba1c 100644--- a/apps/web/src/features/crm/collection-filters.ts+++ b/apps/web/src/features/crm/collection-filters.ts@@ -108,6 +108,9 @@ function crmCompanyActivePredicate(entity: EntityData): boolean {function crmCompanyHiddenPredicate(entity: EntityData): boolean {return entity.type === 'crm_company' && entity.hidden;}+function crmContactActivePredicate(entity: EntityData): boolean {+ return entity.type === 'crm_contact' && !entity.hidden;+}export const crmCompanyFilter = config({id: 'crm-company',@@ -130,3 +133,11 @@ export const crmCompanyHiddenFilter = config({{ skipTargets: ['ccf'] }),});+export const crmContactActiveFilter = config({+ id: 'crm-contact-active',+ predicate: crmContactActivePredicate,+ query: defineQueryFilters(+ { include: { crmContactHidden: false } },+ { skipTargets: ['crmf'] }+ ),+});diff --git a/apps/web/src/features/crm/collection-presets.ts b/apps/web/src/features/crm/collection-presets.tsindex f23daedcdb..0824b72e2d 100644--- a/apps/web/src/features/crm/collection-presets.ts+++ b/apps/web/src/features/crm/collection-presets.ts@@ -26,5 +26,12 @@ export const CRM_TAB_PRESETS: ViewTabConfig = {groupBy: `property:${SYSTEM_PROPERTY_IDS.STAGE}`,};},+ people: () => ({+ filters: defineQueryFilters(+ { include: { crmContactHidden: false } },+ { skipTargets: ['crmf'] }+ ),+ clientFilters: { and: ['crm-contact-active'] },+ }),},};diff --git a/apps/web/src/features/crm/components/company-select.tsx b/apps/web/src/features/crm/components/company-select.tsxnew file mode 100644index 0000000000..82ed06a49a--- /dev/null+++ b/apps/web/src/features/crm/components/company-select.tsx@@ -0,0 +1,169 @@+import type { CollectionNode } from '@kobalte/core';+import { Combobox } from '@kobalte/core/combobox';+import BuildingsIcon from '@phosphor/buildings.svg';+import CaretDownIcon from '@phosphor/caret-down.svg';+import CheckIcon from '@phosphor/check.svg';+import SearchIcon from '@phosphor/magnifying-glass.svg';+import { Layer } from '@ui';+import { type Accessor, createSignal, Show } from 'solid-js';+import { Virtualizer, type VirtualizerHandle } from 'virtua/solid';++export type CompanyOption = { id: string; name: string; domain: string };++const ITEM_HEIGHT = 32;++function CompanyListbox() {+ let handle: VirtualizerHandle | undefined;+ // Kobalte hands back the filtered collection, so scrolling indexes into it.+ let visible: Accessor<Iterable<CollectionNode<CompanyOption>>> | undefined;+ return (+ <Combobox.Listbox<CompanyOption>+ scrollToItem={(key) => {+ const index = Array.from(visible?.() ?? []).findIndex(+ (item) => item.rawValue.id === key+ );+ if (index !== -1) handle?.scrollToIndex(index, { align: 'nearest' });+ }}+ class="max-h-60 overflow-y-auto scrollbar-hidden"+ >+ {(items) => {+ visible = items;+ return (+ <Virtualizer+ ref={(h) => (handle = h)}+ data={[...items()]}+ itemSize={ITEM_HEIGHT}+ >+ {(item) => (+ <Combobox.Item+ item={item}+ class="flex w-full cursor-default items-center gap-1.5 rounded-lg p-1.5 px-2 text-left text-sm data-highlighted:bg-ink/5"+ >+ <span class="flex size-3.5 shrink-0 items-center justify-center text-accent">+ <Combobox.ItemIndicator>+ <CheckIcon class="size-3" />+ </Combobox.ItemIndicator>+ </span>+ <Combobox.ItemLabel class="min-w-0 truncate text-ink">+ {item.rawValue.name}+ </Combobox.ItemLabel>+ <span class="ml-auto min-w-0 shrink-[2] truncate text-xs text-ink-extra-muted">+ {item.rawValue.domain}+ </span>+ </Combobox.Item>+ )}+ </Virtualizer>+ );+ }}+ </Combobox.Listbox>+ );+}++/** Searchable single-company picker, matching on name or domain. */+export function CompanySelect(props: {+ id?: string;+ companies: CompanyOption[];+ value: CompanyOption | undefined;+ onChange: (company: CompanyOption) => void;+ loading: boolean;+ /** Mount the menu in the nearest portal scope, e.g. inside a modal dialog. */+ portalScope?: 'local';+}) {+ let trigger: HTMLButtonElement | undefined;+ const [search, setSearch] = createSignal('');+ const matches = (option: CompanyOption, query: string) =>+ option.name.toLowerCase().includes(query) ||+ option.domain.toLowerCase().includes(query);+ const hasMatches = () => {+ const query = search().trim().toLowerCase();+ return props.companies.some((option) => matches(option, query));+ };+ return (+ <Combobox<CompanyOption>+ multiple={false}+ options={props.companies}+ value={props.value ?? null}+ onChange={(option) => option && props.onChange(option)}+ onInputChange={setSearch}+ onOpenChange={(open) => !open && setSearch('')}+ optionValue="id"+ optionTextValue={(option) => `${option.name} ${option.domain}`}+ // The trigger shows the selection; keep the search box empty on open.+ optionLabel={() => ''}+ defaultFilter={(option, input) =>+ matches(option, input.trim().toLowerCase())+ }+ virtualized+ allowsEmptyCollection+ placement="bottom-start"+ sameWidth+ gutter={4}+ >+ <Combobox.Control>+ <Combobox.Trigger+ ref={trigger}+ id={props.id}+ type="button"+ class="flex h-9 w-full min-w-0 items-center gap-2 rounded-lg border border-edge-muted px-3 text-left text-sm text-ink outline-none focus-visible:border-edge"+ >+ <BuildingsIcon class="size-4 shrink-0 text-ink-placeholder" />+ <Show+ when={props.value}+ fallback={+ <span class="flex-1 truncate text-ink-placeholder">+ {props.loading ? 'Loading companies…' : 'Choose a company'}+ </span>+ }+ >+ {(company) => (+ <span class="flex min-w-0 flex-1 items-baseline gap-2">+ <span class="truncate">{company().name}</span>+ <span class="truncate text-xs text-ink-extra-muted">+ {company().domain}+ </span>+ </span>+ )}+ </Show>+ <CaretDownIcon class="size-3 shrink-0 text-ink-muted" />+ </Combobox.Trigger>+ </Combobox.Control>+ <Combobox.Portal+ mount={+ props.portalScope === 'local'+ ? (trigger?.closest<HTMLElement>('.portal-scope') ?? undefined)+ : undefined+ }+ >+ <Layer depth={2}>+ <Combobox.Content class="z-action-menu overflow-hidden rounded-xl border border-edge-muted bg-surface shadow-md">+ <div class="flex items-center gap-2 border-b border-edge-muted px-3 py-2">+ <SearchIcon class="size-3.5 shrink-0 text-ink-muted" />+ <Combobox.Input+ class="min-w-0 flex-1 bg-transparent text-sm caret-accent outline-none placeholder:text-ink-placeholder"+ placeholder="Search companies..."+ />+ </div>+ {/* Pressing an option must not move focus to the dialog, which+ closes the menu before the click selects it. */}+ <div class="p-1" onMouseDown={(event) => event.preventDefault()}>+ <Show+ when={hasMatches()}+ fallback={+ <div class="px-2 py-3 text-center text-xs text-ink-muted">+ {props.loading+ ? 'Loading companies…'+ : search().trim()+ ? `No companies match "${search().trim()}"`+ : 'No companies yet'}+ </div>+ }+ >+ <CompanyListbox />+ </Show>+ </div>+ </Combobox.Content>+ </Layer>+ </Combobox.Portal>+ </Combobox>+ );+}diff --git a/apps/web/src/features/crm/components/contact-grid-template.ts b/apps/web/src/features/crm/components/contact-grid-template.tsnew file mode 100644index 0000000000..56fe627123--- /dev/null+++ b/apps/web/src/features/crm/components/contact-grid-template.ts@@ -0,0 +1,17 @@+/** People columns, shared by the rows and header so their tracks line up. */+export function contactGridTemplate(hideIndicator: boolean) {+ return {+ 'grid-template-columns': [+ ...(hideIndicator ? [] : ['1rem']),+ 'minmax(0, 100%)',+ 'var(--contact-col-company, 12rem)',+ 'var(--contact-col-timestamp, 7rem)',+ ].join(' '),+ 'grid-template-areas': `"${[+ ...(hideIndicator ? [] : ['indicator']),+ 'content',+ 'company',+ 'timestamp',+ ].join(' ')}"`,+ };+}diff --git a/apps/web/src/features/crm/components/crm-create-menu.tsx b/apps/web/src/features/crm/components/crm-create-menu.tsxnew file mode 100644index 0000000000..1be64dcd20--- /dev/null+++ b/apps/web/src/features/crm/components/crm-create-menu.tsx@@ -0,0 +1,51 @@+import { ViewSidebar } from '@app/components/view-shell';+import BuildingsIcon from '@phosphor/buildings.svg';+import CaretDownIcon from '@phosphor/caret-down.svg';+import PlusIcon from '@phosphor/plus.svg';+import TableIcon from '@phosphor/table.svg';+import UserIcon from '@phosphor/user.svg';+import { Dropdown } from '@ui';+import { Show } from 'solid-js';++/** Sidebar create action for every CRM record type. */+export function CrmCreateMenu(props: {+ onCreateCompany(): void;+ onCreateContact(): void;+ /** Omitted while pipelines are unavailable to the viewer. */+ pipeline?: { disabled: boolean; onCreate(): void };+}) {+ return (+ <Dropdown placement="bottom-start">+ <Dropdown.Trigger as={ViewSidebar.Action} aria-label="Create CRM record">+ <ViewSidebar.Icon>+ <PlusIcon class="size-4" />+ </ViewSidebar.Icon>+ <span class="truncate">New</span>+ <ViewSidebar.Trailing>+ <CaretDownIcon class="size-3 shrink-0" />+ </ViewSidebar.Trailing>+ </Dropdown.Trigger>+ <Dropdown.Content class="min-w-48">+ <Dropdown.Item onSelect={props.onCreateCompany}>+ <BuildingsIcon aria-hidden="true" class="size-4 shrink-0" />+ <span>Company</span>+ </Dropdown.Item>+ <Dropdown.Item onSelect={props.onCreateContact}>+ <UserIcon aria-hidden="true" class="size-4 shrink-0" />+ <span>Contact</span>+ </Dropdown.Item>+ <Show when={props.pipeline}>+ {(pipeline) => (+ <Dropdown.Item+ disabled={pipeline().disabled}+ onSelect={() => pipeline().onCreate()}+ >+ <TableIcon aria-hidden="true" class="size-4 shrink-0" />+ <span>Pipeline</span>+ </Dropdown.Item>+ )}+ </Show>+ </Dropdown.Content>+ </Dropdown>+ );+}diff --git a/apps/web/src/features/crm/components/crm-sidebar.tsx b/apps/web/src/features/crm/components/crm-sidebar.tsxindex 8f2feb7350..00a3918a5d 100644--- a/apps/web/src/features/crm/components/crm-sidebar.tsx+++ b/apps/web/src/features/crm/components/crm-sidebar.tsx@@ -1,110 +1,101 @@import { CollapsibleSection, ViewSidebar } from '@app/components/view-shell';-import { SidebarCreateHeader } from '@app/components/view-shell/SidebarCreateButton';-import { TabsInset } from '@core/component/TabsInset';+import { isTouchDevice } from '@core/mobile/isTouchDevice';+import BuildingsIcon from '@phosphor/buildings.svg';import ExportIcon from '@phosphor/download-simple.svg';import GearIcon from '@phosphor/gear-six.svg';import ListIcon from '@phosphor/list-bullets.svg';import PlusIcon from '@phosphor/plus.svg';import SidebarIcon from '@phosphor/sidebar-simple.svg';-import StackIcon from '@phosphor/stack.svg';import ImportIcon from '@phosphor/upload-simple.svg';+import UsersIcon from '@phosphor/users.svg';import { Button, Tooltip } from '@ui';import { tourTarget } from '@ui/components/Tour';import { createSignal, For, type JSX, Show } from 'solid-js';-import { CRM_VIEWS } from '../core/navigation';+import { Dynamic } from 'solid-js/web';+import { CRM_RECORDS } from '../core/navigation';import { COMPANIES_TOUR } from '../tour';+import { CrmCreateMenu } from './crm-create-menu';++const RECORD_ICONS = { active: BuildingsIcon, people: UsersIcon };export function CrmSidebar(props: {+ /** The highlighted record type, list, or pipeline. */active: string;pipelines?: JSX.Element;- viewMode: 'board' | 'list';- onViewModeChange: (mode: 'board' | 'list') => void;lists: { id: string; name: string; count: number }[];- savedViews: { id: string; name: string }[];listsEnabled: boolean;listsLoading: boolean;listsError: boolean;canCreateList: boolean;onNavigate: (id: string) => void;- onCreate: () => void;+ onCreateCompany: () => void;+ onCreateContact: () => void;+ /** Pipeline creation, omitted while pipelines are unavailable. */+ pipeline?: { disabled: boolean; onCreate(): void };onNewList: () => void;onImport: () => void;onExport: () => void;onSettings: () => void;onCollapse: () => void;}) {- const [viewsOpen, setViewsOpen] = createSignal(true);+ const [recordsOpen, setRecordsOpen] = createSignal(true);const [listsOpen, setListsOpen] = createSignal(true);return (<ViewSidebar.Root aria-label="CRM navigation">- <SidebarCreateHeader- title="Customers"- label="New company"- onCreate={props.onCreate}- actions={- <Tooltip label="Collapse CRM sidebar">- <Button- variant="ghost"- size="icon-sm"- label="Collapse CRM sidebar"- onClick={props.onCollapse}- >- <SidebarIcon class="size-4" />- </Button>- </Tooltip>- }- />- <ViewSidebar.Content>- <div ref={tourTarget(COMPANIES_TOUR.layout)} class="px-1.5">- <TabsInset- aria-label="Company layout"- fullWidth- class="h-auto"- labelClass="py-1.5"- list={[- { value: 'board', label: 'Board' },- { value: 'list', label: 'List' },- ]}- value={props.viewMode}- onChange={(mode) =>- props.onViewModeChange(mode === 'board' ? 'board' : 'list')- }+ <header class="flex shrink-0 flex-col">+ <Show when={!isTouchDevice()}>+ <ViewSidebar.Header>+ <div class="flex min-w-0 items-center gap-1">+ <ViewSidebar.CloseButton class="shrink-0" />+ <ViewSidebar.Title>Customers</ViewSidebar.Title>+ </div>+ <Tooltip label="Collapse CRM sidebar">+ <Button+ variant="ghost"+ size="icon-sm"+ label="Collapse CRM sidebar"+ onClick={props.onCollapse}+ >+ <SidebarIcon class="size-4" />+ </Button>+ </Tooltip>+ </ViewSidebar.Header>+ </Show>+ <ViewSidebar.Primary ref={tourTarget(COMPANIES_TOUR.create)}>+ <CrmCreateMenu+ onCreateCompany={props.onCreateCompany}+ onCreateContact={props.onCreateContact}+ pipeline={props.pipeline}/>- </div>- <CollapsibleSection.Root open={viewsOpen()} onOpenChange={setViewsOpen}>+ </ViewSidebar.Primary>+ </header>+ <ViewSidebar.Content>+ <CollapsibleSection.Root+ open={recordsOpen()}+ onOpenChange={setRecordsOpen}+ ><CollapsibleSection.Trigger>- <span>Views</span>+ <span>Records</span><CollapsibleSection.Indicator /></CollapsibleSection.Trigger><CollapsibleSection.Content><ViewSidebar.Nav- aria-label="Company views"- ref={tourTarget(COMPANIES_TOUR.views)}+ aria-label="CRM records"+ ref={tourTarget(COMPANIES_TOUR.records)}>- <For each={CRM_VIEWS}>- {(view) => (- <Tooltip label={view.description} placement="right">- <ViewSidebar.Item- active={props.active === view.id}- onClick={() => props.onNavigate(view.id)}- >- <ViewSidebar.Icon />- <span class="truncate">{view.label}</span>- </ViewSidebar.Item>- </Tooltip>- )}- </For>- <For each={props.savedViews}>- {(view) => (+ <For each={CRM_RECORDS}>+ {(record) => (<ViewSidebar.Item- active={props.active === view.id}- title={view.name}- onClick={() => props.onNavigate(view.id)}+ active={props.active === record.id}+ onClick={() => props.onNavigate(record.id)}><ViewSidebar.Icon>- <StackIcon class="size-4" />+ <Dynamic+ component={RECORD_ICONS[record.id]}+ class="size-4"+ /></ViewSidebar.Icon>- <span class="truncate">{view.name}</span>+ <span class="truncate">{record.label}</span></ViewSidebar.Item>)}</For>diff --git a/apps/web/src/features/crm/context/company-board-source.ts b/apps/web/src/features/crm/context/company-board-source.tsdeleted file mode 100644index 727d5ccd3f..0000000000--- a/apps/web/src/features/crm/context/company-board-source.ts+++ /dev/null@@ -1,15 +0,0 @@-import type { Accessor } from 'solid-js';-import type { DealStage } from '../core/stages';--export type CompanyBoardSource<T extends { id: string }> = {- companies: Accessor<T[]>;- stages: Accessor<DealStage[]>;- filterStages: Accessor<DealStage[]>;- selectedStages: Accessor<string[]>;- noStageFilter: string;- resolveStage(company: T): string | undefined;- canEdit: Accessor<boolean>;- canMoveClosed: Accessor<boolean>;- closedStages: Accessor<ReadonlySet<string>>;- saveStage(id: string, stage: string, onError: () => void): void;-};diff --git a/apps/web/src/features/crm/context/crm-context.tsx b/apps/web/src/features/crm/context/crm-context.tsxindex 7cce3f8384..3016b15755 100644--- a/apps/web/src/features/crm/context/crm-context.tsx+++ b/apps/web/src/features/crm/context/crm-context.tsx@@ -23,7 +23,6 @@ import type {ExportDefinitionsSource,ItemListSource,ListsSource,- PeopleSource,PersonalViewsSource,PropertyCommands,TeamConfigSource,@@ -92,7 +91,9 @@ export type CrmContext = {createResetStages(): CrmMutation<void>;createExportDefinitions(enabled: Accessor<boolean>): ExportDefinitionsSource;createCompanySuggestions(): {- companies: Accessor<{ id: string; name: string }[]>;+ companies: Accessor<+ { id: string; name: string; domains: { domain: string }[] }[]+ >;query: { readonly isLoading: boolean };};exportCompanies(@@ -105,17 +106,16 @@ export type CrmContext = {toggleListColumn(column: CrmListColumnId): void;};openCreateCompany(): void;- openCreateContact(companyId: string, domain: string): void;+ /** Without a company, the dialog asks which company the contact joins. */+ openCreateContact(company?: { companyId: string; domain: string }): void;userId: Accessor<string | undefined>;isTeamAdmin: () => Accessor<boolean>;createCompanySource(id: Accessor<string>): CompanySource;createContactSource(id: Accessor<string>): ContactSource;createTeamSource(): TeamSource;- createPeopleSource(enabled: Accessor<boolean>): PeopleSource;createTeamConfigSource(): TeamConfigSource;createCapabilities(): CrmCapabilities;createDealStages(): DealStages;- createUnavailable(): Accessor<boolean>;createClosedStageIds(stages: Accessor<{ id: string; label: string }[]>): Accessor<Set<string>>;diff --git a/apps/web/src/features/crm/context/crm-sources.ts b/apps/web/src/features/crm/context/crm-sources.tsindex 3ee4d11939..98319b8d58 100644--- a/apps/web/src/features/crm/context/crm-sources.ts+++ b/apps/web/src/features/crm/context/crm-sources.ts@@ -155,15 +155,3 @@ export type ExportDefinitionsSource = {readonly isError: boolean;readonly data: ExportDefinition[];};--export type PeopleSource = {- people: Accessor<import('../core/people').CrmPerson[]>;- query: {- readonly isError: boolean;- readonly isFetching: boolean;- readonly hasNextPage: boolean;- readonly isFetchNextPageError: boolean;- fetchNextPage(): Promise<unknown>;- refetch(): Promise<unknown>;- };-};diff --git a/apps/web/src/features/crm/context/view-commands.ts b/apps/web/src/features/crm/context/view-commands.tsindex ecd764485c..62eb97c910 100644--- a/apps/web/src/features/crm/context/view-commands.ts+++ b/apps/web/src/features/crm/context/view-commands.ts@@ -8,6 +8,4 @@ export type CrmViewCommands = {setSort(value: string[]): void;setStageFilter(value: string[]): void;setOwnerFilter(value: string[]): void;- setViewMode(value: 'list' | 'board'): void;- defaultMode(): 'list' | 'board';};diff --git a/apps/web/src/features/crm/context/workspace-context.tsx b/apps/web/src/features/crm/context/workspace-context.tsxindex f0a4c124af..0c80529c97 100644--- a/apps/web/src/features/crm/context/workspace-context.tsx+++ b/apps/web/src/features/crm/context/workspace-context.tsx@@ -38,7 +38,7 @@ export type CrmWorkspace = {hasNextPage: Accessor<boolean>;fetchNextPage(): Promise<void>;};- queryFilters: Pick<QueryStore, 'state' | 'replace'>;+ queryFilters: Pick<QueryStore, 'state' | 'set' | 'replace'>;searchText: Accessor<string>;setSearchText(value: string): void;activeTab: Accessor<string | undefined>;@@ -47,8 +47,6 @@ export type CrmWorkspace = {setStageFilter: Setter<string[]>;ownerFilter: Accessor<string[]>;setOwnerFilter: Setter<string[]>;- viewMode: Accessor<'list' | 'board'>;- setViewMode: Setter<'list' | 'board'>;};const Context = createContext<CrmWorkspace>();export const CrmWorkspaceProvider = Context.Provider;diff --git a/apps/web/src/features/crm/core/navigation.ts b/apps/web/src/features/crm/core/navigation.tsindex 603185c4dd..a937a13325 100644--- a/apps/web/src/features/crm/core/navigation.ts+++ b/apps/web/src/features/crm/core/navigation.ts@@ -1,36 +1,7 @@-export const CRM_VIEWS = [- {- id: 'people',- label: 'People',- description: 'Contacts across your teams, combined by email',- },- {- id: 'active',- label: 'All companies',- description: 'Every visible company in your CRM',- },- {- id: 'my-companies',- label: 'My companies',- description: 'Companies assigned to you',- },- {- id: 'needs-follow-up',- label: 'Needs follow-up',- description:- 'Has a stage other than Churned, with no interaction in the last 14 days',- },- {- id: 'recently-active',- label: 'Recently active',- description:- 'Team email activity in the last 7 days. Newly added companies may also appear.',- },- {- id: 'unassigned',- label: 'Unassigned',- description: 'Companies without an owner',- },+/** The record types the CRM sidebar lists; ids are workspace tabs. */+export const CRM_RECORDS = [+ { id: 'active', label: 'Companies' },+ { id: 'people', label: 'People' },] as const;export type CrmListConfig = {diff --git a/apps/web/src/features/crm/core/people.test.ts b/apps/web/src/features/crm/core/people.test.tsindex c16ab524a6..e289ab71e1 100644--- a/apps/web/src/features/crm/core/people.test.ts+++ b/apps/web/src/features/crm/core/people.test.ts@@ -1,9 +1,5 @@import { describe, expect, it } from 'vitest';-import {- type CrmPerson,- deduplicatePeople,- filterAndSortPeople,-} from './people';+import { type CrmPerson, deduplicatePeople } from './people';const person = (id: string, overrides: Partial<CrmPerson> = {}): CrmPerson => ({id,@@ -40,35 +36,4 @@ describe('people directory', () => {).toEqual(['z', 'alias']);expect(firstPage[0].id).toBe('new');});- it('searches contact names, emails and companies without exposing hidden contacts', () => {- const rows = [- person('Ada'),- person('B', { companyName: 'Ada Labs' }),- person('C', { email: '[email protected]' }),- person('D', { name: 'Ada', hidden: true }),- ];- expect(- filterAndSortPeople(rows, ' ADA ', 'name', false).map((row) => row.id)- ).toEqual(['Ada', 'B', 'C']);- expect(rows).toHaveLength(4);- });- it('orders actual interaction dates across companies and places missing dates last', () => {- const rows = [- person('old', { lastInteraction: '2024-09-16' }),- person('unknown', { lastInteraction: '' }),- person('new', { lastInteraction: '2026-09-16' }),- ];- expect(- filterAndSortPeople(rows, '', 'lastInteraction', true).map(- (row) => row.id- )- ).toEqual(['new', 'old', 'unknown']);- });- it('sorts unnamed contacts by email and leaves the input order unchanged', () => {- const rows = [person('z', { name: null }), person('a')];- expect(- filterAndSortPeople(rows, '', 'name', false).map((row) => row.id)- ).toEqual(['a', 'z']);- expect(rows.map((row) => row.id)).toEqual(['z', 'a']);- });});diff --git a/apps/web/src/features/crm/core/people.ts b/apps/web/src/features/crm/core/people.tsindex 95be8fed52..7e393617bf 100644--- a/apps/web/src/features/crm/core/people.ts+++ b/apps/web/src/features/crm/core/people.ts@@ -1,11 +1,6 @@import type { CrmContact } from './contact';export type CrmPerson = CrmContact & { companyName: string };-export type PeopleSort =- | 'name'- | 'companyName'- | 'lastInteraction'- | 'firstInteraction';/** The fields that choose one visible record for a contact email. */export type ContactRepresentative = {@@ -39,29 +34,3 @@ export function deduplicatePeople<T extends ContactRepresentative>(}return [...byEmail.values()];}--export function filterAndSortPeople(- people: CrmPerson[],- search: string,- sort: PeopleSort,- descending: boolean-) {- const term = search.trim().toLowerCase();- return people- .filter(- (person) =>- !person.hidden &&- [person.name, person.email, person.companyName].some((value) =>- value?.toLowerCase().includes(term)- )- )- .sort((a, b) => {- const left = sort === 'name' ? a.name || a.email : a[sort];- const right = sort === 'name' ? b.name || b.email : b[sort];- const order =- sort === 'lastInteraction' || sort === 'firstInteraction'- ? (Date.parse(left) || 0) - (Date.parse(right) || 0)- : left.localeCompare(right, undefined, { sensitivity: 'base' });- return (descending ? -order : order) || a.id.localeCompare(b.id);- });-}diff --git a/apps/web/src/features/crm/core/saved-view.ts b/apps/web/src/features/crm/core/saved-view.tsindex c97131a5a4..c5e18682b2 100644--- a/apps/web/src/features/crm/core/saved-view.ts+++ b/apps/web/src/features/crm/core/saved-view.ts@@ -11,7 +11,6 @@ export type CrmViewConfig = {groupBy?: string | null;/** Sort ids (soup sort state). */sort?: string[];- viewMode?: 'list' | 'board';/** Stage option ids selected in the Stage filter (may include NO_STAGE). */stageFilter?: string[];/** Owner ids selected in the Owner filter. */@@ -52,12 +51,6 @@ export function isCrmViewConfig(value: unknown): value is CrmViewConfig {typeof value.groupBy !== 'string')return false;- if (- value.viewMode !== undefined &&- value.viewMode !== 'list' &&- value.viewMode !== 'board'- )- return false;if (value.isDefault !== undefined && typeof value.isDefault !== 'boolean')return false;return (diff --git a/apps/web/src/features/crm/core/stages.ts b/apps/web/src/features/crm/core/stages.tsindex 56e8efe0c1..a7bd542024 100644--- a/apps/web/src/features/crm/core/stages.ts+++ b/apps/web/src/features/crm/core/stages.ts@@ -1,39 +1,4 @@export type DealStage = { id: string; label: string };-export const NO_STAGE_KEY = '';-export type StageColumn = { key: string; label: string };--export function boardStageColumns(- stages: readonly DealStage[],- filterStages: readonly DealStage[],- selected: readonly string[],- noStageFilter: string-): StageColumn[] {- const candidates = [- ...filterStages.map((stage) => ({ key: stage.id, label: stage.label })),- { key: NO_STAGE_KEY, label: 'No stage' },- ];- if (selected.length === 0) {- const active = new Set(stages.map((stage) => stage.id));- return candidates.filter(- (column) => column.key === NO_STAGE_KEY || active.has(column.key)- );- }- return candidates.filter((column) =>- selected.includes(column.key === NO_STAGE_KEY ? noStageFilter : column.key)- );-}--export function canDragCompanyStage(- stageKey: string,- canEdit: boolean,- closed: ReadonlySet<string>,- canMoveClosed: boolean-): boolean {- return (- canEdit &&- (stageKey === NO_STAGE_KEY || !closed.has(stageKey) || canMoveClosed)- );-}export function resolveCompanyStage(input: {direct: string | undefined;diff --git a/apps/web/src/features/crm/creation-adapter.ts b/apps/web/src/features/crm/creation-adapter.tsindex 09ec9b1c2e..36400f5e4c 100644--- a/apps/web/src/features/crm/creation-adapter.ts+++ b/apps/web/src/features/crm/creation-adapter.ts@@ -3,19 +3,22 @@ import { createSignal } from 'solid-js';// App-level launchers connect global create actions to the one mounted dialog host.const [companyOpen, setCompanyOpen] = createSignal(false);-const [contactTarget, setContactTarget] = createSignal<{- companyId: string;- domain: string;-}>();+type ContactCreationTarget = {+ company?: { companyId: string; domain: string };+};+const [contactTarget, setContactTarget] = createSignal<ContactCreationTarget>();const companyLock = useFocusLock('create-company');const contactLock = useFocusLock('create-contact');export function openCreateCompanyModal() {companyLock.acquire();setCompanyOpen(true);}-export function openCreateContactModal(companyId: string, domain: string) {+export function openCreateContactModal(company?: {+ companyId: string;+ domain: string;+}) {contactLock.acquire();- setContactTarget({ companyId, domain });+ setContactTarget({ company });}export const companyCreation = {open: companyOpen,diff --git a/apps/web/src/features/crm/crm-adapter.ts b/apps/web/src/features/crm/crm-adapter.tsindex 58c67c2a57..6ab95e3c87 100644--- a/apps/web/src/features/crm/crm-adapter.ts+++ b/apps/web/src/features/crm/crm-adapter.ts@@ -41,7 +41,6 @@ import { PipelineDatabaseEditor, PipelineShare } from './pipeline-adapter';import {createClosedStageIds,createCrmPermissions,- createCrmUnavailable,} from './primitives/team-config';import {useCompanyQuery,@@ -60,7 +59,6 @@ import {} from './queries/contacts';import { fetchCrmExportCompanies } from './queries/export';import { useCrmLists } from './queries/lists';-import { useCrmPeopleQuery } from './queries/people';import { createPipelinesSource } from './queries/pipelines';import {useRecordCallsQuery,@@ -241,12 +239,10 @@ export function createAppCrmContext(): CrmContext {createContactSource: (...args) =>withReadyGate(useContactQuery(deps, ...args)),createTeamSource: useCurrentTeamQuery,- createPeopleSource: (enabled) => useCrmPeopleQuery(deps, enabled),createTeamConfigSource: createSettings,createCapabilities: () =>createCrmPermissions(userId, useCurrentTeamQuery(), createSettings()),createDealStages: createAppDealStages,- createUnavailable: () => createCrmUnavailable(useCurrentTeamQuery()),createClosedStageIds: (stages) =>createClosedStageIds(createSettings(), stages),createPersonalViews: () => usePersonalCrmViews(deps),diff --git a/apps/web/src/features/crm/filter-adapter.tsx b/apps/web/src/features/crm/filter-adapter.tsxindex 950a5a22a7..7493703147 100644--- a/apps/web/src/features/crm/filter-adapter.tsx+++ b/apps/web/src/features/crm/filter-adapter.tsx@@ -1,7 +1,6 @@import { makeFlaggedPersisted } from '@app/preferences/make-flagged-persisted';import { useEntryState } from '@components/app/split-layout/entry-state';import { UserIcon } from '@core/component/UserIcon';-import { isTouchDevice } from '@core/mobile/isTouchDevice';import { idToDisplayName } from '@core/user/util';import CircleDashedIcon from '@phosphor/circle-dashed.svg';import { useContacts } from '@queries/contacts/contacts';@@ -31,10 +30,6 @@ export function createCrmCollectionFilters(useEntryState<string[]>('soup.stageFilter', { default: [] }),{ enabled: persist, name: 'soup-view-stage-filter-v2' });- const [viewMode, setViewMode] = useEntryState<'list' | 'board'>(- 'soup.viewMode',- { default: isTouchDevice() ? 'list' : 'board' }- );const userId = crm.userId;const currentUserId = userId;const teamQuery = crm.createTeamSource();@@ -232,8 +227,6 @@ export function createCrmCollectionFilters(setOwnerFilter,stageFilter,setStageFilter,- viewMode,- setViewMode,},};}diff --git a/apps/web/src/features/crm/pipeline-adapter.tsx b/apps/web/src/features/crm/pipeline-adapter.tsxindex 31a07a1c38..6f0780a359 100644--- a/apps/web/src/features/crm/pipeline-adapter.tsx+++ b/apps/web/src/features/crm/pipeline-adapter.tsx@@ -1,21 +1,43 @@+import { usePreference } from '@app/preferences/use-preference';import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';import { getPermissions } from '@core/component/SharePermissions';+import { toast } from '@core/component/Toast/Toast';import { ShareTrigger } from '@core/component/TopBar/ShareButton';import { useShareModal } from '@core/component/TopBar/shareModal';+import PlusIcon from '@phosphor/plus.svg';+import { queryReadyGate } from '@queries/gate';import { storageServiceClient } from '@service-storage/client';+import type { CardPosition } from '@service-storage/generated/schemas/cardPosition';+import type { DatabaseView } from '@service-storage/generated/schemas/databaseView';+import { useQueryClient } from '@tanstack/solid-query';import { Button } from '@ui';import { createSignal, onCleanup, onMount, Show, Suspense } from 'solid-js';+import { match } from 'ts-pattern';import {DatabaseMentionPicker,DatabaseMentionValue,DatabaseTextEditor,DatabaseTextValue,} from '../block-database/database-mentions';+import { DatabaseToolbar } from '../database/components/database-toolbar';import { DatabaseProvider, useDatabase } from '../database/context/database';-import type { DatabaseViewState } from '../database/core/view-state';+import type { CardMove } from '../database/core/board-moves';+import type { ViewChange } from '../database/core/view-state';+import { allRecordsView, boardLayout } from '../database/core/views';+import {+ type DatabaseOpFailure,+ databaseOpMessage,+} from '../database/core/write-failure';+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 type { Pipeline } from './core/pipeline';import { createPipelineApi } from './queries/pipeline-data';+import {+ createPipelineViews,+ type PipelineViews,+ usePipelineTableQuery,+} from './queries/pipeline-views';/** Pipelines supply their own identity and owner to the existing share dialog. */export function PipelineShare(props: {@@ -44,24 +66,78 @@ export function PipelineShare(props: {/** The CRM adapter supplies authorized data to the reusable records UI. */export function PipelineDatabaseEditor(props: { pipeline: Pipeline }) {return (- <Suspense- fallback={<div class="p-4 text-sm text-ink-muted">Loading pipeline…</div>}+ <div+ 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' }}>- <Show when={props.pipeline.id} keyed>- {(_id) => <PipelineRecords pipeline={props.pipeline} />}- </Show>- </Suspense>+ <Suspense+ fallback={+ <div class="p-4 text-sm text-ink-muted">Loading pipeline…</div>+ }+ >+ <Show when={props.pipeline.id} keyed>+ {(_id) => <PipelineRecords pipeline={props.pipeline} />}+ </Show>+ </Suspense>+ </div>);}+const viewFailure = (failure: DatabaseOpFailure) =>+ toast.failure(databaseOpMessage(failure, 'this view'));+function PipelineRecords(props: { pipeline: Pipeline }) {- const [view, setView] = createSignal<DatabaseViewState>({- query: { filter: null },- layout: { kind: 'table', columns: [] },- });- const api = createPipelineApi(storageServiceClient, props.pipeline);+ const deps = { storage: storageServiceClient, client: useQueryClient() };+ const tableQuery = usePipelineTableQuery(deps, props.pipeline);+ const views = createPipelineViews(deps, props.pipeline);+ const storedViews = () =>+ queryReadyGate(tableQuery) ? tableQuery.data.views : [];+ const [selectedViewId, setSelectedViewId] = usePreference<string | undefined>(+ `macro:pref:crm:pipeline-view:${props.pipeline.id}`,+ {+ default: undefined,+ }+ );+ const selectedView = () =>+ storedViews().find((view) => view.id === selectedViewId());+ // All records is this viewer's own, like a database's.+ const [allRecords, setAllRecords] = createSignal<DatabaseView>(+ allRecordsView({+ id: props.pipeline.tableId,+ database_id: props.pipeline.databaseId,+ })+ );+ const view = () => selectedView() ?? allRecords();+ const changeView = (change: ViewChange) => {+ const stored = selectedView();+ if (stored) void views.update(stored, change).mapErr(viewFailure);+ else setAllRecords((current) => ({ ...current, ...change }));+ };+ // No read of stored card places exists for pipelines; moves keep theirs here.+ const [positions, setPositions] = createSignal<+ Record<string, CardPosition[]>+ >({});+ const boardPositions: BoardPositions = {+ state: () => ({+ kind: 'ready',+ positions: positions()[view().id] ?? [],+ }),+ setPositions: (change) =>+ setPositions((current) => ({+ ...current,+ [view().id]: change(current[view().id] ?? []),+ })),+ // The server moves cards only on stored boards.+ get move() {+ const stored = selectedView();+ return stored+ ? (move: CardMove) => views.moveCard(stored, move)+ : undefined;+ },+ };const canEdit = () =>props.pipeline.grant === 'owner' || props.pipeline.grant === 'edit';+ const api = createPipelineApi(storageServiceClient, props.pipeline);return (<StaticMarkdownContext><DatabaseProvider@@ -72,11 +148,14 @@ function PipelineRecords(props: { pipeline: Pipeline }) {><PipelineRefresh /><DatabaseRecords+ contentClass="mx-4 mb-4 mt-1 rounded-xl border border-edge-muted"view={view()}- stored={false}- onViewChange={(change) =>- setView((previous) => ({ ...previous, ...change }))+ stored={!!selectedView()}+ onViewChange={changeView}+ onClearConstraints={() =>+ changeView({ query: { ...view().query, filter: null } })}+ boardPositions={boardPositions}renderTextEditor={(editor) => <DatabaseTextEditor {...editor} />}renderTextValue={(value) => <DatabaseTextValue value={value} />}renderMentionPicker={(picker) => (@@ -86,25 +165,17 @@ function PipelineRecords(props: { pipeline: Pipeline }) {<DatabaseMentionValue id={id} entityType={entityType} />)}renderToolbar={(actions) => (- <div class="flex items-center justify-between gap-3 border-b border-edge-muted px-4 py-2">- <span class="text-xs text-ink-muted">- {props.pipeline.recordType === 'company'- ? 'Companies'- : 'Contacts'}{' '}- · Customize columns from their headers- </span>- <Show when={canEdit()}>- <Button- size="sm"- disabled={actions.pending()}- onClick={() => void actions.createRecord()}- >- {props.pipeline.recordType === 'company'- ? 'Add company'- : 'Add contact'}- </Button>- </Show>- </div>+ <PipelineToolbar+ views={views}+ storedViews={storedViews()}+ view={view()}+ selectedViewId={selectedView()?.id}+ canEdit={canEdit()}+ recordType={props.pipeline.recordType}+ onSelectView={setSelectedViewId}+ onChangeView={changeView}+ actions={actions}+ />)}/></DatabaseProvider>@@ -112,6 +183,85 @@ function PipelineRecords(props: { pipeline: Pipeline }) {);}+/** The database toolbar over a pipeline's one table: its views and record controls. */+function PipelineToolbar(props: {+ views: PipelineViews;+ storedViews: DatabaseView[];+ view: DatabaseView;+ selectedViewId: string | undefined;+ canEdit: boolean;+ recordType: Pipeline['recordType'];+ onSelectView: (id: string | undefined) => void;+ onChangeView: (change: ViewChange) => void;+ actions: DatabaseRecordsActions;+}) {+ const database = useDatabase();+ const columns = () => database.data.rows.columns();+ // A column added with a board shows once the table is read again.+ const refreshColumns = () => void database.data.rows.refresh('refresh');+ return (+ <DatabaseToolbar+ columns={columns()}+ views={props.storedViews}+ view={props.view}+ selectedViewId={props.selectedViewId}+ canEdit={props.canEdit}+ onSelectView={props.onSelectView}+ onChangeView={props.onChangeView}+ onCreateView={(created) =>+ props.views.create(props.view, created, columns()).map((view) => {+ props.onSelectView(view.id);+ if (+ created.layout === 'board' &&+ created.groupBy.kind === 'new-status'+ )+ refreshColumns();+ })+ }+ onRenameView={(target, name) =>+ props.views.update(target, { name }).map(() => undefined)+ }+ onShowViewAs={(target, shown) =>+ match(shown)+ .with({ kind: 'table' }, () =>+ props.views+ .update(target, { layout: { kind: 'table', columns: [] } })+ .map(() => undefined)+ )+ .with({ kind: 'board', groupBy: { kind: 'column' } }, ({ groupBy }) =>+ props.views+ .update(target, {+ layout: boardLayout(groupBy.columnId, columns()),+ })+ .map(() => undefined)+ )+ .with({ kind: 'board', groupBy: { kind: 'new-status' } }, () =>+ props.views+ .showAsBoardWithStatusColumn(target, columns())+ .map(refreshColumns)+ )+ .exhaustive()+ }+ onDeleteView={(target) => {+ if (props.selectedViewId === target.id) props.onSelectView(undefined);+ return props.views.remove(target);+ }}+ actions={+ <Show when={props.canEdit}>+ <Button+ variant="outline"+ disabled={props.actions.pending()}+ onClick={() => void props.actions.createRecord()}+ >+ <PlusIcon class="size-4" />+ {props.recordType === 'company' ? 'Add company' : 'Add contact'}+ </Button>+ </Show>+ }+ />+ );+}+/** CRM owns the polling subscription; the shared source owns invalidation. */function PipelineRefresh() {const database = useDatabase();diff --git a/apps/web/src/features/crm/primitives/apply-view.ts b/apps/web/src/features/crm/primitives/apply-view.tsindex cb4cc53027..11c931a9af 100644--- a/apps/web/src/features/crm/primitives/apply-view.ts+++ b/apps/web/src/features/crm/primitives/apply-view.ts@@ -14,6 +14,5 @@ export function createApplyCrmView(commands: CrmViewCommands) {commands.setSort(config.sort?.length ? config.sort : ['updated_at']);commands.setStageFilter(config.stageFilter ?? []);commands.setOwnerFilter(config.ownerFilter ?? []);- commands.setViewMode(config.viewMode ?? commands.defaultMode());});}diff --git a/apps/web/src/features/crm/primitives/company-board.test.ts b/apps/web/src/features/crm/primitives/company-board.test.tsdeleted file mode 100644index def38847bc..0000000000--- a/apps/web/src/features/crm/primitives/company-board.test.ts+++ /dev/null@@ -1,73 +0,0 @@-import { createRoot, createSignal } from 'solid-js';-import { describe, expect, it, vi } from 'vitest';-import { createCompanyBoard } from './company-board';--describe('company board', () => {- it('retains a newer drag when an earlier request fails, then accepts remote updates', () => {- const [companies, setCompanies] = createSignal([- { id: 'acme', stage: 'lead' },- ]);- const failures: (() => void)[] = [];- const { board, dispose } = createRoot((dispose) => ({- dispose,- board: createCompanyBoard({- companies,- stages: () =>- ['lead', 'active', 'closed'].map((id) => ({ id, label: id })),- filterStages: () => [],- selectedStages: () => [],- noStageFilter: 'NO_STAGE',- resolveStage: (company) => company.stage,- canEdit: () => true,- canMoveClosed: () => false,- closedStages: () => new Set(['closed']),- saveStage: (_id, _stage, failed) => failures.push(failed),- }),- }));- board.moveToStage('acme', 'active');- board.moveToStage('acme', 'closed');- failures[0]();- expect(board.effectiveStage(companies()[0])).toBe('closed');- setCompanies([{ id: 'acme', stage: 'closed' }]);- setCompanies([{ id: 'acme', stage: 'lead' }]);- expect(board.effectiveStage(companies()[0])).toBe('lead');- expect(board.canDragFrom('closed')).toBe(false);- expect(board.canDragFrom('lead')).toBe(true);- dispose();- });- it('shows selected legacy and no-stage columns in pipeline order', () => {- const stages = [{ id: 'new', label: 'New' }];- const legacy = { id: 'legacy', label: 'Legacy' };- const saveStage = vi.fn();- const { board, dispose } = createRoot((dispose) => ({- dispose,- board: createCompanyBoard({- companies: () => [- { id: 'a', stage: 'legacy' },- { id: 'b', stage: undefined },- ],- stages: () => stages,- filterStages: () => [...stages, legacy],- selectedStages: () => ['NO_STAGE', 'legacy'],- noStageFilter: 'NO_STAGE',- resolveStage: (company) => company.stage,- canEdit: () => false,- canMoveClosed: () => true,- closedStages: () => new Set<string>(),- saveStage,- }),- }));- expect(- board- .columns()- .map((column) => [column.key, column.entities.map((e) => e.id)])- ).toEqual([- ['legacy', ['a']],- ['', ['b']],- ]);- board.moveToStage('a', 'legacy');- expect(saveStage).not.toHaveBeenCalled();- expect(board.canDragFrom('')).toBe(false);- dispose();- });-});diff --git a/apps/web/src/features/crm/primitives/company-board.ts b/apps/web/src/features/crm/primitives/company-board.tsdeleted file mode 100644index 9380487ca5..0000000000--- a/apps/web/src/features/crm/primitives/company-board.ts+++ /dev/null@@ -1,69 +0,0 @@-import { createEffect, createMemo, createSignal } from 'solid-js';-import type { CompanyBoardSource } from '../context/company-board-source';-import {- boardStageColumns,- canDragCompanyStage,- NO_STAGE_KEY,-} from '../core/stages';--/** Keeps board moves visible during search and protects newer moves from stale failures. */-export function createCompanyBoard<T extends { id: string }>(- source: CompanyBoardSource<T>-) {- const [overrides, setOverrides] = createSignal<ReadonlyMap<string, string>>(- new Map()- );- const clearOverride = (id: string, stage: string) =>- setOverrides((previous) => {- if (previous.get(id) !== stage) return previous;- const next = new Map(previous);- next.delete(id);- return next;- });- const effectiveStage = (company: T) =>- overrides().get(company.id) ?? source.resolveStage(company) ?? NO_STAGE_KEY;- const stageColumns = createMemo(() =>- boardStageColumns(- source.stages(),- source.filterStages(),- source.selectedStages(),- source.noStageFilter- )- );- // Acknowledged server/cache values retire the optimistic overlay.- createEffect(() => {- const pending = overrides();- if (!pending.size) return;- for (const company of source.companies()) {- const stage = source.resolveStage(company) ?? NO_STAGE_KEY;- if (pending.get(company.id) === stage) clearOverride(company.id, stage);- }- });- const columns = createMemo(() => {- const buckets = new Map<string, T[]>(- stageColumns().map((column) => [column.key, []])- );- for (const company of source.companies()) {- const key = effectiveStage(company);- (buckets.get(buckets.has(key) ? key : NO_STAGE_KEY) ?? []).push(company);- }- return stageColumns().map((column) => ({- ...column,- entities: buckets.get(column.key) ?? [],- }));- });- const canDragFrom = (stage: string) =>- canDragCompanyStage(- stage,- source.canEdit(),- source.closedStages(),- source.canMoveClosed()- );- const moveToStage = (id: string, stage: string) => {- const company = source.companies().find((company) => company.id === id);- if (!company || effectiveStage(company) === stage) return;- setOverrides((previous) => new Map(previous).set(id, stage));- source.saveStage(id, stage, () => clearOverride(id, stage));- };- return { columns, stageColumns, effectiveStage, canDragFrom, moveToStage };-}diff --git a/apps/web/src/features/crm/primitives/default-view.test.ts b/apps/web/src/features/crm/primitives/default-view.test.tsindex e5ae600187..238633a541 100644--- a/apps/web/src/features/crm/primitives/default-view.test.ts+++ b/apps/web/src/features/crm/primitives/default-view.test.ts@@ -5,34 +5,10 @@ import { createDefaultCrmView } from './default-view';const config: CrmViewConfig = {kind: 'crm',- viewMode: 'board',searchText: 'Acme',};describe('default CRM view', () => {- it.each([true, false])(- 'retains filters and uses the correct layout on mobile=%s',- (mobile) => {- const apply = vi.fn();- const dispose = createRoot((dispose) => {- createDefaultCrmView({- personalLoading: () => false,- teamLoading: () => false,- personal: () => config,- team: () => undefined,- mobile: () => mobile,- apply,- });- return dispose;- });- expect(apply).toHaveBeenCalledWith({- ...config,- viewMode: mobile ? 'list' : 'board',- });- expect(config.viewMode).toBe('board');- dispose();- }- );it('waits for both sources, prefers personal, and never reapplies on refetch', () => {const apply = vi.fn();const [loading, setLoading] = createSignal(true);@@ -43,7 +19,6 @@ describe('default CRM view', () => {teamLoading: () => false,personal,team: () => ({ kind: 'crm', searchText: 'team' }),- mobile: () => false,apply,});return dispose;@@ -64,7 +39,6 @@ describe('default CRM view', () => {teamLoading: () => false,personal: () => undefined,team: () => config,- mobile: () => false,apply,});return dispose;diff --git a/apps/web/src/features/crm/primitives/default-view.ts b/apps/web/src/features/crm/primitives/default-view.tsindex 3dbb969ced..7b3152ad8f 100644--- a/apps/web/src/features/crm/primitives/default-view.ts+++ b/apps/web/src/features/crm/primitives/default-view.ts@@ -6,7 +6,6 @@ export function createDefaultCrmView(input: {teamLoading: Accessor<boolean>;personal: Accessor<CrmViewConfig | undefined>;team: Accessor<CrmViewConfig | undefined>;- mobile: Accessor<boolean>;apply(config: CrmViewConfig): void;}) {let applied = false;@@ -15,7 +14,6 @@ export function createDefaultCrmView(input: {if (applied || input.personalLoading() || input.teamLoading()) return;applied = true;const config = input.personal() ?? input.team();- if (config)- input.apply(input.mobile() ? { ...config, viewMode: 'list' } : config);+ if (config) input.apply(config);});}diff --git a/apps/web/src/features/crm/primitives/team-config.ts b/apps/web/src/features/crm/primitives/team-config.tsindex eae1965f71..a16f44db03 100644--- a/apps/web/src/features/crm/primitives/team-config.ts+++ b/apps/web/src/features/crm/primitives/team-config.ts@@ -51,17 +51,6 @@ export function createCrmPermissions(};}-/**- * True once the current-team query resolves to no team (null) or a team- * with CRM disabled — the companies views swap in an explanatory empty- * state and keep bottom chrome like the AI bar. Stays false while the- * query loads so enabled teams don't flash the empty state.- */-export function createCrmUnavailable(teamQuery: TeamSource): Accessor<boolean> {- return () =>- teamQuery.data === null || teamQuery.data?.team.crm_enabled === false;-}-/*** The set of stage option ids considered "closed" — explicit config when* present, else a label heuristic over the active stages.diff --git a/apps/web/src/features/crm/queries/contact-suggestions.ts b/apps/web/src/features/crm/queries/contact-suggestions.tsindex 1fbd405fc9..895e3d4aae 100644--- a/apps/web/src/features/crm/queries/contact-suggestions.ts+++ b/apps/web/src/features/crm/queries/contact-suggestions.ts@@ -7,7 +7,7 @@ import { type Accessor, createMemo } from 'solid-js';import type { CrmRecordDependencies } from './dependencies';import { toCrmContactEntity } from './graphql';-/** Cursor-paged GraphQL source shared by suggestions and the People directory. */+/** Cursor-paged GraphQL source for contact suggestions. */export function useCrmContactsQuery(deps: Pick<CrmRecordDependencies, 'client'>,enabled: Accessor<boolean>,diff --git a/apps/web/src/features/crm/queries/people.ts b/apps/web/src/features/crm/queries/people.tsdeleted file mode 100644index 101b63e093..0000000000--- a/apps/web/src/features/crm/queries/people.ts+++ /dev/null@@ -1,39 +0,0 @@-import { queryReadyGate } from '@queries/gate';-import { type Accessor, createEffect } from 'solid-js';-import { type CrmPerson, deduplicatePeople } from '../core/people';-import { useCrmContactsQuery } from './contact-suggestions';-import type { CrmQueryDependencies } from './dependencies';--/** Progressively loads one deduplicated directory across all accessible teams. */-export function useCrmPeopleQuery(- deps: CrmQueryDependencies,- enabled: Accessor<boolean>-) {- const query = useCrmContactsQuery(deps, enabled);- // Synchronize the paged network source while the directory is mounted.- createEffect(() => {- if (enabled() && query.hasNextPage && !query.isFetching && !query.isError) {- void query.fetchNextPage();- }- });- const people = (): CrmPerson[] =>- queryReadyGate(query)- ? deduplicatePeople(- query.data.pages.flatMap((page) =>- page.contacts.map((contact) => ({- id: contact.id,- companyId: contact.companyId,- companyName: contact.companyName,- email: contact.email,- name: contact.crmContactName,- hidden: contact.hidden,- firstInteraction: contact.firstInteraction,- lastInteraction: contact.lastInteraction,- createdAt: contact.createdAt,- updatedAt: contact.updatedAt,- }))- )- )- : [];- return { query, people };-}diff --git a/apps/web/src/features/crm/queries/pipeline-views.test.ts b/apps/web/src/features/crm/queries/pipeline-views.test.tsnew file mode 100644index 0000000000..cf363732c2--- /dev/null+++ b/apps/web/src/features/crm/queries/pipeline-views.test.ts@@ -0,0 +1,138 @@+import type { DatabaseView } from '@service-storage/generated/schemas/databaseView';+import type { TableDetail } from '@service-storage/generated/schemas/tableDetail';+import { QueryClient } from '@tanstack/solid-query';+import { errAsync, okAsync } from 'neverthrow';+import { afterEach, expect, it, vi } from 'vitest';+import { allRecordsView } from '../../database/core/views';+import type { Pipeline } from '../core/pipeline';+import type { CrmRecordDependencies } from './dependencies';+import { crmKeys } from './keys';+import { createPipelineViews } from './pipeline-views';++const pipeline: Pipeline = {+ id: 'pipeline',+ databaseId: 'storage-only',+ tableId: 'records',+ primaryColumnId: 'company',+ name: 'Sales',+ userId: 'macro|[email protected]',+ teamId: 'team',+ recordType: 'company',+ sharing: 'team',+ grant: 'owner',+ createdAt: '2026-10-01T00:00:00Z',+ trashedAt: null,+};+const allRecords = allRecordsView({+ id: 'records',+ database_id: 'storage-only',+});+const stored = (overrides: Partial<DatabaseView> = {}): DatabaseView => ({+ ...allRecords,+ id: 'view',+ name: 'Table view',+ position: 'a0',+ ...overrides,+});+const clients: QueryClient[] = [];+afterEach(() => {+ for (const client of clients.splice(0)) client.clear();+});++function setup(views: DatabaseView[] = []) {+ const client = new QueryClient();+ clients.push(client);+ client.setQueryData(crmKeys.pipelineTable(pipeline.id).queryKey, {+ views,+ } as unknown as TableDetail);+ const applyCrmPipelineOps = vi.fn();+ const deps = {+ client,+ storage: { applyCrmPipelineOps },+ } as unknown as CrmRecordDependencies;+ const cached = () =>+ client.getQueryData<TableDetail>(+ crmKeys.pipelineTable(pipeline.id).queryKey+ )?.views;+ return {+ client,+ applyCrmPipelineOps,+ cached,+ views: createPipelineViews(deps, pipeline),+ };+}++const answered = (view: DatabaseView, change: 'created' | 'updated') =>+ okAsync({+ results: [+ {+ kind: 'view',+ table: 'records',+ view: view.id,+ change: { kind: change, view },+ },+ ],+ changes: [],+ });++it('creates a view on the pipeline table through the pipeline endpoint', async () => {+ const { views, applyCrmPipelineOps, cached } = setup();+ const created = stored();+ applyCrmPipelineOps.mockReturnValue(answered(created, 'created'));+ const result = await views.create(+ allRecords,+ { name: 'Table view', layout: 'table' },+ []+ );+ expect(result.isOk()).toBe(true);+ expect(applyCrmPipelineOps).toHaveBeenCalledWith('pipeline', {+ ops: [+ {+ kind: 'view',+ table: 'records',+ view: expect.any(String),+ change: {+ kind: 'create',+ view: {+ name: 'Table view',+ query: allRecords.query,+ layout: { kind: 'table', columns: [] },+ },+ },+ },+ ],+ });+ expect(cached()).toEqual([created]);+});++it('adds a Status column and its board in one batch when nothing can group', async () => {+ const { views, applyCrmPipelineOps } = setup();+ applyCrmPipelineOps.mockReturnValue(answered(stored(), 'created'));+ await views.create(+ allRecords,+ { name: 'Board view', layout: 'board', groupBy: { kind: 'new-status' } },+ []+ );+ const [, { ops }] = applyCrmPipelineOps.mock.calls[0];+ expect(ops.map((op: { kind: string }) => op.kind)).toEqual([+ 'column',+ 'view',+ ]);+});++it('shows a change ahead of the answer and reloads what is stored when refused', async () => {+ const view = stored();+ const { client, views, applyCrmPipelineOps, cached } = setup([view]);+ const invalidate = vi.spyOn(client, 'invalidateQueries');+ applyCrmPipelineOps.mockImplementation(() => {+ expect(cached()?.[0]?.name).toBe('Renamed');+ return errAsync([+ { code: 'INVALID_OP', message: 'Refused', refusal: null },+ ]);+ });+ const result = await views.update(view, { name: 'Renamed' });+ expect(result.isErr()).toBe(true);+ expect(invalidate).toHaveBeenCalledWith({+ queryKey: crmKeys.pipelineTable(pipeline.id).queryKey,+ });+});diff --git a/apps/web/src/features/crm/queries/pipeline-views.ts b/apps/web/src/features/crm/queries/pipeline-views.tsnew file mode 100644index 0000000000..ea098e9145--- /dev/null+++ b/apps/web/src/features/crm/queries/pipeline-views.ts@@ -0,0 +1,219 @@+import type { DatabaseOp } from '@core/database-sql/generated/types';+import { throwOnErr } from '@core/util/result';+import type { DatabaseView } from '@service-storage/generated/schemas/databaseView';+import type { OpResult } from '@service-storage/generated/schemas/opResult';+import type { TableDetail } from '@service-storage/generated/schemas/tableDetail';+import { useQuery } from '@tanstack/solid-query';+import { errAsync, okAsync, ResultAsync } from 'neverthrow';+import { v7 as uuidv7 } from 'uuid';+import {+ boardWithStatusColumn,+ newBoardWithStatusColumn,+} from '../../database/core/board-grouping';+import type { CardMove } from '../../database/core/board-moves';+import type { DatabaseViewColumn } from '../../database/core/database-view';+import { createKeyedSerializer } from '../../database/core/keyed-serializer';+import type { NewView } from '../../database/core/view-creation';+import type { CardMoved, ViewChange } from '../../database/core/view-state';+import { boardLayout } from '../../database/core/views';+import type { DatabaseOpFailure } from '../../database/core/write-failure';+import type { Pipeline } from '../core/pipeline';+import type { CrmRecordDependencies } from './dependencies';+import { crmKeys } from './keys';++type ViewOpResult = Extract<OpResult, { kind: 'view' }>;++/** The pipeline's single table, whose stored views the toolbar lists. */+export function usePipelineTableQuery(+ deps: CrmRecordDependencies,+ pipeline: Pipeline+) {+ return useQuery(+ () => ({+ queryKey: crmKeys.pipelineTable(pipeline.id).queryKey,+ queryFn: () =>+ throwOnErr(() => deps.storage.getCrmPipelineTable(pipeline.id)),+ }),+ () => deps.client+ );+}++/**+ * Stored views of a pipeline's table, written as database view ops through the+ * pipeline's own endpoint. Its storage database is not the viewer's to address.+ */+export function createPipelineViews(+ deps: CrmRecordDependencies,+ pipeline: Pipeline+) {+ const key = crmKeys.pipelineTable(pipeline.id).queryKey;+ // Each view's writes, and the view list's, reach the server in order.+ const writes = createKeyedSerializer();+ const inOrder = <Value>(+ order: string,+ write: () => ResultAsync<Value, DatabaseOpFailure>+ ) => new ResultAsync(writes.run(order, async () => await write()));+ const patchViews = (change: (views: DatabaseView[]) => DatabaseView[]) =>+ deps.client.setQueryData<TableDetail>(+ key,+ (detail) => detail && { ...detail, views: change(detail.views) }+ );+ const upsert = (view: DatabaseView) =>+ patchViews((views) =>+ views.some((existing) => existing.id === view.id)+ ? views.map((existing) => (existing.id === view.id ? view : existing))+ : [...views, view]+ );+ const apply = (ops: DatabaseOp[]) =>+ deps.storage+ .applyCrmPipelineOps(pipeline.id, { ops })+ .map((response) => response.results)+ .mapErr(([error]): DatabaseOpFailure => ({ kind: 'ops', error }))+ .orElse((failure) => {+ // A refusal shows what is stored instead of what was patched in.+ void deps.client.invalidateQueries({ queryKey: key });+ return errAsync(failure);+ });+ const lastView = (results: OpResult[]) => {+ const result = results.at(-1) as ViewOpResult | undefined;+ return result?.kind === 'view' && 'view' in result.change+ ? okAsync(result.change.view)+ : errAsync<DatabaseView, DatabaseOpFailure>({+ kind: 'unexpected-result',+ });+ };+ const listKey = `table:${pipeline.tableId}`;+ const status = () => ({+ column: uuidv7(),+ options: [uuidv7(), uuidv7(), uuidv7()] as [string, string, string],+ });++ return {+ /** Add a view that starts from `current`; a board without a grouping column adds a Status column. */+ create(+ current: DatabaseView,+ input: NewView,+ columns: readonly DatabaseViewColumn[]+ ) {+ const viewId = uuidv7();+ const created = (layout: DatabaseView['layout']): DatabaseOp[] => [+ {+ kind: 'view',+ table: pipeline.tableId,+ view: viewId,+ change: {+ kind: 'create',+ view: { name: input.name, query: current.query, layout },+ },+ },+ ];+ let ops: DatabaseOp[];+ if (input.layout === 'table')+ ops = created(+ current.layout.kind === 'table'+ ? current.layout+ : { kind: 'table', columns: [] }+ );+ else if (input.groupBy.kind === 'column')+ ops = created(boardLayout(input.groupBy.columnId, columns));+ else+ ops = newBoardWithStatusColumn({+ tableId: pipeline.tableId,+ viewId,+ name: input.name,+ query: current.query,+ columns,+ status: status(),+ });+ return inOrder(listKey, () => apply(ops).andThen(lastView)).map(+ (view) => {+ upsert(view);+ return view;+ }+ );+ },+ update(view: DatabaseView, change: ViewChange) {+ patchViews((views) =>+ views.map((existing) =>+ existing.id === view.id ? { ...existing, ...change } : existing+ )+ );+ return inOrder(view.id, () =>+ apply([+ {+ kind: 'view',+ table: view.tableId,+ view: view.id,+ change: { kind: 'update', ...change },+ },+ ]).andThen(lastView)+ ).map(upsert);+ },+ /** Lay a view out as a board grouped by a new Status column, in one batch. */+ showAsBoardWithStatusColumn(+ view: DatabaseView,+ columns: readonly DatabaseViewColumn[]+ ) {+ return inOrder(view.id, () =>+ apply(boardWithStatusColumn({ view, columns, status: status() }))+ .andThen(lastView)+ .map((stored) => {+ upsert(stored);+ // The new column arrives with the table read.+ void deps.client.invalidateQueries({ queryKey: key });+ })+ );+ },+ remove(view: DatabaseView) {+ patchViews((views) =>+ views.filter((existing) => existing.id !== view.id)+ );+ return inOrder(view.id, () =>+ apply([+ {+ kind: 'view',+ table: view.tableId,+ view: view.id,+ change: { kind: 'delete' },+ },+ ])+ ).map(() => undefined);+ },+ /** Move a stored board's card, which also sets its row's grouping cell. */+ moveCard(+ view: DatabaseView,+ move: CardMove+ ): ResultAsync<CardMoved, DatabaseOpFailure> {+ return inOrder(view.id, () =>+ apply([+ {+ kind: 'view',+ table: view.tableId,+ view: view.id,+ change: {+ kind: 'move_card',+ row: move.row,+ lane: move.lane,+ before: move.before,+ after: move.after,+ },+ },+ ])+ ).andThen((results) => {+ const result = results.at(-1) as ViewOpResult | undefined;+ return result?.kind === 'view' &&+ result.change.kind === 'card_moved' &&+ result.tableVersion != null+ ? okAsync({+ positions: result.change.positions,+ tableVersion: result.tableVersion,+ })+ : errAsync<CardMoved, DatabaseOpFailure>({+ kind: 'unexpected-result',+ });+ });+ },+ };+}++export type PipelineViews = ReturnType<typeof createPipelineViews>;diff --git a/apps/web/src/features/crm/queries/saved-view-codec.test.ts b/apps/web/src/features/crm/queries/saved-view-codec.test.tsindex e5faee8438..fcea097ea3 100644--- a/apps/web/src/features/crm/queries/saved-view-codec.test.ts+++ b/apps/web/src/features/crm/queries/saved-view-codec.test.ts@@ -9,7 +9,6 @@ describe('CRM saved state boundary', () => {searchText: 'Zoë 日本',groupBy: null,stageFilter: ['qualified'],- viewMode: 'board' as const,};expect(decodeCrmViewParam(encodeCrmViewParam(view))).toEqual(view);});@@ -17,6 +16,12 @@ describe('CRM saved state boundary', () => {expect(decodeCrmViewParam(btoa(JSON.stringify({ kind: 'crm', future: true })))).toEqual({ kind: 'crm', future: true });+ // Links from before Customers became list-only still open.+ expect(+ decodeCrmViewParam(+ btoa(JSON.stringify({ kind: 'crm', viewMode: 'board' }))+ )+ ).toEqual({ kind: 'crm', viewMode: 'board' });});it.each([{ stageFilter: 42 },@@ -24,7 +29,6 @@ describe('CRM saved state boundary', () => {{ sort: 'updated_at' },{ clientFilters: [] },{ clientFilters: { and: 'company-stage' } },- { viewMode: 'grid' },{ searchText: { text: 'acme' } },])('rejects malformed known state %j', (invalid) => {expect(diff --git a/apps/web/src/features/crm/tour.ts b/apps/web/src/features/crm/tour.tsindex ac40ed51d9..532387e617 100644--- a/apps/web/src/features/crm/tour.ts+++ b/apps/web/src/features/crm/tour.ts@@ -3,8 +3,8 @@ import { defineViewTour } from '@app/features/tours/core/view-tour';import { defineTourTargets } from '@ui/components/Tour';export const COMPANIES_TOUR = defineTourTargets('companies', [- 'layout',- 'views',+ 'records',+ 'create',]);export const companiesTour = defineViewTour({@@ -22,12 +22,12 @@ export const companiesTour = defineViewTour({},steps: [{- target: COMPANIES_TOUR.layout,+ target: COMPANIES_TOUR.records,entry: VIEW_SHELL_TOUR.sidebarToggle,entryLabel: 'Show the Customers sidebar to continue',- title: 'Your pipeline, as a board or list',+ title: 'Companies and people',description:- 'Switch to Board to see companies by stage, or List to scan their details in rows. Both show the same customer relationships—choose the view that fits your work.',+ 'Companies lists every customer your team works with. People lists their contacts across your teams.',},{target: VIEW_SHELL_TOUR.main,@@ -36,12 +36,12 @@ export const companiesTour = defineViewTour({'Open a company to view its contacts and details. Update properties as the relationship develops.',},{- target: COMPANIES_TOUR.views,+ target: COMPANIES_TOUR.create,entry: VIEW_SHELL_TOUR.sidebarToggle,entryLabel: 'Show the Customers sidebar to continue',- title: 'Make your pipeline useful',+ title: 'Add your own records',description:- 'Use filters and saved views to focus on the right companies. Switch to the board to see work by stage.',+ 'Use New to add a company, a contact, or a pipeline. Filters and saved views in the toolbar focus the list on the companies that matter.',},],});diff --git a/apps/web/src/features/crm/views/apply-view.ts b/apps/web/src/features/crm/views/apply-view.tsindex f043e1e8c1..8d0e2c9b15 100644--- a/apps/web/src/features/crm/views/apply-view.ts+++ b/apps/web/src/features/crm/views/apply-view.ts@@ -1,4 +1,3 @@-import { isTouchDevice } from '@core/mobile/isTouchDevice';import type { Query } from '../../next-soup/filters/filter-store';import { useCrmWorkspace } from '../context/workspace-context';import { createApplyCrmView } from '../primitives/apply-view';@@ -23,7 +22,5 @@ export function useApplyCrmView() {if (ids.length > 0 !== view.soup.predicates.isActive('company-owner'))view.soup.predicates.toggle({ and: ['company-owner'] });},- setViewMode: view.setViewMode,- defaultMode: () => (isTouchDevice() ? 'list' : 'board'),});}diff --git a/apps/web/src/features/crm/views/companies.tsx b/apps/web/src/features/crm/views/companies.tsxindex dad7dc10bd..21438ee817 100644--- a/apps/web/src/features/crm/views/companies.tsx+++ b/apps/web/src/features/crm/views/companies.tsx@@ -1,25 +1,21 @@-import { PillTabs } from '@components/app/mobile/PillTabs';import { SplitHeaderLeft } from '@components/app/split-layout/components/SplitHeader';-import { ENABLE_UNIFIED_LIST_AI_INPUT } from '@core/constant/featureFlags';import { isTouchDevice } from '@core/mobile/isTouchDevice';import { Show, Suspense } from 'solid-js';-import { SoupChatInput } from '../../chat/SoupChatInput';import { MobileFilterDrawer } from '../../next-soup/soup-view/filters-bar/mobile-filter-drawer';import { SoupFiltersBar } from '../../next-soup/soup-view/filters-bar/soup-filters-bar';import { SoupViewList } from '../../next-soup/soup-view/soup-view';-import { MaybeSoupEntityActionDrawerManager } from '../../soup';import { useCrmWorkspace } from '../context/workspace-context';-import { CompanyKanban } from './company-board';import { CompanyGroupHeader } from './company-group-header';import { ResponsiveCompanyListHeader } from './company-list-header';import { CompanyListEntity } from './company-row';+import { ResponsiveContactListHeader } from './contact-list-header';+import { ContactListEntity } from './contact-row';import { CrmWorkspaceView } from './crm-workspace';import { CrmEmptyState } from './empty-state';-import { useCrmUnavailable } from './use-crm';export function Companies() {const view = useCrmWorkspace();- const unavailable = useCrmUnavailable();+ const people = () => view.activeTab() === 'people';return (<CrmWorkspaceView>{(options) => (@@ -27,29 +23,15 @@ export function Companies() {class="size-full flex flex-col @container"data-list-view="companies">- <Show when={isTouchDevice()}>+ {/* People keeps the workspace title row and search on touch. */}+ <Show when={isTouchDevice() && !people()}><div class="flex flex-col w-full"><SplitHeaderLeft><div class="h-full flex gap-3 @max-[380px]/split-header:gap-2 items-center w-full flex-1 min-w-0">- <PillTabs- scrollable- class="-ml-(--mobile-chrome-gutter) w-[100cqw] max-w-none flex-none"- contentClass="px-(--mobile-chrome-gutter)"- leading={- <>- {options.mobileHeaderLeading}- <MobileFilterDrawer />- </>- }- items={[- { value: 'board', label: 'Board' },- { value: 'list', label: 'List' },- ]}- value={view.viewMode()}- onChange={(value) =>- view.setViewMode(value as 'list' | 'board')- }- />+ <div class="pointer-events-auto flex shrink-0 items-center gap-2">+ {options.mobileHeaderLeading}+ <MobileFilterDrawer />+ </div></div></SplitHeaderLeft></div>@@ -58,42 +40,34 @@ export function Companies() {<div class="relative grow min-h-1 flex max-sm:flex-col flex-row size-full"><Suspense><Show- when={view.viewMode() !== 'board'}+ when={people()}fallback={- <MaybeSoupEntityActionDrawerManager>- <CompanyKanban onOpenEntity={options.onOpenEntity} />- </MaybeSoupEntityActionDrawerManager>+ <SoupViewList+ emptyContent={<CrmEmptyState />}+ onOpenEntity={options.onOpenEntity}+ rowEntry={{ component: CompanyListEntity, family: 'row' }}+ groupHeader={CompanyGroupHeader}+ listHeader={+ <Show when={!isTouchDevice()}>+ <ResponsiveCompanyListHeader class="shrink-0" />+ </Show>+ }+ />}><SoupViewListemptyContent={<CrmEmptyState />}onOpenEntity={options.onOpenEntity}- rowEntry={{ component: CompanyListEntity, family: 'row' }}- groupHeader={CompanyGroupHeader}+ rowEntry={{ component: ContactListEntity, family: 'row' }}listHeader={<Show when={!isTouchDevice()}>- <ResponsiveCompanyListHeader class="shrink-0" />+ <ResponsiveContactListHeader class="shrink-0" /></Show>}/></Show></Suspense></div>- <Suspense>- <Show- when={- !isTouchDevice() &&- ENABLE_UNIFIED_LIST_AI_INPUT &&- (view.viewMode() !== 'board' || unavailable())- }- >- <div class="absolute bottom-0 inset-x-px pb-2.5 px-2 flex justify-center pointer-events-none">- <div class="pointer-events-auto w-full min-w-0 max-w-3xl">- <SoupChatInput />- </div>- </div>- </Show>- </Suspense></div>)}</CrmWorkspaceView>diff --git a/apps/web/src/features/crm/views/company-board.tsx b/apps/web/src/features/crm/views/company-board.tsxdeleted file mode 100644index 79e4f9ebdd..0000000000--- a/apps/web/src/features/crm/views/company-board.tsx+++ /dev/null@@ -1,352 +0,0 @@-import { resolveEntityActionViewContext } from '@app/features/next-soup/actions';-import { NO_STAGE } from '@app/features/next-soup/filters/configs/';-import { EmptyState } from '@app/features/next-soup/soup-view/empty-states';-import { useFilterRefinements } from '@app/features/next-soup/soup-view/filters-bar/use-filter-refinements';-import { SoupEntityContextMenu } from '@app/features/soup';-import { DEBUG_SETTING_KEYS, useDebugSetting } from '@app/lib/debugSettings';-import { CustomScrollbar } from '@core/component/CustomScrollbar';-import { UserIcon } from '@core/component/UserIcon';-import {- Entity,- type EntityData,- formatTimestamp,- getCompanyOwnerId,- isCrmCompanyEntity,-} from '@entity';-import CircleDashed from '@phosphor/circle-dashed.svg';-import { createElementSize } from '@solid-primitives/resize-observer';-import { cn, Layer } from '@ui';-import { createMemo, createSignal, For, Show } from 'solid-js';-import { CrmStageIcon } from '../components/stage-icon';-import { useCrmContext } from '../context/crm-context';-import { useCrmWorkspace } from '../context/workspace-context';-import { createCompanyBoard } from '../primitives/company-board';-import { CrmEmptyState } from './empty-state';-import {- useBulkSaveEntityPropertiesMutation,- useClosedStageIds,- useCrmPermissions,- useCrmUnavailable,- useDealStages,-} from './use-crm';--/** Column key for companies without a Stage value. */-const NO_STAGE_KEY = '';--/** Minimum column width the snapping layout will shrink to. */-const MIN_COLUMN_WIDTH = 224;-/** gap-3 between columns. */-const COLUMN_GAP = 12;-/** p-3 on each side of the column row. */-const BOARD_PADDING_X = 24;--/**- * Kanban board for the Customers view: one column per active deal stage- * (team-customized set when present, else the seeded system stages) plus- * "No stage", fed by the same filtered soup entities as the list. Cards- * drag between columns to update the company's Stage property (team- * admins/owners only, matching CRM edit access; moving deals out of a- * closed stage additionally requires the move-closed-deals permission).- *- */-export function CompanyKanban(props: {- onOpenEntity?: (entity: EntityData) => boolean;-}) {- const { source, soup, stageFilter, searchText, activeTab, host } =- useCrmWorkspace();- const entityActionViewContext = () =>- resolveEntityActionViewContext({- activeListView: 'companies',- activeTab: activeTab(),- });-- const { stages, filterStages, stageProperty, resolveStage } = useDealStages();- const { canEditCrm, canMoveClosedDeals } = useCrmPermissions();- const closedStageIds = useClosedStageIds(stages);-- // Mirror the list view's no-team / CRM-disabled empty states.- const crmUnavailable = useCrmUnavailable();- const { hasActiveRefinements, hasHiddenItems, resetToTabDefaults } =- useFilterRefinements();-- // Debug: force the board to render its empty state regardless of content.- const forceEmptyState = useDebugSetting(- DEBUG_SETTING_KEYS.FORCE_EMPTY_STATES- );-- // Search results don't carry properties, which would strand every match- // in "No stage" (and skip closed-stage drag gating). Backfill from the- // normalized soup cache, which still holds the full rows the search is- // narrowing.- const companies = createMemo(() =>- source.data().filter(isCrmCompanyEntity).map(useCrmContext().hydrateCompany)- );-- // Mirror the list view's empty states: beyond CRM-unavailable, an empty- // board ("No customers yet" / no search or filter matches) shows the- // panel instead of a row of empty columns. Fetches keep the board- // mounted so the empty state doesn't flash during refetches.- const showEmptyState = () =>- crmUnavailable() ||- (!source.isFetching() && companies().length === 0) ||- forceEmptyState();-- const saveMutation = useBulkSaveEntityPropertiesMutation();- const { columns, stageColumns, canDragFrom, moveToStage } =- createCompanyBoard<import('@entity').CrmCompanyEntity>({- companies,- stages,- filterStages,- selectedStages: stageFilter,- noStageFilter: NO_STAGE,- resolveStage,- canEdit: canEditCrm,- canMoveClosed: canMoveClosedDeals,- closedStages: closedStageIds,- saveStage: (entityId, stageKey, onError) =>- void saveMutation- .mutateAsync({- properties: [- {- entityId,- entityType: 'COMPANY',- property: stageProperty(),- apiValues: {- valueType: 'SELECT_STRING',- values: stageKey === NO_STAGE_KEY ? null : [stageKey],- },- },- ],- })- .catch(onError),- });-- const [draggedId, setDraggedId] = createSignal<string>();- const [dropTarget, setDropTarget] = createSignal<string>();- const [scrollRef, setScrollRef] = createSignal<HTMLDivElement>();-- // Columns snap to a whole-column layout: as many columns as fit at the- // minimum width, each widened to exactly fill the viewport. Growing the- // board snaps in the next column once there's room; the rest scroll.- const boardSize = createElementSize(scrollRef);- const columnWidth = createMemo(() => {- const width = boardSize.width;- const count = stageColumns().length;- if (!width || count === 0) return undefined;- const usable = width - BOARD_PADDING_X;- const fit = Math.max(- 1,- Math.min(- count,- Math.floor((usable + COLUMN_GAP) / (MIN_COLUMN_WIDTH + COLUMN_GAP))- )- );- // Floored so rounding can't overflow the viewport by a pixel and- // phantom-trigger the horizontal scrollbar.- return Math.floor((usable - (fit - 1) * COLUMN_GAP) / fit);- });-- const openCompany = (entity: EntityData, event: MouseEvent) => {- if (- !event.metaKey &&- !event.ctrlKey &&- !event.shiftKey &&- !event.altKey &&- props.onOpenEntity?.(entity)- )- return;- soup.focus.set(entity.id);-- host.openCompany(entity, event.shiftKey);- };-- return (- <Show- when={!showEmptyState()}- fallback={- <EmptyState- content={<CrmEmptyState />}- search={!!searchText()}- hasRefinementsFromBase={hasActiveRefinements()}- hasHiddenItems={hasHiddenItems()}- onClearFilters={resetToTabDefaults}- />- }- >- {/* Relative wrapper anchors the horizontal scrollbar to the board's- bottom edge when the split is too narrow for all columns. */}- <div class="relative size-full min-w-0">- <div- ref={setScrollRef}- class="size-full overflow-x-auto overflow-y-hidden scrollbar-hidden"- >- <div class="flex h-full gap-3 p-3">- <For each={columns()}>- {(column, columnIndex) => (- <div- class={cn(- // Fallback sizing until the board is measured; after- // that the snapping columnWidth() takes over.- 'flex h-full min-w-56 flex-1 flex-col rounded-xl bg-surface-2/30 transition-colors',- dropTarget() === column.key && draggedId() && 'bg-accent/10'- )}- style={- columnWidth() !== undefined- ? { width: `${columnWidth()}px`, flex: 'none' }- : undefined- }- onDragOver={(e) => {- if (!draggedId()) return;- e.preventDefault();- setDropTarget(column.key);- }}- onDragLeave={(e) => {- if (- e.relatedTarget instanceof Node &&- e.currentTarget.contains(e.relatedTarget)- ) {- return;- }- if (dropTarget() === column.key) setDropTarget(undefined);- }}- onDrop={(e) => {- e.preventDefault();- const id =- draggedId() ?? e.dataTransfer?.getData('text/plain');- setDropTarget(undefined);- setDraggedId(undefined);- if (id) moveToStage(id, column.key);- }}- >- <div class="flex items-center gap-2 px-3 py-2.5 text-xs font-semibold text-ink-muted">- <Show- when={column.key !== NO_STAGE_KEY}- fallback={- <CircleDashed class="size-3.5 text-ink-extra-muted" />- }- >- <CrmStageIcon- optionId={column.key}- index={columnIndex()}- class="size-3.5"- />- </Show>- <span class="truncate">{column.label}</span>- </div>- <div class="min-h-0 flex-1 overflow-y-auto scrollbar-hidden flex flex-col gap-2 px-2 pb-2">- <For each={column.entities}>- {(entity) => (- // The context-menu trigger is h-full (sized for list- // rows); an auto-height wrapper resolves that to the- // card's content height instead of the column's.- <div class="shrink-0">- <SoupEntityContextMenu- entity={entity}- list={soup}- selectedEntities={soup.selection.selected}- viewContext={entityActionViewContext()}- >- <CompanyKanbanCard- entity={entity}- draggable={canDragFrom(column.key)}- dragging={draggedId() === entity.id}- onDragStart={(e) => {- e.dataTransfer?.setData(- 'text/plain',- entity.id- );- if (e.dataTransfer) {- e.dataTransfer.effectAllowed = 'move';- }- setDraggedId(entity.id);- }}- onDragEnd={() => {- setDraggedId(undefined);- setDropTarget(undefined);- }}- onClick={(e) => openCompany(entity, e)}- />- </SoupEntityContextMenu>- </div>- )}- </For>- </div>- </div>- )}- </For>- </div>- </div>- {/* watchContent: columns mount after the initial measurement, so- overflow must be re-detected as they load in. */}- <CustomScrollbar- scrollContainer={scrollRef}- horizontal- revealZone={48}- gutterSize={20}- watchContent- />- </div>- </Show>- );-}--function CompanyKanbanCard(props: {- entity: EntityData;- draggable: boolean;- dragging: boolean;- onDragStart: (e: DragEvent) => void;- onDragEnd: () => void;- onClick: (e: MouseEvent) => void;-}) {- const ownerId = () =>- isCrmCompanyEntity(props.entity)- ? getCompanyOwnerId(props.entity)- : undefined;- const primaryDomain = () =>- isCrmCompanyEntity(props.entity)- ? props.entity.domains[0]?.domain- : undefined;-- return (- <Layer depth={2}>- <div- draggable={props.draggable}- onDragStart={props.onDragStart}- onDragEnd={props.onDragEnd}- onClick={props.onClick}- class={cn(- 'flex flex-col gap-1.5 rounded-lg bg-surface p-2.5 text-sm shadow-sm',- 'hover:bg-hover hover:shadow-md transition-[background-color,box-shadow]',- props.dragging && 'opacity-40'- )}- >- <div class="flex items-center gap-2 min-w-0">- <div class="size-4 shrink-0">- <Entity.Icon entity={props.entity} />- </div>- <span class="ph-no-capture truncate font-semibold min-w-0">- <Entity.Title entity={props.entity} />- </span>- <Show when={ownerId()}>- {(id) => (- <span class="ml-auto shrink-0">- <UserIcon id={id()} size="sm" suppressClick />- </span>- )}- </Show>- </div>- <div class="flex items-center gap-2 min-w-0 text-xs text-ink-extra-muted">- <Show when={primaryDomain()}>- {(domain) => <span class="truncate min-w-0">{domain()}</span>}- </Show>- {/* Last interaction — updatedAt carries crm_companies.last_interaction. */}- <Show when={props.entity.updatedAt}>- {(ts) => (- <span class="ml-auto shrink-0">{formatTimestamp(ts())}</span>- )}- </Show>- </div>- </div>- </Layer>- );-}diff --git a/apps/web/src/features/crm/views/company-detail.tsx b/apps/web/src/features/crm/views/company-detail.tsxindex 0ad6fbed72..dea2890aa9 100644--- a/apps/web/src/features/crm/views/company-detail.tsx+++ b/apps/web/src/features/crm/views/company-detail.tsx@@ -82,7 +82,10 @@ export function Company(props: {onClick={() => {const domain = company()?.domains[0]?.domain;if (domain)- openCreateContactModal(props.companyId, domain);+ openCreateContactModal({+ companyId: props.companyId,+ domain,+ });}}><PlusIcon class="size-3.5" />diff --git a/apps/web/src/features/crm/views/company-row.tsx b/apps/web/src/features/crm/views/company-row.tsxindex 429778726b..0ceaefd3dd 100644--- a/apps/web/src/features/crm/views/company-row.tsx+++ b/apps/web/src/features/crm/views/company-row.tsx@@ -1,124 +1,8 @@-import '@entity/composed/ListEntity.css';-import {- SwipableRow,- SwipableRowContext,-} from '@components/app/mobile/SwipableRow';-import { isMobile } from '@core/mobile/isMobile';-import { isTouchDevice } from '@core/mobile/isTouchDevice';-import { createEntityDraggable, Entity, unreadFilterFn } from '@entity';-import { NarrowLayout } from '@entity/composed/list-entity/narrow-layout';-import { SOUP_ROW_CLASS } from '@entity/composed/list-entity/row-geometry';-import {- type BaseListEntityProps,- type LayoutProps,- useListLayout,-} from '@entity/composed/list-entity/shared';-import type { EntityRowConfig } from '@entity/extractors-notification';-import { mergeRefs } from '@solid-primitives/refs';-import { cn } from '@ui/utils/classname';-import { type JSX, Match, Show, Switch, useContext } from 'solid-js';-import { useCrmContext } from '../context/crm-context';+import type { BaseListEntityProps } from '@entity/composed/list-entity/shared';import { CompanyGridLayout } from './company-grid-layout';+import { CrmListRow } from './record-row';-function MaybeEntityRow(props: {- entityId: string;- children: JSX.Element;- config?: EntityRowConfig;-}) {- const ctx = useContext(SwipableRowContext);- return (- <Show when={isMobile() && ctx} fallback={props.children}>- <SwipableRow- id={props.entityId}- swipeLeftColor={props.config?.swipeLeftColor}- swipeLeftRevealedComponent={props.config?.swipeLeftRevealedComponent}- swipeRightColor={props.config?.swipeRightColor}- swipeRightRevealedComponent={props.config?.swipeRightRevealedComponent}- >- {props.children}- </SwipableRow>- </Show>- );-}--/**- * Customers-list row that renders CRM properties (Stage, Owner, Revenue)- * in fixed-width grid columns so they line up vertically across rows,- * mirroring `TaskListEntity`.- */+/** Customers-list row with the editable Stage, Owner, and Revenue columns. */export function CompanyListEntity(props: BaseListEntityProps) {- const unread = () => unreadFilterFn(props.entity);-- const layoutProps = (): LayoutProps => ({- entity: props.entity,- checked: props.checked,- hideCheckbox: props.hideCheckbox,- onChecked: props.onChecked,- unread: unread(),- isShared: false,- hasNotifications: false,- showHitSnippet: false,- streamState: undefined,- setSnippetContainerRef: () => {},- chars: 0,- onProjectClick: props.onProjectClick,- });-- const draggable = createEntityDraggable({- entity: props.entity,- splitId: useCrmContext().createNavigation().splitId,- deferUntilInteraction: () => props.deferInteractions === true,- });-- const isWide = useListLayout()?.isWide ?? (() => true);-- return (- <Entity.Root- entity={props.entity}- onClick={(e) => {- if (e.metaKey && props.onChecked) {- props.onChecked(!props.checked, e.shiftKey);- return;- }- props.onClick?.(e);- }}- ref={mergeRefs(props.ref, draggable)}- class={cn(- // Carries the --soup-row-* geometry (ListEntity.css) that the narrow- // layout below reads for its leading edge.- isWide() ? SOUP_ROW_CLASS.wide : SOUP_ROW_CLASS.narrow,- 'soup-list-entity @container/entity w-[calc(100%-0.5rem)] mr-1 relative group/narrow flex flex-col py-0.5 rounded-xl',- {- 'min-h-10 mx-(--soup-row-gutter)': !isMobile(),- 'bg-list-selected': props.checked,- 'bg-list-selected-highlighted':- props.checked && props.highlighted && !isTouchDevice(),- 'bg-list-highlighted':- props.highlighted && !props.checked && !isTouchDevice(),- 'hover:bg-list-hover':- !props.highlighted && !props.checked && !isTouchDevice(),- }- )}- onMouseMove={props.onMouseMove}- >- <Switch>- <Match when={isWide()}>- <MaybeEntityRow- entityId={props.entity.id}- config={props.entityRowConfig}- >- <CompanyGridLayout {...layoutProps()} />- </MaybeEntityRow>- </Match>- <Match when={true}>- <MaybeEntityRow- entityId={props.entity.id}- config={props.entityRowConfig}- >- <NarrowLayout {...layoutProps()} />- </MaybeEntityRow>- </Match>- </Switch>- </Entity.Root>- );+ return <CrmListRow {...props} layout={CompanyGridLayout} />;}diff --git a/apps/web/src/features/crm/views/contact-list-header.tsx b/apps/web/src/features/crm/views/contact-list-header.tsxnew file mode 100644index 0000000000..21ae1945d9--- /dev/null+++ b/apps/web/src/features/crm/views/contact-list-header.tsx@@ -0,0 +1,62 @@+import { useListLayout } from '@entity/composed/list-entity/shared';+import ArrowDownIcon from '@phosphor/arrow-down.svg';+import { cn } from '@ui/utils/classname';+import { Show } from 'solid-js';+import { contactGridTemplate } from '../components/contact-grid-template';+import { useCrmWorkspace } from '../context/workspace-context';++/**+ * Sticky People header aligned with the contact row tracks. Must be used+ * inside a ListLayoutProvider; only the wide layout has columns.+ */+export function ResponsiveContactListHeader(props: { class?: string }) {+ const layout = useListLayout();+ const { soup } = useCrmWorkspace();+ const sortedByInteraction = () => soup.sort.active()[0]?.id === 'updated_at';+ const sortByInteraction = () =>+ sortedByInteraction()+ ? soup.sort.flip('updated_at')+ : soup.sort.setAll(['updated_at']);+ return (+ <Show when={layout?.isWide() ?? true}>+ <div+ // px-3 matches the row's Entity.Root `mx-1` plus Entity.Layout `px-2`.+ class={cn(+ 'w-full grid items-center gap-2 px-3 h-10 text-xs font-medium text-ink-extra-muted bg-surface',+ props.class+ )}+ style={contactGridTemplate(false)}+ >+ <div style={{ 'grid-area': 'indicator' }} />+ <div style={{ 'grid-area': 'content' }} class="truncate">+ Person+ </div>+ <div style={{ 'grid-area': 'company' }} class="truncate">+ Company+ </div>+ <div style={{ 'grid-area': 'timestamp' }} class="flex min-w-0">+ <button+ type="button"+ onClick={sortByInteraction}+ title="Most recent email interaction, incoming or outgoing"+ class={cn(+ 'flex items-center gap-1 min-w-0 w-full h-full justify-end hover:text-ink transition-colors',+ sortedByInteraction() && 'text-ink'+ )}+ >+ <span class="truncate">Last contacted</span>+ <ArrowDownIcon+ class={cn(+ 'size-3 shrink-0 transition-transform',+ sortedByInteraction() ? 'text-ink' : 'text-ink-extra-muted',+ sortedByInteraction() &&+ soup.sort.active()[0]?.reversed &&+ 'rotate-180'+ )}+ />+ </button>+ </div>+ </div>+ </Show>+ );+}diff --git a/apps/web/src/features/crm/views/contact-row.tsx b/apps/web/src/features/crm/views/contact-row.tsxnew file mode 100644index 0000000000..33d1b6c98d--- /dev/null+++ b/apps/web/src/features/crm/views/contact-row.tsx@@ -0,0 +1,92 @@+import {+ Entity,+ isCrmContactEntity,+ MultiSelectCheckbox,+ UnreadIndicator,+} from '@entity';+import type {+ BaseListEntityProps,+ LayoutProps,+} from '@entity/composed/list-entity/shared';+import BuildingsIcon from '@phosphor/buildings.svg';+import { cn } from '@ui/utils/classname';+import { Show } from 'solid-js';+import { contactGridTemplate } from '../components/contact-grid-template';+import { CrmListRow } from './record-row';++/** People row: name and email, company, and last interaction. */+function ContactGridLayout(props: LayoutProps) {+ const contact = () =>+ isCrmContactEntity(props.entity) ? props.entity : undefined;+ return (+ <Entity.Layout+ class="w-full min-h-[inherit] items-center text-sm px-2 gap-2 grid grid-rows-[1fr]"+ style={contactGridTemplate(!!props.hideCheckbox)}+ >+ <Show when={!props.hideCheckbox}>+ <Entity.Slot placement="indicator" class="relative size-full group">+ <div class="absolute inset-0 grid place-items-center group-hover:opacity-0">+ <UnreadIndicator active={props.unread} />+ </div>+ <div+ class={cn(+ 'absolute inset-0 grid place-items-center opacity-0 group-hover:opacity-100',+ { 'opacity-100': props.checked }+ )}+ >+ <MultiSelectCheckbox+ checked={props.checked}+ onChecked={props.onChecked}+ />+ </div>+ </Entity.Slot>+ </Show>++ <Entity.Slot+ placement="content"+ class="ph-no-capture font-medium truncate items-center gap-2 flex min-w-0"+ >+ <div class="size-4 shrink-0">+ <Entity.Icon entity={props.entity} />+ </div>+ <span class="truncate min-w-0">+ <Entity.Title entity={props.entity} />+ </span>+ <Show when={contact()?.email !== contact()?.name && contact()?.email}>+ {(email) => (+ <span class="truncate shrink-[2] min-w-0 text-xs font-normal text-ink-extra-muted">+ {email()}+ </span>+ )}+ </Show>+ </Entity.Slot>++ <Entity.Slot+ placement="company"+ class="ph-no-capture flex items-center gap-1.5 min-w-0 text-xs text-ink-muted"+ >+ <Show when={contact()?.companyName}>+ {(companyName) => (+ <>+ <BuildingsIcon class="size-3.5 shrink-0 text-ink-extra-muted" />+ <span class="truncate">{companyName()}</span>+ </>+ )}+ </Show>+ </Entity.Slot>++ {/* Contacts sort by last interaction, which `sortTs` carries. */}+ <Entity.Slot+ placement="timestamp"+ class="text-xs text-right text-ink-extra-muted font-light"+ >+ <Entity.Timestamp entity={props.entity} />+ </Entity.Slot>+ </Entity.Layout>+ );+}++/** People-list row for a CRM contact. */+export function ContactListEntity(props: BaseListEntityProps) {+ return <CrmListRow {...props} layout={ContactGridLayout} />;+}diff --git a/apps/web/src/features/crm/views/create-contact.tsx b/apps/web/src/features/crm/views/create-contact.tsxindex 63a873e753..9d0036a09f 100644--- a/apps/web/src/features/crm/views/create-contact.tsx+++ b/apps/web/src/features/crm/views/create-contact.tsx@@ -3,7 +3,14 @@ import UserPlusIcon from '@phosphor/user-plus.svg';import XIcon from '@phosphor/x.svg';import { Button, Dialog, Panel } from '@ui';import { createMemo, createSignal, Show } from 'solid-js';-import { useCreateContactMutation } from './use-crm';+import {+ type CompanyOption,+ CompanySelect,+} from '../components/company-select';+import {+ useCreateContactMutation,+ useQuickAccessCrmCompaniesQuery,+} from './use-crm';// The part before the @: non-empty, no whitespace or a second @.const LOCAL_PART_PATTERN = /^[^\s@]+$/;@@ -20,27 +27,69 @@ function createErrorMessage(cause: unknown): string {return 'Failed to create contact. Try again.';}+/** Companies without a domain cannot hold contacts, whose emails must match one. */+function ContactCompanySelect(props: {+ value: CompanyOption | undefined;+ onChange: (company: CompanyOption) => void;+}) {+ const suggestions = useQuickAccessCrmCompaniesQuery();+ const options = createMemo(() =>+ suggestions.companies().flatMap((company) =>+ company.domains[0]+ ? [+ {+ id: company.id,+ name: company.name,+ domain: company.domains[0].domain,+ },+ ]+ : []+ )+ );+ return (+ <CompanySelect+ id="new-contact-company"+ companies={options()}+ value={props.value}+ onChange={props.onChange}+ loading={suggestions.query.isLoading}+ portalScope="local"+ />+ );+}+export function CreateContactModal(props: {- target?: { companyId: string; domain: string };+ /** Opens the dialog; without a company, the dialog asks for one. */+ target?: { company?: { companyId: string; domain: string } };onClose(): void;onCreated(id: string): void;}) {const createContactMutation = useCreateContactMutation();const [name, setName] = createSignal('');const [localPart, setLocalPart] = createSignal('');+ const [pickedCompany, setPickedCompany] = createSignal<CompanyOption>();const [error, setError] = createSignal<string>();+ const company = () => {+ const picked = pickedCompany();+ return (+ props.target?.company ??+ (picked && { companyId: picked.id, domain: picked.domain })+ );+ };const contactName = createMemo(() => name().trim());const emailLocalPart = createMemo(() => localPart().trim().toLowerCase());const canSubmit = createMemo(() =>contactName().length > 0 &&emailLocalPart().length > 0 &&+ company() !== undefined &&!createContactMutation.isPending);function reset() {setName('');setLocalPart('');+ setPickedCompany(undefined);setError(undefined);}@@ -57,7 +106,7 @@ export function CreateContactModal(props: {// Pasting a full address is common — strip our fixed suffix so// "[email protected]" collapses to "jane" instead of failing validation.function handleLocalPartInput(value: string) {- const domain = props.target?.domain;+ const domain = company()?.domain;const suffix = domain ? `@${domain}` : undefined;setLocalPart(suffix && value.toLowerCase().endsWith(suffix)@@ -69,8 +118,11 @@ export function CreateContactModal(props: {async function handleSubmit(event: SubmitEvent) {event.preventDefault();- const target = props.target;- if (!target) return;+ const target = company();+ if (!target) {+ setError('Choose a company');+ return;+ }if (!contactName()) {setError('Enter a name');return;@@ -143,6 +195,24 @@ export function CreateContactModal(props: {/></div>+ <Show when={!props.target?.company}>+ <div class="flex flex-col gap-2 px-2">+ <label+ for="new-contact-company"+ class="text-xs font-medium text-ink-muted"+ >+ Company+ </label>+ <ContactCompanySelect+ value={pickedCompany()}+ onChange={(picked) => {+ setPickedCompany(picked);+ setError(undefined);+ }}+ />+ </div>+ </Show>+<div class="flex flex-col gap-2 px-2"><labelfor="new-contact-email"@@ -168,7 +238,7 @@ export function CreateContactModal(props: {class="h-full min-w-0 flex-1 border-none bg-transparent pl-3 text-sm text-ink outline-none placeholder:text-ink-placeholder focus:ring-0"/><span class="shrink-0 select-none pr-3 pl-0.5 text-sm text-ink-placeholder">- @{props.target?.domain}+ @{company()?.domain ?? 'company domain'}</span></div></div>diff --git a/apps/web/src/features/crm/views/crm-workspace.tsx b/apps/web/src/features/crm/views/crm-workspace.tsxindex 149c7d29bb..9b4d2e7cab 100644--- a/apps/web/src/features/crm/views/crm-workspace.tsx+++ b/apps/web/src/features/crm/views/crm-workspace.tsx@@ -5,7 +5,6 @@ import {ViewShell,} from '@app/components/view-shell';import { VIEW_SHELL_TOUR } from '@app/components/view-shell/tour';-import { NO_ASSIGNEE } from '@app/features/next-soup/filters/configs';import { NIL_UUID } from '@app/features/next-soup/filters/filter-store';import { getViewPreset } from '@app/features/next-soup/sidebar/soup-filter-presets';import { SoupActiveFiltersBar } from '@app/features/next-soup/soup-view/filters-bar/soup-active-filters-bar';@@ -15,35 +14,42 @@ import { UnifiedFilterDropdown } from '@app/features/next-soup/soup-view/filtersimport { useFilterRefinements } from '@app/features/next-soup/soup-view/filters-bar/use-filter-refinements';import { usePreference } from '@app/preferences/use-preference';import { isTouchDevice } from '@core/mobile/isTouchDevice';-import { type EntityData, isCrmCompanyEntity } from '@entity';+import { debounce } from '@core/util/debounce';+import {+ type EntityData,+ isCrmCompanyEntity,+ isCrmContactEntity,+} from '@entity';import ListIcon from '@phosphor/list.svg';+import PlusIcon from '@phosphor/plus.svg';import { Button, Dropdown, Tooltip } from '@ui';import { tourTarget } from '@ui/components/Tour';-import { createSignal, type JSX, onMount, Show, Suspense } from 'solid-js';+import {+ createSignal,+ type JSX,+ onCleanup,+ onMount,+ Show,+ Suspense,+} from 'solid-js';import { CrmListDialog } from '../components/company-list-dialog';import { CrmSidebar } from '../components/crm-sidebar';import { PipelineDialog } from '../components/pipeline-dialog';import { PipelineSidebar } from '../components/pipeline-sidebar';import { useCrmContext } from '../context/crm-context';import { useCrmWorkspace } from '../context/workspace-context';-import { CRM_VIEWS } from '../core/navigation';-import type { PeopleSort } from '../core/people';-import type { CrmViewConfig } from '../core/saved-view';+import { CRM_RECORDS } from '../core/navigation';import { createCrmExportLoader } from '../primitives/export-source';import { useApplyCrmView } from './apply-view';import { CrmExport } from './export-companies';import { CrmImport } from './import-companies';-import { CrmPeople } from './people';import { PipelineView } from './pipeline';-import { CrmCompanyDetail } from './record-detail';+import { CrmRecordDetail, type CrmRecordRef } from './record-detail';import { CompanyDisplayMenu, CompanyViewsMenu } from './saved-views-menu';import {useCrmLists,useCurrentTeamQuery,- usePersonalCrmViews,useQuickAccessCrmCompaniesQuery,- useTeamCrmViews,- useCrmUserId as useUserId,} from './use-crm';function NavigationToggle(props: {@@ -88,11 +94,7 @@ function NavigationToggle(props: {<Dropdown.Content class="w-55 max-h-[80vh] overflow-auto p-0"><divonClick={(event) => {- if (- (event.target as HTMLElement).closest(- 'nav button, [role="radiogroup"]'- )- )+ if ((event.target as HTMLElement).closest('nav button'))setOpen(false);}}>@@ -134,27 +136,59 @@ function CrmSearchBar() {);}+/** Contacts are not in the search index, so People searches the soup query. */+function PeopleSearchBar() {+ const view = useCrmWorkspace();+ let input: HTMLInputElement | undefined;+ const [text, setText] = createSignal(+ view.queryFilters.state.include.crmContactSearch ?? ''+ );+ // Every applied search restarts the server query; wait for a typing pause.+ const applySearch = debounce(+ (value: string) =>+ view.queryFilters.set({+ include: { crmContactSearch: value.trim() || undefined },+ }),+ 250+ );+ onCleanup(applySearch.clear);+ const search = (value: string) => {+ setText(value);+ applySearch(value);+ };+ useViewControlHotkeys({+ scopeId: view.host.scopeId,+ enabled: view.host.isActive,+ search: {+ description: 'Search people',+ run: () => {+ input?.focus();+ input?.select();+ return true;+ },+ },+ });+ return (+ <SearchBar+ ref={(element) => (input = element)}+ label="Search people"+ placeholder="Search people"+ value={text()}+ onValueChange={search}+ onEscape={view.host.focus}+ hotkey="cmd+f"+ class="max-w-md flex-1"+ />+ );+}+function CrmFilterChips(props: { onReset: () => void }) {const { consolidatedFiltersList } = useFilterRefinements();- const view = useCrmWorkspace();- const userId = useUserId();- const filters = () =>- consolidatedFiltersList().filter((filter) => {- const defaultOwner =- view.activeTab() === 'my-companies'- ? userId()- : view.activeTab() === 'unassigned'- ? NO_ASSIGNEE- : undefined;- return !(- filter.key === 'owner' &&- defaultOwner &&- filter.values().length === 1 &&- filter.values()[0].id === defaultOwner- );- });return (- <SoupActiveFiltersBar filters={filters()} onClearAll={props.onReset} />+ <SoupActiveFiltersBar+ filters={consolidatedFiltersList()}+ onClearAll={props.onReset}+ />);}@@ -166,25 +200,27 @@ export function CrmWorkspaceView(props: {}) {const {openCreateCompany: openCreateCompanyModal,+ openCreateContact: openCreateContactModal,exportCompanies: fetchCrmExportCompanies,PipelineEditor,copyViewLink,} = useCrmContext();const view = useCrmWorkspace();- const [selectedCompany, setSelectedCompany] = createSignal<{- id: string;- name: string;- }>();- const closeCompany = () => setSelectedCompany(undefined);- const openCompany = (entity: EntityData) => {- if (!isCrmCompanyEntity(entity)) return false;+ const [selectedRecord, setSelectedRecord] = createSignal<CrmRecordRef>();+ const closeRecord = () => setSelectedRecord(undefined);+ const openRecord = (entity: EntityData) => {+ const type = isCrmCompanyEntity(entity)+ ? 'company'+ : isCrmContactEntity(entity)+ ? 'contact'+ : undefined;+ if (!type) return false;view.soup.focus.set(entity.id);view.host.captureEntryState();- setSelectedCompany({ id: entity.id, name: entity.name });+ setSelectedRecord({ type, id: entity.id, name: entity.name });return true;};const apply = useApplyCrmView();- const userId = useUserId();const [collapsed, setCollapsed] = usePreference('macro:pref:crm:sidebar-collapsed',{ default: false }@@ -208,23 +244,11 @@ export function CrmWorkspaceView(props: {const activePipeline = () =>pipelines.pipelines().find((pipeline) => pipeline.id === pipelineId());const selectPipeline = (id: string) => {- closeCompany();+ closeRecord();view.setActiveTab(`pipeline:${id}`);};const listsEnabled = useCrmContext().listsEnabled();const lists = useCrmLists(() => (listsEnabled() ? teamId() : undefined));- const personal = usePersonalCrmViews();- const team = useTeamCrmViews();- const savedViews = () => [- ...personal- .views()- .map((v) => ({ id: `personal:${v.id}`, name: v.name, config: v.config })),- ...team.views().map((v) => ({- id: `team:${v.id}`,- name: v.name,- config: v.config as CrmViewConfig,- })),- ];const [editing, setEditing] = createSignal<{id?: string;name: string;@@ -233,32 +257,36 @@ export function CrmWorkspaceView(props: {const [importing, setImporting] = createSignal(false);const active = () => view.activeTab() ?? 'active';const peopleActive = () => active() === 'people';- const directory = useCrmContext().createPeopleSource(peopleActive);- const [peopleSearch, setPeopleSearch] = createSignal('');- const [peopleSort, setPeopleSort] =- createSignal<PeopleSort>('lastInteraction');- const [peopleDescending, setPeopleDescending] = createSignal(true);const [exporting, setExporting] = createSignal(false);const activeList = () =>lists.lists().find((list) => `list:${list.id}` === active());+ // Every other tab (hidden companies, saved or shared views) is a company view.+ const activeRecord = () =>+ pipelineId()+ ? `pipeline:${pipelineId()}`+ : active().startsWith('list:') || peopleActive()+ ? active()+ : 'active';const title = () =>activeList()?.name ??- savedViews().find((v) => v.id === active())?.name ??- CRM_VIEWS.find((v) => v.id === active())?.label ??+ CRM_RECORDS.find((record) => record.id === activeRecord())?.label ??'Companies';const navigate = (id: string) => {if (!listsEnabled() && id.startsWith('list:')) id = 'active';- closeCompany();+ closeRecord();if (id === 'people') {- view.setActiveTab(id);- return;- }- const saved = savedViews().find((v) => v.id === id);- if (saved) {- apply({ ...saved.config, viewMode: view.viewMode() });- view.setActiveTab(id);+ // Re-applying would clear a search the People search bar still shows.+ if (peopleActive()) return;+ const people = getViewPreset('companies', 'people');+ apply({+ kind: 'crm',+ activeTab: id,+ filters: people?.filters,+ clientFilters: people?.clientFilters,+ });return;}+ if (!id.startsWith('list:')) id = 'active';const preset = getViewPreset('companies');const list = lists.lists().find((list) => `list:${list.id}` === id);const filters = structuredClone(preset?.filters ?? {});@@ -273,24 +301,8 @@ export function CrmWorkspaceView(props: {kind: 'crm',activeTab: id,filters,- clientFilters: {- and: [- 'crm-company-active',- ...(id === 'needs-follow-up'- ? ['company-needs-follow-up']- : id === 'recently-active'- ? ['company-recently-active']- : []),- ],- },- ownerFilter:- id === 'my-companies'- ? [userId() ?? NIL_UUID]- : id === 'unassigned'- ? [NO_ASSIGNEE]- : [],+ clientFilters: preset?.clientFilters,groupBy: preset?.groupBy,- viewMode: view.viewMode(),});};onMount(() => {@@ -312,24 +324,27 @@ export function CrmWorkspaceView(props: {/></Show>}- active={pipelineId() ? `pipeline:${pipelineId()}` : active()}- viewMode={view.viewMode()}- onViewModeChange={(mode) => {- closeCompany();- view.setViewMode(mode);- }}+ active={activeRecord()}lists={lists.lists().map((list) => ({id: list.id,name: list.name,count: list.config.companyIds.length,}))}- savedViews={savedViews()}listsEnabled={listsEnabled()}listsLoading={lists.query.isLoading}listsError={lists.query.isError}canCreateList={!!teamId()}onNavigate={navigate}- onCreate={openCreateCompanyModal}+ onCreateCompany={openCreateCompanyModal}+ onCreateContact={() => openCreateContactModal()}+ pipeline={+ pipelinesEnabled()+ ? {+ disabled: !canCreatePipeline(),+ onCreate: () => setCreatingPipeline(true),+ }+ : undefined+ }onNewList={() => setEditing({ name: '', companyIds: [] })}onImport={() => setImporting(true)}onExport={() => setExporting(true)}@@ -347,12 +362,12 @@ export function CrmWorkspaceView(props: {</Suspense></ViewShell.Aside><ViewShell.Main>- <Show when={selectedCompany()} keyed>- {(company) => (- <CrmCompanyDetail- company={company}+ <Show when={selectedRecord()} keyed>+ {(record) => (+ <CrmRecordDetail+ record={record}viewName={title()}- onClose={closeCompany}+ onClose={closeRecord}navigation={<NavigationToggle onExpand={() => setCollapsed(false)}><Suspense>{sidebar()}</Suspense>@@ -376,7 +391,7 @@ export function CrmWorkspaceView(props: {activeTab: `pipeline:${id}`,})}- onBack={() => navigate('active')}+ onTrashed={() => navigate('active')}navigation={<NavigationToggle onExpand={() => setCollapsed(false)}><Suspense>{sidebar()}</Suspense>@@ -401,7 +416,7 @@ export function CrmWorkspaceView(props: {</Button></div></Show>- <Show when={!selectedCompany() && !pipelineId()}>+ <Show when={!selectedRecord() && !pipelineId()}><Show when={!isTouchDevice() || peopleActive()}><div class="flex h-12 shrink-0 items-center gap-3 px-4"><NavigationToggle onExpand={() => setCollapsed(false)}>@@ -414,7 +429,24 @@ export function CrmWorkspaceView(props: {<span class="truncate">{title()}</span></h1></div>- <Show when={!peopleActive()}>+ <Show+ when={!peopleActive()}+ fallback={+ <ViewShell.Header>+ <div class="flex min-w-0 items-center justify-between gap-3">+ <PeopleSearchBar />+ <Button+ variant="outline"+ class="ml-auto shrink-0"+ onClick={() => openCreateContactModal()}+ >+ <PlusIcon class="size-4" />+ New contact+ </Button>+ </div>+ </ViewShell.Header>+ }+ ><ViewShell.Header><div class="flex min-w-0 items-center justify-between gap-3"><CrmSearchBar />@@ -443,6 +475,10 @@ export function CrmWorkspaceView(props: {</Button>)}</Show>+ <Button variant="outline" onClick={openCreateCompanyModal}>+ <PlusIcon />+ New company+ </Button></div></div></ViewShell.Header>@@ -452,27 +488,14 @@ export function CrmWorkspaceView(props: {</Show></Show><div class="flex min-h-0 min-w-0 flex-1 flex-col">- <Show- when={peopleActive()}- fallback={props.children({- onOpenEntity: isTouchDevice() ? undefined : openCompany,- mobileHeaderLeading: isTouchDevice() ? (- <NavigationToggle onExpand={() => setCollapsed(false)}>- <Suspense>{sidebar()}</Suspense>- </NavigationToggle>- ) : undefined,- })}- >- <CrmPeople- directory={directory}- search={peopleSearch()}- onSearch={setPeopleSearch}- sort={peopleSort()}- onSort={setPeopleSort}- descending={peopleDescending()}- onDescending={setPeopleDescending}- />- </Show>+ {props.children({+ onOpenEntity: isTouchDevice() ? undefined : openRecord,+ mobileHeaderLeading: isTouchDevice() ? (+ <NavigationToggle onExpand={() => setCollapsed(false)}>+ <Suspense>{sidebar()}</Suspense>+ </NavigationToggle>+ ) : undefined,+ })}</div></Show></ViewShell.Main>diff --git a/apps/web/src/features/crm/views/default-view.tsx b/apps/web/src/features/crm/views/default-view.tsxindex fcb5d6b2fa..32b4d69905 100644--- a/apps/web/src/features/crm/views/default-view.tsx+++ b/apps/web/src/features/crm/views/default-view.tsx@@ -1,4 +1,3 @@-import { isTouchDevice } from '@core/mobile/isTouchDevice';import type { CrmViewConfig } from '../core/saved-view';import { createDefaultCrmView } from '../primitives/default-view';import { useApplyCrmView } from './apply-view';@@ -21,7 +20,6 @@ export function CrmDefaultViewLoader() {teamLoading: team.isLoading,personal: () => personal.defaultView()?.config,team: () => team.defaultView()?.config as CrmViewConfig | undefined,- mobile: isTouchDevice,apply: applyView,});diff --git a/apps/web/src/features/crm/views/empty-state.tsx b/apps/web/src/features/crm/views/empty-state.tsxindex 3a7ef328c5..e104d0d983 100644--- a/apps/web/src/features/crm/views/empty-state.tsx+++ b/apps/web/src/features/crm/views/empty-state.tsx@@ -5,7 +5,8 @@ import { useCrmWorkspace } from '../context/workspace-context';import { useCurrentTeamQuery, useIsTeamAdmin } from './use-crm';export function CrmEmptyState() {- const { host, activeTab } = useCrmWorkspace();+ const { host, activeTab, queryFilters } = useCrmWorkspace();+ const peopleSearch = () => queryFilters.state.include.crmContactSearch;const teamQuery = useCurrentTeamQuery();const isTeamAdmin = useIsTeamAdmin();const teamResolved = () => teamQuery.data !== undefined;@@ -48,6 +49,17 @@ export function CrmEmptyState() {}/></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.'+ }+ />+ </Match><Match when={true}><EmptyStatePanelgraphic={EmptyStateCompaniesGraphic}diff --git a/apps/web/src/features/crm/views/people.tsx b/apps/web/src/features/crm/views/people.tsxdeleted file mode 100644index 35b576ec40..0000000000--- a/apps/web/src/features/crm/views/people.tsx+++ /dev/null@@ -1,275 +0,0 @@-import BuildingsIcon from '@phosphor/buildings.svg';-import CaretDownIcon from '@phosphor/caret-down.svg';-import MagnifyingGlassIcon from '@phosphor/magnifying-glass.svg';-import UsersIcon from '@phosphor/users.svg';-import { Button } from '@ui';-import { createMemo, createSignal, For, Show } from 'solid-js';-import { useCrmContext } from '../context/crm-context';-import type { PeopleSource } from '../context/crm-sources';-import { filterAndSortPeople, type PeopleSort } from '../core/people';--const PAGE_SIZE = 50;-const dateLabel = (value: string) => {- const date = new Date(value);- return Number.isNaN(date.getTime())- ? '—'- : date.toLocaleDateString(undefined, {- month: 'short',- day: 'numeric',- year: 'numeric',- });-};-const columns: { label: string; sort?: PeopleSort; class: string }[] = [- { label: 'Name', sort: 'name', class: 'w-[25%]' },- { label: 'Email', class: 'w-[26%]' },- { label: 'Company', sort: 'companyName', class: 'w-[23%]' },- { label: 'Last contacted', sort: 'lastInteraction', class: 'w-40' },- { label: 'First contact', sort: 'firstInteraction', class: 'w-40' },-];--export function CrmPeople(props: {- directory: PeopleSource;- search: string;- onSearch: (value: string) => void;- sort: PeopleSort;- onSort: (value: PeopleSort) => void;- descending: boolean;- onDescending: (value: boolean) => void;-}) {- const directory = props.directory;- const { openWithSplit } = useCrmContext().createNavigation();- const search = () => props.search;- const sort = () => props.sort;- const descending = () => props.descending;- const [page, setPage] = createSignal(0);- const people = createMemo(() =>- filterAndSortPeople(directory.people(), search(), sort(), descending())- );- const currentPage = () =>- Math.min(page(), Math.max(0, Math.ceil(people().length / PAGE_SIZE) - 1));- const rows = () =>- people().slice(currentPage() * PAGE_SIZE, (currentPage() + 1) * PAGE_SIZE);- const loading = () =>- !directory.query.isError &&- (directory.query.isFetching || directory.query.hasNextPage);- const changeSort = (value: PeopleSort) => {- props.onDescending(- sort() === value- ? !descending()- : value === 'lastInteraction' || value === 'firstInteraction'- );- props.onSort(value);- setPage(0);- };- return (- <div class="flex min-h-0 min-w-0 flex-1 flex-col">- <div class="flex flex-wrap items-center gap-3 border-b border-edge-muted px-4 py-3">- <div class="flex min-w-40 max-w-sm flex-1 items-center gap-2 rounded-md border border-edge-muted bg-input px-3 py-1.5 focus-within:border-accent">- <MagnifyingGlassIcon class="size-4 shrink-0 text-ink-muted" />- <input- type="search"- aria-label="Search people"- value={search()}- onInput={(event) => {- props.onSearch(event.currentTarget.value);- setPage(0);- }}- placeholder="Search people, emails, companies…"- class="min-w-0 flex-1 bg-transparent text-sm outline-none placeholder:text-ink-placeholder"- />- </div>- <span class="ml-auto text-xs tabular-nums text-ink-muted" role="status">- {people().length.toLocaleString()}{' '}- {people().length === 1 ? 'person' : 'people'}- <Show when={loading()}> · Loading contacts…</Show>- </span>- </div>- <Show when={directory.query.isError}>- <div- class="flex items-center justify-between gap-3 border-b border-edge-muted px-4 py-3 text-sm text-ink-muted"- role="alert"- >- <span>- Some contacts could not be loaded. The people already loaded are- still available.- </span>- <Button- variant="ghost"- size="sm"- onClick={() =>- directory.query.isFetchNextPageError- ? void directory.query.fetchNextPage()- : void directory.query.refetch()- }- >- Retry- </Button>- </div>- </Show>- <div class="min-h-0 flex-1 overflow-auto">- <table- class="w-full min-w-[960px] table-fixed border-collapse text-left text-sm"- aria-label="People"- >- <thead class="sticky top-0 z-1 bg-panel text-xs text-ink-muted">- <tr>- <For each={columns}>- {(column) => (- <th- scope="col"- class={`border-b border-edge-muted px-4 py-3 font-medium ${column.class}`}- aria-sort={- column.sort === sort()- ? descending()- ? 'descending'- : 'ascending'- : undefined- }- >- <Show when={column.sort} fallback={column.label}>- {(field) => (- <button- type="button"- class="flex items-center gap-2 hover:text-ink"- onClick={() => changeSort(field())}- title={- field() === 'lastInteraction'- ? 'Most recent email interaction, incoming or outgoing'- : undefined- }- >- {column.label}- <Show when={sort() === field()}>- <CaretDownIcon- class="size-3"- classList={{ 'rotate-180': !descending() }}- />- </Show>- </button>- )}- </Show>- </th>- )}- </For>- </tr>- </thead>- <tbody>- <For each={rows()}>- {(person) => (- <tr class="group border-b border-edge-muted/60 hover:bg-hover">- <td class="px-4 py-2.5">- <button- type="button"- class="flex w-full min-w-0 items-center gap-3 text-left"- onClick={(event) =>- openWithSplit(- { type: 'contact', id: person.id },- { activate: true, preferNewSplit: event.shiftKey }- )- }- >- <span- class="flex size-7 shrink-0 items-center justify-center rounded-full bg-accent/10 text-xs font-medium text-accent"- aria-hidden="true"- >- {(person.name || person.email)- .slice(0, 1)- .toUpperCase()}- </span>- <span- class="truncate font-medium"- title={person.name || person.email}- >- {person.name || person.email}- </span>- </button>- </td>- <td- class="truncate px-4 py-2.5 text-ink-muted"- title={person.email}- >- {person.email}- </td>- <td class="px-4 py-2.5">- <button- type="button"- class="flex max-w-full items-center gap-2 text-ink-muted hover:text-ink"- onClick={(event) =>- openWithSplit(- { type: 'company', id: person.companyId },- { activate: true, preferNewSplit: event.shiftKey }- )- }- >- <BuildingsIcon class="size-4 shrink-0 text-ink-extra-muted" />- <span class="truncate" title={person.companyName}>- {person.companyName}- </span>- </button>- </td>- <td- class="px-4 py-2.5 text-ink-muted"- title={new Date(person.lastInteraction).toLocaleString()}- >- {dateLabel(person.lastInteraction)}- </td>- <td- class="px-4 py-2.5 text-ink-muted"- title={new Date(person.firstInteraction).toLocaleString()}- >- {dateLabel(person.firstInteraction)}- </td>- </tr>- )}- </For>- </tbody>- </table>- <Show when={!rows().length}>- <div- class="flex flex-col items-center gap-3 px-6 py-20 text-center"- role="status"- >- <UsersIcon class="size-8 text-ink-extra-muted" />- <p class="text-sm font-medium">- {loading()- ? 'Loading people…'- : search()- ? 'No matching people'- : 'No people yet'}- </p>- <p class="max-w-sm text-sm text-ink-muted">- {loading()- ? 'Your contacts will appear here as they load.'- : search()- ? 'Try a name, email address, or company.'- : 'People connected to your CRM companies will appear here.'}- </p>- </div>- </Show>- </div>- <div class="flex shrink-0 items-center gap-3 border-t border-edge-muted px-4 py-2 text-xs text-ink-muted">- <span class="mr-auto">- {people().length- ? `${currentPage() * PAGE_SIZE + 1}–${Math.min((currentPage() + 1) * PAGE_SIZE, people().length)} of ${people().length.toLocaleString()}`- : '0 people'}- </span>- <Button- variant="ghost"- size="sm"- disabled={currentPage() === 0}- onClick={() => setPage(currentPage() - 1)}- >- Previous- </Button>- <Button- variant="ghost"- size="sm"- disabled={(currentPage() + 1) * PAGE_SIZE >= people().length}- onClick={() => setPage(currentPage() + 1)}- >- Next- </Button>- </div>- </div>- );-}diff --git a/apps/web/src/features/crm/views/pipeline.tsx b/apps/web/src/features/crm/views/pipeline.tsxindex 4a3eface01..baa052094a 100644--- a/apps/web/src/features/crm/views/pipeline.tsx+++ b/apps/web/src/features/crm/views/pipeline.tsx@@ -1,5 +1,9 @@-import { Button } from '@ui';+import { InlineTitleEditor } from '@core/component/InlineTitleEditor';+import DotsThreeIcon from '@phosphor/dots-three.svg';+import PencilIcon from '@phosphor/pencil-line.svg';+import TrashIcon from '@phosphor/trash-simple.svg';import { DeleteDialog } from '@ui/components/DeleteDialog';+import { Dropdown } from '@ui/components/Dropdown';import { createSignal, type JSX, Show } from 'solid-js';import type {PipelineEditor,@@ -8,6 +12,7 @@ import type {} from '../context/pipelines';import type { Pipeline } from '../core/pipeline';+/** A pipeline's page: its name, sharing and actions above its one table. */export function PipelineView(props: {pipeline: Pipeline;source: PipelinesSource;@@ -15,13 +20,15 @@ export function PipelineView(props: {Editor: PipelineEditor;Sharing: PipelineSharing;onCopyLink(): void;- onBack(): void;+ /** After the pipeline moves to trash, leave its page. */+ onTrashed(): void;}) {- const [draftName, setDraftName] = createSignal<string>();- const name = () => draftName() ?? props.pipeline.name;const [pending, setPending] = createSignal(false);const [error, setError] = createSignal('');const [deleting, setDeleting] = createSignal(false);+ let title: HTMLSpanElement | undefined;+ const canEdit = () => ['owner', 'edit'].includes(props.pipeline.grant);+ const isOwner = () => props.pipeline.grant === 'owner';async function save(action: () => Promise<void>) {if (pending()) return;setPending(true);@@ -34,70 +41,71 @@ export function PipelineView(props: {setPending(false);}}+ const editTitle = () => {+ const input = title?.querySelector('input');+ input?.focus();+ input?.select();+ };return (<div class="flex size-full min-h-0 flex-col">- <div class="flex flex-wrap items-center gap-3 border-b border-edge-muted p-3">+ <div class="flex h-12 min-w-0 shrink-0 items-center gap-2 px-4">{props.navigation}- <Button variant="ghost" size="sm" onClick={props.onBack}>- Back to companies- </Button>- <form- class="flex min-w-0 flex-1 items-center gap-2"- onSubmit={(event) => {- event.preventDefault();- void save(async () => {- await props.source.rename(props.pipeline.id, name().trim());- setDraftName(undefined);- });- }}- >- <input- aria-label="Pipeline name"- value={name()}- maxlength={200}- required- disabled={- pending() || !['owner', 'edit'].includes(props.pipeline.grant)- }- onInput={(event) => setDraftName(event.currentTarget.value)}- class="min-w-0 flex-1 rounded border border-transparent bg-transparent px-2 py-1 text-sm font-semibold outline-none focus:border-accent"- />- <Show when={name().trim() !== props.pipeline.name}>- <Button- size="sm"- type="submit"- disabled={pending() || !name().trim()}- >- Save name- </Button>- </Show>- </form>- <props.Sharing- pipeline={props.pipeline}- onCopyLink={props.onCopyLink}- /><Show- when={props.pipeline.grant === 'owner'}+ when={canEdit()}fallback={- <span class="text-xs text-ink-muted">- {props.pipeline.sharing === 'team'- ? 'Shared with team'- : 'Private'}- </span>+ <h1 class="min-w-0 truncate px-1 text-sm font-semibold">+ {props.pipeline.name}+ </h1>}>- <Button- variant="ghost"- size="sm"- disabled={pending()}- onClick={() => setDeleting(true)}- >- Trash pipeline- </Button>+ <span ref={title} class="flex min-w-0 px-1">+ <InlineTitleEditor+ value={props.pipeline.name}+ placeholder="Untitled pipeline"+ ariaLabel="Pipeline name"+ class="text-sm"+ onRename={(name) =>+ void save(() => props.source.rename(props.pipeline.id, name))+ }+ />+ </span></Show>+ <Show when={canEdit() || isOwner()}>+ <Dropdown placement="bottom-start">+ <Dropdown.Trigger+ variant="ghost"+ size="icon-sm"+ aria-label="Pipeline actions"+ class="shrink-0"+ disabled={pending()}+ >+ <DotsThreeIcon class="size-4" />+ </Dropdown.Trigger>+ <Dropdown.Content class="min-w-44">+ <Show when={canEdit()}>+ <Dropdown.Item onSelect={() => queueMicrotask(editTitle)}>+ <PencilIcon class="size-4" />+ Rename+ </Dropdown.Item>+ </Show>+ <Show when={isOwner()}>+ <Dropdown.Item onSelect={() => setDeleting(true)}>+ <TrashIcon class="size-4" />+ Trash pipeline+ </Dropdown.Item>+ </Show>+ </Dropdown.Content>+ </Dropdown>+ </Show>+ <div class="ml-auto flex shrink-0 items-center gap-1">+ <props.Sharing+ pipeline={props.pipeline}+ onCopyLink={props.onCopyLink}+ />+ </div></div><Show when={error()}>- <p role="alert" class="px-4 py-2 text-sm text-failure-ink">+ <p role="alert" class="px-4 pb-2 text-sm text-failure-ink">{error()}</p></Show>@@ -116,7 +124,7 @@ export function PipelineView(props: {onDelete={() =>void save(async () => {await props.source.trash(props.pipeline.id);- props.onBack();+ props.onTrashed();})}/>diff --git a/apps/web/src/features/crm/views/record-detail.test.tsx b/apps/web/src/features/crm/views/record-detail.test.tsxindex f1378a966e..d720b387f8 100644--- a/apps/web/src/features/crm/views/record-detail.test.tsx+++ b/apps/web/src/features/crm/views/record-detail.test.tsx@@ -14,7 +14,7 @@ import {} from 'solid-js';import { afterEach, expect, it, vi } from 'vitest';import type { CrmContact } from '../core/contact';-import { CrmCompanyDetail } from './record-detail';+import { CrmRecordDetail } from './record-detail';vi.mock('@ui', async () => ({...(await import('../../../components/ui/utils/classname')),@@ -61,8 +61,16 @@ vi.mock('./company-detail', () => ({),}));vi.mock('./contact-detail', () => ({- Contact: (props: { contactId: string }) => (- <div>Contact content: {props.contactId}</div>+ Contact: (props: {+ contactId: string;+ onOpenCompany(companyId: string): boolean;+ }) => (+ <div>+ Contact content: {props.contactId}+ <button onClick={() => props.onOpenCompany('company-1')}>+ Open contact company+ </button>+ </div>),}));afterEach(cleanup);@@ -78,8 +86,8 @@ it('removes contact breadcrumbs safely when returning to the company and reopeni<button onClick={() => setSelected(true)}>Open company</button>}>- <CrmCompanyDetail- company={{ id: 'company-1', name: 'Northstar' }}+ <CrmRecordDetail+ record={{ type: 'company', id: 'company-1', name: 'Northstar' }}viewName="Pipeline"onClose={() => setSelected(false)}navigation={null}@@ -105,3 +113,31 @@ it('removes contact breadcrumbs safely when returning to the company and reopeni}expect(failed).not.toHaveBeenCalled();});++it('opens a People contact in place and follows its company without duplicating the trail', () => {+ const close = vi.fn();+ render(() => (+ <CrmRecordDetail+ record={{ type: 'contact', id: 'contact-1', name: 'Maya' }}+ viewName="People"+ onClose={close}+ navigation={null}+ />+ ));+ const crumbs = () =>+ within(screen.getByRole('navigation', { name: 'CRM record location' }))+ .getAllByRole('button')+ .map((button) => button.textContent);+ expect(crumbs()).toEqual(['People', 'Maya']);+ expect(screen.getByText('Contact content: contact-1')).toBeTruthy();++ fireEvent.click(screen.getByRole('button', { name: 'Open contact company' }));+ expect(crumbs()).toEqual(['People', 'Maya', 'Company']);++ // The company's contact is already in the trail, so opening it returns there.+ fireEvent.click(screen.getByRole('button', { name: 'Open Maya' }));+ expect(crumbs()).toEqual(['People', 'Maya']);++ fireEvent.click(screen.getByRole('button', { name: 'People' }));+ expect(close).toHaveBeenCalledOnce();+});diff --git a/apps/web/src/features/crm/views/record-detail.tsx b/apps/web/src/features/crm/views/record-detail.tsxindex 109f420975..136b7a8ec4 100644--- a/apps/web/src/features/crm/views/record-detail.tsx+++ b/apps/web/src/features/crm/views/record-detail.tsx@@ -6,13 +6,13 @@ import { Button, Tooltip } from '@ui';import {createSignal,ErrorBoundary,+ For,type JSX,onMount,Show,Suspense,} from 'solid-js';import { RecordTabs } from '../components/record-tabs';-import type { CrmContact as CompanyContact } from '../core/contact';import {COMPANY_SECTIONS,CONTACT_SECTIONS,@@ -24,47 +24,71 @@ import { Contact } from './contact-detail';import { CrmCopyLinkButton } from './copy-link-button';import { useCompanyQuery, useContactQuery } from './use-crm';-export function CrmCompanyDetail(props: {- company: { id: string; name: string };+/** A CRM record shown inside the workspace, with its fallback label. */+export type CrmRecordRef = {+ type: 'company' | 'contact';+ id: string;+ name: string;+};++const recordKey = (record: CrmRecordRef) => `${record.type}:${record.id}`;++function createRecordName(record: CrmRecordRef): () => string {+ const fallback =+ record.name || (record.type === 'company' ? 'Company' : 'Contact');+ if (record.type === 'company') {+ const { company } = useCompanyQuery(() => record.id);+ return () => company()?.name ?? fallback;+ }+ const query = useContactQuery(() => record.id);+ return () => {+ const contact = query.isSuccess ? query.data : undefined;+ return contact?.name ?? contact?.email ?? fallback;+ };+}++/**+ * Records opened inside the CRM workspace. Each opened record appends a+ * breadcrumb after the originating view; reopening one already in the trail+ * returns to it.+ */+export function CrmRecordDetail(props: {+ record: CrmRecordRef;viewName: string;onClose: () => void;navigation: JSX.Element;}) {- const { query, company } = useCompanyQuery(() => props.company.id);- const companyName = () => company()?.name ?? props.company.name;- const [selectedContact, setSelectedContact] = createSignal<CompanyContact>();+ const [trail, setTrail] = createSignal<CrmRecordRef[]>([props.record]);+ const current = () => trail()[trail().length - 1];const [companySection, setCompanySection] =createSignal<CompanySection>('overview');const [contactSection, setContactSection] =createSignal<ContactSection>('overview');- const openContact = (contact: CompanyContact) => {- setContactSection('overview');- setSelectedContact(contact);+ const returnTo = (index: number) =>+ setTrail((records) => records.slice(0, index + 1));+ const open = (record: CrmRecordRef) => {+ const index = trail().findIndex(+ (entry) => recordKey(entry) === recordKey(record)+ );+ if (index !== -1) return returnTo(index);+ if (record.type === 'company') setCompanySection('overview');+ else setContactSection('overview');+ setTrail((records) => [...records, record]);};- const contactQuery = useContactQuery(() => selectedContact()?.id ?? '');- const contactName = () => {- const contact = contactQuery.isSuccess- ? contactQuery.data- : selectedContact();- return contact?.name ?? contact?.email ?? 'Contact';- };- const closeContact = () => setSelectedContact(undefined);- const activeQuery = () => (selectedContact() ? contactQuery : query);- const closeDetail = () =>- selectedContact() ? closeContact() : props.onClose();+ const back = () =>+ trail().length > 1 ? returnTo(trail().length - 2) : props.onClose();let container: HTMLDivElement | undefined;onMount(() => container?.focus());return (<ViewBreadcrumbs.Root- value={- selectedContact()- ? `contact:${selectedContact()!.id}`- : `company:${props.company.id}`- }+ value={recordKey(current())}onChange={(value) => {- if (value === 'crm-view') props.onClose();- if (value === `company:${props.company.id}`) closeContact();+ if (value === 'crm-view') return props.onClose();+ const index = trail().findIndex(+ (record) => recordKey(record) === value+ );+ if (index !== -1) returnTo(index);}}><ViewBreadcrumbs.Item@@ -83,46 +107,37 @@ export function CrmCompanyDetail(props: {</Tooltip>)}</ViewBreadcrumbs.Item>- <ViewBreadcrumbs.Item- value={`company:${props.company.id}`}- metadata={{ type: 'company', id: props.company.id }}- order={1}- >- {(item) => (- <Tooltip label={companyName()} class="min-w-0">- <ViewBreadcrumbs.Button- isActive={item.isActive()}- onClick={item.onSelect}- class="gap-1.5"+ <For each={trail()}>+ {(record, index) => {+ const name = createRecordName(record);+ return (+ <ViewBreadcrumbs.Item+ value={recordKey(record)}+ metadata={{ type: record.type, id: record.id }}+ order={index() + 1}>- <EntityIcon targetType="crm_company" size="xs" class="shrink-0" />- <span class="truncate">{companyName()}</span>- </ViewBreadcrumbs.Button>- </Tooltip>- )}- </ViewBreadcrumbs.Item>- <Show when={selectedContact()} keyed>- {(contact) => (- <ViewBreadcrumbs.Item- value={`contact:${contact.id}`}- metadata={{ type: 'contact', id: contact.id }}- order={2}- >- {(item) => (- <Tooltip label={contactName()} class="min-w-0">- <ViewBreadcrumbs.Button- isActive={item.isActive()}- onClick={item.onSelect}- class="gap-1.5"- >- <EntityIcon targetType="contact" size="xs" class="shrink-0" />- <span class="truncate">{contactName()}</span>- </ViewBreadcrumbs.Button>- </Tooltip>- )}- </ViewBreadcrumbs.Item>- )}- </Show>+ {(item) => (+ <Tooltip label={name()} class="min-w-0">+ <ViewBreadcrumbs.Button+ isActive={item.isActive()}+ onClick={item.onSelect}+ class="gap-1.5"+ >+ <EntityIcon+ targetType={+ record.type === 'company' ? 'crm_company' : 'contact'+ }+ size="xs"+ class="shrink-0"+ />+ <span class="truncate">{name()}</span>+ </ViewBreadcrumbs.Button>+ </Tooltip>+ )}+ </ViewBreadcrumbs.Item>+ );+ }}+ </For><SidePanel.Root floating defaultOpen={false}><divref={container}@@ -137,7 +152,7 @@ export function CrmCompanyDetail(props: {/><div class="min-w-0 overflow-x-auto"><Show- when={selectedContact()}+ when={current().type === 'contact'}fallback={<RecordTabssections={COMPANY_SECTIONS}@@ -154,81 +169,47 @@ export function CrmCompanyDetail(props: {</Show></div><div class="ml-auto flex shrink-0 items-center gap-1">- <CrmCopyLinkButton- type={selectedContact() ? 'contact' : 'company'}- id={selectedContact()?.id ?? props.company.id}- />+ <CrmCopyLinkButton type={current().type} id={current().id} /><SidePanel.Toggle /></div></div><div class="relative min-h-0 min-w-0 flex-1">- <Show when={selectedContact()?.id ?? props.company.id} keyed>- {(_recordId) => (- <ErrorBoundary- fallback={(error, reset) => {- console.error('Failed to render CRM record', error);- return (- <DetailError- onRetry={reset}- onClose={closeDetail}- isContact={!!selectedContact()}- />- );- }}+ <Show when={current()} keyed>+ {(record) => (+ <RecordContent+ record={record}+ nested={trail().length > 1}+ onBack={back}><Show- when={!activeQuery().isError}+ when={record.type === 'contact'}fallback={- <DetailError- onRetry={() => void activeQuery().refetch()}- onClose={closeDetail}- isContact={!!selectedContact()}+ <Company+ companyId={record.id}+ section={companySection()}+ headerToggle={false}+ onHidden={back}+ onOpenContact={(contact) =>+ open({+ type: 'contact',+ id: contact.id,+ name: contact.name ?? contact.email,+ })+ }/>}>- <Suspense- fallback={- <div class="grid size-full place-items-center text-ink-muted">- <SpinnerIcon- aria-label={- selectedContact()- ? 'Loading contact'- : 'Loading company'- }- class="size-5 animate-spin"- />- </div>- }- >- <Show- when={selectedContact()}- keyed- fallback={- <Company- companyId={props.company.id}- section={companySection()}- headerToggle={false}- onHidden={props.onClose}- onOpenContact={openContact}- />- }- >- {(contact) => (- <Contact- contactId={contact.id}- section={contactSection()}- headerToggle={false}- onOpenCompany={(companyId) => {- if (companyId !== props.company.id) return false;- closeContact();- return true;- }}- />- )}- </Show>- </Suspense>+ <Contact+ contactId={record.id}+ section={contactSection()}+ headerToggle={false}+ onOpenCompany={(companyId) => {+ open({ type: 'company', id: companyId, name: '' });+ return true;+ }}+ /></Show>- </ErrorBoundary>+ </RecordContent>)}</Show></div>@@ -238,20 +219,64 @@ export function CrmCompanyDetail(props: {);}+function RecordContent(props: {+ record: CrmRecordRef;+ nested: boolean;+ onBack: () => void;+ children: JSX.Element;+}) {+ const query =+ props.record.type === 'company'+ ? useCompanyQuery(() => props.record.id).query+ : useContactQuery(() => props.record.id);+ const error = (onRetry: () => void) => (+ <DetailError+ onRetry={onRetry}+ onBack={props.onBack}+ record={props.record.type}+ nested={props.nested}+ />+ );+ return (+ <ErrorBoundary+ fallback={(cause, reset) => {+ console.error('Failed to render CRM record', cause);+ return error(reset);+ }}+ >+ <Show when={!query.isError} fallback={error(() => void query.refetch())}>+ <Suspense+ fallback={+ <div class="grid size-full place-items-center text-ink-muted">+ <SpinnerIcon+ aria-label={`Loading ${props.record.type}`}+ class="size-5 animate-spin"+ />+ </div>+ }+ >+ {props.children}+ </Suspense>+ </Show>+ </ErrorBoundary>+ );+}+function DetailError(props: {onRetry: () => void;- onClose: () => void;- isContact: boolean;+ onBack: () => void;+ record: CrmRecordRef['type'];+ nested: boolean;}) {return (<div class="flex size-full flex-col items-center justify-center gap-3 text-sm text-ink-muted">- <p>This {props.isContact ? 'contact' : 'company'} couldn’t be loaded.</p>+ <p>This {props.record} couldn’t be loaded.</p><div class="flex gap-2"><Button variant="outline" size="sm" onClick={props.onRetry}>Try again</Button>- <Button variant="ghost" size="sm" onClick={props.onClose}>- {props.isContact ? 'Back to company' : 'Back to view'}+ <Button variant="ghost" size="sm" onClick={props.onBack}>+ {props.nested ? 'Go back' : 'Back to view'}</Button></div></div>diff --git a/apps/web/src/features/crm/views/record-row.tsx b/apps/web/src/features/crm/views/record-row.tsxnew file mode 100644index 0000000000..05ec93569a--- /dev/null+++ b/apps/web/src/features/crm/views/record-row.tsx@@ -0,0 +1,132 @@+import '@entity/composed/ListEntity.css';+import {+ SwipableRow,+ SwipableRowContext,+} from '@components/app/mobile/SwipableRow';+import { isMobile } from '@core/mobile/isMobile';+import { isTouchDevice } from '@core/mobile/isTouchDevice';+import { createEntityDraggable, Entity, unreadFilterFn } from '@entity';+import { NarrowLayout } from '@entity/composed/list-entity/narrow-layout';+import { SOUP_ROW_CLASS } from '@entity/composed/list-entity/row-geometry';+import {+ type BaseListEntityProps,+ type LayoutProps,+ useListLayout,+} from '@entity/composed/list-entity/shared';+import type { EntityRowConfig } from '@entity/extractors-notification';+import { mergeRefs } from '@solid-primitives/refs';+import { cn } from '@ui/utils/classname';+import {+ type Component,+ type JSX,+ Match,+ Show,+ Switch,+ useContext,+} from 'solid-js';+import { Dynamic } from 'solid-js/web';+import { useCrmContext } from '../context/crm-context';++function MaybeEntityRow(props: {+ entityId: string;+ children: JSX.Element;+ config?: EntityRowConfig;+}) {+ const ctx = useContext(SwipableRowContext);+ return (+ <Show when={isMobile() && ctx} fallback={props.children}>+ <SwipableRow+ id={props.entityId}+ swipeLeftColor={props.config?.swipeLeftColor}+ swipeLeftRevealedComponent={props.config?.swipeLeftRevealedComponent}+ swipeRightColor={props.config?.swipeRightColor}+ swipeRightRevealedComponent={props.config?.swipeRightRevealedComponent}+ >+ {props.children}+ </SwipableRow>+ </Show>+ );+}++/**+ * CRM list row: selection, drag, and swipe chrome around a record-specific+ * grid layout whose columns line up across rows, mirroring `TaskListEntity`.+ */+export function CrmListRow(+ props: BaseListEntityProps & { layout: Component<LayoutProps> }+) {+ const unread = () => unreadFilterFn(props.entity);++ const layoutProps = (): LayoutProps => ({+ entity: props.entity,+ checked: props.checked,+ hideCheckbox: props.hideCheckbox,+ onChecked: props.onChecked,+ unread: unread(),+ isShared: false,+ hasNotifications: false,+ showHitSnippet: false,+ streamState: undefined,+ setSnippetContainerRef: () => {},+ chars: 0,+ onProjectClick: props.onProjectClick,+ });++ const draggable = createEntityDraggable({+ entity: props.entity,+ splitId: useCrmContext().createNavigation().splitId,+ deferUntilInteraction: () => props.deferInteractions === true,+ });++ const isWide = useListLayout()?.isWide ?? (() => true);++ return (+ <Entity.Root+ entity={props.entity}+ onClick={(e) => {+ if (e.metaKey && props.onChecked) {+ props.onChecked(!props.checked, e.shiftKey);+ return;+ }+ props.onClick?.(e);+ }}+ ref={mergeRefs(props.ref, draggable)}+ class={cn(+ // Carries the --soup-row-* geometry (ListEntity.css) that the narrow+ // layout below reads for its leading edge.+ isWide() ? SOUP_ROW_CLASS.wide : SOUP_ROW_CLASS.narrow,+ 'soup-list-entity @container/entity w-[calc(100%-0.5rem)] mr-1 relative group/narrow flex flex-col py-0.5 rounded-xl',+ {+ 'min-h-10 mx-(--soup-row-gutter)': !isMobile(),+ 'bg-list-selected': props.checked,+ 'bg-list-selected-highlighted':+ props.checked && props.highlighted && !isTouchDevice(),+ 'bg-list-highlighted':+ props.highlighted && !props.checked && !isTouchDevice(),+ 'hover:bg-list-hover':+ !props.highlighted && !props.checked && !isTouchDevice(),+ }+ )}+ onMouseMove={props.onMouseMove}+ >+ <Switch>+ <Match when={isWide()}>+ <MaybeEntityRow+ entityId={props.entity.id}+ config={props.entityRowConfig}+ >+ <Dynamic component={props.layout} {...layoutProps()} />+ </MaybeEntityRow>+ </Match>+ <Match when={true}>+ <MaybeEntityRow+ entityId={props.entity.id}+ config={props.entityRowConfig}+ >+ <NarrowLayout {...layoutProps()} />+ </MaybeEntityRow>+ </Match>+ </Switch>+ </Entity.Root>+ );+}diff --git a/apps/web/src/features/crm/views/saved-views-menu.tsx b/apps/web/src/features/crm/views/saved-views-menu.tsxindex 4c6eb55325..2ec2a5084d 100644--- a/apps/web/src/features/crm/views/saved-views-menu.tsx+++ b/apps/web/src/features/crm/views/saved-views-menu.tsx@@ -117,7 +117,6 @@ export function CompanyViewsMenu(props: { hideLabel?: boolean } = {}) {stageFilter,ownerFilter,activeTab,- viewMode,} = useCrmWorkspace();const personal = usePersonalCrmViews();const team = useTeamCrmViews();@@ -142,7 +141,6 @@ export function CompanyViewsMenu(props: { hideLabel?: boolean } = {}) {searchText: searchText(),groupBy: soup.grouping.activeGroupId() ?? null,sort: soup.sort.active().map((s) => s.id),- viewMode: viewMode(),stageFilter: [...stageFilter()],ownerFilter: [...ownerFilter()],activeTab: activeTab(),@@ -322,71 +320,56 @@ export function CompanyViewsMenu(props: { hideLabel?: boolean } = {}) {*/export function CompanyDisplayMenu() {const { options, toggleListColumn } = useCrmDisplayOptions();- const { activeTab, viewMode } = useCrmWorkspace();+ const { activeTab } = useCrmWorkspace();const { applyTabPreset } = useApplyPreset();const isTeamAdmin = useIsTeamAdmin();const showingHidden = () => activeTab() === 'hidden';- // On the board, the menu holds only the admin-gated hidden toggle — hide- // the trigger entirely when there'd be nothing to show.- const hasContent = () => viewMode() === 'list' || isTeamAdmin();-return (- <Show when={hasContent()}>- <Dropdown>- <Tooltip label="Display options">- <Dropdown.Trigger- depth={2}- class="bg-surface"- label="Display options"- >- <SlidersIcon />- </Dropdown.Trigger>- </Tooltip>+ <Dropdown>+ <Tooltip label="Display options">+ <Dropdown.Trigger depth={2} class="bg-surface" label="Display options">+ <SlidersIcon />+ </Dropdown.Trigger>+ </Tooltip>- <Dropdown.Content class="w-56">- {/* Column visibility only applies to the list. */}- <Show when={viewMode() === 'list'}>- <Dropdown.Group>- <Dropdown.GroupLabel>List columns</Dropdown.GroupLabel>- <For- each={Object.keys(CRM_LIST_COLUMN_LABELS) as CrmListColumnId[]}- >- {(column) => (- <Dropdown.CheckboxItem- checked={options().listColumns[column]}- onChange={() => toggleListColumn(column)}- closeOnSelect={false}- >- <span class="flex-1 truncate">- {CRM_LIST_COLUMN_LABELS[column]}- </span>- </Dropdown.CheckboxItem>- )}- </For>- </Dropdown.Group>- </Show>- {/* Admin/owner only — the BE rejects hidden-set requests from- non-admins, matching the old Hidden tab's gating. */}- <Show when={isTeamAdmin()}>- <Dropdown.Group>+ <Dropdown.Content class="w-56">+ <Dropdown.Group>+ <Dropdown.GroupLabel>List columns</Dropdown.GroupLabel>+ <For each={Object.keys(CRM_LIST_COLUMN_LABELS) as CrmListColumnId[]}>+ {(column) => (<Dropdown.CheckboxItem- checked={showingHidden()}- onChange={() =>- applyTabPreset(- 'companies',- showingHidden() ? 'active' : 'hidden'- )- }+ checked={options().listColumns[column]}+ onChange={() => toggleListColumn(column)}closeOnSelect={false}>- <span class="flex-1 truncate">Show hidden companies</span>+ <span class="flex-1 truncate">+ {CRM_LIST_COLUMN_LABELS[column]}+ </span></Dropdown.CheckboxItem>- </Dropdown.Group>- </Show>- </Dropdown.Content>- </Dropdown>- </Show>+ )}+ </For>+ </Dropdown.Group>+ {/* Admin/owner only — the BE rejects hidden-set requests from+ non-admins, matching the old Hidden tab's gating. */}+ <Show when={isTeamAdmin()}>+ <Dropdown.Group>+ <Dropdown.CheckboxItem+ checked={showingHidden()}+ onChange={() =>+ applyTabPreset(+ 'companies',+ showingHidden() ? 'active' : 'hidden'+ )+ }+ closeOnSelect={false}+ >+ <span class="flex-1 truncate">Show hidden companies</span>+ </Dropdown.CheckboxItem>+ </Dropdown.Group>+ </Show>+ </Dropdown.Content>+ </Dropdown>);}diff --git a/apps/web/src/features/crm/views/use-crm.ts b/apps/web/src/features/crm/views/use-crm.tsindex 607fe61149..65db239a89 100644--- a/apps/web/src/features/crm/views/use-crm.ts+++ b/apps/web/src/features/crm/views/use-crm.ts@@ -20,9 +20,6 @@ export const useCrmPermissions = (export const useDealStages = (...args: Parameters<CrmContext['createDealStages']>) => useCrmContext().createDealStages(...args);-export const useCrmUnavailable = (- ...args: Parameters<CrmContext['createUnavailable']>-) => useCrmContext().createUnavailable(...args);export const useClosedStageIds = (...args: Parameters<CrmContext['createClosedStageIds']>) => useCrmContext().createClosedStageIds(...args);diff --git a/apps/web/src/features/crm/workspace-adapter.tsx b/apps/web/src/features/crm/workspace-adapter.tsxindex a68b81e993..edce303490 100644--- a/apps/web/src/features/crm/workspace-adapter.tsx+++ b/apps/web/src/features/crm/workspace-adapter.tsx@@ -1,7 +1,6 @@import { usePreference } from '@app/preferences/use-preference';import { useSplitPanelOrThrow } from '@components/app/split-layout/layoutUtils';import { useSettingsState } from '@core/constant/SettingsState';-import { isTouchDevice } from '@core/mobile/isTouchDevice';import { idToDisplayName } from '@core/user/util';import { type EntityData, isCrmCompanyEntity } from '@entity';import { COMPANY_STAGE_OPTIONS } from '@entity/utils/task-properties';@@ -72,7 +71,7 @@ export function createCrmWorkspace(}),selectFilters: filters.facets,groupOptions: {- visible: () => filters.state.viewMode() === 'list',+ visible: () => true,options: COMPANY_GROUP_OPTIONS,},},@@ -174,9 +173,6 @@ export function createCrmWorkspace(if (owners.length > 0 !== soup.predicates.isActive('company-owner')) {soup.predicates.toggle({ and: ['company-owner'] });}- soupView.setViewMode(- initialCrmView.viewMode ?? (isTouchDevice() ? 'list' : 'board')- );}});});diff --git a/apps/web/src/features/database/components/database-toolbar.test.tsx b/apps/web/src/features/database/components/database-toolbar.test.tsxindex 2c2788ccf0..da787054dd 100644--- a/apps/web/src/features/database/components/database-toolbar.test.tsx+++ b/apps/web/src/features/database/components/database-toolbar.test.tsx@@ -106,6 +106,43 @@ describe('database toolbar views', () => {expect(select).toHaveBeenLastCalledWith();});+ it('shows a host action after the view controls', () => {+ const view: DatabaseView = {+ id: 'table',+ databaseId: 'database',+ tableId: 'table',+ name: 'All records',+ position: '80',+ query: { filter: null, sort: [] },+ layout: { kind: 'table', columns: [] },+ createdAt: '2026-09-01T00:00:00Z',+ updatedAt: '2026-09-01T00:00:00Z',+ };+ const add = vi.fn();+ render(() => (+ <DatabaseToolbar+ columns={[]}+ views={[]}+ view={view}+ canEdit+ onSelectView={vi.fn()}+ onChangeView={vi.fn()}+ onCreateView={vi.fn(() => okAsync(undefined))}+ onRenameView={vi.fn(() => okAsync(undefined))}+ onShowViewAs={vi.fn()}+ onDeleteView={vi.fn(() => okAsync(undefined))}+ actions={+ <button type="button" onClick={add}>+ Add company+ </button>+ }+ />+ ));+ fireEvent.click(screen.getByRole('button', { name: 'Add company' }));+ expect(add).toHaveBeenCalledOnce();+ expect(screen.queryByRole('button', { name: 'New record' })).toBeNull();+ });+it('renames a view inline from a double click, saving on Enter', async () => {const rename = vi.fn(() => okAsync(undefined));const select = vi.fn();diff --git a/apps/web/src/features/database/components/database-toolbar.tsx b/apps/web/src/features/database/components/database-toolbar.tsxindex a070cb9588..1df1a8f2be 100644--- a/apps/web/src/features/database/components/database-toolbar.tsx+++ b/apps/web/src/features/database/components/database-toolbar.tsx@@ -69,11 +69,13 @@ type DatabaseToolbarProps = {view: DatabaseView,layout: ShownLayout) => ResultAsync<void, DatabaseOpFailure>;- /** Every stored view of the table, in its new order. */- onReorderViews: (order: string[]) => void;+ /** Every stored view of the table, in its new order; omitted when the host cannot store an order. */+ onReorderViews?: (order: string[]) => void;onCreateRecord?: () => void;canCreateRecord?: boolean;creating?: boolean;+ /** The host's own actions after the view controls, e.g. a labelled create button. */+ actions?: JSX.Element;};/** View controls contain no data fetching or mutation implementation. */@@ -137,7 +139,7 @@ export function DatabaseToolbar(props: DatabaseToolbarProps) {const order = props.views.map((view) => view.id);const moved = movedViewOrder(order, id, targetId);if (moved.some((view, index) => view !== order[index]))- props.onReorderViews(moved);+ props.onReorderViews?.(moved);}return (<div@@ -175,6 +177,7 @@ export function DatabaseToolbar(props: DatabaseToolbarProps) {view={view()}selected={props.selectedViewId === view().id}canEdit={props.canEdit}+ canReorder={props.canEdit && !!props.onReorderViews}renaming={viewRename.target()?.id === view().id}renameDraft={viewRename.draft()}renamePending={viewRename.pending()}@@ -331,6 +334,7 @@ export function DatabaseToolbar(props: DatabaseToolbarProps) {</Show></Button></Show>+ {props.actions}</div></div></div>@@ -375,6 +379,7 @@ function ViewTab(props: {view: DatabaseView;selected: boolean;canEdit: boolean;+ canReorder: boolean;renaming: boolean;renameDraft: string;renamePending: boolean;@@ -435,7 +440,7 @@ function ViewTab(props: {<ContextMenu.Triggeras="button"type="button"- {...(props.canEdit ? sortable.dragActivators : {})}+ {...(props.canReorder ? sortable.dragActivators : {})}data-view-id={props.view.id}aria-pressed={props.selected}aria-keyshortcuts={props.canEdit ? 'F2 Shift+F10' : undefined}diff --git a/apps/web/src/features/next-soup/filters/configs/entity.ts b/apps/web/src/features/next-soup/filters/configs/entity.tsindex 072ae15b10..45fe37fd7d 100644--- a/apps/web/src/features/next-soup/filters/configs/entity.ts+++ b/apps/web/src/features/next-soup/filters/configs/entity.ts@@ -2,6 +2,7 @@ export {crmCompanyActiveFilter,crmCompanyFilter,crmCompanyHiddenFilter,+ crmContactActiveFilter,} from '../../../crm/collection-filters';import { getEntityProjectId } from '@entity';diff --git a/apps/web/src/features/next-soup/filters/configs/index.ts b/apps/web/src/features/next-soup/filters/configs/index.tsindex c8b13b35fb..3bd897f903 100644--- a/apps/web/src/features/next-soup/filters/configs/index.ts+++ b/apps/web/src/features/next-soup/filters/configs/index.ts@@ -38,6 +38,7 @@ import {crmCompanyActiveFilter,crmCompanyFilter,crmCompanyHiddenFilter,+ crmContactActiveFilter,documentOrFileFilter,filesAndFolderFilter,foldersFilter,@@ -98,6 +99,7 @@ export const SOUP_FILTERS = [crmCompanyFilter,crmCompanyActiveFilter,crmCompanyHiddenFilter,+ crmContactActiveFilter,companyOwnerFilter,companyNeedsFollowUpFilter,companyRecentlyActiveFilter,diff --git a/apps/web/src/features/next-soup/filters/filter-store/compile.test.ts b/apps/web/src/features/next-soup/filters/filter-store/compile.test.tsindex 35e25fff63..2d72a52ceb 100644--- a/apps/web/src/features/next-soup/filters/filter-store/compile.test.ts+++ b/apps/web/src/features/next-soup/filters/filter-store/compile.test.ts@@ -182,6 +182,24 @@ describe('compileToAst', () => {});});+ it('opts into CRM contacts only through contact filters, excluding every other type', () => {+ const query = defineQueryFilters(+ { include: { crmContactHidden: false, crmContactSearch: 'ada' } },+ { skipTargets: ['crmf'] }+ );+ const ast = compileToAst(queryStateFrom(query));++ expect(ast.crmf).toEqual({+ '&': [{ l: { hidden: false } }, { l: { search: 'ada' } }],+ });+ expect(ast.ccf).toEqual({ l: { id: NIL_UUID } });+ expect(ast.df).toEqual({ l: { id: NIL_UUID } });+ // Contacts are opt-in, so queries that never mention them carry no crmf.+ expect(compileToAst(queryStateFrom(defineQueryFilters({}))).crmf).toBe(+ undefined+ );+ });+it('compiles channel message thread ids onto regular channel filters', () => {const ast = compileToAst(queryStateFrom({diff --git a/apps/web/src/features/next-soup/filters/filter-store/compile.ts b/apps/web/src/features/next-soup/filters/filter-store/compile.tsindex f7c597feb3..9caadce9a0 100644--- a/apps/web/src/features/next-soup/filters/filter-store/compile.ts+++ b/apps/web/src/features/next-soup/filters/filter-store/compile.ts@@ -30,6 +30,7 @@ type QueryTarget =| 'callf'| 'fef'| 'ccf'+ | 'crmf'| 'asf'| 'propf';@@ -167,6 +168,8 @@ const FIELD_CONFIG: Record<foreignEntityIncludesMe: { target: 'fef', field: 'me', unit: true },crmCompanyId: { target: 'ccf', field: 'id' },crmCompanyHidden: { target: 'ccf', field: 'hidden' },+ crmContactHidden: { target: 'crmf', field: 'hidden' },+ crmContactSearch: { target: 'crmf', field: 'search' },agentSessionId: { target: 'asf', field: 'id' },agentSessionOwnerId: { target: 'asf', field: 'o' },includeAgentSessions: { target: 'asf', field: 'inc', unit: true },@@ -230,6 +233,7 @@ const emptyTargetAstLists = (): Record<QueryTarget, BackendAst[]> => ({callf: [],fef: [],ccf: [],+ crmf: [],asf: [],propf: [],});diff --git a/apps/web/src/features/next-soup/filters/filter-store/types.ts b/apps/web/src/features/next-soup/filters/filter-store/types.tsindex 3a63b8dc20..77f106ebf0 100644--- a/apps/web/src/features/next-soup/filters/filter-store/types.ts+++ b/apps/web/src/features/next-soup/filters/filter-store/types.ts@@ -101,6 +101,9 @@ export type ScalarFieldFilters = {callStatus?: CallStatus;callAttended?: boolean;crmCompanyHidden?: boolean;+ crmContactHidden?: boolean;+ /** Literal text matched against a CRM contact's name or email. */+ crmContactSearch?: string;calendarEventSeen?: boolean;calendarEventDone?: boolean;includeAgentSessions?: boolean;diff --git a/apps/web/src/lib/constants/list-views.ts b/apps/web/src/lib/constants/list-views.tsindex 6f760c8755..d1cf9e3e4a 100644--- a/apps/web/src/lib/constants/list-views.ts+++ b/apps/web/src/lib/constants/list-views.ts@@ -116,7 +116,11 @@ export const soupItemMatchesListView = ('recent',() => item.touched_at != null || hasOwnTouchFloor(soupItemEntityId(item)))- .with('companies', () => item.tag === 'crmCompany')+ // Customers lists companies and, on its People tab, contacts.+ .with(+ 'companies',+ () => item.tag === 'crmCompany' || item.tag === 'crmContact'+ ).exhaustive();const propertiesMatchTagFilter = (diff --git a/apps/web/src/lib/queries/email/local-draft-source.test.ts b/apps/web/src/lib/queries/email/local-draft-source.test.tsindex 95612a133c..2595827105 100644--- a/apps/web/src/lib/queries/email/local-draft-source.test.ts+++ b/apps/web/src/lib/queries/email/local-draft-source.test.ts@@ -5,6 +5,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';const runtime = vi.hoisted(() => ({list: vi.fn<() => Promise<LocalDraft[]>>(),listeners: new Set<() => void>(),+ cacheListeners: new Set<(event: { query: { queryHash: string } }) => void>(),}));vi.mock('./local-drafts', () => ({listLocalDrafts: runtime.list,@@ -16,9 +17,17 @@ vi.mock('./local-drafts', () => ({},}));vi.mock('../client', () => ({- queryClient: { getQueryCache: () => ({ subscribe: () => () => {} }) },+ queryClient: {+ getQueryCache: () => ({+ subscribe(listener: (event: { query: { queryHash: string } }) => void) {+ runtime.cacheListeners.add(listener);+ return () => runtime.cacheListeners.delete(listener);+ },+ }),+ },}));+import { authKeys } from '../auth/keys';import {createLocalDraftSource,localDraftEntities,@@ -43,9 +52,32 @@ const draft = (overrides: Partial<LocalDraft> = {}): LocalDraft => ({beforeEach(() => {runtime.list.mockReset();runtime.listeners.clear();+ runtime.cacheListeners.clear();});describe('local draft discovery', () => {+ it('never reads view state synchronously from a notification, and skips refreshes once disposed', async () => {+ runtime.list.mockResolvedValue([]);+ const enabled = vi.fn(() => true);+ const dispose = createRoot((dispose) => {+ createLocalDraftSource(enabled);+ return dispose;+ });+ await Promise.resolve();+ enabled.mockClear();+ // Query observers are removed, and notify, while Solid disposes the view.+ const userInfo = {+ query: { queryHash: JSON.stringify(authKeys.userInfo.queryKey) },+ };+ for (const listener of runtime.cacheListeners) listener(userInfo);+ for (const listener of runtime.listeners) listener();+ expect(enabled).not.toHaveBeenCalled();+ dispose();+ await Promise.resolve();+ expect(enabled).not.toHaveBeenCalled();+ expect(runtime.cacheListeners.size).toBe(0);+ });+it('does not touch draft storage in REST mode and ignores a late result after disabling', async () => {let resolve!: (drafts: LocalDraft[]) => void;runtime.list.mockReturnValue(@@ -83,6 +115,8 @@ describe('local draft discovery', () => {expect(state.source.drafts()).toEqual([]);runtime.list.mockResolvedValue([draft()]);for (const listener of runtime.listeners) listener();+ // One tick for the deferred refresh, one for the listing it awaits.+ await Promise.resolve();await Promise.resolve();expect(state.source.drafts()[0].content.subject).toBe('Recover me');} finally {diff --git a/apps/web/src/lib/queries/email/local-draft-source.ts b/apps/web/src/lib/queries/email/local-draft-source.tsindex a39e58650c..5ea063fad0 100644--- a/apps/web/src/lib/queries/email/local-draft-source.ts+++ b/apps/web/src/lib/queries/email/local-draft-source.ts@@ -38,12 +38,16 @@ export function createLocalDraftSource(enabled: Accessor<boolean>) {if (!disposed && request === generation) setReady(true);}};- const unsubscribe = localDraftStore.subscribe(() => {- void refresh();- });+ // Notifications can arrive mid-disposal (an observer removed by navigation),+ // where reading `enabled` re-runs the disposing owner's stale memos.+ const scheduleRefresh = () =>+ queueMicrotask(() => {+ if (!disposed) void refresh();+ });+ const unsubscribe = localDraftStore.subscribe(scheduleRefresh);const auth = queryClient.getQueryCache().subscribe((event) => {if (event.query.queryHash === JSON.stringify(authKeys.userInfo.queryKey))- void refresh();+ scheduleRefresh();});onCleanup(() => {disposed = true;diff --git a/docs/AGENT_GUIDE/navigation.md b/docs/AGENT_GUIDE/navigation.mdindex b68ecffe09..91c9c62d4a 100644--- a/docs/AGENT_GUIDE/navigation.md+++ b/docs/AGENT_GUIDE/navigation.md@@ -491,10 +491,8 @@ directly in the sheet without replacing the current view or changing its URL.If a requested section is unavailable, the sheet shows an unavailable messageand a **Back to settings** button that returns to the grouped main page.-Fresh mobile CRM visits default to list view, including when-applying a default saved view; explicitly selected saved views and back/forward-navigation retain their layout. The mobile **+ Company** button opens the-company-creation sheet.+CRM Companies and People are list-only on every device. The mobile+**+ Company** button opens the company-creation sheet.The labeled glass button one row above Search opens the current page's creationflow directly: **+ Task** on Tasks, **+ Email** on Email, **+ Message** on Channels,diff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.mdindex 292b7b99b0..a4ac805449 100644--- a/docs/AGENT_GUIDE/surfaces.md+++ b/docs/AGENT_GUIDE/surfaces.md@@ -1878,47 +1878,51 @@ joining a standalone call never makes its content available to the wider team.## Customers (CRM) — `/app/component/companies`On desktop, the local sidebar uses the same navigation primitives as Email and Tasks.-Board and List share a horizontal segmented toggle at the top of the sidebar; the-main header has no layout toggle. People lists contacts across every CRM-enabled-team the viewer belongs to. Duplicate full email addresses (case-insensitive)-collapse to the visible contact with the most recent interaction; ties use the-contact ID. Each team's record and existing contact links remain separate. Hidden-contacts and contacts under hidden companies are excluded. The directory supports-name/email search and sorting, and its navigation remains available on touch devices.-Company views include All companies, My companies-(Owner = current user), Needs follow-up (has a stage other than Churned and last-interaction at least 14 days ago),-Recently active (team email activity within 7 days), and Unassigned (no Owner). Existing personal/team-saved views also appear under Views. Stages remain board columns or list properties.-Board/List switches the representation without changing the selected set.-Recently active uses the CRM last-interaction timestamp, advanced by sent and received-email. It does not count company @mentions or chat discussions. Manually created-companies initialize that timestamp to creation time, so newly added companies may-also appear before any email; the sidebar hover tooltip discloses this limitation.-View descriptions appear in sidebar tooltips, not above the main board or list.-The `Search companies` field uses the shared Email/Tasks search bar. Command-F-focuses it, `Clear search` resets it, and Escape leaves the field.--On touch devices, Customers uses the same full-frame list layout as the other-mobile views: floating CRM-navigation and filter buttons with Board/List pills,-List as the fresh default, and the global **+ Company** action above the dock.-The navigation button opens the CRM views and lists; the desktop toolbar and-embedded detail stack stay out of the mobile flow, so selecting a row navigates-in place.--On desktop, clicking a company in Board or List (or pressing Enter on a focused list row)-opens its details inside the CRM workspace, keeping the left navigation visible.-The top breadcrumb reads `<current view or list> > <company>`; click the first-segment to return with the same filters, layout, and list scroll position. Selecting-another sidebar view or switching Board/List closes the company details.-Shift-click still opens the company in a separate split. Direct company links use-the standalone company page.-Clicking a contact in an embedded company's Team tab appends a third-breadcrumb: `<current view or list> > <company> > <contact>`. The CRM sidebar stays-visible. Click the company breadcrumb or the contact's Company link to return to-the company; click the first breadcrumb to return directly to the originating-view. Shift-click still opens a contact in a separate split. Direct contact links-use the standalone contact page.+Its **New** menu creates a **Company**, a **Contact**, or a **Pipeline** (Pipeline+only when pipelines are enabled; disabled until the team's CRM is enabled). The+**Records** section lists **Companies** and **People**; Pipelines and Lists follow.+There are no built-in company views or Board/List layout: Companies and People+are plain soup lists with the shared pagination. Existing personal/team saved+views stay in the toolbar's Views menu.++Companies lists every visible company, grouped by Stage by default, with Owner,+Revenue and Last Interaction columns. Its toolbar holds sort, group, filter,+display options, saved views, and **New company** at the right end.++People lists contacts across every CRM-enabled team the viewer belongs to, from+the same Soup query with only CRM contacts opted in (`crmf`). The server collapses+duplicate full email addresses (case-insensitive) to one contact. Hidden contacts+and contacts under hidden companies are excluded. Columns are Person (name and+email), Company and Last contacted (sortable). `Search people` matches name or+email on the server after a short typing pause, so results include contacts not+yet scrolled into view. **New contact** sits at the right end of the toolbar. Its+dialog asks for a company (searchable by name or domain, from the up to 500 most+relevant companies with a domain) and fixes the email to that company's primary+domain; **Add contact** on a company's Team tab skips the company field.++`Search companies` and `Search people` use the shared Email/Tasks search bar.+Command-F focuses it, `Clear search` resets it, and Escape leaves the field.++On touch devices, Companies uses the same full-frame list layout as the other+mobile views: floating CRM-navigation and filter buttons and the global+**+ Company** action above the dock. People keeps its title row, search and+**New contact**. The navigation button opens the CRM records, pipelines and+lists; the embedded detail stack stays out of the mobile flow, so selecting a+row navigates in place.++On desktop, clicking a company or a person in the list (or pressing Enter on a+focused row) opens its details inside the CRM workspace, keeping the left+navigation visible. The top breadcrumb reads `<Companies, People or list> >+<record>`; click the first segment to return with the same filters and list+scroll position. Selecting another sidebar entry closes the details. Shift-click+still opens the record in a separate split. Direct company and contact links use+the standalone pages.+Each record opened from the details appends a breadcrumb: a contact from a+company's Team tab gives `Companies > <company> > <contact>`, and a person's+Company link gives `People > <contact> > <company>`. Opening a record already in+the trail (such as the contact's own company from `Companies > <company> >+<contact>`) returns to it instead of adding a duplicate. The CRM sidebar stays+visible throughout.Company and contact headers have `Copy link` beside the side-panel toggle.Their information panel starts closed and opens as a floating bubble at everywidth, without shrinking the record content. Click outside the bubble or use@@ -1958,7 +1962,7 @@ editors without changing hosted data.`Collapse CRM sidebar` persists across visits; `Expand CRM sidebar` restores it.At narrow widths, `Show CRM navigation` opens the same navigation in a menu.-The sidebar's Views and Lists sections can also collapse independently.+The sidebar's Records and Lists sections can also collapse independently.**Pipelines** in the CRM sidebar hold company or contact entries in the sharedrecords editor. They have their own identity, ownership and sharing; their@@ -1985,13 +1989,25 @@ company's CRM fields. Use **Add column** or a column header's menu to customizecolumns. Pipeline Stage options initially copy the team's current deal stages. Openpipelines refresh other editors' changes periodically; a local edit refreshesimmediately after saving.+A pipeline page uses the database page's styling with one table and no table+tabs. Its header shows the name, edited in place by editors, a **Pipeline+actions** menu (**Rename**; **Trash pipeline** for the owner) and **Share**. The+toolbar below has **All records**, the pipeline's stored views and **New view**+(Table or Board), plus Group by (boards), Filter and Sort, then **Add company**+or **Add contact** (by the pipeline's record type) for editors, which starts a+row whose reference cell picks the record.+Stored views are everyone's and are written through the pipeline, so changing one+changes it for all viewers; All records is each viewer's own. A board can move a+card to another group from its card menu or by dragging, which sets the row's+grouping cell. Card order within a group is not read back after a reload, and+views cannot be reordered yet. The selected view is remembered per pipeline.**Trash pipeline** removes its table from navigation without deleting the linked-companies or contacts. **Back to companies** returns to the main CRM views.+companies or contacts, then returns to Companies.CRM lists are currently disabled by `enableCrmLists` (default `false`). The sidebarLists section, list editor, and company membership controls only mount when enabled.Existing list data is preserved; a restored list view returns to All companies while-disabled. Board/List layout and saved filter views remain available.+disabled. Saved filter views remain available.When enabled, lists are personal, team-scoped collections of explicit company IDs, persisted throughsaved-view storage separately from saved filter views. `New list` opens a name anddiff --git a/docs/AGENT_GUIDE/view-tours.md b/docs/AGENT_GUIDE/view-tours.mdindex ec1108e88b..72bb1e9a1c 100644--- a/docs/AGENT_GUIDE/view-tours.md+++ b/docs/AGENT_GUIDE/view-tours.md@@ -40,7 +40,8 @@ and highlights.- **Channels:** channels and DMs, creation, then threads, @mentions, and calls,which wait on the channel list until a conversation is open. No Slack action.- **Email:** Signal/Noise, tags, then keyboard shortcuts.-- **Customers:** Board/List, relationship details, then company views.+- **Customers:** Companies and People records, relationship details, then the+ **New** menu.- **Calendar:** calendar sources and copy availability (beacon on the sidebartoggle while the sidebar is collapsed), calendar periods, then event details.- **Tasks:** also offers Import from Linear, which opens the CSV importer.