Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(crm): open company and contact links inside Customers on desktop (#8345)
gbirmanf76e6f2524ad
diff --git a/apps/web/src/components/app/split-layout/split-router/app-middleware.ts b/apps/web/src/components/app/split-layout/split-router/app-middleware.tsindex 7b564b1550..4d78269f0e 100644--- a/apps/web/src/components/app/split-layout/split-router/app-middleware.ts+++ b/apps/web/src/components/app/split-layout/split-router/app-middleware.ts@@ -6,7 +6,11 @@ import {} from '@app/features/calendar-view/calendar-url';import { CALENDAR_VIEW_ID } from '@app/features/calendar-view/types';import { channelsSearch } from '@app/features/channels-view/channels-route';-import { legacyCrmPipelineId } from '@app/features/crm/crm-route';+import {+ crmPeopleSearch,+ crmRecordSearch,+ legacyCrmPipelineId,+} from '@app/features/crm/crm-route';import {driveDocumentFromContent,drivePath,@@ -28,6 +32,7 @@ import { URL_PARAMS as CALL_URL_PARAMS } from '@block-call/constants';import { URL_PARAMS as CHANNEL_URL_PARAMS } from '@block-channel/constants';import { URL_PARAMS as MD_URL_PARAMS } from '@block-md/constants';import { URL_PARAMS as PDF_URL_PARAMS } from '@block-pdf/constants';+import { COMMENT_LINK_PARAM } from '@core/messages/comment-link';import { match } from 'ts-pattern';import { decodeLegacyPair } from './legacy-route';@@ -77,6 +82,14 @@ function redirectLegacyRoutes(}}+ // Touch shows records on their own pages, as the Customers lists open them.+ if (rootId === 'view-companies' && isTouch) {+ const { recordType, recordId } = routeParams(route);+ if (typeof recordType === 'string' && typeof recordId === 'string') {+ return redirect(`/${recordType}/${encodeURIComponent(recordId)}`);+ }+ }+if (rootId === 'call-detail') {const { callId } = routeParams(route);if (typeof callId === 'string') {@@ -119,6 +132,19 @@ function redirectLegacyRoutes(({ id }) => `/channels/${encodeURIComponent(id)}`).with({ type: 'task' }, ({ id }) => `/tasks/${encodeURIComponent(id)}`)+ .with(+ { type: 'company' },+ ({ id }) => `/companies/company/${encodeURIComponent(id)}`+ )+ // A contact opens from People, whose list its breadcrumb returns to.+ .with({ type: 'contact' }, ({ id }) => {+ const query = new URLSearchParams();+ // An explicit query replaces the entry's search, so keep what it carries.+ replacePaneSearchParams(query, [+ { ...to.location.search, ...crmPeopleSearch },+ ]);+ return `/companies/contact/${encodeURIComponent(id)}?${query}`;+ })// Like a task, a project opens in Tasks, under its Projects tab..with({ type: 'initiative' }, ({ id }) => {const query = new URLSearchParams();@@ -199,6 +225,10 @@ function migrateLegacySearch({(id) => id === 'home-document' || id === 'home-preview',() => homeDocumentMapping)+ .with('companies-record', () => ({+ namespace: crmRecordSearch.namespace,+ fields: [[COMMENT_LINK_PARAM, 'commentId']] as const,+ })).with(CALENDAR_ROUTE_ID, () => ({namespace: CALENDAR_SEARCH_NAMESPACE,fields: [['eventId', 'eventId']] as const,diff --git a/apps/web/src/components/app/split-layout/split-router/legacy-route.test.ts b/apps/web/src/components/app/split-layout/split-router/legacy-route.test.tsindex 782fb18daa..24e143cfda 100644--- a/apps/web/src/components/app/split-layout/split-router/legacy-route.test.ts+++ b/apps/web/src/components/app/split-layout/split-router/legacy-route.test.ts@@ -6,7 +6,7 @@ import {notFoundRoute,} from '@app/routes/routes';import { describe, expect, it, vi } from 'vitest';-import { upgradeLegacyPath } from './legacy-route';+import { resolveContentLocation, upgradeLegacyPath } from './legacy-route';vi.mock('@components/app/split-layout/componentRegistry', () => ({resolveComponent: vi.fn(() => ({ type: 'mock-component' })),@@ -37,3 +37,25 @@ describe('upgradeLegacyPath', () => {expect(upgradeLegacyPath(routes, '/getting-started')).toBe('/home');});});++describe('resolveContentLocation', () => {+ it.each(['company', 'contact'] as const)(+ 'keeps the Discussion message a %s opens at',+ (type) => {+ const location = resolveContentLocation(routes, {+ type,+ id: 'record',+ params: { comment_id: 'message' },+ });+ expect(location.search).toEqual({+ 'crm-record': { commentId: ['message'], seek: [expect.any(String)] },+ });+ }+ );++ it('adds no message to a record opened without one', () => {+ expect(+ resolveContentLocation(routes, { type: 'company', id: 'record' }).search+ ).toBeUndefined();+ });+});diff --git a/apps/web/src/components/app/split-layout/split-router/legacy-route.ts b/apps/web/src/components/app/split-layout/split-router/legacy-route.tsindex 82aab2cd06..40d80ab2a4 100644--- a/apps/web/src/components/app/split-layout/split-router/legacy-route.ts+++ b/apps/web/src/components/app/split-layout/split-router/legacy-route.ts@@ -12,6 +12,7 @@ import {} from '@app/features/calendar-view/calendar-url';import { CALENDAR_VIEW_ID } from '@app/features/calendar-view/types';import { channelsSearch } from '@app/features/channels-view/channels-route';+import { crmRecordSearch } from '@app/features/crm/crm-route';import {ROUTINE_CREATE_ROUTE_ID,ROUTINE_DETAIL_ROUTE_ID,@@ -47,6 +48,7 @@ import {isBlockAlias,resolveBlockAlias,} from '@core/constant/allBlocks';+import { COMMENT_LINK_PARAM } from '@core/messages/comment-link';import type { SplitContent } from '../layoutManager';type LegacySplitPathContext = {@@ -304,6 +306,31 @@ export function splitLocationFromContent(return { route: paneRoute({ id: 'legacy-content', params: { type, id } }) };}+/**+ * A record opened at a Discussion message keeps it when desktop moves the+ * record into Customers, which has no block to hand the params to.+ */+function withCrmCommentTarget(+ content: SplitContent,+ search: SplitSearchState | undefined+): SplitSearchState | undefined {+ const params: Record<string, unknown> | undefined =+ (content.type === 'company' || content.type === 'contact') &&+ isRecord(content.params)+ ? content.params+ : undefined;+ const commentId = params?.[COMMENT_LINK_PARAM];+ if (typeof commentId !== 'string') return search;++ return {+ ...search,+ [crmRecordSearch.namespace]: {+ commentId: [commentId],+ seek: [crypto.randomUUID()],+ },+ };+}+/** Resolve legacy/persisted metadata before it reaches router state. */export function resolveContentLocation(routes: SplitRoutesManifest,@@ -343,7 +370,7 @@ export function resolveContentLocation(: undefined;const messageId = channelParams?.[CHANNEL_URL_PARAMS.message];const threadId = channelParams?.[CHANNEL_URL_PARAMS.thread];- let contentSearch = savedSearch;+ let contentSearch = withCrmCommentTarget(content, savedSearch);if (typeof messageId === 'string') {const channelSearch = { ...savedSearch?.[channelsSearch.namespace] };// Message and thread identify one target; never combine two saved opens.diff --git a/apps/web/src/features/crm/README.md b/apps/web/src/features/crm/README.mdindex 80298f14f5..db2a603fdb 100644--- a/apps/web/src/features/crm/README.md+++ b/apps/web/src/features/crm/README.md@@ -20,7 +20,7 @@ crm/crm-search.ts / crm-tool-renderers.tsxcrm-route.ts Route params, record trail, and legacy pipeline link decodingroute-views.tsx Authenticated route and shared-view decoding- crm-hosted-content.ts Split content that opens Customers on a pipeline+ crm-hosted-content.ts Split content that opens Customers on a pipeline or record*-adapter.* Production sources, navigation, persistence, download, collection wiring```diff --git a/apps/web/src/features/crm/context/workspace-context.tsx b/apps/web/src/features/crm/context/workspace-context.tsxindex f12862ead9..a26e196529 100644--- a/apps/web/src/features/crm/context/workspace-context.tsx+++ b/apps/web/src/features/crm/context/workspace-context.tsx@@ -10,12 +10,17 @@ import type { SoupState } from '../../next-soup/create-soup-state';import type { QueryStore } from '../../next-soup/filters/filter-store/query-store';import type { CrmRecordRef, CrmRecordSection } from '../core/record';+/** A new `seek` asks to show the same message again. */+export type CrmCommentTarget = { commentId: string; seek: string };+/** Records opened inside the workspace; the route holds them. */export type CrmRecordNavigation = {/** Records opened from the list, oldest first; empty on the list. */records: Accessor<readonly CrmRecordRef[]>;/** The shown record's tab; none is its Overview. */section: Accessor<CrmRecordSection | undefined>;+ /** A Discussion message of the shown record to scroll to. */+ commentTarget: Accessor<CrmCommentTarget | undefined>;/** Shows the last record of `trail` at its Overview. */open(trail: readonly CrmRecordRef[]): void;setSection(section: CrmRecordSection): void;diff --git a/apps/web/src/features/crm/crm-hosted-content.ts b/apps/web/src/features/crm/crm-hosted-content.tsindex 3122358712..9ad079d2a2 100644--- a/apps/web/src/features/crm/crm-hosted-content.ts+++ b/apps/web/src/features/crm/crm-hosted-content.ts@@ -1,5 +1,6 @@import { paneRoute } from '@app/routes/app-route';import type { SplitContent } from '@components/app/split-layout/layoutManager';+import { crmPeopleSearch, crmRecordSearch } from './crm-route';/** Customers showing `pipelineId`, without mounting a legacy pipeline block. */export function crmPipelineContent(pipelineId: string): SplitContent {@@ -14,3 +15,34 @@ export function crmPipelineContent(pipelineId: string): SplitContent {},};}++/** Customers showing a record, scrolled to `commentId` in its Discussion. */+export function crmRecordContent(+ record: { type: 'company' | 'contact'; id: string },+ commentId?: string+): SplitContent {+ return {+ type: 'component',+ id: 'companies',+ entryMetadata: {+ route: paneRoute(+ { id: 'view-companies', params: {} },+ {+ id: 'companies-record',+ params: { recordType: record.type, recordId: record.id },+ }+ ),+ search: {+ ...(record.type === 'contact' ? crmPeopleSearch : {}),+ ...(commentId+ ? {+ [crmRecordSearch.namespace]: {+ commentId: [commentId],+ seek: [crypto.randomUUID()],+ },+ }+ : {}),+ },+ },+ };+}diff --git a/apps/web/src/features/crm/crm-route.test.ts b/apps/web/src/features/crm/crm-route.test.tsindex 2708ab82c4..ba2cc21e90 100644--- a/apps/web/src/features/crm/crm-route.test.ts+++ b/apps/web/src/features/crm/crm-route.test.ts@@ -185,13 +185,41 @@ describe('pipeline links', () => {});});-describe('legacy pipeline URLs', () => {+const legacyEntry = (type: string, id: string): Entry => ({+ id: 'entry',+ location: {+ route: paneRoute({ id: legacyContentRoute.id, params: { type, id } }),+ },+});++const recordEntry = (+ recordType: 'company' | 'contact',+ recordId: string,+ pipelineId?: string+): Entry => ({+ id: 'entry',+ location: {+ route: pipelineId+ ? paneRoute(+ { id: companiesRoute.id, params: {} },+ { id: crmPipelineRoute.id, params: { pipelineId } },+ { id: crmPipelineRecordRoute.id, params: { recordType, recordId } }+ )+ : paneRoute(+ { id: companiesRoute.id, params: {} },+ { id: crmRecordRoute.id, params: { recordType, recordId } }+ ),+ },+});++describe('legacy CRM URLs', () => {const run = (to: Entry,options: {touch?: boolean;cause?: NavigationCause;externalSearch?: string;+ path?: string;} = {}) => {const middleware = createAppSplitRouterMiddleware({@@ -202,7 +230,7 @@ describe('legacy pipeline URLs', () => {routes,from: undefined,to,- path: '',+ path: options.path ?? '',cause: options.cause ?? 'navigate',externalSearch: options.externalSearch,signal: new AbortController().signal,@@ -284,4 +312,66 @@ describe('legacy pipeline URLs', () => {})).toBeUndefined();});++ it('opens company and contact links in Customers on desktop', () => {+ expect(run(legacyEntry('company', companyId))).toEqual({+ type: 'redirect',+ to: `/companies/company/${companyId}`,+ });+ // A contact opens from People.+ expect(run(legacyEntry('contact', contactId))).toEqual({+ type: 'redirect',+ to: `/companies/contact/${contactId}?s0.crm.tab=people`,+ });+ });++ it('keeps the Discussion message an in-app contact open carries', () => {+ const entry = legacyEntry('contact', contactId);+ const result = run({+ ...entry,+ location: {+ ...entry.location,+ search: { 'crm-record': { commentId: ['message'], seek: ['s'] } },+ },+ });+ if (result?.type !== 'redirect') throw new Error('Expected a redirect');+ const url = new URL(result.to, window.location.origin);+ expect(url.pathname).toBe(`/companies/contact/${contactId}`);+ expect(url.searchParams.get('s0.crm.tab')).toBe('people');+ expect(url.searchParams.get('s0.crm-record.commentId')).toBe('message');+ expect(url.searchParams.get('s0.crm-record.seek')).toBe('s');+ });++ it('keeps company and contact links on their own pages on touch', () => {+ expect(run(legacyEntry('company', companyId), { touch: true })).toBe(+ undefined+ );+ expect(run(legacyEntry('contact', contactId), { touch: true })).toBe(+ undefined+ );+ });++ it('shows Customers record URLs on their own pages on touch', () => {+ expect(run(recordEntry('company', companyId), { touch: true })).toEqual({+ type: 'redirect',+ to: `/company/${companyId}`,+ });+ expect(+ run(recordEntry('contact', contactId, pipelineId), { touch: true })+ ).toEqual({ type: 'redirect', to: `/contact/${contactId}` });+ expect(run(recordEntry('company', companyId))).toBeUndefined();+ });++ it('carries a linked Discussion message into the record on entry', () => {+ const path = `/companies/company/${companyId}`;+ const result = run(recordEntry('company', companyId), {+ cause: 'external',+ externalSearch: 'comment_id=message',+ path,+ });+ if (result?.type !== 'redirect') throw new Error('Expected a redirect');+ const url = new URL(result.to, window.location.origin);+ expect(url.pathname).toBe(path);+ expect(url.searchParams.get('s0.crm-record.commentId')).toBe('message');+ });});diff --git a/apps/web/src/features/crm/crm-route.ts b/apps/web/src/features/crm/crm-route.tsindex f236c9bcc4..7042e43698 100644--- a/apps/web/src/features/crm/crm-route.ts+++ b/apps/web/src/features/crm/crm-route.ts@@ -24,6 +24,18 @@ export type CrmSearchParams = z.infer<typeof crmSearch.schema>;export const crmSearchCodec = createSearchParamsCodec(crmSearch);+/** The Customers pane search of the People list, where contacts open from. */+export const crmPeopleSearch: SplitSearchState = {+ [crmSearch.namespace]: { tab: ['people'] },+};++/** The Discussion message an open record shows; a new `seek` repeats a request. */+export const crmRecordSearch = {+ namespace: 'crm-record',+ schema: z.object({ commentId: z.string(), seek: z.string() }),+ defaults: { commentId: '', seek: '' },+};+export const crmPipelineParams = z.object({ pipelineId: z.string().min(1) });/** A company or contact opened inside Customers; no section is its Overview. */diff --git a/apps/web/src/features/crm/route-adapter.test.tsx b/apps/web/src/features/crm/route-adapter.test.tsxindex 441f04673b..acf4fedcea 100644--- a/apps/web/src/features/crm/route-adapter.test.tsx+++ b/apps/web/src/features/crm/route-adapter.test.tsx@@ -42,12 +42,15 @@ let route: CrmRoute;function Customers() {route = createCrmRoute();return (- <p data-testid="customers">- {`tab:${route.tab()} section:${route.section() ?? '-'} records:${route- .records()- .map((record) => `${record.type}:${record.id}:${record.name}`)- .join(',')}`}- </p>+ <>+ <p data-testid="customers">+ {`tab:${route.tab()} section:${route.section() ?? '-'} records:${route+ .records()+ .map((record) => `${record.type}:${record.id}:${record.name}`)+ .join(',')}`}+ </p>+ <p data-testid="comment">{route.commentTarget()?.commentId ?? '-'}</p>+ </>);}@@ -192,3 +195,18 @@ it('shows another list in place of an open record', async () => {await shows('tab:active section:- records:company:acme:Acme');expect(url()).toBe('/companies/company/acme');});++it('shows a linked Discussion message only on the record it was asked for', async () => {+ const { url, shows } = renderCustomers(+ '/companies/company/acme?s0.crm-record.commentId=m1&s0.crm-record.seek=s1'+ );+ await shows('tab:active section:- records:company:acme:');+ expect(screen.getByTestId('comment').textContent).toBe('m1');++ route.open([acme, maya]);+ await shows(+ 'tab:active section:- records:company:acme:Acme,contact:maya:Maya'+ );+ expect(screen.getByTestId('comment').textContent).toBe('-');+ expect(url()).toBe('/companies/contact/maya');+});diff --git a/apps/web/src/features/crm/route-adapter.ts b/apps/web/src/features/crm/route-adapter.tsindex 5783680eb3..85839a833a 100644--- a/apps/web/src/features/crm/route-adapter.ts+++ b/apps/web/src/features/crm/route-adapter.ts@@ -16,7 +16,12 @@ import { fireAndForget } from '@core/util/fireAndForget';import type { CrmRoute } from './context/workspace-context';import { pipelineIdOfTab, pipelineTab } from './core/navigation';import type { CrmRecordRef, CrmRecordSection } from './core/record';-import { type CrmRecordParams, crmSearch, crmSearchCodec } from './crm-route';+import {+ type CrmRecordParams,+ crmRecordSearch,+ crmSearch,+ crmSearchCodec,+} from './crm-route';type CrmBranchParams = Partial<CrmRecordParams> & { pipelineId?: string };@@ -35,6 +40,7 @@ function listTab(entry: Entry): string | undefined {/** The Customers location held by the pane's route. */export function createCrmRoute(): CrmRoute {const [search] = createSearchParams(crmSearch);+ const [recordSearch] = createSearchParams(crmRecordSearch);const params = useParams<CrmBranchParams>();const routeTrail = useRouteState(companiesRoute);const navigate = useNavigate();@@ -70,7 +76,12 @@ export function createCrmRoute(): CrmRoute {recordId: record.id,section: section === 'overview' ? undefined : section,};- const options = { allowDuplicate: true, state: [...trail] };+ // A message target belongs to the record it was asked for.+ const options = {+ allowDuplicate: true,+ state: [...trail],+ search: { [crmRecordSearch.namespace]: undefined },+ };const pipelineId = params.pipelineId;fireAndForget(pipelineId@@ -95,6 +106,7 @@ export function createCrmRoute(): CrmRoute {[crmSearch.namespace]: pipelineId? undefined: crmSearchCodec.serialize({ tab: next }),+ [crmRecordSearch.namespace]: undefined,},};fireAndForget(@@ -130,6 +142,10 @@ export function createCrmRoute(): CrmRoute {setTab: (next, options) => showList(next, options?.replace),records,section: () => params.section,+ commentTarget: () =>+ shown() && recordSearch.commentId+ ? { commentId: recordSearch.commentId, seek: recordSearch.seek }+ : undefined,open: (trail) => showRecord(trail, undefined),setSection: (section) => showRecord(records(), section),close,diff --git a/apps/web/src/features/crm/views/crm-workspace.test.tsx b/apps/web/src/features/crm/views/crm-workspace.test.tsxindex f640772274..09bdc7e238 100644--- a/apps/web/src/features/crm/views/crm-workspace.test.tsx+++ b/apps/web/src/features/crm/views/crm-workspace.test.tsx@@ -274,6 +274,7 @@ function setup(initialTab = 'active') {const record = {records,section: () => undefined,+ commentTarget: () => undefined,open: vi.fn(setRecords),setSection: vi.fn(),close: vi.fn(() => setRecords([])),diff --git a/apps/web/src/features/crm/views/crm-workspace.tsx b/apps/web/src/features/crm/views/crm-workspace.tsxindex c8a96032f3..94c6fc8f71 100644--- a/apps/web/src/features/crm/views/crm-workspace.tsx+++ b/apps/web/src/features/crm/views/crm-workspace.tsx@@ -435,6 +435,7 @@ export function CrmWorkspaceView(props: {<CrmRecordDetailrecords={records()}section={view.host.record.section()}+ commentTarget={view.host.record.commentTarget()}viewName={activePipeline()?.name ?? title()}onOpen={view.host.record.open}onSectionChange={view.host.record.setSection}diff --git a/apps/web/src/features/crm/views/record-detail.test.tsx b/apps/web/src/features/crm/views/record-detail.test.tsxindex bff9c84071..6625fc6a73 100644--- a/apps/web/src/features/crm/views/record-detail.test.tsx+++ b/apps/web/src/features/crm/views/record-detail.test.tsx@@ -13,6 +13,7 @@ import {Show,} from 'solid-js';import { afterEach, expect, it, vi } from 'vitest';+import type { CrmCommentTarget } from '../context/workspace-context';import type { CrmContact } from '../core/contact';import type { CrmRecordRef, CrmRecordSection } from '../core/record';import { CrmRecordDetail } from './record-detail';@@ -46,27 +47,43 @@ vi.mock('./use-crm', () => ({}),useContactQuery: () => ({ isSuccess: false, isError: false }),}));-vi.mock('./company-detail', () => ({- Company: (props: { onOpenContact(contact: CrmContact): void }) => (- <button- onClick={() =>- props.onOpenContact({- id: 'contact-1',- companyId: 'company-1',- name: 'Maya',- email: '[email protected]',- hidden: false,- firstInteraction: '',- lastInteraction: '',- createdAt: '',- updatedAt: '',- })- }- >- Open Maya- </button>- ),-}));+vi.mock('@solidjs/router', () => ({ useSearchParams: () => [{}] }));+vi.mock('./company-detail', async () => {+ const { useParamNavigationCount, useUrlParams } = await import(+ '@core/component/ParamsProvider'+ );+ return {+ // Reads its linked message the way the Discussion does.+ Company: (props: { onOpenContact(contact: CrmContact): void }) => {+ const params = useUrlParams({ commentId: 'comment_id' });+ const navigations = useParamNavigationCount('comment_id');+ return (+ <>+ <p data-testid="linked-message">+ {`${params.commentId() ?? '-'}:${navigations()}`}+ </p>+ <button+ onClick={() =>+ props.onOpenContact({+ id: 'contact-1',+ companyId: 'company-1',+ name: 'Maya',+ email: '[email protected]',+ hidden: false,+ firstInteraction: '',+ lastInteraction: '',+ createdAt: '',+ updatedAt: '',+ })+ }+ >+ Open Maya+ </button>+ </>+ );+ },+ };+});vi.mock('./contact-detail', () => ({Contact: (props: {contactId: string;@@ -86,6 +103,7 @@ afterEach(cleanup);function renderDetail(record: CrmRecordRef, viewName: string) {const [records, setRecords] = createSignal<readonly CrmRecordRef[]>([record]);const [section, setSection] = createSignal<CrmRecordSection>();+ const [commentTarget, setCommentTarget] = createSignal<CrmCommentTarget>();const open = (trail: readonly CrmRecordRef[]) =>setRecords(trail.map((entry) => ({ ...entry })));const close = vi.fn(() => setRecords([]));@@ -103,6 +121,7 @@ function renderDetail(record: CrmRecordRef, viewName: string) {<CrmRecordDetailrecords={records()}section={section()}+ commentTarget={commentTarget()}viewName={viewName}onOpen={open}onSectionChange={(next) => {@@ -115,7 +134,7 @@ function renderDetail(record: CrmRecordRef, viewName: string) {</Show></ErrorBoundary>));- return { close, records, failed };+ return { close, records, failed, setCommentTarget };}const crumbs = () =>@@ -174,3 +193,20 @@ it('keeps the shown record mounted while the route only changes its tab', () =>expect(screen.getByText('Contact content: contact-1')).toBe(content);expect(crumbs()).toEqual(['People', 'Maya']);});++it('hands the Discussion each request for a linked message', () => {+ const { setCommentTarget } = renderDetail(+ { type: 'company', id: 'company-1', name: 'Northstar' },+ 'Companies'+ );+ const linked = () => screen.getByTestId('linked-message').textContent;+ expect(linked()).toBe('-:0');+ setCommentTarget({ commentId: 'message-1', seek: 'first' });+ expect(linked()).toBe('message-1:1');+ // The same message asked for again scrolls again.+ setCommentTarget({ commentId: 'message-1', seek: 'second' });+ expect(linked()).toBe('message-1:2');+ // Leaving the target, as another tab of the record does, forgets it.+ setCommentTarget(undefined);+ expect(linked()).toBe('-:2');+});diff --git a/apps/web/src/features/crm/views/record-detail.tsx b/apps/web/src/features/crm/views/record-detail.tsxindex 5b5b52ac70..de484570f3 100644--- a/apps/web/src/features/crm/views/record-detail.tsx+++ b/apps/web/src/features/crm/views/record-detail.tsx@@ -1,20 +1,28 @@import { ViewBreadcrumbs } from '@app/components/view-shell';import { SidePanel } from '@components/app/side-panel';import { EntityIcon } from '@core/component/EntityIcon';+import {+ createParamsState,+ ParamsProvider,+} from '@core/component/ParamsProvider';+import { COMMENT_LINK_PARAM } from '@core/messages/comment-link';import { fireAndForget } from '@core/util/fireAndForget';import SpinnerIcon from '@phosphor/spinner.svg';import { Button, Tooltip } from '@ui';import {+ createEffect,createMemo,ErrorBoundary,For,type JSX,+ on,onMount,Show,Suspense,untrack,} from 'solid-js';import { RecordTabs } from '../components/record-tabs';+import type { CrmCommentTarget } from '../context/workspace-context';import {COMPANY_SECTIONS,CONTACT_SECTIONS,@@ -60,6 +68,7 @@ export function CrmRecordDetail(props: {/** Opened records, oldest first; the last one is shown. */records: readonly CrmRecordRef[];section: CrmRecordSection | undefined;+ commentTarget?: CrmCommentTarget;viewName: string;onOpen: (records: readonly CrmRecordRef[]) => void;onSectionChange: (section: CrmRecordSection) => void;@@ -194,6 +203,7 @@ export function CrmRecordDetail(props: {<RecordContentrecord={record}nested={trail().length > 1}+ commentTarget={props.commentTarget}onBack={back}><Show@@ -239,6 +249,7 @@ export function CrmRecordDetail(props: {function RecordContent(props: {record: CrmRecordRef;nested: boolean;+ commentTarget: CrmCommentTarget | undefined;onBack: () => void;children: JSX.Element;}) {@@ -246,6 +257,23 @@ function RecordContent(props: {props.record.type === 'company'? useCompanyQuery(() => props.record.id).query: useContactQuery(() => props.record.id);+ // The Discussion reads its linked message from these params; each request,+ // a new `seek`, scrolls to it again.+ const params = createParamsState();+ createEffect(+ on(+ () =>+ props.commentTarget &&+ `${props.commentTarget.commentId}:${props.commentTarget.seek}`,+ () => {+ const target = untrack(() => props.commentTarget);+ // Without a target, a remounted Discussion must not show the last one.+ params.navigate(+ target ? { [COMMENT_LINK_PARAM]: target.commentId } : {}+ );+ }+ )+ );const error = (onRetry: () => void) => (<DetailErroronRetry={onRetry}@@ -275,7 +303,7 @@ function RecordContent(props: {</div>}>- {props.children}+ <ParamsProvider state={params}>{props.children}</ParamsProvider></Suspense></Show></ErrorBoundary>diff --git a/apps/web/src/features/notifications/notification-navigation.ts b/apps/web/src/features/notifications/notification-navigation.tsindex 4e9b33573e..1ea5feac31 100644--- a/apps/web/src/features/notifications/notification-navigation.ts+++ b/apps/web/src/features/notifications/notification-navigation.ts@@ -1,5 +1,6 @@import { openCalendarView } from '@app/features/calendar-view/calendar-navigation';import { createCalendarRange } from '@app/features/calendar-view/calendar-range';+import { crmRecordContent } from '@app/features/crm/crm-hosted-content';import {getChannelParams,navigateToChannelMessage,@@ -21,6 +22,7 @@ import {USE_MACRO_PR_SUMMARY_BLOCK,} from '@core/constant/featureFlags';import { COMMENT_LINK_PARAM } from '@core/messages/comment-link';+import { isTouchDevice } from '@core/mobile/isTouchDevice';import type { NotificationType } from '@core/types';import { catchToResult } from '@core/util/result';import { openExternalUrl } from '@core/util/url';@@ -538,13 +540,40 @@ function getSupportedHandler(if (meta.tag !== 'crm_discussion') return null;const blockName =notification.entity_type === 'crm_contact' ? 'contact' : 'company';- return async (lm: SplitManager, newSplit: boolean = false) =>+ return async (lm: SplitManager, newSplit: boolean = false) => {+ // Desktop shows records in Customers, which takes the message from its route.+ if (!isTouchDevice()) {+ let pending = onApplied;+ const reportApplied = () => {+ const callback = pending;+ pending = undefined;+ callback?.();+ };+ const result = lm.openWithSplit(+ crmRecordContent(+ { type: blockName, id: notification.entity_id },+ meta.content.messageId+ ),+ {+ activate: true,+ referredFrom: null,+ preferNewSplit: newSplit,+ handle: sourceHandle,+ allowDuplicate: true,+ ...(onApplied ? { onApplied: reportApplied } : {}),+ }+ );+ if (result.status === 'opened' || result.status === 'reused')+ reportApplied();+ return;+ }openSplitIfNotOpen(lm, blockName, notification.entity_id, {newSplit,params: { [COMMENT_LINK_PARAM]: meta.content.messageId },sourceHandle,onApplied,});+ };}).with('inbox_reauth_required', () => null).exhaustive()diff --git a/apps/web/src/features/notifications/tests/crm-discussion-navigation.test.ts b/apps/web/src/features/notifications/tests/crm-discussion-navigation.test.tsindex 8a967e9373..a0af3dd82e 100644--- a/apps/web/src/features/notifications/tests/crm-discussion-navigation.test.ts+++ b/apps/web/src/features/notifications/tests/crm-discussion-navigation.test.ts@@ -15,9 +15,11 @@ vi.mock('../notification-stacking', () => ({}));import type { SplitManager } from '@components/app/split-layout/layoutManager';-import { expect, it, vi } from 'vitest';+import { afterEach, expect, it, vi } from 'vitest';import type { UnifiedNotification } from '../types';+const fixture = vi.hoisted(() => ({ touch: false }));+vi.mock('@app/features/calendar-view/calendar-range', () => ({createCalendarRange: vi.fn(),}));@@ -38,6 +40,9 @@ vi.mock('@core/constant/featureFlags', () => ({isFeatureEnabled: vi.fn(),USE_MACRO_PR_SUMMARY_BLOCK: true,}));+vi.mock('@core/mobile/isTouchDevice', () => ({+ isTouchDevice: () => fixture.touch,+}));vi.mock('@core/util/url', () => ({ openExternalUrl: vi.fn() }));vi.mock('@queries/notification/user-notifications', () => ({getNotificationById: vi.fn(),@@ -49,34 +54,87 @@ vi.mock('../notification-resolvers', () => ({import { openNotification } from '../notification-navigation';-it.each([+afterEach(() => {+ fixture.touch = false;+});++const records = [['crm_company', 'company'],['crm_contact', 'contact'],-] as const)(- 'opens a %s discussion notification at its message',- async (entityType, blockName) => {- const navigate = vi.fn();- const open = vi.fn();- const layout = {- getSplitByContent: vi.fn(() => undefined as unknown),- openWithSplit: open,- getOrchestrator: () => ({- getBlockHandle: async () => ({ goToLocationFromParams: navigate }),- }),- };- const notification = {- entity_id: 'record',- entity_type: entityType,- notification_metadata: {- tag: 'crm_discussion',- content: { messageId: 'message', threadId: 'root', reason: 'reply' },- },- } as UnifiedNotification;+] as const;++function setup(entityType: (typeof records)[number][0]) {+ const navigate = vi.fn();+ const open = vi.fn(() => ({ status: 'opened' }));+ const layout = {+ getSplitByContent: vi.fn(() => undefined as unknown),+ openWithSplit: open,+ getOrchestrator: () => ({+ getBlockHandle: async () => ({ goToLocationFromParams: navigate }),+ }),+ };+ const notification = {+ entity_id: 'record',+ entity_type: entityType,+ notification_metadata: {+ tag: 'crm_discussion',+ content: { messageId: 'message', threadId: 'root', reason: 'reply' },+ },+ } as UnifiedNotification;+ return {+ navigate,+ open,+ run: () =>+ openNotification(notification, layout as unknown as SplitManager),+ };+}++it.each(records)(+ 'opens a %s discussion notification in Customers at its message on desktop',+ async (entityType, recordType) => {+ const { navigate, open, run } = setup(entityType);++ const result = await run();- const result = await openNotification(- notification,- layout as unknown as SplitManager+ expect(result.isOk()).toBe(true);+ expect(open).toHaveBeenCalledWith(+ {+ type: 'component',+ id: 'companies',+ entryMetadata: {+ route: {+ matches: [+ { id: 'app', params: {} },+ { id: 'view-companies', params: {} },+ {+ id: 'companies-record',+ params: { recordType, recordId: 'record' },+ },+ ],+ },+ search: {+ // A contact opens from People.+ ...(recordType === 'contact' ? { crm: { tab: ['people'] } } : {}),+ 'crm-record': {+ commentId: ['message'],+ seek: [expect.any(String)],+ },+ },+ },+ },+ expect.objectContaining({ allowDuplicate: true }));+ expect(navigate).not.toHaveBeenCalled();+ }+);++it.each(records)(+ 'opens a %s discussion notification on its own page at its message on touch',+ async (entityType, blockName) => {+ fixture.touch = true;+ const { navigate, open, run } = setup(entityType);++ const result = await run();expect(result.isOk()).toBe(true);expect(open).toHaveBeenCalledWith(diff --git a/docs/agent-guide/crm.md b/docs/agent-guide/crm.mdindex 13dc81cfcc..fff0783edd 100644--- a/docs/agent-guide/crm.md+++ b/docs/agent-guide/crm.md@@ -65,8 +65,14 @@ with the same filters and list scroll position, and Forward reopens the record.The top breadcrumb reads `<Companies, People, list or pipeline> > <record>`;click the first segment to return the same way. Selecting another sidebar entryshows that list in place of the details; selecting the record's own list returns-to it. Shift-click still opens the record in a separate split. Direct company and-contact links use the standalone pages.+to it. Shift-click still opens the record in a separate split, also inside+Customers. On desktop, every other way to a company or contact opens it inside+Customers too: `/app/company/<uuid>` and `/app/contact/<uuid>` links (which+**Copy link** still copies), `@` mentions, search and Command-K results,+favorites, and CRM discussion notifications. A contact opens under People, so its+breadcrumb returns to People. A split already showing that record is brought+forward instead. Touch devices keep the standalone pages, and a+Customers record URL opened on touch redirects to its standalone page.Each record opened from the details appends a breadcrumb and a history entry: acontact from a company's Team tab gives `Companies > <company> > <contact>`, anda person's Company link gives `People > <contact> > <company>`. Opening a record@@ -159,9 +165,12 @@ drops out.Company and contact pages have a **Discussion** section built from the samemessage conversation as a document's Discussion: threaded replies, reactions,attachments, and edit/delete from the message menu. `@` suggests the team's-members and agents. A message's copied link is the standalone record URL-with `comment_id`; opening it, or a CRM discussion notification, scrolls to and-highlights that message. Deleting a thread's first comment deletes the thread.+members and agents. A message's copied link is the record URL+`/app/company/<uuid>?comment_id=<message>` (or `/app/contact/…`); opening it, or+a CRM discussion notification, scrolls to and highlights that message. On+desktop the record opens in Customers with the message in the pane search+`sN.crm-record.commentId`, which the next record or list you open drops.+Deleting a thread's first comment deletes the thread.Company selection actions **Set owner** and **Set revenue** remain availablewhile team deal-stage definitions are loading. **Set stage** waits for the activediff --git a/docs/agent-guide/navigation.md b/docs/agent-guide/navigation.mdindex 50b6220a25..fca3b7b71d 100644--- a/docs/agent-guide/navigation.md+++ b/docs/agent-guide/navigation.md@@ -122,7 +122,7 @@ successfully rather than hashing the empty JavaScript placeholder.| `/app/agents/chat/<uuid>` | Legacy AI chat opened in the Agents workspace (`/app/agent-chats/<uuid>` remains a compatibility alias) || `/app/calls` | Calls list || `/app/companies` | Customers (CRM; needs a team). The selected list is `sN.crm.tab` |-| `/app/companies/<company-or-contact>/<uuid>` | Customers with a company or contact opened inline, keeping its list's `sN.crm.tab`; a record tab other than Overview adds `/<team-emails-files-tasks-or-calls>` |+| `/app/companies/<company-or-contact>/<uuid>` | Customers with a company or contact opened inline, keeping its list's `sN.crm.tab`; a record tab other than Overview adds `/<team-emails-files-tasks-or-calls>`. On desktop, `/app/company/<uuid>` and `/app/contact/<uuid>` redirect here, a `comment_id` moving to `sN.crm-record.commentId`; touch devices keep those standalone pages || `/app/companies/pipeline/<uuid>` | Customers on a pipeline; `/<company-or-contact>/<uuid>` after it opens a record from the pipeline. `/app/pipeline/<uuid>` redirects here || `/app/activity` | Activity heatmap + feed || `/app/calendar/<month-or-week-or-day>` | Calendar; the focused event, its occurrence, and the locator range use `sN.calendar.*` |