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
fix(crm): add admin discovery for removed people (#9505)
gbirman1f9b71da949e
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex 2c6aaa6eb3..fbe5d1695a 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -411,6 +411,11 @@ resolved session ID; keep the existing `AgentSessionProvider` subscription to`src/features/crm/README.md` and `docs/agent-guide/crm.md` at the repo root.Company Team lists exclude hidden contacts for every role; keep authorizeddetail/restore access and invalidate embedded company contacts on hide/restore.+ People display options expose removed records only after an explicit admin/owner+ choice scoped to the current team; query hidden state on the server before+ pagination, reset the choice on session/team/role/list changes, and refresh+ mounted GraphQL contact readers after visibility mutations. Exercise discovery+ with `bunx playwright test --config src/features/crm/browser-test/people/playwright.config.ts`.The backend-free desktop/phone regression uses real CRM query adapters:`bunx playwright test --config src/features/crm/browser-test/team/playwright.config.ts`.- Main Tasks mounts reusable GraphQL saved views; keep embedded Project/CRM task lists unchanged. Read `src/features/tasks-view/AGENTS.md` for filter, draft, navigation, and browser checks.diff --git a/apps/web/src/features/crm/README.md b/apps/web/src/features/crm/README.mdindex 8e7e19f38c..51d870e57b 100644--- a/apps/web/src/features/crm/README.md+++ b/apps/web/src/features/crm/README.md@@ -64,7 +64,24 @@ Company Team lists filter hidden contacts for every role without changing theunderlying response or admin detail access. Contact visibility mutations invalidatethe company query family because those responses embed contacts: mounted listsrefetch before completion, and inactive lists reload when revisited. No company ID-is required, so unfiled contacts use the same mutation safely.+is required, so unfiled contacts use the same mutation safely. Contact visibility+also awaits explicit refresh of mounted GraphQL contact lists; normalized-record+eviction and TanStack invalidation alone cannot refresh their membership.++People display options offer **Show removed people** only for current-team+admins/owners. `people-visibility` owns a local explicit choice, resets it on+account/team/role/list changes, and sanitizes shared or persisted filters.+Retained team data preserves the choice through a background refetch error;+current-user membership and admin/owner checks still apply.+Removed mode queries `crmf` with hidden=true and the administered team ID, using+the existing server search, deduplication and cursor pagination. The client+predicate also checks that team scope so retained rows cannot cross the display+boundary. Normal People remains viewer-wide and hidden=false. Removed mode+includes effective hidden state from a hidden parent company; restoring a+contact does not restore its company. No-company contacts remain supported.+`browser-test/people` uses the production filter compiler, predicates, GraphQL+live page source, display controls and eye confirmation with a synthetic API;+cache-host persistence and full app routing remain outside that fixture.`browser-test/team` exercises the real Team component, visibility action and queryadapters with a synthetic storage client on desktop and phone; entity row metadataand app navigation are isolated. Run its `playwright.config.ts` from `apps/web`.@@ -72,6 +89,8 @@ Both hidden mutations emit `crm.visibility_change` through request and cacherefresh completion, with the opaque record ID, record type, requested hiddenstate, and outcome. `crm.visibility_change.refresh` times cache invalidation andthe dependent query refreshes before the mutation stops being pending.+`crm.people_visibility` measures the display choice through the next paint;+Soup retains its existing query/loading instrumentation.`task-composer.ts` owns the CRM task preset: Companies/Contacts are visible,Status remains a task default but is not initially shown. CRM registers livediff --git a/apps/web/src/features/crm/browser-test/people/entity-preview.ts b/apps/web/src/features/crm/browser-test/people/entity-preview.tsnew file mode 100644index 0000000000..ebd508f7a0--- /dev/null+++ b/apps/web/src/features/crm/browser-test/people/entity-preview.ts@@ -0,0 +1,2 @@+// Collection tests exercise contact predicates; company-only metadata is outside this fixture.+export const getCompanyOwnerId = () => undefined;diff --git a/apps/web/src/features/crm/browser-test/people/fixture.tsx b/apps/web/src/features/crm/browser-test/people/fixture.tsxnew file mode 100644index 0000000000..cb06a7fe36--- /dev/null+++ b/apps/web/src/features/crm/browser-test/people/fixture.tsx@@ -0,0 +1,312 @@+import type { FilterContext } from '@app/features/next-soup/filters/configs/base';+import type { PredicateConfig } from '@app/features/next-soup/filters/filter-store/predicates-store';+import type { EntityData } from '@entity';+import '../../../../index.css';+import { SearchBar } from '@app/components/view-shell';+import { isTouchDevice } from '@core/mobile/isTouchDevice';+import { registerActiveGraphqlSoupQuery } from '@queries/soup/graphql/active-queries';+import { makeGraphqlSoupInput } from '@queries/soup/graphql/ast';+import { createSoupLiveQuery } from '@queries/soup/graphql/create-soup-live-query';+import { storageServiceClient } from '@service-storage/client';+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';+import { Button } from '@ui';+import { createSignal, For, onCleanup, Show, Suspense } from 'solid-js';+import { render } from 'solid-js/web';+import { createPredicatesStore } from '../../../next-soup/filters/filter-store/predicates-store';+import { createQueryStore } from '../../../next-soup/filters/filter-store/query-store';+import {+ crmContactActiveFilter,+ crmContactHiddenFilter,+} from '../../collection-filters';+import {+ PeopleDisplayMenu,+ RemovedPeopleNotice,+} from '../../components/people-display-menu';+import { RecordVisibilityAction } from '../../components/record-visibility-action';+import {+ bindPeopleVisibility,+ createPeopleVisibility,+} from '../../primitives/people-visibility';+import {+ useContactQuery,+ useSetContactHiddenMutation,+} from '../../queries/contacts';+import {+ readHeld,+ releaseRead,+ requests,+ setHoldNextRead,+} from './graphql-preview';+import {+ role,+ setFailNext,+ setFailRead,+ setRole,+ setTeamId,+ setUserId,+ teamId,+ userId,+ writes,+} from './preview-adapters';++const client = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+});+const deps = { client, storage: storageServiceClient };+document.documentElement.dataset.touchDevice = String(isTouchDevice());++function Detail(props: { id: string; close(): void }) {+ const query = useContactQuery(deps, () => props.id);+ const mutation = useSetContactHiddenMutation(deps);+ const [error, setError] = createSignal('');+ return (+ <section+ aria-label="Contact detail"+ class="flex flex-col gap-3 p-4 border-b border-edge-muted"+ >+ <Button onClick={props.close}>Back to People</Button>+ <Show+ when={query.isSuccess ? query.data : undefined}+ fallback={<p>Contact unavailable</p>}+ >+ {(contact) => (+ <>+ <h2>{contact().name}</h2>+ <RecordVisibilityAction+ recordId={contact().id}+ name={contact().name ?? 'Contact'}+ kind="contact"+ hidden={contact().hidden}+ canManage={role() !== 'member'}+ pending={mutation.isPending}+ onChange={(hidden, onSuccess) => {+ setError('');+ mutation.mutate(+ { contactId: contact().id, hidden },+ {+ onSuccess,+ onError: () =>+ setError('Could not update contact visibility'),+ }+ );+ }}+ />+ <output aria-label="Contact identity">+ {contact().id} / {contact().companyId ?? 'unfiled'}+ </output>+ <Show when={error()}>+ <p role="alert">{error()}</p>+ </Show>+ </>+ )}+ </Show>+ </section>+ );+}+function Fixture() {+ const [activeTab, setActiveTab] = createSignal('people');+ const [selected, setSelected] = createSignal<string>();+ const visibility = createPeopleVisibility({+ userId,+ teamId,+ isAdmin: () => role() !== 'member',+ activeTab,+ });+ const queryFilters = createQueryStore({+ initial: { include: { crmContactHidden: false } },+ });+ const predicates = createPredicatesStore<+ EntityData,+ FilterContext,+ PredicateConfig<EntityData, string, FilterContext>+ >({ configs: [crmContactActiveFilter, crmContactHiddenFilter] });+ bindPeopleVisibility(visibility, {+ activeTab,+ queryFilters,+ soup: { predicates },+ });+ const source = createSoupLiveQuery(+ () =>+ makeGraphqlSoupInput({+ params: { limit: 2, sort_method: 'updated_at' },+ body: queryFilters.compile(),+ }).initial,+ () => ({ enabled: activeTab() === 'people' })+ );+ onCleanup(+ registerActiveGraphqlSoupQuery({+ isEnabled: source.isEnabled,+ body: queryFilters.compile,+ refresh: source.refresh,+ })+ );+ const rows = () =>+ (source.data() ?? []).flatMap((row) => {+ if (row.__typename !== 'GraphqlSoupCrmContact') return [];+ const entity: EntityData = {+ type: 'crm_contact',+ id: row.id,+ name: row.crmContactName ?? '',+ ownerId: row.contactTeamId,+ teamId: row.contactTeamId,+ hidden: row.hidden,+ companyId: row.contactCompanyId,+ };+ return predicates.test(entity, {+ crmRemovedPeopleTeamId: visibility.removedTeamId(),+ })+ ? [row]+ : [];+ });+ return (+ <QueryClientProvider client={client}>+ <main class="flex h-dvh flex-col overflow-auto bg-panel text-ink">+ <nav+ class="flex flex-wrap gap-2 p-3 border-b border-edge-muted"+ aria-label="Fixture controls"+ >+ <Button+ onClick={() => {+ setSelected(undefined);+ setActiveTab(activeTab() === 'people' ? 'active' : 'people');+ }}+ >+ Toggle list+ </Button>+ <Button+ onClick={() => {+ setSelected(undefined);+ setRole(role() === 'member' ? 'admin' : 'member');+ client.clear();+ }}+ >+ Toggle member+ </Button>+ <Button+ onClick={() => {+ setSelected(undefined);+ setTeamId(teamId() === 'team-1' ? 'team-2' : 'team-1');+ client.clear();+ }}+ >+ Switch team+ </Button>+ <Button+ onClick={() => {+ setSelected(undefined);+ setUserId(userId() === 'user-1' ? 'user-2' : 'user-1');+ client.clear();+ }}+ >+ Switch account+ </Button>+ <Button onClick={() => setFailNext(true)}>Fail next write</Button>+ <Button onClick={() => setFailRead(true)}>Fail next query</Button>+ <Button onClick={() => setHoldNextRead(true)}>Hold next query</Button>+ <Show when={readHeld()}>+ <Button onClick={releaseRead}>Release query</Button>+ </Show>+ <Button+ onClick={() => {+ queryFilters.set({+ include: {+ crmContactHidden: true,+ crmContactTeamId: ['team-2'],+ },+ });+ predicates.set({ or: ['crm-contact-hidden'] });+ }}+ >+ Inject hidden filters+ </Button>+ <Button onClick={() => setSelected('removed-a')}>+ Open removed directly+ </Button>+ </nav>+ <Show when={activeTab() === 'people'} fallback={<h1>Companies</h1>}>+ <header class="flex items-center gap-2 px-4 py-3">+ <h1 class="flex-1 text-lg font-semibold">+ {visibility.showRemoved() ? 'Removed people' : 'People'}+ </h1>+ <PeopleDisplayMenu visibility={visibility} />+ </header>+ <div class="px-4 pb-3">+ <SearchBar+ label="Search people"+ placeholder="Search people"+ value={queryFilters.state.include.crmContactSearch ?? ''}+ onValueChange={(value) =>+ queryFilters.set({+ include: { crmContactSearch: value || undefined },+ })+ }+ />+ </div>+ <Show when={visibility.showRemoved()}>+ <RemovedPeopleNotice+ onShowActive={() => visibility.setShowRemoved(false)}+ />+ </Show>+ <Suspense fallback={<p>Loading contact</p>}>+ <Show when={selected()}>+ {(id) => (+ <Detail id={id()} close={() => setSelected(undefined)} />+ )}+ </Show>+ </Suspense>+ <section aria-label="People results" class="flex flex-col px-4">+ <Show when={source.isLoading()}>+ <p role="status">Loading people</p>+ </Show>+ <Show when={source.error()}>+ <p role="alert">Could not load people</p>+ <Button onClick={() => source.refresh()}>Retry</Button>+ </Show>+ <For each={rows()}>+ {(row) => (+ <Show+ when={+ row.__typename === 'GraphqlSoupCrmContact' ? row : undefined+ }+ >+ {(contact) => (+ <button+ type="button"+ class="text-left min-h-12 border-b border-edge-muted"+ onClick={() => setSelected(contact().id)}+ >+ {contact().crmContactName}+ </button>+ )}+ </Show>+ )}+ </For>+ <Show+ when={+ !source.isLoading() && !source.error() && rows().length === 0+ }+ >+ <p>+ {visibility.showRemoved() ? 'No removed people' : 'No people'}+ </p>+ </Show>+ <Show when={source.hasNextPage()}>+ <Button+ disabled={source.isFetchingNextPage()}+ onClick={() => source.fetchNextPage()}+ >+ Load more+ </Button>+ </Show>+ </section>+ <output aria-label="Successful writes">{writes()}</output>+ <output aria-label="Request count">{requests().length}</output>+ <output aria-label="Requests" class="hidden">+ {JSON.stringify(requests())}+ </output>+ </Show>+ </main>+ </QueryClientProvider>+ );+}+render(Fixture, document.getElementById('root')!);diff --git a/apps/web/src/features/crm/browser-test/people/graphql-preview.ts b/apps/web/src/features/crm/browser-test/people/graphql-preview.tsnew file mode 100644index 0000000000..f43d44769f--- /dev/null+++ b/apps/web/src/features/crm/browser-test/people/graphql-preview.ts@@ -0,0 +1,151 @@+import type { CacheHost } from '@app/lib/graphql-cache/host/types';+import type {+ GraphqlCrmContactExpr,+ GraphqlCrmContactFieldsFragment,+ SoupInput,+} from '@service-storage/graphql/generated/graphql';+import { createClient, fetchExchange } from '@urql/core';+import { createSignal } from 'solid-js';+import {+ contacts,+ failRead,+ role,+ setFailRead,+ userId,+} from './preview-adapters';++export const [requests, setRequests] = createSignal<SoupInput[]>([]);+export const [holdNextRead, setHoldNextRead] = createSignal(false);+export const [readHeld, setReadHeld] = createSignal(false);+let release: (() => void) | undefined;+export function releaseRead() {+ release?.();+}+export function usePending() {}+export const useFlowTrace = () => undefined;+export function getGraphqlSoupCacheHost(): CacheHost | undefined {+ return undefined;+}+export const hasGraphqlCacheHost = () => false;+export const graphqlSoupProjectionSupported = () => true;+export const normalizedCacheResultMetadata = () => undefined;+const deleted = new Set<string>();+export const usePendingGraphqlSoupDeleteKeys = () => () => deleted;+export function withoutPendingSoupEntities<T>(entities: T[]) {+ return entities;+}++// Synthetic API boundary. Filtering and authorization happen before paging;+// the browser uses the production AST compiler and live GraphQL page source.+function matches(+ contact: (typeof contacts)[number],+ expr: GraphqlCrmContactExpr+): boolean {+ if (expr.and)+ return matches(contact, expr.and.left) && matches(contact, expr.and.right);+ if (expr.or)+ return matches(contact, expr.or.left) || matches(contact, expr.or.right);+ if (expr.not) return !matches(contact, expr.not);+ const literal = expr.literal;+ if (literal.hidden !== undefined)+ return (contact.hidden || contact.parentHidden) === literal.hidden;+ if (literal.teamId !== undefined) return contact.teamId === literal.teamId;+ if (literal.search !== undefined)+ return `${contact.name} ${contact.email}`+ .toLowerCase()+ .includes(literal.search.toLowerCase());+ if (literal.id !== undefined) return contact.id === literal.id;+ if (literal.companyId !== undefined)+ return contact.companyId === literal.companyId;+ if (literal.email !== undefined) return contact.email === literal.email;+ return literal.include === true;+}+const cursors = new Map<+ string,+ {+ filter: GraphqlCrmContactExpr;+ after: string;+ limit: number;+ viewer: string;+ }+>();+let cursorId = 0;+const client = createClient({+ url: '/fixture-graphql',+ exchanges: [fetchExchange],+ fetch: async (_url, init) => {+ const { variables }: { variables: { input: SoupInput } } = JSON.parse(+ String(init?.body)+ );+ const input = variables.input;+ setRequests((previous) => [...previous, input]);+ if (failRead()) {+ setFailRead(false);+ return new Response(+ JSON.stringify({ errors: [{ message: 'Fixture query unavailable' }] }),+ { headers: { 'content-type': 'application/json' } }+ );+ }+ const cursor = input.continuation+ ? cursors.get(input.continuation.cursor)+ : undefined;+ const filter = input.initial?.filters?.crmContactFilter ?? cursor?.filter;+ const limit = input.initial?.limit ?? cursor?.limit ?? 2;+ const rows =+ filter && (!cursor || cursor.viewer === userId())+ ? contacts+ .filter(+ (contact) =>+ // Fixture viewer belongs to both teams; the production removed filter+ // must still exclude the other team's records before pagination.+ (role() !== 'member' ||+ !(contact.hidden || contact.parentHidden)) &&+ matches(contact, filter)+ )+ .sort((a, b) => a.id.localeCompare(b.id))+ : [];+ const after = cursor+ ? rows.findIndex((row) => row.id === cursor.after) + 1+ : 0;+ const page = rows.slice(after, after + limit);+ let nextCursor: string | null = null;+ if (filter && after + limit < rows.length) {+ nextCursor = `cursor-${++cursorId}`;+ cursors.set(nextCursor, {+ filter,+ after: page[page.length - 1].id,+ limit,+ viewer: userId(),+ });+ }+ const items: GraphqlCrmContactFieldsFragment[] = page.map((contact) => ({+ __typename: 'GraphqlSoupCrmContact',+ id: contact.id,+ hidden: contact.hidden || contact.parentHidden,+ contactTeamId: contact.teamId,+ contactCompanyId: contact.companyId ?? null,+ contactCompanyName: contact.companyId ? 'Example company' : null,+ crmContactName: contact.name ?? null,+ contactEmail: contact.email ?? null,+ firstInteraction: contact.firstInteraction,+ lastInteraction: contact.lastInteraction,+ createdAt: contact.createdAt,+ updatedAt: contact.updatedAt,+ viewedAt: null,+ }));+ if (holdNextRead()) {+ setHoldNextRead(false);+ setReadHeld(true);+ await new Promise<void>((resolve) => {+ release = resolve;+ });+ release = undefined;+ setReadHeld(false);+ }+ return new Response(+ JSON.stringify({ data: { user: { soup: { items, nextCursor } } } }),+ { headers: { 'content-type': 'application/json' } }+ );+ },+});+export const getGraphqlSoupClient = () => client;diff --git a/apps/web/src/features/crm/browser-test/people/index.html b/apps/web/src/features/crm/browser-test/people/index.htmlnew file mode 100644index 0000000000..7e832d38e0--- /dev/null+++ b/apps/web/src/features/crm/browser-test/people/index.html@@ -0,0 +1,5 @@+<!doctype html>+<html lang="en" data-modality="keyboard">+ <head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>CRM removed People</title></head>+ <body><div id="root"></div><script type="module" src="/fixture.tsx"></script></body>+</html>diff --git a/apps/web/src/features/crm/browser-test/people/people.browser.e2e.ts b/apps/web/src/features/crm/browser-test/people/people.browser.e2e.tsnew file mode 100644index 0000000000..25ea532517--- /dev/null+++ b/apps/web/src/features/crm/browser-test/people/people.browser.e2e.ts@@ -0,0 +1,208 @@+import { expect, type Page, test } from '@playwright/test';++async function removed(page: Page) {+ await page+ .getByRole('button', { name: 'People display options', exact: true })+ .click();+ const checkbox = page.getByRole('menuitemcheckbox', {+ name: 'Show removed people',+ });+ await expect(checkbox).toBeInViewport({ ratio: 1 });+ await checkbox.click();+ await page.keyboard.press('Escape');+ await expect(+ page.getByRole('heading', { name: 'Removed people', exact: true })+ ).toBeVisible();+}+async function confirm(page: Page, action: string) {+ await page.getByRole('button', { name: action, exact: true }).click();+ const dialog = page.getByRole('dialog');+ await expect(dialog).not.toHaveAttribute('data-transitioning');+ await dialog.getByRole('button', { name: action, exact: true }).click();+}+const results = (page: Page) =>+ page.getByRole('region', { name: 'People results' });++test.beforeEach(async ({ page }) => {+ await page.route('https://**', (route) => route.abort());+ await page.routeWebSocket('**', (socket) => socket.close());+ await page.goto('/');+ await expect(+ results(page).getByRole('button', { name: 'Active person', exact: true })+ ).toBeVisible();+});++test('admin hides, discovers through removed search, and restores with the existing eye', async ({+ page,+}, info) => {+ await results(page).getByRole('button', { name: 'Active person' }).click();+ await confirm(page, 'Remove from CRM');+ await expect(page.getByRole('dialog')).toHaveCount(0);+ await expect(+ results(page).getByRole('button', { name: 'Active person' })+ ).toHaveCount(0);+ await page.getByRole('button', { name: 'Back to People' }).click();+ await removed(page);+ await page.getByRole('searchbox', { name: 'Search people' }).fill('Active');+ await results(page).getByRole('button', { name: 'Active person' }).click();+ await expect(page.getByLabel('Contact identity')).toHaveText(+ 'active / company-1'+ );+ await page.screenshot({+ path: info.outputPath('removed-people-restore.png'),+ });+ await confirm(page, 'Restore to CRM');+ await expect(page.getByRole('dialog')).toHaveCount(0);+ await expect(+ results(page).getByRole('button', { name: 'Active person' })+ ).toHaveCount(0);+ await expect(results(page).getByText('No removed people')).toBeVisible();+ await page.getByRole('button', { name: 'Back to People' }).click();+ await page+ .getByRole('button', { name: 'Show active people', exact: true })+ .click();+ await expect(+ results(page).getByRole('button', { name: 'Active person' })+ ).toBeVisible();+ await expect(page.getByRole('searchbox')).toHaveValue('Active');+ await expect(page.getByLabel('Successful writes')).toHaveText('2');+ await page.screenshot({ path: info.outputPath('people-restored.png') });+});++test('server pagination and search find later removed rows, handle errors and preserve hidden-parent semantics', async ({+ page,+}, info) => {+ await removed(page);+ await expect(+ results(page).getByRole('button', { name: 'Removed paged' })+ ).toHaveCount(0);+ await results(page).getByRole('button', { name: 'Load more' }).click();+ await expect(+ results(page).getByRole('button', { name: 'Removed paged' })+ ).toBeVisible();+ await expect(+ results(page).getByRole('button', { name: 'Other team removed' })+ ).toHaveCount(0);+ const requests = JSON.parse(+ (await page.getByLabel('Requests', { exact: true }).textContent()) ?? '[]'+ );+ expect(+ requests.some((request: { continuation?: unknown }) => request.continuation)+ ).toBe(true);+ await page.getByRole('searchbox').fill('[email protected]');+ await expect(+ results(page).getByRole('button', { name: 'Removed paged' })+ ).toBeVisible();+ await expect(+ results(page).getByRole('button', { name: 'Removed first' })+ ).toHaveCount(0);+ await page.getByRole('button', { name: 'Fail next query' }).click();+ await page.getByRole('searchbox').fill('Hidden company');+ await expect(page.getByRole('alert')).toHaveText('Could not load people');+ await page.getByRole('button', { name: 'Retry', exact: true }).click();+ await results(page)+ .getByRole('button', { name: 'Hidden company person' })+ .click();+ await expect(+ page.getByRole('button', { name: 'Restore to CRM', exact: true })+ ).toHaveCount(0);+ await expect(+ page.getByText(/stay removed until their company is restored/)+ ).toBeVisible();+ await page.screenshot({+ path: info.outputPath('removed-hidden-company.png'),+ });+ await page.getByRole('searchbox').fill('no-match');+ await expect(results(page).getByText('No removed people')).toBeVisible();+});++test('unfiled records restore, rejected writes stay retryable, and scope changes close removed mode', async ({+ page,+}) => {+ await results(page).getByRole('button', { name: 'Unfiled person' }).click();+ await page.getByRole('button', { name: 'Fail next write' }).click();+ await confirm(page, 'Remove from CRM');+ await expect(page.getByRole('alert', { includeHidden: true })).toHaveText(+ 'Could not update contact visibility'+ );+ await page+ .getByRole('dialog')+ .getByRole('button', { name: 'Remove from CRM', exact: true })+ .click();+ await expect(page.getByRole('dialog')).toHaveCount(0);+ await page.getByRole('button', { name: 'Back to People' }).click();+ await removed(page);+ await page.getByRole('searchbox').fill('Unfiled');+ await results(page).getByRole('button', { name: 'Unfiled person' }).click();+ await confirm(page, 'Restore to CRM');+ await expect(page.getByRole('dialog')).toHaveCount(0);+ await expect(page.getByLabel('Contact identity')).toHaveText(+ 'unfiled / unfiled'+ );+ await expect(results(page).getByText('No removed people')).toBeVisible();+ await page.getByRole('button', { name: 'Back to People' }).click();+ await page.getByRole('searchbox').fill('');+ await page.getByRole('button', { name: 'Switch team' }).click();+ await expect(+ page.getByRole('heading', { name: 'People', exact: true })+ ).toBeVisible();+ await removed(page);+ await expect(+ results(page).getByRole('button', { name: 'Other team removed' })+ ).toBeVisible();+ await expect(+ results(page).getByRole('button', { name: 'Removed first' })+ ).toHaveCount(0);+ await page.getByRole('button', { name: 'Switch account' }).click();+ await expect(+ page.getByRole('heading', { name: 'People', exact: true })+ ).toBeVisible();+ await removed(page);+ await page.getByRole('button', { name: 'Toggle list' }).click();+ await page.getByRole('button', { name: 'Toggle list' }).click();+ await expect(+ page.getByRole('heading', { name: 'People', exact: true })+ ).toBeVisible();+ await removed(page);+ await page+ .getByRole('button', { name: 'Toggle member', exact: true })+ .click();+ await expect(+ page.getByRole('button', { name: 'People display options' })+ ).toHaveCount(0);+ await page.getByRole('button', { name: 'Inject hidden filters' }).click();+ await expect(+ results(page).getByRole('button', { name: /Removed|Other team/ })+ ).toHaveCount(0);+ await page.getByRole('button', { name: 'Open removed directly' }).click();+ await expect(page.getByText('Contact unavailable')).toBeVisible();+});++test('loading and late removed responses cannot resurrect rows after a role change', async ({+ page,+}) => {+ await page.getByRole('button', { name: 'Hold next query' }).click();+ await removed(page);+ await expect(results(page).getByRole('status')).toHaveText('Loading people');+ await expect(+ results(page).getByRole('button', { name: /Removed/ })+ ).toHaveCount(0);+ await page+ .getByRole('button', { name: 'Toggle member', exact: true })+ .click();+ await page.getByRole('button', { name: 'Release query' }).click();+ await expect(+ page.getByRole('heading', { name: 'People', exact: true })+ ).toBeVisible();+ await expect(+ results(page).getByRole('button', { name: 'Active person' })+ ).toBeVisible();+ await expect(+ results(page).getByRole('button', {+ name: /Removed|Other team|Hidden company/,+ })+ ).toHaveCount(0);+ await expect(+ page.getByRole('button', { name: 'People display options' })+ ).toHaveCount(0);+});diff --git a/apps/web/src/features/crm/browser-test/people/playwright.config.ts b/apps/web/src/features/crm/browser-test/people/playwright.config.tsnew file mode 100644index 0000000000..b49fd546a1--- /dev/null+++ b/apps/web/src/features/crm/browser-test/people/playwright.config.ts@@ -0,0 +1,40 @@+import { fileURLToPath } from 'node:url';+import { defineConfig, devices } from '@playwright/test';++const directory = fileURLToPath(new URL('.', import.meta.url));+const webDirectory = fileURLToPath(new URL('../../../../../', import.meta.url));+const port = Number(process.env.CRM_PEOPLE_BROWSER_PORT ?? 23942);+const launchOptions = {+ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,+};++export default defineConfig({+ testDir: directory,+ testMatch: '*.browser.e2e.ts',+ outputDir: `${directory}/test-results`,+ timeout: 45_000,+ workers: 1,+ use: {+ baseURL: `http://127.0.0.1:${port}`,+ screenshot: 'only-on-failure',+ trace: 'retain-on-failure',+ },+ webServer: {+ command: `bunx vite build --config src/features/crm/browser-test/people/vite.config.ts && bunx vite preview --config src/features/crm/browser-test/people/vite.config.ts --port ${port}`,+ cwd: webDirectory,+ url: `http://127.0.0.1:${port}`,+ reuseExistingServer: false,+ timeout: 120_000,+ },+ projects: [+ { name: 'desktop', use: { ...devices['Desktop Chrome'], launchOptions } },+ {+ name: 'phone',+ use: {+ ...devices['iPhone 13'],+ defaultBrowserType: 'chromium',+ launchOptions,+ },+ },+ ],+});diff --git a/apps/web/src/features/crm/browser-test/people/preview-adapters.ts b/apps/web/src/features/crm/browser-test/people/preview-adapters.tsnew file mode 100644index 0000000000..a2e8a527b0--- /dev/null+++ b/apps/web/src/features/crm/browser-test/people/preview-adapters.ts@@ -0,0 +1,113 @@+import type { storageServiceClient as Storage } from '@service-storage/client';+import type { CrmContactResponse } from '@service-storage/generated/schemas/crmContactResponse';+import { err, ok } from 'neverthrow';+import { createSignal } from 'solid-js';++export const analytics = { track() {} };+export async function invalidateCachedCrmContacts() {}+export const [role, setRole] = createSignal('admin');+export const [userId, setUserId] = createSignal('user-1');+export const [teamId, setTeamId] = createSignal('team-1');+export const [failNext, setFailNext] = createSignal(false);+export const [failRead, setFailRead] = createSignal(false);+export const [writes, setWrites] = createSignal(0);+const base: CrmContactResponse = {+ id: 'active',+ companyId: 'company-1',+ name: 'Active person',+ email: '[email protected]',+ hidden: false,+ createdAt: '2026-10-15',+ updatedAt: '2026-10-15',+ firstInteraction: '2026-10-15',+ lastInteraction: '2026-10-15',+};+export let contacts = [+ { ...base, teamId: 'team-1', parentHidden: false },+ {+ ...base,+ id: 'unfiled',+ name: 'Unfiled person',+ email: '[email protected]',+ companyId: null,+ teamId: 'team-1',+ parentHidden: false,+ },+ {+ ...base,+ id: 'removed-a',+ email: '[email protected]',+ name: 'Removed first',+ hidden: true,+ teamId: 'team-1',+ parentHidden: false,+ },+ {+ ...base,+ id: 'removed-b',+ email: '[email protected]',+ name: 'Removed second',+ hidden: true,+ teamId: 'team-1',+ parentHidden: false,+ },+ {+ ...base,+ id: 'removed-c',+ name: 'Removed paged',+ email: '[email protected]',+ hidden: true,+ teamId: 'team-1',+ parentHidden: false,+ },+ {+ ...base,+ id: 'parent-hidden',+ email: '[email protected]',+ name: 'Hidden company person',+ companyId: 'hidden-company',+ teamId: 'team-1',+ parentHidden: true,+ },+ {+ ...base,+ id: 'other-team',+ email: '[email protected]',+ name: 'Other team removed',+ hidden: true,+ teamId: 'team-2',+ parentHidden: false,+ },+];+export const storageServiceClient = {+ async getContact({ contactId }) {+ const contact = contacts.find(+ (item) => item.id === contactId && item.teamId === teamId()+ );+ if (+ !contact ||+ (role() === 'member' && (contact.hidden || contact.parentHidden))+ )+ return err([{ code: 'NOT_FOUND', message: 'Not found' }]);+ return ok({ ...contact });+ },+ async setContactHidden({ contactId, hidden }) {+ if (+ role() === 'member' ||+ failNext() ||+ !contacts.some(+ (item) => item.id === contactId && item.teamId === teamId()+ )+ ) {+ setFailNext(false);+ return err([+ { code: 'FORBIDDEN', message: 'Visibility update rejected' },+ ]);+ }+ setWrites((count) => count + 1);+ contacts = contacts.map((contact) =>+ contact.id === contactId ? { ...contact, hidden } : contact+ );+ return ok(undefined);+ },+} satisfies Pick<typeof Storage, 'getContact' | 'setContactHidden'>;diff --git a/apps/web/src/features/crm/browser-test/people/vite.config.ts b/apps/web/src/features/crm/browser-test/people/vite.config.tsnew file mode 100644index 0000000000..7a85df4209--- /dev/null+++ b/apps/web/src/features/crm/browser-test/people/vite.config.ts@@ -0,0 +1,63 @@+import { fileURLToPath } from 'node:url';+import tailwind from '@tailwindcss/vite';+import { defineConfig } from 'vite';+import solidPlugin from 'vite-plugin-solid';+import solidSvg from 'vite-plugin-solid-svg';+import tsconfigPaths from 'vite-tsconfig-paths';++const directory = fileURLToPath(new URL('.', import.meta.url));+const webDirectory = fileURLToPath(new URL('../../../../../', import.meta.url));+const workspaceDirectory = fileURLToPath(+ new URL('../../../../../../../', import.meta.url)+);++export default defineConfig({+ root: directory,+ cacheDir: `${directory}/.vite`,+ plugins: [+ solidPlugin(),+ solidSvg({ defaultAsComponent: true }),+ tsconfigPaths({ projects: [`${webDirectory}/tsconfig.json`] }),+ tailwind(),+ ],+ resolve: {+ dedupe: ['solid-js'],+ alias: [+ {+ find: /^.*service-storage\/graphql-soup$/,+ replacement: `${directory}/graphql-preview.ts`,+ },+ {+ find: /^.*\/optimistic-deletions$/,+ replacement: `${directory}/graphql-preview.ts`,+ },+ {+ find: /^.*normalized-cache-exchange$/,+ replacement: `${directory}/graphql-preview.ts`,+ },+ {+ find: /^@app\/observability\/flow$/,+ replacement: `${directory}/graphql-preview.ts`,+ },+ ...[+ '@service-storage/client',+ '@service-storage/crm-contacts',+ '@app/lib/analytics',+ ].map((find) => ({+ find,+ replacement: `${directory}/preview-adapters.ts`,+ })),+ { find: /^@entity$/, replacement: `${directory}/entity-preview.ts` },+ {+ find: /^@app\/components\/view-shell$/,+ replacement: `${webDirectory}/src/components/view-shell/SearchBar.tsx`,+ },+ ],+ },+ build: { target: 'esnext' },+ server: {+ host: '127.0.0.1',+ strictPort: true,+ fs: { allow: [workspaceDirectory] },+ },+});diff --git a/apps/web/src/features/crm/collection-filters.ts b/apps/web/src/features/crm/collection-filters.tsindex c0182eba1c..ff0d9a94b6 100644--- a/apps/web/src/features/crm/collection-filters.ts+++ b/apps/web/src/features/crm/collection-filters.ts@@ -141,3 +141,17 @@ export const crmContactActiveFilter = config({{ skipTargets: ['crmf'] }),});++/** Effective hidden includes contacts whose company is hidden. */+export const crmContactHiddenFilter = config({+ id: 'crm-contact-hidden',+ predicate: (entity, ctx) =>+ entity.type === 'crm_contact' &&+ entity.hidden &&+ !!ctx.crmRemovedPeopleTeamId &&+ entity.teamId === ctx.crmRemovedPeopleTeamId,+ query: defineQueryFilters(+ { include: { crmContactHidden: true } },+ { skipTargets: ['crmf'] }+ ),+});diff --git a/apps/web/src/features/crm/components/people-display-menu.tsx b/apps/web/src/features/crm/components/people-display-menu.tsxnew file mode 100644index 0000000000..b7cb8c67fb--- /dev/null+++ b/apps/web/src/features/crm/components/people-display-menu.tsx@@ -0,0 +1,45 @@+import { t } from '@app/lib/i18n';+import SlidersIcon from '@icon/system/regular/sliders-horizontal.svg';+import { Button, Dropdown } from '@ui';+import { Show } from 'solid-js';+import type { PeopleVisibility } from '../context/workspace-context';++export function PeopleDisplayMenu(props: { visibility: PeopleVisibility }) {+ return (+ <Show when={props.visibility.canShowRemoved()}>+ <Dropdown>+ <Dropdown.Trigger+ as={Button}+ aria-label={t('viewMenus.peopleDisplayOptions')}+ tooltip={t('viewMenus.peopleDisplayOptions')}+ variant="ghost"+ size="icon-md"+ >+ <SlidersIcon class="size-4 touch:size-6 shrink-0 pointer-events-none" />+ </Dropdown.Trigger>+ <Dropdown.Content class="min-w-56 max-w-[calc(100vw-2rem)]">+ <Dropdown.CheckboxItem+ checked={props.visibility.showRemoved()}+ onChange={props.visibility.setShowRemoved}+ closeOnSelect={false}+ >+ <span class="flex-1 truncate">+ {t('viewMenus.showRemovedPeople')}+ </span>+ </Dropdown.CheckboxItem>+ </Dropdown.Content>+ </Dropdown>+ </Show>+ );+}++export function RemovedPeopleNotice(props: { onShowActive(): void }) {+ return (+ <div class="flex flex-wrap items-center gap-x-3 gap-y-1 px-4 py-2 text-xs text-ink-muted border-b border-edge-muted">+ <p class="min-w-0 flex-1">{t('viewMenus.removedPeopleDescription')}</p>+ <Button variant="ghost" size="sm" onClick={props.onShowActive}>+ {t('viewMenus.showActivePeople')}+ </Button>+ </div>+ );+}diff --git a/apps/web/src/features/crm/context/workspace-context.tsx b/apps/web/src/features/crm/context/workspace-context.tsxindex c40e786d9b..c1e81b6b7e 100644--- a/apps/web/src/features/crm/context/workspace-context.tsx+++ b/apps/web/src/features/crm/context/workspace-context.tsx@@ -55,8 +55,16 @@ export type CrmRoute = CrmRecordNavigation & {setTab(tab: string, options?: { replace?: boolean }): void;};+export type PeopleVisibility = {+ canShowRemoved: Accessor<boolean>;+ showRemoved: Accessor<boolean>;+ removedTeamId: Accessor<string | undefined>;+ setShowRemoved(value: boolean): void;+};+/** Collection capabilities consumed by CRM views, supplied by the host adapter. */export type CrmWorkspace = {+ peopleVisibility: PeopleVisibility;host: {scopeId: string;isActive: Accessor<boolean>;diff --git a/apps/web/src/features/crm/primitives/people-visibility.test.ts b/apps/web/src/features/crm/primitives/people-visibility.test.tsnew file mode 100644index 0000000000..0ccf6d8d47--- /dev/null+++ b/apps/web/src/features/crm/primitives/people-visibility.test.ts@@ -0,0 +1,186 @@+import type { FilterContext } from '@app/features/next-soup/filters/configs/base';+import type { PredicateConfig } from '@app/features/next-soup/filters/filter-store/predicates-store';+import type { EntityData } from '@entity';+import { makeGraphqlSoupInput } from '@queries/soup/graphql/ast';+import { cleanup, render } from '@solidjs/testing-library';+import { createSignal } from 'solid-js';+import { afterEach, expect, it } from 'vitest';+import { createPredicatesStore } from '../../next-soup/filters/filter-store/predicates-store';+import { createQueryStore } from '../../next-soup/filters/filter-store/query-store';+import {+ crmContactActiveFilter,+ crmContactHiddenFilter,+} from '../collection-filters';+import {+ bindPeopleVisibility,+ createPeopleVisibility,+} from './people-visibility';++afterEach(cleanup);++function mount() {+ let result!: ReturnType<typeof setup>;+ render(() => {+ result = setup();+ return null;+ });+ return result;+}++function setup() {+ const [userId, setUserId] = createSignal<string | undefined>('user-1');+ const [teamId, setTeamId] = createSignal<string | undefined>('team-1');+ const [isAdmin, setAdmin] = createSignal(true);+ const [activeTab, setActiveTab] = createSignal('people');+ const queryFilters = createQueryStore({+ initial: {+ include: {+ crmContactHidden: true,+ crmContactTeamId: ['other-team'],+ crmContactSearch: 'example',+ },+ exclude: { crmContactHidden: false },+ },+ });+ const predicates = createPredicatesStore<+ EntityData,+ FilterContext,+ PredicateConfig<EntityData, string, FilterContext>+ >({+ configs: [crmContactActiveFilter, crmContactHiddenFilter],+ initial: { or: ['crm-contact-hidden'] },+ });+ const visibility = createPeopleVisibility({+ userId,+ teamId,+ isAdmin,+ activeTab,+ });+ bindPeopleVisibility(visibility, {+ activeTab,+ queryFilters,+ soup: { predicates },+ });+ return {+ visibility,+ queryFilters,+ predicates,+ setUserId,+ setTeamId,+ setAdmin,+ setActiveTab,+ };+}++it('requires an explicit choice, compiles a real hidden/team/search request, and preserves search on return', () => {+ const { visibility, queryFilters, predicates } = mount();+ expect(visibility.showRemoved()).toBe(false);+ expect(queryFilters.state.include.crmContactHidden).toBe(false);+ expect(queryFilters.state.exclude.crmContactHidden).toBeUndefined();+ expect(predicates.andIds()).toEqual(['crm-contact-active']);+ visibility.setShowRemoved(true);+ const request = makeGraphqlSoupInput({+ params: { limit: 25 },+ body: queryFilters.compile(),+ });+ expect(request.initial?.filters?.crmContactFilter).toEqual({+ and: {+ left: { literal: { hidden: true } },+ right: {+ and: {+ left: { literal: { teamId: 'team-1' } },+ right: { literal: { search: 'example' } },+ },+ },+ },+ });+ expect(predicates.andIds()).toEqual(['crm-contact-hidden']);+ visibility.setShowRemoved(false);+ expect(queryFilters.state.include.crmContactHidden).toBe(false);+ expect(queryFilters.state.include.crmContactTeamId).toBeUndefined();+ expect(queryFilters.state.include.crmContactSearch).toBe('example');+});++it('cannot enable hidden reads by injecting filters or predicates for a member', () => {+ const { visibility, queryFilters, predicates, setAdmin } = mount();+ setAdmin(false);+ visibility.setShowRemoved(true);+ queryFilters.set({+ include: { crmContactHidden: true, crmContactTeamId: ['other-team'] },+ exclude: { crmContactHidden: false },+ });+ predicates.set({ or: ['crm-contact-hidden'] });+ expect(visibility.canShowRemoved()).toBe(false);+ expect(visibility.showRemoved()).toBe(false);+ expect(queryFilters.state.include.crmContactHidden).toBe(false);+ expect(queryFilters.state.include.crmContactTeamId).toBeUndefined();+ expect(predicates.andIds()).toEqual(['crm-contact-active']);+ expect(predicates.orIds()).toEqual([]);+});++it('resets on role, account, team and tab transitions without resurrecting an old selection', () => {+ const { visibility, setAdmin, setUserId, setTeamId, setActiveTab } = mount();+ const transitions = [+ [() => setAdmin(false), () => setAdmin(true)],+ [() => setUserId('user-2'), () => setUserId('user-1')],+ [() => setTeamId('team-2'), () => setTeamId('team-1')],+ [() => setTeamId(undefined), () => setTeamId('team-1')],+ [() => setActiveTab('active'), () => setActiveTab('people')],+ ];+ for (const [leave, back] of transitions) {+ visibility.setShowRemoved(true);+ expect(visibility.showRemoved()).toBe(true);+ leave();+ expect(visibility.showRemoved()).toBe(false);+ back();+ expect(visibility.showRemoved()).toBe(false);+ }+});++it('rejects retained hidden rows from another scope and preserves unfiled and effectively hidden rows', () => {+ const { visibility, predicates, setAdmin, setTeamId } = mount();+ const contact: EntityData = {+ type: 'crm_contact',+ id: 'removed',+ name: 'Removed',+ ownerId: 'team-1',+ teamId: 'team-1',+ companyId: null,+ hidden: true,+ };+ const matches = (entity: EntityData) =>+ predicates.test(entity, {+ crmRemovedPeopleTeamId: visibility.removedTeamId(),+ });+ expect(matches(contact)).toBe(false);+ visibility.setShowRemoved(true);+ expect(matches(contact)).toBe(true);+ expect(matches({ ...contact, companyId: 'hidden-company' })).toBe(true);+ expect(matches({ ...contact, teamId: 'team-2' })).toBe(false);+ expect(matches({ ...contact, hidden: false })).toBe(false);+ setTeamId('team-2');+ expect(matches(contact)).toBe(false);+ visibility.setShowRemoved(true);+ expect(matches(contact)).toBe(false);+ setAdmin(false);+ expect(matches({ ...contact, teamId: 'team-2' })).toBe(false);+ expect(crmContactHiddenFilter.predicate(contact, {})).toBe(false);+});++it('does not opt contacts into a company request after leaving removed People', () => {+ const { visibility, queryFilters, setActiveTab } = mount();+ visibility.setShowRemoved(true);+ queryFilters.set({ include: { crmContactSearch: undefined } });+ setActiveTab('active');+ expect(queryFilters.compile().crmf).toBeUndefined();+});++it('keeps an explicitly selected removed view scoped when a shared filter replaces its team', () => {+ const { visibility, queryFilters } = mount();+ visibility.setShowRemoved(true);+ queryFilters.replace({+ include: { crmContactHidden: true, crmContactTeamId: ['other-team'] },+ });+ expect(queryFilters.state.include.crmContactTeamId).toEqual(['team-1']);+ expect(visibility.showRemoved()).toBe(true);+});diff --git a/apps/web/src/features/crm/primitives/people-visibility.ts b/apps/web/src/features/crm/primitives/people-visibility.tsnew file mode 100644index 0000000000..48ca4f30ed--- /dev/null+++ b/apps/web/src/features/crm/primitives/people-visibility.ts@@ -0,0 +1,135 @@+import { startUiOperation } from '@app/observability/ui-operation';+import {+ type Accessor,+ batch,+ createMemo,+ createRenderEffect,+ createSignal,+ on,+} from 'solid-js';+import type {+ CrmWorkspace,+ PeopleVisibility,+} from '../context/workspace-context';++/** A local, explicit choice. Shared links and saved filters cannot enable it. */+export function createPeopleVisibility(scope: {+ userId: Accessor<string | undefined>;+ teamId: Accessor<string | undefined>;+ isAdmin: Accessor<boolean>;+ activeTab: Accessor<string | undefined>;+}): PeopleVisibility {+ const identity = createMemo(() =>+ scope.userId() && scope.teamId() && scope.isAdmin()+ ? JSON.stringify([scope.userId(), scope.teamId()])+ : undefined+ );+ const [requested, setRequested] = createSignal<string>();+ const people = () => scope.activeTab() === 'people';+ const canShowRemoved = () => !!identity();+ const showRemoved = () =>+ people() && !!identity() && requested() === identity();++ // Synchronize the local choice with the host session/navigation lifecycle.+ // Comparing the identity also closes the gate before this effect runs.+ createRenderEffect(+ on([identity, people], () => setRequested(undefined), { defer: true })+ );++ return {+ canShowRemoved,+ showRemoved,+ removedTeamId: () => (showRemoved() ? scope.teamId() : undefined),+ setShowRemoved(value: boolean) {+ const next = value && people() ? identity() : undefined;+ if (next === requested()) return;+ const operation = startUiOperation('crm.people_visibility', {+ attributes: { 'crm.hidden': !!next },+ });+ operation.run(() => setRequested(next));+ operation.afterPaint();+ },+ };+}++/** Keep shared Soup query/predicate stores aligned with the local display choice. */+export function bindPeopleVisibility(+ visibility: PeopleVisibility,+ view: Pick<CrmWorkspace, 'activeTab' | 'queryFilters'> & {+ soup: { predicates: CrmWorkspace['soup']['predicates'] };+ }+) {+ createRenderEffect(+ on(+ () => ({+ people: view.activeTab() === 'people',+ showRemoved: visibility.showRemoved(),+ removedTeamId: visibility.removedTeamId(),+ includedHidden: view.queryFilters.state.include.crmContactHidden,+ teams: view.queryFilters.state.include.crmContactTeamId?.slice(),+ excludedHidden: view.queryFilters.state.exclude.crmContactHidden,+ excludedTeams: view.queryFilters.state.exclude.crmContactTeamId,+ and: view.soup.predicates.andIds(),+ or: view.soup.predicates.orIds(),+ }),+ ({+ people,+ showRemoved,+ removedTeamId,+ includedHidden,+ teams,+ excludedHidden,+ excludedTeams,+ and,+ or,+ }) => {+ const hidden = people && showRemoved;+ const teamId = hidden ? removedTeamId : undefined;+ const expected = hidden ? 'crm-contact-hidden' : 'crm-contact-active';+ const isVisibility = (id: string) =>+ id === 'crm-contact-active' || id === 'crm-contact-hidden';+ batch(() => {+ if (+ includedHidden !== (people ? hidden : undefined) ||+ (teamId+ ? teams?.length !== 1 || teams[0] !== teamId+ : !!teams?.length) ||+ excludedHidden !== undefined ||+ excludedTeams !== undefined+ ) {+ view.queryFilters.set({+ include: {+ crmContactHidden: people ? hidden : undefined,+ crmContactTeamId: teamId ? [teamId] : undefined,+ },+ exclude: {+ crmContactHidden: undefined,+ crmContactTeamId: undefined,+ },+ });+ }+ if (+ people &&+ (!and.includes(expected) ||+ and.some((id) => isVisibility(id) && id !== expected) ||+ or.some(isVisibility))+ ) {+ view.soup.predicates.set({+ and: [...and.filter((id) => !isVisibility(id)), expected],+ or: or.filter((id) => !isVisibility(id)),+ });+ } else if (+ !people &&+ (and.includes('crm-contact-hidden') ||+ or.includes('crm-contact-hidden'))+ ) {+ view.soup.predicates.set({+ and: and.filter((id) => id !== 'crm-contact-hidden'),+ or: or.filter((id) => id !== 'crm-contact-hidden'),+ });+ }+ });+ }+ )+ );+}diff --git a/apps/web/src/features/crm/queries/blocked-domains.ts b/apps/web/src/features/crm/queries/blocked-domains.tsindex da9831045c..31e5b00f89 100644--- a/apps/web/src/features/crm/queries/blocked-domains.ts+++ b/apps/web/src/features/crm/queries/blocked-domains.ts@@ -17,28 +17,7 @@ import { queryOptions, useMutation, useQuery } from '@tanstack/solid-query';import type { BlockedDomainsSource } from '../context/crm-sources';import type { CrmQueryDependencies } from './dependencies';import { crmKeys } from './keys';--function excludesCrmRecords(filter: unknown): boolean {- if (typeof filter !== 'object' || filter === null) return false;- if ('&' in filter && Array.isArray(filter['&']))- return filter['&'].some(excludesCrmRecords);- return (- 'l' in filter &&- typeof filter.l === 'object' &&- filter.l !== null &&- 'id' in filter.l &&- filter.l.id === '00000000-0000-0000-0000-000000000000'- );-}--function listCanIncludeCrm(body: unknown): boolean {- if (typeof body !== 'object' || body === null) return false;- const excludesCompanies = 'ccf' in body && excludesCrmRecords(body.ccf);- // Contacts are opt-in, unlike companies in a general Soup list.- const excludesContacts =- !('crmf' in body) || body.crmf == null || excludesCrmRecords(body.crmf);- return !(excludesCompanies && excludesContacts);-}+import { listCanIncludeCrm } from './list-refresh';async function refreshBlockedDomainRecords(): Promise<void> {await Promise.all([diff --git a/apps/web/src/features/crm/queries/contact-visibility.test.tsx b/apps/web/src/features/crm/queries/contact-visibility.test.tsxindex 08dc76a638..e225ebf348 100644--- a/apps/web/src/features/crm/queries/contact-visibility.test.tsx+++ b/apps/web/src/features/crm/queries/contact-visibility.test.tsx@@ -1,3 +1,4 @@+import { registerActiveGraphqlSoupQuery } from '@queries/soup/graphql/active-queries';import { storageServiceClient } from '@service-storage/client';import { invalidateCachedCrmContacts } from '@service-storage/crm-contacts';import type { CrmContactResponse } from '@service-storage/generated/schemas/crmContactResponse';@@ -156,3 +157,79 @@ it('surfaces a cache refresh failure after a successful write', async () => {).rejects.toThrow('Cache unavailable');expect(contact.hidden).toBe(true);});++it('awaits GraphQL People membership refresh for hide and restore, excluding unrelated lists', async () => {+ let visible = [CONTACT.id];+ let removed: string[] = [];+ const visibleReader = vi.fn(async () => {+ visible = contact.hidden ? [] : [contact.id];+ });+ const removedReader = vi.fn(async () => {+ removed = contact.hidden ? [contact.id] : [];+ });+ const unrelated = vi.fn(async () => {});+ const unregister = [+ registerActiveGraphqlSoupQuery({+ isEnabled: () => true,+ body: () => ({ crmf: { l: { hidden: false } } }),+ refresh: visibleReader,+ }),+ registerActiveGraphqlSoupQuery({+ isEnabled: () => true,+ body: () => ({ crmf: { l: { hidden: true } } }),+ refresh: removedReader,+ }),+ registerActiveGraphqlSoupQuery({+ isEnabled: () => true,+ body: () => ({ df: {} }),+ refresh: unrelated,+ }),+ registerActiveGraphqlSoupQuery({+ isEnabled: () => true,+ body: () => ({+ crmf: { l: { id: '00000000-0000-0000-0000-000000000000' } },+ }),+ refresh: unrelated,+ }),+ ];+ try {+ const { mutation } = mount();+ await mutation.mutateAsync({ contactId: CONTACT.id, hidden: true });+ expect(visible).toEqual([]);+ expect(removed).toEqual([CONTACT.id]);+ await mutation.mutateAsync({ contactId: CONTACT.id, hidden: false });+ expect(visible).toEqual([CONTACT.id]);+ expect(removed).toEqual([]);+ expect(visibleReader).toHaveBeenCalledTimes(2);+ expect(removedReader).toHaveBeenCalledTimes(2);+ expect(unrelated).not.toHaveBeenCalled();+ } finally {+ unregister.forEach((dispose) => dispose());+ }+});++it('reports an active GraphQL refresh failure and does not refresh after a rejected write', async () => {+ const refresh = vi.fn(async () => {+ throw new Error('Unavailable');+ });+ const unregister = registerActiveGraphqlSoupQuery({+ isEnabled: () => true,+ body: () => ({ crmf: { l: { hidden: true } } }),+ refresh,+ });+ try {+ const { mutation } = mount();+ await expect(+ mutation.mutateAsync({ contactId: CONTACT.id, hidden: true })+ ).rejects.toThrow('revalidation');+ vi.mocked(storageServiceClient.setContactHidden).mockResolvedValue(+ err([{ code: 'FORBIDDEN', message: 'Denied' }])+ );+ await expect(+ mutation.mutateAsync({ contactId: CONTACT.id, hidden: false })+ ).rejects.toThrow();+ expect(refresh).toHaveBeenCalledTimes(1);+ } finally {+ unregister();+ }+});diff --git a/apps/web/src/features/crm/queries/contacts.ts b/apps/web/src/features/crm/queries/contacts.tsindex 27c7f274b7..0c3d887244 100644--- a/apps/web/src/features/crm/queries/contacts.ts+++ b/apps/web/src/features/crm/queries/contacts.ts@@ -1,5 +1,6 @@import { throwOnErr } from '@core/util/result';import { Telemetry } from '@macro-inc/observability';+import { refreshActiveGraphqlSoupQueries } from '@queries/soup/graphql/active-queries';import { soupKeys } from '@queries/soup/keys';import { invalidateCachedCrmContacts } from '@service-storage/crm-contacts';import type { CrmContactResponse } from '@service-storage/generated/schemas/crmContactResponse';@@ -7,6 +8,7 @@ import { queryOptions, useMutation, useQuery } from '@tanstack/solid-query';import type { Accessor } from 'solid-js';import type { CrmRecordDependencies } from './dependencies';import { crmKeys } from './keys';+import { listCanIncludeCrmContacts } from './list-refresh';const CONTACT_STALE_TIME = 60 * 1000;@@ -176,6 +178,10 @@ export function useSetContactHiddenMutation(deps: CrmRecordDependencies) {try {await invalidateCachedCrmContacts(contactId);await Promise.all([+ refreshActiveGraphqlSoupQueries({+ where: listCanIncludeCrmContacts,+ throwOnError: true,+ }),deps.client.invalidateQueries({ queryKey: soupKeys._def }),deps.client.invalidateQueries({queryKey: crmKeys.contact(contactId).queryKey,diff --git a/apps/web/src/features/crm/queries/list-refresh.ts b/apps/web/src/features/crm/queries/list-refresh.tsnew file mode 100644index 0000000000..bb8e878abd--- /dev/null+++ b/apps/web/src/features/crm/queries/list-refresh.ts@@ -0,0 +1,31 @@+function excludesCrmRecords(filter: unknown): boolean {+ if (typeof filter !== 'object' || filter === null) return false;+ if ('&' in filter && Array.isArray(filter['&']))+ return filter['&'].some(excludesCrmRecords);+ return (+ 'l' in filter &&+ typeof filter.l === 'object' &&+ filter.l !== null &&+ 'id' in filter.l &&+ filter.l.id === '00000000-0000-0000-0000-000000000000'+ );+}++export function listCanIncludeCrm(body: unknown): boolean {+ if (typeof body !== 'object' || body === null) return false;+ const excludesCompanies = 'ccf' in body && excludesCrmRecords(body.ccf);+ // Contacts are opt-in, unlike companies in a general Soup list.+ const excludesContacts = !listCanIncludeCrmContacts(body);+ return !(excludesCompanies && excludesContacts);+}++/** Contacts are an explicit Soup target; an absent or excluded target cannot change. */+export function listCanIncludeCrmContacts(body: unknown): boolean {+ return (+ typeof body === 'object' &&+ body !== null &&+ 'crmf' in body &&+ body.crmf != null &&+ !excludesCrmRecords(body.crmf)+ );+}diff --git a/apps/web/src/features/crm/views/crm-workspace.test.tsx b/apps/web/src/features/crm/views/crm-workspace.test.tsxindex aa0743fcd1..55f413b458 100644--- a/apps/web/src/features/crm/views/crm-workspace.test.tsx+++ b/apps/web/src/features/crm/views/crm-workspace.test.tsx@@ -311,6 +311,7 @@ function setup([activeTab(), ...records().map((record) => record.id)].join(' '));fixture.workspace = {+ peopleVisibility: { canShowRemoved: () => false, showRemoved: () => false },activeTab,setActiveTab,host: {diff --git a/apps/web/src/features/crm/views/crm-workspace.tsx b/apps/web/src/features/crm/views/crm-workspace.tsxindex 5d3e0e761e..a6a2df8a59 100644--- a/apps/web/src/features/crm/views/crm-workspace.tsx+++ b/apps/web/src/features/crm/views/crm-workspace.tsx@@ -21,6 +21,7 @@ import { SoupViewContextSort } from '@app/features/next-soup/soup-view/filters-bimport { UnifiedFilterDropdown } from '@app/features/next-soup/soup-view/filters-bar/unified-filter-dropdown';import { useFilterRefinements } from '@app/features/next-soup/soup-view/filters-bar/use-filter-refinements';import { useFeatureFlag } from '@app/lib/analytics/posthog';+import { t } from '@app/lib/i18n';import { usePreference } from '@app/preferences/use-preference';import { HeaderActionGroup } from '@components/app/HeaderActionGroup';import { SplitPanel } from '@components/app/split-panel';@@ -57,6 +58,10 @@ import { CrmCreateMenu } from '../components/crm-create-menu';import { CrmMobileTabs } from '../components/crm-mobile-tabs';import { CrmSidebar } from '../components/crm-sidebar';import { CrmListError, CrmListSkeleton } from '../components/list-state';+import {+ PeopleDisplayMenu,+ RemovedPeopleNotice,+} from '../components/people-display-menu';import { PipelineDialog } from '../components/pipeline-dialog';import { PipelineSidebar } from '../components/pipeline-sidebar';import { useCrmContext } from '../context/crm-context';@@ -409,6 +414,9 @@ export function CrmWorkspaceView(props: {: 'active';};const title = () =>+ (view.peopleVisibility.showRemoved()+ ? t('viewMenus.removedPeople')+ : undefined) ??activeList()?.name ??[...CRM_RECORDS, ...CRM_ACTIVITY_TABS].find((record) => record.id === activeRecord()@@ -759,6 +767,7 @@ export function CrmWorkspaceView(props: {value={peopleSearch()}onValueChange={searchPeople}/>+ <PeopleDisplayMenu visibility={view.peopleVisibility} /><Buttonvariant="secondary"class="ml-auto shrink-0"@@ -805,6 +814,9 @@ export function CrmWorkspaceView(props: {</Show></HeaderActionGroup></Show>+ <Show when={peopleActive()}>+ <PeopleDisplayMenu visibility={view.peopleVisibility} />+ </Show>{toolbarCreateMenu()}<CrmHeaderSearchlabel={peopleActive() ? 'Search people' : 'Search companies'}@@ -822,6 +834,11 @@ export function CrmWorkspaceView(props: {</Suspense></Show></Show>+ <Show when={view.peopleVisibility.showRemoved()}>+ <RemovedPeopleNotice+ onShowActive={() => view.peopleVisibility.setShowRemoved(false)}+ />+ </Show>{/* The header above already clears the status bar on touch. */}<div class="flex min-h-0 min-w-0 flex-1 flex-col [--mobile-content-inset-top:0px]">{props.children({diff --git a/apps/web/src/features/crm/views/empty-state.tsx b/apps/web/src/features/crm/views/empty-state.tsxindex 7032182393..6d3393ff6c 100644--- a/apps/web/src/features/crm/views/empty-state.tsx+++ b/apps/web/src/features/crm/views/empty-state.tsx@@ -22,6 +22,7 @@ export function CrmEmptyState(const {host,activeTab,+ peopleVisibility,queryFilters,searchText,setSearchText,@@ -82,11 +83,25 @@ export function CrmEmptyState(</Match><Match when={activeTab() === 'people' && !!peopleSearch()}><CrmListSearchEmpty- title="No matching people"+ title={+ peopleVisibility.showRemoved()+ ? 'No matching removed people'+ : 'No matching people'+ }description="Try a different name or email address."onClearSearch={props.onClearPeopleSearch}/></Match>+ <Match when={peopleVisibility.showRemoved()}>+ <CrmListEmpty+ title="No removed people"+ description="Removed people from this team will appear here."+ action={{+ label: 'Show active people',+ onClick: () => peopleVisibility.setShowRemoved(false),+ }}+ />+ </Match><Match when={activeTab() === 'people' && props.filtered}><CrmListEmptyfiltereddiff --git a/apps/web/src/features/crm/workspace-adapter.tsx b/apps/web/src/features/crm/workspace-adapter.tsxindex cbaab8f4e9..b4c92b1d71 100644--- a/apps/web/src/features/crm/workspace-adapter.tsx+++ b/apps/web/src/features/crm/workspace-adapter.tsx@@ -23,6 +23,10 @@ import type { CrmRoute, CrmWorkspace } from './context/workspace-context';import type { CrmViewConfig } from './core/saved-view';import { createCrmCollectionFilters } from './filter-adapter';import { COMPANY_GROUP_OPTIONS } from './group-options';+import {+ bindPeopleVisibility,+ createPeopleVisibility,+} from './primitives/people-visibility';import { createSettingsPage } from './primitives/settings-page';// The filter context lands in cached soup query meta, so its stage resolvers@@ -76,6 +80,17 @@ export function createCrmWorkspace() {const soup = useSoup();const panel = useSplitPanelOrThrow();+ const team = crm.createTeamSource();+ const isAdmin = crm.isTeamAdmin();+ const peopleVisibility = createPeopleVisibility({+ userId: crm.userId,+ teamId: () =>+ !team.isPending && team.data?.team.crm_enabled+ ? team.data.team.id+ : undefined,+ isAdmin,+ activeTab: route.tab,+ });const stages = crm.createDealStages();const stageResolvers = stageFilterResolvers(stages);const [persistFilters] = useSoupFilterPersistence();@@ -102,6 +117,7 @@ export function createCrmWorkspace(},filterContext: () => ({...stageResolvers,+ crmRemovedPeopleTeamId: peopleVisibility.removedTeamId(),owners: filters.state.ownerFilter(),stages: filters.state.stageFilter(),}),@@ -289,8 +305,10 @@ export function createCrmWorkspace(route.commentTarget()?.seek ?? '',].join(' '));+ bindPeopleVisibility(peopleVisibility, soupView);const context: CrmWorkspace = {...soupView,+ peopleVisibility,setActiveTab: wrappedSetActiveTab,host: {scopeId: panel.splitHotkeyScope,diff --git a/apps/web/src/features/next-soup/filters/configs/base.ts b/apps/web/src/features/next-soup/filters/configs/base.tsindex 50eaa4c781..bc318052dc 100644--- a/apps/web/src/features/next-soup/filters/configs/base.ts+++ b/apps/web/src/features/next-soup/filters/configs/base.ts@@ -45,6 +45,8 @@ const _isFolder = { exclude: { folderId: [NIL_UUID] } };export type FilterContext = {userId?: string;+ /** Explicit, authorized removed-People scope; absent outside that view. */+ crmRemovedPeopleTeamId?: string;notificationSource?: NotificationSource;assignees?: string[];/** Selected company Owner ids for the Customers view's owner filter. */diff --git a/apps/web/src/features/next-soup/filters/configs/entity.ts b/apps/web/src/features/next-soup/filters/configs/entity.tsindex 61692ac68d..94c4c2e0bb 100644--- a/apps/web/src/features/next-soup/filters/configs/entity.ts+++ b/apps/web/src/features/next-soup/filters/configs/entity.ts@@ -3,6 +3,7 @@ export {crmCompanyFilter,crmCompanyHiddenFilter,crmContactActiveFilter,+ crmContactHiddenFilter,} 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 ea741f46f4..1f9da1af6e 100644--- a/apps/web/src/features/next-soup/filters/configs/index.ts+++ b/apps/web/src/features/next-soup/filters/configs/index.ts@@ -41,6 +41,7 @@ import {crmCompanyFilter,crmCompanyHiddenFilter,crmContactActiveFilter,+ crmContactHiddenFilter,documentOrFileFilter,filesAndFolderFilter,foldersFilter,@@ -104,6 +105,7 @@ export const SOUP_FILTERS = [crmCompanyActiveFilter,crmCompanyHiddenFilter,crmContactActiveFilter,+ crmContactHiddenFilter,companyOwnerFilter,companyNeedsFollowUpFilter,companyRecentlyActiveFilter,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 a9bbafc564..6f89172729 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@@ -174,6 +174,7 @@ const FIELD_CONFIG: Record<crmCompanyId: { target: 'ccf', field: 'id' },crmCompanyHidden: { target: 'ccf', field: 'hidden' },crmContactHidden: { target: 'crmf', field: 'hidden' },+ crmContactTeamId: { target: 'crmf', field: 'team_id' },crmContactSearch: { target: 'crmf', field: 'search' },agentSessionId: { target: 'asf', field: 'id' },agentSessionOwnerId: { target: 'asf', field: 'o' },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 125329c6f9..2b11abd836 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@@ -104,6 +104,8 @@ export type ScalarFieldFilters = {callAttended?: boolean;crmCompanyHidden?: boolean;crmContactHidden?: boolean;+ /** Owning teams, applied by the server before contact deduplication and paging. */+ crmContactTeamId?: string[];/** Literal text matched against a CRM contact's name or email. */crmContactSearch?: string;calendarEventSeen?: boolean;diff --git a/apps/web/src/lib/i18n/locales/en/view-menus.ts b/apps/web/src/lib/i18n/locales/en/view-menus.tsindex f773c76663..ec0a17e2b0 100644--- a/apps/web/src/lib/i18n/locales/en/view-menus.ts+++ b/apps/web/src/lib/i18n/locales/en/view-menus.ts@@ -58,6 +58,14 @@ export default {priorities: 'Priorities',assignee: 'Assignee',+ // People display options+ peopleDisplayOptions: 'People display options',+ showRemovedPeople: 'Show removed people',+ removedPeople: 'Removed people',+ removedPeopleDescription:+ 'Removed people in this team. Open a person and use Restore. People in hidden companies stay removed until their company is restored.',+ showActivePeople: 'Show active people',+// List controlslayout: 'Layout',layoutList: 'List',diff --git a/docs/agent-guide/crm.md b/docs/agent-guide/crm.mdindex a10b2ce342..4b55b8979a 100644--- a/docs/agent-guide/crm.md+++ b/docs/agent-guide/crm.md@@ -123,12 +123,23 @@ People lists contacts across every CRM-enabled team the viewer belongs to, fromthe same Soup query with only CRM contacts opted in (`crmf`). The server collapsesduplicate full email addresses (case-insensitive) to one contact; contactswithout an email never collapse. Hidden contacts-and contacts under hidden companies are excluded. Columns are Person (name and+and contacts under hidden companies are excluded by default. Columns are Person (name andemail), Company and Last contacted (sortable). `Search people` matches name oremail on the server after a short typing pause, so results include contacts notyet scrolled into view. The desktop header has the title, shared **New** menu,and expandable Search; choose **Contact** from New. On touch, **New contact**-is unchanged. The contact dialog offers an optional **Choose a company** pill (searchable by name+is unchanged. Admins/owners have **People display options → Show removed people**+on desktop and touch. This shows **Removed people** from the current team only,+with server search and normal pagination. Open a person and use the existing+**Restore to CRM** eye action; successful restoration removes the row from this+view and returns it to normal People and company Team lists. **Show active people**+returns to the normal list while keeping the search text. A hidden company also+hides its people: restore the company first to make them visible. The banner+explains this; no company is silently restored by an individual contact action.+The choice is local to this workspace, clears on leaving People or changing+account/team/role, and is not activated by a shared URL or saved filter. Members+have no removed control, and server role checks still exclude hidden records.+The contact dialog offers an optional **Choose a company** pill (searchable by nameor domain, from the up to 500 most relevant companies, including name-onlycompanies); without one the person is added with no company. The email isoptional: personal addresses and different domains are accepted, and leaving it@@ -233,8 +244,8 @@ Hiding a company hides all its contacts and turns off team email sync. Restoringthe company restores every contact, including individually hidden ones, but leavesemail sync off; re-enable **Sync Emails** under the information panel's **Sharing**section if needed. A company's Team tab excludes hidden contacts for every role,-including search results. Admins retain direct-link access to hidden contacts for-restoration. Removing or restoring a person refreshes open company Team lists;+including search results. Admins can find removed contacts in People display options and retain direct-link+access for restoration. Removing or restoring a person refreshes open company Team lists;returning to a previously visited company reloads its contacts. The existing**Sharing → Visible in CRM** checkbox and company row **Hide /Unhide** actions control the same state.@@ -242,6 +253,12 @@ Restoring a person under a hidden company does not make them appear in Peopleuntil that company is restored too. People without a company can be restoreddirectly; a person without a name or email is labeled **Contact** in the confirmation.+The removed-People discovery check is+`bunx playwright test --config src/features/crm/browser-test/people/playwright.config.ts`+from `apps/web`. It covers desktop/phone discovery, server-side search and cursor+paging, query errors, unfiled records, hidden-parent behavior, rejected writes,+member filter injection, and account/team/list transitions with synthetic data.+The backend-free browser check is`bunx playwright test --config src/features/crm/browser-test/playwright.config.ts visibility.browser.e2e.ts`from `apps/web`. It exercises cancellation, pending/error handling, restoration,