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): move contact visibility actions and refresh team lists
gbirman54ea0f5f1baa
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.mdindex 5ea905780f..ce64f51a1d 100644--- a/apps/web/AGENTS.md+++ b/apps/web/AGENTS.md@@ -365,8 +365,9 @@ not to account-wide paired runtime count; a user can pair several computers.### General-- Keep CRM removal and restoration visible on company/contact Overview pages;- use the existing hidden mutations and confirm company contact/email-sync effects.+- Keep contact removal and restoration beside Copy contact link in both record+ headers; keep company actions on Overview. Reuse the hidden mutations and+ confirm company contact/email-sync effects.- Keep selection controls on shared `Checkbox`, `ToggleSwitch`, and `RadioGroup`;preserve their native input semantics and use root sizing instead of internal@@ -408,6 +409,10 @@ resolved session ID; keep the existing `AgentSessionProvider` subscription toRecord search fills the row beside filters with header spacing; section creationreplaces the default floating dock action through FloatRegion. See`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 authorized+ detail/restore access and invalidate embedded company contacts on hide/restore.+ 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.- Enable persisted email/calendar review controls only for the review’s saved acting account; historical reviews fall back to the session owner. Require session edit access on desktop and mobile.- Email draft reads compare server generations before choosing cached delivery state over a restored working copy; only a definitive first-submission rejection permits local send recovery without server cancellation.diff --git a/apps/web/src/features/block-contact/component/ContactBlockAdapter.tsx b/apps/web/src/features/block-contact/component/ContactBlockAdapter.tsxindex 6636775024..5859ddfd3a 100644--- a/apps/web/src/features/block-contact/component/ContactBlockAdapter.tsx+++ b/apps/web/src/features/block-contact/component/ContactBlockAdapter.tsx@@ -2,6 +2,7 @@ import {Contact,type ContactSection,ContactTabs,+ ContactVisibilityButton,} from '@app/features/crm/crm-contact';import { CrmCopyLinkButton } from '@app/features/crm/crm-link';import { CollapsibleHeaderItem } from '@components/app/split-layout/components/CollapsibleItem';@@ -59,6 +60,7 @@ export function ContactBlockAdapter() {<SplitHeaderRight><HeaderIsland class="p-0"><CrmCopyLinkButton type="contact" id={contactId} />+ <ContactVisibilityButton contactId={contactId} /></HeaderIsland></SplitHeaderRight><ParamsProvider state={params}>diff --git a/apps/web/src/features/crm/README.md b/apps/web/src/features/crm/README.mdindex 7e59d806d4..8e7e19f38c 100644--- a/apps/web/src/features/crm/README.md+++ b/apps/web/src/features/crm/README.md@@ -56,10 +56,18 @@ CRM supplies row/header/empty state slots, filter choices, grouping policy, andits own collection state to the shared collection renderer. Shared collection code must not acquire CRM hooks orCRM-specific state again.-Company and contact Overview pages expose `RecordVisibilityAction` for removal+Company Overview and contact headers expose `RecordVisibilityAction` for removaland restoration through the existing hidden mutations. Keep admin/owner checks,confirmation of the company-wide contact cascade, and the restore action on theopen record. The information panel's visibility checkbox uses the same state.+Company Team lists filter hidden contacts for every role without changing the+underlying response or admin detail access. Contact visibility mutations invalidate+the company query family because those responses embed contacts: mounted lists+refetch before completion, and inactive lists reload when revisited. No company ID+is required, so unfiled contacts use the same mutation safely.+`browser-test/team` exercises the real Team component, visibility action and query+adapters with a synthetic storage client on desktop and phone; entity row metadata+and app navigation are isolated. Run its `playwright.config.ts` from `apps/web`.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 anddiff --git a/apps/web/src/features/crm/browser-test/team/entity-preview.tsx b/apps/web/src/features/crm/browser-test/team/entity-preview.tsxnew file mode 100644index 0000000000..53ee810a85--- /dev/null+++ b/apps/web/src/features/crm/browser-test/team/entity-preview.tsx@@ -0,0 +1,26 @@+import type { CrmContactEntity } from '@entity';+import type { JSX, ParentProps } from 'solid-js';++// Isolate global entity metadata/navigation services; the Team component,+// filtering, queries, visibility action, search, and confirmation are real.+export const ListEntityMetadataQueryProvider = (props: ParentProps) =>+ props.children;+export const ListLayoutProvider = (props: ParentProps) => props.children;+export function ListEntity(props: {+ entity: CrmContactEntity;+ icon: JSX.Element;+ titleTrailing: JSX.Element;+ onClick: JSX.EventHandler<HTMLButtonElement, MouseEvent>;+}) {+ return (+ <button+ type="button"+ class="flex min-h-12 items-center gap-2 px-4 text-left"+ onClick={props.onClick}+ >+ {props.icon}+ <span>{props.entity.name}</span>+ {props.titleTrailing}+ </button>+ );+}diff --git a/apps/web/src/features/crm/browser-test/team/fixture.tsx b/apps/web/src/features/crm/browser-test/team/fixture.tsxnew file mode 100644index 0000000000..55cf6b220f--- /dev/null+++ b/apps/web/src/features/crm/browser-test/team/fixture.tsx@@ -0,0 +1,125 @@+import '../../../../index.css';+import { isTouchDevice } from '@core/mobile/isTouchDevice';+import { storageServiceClient } from '@service-storage/client';+import { QueryClient, QueryClientProvider } from '@tanstack/solid-query';+import { Button } from '@ui';+import { createSignal, Show, Suspense } from 'solid-js';+import { render } from 'solid-js/web';+import { RecordVisibilityAction } from '../../components/record-visibility-action';+import { useCompanyQuery } from '../../queries/companies';+import {+ useContactQuery,+ useSetContactHiddenMutation,+} from '../../queries/contacts';+import { CompanyContactsSection } from '../../views/company-contacts-section';+import {+ companyReads,+ failNext,+ role,+ setFailNext,+ setRole,+ 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 Team(props: { open(id: string): void }) {+ const company = useCompanyQuery(deps, () => 'company-1');+ return (+ <CompanyContactsSection+ company={company.company()}+ contacts={company.contacts()}+ onOpenContact={(contact) => props.open(contact.id)}+ />+ );+}++function Detail(props: { id: string }) {+ const contact = useContactQuery(deps, () => props.id);+ const mutation = useSetContactHiddenMutation(deps);+ const [error, setError] = createSignal('');+ return (+ <Show+ when={contact.isSuccess ? contact.data : undefined}+ fallback={<p>Contact unavailable</p>}+ >+ {(record) => (+ <div class="flex flex-col gap-4 p-4">+ <h2>{record().name}</h2>+ <RecordVisibilityAction+ recordId={record().id}+ name={record().name ?? 'Contact'}+ kind="contact"+ hidden={record().hidden}+ canManage={role() !== 'member'}+ pending={mutation.isPending}+ onChange={(hidden, onSuccess) => {+ setError('');+ mutation.mutate(+ { contactId: record().id, hidden },+ {+ onSuccess,+ onError: () =>+ setError('Could not update contact visibility'),+ }+ );+ }}+ />+ <output aria-label="Contact identity">+ {record().id} / {record().companyId ?? 'unfiled'}+ </output>+ <Show when={error()}>+ <p role="alert">{error()}</p>+ </Show>+ </div>+ )}+ </Show>+ );+}+function Fixture() {+ const [contactId, setContactId] = createSignal<string>();+ const [keepTeam, setKeepTeam] = createSignal(false);+ return (+ <QueryClientProvider client={client}>+ <main class="flex h-dvh flex-col bg-panel text-ink">+ <h1 class="p-4 text-xl font-semibold">Example company</h1>+ <nav class="flex flex-wrap gap-2 p-4" aria-label="Fixture navigation">+ <Button onClick={() => setContactId(undefined)}>Company Team</Button>+ <Button onClick={() => setContactId('visible-contact')}>+ Open contact directly+ </Button>+ <Button onClick={() => setContactId('removed-contact')}>+ Open removed directly+ </Button>+ <Button onClick={() => setContactId('unfiled-contact')}>+ Open unfiled directly+ </Button>+ <Button onClick={() => setKeepTeam((value) => !value)}>+ Keep Team mounted+ </Button>+ <Button onClick={() => setFailNext(true)} disabled={failNext()}>+ Fail next write+ </Button>+ <Button+ onClick={() => setRole(role() === 'member' ? 'admin' : 'member')}+ >+ Toggle member role+ </Button>+ </nav>+ <Suspense fallback={<p>Loading</p>}>+ <Show when={contactId()}>{(id) => <Detail id={id()} />}</Show>+ <Show when={!contactId() || keepTeam()}>+ <Team open={setContactId} />+ </Show>+ </Suspense>+ <output aria-label="Company reads">{companyReads()}</output>+ <output aria-label="Successful writes">{writes()}</output>+ </main>+ </QueryClientProvider>+ );+}+render(Fixture, document.getElementById('root')!);diff --git a/apps/web/src/features/crm/browser-test/team/index.html b/apps/web/src/features/crm/browser-test/team/index.htmlnew file mode 100644index 0000000000..23ecada925--- /dev/null+++ b/apps/web/src/features/crm/browser-test/team/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 company Team visibility</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/team/playwright.config.ts b/apps/web/src/features/crm/browser-test/team/playwright.config.tsnew file mode 100644index 0000000000..2f0a2cc02a--- /dev/null+++ b/apps/web/src/features/crm/browser-test/team/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_TEAM_BROWSER_PORT ?? 23941);+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/team/vite.config.ts && bunx vite preview --config src/features/crm/browser-test/team/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/team/preview-adapters.ts b/apps/web/src/features/crm/browser-test/team/preview-adapters.tsnew file mode 100644index 0000000000..db1003e819--- /dev/null+++ b/apps/web/src/features/crm/browser-test/team/preview-adapters.ts@@ -0,0 +1,90 @@+import type { storageServiceClient as Storage } from '@service-storage/client';+import type { CrmCompanyResponse } from '@service-storage/generated/schemas/crmCompanyResponse';+import type { CrmContactResponse } from '@service-storage/generated/schemas/crmContactResponse';+import { err, ok } from 'neverthrow';+import { createSignal } from 'solid-js';++export const NIL_UUID = '00000000-0000-0000-0000-000000000000';+export const analytics = { track() {} };+export async function invalidateCachedCrmContacts() {}+export const useCrmContext = () => ({+ createNavigation: () => ({ openWithSplit() {} }),+ openCreateContact() {},+});++const CONTACT: CrmContactResponse = {+ id: 'visible-contact',+ companyId: 'company-1',+ name: 'Visible person',+ email: '[email protected]',+ hidden: false,+ createdAt: '2026-10-15',+ updatedAt: '2026-10-15',+ firstInteraction: '2026-10-15',+ lastInteraction: '2026-10-15',+};+let contacts: CrmContactResponse[] = [+ CONTACT,+ {+ ...CONTACT,+ id: 'removed-contact',+ name: 'Removed person',+ email: '[email protected]',+ hidden: true,+ },+ {+ ...CONTACT,+ id: 'unfiled-contact',+ name: 'Unfiled person',+ email: '[email protected]',+ companyId: null,+ },+];+export const [role, setRole] = createSignal('admin');+export const [failNext, setFailNext] = createSignal(false);+export const [companyReads, setCompanyReads] = createSignal(0);+export const [writes, setWrites] = createSignal(0);++export const storageServiceClient = {+ async getCompany() {+ setCompanyReads((count) => count + 1);+ const company: CrmCompanyResponse = {+ id: 'company-1',+ name: 'Example company',+ teamId: 'team-1',+ hidden: false,+ emailSync: false,+ domains: [],+ createdAt: '2026-10-15',+ updatedAt: '2026-10-15',+ contacts: contacts.filter(+ (contact) =>+ contact.companyId === 'company-1' &&+ (role() !== 'member' || !contact.hidden)+ ),+ };+ return ok(company);+ },+ async getContact({ contactId }) {+ const contact = contacts.find((item) => item.id === contactId);+ if (!contact || (role() === 'member' && contact.hidden))+ return err([{ code: 'NOT_FOUND', message: 'Not found' }]);+ return ok(contact);+ },+ async setContactHidden({ contactId, hidden }) {+ if (role() === 'member' || failNext()) {+ 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,+ 'getCompany' | 'getContact' | 'setContactHidden'+>;diff --git a/apps/web/src/features/crm/browser-test/team/team.browser.e2e.ts b/apps/web/src/features/crm/browser-test/team/team.browser.e2e.tsnew file mode 100644index 0000000000..9a35df35e0--- /dev/null+++ b/apps/web/src/features/crm/browser-test/team/team.browser.e2e.ts@@ -0,0 +1,110 @@+import { expect, type Page, test } from '@playwright/test';++async function confirmVisibility(page: Page, label: string) {+ await page.getByRole('button', { name: label, exact: true }).click();+ const dialog = page.getByRole('dialog');+ await expect(dialog).toBeInViewport({ ratio: 1 });+ await expect(dialog).not.toHaveAttribute('data-transitioning');+ await dialog.getByRole('button', { name: label, exact: true }).click();+}++test.beforeEach(async ({ page }) => {+ await page.route('https://**', (route) => route.abort());+ await page.routeWebSocket('**', (socket) => socket.close());+ await page.goto('/');+});++test('admin Team excludes removed rows and refreshes after navigating away to hide and restore', async ({+ page,+}, info) => {+ const visible = page.getByRole('button', { name: /Visible person/ });+ await expect(visible).toBeVisible();+ await expect(+ page.getByRole('button', { name: /Removed person/ })+ ).toHaveCount(0);+ await page.getByRole('searchbox', { name: 'Search team' }).fill('removed');+ await expect(page.getByText('No matching contacts.')).toBeVisible();+ await page.getByRole('searchbox', { name: 'Search team' }).fill('');+ await page.screenshot({ path: info.outputPath('team-before.png') });+ await visible.click();+ await expect(page.getByRole('region', { name: 'Team' })).toHaveCount(0);+ await confirmVisibility(page, 'Remove from CRM');+ await expect(page.getByRole('dialog')).toHaveCount(0);+ await expect(page.getByLabel('Contact identity')).toHaveText(+ 'visible-contact / company-1'+ );+ await page.getByRole('button', { name: 'Company Team', exact: true }).click();+ await expect(page.getByText('No contacts yet')).toBeVisible();+ await expect(visible).toHaveCount(0);+ await expect(page.getByLabel('Company reads')).toHaveText('2');+ await page.screenshot({ path: info.outputPath('team-removed.png') });+ await page.getByRole('button', { name: 'Open contact directly' }).click();+ await confirmVisibility(page, 'Restore to CRM');+ await expect(page.getByRole('dialog')).toHaveCount(0);+ await page.getByRole('button', { name: 'Company Team', exact: true }).click();+ await expect(visible).toBeVisible();+ await expect(page.getByLabel('Successful writes')).toHaveText('2');+ await expect(page.getByLabel('Company reads')).toHaveText('3');+ await page.screenshot({ path: info.outputPath('team-restored.png') });+});++test('mounted Team updates on hide and restore; rejected writes and member controls preserve state', async ({+ page,+}) => {+ await expect(+ page.getByRole('button', { name: /Visible person/ })+ ).toBeVisible();+ await page.getByRole('button', { name: 'Keep Team mounted' }).click();+ await page.getByRole('button', { name: /Visible person/ }).click();+ await page.getByRole('button', { name: 'Fail next write' }).click();+ await confirmVisibility(page, 'Remove from CRM');+ await expect(page.getByRole('alert', { includeHidden: true })).toHaveText(+ 'Could not update contact visibility'+ );+ await expect(+ page.getByRole('button', { name: /Visible person/, includeHidden: true })+ ).toBeVisible();+ await expect(page.getByLabel('Successful writes')).toHaveText('0');+ await page+ .getByRole('dialog')+ .getByRole('button', { name: 'Remove from CRM', exact: true })+ .click();+ await expect(page.getByRole('dialog')).toHaveCount(0);+ await expect(+ page.getByRole('button', { name: /Visible person/ })+ ).toHaveCount(0);+ await confirmVisibility(page, 'Restore to CRM');+ await expect(page.getByRole('dialog')).toHaveCount(0);+ await expect(+ page.getByRole('button', { name: /Visible person/ })+ ).toBeVisible();+ await page.getByRole('button', { name: 'Toggle member role' }).click();+ await expect(+ page.getByRole('button', { name: 'Remove from CRM', exact: true })+ ).toBeDisabled();+ await page.getByRole('button', { name: 'Open removed directly' }).click();+ await expect(page.getByText('Contact unavailable')).toBeVisible();+});++test('unfiled contact keeps its identity through removal and restoration', async ({+ page,+}) => {+ await page.getByRole('button', { name: 'Open unfiled directly' }).click();+ await confirmVisibility(page, 'Remove from CRM');+ await expect(page.getByRole('dialog')).toHaveCount(0);+ await expect(page.getByLabel('Contact identity')).toHaveText(+ 'unfiled-contact / unfiled'+ );+ await confirmVisibility(page, 'Restore to CRM');+ await expect(page.getByRole('dialog')).toHaveCount(0);+ await expect(page.getByLabel('Contact identity')).toHaveText(+ 'unfiled-contact / unfiled'+ );+ await page.getByRole('button', { name: 'Company Team', exact: true }).click();+ await expect(+ page.getByRole('button', { name: /Visible person/ })+ ).toBeVisible();+ await expect(+ page.getByRole('button', { name: /Unfiled person/ })+ ).toHaveCount(0);+});diff --git a/apps/web/src/features/crm/browser-test/team/vite.config.ts b/apps/web/src/features/crm/browser-test/team/vite.config.tsnew file mode 100644index 0000000000..9b850515a1--- /dev/null+++ b/apps/web/src/features/crm/browser-test/team/vite.config.ts@@ -0,0 +1,49 @@+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: [+ ...[+ '@service-storage/client',+ '@service-storage/crm-contacts',+ '@app/lib/analytics',+ '@app/features/next-soup/filters/filter-store',+ '../context/crm-context',+ ].map((find) => ({+ find,+ replacement: `${directory}/preview-adapters.ts`,+ })),+ { find: /^@entity$/, replacement: `${directory}/entity-preview.tsx` },+ {+ 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/browser-test/visibility.browser.e2e.ts b/apps/web/src/features/crm/browser-test/visibility.browser.e2e.tsindex 90799565f7..bc23a3b853 100644--- a/apps/web/src/features/crm/browser-test/visibility.browser.e2e.ts+++ b/apps/web/src/features/crm/browser-test/visibility.browser.e2e.ts@@ -25,12 +25,16 @@ for (const device of [await page.route('**/__macro_dev/**', (route) => route.abort());});- for (const kind of ['company', 'contact']) {- test(`${kind} removal can cancel, retry and restore`, async ({+ for (const { kind, grouped } of [+ { kind: 'company', grouped: false },+ { kind: 'contact', grouped: false },+ { kind: 'contact', grouped: true },+ ]) {+ test(`${kind}${grouped ? ' grouped' : ''} removal can cancel, retry and restore`, async ({page,}, testInfo) => {await page.goto(- `/src/features/crm/browser-test/visibility.html?kind=${kind}`+ `/src/features/crm/browser-test/visibility.html?kind=${kind}&grouped=${grouped}`);const remove = page.getByRole('button', {name: 'Remove from CRM',@@ -43,6 +47,7 @@ for (const device of [await expect(dialog).not.toHaveAttribute('data-transitioning');await page.keyboard.press('Escape');await expect(dialog).not.toBeVisible();+ if (kind === 'contact') await expect(remove).toBeFocused();await expect(page.getByLabel('Visibility writes')).toHaveText('0');await remove.click();@@ -79,6 +84,9 @@ for (const device of [await expect(page.getByLabel('Visibility writes')).toHaveText('3');await page.getByRole('button', { name: 'Toggle admin role' }).click();await expect(remove).toBeDisabled();+ await expect(remove).toHaveAccessibleDescription(+ 'Ask a team admin or owner to remove or restore this record.'+ );});}diff --git a/apps/web/src/features/crm/browser-test/visibility.tsx b/apps/web/src/features/crm/browser-test/visibility.tsxindex 55c0f731c8..f0c4a1bfc8 100644--- a/apps/web/src/features/crm/browser-test/visibility.tsx+++ b/apps/web/src/features/crm/browser-test/visibility.tsx@@ -1,7 +1,8 @@import '@app/index.css';+import { HeaderActionGroup } from '@components/app/HeaderActionGroup';import { isTouchDevice } from '@core/mobile/isTouchDevice';import { Button } from '@ui';-import { createSignal } from 'solid-js';+import { createSignal, Show } from 'solid-js';import { render } from 'solid-js/web';import { RecordOverview } from '../components/record-overview';import { RecordVisibilityAction } from '../components/record-visibility-action';@@ -10,6 +11,7 @@ import { RecordVisibilityAction } from '../components/record-visibility-action';// changing hosted CRM data. The action and responsive confirmation are production UI.document.documentElement.dataset.touchDevice = String(isTouchDevice());const params = new URLSearchParams(location.search);+const grouped = params.get('grouped') === 'true';const kind = params.get('kind') === 'contact' ? 'contact' : 'company';function Fixture() {@@ -28,31 +30,41 @@ function Fixture() {},});+ const VisibilityAction = () => (+ <RecordVisibilityAction+ iconOnly={kind === 'contact'}+ grouped={grouped}+ recordId={recordId()}+ kind={kind}+ name={kind === 'company' ? 'Acme' : 'Maya Chen'}+ hidden={hidden()}+ pending={pending()}+ canManage={canManage()}+ onChange={(value, onSuccess) => {+ setPending(true);+ setWrites((count) => count + 1);+ finish = (success) => {+ finish = undefined;+ setPending(false);+ if (!success) return;+ setHidden(value);+ onSuccess();+ };+ }}+ />+ );+return (<main class="flex h-dvh flex-col bg-panel text-ink"><RecordOverview><h1 class="text-2xl font-semibold">{kind === 'company' ? 'Acme' : 'Maya Chen'}</h1>- <RecordVisibilityAction- recordId={recordId()}- kind={kind}- name={kind === 'company' ? 'Acme' : 'Maya Chen'}- hidden={hidden()}- pending={pending()}- canManage={canManage()}- onChange={(value, onSuccess) => {- setPending(true);- setWrites((count) => count + 1);- finish = (success) => {- finish = undefined;- setPending(false);- if (!success) return;- setHidden(value);- onSuccess();- };- }}- />+ <Show when={grouped} fallback={<VisibilityAction />}>+ <HeaderActionGroup label="Contact actions">+ <VisibilityAction />+ </HeaderActionGroup>+ </Show><output aria-label="Visibility writes">{writes()}</output><Button onClick={() => setCanManage((value) => !value)}>Toggle admin rolediff --git a/apps/web/src/features/crm/components/record-visibility-action.tsx b/apps/web/src/features/crm/components/record-visibility-action.tsxindex f57d8bdd1b..13e775e854 100644--- a/apps/web/src/features/crm/components/record-visibility-action.tsx+++ b/apps/web/src/features/crm/components/record-visibility-action.tsx@@ -1,7 +1,9 @@+import { isTouchDevice } from '@core/mobile/isTouchDevice';import EyeIcon from '@icon/system/regular/eye.svg';import EyeSlashIcon from '@icon/system/regular/eye-slash.svg';-import { Button, ConfirmDialog } from '@ui';-import { createSignal, Show } from 'solid-js';+import { Button, ButtonGroup, ConfirmDialog } from '@ui';+import { createSignal, createUniqueId, Show } from 'solid-js';+import { Dynamic } from 'solid-js/web';type RecordVisibilityActionProps = {recordId: string;@@ -10,6 +12,8 @@ type RecordVisibilityActionProps = {hidden: boolean;canManage: boolean;pending: boolean;+ iconOnly?: boolean;+ grouped?: boolean;onChange: (hidden: boolean, onSuccess: () => void) => void;};@@ -24,36 +28,81 @@ export function RecordVisibilityAction(props: RecordVisibilityActionProps) {function VisibilityControl(props: RecordVisibilityActionProps) {const [confirming, setConfirming] = createSignal(false);+ const permissionHintId = createUniqueId();+ const permissionHint =+ 'Ask a team admin or owner to remove or restore this record.';+ let button: HTMLButtonElement | undefined;const label = () => (props.hidden ? 'Restore to CRM' : 'Remove from CRM');+ const tooltip = () => {+ if (!props.iconOnly) return;+ return props.canManage ? label() : permissionHint;+ };+ const size = () => {+ if (!props.iconOnly) return;+ if (isTouchDevice()) return 'icon-lg';+ return props.grouped ? 'icon-sm' : 'icon-md';+ };return (- <div class="flex flex-col items-start gap-2">- <Button- variant="secondary"+ <div+ class={props.iconOnly ? 'contents' : 'flex flex-col items-start gap-2'}+ >+ <Dynamic+ component={props.grouped ? ButtonGroup.Button : Button}+ ref={button}+ variant={props.iconOnly ? 'ghost' : 'secondary'}+ size={size()}+ aria-label={label()}+ aria-describedby={!props.canManage ? permissionHintId : undefined}+ tooltip={tooltip()}disabled={!props.canManage || props.pending}onClick={() => setConfirming(true)}>- <Show when={props.hidden} fallback={<EyeSlashIcon class="size-4" />}>- <EyeIcon class="size-4" />+ <Show+ when={props.hidden}+ fallback={+ <EyeSlashIcon+ class={props.iconOnly ? 'size-4 touch:size-6' : 'size-4'}+ />+ }+ >+ <EyeIcon class={props.iconOnly ? 'size-4 touch:size-6' : 'size-4'} /></Show>- {label()}- </Button>- <Show when={props.hidden}>+ <Show when={!props.iconOnly}>{label()}</Show>+ </Dynamic>+ <Show when={props.hidden && !props.iconOnly}><p class="text-xs text-ink-muted">This {props.kind === 'company' ? 'company' : 'person'} is hidden fromyour team's CRM lists.</p></Show><Show when={!props.canManage}>- <p class="text-xs text-ink-muted">- Ask a team admin or owner to remove or restore this record.+ <p+ id={permissionHintId}+ class={props.iconOnly ? 'sr-only' : 'text-xs text-ink-muted'}+ >+ {permissionHint}</p></Show><ConfirmDialogopen={confirming()}onOpenChange={setConfirming}+ onCloseAutoFocus={+ props.iconOnly+ ? (event) => {+ event.preventDefault();+ button?.focus();+ }+ : undefined+ }title={`${label()}?`}- confirmLabel={label()}+ confirmLabel={+ props.iconOnly ? (+ <span class="whitespace-normal">{label()}</span>+ ) : (+ label()+ )+ }pending={props.pending}onConfirm={() => {if (!props.canManage || props.pending) return;diff --git a/apps/web/src/features/crm/crm-contact.tsx b/apps/web/src/features/crm/crm-contact.tsxindex 81ba69a1a5..30ac70223d 100644--- a/apps/web/src/features/crm/crm-contact.tsx+++ b/apps/web/src/features/crm/crm-contact.tsx@@ -4,6 +4,7 @@ import { CrmProvider } from './context/crm-context';import { CONTACT_SECTIONS, type ContactSection } from './core/record';import { createAppCrmContext } from './crm-adapter';import { Contact as View } from './views/contact-detail';+import { ContactVisibilityButton as VisibilityButton } from './views/contact-visibility-button';export type { ContactSection } from './core/record';@@ -23,3 +24,14 @@ export function ContactTabs(props: {}) {return <RecordTabs sections={CONTACT_SECTIONS} {...props} />;}++/** The contact visibility action, for a host's top bar. */+export function ContactVisibilityButton(+ props: ComponentProps<typeof VisibilityButton>+) {+ return (+ <CrmProvider value={createAppCrmContext()}>+ <VisibilityButton {...props} />+ </CrmProvider>+ );+}diff --git a/apps/web/src/features/crm/queries/contact-visibility.test.tsx b/apps/web/src/features/crm/queries/contact-visibility.test.tsxnew file mode 100644index 0000000000..08dc76a638--- /dev/null+++ b/apps/web/src/features/crm/queries/contact-visibility.test.tsx@@ -0,0 +1,158 @@+import { storageServiceClient } from '@service-storage/client';+import { invalidateCachedCrmContacts } from '@service-storage/crm-contacts';+import type { CrmContactResponse } from '@service-storage/generated/schemas/crmContactResponse';+import { cleanup, render } from '@solidjs/testing-library';+import { QueryClient, QueryObserver } from '@tanstack/solid-query';+import { err, ok } from 'neverthrow';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { useContactQuery, useSetContactHiddenMutation } from './contacts';+import { crmKeys } from './keys';++vi.mock('@service-storage/client', () => ({+ storageServiceClient: { setContactHidden: vi.fn(), getContact: vi.fn() },+}));+vi.mock('@service-storage/crm-contacts', () => ({+ invalidateCachedCrmContacts: vi.fn(async () => {}),+}));++const CONTACT: CrmContactResponse = {+ id: 'contact-1',+ companyId: 'company-1',+ name: 'Example person',+ email: '[email protected]',+ hidden: false,+ createdAt: '2026-10-15',+ updatedAt: '2026-10-15',+ firstInteraction: '2026-10-15',+ lastInteraction: '2026-10-15',+};+let client: QueryClient;+let contact: CrmContactResponse;++beforeEach(() => {+ vi.clearAllMocks();+ contact = { ...CONTACT };+ client = new QueryClient({+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },+ });+ vi.mocked(storageServiceClient.setContactHidden).mockImplementation(+ async ({ hidden }) => {+ contact = { ...contact, hidden };+ return ok(undefined);+ }+ );+ vi.mocked(storageServiceClient.getContact).mockImplementation(async () =>+ ok({ ...contact })+ );+ vi.mocked(invalidateCachedCrmContacts).mockResolvedValue(undefined);+});+afterEach(() => {+ cleanup();+ client.clear();+});++function mount() {+ let mutation!: ReturnType<typeof useSetContactHiddenMutation>;+ let detail!: ReturnType<typeof useContactQuery>;+ render(() => {+ const deps = { client, storage: storageServiceClient };+ mutation = useSetContactHiddenMutation(deps);+ detail = useContactQuery(deps, () => CONTACT.id);+ return null;+ });+ return { mutation, detail };+}++it('refreshes active company lists on hide and restore while preserving admin detail access', async () => {+ const company = new QueryObserver(client, {+ queryKey: crmKeys.company('company-1').queryKey,+ queryFn: async () => ({ contacts: [{ ...contact }] }),+ staleTime: Infinity,+ });+ const unsubscribe = company.subscribe(() => {});+ await company.refetch();+ const { mutation } = mount();+ for (const hidden of [true, false]) {+ await mutation.mutateAsync({ contactId: CONTACT.id, hidden });+ expect(company.getCurrentResult().data?.contacts).toEqual([+ { ...CONTACT, hidden },+ ]);+ expect(client.getQueryData(crmKeys.contact(CONTACT.id).queryKey)).toEqual({+ ...CONTACT,+ hidden,+ });+ }+ unsubscribe();+});++it('invalidates an inactive company so returning to Team reloads its contacts', async () => {+ const options = {+ queryKey: crmKeys.company('company-1').queryKey,+ queryFn: async () => ({ contacts: [{ ...contact }] }),+ staleTime: Infinity,+ };+ await client.fetchQuery(options);+ const { mutation } = mount();+ await mutation.mutateAsync({ contactId: CONTACT.id, hidden: true });+ expect(client.getQueryState(options.queryKey)?.isInvalidated).toBe(true);+ expect((await client.fetchQuery(options)).contacts).toEqual([+ { ...CONTACT, hidden: true },+ ]);+});++it('hides and restores contacts without a company or an invented company query', async () => {+ contact = { ...CONTACT, companyId: null };+ const { mutation } = mount();+ for (const hidden of [true, false]) {+ await mutation.mutateAsync({ contactId: CONTACT.id, hidden });+ expect(client.getQueryData(crmKeys.contact(CONTACT.id).queryKey)).toEqual({+ ...CONTACT,+ companyId: null,+ hidden,+ });+ expect(+ client.getQueryCache().findAll({ queryKey: crmKeys.company._def })+ ).toHaveLength(0);+ }+});++it('leaves cached lists unchanged and surfaces a rejected visibility write', async () => {+ vi.mocked(storageServiceClient.setContactHidden).mockResolvedValue(+ err([{ code: 'FORBIDDEN', message: 'Denied' }])+ );+ const key = crmKeys.company('company-1').queryKey;+ const cached = { contacts: [CONTACT] };+ client.setQueryData(key, cached);+ const { mutation } = mount();+ await expect(+ mutation.mutateAsync({ contactId: CONTACT.id, hidden: true })+ ).rejects.toThrow();+ expect(client.getQueryData(key)).toEqual(cached);+ expect(client.getQueryState(key)?.isInvalidated).toBe(false);+ expect(invalidateCachedCrmContacts).not.toHaveBeenCalled();+});++it('preserves a member denial when loading a hidden contact directly', async () => {+ vi.mocked(storageServiceClient.getContact).mockResolvedValue(+ err([{ code: 'NOT_FOUND', message: 'Not found' }])+ );+ const { detail } = mount();+ await detail.refetch();+ expect(+ client.getQueryState(crmKeys.contact(CONTACT.id).queryKey)?.status+ ).toBe('error');+ expect(+ client.getQueryData(crmKeys.contact(CONTACT.id).queryKey)+ ).toBeUndefined();+});++it('surfaces a cache refresh failure after a successful write', async () => {+ vi.mocked(invalidateCachedCrmContacts).mockRejectedValueOnce(+ new Error('Cache unavailable')+ );+ const { mutation } = mount();+ await expect(+ mutation.mutateAsync({ contactId: CONTACT.id, hidden: true })+ ).rejects.toThrow('Cache unavailable');+ expect(contact.hidden).toBe(true);+});diff --git a/apps/web/src/features/crm/queries/contacts.ts b/apps/web/src/features/crm/queries/contacts.tsindex 7f28fdc984..27c7f274b7 100644--- a/apps/web/src/features/crm/queries/contacts.ts+++ b/apps/web/src/features/crm/queries/contacts.ts@@ -144,12 +144,13 @@ export function useSetContactNameMutation(deps: CrmRecordDependencies) {/*** Toggles `crm_contacts.hidden` via `PUT /crm/contacts/{id}/hidden`.- * Hidden contacts disappear from the parent company's contact list- * (non-admin view) and from any soup surface that filters them.+ * Hidden contacts disappear from normal company Team lists for every role+ * and from any soup surface that filters them. Authorized detail reads still+ * include hidden contacts for restoration.** Awaits cache invalidation in the visibility trace so the mutation- * stays pending until both the contact query and the soup queries- * refetch — the toggle state and any dependent UI all flip in one beat.+ * stays pending until active contact, company and soup queries refetch.+ * Inactive company queries become stale and reload when revisited.*/export function useSetContactHiddenMutation(deps: CrmRecordDependencies) {return useMutation(@@ -179,6 +180,11 @@ export function useSetContactHiddenMutation(deps: CrmRecordDependencies) {deps.client.invalidateQueries({queryKey: crmKeys.contact(contactId).queryKey,}),+ // Company responses embed contacts. Invalidate the family+ // even when no contact detail (or company ID) is cached.+ deps.client.invalidateQueries({+ queryKey: crmKeys.company._def,+ }),]);} catch (error) {refresh.error('Contact visibility refresh failed');diff --git a/apps/web/src/features/crm/views/company-contacts-section.test.tsx b/apps/web/src/features/crm/views/company-contacts-section.test.tsxindex 62c936eef9..38f002bfdb 100644--- a/apps/web/src/features/crm/views/company-contacts-section.test.tsx+++ b/apps/web/src/features/crm/views/company-contacts-section.test.tsx@@ -153,3 +153,28 @@ it('filters by email and keeps the search available with no results', () => {screen.getByRole('button', { name: /Avery Chen/ });expect(screen.getByRole('textbox', { name: 'Search team' })).toBe(search);});++it('excludes hidden contacts from an admin response, including search matches', () => {+ const removed = {+ ...contacts[0],+ id: 'removed',+ hidden: true,+ name: 'Removed person',+ };+ const response = [...contacts, removed];+ render(() => (+ <CompanyContactsSection+ company={{ id: 'co' } as CrmCompanyEntity}+ contacts={response}+ />+ ));+ screen.getByRole('button', { name: /Avery Chen/ });+ expect(screen.queryByRole('button', { name: /Removed person/ })).toBeNull();+ fireEvent.input(screen.getByRole('textbox', { name: 'Search team' }), {+ target: { value: 'Removed person' },+ });+ screen.getByText('No matching contacts.');+ // Presentation must preserve the record for authorized detail/restore access.+ expect(response).toContain(removed);+ expect(removed.companyId).toBe('co');+});diff --git a/apps/web/src/features/crm/views/company-contacts-section.tsx b/apps/web/src/features/crm/views/company-contacts-section.tsxindex c143f4ecfb..e705b07f23 100644--- a/apps/web/src/features/crm/views/company-contacts-section.tsx+++ b/apps/web/src/features/crm/views/company-contacts-section.tsx@@ -76,9 +76,10 @@ export function CompanyContactsSection(props: {const query = search().trim().toLowerCase();return (props.contacts ?? []).filter((contact) =>- !query ||- contact.name?.toLowerCase().includes(query) ||- contact.email?.toLowerCase().includes(query)+ !contact.hidden &&+ (!query ||+ contact.name?.toLowerCase().includes(query) ||+ contact.email?.toLowerCase().includes(query)));});const createContact = () => {diff --git a/apps/web/src/features/crm/views/contact-detail.tsx b/apps/web/src/features/crm/views/contact-detail.tsxindex afbea57fb7..f614d8e615 100644--- a/apps/web/src/features/crm/views/contact-detail.tsx+++ b/apps/web/src/features/crm/views/contact-detail.tsx@@ -3,7 +3,6 @@ import { SidePanel } from '@components/app/side-panel';import { createMemo, Match, onCleanup, Show, Suspense, Switch } from 'solid-js';import { CrmListSkeleton } from '../components/list-state';import { RecordOverview } from '../components/record-overview';-import { RecordVisibilityAction } from '../components/record-visibility-action';import { useCrmContext } from '../context/crm-context';import {type ContactSection,@@ -20,11 +19,7 @@ import {RecordFilesSection,RecordReferencesSection,} from './record-associations';-import {- useContactQuery,- useIsTeamAdmin,- useSetContactHiddenMutation,-} from './use-crm';+import { useContactQuery, useIsTeamAdmin } from './use-crm';/*** Root of the contact detail view, laid out like a project: the host's top@@ -69,7 +64,6 @@ function ContactContent(props: ContactProps) {})));const isTeamAdmin = useIsTeamAdmin();- const hiddenMutation = useSetContactHiddenMutation();const section = () => props.section ?? 'overview';const scope = createMemo((): CrmRecordScope | undefined => {@@ -101,37 +95,6 @@ function ContactContent(props: ContactProps) {contact={contact()}onOpenCompany={props.onOpenCompany}/>- <Show when={contact()}>- {(current) => (- <RecordVisibilityAction- recordId={current().id}- kind="contact"- name={current().name ?? current().email ?? 'Contact'}- hidden={current().hidden}- canManage={isTeamAdmin()}- pending={hiddenMutation.isPending}- onChange={(hidden, onSuccess) =>- hiddenMutation.mutate(- { contactId: current().id, hidden },- {- onSuccess: () => {- onSuccess();- context.feedback.success(- hidden- ? 'Person removed from CRM'- : 'Person restored to CRM'- );- },- onError: () =>- context.feedback.failure(- 'Could not update contact visibility'- ),- }- )- }- />- )}- </Show><Show when={pipelinesEnabled()}><context.PipelineEntriesrecord={{ type: 'contact', id: props.contactId }}diff --git a/apps/web/src/features/crm/views/contact-visibility-button.tsx b/apps/web/src/features/crm/views/contact-visibility-button.tsxnew file mode 100644index 0000000000..c23d600a62--- /dev/null+++ b/apps/web/src/features/crm/views/contact-visibility-button.tsx@@ -0,0 +1,54 @@+import { Show } from 'solid-js';+import { RecordVisibilityAction } from '../components/record-visibility-action';+import { useCrmContext } from '../context/crm-context';+import {+ useContactQuery,+ useIsTeamAdmin,+ useSetContactHiddenMutation,+} from './use-crm';++export function ContactVisibilityButton(props: {+ contactId: string;+ grouped?: boolean;+}) {+ const context = useCrmContext();+ const contactQuery = useContactQuery(() => props.contactId);+ const isTeamAdmin = useIsTeamAdmin();+ const hiddenMutation = useSetContactHiddenMutation();++ return (+ <Show when={contactQuery.data}>+ {(current) => (+ <RecordVisibilityAction+ iconOnly+ grouped={props.grouped}+ recordId={current().id}+ kind="contact"+ name={current().name ?? current().email ?? 'Contact'}+ hidden={current().hidden}+ canManage={isTeamAdmin()}+ pending={hiddenMutation.isPending}+ onChange={(hidden, onSuccess) =>+ hiddenMutation.mutate(+ { contactId: current().id, hidden },+ {+ onSuccess: () => {+ onSuccess();+ context.feedback.success(+ hidden+ ? 'Person removed from CRM'+ : 'Person restored to CRM'+ );+ },+ onError: () =>+ context.feedback.failure(+ 'Could not update contact visibility'+ ),+ }+ )+ }+ />+ )}+ </Show>+ );+}diff --git a/apps/web/src/features/crm/views/record-detail.tsx b/apps/web/src/features/crm/views/record-detail.tsxindex dd9cb9f94c..3fe3a91a0c 100644--- a/apps/web/src/features/crm/views/record-detail.tsx+++ b/apps/web/src/features/crm/views/record-detail.tsx@@ -38,6 +38,7 @@ import {} from '../core/record';import { Company } from './company-detail';import { Contact } from './contact-detail';+import { ContactVisibilityButton } from './contact-visibility-button';import { CrmCopyLinkButton } from './copy-link-button';import { useCompanyQuery, useContactQuery } from './use-crm';@@ -204,12 +205,21 @@ export function CrmRecordDetail(props: {</Show></div><div class="ml-auto flex shrink-0 items-center gap-2 touch:gap-1">- <HeaderActionGroup label="Sharing">+ <HeaderActionGroup+ label={+ current().type === 'contact' ? 'Contact actions' : 'Sharing'+ }+ ><CrmCopyLinkButtongroupedtype={current().type}id={current().id}/>+ <Show when={current().type === 'contact' && current().id} keyed>+ {(contactId) => (+ <ContactVisibilityButton grouped contactId={contactId} />+ )}+ </Show></HeaderActionGroup><SidePanel.Toggle /></div>diff --git a/docs/agent-guide/crm.md b/docs/agent-guide/crm.mdindex b2d3a5ce1d..a10b2ce342 100644--- a/docs/agent-guide/crm.md+++ b/docs/agent-guide/crm.md@@ -220,17 +220,23 @@ queries or creation actions. Copy-link islands are 40px square on touch witha 24px icon. Verify both record types, section changes, dismissal, copy feedback,and header fit at phone and tablet widths.-To remove a company or person manually, open its **Overview**, choose **Remove-from CRM** below its details, and confirm. On phones the confirmation is a bottom-sheet. Only team admins and owners can remove or restore records; other members-see a disabled action and an explanation. Removal hides the record from the+To remove a person manually, choose the eye-slash **Remove from CRM** button+beside **Copy contact link** in the top toolbar and confirm. Hidden people show+the regular eye **Restore to CRM** action in the same place. Both the Customers+record header and standalone contact header offer it on every section; there is+no second action in Overview. Company removal stays below the details on+**Overview**. On phones the confirmation is a bottom sheet. Only team admins+and owners can remove or restore records; other members see a disabled action. Removal hides the record from theteam's CRM lists without permanently deleting it. The page stays open and offers**Restore to CRM**; admins can also reopen the record's direct link to restore it.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. Admins can still inspect hidden contacts in a company's Team-tab. The existing **Sharing → Visible in CRM** checkbox and company row **Hide /+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;+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.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 restored