Skip to content

armgit / macro

Public Imported from GitHub
0

Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.

feat(crm): unify archive and restore controls (#9572)

gbirmanb12526343d5e
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 3571cb9294..caad395c95 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -431,17 +431,20 @@ resolved session ID; keep the existing `AgentSessionProvider` subscription to
Record search fills the row beside filters with header spacing; section creation
replaces the default floating dock action through FloatRegion. See
`src/features/crm/README.md` and `docs/agent-guide/crm.md` at the repo root.
- Keep record Remove/Restore actions out of the information panel: contact Sharing
- is absent, and company Sharing contains only permission-gated Sync Emails.
- Company Team lists exclude hidden contacts for every role; keep authorized
- detail/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`.
+ Put Archive beside Copy link for visible CRM records; put the Archived chip and
+ separate borderless Restore action in the identity heading for archived records.
+ Keep explanations on the chip and retain company-only Email sharing controls.
+ Use the explicit Visible/Archived filter for People, Companies and company Team;
+ reset its admin-only choice on account/team/role/list changes and preserve search.
+ Apply confirmed visibility changes to detail, list and normalized search caches;
+ fence in-flight pre-write responses and refresh only affected CRM readers.
+ Declare CRM membership dependencies from each Soup query's initial filter scope
+ on every page so empty late responses are fenced without refreshing excluded types.
+ Recover missing dependencies before forwarding durable/imperative revalidations;
+ a later observer may share an in-flight request without forwarding its context.
+ Preserve company cascade semantics and require company restoration before a person.
+ Run desktop/phone controls with `bunx playwright test --config src/features/crm/browser-test/archive/playwright.config.ts`;
+ `browser-test/people` and `browser-test/team` additionally cover synthetic query adapters.
- 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-company/component/CompanyBlockAdapter.tsx b/apps/web/src/features/block-company/component/CompanyBlockAdapter.tsx
index fb8bb4d465..cdd62c62a6 100644
--- a/apps/web/src/features/block-company/component/CompanyBlockAdapter.tsx
+++ b/apps/web/src/features/block-company/component/CompanyBlockAdapter.tsx
@@ -2,6 +2,7 @@ import {
Company,
type CompanySection,
CompanyTabs,
+ CompanyVisibilityButton,
} from '@app/features/crm/crm-company';
import { CrmCopyLinkButton } from '@app/features/crm/crm-link';
import { CollapsibleHeaderItem } from '@components/app/split-layout/components/CollapsibleItem';
@@ -59,6 +60,7 @@ export function CompanyBlockAdapter() {
<SplitHeaderRight>
<HeaderIsland class="p-0">
<CrmCopyLinkButton type="company" id={companyId} />
+ <CompanyVisibilityButton companyId={companyId} />
</HeaderIsland>
</SplitHeaderRight>
<ParamsProvider state={params}>
diff --git a/apps/web/src/features/crm/README.md b/apps/web/src/features/crm/README.md
index cca769797f..39d7c73023 100644
--- a/apps/web/src/features/crm/README.md
+++ b/apps/web/src/features/crm/README.md
@@ -62,36 +62,48 @@ CRM supplies row/header/empty state slots, filter choices, grouping policy, and
its own collection state to the shared collection renderer. Shared collection code must not acquire CRM hooks or
CRM-specific state again.
-Company Overview and contact headers expose `RecordVisibilityAction` for removal
-and restoration through the existing hidden mutations. Keep admin/owner checks,
-confirmation of the company-wide contact cascade, and the restore action on the
-open record. Do not duplicate visibility controls in the information panel: contacts
-have no Sharing section, and company Sharing contains only Sync Emails.
-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. 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 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`.
+Visible contact and company toolbars put the archive-system icon beside Copy link.
+Archived identities group one Archived chip with a borderless Restore action; on
+phones the group wraps beneath the name and Restore retains a 44px touch target.
+The chip owns hover/focus/tap explanation; Restore does not trigger that explanation.
+`RecordVisibilityAction` handles confirmation, pending, cancellation and retry.
+Only admins/owners can change visibility. Company archive cascades to all people
+and disables email syncing; company restore explicitly confirms restoring every
+person, including individually archived people, while email syncing stays off.
+A person under an archived company routes to that company before restoration.
+Both information panels start with Record details and References; company-only
+Properties, Lists and Email sharing follow, with no duplicate visibility toggle.
+
+People, Companies and company Team use an exclusive Visible/Archived filter.
+`people-visibility` keeps the workspace choice local to the account/team/role/view,
+preserves search and other display choices, and sanitizes shared/persisted contact
+filters. Archived People is current-administered-team scoped, server filtered
+before pagination; visible People remains viewer-wide. Team applies the same
+exclusive choice to its embedded contact response, including effective parent state.
+
+Successful REST mutations write confirmed flags through the normalized Soup update
+path and patch paginated suggestions, company search pages, REST Soup and embedded
+detail snapshots. Confirmed detail snapshots become stale without an immediate
+refetch; active initial reads that were cancelled are restarted.
+Pre-write REST reads are cancelled; the normalized exchange fences older responses
+containing or declaring the affected CRM types before publication, hydration or
+persistence. Flat and grouped Soup pages retain their initial filter dependencies
+on continuations, so old empty pages cannot briefly hide a restored record.
+Imperative and durable revalidations recover these dependencies at dispatch, before
+urql can share them with a later mounted reader. Unknown opaque continuation scopes
+conservatively fence both CRM types; known initial scopes retain explicit exclusions.
+Refreshes target CRM-capable readers, leaving unrelated lists alone. A refresh
+failure is logged separately and never misreports a committed save as rejected.
+Session identity is captured before dispatch so a late response cannot populate a
+replacement session. Ordinary Cmd-K continues to exclude archived companies and
+people through its existing feeds and normalized projections; it has no recovery UI.
+
+`browser-test/archive` uses production record headers, toolbar actions, tabs,
+SidePanel, Team filtering and confirmations with synthetic storage and isolated
+shell services/entity-row metadata. It does not verify authenticated persistence.
+`browser-test/people` additionally exercises the production AST compiler and live
+GraphQL page source. Exchange tests cover the normalized-cache race boundary.
+Run the fixture's `playwright.config.ts` from `apps/web`.
Both hidden mutations emit `crm.visibility_change` through request and cache
refresh completion, with the opaque record ID, record type, requested hidden
state, and outcome. `crm.visibility_change.refresh` times cache invalidation and
diff --git a/apps/web/src/features/crm/browser-test/archive/archive.browser.e2e.ts b/apps/web/src/features/crm/browser-test/archive/archive.browser.e2e.ts
new file mode 100644
index 0000000000..c90a78a95a
--- /dev/null
+++ b/apps/web/src/features/crm/browser-test/archive/archive.browser.e2e.ts
@@ -0,0 +1,233 @@
+import { expect, type Page, test } from '@playwright/test';
+
+async function archive(page: Page) {
+ await page.getByRole('button', { name: 'Archive', exact: true }).click();
+ const dialog = page.getByRole('dialog');
+ await expect(dialog).not.toHaveAttribute('data-transitioning');
+ return dialog;
+}
+test.beforeEach(async ({ page }) => {
+ await page.route('https://**', (route) => route.abort());
+ await page.routeWebSocket('**', (socket) => socket.close());
+});
+
+test('archive, cancel, rejected save, retry and direct person restore', async ({
+ page,
+}, info) => {
+ await page.goto('/');
+ await expect(page.getByRole('textbox', { name: 'Contact name' })).toHaveValue(
+ 'Example person'
+ );
+ await page.screenshot({ path: info.outputPath('visible.png') });
+ const dialog = await archive(page);
+ await expect(dialog).toContainText('record and its history are kept');
+ await dialog.getByRole('button', { name: 'Cancel', exact: true }).click();
+ expect(await page.evaluate(() => window.archiveFixture.writes())).toBe(0);
+ await expect(dialog).toHaveCount(0);
+ await expect(
+ page.getByRole('button', { name: 'Archive', exact: true })
+ ).toBeFocused();
+ await page.evaluate(() => window.archiveFixture.failNext());
+ await archive(page);
+ await dialog.getByRole('button', { name: 'Archive', exact: true }).click();
+ await expect(dialog.getByRole('alert')).toContainText('Could not save');
+ expect(
+ await page.evaluate(
+ () => window.archiveFixture.snapshot().contacts[0].hidden
+ )
+ ).toBe(false);
+ await dialog.getByRole('button', { name: 'Archive', exact: true }).click();
+ await expect(
+ page.getByRole('button', { name: 'Archived — details' })
+ ).toBeVisible();
+ await expect(
+ page.getByRole('button', { name: 'Archive', exact: true })
+ ).toHaveCount(0);
+ const restore = page.getByRole('button', { name: 'Restore', exact: true });
+ await expect(restore).toBeVisible();
+ await page.screenshot({ path: info.outputPath('archived.png') });
+ await restore.click();
+ await expect(
+ page.getByRole('button', { name: 'Archive', exact: true })
+ ).toBeVisible();
+ expect(
+ await page.evaluate(
+ () => window.archiveFixture.snapshot().contacts[0].hidden
+ )
+ ).toBe(false);
+});
+
+test('pending prevents duplicates and company restore confirms the full cascade', async ({
+ page,
+}, info) => {
+ await page.goto('/?kind=company');
+ const dialog = await archive(page);
+ await expect(dialog).toContainText('All of its people will also be archived');
+ await page.evaluate(() => window.archiveFixture.holdNext());
+ await dialog.getByRole('button', { name: 'Archive', exact: true }).click();
+ await expect(
+ dialog.getByRole('button', { name: 'Archive', exact: true })
+ ).toBeDisabled();
+ await page.keyboard.press('Escape');
+ await expect(dialog).toBeVisible();
+ expect(await page.evaluate(() => window.archiveFixture.writes())).toBe(1);
+ await page.evaluate(() => window.archiveFixture.release());
+ await expect(
+ page.getByRole('button', { name: 'Restore', exact: true })
+ ).toBeVisible();
+ expect(
+ await page.evaluate(
+ () => window.archiveFixture.snapshot().company.emailSync
+ )
+ ).toBe(false);
+ await page.getByRole('button', { name: 'Restore', exact: true }).click();
+ await expect(dialog).toContainText('including people archived individually');
+ await expect(dialog).toContainText('Email syncing will stay off');
+ await expect(dialog).not.toHaveAttribute('data-transitioning');
+ await expect(
+ dialog.getByRole('button', { name: 'Restore', exact: true })
+ ).toBeInViewport({ ratio: 1 });
+ await page.screenshot({
+ path: info.outputPath('company-restore-confirmation.png'),
+ });
+ await dialog.getByRole('button', { name: 'Restore', exact: true }).click();
+ await expect(
+ page.getByRole('button', { name: 'Archive', exact: true })
+ ).toBeVisible();
+ const saved = await page.evaluate(() => window.archiveFixture.snapshot());
+ expect(saved.company.emailSync).toBe(false);
+ expect(saved.contacts.map((contact) => contact.hidden)).toEqual([
+ false,
+ false,
+ ]);
+});
+
+test('chip explanation has its own keyboard and touch lifecycle with narrow layout', async ({
+ page,
+ isMobile,
+}, info) => {
+ await page.goto('/?archived');
+ const chip = page.getByRole('button', { name: 'Archived — details' });
+ const restore = page.getByRole('button', { name: 'Restore', exact: true });
+ if (isMobile) {
+ for (const width of [390, 320]) {
+ await page.setViewportSize({ width, height: 844 });
+ await expect(restore).toBeInViewport({ ratio: 1 });
+ expect((await restore.boundingBox())!.height).toBeGreaterThanOrEqual(44);
+ expect(
+ await page.evaluate(
+ () => document.documentElement.scrollWidth <= innerWidth
+ )
+ ).toBe(true);
+ await page.screenshot({ path: info.outputPath(`archived-${width}.png`) });
+ }
+ await chip.click();
+ await expect(page.getByRole('dialog')).toContainText(
+ 'Excluded from visible People'
+ );
+ await expect(page.getByRole('dialog')).not.toHaveAttribute(
+ 'data-transitioning'
+ );
+ } else {
+ await chip.focus();
+ await expect(page.getByRole('tooltip')).toContainText(
+ 'Excluded from visible People'
+ );
+ }
+ await page.keyboard.press('Escape');
+ await expect(page.getByRole(isMobile ? 'dialog' : 'tooltip')).toHaveCount(0);
+ await restore.focus();
+ await expect(page.getByRole('tooltip')).toHaveCount(0);
+ await page.evaluate(() => window.archiveFixture.setRole('member'));
+ await expect(restore).toBeDisabled();
+});
+
+test('restoring a person whose company is archived routes to company confirmation', async ({
+ page,
+}) => {
+ await page.goto('/?companyArchived&legacyParent');
+ await page.getByRole('button', { name: 'Restore', exact: true }).click();
+ const dialog = page.getByRole('dialog');
+ await expect(dialog).toContainText('Restore the company first');
+ expect(await page.evaluate(() => window.archiveFixture.writes())).toBe(0);
+ await dialog.getByRole('button', { name: 'Open company' }).click();
+ await expect(
+ page.getByRole('textbox', { name: 'Company name' })
+ ).toBeVisible();
+});
+
+test('Team Visible and Archived are exclusive and preserve scoped search', async ({
+ page,
+}, info) => {
+ await page.goto('/?kind=company&team');
+ await expect(
+ page.getByRole('button', { name: /Example person/ })
+ ).toBeVisible();
+ await expect(page.getByRole('button', { name: /Second person/ })).toHaveCount(
+ 0
+ );
+ const search = page.getByRole('searchbox');
+ await search.fill('person');
+ const filter = page.getByRole('button', { name: 'Visibility' });
+ await filter.click();
+ await expect(
+ page.getByRole('menuitemradio', { name: 'Visible', exact: true })
+ ).toHaveAttribute('aria-checked', 'true');
+ await page
+ .getByRole('menuitemradio', { name: 'Archived', exact: true })
+ .click();
+ await page.keyboard.press('Escape');
+ await expect(
+ page.getByRole('button', { name: /Second person/ })
+ ).toBeVisible();
+ await expect(
+ page.getByRole('button', { name: /Example person/ })
+ ).toHaveCount(0);
+ await expect(search).toHaveValue('person');
+ await page.screenshot({ path: info.outputPath('team-archived.png') });
+ await page.evaluate(() => window.archiveFixture.setRole('member'));
+ await expect(filter).toContainText('Visible');
+ await page.goto('/?kind=company&team&companyArchived&legacyParent');
+ await expect(
+ page.getByRole('heading', { name: 'No contacts yet' })
+ ).toBeVisible();
+ await expect(
+ page.getByRole('button', {
+ name: 'Add contact',
+ exact: true,
+ disabled: false,
+ })
+ ).toHaveCount(0);
+ await filter.click();
+ await page
+ .getByRole('menuitemradio', { name: 'Archived', exact: true })
+ .click();
+ await page.keyboard.press('Escape');
+ await expect(
+ page
+ .getByRole('button', { name: /Example person/ })
+ .getByText('Archived', { exact: true })
+ ).toBeVisible();
+});
+
+test('Details uses the same record details then references order', async ({
+ page,
+}) => {
+ for (const kind of ['contact', 'company']) {
+ await page.goto(`/?kind=${kind}`);
+ await page
+ .getByRole('button', { name: 'Show details', exact: true })
+ .click();
+ const details = page.getByText('Record details', { exact: true });
+ const references = page.getByText('References', { exact: true });
+ await expect(details).toBeVisible();
+ await expect(references).toBeVisible();
+ expect((await details.boundingBox())!.y).toBeLessThan(
+ (await references.boundingBox())!.y
+ );
+ if (kind === 'company')
+ await expect(
+ page.getByText('Email sharing', { exact: true })
+ ).toBeVisible();
+ }
+});
diff --git a/apps/web/src/features/crm/browser-test/archive/entity-preview.tsx b/apps/web/src/features/crm/browser-test/archive/entity-preview.tsx
new file mode 100644
index 0000000000..0937f65f7a
--- /dev/null
+++ b/apps/web/src/features/crm/browser-test/archive/entity-preview.tsx
@@ -0,0 +1,31 @@
+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>
+ );
+}
+
+export {
+ formatDateAndTime,
+ formatRelativeTimestamp,
+} from '../../../entity/utils/timestamp';
diff --git a/apps/web/src/features/crm/browser-test/archive/fixture.tsx b/apps/web/src/features/crm/browser-test/archive/fixture.tsx
new file mode 100644
index 0000000000..ea39eef3f8
--- /dev/null
+++ b/apps/web/src/features/crm/browser-test/archive/fixture.tsx
@@ -0,0 +1,107 @@
+import '../../../../index.css';
+import { SidePanel } from '@components/app/side-panel';
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
+import type { storageServiceClient as Storage } from '@service-storage/client';
+import { QueryClientProvider } from '@tanstack/solid-query';
+import { createSignal, Show, Suspense } from 'solid-js';
+import { render } from 'solid-js/web';
+import { RecordOverview } from '../../components/record-overview';
+import { RecordTabs } from '../../components/record-tabs';
+import {
+ COMPANY_SECTIONS,
+ CONTACT_SECTIONS,
+ type CrmRecordSection,
+} from '../../core/record';
+import { useCompanyQuery } from '../../queries/companies';
+import { useContactQuery } from '../../queries/contacts';
+import { CompanyContactsSection } from '../../views/company-contacts-section';
+import { CompanyHeader } from '../../views/company-header';
+import { CompanySharingSection } from '../../views/company-sharing-section';
+import { ContactHeader } from '../../views/contact-header';
+import { RecordDetailsSection } from '../../views/record-details-section';
+import { RecordHeaderActions } from '../../views/record-header-actions';
+import { client, message, storageServiceClient } from './preview-adapters';
+
+document.documentElement.dataset.touchDevice = String(isTouchDevice());
+const params = new URLSearchParams(location.search);
+const kind = params.get('kind') === 'company' ? 'company' : 'contact';
+const record = { type: kind, id: `${kind}-1`, name: '' } as const;
+function Fixture() {
+ const [section, setSection] = createSignal<CrmRecordSection>(
+ params.has('team') ? 'team' : 'overview'
+ );
+ const deps = {
+ client,
+ storage: storageServiceClient as unknown as typeof Storage,
+ };
+ const source = useCompanyQuery(deps, () => 'company-1');
+ const contact = useContactQuery(deps, () => 'contact-1');
+ return (
+ <main class="flex h-dvh min-w-0 flex-col bg-panel text-ink">
+ <SidePanel.Root floating defaultOpen={false}>
+ <header class="flex min-h-12 min-w-0 shrink-0 items-center gap-2 px-3 mobile:flex-wrap">
+ <span class="min-w-0 truncate text-sm">
+ {kind === 'company' ? 'Companies' : 'People'}
+ </span>
+ <RecordTabs
+ sections={kind === 'company' ? COMPANY_SECTIONS : CONTACT_SECTIONS}
+ value={section()}
+ onChange={setSection}
+ />
+ <RecordHeaderActions record={record} />
+ </header>
+ <div class="min-h-0 flex-1">
+ <SidePanel.Layout floating headerToggle={false}>
+ <Suspense fallback={<p>Loading record</p>}>
+ <Show
+ when={section() === 'team'}
+ fallback={
+ <RecordOverview>
+ <Show
+ when={kind === 'company'}
+ fallback={<ContactHeader contact={contact.data} />}
+ >
+ <CompanyHeader company={source.company()} />
+ </Show>
+ </RecordOverview>
+ }
+ >
+ <CompanyContactsSection
+ company={source.company()}
+ contacts={source.contacts()}
+ />
+ </Show>
+ <RecordDetailsSection
+ company={kind === 'company' ? source.company() : undefined}
+ contact={kind === 'contact' ? contact.data : undefined}
+ />
+ <SidePanel.Section id="references" title="References" order={20}>
+ <p>No references</p>
+ </SidePanel.Section>
+ <Show when={kind === 'company'}>
+ <SidePanel.Section
+ id="sharing"
+ title="Email sharing"
+ order={50}
+ >
+ <CompanySharingSection company={source.company()} />
+ </SidePanel.Section>
+ </Show>
+ </Suspense>
+ </SidePanel.Layout>
+ </div>
+ </SidePanel.Root>
+ <output class="sr-only" aria-live="polite">
+ {message()}
+ </output>
+ </main>
+ );
+}
+render(
+ () => (
+ <QueryClientProvider client={client}>
+ <Fixture />
+ </QueryClientProvider>
+ ),
+ document.getElementById('root')!
+);
diff --git a/apps/web/src/features/crm/browser-test/archive/host-preview.tsx b/apps/web/src/features/crm/browser-test/archive/host-preview.tsx
new file mode 100644
index 0000000000..caf25fbc11
--- /dev/null
+++ b/apps/web/src/features/crm/browser-test/archive/host-preview.tsx
@@ -0,0 +1,12 @@
+import type { ParentProps } from 'solid-js';
+// Shell service boundaries; SidePanel, record chrome and all changed controls are production components.
+export const useMaybeBlockAliasedName = () => undefined;
+export const useSplitPanel = () => undefined;
+export const registerHotkey = () => () => {};
+export const SplitHeaderRight = (props: ParentProps) => props.children;
+export const OwnerLabel = () => null;
+
+export const blockAcceptedFileExtensionSet = new Set();
+export const fileTypeToBlockName = () => 'unknown';
+export const isBlockAlias = () => false;
+export const itemToBlockName = () => 'unknown';
diff --git a/apps/web/src/features/crm/browser-test/archive/index.html b/apps/web/src/features/crm/browser-test/archive/index.html
new file mode 100644
index 0000000000..71107f153d
--- /dev/null
+++ b/apps/web/src/features/crm/browser-test/archive/index.html
@@ -0,0 +1 @@
+<!doctype html><html><head><meta name="viewport" content="width=device-width, initial-scale=1.0"></head><body><div id="root"></div><script type="module" src="./fixture.tsx"></script></body></html>
\ No newline at end of file
diff --git a/apps/web/src/features/crm/browser-test/archive/playwright.config.ts b/apps/web/src/features/crm/browser-test/archive/playwright.config.ts
new file mode 100644
index 0000000000..8e89a00917
--- /dev/null
+++ b/apps/web/src/features/crm/browser-test/archive/playwright.config.ts
@@ -0,0 +1,41 @@
+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_ARCHIVE_BROWSER_PORT ?? 23943);
+const launchOptions = {
+ executablePath: process.env.PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH,
+};
+
+export default defineConfig({
+ testDir: directory,
+ testMatch: '*.browser.e2e.ts',
+ outputDir: process.env.CRM_ARCHIVE_PROOF_DIR ?? `${directory}/test-results`,
+ timeout: 45_000,
+ workers: 1,
+ use: {
+ baseURL: `http://127.0.0.1:${port}`,
+ screenshot: 'only-on-failure',
+ video: 'on',
+ trace: 'retain-on-failure',
+ },
+ webServer: {
+ command: `bunx vite build --config src/features/crm/browser-test/archive/vite.config.ts && bunx vite preview --config src/features/crm/browser-test/archive/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/archive/preview-adapters.ts b/apps/web/src/features/crm/browser-test/archive/preview-adapters.ts
new file mode 100644
index 0000000000..9ca19e5c5f
--- /dev/null
+++ b/apps/web/src/features/crm/browser-test/archive/preview-adapters.ts
@@ -0,0 +1,198 @@
+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 { QueryClient } from '@tanstack/solid-query';
+import { err, ok } from 'neverthrow';
+import { type Accessor, createSignal } from 'solid-js';
+import {
+ useCompanyQuery,
+ useSetCompanyHiddenMutation,
+ useSetCompanyNameMutation,
+ useSetEmailSyncMutation,
+} from '../../queries/companies';
+import {
+ useContactQuery,
+ useSetContactHiddenMutation,
+ useSetContactNameMutation,
+} from '../../queries/contacts';
+
+export const NIL_UUID = '00000000-0000-0000-0000-000000000000';
+export const analytics = { track() {} };
+export async function invalidateCachedCrmContacts() {}
+// This fixture verifies REST/UI integration; normalized-cache fencing has separate exchange tests.
+export const prepareCrmVisibilityWrite = () => ({
+ isCurrent: () => true,
+ async commit() {},
+});
+export const client = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+});
+export const [role, setRole] = createSignal('admin');
+export const [writes, setWrites] = createSignal(0);
+export const [message, setMessage] = createSignal('');
+let failNext = false;
+let release: (() => void) | undefined;
+let hold = false;
+const params = new URLSearchParams(location.search);
+let company: CrmCompanyResponse = {
+ id: 'company-1',
+ name: 'Example company',
+ teamId: 'team-1',
+ hidden: params.has('companyArchived'),
+ emailSync: !params.has('companyArchived'),
+ domains: [
+ {
+ id: 'domain-1',
+ companyId: 'company-1',
+ domain: 'example.com',
+ createdAt: '2026-10-15',
+ },
+ ],
+ createdAt: '2026-10-15',
+ updatedAt: '2026-10-15',
+ contacts: [],
+};
+let contacts: CrmContactResponse[] = ['Example person', 'Second person'].map(
+ (name, index) => ({
+ id: `contact-${index + 1}`,
+ companyId: company.id,
+ name,
+ email: `person${index + 1}@example.com`,
+ hidden:
+ params.has('legacyParent') && index === 0
+ ? false
+ : company.hidden || index === 1 || params.has('archived'),
+ createdAt: '2026-10-15',
+ updatedAt: '2026-10-15',
+ firstInteraction: '2026-10-15',
+ lastInteraction: '2026-10-15',
+ })
+);
+async function save() {
+ setWrites((value) => value + 1);
+ if (hold)
+ await new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ hold = false;
+ if (failNext || role() === 'member') {
+ failNext = false;
+ return false;
+ }
+ return true;
+}
+export const storageServiceClient = {
+ async getCompany() {
+ return ok({
+ ...company,
+ contacts: contacts.map((contact) => ({ ...contact })),
+ });
+ },
+ async getContact({ contactId }) {
+ return ok({ ...contacts.find((contact) => contact.id === contactId)! });
+ },
+ async setContactHidden({ contactId, hidden }) {
+ if (!(await save()))
+ return err([{ code: 'FORBIDDEN', message: 'Save rejected' }]);
+ contacts = contacts.map((contact) =>
+ contact.id === contactId ? { ...contact, hidden } : contact
+ );
+ return ok(undefined);
+ },
+ async setCompanyHidden({ hidden }) {
+ if (!(await save()))
+ return err([{ code: 'FORBIDDEN', message: 'Save rejected' }]);
+ company = {
+ ...company,
+ hidden,
+ emailSync: hidden ? false : company.emailSync,
+ };
+ contacts = contacts.map((contact) => ({ ...contact, hidden }));
+ return ok(undefined);
+ },
+ async setCompanyName({ name }) {
+ company = { ...company, name };
+ return ok(undefined);
+ },
+ async setContactName({ contactId, name }) {
+ contacts = contacts.map((contact) =>
+ contact.id === contactId ? { ...contact, name } : contact
+ );
+ return ok(undefined);
+ },
+ async setEmailSync({ emailSync }) {
+ company = { ...company, emailSync };
+ return ok(undefined);
+ },
+} satisfies Pick<
+ typeof Storage,
+ | 'getCompany'
+ | 'getContact'
+ | 'setCompanyHidden'
+ | 'setContactHidden'
+ | 'setCompanyName'
+ | 'setContactName'
+ | 'setEmailSync'
+>;
+const deps = {
+ client,
+ storage: storageServiceClient as unknown as typeof Storage,
+};
+export const useCrmContext = () => ({
+ userId: () => 'user-1',
+ isTeamAdmin: () => () => role() !== 'member',
+ createCompanySource: (id: Accessor<string>) => useCompanyQuery(deps, id),
+ createContactSource: (id: Accessor<string>) => useContactQuery(deps, id),
+ hideCompany: () => useSetCompanyHiddenMutation(deps),
+ hideContact: () => useSetContactHiddenMutation(deps),
+ renameCompany: () => useSetCompanyNameMutation(deps),
+ renameContact: () => useSetContactNameMutation(deps),
+ setEmailSync: () => useSetEmailSyncMutation(deps),
+ createNavigation: () => ({
+ openWithSplit() {
+ location.search = '?kind=company&companyArchived';
+ },
+ }),
+ copyRecordLink: async () => true,
+ contactInitials: (name: string) =>
+ name
+ .split(' ')
+ .map((part) => part[0])
+ .join(''),
+ feedback: { success: setMessage, failure: setMessage },
+ openCreateContact() {},
+});
+Object.assign(window, {
+ archiveFixture: {
+ failNext() {
+ failNext = true;
+ },
+ holdNext() {
+ hold = true;
+ },
+ release() {
+ release?.();
+ },
+ setRole,
+ writes,
+ snapshot: () => ({ company, contacts }),
+ },
+});
+
+export const useFeatureFlag = () => () => ({ enabled: true, loading: false });
+
+declare global {
+ interface Window {
+ archiveFixture: {
+ failNext(): void;
+ holdNext(): void;
+ release(): void;
+ setRole(value: string): void;
+ writes(): number;
+ snapshot(): {
+ company: CrmCompanyResponse;
+ contacts: CrmContactResponse[];
+ };
+ };
+ }
+}
diff --git a/apps/web/src/features/crm/browser-test/archive/vite.config.ts b/apps/web/src/features/crm/browser-test/archive/vite.config.ts
new file mode 100644
index 0000000000..b122e789c7
--- /dev/null
+++ b/apps/web/src/features/crm/browser-test/archive/vite.config.ts
@@ -0,0 +1,77 @@
+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: /^@components\/app\/side-panel$/,
+ replacement: `${webDirectory}/src/components/app/side-panel/SidePanel.tsx`,
+ },
+ {
+ find: /^@core\/constant\/allBlocks$/,
+ replacement: `${directory}/host-preview.tsx`,
+ },
+ { find: /^@core\/block$/, replacement: `${directory}/host-preview.tsx` },
+ {
+ find: /^.*split-layout\/layoutUtils$/,
+ replacement: `${directory}/host-preview.tsx`,
+ },
+ {
+ find: /^.*split-layout\/components\/SplitHeader$/,
+ replacement: `${directory}/host-preview.tsx`,
+ },
+ {
+ find: /^@core\/hotkey\/hotkeys$/,
+ replacement: `${directory}/host-preview.tsx`,
+ },
+ {
+ find: /^@entity\/owner\/owner-display$/,
+ replacement: `${directory}/host-preview.tsx`,
+ },
+ ...[
+ '@service-storage/client',
+ '@service-storage/crm-contacts',
+ '@service-storage/crm-visibility',
+ '@app/lib/analytics',
+ '@app/lib/analytics/posthog',
+ '@app/features/next-soup/filters/filter-store',
+ '../context/crm-context',
+ ].map((find) => ({
+ find: new RegExp(`^${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`,
+ },
+ ],
+ },
+ worker: { format: 'es' },
+ build: { target: 'esnext' },
+ server: {
+ host: '127.0.0.1',
+ strictPort: true,
+ fs: { allow: [workspaceDirectory] },
+ },
+});
diff --git a/apps/web/src/features/crm/browser-test/people/fixture.tsx b/apps/web/src/features/crm/browser-test/people/fixture.tsx
index cb06a7fe36..d1bee8ece5 100644
--- a/apps/web/src/features/crm/browser-test/people/fixture.tsx
+++ b/apps/web/src/features/crm/browser-test/people/fixture.tsx
@@ -1,6 +1,6 @@
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 type { CrmCompanyEntity, EntityData } from '@entity';
import '../../../../index.css';
import { SearchBar } from '@app/components/view-shell';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
@@ -15,13 +15,12 @@ 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 {
+ crmCompanyActiveFilter,
+ crmCompanyHiddenFilter,
crmContactActiveFilter,
crmContactHiddenFilter,
} from '../../collection-filters';
-import {
- PeopleDisplayMenu,
- RemovedPeopleNotice,
-} from '../../components/people-display-menu';
+import { PeopleDisplayMenu } from '../../components/people-display-menu';
import { RecordVisibilityAction } from '../../components/record-visibility-action';
import {
bindPeopleVisibility,
@@ -38,6 +37,7 @@ import {
setHoldNextRead,
} from './graphql-preview';
import {
+ contacts,
role,
setFailNext,
setFailRead,
@@ -76,17 +76,28 @@ function Detail(props: { id: string; close(): void }) {
recordId={contact().id}
name={contact().name ?? 'Contact'}
kind="contact"
- hidden={contact().hidden}
+ hidden={
+ contact().hidden ||
+ contacts.some(
+ (item) => item.id === contact().id && item.parentHidden
+ )
+ }
+ parentArchived={contacts.some(
+ (item) => item.id === contact().id && item.parentHidden
+ )}
+ onOpenParent={() => {}}
canManage={role() !== 'member'}
pending={mutation.isPending}
- onChange={(hidden, onSuccess) => {
+ onChange={(hidden, onSuccess, onError) => {
setError('');
mutation.mutate(
{ contactId: contact().id, hidden },
{
onSuccess,
- onError: () =>
- setError('Could not update contact visibility'),
+ onError: () => {
+ onError();
+ setError('Could not update contact visibility');
+ },
}
);
}}
@@ -106,6 +117,27 @@ function Detail(props: { id: string; close(): void }) {
function Fixture() {
const [activeTab, setActiveTab] = createSignal('people');
const [selected, setSelected] = createSignal<string>();
+ const [companySearch, setCompanySearch] = createSignal('');
+ const companies: CrmCompanyEntity[] = [
+ {
+ type: 'crm_company',
+ id: 'company-visible',
+ name: 'Example visible company',
+ ownerId: 'team-1',
+ teamId: 'team-1',
+ hidden: false,
+ domains: [],
+ },
+ {
+ type: 'crm_company',
+ id: 'company-archived',
+ name: 'Example archived company',
+ ownerId: 'team-1',
+ teamId: 'team-1',
+ hidden: true,
+ domains: [],
+ },
+ ];
const visibility = createPeopleVisibility({
userId,
teamId,
@@ -119,7 +151,14 @@ function Fixture() {
EntityData,
FilterContext,
PredicateConfig<EntityData, string, FilterContext>
- >({ configs: [crmContactActiveFilter, crmContactHiddenFilter] });
+ >({
+ configs: [
+ crmContactActiveFilter,
+ crmContactHiddenFilter,
+ crmCompanyActiveFilter,
+ crmCompanyHiddenFilter,
+ ],
+ });
bindPeopleVisibility(visibility, {
activeTab,
queryFilters,
@@ -223,11 +262,36 @@ function Fixture() {
Open removed directly
</Button>
</nav>
- <Show when={activeTab() === 'people'} fallback={<h1>Companies</h1>}>
+ <Show
+ when={activeTab() === 'people'}
+ fallback={
+ <section aria-label="Company results" class="p-4">
+ <h1>Companies</h1>
+ <PeopleDisplayMenu visibility={visibility} />
+ <SearchBar
+ label="Search companies"
+ value={companySearch()}
+ onValueChange={setCompanySearch}
+ />
+ <For
+ each={companies.filter(
+ (company) =>
+ company.name
+ .toLowerCase()
+ .includes(companySearch().toLowerCase()) &&
+ predicates.test(company, {})
+ )}
+ >
+ {(company) => <div>{company.name}</div>}
+ </For>
+ <output aria-label="Company filter">
+ {String(queryFilters.state.include.crmCompanyHidden)}
+ </output>
+ </section>
+ }
+ >
<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>
+ <h1 class="flex-1 text-lg font-semibold">{'People'}</h1>
<PeopleDisplayMenu visibility={visibility} />
</header>
<div class="px-4 pb-3">
@@ -242,11 +306,6 @@ function Fixture() {
}
/>
</div>
- <Show when={visibility.showRemoved()}>
- <RemovedPeopleNotice
- onShowActive={() => visibility.setShowRemoved(false)}
- />
- </Show>
<Suspense fallback={<p>Loading contact</p>}>
<Show when={selected()}>
{(id) => (
@@ -287,7 +346,7 @@ function Fixture() {
}
>
<p>
- {visibility.showRemoved() ? 'No removed people' : 'No people'}
+ {visibility.showRemoved() ? 'No archived people' : 'No people'}
</p>
</Show>
<Show when={source.hasNextPage()}>
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.ts
index 25ea532517..0f0a69e287 100644
--- 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.ts
@@ -1,21 +1,15 @@
import { expect, type Page, test } from '@playwright/test';
async function removed(page: Page) {
+ await page.getByRole('button', { name: 'Visibility', exact: true }).click();
await page
- .getByRole('button', { name: 'People display options', exact: true })
+ .getByRole('menuitemradio', { name: 'Archived', 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();
+ if (action === 'Restore') return;
const dialog = page.getByRole('dialog');
await expect(dialog).not.toHaveAttribute('data-transitioning');
await dialog.getByRole('button', { name: action, exact: true }).click();
@@ -32,11 +26,11 @@ test.beforeEach(async ({ page }) => {
).toBeVisible();
});
-test('admin hides, discovers through removed search, and restores with the existing eye', async ({
+test('admin archives, discovers through archived search, and restores', async ({
page,
}, info) => {
await results(page).getByRole('button', { name: 'Active person' }).click();
- await confirm(page, 'Remove from CRM');
+ await confirm(page, 'Archive');
await expect(page.getByRole('dialog')).toHaveCount(0);
await expect(
results(page).getByRole('button', { name: 'Active person' })
@@ -51,16 +45,18 @@ test('admin hides, discovers through removed search, and restores with the exist
await page.screenshot({
path: info.outputPath('removed-people-restore.png'),
});
- await confirm(page, 'Restore to CRM');
+ await confirm(page, 'Restore');
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 expect(results(page).getByText('No archived people')).toBeVisible();
await page.getByRole('button', { name: 'Back to People' }).click();
+ await page.getByRole('button', { name: 'Visibility' }).click();
await page
- .getByRole('button', { name: 'Show active people', exact: true })
+ .getByRole('menuitemradio', { name: 'Visible', exact: true })
.click();
+ await page.keyboard.press('Escape');
await expect(
results(page).getByRole('button', { name: 'Active person' })
).toBeVisible();
@@ -103,17 +99,17 @@ test('server pagination and search find later removed rows, handle errors and pr
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.getByRole('button', { name: 'Restore', exact: true }).click();
+ await expect(page.getByRole('dialog')).toContainText(
+ 'Restore the company first'
+ );
+ await page.getByRole('button', { name: 'Cancel', exact: true }).click();
+ await expect(page.getByRole('dialog')).toHaveCount(0);
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();
+ await expect(results(page).getByText('No archived people')).toBeVisible();
});
test('unfiled records restore, rejected writes stay retryable, and scope changes close removed mode', async ({
@@ -121,25 +117,27 @@ test('unfiled records restore, rejected writes stay retryable, and scope changes
}) => {
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 confirm(page, 'Archive');
+ await expect(
+ page
+ .getByRole('alert', { includeHidden: true })
+ .filter({ hasText: 'Could not update contact visibility' })
+ ).toHaveText('Could not update contact visibility');
await page
.getByRole('dialog')
- .getByRole('button', { name: 'Remove from CRM', exact: true })
+ .getByRole('button', { name: 'Archive', 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 confirm(page, 'Restore');
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 expect(results(page).getByText('No archived people')).toBeVisible();
await page.getByRole('button', { name: 'Back to People' }).click();
await page.getByRole('searchbox').fill('');
await page.getByRole('button', { name: 'Switch team' }).click();
@@ -168,8 +166,8 @@ test('unfiled records restore, rejected writes stay retryable, and scope changes
.getByRole('button', { name: 'Toggle member', exact: true })
.click();
await expect(
- page.getByRole('button', { name: 'People display options' })
- ).toHaveCount(0);
+ page.getByRole('button', { name: 'Visibility', exact: true })
+ ).toContainText('Visible');
await page.getByRole('button', { name: 'Inject hidden filters' }).click();
await expect(
results(page).getByRole('button', { name: /Removed|Other team/ })
@@ -203,6 +201,30 @@ test('loading and late removed responses cannot resurrect rows after a role chan
})
).toHaveCount(0);
await expect(
- page.getByRole('button', { name: 'People display options' })
- ).toHaveCount(0);
+ page.getByRole('button', { name: 'Visibility', exact: true })
+ ).toContainText('Visible');
+});
+
+test('Companies keeps its search while switching exclusive visibility', async ({
+ page,
+}) => {
+ await page.getByRole('button', { name: 'Toggle list', exact: true }).click();
+ const results = page.getByRole('region', { name: 'Company results' });
+ await expect(results.getByText('Example visible company')).toBeVisible();
+ await expect(results.getByText('Example archived company')).toHaveCount(0);
+ await page
+ .getByRole('searchbox', { name: 'Search companies' })
+ .fill('Example');
+ await removed(page);
+ await expect(results.getByText('Example archived company')).toBeVisible();
+ await expect(results.getByText('Example visible company')).toHaveCount(0);
+ await expect(
+ page.getByRole('searchbox', { name: 'Search companies' })
+ ).toHaveValue('Example');
+ await expect(page.getByLabel('Company filter')).toHaveText('true');
+ await page
+ .getByRole('button', { name: 'Toggle member', exact: true })
+ .click();
+ await expect(results.getByText('Example visible company')).toBeVisible();
+ await expect(results.getByText('Example archived company')).toHaveCount(0);
});
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.ts
index a2e8a527b0..02d73a9f3f 100644
--- a/apps/web/src/features/crm/browser-test/people/preview-adapters.ts
+++ b/apps/web/src/features/crm/browser-test/people/preview-adapters.ts
@@ -111,3 +111,8 @@ export const storageServiceClient = {
return ok(undefined);
},
} satisfies Pick<typeof Storage, 'getContact' | 'setContactHidden'>;
+
+export const prepareCrmVisibilityWrite = () => ({
+ isCurrent: () => true,
+ async commit() {},
+});
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.ts
index 7a85df4209..bca5c1235b 100644
--- a/apps/web/src/features/crm/browser-test/people/vite.config.ts
+++ b/apps/web/src/features/crm/browser-test/people/vite.config.ts
@@ -42,6 +42,7 @@ export default defineConfig({
...[
'@service-storage/client',
'@service-storage/crm-contacts',
+ '@service-storage/crm-visibility',
'@app/lib/analytics',
].map((find) => ({
find,
diff --git a/apps/web/src/features/crm/browser-test/team/fixture.tsx b/apps/web/src/features/crm/browser-test/team/fixture.tsx
index 55cf6b220f..c3de50632d 100644
--- a/apps/web/src/features/crm/browser-test/team/fixture.tsx
+++ b/apps/web/src/features/crm/browser-test/team/fixture.tsx
@@ -57,14 +57,16 @@ function Detail(props: { id: string }) {
hidden={record().hidden}
canManage={role() !== 'member'}
pending={mutation.isPending}
- onChange={(hidden, onSuccess) => {
+ onChange={(hidden, onSuccess, onError) => {
setError('');
mutation.mutate(
{ contactId: record().id, hidden },
{
onSuccess,
- onError: () =>
- setError('Could not update contact visibility'),
+ onError: () => {
+ onError();
+ setError('Could not update contact visibility');
+ },
}
);
}}
@@ -111,7 +113,9 @@ function Fixture() {
</Button>
</nav>
<Suspense fallback={<p>Loading</p>}>
- <Show when={contactId()}>{(id) => <Detail id={id()} />}</Show>
+ <Show when={contactId()} keyed>
+ {(id) => <Detail id={id} />}
+ </Show>
<Show when={!contactId() || keepTeam()}>
<Team open={setContactId} />
</Show>
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.ts
index db1003e819..68654ca9b6 100644
--- a/apps/web/src/features/crm/browser-test/team/preview-adapters.ts
+++ b/apps/web/src/features/crm/browser-test/team/preview-adapters.ts
@@ -10,6 +10,8 @@ export async function invalidateCachedCrmContacts() {}
export const useCrmContext = () => ({
createNavigation: () => ({ openWithSplit() {} }),
openCreateContact() {},
+ userId: () => 'user-1',
+ isTeamAdmin: () => () => role() !== 'member',
});
const CONTACT: CrmContactResponse = {
@@ -88,3 +90,8 @@ export const storageServiceClient = {
typeof Storage,
'getCompany' | 'getContact' | 'setContactHidden'
>;
+
+export const prepareCrmVisibilityWrite = () => ({
+ isCurrent: () => true,
+ async commit() {},
+});
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.ts
index 9a35df35e0..e740be988b 100644
--- 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.ts
@@ -2,6 +2,7 @@ import { expect, type Page, test } from '@playwright/test';
async function confirmVisibility(page: Page, label: string) {
await page.getByRole('button', { name: label, exact: true }).click();
+ if (label === 'Restore') return;
const dialog = page.getByRole('dialog');
await expect(dialog).toBeInViewport({ ratio: 1 });
await expect(dialog).not.toHaveAttribute('data-transitioning');
@@ -28,7 +29,7 @@ test('admin Team excludes removed rows and refreshes after navigating away to hi
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 confirmVisibility(page, 'Archive');
await expect(page.getByRole('dialog')).toHaveCount(0);
await expect(page.getByLabel('Contact identity')).toHaveText(
'visible-contact / company-1'
@@ -39,7 +40,7 @@ test('admin Team excludes removed rows and refreshes after navigating away to hi
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 confirmVisibility(page, 'Restore');
await expect(page.getByRole('dialog')).toHaveCount(0);
await page.getByRole('button', { name: 'Company Team', exact: true }).click();
await expect(visible).toBeVisible();
@@ -57,30 +58,32 @@ test('mounted Team updates on hide and restore; rejected writes and member contr
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 confirmVisibility(page, 'Archive');
+ await expect(
+ page
+ .getByRole('alert', { includeHidden: true })
+ .filter({ hasText: 'Could not update contact visibility' })
+ ).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 })
+ .getByRole('button', { name: 'Archive', 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 confirmVisibility(page, 'Restore');
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 })
+ page.getByRole('button', { name: 'Archive', exact: true })
).toBeDisabled();
await page.getByRole('button', { name: 'Open removed directly' }).click();
await expect(page.getByText('Contact unavailable')).toBeVisible();
@@ -90,12 +93,12 @@ 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 confirmVisibility(page, 'Archive');
await expect(page.getByRole('dialog')).toHaveCount(0);
await expect(page.getByLabel('Contact identity')).toHaveText(
'unfiled-contact / unfiled'
);
- await confirmVisibility(page, 'Restore to CRM');
+ await confirmVisibility(page, 'Restore');
await expect(page.getByRole('dialog')).toHaveCount(0);
await expect(page.getByLabel('Contact identity')).toHaveText(
'unfiled-contact / unfiled'
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.ts
index 9b850515a1..db10b1e4b7 100644
--- a/apps/web/src/features/crm/browser-test/team/vite.config.ts
+++ b/apps/web/src/features/crm/browser-test/team/vite.config.ts
@@ -26,6 +26,7 @@ export default defineConfig({
...[
'@service-storage/client',
'@service-storage/crm-contacts',
+ '@service-storage/crm-visibility',
'@app/lib/analytics',
'@app/features/next-soup/filters/filter-store',
'../context/crm-context',
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.ts
index bc23a3b853..f14effd872 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
@@ -37,7 +37,7 @@ for (const device of [
`/src/features/crm/browser-test/visibility.html?kind=${kind}&grouped=${grouped}`
);
const remove = page.getByRole('button', {
- name: 'Remove from CRM',
+ name: 'Archive',
exact: true,
});
await remove.click();
@@ -57,7 +57,7 @@ for (const device of [
path: testInfo.outputPath(`${kind}-${device.name}.png`),
});
const confirm = dialog.getByRole('button', {
- name: 'Remove from CRM',
+ name: 'Archive',
exact: true,
});
await confirm.click();
@@ -71,13 +71,15 @@ for (const device of [
await expect(page.getByLabel('Visibility writes')).toHaveText('2');
await page
- .getByRole('button', { name: 'Restore to CRM', exact: true })
- .click();
- await expect(dialog).toBeInViewport({ ratio: 1 });
- await expect(dialog).not.toHaveAttribute('data-transitioning');
- await dialog
- .getByRole('button', { name: 'Restore to CRM', exact: true })
+ .getByRole('button', { name: 'Restore', exact: true })
.click();
+ if (kind === 'company') {
+ await expect(dialog).toBeInViewport({ ratio: 1 });
+ await expect(dialog).not.toHaveAttribute('data-transitioning');
+ await dialog
+ .getByRole('button', { name: 'Restore', exact: true })
+ .click();
+ }
await page.evaluate(() => window.finishVisibilitySave(true));
await expect(dialog).not.toBeVisible();
await expect(remove).toBeEnabled();
@@ -85,7 +87,7 @@ for (const device of [
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.'
+ 'Ask a team admin or owner to archive or restore this record.'
);
});
}
@@ -94,9 +96,7 @@ for (const device of [
page,
}) => {
await page.goto('/src/features/crm/browser-test/visibility.html');
- await page
- .getByRole('button', { name: 'Remove from CRM', exact: true })
- .click();
+ await page.getByRole('button', { name: 'Archive', exact: true }).click();
await expect(page.getByRole('dialog')).toBeVisible();
await page.evaluate(() => window.switchVisibilityRecord());
await expect(page.getByRole('dialog')).not.toBeVisible();
diff --git a/apps/web/src/features/crm/browser-test/visibility.tsx b/apps/web/src/features/crm/browser-test/visibility.tsx
index f0c4a1bfc8..acd48c62d6 100644
--- a/apps/web/src/features/crm/browser-test/visibility.tsx
+++ b/apps/web/src/features/crm/browser-test/visibility.tsx
@@ -40,13 +40,16 @@ function Fixture() {
hidden={hidden()}
pending={pending()}
canManage={canManage()}
- onChange={(value, onSuccess) => {
+ onChange={(value, onSuccess, onError) => {
setPending(true);
setWrites((count) => count + 1);
finish = (success) => {
finish = undefined;
setPending(false);
- if (!success) return;
+ if (!success) {
+ onError();
+ return;
+ }
setHidden(value);
onSuccess();
};
diff --git a/apps/web/src/features/crm/components/people-display-menu.tsx b/apps/web/src/features/crm/components/people-display-menu.tsx
index b7cb8c67fb..011818bd40 100644
--- a/apps/web/src/features/crm/components/people-display-menu.tsx
+++ b/apps/web/src/features/crm/components/people-display-menu.tsx
@@ -1,45 +1,12 @@
-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';
+import { RecordVisibilityFilter } from './record-visibility-filter';
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>
+ <RecordVisibilityFilter
+ archived={props.visibility.showRemoved()}
+ onChange={props.visibility.setShowRemoved}
+ disabled={!props.visibility.canShowRemoved()}
+ />
);
}
diff --git a/apps/web/src/features/crm/components/record-archived-status.tsx b/apps/web/src/features/crm/components/record-archived-status.tsx
new file mode 100644
index 0000000000..a4fccbc78f
--- /dev/null
+++ b/apps/web/src/features/crm/components/record-archived-status.tsx
@@ -0,0 +1,75 @@
+import { isTouchDevice } from '@core/mobile/isTouchDevice';
+import { Popover } from '@kobalte/core/popover';
+import { Badge, Button, badgeTriggerClasses, Tooltip } from '@ui';
+import { type JSX, Show } from 'solid-js';
+
+/** The explanation belongs to the chip; Restore is a separate focus target. */
+export function RecordArchivedStatus(props: {
+ kind: 'company' | 'contact';
+ parentArchived?: boolean;
+ children: JSX.Element;
+}) {
+ const explanation = () => {
+ if (props.parentArchived)
+ return 'Archived with their company. Restore the company first. The record, history and discussion are kept.';
+ if (props.kind === 'company')
+ return 'Excluded from visible CRM lists and search. Records and history are kept. Email syncing is off.';
+ return 'Excluded from visible People, company Team and CRM search results. History and discussion are kept.';
+ };
+ return (
+ <span
+ class={`inline-flex min-w-0 flex-wrap items-center gap-x-2 mobile:basis-full ${props.kind === 'contact' ? 'mobile:pl-13' : 'mobile:pl-11'}`}
+ data-crm-archived-status
+ >
+ <Show
+ when={isTouchDevice()}
+ fallback={
+ <Tooltip.Root>
+ <Tooltip.Trigger
+ class={badgeTriggerClasses({ variant: 'outline', size: 'sm' })}
+ aria-label="Archived — details"
+ >
+ Archived
+ </Tooltip.Trigger>
+ <Tooltip.Portal>
+ <Tooltip.Content>
+ <span class="max-w-72">{explanation()}</span>
+ </Tooltip.Content>
+ </Tooltip.Portal>
+ </Tooltip.Root>
+ }
+ >
+ <Popover placement="bottom-start" gutter={6} modal={false}>
+ <Popover.Trigger
+ as={Button}
+ variant="ghost"
+ size="sm"
+ class="touch:min-h-11"
+ aria-label="Archived — details"
+ >
+ <Badge variant="outline" size="sm">
+ Archived
+ </Badge>
+ </Popover.Trigger>
+ <Popover.Portal>
+ <Popover.Content class="menu-surface z-modal w-72 max-w-[calc(100vw-2rem)] p-3">
+ <Popover.Title class="sr-only">Archived</Popover.Title>
+ <Popover.Description class="text-sm text-ink-muted">
+ {explanation()}
+ </Popover.Description>
+ </Popover.Content>
+ </Popover.Portal>
+ </Popover>
+ </Show>
+ {props.children}
+ </span>
+ );
+}
+
+export function ArchivedRecordBadge() {
+ return (
+ <Badge variant="outline" size="xs">
+ Archived
+ </Badge>
+ );
+}
diff --git a/apps/web/src/features/crm/components/record-visibility-action.tsx b/apps/web/src/features/crm/components/record-visibility-action.tsx
index 13e775e854..c0144ef901 100644
--- a/apps/web/src/features/crm/components/record-visibility-action.tsx
+++ b/apps/web/src/features/crm/components/record-visibility-action.tsx
@@ -1,8 +1,8 @@
import { isTouchDevice } from '@core/mobile/isTouchDevice';
-import EyeIcon from '@icon/system/regular/eye.svg';
-import EyeSlashIcon from '@icon/system/regular/eye-slash.svg';
+import ArchiveIcon from '@icon/system/regular/archive.svg';
+import UndoIcon from '@icon/system/regular/arrow-u-up-left.svg';
import { Button, ButtonGroup, ConfirmDialog } from '@ui';
-import { createSignal, createUniqueId, Show } from 'solid-js';
+import { createSignal, createUniqueId, onCleanup, Show } from 'solid-js';
import { Dynamic } from 'solid-js/web';
type RecordVisibilityActionProps = {
@@ -14,10 +14,17 @@ type RecordVisibilityActionProps = {
pending: boolean;
iconOnly?: boolean;
grouped?: boolean;
- onChange: (hidden: boolean, onSuccess: () => void) => void;
+ parentArchived?: boolean;
+ parentPending?: boolean;
+ onOpenParent?: () => void;
+ onChange: (
+ hidden: boolean,
+ onSuccess: () => void,
+ onError: () => void
+ ) => void;
};
-/** Removal uses the existing reversible, team-wide hidden state. */
+/** Archive uses the existing reversible, team-scoped hidden state. */
export function RecordVisibilityAction(props: RecordVisibilityActionProps) {
return (
<Show when={props.recordId} keyed>
@@ -28,118 +35,177 @@ export function RecordVisibilityAction(props: RecordVisibilityActionProps) {
function VisibilityControl(props: RecordVisibilityActionProps) {
const [confirming, setConfirming] = createSignal(false);
+ const [failed, setFailed] = createSignal(false);
+ const [submitting, setSubmitting] = createSignal(false);
const permissionHintId = createUniqueId();
const permissionHint =
- 'Ask a team admin or owner to remove or restore this record.';
+ 'Ask a team admin or owner to archive or restore this record.';
+ let alive = true;
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;
+ onCleanup(() => {
+ alive = false;
+ if (!submitting() || (!confirming() && document.activeElement !== button))
+ return;
+ const id = props.recordId;
+ requestAnimationFrame(() =>
+ document
+ .querySelector<HTMLButtonElement>(
+ `[data-crm-visibility-record="${CSS.escape(id)}"]`
+ )
+ ?.focus()
+ );
+ });
+ const label = () => (props.hidden ? 'Restore' : 'Archive');
+ const pending = () => props.pending || submitting();
+ const submit = () => {
+ if (!props.canManage || pending() || props.parentPending) return;
+ if (props.hidden && props.parentArchived) return;
+ setFailed(false);
+ setSubmitting(true);
+ props.onChange(
+ !props.hidden,
+ () => {
+ if (!alive) return;
+ setSubmitting(false);
+ setConfirming(false);
+ },
+ () => {
+ if (!alive) return;
+ setSubmitting(false);
+ setFailed(true);
+ }
+ );
};
- const size = () => {
- if (!props.iconOnly) return;
- if (isTouchDevice()) return 'icon-lg';
- return props.grouped ? 'icon-sm' : 'icon-md';
+ const activate = () => {
+ setFailed(false);
+ if (props.hidden && props.kind === 'contact' && !props.parentArchived) {
+ submit();
+ } else {
+ setConfirming(true);
+ }
};
return (
- <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()}
+ data-crm-visibility-record={props.recordId}
+ variant={props.hidden ? 'link' : 'ghost'}
+ size={
+ props.hidden
+ ? 'sm'
+ : isTouchDevice()
+ ? 'icon-lg'
+ : props.grouped
+ ? 'icon-sm'
+ : 'icon-md'
+ }
+ class={props.hidden ? 'touch:min-h-11' : undefined}
aria-label={label()}
aria-describedby={!props.canManage ? permissionHintId : undefined}
- tooltip={tooltip()}
- disabled={!props.canManage || props.pending}
- onClick={() => setConfirming(true)}
+ tooltip={
+ !props.canManage
+ ? permissionHint
+ : !props.hidden
+ ? label()
+ : undefined
+ }
+ disabled={!props.canManage || pending() || props.parentPending}
+ onClick={activate}
>
<Show
when={props.hidden}
- fallback={
- <EyeSlashIcon
- class={props.iconOnly ? 'size-4 touch:size-6' : 'size-4'}
- />
- }
+ fallback={<ArchiveIcon class="size-4 touch:size-6" />}
>
- <EyeIcon class={props.iconOnly ? 'size-4 touch:size-6' : 'size-4'} />
+ <UndoIcon class="size-4" />
</Show>
- <Show when={!props.iconOnly}>{label()}</Show>
+ <Show when={props.hidden}>{label()}</Show>
</Dynamic>
- <Show when={props.hidden && !props.iconOnly}>
- <p class="text-xs text-ink-muted">
- This {props.kind === 'company' ? 'company' : 'person'} is hidden from
- your team's CRM lists.
- </p>
- </Show>
<Show when={!props.canManage}>
- <p
- id={permissionHintId}
- class={props.iconOnly ? 'sr-only' : 'text-xs text-ink-muted'}
- >
+ <span id={permissionHintId} class="sr-only">
{permissionHint}
- </p>
+ </span>
+ </Show>
+ <Show when={failed() && !confirming()}>
+ <span role="alert" class="text-xs text-failure">
+ Could not restore. Try again.
+ </span>
</Show>
<ConfirmDialog
open={confirming()}
- onOpenChange={setConfirming}
- onCloseAutoFocus={
- props.iconOnly
- ? (event) => {
- event.preventDefault();
- button?.focus();
- }
- : undefined
+ onOpenChange={(open) => {
+ setConfirming(open);
+ if (!open) setFailed(false);
+ }}
+ onCloseAutoFocus={(event) => {
+ if (button?.isConnected) {
+ event.preventDefault();
+ button.focus();
+ }
+ }}
+ title={
+ props.hidden && props.parentArchived
+ ? 'Restore the company first'
+ : `${label()} ${props.kind === 'company' ? 'company' : 'person'}?`
}
- title={`${label()}?`}
confirmLabel={
- props.iconOnly ? (
- <span class="whitespace-normal">{label()}</span>
- ) : (
- label()
- )
+ props.hidden && props.parentArchived ? 'Open company' : label()
}
- pending={props.pending}
+ pending={pending()}
onConfirm={() => {
- if (!props.canManage || props.pending) return;
- props.onChange(!props.hidden, () => setConfirming(false));
+ if (!props.canManage || pending()) return;
+ if (props.hidden && props.parentArchived) {
+ setConfirming(false);
+ props.onOpenParent?.();
+ } else submit();
}}
body={
- <Show
- when={props.hidden}
- fallback={
- <>
- Hide <span class="font-medium text-ink">{props.name}</span> from
- your team's CRM lists. This does not permanently delete the
- record. You can restore it from this page.
- <Show when={props.kind === 'company'}>
- {' '}
- All of its contacts will also be hidden, and team email sync
- will be turned off.
- </Show>
- </>
- }
- >
- Show <span class="font-medium text-ink">{props.name}</span> in your
- team's CRM lists again.
- <Show when={props.kind === 'company'}>
- {' '}
- All of its contacts will also be restored, including any hidden
- individually. Team email sync will stay off until you enable it
- separately.
+ <>
+ <Show
+ when={props.hidden}
+ fallback={
+ <>
+ Archive <span class="font-medium text-ink">{props.name}</span>{' '}
+ for your team. The record and its history are kept, and you
+ can restore it later.
+ <Show when={props.kind === 'company'}>
+ {' '}
+ All of its people will also be archived, and team email
+ syncing will be turned off.
+ </Show>
+ </>
+ }
+ >
+ <Show
+ when={props.parentArchived}
+ fallback={
+ <>
+ Restore{' '}
+ <span class="font-medium text-ink">{props.name}</span> to
+ your team's visible CRM lists.
+ <Show when={props.kind === 'company'}>
+ {' '}
+ All of its people will also be restored, including people
+ archived individually. Email syncing will stay off until
+ enabled separately.
+ </Show>
+ </>
+ }
+ >
+ This person is archived with their company. Open the company to
+ review and confirm restoring it and all its people. Email
+ syncing stays off.
+ </Show>
</Show>
- <Show when={props.kind === 'contact'}>
- {' '}
- If linked to a company, that company must also be visible for them
- to appear in People.
+ <Show when={failed()}>
+ <p role="alert" class="mt-3 text-failure">
+ Could not save the change. Try again or cancel.
+ </p>
</Show>
- </Show>
+ </>
}
/>
- </div>
+ </>
);
}
diff --git a/apps/web/src/features/crm/components/record-visibility-filter.tsx b/apps/web/src/features/crm/components/record-visibility-filter.tsx
new file mode 100644
index 0000000000..57d86e6cfa
--- /dev/null
+++ b/apps/web/src/features/crm/components/record-visibility-filter.tsx
@@ -0,0 +1,39 @@
+import { t } from '@app/lib/i18n';
+import FunnelIcon from '@icon/system/regular/funnel.svg';
+import { Button, Dropdown } from '@ui';
+
+/** One explicit, exclusive view shared by CRM record lists. */
+export function RecordVisibilityFilter(props: {
+ archived: boolean;
+ onChange: (archived: boolean) => void;
+ disabled?: boolean;
+}) {
+ return (
+ <Dropdown>
+ <Dropdown.Trigger
+ as={Button}
+ variant="secondary"
+ size="sm"
+ aria-label={t('viewMenus.crmVisibility')}
+ >
+ <FunnelIcon class="size-4" />
+ {props.archived
+ ? t('viewMenus.crmArchived')
+ : t('viewMenus.crmVisible')}
+ </Dropdown.Trigger>
+ <Dropdown.Content class="min-w-44 max-w-[calc(100vw-2rem)]">
+ <Dropdown.RadioGroup
+ value={props.archived ? 'archived' : 'visible'}
+ onChange={(value) => props.onChange(value === 'archived')}
+ >
+ <Dropdown.RadioItem value="visible">
+ {t('viewMenus.crmVisible')}
+ </Dropdown.RadioItem>
+ <Dropdown.RadioItem value="archived" disabled={props.disabled}>
+ {t('viewMenus.crmArchived')}
+ </Dropdown.RadioItem>
+ </Dropdown.RadioGroup>
+ </Dropdown.Content>
+ </Dropdown>
+ );
+}
diff --git a/apps/web/src/features/crm/crm-action-items.ts b/apps/web/src/features/crm/crm-action-items.ts
index ce7bc1d632..72a314ab68 100644
--- a/apps/web/src/features/crm/crm-action-items.ts
+++ b/apps/web/src/features/crm/crm-action-items.ts
@@ -1,4 +1,6 @@
+import { t } from '@app/lib/i18n';
import type { EntityData } from '@entity';
+import { useIsTeamAdmin } from '@queries/team/teams';
import type { EntityActionListState } from '../next-soup/actions/entity-action-context';
import { makeSetCompanyPropertyAction } from './crm-actions';
import { makeHideCompanyAction } from './crm-hide-action';
@@ -11,8 +13,10 @@ type CrmEntityActionItem = {
};
/** CRM actions contributed to shared entity menus. */
export function createCrmEntityActionItems() {
+ const canManage = useIsTeamAdmin();
const hiddenMutation = useSetCompanyHiddenMutation();
const hideCompanyAction = makeHideCompanyAction({
+ canManage,
setHidden: (companyId, hidden) =>
hiddenMutation.mutateAsync({ companyId, hidden }),
});
@@ -25,7 +29,7 @@ export function createCrmEntityActionItems() {
const canExecuteAll = (canExecute: (entity: EntityData) => boolean) =>
entities.length > 0 && entities.every(canExecute);
// CRM group: Set stage/owner/revenue on the whole company
- // selection, Hide / Unhide for a single company.
+ // selection, Archive / Restore for a single company.
const crmItems: CrmEntityActionItem[] = [];
for (const [field, label] of [
@@ -53,7 +57,9 @@ export function createCrmEntityActionItems() {
) {
crmItems.push({
id: 'hide-company',
- label: singleEntity.hidden ? 'Unhide' : 'Hide',
+ label: singleEntity.hidden
+ ? t('viewMenus.crmRestore')
+ : t('viewMenus.crmArchive'),
onClick: () => hideCompanyAction.executeWithSoup(entities, soup),
});
}
diff --git a/apps/web/src/features/crm/crm-company.tsx b/apps/web/src/features/crm/crm-company.tsx
index b3e69fb65a..2ce6ee9146 100644
--- a/apps/web/src/features/crm/crm-company.tsx
+++ b/apps/web/src/features/crm/crm-company.tsx
@@ -4,6 +4,7 @@ import { CrmProvider } from './context/crm-context';
import { COMPANY_SECTIONS, type CompanySection } from './core/record';
import { createAppCrmContext } from './crm-adapter';
import { Company as View } from './views/company-detail';
+import { CompanyVisibilityButton as VisibilityButton } from './views/company-visibility-button';
export type { CompanySection } from './core/record';
@@ -23,3 +24,14 @@ export function CompanyTabs(props: {
}) {
return <RecordTabs sections={COMPANY_SECTIONS} {...props} />;
}
+
+/** Company archive action for a host's top bar. */
+export function CompanyVisibilityButton(
+ props: ComponentProps<typeof VisibilityButton>
+) {
+ return (
+ <CrmProvider value={createAppCrmContext()}>
+ <VisibilityButton {...props} />
+ </CrmProvider>
+ );
+}
diff --git a/apps/web/src/features/crm/crm-hide-action.ts b/apps/web/src/features/crm/crm-hide-action.ts
index 264d5b1420..14a652ba76 100644
--- a/apps/web/src/features/crm/crm-hide-action.ts
+++ b/apps/web/src/features/crm/crm-hide-action.ts
@@ -1,45 +1,63 @@
import { toast } from '@core/component/Toast/Toast';
import type { EntityData } from '@entity';
+import { confirmDialog } from '@ui';
import type { EntityActionListState } from '../next-soup/actions/entity-action-context';
import { restoreSoupFocus } from '../next-soup/utils';
type MakeHideCompanyOptions = {
- // Available to all team members; the backend enforces
- // EditAccessLevel on PUT /crm/companies/{id}/hidden.
+ canManage: () => boolean;
setHidden: (companyId: string, hidden: boolean) => Promise<unknown>;
};
export const makeHideCompanyAction = (options: MakeHideCompanyOptions) => {
const { setHidden } = options;
+ let pending = false;
const canExecute = (entity: EntityData): boolean =>
- entity.type === 'crm_company';
+ entity.type === 'crm_company' && options.canManage();
const executeWithSoup = async (
entities: EntityData[],
soup: EntityActionListState
) => {
const entity = entities[0];
- if (entity?.type !== 'crm_company') return;
+ if (entity?.type !== 'crm_company' || !options.canManage() || pending)
+ return;
+ pending = true;
+ try {
+ const confirmed = await confirmDialog({
+ title: entity.hidden ? 'Restore company?' : 'Archive company?',
+ confirmLabel: entity.hidden ? 'Restore' : 'Archive',
+ body: entity.hidden
+ ? 'Restore this company for your team and all of its people, including people archived individually. Email syncing stays off until enabled separately.'
+ : 'Archive this company and all of its people for your team. Records and history are kept and can be restored later. Team email syncing will be turned off.',
+ });
+ if (!confirmed || !options.canManage()) return;
- // The row leaves (Hide) or joins (Unhide) the active list once soup
- // refetches, so move focus to a neighbour first — same as delete.
- const currentIndex = soup.focus.index();
- const nextRow =
- soup.items.at(currentIndex + 1) ?? soup.items.at(currentIndex - 1);
- const hidden = entity.hidden;
+ // The row leaves or joins the selected view once soup
+ // refetches, so move focus to a neighbour first — same as delete.
+ const currentIndex = soup.focus.index();
+ const nextRow =
+ soup.items.at(currentIndex + 1) ?? soup.items.at(currentIndex - 1);
+ const hidden = entity.hidden;
- soup.selection.clear();
- if (nextRow) soup.focus.set(nextRow.id);
+ try {
+ await setHidden(entity.id, !hidden);
+ soup.selection.clear();
+ if (nextRow) soup.focus.set(nextRow.id);
+ toast.success(hidden ? 'Company restored' : 'Company archived');
+ } catch {
+ toast.failure(
+ hidden
+ ? 'Could not restore. Try again.'
+ : 'Could not archive. Try again.'
+ );
+ }
- try {
- await setHidden(entity.id, !hidden);
- toast.success(hidden ? 'Unhidden' : 'Hidden');
- } catch {
- toast.failure(hidden ? 'Failed to unhide' : 'Failed to hide');
+ await restoreSoupFocus(nextRow?.id);
+ } finally {
+ pending = false;
}
-
- await restoreSoupFocus(nextRow?.id);
};
return { canExecute, executeWithSoup };
diff --git a/apps/web/src/features/crm/primitives/people-visibility.test.ts b/apps/web/src/features/crm/primitives/people-visibility.test.ts
index 0ccf6d8d47..919a54c32a 100644
--- a/apps/web/src/features/crm/primitives/people-visibility.test.ts
+++ b/apps/web/src/features/crm/primitives/people-visibility.test.ts
@@ -8,6 +8,8 @@ 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 {
+ crmCompanyActiveFilter,
+ crmCompanyHiddenFilter,
crmContactActiveFilter,
crmContactHiddenFilter,
} from '../collection-filters';
@@ -47,7 +49,12 @@ function setup() {
FilterContext,
PredicateConfig<EntityData, string, FilterContext>
>({
- configs: [crmContactActiveFilter, crmContactHiddenFilter],
+ configs: [
+ crmContactActiveFilter,
+ crmContactHiddenFilter,
+ crmCompanyActiveFilter,
+ crmCompanyHiddenFilter,
+ ],
initial: { or: ['crm-contact-hidden'] },
});
const visibility = createPeopleVisibility({
@@ -184,3 +191,21 @@ it('keeps an explicitly selected removed view scoped when a shared filter replac
expect(queryFilters.state.include.crmContactTeamId).toEqual(['team-1']);
expect(visibility.showRemoved()).toBe(true);
});
+
+it('selects archived-only companies without changing search or unrelated filters', () => {
+ const { visibility, queryFilters, predicates, setActiveTab, setAdmin } =
+ mount();
+ setActiveTab('active');
+ queryFilters.set({ include: { crmCompanyId: ['company-1'] } });
+ visibility.setShowRemoved(true);
+ expect(queryFilters.state.include.crmCompanyHidden).toBe(true);
+ expect(queryFilters.state.include.crmCompanyId).toEqual(['company-1']);
+ expect(predicates.andIds()).toEqual(['crm-company-hidden']);
+ visibility.setShowRemoved(false);
+ expect(queryFilters.state.include.crmCompanyHidden).toBe(false);
+ expect(predicates.andIds()).toEqual(['crm-company-active']);
+ visibility.setShowRemoved(true);
+ setAdmin(false);
+ setAdmin(true);
+ expect(visibility.showRemoved()).toBe(false);
+});
diff --git a/apps/web/src/features/crm/primitives/people-visibility.ts b/apps/web/src/features/crm/primitives/people-visibility.ts
index 48ca4f30ed..4e29a9403f 100644
--- a/apps/web/src/features/crm/primitives/people-visibility.ts
+++ b/apps/web/src/features/crm/primitives/people-visibility.ts
@@ -11,6 +11,11 @@ import type {
CrmWorkspace,
PeopleVisibility,
} from '../context/workspace-context';
+import { isCrmActivityTab, pipelineIdOfTab } from '../core/navigation';
+
+function recordList(tab: string | undefined): boolean {
+ return !!tab && !isCrmActivityTab(tab) && !pipelineIdOfTab(tab);
+}
/** A local, explicit choice. Shared links and saved filters cannot enable it. */
export function createPeopleVisibility(scope: {
@@ -24,16 +29,23 @@ export function createPeopleVisibility(scope: {
? JSON.stringify([scope.userId(), scope.teamId()])
: undefined
);
- const [requested, setRequested] = createSignal<string>();
- const people = () => scope.activeTab() === 'people';
+ const [requested, setRequested] = createSignal<string | undefined>(
+ scope.activeTab() === 'hidden' ? identity() : undefined
+ );
+ const isList = () => recordList(scope.activeTab());
const canShowRemoved = () => !!identity();
const showRemoved = () =>
- people() && !!identity() && requested() === identity();
+ isList() && !!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 })
+ on(
+ [identity, scope.activeTab],
+ () =>
+ setRequested(scope.activeTab() === 'hidden' ? identity() : undefined),
+ { defer: true }
+ )
);
return {
@@ -41,7 +53,7 @@ export function createPeopleVisibility(scope: {
showRemoved,
removedTeamId: () => (showRemoved() ? scope.teamId() : undefined),
setShowRemoved(value: boolean) {
- const next = value && people() ? identity() : undefined;
+ const next = value && isList() ? identity() : undefined;
if (next === requested()) return;
const operation = startUiOperation('crm.people_visibility', {
attributes: { 'crm.hidden': !!next },
@@ -63,6 +75,10 @@ export function bindPeopleVisibility(
on(
() => ({
people: view.activeTab() === 'people',
+ companies:
+ view.activeTab() !== 'people' && recordList(view.activeTab()),
+ companyHidden: view.queryFilters.state.include.crmCompanyHidden,
+ excludedCompanyHidden: view.queryFilters.state.exclude.crmCompanyHidden,
showRemoved: visibility.showRemoved(),
removedTeamId: visibility.removedTeamId(),
includedHidden: view.queryFilters.state.include.crmContactHidden,
@@ -74,6 +90,9 @@ export function bindPeopleVisibility(
}),
({
people,
+ companies,
+ companyHidden,
+ excludedCompanyHidden,
showRemoved,
removedTeamId,
includedHidden,
@@ -85,9 +104,6 @@ export function bindPeopleVisibility(
}) => {
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) ||
@@ -108,26 +124,40 @@ export function bindPeopleVisibility(
},
});
}
- if (
- people &&
- (!and.includes(expected) ||
+ const companyVisibility = (id: string) =>
+ id === 'crm-company-active' || id === 'crm-company-hidden';
+ const contactVisibility = (id: string) =>
+ id === 'crm-contact-active' || id === 'crm-contact-hidden';
+ if (people || companies) {
+ const expected = people
+ ? hidden
+ ? 'crm-contact-hidden'
+ : 'crm-contact-active'
+ : showRemoved
+ ? 'crm-company-hidden'
+ : 'crm-company-active';
+ const isVisibility = (id: string) =>
+ companyVisibility(id) || contactVisibility(id);
+ if (
+ !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'),
- });
+ or.some(isVisibility)
+ ) {
+ view.soup.predicates.set({
+ and: [...and.filter((id) => !isVisibility(id)), expected],
+ or: or.filter((id) => !isVisibility(id)),
+ });
+ }
}
+ if (
+ companies &&
+ (companyHidden !== showRemoved ||
+ excludedCompanyHidden !== undefined)
+ )
+ view.queryFilters.set({
+ include: { crmCompanyHidden: showRemoved },
+ exclude: { crmCompanyHidden: undefined },
+ });
});
}
)
diff --git a/apps/web/src/features/crm/queries/companies.ts b/apps/web/src/features/crm/queries/companies.ts
index 3ae4f2027a..76ab4b1dd5 100644
--- a/apps/web/src/features/crm/queries/companies.ts
+++ b/apps/web/src/features/crm/queries/companies.ts
@@ -3,8 +3,10 @@ import { analytics } from '@app/lib/analytics';
import { ThrownResultError, throwOnErr } from '@core/util/result';
import type { CrmCompanyEntity } from '@entity';
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 { prepareCrmVisibilityWrite } from '@service-storage/crm-visibility';
import type { CrmCompanyResponse } from '@service-storage/generated/schemas/crmCompanyResponse';
import type { CrmContactResponse } from '@service-storage/generated/schemas/crmContactResponse';
import {
@@ -17,6 +19,12 @@ import { type Accessor, createMemo } from 'solid-js';
import type { CompanyImporter } from '../context/crm-sources';
import type { CrmRecordDependencies } from './dependencies';
import { crmKeys } from './keys';
+import { listCanIncludeCrm } from './list-refresh';
+import {
+ updateVisibilityDetails,
+ visibilityDetailsFilter,
+ visibilityQueryFilter,
+} from './visibility-refresh';
const COMPANY_STALE_TIME = 60 * 1000;
@@ -319,24 +327,65 @@ export function useSetCompanyHiddenMutation(deps: CrmRecordDependencies) {
span.setAttr('crm.record_id', companyId);
span.setAttr('crm.hidden', hidden);
try {
- const result = await throwOnErr(() =>
- deps.storage.setCompanyHidden({ companyId, hidden })
+ const cacheWrite = prepareCrmVisibilityWrite();
+ // The write returns no affected contact IDs. A stale or empty roster
+ // would leave cascaded contacts eligible in normalized search.
+ const company = await throwOnErr(() =>
+ deps.storage.getCompany({ companyId })
+ );
+ if (!cacheWrite.isCurrent()) throw new Error('Session changed');
+ const result = await span.run(() =>
+ throwOnErr(() =>
+ deps.storage.setCompanyHidden({ companyId, hidden })
+ )
);
+ if (!cacheWrite.isCurrent()) return result;
await span.span(
'crm.visibility_change.refresh',
async (refresh) => {
try {
- await invalidateCachedCrmContacts();
+ const change = {
+ kind: 'company' as const,
+ id: companyId,
+ hidden,
+ };
+ await Promise.all([
+ cacheWrite.commit({
+ companyId,
+ contactIds: company.contacts.map((contact) => contact.id),
+ hidden,
+ }),
+ updateVisibilityDetails(
+ deps.client,
+ change,
+ cacheWrite.isCurrent
+ ),
+ ]);
+ if (!cacheWrite.isCurrent()) return;
wipeCompanyEmailCache(deps, companyId);
await Promise.all([
- deps.client.invalidateQueries({ queryKey: soupKeys._def }),
+ refreshActiveGraphqlSoupQueries({
+ where: listCanIncludeCrm,
+ unmaintainedOnly: true,
+ }),
+ deps.client.invalidateQueries({
+ predicate: visibilityQueryFilter(change),
+ }),
deps.client.invalidateQueries({
- queryKey: crmKeys.company(companyId).queryKey,
+ predicate: visibilityDetailsFilter(change),
+ // Confirmed flags are already patched; refresh on the next visit.
+ refetchType: 'none',
+ }),
+ deps.client.refetchQueries({
+ type: 'active',
+ predicate: (query) =>
+ query.state.data === undefined &&
+ visibilityDetailsFilter(change)(query),
}),
]);
} catch (error) {
refresh.error('Company visibility refresh failed');
- throw error;
+ Telemetry.error(error);
}
}
);
diff --git a/apps/web/src/features/crm/queries/company-suggestions.ts b/apps/web/src/features/crm/queries/company-suggestions.ts
index aeb108d18d..bab0f22c50 100644
--- a/apps/web/src/features/crm/queries/company-suggestions.ts
+++ b/apps/web/src/features/crm/queries/company-suggestions.ts
@@ -38,7 +38,12 @@ export function useQuickAccessCrmCompaniesQuery(
);
const companies = createMemo<CrmCompanyEntity[]>(() =>
- query.isSuccess ? (query.data?.filter(isCrmCompanyEntity) ?? []) : []
+ query.isSuccess
+ ? (query.data?.filter(
+ (entity): entity is CrmCompanyEntity =>
+ isCrmCompanyEntity(entity) && !entity.hidden
+ ) ?? [])
+ : []
);
return { query, companies };
diff --git a/apps/web/src/features/crm/queries/company-visibility.test.tsx b/apps/web/src/features/crm/queries/company-visibility.test.tsx
new file mode 100644
index 0000000000..7922f184b9
--- /dev/null
+++ b/apps/web/src/features/crm/queries/company-visibility.test.tsx
@@ -0,0 +1,91 @@
+import { storageServiceClient } from '@service-storage/client';
+import { cleanup, render } from '@solidjs/testing-library';
+import { QueryClient } from '@tanstack/solid-query';
+import { err, ok } from 'neverthrow';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import { useSetCompanyHiddenMutation } from './companies';
+import { crmKeys } from './keys';
+
+const cache = vi.hoisted(() => ({
+ commit: vi.fn(async () => {}),
+ isCurrent: () => true,
+}));
+vi.mock('@service-storage/crm-visibility', () => ({
+ prepareCrmVisibilityWrite: () => cache,
+}));
+vi.mock('@service-storage/client', () => ({
+ storageServiceClient: { getCompany: vi.fn(), setCompanyHidden: vi.fn() },
+}));
+const company = {
+ id: 'company-1',
+ teamId: 'team-1',
+ name: 'Example company',
+ hidden: false,
+ emailSync: true,
+ domains: [],
+ createdAt: '2026-10-15',
+ updatedAt: '2026-10-15',
+ contacts: [],
+};
+let client: QueryClient;
+beforeEach(() => {
+ vi.clearAllMocks();
+ client = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ vi.mocked(storageServiceClient.setCompanyHidden).mockResolvedValue(
+ ok(undefined)
+ );
+});
+afterEach(() => {
+ cleanup();
+ client.clear();
+});
+function mount() {
+ let mutation!: ReturnType<typeof useSetCompanyHiddenMutation>;
+ render(() => {
+ mutation = useSetCompanyHiddenMutation({
+ client,
+ storage: storageServiceClient,
+ });
+ return null;
+ });
+ return mutation;
+}
+it('does not archive with an incomplete cached roster when the fresh roster fails', async () => {
+ client.setQueryData(crmKeys.company(company.id).queryKey, company);
+ vi.mocked(storageServiceClient.getCompany).mockResolvedValue(
+ err([{ code: 'NETWORK_ERROR', message: 'Offline' }])
+ );
+ await expect(
+ mount().mutateAsync({ companyId: company.id, hidden: true })
+ ).rejects.toThrow();
+ expect(storageServiceClient.setCompanyHidden).not.toHaveBeenCalled();
+ expect(cache.commit).not.toHaveBeenCalled();
+ expect(client.getQueryData(crmKeys.company(company.id).queryKey)).toEqual(
+ company
+ );
+});
+it('includes contacts absent from the cached company when applying a confirmed cascade', async () => {
+ client.setQueryData(crmKeys.company(company.id).queryKey, company);
+ const contact = {
+ id: 'contact-1',
+ companyId: company.id,
+ name: 'Example person',
+ email: '[email protected]',
+ hidden: false,
+ createdAt: '2026-10-15',
+ updatedAt: '2026-10-15',
+ firstInteraction: '2026-10-15',
+ lastInteraction: '2026-10-15',
+ };
+ vi.mocked(storageServiceClient.getCompany).mockResolvedValue(
+ ok({ ...company, contacts: [contact] })
+ );
+ await mount().mutateAsync({ companyId: company.id, hidden: true });
+ expect(cache.commit).toHaveBeenCalledWith({
+ companyId: company.id,
+ contactIds: [contact.id],
+ hidden: true,
+ });
+});
diff --git a/apps/web/src/features/crm/queries/contact-visibility.test.tsx b/apps/web/src/features/crm/queries/contact-visibility.test.tsx
index e225ebf348..8077fec332 100644
--- a/apps/web/src/features/crm/queries/contact-visibility.test.tsx
+++ b/apps/web/src/features/crm/queries/contact-visibility.test.tsx
@@ -1,6 +1,15 @@
import { registerActiveGraphqlSoupQuery } from '@queries/soup/graphql/active-queries';
import { storageServiceClient } from '@service-storage/client';
import { invalidateCachedCrmContacts } from '@service-storage/crm-contacts';
+
+const cache = vi.hoisted(() => ({
+ commit: vi.fn(async () => {}),
+ isCurrent: vi.fn(() => true),
+}));
+vi.mock('@service-storage/crm-visibility', () => ({
+ prepareCrmVisibilityWrite: () => cache,
+}));
+
import type { CrmContactResponse } from '@service-storage/generated/schemas/crmContactResponse';
import { cleanup, render } from '@solidjs/testing-library';
import { QueryClient, QueryObserver } from '@tanstack/solid-query';
@@ -32,6 +41,8 @@ let contact: CrmContactResponse;
beforeEach(() => {
vi.clearAllMocks();
+ cache.isCurrent.mockReturnValue(true);
+ cache.commit.mockResolvedValue(undefined);
contact = { ...CONTACT };
client = new QueryClient({
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
@@ -147,14 +158,12 @@ it('preserves a member denial when loading a hidden contact directly', async ()
).toBeUndefined();
});
-it('surfaces a cache refresh failure after a successful write', async () => {
- vi.mocked(invalidateCachedCrmContacts).mockRejectedValueOnce(
- new Error('Cache unavailable')
- );
+it('keeps a successful backend write successful when a refresh fails', async () => {
+ cache.commit.mockRejectedValueOnce(new Error('Cache unavailable'));
const { mutation } = mount();
await expect(
mutation.mutateAsync({ contactId: CONTACT.id, hidden: true })
- ).rejects.toThrow('Cache unavailable');
+ ).resolves.toBeUndefined();
expect(contact.hidden).toBe(true);
});
@@ -208,7 +217,7 @@ it('awaits GraphQL People membership refresh for hide and restore, excluding unr
}
});
-it('reports an active GraphQL refresh failure and does not refresh after a rejected write', async () => {
+it('preserves confirmed state after an active GraphQL refresh failure and skips refresh after a rejected write', async () => {
const refresh = vi.fn(async () => {
throw new Error('Unavailable');
});
@@ -221,7 +230,12 @@ it('reports an active GraphQL refresh failure and does not refresh after a rejec
const { mutation } = mount();
await expect(
mutation.mutateAsync({ contactId: CONTACT.id, hidden: true })
- ).rejects.toThrow('revalidation');
+ ).resolves.toBeUndefined();
+ expect(
+ client.getQueryData<CrmContactResponse>(
+ crmKeys.contact(CONTACT.id).queryKey
+ )?.hidden
+ ).toBe(true);
vi.mocked(storageServiceClient.setContactHidden).mockResolvedValue(
err([{ code: 'FORBIDDEN', message: 'Denied' }])
);
@@ -233,3 +247,49 @@ it('reports an active GraphQL refresh failure and does not refresh after a rejec
unregister();
}
});
+
+it('ignores a late response after the session changes', async () => {
+ const key = crmKeys.contact(CONTACT.id).queryKey;
+ client.setQueryData(key, CONTACT);
+ vi.mocked(storageServiceClient.setContactHidden).mockImplementation(
+ async () => {
+ cache.isCurrent.mockReturnValue(false);
+ return ok(undefined);
+ }
+ );
+ const { mutation } = mount();
+ await mutation.mutateAsync({ contactId: CONTACT.id, hidden: true });
+ expect(cache.commit).not.toHaveBeenCalled();
+ expect(client.getQueryData<CrmContactResponse>(key)?.hidden).toBe(false);
+});
+
+it('keeps confirmed detail usable when background reads are unavailable', async () => {
+ const { mutation, detail } = mount();
+ await detail.refetch();
+ vi.mocked(storageServiceClient.getContact).mockResolvedValue(
+ err([{ code: 'NETWORK_ERROR', message: 'Offline' }])
+ );
+ const reads = vi.mocked(storageServiceClient.getContact).mock.calls.length;
+ await mutation.mutateAsync({ contactId: CONTACT.id, hidden: true });
+ expect(detail.isSuccess).toBe(true);
+ expect(detail.data?.hidden).toBe(true);
+ expect(storageServiceClient.getContact).toHaveBeenCalledTimes(reads);
+});
+
+it('restarts an active initial detail read cancelled by a successful row action', async () => {
+ let release!: (
+ value: Awaited<ReturnType<typeof storageServiceClient.getContact>>
+ ) => void;
+ vi.mocked(storageServiceClient.getContact).mockImplementationOnce(
+ () =>
+ new Promise((resolve) => {
+ release = resolve;
+ })
+ );
+ const { mutation, detail } = mount();
+ await vi.waitFor(() => expect(release).toBeTypeOf('function'));
+ await mutation.mutateAsync({ contactId: CONTACT.id, hidden: true });
+ release(ok(CONTACT));
+ await vi.waitFor(() => expect(detail.isSuccess).toBe(true));
+ expect(detail.data?.hidden).toBe(true);
+});
diff --git a/apps/web/src/features/crm/queries/contacts.ts b/apps/web/src/features/crm/queries/contacts.ts
index 0c3d887244..fcbd3744a8 100644
--- a/apps/web/src/features/crm/queries/contacts.ts
+++ b/apps/web/src/features/crm/queries/contacts.ts
@@ -3,12 +3,18 @@ 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 { prepareCrmVisibilityWrite } from '@service-storage/crm-visibility';
import type { CrmContactResponse } from '@service-storage/generated/schemas/crmContactResponse';
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';
+import {
+ updateVisibilityDetails,
+ visibilityDetailsFilter,
+ visibilityQueryFilter,
+} from './visibility-refresh';
const CONTACT_STALE_TIME = 60 * 1000;
@@ -27,7 +33,7 @@ function crmContactByEmailQueryOptions(
signal,
})
);
- if (contact) {
+ if (contact && !signal.aborted) {
deps.client.setQueryData(crmKeys.contact(contact.id).queryKey, contact);
}
return contact;
@@ -169,32 +175,52 @@ export function useSetContactHiddenMutation(deps: CrmRecordDependencies) {
span.setAttr('crm.record_id', contactId);
span.setAttr('crm.hidden', hidden);
try {
+ const cacheWrite = prepareCrmVisibilityWrite();
const result = await throwOnErr(() =>
deps.storage.setContactHidden({ contactId, hidden })
);
+ if (!cacheWrite.isCurrent()) return result;
await span.span(
'crm.visibility_change.refresh',
async (refresh) => {
try {
- await invalidateCachedCrmContacts(contactId);
+ const change = {
+ kind: 'contact' as const,
+ id: contactId,
+ hidden,
+ };
+ await Promise.all([
+ cacheWrite.commit({ contactIds: [contactId], hidden }),
+ updateVisibilityDetails(
+ deps.client,
+ change,
+ cacheWrite.isCurrent
+ ),
+ ]);
+ if (!cacheWrite.isCurrent()) return;
await Promise.all([
refreshActiveGraphqlSoupQueries({
where: listCanIncludeCrmContacts,
- throwOnError: true,
+ unmaintainedOnly: true,
}),
- deps.client.invalidateQueries({ queryKey: soupKeys._def }),
deps.client.invalidateQueries({
- queryKey: crmKeys.contact(contactId).queryKey,
+ predicate: visibilityQueryFilter(change),
}),
- // Company responses embed contacts. Invalidate the family
- // even when no contact detail (or company ID) is cached.
deps.client.invalidateQueries({
- queryKey: crmKeys.company._def,
+ predicate: visibilityDetailsFilter(change),
+ // Confirmed flags are already patched; refresh on the next visit.
+ refetchType: 'none',
+ }),
+ deps.client.refetchQueries({
+ type: 'active',
+ predicate: (query) =>
+ query.state.data === undefined &&
+ visibilityDetailsFilter(change)(query),
}),
]);
} catch (error) {
refresh.error('Contact visibility refresh failed');
- throw error;
+ Telemetry.error(error);
}
}
);
diff --git a/apps/web/src/features/crm/queries/visibility-refresh.test.ts b/apps/web/src/features/crm/queries/visibility-refresh.test.ts
new file mode 100644
index 0000000000..fc5bb1fd51
--- /dev/null
+++ b/apps/web/src/features/crm/queries/visibility-refresh.test.ts
@@ -0,0 +1,188 @@
+import { QueryClient } from '@tanstack/solid-query';
+import { expect, it } from 'vitest';
+import { crmKeys } from './keys';
+import {
+ patchVisibilitySnapshot,
+ updateVisibilityDetails,
+ visibilityQueryFilter,
+} from './visibility-refresh';
+
+it('updates cached suggestion pages and parent contacts without touching documents, dates, cursors or other companies', () => {
+ const date = new Date('2026-10-15');
+ const data = {
+ pages: [
+ {
+ contacts: [
+ {
+ __typename: 'GraphqlSoupCrmContact',
+ id: 'contact-1',
+ contactCompanyId: 'company-1',
+ hidden: false,
+ },
+ {
+ __typename: 'GraphqlSoupCrmContact',
+ id: 'contact-2',
+ contactCompanyId: 'company-2',
+ hidden: false,
+ },
+ ],
+ items: [
+ { tag: 'crmCompany', data: { id: 'company-1', hidden: false } },
+ { tag: 'document', data: { id: 'company-1', hidden: false, date } },
+ ],
+ nextCursor: 'next',
+ },
+ ],
+ pageParams: [null],
+ };
+ const result = patchVisibilitySnapshot(data, {
+ kind: 'company',
+ id: 'company-1',
+ hidden: true,
+ }) as typeof data;
+ expect(result.pages[0].contacts.map((contact) => contact.hidden)).toEqual([
+ true,
+ false,
+ ]);
+ expect(result.pages[0].items[0].data.hidden).toBe(true);
+ expect(result.pages[0].items[1]).toEqual(data.pages[0].items[1]);
+ expect(result.pages[0].items[1].data.date).toBe(date);
+ expect(result.pages[0].nextCursor).toBe('next');
+ expect(result.pageParams).toEqual([null]);
+});
+
+it('scopes paginated grouped refreshes using the body rather than the params', () => {
+ const client = new QueryClient();
+ const affected = [
+ 'soup',
+ 'groupedGroup',
+ 'group',
+ 'one',
+ 'none',
+ { limit: 25 },
+ { crmf: { l: { hidden: false } } },
+ ];
+ const other = [
+ 'soup',
+ 'groupedGroup',
+ 'group',
+ 'two',
+ 'none',
+ { limit: 25 },
+ { df: {} },
+ ];
+ for (const key of [affected, other, ['settings']])
+ client.setQueryData(key, {});
+ expect(
+ client
+ .getQueryCache()
+ .findAll({
+ predicate: visibilityQueryFilter({
+ kind: 'contact',
+ id: 'contact-1',
+ hidden: true,
+ }),
+ })
+ .map((q) => q.queryKey)
+ ).toEqual([affected]);
+ client.clear();
+});
+
+it('cancels pre-save REST reads before applying confirmed state', async () => {
+ const client = new QueryClient();
+ const key = crmKeys.contact('contact-1').queryKey;
+ const contact = { id: 'contact-1', companyId: 'company-1', hidden: false };
+ client.setQueryData(key, contact);
+ let release!: (value: typeof contact) => void;
+ const read = client
+ .fetchQuery({
+ queryKey: key,
+ queryFn: () =>
+ new Promise<typeof contact>((resolve) => {
+ release = resolve;
+ }),
+ })
+ .catch(() => undefined);
+ await updateVisibilityDetails(client, {
+ kind: 'contact',
+ id: 'contact-1',
+ hidden: true,
+ });
+ release(contact);
+ await read;
+ expect(client.getQueryData(key)).toEqual({ ...contact, hidden: true });
+ client.clear();
+});
+
+it('patches company-capable search pages and cancels old responses without touching unrelated search', async () => {
+ const client = new QueryClient();
+ const companyKey = [
+ 'soup',
+ 'search',
+ { page_size: 20 },
+ { query: 'example', include_crm: true },
+ ];
+ const documentKey = ['soup', 'search', {}, { query: 'example' }];
+ const otherCompanyKey = [
+ 'soup',
+ 'search',
+ {},
+ {
+ query: 'example',
+ include_crm: true,
+ filters: { crm_company_filters: { company_ids: ['company-2'] } },
+ },
+ ];
+ const page = {
+ pages: [
+ {
+ results: [
+ { type: 'company', id: 'company-1', hidden: false },
+ { type: 'document', id: 'company-1', hidden: false },
+ ],
+ next_cursor: 'more',
+ },
+ ],
+ pageParams: [null],
+ };
+ for (const key of [companyKey, documentKey, otherCompanyKey])
+ client.setQueryData(key, page);
+ let release!: (value: typeof page) => void;
+ const read = client
+ .fetchQuery({
+ queryKey: companyKey,
+ queryFn: () =>
+ new Promise<typeof page>((resolve) => {
+ release = resolve;
+ }),
+ })
+ .catch(() => undefined);
+ await updateVisibilityDetails(client, {
+ kind: 'company',
+ id: 'company-1',
+ hidden: true,
+ });
+ release(page);
+ await read;
+ expect(client.getQueryData(companyKey)).toEqual({
+ ...page,
+ pages: [
+ {
+ ...page.pages[0],
+ results: [
+ { type: 'company', id: 'company-1', hidden: true },
+ page.pages[0].results[1],
+ ],
+ },
+ ],
+ });
+ expect(client.getQueryData(documentKey)).toEqual(page);
+ expect(client.getQueryData(otherCompanyKey)).toEqual(page);
+ await updateVisibilityDetails(client, {
+ kind: 'company',
+ id: 'company-1',
+ hidden: false,
+ });
+ expect(client.getQueryData(companyKey)).toEqual(page);
+ client.clear();
+});
diff --git a/apps/web/src/features/crm/queries/visibility-refresh.ts b/apps/web/src/features/crm/queries/visibility-refresh.ts
new file mode 100644
index 0000000000..515baf877e
--- /dev/null
+++ b/apps/web/src/features/crm/queries/visibility-refresh.ts
@@ -0,0 +1,193 @@
+import type { CrmCompanyResponse } from '@service-storage/generated/schemas/crmCompanyResponse';
+import type { CrmContactResponse } from '@service-storage/generated/schemas/crmContactResponse';
+import type { Query, QueryClient } from '@tanstack/solid-query';
+import { crmKeys } from './keys';
+import { listCanIncludeCrm, listCanIncludeCrmContacts } from './list-refresh';
+
+export type CrmVisibilityChange = {
+ kind: 'company' | 'contact';
+ id: string;
+ hidden: boolean;
+};
+
+/** REST Soup and paginated suggestions are separate from the normalized cache. */
+export function visibilityQueryFilter(change: CrmVisibilityChange) {
+ return (query: Query): boolean => {
+ const key = query.queryKey;
+ if (key[0] !== 'soup') return false;
+ if (key[1] === 'crmPeople') return true;
+ if (key[1] === 'astItems')
+ return change.kind === 'company'
+ ? listCanIncludeCrm(key[3])
+ : listCanIncludeCrmContacts(key[3]);
+ if (key[1] === 'groupedGroup')
+ return change.kind === 'company'
+ ? listCanIncludeCrm(key[6])
+ : listCanIncludeCrmContacts(key[6]);
+ if (change.kind !== 'company') return false;
+ let body = key[3];
+ if (key[1] === 'search') {
+ if (
+ !body ||
+ typeof body !== 'object' ||
+ !('include_crm' in body) ||
+ body.include_crm !== true
+ )
+ return false;
+ body = 'filters' in body ? body.filters : undefined;
+ } else if (key[1] !== 'items') return false;
+ if (
+ typeof body !== 'object' ||
+ body === null ||
+ !('crm_company_filters' in body)
+ )
+ return true;
+ const filter = body.crm_company_filters;
+ if (
+ typeof filter !== 'object' ||
+ filter === null ||
+ !('company_ids' in filter)
+ )
+ return true;
+ return (
+ !Array.isArray(filter.company_ids) ||
+ !filter.company_ids.length ||
+ filter.company_ids.includes(change.id)
+ );
+ };
+}
+
+/** Unknown detail responses may embed the affected record; known unrelated records stay warm. */
+export function visibilityDetailsFilter(change: CrmVisibilityChange) {
+ return (query: Query): boolean => {
+ const key = query.queryKey;
+ if (key[0] !== 'crm') return false;
+ if (key[1] === 'contact' && change.kind === 'contact')
+ return key[2] === change.id;
+ const data = query.state.data;
+ if (key[1] === 'company') {
+ if (change.kind === 'company') return key[2] === change.id;
+ if (
+ !data ||
+ typeof data !== 'object' ||
+ !('contacts' in data) ||
+ !Array.isArray(data.contacts)
+ )
+ return true;
+ return data.contacts.some((contact) => contact.id === change.id);
+ }
+ if (key[1] !== 'contact' && key[1] !== 'contactByEmail') return false;
+ if (!data || typeof data !== 'object') return true;
+ return change.kind === 'contact'
+ ? 'id' in data && data.id === change.id
+ : 'companyId' in data && data.companyId === change.id;
+ };
+}
+
+/** Apply only confirmed facts, before a background read can render an old row. */
+export async function updateVisibilityDetails(
+ client: QueryClient,
+ change: CrmVisibilityChange,
+ isCurrent: () => boolean = () => true
+) {
+ await Promise.all([
+ client.cancelQueries({ predicate: visibilityDetailsFilter(change) }),
+ client.cancelQueries({ predicate: visibilityQueryFilter(change) }),
+ ]);
+ if (!isCurrent()) return;
+ client.setQueriesData({ predicate: visibilityQueryFilter(change) }, (data) =>
+ patchVisibilitySnapshot(data, change)
+ );
+ const patchContact = (contact: CrmContactResponse | undefined) => {
+ if (!contact) return contact;
+ if (
+ change.kind === 'contact'
+ ? contact.id !== change.id
+ : contact.companyId !== change.id
+ )
+ return contact;
+ return { ...contact, hidden: change.hidden };
+ };
+ client.setQueriesData<CrmContactResponse>(
+ { queryKey: crmKeys.contact._def },
+ patchContact
+ );
+ client.setQueriesData<CrmContactResponse | null>(
+ { queryKey: crmKeys.contactByEmail._def },
+ (contact) => (contact ? patchContact(contact) : contact)
+ );
+ client.setQueriesData<CrmCompanyResponse>(
+ { queryKey: crmKeys.company._def },
+ (company) => {
+ if (!company) return company;
+ const contacts = company.contacts.map(
+ (contact) => patchContact(contact)!
+ );
+ if (change.kind === 'company' && company.id === change.id)
+ return {
+ ...company,
+ contacts,
+ hidden: change.hidden,
+ emailSync: change.hidden ? false : company.emailSync,
+ };
+ return contacts.some(
+ (contact, index) => contact !== company.contacts[index]
+ )
+ ? { ...company, contacts }
+ : company;
+ }
+ );
+}
+
+/** Preserve page/cursor structure while patching CRM records in legacy query snapshots. */
+export function patchVisibilitySnapshot(
+ data: unknown,
+ change: CrmVisibilityChange,
+ recordType?: 'company' | 'contact'
+): unknown {
+ if (Array.isArray(data))
+ return data.map((value) => patchVisibilitySnapshot(value, change));
+ if (typeof data !== 'object' || data === null || data instanceof Date)
+ return data;
+ let kind = recordType;
+ if ('__typename' in data) {
+ if (data.__typename === 'GraphqlSoupCrmCompany') kind = 'company';
+ if (data.__typename === 'GraphqlSoupCrmContact') kind = 'contact';
+ }
+ if ('type' in data) {
+ if (data.type === 'crm_company' || data.type === 'company')
+ kind = 'company';
+ if (data.type === 'crm_contact') kind = 'contact';
+ }
+ const parent =
+ 'contactCompanyId' in data
+ ? data.contactCompanyId
+ : 'companyId' in data
+ ? data.companyId
+ : undefined;
+ const affected =
+ kind &&
+ 'id' in data &&
+ ((change.kind === kind && data.id === change.id) ||
+ (change.kind === 'company' &&
+ kind === 'contact' &&
+ parent === change.id));
+ const childKind =
+ 'tag' in data && data.tag === 'crmCompany'
+ ? 'company'
+ : 'tag' in data && data.tag === 'crmContact'
+ ? 'contact'
+ : undefined;
+ return Object.fromEntries(
+ Object.entries(data).map(([key, value]) => [
+ key,
+ affected && key === 'hidden'
+ ? change.hidden
+ : patchVisibilitySnapshot(
+ value,
+ change,
+ key === 'data' ? childKind : undefined
+ ),
+ ])
+ );
+}
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.tsx
index 38f002bfdb..90cc4ba556 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
@@ -9,6 +9,12 @@ const { openCreateContact } = vi.hoisted(() => ({
openCreateContact: vi.fn(),
}));
+vi.mock('../components/record-visibility-filter', () => ({
+ RecordVisibilityFilter: () => null,
+}));
+vi.mock('../components/record-archived-status', () => ({
+ ArchivedRecordBadge: () => null,
+}));
vi.mock('@entity', () => ({
ListEntity: (props: {
entity: { name: string };
@@ -59,6 +65,8 @@ vi.mock('@app/components/view-shell', () => ({
}));
vi.mock('../context/crm-context', () => ({
useCrmContext: () => ({
+ userId: () => 'user-1',
+ isTeamAdmin: () => () => true,
openCreateContact,
createNavigation: () => ({ openWithSplit: vi.fn() }),
createContactPhoto: (email: string) => () =>
diff --git a/apps/web/src/features/crm/views/company-contacts-section.tsx b/apps/web/src/features/crm/views/company-contacts-section.tsx
index e705b07f23..17916ab24e 100644
--- a/apps/web/src/features/crm/views/company-contacts-section.tsx
+++ b/apps/web/src/features/crm/views/company-contacts-section.tsx
@@ -6,20 +6,31 @@ import {
ListLayoutProvider,
} from '@entity';
import { Avatar } from '@ui';
-import { createMemo, createSignal, For, Show } from 'solid-js';
+import {
+ createMemo,
+ createRenderEffect,
+ createSignal,
+ For,
+ on,
+ Show,
+} from 'solid-js';
import {
CrmListEmpty,
CrmListSearchEmpty,
CrmListSkeleton,
} from '../components/list-state';
+import { ArchivedRecordBadge } from '../components/record-archived-status';
import { RecordSection } from '../components/record-section';
+import { RecordVisibilityFilter } from '../components/record-visibility-filter';
import { useCrmContext } from '../context/crm-context';
import type { CrmContact } from '../core/contact';
+import { useIsTeamAdmin } from './use-crm';
function ContactRow(props: {
contact: CrmContact;
onOpen: (event: MouseEvent) => void;
ownerId: string;
+ archived: boolean;
}) {
const email = props.contact.email;
const photo = email ? useCrmContext().createContactPhoto?.(email) : undefined;
@@ -27,6 +38,7 @@ function ContactRow(props: {
const entity = (): CrmContactEntity => ({
...props.contact,
type: 'crm_contact',
+ hidden: props.archived,
name: name(),
ownerId: props.ownerId,
sortTs: props.contact.lastInteraction,
@@ -53,11 +65,16 @@ function ContactRow(props: {
</Avatar>
}
titleTrailing={
- <Show when={props.contact.name && props.contact.email}>
- <span class="min-w-0 truncate font-normal text-ink-extra-muted">
- {props.contact.email}
- </span>
- </Show>
+ <>
+ <Show when={props.archived}>
+ <ArchivedRecordBadge />
+ </Show>
+ <Show when={props.contact.name && props.contact.email}>
+ <span class="min-w-0 truncate font-normal text-ink-extra-muted">
+ {props.contact.email}
+ </span>
+ </Show>
+ </>
}
/>
);
@@ -70,26 +87,51 @@ export function CompanyContactsSection(props: {
}) {
const context = useCrmContext();
const { openWithSplit } = context.createNavigation();
+ const isAdmin = useIsTeamAdmin();
+ const [archivedCompany, setArchivedCompany] = createSignal<string>();
+ const archived = () =>
+ isAdmin() && !!props.company && archivedCompany() === props.company?.id;
+ createRenderEffect(
+ on(
+ [
+ context.userId,
+ isAdmin,
+ () => props.company?.teamId,
+ () => props.company?.id,
+ ],
+ () => setArchivedCompany(undefined),
+ { defer: true }
+ )
+ );
const [search, setSearch] = createSignal('');
const [listRef, setListRef] = createSignal<HTMLElement>();
const filtered = createMemo(() => {
const query = search().trim().toLowerCase();
return (props.contacts ?? []).filter(
(contact) =>
- !contact.hidden &&
+ (contact.hidden || !!props.company?.hidden) === archived() &&
(!query ||
contact.name?.toLowerCase().includes(query) ||
contact.email?.toLowerCase().includes(query))
);
});
const createContact = () => {
- if (props.company)
+ if (props.company && !props.company.hidden)
context.openCreateContact({ companyId: props.company.id });
};
return (
<RecordSection
title="Team"
+ actions={
+ <RecordVisibilityFilter
+ archived={archived()}
+ onChange={(value) =>
+ setArchivedCompany(value ? props.company?.id : undefined)
+ }
+ disabled={!isAdmin()}
+ />
+ }
search={search()}
onSearchChange={setSearch}
searchPlaceholder="Search contacts…"
@@ -97,7 +139,7 @@ export function CompanyContactsSection(props: {
createAction={{
label: 'Add contact',
onClick: createContact,
- disabled: !props.company,
+ disabled: !props.company || props.company.hidden,
}}
toolbarCreate
>
@@ -112,10 +154,14 @@ export function CompanyContactsSection(props: {
when={search().trim()}
fallback={
<CrmListEmpty
- title="No contacts yet"
- description="Add a contact to this company to see them here."
+ title={archived() ? 'No archived people' : 'No contacts yet'}
+ description={
+ archived() || props.company?.hidden
+ ? undefined
+ : 'Add a contact to this company to see them here.'
+ }
action={
- props.company
+ props.company && !props.company.hidden && !archived()
? { label: 'Add contact', onClick: createContact }
: undefined
}
@@ -136,6 +182,7 @@ export function CompanyContactsSection(props: {
{(contact) => (
<ContactRow
contact={contact}
+ archived={archived()}
ownerId={props.company?.ownerId ?? ''}
onOpen={(event) => {
if (props.onOpenContact && !event.shiftKey) {
diff --git a/apps/web/src/features/crm/views/company-detail.tsx b/apps/web/src/features/crm/views/company-detail.tsx
index b489daf3c0..c36d6ee65e 100644
--- a/apps/web/src/features/crm/views/company-detail.tsx
+++ b/apps/web/src/features/crm/views/company-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 { CrmContact as CompanyContact } from '../core/contact';
import {
@@ -24,11 +23,8 @@ import {
RecordFilesSection,
RecordReferencesSection,
} from './record-associations';
-import {
- useCompanyQuery,
- useIsTeamAdmin,
- useSetCompanyHiddenMutation,
-} from './use-crm';
+import { RecordDetailsSection } from './record-details-section';
+import { useCompanyQuery } from './use-crm';
/**
* Root of the company detail view, laid out like a project: the host's top
@@ -72,8 +68,6 @@ function CompanyContent(props: CompanyProps) {
const pipelinesEnabled = context.pipelinesEnabled();
const { company, contacts, query } = useCompanyQuery(() => props.companyId);
usePending('crm.record', () => query.isLoading);
- const isTeamAdmin = useIsTeamAdmin();
- const hiddenMutation = useSetCompanyHiddenMutation();
const section = () => props.section ?? 'overview';
const scope = createMemo(
(): CrmRecordScope | undefined => {
@@ -101,37 +95,6 @@ function CompanyContent(props: CompanyProps) {
<Match when={section() === 'overview'}>
<RecordOverview>
<CompanyHeader company={company()} />
- <Show when={company()}>
- {(current) => (
- <RecordVisibilityAction
- recordId={current().id}
- kind="company"
- name={current().name}
- hidden={current().hidden}
- canManage={isTeamAdmin()}
- pending={hiddenMutation.isPending}
- onChange={(hidden, onSuccess) =>
- hiddenMutation.mutate(
- { companyId: current().id, hidden },
- {
- onSuccess: () => {
- onSuccess();
- context.feedback.success(
- hidden
- ? 'Company removed from CRM'
- : 'Company restored to CRM'
- );
- },
- onError: () =>
- context.feedback.failure(
- 'Could not update company visibility'
- ),
- }
- )
- }
- />
- )}
- </Show>
<Show when={pipelinesEnabled()}>
<context.PipelineEntries
record={{ type: 'company', id: props.companyId }}
@@ -174,10 +137,11 @@ function CompanyContent(props: CompanyProps) {
</div>
</div>
+ <RecordDetailsSection company={company()} />
<SidePanel.Section
id="company-properties"
title="Properties"
- order={15}
+ order={30}
defaultOpen
render={(renderSection) => (
<CompanyPropertiesSection
@@ -191,10 +155,10 @@ function CompanyContent(props: CompanyProps) {
<CompanyListsSection companyId={props.companyId} />
</Suspense>
</Show>
- <SidePanel.Section id="company-sharing" title="Sharing" order={25}>
+ <SidePanel.Section id="company-sharing" title="Email sharing" order={50}>
<CompanySharingSection company={company()} />
</SidePanel.Section>
- <SidePanel.Section id="company-references" title="References" order={30}>
+ <SidePanel.Section id="company-references" title="References" order={20}>
<RecordReferencesSection scope={scope()} />
</SidePanel.Section>
</SidePanel.Layout>
diff --git a/apps/web/src/features/crm/views/company-grid-layout.tsx b/apps/web/src/features/crm/views/company-grid-layout.tsx
index 5c0797e4cc..5921ca6295 100644
--- a/apps/web/src/features/crm/views/company-grid-layout.tsx
+++ b/apps/web/src/features/crm/views/company-grid-layout.tsx
@@ -25,6 +25,7 @@ import {
companyGridTemplateAreas,
companyGridTemplateColumns,
} from '../components/company-grid-template';
+import { ArchivedRecordBadge } from '../components/record-archived-status';
import {
useBulkSaveEntityPropertiesMutation,
useCrmDisplayOptions,
@@ -185,6 +186,9 @@ export function CompanyGridLayout(props: LayoutProps) {
<span class="truncate min-w-0">
<Entity.Title entity={props.entity} />
</span>
+ <Show when={isCrmCompanyEntity(props.entity) && props.entity.hidden}>
+ <ArchivedRecordBadge />
+ </Show>
<Show when={primaryDomain()}>
{(domain) => (
<span class="truncate shrink-[2] min-w-0 text-xs font-normal text-ink-extra-muted">
diff --git a/apps/web/src/features/crm/views/company-header.tsx b/apps/web/src/features/crm/views/company-header.tsx
index c81eb654b2..1154a932a9 100644
--- a/apps/web/src/features/crm/views/company-header.tsx
+++ b/apps/web/src/features/crm/views/company-header.tsx
@@ -11,6 +11,7 @@ import GlobeIcon from '@icon/system/regular/globe.svg';
import { createResizeObserver } from '@solid-primitives/resize-observer';
import { Badge, Tooltip } from '@ui';
import { createEffect, createSignal, For, onMount, Show } from 'solid-js';
+import { CompanyVisibilityButton } from './company-visibility-button';
import { useSetCompanyNameMutation } from './use-crm';
function Description(props: { text: string }) {
@@ -78,11 +79,11 @@ function TitleEditor(props: { company: CrmCompanyEntity }) {
export function CompanyHeader(props: { company?: CrmCompanyEntity }) {
return (
<div>
- <div class="flex items-center gap-3">
+ <div class="flex flex-wrap items-center gap-x-3 gap-y-1">
<div class="size-8 shrink-0">
<EntityIcon targetType="crm_company" size="fill" />
</div>
- <h1 class="min-w-0 flex-1 text-2xl font-semibold">
+ <h1 class="min-w-0 max-w-full mobile:flex-1 text-2xl font-semibold">
<Show
when={props.company}
fallback={<ListSkeleton.Bar class="h-6 w-48" />}
@@ -90,6 +91,11 @@ export function CompanyHeader(props: { company?: CrmCompanyEntity }) {
{(company) => <TitleEditor company={company()} />}
</Show>
</h1>
+ <Show when={props.company}>
+ {(company) => (
+ <CompanyVisibilityButton identity companyId={company().id} />
+ )}
+ </Show>
</div>
<Show when={props.company}>
{(company) => (
diff --git a/apps/web/src/features/crm/views/company-list-membership.tsx b/apps/web/src/features/crm/views/company-list-membership.tsx
index a7c0515c96..b9b5ad9ab9 100644
--- a/apps/web/src/features/crm/views/company-list-membership.tsx
+++ b/apps/web/src/features/crm/views/company-list-membership.tsx
@@ -36,7 +36,7 @@ export function CompanyListsSection(props: { companyId: string }) {
}
}
return (
- <SidePanel.Section id="company-lists" title="Lists" order={18} defaultOpen>
+ <SidePanel.Section id="company-lists" title="Lists" order={40} defaultOpen>
<div class="flex flex-col gap-3">
<Show when={team.isError || lists.query.isError}>
<div
diff --git a/apps/web/src/features/crm/views/company-visibility-button.tsx b/apps/web/src/features/crm/views/company-visibility-button.tsx
new file mode 100644
index 0000000000..1383034ec4
--- /dev/null
+++ b/apps/web/src/features/crm/views/company-visibility-button.tsx
@@ -0,0 +1,59 @@
+import { Show } from 'solid-js';
+import { RecordArchivedStatus } from '../components/record-archived-status';
+import { RecordVisibilityAction } from '../components/record-visibility-action';
+import { useCrmContext } from '../context/crm-context';
+import {
+ useCompanyQuery,
+ useIsTeamAdmin,
+ useSetCompanyHiddenMutation,
+} from './use-crm';
+
+export function CompanyVisibilityButton(props: {
+ companyId: string;
+ grouped?: boolean;
+ identity?: boolean;
+}) {
+ const context = useCrmContext();
+ const { company } = useCompanyQuery(() => props.companyId);
+ const isAdmin = useIsTeamAdmin();
+ const mutation = useSetCompanyHiddenMutation();
+ const action = () => (
+ <Show when={company()}>
+ {(current) => (
+ <RecordVisibilityAction
+ recordId={current().id}
+ kind="company"
+ name={current().name}
+ hidden={current().hidden}
+ grouped={props.grouped}
+ canManage={isAdmin()}
+ pending={mutation.isPending}
+ onChange={(hidden, success, failure) =>
+ mutation.mutate(
+ { companyId: current().id, hidden },
+ {
+ onSuccess: () => {
+ success();
+ context.feedback.success(
+ hidden ? 'Company archived' : 'Company restored'
+ );
+ },
+ onError: () => {
+ failure();
+ context.feedback.failure('Could not update company');
+ },
+ }
+ )
+ }
+ />
+ )}
+ </Show>
+ );
+ return (
+ <Show when={company() && !!company()?.hidden === !!props.identity}>
+ <Show when={props.identity} fallback={action()}>
+ <RecordArchivedStatus kind="company">{action()}</RecordArchivedStatus>
+ </Show>
+ </Show>
+ );
+}
diff --git a/apps/web/src/features/crm/views/contact-detail.tsx b/apps/web/src/features/crm/views/contact-detail.tsx
index 8f378b86db..cfad9e3e03 100644
--- a/apps/web/src/features/crm/views/contact-detail.tsx
+++ b/apps/web/src/features/crm/views/contact-detail.tsx
@@ -18,6 +18,7 @@ import {
RecordFilesSection,
RecordReferencesSection,
} from './record-associations';
+import { RecordDetailsSection } from './record-details-section';
import { useContactQuery } from './use-crm';
/**
@@ -128,7 +129,11 @@ function ContactContent(props: ContactProps) {
</div>
</div>
- <SidePanel.Section id="contact-references" title="References" order={30}>
+ <RecordDetailsSection
+ contact={contact()}
+ onOpenCompany={props.onOpenCompany}
+ />
+ <SidePanel.Section id="contact-references" title="References" order={20}>
<RecordReferencesSection scope={scope()} />
</SidePanel.Section>
</SidePanel.Layout>
diff --git a/apps/web/src/features/crm/views/contact-header.tsx b/apps/web/src/features/crm/views/contact-header.tsx
index 9e80ac6c93..b623887023 100644
--- a/apps/web/src/features/crm/views/contact-header.tsx
+++ b/apps/web/src/features/crm/views/contact-header.tsx
@@ -9,6 +9,7 @@ import { Avatar, Badge, badgeTriggerClasses, Tooltip } from '@ui';
import { Show } from 'solid-js';
import { useCrmContext } from '../context/crm-context';
import type { CrmContact as CrmContactResponse } from '../core/contact';
+import { ContactVisibilityButton } from './contact-visibility-button';
import { useCompanyQuery, useSetContactNameMutation } from './use-crm';
// Renames overwrite `crm_contacts.name`, which is already team-scoped —
@@ -79,7 +80,7 @@ export function ContactHeader(props: {
return (
<div>
- <div class="flex items-center gap-3">
+ <div class="flex flex-wrap items-center gap-x-3 gap-y-1">
<Avatar size="lg" class="shrink-0">
<Show
when={initials()}
@@ -95,7 +96,7 @@ export function ContactHeader(props: {
)}
</Show>
</Avatar>
- <h1 class="min-w-0 flex-1 text-2xl font-semibold">
+ <h1 class="min-w-0 max-w-full mobile:flex-1 text-2xl font-semibold">
<Show
when={props.contact}
fallback={<ListSkeleton.Bar class="h-6 w-48" />}
@@ -103,6 +104,15 @@ export function ContactHeader(props: {
{(contact) => <TitleEditor contact={contact()} />}
</Show>
</h1>
+ <Show when={props.contact}>
+ {(contact) => (
+ <ContactVisibilityButton
+ identity
+ contactId={contact().id}
+ onOpenCompany={props.onOpenCompany}
+ />
+ )}
+ </Show>
</div>
<Show when={props.contact}>
{(contact) => (
diff --git a/apps/web/src/features/crm/views/contact-row.tsx b/apps/web/src/features/crm/views/contact-row.tsx
index 9328584711..0b54b2b8cb 100644
--- a/apps/web/src/features/crm/views/contact-row.tsx
+++ b/apps/web/src/features/crm/views/contact-row.tsx
@@ -12,6 +12,7 @@ import BuildingsIcon from '@icon/system/regular/buildings.svg';
import { cn } from '@ui/utils/classname';
import { Show } from 'solid-js';
import { contactGridTemplate } from '../components/contact-grid-template';
+import { ArchivedRecordBadge } from '../components/record-archived-status';
import { CrmListRow } from './record-row';
/** People row: name and email, company, and last interaction. */
@@ -52,6 +53,9 @@ function ContactGridLayout(props: LayoutProps) {
<span class="truncate min-w-0">
<Entity.Title entity={props.entity} />
</span>
+ <Show when={'hidden' in props.entity && props.entity.hidden}>
+ <ArchivedRecordBadge />
+ </Show>
<Show when={contact()?.email !== contact()?.name && contact()?.email}>
{(email) => (
<span class="truncate shrink-[2] min-w-0 text-xs font-normal text-ink-extra-muted">
diff --git a/apps/web/src/features/crm/views/contact-visibility-button.tsx b/apps/web/src/features/crm/views/contact-visibility-button.tsx
index c23d600a62..2c4244fb0d 100644
--- a/apps/web/src/features/crm/views/contact-visibility-button.tsx
+++ b/apps/web/src/features/crm/views/contact-visibility-button.tsx
@@ -1,7 +1,10 @@
+import { Button } from '@ui';
import { Show } from 'solid-js';
+import { RecordArchivedStatus } from '../components/record-archived-status';
import { RecordVisibilityAction } from '../components/record-visibility-action';
import { useCrmContext } from '../context/crm-context';
import {
+ useCompanyQuery,
useContactQuery,
useIsTeamAdmin,
useSetContactHiddenMutation,
@@ -10,40 +13,57 @@ import {
export function ContactVisibilityButton(props: {
contactId: string;
grouped?: boolean;
+ identity?: boolean;
+ onOpenCompany?: (companyId: string) => boolean;
}) {
const context = useCrmContext();
const contactQuery = useContactQuery(() => props.contactId);
+ const parent = useCompanyQuery(() =>
+ contactQuery.isSuccess ? (contactQuery.data?.companyId ?? '') : ''
+ );
+ const hidden = () =>
+ !!contactQuery.data?.hidden || !!parent.company()?.hidden;
+ const navigation = context.createNavigation();
+ const openCompany = () => {
+ const id = contactQuery.data?.companyId;
+ if (!id || props.onOpenCompany?.(id)) return;
+ navigation.openWithSplit({ type: 'company', id }, { activate: true });
+ };
const isTeamAdmin = useIsTeamAdmin();
const hiddenMutation = useSetContactHiddenMutation();
- return (
- <Show when={contactQuery.data}>
+ const action = () => (
+ <Show when={contactQuery.isSuccess ? contactQuery.data : undefined}>
{(current) => (
<RecordVisibilityAction
- iconOnly
grouped={props.grouped}
recordId={current().id}
kind="contact"
name={current().name ?? current().email ?? 'Contact'}
- hidden={current().hidden}
+ hidden={hidden()}
+ parentArchived={parent.company()?.hidden}
+ parentPending={
+ hidden() &&
+ !!current().companyId &&
+ (parent.query.isLoading || parent.query.isError)
+ }
+ onOpenParent={openCompany}
canManage={isTeamAdmin()}
pending={hiddenMutation.isPending}
- onChange={(hidden, onSuccess) =>
+ onChange={(hidden, onSuccess, onError) =>
hiddenMutation.mutate(
{ contactId: current().id, hidden },
{
onSuccess: () => {
onSuccess();
context.feedback.success(
- hidden
- ? 'Person removed from CRM'
- : 'Person restored to CRM'
+ hidden ? 'Person archived' : 'Person restored'
);
},
- onError: () =>
- context.feedback.failure(
- 'Could not update contact visibility'
- ),
+ onError: () => {
+ onError();
+ context.feedback.failure('Could not update person');
+ },
}
)
}
@@ -51,4 +71,25 @@ export function ContactVisibilityButton(props: {
)}
</Show>
);
+ return (
+ <Show when={contactQuery.isSuccess && hidden() === !!props.identity}>
+ <Show when={props.identity} fallback={action()}>
+ <RecordArchivedStatus
+ kind="contact"
+ parentArchived={parent.company()?.hidden}
+ >
+ {action()}
+ <Show when={parent.query.isError}>
+ <Button
+ variant="link"
+ size="sm"
+ onClick={() => parent.query.refetch()}
+ >
+ Retry company check
+ </Button>
+ </Show>
+ </RecordArchivedStatus>
+ </Show>
+ </Show>
+ );
}
diff --git a/apps/web/src/features/crm/views/crm-workspace.tsx b/apps/web/src/features/crm/views/crm-workspace.tsx
index a6a2df8a59..a564d7684a 100644
--- a/apps/web/src/features/crm/views/crm-workspace.tsx
+++ b/apps/web/src/features/crm/views/crm-workspace.tsx
@@ -21,7 +21,6 @@ import { SoupViewContextSort } from '@app/features/next-soup/soup-view/filters-b
import { 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';
@@ -58,10 +57,7 @@ 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 { PeopleDisplayMenu } from '../components/people-display-menu';
import { PipelineDialog } from '../components/pipeline-dialog';
import { PipelineSidebar } from '../components/pipeline-sidebar';
import { useCrmContext } from '../context/crm-context';
@@ -414,9 +410,6 @@ 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()
@@ -760,14 +753,16 @@ export function CrmWorkspaceView(props: {
<Show
when={!isTouchDevice()}
fallback={
- <Show when={peopleActive()}>
- <ViewShell.Header class="touch:pt-0">
- <div class="flex min-w-0 items-center justify-between gap-3">
+ <ViewShell.Header class="touch:pt-0">
+ <div class="flex min-w-0 items-center justify-between gap-3">
+ <Show when={peopleActive()}>
<PeopleSearchBar
value={peopleSearch()}
onValueChange={searchPeople}
/>
- <PeopleDisplayMenu visibility={view.peopleVisibility} />
+ </Show>
+ <PeopleDisplayMenu visibility={view.peopleVisibility} />
+ <Show when={peopleActive()}>
<Button
variant="secondary"
class="ml-auto shrink-0"
@@ -776,9 +771,9 @@ export function CrmWorkspaceView(props: {
<PlusIcon class="size-4" />
New contact
</Button>
- </div>
- </ViewShell.Header>
- </Show>
+ </Show>
+ </div>
+ </ViewShell.Header>
}
>
<ListHeader
@@ -814,9 +809,7 @@ export function CrmWorkspaceView(props: {
</Show>
</HeaderActionGroup>
</Show>
- <Show when={peopleActive()}>
- <PeopleDisplayMenu visibility={view.peopleVisibility} />
- </Show>
+ <PeopleDisplayMenu visibility={view.peopleVisibility} />
{toolbarCreateMenu()}
<CrmHeaderSearch
label={peopleActive() ? 'Search people' : 'Search companies'}
@@ -834,11 +827,6 @@ 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.tsx
index 6d3393ff6c..6e10648ac2 100644
--- a/apps/web/src/features/crm/views/empty-state.tsx
+++ b/apps/web/src/features/crm/views/empty-state.tsx
@@ -85,7 +85,7 @@ export function CrmEmptyState(
<CrmListSearchEmpty
title={
peopleVisibility.showRemoved()
- ? 'No matching removed people'
+ ? 'No matching archived people'
: 'No matching people'
}
description="Try a different name or email address."
@@ -94,12 +94,11 @@ export function CrmEmptyState(
</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),
- }}
+ title={
+ activeTab() === 'people'
+ ? 'No archived people'
+ : 'No archived companies'
+ }
/>
</Match>
<Match when={activeTab() === 'people' && props.filtered}>
diff --git a/apps/web/src/features/crm/views/record-detail.test.tsx b/apps/web/src/features/crm/views/record-detail.test.tsx
index 6194ef42c9..f347cf3322 100644
--- a/apps/web/src/features/crm/views/record-detail.test.tsx
+++ b/apps/web/src/features/crm/views/record-detail.test.tsx
@@ -34,6 +34,7 @@ const taskContext = vi.hoisted(() => ({
}));
vi.mock('../context/crm-context', () => ({
useCrmContext: () => ({
+ createNavigation: () => ({ openWithSplit: vi.fn() }),
listsEnabled: () => () => false,
pipelinesEnabled: () => () => false,
isTeamAdmin: () => () => false,
@@ -64,6 +65,10 @@ vi.mock('@components/app/side-panel', () => ({
},
}));
vi.mock('@core/component/EntityIcon', () => ({ EntityIcon: () => null }));
+vi.mock('./record-header-actions', () => ({ RecordHeaderActions: () => null }));
+vi.mock('./record-details-section', () => ({
+ RecordDetailsSection: () => null,
+}));
vi.mock('./copy-link-button', () => ({ CrmCopyLinkButton: () => null }));
vi.mock('../components/record-tabs', () => ({
RecordTabs: (props: { onChange(section: CrmRecordSection): void }) => (
diff --git a/apps/web/src/features/crm/views/record-detail.tsx b/apps/web/src/features/crm/views/record-detail.tsx
index ac142e27cd..c6e6be9857 100644
--- a/apps/web/src/features/crm/views/record-detail.tsx
+++ b/apps/web/src/features/crm/views/record-detail.tsx
@@ -1,5 +1,4 @@
import { ViewBreadcrumbs } from '@app/components/view-shell';
-import { HeaderActionGroup } from '@components/app/HeaderActionGroup';
import { SidePanel } from '@components/app/side-panel';
import { EntityIcon } from '@core/component/EntityIcon';
import {
@@ -38,8 +37,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 { RecordHeaderActions } from './record-header-actions';
import { useCompanyQuery, useContactQuery } from './use-crm';
const recordKey = (record: CrmRecordRef) => `${record.type}:${record.id}`;
@@ -204,25 +202,7 @@ export function CrmRecordDetail(props: {
/>
</Show>
</div>
- <div class="ml-auto flex shrink-0 items-center gap-2 touch:gap-1">
- <HeaderActionGroup
- label={
- current().type === 'contact' ? 'Contact actions' : 'Sharing'
- }
- >
- <CrmCopyLinkButton
- grouped
- type={current().type}
- id={current().id}
- />
- <Show when={current().type === 'contact' && current().id} keyed>
- {(contactId) => (
- <ContactVisibilityButton grouped contactId={contactId} />
- )}
- </Show>
- </HeaderActionGroup>
- <SidePanel.Toggle />
- </div>
+ <RecordHeaderActions record={current()} />
</div>
<div class="relative min-h-0 min-w-0 flex-1 touch:[--mobile-content-inset-top:0px]">
<Show when={current()} keyed>
diff --git a/apps/web/src/features/crm/views/record-details-section.tsx b/apps/web/src/features/crm/views/record-details-section.tsx
new file mode 100644
index 0000000000..eae59f4082
--- /dev/null
+++ b/apps/web/src/features/crm/views/record-details-section.tsx
@@ -0,0 +1,80 @@
+import { SidePanel } from '@components/app/side-panel';
+import { EntityMetadataRow } from '@components/app/side-panel/EntityMetadata';
+import { Button } from '@ui';
+import { For, Show } from 'solid-js';
+import { useCrmContext } from '../context/crm-context';
+import type { CrmCompany } from '../core/company';
+import type { CrmContact } from '../core/contact';
+import { useCompanyQuery } from './use-crm';
+
+function ContactCompany(props: {
+ id: string;
+ onOpen?: (id: string) => boolean;
+}) {
+ const { company } = useCompanyQuery(() => props.id);
+ const navigation = useCrmContext().createNavigation();
+ return (
+ <EntityMetadataRow label="Company">
+ <Button
+ variant="link"
+ size="sm"
+ onClick={() => {
+ if (!props.onOpen?.(props.id))
+ navigation.openWithSplit(
+ { type: 'company', id: props.id },
+ { activate: true }
+ );
+ }}
+ >
+ {company()?.name ?? 'Open company'}
+ </Button>
+ </EntityMetadataRow>
+ );
+}
+
+/** Both records begin with factual details and References in the same order. */
+export function RecordDetailsSection(props: {
+ company?: CrmCompany;
+ contact?: CrmContact;
+ onOpenCompany?: (id: string) => boolean;
+}) {
+ return (
+ <SidePanel.Section
+ id="crm-record-details"
+ title="Record details"
+ order={10}
+ defaultOpen
+ >
+ <div class="flex min-w-0 flex-col gap-2">
+ <EntityMetadataRow label="Name">
+ {props.company?.name ?? props.contact?.name ?? '—'}
+ </EntityMetadataRow>
+ <Show when={props.company}>
+ {(company) => (
+ <EntityMetadataRow label="Website">
+ <For each={company().domains}>
+ {(domain) => <div>{domain.domain}</div>}
+ </For>
+ </EntityMetadataRow>
+ )}
+ </Show>
+ <Show when={props.contact}>
+ {(contact) => (
+ <>
+ <Show when={contact().email}>
+ {(email) => (
+ <EntityMetadataRow label="Email">{email()}</EntityMetadataRow>
+ )}
+ </Show>
+ <Show when={contact().companyId}>
+ {(id) => (
+ <ContactCompany id={id()} onOpen={props.onOpenCompany} />
+ )}
+ </Show>
+ </>
+ )}
+ </Show>
+ </div>
+ </SidePanel.Section>
+ );
+}
diff --git a/apps/web/src/features/crm/views/record-header-actions.tsx b/apps/web/src/features/crm/views/record-header-actions.tsx
new file mode 100644
index 0000000000..0c71257fb8
--- /dev/null
+++ b/apps/web/src/features/crm/views/record-header-actions.tsx
@@ -0,0 +1,34 @@
+import { HeaderActionGroup } from '@components/app/HeaderActionGroup';
+import { SidePanel } from '@components/app/side-panel';
+import { Show } from 'solid-js';
+import type { CrmRecordRef } from '../core/record';
+import { CompanyVisibilityButton } from './company-visibility-button';
+import { ContactVisibilityButton } from './contact-visibility-button';
+import { CrmCopyLinkButton } from './copy-link-button';
+
+export function RecordHeaderActions(props: { record: CrmRecordRef }) {
+ return (
+ <div class="ml-auto flex shrink-0 items-center gap-2 touch:gap-1">
+ <HeaderActionGroup
+ label={
+ props.record.type === 'contact'
+ ? 'Contact actions'
+ : 'Company actions'
+ }
+ >
+ <CrmCopyLinkButton
+ grouped
+ type={props.record.type}
+ id={props.record.id}
+ />
+ <Show when={props.record.type === 'company' && props.record.id} keyed>
+ {(id) => <CompanyVisibilityButton grouped companyId={id} />}
+ </Show>
+ <Show when={props.record.type === 'contact' && props.record.id} keyed>
+ {(id) => <ContactVisibilityButton grouped contactId={id} />}
+ </Show>
+ </HeaderActionGroup>
+ <SidePanel.Toggle />
+ </div>
+ );
+}
diff --git a/apps/web/src/features/crm/views/record-row.tsx b/apps/web/src/features/crm/views/record-row.tsx
index 51ebd63170..dbde206640 100644
--- a/apps/web/src/features/crm/views/record-row.tsx
+++ b/apps/web/src/features/crm/views/record-row.tsx
@@ -1,3 +1,4 @@
+import { ArchivedRecordBadge } from '../components/record-archived-status';
import '@entity/composed/ListEntity.css';
import {
SwipableRow,
@@ -69,6 +70,13 @@ export function CrmListRow(
streamState: undefined,
setSnippetContainerRef: () => {},
chars: 0,
+ get titleTrailing() {
+ return (
+ <Show when={'hidden' in props.entity && props.entity.hidden}>
+ <ArchivedRecordBadge />
+ </Show>
+ );
+ },
onProjectClick: props.onProjectClick,
});
diff --git a/apps/web/src/features/crm/views/saved-views-menu.tsx b/apps/web/src/features/crm/views/saved-views-menu.tsx
index 74cd983b18..8af2d7d5eb 100644
--- a/apps/web/src/features/crm/views/saved-views-menu.tsx
+++ b/apps/web/src/features/crm/views/saved-views-menu.tsx
@@ -1,4 +1,3 @@
-import { useApplyPreset } from '@app/features/next-soup/soup-view/soup-view-tabs';
import { toast } from '@core/component/Toast/Toast';
import FloppyDiskIcon from '@icon/system/regular/floppy-disk.svg';
import LinkIcon from '@icon/system/regular/link.svg';
@@ -20,7 +19,6 @@ import { useApplyCrmView } from './apply-view';
import {
useCrmDisplayOptions,
useCrmPermissions,
- useIsTeamAdmin,
usePersonalCrmViews,
useTeamCrmViews,
useCrmUserId as useUserId,
@@ -328,16 +326,10 @@ export function CompanyViewsMenu(
/**
* Personal display options for the Customers view: which property columns
* show in the list. Device-level (preference-backed) — deliberately not
- * captured by saved views. Admins/owners additionally get a toggle to view
- * the hidden-companies set (backed by the active/hidden tab presets).
+ * captured by saved views. Archive visibility is a separate scoped filter.
*/
export function CompanyDisplayMenu(props: { grouped?: boolean } = {}) {
const { options, toggleListColumn } = useCrmDisplayOptions();
- const { activeTab } = useCrmWorkspace();
- const { applyTabPreset } = useApplyPreset();
- const isTeamAdmin = useIsTeamAdmin();
-
- const showingHidden = () => activeTab() === 'hidden';
return (
<Dropdown>
@@ -370,24 +362,6 @@ export function CompanyDisplayMenu(props: { grouped?: boolean } = {}) {
)}
</For>
</Dropdown.Group>
- {/* Admin/owner only — the BE rejects hidden-set requests from
- non-admins, matching the old Hidden tab's gating. */}
- <Show when={isTeamAdmin()}>
- <Dropdown.Group>
- <Dropdown.CheckboxItem
- checked={showingHidden()}
- onChange={() =>
- applyTabPreset(
- 'companies',
- showingHidden() ? 'active' : 'hidden'
- )
- }
- closeOnSelect={false}
- >
- <span class="flex-1 truncate">Show hidden companies</span>
- </Dropdown.CheckboxItem>
- </Dropdown.Group>
- </Show>
</Dropdown.Content>
</Dropdown>
);
diff --git a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts
index f2cb278326..a30b059313 100644
--- a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts
+++ b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts
@@ -1222,6 +1222,17 @@ describe('Quick Access source integration', () => {
expect(list.items()[0].data).toMatchObject(restCompany);
});
+ it('excludes archived REST suggestions and includes restored companies', () => {
+ mocks.cacheEnabled = false;
+ mocks.companies = [{ ...restCompany, hidden: true }];
+ const archived = setup((source) => source.useList('crm_company'));
+ expect(archived.items()).toEqual([]);
+ dispose?.();
+ mocks.companies = [{ ...restCompany, hidden: false }];
+ const restored = setup((source) => source.useList('crm_company'));
+ expect(restored.items().map((item) => item.id)).toEqual(['company-1']);
+ });
+
it('preserves REST company mentions with GraphQL disabled', () => {
mocks.cacheEnabled = false;
mocks.companies = [restCompany];
diff --git a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx
index 227acf7661..13272ed5f7 100644
--- a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx
+++ b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx
@@ -656,6 +656,7 @@ export function createQuickAccessValue(): QuickAccessContextValue {
// updated_at for unviewed companies — same shape as channels.
const crmCompanyData = crmCompaniesAccessor();
for (const company of crmCompanyData) {
+ if (company.hidden) continue;
const viewedAt =
viewedAtMap.get(company.id) ?? company.viewedAt ?? undefined;
diff --git a/apps/web/src/lib/graphql-cache/exchange/external-writes.ts b/apps/web/src/lib/graphql-cache/exchange/external-writes.ts
new file mode 100644
index 0000000000..3b2f381591
--- /dev/null
+++ b/apps/web/src/lib/graphql-cache/exchange/external-writes.ts
@@ -0,0 +1,43 @@
+import type { CacheHost } from '../host/types';
+
+// REST mutations share the normalized cache, but do not pass through the
+// GraphQL mutation exchange. Fence their affected record types at that boundary.
+const WRITES = new WeakMap<CacheHost, Map<string, number>>();
+
+export function externalWriteVersion(host: CacheHost): number {
+ return Math.max(0, ...(WRITES.get(host)?.values() ?? []));
+}
+
+export function recordExternalWrite(
+ host: CacheHost,
+ types: readonly string[]
+): void {
+ const versions = WRITES.get(host) ?? new Map<string, number>();
+ const version = externalWriteVersion(host) + 1;
+ for (const type of types) versions.set(type, version);
+ WRITES.set(host, versions);
+}
+
+/** Fence declared dependencies too: an old empty list can omit a restored record. */
+export function predatesExternalWrite(
+ host: CacheHost,
+ version: unknown,
+ data: unknown,
+ types: readonly string[] = []
+): boolean {
+ if (typeof version !== 'number') return false;
+ const versions = WRITES.get(host);
+ if (!versions || externalWriteVersion(host) <= version) return false;
+ if (types.some((type) => (versions.get(type) ?? 0) > version)) return true;
+ const visit = (value: unknown): boolean => {
+ if (typeof value !== 'object' || value === null) return false;
+ if (
+ '__typename' in value &&
+ typeof value.__typename === 'string' &&
+ (versions.get(value.__typename) ?? 0) > version
+ )
+ return true;
+ return Object.values(value).some(visit);
+ };
+ return visit(data);
+}
diff --git a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts
index be94a63b6a..dbedc1c1c0 100644
--- a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts
+++ b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.test.ts
@@ -1,6 +1,7 @@
import {
SaveEmailDraftDocument,
SetEmailThreadArchivedDocument,
+ SoupDocument,
UpdateNotificationsDocument,
} from '@service-storage/graphql/generated/graphql';
import {
@@ -32,6 +33,7 @@ import {
subscribe,
} from 'wonka';
import { soupOptimisticResolvers } from '../../queries/optimistic-resolvers';
+import { resolveCrmExternalWriteTypes } from '../../queries/soup/graphql/external-write-scope';
import { createUrqlQuery } from '../../urql-solid/create-urql-query';
import { CacheNavigationError } from '../host/navigation-error';
import { createRetirableCacheHost } from '../host/retirable-host';
@@ -55,6 +57,7 @@ import {
type WriteResult,
} from '../protocol';
import { entityFromArgument } from './entity-resolvers';
+import { recordExternalWrite } from './external-writes';
import { liveQueryData } from './live-query';
import { NOOP_MUTATION_QUEUE_TELEMETRY } from './mutation-queue-telemetry';
import {
@@ -3058,6 +3061,109 @@ describe('normalizedCacheExchange', () => {
}
);
+ it.each([false, true])(
+ 'fences CRM responses dispatched before a confirmed REST write (hydration=%s)',
+ async (hydration) => {
+ const { ops, network, forwarded, results } =
+ controlledQueryHarness(host);
+ ops.next(hydration ? makeHydrationOp(1) : makeOp(1, 'network-only'));
+ await tick();
+ recordExternalWrite(host, ['GraphqlSoupCrmContact']);
+ network.next(
+ queryResult(forwarded[0], {
+ item: {
+ __typename: 'GraphqlSoupCrmContact',
+ id: 'contact-1',
+ hidden: false,
+ },
+ })
+ );
+ await tick();
+ expect(results).toEqual([]);
+ expect(host.writes).toEqual([]);
+ expect(forwarded).toHaveLength(2);
+ const fresh = {
+ item: {
+ __typename: 'GraphqlSoupCrmContact',
+ id: 'contact-1',
+ hidden: true,
+ },
+ };
+ network.next(queryResult(forwarded[1], fresh));
+ await tick();
+ expect(results.at(-1)?.data).toEqual(fresh);
+ }
+ );
+
+ it.each([false, true])(
+ 'fences empty and CRM-free pages with declared membership dependencies (hydration=%s)',
+ async (hydration) => {
+ const { ops, network, forwarded, results } =
+ controlledQueryHarness(host);
+ const operation = hydration
+ ? makeHydrationOp(1)
+ : makeOp(1, 'network-only');
+ ops.next(
+ makeOperation('query', operation, {
+ ...operation.context,
+ externalCacheWriteTypes: ['GraphqlSoupCrmContact'],
+ })
+ );
+ await tick();
+ recordExternalWrite(host, ['GraphqlSoupCrmContact']);
+ network.next(queryResult(forwarded[0], { items: [] }));
+ await tick();
+ expect(results).toEqual([]);
+ expect(host.writes).toEqual([]);
+ expect(forwarded).toHaveLength(2);
+ recordExternalWrite(host, ['GraphqlSoupCrmContact']);
+ network.next(
+ queryResult(forwarded[1], {
+ items: [{ __typename: 'GraphqlSoupDocument', id: 'document-1' }],
+ })
+ );
+ await tick();
+ expect(results).toEqual([]);
+ expect(host.writes).toEqual([]);
+ expect(forwarded).toHaveLength(3);
+ const restored = {
+ items: [
+ {
+ __typename: 'GraphqlSoupCrmContact',
+ id: 'contact-1',
+ hidden: false,
+ },
+ ],
+ };
+ network.next(queryResult(forwarded[2], restored));
+ await tick();
+ expect(results.at(-1)?.data).toEqual(restored);
+ }
+ );
+
+ it('keeps unrelated in-flight responses after a REST CRM write', async () => {
+ const { ops, network, forwarded, results } = controlledQueryHarness(host);
+ const operation = makeOp(1, 'network-only');
+ ops.next(
+ makeOperation('query', operation, {
+ ...operation.context,
+ externalCacheWriteTypes: [],
+ })
+ );
+ await tick();
+ recordExternalWrite(host, [
+ 'GraphqlSoupCrmCompany',
+ 'GraphqlSoupCrmContact',
+ ]);
+ const document = {
+ item: { __typename: 'GraphqlSoupDocument', id: 'document-1' },
+ };
+ network.next(queryResult(forwarded[0], document));
+ await tick();
+ expect(results.at(-1)?.data).toEqual(document);
+ expect(forwarded).toHaveLength(1);
+ });
+
it('honors cache-only if a subscriber changes policy before an obsolete response arrives', async () => {
const { ops, network, forwarded } = controlledQueryHarness(host);
ops.next(makeOp(1, 'network-only'));
@@ -5237,6 +5343,119 @@ describe('normalizedCacheExchange', () => {
});
});
+ it.each(['initial', 'continuation'] as const)(
+ 'fences a contextless %s fallback shared by a later CRM observer',
+ async (mode) => {
+ const variables = {
+ input:
+ mode === 'initial'
+ ? {
+ initial: {
+ filters: {
+ crmContactFilter: { literal: { hidden: false } },
+ },
+ },
+ }
+ : { continuation: { cursor: 'durable-opaque-page' } },
+ };
+ const commit = host.commitOptimisticWrite.bind(host);
+ host.commitOptimisticWrite = async (...args) => ({
+ ...(await commit(...args)),
+ revalidations: [
+ {
+ query: stringifyDocument(SoupDocument),
+ operationName: 'Soup',
+ variablesJson: JSON.stringify(variables),
+ },
+ ],
+ });
+ const requests: Array<ReturnType<typeof deferred<Response>>> = [];
+ const client = createClient({
+ url: 'http://test/graphql',
+ preferGetMethod: false,
+ exchanges: [
+ normalizedCacheExchange(host, {
+ externalWriteTypes: resolveCrmExternalWriteTypes,
+ }),
+ fetchExchange,
+ ],
+ fetch: vi.fn(async (_input, init) => {
+ const body =
+ typeof init?.body === 'string' ? JSON.parse(init.body) : {};
+ if (body.query?.includes('mutation'))
+ return new Response(JSON.stringify({ data: optimistic }), {
+ headers: { 'content-type': 'application/json' },
+ });
+ const response = deferred<Response>();
+ requests.push(response);
+ return response.promise;
+ }),
+ });
+ await executeOptimisticMutation(
+ client,
+ MUTATION,
+ { input: {} },
+ optimistic,
+ {
+ uuid: crypto.randomUUID(),
+ }
+ ).toPromise();
+ await vi.waitFor(() => expect(requests).toHaveLength(1));
+ const results: OperationResult[] = [];
+ const subscription = client
+ .query(SoupDocument, variables, {
+ requestPolicy: 'network-only',
+ externalCacheWriteTypes: ['GraphqlSoupCrmContact'],
+ })
+ .subscribe((result) => results.push(result));
+ try {
+ await tick();
+ expect(requests).toHaveLength(1);
+ recordExternalWrite(host, ['GraphqlSoupCrmContact']);
+ const old = {
+ user: { id: 'viewer', soup: { items: [], nextCursor: null } },
+ };
+ requests[0].resolve(
+ new Response(JSON.stringify({ data: old }), {
+ headers: { 'content-type': 'application/json' },
+ })
+ );
+ await vi.waitFor(() => expect(requests).toHaveLength(2));
+ expect(results).toEqual([]);
+ expect(
+ host.writes.some(
+ (write) => JSON.stringify(write.data) === JSON.stringify(old)
+ )
+ ).toBe(false);
+ const restored = {
+ user: {
+ id: 'viewer',
+ soup: {
+ items: [
+ {
+ __typename: 'GraphqlSoupCrmContact',
+ id: 'contact-1',
+ hidden: false,
+ },
+ ],
+ nextCursor: null,
+ },
+ },
+ };
+ requests[1].resolve(
+ new Response(JSON.stringify({ data: restored }), {
+ headers: { 'content-type': 'application/json' },
+ })
+ );
+ await vi.waitFor(() =>
+ expect(results.at(-1)?.data).toEqual(restored)
+ );
+ } finally {
+ subscription.unsubscribe();
+ }
+ }
+ );
+
it.each(['query', 'persistence'] as const)(
'bounds conditional link recovery while %s is stalled without retrying a committed mutation',
async (stage) => {
diff --git a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.ts b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.ts
index c2827d0625..9b617bc2d3 100644
--- a/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.ts
+++ b/apps/web/src/lib/graphql-cache/exchange/normalized-cache-exchange.ts
@@ -1,3 +1,4 @@
+import { externalWriteVersion, predatesExternalWrite } from './external-writes';
/**
* urql exchange backed by the normalized wasm cache (via a `CacheHost`).
*
@@ -127,6 +128,8 @@ declare module '@urql/core' {
interface OperationContext {
/** Publish the network result without storing it in the cache. */
persistResult?: false;
+ /** Types that can change this query's membership, even in an empty response. */
+ externalCacheWriteTypes?: readonly string[];
}
}
@@ -416,6 +419,8 @@ export interface NormalizedCacheExchangeOptions {
/** Return true to transfer a committed query refresh to an active reader's queue.
* Persisted descriptors without an owner retain the normal network fallback. */
delegateRevalidation?: (client: Client, query: QueryRevalidation) => boolean;
+ /** Recover membership dependencies for imperative or durably replayed queries. */
+ externalWriteTypes?: (operation: Operation) => readonly string[] | undefined;
/** Schema-typed singular entity relations derived from field arguments. */
entityResolvers?: EntityResolverConfig;
/** Called when cache work fails; the operation may degrade or emit uncertainty. */
@@ -813,6 +818,10 @@ export function normalizedCacheExchange(
makeOperation('query', op, {
...op.context,
[QUERY_MUTATION_VERSION_CONTEXT_KEY]: mutationVersion,
+ externalCacheWriteVersion: externalWriteVersion(host),
+ externalCacheWriteTypes:
+ op.context.externalCacheWriteTypes ??
+ options.externalWriteTypes?.(op),
});
const enqueueHydrationForward = (op: Operation): void => {
@@ -1299,7 +1308,15 @@ export function normalizedCacheExchange(
await invalidateOlderRetainedFallback(state, resultVersion);
// A previous write turn may have delayed this response until after
// mutation settlement, even though publication happened earlier.
- if (predatesMutation(op)) {
+ if (
+ predatesMutation(op) ||
+ predatesExternalWrite(
+ host,
+ op.context.externalCacheWriteVersion,
+ result.data,
+ op.context.externalCacheWriteTypes
+ )
+ ) {
refreshObsoleteQuery(op);
return undefined;
}
@@ -1455,7 +1472,15 @@ export function normalizedCacheExchange(
}
}
} else if (op.kind === 'query' && isHydrateOnly(op)) {
- if (predatesMutation(op)) {
+ if (
+ predatesMutation(op) ||
+ predatesExternalWrite(
+ host,
+ op.context.externalCacheWriteVersion,
+ result.data,
+ op.context.externalCacheWriteTypes
+ )
+ ) {
if (!result.hasNext && hydrationRequests.has(op.key)) {
enqueueHydrationForward(op);
}
@@ -1497,7 +1522,15 @@ export function normalizedCacheExchange(
}
} else if (op.kind === 'query') {
const state = queryState(op.key);
- if (predatesMutation(op)) {
+ if (
+ predatesMutation(op) ||
+ predatesExternalWrite(
+ host,
+ op.context.externalCacheWriteVersion,
+ result.data,
+ op.context.externalCacheWriteTypes
+ )
+ ) {
if (result.hasNext !== true) {
state.networkRequestsInFlight = Math.max(
0,
@@ -1555,9 +1588,21 @@ export function normalizedCacheExchange(
shared,
filter((op) => op.kind === 'query'),
mergeMap((op) => {
- if (!isHydrateOnly(op)) activeOps.set(op.key, op);
+ // A contextless same-key revalidation shares the mounted reader's scope.
+ const types =
+ op.context.externalCacheWriteTypes ??
+ activeOps.get(op.key)?.context.externalCacheWriteTypes;
+ const operation =
+ types === undefined
+ ? op
+ : makeOperation('query', op, {
+ ...op.context,
+ externalCacheWriteTypes: types,
+ });
+ if (!isHydrateOnly(operation))
+ activeOps.set(operation.key, operation);
return pipe(
- fromPromise(readThenRoute(op)),
+ fromPromise(readThenRoute(operation)),
mergeMap((result) =>
result ? fromValue(result) : (empty as Source<OperationResult>)
)
diff --git a/apps/web/src/lib/i18n/locales/en/view-menus.ts b/apps/web/src/lib/i18n/locales/en/view-menus.ts
index ec0a17e2b0..f7bb29c6a4 100644
--- a/apps/web/src/lib/i18n/locales/en/view-menus.ts
+++ b/apps/web/src/lib/i18n/locales/en/view-menus.ts
@@ -1,4 +1,9 @@
export default {
+ crmVisibility: 'Visibility',
+ crmVisible: 'Visible',
+ crmArchived: 'Archived',
+ crmArchive: 'Archive',
+ crmRestore: 'Restore',
// View tabs
favorites: 'Favorites',
scheduled: 'Scheduled',
diff --git a/apps/web/src/lib/queries/soup/graphql/create-grouped-soup-live-query.test.ts b/apps/web/src/lib/queries/soup/graphql/create-grouped-soup-live-query.test.ts
index 0006774826..91111adeaa 100644
--- a/apps/web/src/lib/queries/soup/graphql/create-grouped-soup-live-query.test.ts
+++ b/apps/web/src/lib/queries/soup/graphql/create-grouped-soup-live-query.test.ts
@@ -27,6 +27,7 @@ import {
parseCacheRevision,
} from '../../../graphql-cache/protocol';
import type {
+ GraphqlEntityFilterAst,
GroupedSoupInput,
GroupSoupQuery,
GroupSoupQueryVariables,
@@ -47,9 +48,10 @@ afterEach(() => {
cleanups.splice(0).forEach((dispose) => dispose());
});
-function setup() {
+function setup(filters: GraphqlEntityFilterAst = {}) {
type Execution = {
variables: GroupSoupQueryVariables;
+ context: Partial<OperationContext>;
publish(
data: GroupSoupQuery,
persistence?: Promise<string | undefined>,
@@ -76,6 +78,7 @@ function setup() {
});
const execution: Execution = {
variables: request.variables,
+ context,
publish: (data, persistence, source = 'live-network') =>
subject.next({
operation,
@@ -146,7 +149,7 @@ function setup() {
propertyDefinitionId: 'status-definition',
},
limit: 2,
- filters: {},
+ filters,
},
});
const query = createGroupedSoupLiveQuery(
@@ -222,6 +225,27 @@ const ids = (data: GroupSoupQuery | undefined) =>
}));
describe('grouped Soup live ownership', () => {
+ it('retains CRM membership dependencies on group continuations', async () => {
+ const state = setup({
+ crmCompanyFilter: {
+ literal: { id: '00000000-0000-0000-0000-000000000000' },
+ },
+ crmContactFilter: { literal: { hidden: false } },
+ });
+ const initial = await state.execution(0);
+ expect(initial.context.externalCacheWriteTypes).toEqual([
+ 'GraphqlSoupCrmContact',
+ ]);
+ initial.publish(page([], 'next'));
+ const more = state.query.paging.fetchNextPage('todo');
+ const continuation = await state.execution(1);
+ expect(continuation.context.externalCacheWriteTypes).toEqual([
+ 'GraphqlSoupCrmContact',
+ ]);
+ continuation.publish(page([], null));
+ await more;
+ });
+
it('does not refetch a continuation started automatically during the initial result', async () => {
const state = setup();
createRoot((dispose) => {
diff --git a/apps/web/src/lib/queries/soup/graphql/create-grouped-soup-live-query.ts b/apps/web/src/lib/queries/soup/graphql/create-grouped-soup-live-query.ts
index d9fc4cc75f..eec98ea3d3 100644
--- a/apps/web/src/lib/queries/soup/graphql/create-grouped-soup-live-query.ts
+++ b/apps/web/src/lib/queries/soup/graphql/create-grouped-soup-live-query.ts
@@ -30,6 +30,7 @@ import {
import { registerGroupedSoupContinuation } from '../grouped/graphql-operation-registry';
import { registerGraphqlSoupRevalidations } from './active-queries';
import { createPredicateQuery } from './create-predicate-query';
+import { crmExternalWriteTypes } from './external-write-scope';
import {
mergeGroupedSoupBins,
projectLocalGroupedSoup,
@@ -90,6 +91,11 @@ export function createGroupedSoupLiveQuery(
const common = {
query: GroupSoupDocument,
client: getGraphqlSoupClient(),
+ context: {
+ externalCacheWriteTypes: crmExternalWriteTypes(
+ queryInput?.initial?.filters
+ ),
+ },
requestPolicy: queryOptions.networkPaused
? ('cache-only' as const)
: ('cache-and-network' as const),
@@ -163,6 +169,11 @@ export function createGroupedSoupLiveQuery(
query: GroupSoupDocument,
client: getGraphqlSoupClient(),
initialPageParam: cursor,
+ context: {
+ externalCacheWriteTypes: crmExternalWriteTypes(
+ initial.initial?.filters
+ ),
+ },
variables: (cursor) => {
const pageInput = continuationInput(cursor);
registerGroupedSoupContinuation(initial, pageInput);
diff --git a/apps/web/src/lib/queries/soup/graphql/create-soup-live-query.ts b/apps/web/src/lib/queries/soup/graphql/create-soup-live-query.ts
index 95777e51eb..f3b156f89e 100644
--- a/apps/web/src/lib/queries/soup/graphql/create-soup-live-query.ts
+++ b/apps/web/src/lib/queries/soup/graphql/create-soup-live-query.ts
@@ -58,6 +58,7 @@ import {
type SoupEntityRef,
soupEntityRefKey,
} from './entity-input';
+import { crmExternalWriteTypes } from './external-write-scope';
import { isCachedMailView } from './mail-view';
import {
usePendingGraphqlSoupDeleteKeys,
@@ -385,6 +386,11 @@ export function createSoupLiveQuery(
query: queryDocument(),
client: getGraphqlSoupClient(),
initialPageParam: null,
+ context: {
+ externalCacheWriteTypes: crmExternalWriteTypes(
+ networkInput()?.initial?.filters
+ ),
+ },
variables: (cursor) => {
const input = inputForCursor(cursor);
if (!input) {
diff --git a/apps/web/src/lib/queries/soup/graphql/external-write-scope.test.ts b/apps/web/src/lib/queries/soup/graphql/external-write-scope.test.ts
new file mode 100644
index 0000000000..93395c626e
--- /dev/null
+++ b/apps/web/src/lib/queries/soup/graphql/external-write-scope.test.ts
@@ -0,0 +1,98 @@
+import { gql } from '@urql/core';
+import { expect, it } from 'vitest';
+import { registerGroupedSoupContinuation } from '../grouped/graphql-operation-registry';
+import {
+ crmExternalWriteTypes,
+ resolveCrmExternalWriteTypes,
+} from './external-write-scope';
+
+it('does not fence explicitly excluded companies or non-opted-in contacts', () => {
+ expect(
+ crmExternalWriteTypes({
+ crmCompanyFilter: {
+ and: {
+ left: { literal: { hidden: false } },
+ right: { literal: { id: '00000000-0000-0000-0000-000000000000' } },
+ },
+ },
+ })
+ ).toEqual([]);
+});
+
+it('recovers initial fallback scope without depending on page-local context', () => {
+ expect(
+ resolveCrmExternalWriteTypes({
+ query: gql`query Replay($page: SoupInput!) { user { soup(input: $page) { nextCursor } } }`,
+ variables: {
+ page: {
+ initial: {
+ filters: {
+ crmCompanyFilter: {
+ literal: { id: '00000000-0000-0000-0000-000000000000' },
+ },
+ },
+ },
+ },
+ },
+ })
+ ).toEqual([]);
+});
+
+it('protects both CRM types when an opaque fallback cursor has no retained scope', () => {
+ expect(
+ resolveCrmExternalWriteTypes({
+ query: gql`query Replay($input: SoupInput!) { user { soup(input: $input) { nextCursor } } }`,
+ variables: { input: { continuation: { cursor: 'unregistered-page' } } },
+ })
+ ).toEqual(['GraphqlSoupCrmCompany', 'GraphqlSoupCrmContact']);
+});
+
+it('recovers a registered grouped fallback scope and leaves non-Soup queries alone', () => {
+ const groupBy = {
+ field: 'PROPERTY' as const,
+ propertyDefinitionId: 'status-definition',
+ };
+ const initial = {
+ initial: {
+ groupBy,
+ filters: {
+ crmCompanyFilter: {
+ literal: { id: '00000000-0000-0000-0000-000000000000' },
+ },
+ crmContactFilter: { literal: { hidden: false } },
+ },
+ },
+ };
+ const continuation = {
+ continuation: { groupBy, groupKey: 'open', cursor: 'known-group' },
+ };
+ registerGroupedSoupContinuation(initial, continuation);
+ expect(
+ resolveCrmExternalWriteTypes({
+ query: gql`query Replay($input: GroupedSoupInput!) { user { groupSoup(input: $input) { bins { key } } } }`,
+ variables: { input: continuation },
+ })
+ ).toEqual(['GraphqlSoupCrmContact']);
+ expect(
+ resolveCrmExternalWriteTypes({
+ query: gql`query Other { user { id } }`,
+ variables: {},
+ })
+ ).toBeUndefined();
+});
+
+it('retains a CRM dependency when either OR branch can return records', () => {
+ expect(
+ crmExternalWriteTypes({
+ crmCompanyFilter: {
+ or: {
+ left: { literal: { hidden: false } },
+ right: { literal: { id: '00000000-0000-0000-0000-000000000000' } },
+ },
+ },
+ crmContactFilter: {
+ literal: { id: '00000000-0000-0000-0000-000000000000' },
+ },
+ })
+ ).toEqual(['GraphqlSoupCrmCompany']);
+});
diff --git a/apps/web/src/lib/queries/soup/graphql/external-write-scope.ts b/apps/web/src/lib/queries/soup/graphql/external-write-scope.ts
new file mode 100644
index 0000000000..439dbb3088
--- /dev/null
+++ b/apps/web/src/lib/queries/soup/graphql/external-write-scope.ts
@@ -0,0 +1,99 @@
+import type { Operation } from '@urql/core';
+import { valueFromASTUntyped, visit } from 'graphql';
+import { NIL } from 'uuid';
+import { groupedSoupLogicalViewKey } from '../grouped/graphql-operation-registry';
+
+// Query observers compare context values by identity; preserve it across UI updates.
+const NO_TYPES: readonly string[] = [];
+const COMPANY_TYPES = ['GraphqlSoupCrmCompany'] as const;
+const CONTACT_TYPES = ['GraphqlSoupCrmContact'] as const;
+const CRM_TYPES = [...COMPANY_TYPES, ...CONTACT_TYPES] as const;
+
+function excludesCrmRecords(filter: unknown): boolean {
+ if (!filter || typeof filter !== 'object') return false;
+ if (
+ 'and' in filter &&
+ filter.and &&
+ typeof filter.and === 'object' &&
+ 'left' in filter.and &&
+ 'right' in filter.and
+ )
+ return (
+ excludesCrmRecords(filter.and.left) ||
+ excludesCrmRecords(filter.and.right)
+ );
+ if (
+ 'or' in filter &&
+ filter.or &&
+ typeof filter.or === 'object' &&
+ 'left' in filter.or &&
+ 'right' in filter.or
+ )
+ return (
+ excludesCrmRecords(filter.or.left) && excludesCrmRecords(filter.or.right)
+ );
+ return (
+ 'literal' in filter &&
+ !!filter.literal &&
+ typeof filter.literal === 'object' &&
+ 'id' in filter.literal &&
+ filter.literal.id === NIL
+ );
+}
+
+/** Use the initial scope for every page; opaque continuation cursors omit filters. */
+export function crmExternalWriteTypes(filters: unknown): readonly string[] {
+ const companyFilter =
+ filters && typeof filters === 'object' && 'crmCompanyFilter' in filters
+ ? filters.crmCompanyFilter
+ : undefined;
+ const contactFilter =
+ filters && typeof filters === 'object' && 'crmContactFilter' in filters
+ ? filters.crmContactFilter
+ : undefined;
+ const companies = !excludesCrmRecords(companyFilter);
+ // Contacts are opt-in, unlike companies in a general Soup list.
+ const contacts = contactFilter && !excludesCrmRecords(contactFilter);
+ if (companies && contacts) return CRM_TYPES;
+ if (companies) return COMPANY_TYPES;
+ if (contacts) return CONTACT_TYPES;
+ return NO_TYPES;
+}
+
+/** Durable descriptors omit page-local context; recover it before urql can share a request. */
+export function resolveCrmExternalWriteTypes(
+ operation: Pick<Operation, 'query' | 'variables'>
+): readonly string[] | undefined {
+ let found = false;
+ const types = new Set<string>();
+ visit(operation.query, {
+ Field(node) {
+ if (node.name.value !== 'soup' && node.name.value !== 'groupSoup') return;
+ found = true;
+ const argument = node.arguments?.find(
+ (argument) => argument.name.value === 'input'
+ );
+ let input: unknown = argument
+ ? valueFromASTUntyped(argument.value, operation.variables ?? {})
+ : undefined;
+ if (node.name.value === 'groupSoup') {
+ const initial = groupedSoupLogicalViewKey(input);
+ if (initial) input = JSON.parse(initial);
+ }
+ const initial =
+ input && typeof input === 'object' && 'initial' in input
+ ? input.initial
+ : undefined;
+ // An opaque replayed cursor may outlive every mounted reader. Its precise
+ // scope is unavailable, so conservatively protect both CRM record types.
+ const dependencies =
+ initial && typeof initial === 'object'
+ ? crmExternalWriteTypes(
+ 'filters' in initial ? initial.filters : undefined
+ )
+ : CRM_TYPES;
+ for (const type of dependencies) types.add(type);
+ },
+ });
+ return found ? [...types] : undefined;
+}
diff --git a/apps/web/src/lib/queries/soup/graphql/items.test.ts b/apps/web/src/lib/queries/soup/graphql/items.test.ts
index a2be44aea6..28e76fc5b2 100644
--- a/apps/web/src/lib/queries/soup/graphql/items.test.ts
+++ b/apps/web/src/lib/queries/soup/graphql/items.test.ts
@@ -82,6 +82,7 @@ import {
type FakeExecution = {
document: DocumentNode;
+ context: Partial<OperationContext>;
variables: Record<string, unknown>;
fail(error: CombinedError): void;
next(
@@ -133,6 +134,7 @@ function makeFakeClient(): {
} as Operation<unknown, Record<string, unknown>>;
executions.push({
document: _request.query,
+ context,
variables: _request.variables,
fail: (error) =>
subject.next({ operation, error, stale: false, hasNext: false }),
@@ -205,6 +207,46 @@ describe('createGraphqlSoupAstItemsQuery', () => {
});
});
+ it('retains CRM dependency scope on opaque continuation pages', async () => {
+ const fake = makeFakeClient();
+ getGraphqlSoupClientMock.mockReturnValue(fake.client);
+ const { query, dispose } = createRoot((dispose) => ({
+ query: createSoupLiveQuery(() => ({
+ sortMethod: 'UPDATED_AT',
+ filters: {
+ crmCompanyFilter: {
+ literal: { id: '00000000-0000-0000-0000-000000000000' },
+ },
+ crmContactFilter: { literal: { hidden: false } },
+ },
+ })),
+ dispose,
+ }));
+ try {
+ await vi.waitFor(() => expect(fake.executions).toHaveLength(1));
+ expect(fake.executions[0].context.externalCacheWriteTypes).toEqual([
+ 'GraphqlSoupCrmContact',
+ ]);
+ fake.executions[0].next(
+ graphqlSoupPage({ items: [], next_cursor: 'page-2' })
+ );
+ const more = query.fetchNextPage();
+ await vi.waitFor(() => expect(fake.executions).toHaveLength(2));
+ expect(fake.executions[1].variables).toMatchObject({
+ input: { continuation: { cursor: 'page-2' } },
+ });
+ expect(fake.executions[1].context.externalCacheWriteTypes).toEqual([
+ 'GraphqlSoupCrmContact',
+ ]);
+ fake.executions[1].next(
+ graphqlSoupPage({ items: [], next_cursor: null })
+ );
+ await more;
+ } finally {
+ dispose();
+ }
+ });
+
it.each([
{ entityType: 'CHANNEL', typename: 'GraphqlSoupChannel' },
{ entityType: 'DOCUMENT', typename: 'GraphqlSoupDocument' },
diff --git a/apps/web/src/lib/service-clients/service-storage/crm-visibility.test.ts b/apps/web/src/lib/service-clients/service-storage/crm-visibility.test.ts
new file mode 100644
index 0000000000..c159900ed5
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/crm-visibility.test.ts
@@ -0,0 +1,106 @@
+import { externalWriteVersion } from '@graphql-cache/exchange/external-writes';
+import type { CacheHost } from '@graphql-cache/host/types';
+import { beforeEach, expect, it, vi } from 'vitest';
+import { prepareCrmVisibilityWrite } from './crm-visibility';
+
+const mocks = vi.hoisted(() => ({
+ client: {},
+ host: { writeQuery: vi.fn(), deleteRecords: vi.fn() },
+ error: vi.fn(),
+}));
+vi.mock('./graphql-soup', () => ({
+ getGraphqlSoupClient: () => mocks.client,
+ getGraphqlSoupCacheHost: () => mocks.host,
+}));
+vi.mock('@macro-inc/observability', () => ({
+ Telemetry: { error: mocks.error },
+}));
+beforeEach(() => {
+ mocks.client = {};
+ mocks.host = {
+ writeQuery: vi.fn(async () => undefined),
+ deleteRecords: vi.fn(async () => undefined),
+ };
+ mocks.error.mockClear();
+});
+
+it('writes confirmed company and contact flags with the generated normalized subscription document', async () => {
+ const writer = prepareCrmVisibilityWrite();
+ const host = mocks.host as unknown as CacheHost;
+ const before = externalWriteVersion(host);
+ await writer.commit({
+ companyId: 'company-1',
+ contactIds: ['contact-1', 'contact-2'],
+ hidden: true,
+ });
+ expect(externalWriteVersion(host)).toBeGreaterThan(before);
+ expect(mocks.host.writeQuery).toHaveBeenCalledWith(
+ expect.objectContaining({
+ operationName: 'CrmVisibilityCacheWrite',
+ query: expect.stringContaining('... on GraphqlSoupCrmContact'),
+ data: {
+ soupUpdates: [
+ {
+ __typename: 'SoupUpdated',
+ item: {
+ __typename: 'GraphqlSoupCrmContact',
+ id: 'contact-1',
+ hidden: true,
+ },
+ },
+ {
+ __typename: 'SoupUpdated',
+ item: {
+ __typename: 'GraphqlSoupCrmContact',
+ id: 'contact-2',
+ hidden: true,
+ },
+ },
+ {
+ __typename: 'SoupUpdated',
+ item: {
+ __typename: 'GraphqlSoupCrmCompany',
+ id: 'company-1',
+ hidden: true,
+ },
+ },
+ ],
+ },
+ })
+ );
+ await writer.commit({ contactIds: ['contact-1'], hidden: false });
+ expect(mocks.host.writeQuery.mock.calls[1][0].data.soupUpdates).toEqual([
+ {
+ __typename: 'SoupUpdated',
+ item: {
+ __typename: 'GraphqlSoupCrmContact',
+ id: 'contact-1',
+ hidden: false,
+ },
+ },
+ ]);
+});
+
+it('does not write a previous session response into the next session', async () => {
+ const writer = prepareCrmVisibilityWrite();
+ mocks.client = {};
+ expect(writer.isCurrent()).toBe(false);
+ await writer.commit({ contactIds: ['contact-1'], hidden: true });
+ expect(mocks.host.writeQuery).not.toHaveBeenCalled();
+});
+
+it('removes only affected stale records if a confirmed cache write fails, without rejecting the saved action', async () => {
+ mocks.host.writeQuery.mockRejectedValueOnce(new Error('worker unavailable'));
+ await expect(
+ prepareCrmVisibilityWrite().commit({
+ companyId: 'company-1',
+ contactIds: ['contact-1'],
+ hidden: true,
+ })
+ ).resolves.toBeUndefined();
+ expect(mocks.host.deleteRecords).toHaveBeenCalledWith([
+ 'GraphqlSoupCrmContact:contact-1',
+ 'GraphqlSoupCrmCompany:company-1',
+ ]);
+ expect(mocks.error).toHaveBeenCalledOnce();
+});
diff --git a/apps/web/src/lib/service-clients/service-storage/crm-visibility.ts b/apps/web/src/lib/service-clients/service-storage/crm-visibility.ts
new file mode 100644
index 0000000000..124060610d
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/crm-visibility.ts
@@ -0,0 +1,75 @@
+import { recordExternalWrite } from '@graphql-cache/exchange/external-writes';
+import { Telemetry } from '@macro-inc/observability';
+import { stringifyDocument } from '@urql/core';
+import {
+ CrmVisibilityCacheWriteDocument,
+ type CrmVisibilityCacheWriteSubscription,
+} from './graphql/generated/graphql';
+import { getGraphqlSoupCacheHost, getGraphqlSoupClient } from './graphql-soup';
+
+/** Capture the session before REST dispatch; a late response cannot enter a new session. */
+export function prepareCrmVisibilityWrite() {
+ const client = getGraphqlSoupClient();
+ const host = getGraphqlSoupCacheHost();
+ const isCurrent = () =>
+ client === getGraphqlSoupClient() && host === getGraphqlSoupCacheHost();
+ return {
+ isCurrent,
+ async commit(change: {
+ companyId?: string;
+ contactIds: string[];
+ hidden: boolean;
+ }) {
+ if (!isCurrent() || !host) return;
+ recordExternalWrite(
+ host,
+ change.companyId
+ ? ['GraphqlSoupCrmCompany', 'GraphqlSoupCrmContact']
+ : ['GraphqlSoupCrmContact']
+ );
+ const items: CrmVisibilityCacheWriteSubscription['soupUpdates'] =
+ change.contactIds.map((id) => ({
+ __typename: 'SoupUpdated',
+ item: {
+ __typename: 'GraphqlSoupCrmContact',
+ id,
+ hidden: change.hidden,
+ },
+ }));
+ if (change.companyId)
+ items.push({
+ __typename: 'SoupUpdated',
+ item: {
+ __typename: 'GraphqlSoupCrmCompany',
+ id: change.companyId,
+ hidden: change.hidden,
+ },
+ });
+ try {
+ await host.writeQuery({
+ query: stringifyDocument(CrmVisibilityCacheWriteDocument),
+ operationName: 'CrmVisibilityCacheWrite',
+ data: {
+ soupUpdates: items,
+ } satisfies CrmVisibilityCacheWriteSubscription,
+ });
+ } catch (error) {
+ Telemetry.error(error);
+ // Confirmed writes stay successful even if the local cache is unavailable.
+ if (isCurrent()) {
+ try {
+ await host.deleteRecords(
+ items.flatMap((item) =>
+ item.__typename === 'SoupUpdated' && 'id' in item.item
+ ? [`${item.item.__typename}:${item.item.id}`]
+ : []
+ )
+ );
+ } catch (error) {
+ Telemetry.error(error);
+ }
+ }
+ }
+ },
+ };
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts b/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts
index f5b5b375d7..a81ac642ad 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql-soup.ts
@@ -86,6 +86,7 @@ import { batch, createSignal, untrack } from 'solid-js';
import { match } from 'ts-pattern';
import { delegateChannelNotificationRefresh } from '../../queries/channel/notification-refresh';
import { soupOptimisticResolvers } from '../../queries/optimistic-resolvers';
+import { resolveCrmExternalWriteTypes } from '../../queries/soup/graphql/external-write-scope';
import { createCacheRecovery } from './cache-recovery';
import { emailCacheDeletionKeys } from './email-cache-deletions';
import { emailThreadSortTs } from './email-thread-sort';
@@ -863,6 +864,7 @@ export function getGraphqlSoupClient(): Client {
shouldRetryMutation: shouldRetryGraphqlMutation,
mutationQueueTelemetry,
delegateRevalidation: delegateChannelNotificationRefresh,
+ externalWriteTypes: resolveCrmExternalWriteTypes,
}),
notificationReceiptExchange(publishNotificationPatch),
graphqlSoupSubscriptionExchange(graphqlWsClient),
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql/crm-visibility-cache-write.graphql b/apps/web/src/lib/service-clients/service-storage/graphql/crm-visibility-cache-write.graphql
new file mode 100644
index 0000000000..85329d0c67
--- /dev/null
+++ b/apps/web/src/lib/service-clients/service-storage/graphql/crm-visibility-cache-write.graphql
@@ -0,0 +1,19 @@
+# Confirmed REST archive effects use the existing Soup update normalization path.
+subscription CrmVisibilityCacheWrite {
+ soupUpdates {
+ __typename
+ ... on SoupUpdated {
+ item {
+ __typename
+ ... on GraphqlSoupCrmCompany {
+ id
+ hidden
+ }
+ ... on GraphqlSoupCrmContact {
+ id
+ hidden
+ }
+ }
+ }
+ }
+}
diff --git a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts
index 6233624023..b6b2f99a2d 100644
--- a/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts
+++ b/apps/web/src/lib/service-clients/service-storage/graphql/generated/graphql.ts
@@ -4667,6 +4667,30 @@ export type ChannelUnreadPresenceQuery = { user: { id: string, soup: { items: Ar
| { __typename: 'GraphqlSoupReminder', id: string }
> } } };
+export type CrmVisibilityCacheWriteSubscriptionVariables = Exact<{ [key: string]: never; }>;
+
+
+export type CrmVisibilityCacheWriteSubscription = { soupUpdates: Array<
+ | { __typename: 'GraphqlCacheDeletion' }
+ | { __typename: 'SoupUpdated', item:
+ | { __typename: 'GraphqlSoupAgentSession' }
+ | { __typename: 'GraphqlSoupCalendarEvent' }
+ | { __typename: 'GraphqlSoupCall' }
+ | { __typename: 'GraphqlSoupChannel' }
+ | { __typename: 'GraphqlSoupChannelMessage' }
+ | { __typename: 'GraphqlSoupChat' }
+ | { __typename: 'GraphqlSoupCrmCompany', id: string, hidden: boolean }
+ | { __typename: 'GraphqlSoupCrmContact', id: string, hidden: boolean }
+ | { __typename: 'GraphqlSoupDatabaseRow' }
+ | { __typename: 'GraphqlSoupDocument' }
+ | { __typename: 'GraphqlSoupEmailThread' }
+ | { __typename: 'GraphqlSoupForeignEntity' }
+ | { __typename: 'GraphqlSoupInitiative' }
+ | { __typename: 'GraphqlSoupProject' }
+ | { __typename: 'GraphqlSoupReminder' }
+ }
+ > };
+
export type GraphqlCrmCompanyQuickAccessFieldsFragment = { __typename: 'GraphqlSoupCrmCompany', name: string | null, teamId: string, hidden: boolean, domains: Array<string>, createdAt: string, updatedAt: string, viewedAt: string | null };
export type GraphqlCrmContactFieldsFragment = { __typename: 'GraphqlSoupCrmContact', id: string, hidden: boolean, firstInteraction: string, lastInteraction: string, createdAt: string, updatedAt: string, viewedAt: string | null, contactTeamId: string, contactCompanyId: string | null, contactCompanyName: string | null, contactEmail: string | null, crmContactName: string | null };
@@ -22636,6 +22660,7 @@ export const ChannelListSoupDocument = {"kind":"Document","definitions":[{"kind"
export const ChannelUnreadMembershipCacheWriteDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"ChannelUnreadMembershipCacheWrite"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"SoupInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"soup"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"items"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}}]}}]}}]}}]}}]} as unknown as DocumentNode<ChannelUnreadMembershipCacheWriteQuery, ChannelUnreadMembershipCacheWriteQueryVariables>;
export const ChannelUnreadCacheWriteDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"subscription","name":{"kind":"Name","value":"ChannelUnreadCacheWrite"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"soupUpdates"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"SoupUpdated"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"item"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannel"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"unreadNotifications"},"name":{"kind":"Name","value":"notifications"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"filter"},"value":{"kind":"ObjectValue","fields":[{"kind":"ObjectField","name":{"kind":"Name","value":"states"},"value":{"kind":"ListValue","values":[{"kind":"EnumValue","value":"UNSEEN"}]}},{"kind":"ObjectField","name":{"kind":"Name","value":"topLevelMessagesOnly"},"value":{"kind":"BooleanValue","value":true}}]}},{"kind":"Argument","name":{"kind":"Name","value":"limit"},"value":{"kind":"IntValue","value":"1"}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"state"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}}]}}]}}]}}]}}]}}]} as unknown as DocumentNode<ChannelUnreadCacheWriteSubscription, ChannelUnreadCacheWriteSubscriptionVariables>;
export const ChannelUnreadPresenceDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"ChannelUnreadPresence"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"SoupInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"soup"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"items"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupChannel"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"unreadNotifications"},"name":{"kind":"Name","value":"notifications"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"filter"},"value":{"kind":"ObjectValue","fields":[{"kind":"ObjectField","name":{"kind":"Name","value":"states"},"value":{"kind":"ListValue","values":[{"kind":"EnumValue","value":"UNSEEN"}]}},{"kind":"ObjectField","name":{"kind":"Name","value":"topLevelMessagesOnly"},"value":{"kind":"BooleanValue","value":true}}]}},{"kind":"Argument","name":{"kind":"Name","value":"limit"},"value":{"kind":"IntValue","value":"1"}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"state"}}]}}]}}]}}]}}]}}]}}]} as unknown as DocumentNode<ChannelUnreadPresenceQuery, ChannelUnreadPresenceQueryVariables>;
+export const CrmVisibilityCacheWriteDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"subscription","name":{"kind":"Name","value":"CrmVisibilityCacheWrite"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"soupUpdates"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"SoupUpdated"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"item"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCrmCompany"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"hidden"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCrmContact"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"hidden"}}]}}]}}]}}]}}]}}]} as unknown as DocumentNode<CrmVisibilityCacheWriteSubscription, CrmVisibilityCacheWriteSubscriptionVariables>;
export const CrmContactsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"CrmContacts"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"SoupInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"soup"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"items"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"FragmentSpread","name":{"kind":"Name","value":"GraphqlCrmContactFields"}}]}},{"kind":"Field","name":{"kind":"Name","value":"nextCursor"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"GraphqlCrmContactFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCrmContact"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","alias":{"kind":"Name","value":"contactTeamId"},"name":{"kind":"Name","value":"teamId"}},{"kind":"Field","alias":{"kind":"Name","value":"contactCompanyId"},"name":{"kind":"Name","value":"parentCompanyId"}},{"kind":"Field","alias":{"kind":"Name","value":"contactCompanyName"},"name":{"kind":"Name","value":"parentCompanyName"}},{"kind":"Field","alias":{"kind":"Name","value":"contactEmail"},"name":{"kind":"Name","value":"emailAddress"}},{"kind":"Field","alias":{"kind":"Name","value":"crmContactName"},"name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"hidden"}},{"kind":"Field","name":{"kind":"Name","value":"firstInteraction"}},{"kind":"Field","name":{"kind":"Name","value":"lastInteraction"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}},{"kind":"Field","name":{"kind":"Name","value":"viewedAt"}}]}}]} as unknown as DocumentNode<CrmContactsQuery, CrmContactsQueryVariables>;
export const CrmRecordPipelineEntriesDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"CrmRecordPipelineEntries"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"SoupInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"user"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"soup"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"items"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCrmCompany"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"pipelineEntries"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"CrmPipelineEntryFields"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSoupCrmContact"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"pipelineEntries"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"CrmPipelineEntryFields"}}]}}]}}]}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"SoupPropertyValueFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlBooleanPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"boolValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNumberPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"numberValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlStringPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"stringValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlDatePropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"dateValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlDateRangePropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"rangeStart"},"name":{"kind":"Name","value":"start"}},{"kind":"Field","alias":{"kind":"Name","value":"rangeEnd"},"name":{"kind":"Name","value":"end"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlSelectOptionPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"optionIds"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlEntityReferencePropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"references"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"entityId"}},{"kind":"Field","name":{"kind":"Name","value":"entityType"}},{"kind":"Field","name":{"kind":"Name","value":"specificMessageId"}}]}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlLinkPropertyValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"urls"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"CrmPipelineEntryFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlCrmPipelineEntry"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"pipeline"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"sharing"}},{"kind":"Field","name":{"kind":"Name","value":"tableId"}},{"kind":"Field","name":{"kind":"Name","value":"canEdit"}}]}},{"kind":"Field","name":{"kind":"Name","value":"cells"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"column"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"dataType"}},{"kind":"Field","name":{"kind":"Name","value":"isMultiSelect"}},{"kind":"Field","name":{"kind":"Name","value":"specificEntityType"}},{"kind":"Field","name":{"kind":"Name","value":"writable"}},{"kind":"Field","name":{"kind":"Name","value":"options"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"color"}},{"kind":"Field","name":{"kind":"Name","value":"value"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlStringPropertyOptionValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"stringValue"},"name":{"kind":"Name","value":"value"}}]}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlNumberPropertyOptionValue"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","alias":{"kind":"Name","value":"numberValue"},"name":{"kind":"Name","value":"value"}}]}}]}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"value"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"SoupPropertyValueFields"}}]}}]}}]}}]} as unknown as DocumentNode<CrmRecordPipelineEntriesQuery, CrmRecordPipelineEntriesQueryVariables>;
export const RenameDatabaseDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"RenameDatabase"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"ID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"displayName"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"renameEntities"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"inputs"},"value":{"kind":"ListValue","values":[{"kind":"ObjectValue","fields":[{"kind":"ObjectField","name":{"kind":"Name","value":"entity"},"value":{"kind":"ObjectValue","fields":[{"kind":"ObjectField","name":{"kind":"Name","value":"type"},"value":{"kind":"EnumValue","value":"DATABASE"}},{"kind":"ObjectField","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}]}},{"kind":"ObjectField","name":{"kind":"Name","value":"displayName"},"value":{"kind":"Variable","name":{"kind":"Name","value":"displayName"}}}]}]}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"results"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"DatabaseEntityMutationResultFields"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"DatabaseEntityMutationResultFields"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlEntityMutationResult"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"__typename"}},{"kind":"InlineFragment","typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"GraphqlMutationError"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"errorCode"}},{"kind":"Field","name":{"kind":"Name","value":"message"}}]}}]}}]} as unknown as DocumentNode<RenameDatabaseMutation, RenameDatabaseMutationVariables>;
diff --git a/docs/agent-guide/crm.md b/docs/agent-guide/crm.md
index 8f69ddc1c8..3e68d1055c 100644
--- a/docs/agent-guide/crm.md
+++ b/docs/agent-guide/crm.md
@@ -128,29 +128,13 @@ email), Company and Last contacted (sortable). `Search people` matches name or
email on the server after a short typing pause, so results include contacts not
yet scrolled into view. The desktop header has the title, shared **New** menu,
and expandable Search; choose **Contact** from New. On touch, **New contact**
-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 name
-or domain, from the up to 500 most relevant companies, including name-only
-companies); without one the person is added with no company. The email is
-optional: personal addresses and different domains are accepted, and leaving it
-empty adds the person by name alone. Contacts without a company show no company
-pill. **Add contact** on a company's Team tab skips the company pill.
-Contact names allow up to 200 characters. A longer name keeps the form open
-with an error; shortening it allows submission without re-entering other fields.
-**New company** requires a name; its domain is optional. If supplied, it must be
-a company domain, not a personal email provider. The company, contact and pipeline dialogs share the
-task/project composer layout: name on the first row beside **Close**, details
-below, and a **Create …** button that also submits on Command-Enter.
+is unchanged. The **Visible / Archived** filter selects one view on People,
+Companies and company Team. Archived is available to admins/owners; People recovery
+is scoped to their current team. Search and sorting stay in place when switching.
+Archived rows carry a chip. Open a record and choose **Restore** beside its identity
+chip; the row leaves Archived and returns to ordinary lists and Cmd-K. People under
+an archived company require that company to be restored first. There is no permanent
+explanatory banner or recovery UI inside Cmd-K.
Verify company domain validation by creating a company with an allowed business
domain, then adding a contact whose email matches it. Personal email provider
@@ -231,29 +215,35 @@ queries or creation actions. Copy-link islands are 40px square on touch with
a 24px icon. Verify both record types, section changes, dismissal, copy feedback,
and header fit at phone and tablet widths.
-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 the
-team'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. Restoring
-the company restores every contact, including individually hidden ones, but leaves
-email 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 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. Company row
-**Hide / Unhide** actions control the same state. The information panel has no
-visibility toggle; company Sharing contains only **Sync Emails**.
-Restoring a person under a hidden company does not make them appear in People
-until that company is restored too. People without a company can be restored
-directly; a person without a name or email is labeled **Contact** in the confirmation.
-
-The removed-People discovery check is
+To archive a person or company, choose **Archive** immediately beside **Copy link**
+in the top toolbar. Confirming archives the record for the team while retaining its
+history; Cancel changes nothing. While saving, duplicate actions and dismissal are
+blocked. A rejected save retains the prior state and an actionable retry. Only team
+admins/owners can archive or restore; other members see a disabled action.
+
+An archived record has a single **Archived** chip and a quiet borderless **Restore**
+action beside its name on desktop, grouped beneath it on phones. Its toolbar keeps
+Copy link and Details. Hover or focus the chip for the explanation; tap on phones.
+Escape dismisses it. Restore is a separate focus target. Verify 320px and 390px phone
+widths, a usable Restore touch target and focus after confirmation or cancellation.
+
+Company archive archives all its people and turns off team email sync. Restoring the
+company requires an explicit confirmation: every person is restored, including those
+archived individually, while email syncing stays off. Re-enable **Sync Emails** under
+**Email sharing** separately. A person whose company is archived offers **Open company**
+so that restoration happens there first. Unfiled people restore directly. Company row
+**Archive / Restore** actions also confirm the cascade. Record details and References
+appear first in both information panels; company Properties, Lists and Email sharing
+follow. Neither panel has a duplicate visibility control.
+
+Verify successful changes update open People, Companies, Team and ordinary Cmd-K;
+late responses must not reintroduce archived rows or hide restored rows with an
+old empty page. Returning to a cached company
+must show confirmed embedded contacts. Failed reads after a successful save must not
+claim the save failed. Run the actual-control desktop/phone fixture with
+`bunx playwright test --config src/features/crm/browser-test/archive/playwright.config.ts`.
+
+The archived-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,
@@ -264,8 +254,6 @@ The backend-free browser check is
from `apps/web`. It exercises cancellation, pending/error handling, restoration,
permissions, and changing records with an open confirmation on desktop, phone,
and tablet.
-Fixture screenshots: [company confirmation on desktop](media/crm-removal/company-desktop.png)
-and [person confirmation on phone](media/crm-removal/contact-phone.png).
Their information panel starts closed and opens as a floating bubble at every
width, without shrinking the record content. Click outside the bubble or use
@@ -280,7 +268,7 @@ fills the row beside the filter button, or the whole row without filters.
Email importance and inbox choices open in the shared filter drawer.
Section creation actions appear at the bottom right above the navigation dock,
replacing the default app-wide action: Add contact, New email, New note, New task,
-New call, or New database. Add contact is available once the company is loaded,
+New call, or New database. Add contact is available once the company is loaded and visible,
including companies without a domain; contact emails may use any valid domain.
Email-sync and database gates, recipients, and task associations still apply. With company email
sync off, New email stays visible but disabled; New company must not replace it.