Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
fix(crm): sync Customers tab state with URL search and history (#8077)
teo56a7b9d75471
diff --git a/apps/web/src/features/crm/context/workspace-context.tsx b/apps/web/src/features/crm/context/workspace-context.tsxindex ce0ed66879..794e81c2b5 100644--- a/apps/web/src/features/crm/context/workspace-context.tsx+++ b/apps/web/src/features/crm/context/workspace-context.tsx@@ -9,6 +9,14 @@ import type { EntityActionListState } from '../../next-soup/actions/entity-actioimport type { SoupState } from '../../next-soup/create-soup-state';import type { QueryStore } from '../../next-soup/filters/filter-store/query-store';+export type CrmRouteSearch = {+ tab: Accessor<string>;+ setTab(+ tab: string,+ options?: { replace?: boolean; clearPipelineRequest?: boolean }+ ): void;+};+/** A pipeline another view asked the workspace to show. */export type CrmPipelineRequest = {/** A new `seek` repeats a request for the same pipeline. */diff --git a/apps/web/src/features/crm/crm-route.test.ts b/apps/web/src/features/crm/crm-route.test.tsindex 5c954721f1..1cc8d725fe 100644--- a/apps/web/src/features/crm/crm-route.test.ts+++ b/apps/web/src/features/crm/crm-route.test.ts@@ -15,6 +15,7 @@ import { createMacroMentionLinkResolver } from '@components/app/split-layout/splimport { describe, expect, it, vi } from 'vitest';import { pipelineTab } from './core/navigation';import type { CrmViewConfig } from './core/saved-view';+import { crmSearchCodec } from './crm-route';import { encodeCrmViewParam } from './queries/saved-view-codec';vi.mock('@components/app/split-layout/componentRegistry', () => ({@@ -46,6 +47,27 @@ const resolveMention = createMacroMentionLinkResolver(routes);const crmViewLink = (view: CrmViewConfig) =>`${window.location.origin}/app/companies?crmView=${encodeCrmViewParam(view)}`;+describe('crm tab search params', () => {+ it.each([+ 'active',+ 'people',+ 'hidden',+ pipelineTab(pipelineId),+ 'list:favorites',+ ])('keeps the %s tab through the URL', (tab) => {+ const params = crmSearchCodec.serialize({ tab, pipeline: '', seek: '' });+ if (tab === 'active') {+ expect(params).toBeUndefined();+ } else {+ expect(params).toEqual({ tab: [tab] });+ }+ expect(crmSearchCodec.parse(params)).toEqual({+ value: { tab, pipeline: '', seek: '' },+ valid: true,+ });+ });+});+describe('pipeline links', () => {it('pastes a copied pipeline link as a mention of the pipeline', () => {expect(@@ -55,12 +77,26 @@ describe('pipeline links', () => {).toEqual({ id: pipelineId, block: 'pipeline', params: {} });});+ it.each(['s0.crm.tab', 'crm.tab'])(+ 'pastes a Customers link with %s as a mention of the pipeline',+ (key) => {+ expect(+ resolveMention(+ `${window.location.origin}/app/companies?${key}=${pipelineTab(pipelineId)}`+ )+ ).toEqual({ id: pipelineId, block: 'pipeline', params: {} });+ }+ );+it.each([crmViewLink({ kind: 'crm', activeTab: 'active' }),crmViewLink({ kind: 'crm', activeTab: 'list:favorites' }),crmViewLink({ kind: 'crm', activeTab: pipelineTab('not-a-uuid') }),`${window.location.origin}/app/companies?crmView=garbage`,`${window.location.origin}/app/companies`,+ `${window.location.origin}/app/companies?s0.crm.tab=people`,+ `${window.location.origin}/app/companies?s0.crm.tab=${pipelineTab('not-a-uuid')}`,+ `${window.location.origin}/app/companies?crmView=${encodeCrmViewParam({ kind: 'crm', activeTab: 'active' })}&s0.crm.tab=${pipelineTab(pipelineId)}`,])('leaves other Customers links as links: %s', (url) => {expect(resolveMention(url)).toBeUndefined();});@@ -98,6 +134,9 @@ describe('pipeline links', () => {const first = open();expect(first.pathname).toBe('/companies');+ expect(first.searchParams.get('s0.crm.tab')).toBe(+ pipelineTab(pipelineId)+ );expect(first.searchParams.get('s0.crm.pipeline')).toBe(pipelineId);// Opening the same pipeline again is a new request.expect(open().searchParams.get('s0.crm.seek')).not.toBe(diff --git a/apps/web/src/features/crm/crm-route.ts b/apps/web/src/features/crm/crm-route.tsindex 5699779326..946b78b05f 100644--- a/apps/web/src/features/crm/crm-route.ts+++ b/apps/web/src/features/crm/crm-route.ts@@ -5,39 +5,56 @@ import {} from '@app/lib/split-router';import { uuidRouteReference } from '@components/app/split-layout/split-router/mention-links';import { z } from 'zod';-import { pipelineIdOfTab } from './core/navigation';+import { pipelineIdOfTab, pipelineTab } from './core/navigation';import {CRM_VIEW_URL_PARAM,decodeCrmViewParam,} from './queries/saved-view-codec';-/** A pipeline another view asked Customers to show; a new `seek` repeats the request. */+/** Customers pane search. `tab` is the open view. A new `seek` repeats a pipeline request. */export const crmSearch = {namespace: 'crm',- schema: z.object({ pipeline: z.string(), seek: z.string() }),- defaults: { pipeline: '', seek: '' },+ schema: z.object({+ tab: z.string(),+ pipeline: z.string(),+ seek: z.string(),+ }),+ defaults: { tab: 'active', pipeline: '', seek: '' },};-const crmSearchCodec = createSearchParamsCodec(crmSearch);+export type CrmSearchParams = z.infer<typeof crmSearch.schema>;++export const crmSearchCodec = createSearchParamsCodec(crmSearch);/** The Customers pane search that opens it on `pipelineId`. */export function crmPipelineSearch(pipelineId: string): SplitSearchState {return {[crmSearch.namespace]:crmSearchCodec.serialize({+ tab: pipelineTab(pipelineId),pipeline: pipelineId,seek: crypto.randomUUID(),}) ?? {},};}+function crmTabFromQuery(query: URLSearchParams): string | undefined {+ const view = query.get(CRM_VIEW_URL_PARAM);+ if (view) return decodeCrmViewParam(view)?.activeTab;+ for (const [key, value] of query) {+ if (key === 'crm.tab' || key.endsWith('.crm.tab')) return value;+ }+ return undefined;+}+/** A shared Customers link that shows a pipeline references the pipeline. */export function crmViewReference(query: URLSearchParams): SplitReference | undefined {- const view = query.get(CRM_VIEW_URL_PARAM);- const tab = view ? decodeCrmViewParam(view)?.activeTab : undefined;- const reference = uuidRouteReference(pipelineIdOfTab(tab), 'pipeline');+ const reference = uuidRouteReference(+ pipelineIdOfTab(crmTabFromQuery(query)),+ 'pipeline'+ );// The rest of the shared view state is no place within the pipeline.return reference && { ...reference, params: {} };}diff --git a/apps/web/src/features/crm/crm.tsx b/apps/web/src/features/crm/crm.tsxindex 0a5f259084..acbc67a51c 100644--- a/apps/web/src/features/crm/crm.tsx+++ b/apps/web/src/features/crm/crm.tsx@@ -4,6 +4,7 @@ import { ViewTour } from '../tours/ViewTour';import { CrmProvider } from './context/crm-context';import {type CrmPipelineRequest,+ type CrmRouteSearch,CrmWorkspaceProvider,} from './context/workspace-context';import type { CrmViewConfig } from './core/saved-view';@@ -16,19 +17,23 @@ import { createCrmWorkspace } from './workspace-adapter';export function Crm(props: {initialView?: CrmViewConfig;pipelineRequest?: CrmPipelineRequest;+ routeSearch?: CrmRouteSearch;}) {const crm = createAppCrmContext();const workspace = createCrmWorkspace(crm,props.initialView,- props.pipelineRequest+ props.pipelineRequest,+ props.routeSearch);return (<CrmProvider value={crm}><SoupViewStateProvider state={workspace.state}><CrmWorkspaceProvider value={workspace.context}><Show when={workspace.applyDefaultCrmView}>- <CrmDefaultViewLoader />+ <CrmDefaultViewLoader+ withReplaceHistory={workspace.withReplaceHistory}+ /></Show><Companies /><ViewTour tour={companiesTour} />diff --git a/apps/web/src/features/crm/route-views.tsx b/apps/web/src/features/crm/route-views.tsxindex d499b4b530..16579d7c5c 100644--- a/apps/web/src/features/crm/route-views.tsx+++ b/apps/web/src/features/crm/route-views.tsx@@ -6,7 +6,8 @@ import {} from '@components/app/split-layout/split-router/app-route-shell';import { enableCrm, isFeatureEnabled } from '@core/constant/featureFlags';import { lazy, untrack } from 'solid-js';-import { pipelineTab } from './core/navigation';+import type { CrmRouteSearch } from './context/workspace-context';+import { pipelineIdOfTab, pipelineTab } from './core/navigation';import { crmSearch } from './crm-route';import {CRM_VIEW_URL_PARAM,@@ -30,6 +31,28 @@ export const CompaniesRouteView = withAuth(() => {const crmView = new URLSearchParams(window.location.search).get(CRM_VIEW_URL_PARAM);+ const routeSearch: CrmRouteSearch = {+ tab: () => search.tab,+ setTab: (+ tab: string,+ options?: { replace?: boolean; clearPipelineRequest?: boolean }+ ) => {+ const nextTab = tab || 'active';+ const clearRequest =+ options?.clearPipelineRequest ||+ (untrack(() => search.pipeline) !== '' &&+ pipelineIdOfTab(nextTab) !== untrack(() => search.pipeline));+ setSearch(+ clearRequest+ ? { tab: nextTab, pipeline: '', seek: '' }+ : { tab: nextTab },+ {+ mode: 'merge',+ history: options?.replace ? 'replace' : 'push',+ }+ );+ },+ };return (<CrminitialView={@@ -41,8 +64,13 @@ export const CompaniesRouteView = withAuth(() => {}pipelineRequest={{current: pipelineRequest,- release: () => setSearch({}, { mode: 'replace', history: 'replace' }),+ release: () =>+ setSearch(+ { pipeline: '', seek: '' },+ { mode: 'merge', history: 'replace' }+ ),}}+ routeSearch={routeSearch}/>);});diff --git a/apps/web/src/features/crm/views/crm-workspace.test.tsx b/apps/web/src/features/crm/views/crm-workspace.test.tsxindex 9b22cacccb..3e4bfb9d68 100644--- a/apps/web/src/features/crm/views/crm-workspace.test.tsx+++ b/apps/web/src/features/crm/views/crm-workspace.test.tsx@@ -5,7 +5,7 @@ import {screen,within,} from '@solidjs/testing-library';-import { createSignal, type JSX, type ParentProps } from 'solid-js';+import { createSignal, For, type JSX, type ParentProps } from 'solid-js';import { afterEach, expect, it, vi } from 'vitest';import { CrmWorkspaceView } from './crm-workspace';@@ -20,7 +20,7 @@ const fixture = vi.hoisted(() => ({vi.mock('@app/components/view-shell', () => ({ViewShell: {Root: (props: ParentProps) => props.children,- Aside: () => null,+ Aside: (props: ParentProps) => props.children,Main: (props: ParentProps) => props.children,Header: (props: ParentProps) => <header>{props.children}</header>,},@@ -108,9 +108,35 @@ vi.mock(vi.mock('../components/company-list-dialog', () => ({CrmListDialog: () => null,}));-vi.mock('../components/crm-sidebar', () => ({ CrmSidebar: () => null }));+vi.mock('../components/crm-sidebar', () => ({+ CrmSidebar: (props: {+ pipelines?: JSX.Element;+ onNavigate: (id: string) => void;+ }) => (+ <nav aria-label="CRM sidebar">+ <button type="button" onClick={() => props.onNavigate('active')}>+ Companies+ </button>+ <button type="button" onClick={() => props.onNavigate('people')}>+ People+ </button>+ {props.pipelines}+ </nav>+ ),+}));vi.mock('../components/pipeline-sidebar', () => ({- PipelineSidebar: () => null,+ PipelineSidebar: (props: {+ pipelines: { id: string; name: string }[];+ onSelect: (id: string) => void;+ }) => (+ <For each={props.pipelines}>+ {(pipeline) => (+ <button type="button" onClick={() => props.onSelect(pipeline.id)}>+ {pipeline.name}+ </button>+ )}+ </For>+ ),}));vi.mock('../components/pipeline-dialog', () => ({PipelineDialog: () => null,@@ -212,12 +238,12 @@ function setup(initialTab = 'active') {pipelineRequest,},source: {},- queryFilters: { state: { include: {} } },+ queryFilters: { state: { include: {} }, replace: vi.fn() },};render(() => (<CrmWorkspaceView>{() => <div>Record list</div>}</CrmWorkspaceView>));- return { activeTab, setPipelineRequest };+ return { activeTab, setActiveTab, setPipelineRequest };}it('keeps sidebar destinations in the mobile header when switching records, pipelines and lists', () => {@@ -287,3 +313,13 @@ it('opens the company of a pipeline row in its own split on touch', () => {);expect(screen.getByText('Sales table')).toBeTruthy();});++it('closes an open record when activeTab changes via history navigation', () => {+ fixture.touch = false;+ const { setActiveTab } = setup('pipeline:sales');+ fireEvent.click(screen.getByRole('button', { name: 'Open Acme' }));+ expect(screen.getByText('Sales record company:acme')).toBeTruthy();+ setActiveTab('people');+ expect(screen.queryByText(/record company:acme/)).toBeNull();+ expect(screen.getByText('Record list')).toBeTruthy();+});diff --git a/apps/web/src/features/crm/views/crm-workspace.tsx b/apps/web/src/features/crm/views/crm-workspace.tsxindex fc8cfcb3e9..7ee1a04c33 100644--- a/apps/web/src/features/crm/views/crm-workspace.tsx+++ b/apps/web/src/features/crm/views/crm-workspace.tsx@@ -211,6 +211,16 @@ export function CrmWorkspaceView(props: {const { openWithSplit } = useCrmContext().createNavigation();const [selectedRecord, setSelectedRecord] = createSignal<CrmRecordRef>();const closeRecord = () => setSelectedRecord(undefined);+ // Back and Forward change the tab without going through sidebar navigation.+ createEffect(+ on(+ view.activeTab,+ () => {+ closeRecord();+ },+ { defer: true }+ )+ );const showRecord = (record: CrmRecordRef) => {view.host.captureEntryState();setSelectedRecord(record);@@ -282,6 +292,27 @@ export function CrmWorkspaceView(props: {const [exporting, setExporting] = createSignal(false);const activeList = () =>lists.lists().find((list) => `list:${list.id}` === active());+ // A list tab from the URL has no preset, so apply its company filter once the list loads.+ createEffect(() => {+ const list = activeList();+ if (!list) return;+ const expected = list.config.companyIds.length+ ? list.config.companyIds+ : [NIL_UUID];+ const current = view.queryFilters.state.include.crmCompanyId;+ if (+ current?.length === expected.length &&+ current.every((id, index) => id === expected[index])+ )+ return;+ const preset = getViewPreset('companies');+ const filters = structuredClone(preset?.filters ?? {});+ filters.include = {+ ...filters.include,+ crmCompanyId: expected,+ };+ view.queryFilters.replace(filters);+ });// Every other tab (hidden companies, saved or shared views) is a company view.const activeRecord = () => {const id = pipelineId();diff --git a/apps/web/src/features/crm/views/default-view.tsx b/apps/web/src/features/crm/views/default-view.tsxindex 32b4d69905..fbcd3b7718 100644--- a/apps/web/src/features/crm/views/default-view.tsx+++ b/apps/web/src/features/crm/views/default-view.tsx@@ -10,7 +10,9 @@ import { usePersonalCrmViews, useTeamCrmViews } from './use-crm';* state. One-shot: later refetches never re-apply, so a default set while* the view is open doesn't yank the user's state out from under them.*/-export function CrmDefaultViewLoader() {+export function CrmDefaultViewLoader(props: {+ withReplaceHistory(apply: () => void): void;+}) {const personal = usePersonalCrmViews();const team = useTeamCrmViews();const applyView = useApplyCrmView();@@ -20,7 +22,7 @@ export function CrmDefaultViewLoader() {teamLoading: team.isLoading,personal: () => personal.defaultView()?.config,team: () => team.defaultView()?.config as CrmViewConfig | undefined,- apply: applyView,+ apply: (config) => props.withReplaceHistory(() => applyView(config)),});return null;diff --git a/apps/web/src/features/crm/workspace-adapter.tsx b/apps/web/src/features/crm/workspace-adapter.tsxindex bca270664d..87cab08460 100644--- a/apps/web/src/features/crm/workspace-adapter.tsx+++ b/apps/web/src/features/crm/workspace-adapter.tsx@@ -20,6 +20,7 @@ import type { CrmContext } from './context/crm-context';import type { DealStages } from './context/crm-sources';import type {CrmPipelineRequest,+ CrmRouteSearch,CrmWorkspace,} from './context/workspace-context';import { pipelineIdOfTab } from './core/navigation';@@ -38,10 +39,44 @@ function stageFilterResolvers(stages: DealStages) {};}+function resolveInitialGroupBy(+ initialCrmView: CrmViewConfig | undefined,+ persistedGroupBy: string | null | undefined,+ fallbackPreset: ReturnType<typeof getViewPreset>+) {+ if (initialCrmView) return initialCrmView.groupBy ?? undefined;+ if (persistedGroupBy != null) return persistedGroupBy;+ return fallbackPreset?.groupBy;+}++function applySharedSubFilters(+ initialCrmView: CrmViewConfig,+ soupView: {+ setStageFilter(stages: string[]): void;+ setOwnerFilter(owners: string[]): void;+ },+ predicates: {+ isActive(id: string): boolean;+ toggle(input: { and: string[] }): void;+ }+) {+ const stages = initialCrmView.stageFilter ?? [];+ soupView.setStageFilter(stages);+ if (stages.length > 0 !== predicates.isActive('company-stage')) {+ predicates.toggle({ and: ['company-stage'] });+ }+ const owners = initialCrmView.ownerFilter ?? [];+ soupView.setOwnerFilter(owners);+ if (owners.length > 0 !== predicates.isActive('company-owner')) {+ predicates.toggle({ and: ['company-owner'] });+ }+}+export function createCrmWorkspace(crm: CrmContext,sharedView?: CrmViewConfig,- pipelineRequest?: CrmPipelineRequest+ pipelineRequest?: CrmPipelineRequest,+ routeSearch?: CrmRouteSearch) {const soup = useSoup();const panel = useSplitPanelOrThrow();@@ -83,6 +118,14 @@ export function createCrmWorkspace(});const soupView = { ...state.context, ...filters.state };const preset = getViewPreset('companies');+ const initialUrlTab = untrack(() => {+ const tab = routeSearch?.tab();+ return tab && tab !== VIEW_TAB_PRESETS.companies.default ? tab : undefined;+ });+ const initialTabPreset =+ initialUrlTab && initialUrlTab in VIEW_TAB_PRESETS.companies.tabs+ ? getViewPreset('companies', initialUrlTab)+ : undefined;const entryState = panel.handle.currentEntryState();const persistedFilters = entryState?.['search.filters'] as Query | undefined;@@ -110,14 +153,30 @@ export function createCrmWorkspace();const initialCrmView = sharedView;- // A default saved view only applies to a fresh Customers entry: restored- // (back/forward) entries keep what the user was looking at, and share- // links carry their own state.+ // A default saved view only applies to a fresh Customers entry. Restored+ // entries, share links, and an explicit URL tab keep their own state.const applyDefaultCrmView =initialCrmView === undefined &&+ initialUrlTab === undefined &&persistedFilters === undefined &&persistedPredicates === undefined;+ const fallbackPreset = initialTabPreset ?? preset;+ const defaultTab = VIEW_TAB_PRESETS.companies.default;+ const rememberedTab = routeSearch+ ? defaultTab+ : (soupView.getPersistedActiveTab('companies') ?? defaultTab);+ const initialActiveTab =+ initialCrmView?.activeTab ??+ initialUrlTab ??+ persistedActiveTab ??+ rememberedTab;+ const initialGroupBy = resolveInitialGroupBy(+ initialCrmView,+ persistedGroupBy,+ fallbackPreset+ );+// Restore before child controls mount; shared links take precedence over storage.let init = false;createRenderEffect(() => {@@ -127,61 +186,63 @@ export function createCrmWorkspace(soupView.initialize({initialQuery: initialCrmView? (initialCrmView.filters as Query | undefined)- : (persistedFilters ?? preset?.filters),+ : (persistedFilters ?? fallbackPreset?.filters),initialClientFilters: initialCrmView? (initialCrmView.clientFilters ?? {})- : (persistedPredicates ?? preset?.clientFilters),+ : (persistedPredicates ?? fallbackPreset?.clientFilters),initialSearchText: initialCrmView? (initialCrmView.searchText ?? ''): persistedSearchText,- preferInitialFilters: initialCrmView !== undefined,+ preferInitialFilters:+ initialCrmView !== undefined || initialTabPreset !== undefined,});- // `groupBy: null` in a shared view records an explicit "no grouping",- // which the grouping store expresses as `undefined`.- const initialGroupBy = initialCrmView- ? (initialCrmView.groupBy ?? undefined)- : (persistedGroupBy ?? preset?.groupBy);-- let initialSortIds = initialCrmView?.sort ?? sortPref();- if (initialSortIds.length === 0) {- initialSortIds = ['updated_at'];- }-- const initialActiveTab =- initialCrmView?.activeTab ??- persistedActiveTab ??- soupView.getPersistedActiveTab('companies') ??- VIEW_TAB_PRESETS.companies.default;+ const sortIds = initialCrmView?.sort ?? sortPref();+ const initialSortIds = sortIds.length > 0 ? sortIds : ['updated_at'];soup.grouping.setActiveGroupId(initialGroupBy);soup.grouping.collapseAll(persistedCollapsedGroups ?? []);-soup.sort.setAll(initialSortIds as Parameters<typeof soup.sort.setAll>[0]);soupView.setActiveTab(initialActiveTab);+ if (routeSearch && initialActiveTab !== untrack(routeSearch.tab)) {+ routeSearch.setTab(initialActiveTab, { replace: true });+ }if (initialCrmView) {- // Stage/owner sub-filters ride separate signals plus a client- // predicate that must be active iff the selection is non-empty- // (same rule as handleStageChange/handleOwnerChange in- // unified-filter-dropdown).- const stages = initialCrmView.stageFilter ?? [];- soupView.setStageFilter(stages);- if (stages.length > 0 !== soup.predicates.isActive('company-stage')) {- soup.predicates.toggle({ and: ['company-stage'] });- }- const owners = initialCrmView.ownerFilter ?? [];- soupView.setOwnerFilter(owners);- if (owners.length > 0 !== soup.predicates.isActive('company-owner')) {- soup.predicates.toggle({ and: ['company-owner'] });- }+ applySharedSubFilters(initialCrmView, soupView, soup.predicates);}});});+ if (routeSearch) {+ createEffect(+ on(+ routeSearch.tab,+ (urlTab) => {+ const target = urlTab || VIEW_TAB_PRESETS.companies.default;+ const current =+ untrack(soupView.activeTab) ?? VIEW_TAB_PRESETS.companies.default;+ if (target === current) return;+ batch(() => {+ soupView.setActiveTab(target);+ if (target in VIEW_TAB_PRESETS.companies.tabs) {+ const tabPreset = getViewPreset('companies', target);+ if (tabPreset) {+ soupView.queryFilters.replace(tabPreset.filters);+ soup.predicates.set(tabPreset.clientFilters);+ soup.grouping.setActiveGroupId(tabPreset.groupBy);+ }+ }+ });+ },+ { defer: true }+ )+ );+ }+createEffect(() => {panel.handle.setDisplayName('Customers');});@@ -209,9 +270,43 @@ export function createCrmWorkspace());+ let replaceNextTab = false;+ const withReplaceHistory = (apply: () => void) => {+ replaceNextTab = true;+ try {+ apply();+ } finally {+ replaceNextTab = false;+ }+ };+ const setActiveTab = (+ next?: string | ((prev: string | undefined) => string | undefined)+ ) => {+ const previous =+ untrack(soupView.activeTab) ?? VIEW_TAB_PRESETS.companies.default;+ const resolved = soupView.setActiveTab(next);+ const target =+ (typeof next === 'function' ? resolved : next) ??+ VIEW_TAB_PRESETS.companies.default;+ if (routeSearch && target !== untrack(routeSearch.tab)) {+ const request = untrack(() => pipelineRequest?.current());+ routeSearch.setTab(target, {+ replace: replaceNextTab || target === previous,+ clearPipelineRequest:+ request !== undefined &&+ pipelineIdOfTab(target) !== request.pipelineId,+ });+ }+ return resolved;+ };+ // Setter<string | undefined> has a zero-argument overload a wrapper cannot match.+ const wrappedSetActiveTab = setActiveTab as CrmWorkspace['setActiveTab'];+ state.context.setActiveTab = wrappedSetActiveTab;+const { openSettings } = useSettingsState();const context: CrmWorkspace = {...soupView,+ setActiveTab: wrappedSetActiveTab,host: {scopeId: panel.splitHotkeyScope,isActive: panel.isPanelActive,@@ -229,5 +324,5 @@ export function createCrmWorkspace(pipelineRequest: () => pipelineRequest?.current(),},};- return { state, context, applyDefaultCrmView };+ return { state, context, applyDefaultCrmView, withReplaceHistory };}diff --git a/docs/AGENT_GUIDE/navigation.md b/docs/AGENT_GUIDE/navigation.mdindex aade350ad1..629283d323 100644--- a/docs/AGENT_GUIDE/navigation.md+++ b/docs/AGENT_GUIDE/navigation.md@@ -118,7 +118,7 @@ successfully rather than hashing the empty JavaScript placeholder.| `/app/coders/<uuid>` | Code session with the Agents sidebar || `/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) |+| `/app/companies` | Customers (CRM; needs a team). The selected tab is `sN.crm.tab` || `/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.*` || `/app/<document-type>/<uuid>` | Legacy document URL (including `md`, `pdf`, `canvas`, `spreadsheet`, and the other Drive document types); redirects to `/app/drive/<document-type>/<uuid>` |@@ -194,13 +194,15 @@ while retaining the theme hue. Public variable-length routes use(`/app/drive/folder/<uuid>/~/mail`). Legacy fixed `type/id`pane routes remain accepted. Known app-view URLs under `/app/component/` redirectto their canonical paths above; legacy composers keep their existing paths. Split-specific view state uses positionally-namespaced query parameters such as `s0.drive.sort=created_at`; route identity-and breadcrumb nesting remain in the path. Home, Email, Tasks, and Channels-store the selected tab under `sN.home.tab`, `sN.mail.tab`, `sN.tasks.tab`,-and `sN.channels.tab`, respectively. Channels also stores the phone list-selection as `sN.channels.mobileTab`. Omitted tab keys mean each view's default;-changing tabs updates the URL, and browser Back/Forward restores the selection-independently in each pane. Inline detail links preserve these keys. Desktop panes expose Close when available and omit+namespaced query parameters such as `s0.drive.sort=created_at`. Route identity+and breadcrumb nesting remain in the path. Home, Email, Tasks, Channels, and+Customers store the selected tab under `sN.home.tab`, `sN.mail.tab`,+`sN.tasks.tab`, `sN.channels.tab`, and `sN.crm.tab`. Customers uses `people`,+`pipeline:<uuid>`, `list:<uuid>`, or `hidden`. Companies is the default and+omits the key. Channels also stores the phone list selection as+`sN.channels.mobileTab`. Omitted tab keys mean each view's default.+Changing tabs updates the URL, and browser Back and Forward restore the+selection independently in each pane. Inline detail links preserve these keys. Desktop panes expose Close when available and omitsplit-history back/forward buttons. Mobile content panes retain their back button.Projects are enabled by default in development; production uses the PostHogdiff --git a/docs/AGENT_GUIDE/surfaces.md b/docs/AGENT_GUIDE/surfaces.mdindex 333d2b8ec5..3feee98bdb 100644--- a/docs/AGENT_GUIDE/surfaces.md+++ b/docs/AGENT_GUIDE/surfaces.md@@ -2001,10 +2001,16 @@ On desktop, the local sidebar uses the same navigation primitives as Email and TIts **New** menu creates a **Company**, a **Contact**, or a **Pipeline** (Pipelineonly when pipelines are enabled; disabled until the team's CRM is enabled). The**Records** section lists **Companies** and **People**; Pipelines and Lists follow.-There are no built-in company views or Board/List layout: Companies and People+There are no built-in company views or Board/List layout. Companies and Peopleare plain soup lists with the shared pagination. Existing personal/team savedviews stay in the toolbar's Views menu.+The selected Customers tab is stored on the pane as `sN.crm.tab`. People uses+`people`, a pipeline uses `pipeline:<uuid>`, a list uses `list:<uuid>`, and+hidden companies use `hidden`. Companies is the default and omits the key.+Choosing Companies, People, a pipeline, or a list updates that parameter.+Browser Back and Forward restore the tab and close an open record.+Companies lists every visible company, grouped by Stage by default, with Owner,Revenue and Last Interaction columns. A Stage column is off by default; turn iton, or hide Owner or Revenue, under **Display options**. Its toolbar holds