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): companies & contacts frontend behind ENABLE_CRM flag (#3898)
Evan Hutnik15b063999878
diff --git a/js/app/packages/app/component/PreviewPanel.tsx b/js/app/packages/app/component/PreviewPanel.tsxindex 51a898732b..eef76f657a 100644--- a/js/app/packages/app/component/PreviewPanel.tsx+++ b/js/app/packages/app/component/PreviewPanel.tsx@@ -82,6 +82,12 @@ const PreviewPanelContent: Component<NonNullableFields<PreviewPanel>> = (// TODO(dev-rb/github): Preview GitHub PRs with /pr.blockType = 'unknown';blockId = props.selectedEntity.id;+ } else if (props.selectedEntity.type === 'crm_company') {+ blockType = 'company';+ blockId = props.selectedEntity.id;+ } else if (props.selectedEntity.type === 'crm_contact') {+ blockType = 'contact';+ blockId = props.selectedEntity.id;} else {blockType = props.selectedEntity.type;blockId = props.selectedEntity.id;diff --git a/js/app/packages/app/component/Root.tsx b/js/app/packages/app/component/Root.tsxindex 54ff0b3cf0..ca156a020c 100644--- a/js/app/packages/app/component/Root.tsx+++ b/js/app/packages/app/component/Root.tsx@@ -284,6 +284,10 @@ const ROUTES: RouteDefinition[] = [path: '/calls',component: LAYOUT_ROUTE.component,},+ {+ path: '/companies',+ component: LAYOUT_ROUTE.component,+ },{path: '/files',component: LAYOUT_ROUTE.component,diff --git a/js/app/packages/app/component/app-sidebar/sidebar.tsx b/js/app/packages/app/component/app-sidebar/sidebar.tsxindex f08f2262cb..6dae1f332d 100644--- a/js/app/packages/app/component/app-sidebar/sidebar.tsx+++ b/js/app/packages/app/component/app-sidebar/sidebar.tsx@@ -37,6 +37,7 @@ import {DEV_MODE_ENV,ENABLE_APP_STORE_QR_CODE,ENABLE_CALLS,+ ENABLE_CRM,ENABLE_HOME_OVERRIDE,ENABLE_NEW_PRICING_OVERRIDE,ENABLE_TEAMS_OVERRIDE,@@ -58,6 +59,7 @@ import { AnimatedSquareCommandKIcon } from '@icon/square-command-k';import { AnimatedSquareSidebarIcon } from '@icon/square-sidebar';import { AnimatedCallIcon } from '@icon/wide-call';import { AnimatedChannelIcon } from '@icon/wide-channel';+import { AnimatedCompanyIcon } from '@icon/wide-company';import { AnimatedEmailIcon } from '@icon/wide-email';import { AnimatedFileMdIcon } from '@icon/wide-fileMd';import { AnimatedInboxIcon } from '@icon/wide-inbox';@@ -164,6 +166,18 @@ const SIDEBAR_LINKS = [hotkey: 'c',hotkeyToken: TOKENS.sidebar.goTo.channels,},+ ...(ENABLE_CRM+ ? ([+ {+ id: 'companies',+ label: 'Companies',+ href: LIST_VIEW_PATHS.companies,+ icon: AnimatedCompanyIcon,+ hotkey: 'o',+ hotkeyToken: TOKENS.sidebar.goTo.companies,+ },+ ] satisfies SidebarItem[])+ : []),] satisfies SidebarItem[];export type SidebarState = 'hidden' | 'expanded' | 'slim';diff --git a/js/app/packages/app/component/app-sidebar/soup-filter-presets.ts b/js/app/packages/app/component/app-sidebar/soup-filter-presets.tsindex ba74966f23..adc8f02a6c 100644--- a/js/app/packages/app/component/app-sidebar/soup-filter-presets.ts+++ b/js/app/packages/app/component/app-sidebar/soup-filter-presets.ts@@ -5,7 +5,10 @@ import {type Query,} from '@app/component/next-soup/filters/filter-store';import type { ListView } from '@app/constants/list-views';-import { ENABLE_SUPPORTED_SOUP_FOREIGN_ENTITIES_OVERRIDE } from '@core/constant/featureFlags';+import {+ ENABLE_CRM,+ ENABLE_SUPPORTED_SOUP_FOREIGN_ENTITIES_OVERRIDE,+} from '@core/constant/featureFlags';import { PROPERTY_OPTION_IDS, SYSTEM_PROPERTY_IDS } from '@property/constants';import { startOfDay, subWeeks } from 'date-fns';@@ -26,6 +29,9 @@ type SoupFiltersPreset = {export type PresetContext = {userId: string | undefined;email: string | undefined;+ /** True iff the current user has admin/owner team role. Drives+ * visibility of admin-only tabs (e.g. companies → hidden). */+ isTeamAdmin: boolean;};type TabPresetResolver = (ctx: PresetContext) => SoupFiltersPreset | undefined;@@ -86,6 +92,8 @@ export const VIEW_TAB_PRESETS: Record<ListView, ViewTabConfig> = {}),all: () => ({filters: {+ // crm companies aren't surfaced outside the Companies view.+ include: { crmCompanyId: [NIL_UUID] },exclude: {documentId: [NIL_UUID],threadId: [NIL_UUID],@@ -361,6 +369,31 @@ export const VIEW_TAB_PRESETS: Record<ListView, ViewTabConfig> = {}),},},+ companies: {+ default: 'active',+ tabs: {+ active: () => ({+ filters: defineQueryFilters(+ { include: { crmCompanyHidden: false } },+ { skipTargets: ['ccf'] }+ ),+ clientFilters: { and: ['crm-company-active'] },+ }),+ // Admin/owner only — the BE rejects `hidden: true` requests from+ // non-admins with 403. Returning `undefined` hides the tab for+ // non-admins via the same pattern context-required views use.+ hidden: (ctx) => {+ if (!ctx.isTeamAdmin) return undefined;+ return {+ filters: defineQueryFilters(+ { include: { crmCompanyHidden: true } },+ { skipTargets: ['ccf'] }+ ),+ clientFilters: { and: ['crm-company-hidden'] },+ };+ },+ },+ },folders: {default: 'owned',tabs: {@@ -386,9 +419,17 @@ export const VIEW_TAB_PRESETS: Record<ListView, ViewTabConfig> = {tabs: {all: () => ({// Temporary: search has no full-text index over foreign entities yet,- // so exclude them all from the search view (matching no record id)- // until search supports them.- filters: { include: { foreignEntityRecordId: [NIL_UUID] } },+ // so always exclude them (matching no record id) until search supports+ // them. CRM companies are included only when the CRM feature is enabled+ // (the nil-uuid sentinel excludes them otherwise).+ filters: ENABLE_CRM+ ? { include: { foreignEntityRecordId: [NIL_UUID] } }+ : {+ include: {+ foreignEntityRecordId: [NIL_UUID],+ crmCompanyId: [NIL_UUID],+ },+ },clientFilters: {},}),},@@ -436,6 +477,7 @@ export function getViewPreset(const presetCtx: PresetContext = ctx ?? {userId: undefined,email: undefined,+ isTeamAdmin: false,};const resolved = resolver(presetCtx);if (resolved) return resolved;diff --git a/js/app/packages/app/component/next-soup/filters/configs/entity.ts b/js/app/packages/app/component/next-soup/filters/configs/entity.tsindex 0a4befad6f..78e8fe6c26 100644--- a/js/app/packages/app/component/next-soup/filters/configs/entity.ts+++ b/js/app/packages/app/component/next-soup/filters/configs/entity.ts@@ -4,6 +4,9 @@ import {activeAgentFilter as activeAgentPredicate,callsFilter as callsPredicate,channelsFilter as channelsPredicate,+ crmCompanyActiveFilter as crmCompanyActivePredicate,+ crmCompanyHiddenFilter as crmCompanyHiddenPredicate,+ crmCompanyFilter as crmCompanyPredicate,filesAndFolderFilter as filesAndFolderPredicate,projectFilter as projectPredicate,taskFilter as taskPredicate,@@ -59,3 +62,27 @@ export const callsFilter = config({predicate: callsPredicate,query: defineQueryFilters({}, { skipTargets: ['callf'] }),});++export const crmCompanyFilter = config({+ id: 'crm-company',+ predicate: crmCompanyPredicate,+ query: defineQueryFilters({}, { skipTargets: ['ccf'] }),+});++export const crmCompanyActiveFilter = config({+ id: 'crm-company-active',+ predicate: crmCompanyActivePredicate,+ query: defineQueryFilters(+ { include: { crmCompanyHidden: false } },+ { skipTargets: ['ccf'] }+ ),+});++export const crmCompanyHiddenFilter = config({+ id: 'crm-company-hidden',+ predicate: crmCompanyHiddenPredicate,+ query: defineQueryFilters(+ { include: { crmCompanyHidden: true } },+ { skipTargets: ['ccf'] }+ ),+});diff --git a/js/app/packages/app/component/next-soup/filters/configs/index.ts b/js/app/packages/app/component/next-soup/filters/configs/index.tsindex 57ea30cf7b..4dd3550d65 100644--- a/js/app/packages/app/component/next-soup/filters/configs/index.ts+++ b/js/app/packages/app/component/next-soup/filters/configs/index.ts@@ -27,6 +27,9 @@ import {activeAgentFilter,callsFilter,channelsFilter,+ crmCompanyActiveFilter,+ crmCompanyFilter,+ crmCompanyHiddenFilter,documentOrFileFilter,filesAndFolderFilter,foldersFilter,@@ -80,6 +83,9 @@ export const SOUP_FILTERS = [documentOrFileFilter,activeTaskFilter,callsFilter,+ crmCompanyFilter,+ crmCompanyActiveFilter,+ crmCompanyHiddenFilter,emailAttachmentsFilter,inFolderFilter,...ENTITY_TYPE_FILTERS,diff --git a/js/app/packages/app/component/next-soup/filters/filter-store/compile.ts b/js/app/packages/app/component/next-soup/filters/filter-store/compile.tsindex 1f86de763e..5b5ed9bdbb 100644--- a/js/app/packages/app/component/next-soup/filters/filter-store/compile.ts+++ b/js/app/packages/app/component/next-soup/filters/filter-store/compile.ts@@ -115,6 +115,7 @@ const FIELD_CONFIG: Record<callAttended: { target: 'callf', field: 'Attended' },foreignEntityRecordId: { target: 'fef', field: 'id' },crmCompanyId: { target: 'ccf', field: 'id' },+ crmCompanyHidden: { target: 'ccf', field: 'hidden' },};const DATE_RANGE_FIELDS: Record<@@ -289,11 +290,6 @@ export function compileToAst(state: QueryState): TargetAstMap {result.emailView = state.emailView;}- // crm companies are opt-in: excluded unless a view sets `crmCompanyId`.- if (!result.ccf) {- result.ccf = AST.literal('id', NIL_UUID);- }-return result;}diff --git a/js/app/packages/app/component/next-soup/filters/filter-store/types.ts b/js/app/packages/app/component/next-soup/filters/filter-store/types.tsindex f413de535a..833fd57824 100644--- a/js/app/packages/app/component/next-soup/filters/filter-store/types.ts+++ b/js/app/packages/app/component/next-soup/filters/filter-store/types.ts@@ -68,6 +68,7 @@ export type ScalarFieldFilters = {folderDone?: boolean;callStatus?: CallStatus;callAttended?: boolean;+ crmCompanyHidden?: boolean;documentCreatedAt?: DateRangeFilter;documentUpdatedAt?: DateRangeFilter;chatCreatedAt?: DateRangeFilter;diff --git a/js/app/packages/app/component/next-soup/filters/inbox-filters.ts b/js/app/packages/app/component/next-soup/filters/inbox-filters.tsindex bebe8d09ea..6ce247637d 100644--- a/js/app/packages/app/component/next-soup/filters/inbox-filters.ts+++ b/js/app/packages/app/component/next-soup/filters/inbox-filters.ts@@ -118,6 +118,12 @@ export function signalFilter(entity: EntityData): boolean {return true;case 'call':return true;+ case 'crm_company':+ // CRM companies only show in the Companies view, not Inbox.+ return false;+ case 'crm_contact':+ // CRM contacts only show in CRM views, not Inbox.+ return false;case 'automation':// Automations only show in the Agents > Scheduled tab, not Inbox.return false;diff --git a/js/app/packages/app/component/next-soup/filters/predicates.ts b/js/app/packages/app/component/next-soup/filters/predicates.tsindex 9073044812..599bf3a91d 100644--- a/js/app/packages/app/component/next-soup/filters/predicates.ts+++ b/js/app/packages/app/component/next-soup/filters/predicates.ts@@ -109,6 +109,18 @@ export function callsFilter(entity: EntityData): boolean {return entity.type === 'call';}+export function crmCompanyFilter(entity: EntityData): boolean {+ return entity.type === 'crm_company';+}++export function crmCompanyActiveFilter(entity: EntityData): boolean {+ return entity.type === 'crm_company' && !entity.hidden;+}++export function crmCompanyHiddenFilter(entity: EntityData): boolean {+ return entity.type === 'crm_company' && entity.hidden;+}+export function filesAndFolderFilter(entity: EntityData): boolean {if (entity.type !== 'project' && entity.type !== 'document') return false;diff --git a/js/app/packages/app/component/next-soup/soup-view/create-search-state.ts b/js/app/packages/app/component/next-soup/soup-view/create-search-state.tsindex 12a9a95a95..cd153046b3 100644--- a/js/app/packages/app/component/next-soup/soup-view/create-search-state.ts+++ b/js/app/packages/app/component/next-soup/soup-view/create-search-state.ts@@ -1,7 +1,10 @@import { useGlobalNotificationSource } from '@app/component/GlobalAppState';import type { SoupState } from '@app/component/next-soup/create-soup-state';import type { FilterContext } from '@app/component/next-soup/filters/configs/base';-import type { QueryState } from '@app/component/next-soup/filters/filter-store';+import {+ NIL_UUID,+ type QueryState,+} from '@app/component/next-soup/filters/filter-store';import { useSearchContext } from '@app/component/next-soup/search-context';import {createSoupFreshSearch,@@ -186,14 +189,40 @@ export const createSearchState = ({const searchUnifiedNameContentRequest = createMemo((): UnifiedSearchRequest => {+ const state = filters();const query = debouncedSearchForService();- const baseFilters = filterDataToQueryFilters(filters());-+ const baseFilters = filterDataToQueryFilters(state);++ // CRM is opt-in on the backend. A view includes CRM in search unless it+ // NIL-excludes the CRM target (the same sentinel pattern other entity+ // types use) — so the Companies view (CRM-scoped) and the global Search+ // view (no exclusions) search CRM, while every other view excludes it.+ const includeCrm = !(state.include.crmCompanyId ?? []).includes(NIL_UUID);++ if (!includeCrm) {+ return {+ search_on: 'name_content',+ match_type: 'partial',+ query,+ filters: baseFilters,+ };+ }++ // CRM is opt-in on the backend. Search surfaces visible companies+ // everywhere except the admin Companies → Hidden tab, which sets+ // `crmCompanyHidden: true` to search the hidden set. Elsewhere (global+ // Search, Companies → Active) `crmCompanyHidden` is false/undefined →+ // visible only. Non-CRM targets are already NIL-excluded by the+ // Companies preset.return {search_on: 'name_content',match_type: 'partial',query,- filters: baseFilters,+ include_crm: true,+ filters: {+ ...baseFilters,+ crm_company_filters: { hidden: state.include.crmCompanyHidden },+ },};});diff --git a/js/app/packages/app/component/next-soup/soup-view/create-soup-entity-actions.ts b/js/app/packages/app/component/next-soup/soup-view/create-soup-entity-actions.tsindex ea85ed2e26..f18a9fdaa1 100644--- a/js/app/packages/app/component/next-soup/soup-view/create-soup-entity-actions.ts+++ b/js/app/packages/app/component/next-soup/soup-view/create-soup-entity-actions.ts@@ -164,6 +164,22 @@ export function createSoupEntityActions(): {await blockHandle?.goToLocationFromParams(getChannelParams(entity.messageId, entity.threadId));+ } else if (entity.type === 'crm_company') {+ splitManager.createNewSplit({+ content: {+ type: 'company',+ id: entity.id,+ },+ referredFrom: 'entity-actions-menu',+ });+ } else if (entity.type === 'crm_contact') {+ splitManager.createNewSplit({+ content: {+ type: 'contact',+ id: entity.id,+ },+ referredFrom: 'entity-actions-menu',+ });} else if (entity.type !== 'foreign') {splitManager.createNewSplit({content: {diff --git a/js/app/packages/app/component/next-soup/soup-view/empty-states.tsx b/js/app/packages/app/component/next-soup/soup-view/empty-states.tsxindex a4ac9fd9ec..8faf369882 100644--- a/js/app/packages/app/component/next-soup/soup-view/empty-states.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/empty-states.tsx@@ -226,6 +226,15 @@ export function EmptyState(props: {<AgentsEmptyState /></Match>+ <Match when={props.listView === 'companies'}>+ <EmptyStatePanel+ align="center"+ graphic={EmptyStateInboxZeroIcon}+ title="No companies"+ description="Companies you add or sync into your CRM will appear here."+ />+ </Match>+<Match when={props.listView === 'folders'}><EmptyStatePanelgraphic={EmptyStateFolderIcon}diff --git a/js/app/packages/app/component/next-soup/soup-view/filters-bar/unified-filter-dropdown.tsx b/js/app/packages/app/component/next-soup/soup-view/filters-bar/unified-filter-dropdown.tsxindex 6e54522bc1..26a7ea6ee3 100644--- a/js/app/packages/app/component/next-soup/soup-view/filters-bar/unified-filter-dropdown.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/filters-bar/unified-filter-dropdown.tsx@@ -363,6 +363,7 @@ export const VIEW_FILTER_CATEGORIES: Record<ListView, FilterCategory[]> = {mail: MAIL_FILTER_CATEGORIES,documents: DOCUMENTS_FILTER_CATEGORIES,tasks: TASKS_FILTER_CATEGORIES,+ companies: [],channels: [],calls: [],folders: [],diff --git a/js/app/packages/app/component/next-soup/soup-view/filters-bar/use-filter-refinements.tsx b/js/app/packages/app/component/next-soup/soup-view/filters-bar/use-filter-refinements.tsxindex 14368ad616..fa4e074f9a 100644--- a/js/app/packages/app/component/next-soup/soup-view/filters-bar/use-filter-refinements.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/filters-bar/use-filter-refinements.tsx@@ -96,6 +96,10 @@ export function useFilterRefinements() {const getPresetContext = (): PresetContext => ({userId: user.userId(),email: user.email(),+ // Filter refinements don't surface admin-gated tabs, so passing+ // false here is safe — the value only matters where the resolver+ // gates on it (companies → hidden).+ isTeamAdmin: false,});const currentView = createMemo(() => {diff --git a/js/app/packages/app/component/next-soup/soup-view/soup-view-tabs.tsx b/js/app/packages/app/component/next-soup/soup-view/soup-view-tabs.tsxindex 291cfc842e..2ad5edcbf4 100644--- a/js/app/packages/app/component/next-soup/soup-view/soup-view-tabs.tsx+++ b/js/app/packages/app/component/next-soup/soup-view/soup-view-tabs.tsx@@ -19,6 +19,7 @@ import { type TabItem, Tabs } from '@core/component/Tabs';import { TabsInset } from '@core/component/TabsInset';import { TabsInsetDropdown } from '@core/component/TabsInsetDropdown';import { useUserContext } from '@core/context/user';+import { useIsTeamAdmin } from '@queries/team/teams';import { batch, createEffect, createMemo, For, Match, Switch } from 'solid-js';/** Views that have tab definitions. Shared between VIEW_TAB_LISTS and VIEW_TAB_PRESETS. */@@ -31,6 +32,7 @@ export type TabbedListView = Extract<| 'tasks'| 'channels'| 'calls'+ | 'companies'| 'folders'>;@@ -78,6 +80,13 @@ export const VIEW_TAB_LISTS: Record<TabbedListView, TabItem[]> = {{ value: 'missed', label: 'Missed' },{ value: 'unattended', label: 'Unattended' },],+ companies: [+ { value: 'active', label: 'Active' },+ // The 'hidden' tab is gated to admin/owner team members — see+ // `filterTabsForUser` below and the preset resolver in+ // soup-filter-presets.ts.+ { value: 'hidden', label: 'Hidden' },+ ],folders: [{ value: 'owned', label: 'Owned' },{ value: 'all', label: 'All' },@@ -106,10 +115,12 @@ export const useApplyPreset = () => {const { queryFilters, setActiveTab, activeTab, assigneeFilter } =useSoupView();const user = useUserContext();+ const isTeamAdmin = useIsTeamAdmin();const getPresetContext = (): PresetContext => ({userId: user.userId(),email: user.email(),+ isTeamAdmin: isTeamAdmin(),});const getFilterQuery = (id: string, ctx: FilterContext) => {@@ -201,10 +212,24 @@ export const SoupViewTabs = () => {);};+/** Drops admin-only tabs for non-admin users (currently: companies → hidden). */+function filterTabsForUser(+ view: TabbedListView,+ list: TabItem[],+ isTeamAdmin: boolean+): TabItem[] {+ if (view === 'companies' && !isTeamAdmin) {+ return list.filter((t) => t.value !== 'hidden');+ }+ return list;+}+const ViewTabs = (props: { view: TabbedListView }) => {const { applyTabPreset } = useApplyPreset();const { activeTab } = useSoupView();- const list = () => VIEW_TAB_LISTS[props.view];+ const isTeamAdmin = useIsTeamAdmin();+ const list = () =>+ filterTabsForUser(props.view, VIEW_TAB_LISTS[props.view], isTeamAdmin());return (<TabsInset@@ -221,6 +246,7 @@ export const CollapsedSoupViewTabs = () => {const listView = useCurrentListView();const { applyTabPreset } = useApplyPreset();const { activeTab } = useSoupView();+ const isTeamAdmin = useIsTeamAdmin();const view = createMemo(() => {const v = listView();@@ -229,7 +255,7 @@ export const CollapsedSoupViewTabs = () => {const list = createMemo(() => {const v = view();- return v ? VIEW_TAB_LISTS[v] : [];+ return v ? filterTabsForUser(v, VIEW_TAB_LISTS[v], isTeamAdmin()) : [];});const defaultValue = createMemo(() => {@@ -280,7 +306,9 @@ export const MobileSoupViewTabs = () => {const MobileViewTabs = (props: { view: TabbedListView }) => {const { applyTabPreset } = useApplyPreset();const { activeTab } = useSoupView();- const list = () => VIEW_TAB_LISTS[props.view];+ const isTeamAdmin = useIsTeamAdmin();+ const list = () =>+ filterTabsForUser(props.view, VIEW_TAB_LISTS[props.view], isTeamAdmin());let wrapperRef: HTMLDivElement | undefined;diff --git a/js/app/packages/app/component/next-soup/utils.ts b/js/app/packages/app/component/next-soup/utils.tsindex 89363e770a..002af2f39c 100644--- a/js/app/packages/app/component/next-soup/utils.ts+++ b/js/app/packages/app/component/next-soup/utils.ts@@ -399,6 +399,12 @@ function getEntitySplitContent(entity: EntityData) {.with({ type: 'foreign' }, (entity) => {return { type: 'unknown' as const, id: entity.id };})+ .with({ type: 'crm_company' }, (entity) => {+ return { type: 'company' as const, id: entity.id };+ })+ .with({ type: 'crm_contact' }, (entity) => {+ return { type: 'contact' as const, id: entity.id };+ }).otherwise((entity) => {return { type: entity.type, id: entity.id };});diff --git a/js/app/packages/app/component/split-layout/componentRegistry.tsx b/js/app/packages/app/component/split-layout/componentRegistry.tsxindex fd776713de..15c3e689f6 100644--- a/js/app/packages/app/component/split-layout/componentRegistry.tsx+++ b/js/app/packages/app/component/split-layout/componentRegistry.tsx@@ -8,7 +8,11 @@ import { ChannelCompose } from '@block-channel/component/Compose';import { ComposeTask } from '@block-md/component/ComposeTask';import { useIsAuthenticated } from '@core/auth';import { LoadingBlock } from '@core/component/LoadingBlock';-import { DEV_MODE_ENV, LOCAL_ONLY } from '@core/constant/featureFlags';+import {+ DEV_MODE_ENV,+ ENABLE_CRM,+ LOCAL_ONLY,+} from '@core/constant/featureFlags';import { useUserContext } from '@core/context/user';import type { ViewId } from '@core/types/view';import { useAutomationEntities } from '@queries/agent-schedule/entities';@@ -135,6 +139,7 @@ registerComponent(const preset = getViewPreset('agents', undefined, {userId: user.userId(),email: user.email(),+ isTeamAdmin: false,});const automationEntities = useAutomationEntities();return (@@ -173,6 +178,7 @@ registerComponent(const preset = getViewPreset('documents', undefined, {userId: user.userId(),email: user.email(),+ isTeamAdmin: false,});return (<SoupView@@ -193,6 +199,7 @@ registerComponent(const preset = getViewPreset('tasks', undefined, {userId: user.userId(),email: user.email(),+ isTeamAdmin: false,});return (<SoupView@@ -237,6 +244,27 @@ registerComponent(}));+registerComponent(+ 'companies',+ withAuth(() => {+ // Registered even when the CRM feature is off so direct navigation /+ // restored splits redirect instead of throwing in resolveComponent.+ if (!ENABLE_CRM) {+ return <RedirectSplit to={{ type: 'component', id: 'inbox' }} />;+ }+ usePageViewTracking('companies');+ const preset = getViewPreset('companies');+ return (+ <SoupView+ viewName="Companies"+ initialFilters={preset?.filters}+ initialClientFilters={preset?.clientFilters}+ initialGroupBy={preset?.groupBy}+ />+ );+ })+);+registerComponent('folders',withAuth(() => {@@ -245,6 +273,7 @@ registerComponent(const preset = getViewPreset('folders', undefined, {userId: user.userId(),email: user.email(),+ isTeamAdmin: false,});return (<SoupViewdiff --git a/js/app/packages/app/component/split-layout/components/SplitHeader.tsx b/js/app/packages/app/component/split-layout/components/SplitHeader.tsxindex 3398852542..4f66c6e710 100644--- a/js/app/packages/app/component/split-layout/components/SplitHeader.tsx+++ b/js/app/packages/app/component/split-layout/components/SplitHeader.tsx@@ -46,6 +46,10 @@ function getEntitySplitContent(data: EntityDragEvent['draggable']['data']):if (data.type === 'foreign') return undefined;+ // CRM entity types map to their dedicated blocks (entity type !== block name).+ if (data.type === 'crm_company') return { type: 'company', id: data.id };+ if (data.type === 'crm_contact') return { type: 'contact', id: data.id };+return { type: data.type, id: data.id };}diff --git a/js/app/packages/app/constants/list-views.ts b/js/app/packages/app/constants/list-views.tsindex b483d3db03..52e3d837fd 100644--- a/js/app/packages/app/constants/list-views.ts+++ b/js/app/packages/app/constants/list-views.ts@@ -6,6 +6,7 @@ export const LIST_VIEWS = ['tasks','channels','calls',+ 'companies','folders','search',] as const;@@ -20,6 +21,7 @@ export const LIST_VIEW_PATHS = {tasks: '/tasks',channels: '/channels',calls: '/calls',+ companies: '/companies',folders: '/folders',search: '/search',} as const satisfies Record<ListView, string>;@@ -32,6 +34,7 @@ export const LIST_VIEW_ID = {tasks: 'tasks',channels: 'channels',calls: 'calls',+ companies: 'companies',folders: 'folders',search: 'search',} as const satisfies Record<ListView, string>;diff --git a/js/app/packages/block-call/component/sidepanel/CallSidePanelSections.tsx b/js/app/packages/block-call/component/sidepanel/CallSidePanelSections.tsxindex 9f1458af1c..54a0022225 100644--- a/js/app/packages/block-call/component/sidepanel/CallSidePanelSections.tsx+++ b/js/app/packages/block-call/component/sidepanel/CallSidePanelSections.tsx@@ -1,6 +1,5 @@import { SidePanel } from '@app/component/side-panel';import { useCallContextOptional } from '@channel/Call/CallContext';-import { InlineCheckbox } from '@channel/Call/CallControls/CallMenuPrimitives';import { useBlockId } from '@core/block';import { References } from '@core/component/References';import { UserIcon } from '@core/component/UserIcon';@@ -13,7 +12,7 @@ import {} from '@queries/call/call';import { useAttachmentReferencesQuery } from '@queries/storage/attachment-references';import type { CallRecord } from '@service-storage/generated/schemas/callRecord';-import { cn } from '@ui';+import { cn, InlineCheckbox } from '@ui';import { type Accessor, Show, Suspense } from 'solid-js';import { formatCallDuration } from '../../utils';diff --git a/js/app/packages/block-canvas/component/CanvasController.tsx b/js/app/packages/block-canvas/component/CanvasController.tsxindex 61f3851343..c1bbb84e7e 100644--- a/js/app/packages/block-canvas/component/CanvasController.tsx+++ b/js/app/packages/block-canvas/component/CanvasController.tsx@@ -865,6 +865,9 @@ export function CanvasController(props: ParentProps) {if (entityType === 'channel_message') return;// Automation and foreign entities aren't yet renderable as canvas mentions.if (entityType === 'automation' || entityType === 'foreign') return;+ // CRM companies/contacts aren't renderable as canvas mentions.+ if (entityType === 'crm_company') return;+ if (entityType === 'crm_contact') return;// Track document mention and get UUIDlet mentionUuid: string | undefined;diff --git a/js/app/packages/block-company/component/CompanyBlockAdapter.tsx b/js/app/packages/block-company/component/CompanyBlockAdapter.tsxnew file mode 100644index 0000000000..364c899b62--- /dev/null+++ b/js/app/packages/block-company/component/CompanyBlockAdapter.tsx@@ -0,0 +1,12 @@+import { Company } from '@companies/Company/Company';+import { useBlockId } from '@core/block';++/**+ * Legacy adapter: bridges the block/split-layout system to the standalone+ * `companies` feature package. All block-specific glue lives here; the+ * `companies` package itself has zero block dependencies.+ */+export function CompanyBlockAdapter() {+ const companyId = useBlockId();+ return <Company companyId={companyId} />;+}diff --git a/js/app/packages/block-company/definition.ts b/js/app/packages/block-company/definition.tsnew file mode 100644index 0000000000..86baffeaa3--- /dev/null+++ b/js/app/packages/block-company/definition.ts@@ -0,0 +1,20 @@+import { defineBlock, type ExtractLoadType, LoadErrors } from '@core/block';+import { ok } from 'neverthrow';++import { CompanyBlockAdapter } from './component/CompanyBlockAdapter';++export const definition = defineBlock({+ name: 'company',+ description: 'View a CRM company',+ component: CompanyBlockAdapter,+ liveTrackingEnabled: false,+ async load(source, _intent) {+ if (source.type === 'dss') {+ return ok({ id: source.id });+ }+ return LoadErrors.MISSING;+ },+ accepted: {},+});++export type CompanyData = ExtractLoadType<(typeof definition)['load']>;diff --git a/js/app/packages/block-company/package.json b/js/app/packages/block-company/package.jsonnew file mode 100644index 0000000000..3380deb1d9--- /dev/null+++ b/js/app/packages/block-company/package.json@@ -0,0 +1,6 @@+{+ "name": "block-company",+ "private": true,+ "scripts": {},+ "dependencies": {}+}diff --git a/js/app/packages/block-company/tsconfig.json b/js/app/packages/block-company/tsconfig.jsonnew file mode 100644index 0000000000..d9677aefea--- /dev/null+++ b/js/app/packages/block-company/tsconfig.json@@ -0,0 +1,11 @@+{+ "extends": "../../tsconfig.json",+ "compilerOptions": {+ "jsx": "preserve",+ "jsxImportSource": "solid-js",+ "verbatimModuleSyntax": true,+ "moduleResolution": "bundler",+ "declaration": true,+ "composite": true+ }+}diff --git a/js/app/packages/block-contact/component/ContactBlockAdapter.tsx b/js/app/packages/block-contact/component/ContactBlockAdapter.tsxnew file mode 100644index 0000000000..1541ff3905--- /dev/null+++ b/js/app/packages/block-contact/component/ContactBlockAdapter.tsx@@ -0,0 +1,12 @@+import { Contact } from '@contacts/Contact/Contact';+import { useBlockId } from '@core/block';++/**+ * Legacy adapter: bridges the block/split-layout system to the standalone+ * `contacts` feature package. All block-specific glue lives here; the+ * `contacts` package itself has zero block dependencies.+ */+export function ContactBlockAdapter() {+ const contactId = useBlockId();+ return <Contact contactId={contactId} />;+}diff --git a/js/app/packages/block-contact/definition.ts b/js/app/packages/block-contact/definition.tsnew file mode 100644index 0000000000..91f32df703--- /dev/null+++ b/js/app/packages/block-contact/definition.ts@@ -0,0 +1,20 @@+import { defineBlock, type ExtractLoadType, LoadErrors } from '@core/block';+import { ok } from 'neverthrow';++import { ContactBlockAdapter } from './component/ContactBlockAdapter';++export const definition = defineBlock({+ name: 'contact',+ description: 'View a CRM contact',+ component: ContactBlockAdapter,+ liveTrackingEnabled: false,+ async load(source, _intent) {+ if (source.type === 'dss') {+ return ok({ id: source.id });+ }+ return LoadErrors.MISSING;+ },+ accepted: {},+});++export type ContactData = ExtractLoadType<(typeof definition)['load']>;diff --git a/js/app/packages/block-contact/package.json b/js/app/packages/block-contact/package.jsonnew file mode 100644index 0000000000..52c213e226--- /dev/null+++ b/js/app/packages/block-contact/package.json@@ -0,0 +1,6 @@+{+ "name": "block-contact",+ "private": true,+ "scripts": {},+ "dependencies": {}+}diff --git a/js/app/packages/block-contact/tsconfig.json b/js/app/packages/block-contact/tsconfig.jsonnew file mode 100644index 0000000000..d9677aefea--- /dev/null+++ b/js/app/packages/block-contact/tsconfig.json@@ -0,0 +1,11 @@+{+ "extends": "../../tsconfig.json",+ "compilerOptions": {+ "jsx": "preserve",+ "jsxImportSource": "solid-js",+ "verbatimModuleSyntax": true,+ "moduleResolution": "bundler",+ "declaration": true,+ "composite": true+ }+}diff --git a/js/app/packages/block-md/comments/documentDiscussionSource.ts b/js/app/packages/block-md/comments/documentDiscussionSource.tsnew file mode 100644index 0000000000..02a68d40ae--- /dev/null+++ b/js/app/packages/block-md/comments/documentDiscussionSource.ts@@ -0,0 +1,110 @@+import { useBlockId } from '@core/block';+import type {+ DiscussionComment,+ DiscussionSource,+ DiscussionThread,+} from '@core/comments/discussion';+import type { ItemMention } from '@core/component/LexicalMarkdown/plugins';+import { useUrlParams } from '@core/component/ParamsProvider';+import { useUserId } from '@core/context/user';+import { useCanComment } from '@core/signal/permissions';+import { buildSimpleEntityUrl } from '@core/util/url';+import type { CommentThread } from '@service-storage/generated/schemas/commentThread';+import type { CreateCommentRequestMentions } from '@service-storage/generated/schemas/createCommentRequestMentions';+import { createMemo } from 'solid-js';+import { URL_PARAMS } from '../constants';+import {+ discussionThreads,+ sortComments,+ useCreateDiscussionReply,+ useCreateDiscussionThread,+ useDeleteDiscussionComment,+ useEditDiscussionComment,+} from './discussionResource';++function buildCommentMentions(+ mentions: ItemMention[]+): CreateCommentRequestMentions | undefined {+ const userIds = mentions+ .filter((m) => m.itemType === 'user')+ .map((m) => m.itemId);+ if (userIds.length === 0) return undefined;+ return { mentionId: crypto.randomUUID(), users: userIds };+}++/** Maps a server `CommentThread` (numeric ids) to the normalized view model. */+function toViewThread(ct: CommentThread): DiscussionThread {+ const comments: DiscussionComment[] = [...ct.comments]+ .sort(sortComments)+ .map((c) => ({+ id: String(c.commentId),+ threadId: String(c.threadId),+ authorId: c.sender ?? c.owner,+ text: c.text,+ createdAt: c.createdAt ?? '',+ updatedAt: c.updatedAt ?? c.createdAt ?? '',+ deletedAt: c.deletedAt ?? null,+ }));+ return {+ id: String(ct.thread.threadId),+ resolved: ct.thread.resolved,+ comments,+ };+}++/**+ * [`DiscussionSource`] backed by the document annotations system — the+ * `DISCUSSION:`-marked threads on a task document. Quarantines the numeric+ * id ↔ string adaptation and the document-specific request shapes so the+ * shared discussion UI stays backend-agnostic. Must be called within a+ * block/component owner (it wires the existing block resources).+ */+export function createDocumentDiscussionSource(): DiscussionSource {+ const blockId = useBlockId();+ // Comment affordances gate on can-comment (main switched tasks off can-edit).+ const canComment = useCanComment();+ const userId = useUserId();+ const urlParams = useUrlParams(URL_PARAMS);++ const createThreadFn = useCreateDiscussionThread();+ const createReplyFn = useCreateDiscussionReply();+ const editFn = useEditDiscussionComment();+ const deleteFn = useDeleteDiscussionComment();++ const threads = createMemo(() =>+ (discussionThreads() ?? []).map(toViewThread)+ );+ const targetCommentId = createMemo(() => urlParams.commentId() ?? null);++ return {+ threads,+ canEdit: canComment,+ currentUserId: userId,+ targetCommentId,+ async createThread(text, mentions) {+ await createThreadFn(text, buildCommentMentions(mentions));+ },+ async createReply(threadId, text, mentions) {+ await createReplyFn(+ text,+ Number(threadId),+ buildCommentMentions(mentions)+ );+ },+ async editComment(comment, text) {+ await editFn(Number(comment.id), {+ text,+ threadId: Number(comment.threadId),+ });+ },+ async deleteComment(comment) {+ await deleteFn(Number(comment.id), {});+ },+ buildCommentLink(comment) {+ return buildSimpleEntityUrl(+ { type: 'task', id: blockId },+ { [URL_PARAMS.commentId]: comment.id }+ );+ },+ };+}diff --git a/js/app/packages/block-md/component/TaskDiscussion.tsx b/js/app/packages/block-md/component/TaskDiscussion.tsxindex a854f6f0d6..d33e3ef0a4 100644--- a/js/app/packages/block-md/component/TaskDiscussion.tsx+++ b/js/app/packages/block-md/component/TaskDiscussion.tsx@@ -1,400 +1,12 @@-import type { InputSnapshot } from '@channel/Input/types';-import { Message } from '@channel/Message/Message';-import type {- MessageActionContext,- MessageActions,-} from '@channel/Message/types';-import { Thread } from '@channel/Thread/Thread';-import { ThreadRail } from '@channel/Thread/ThreadRail';-import { ThreadReplyInputConnector } from '@channel/Thread/ThreadReplyInputConnector';-import { replyInputOffsetX } from '@channel/Thread/utils/thread-rail-geometry';-import { useBlockId } from '@core/block';-import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';-import type { ItemMention } from '@core/component/LexicalMarkdown/plugins';-import { useUrlParams } from '@core/component/ParamsProvider';-import { toast } from '@core/component/Toast/Toast';-import { useUserId } from '@core/context/user';-import { useCanComment } from '@core/signal/permissions';-import { tryMacroId, useDisplayName } from '@core/user';-import { buildSimpleEntityUrl } from '@core/util/url';-import CaretDown from '@phosphor/caret-down.svg';-import CaretRight from '@phosphor/caret-right.svg';-import type { Comment } from '@service-storage/generated/schemas/comment';-import type { CommentThread } from '@service-storage/generated/schemas/commentThread';-import type { CreateCommentRequestMentions } from '@service-storage/generated/schemas/createCommentRequestMentions';-import {- createEffect,- createMemo,- createSignal,- For,- onMount,- Show,-} from 'solid-js';-import {- commentToApiChannelMessage,- commentToMessageData,-} from '../comments/discussionAdapter';-import {- discussionThreads,- sortComments,- useCreateDiscussionReply,- useCreateDiscussionThread,- useDeleteDiscussionComment,- useEditDiscussionComment,-} from '../comments/discussionResource';-import { URL_PARAMS } from '../constants';-import { DiscussionInput } from './DiscussionInput';--function buildCommentMentions(- mentions: ItemMention[]-): CreateCommentRequestMentions | undefined {- const userIds = mentions- .filter((m) => m.itemType === 'user')- .map((m) => m.itemId);-- if (userIds.length === 0) {- return undefined;- }-- return {- mentionId: crypto.randomUUID(),- users: userIds,- };-}+import { Discussion, DiscussionProvider } from '@core/comments/discussion';+import { createDocumentDiscussionSource } from '../comments/documentDiscussionSource';+/** Task discussion: the document annotations source feeding the shared UI. */export function TaskDiscussion() {- const canComment = useCanComment();- const createThread = useCreateDiscussionThread();- const [isExpanded, setIsExpanded] = createSignal(true);-- const urlParams = useUrlParams(URL_PARAMS);- const targetCommentId = createMemo(() => {- const raw = urlParams.commentId();- if (!raw) return null;- const id = Number(raw);- return isNaN(id) ? null : id;- });-- createEffect(() => {- if (targetCommentId() !== null) setIsExpanded(true);- });-- let newThreadInputHandle: { clear: () => void } | undefined;-- const toggleExpanded = () => {- setIsExpanded(!isExpanded());- };-- const handleCreateThread = async (snapshot: InputSnapshot) => {- const text = snapshot.value.trim();- if (!text) return;- const mentions = buildCommentMentions(snapshot.mentions);- await createThread(text, mentions);- newThreadInputHandle?.clear();- };-- return (- <section class="mt-8 pb-12">- <div class="flex items-center gap-2 pt-2">- <div class="w-6 border-t border-edge-muted" />- <button- type="button"- class="flex items-center gap-1 px-2 hover:opacity-70 transition-opacity"- onClick={toggleExpanded}- >- {isExpanded() ? (- <CaretDown class="size-3" />- ) : (- <CaretRight class="size-3" />- )}- <span class="text-xs">Discussion</span>- </button>- <div class="flex-1 border-t border-edge-muted" />- </div>-- <Show when={isExpanded()}>- <StaticMarkdownContext>- <div class="py-2 text-xs">- <div>- <For each={discussionThreads() ?? []}>- {(thread) => (- <DiscussionThread- thread={thread}- targetCommentId={targetCommentId()}- />- )}- </For>- </div>-- <Show when={canComment()}>- <div>- <DiscussionInput- input={{ mode: 'channel', placeholder: 'Leave a comment...' }}- onSend={handleCreateThread}- onReady={(handle) => {- newThreadInputHandle = handle;- }}- autofocus={false}- />- </div>- </Show>- </div>- </StaticMarkdownContext>- </Show>- </section>- );-}--function DiscussionThread(props: {- thread: CommentThread;- targetCommentId: number | null;-}) {- const userId = useUserId();- const canComment = useCanComment();- const blockId = useBlockId();- const createReply = useCreateDiscussionReply();- const editComment = useEditDiscussionComment();- const deleteComment = useDeleteDiscussionComment();-- const [isReplying, setIsReplying] = createSignal(false);- const [editingId, setEditingId] = createSignal<number | null>(null);- let replyInputHandle: { clear: () => void } | undefined;- let replyInputContainerRef: HTMLDivElement | undefined;-- const sorted = () => [...props.thread.comments].sort(sortComments);- const root = () => sorted()[0];- const replies = () => sorted().slice(1);- const hasReplies = () => replies().length > 0;-- const threadId = () => props.thread.thread.threadId;-- const replyUserId = () => userId() ?? root()?.sender ?? root()?.owner ?? '';- const macroId = () => tryMacroId(replyUserId());- const [displayName] = useDisplayName(macroId());-- const isOwn = (comment: Comment) =>- (comment.sender ?? comment.owner) === userId();-- const makeCopyLink =- (comment: Comment): ((ctx: MessageActionContext) => Promise<void>) =>- async () => {- const params: Record<string, string> = {- [URL_PARAMS.commentId]: String(comment.commentId),- };- try {- const url = buildSimpleEntityUrl({ type: 'task', id: blockId }, params);- await navigator.clipboard.writeText(url);- toast.success('Link copied to clipboard');- } catch {- toast.failure('Could not copy link');- }- };-- const makeActions = (comment: Comment, isRoot: boolean): MessageActions => {- const own = isOwn(comment);- return {- onReply:- isRoot && canComment()- ? () => {- setIsReplying(true);- }- : undefined,- onEdit: own- ? () => {- setEditingId(comment.commentId);- }- : undefined,- onDelete:- own && canComment()- ? async () => {- await deleteComment(comment.commentId, {});- }- : undefined,- onCopyLink: makeCopyLink(comment),- };- };-- const handleReply = async (snapshot: InputSnapshot) => {- const text = snapshot.value.trim();- if (!text) return;- const mentions = buildCommentMentions(snapshot.mentions);- await createReply(text, threadId(), mentions);- replyInputHandle?.clear();- setIsReplying(false);- };-- const handleEdit = async (comment: Comment, snapshot: InputSnapshot) => {- const text = snapshot.value.trim();- if (!text) return;- await editComment(comment.commentId, {- text,- threadId: threadId(),- });- setEditingId(null);- };-- return (- <Show when={root()}>- {(rootComment) => {- const rootMessageData = () => commentToApiChannelMessage(rootComment());- return (- <div class="flex flex-col w-full gap-0">- <Thread.Row message={rootMessageData()}>- <DiscussionMessage- comment={rootComment()}- actions={makeActions(rootComment(), true)}- editingId={editingId()}- onEditSave={(snapshot) => handleEdit(rootComment(), snapshot)}- onEditCancel={() => setEditingId(null)}- isHighlighted={- props.targetCommentId === rootComment().commentId- }- />-- <Show when={hasReplies() || isReplying()}>- <div class="relative w-full">- <Thread.ReplyRailDecorations- isReplying={isReplying}- firstThreadReplyNewMessage={false}- />- <Thread.RepliesContainer>- <For each={replies()}>- {(reply) => (- <div class="relative">- <ThreadRail />- <DiscussionMessage- comment={reply}- actions={makeActions(reply, false)}- editingId={editingId()}- onEditSave={(snapshot) =>- handleEdit(reply, snapshot)- }- onEditCancel={() => setEditingId(null)}- isHighlighted={- props.targetCommentId === reply.commentId- }- />- </div>- )}- </For>-- <Show when={isReplying() && canComment()}>- <div class="ph-no-capture">- <Show when={!hasReplies()}>- <Thread.ReplyAuthor- userId={replyUserId()}- displayName={displayName()}- />- </Show>- <div- ref={replyInputContainerRef}- class="relative pt-2"- style={{ 'margin-left': replyInputOffsetX }}- >- <ThreadReplyInputConnector />- <DiscussionInput- input={{ mode: 'reply', placeholder: 'Reply...' }}- onSend={handleReply}- onClose={() => {- setIsReplying(false);- }}- onReady={(handle) => {- replyInputHandle = handle;- }}- />- </div>- </div>- </Show>-- <Show when={!isReplying() && canComment()}>- <Thread.ActionsFooter>- <Thread.ReplyButton- getFocusTarget={() =>- replyInputContainerRef?.querySelector<HTMLElement>(- '[contenteditable]'- ) ?? null- }- onClick={() => setIsReplying(true)}- aria-label="Reply"- />- </Thread.ActionsFooter>- </Show>- </Thread.RepliesContainer>- </div>- </Show>- </Thread.Row>- </div>- );- }}- </Show>- );-}--function DiscussionMessage(props: {- comment: Comment;- actions: MessageActions;- editingId: number | null;- onEditSave: (snapshot: InputSnapshot) => void;- onEditCancel: () => void;- isHighlighted?: boolean;-}) {- const isEditing = () => props.editingId === props.comment.commentId;- const messageData = () => commentToMessageData(props.comment);-- let containerRef: HTMLDivElement | undefined;- onMount(() => {- if (props.isHighlighted) {- containerRef?.scrollIntoView({ behavior: 'smooth', block: 'center' });- }- });-+ const source = createDocumentDiscussionSource();return (- <div ref={containerRef}>- <Show- when={!isEditing()}- fallback={- <DiscussionInput- input={{- mode: 'reply',- placeholder: 'Edit comment...',- value: props.comment.text,- }}- onSend={props.onEditSave}- onClose={() => {- props.onEditCancel();- }}- />- }- >- <Message.Root- message={messageData()}- actions={props.actions}- highlighted={props.isHighlighted}- >- <Message.Layout class="pt-(--regular-message-padding-t)">- <Message.Slot placement="icon">- <Message.SenderIcon />- </Message.Slot>- <Message.Slot- placement="header"- class="flex items-center gap-1 min-w-0 w-full"- >- <Message.SenderName />- <Message.EditedIndicator />- <div class="grow shrink-0 min-w-0 flex justify-end group-hover/message:absolute group-hover/message:right-1 group-hover/message:-top-9 group-hover/message:p-1">- <Message.Timestamp- class="ml-auto shrink-0"- format="dateAndTime"- />- </div>- </Message.Slot>- <Message.Slot placement="content" class="ph-no-capture">- <Message.Content />- </Message.Slot>- <Message.ActionMenu />- </Message.Layout>- </Message.Root>- </Show>- </div>+ <DiscussionProvider source={source}>+ <Discussion />+ </DiscussionProvider>);}diff --git a/js/app/packages/channel/Attachments/attachment-utils.ts b/js/app/packages/channel/Attachments/attachment-utils.tsindex e2ae540791..03eb53bc7a 100644--- a/js/app/packages/channel/Attachments/attachment-utils.ts+++ b/js/app/packages/channel/Attachments/attachment-utils.ts@@ -113,5 +113,11 @@ export function getEntityClickContent(entity: EntityData): SplitContent {.with({ type: 'foreign' }, () => {throw new Error('foreign entities do not support channel attachments');})+ .with({ type: 'crm_company' }, () => {+ throw new Error('crm companies are not openable as attachments');+ })+ .with({ type: 'crm_contact' }, () => {+ throw new Error('crm contacts are not openable as attachments');+ }).exhaustive();}diff --git a/js/app/packages/channel/Call/CallControls/CallControlsPanelSmallRow.tsx b/js/app/packages/channel/Call/CallControls/CallControlsPanelSmallRow.tsxindex 4206ec6af2..749be06676 100644--- a/js/app/packages/channel/Call/CallControls/CallControlsPanelSmallRow.tsx+++ b/js/app/packages/channel/Call/CallControls/CallControlsPanelSmallRow.tsx@@ -5,13 +5,13 @@ import MicrophoneSlash from '@phosphor/microphone-slash.svg';import Screencast from '@phosphor/screencast.svg';import VideoCamera from '@phosphor/video-camera.svg';import VideoCameraSlash from '@phosphor/video-camera-slash.svg';-import { cn, Dropdown } from '@ui';+import { cn, Dropdown, InlineCheckbox } from '@ui';import { Show } from 'solid-js';import { match } from 'ts-pattern';import { useCallContext } from '../CallContext';import { CallDeviceList } from '../CallDeviceList';import { useToggleShareWithTeam } from '../use-toggle-share-with-team';-import { InlineCheckbox, MenuDivider, MenuLabel } from './CallMenuPrimitives';+import { MenuDivider, MenuLabel } from './CallMenuPrimitives';const ITEM_ICON_CLASS = 'size-3.5 shrink-0 text-ink-muted';diff --git a/js/app/packages/channel/Call/CallControls/CallMenuPrimitives.tsx b/js/app/packages/channel/Call/CallControls/CallMenuPrimitives.tsxindex 31ca11dc36..6538583347 100644--- a/js/app/packages/channel/Call/CallControls/CallMenuPrimitives.tsx+++ b/js/app/packages/channel/Call/CallControls/CallMenuPrimitives.tsx@@ -1,5 +1,4 @@-import Check from '@phosphor/check.svg';-import { cn, Dropdown } from '@ui';+import { Dropdown } from '@ui';import type { Component, JSX } from 'solid-js';/**@@ -19,22 +18,3 @@ export const MenuLabel: Component<{ children: JSX.Element }> = (props) => (export const MenuDivider: Component = () => (<Dropdown.Separator class="my-1 h-px border-0 bg-edge-muted -mx-1.5" />);--/**- * Inline checkbox affordance — a small square that fills accent when checked- * and shows an outlined empty box when not. Matches the soup-menu checkbox- * pattern. Visual-only; pair with a clickable parent for the actual toggle.- */-export const InlineCheckbox: Component<{ checked: boolean }> = (props) => (- <span- aria-hidden- class={cn(- 'inline-flex items-center justify-center size-3.5 shrink-0 rounded-sm',- props.checked- ? 'bg-accent text-surface'- : 'bg-transparent border border-edge-muted text-transparent'- )}- >- <Check class="size-2.5" />- </span>-);diff --git a/js/app/packages/channel/Call/CallOverlay.tsx b/js/app/packages/channel/Call/CallOverlay.tsxindex 28fd58245c..0dbe659d19 100644--- a/js/app/packages/channel/Call/CallOverlay.tsx+++ b/js/app/packages/channel/Call/CallOverlay.tsx@@ -2,12 +2,11 @@ import { useSplitPanel } from '@app/component/split-layout/layoutUtils';import { UserIcon } from '@core/component/UserIcon';import { useAuthor, useUserId } from '@core/context/user';import { tryMacroId, useDisplayName } from '@core/user';-import { cn, Tooltip } from '@ui';+import { cn, InlineCheckbox, Tooltip } from '@ui';import { type RemoteParticipant, Track } from 'livekit-client';import { For, type JSXElement, Show } from 'solid-js';import { useCallContext } from './CallContext';import { CallControls } from './CallControls/CallControls';-import { InlineCheckbox } from './CallControls/CallMenuPrimitives';import {CALL_PANEL_MEDIUM_NARROW_PX,CALL_PANEL_VERY_NARROW_PX,diff --git a/js/app/packages/companies/Company/Company.tsx b/js/app/packages/companies/Company/Company.tsxnew file mode 100644index 0000000000..4693fe8169--- /dev/null+++ b/js/app/packages/companies/Company/Company.tsx@@ -0,0 +1,60 @@+import { SidePanel } from '@app/component/side-panel';+import { SplitToolbarLeft } from '@app/component/split-layout/components/SplitToolbar';+import { useCompanyQuery } from '@queries/crm/companies';+import { CompanyContactsSection } from './CompanyContactsSection';+import { CompanyDiscussionSection } from './CompanyDiscussionSection';+import { CompanyEmailsSection } from './CompanyEmailsSection';+import { CompanyHeader } from './CompanyHeader';+import { CompanyMetadataSection } from './CompanyMetadataSection';+import { CompanySharingSection } from './CompanySharingSection';++/**+ * Root of the company detail view. Owns the company query and pushes the+ * resolved entity down to presentational children. Layout mirrors the task+ * page: middle content constrained to a centered column, additional info in+ * the right-hand SidePanel.+ */+export function Company(props: { companyId: string }) {+ const { company, contacts } = useCompanyQuery(() => props.companyId);++ return (+ <SidePanel.Layout>+ {/* Narrow-mode Content/Info tabs. Portaled into the split's toolbar+ slot so they sit above the content (and outside the scroll area)+ without restructuring the block's layout. Self-hides in wide+ mode. Mirrors how block-call / block-md mount it. */}+ <SplitToolbarLeft>+ <SidePanel.NarrowTabs />+ </SplitToolbarLeft>+ <div class="flex h-full flex-col overflow-y-auto scrollbar-hidden">+ <div class="mx-auto flex w-full max-w-3xl min-w-0 grow flex-col gap-6 px-6 pt-12 pb-12">+ <CompanyHeader company={company()} />+ <CompanyDiscussionSection companyId={props.companyId} />+ <CompanyEmailsSection company={company()} />+ </div>+ </div>++ <SidePanel.Section+ id="company-details"+ title="Details"+ order={10}+ defaultOpen+ >+ <CompanyMetadataSection company={company()} />+ </SidePanel.Section>+ <SidePanel.Section+ id="company-contacts"+ title="Contacts"+ order={20}+ defaultOpen+ >+ <CompanyContactsSection company={company()} contacts={contacts()} />+ </SidePanel.Section>+ <SidePanel.Section id="company-sharing" title="Sharing" order={25}>+ <CompanySharingSection company={company()} />+ </SidePanel.Section>+ {/* TODO: add a References section (inbound channel messages + documents)+ once the references backend supports the crm_company entity type. */}+ </SidePanel.Layout>+ );+}diff --git a/js/app/packages/companies/Company/CompanyContactsSection.tsx b/js/app/packages/companies/Company/CompanyContactsSection.tsxnew file mode 100644index 0000000000..25a7f8d61f--- /dev/null+++ b/js/app/packages/companies/Company/CompanyContactsSection.tsx@@ -0,0 +1,84 @@+import { useSplitLayout } from '@app/component/split-layout/layout';+import type { CrmCompanyEntity } from '@entity';+import type { CompanyContact } from '@queries/crm/companies';+import { createMemo, createSignal, For, Show } from 'solid-js';++export function CompanyContactsSection(props: {+ company?: CrmCompanyEntity;+ contacts?: CompanyContact[];+}) {+ const contacts = () => props.contacts ?? [];+ const { replaceOrInsertSplit } = useSplitLayout();++ const [search, setSearch] = createSignal('');+ const filtered = createMemo(() => {+ const query = search().trim().toLowerCase();+ if (!query) return contacts();+ return contacts().filter(+ (contact) =>+ contact.name?.toLowerCase().includes(query) ||+ contact.email.toLowerCase().includes(query)+ );+ });++ return (+ <Show+ when={props.company}+ fallback={<div class="text-sm text-ink-muted">Loading…</div>}+ >+ <Show+ when={contacts().length > 0}+ fallback={<div class="text-sm text-ink-muted">No contacts yet.</div>}+ >+ <div class="flex flex-col gap-2">+ <input+ type="text"+ value={search()}+ onInput={(event) => setSearch(event.currentTarget.value)}+ placeholder="Search contacts…"+ class="w-full rounded-md border border-edge bg-surface px-2 py-1 text-sm text-ink placeholder:text-ink-placeholder focus:outline-none"+ />+ <Show+ when={filtered().length > 0}+ fallback={+ <div class="text-sm text-ink-muted">No matching contacts.</div>+ }+ >+ <div+ class="flex flex-col gap-2"+ classList={{+ // ~5 two-line rows tall; scroll for the rest.+ 'max-h-[13.5rem] overflow-y-auto scrollbar-hidden':+ filtered().length > 5,+ }}+ >+ <For each={filtered()}>+ {(contact) => (+ <button+ type="button"+ onClick={() =>+ replaceOrInsertSplit({+ type: 'contact',+ id: contact.id,+ })+ }+ class="flex min-w-0 flex-col gap-0.5 rounded-md px-1 py-0.5 text-left hover:bg-ink-muted/[0.06]"+ >+ <span class="truncate text-sm">+ {contact.name ?? contact.email}+ </span>+ <Show when={contact.name}>+ <span class="truncate text-xs text-ink-muted">+ {contact.email}+ </span>+ </Show>+ </button>+ )}+ </For>+ </div>+ </Show>+ </div>+ </Show>+ </Show>+ );+}diff --git a/js/app/packages/companies/Company/CompanyDiscussionSection.tsx b/js/app/packages/companies/Company/CompanyDiscussionSection.tsxnew file mode 100644index 0000000000..75dfd9ae87--- /dev/null+++ b/js/app/packages/companies/Company/CompanyDiscussionSection.tsx@@ -0,0 +1,16 @@+import { Discussion, DiscussionProvider } from '@core/comments/discussion';+import { CrmCommentEntityType } from '@service-storage/generated/schemas/crmCommentEntityType';+import { useCrmDiscussionSource } from './crmDiscussionSource';++/** Comment discussion for a CRM company, reusing the shared discussion UI. */+export function CompanyDiscussionSection(props: { companyId: string }) {+ const source = useCrmDiscussionSource(+ CrmCommentEntityType.crm_company,+ () => props.companyId+ );+ return (+ <DiscussionProvider source={source}>+ <Discussion />+ </DiscussionProvider>+ );+}diff --git a/js/app/packages/companies/Company/CompanyEmailsSection.tsx b/js/app/packages/companies/Company/CompanyEmailsSection.tsxnew file mode 100644index 0000000000..dab88e0e3f--- /dev/null+++ b/js/app/packages/companies/Company/CompanyEmailsSection.tsx@@ -0,0 +1,89 @@+import { openEntityInSplitFromUnifiedList } from '@app/component/next-soup/utils';+import { TabsInset } from '@core/component/TabsInset';+import { type CrmCompanyEntity, ListEntity, ListLayoutProvider } from '@entity';+import { createMemo, createSignal, For, Show } from 'solid-js';+import {+ type EmailView,+ useCompanyEmailsQuery,+} from './use-company-emails-query';+import { useInfiniteScrollSentinel } from './use-infinite-scroll-sentinel';++export function CompanyEmailsSection(props: { company?: CrmCompanyEntity }) {+ const domains = createMemo(+ () => props.company?.domains.map((domain) => domain.domain) ?? []+ );+ const [view, setView] = createSignal<EmailView>('team');+ const emailsQuery = useCompanyEmailsQuery(domains, view);+ const emails = () => emailsQuery.data?.entities ?? [];++ const [listRef, setListRef] = createSignal<HTMLElement>();+ const [sentinelRef, setSentinelRef] = createSignal<HTMLDivElement>();++ useInfiniteScrollSentinel({+ sentinel: sentinelRef,+ hasNextPage: () => emailsQuery.hasNextPage ?? false,+ isFetchingNextPage: () => emailsQuery.isFetchingNextPage,+ fetchNextPage: () => emailsQuery.fetchNextPage(),+ });++ const emptyMessage = () => {+ if (view() === 'me') return 'No emails with this company in your inbox.';+ if (props.company?.emailSync === false) {+ return 'Email sync is disabled for this company.';+ }+ return 'No emails with this company yet.';+ };++ return (+ <div class="flex flex-col gap-2">+ <div class="flex items-center justify-between gap-2">+ <h2 class="text-sm font-medium text-ink-muted">Emails</h2>+ <TabsInset+ list={[+ { value: 'team', label: 'Team' },+ { value: 'me', label: 'Me' },+ ]}+ value={view()}+ onChange={(v) => setView(v as EmailView)}+ />+ </div>+ <Show+ when={props.company && !emailsQuery.isLoading}+ fallback={+ <div class="p-6 text-center text-sm text-ink-muted">Loading…</div>+ }+ >+ <Show+ when={emails().length > 0}+ fallback={+ <div class="rounded-lg border border-dashed border-edge-muted p-6 text-center text-sm text-ink-muted">+ {emptyMessage()}+ </div>+ }+ >+ <ListLayoutProvider ref={listRef}>+ <div ref={setListRef} class="flex flex-col">+ <For each={emails()}>+ {(entity) => (+ <ListEntity+ entity={entity}+ timestamp={entity.updatedAt}+ onClick={() => openEntityInSplitFromUnifiedList(entity, {})}+ />+ )}+ </For>+ </div>+ </ListLayoutProvider>+ <Show when={emailsQuery.hasNextPage}>+ <div ref={setSentinelRef} class="h-px" />+ </Show>+ <Show when={emailsQuery.isFetchingNextPage}>+ <div class="p-3 text-center text-xs text-ink-muted">+ Loading more…+ </div>+ </Show>+ </Show>+ </Show>+ </div>+ );+}diff --git a/js/app/packages/companies/Company/CompanyHeader.tsx b/js/app/packages/companies/Company/CompanyHeader.tsxnew file mode 100644index 0000000000..1d2af06ad9--- /dev/null+++ b/js/app/packages/companies/Company/CompanyHeader.tsx@@ -0,0 +1,58 @@+import { EntityIcon } from '@core/component/EntityIcon';+import type { CrmCompanyEntity } from '@entity';+import { createEffect, createSignal, Show } from 'solid-js';++function Description(props: { text: string }) {+ const [expanded, setExpanded] = createSignal(false);+ const [hasOverflow, setHasOverflow] = createSignal(false);+ let ref: HTMLParagraphElement | undefined;++ // Measure overflow while clamped; rerun when the text changes or after+ // collapsing back. Skip while expanded — clientHeight then equals+ // scrollHeight and would flip hasOverflow off incorrectly.+ createEffect(() => {+ props.text;+ if (expanded()) return;+ requestAnimationFrame(() => {+ if (ref) setHasOverflow(ref.scrollHeight > ref.clientHeight + 1);+ });+ });++ return (+ <div class="flex flex-col items-start gap-0.5">+ <p+ ref={ref}+ class={`text-sm text-ink-muted ${expanded() ? '' : 'line-clamp-2'}`}+ >+ {props.text}+ </p>+ <Show when={hasOverflow()}>+ <button+ type="button"+ onClick={() => setExpanded(!expanded())}+ class="text-xs text-ink-muted underline hover:text-ink"+ >+ {expanded() ? 'Show less' : 'Show more'}+ </button>+ </Show>+ </div>+ );+}++export function CompanyHeader(props: { company?: CrmCompanyEntity }) {+ return (+ <div class="flex items-start gap-3">+ <div class="size-10 shrink-0">+ <EntityIcon targetType="crm_company" size="fill" />+ </div>+ <div class="flex min-w-0 flex-col gap-1">+ <h1 class="min-w-0 truncate text-xl font-semibold">+ {props.company ? props.company.name || 'Company' : 'Loading company…'}+ </h1>+ <Show when={props.company?.description}>+ {(description) => <Description text={description()} />}+ </Show>+ </div>+ </div>+ );+}diff --git a/js/app/packages/companies/Company/CompanyMetadataSection.tsx b/js/app/packages/companies/Company/CompanyMetadataSection.tsxnew file mode 100644index 0000000000..b8502a2306--- /dev/null+++ b/js/app/packages/companies/Company/CompanyMetadataSection.tsx@@ -0,0 +1,33 @@+import type { CrmCompanyEntity } from '@entity';+import { For, type JSX, Show } from 'solid-js';++function Field(props: { label: string; children: JSX.Element }) {+ return (+ <div class="flex flex-col gap-0.5">+ <span class="text-xs text-ink-muted">{props.label}</span>+ <div class="text-sm">{props.children}</div>+ </div>+ );+}++export function CompanyMetadataSection(props: { company?: CrmCompanyEntity }) {+ return (+ <Show+ when={props.company}+ fallback={<div class="text-sm text-ink-muted">Loading…</div>}+ >+ {(company) => (+ <div class="flex flex-col gap-3">+ <Field label="Domains">+ <For+ each={company().domains}+ fallback={<span class="text-ink-muted">None</span>}+ >+ {(domain) => <div class="truncate">{domain.domain}</div>}+ </For>+ </Field>+ </div>+ )}+ </Show>+ );+}diff --git a/js/app/packages/companies/Company/CompanySharingSection.tsx b/js/app/packages/companies/Company/CompanySharingSection.tsxnew file mode 100644index 0000000000..d43e9e0710--- /dev/null+++ b/js/app/packages/companies/Company/CompanySharingSection.tsx@@ -0,0 +1,131 @@+import { useSplitLayout } from '@app/component/split-layout/layout';+import { toast } from '@core/component/Toast/Toast';+import type { CrmCompanyEntity } from '@entity';+import {+ useSetCompanyHiddenMutation,+ useSetEmailSyncMutation,+} from '@queries/crm/companies';+import { useIsTeamAdmin } from '@queries/team/teams';+import { cn, InlineCheckbox } from '@ui';+import { Show } from 'solid-js';++const TOGGLE_BUTTON_CLASS =+ 'inline-flex items-center gap-2 rounded-md h-7 px-2.5 text-xs select-none w-fit border border-ink-muted/[0.08] bg-ink-muted/[0.025] text-ink hover:bg-ink-muted/[0.06]';++export function CompanySharingSection(props: { company?: CrmCompanyEntity }) {+ const hideMutation = useSetCompanyHiddenMutation();+ const emailSyncMutation = useSetEmailSyncMutation();+ const { replaceOrInsertSplit } = useSplitLayout();+ const isTeamAdmin = useIsTeamAdmin();++ const handleToggleShare = async (+ company: CrmCompanyEntity,+ nextShared: boolean+ ) => {+ const willHide = !nextShared;+ try {+ await hideMutation.mutateAsync({+ companyId: company.id,+ hidden: willHide,+ });+ // On hide (un-share), drop the user back to the companies list and toast.+ // Un-hide leaves them on the block.+ if (willHide) {+ toast.success('Company hidden.');+ replaceOrInsertSplit({ type: 'component', id: 'companies' });+ }+ } catch (error) {+ console.error('failed to update company sharing', error);+ toast.failure('Could not update company visibility');+ }+ };++ const handleToggleEmailSync = async (+ company: CrmCompanyEntity,+ nextEmailSync: boolean+ ) => {+ try {+ await emailSyncMutation.mutateAsync({+ companyId: company.id,+ emailSync: nextEmailSync,+ });+ } catch (error) {+ console.error('failed to update company email sync', error);+ toast.failure('Could not update email sync');+ }+ };++ return (+ <Show+ when={props.company}+ fallback={<div class="text-xs text-ink-muted">Loading…</div>}+ >+ {(company) => {+ const isShared = () => !company().hidden;+ // The detail query always supplies a real boolean; `?? false` only+ // covers the type-level "not loaded" case (search-derived entities).+ const isSyncing = () => company().emailSync ?? false;+ // Disable interaction during pending mutations, when the backend+ // would reject (409 CompanyHidden on re-enabling sync for a hidden+ // company — un-share first), or for non-admins. The greyed-out+ // visual is reserved for the non-admin case only.+ const shareDisabled = () => hideMutation.isPending || !isTeamAdmin();+ const syncDisabled = () =>+ emailSyncMutation.isPending || company().hidden || !isTeamAdmin();++ return (+ <div class="flex flex-col gap-4 text-xs">+ {/* Admin/owner-only: if a non-admin can see the company at all,+ it's already visible to them. */}+ <Show when={isTeamAdmin()}>+ <div class="flex flex-col gap-2">+ <button+ type="button"+ role="checkbox"+ aria-checked={isShared()}+ disabled={shareDisabled()}+ onClick={() => void handleToggleShare(company(), !isShared())}+ class={cn(TOGGLE_BUTTON_CLASS)}+ >+ <InlineCheckbox checked={isShared()} />+ <span class="whitespace-nowrap">Visible in CRM</span>+ </button>+ <p class="text-ink-muted leading-5">+ Shows this company in your team's CRM lists and search. Hide+ companies that aren't relevant to your team's CRM.+ </p>+ </div>+ </Show>++ <div class="flex flex-col gap-2">+ <button+ type="button"+ role="checkbox"+ aria-checked={isSyncing()}+ disabled={syncDisabled()}+ onClick={() =>+ void handleToggleEmailSync(company(), !isSyncing())+ }+ class={cn(+ TOGGLE_BUTTON_CLASS,+ !isTeamAdmin() && 'pointer-events-none opacity-50'+ )}+ >+ <InlineCheckbox checked={isSyncing()} />+ <span class="whitespace-nowrap">Sync Emails</span>+ </button>+ <p class="text-ink-muted leading-5">+ Lets everyone on your team see each other's emails with this+ company.+ <Show when={!isTeamAdmin()}>+ {' '}+ Contact a team admin or owner to toggle.+ </Show>+ </p>+ </div>+ </div>+ );+ }}+ </Show>+ );+}diff --git a/js/app/packages/companies/Company/crmDiscussionSource.ts b/js/app/packages/companies/Company/crmDiscussionSource.tsnew file mode 100644index 0000000000..11d0154b4e--- /dev/null+++ b/js/app/packages/companies/Company/crmDiscussionSource.ts@@ -0,0 +1,183 @@+import type {+ DiscussionComment,+ DiscussionSource,+ DiscussionThread,+} from '@core/comments/discussion';+import { toast } from '@core/component/Toast/Toast';+import { useUserId } from '@core/context/user';+import { compareDateAsc } from '@core/util/date';+import {+ useCreateCrmCommentMutation,+ useCrmCommentsQuery,+ useDeleteCrmCommentMutation,+ useEditCrmCommentMutation,+} from '@queries/crm/comments';+import { crmKeys } from '@queries/crm/keys';+import type { CrmComment } from '@service-storage/generated/schemas/crmComment';+import type { CrmCommentEntityType } from '@service-storage/generated/schemas/crmCommentEntityType';+import type { CrmCommentThread } from '@service-storage/generated/schemas/crmCommentThread';+import { useQueryClient } from '@tanstack/solid-query';+import { type Accessor, createMemo } from 'solid-js';++/** Maps a server `CrmCommentThread` (uuid ids) to the normalized view model. */+function toViewThread(ct: CrmCommentThread): DiscussionThread {+ const comments: DiscussionComment[] = [...ct.comments]+ .sort((a, b) => compareDateAsc(a.createdAt, b.createdAt))+ .map((c) => ({+ id: c.commentId,+ threadId: c.threadId,+ authorId: c.sender ?? c.owner,+ text: c.text,+ createdAt: c.createdAt,+ updatedAt: c.updatedAt,+ deletedAt: c.deletedAt ?? null,+ }));+ return {+ id: ct.thread.threadId,+ resolved: ct.thread.resolved,+ comments,+ };+}++/** Replaces the matching thread or appends it when new. */+function upsertThread(+ prev: CrmCommentThread[],+ next: CrmCommentThread+): CrmCommentThread[] {+ let replaced = false;+ const out = prev.map((t) => {+ if (t.thread.threadId === next.thread.threadId) {+ replaced = true;+ return next;+ }+ return t;+ });+ if (!replaced) out.push(next);+ return out;+}++/**+ * [`DiscussionSource`] backed by the CRM comments API for a company or+ * contact. Ids are already uuid strings, so no id adaptation is needed; the+ * `DISCUSSION:` mark filter doesn't apply either (every CRM thread is a+ * discussion). Backed by the `@queries/crm/comments` TanStack query with+ * point cache updates after each mutation. Must be called within a+ * component owner.+ */+export function useCrmDiscussionSource(+ entityType: CrmCommentEntityType,+ entityId: Accessor<string | undefined>+): DiscussionSource {+ const userId = useUserId();+ const queryClient = useQueryClient();++ const commentsQuery = useCrmCommentsQuery(entityType, entityId);+ const createMutation = useCreateCrmCommentMutation();+ const editMutation = useEditCrmCommentMutation();+ const deleteMutation = useDeleteCrmCommentMutation();++ const threads = createMemo<DiscussionThread[]>(() =>+ (commentsQuery.data ?? []).map(toViewThread)+ );++ const setThreads = (+ updater: (prev: CrmCommentThread[]) => CrmCommentThread[]+ ) => {+ const id = entityId();+ if (!id) return;+ queryClient.setQueryData<CrmCommentThread[]>(+ crmKeys.comments(entityType, id).queryKey,+ (prev) => updater(prev ?? [])+ );+ };++ const replaceComment = (updated: CrmComment) =>+ setThreads((prev) =>+ prev.map((ct) =>+ ct.thread.threadId === updated.threadId+ ? {+ ...ct,+ comments: ct.comments.map((c) =>+ c.commentId === updated.commentId ? updated : c+ ),+ }+ : ct+ )+ );++ return {+ threads,+ canEdit: () => !!userId(),+ currentUserId: userId,+ // CRM comments aren't deep-linked yet: no target to highlight, and+ // `buildCommentLink` is omitted so the copy-link affordance stays hidden.+ targetCommentId: () => null,+ async createThread(text) {+ const id = entityId();+ if (!id) return;+ try {+ const thread = await createMutation.mutateAsync({+ entityType,+ entityId: id,+ text,+ });+ setThreads((prev) => upsertThread(prev, thread));+ } catch (error) {+ console.error('Unable to create CRM comment', error);+ toast.failure('Could not post comment');+ }+ },+ async createReply(threadId, text) {+ const id = entityId();+ if (!id) return;+ try {+ const thread = await createMutation.mutateAsync({+ entityType,+ entityId: id,+ text,+ threadId,+ });+ setThreads((prev) => upsertThread(prev, thread));+ } catch (error) {+ console.error('Unable to reply to CRM comment', error);+ toast.failure('Could not post reply');+ }+ },+ async editComment(comment, text) {+ try {+ const updated = await editMutation.mutateAsync({+ commentId: comment.id,+ text,+ });+ replaceComment(updated);+ } catch (error) {+ console.error('Unable to edit CRM comment', error);+ toast.failure('Could not edit comment');+ }+ },+ async deleteComment(comment) {+ try {+ const { threadId, threadDeleted } = await deleteMutation.mutateAsync({+ commentId: comment.id,+ });+ setThreads((prev) =>+ threadDeleted+ ? prev.filter((ct) => ct.thread.threadId !== threadId)+ : prev.map((ct) =>+ ct.thread.threadId === threadId+ ? {+ ...ct,+ comments: ct.comments.filter(+ (c) => c.commentId !== comment.id+ ),+ }+ : ct+ )+ );+ } catch (error) {+ console.error('Unable to delete CRM comment', error);+ toast.failure('Could not delete comment');+ }+ },+ };+}diff --git a/js/app/packages/companies/Company/emailFilter.ts b/js/app/packages/companies/Company/emailFilter.tsnew file mode 100644index 0000000000..67e6c413fd--- /dev/null+++ b/js/app/packages/companies/Company/emailFilter.ts@@ -0,0 +1,46 @@+/**+ * Builders for the soup `/soup/ast` raw email-filter tree (`ef`). Mirrors+ * the Rust `Expr<EmailLiteral>` serialization so the FE can construct an+ * any-direction OR-tree for the "Me" tab (which intentionally drops the+ * `ecd` / `eca` CRM-scope widener, so the default per-user mailbox scope+ * applies).+ *+ * Wire shape:+ * Or(a, b) → { "|": [a, b] }+ * Literal(EmailLiteral::Sender(Email::Complete("..."))) →+ * { l: { Sender: { Complete: "..." } } }+ */++type EmailValue = { Complete: string } | { Domain: string };++/**+ * OR-tree across Sender / Cc / Bcc / Recipient for a single email value.+ * Mirrors the Rust `any_direction(e)` helper in `item_filters::ast::email`.+ */+function anyDirection(value: EmailValue): unknown {+ return {+ '|': [+ {+ '|': [{ l: { Sender: value } }, { l: { Cc: value } }],+ },+ {+ '|': [{ l: { Bcc: value } }, { l: { Recipient: value } }],+ },+ ],+ };+}++/** Any-direction match for a single fully-qualified email address. */+export function emailFilterForAddress(email: string): unknown {+ return anyDirection({ Complete: email });+}++/**+ * Any-direction match for any of the given domains. Returns `undefined`+ * when the list is empty so the caller can skip setting `ef` entirely.+ */+export function emailFilterForDomains(domains: string[]): unknown | undefined {+ if (domains.length === 0) return undefined;+ const trees = domains.map((d) => anyDirection({ Domain: d }));+ return trees.reduce((acc, cur) => ({ '|': [acc, cur] }));+}diff --git a/js/app/packages/companies/Company/use-company-emails-query.ts b/js/app/packages/companies/Company/use-company-emails-query.tsnew file mode 100644index 0000000000..72cf3a9e12--- /dev/null+++ b/js/app/packages/companies/Company/use-company-emails-query.ts@@ -0,0 +1,45 @@+import { NIL_UUID } from '@app/component/next-soup/filters/filter-store';+import { useSoupAstItemsQuery } from '@queries/soup/items';+import type { Accessor } from 'solid-js';+import { emailFilterForDomains } from './emailFilter';++export type EmailView = 'team' | 'me';++/**+ * Email threads the team has exchanged with a company, fetched via the+ * `/soup/ast` endpoint.+ *+ * - `team` (default): widens visibility to every teammate's mailbox via+ * the CRM-scoped domain filter (`ecd`).+ * - `me`: drops `ecd` and uses a raw `ef` any-direction OR-tree across+ * the company's domains, so the default per-user mailbox scope applies+ * and only the current user's own emails come back.+ */+export function useCompanyEmailsQuery(+ domains: Accessor<string[]>,+ view: Accessor<EmailView>+) {+ return useSoupAstItemsQuery(+ () => {+ const base = {+ df: { l: { id: NIL_UUID } },+ chanf: { l: { ChannelId: NIL_UUID } },+ cf: { l: { cid: NIL_UUID } },+ pf: { l: { pid: NIL_UUID } },+ callf: { l: { CallId: NIL_UUID } },+ ccf: { l: { id: NIL_UUID } },+ fef: { l: { id: NIL_UUID } },+ emailView: 'all',+ };+ const body =+ view() === 'me'+ ? { ...base, ef: emailFilterForDomains(domains()) }+ : { ...base, ecd: domains() };+ return {+ params: { limit: 100, sort_method: 'updated_at' },+ body,+ };+ },+ () => ({ enabled: domains().length > 0 })+ );+}diff --git a/js/app/packages/companies/Company/use-infinite-scroll-sentinel.ts b/js/app/packages/companies/Company/use-infinite-scroll-sentinel.tsnew file mode 100644index 0000000000..85d00c1a34--- /dev/null+++ b/js/app/packages/companies/Company/use-infinite-scroll-sentinel.ts@@ -0,0 +1,60 @@+import { type Accessor, createEffect, onCleanup } from 'solid-js';++interface UseInfiniteScrollSentinelOptions {+ /** Ref to the sentinel element placed at the bottom of the list. */+ sentinel: Accessor<HTMLElement | undefined>;+ /** Whether there's another page to fetch — observation pauses when false. */+ hasNextPage: Accessor<boolean>;+ /** True while a next-page fetch is in flight (used to avoid duplicate calls). */+ isFetchingNextPage: Accessor<boolean>;+ /** Fires when the sentinel scrolls into view and we can fetch more. */+ fetchNextPage: () => void;+ /** Extra pre-trigger margin (default `200px`). */+ rootMargin?: string;+}++/**+ * Walks up the DOM to find the nearest scrollable ancestor. IO with the+ * viewport as root doesn't work reliably for sentinels inside nested+ * scroll containers, so we want to observe relative to the actual scroller.+ * Returns `null` (viewport fallback) when no scrollable ancestor exists.+ */+function findScrollableParent(el: HTMLElement | null): HTMLElement | null {+ let cur = el?.parentElement ?? null;+ while (cur) {+ const overflowY = getComputedStyle(cur).overflowY;+ if (overflowY === 'auto' || overflowY === 'scroll') return cur;+ cur = cur.parentElement;+ }+ return null;+}++/**+ * Fires `fetchNextPage` whenever the sentinel scrolls into (or close to)+ * view, gated by `hasNextPage` + `isFetchingNextPage`. The observer is+ * torn down and re-created whenever the sentinel ref or `hasNextPage`+ * changes — when there are no more pages, no observer runs.+ */+export function useInfiniteScrollSentinel(+ opts: UseInfiniteScrollSentinelOptions+) {+ createEffect(() => {+ const node = opts.sentinel();+ if (!node || !opts.hasNextPage()) return;++ const observer = new IntersectionObserver(+ (entries) => {+ if (!entries[0]?.isIntersecting) return;+ if (!opts.hasNextPage() || opts.isFetchingNextPage()) return;+ opts.fetchNextPage();+ },+ {+ root: findScrollableParent(node),+ rootMargin: opts.rootMargin ?? '200px',+ }+ );++ observer.observe(node);+ onCleanup(() => observer.disconnect());+ });+}diff --git a/js/app/packages/companies/index.ts b/js/app/packages/companies/index.tsnew file mode 100644index 0000000000..f8cd2c2687--- /dev/null+++ b/js/app/packages/companies/index.ts@@ -0,0 +1 @@+export { Company } from './Company/Company';diff --git a/js/app/packages/companies/package.json b/js/app/packages/companies/package.jsonnew file mode 100644index 0000000000..c95c68cae1--- /dev/null+++ b/js/app/packages/companies/package.json@@ -0,0 +1,6 @@+{+ "name": "companies",+ "private": true,+ "scripts": {},+ "dependencies": {}+}diff --git a/js/app/packages/companies/tsconfig.json b/js/app/packages/companies/tsconfig.jsonnew file mode 100644index 0000000000..d9677aefea--- /dev/null+++ b/js/app/packages/companies/tsconfig.json@@ -0,0 +1,11 @@+{+ "extends": "../../tsconfig.json",+ "compilerOptions": {+ "jsx": "preserve",+ "jsxImportSource": "solid-js",+ "verbatimModuleSyntax": true,+ "moduleResolution": "bundler",+ "declaration": true,+ "composite": true+ }+}diff --git a/js/app/packages/contacts/Contact/Contact.tsx b/js/app/packages/contacts/Contact/Contact.tsxnew file mode 100644index 0000000000..462505429a--- /dev/null+++ b/js/app/packages/contacts/Contact/Contact.tsx@@ -0,0 +1,56 @@+import { SidePanel } from '@app/component/side-panel';+import { SplitToolbarLeft } from '@app/component/split-layout/components/SplitToolbar';+import { useContactQuery } from '@queries/crm/contacts';+import { useIsTeamAdmin } from '@queries/team/teams';+import { Show } from 'solid-js';+import { ContactDiscussionSection } from './ContactDiscussionSection';+import { ContactEmailsSection } from './ContactEmailsSection';+import { ContactHeader } from './ContactHeader';+import { ContactMetadataSection } from './ContactMetadataSection';+import { ContactSharingSection } from './ContactSharingSection';++/**+ * Root of the contact detail view. Owns the contact query and pushes the+ * resolved entity down to presentational children. Layout mirrors the+ * company block: middle content constrained to a centered column,+ * additional info in the right-hand SidePanel, Content/Info pill tabs+ * in narrow mode via SplitToolbarLeft.+ */+export function Contact(props: { contactId: string }) {+ const contactQuery = useContactQuery(() => props.contactId);+ const contact = () => contactQuery.data;+ const isTeamAdmin = useIsTeamAdmin();++ return (+ <SidePanel.Layout>+ <SplitToolbarLeft>+ <SidePanel.NarrowTabs />+ </SplitToolbarLeft>+ <div class="flex h-full flex-col overflow-y-auto scrollbar-hidden">+ <div class="mx-auto flex w-full max-w-3xl min-w-0 grow flex-col gap-6 px-6 pt-12 pb-12">+ <ContactHeader contact={contact()} />+ <ContactDiscussionSection contactId={props.contactId} />+ <ContactEmailsSection contact={contact()} />+ </div>+ </div>++ <SidePanel.Section+ id="contact-details"+ title="Details"+ order={10}+ defaultOpen+ >+ <ContactMetadataSection contact={contact()} />+ </SidePanel.Section>+ {/* Sharing is admin-only; hide the whole section for non-admins+ rather than rendering it empty. */}+ <Show when={isTeamAdmin()}>+ <SidePanel.Section id="contact-sharing" title="Sharing" order={25}>+ <ContactSharingSection contact={contact()} />+ </SidePanel.Section>+ </Show>+ {/* TODO: add a References section (inbound channel messages + documents)+ once the references backend supports the crm_contact entity type. */}+ </SidePanel.Layout>+ );+}diff --git a/js/app/packages/contacts/Contact/ContactDiscussionSection.tsx b/js/app/packages/contacts/Contact/ContactDiscussionSection.tsxnew file mode 100644index 0000000000..e67ed79382--- /dev/null+++ b/js/app/packages/contacts/Contact/ContactDiscussionSection.tsx@@ -0,0 +1,16 @@+import { useCrmDiscussionSource } from '@companies/Company/crmDiscussionSource';+import { Discussion, DiscussionProvider } from '@core/comments/discussion';+import { CrmCommentEntityType } from '@service-storage/generated/schemas/crmCommentEntityType';++/** Comment discussion for a CRM contact, reusing the shared CRM discussion source. */+export function ContactDiscussionSection(props: { contactId: string }) {+ const source = useCrmDiscussionSource(+ CrmCommentEntityType.crm_contact,+ () => props.contactId+ );+ return (+ <DiscussionProvider source={source}>+ <Discussion />+ </DiscussionProvider>+ );+}diff --git a/js/app/packages/contacts/Contact/ContactEmailsSection.tsx b/js/app/packages/contacts/Contact/ContactEmailsSection.tsxnew file mode 100644index 0000000000..bf454667ad--- /dev/null+++ b/js/app/packages/contacts/Contact/ContactEmailsSection.tsx@@ -0,0 +1,82 @@+import { openEntityInSplitFromUnifiedList } from '@app/component/next-soup/utils';+import { useInfiniteScrollSentinel } from '@companies/Company/use-infinite-scroll-sentinel';+import { TabsInset } from '@core/component/TabsInset';+import { ListEntity, ListLayoutProvider } from '@entity';+import type { CrmContactResponse } from '@service-storage/generated/schemas/crmContactResponse';+import { createSignal, For, Show } from 'solid-js';+import {+ type EmailView,+ useContactEmailsQuery,+} from './use-contact-emails-query';++export function ContactEmailsSection(props: { contact?: CrmContactResponse }) {+ const email = () => props.contact?.email;+ const [view, setView] = createSignal<EmailView>('team');+ const emailsQuery = useContactEmailsQuery(email, view);+ const emails = () => emailsQuery.data?.entities ?? [];++ const [listRef, setListRef] = createSignal<HTMLElement>();+ const [sentinelRef, setSentinelRef] = createSignal<HTMLDivElement>();++ useInfiniteScrollSentinel({+ sentinel: sentinelRef,+ hasNextPage: () => emailsQuery.hasNextPage ?? false,+ isFetchingNextPage: () => emailsQuery.isFetchingNextPage,+ fetchNextPage: () => emailsQuery.fetchNextPage(),+ });++ return (+ <div class="flex flex-col gap-2">+ <div class="flex items-center justify-between gap-2">+ <h2 class="text-sm font-medium text-ink-muted">Emails</h2>+ <TabsInset+ list={[+ { value: 'team', label: 'Team' },+ { value: 'me', label: 'Me' },+ ]}+ value={view()}+ onChange={(v) => setView(v as EmailView)}+ />+ </div>+ <Show+ when={props.contact && !emailsQuery.isLoading}+ fallback={+ <div class="p-6 text-center text-sm text-ink-muted">Loading…</div>+ }+ >+ <Show+ when={emails().length > 0}+ fallback={+ <div class="rounded-lg border border-dashed border-edge-muted p-6 text-center text-sm text-ink-muted">+ {view() === 'me'+ ? 'No emails with this contact in your inbox.'+ : 'No emails with this contact yet.'}+ </div>+ }+ >+ <ListLayoutProvider ref={listRef}>+ <div ref={setListRef} class="flex flex-col">+ <For each={emails()}>+ {(entity) => (+ <ListEntity+ entity={entity}+ timestamp={entity.updatedAt}+ onClick={() => openEntityInSplitFromUnifiedList(entity, {})}+ />+ )}+ </For>+ </div>+ </ListLayoutProvider>+ <Show when={emailsQuery.hasNextPage}>+ <div ref={setSentinelRef} class="h-px" />+ </Show>+ <Show when={emailsQuery.isFetchingNextPage}>+ <div class="p-3 text-center text-xs text-ink-muted">+ Loading more…+ </div>+ </Show>+ </Show>+ </Show>+ </div>+ );+}diff --git a/js/app/packages/contacts/Contact/ContactHeader.tsx b/js/app/packages/contacts/Contact/ContactHeader.tsxnew file mode 100644index 0000000000..3ce88bd1e8--- /dev/null+++ b/js/app/packages/contacts/Contact/ContactHeader.tsx@@ -0,0 +1,47 @@+import { getInitialsFromName } from '@core/user';+import { AnimatedContactIcon } from '@icon/wide-contact';+import type { CrmContactResponse } from '@service-storage/generated/schemas/crmContactResponse';+import { Avatar } from '@ui';+import { Show } from 'solid-js';++export function ContactHeader(props: { contact?: CrmContactResponse }) {+ const displayName = () => props.contact?.name ?? props.contact?.email;+ const showSubtitle = () =>+ props.contact?.name != null && props.contact.name !== props.contact.email;++ // Default avatar mirrors the channel user avatar: initials on a flat circle.+ // Contacts have no photo, so initials come from the name or email.+ const initials = () => {+ const email = props.contact?.email;+ if (!email) return undefined;+ return getInitialsFromName(props.contact?.name, email);+ };++ return (+ <div class="flex items-start gap-3">+ <Avatar size="lg" class="shrink-0">+ <Show+ when={initials()}+ fallback={+ <Avatar.Fallback>+ <AnimatedContactIcon class="size-5 text-ink-muted" />+ </Avatar.Fallback>+ }+ keyed+ >+ {(value) => (+ <Avatar.Fallback class="font-semibold">{value}</Avatar.Fallback>+ )}+ </Show>+ </Avatar>+ <div class="flex min-w-0 flex-col gap-1">+ <h1 class="min-w-0 truncate text-xl font-semibold">+ {displayName() ?? 'Contact'}+ </h1>+ <Show when={showSubtitle()}>+ <p class="truncate text-sm text-ink-muted">{props.contact?.email}</p>+ </Show>+ </div>+ </div>+ );+}diff --git a/js/app/packages/contacts/Contact/ContactMetadataSection.tsx b/js/app/packages/contacts/Contact/ContactMetadataSection.tsxnew file mode 100644index 0000000000..249a463746--- /dev/null+++ b/js/app/packages/contacts/Contact/ContactMetadataSection.tsx@@ -0,0 +1,53 @@+import { NIL_UUID } from '@app/component/next-soup/filters/filter-store';+import { useSplitLayout } from '@app/component/split-layout/layout';+import { useCompanyQuery } from '@queries/crm/companies';+import type { CrmContactResponse } from '@service-storage/generated/schemas/crmContactResponse';+import { type JSX, Show } from 'solid-js';++function Field(props: { label: string; children: JSX.Element }) {+ return (+ <div class="flex flex-col gap-0.5">+ <span class="text-xs text-ink-muted">{props.label}</span>+ <div class="text-sm">{props.children}</div>+ </div>+ );+}++export function ContactMetadataSection(props: {+ contact?: CrmContactResponse;+}) {+ const { replaceOrInsertSplit } = useSplitLayout();+ // NIL while the contact is loading — useCompanyQuery's `enabled` gate+ // excludes it, so no doomed 404 fires before the real companyId arrives.+ const { company } = useCompanyQuery(+ () => props.contact?.companyId ?? NIL_UUID+ );++ const openCompany = (companyId: string) => {+ replaceOrInsertSplit({ type: 'company', id: companyId });+ };++ return (+ <Show+ when={props.contact}+ fallback={<div class="text-sm text-ink-muted">Loading…</div>}+ >+ {(contact) => (+ <div class="flex flex-col gap-3">+ <Field label="Email">+ <span class="truncate">{contact().email}</span>+ </Field>+ <Field label="Company">+ <button+ type="button"+ onClick={() => openCompany(contact().companyId)}+ class="text-left text-sm text-accent hover:underline"+ >+ {company()?.name ?? 'Open company'}+ </button>+ </Field>+ </div>+ )}+ </Show>+ );+}diff --git a/js/app/packages/contacts/Contact/ContactSharingSection.tsx b/js/app/packages/contacts/Contact/ContactSharingSection.tsxnew file mode 100644index 0000000000..b980c137e5--- /dev/null+++ b/js/app/packages/contacts/Contact/ContactSharingSection.tsx@@ -0,0 +1,67 @@+import { toast } from '@core/component/Toast/Toast';+import { useSetContactHiddenMutation } from '@queries/crm/contacts';+import type { CrmContactResponse } from '@service-storage/generated/schemas/crmContactResponse';+import { cn, InlineCheckbox } from '@ui';+import { Show } from 'solid-js';++const TOGGLE_BUTTON_CLASS =+ 'inline-flex items-center gap-2 rounded-md h-7 px-2.5 text-xs select-none w-fit border border-ink-muted/[0.08] bg-ink-muted/[0.025] text-ink hover:bg-ink-muted/[0.06]';++/**+ * Admin-only (the parent gates the whole section on `useIsTeamAdmin`):+ * if a non-admin can see the contact at all, it's already visible to them.+ */+export function ContactSharingSection(props: { contact?: CrmContactResponse }) {+ const hiddenMutation = useSetContactHiddenMutation();++ const handleToggle = async (+ contact: CrmContactResponse,+ nextShared: boolean+ ) => {+ const willHide = !nextShared;+ try {+ await hiddenMutation.mutateAsync({+ contactId: contact.id,+ hidden: willHide,+ });+ if (willHide) {+ toast.success('Contact hidden.');+ }+ } catch (error) {+ console.error('failed to update contact sharing', error);+ toast.failure('Could not update contact visibility');+ }+ };++ return (+ <Show+ when={props.contact}+ fallback={<div class="text-xs text-ink-muted">Loading…</div>}+ >+ {(contact) => {+ const isShared = () => !contact().hidden;+ return (+ <div class="flex flex-col gap-4 text-xs">+ <div class="flex flex-col gap-2">+ <button+ type="button"+ role="checkbox"+ aria-checked={isShared()}+ disabled={hiddenMutation.isPending}+ onClick={() => void handleToggle(contact(), !isShared())}+ class={cn(TOGGLE_BUTTON_CLASS)}+ >+ <InlineCheckbox checked={isShared()} />+ <span class="whitespace-nowrap">Visible in CRM</span>+ </button>+ <p class="text-ink-muted leading-5">+ Shows this contact in their company's contact list. Hide+ contacts that aren't relevant to your team's CRM.+ </p>+ </div>+ </div>+ );+ }}+ </Show>+ );+}diff --git a/js/app/packages/contacts/Contact/use-contact-emails-query.ts b/js/app/packages/contacts/Contact/use-contact-emails-query.tsnew file mode 100644index 0000000000..b3f9a3abc5--- /dev/null+++ b/js/app/packages/contacts/Contact/use-contact-emails-query.ts@@ -0,0 +1,49 @@+import { NIL_UUID } from '@app/component/next-soup/filters/filter-store';+import { emailFilterForAddress } from '@companies/Company/emailFilter';+import { useSoupAstItemsQuery } from '@queries/soup/items';+import type { Accessor } from 'solid-js';++export type EmailView = 'team' | 'me';++/**+ * Email threads involving a single CRM contact, fetched via the+ * `/soup/ast` endpoint.+ *+ * - `team` (default): widens visibility to every teammate's mailbox via+ * the CRM-scoped address filter (`eca`).+ * - `me`: drops `eca` and uses a raw `ef` any-direction OR-tree on the+ * contact's address, so the default per-user mailbox scope applies and+ * only the current user's own emails come back.+ */+export function useContactEmailsQuery(+ email: Accessor<string | undefined>,+ view: Accessor<EmailView>+) {+ return useSoupAstItemsQuery(+ () => {+ const addr = email();+ const base = {+ df: { l: { id: NIL_UUID } },+ chanf: { l: { ChannelId: NIL_UUID } },+ cf: { l: { cid: NIL_UUID } },+ pf: { l: { pid: NIL_UUID } },+ callf: { l: { CallId: NIL_UUID } },+ ccf: { l: { id: NIL_UUID } },+ fef: { l: { id: NIL_UUID } },+ emailView: 'all',+ };+ const body =+ view() === 'me'+ ? {+ ...base,+ ef: addr ? emailFilterForAddress(addr) : undefined,+ }+ : { ...base, eca: addr ? [addr] : [] };+ return {+ params: { limit: 100, sort_method: 'updated_at' },+ body,+ };+ },+ () => ({ enabled: !!email() })+ );+}diff --git a/js/app/packages/contacts/index.ts b/js/app/packages/contacts/index.tsnew file mode 100644index 0000000000..e86774569d--- /dev/null+++ b/js/app/packages/contacts/index.ts@@ -0,0 +1 @@+export { Contact } from './Contact/Contact';diff --git a/js/app/packages/contacts/package.json b/js/app/packages/contacts/package.jsonnew file mode 100644index 0000000000..ebd560099a--- /dev/null+++ b/js/app/packages/contacts/package.json@@ -0,0 +1,6 @@+{+ "name": "contacts",+ "private": true,+ "scripts": {},+ "dependencies": {}+}diff --git a/js/app/packages/contacts/tsconfig.json b/js/app/packages/contacts/tsconfig.jsonnew file mode 100644index 0000000000..d9677aefea--- /dev/null+++ b/js/app/packages/contacts/tsconfig.json@@ -0,0 +1,11 @@+{+ "extends": "../../tsconfig.json",+ "compilerOptions": {+ "jsx": "preserve",+ "jsxImportSource": "solid-js",+ "verbatimModuleSyntax": true,+ "moduleResolution": "bundler",+ "declaration": true,+ "composite": true+ }+}diff --git a/js/app/packages/core/block.ts b/js/app/packages/core/block.tsindex c1da0d5b39..777dbb4ad9 100644--- a/js/app/packages/core/block.ts+++ b/js/app/packages/core/block.ts@@ -62,6 +62,7 @@ export const BlockRegistry = ['video','email','contact',+ 'company','automation',] as const;@@ -96,6 +97,7 @@ export const NonDocumentBlockTypes = ['project','email','contact',+ 'company','automation',] as const as (BlockName | BlockAlias)[];@@ -146,6 +148,7 @@ const _ValidBlockCombinations: BlockCombinationRules = {unknown: allBlockNames,video: allBlockNames,contact: allBlockNames,+ company: allBlockNames,task: allBlockNames,automation: allBlockNames,csv: allBlockNames,@@ -167,6 +170,7 @@ export const ValidNestingCombinations: BlockCombinationRules = {unknown: new Set([]),video: new Set([]),contact: new Set([]),+ company: new Set([]),task: new Set([]),automation: new Set([]),csv: new Set([]),diff --git a/js/app/packages/core/blockMethodRegistry.ts b/js/app/packages/core/blockMethodRegistry.tsindex b059120424..b61f99f0a1 100644--- a/js/app/packages/core/blockMethodRegistry.ts+++ b/js/app/packages/core/blockMethodRegistry.ts@@ -31,6 +31,7 @@ export interface BlockMethodRegistry {video: EmptySpec;email: EmptySpec;contact: EmptySpec;+ company: EmptySpec;color: EmptySpec;component: EmptySpec;task: EmptySpec;diff --git a/js/app/packages/core/comments/discussion/Discussion.tsx b/js/app/packages/core/comments/discussion/Discussion.tsxnew file mode 100644index 0000000000..0f1cf1c25b--- /dev/null+++ b/js/app/packages/core/comments/discussion/Discussion.tsx@@ -0,0 +1,340 @@+import type { InputSnapshot } from '@channel/Input/types';+import { Message } from '@channel/Message/Message';+import type { MessageActions } from '@channel/Message/types';+import { Thread } from '@channel/Thread/Thread';+import { ThreadRail } from '@channel/Thread/ThreadRail';+import { ThreadReplyInputConnector } from '@channel/Thread/ThreadReplyInputConnector';+import { replyInputOffsetX } from '@channel/Thread/utils/thread-rail-geometry';+import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';+import { toast } from '@core/component/Toast/Toast';+import { tryMacroId, useDisplayName } from '@core/user';+import CaretDown from '@phosphor/caret-down.svg';+import CaretRight from '@phosphor/caret-right.svg';+import { createEffect, createSignal, For, onMount, Show } from 'solid-js';+import { useDiscussion } from './context';+import { DiscussionInput } from './DiscussionInput';+import {+ discussionCommentToApiChannelMessage,+ discussionCommentToMessageData,+} from './messageAdapter';+import type {+ DiscussionComment,+ DiscussionThread as ViewThread,+} from './types';++/**+ * Renders a collapsible discussion (threads + composer) from the current+ * [`DiscussionSource`]. Backend-agnostic: drive it via a `DiscussionProvider`+ * supplying a document/task or CRM source.+ */+export function Discussion() {+ const source = useDiscussion();+ const [isExpanded, setIsExpanded] = createSignal(true);++ // Deep-linking to a comment expands the discussion.+ createEffect(() => {+ if (source.targetCommentId() !== null) setIsExpanded(true);+ });++ let newThreadInputHandle: { clear: () => void } | undefined;++ const handleCreateThread = async (snapshot: InputSnapshot) => {+ const text = snapshot.value.trim();+ if (!text) return;+ await source.createThread(text, snapshot.mentions);+ newThreadInputHandle?.clear();+ };++ return (+ <section class="mt-8 pb-12">+ <div class="flex items-center gap-2 pt-2">+ <div class="w-6 border-t border-edge-muted" />+ <button+ type="button"+ class="flex items-center gap-1 px-2 hover:opacity-70 transition-opacity"+ onClick={() => setIsExpanded(!isExpanded())}+ >+ {isExpanded() ? (+ <CaretDown class="size-3" />+ ) : (+ <CaretRight class="size-3" />+ )}+ <span class="text-xs">Discussion</span>+ </button>+ <div class="flex-1 border-t border-edge-muted" />+ </div>++ <Show when={isExpanded()}>+ <StaticMarkdownContext>+ <div class="py-2 text-xs">+ <div>+ <For each={source.threads()}>+ {(thread) => <DiscussionThreadView thread={thread} />}+ </For>+ </div>++ <Show when={source.canEdit()}>+ <div>+ <DiscussionInput+ input={{ mode: 'channel', placeholder: 'Leave a comment...' }}+ onSend={handleCreateThread}+ onReady={(handle) => {+ newThreadInputHandle = handle;+ }}+ autofocus={false}+ />+ </div>+ </Show>+ </div>+ </StaticMarkdownContext>+ </Show>+ </section>+ );+}++function DiscussionThreadView(props: { thread: ViewThread }) {+ const source = useDiscussion();+ const canEdit = source.canEdit;++ const [isReplying, setIsReplying] = createSignal(false);+ const [editingId, setEditingId] = createSignal<string | null>(null);+ let replyInputHandle: { clear: () => void } | undefined;+ let replyInputContainerRef: HTMLDivElement | undefined;++ const comments = () => props.thread.comments;+ const root = () => comments()[0];+ const replies = () => comments().slice(1);+ const hasReplies = () => replies().length > 0;+ const threadId = () => props.thread.id;++ const replyUserId = () => source.currentUserId() ?? root()?.authorId ?? '';+ const macroId = () => tryMacroId(replyUserId());+ const [displayName] = useDisplayName(macroId());++ const isOwn = (comment: DiscussionComment) =>+ comment.authorId === source.currentUserId();++ // undefined when the source has no deep-linking — hides the copy-link button.+ const makeCopyLink = (comment: DiscussionComment) => {+ const build = source.buildCommentLink;+ if (!build) return undefined;+ return async () => {+ try {+ const url = build(comment);+ await navigator.clipboard.writeText(url);+ toast.success('Link copied to clipboard');+ } catch {+ toast.failure('Could not copy link');+ }+ };+ };++ const makeActions = (+ comment: DiscussionComment,+ isRoot: boolean+ ): MessageActions => {+ const own = isOwn(comment);+ return {+ onReply:+ isRoot && canEdit()+ ? () => {+ setIsReplying(true);+ }+ : undefined,+ onEdit: own+ ? () => {+ setEditingId(comment.id);+ }+ : undefined,+ onDelete:+ own && canEdit()+ ? async () => {+ await source.deleteComment(comment);+ }+ : undefined,+ onCopyLink: makeCopyLink(comment),+ };+ };++ const handleReply = async (snapshot: InputSnapshot) => {+ const text = snapshot.value.trim();+ if (!text) return;+ await source.createReply(threadId(), text, snapshot.mentions);+ replyInputHandle?.clear();+ setIsReplying(false);+ };++ const handleEdit = async (+ comment: DiscussionComment,+ snapshot: InputSnapshot+ ) => {+ const text = snapshot.value.trim();+ if (!text) return;+ await source.editComment(comment, text);+ setEditingId(null);+ };++ return (+ <Show when={root()}>+ {(rootComment) => {+ const rootMessageData = () =>+ discussionCommentToApiChannelMessage(rootComment());+ return (+ <div class="flex flex-col w-full gap-0">+ <Thread.Row message={rootMessageData()}>+ <DiscussionMessageView+ comment={rootComment()}+ actions={makeActions(rootComment(), true)}+ editingId={editingId()}+ onEditSave={(snapshot) => handleEdit(rootComment(), snapshot)}+ onEditCancel={() => setEditingId(null)}+ isHighlighted={source.targetCommentId() === rootComment().id}+ />++ <Show when={hasReplies() || isReplying()}>+ <div class="relative w-full">+ <Thread.ReplyRailDecorations+ isReplying={isReplying}+ firstThreadReplyNewMessage={false}+ />+ <Thread.RepliesContainer>+ <For each={replies()}>+ {(reply) => (+ <div class="relative">+ <ThreadRail />+ <DiscussionMessageView+ comment={reply}+ actions={makeActions(reply, false)}+ editingId={editingId()}+ onEditSave={(snapshot) =>+ handleEdit(reply, snapshot)+ }+ onEditCancel={() => setEditingId(null)}+ isHighlighted={+ source.targetCommentId() === reply.id+ }+ />+ </div>+ )}+ </For>++ <Show when={isReplying() && canEdit()}>+ <div class="ph-no-capture">+ <Show when={!hasReplies()}>+ <Thread.ReplyAuthor+ userId={replyUserId()}+ displayName={displayName()}+ />+ </Show>+ <div+ ref={replyInputContainerRef}+ class="relative pt-2"+ style={{ 'margin-left': replyInputOffsetX }}+ >+ <ThreadReplyInputConnector />+ <DiscussionInput+ input={{ mode: 'reply', placeholder: 'Reply...' }}+ onSend={handleReply}+ onClose={() => {+ setIsReplying(false);+ }}+ onReady={(handle) => {+ replyInputHandle = handle;+ }}+ />+ </div>+ </div>+ </Show>++ <Show when={!isReplying() && canEdit()}>+ <Thread.ActionsFooter>+ <Thread.ReplyButton+ getFocusTarget={() =>+ replyInputContainerRef?.querySelector<HTMLElement>(+ '[contenteditable]'+ ) ?? null+ }+ onClick={() => setIsReplying(true)}+ aria-label="Reply"+ />+ </Thread.ActionsFooter>+ </Show>+ </Thread.RepliesContainer>+ </div>+ </Show>+ </Thread.Row>+ </div>+ );+ }}+ </Show>+ );+}++function DiscussionMessageView(props: {+ comment: DiscussionComment;+ actions: MessageActions;+ editingId: string | null;+ onEditSave: (snapshot: InputSnapshot) => void;+ onEditCancel: () => void;+ isHighlighted?: boolean;+}) {+ const isEditing = () => props.editingId === props.comment.id;+ const messageData = () => discussionCommentToMessageData(props.comment);++ let containerRef: HTMLDivElement | undefined;+ onMount(() => {+ if (props.isHighlighted) {+ containerRef?.scrollIntoView({ behavior: 'smooth', block: 'center' });+ }+ });++ return (+ <div ref={containerRef}>+ <Show+ when={!isEditing()}+ fallback={+ <DiscussionInput+ input={{+ mode: 'reply',+ placeholder: 'Edit comment...',+ value: props.comment.text,+ }}+ onSend={props.onEditSave}+ onClose={() => {+ props.onEditCancel();+ }}+ />+ }+ >+ <Message.Root+ message={messageData()}+ actions={props.actions}+ highlighted={props.isHighlighted}+ >+ <Message.Layout class="pt-(--regular-message-padding-t)">+ <Message.Slot placement="icon">+ <Message.SenderIcon />+ </Message.Slot>+ <Message.Slot+ placement="header"+ class="flex items-center gap-1 min-w-0 w-full"+ >+ <Message.SenderName />+ <Message.EditedIndicator />+ <div class="grow shrink-0 min-w-0 flex justify-end group-hover/message:absolute group-hover/message:right-1 group-hover/message:-top-9 group-hover/message:p-1">+ <Message.Timestamp+ class="ml-auto shrink-0"+ format="dateAndTime"+ />+ </div>+ </Message.Slot>+ <Message.Slot placement="content" class="ph-no-capture">+ <Message.Content />+ </Message.Slot>+ <Message.ActionMenu />+ </Message.Layout>+ </Message.Root>+ </Show>+ </div>+ );+}diff --git a/js/app/packages/block-md/component/DiscussionInput.tsx b/js/app/packages/core/comments/discussion/DiscussionInput.tsxsimilarity index 100%rename from js/app/packages/block-md/component/DiscussionInput.tsxrename to js/app/packages/core/comments/discussion/DiscussionInput.tsxdiff --git a/js/app/packages/block-md/component/configured-discussion-markdown-editor.ts b/js/app/packages/core/comments/discussion/configured-discussion-markdown-editor.tssimilarity index 100%rename from js/app/packages/block-md/component/configured-discussion-markdown-editor.tsrename to js/app/packages/core/comments/discussion/configured-discussion-markdown-editor.tsdiff --git a/js/app/packages/core/comments/discussion/context.tsx b/js/app/packages/core/comments/discussion/context.tsxnew file mode 100644index 0000000000..7af5936298--- /dev/null+++ b/js/app/packages/core/comments/discussion/context.tsx@@ -0,0 +1,24 @@+import { createContext, type ParentProps, useContext } from 'solid-js';+import type { DiscussionSource } from './types';++const DiscussionContext = createContext<DiscussionSource>();++/** Provides a [`DiscussionSource`] to the discussion components below it. */+export function DiscussionProvider(+ props: ParentProps<{ source: DiscussionSource }>+) {+ return (+ <DiscussionContext.Provider value={props.source}>+ {props.children}+ </DiscussionContext.Provider>+ );+}++/** Reads the current [`DiscussionSource`]. Throws outside a provider. */+export function useDiscussion(): DiscussionSource {+ const source = useContext(DiscussionContext);+ if (!source) {+ throw new Error('useDiscussion must be used within a DiscussionProvider');+ }+ return source;+}diff --git a/js/app/packages/core/comments/discussion/index.ts b/js/app/packages/core/comments/discussion/index.tsnew file mode 100644index 0000000000..9414599333--- /dev/null+++ b/js/app/packages/core/comments/discussion/index.ts@@ -0,0 +1,11 @@+export { DiscussionProvider, useDiscussion } from './context';+export { Discussion } from './Discussion';+export {+ discussionCommentToApiChannelMessage,+ discussionCommentToMessageData,+} from './messageAdapter';+export type {+ DiscussionComment,+ DiscussionSource,+ DiscussionThread,+} from './types';diff --git a/js/app/packages/block-md/comments/discussionAdapter.ts b/js/app/packages/core/comments/discussion/messageAdapter.tssimilarity index 51%rename from js/app/packages/block-md/comments/discussionAdapter.tsrename to js/app/packages/core/comments/discussion/messageAdapter.tsindex 9dafd6e985..4b85e07635 100644--- a/js/app/packages/block-md/comments/discussionAdapter.ts+++ b/js/app/packages/core/comments/discussion/messageAdapter.ts@@ -1,16 +1,19 @@import type { MessageData } from '@channel/Message/types';import { senderFromStorageId } from '@queries/channel/message-sender';import type { ApiChannelMessage } from '@service-storage/generated/schemas/apiChannelMessage';-import type { Comment } from '@service-storage/generated/schemas/comment';+import type { DiscussionComment } from './types';-export function commentToMessageData(comment: Comment): MessageData {+/** Maps a normalized discussion comment to the channel `Message` shape. */+export function discussionCommentToMessageData(+ comment: DiscussionComment+): MessageData {return {- id: String(comment.commentId),+ id: comment.id,content: comment.text,- sender_id: comment.sender ?? comment.owner,- created_at: comment.createdAt ?? '',- updated_at: comment.updatedAt ?? comment.createdAt ?? '',- deleted_at: comment.deletedAt ?? null,+ sender_id: comment.authorId,+ created_at: comment.createdAt,+ updated_at: comment.updatedAt,+ deleted_at: comment.deletedAt,edited_at:comment.updatedAt && comment.updatedAt !== comment.createdAt? comment.updatedAt@@ -20,17 +23,18 @@ export function commentToMessageData(comment: Comment): MessageData {};}-export function commentToApiChannelMessage(- comment: Comment+/** Maps a normalized discussion comment to the channel `Thread.Row` shape. */+export function discussionCommentToApiChannelMessage(+ comment: DiscussionComment): ApiChannelMessage {return {- id: String(comment.commentId),+ id: comment.id,content: comment.text,- sender: senderFromStorageId(comment.sender ?? comment.owner),- sender_id: comment.sender ?? comment.owner,- created_at: comment.createdAt ?? '',- updated_at: comment.updatedAt ?? comment.createdAt ?? '',- deleted_at: comment.deletedAt ?? null,+ sender: senderFromStorageId(comment.authorId),+ sender_id: comment.authorId,+ created_at: comment.createdAt,+ updated_at: comment.updatedAt,+ deleted_at: comment.deletedAt,edited_at:comment.updatedAt && comment.updatedAt !== comment.createdAt? comment.updatedAtdiff --git a/js/app/packages/core/comments/discussion/types.ts b/js/app/packages/core/comments/discussion/types.tsnew file mode 100644index 0000000000..b00f51355c--- /dev/null+++ b/js/app/packages/core/comments/discussion/types.ts@@ -0,0 +1,68 @@+import type { ItemMention } from '@core/component/LexicalMarkdown/plugins';+import type { Accessor } from 'solid-js';++/**+ * A single comment within a discussion thread, normalized across backends.+ * Ids are strings: document comment ids are numeric and stringified by their+ * source; CRM comment ids are already uuids.+ */+export interface DiscussionComment {+ /** Stable string id (document comments use `String(numericId)`). */+ id: string;+ /** Id of the thread this comment belongs to. */+ threadId: string;+ /** Resolved author id (`sender ?? owner`). */+ authorId: string;+ /** Comment body (markdown). */+ text: string;+ /** ISO creation timestamp. */+ createdAt: string;+ /** ISO last-updated timestamp. */+ updatedAt: string;+ /** ISO soft-delete timestamp, or null. */+ deletedAt: string | null;+}++/** A discussion thread with its comments, oldest-first. */+export interface DiscussionThread {+ /** Stable string thread id. */+ id: string;+ /** Whether the thread is resolved. */+ resolved: boolean;+ /** The thread's comments, pre-sorted oldest-first. */+ comments: DiscussionComment[];+}++/**+ * Backing data + actions for a discussion, supplied per entity kind+ * (document/task, CRM company/contact). The presentational components are+ * agnostic to which source backs them — this is the seam that lets the same+ * discussion UI render document and CRM comments.+ */+export interface DiscussionSource {+ /** Threads to render, oldest-first; each thread's comments pre-sorted. */+ threads: Accessor<DiscussionThread[]>;+ /** Whether the current user may create/edit/delete here. */+ canEdit: Accessor<boolean>;+ /** Current user id, for own-comment checks. */+ currentUserId: Accessor<string | undefined>;+ /** Comment id to highlight/scroll to (deep link), or null. */+ targetCommentId: Accessor<string | null>;+ /** Start a new thread. */+ createThread(text: string, mentions: ItemMention[]): Promise<void>;+ /** Reply to an existing thread. */+ createReply(+ threadId: string,+ text: string,+ mentions: ItemMention[]+ ): Promise<void>;+ /** Edit a comment's text. */+ editComment(comment: DiscussionComment, text: string): Promise<void>;+ /** Delete a comment. */+ deleteComment(comment: DiscussionComment): Promise<void>;+ /**+ * Build a shareable deep link to a comment. Omit it when the source has no+ * deep-linking yet — the copy-link affordance is then hidden.+ */+ buildCommentLink?(comment: DiscussionComment): string;+}diff --git a/js/app/packages/core/component/AI/hook/useEntityDropAttachment.ts b/js/app/packages/core/component/AI/hook/useEntityDropAttachment.tsindex f89a6b3e84..d607e20145 100644--- a/js/app/packages/core/component/AI/hook/useEntityDropAttachment.ts+++ b/js/app/packages/core/component/AI/hook/useEntityDropAttachment.ts@@ -94,6 +94,8 @@ export function useEntityDropAttachment(.with('call', () => undefined).with('automation', () => undefined).with('foreign', () => undefined)+ .with('crm_company', () => undefined)+ .with('crm_contact', () => undefined).exhaustive();if (attachment) {diff --git a/js/app/packages/core/component/EntityIcon.tsx b/js/app/packages/core/component/EntityIcon.tsxindex 4db72fea1f..aee7660460 100644--- a/js/app/packages/core/component/EntityIcon.tsx+++ b/js/app/packages/core/component/EntityIcon.tsx@@ -18,6 +18,8 @@ import WideCalendar from '@icon/wide-calendar.svg';import PhoneCall from '@icon/wide-call.svg';import WideChannel from '@icon/wide-channel.svg';import WideChat from '@icon/wide-chat.svg';+import { AnimatedCompanyIcon } from '@icon/wide-company';+import { AnimatedContactIcon } from '@icon/wide-contact';import WideCsv from '@icon/wide-csv.svg';import WideDiagram from '@icon/wide-diagram.svg';import WideDocx from '@icon/wide-docx.svg';@@ -31,7 +33,6 @@ import WideGlobe from '@icon/wide-globe.svg';import WideStar from '@icon/wide-star.svg';import WideTask from '@icon/wide-task.svg';import WideUnknown from '@icon/wide-unknown.svg';-import WideUser from '@icon/wide-user.svg';import WideVideo from '@icon/wide-video.svg';import Building from '@phosphor/building.svg';import Chat from '@phosphor/chat.svg';@@ -53,7 +54,6 @@ import GlobeIcon from '@phosphor/globe.svg';import FileImage from '@phosphor/image.svg';import Canvas from '@phosphor/pencil-circle.svg';import Robot from '@phosphor/robot.svg';-import User from '@phosphor/user.svg';import Users from '@phosphor/users.svg';import type { PreviewItem } from '@queries/preview';import type { ChannelType } from '@service-cognition/generated/schemas/channelType';@@ -83,6 +83,7 @@ export type EntityWithValidIcon =| 'githubPullRequest'| 'archive'| 'files'+ | 'crm_company'| 'html';const ARCHIVE_EXTENSIONS = new Set(@@ -231,7 +232,7 @@ export const ENTITY_ICON_CONFIGS: Record<EntityWithValidIcon, IconConfig> = {prettyName: 'Video',},contact: {- icon: User,+ icon: AnimatedContactIcon,foreground: 'text-default',background: 'bg-default/20',prettyName: 'Contact',@@ -272,6 +273,18 @@ export const ENTITY_ICON_CONFIGS: Record<EntityWithValidIcon, IconConfig> = {background: 'bg-default/20',prettyName: 'Automation',},+ crm_company: {+ icon: AnimatedCompanyIcon,+ foreground: 'text-default',+ background: 'bg-default/20',+ prettyName: 'Company',+ },+ company: {+ icon: AnimatedCompanyIcon,+ foreground: 'text-default',+ background: 'bg-default/20',+ prettyName: 'Company',+ },};// this will match fall-through cases like code files which match multiple extensions@@ -299,7 +312,10 @@ function validateEntity(entity: string): EntityWithValidIcon {}}-const WIDE_ICONS: Record<EntityWithValidIcon, Component> = {+const WIDE_ICONS: Record<+ EntityWithValidIcon,+ Component<JSX.SvgSVGAttributes<SVGSVGElement>>+> = {call: PhoneCall,canvas: WideDiagram,html: WideFileCode,@@ -323,13 +339,15 @@ const WIDE_ICONS: Record<EntityWithValidIcon, Component> = {files: WideFiles,archive: WideUnknown,video: WideVideo,- contact: WideUser,+ contact: AnimatedContactIcon,default: WideUnknown,emailRead: WideEmail,emailInvite: WideCalendar,githubPullRequest: GithubIcon,task: WideTask,automation: Robot,+ crm_company: AnimatedCompanyIcon,+ company: AnimatedCompanyIcon,};const ICON_SIZES = {diff --git a/js/app/packages/core/component/FileList/constants.tsx b/js/app/packages/core/component/FileList/constants.tsxindex 2875ff5917..e9f32a9180 100644--- a/js/app/packages/core/component/FileList/constants.tsx+++ b/js/app/packages/core/component/FileList/constants.tsx@@ -67,6 +67,7 @@ const _fileTypeColors: Record<BlockName | BlockAlias | 'default', string> = {video: 'bg-video/20 group/item',call: defaultFileColor,contact: defaultFileColor,+ company: defaultFileColor,default: defaultFileColor,chat: defaultFileColor,channel: defaultFileColor,diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsxindex 0c4b575155..e19928c2bd 100644--- a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx@@ -3,6 +3,7 @@ import type { BlockName } from '@core/block';import { useMaybeBlockId, useMaybeBlockName } from '@core/block';import { SUPPORTED_CHAT_ATTACHMENT_BLOCKS } from '@core/component/AI/constant/fileType';import { type PortalScope, ScopedPortal } from '@core/component/ScopedPortal';+import { ENABLE_CRM } from '@core/constant/featureFlags';import { type EntityItem, useQuickAccess } from '@core/context/quickAccess';import clickOutside from '@core/directive/clickOutside';import { isMobile } from '@core/mobile/isMobile';@@ -124,6 +125,15 @@ function MentionsMenuInner(props: MentionsMenuProps) {}): undefined;+ const customCompanies =+ ENABLE_CRM && props.entities+ ? useEntityMentionFromList({+ items: props.entities,+ buckets: ['crm_company'],+ searchTerm,+ })+ : undefined;+const { searchedEntities: docs } =customDocs ??useEntityMention({@@ -138,6 +148,17 @@ function MentionsMenuInner(props: MentionsMenuProps) {searchTerm,});+ // CRM companies only surface in mentions when the feature is enabled —+ // the mention hook isn't even wired up otherwise.+ const companyMention = ENABLE_CRM+ ? (customCompanies ??+ useEntityMention({+ buckets: ['crm_company'],+ searchTerm,+ }))+ : undefined;+ const companies = () => companyMention?.searchedEntities() ?? [];+const { emails, emailSearchQuery: emailUnifiedSearchInfiniteQuery } =hasCustomEntities()? {@@ -215,6 +236,7 @@ function MentionsMenuInner(props: MentionsMenuProps) {...users,...(docs() ?? []),...(channels() ?? []),+ ...(companies() ?? []),...(emails() ?? []),...(dates() ?? []),];@@ -252,6 +274,12 @@ function MentionsMenuInner(props: MentionsMenuProps) {getData: () => channels() ?? [],getFullCount: () => channels()?.length ?? 0,},+ {+ id: 'companies',+ label: 'Companies',+ getData: () => companies() ?? [],+ getFullCount: () => companies()?.length ?? 0,+ },{id: 'emails',label: 'Emails',diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenuController.ts b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenuController.tsindex 6b8faf9f9e..e30914b1e6 100644--- a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenuController.ts+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenuController.ts@@ -8,6 +8,7 @@ export type MentionBucketId =| 'users'| 'documents'| 'channels'+ | 'companies'| 'emails'| 'dates'| 'openTabs';diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/entityUtils.ts b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/entityUtils.tsindex b07068915e..e573e02518 100644--- a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/entityUtils.ts+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/entityUtils.ts@@ -18,6 +18,7 @@ export function getBlockNameFromEntity(.with('project', () => 'project' as const).with('task', () => 'task' as const).with('note', () => 'md' as const)+ .with('crm_company', () => 'company' as const).otherwise(() => {const entity = item.data;if ('fileType' in entity && typeof entity.fileType === 'string') {diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mentionHandlers.ts b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mentionHandlers.tsindex 62268d77cf..ecd1175e4c 100644--- a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mentionHandlers.ts+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mentionHandlers.ts@@ -1,7 +1,7 @@import type { EntityItem } from '@core/context/quickAccess';import { trackMention } from '@core/signal/mention';import type { DateOption } from '@core/util/dateSearch/useDateSearch';-import type { ChannelEntity, EmailEntity } from '@entity';+import type { ChannelEntity, CrmCompanyEntity, EmailEntity } from '@entity';import { REMOVE_INLINE_SEARCH_COMMAND } from '../../../../plugins';import {INSERT_DATE_MENTION_COMMAND,@@ -15,6 +15,22 @@ import type {import { handleUserMention } from '../../../../utils/mentionsUtils';import { getBlockNameFromEntity } from './entityUtils';+// Resolve the display name for a mention insert. `entity.name` is the+// happy path; falls back per-bucket so the inserted mention is never+// blank — empty string here would render an invisible mention until the+// preview fetch lands and re-triggers a Lexical render (typically only+// after the next keystroke).+function entityDisplayName(item: EntityItem): string {+ const name = item.data.name;+ if (name) return name;+ if (item.bucket === 'email') return 'No Subject';+ if (item.bucket === 'crm_company') {+ const domain = (item.data as CrmCompanyEntity).domains?.[0]?.domain;+ return domain ?? 'Unknown company';+ }+ return '';+}+/*** Handle entity mention (documents, channels, emails, etc.).*/@@ -34,7 +50,7 @@ async function handleEntityMention(const entity = item.data;const blockNameForMention = getBlockNameFromEntity(item);- const itemName = entity.name ?? (item.bucket === 'email' ? 'No Subject' : '');+ const itemName = entityDisplayName(item);let mentionId: string | undefined;if (diff --git a/js/app/packages/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts b/js/app/packages/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.tsindex aa335aeb3b..8a055c4909 100644--- a/js/app/packages/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts+++ b/js/app/packages/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts@@ -123,7 +123,9 @@ export type ItemMention = {| 'color'| 'call'| 'group'- | 'automation';+ | 'automation'+ | 'crm_company'+ | 'crm_contact';itemId: string;fileType?: string;documentName?: string;@@ -177,6 +179,12 @@ function $mentionItemFromNode(node: MentionNode): ItemMention {} else if (blockName === 'email') {fileType = 'email';itemType = 'thread';+ } else if (blockName === 'company') {+ fileType = 'company';+ itemType = 'crm_company';+ } else if (blockName === 'contact') {+ fileType = 'contact';+ itemType = 'crm_contact';} else if (blockName === 'unknown') {fileType = 'unknown';}@@ -257,6 +265,8 @@ const getDocumentMentionItemType = (.with('foreign', () => {throw new Error('foreign entities cannot be document mentions');})+ .with('crm_company', () => 'crm_company')+ .with('crm_contact', () => 'crm_contact').exhaustive();};diff --git a/js/app/packages/core/component/UserIcon.tsx b/js/app/packages/core/component/UserIcon.tsxindex 3ea4340af4..44423484ff 100644--- a/js/app/packages/core/component/UserIcon.tsx+++ b/js/app/packages/core/component/UserIcon.tsx@@ -4,6 +4,7 @@ import { staticFileSizedUrl } from '@core/constant/servers';import { internalDrag } from '@core/directive/internalDragState';import { useProfilePictureUrl } from '@core/signal/profilePicture';import {+ getInitials,macroIdToEmail,tryMacroId,useDisplayName,@@ -38,23 +39,6 @@ export type UserIconProps = {photoUrl?: string;} & ({ id: string; email?: never } | { email: string; id?: never });-function getInitials(- firstName: string,- lastName: string,- email: string-): string {- const first = firstName.trim();- const last = lastName.trim();-- if (first && last) {- return (first[0] + last[0]).toUpperCase();- }- if (first) {- return first[0].toUpperCase();- }- return email.substring(0, 1).toUpperCase();-}-/*** Internal render. Image or fallback.*/diff --git a/js/app/packages/core/constant/allBlocks.ts b/js/app/packages/core/constant/allBlocks.tsindex 43f23432d4..5088789c49 100644--- a/js/app/packages/core/constant/allBlocks.ts+++ b/js/app/packages/core/constant/allBlocks.ts@@ -157,6 +157,10 @@ export function fileTypeToBlockName(if (blockOrFiletype === 'channel_message') return 'channel';+ // CRM entity types map to their dedicated blocks (entity type !== block name).+ if (blockOrFiletype === 'crm_company') return 'company';+ if (blockOrFiletype === 'crm_contact') return 'contact';+if (ENABLE_DOCX_TO_PDF) {if (blockOrFiletype === 'docx' || blockOrFiletype === 'write') {return icon ? 'write' : 'pdf';@@ -205,7 +209,7 @@ export function blockNameToDefaultFile(block?: BlockName | string | null) {}export type ItemLike = {- type: ItemType | 'call';+ type: ItemType | 'call' | 'crm_company';fileType?: BasicDocumentFileType;subType?: SubType | BasicDocumentSubTypeProperty;name?: string;diff --git a/js/app/packages/core/constant/featureFlags.ts b/js/app/packages/core/constant/featureFlags.tsindex 50a777355c..69ec67df95 100644--- a/js/app/packages/core/constant/featureFlags.ts+++ b/js/app/packages/core/constant/featureFlags.ts@@ -122,6 +122,11 @@ export const ENABLE_MARKDOWN_LIVE_COLLABORATION = resolveFeatureFlag(export const ENABLE_EMAIL = resolveFeatureFlag('ENABLE_EMAIL', true);+// CRM companies & contacts frontend: the Companies view + sidebar entry, the+// company/contact detail blocks, CRM mentions / quick-access, and CRM rows in+// global search. Off everywhere until GA; override with VITE_ENABLE_CRM.+export const ENABLE_CRM = resolveFeatureFlag('ENABLE_CRM', false);+export const ENABLE_BLOCK_IN_BLOCK = resolveFeatureFlag('ENABLE_BLOCK_IN_BLOCK',truediff --git a/js/app/packages/core/context/quickAccess/QuickAccessProvider.tsx b/js/app/packages/core/context/quickAccess/QuickAccessProvider.tsxindex 3c423d4ead..37f3aadc13 100644--- a/js/app/packages/core/context/quickAccess/QuickAccessProvider.tsx+++ b/js/app/packages/core/context/quickAccess/QuickAccessProvider.tsx@@ -7,9 +7,10 @@ import {useIsConnectedSecondaryInbox,} from '@core/user';import type { DateValue } from '@core/util/date';-import type { ChannelEntity } from '@entity';+import type { ChannelEntity, CrmCompanyEntity } from '@entity';import { queryReadyGate } from '@queries/gate';import { type HistoryItem, useHistoryQuery } from '@queries/history/history';+import { useQuickAccessCrmCompaniesQuery } from '@queries/soup/quick-access-crm-companies';import { useRecentlyViewedSoupQuery } from '@queries/soup/recently-viewed';import { useInstructionsMdIdQuery } from '@queries/storage/instructions-md';import type { ApiChannelWithLatest } from '@service-storage/channel-list-types';@@ -164,6 +165,19 @@ function getUserVersion(user: IUser): string {return `${user.name}|${user.email}|${user.lastInteraction}`;}+function getCrmCompanySearchText(company: CrmCompanyEntity): string {+ const domains = company.domains.map((d) => d.domain).join(' ');+ return domains ? `${company.name} | ${domains}` : company.name;+}++function getCrmCompanyVersion(+ company: CrmCompanyEntity,+ viewedAt?: string+): string {+ const domains = company.domains.map((d) => d.domain).join(',');+ return `${company.name}|${domains}|${company.updatedAt}|${viewedAt}`;+}+/*** Merge two *already* sorted index arrays into a single sorted array.*/@@ -214,6 +228,8 @@ export const [QuickAccessProvider, useQuickAccess] =const augmentUserWithDmActivity = useAugmentUserWithDmActivity();const isConnectedSecondaryInbox = useIsConnectedSecondaryInbox();const instructionsIdQuery = useInstructionsMdIdQuery();+ const { query: crmCompaniesQuery, companies: crmCompaniesAccessor } =+ useQuickAccessCrmCompaniesQuery();// globally hidden idsconst [hiddenIds, setHiddenIds] = createSignal<Set<string>>(new Set());@@ -424,6 +440,71 @@ export const [QuickAccessProvider, useQuickAccess] =}}+ // Process CRM companies (live soup list, complements the+ // recently-viewed feed which only has companies the user has+ // opened). Sort timestamp prefers viewed_at; falls back to+ // updated_at for unviewed companies — same shape as channels.+ const crmCompanyData = crmCompaniesAccessor();+ for (const company of crmCompanyData) {+ if (hidden.has(company.id)) continue;+ seenIds.add(company.id);++ const viewedAt =+ viewedAtMap.get(company.id) ?? company.viewedAt ?? undefined;++ const version = getCrmCompanyVersion(+ company,+ viewedAt as string | undefined+ );+ const cached = itemCache.get(company.id);++ if (!cached || cached.version !== version) {+ const reason = !cached+ ? 'new'+ : `changed (${cached.version} -> ${version})`;+ transformedItems.push({+ id: company.id,+ name: company.name,+ type: 'crm_company',+ reason,+ });+ const entity: CrmCompanyEntity = {+ ...company,+ viewedAt: (viewedAt ?? company.viewedAt) as DateValue | null,+ };+ const viewedAtMs = toTimestamp(viewedAt);+ const updatedAtMs = toTimestamp(company.updatedAt);+ const sortTimestamp = viewedAtMs || updatedAtMs;++ const quickAccessItem: QuickAccessItem = {+ kind: 'entity',+ id: company.id,+ bucket: 'crm_company',+ searchText: getCrmCompanySearchText(entity),+ sortTimestamp,+ timestamps: {+ viewedAt,+ updatedAt: company.updatedAt,+ createdAt: company.createdAt,+ },+ data: entity,+ };++ itemCache.set(company.id, { item: quickAccessItem, version });+ allEntries.push({+ id: company.id,+ bucket: 'crm_company',+ sortTimestamp,+ });+ } else {+ allEntries.push({+ id: company.id,+ bucket: cached.item.bucket,+ sortTimestamp: cached.item.sortTimestamp,+ });+ }+ }+// Clean up stale cache entries (items that no longer exist)for (const id of itemCache.keys()) {if (!seenIds.has(id)) {@@ -550,10 +631,13 @@ export const [QuickAccessProvider, useQuickAccess] =});};+ // CRM companies are additive — they fold into the list when their query+ // resolves rather than gating quick access on a slower/failing CRM fetch.const isLoading = () => historyQuery.isLoading || channelsLoading();const refresh = () => {historyQuery.refetch();+ crmCompaniesQuery.refetch();};return {diff --git a/js/app/packages/core/context/quickAccess/types.ts b/js/app/packages/core/context/quickAccess/types.tsindex bab948d0bf..6a273d2b28 100644--- a/js/app/packages/core/context/quickAccess/types.ts+++ b/js/app/packages/core/context/quickAccess/types.ts@@ -3,6 +3,7 @@ import type { DateValue } from '@core/util/date';import type {ChannelEntity,ChatEntity,+ CrmCompanyEntity,DocumentEntity,EmailEntity,EntityData,@@ -24,7 +25,8 @@ export type Bucket =| 'note'| 'chat'| 'project'- | 'email';+ | 'email'+ | 'crm_company';export type EntityBucket = Exclude<Bucket, 'person'>;@@ -38,6 +40,7 @@ const ALL_BUCKETS: Bucket[] = ['chat','project','email',+ 'crm_company',];export type BucketCombination = 'all' | 'channels' | 'documents';@@ -111,6 +114,7 @@ export type BucketItemMap = {chat: EntityItem<ChatEntity>;project: EntityItem<ProjectEntity>;email: EntityItem<EmailEntity>;+ crm_company: EntityItem<CrmCompanyEntity>;person: UserItem;};diff --git a/js/app/packages/core/hotkey/tokens.ts b/js/app/packages/core/hotkey/tokens.tsindex 1d46008e93..33f968b8dd 100644--- a/js/app/packages/core/hotkey/tokens.ts+++ b/js/app/packages/core/hotkey/tokens.ts@@ -95,6 +95,7 @@ export const TOKENS = {tasks: 'sidebar.goTo.tasks',channels: 'sidebar.goTo.channels',calls: 'sidebar.goTo.calls',+ companies: 'sidebar.goTo.companies',folders: 'sidebar.goTo.folders',},},diff --git a/js/app/packages/core/internal/trackBlockOpened.ts b/js/app/packages/core/internal/trackBlockOpened.tsindex 2b6fe4e248..4266b21ba5 100644--- a/js/app/packages/core/internal/trackBlockOpened.ts+++ b/js/app/packages/core/internal/trackBlockOpened.ts@@ -19,11 +19,33 @@ function isSoupEntityTag(itemType: ItemType): itemType is ItemType & SoupEntityTag {return match(itemType)- .with('email', 'channel_message', 'automation', 'foreign', () => false)+ .with(+ 'email',+ 'channel_message',+ 'automation',+ 'foreign',+ 'crm_company',+ 'crm_contact',+ () => false+ ).with('document', 'chat', 'project', 'channel', 'call', () => true).exhaustive();}+// Item types we want recorded in UserHistory on open. CRM types aren't+// CloudStorageItemType (they're not stored in document_storage), but the+// /history endpoint accepts any item_type as text and the soup's+// `viewed_updated` sort joins UserHistory generically — so writing+// these rows is what surfaces recently-opened companies/contacts in+// Quick Access and the @ mention menu.+function shouldTrackInUserHistory(itemType: ItemType): boolean {+ return (+ isCloudStorageItem(itemType) ||+ itemType === 'crm_company' ||+ itemType === 'crm_contact'+ );+}+/*** Tracks opening of a block and updates history accordingly.* We have this in a separate file to prevent cyclic dependencies.@@ -45,7 +67,7 @@ export function track({refetchSoupEntity(itemId, itemType);}- if (!isCloudStorageItem(itemType)) return;+ if (!shouldTrackInUserHistory(itemType)) return;const upsertToHistoryMutation = useUpsertToHistoryMutation(undefined, client);upsertToHistoryMutation.mutate({ itemId, itemType });diff --git a/js/app/packages/core/user/displayName.ts b/js/app/packages/core/user/displayName.tsindex 53b1adda98..678f4ff227 100644--- a/js/app/packages/core/user/displayName.ts+++ b/js/app/packages/core/user/displayName.ts@@ -6,6 +6,41 @@ import { createStore, unwrap } from 'solid-js/store';import { type MacroId, macroIdToEmail } from './macroId';import type { UserNameItem, UserNamePreviewFetcher } from './types';+/**+ * Initials from a structured name, falling back to the email's first letter.+ * Two letters when both names are present, otherwise one.+ */+export function getInitials(+ firstName: string,+ lastName: string,+ email: string+): string {+ const first = firstName.trim();+ const last = lastName.trim();++ if (first && last) {+ return (first[0] + last[0]).toUpperCase();+ }+ if (first) {+ return first[0].toUpperCase();+ }+ return email.substring(0, 1).toUpperCase();+}++/**+ * Initials from a free-form display name (split on whitespace into first/last+ * tokens), falling back to the email's first letter. For data sources that+ * carry a single name string rather than structured first/last fields.+ */+export function getInitialsFromName(+ name: string | null | undefined,+ email: string+): string {+ const parts = (name ?? '').trim().split(/\s+/).filter(Boolean);+ const last = parts.length > 1 ? (parts.at(-1) ?? '') : '';+ return getInitials(parts[0] ?? '', last, email);+}+const DEFAULT_CACHE_TIME_SECONDS = 60 * 10;type DisplayNameStore = Record<string, UserNameItem>;diff --git a/js/app/packages/core/user/index.ts b/js/app/packages/core/user/index.tsindex c25544bb76..e15a0a7a54 100644--- a/js/app/packages/core/user/index.ts+++ b/js/app/packages/core/user/index.ts@@ -8,6 +8,8 @@ export {} from './combinedRecipient';export { useContacts } from './contactService';export {+ getInitials,+ getInitialsFromName,seedMockDisplayNames,useDisplayName,useDisplayNameParts,diff --git a/js/app/packages/entity/src/extractors-property/entity-key-properties.tsx b/js/app/packages/entity/src/extractors-property/entity-key-properties.tsxindex 071a8d6dea..5ee90886d4 100644--- a/js/app/packages/entity/src/extractors-property/entity-key-properties.tsx+++ b/js/app/packages/entity/src/extractors-property/entity-key-properties.tsx@@ -42,6 +42,11 @@ function getEntityType(entity: EntityData): EntityType {.with({ type: 'document' }, () => EntityType.DOCUMENT).with({ type: 'channel_message' }, () => EntityType.CHANNEL).with({ type: 'call' }, () => EntityType.CHANNEL)+ .with({ type: 'crm_company' }, () => EntityType.COMPANY)+ .with({ type: 'crm_contact' }, () => {+ // No CONTACT in the properties-service EntityType yet.+ throw new Error('crm contacts do not support properties');+ }).with({ type: 'automation' }, () => {throw new Error('automation entities do not support properties');})diff --git a/js/app/packages/entity/src/extractors/entity-icon.tsx b/js/app/packages/entity/src/extractors/entity-icon.tsxindex 832e8d6283..046abb27ce 100644--- a/js/app/packages/entity/src/extractors/entity-icon.tsx+++ b/js/app/packages/entity/src/extractors/entity-icon.tsx@@ -125,6 +125,7 @@ export function EntityIcon(props: EntityIconProps) {() => 'githubPullRequest').with({ type: 'foreign' }, () => 'default')+ .with({ type: 'crm_company' }, () => 'crm_company').otherwise(() => 'default');};diff --git a/js/app/packages/entity/src/extractors/entity-title.tsx b/js/app/packages/entity/src/extractors/entity-title.tsxindex 2c5161fd55..2af6ca0867 100644--- a/js/app/packages/entity/src/extractors/entity-title.tsx+++ b/js/app/packages/entity/src/extractors/entity-title.tsx@@ -33,6 +33,11 @@ function extractRawTitle(entity: EntityData): JSX.Element {</>)).with({ type: 'foreign' }, (e) => e.name)+ .with({ type: 'crm_company' }, (e) => e.name || 'Unknown Company')+ .with(+ { type: 'crm_contact' },+ (e) => e.name || e.email || 'Unknown Contact'+ ).otherwise(() => 'Unknown');}diff --git a/js/app/packages/entity/src/types/entity.ts b/js/app/packages/entity/src/types/entity.tsindex c68e96731d..c185660cde 100644--- a/js/app/packages/entity/src/types/entity.ts+++ b/js/app/packages/entity/src/types/entity.ts@@ -185,6 +185,39 @@ export type AutomationEntity = EntityBase & {isRunning?: boolean;};+export type CrmCompanyDomain = {+ id: string;+ companyId: string;+ domain: string;+ createdAt?: DateValue | null;+};++export type CrmCompanyEntity = EntityBase & {+ type: 'crm_company';+ teamId: string;+ description?: string;+ /** Whether team-wide email visibility is enabled for this company.+ * `undefined` means not loaded — search results don't carry it; the+ * full value arrives with the soup row or the company detail query. */+ emailSync?: boolean;+ /** Whether the company has been hidden from the CRM listings. Only+ * admin/owner team members can see `hidden: true` rows from the soup+ * endpoint. */+ hidden: boolean;+ domains: CrmCompanyDomain[];+};++export type CrmContactEntity = EntityBase & {+ type: 'crm_contact';+ /** The company the contact belongs to. */+ companyId: string;+ /** The contact's email address. */+ email: string;+ /** Whether the contact has been hidden from the CRM listings. Only+ * admin/owner team members can see `hidden: true` rows. */+ hidden: boolean;+};+export type EntityData =| ChannelEntity| ChannelMessageEntity@@ -194,6 +227,8 @@ export type EntityData =| EmailEntity| ProjectEntity| CallEntity+ | CrmCompanyEntity+ | CrmContactEntity| AutomationEntity| ForeignEntity;@@ -205,6 +240,8 @@ const ENTITY_TYPE_VALUES = new Set<EntityData['type']>(['email','project','call',+ 'crm_company',+ 'crm_contact','automation','foreign',]);@@ -277,6 +314,18 @@ export const isAutomationEntity = (return entity.type === 'automation';};+export const isCrmCompanyEntity = (+ entity: EntityData+): entity is CrmCompanyEntity => {+ return entity.type === 'crm_company';+};++export const isCrmContactEntity = (+ entity: EntityData+): entity is CrmContactEntity => {+ return entity.type === 'crm_contact';+};+export const isDocumentEntity = (entity: EntityData): entity is DocumentEntity => {diff --git a/js/app/packages/entity/src/utils/buildEntityData.ts b/js/app/packages/entity/src/utils/buildEntityData.tsindex 87d6afb361..8dc4f319d3 100644--- a/js/app/packages/entity/src/utils/buildEntityData.ts+++ b/js/app/packages/entity/src/utils/buildEntityData.ts@@ -54,101 +54,104 @@ export function buildEntityData(const base = { id, name, ownerId };- return match<BlockName | BlockAlias, EntityData | undefined>(blockName)- .with(- 'task',- (): TaskEntity => ({- ...base,- type: 'document',- fileType: 'md',- subType: { type: 'task', is_completed: args.isCompleted ?? false },- projectId: args.projectId,+ return (+ match<BlockName | BlockAlias, EntityData | undefined>(blockName)+ .with(+ 'task',+ (): TaskEntity => ({+ ...base,+ type: 'document',+ fileType: 'md',+ subType: { type: 'task', is_completed: args.isCompleted ?? false },+ projectId: args.projectId,+ })+ )+ .with(+ 'md',+ (): DocumentEntity => ({+ ...base,+ type: 'document',+ fileType: 'md',+ projectId: args.projectId,+ })+ )+ .with(+ 'pdf',+ 'write',+ 'code',+ 'image',+ 'canvas',+ 'video',+ 'unknown',+ 'csv',+ (name): DocumentEntity => ({+ ...base,+ type: 'document',+ fileType: args.fileType ?? name,+ projectId: args.projectId,+ })+ )+ .with(+ 'chat',+ (): ChatEntity => ({+ ...base,+ type: 'chat',+ projectId: args.projectId,+ })+ )+ .with(+ 'project',+ (): ProjectEntity => ({+ ...base,+ type: 'project',+ projectId: args.projectId,+ })+ )+ .with('channel', (): ChannelEntity | undefined => {+ if (!args.channelType) return undefined;+ return {+ ...base,+ type: 'channel',+ channelType: args.channelType,+ };})- )- .with(- 'md',- (): DocumentEntity => ({- ...base,- type: 'document',- fileType: 'md',- projectId: args.projectId,+ .with(+ 'email',+ (): EmailEntity => ({+ ...base,+ type: 'email',+ isRead: args.isRead ?? true,+ isDraft: args.isDraft ?? false,+ isImportant: args.isImportant ?? false,+ done: args.done ?? false,+ })+ )+ .with('automation', (): AutomationEntity | undefined => {+ if (!args.cron) return undefined;+ return {+ ...base,+ type: 'automation',+ cron: args.cron,+ enabled: args.enabled ?? false,+ };})- )- .with(- 'pdf',- 'write',- 'code',- 'image',- 'canvas',- 'video',- 'contact',- 'unknown',- 'csv',- (name): DocumentEntity => ({- ...base,- type: 'document',- fileType: args.fileType ?? name,- projectId: args.projectId,- })- )- .with(- 'chat',- (): ChatEntity => ({- ...base,- type: 'chat',- projectId: args.projectId,- })- )- .with(- 'project',- (): ProjectEntity => ({- ...base,- type: 'project',- projectId: args.projectId,- })- )- .with('channel', (): ChannelEntity | undefined => {- if (!args.channelType) return undefined;- return {- ...base,- type: 'channel',- channelType: args.channelType,- };- })- .with(- 'email',- (): EmailEntity => ({- ...base,- type: 'email',- isRead: args.isRead ?? true,- isDraft: args.isDraft ?? false,- isImportant: args.isImportant ?? false,- done: args.done ?? false,- })- )- .with('automation', (): AutomationEntity | undefined => {- if (!args.cron) return undefined;- return {- ...base,- type: 'automation',- cron: args.cron,- enabled: args.enabled ?? false,- };- })- .with('call', (): CallEntity | undefined => {- if (!args.channelId) return undefined;- const status: CallEntity['status'] =- args.status ?? (args.attended ? 'ATTENDED' : 'UNATTENDED');+ .with('call', (): CallEntity | undefined => {+ if (!args.channelId) return undefined;+ const status: CallEntity['status'] =+ args.status ?? (args.attended ? 'ATTENDED' : 'UNATTENDED');- return {- ...base,- type: 'call',- channelId: args.channelId,- isActive: args.isActive ?? false,- status,- attended: status === 'ATTENDED',- participantIds: args.participantIds ?? [],- };- })- .exhaustive();+ return {+ ...base,+ type: 'call',+ channelId: args.channelId,+ isActive: args.isActive ?? false,+ status,+ attended: status === 'ATTENDED',+ participantIds: args.participantIds ?? [],+ };+ })+ // CRM companies/contacts aren't constructed from block args; soup is the source.+ .with('company', 'contact', (): undefined => undefined)+ .exhaustive()+ );}diff --git a/js/app/packages/entity/src/utils/shared.ts b/js/app/packages/entity/src/utils/shared.tsindex a6377c7c8d..62ea6d50b6 100644--- a/js/app/packages/entity/src/utils/shared.ts+++ b/js/app/packages/entity/src/utils/shared.ts@@ -7,6 +7,7 @@ export function useIsShared(entity: EntityData) {if (entity.type === 'channel') return false;if (entity.type === 'call') return false;if (entity.type === 'foreign') return entity.storedForId !== userId();+ if (entity.type === 'crm_company') return false;if (entity.ownerId === userId()) return false;return true;};diff --git a/js/app/packages/macro-entity/src/queries/rename.ts b/js/app/packages/macro-entity/src/queries/rename.tsindex 59a4f257e4..15575f4238 100644--- a/js/app/packages/macro-entity/src/queries/rename.ts+++ b/js/app/packages/macro-entity/src/queries/rename.ts@@ -63,6 +63,10 @@ const getEntityRenameData = (operation: EntityRenameOperation): EntityRenameData | null => {const { entity, newName } = operation;+ // crm companies/contacts aren't renamable and have no storage item type.+ if (entity.type === 'crm_company' || entity.type === 'crm_contact') {+ return null;+ }return {id: entity.id,itemType: entity.type,@@ -127,7 +131,12 @@ const renameDssSetData = (itemType !== 'email' &&itemType !== 'channel_message' &&itemType !== 'automation' &&- itemType !== 'foreign'+ itemType !== 'foreign' &&+ // CRM companies/contacts aren't renamed via the FileList path (their+ // names derive from the directory/email, and their soup tags are+ // camelCase 'crmCompany'/'crmContact', not these snake-case itemTypes).+ itemType !== 'crm_company' &&+ itemType !== 'crm_contact') {txns.set(id,diff --git a/js/app/packages/property/src/utils/entityConversion.ts b/js/app/packages/property/src/utils/entityConversion.tsindex 3c53f4ebbc..88aab5c6e0 100644--- a/js/app/packages/property/src/utils/entityConversion.ts+++ b/js/app/packages/property/src/utils/entityConversion.ts@@ -73,6 +73,11 @@ export function macroEntityToPropertyEntityType(.with({ type: 'document' }, () => EntityType.DOCUMENT).with({ type: 'channel_message' }, () => EntityType.CHANNEL).with({ type: 'call' }, () => EntityType.CHANNEL)+ .with({ type: 'crm_company' }, () => EntityType.COMPANY)+ .with({ type: 'crm_contact' }, () => {+ // No CONTACT in the properties-service EntityType yet.+ throw new Error('crm contacts do not support properties');+ }).with({ type: 'automation' }, () => {throw new Error('automation entities do not support properties');})diff --git a/js/app/packages/queries/crm/comments.ts b/js/app/packages/queries/crm/comments.tsnew file mode 100644index 0000000000..e64eca9b2b--- /dev/null+++ b/js/app/packages/queries/crm/comments.ts@@ -0,0 +1,84 @@+import { throwOnErr } from '@core/util/result';+import { storageServiceClient } from '@service-storage/client';+import type { CrmCommentEntityType } from '@service-storage/generated/schemas/crmCommentEntityType';+import { useMutation, useQuery } from '@tanstack/solid-query';+import type { Accessor } from 'solid-js';+import { crmKeys } from './keys';++const CRM_COMMENTS_STALE_TIME = 60 * 1000;++/**+ * Comment threads for a CRM company or contact via+ * `GET /crm/comments/{entityType}/{entityId}`. Disabled until an entity+ * id is available.+ */+export function useCrmCommentsQuery(+ entityType: CrmCommentEntityType,+ entityId: Accessor<string | undefined>+) {+ return useQuery(() => {+ const id = entityId();+ return {+ queryKey: crmKeys.comments(entityType, id ?? '').queryKey,+ queryFn: () => {+ if (!id) {+ throw new Error('entity id is required to fetch comments');+ }+ return throwOnErr(() =>+ storageServiceClient.crmComments.list({ entityType, entityId: id })+ );+ },+ enabled: !!id,+ staleTime: CRM_COMMENTS_STALE_TIME,+ };+ });+}++/**+ * Creates a CRM comment — a new thread when `threadId` is omitted, a reply+ * otherwise. Returns the updated thread; cache reconciliation is left to+ * the caller (the discussion source does point updates).+ */+export function useCreateCrmCommentMutation() {+ return useMutation(() => ({+ mutationFn: ({+ entityType,+ entityId,+ text,+ threadId,+ }: {+ entityType: CrmCommentEntityType;+ entityId: string;+ text: string;+ threadId?: string;+ }) =>+ throwOnErr(() =>+ storageServiceClient.crmComments.create({+ entityType,+ entityId,+ body: { text, threadId },+ })+ ),+ }));+}++/** Edits a CRM comment's text; returns the updated comment. */+export function useEditCrmCommentMutation() {+ return useMutation(() => ({+ mutationFn: ({ commentId, text }: { commentId: string; text: string }) =>+ throwOnErr(() =>+ storageServiceClient.crmComments.edit({ commentId, body: { text } })+ ),+ }));+}++/**+ * Deletes a CRM comment; the result reports whether the whole thread+ * went with it (last comment deleted).+ */+export function useDeleteCrmCommentMutation() {+ return useMutation(() => ({+ mutationFn: ({ commentId }: { commentId: string }) =>+ throwOnErr(() => storageServiceClient.crmComments.delete({ commentId })),+ }));+}diff --git a/js/app/packages/queries/crm/companies.ts b/js/app/packages/queries/crm/companies.tsnew file mode 100644index 0000000000..81c88e2315--- /dev/null+++ b/js/app/packages/queries/crm/companies.ts@@ -0,0 +1,145 @@+import { NIL_UUID } from '@app/component/next-soup/filters/filter-store';+import { throwOnErr } from '@core/util/result';+import type { CrmCompanyEntity } from '@entity';+import { storageServiceClient } from '@service-storage/client';+import type { CrmCompanyResponse } from '@service-storage/generated/schemas/crmCompanyResponse';+import type { CrmContactResponse } from '@service-storage/generated/schemas/crmContactResponse';+import { useMutation, useQuery } from '@tanstack/solid-query';+import { type Accessor, createMemo } from 'solid-js';+import { queryClient } from '../client';+import { soupKeys } from '../soup/keys';+import { crmKeys } from './keys';++const COMPANY_STALE_TIME = 60 * 1000;++/** A contact row as embedded in the company response. */+export type CompanyContact = CrmContactResponse;++/**+ * Fetches a single CRM company by id via `GET /crm/companies/{id}`.+ * The endpoint is role-aware via [`CrmCompanyAccessLevelExtractor`]:+ * non-admin viewers 404 on hidden rows, admin/owner reach hidden rows+ * for unhide UI. Contacts arrive embedded in the response so the+ * company panel hydrates in a single round trip.+ *+ * Disabled until a non-NIL companyId is available so callers can pass+ * a sentinel placeholder before their own data loads without firing a+ * doomed 404.+ */+export function useCompanyQuery(companyId: Accessor<string>) {+ const query = useQuery(() => {+ const id = companyId();+ return {+ queryKey: crmKeys.company(id).queryKey,+ queryFn: () => {+ if (!id) {+ throw new Error('company id is required to fetch company');+ }+ return throwOnErr(() =>+ storageServiceClient.getCompany({ companyId: id })+ );+ },+ staleTime: COMPANY_STALE_TIME,+ enabled: !!companyId() && companyId() !== NIL_UUID,+ };+ });++ const company = createMemo<CrmCompanyEntity | undefined>(() => {+ const data = query.data;+ if (!data) return undefined;+ return responseToEntity(data);+ });++ const contacts = createMemo<CompanyContact[]>(+ () => query.data?.contacts ?? []+ );++ return { query, company, contacts };+}++function responseToEntity(response: CrmCompanyResponse): CrmCompanyEntity {+ return {+ type: 'crm_company',+ id: response.id,+ // CrmCompanyEntity.name is a required string; the wire schema's+ // primary-directory `name` is nullable. Fall back to the primary+ // domain (or empty) so consumers don't have to special-case.+ name: response.name ?? response.domains[0]?.domain ?? '',+ // Companies are team-owned, not user-owned; the team id fills the+ // ownerId slot (matching the soup/search mappers in transform-utils).+ ownerId: response.teamId,+ createdAt: response.createdAt,+ updatedAt: response.updatedAt,+ teamId: response.teamId,+ description: response.description ?? undefined,+ emailSync: response.emailSync,+ hidden: response.hidden,+ domains: response.domains.map((d) => ({+ id: d.id,+ companyId: d.companyId,+ domain: d.domain,+ createdAt: d.createdAt,+ })),+ };+}++/**+ * Toggles `crm_companies.hidden` via `PUT /crm/companies/{id}/hidden`. Hiding+ * also disables `email_sync` and soft-hides the company's contacts; un-hide+ * restores contact visibility (contact rows and sources survive the cycle).+ * Invalidates soup (the company drops out of / returns to the listings) and the+ * company detail query so an open panel reflects the new hidden/email-sync state.+ */+export function useSetCompanyHiddenMutation() {+ return useMutation(() => ({+ mutationFn: ({+ companyId,+ hidden,+ }: {+ companyId: string;+ hidden: boolean;+ }) =>+ throwOnErr(() =>+ storageServiceClient.setCompanyHidden({ companyId, hidden })+ ),+ onSuccess: (_data, { companyId }) =>+ Promise.all([+ queryClient.invalidateQueries({ queryKey: soupKeys._def }),+ queryClient.invalidateQueries({+ queryKey: crmKeys.company(companyId).queryKey,+ }),+ ]),+ }));+}++/**+ * Toggles `crm_companies.email_sync` via `PUT /crm/companies/{id}/email-sync`.+ * Purely a read-side visibility gate controlling whether the team can see each+ * other's emails with this company — existing CRM data is never destroyed and+ * re-enabling needs no backfill.+ */+export function useSetEmailSyncMutation() {+ return useMutation(() => ({+ mutationFn: ({+ companyId,+ emailSync,+ }: {+ companyId: string;+ emailSync: boolean;+ }) =>+ throwOnErr(() =>+ storageServiceClient.setEmailSync({ companyId, emailSync })+ ),+ // Return the invalidation promise so the mutation stays pending until the+ // refetches resolve — the company entity, empty-state message, and emails+ // list flip in one beat. Soup carries the team-wide email visibility change;+ // the company detail query backs the panel's `emailSync` empty-state text.+ onSuccess: (_data, { companyId }) =>+ Promise.all([+ queryClient.invalidateQueries({ queryKey: soupKeys._def }),+ queryClient.invalidateQueries({+ queryKey: crmKeys.company(companyId).queryKey,+ }),+ ]),+ }));+}diff --git a/js/app/packages/queries/crm/contacts.ts b/js/app/packages/queries/crm/contacts.tsnew file mode 100644index 0000000000..bda1923399--- /dev/null+++ b/js/app/packages/queries/crm/contacts.ts@@ -0,0 +1,65 @@+import { throwOnErr } from '@core/util/result';+import { storageServiceClient } from '@service-storage/client';+import { useMutation, useQuery } from '@tanstack/solid-query';+import type { Accessor } from 'solid-js';+import { queryClient } from '../client';+import { soupKeys } from '../soup/keys';+import { crmKeys } from './keys';++const CONTACT_STALE_TIME = 60 * 1000;++/**+ * Fetches a single CRM contact by id via `GET /crm/contacts/{id}`.+ * The endpoint is role-aware: admins/owners see hidden contacts too,+ * non-admins get 404 on hidden rows. The frontend doesn't branch — it+ * just calls the endpoint and trusts the response.+ */+export function useContactQuery(contactId: Accessor<string>) {+ return useQuery(() => {+ const id = contactId();+ return {+ queryKey: crmKeys.contact(id).queryKey,+ queryFn: () => {+ if (!id) {+ throw new Error('contact id is required to fetch contact');+ }+ return throwOnErr(() =>+ storageServiceClient.getContact({ contactId: id })+ );+ },+ staleTime: CONTACT_STALE_TIME,+ enabled: !!id,+ };+ });+}++/**+ * Toggles `crm_contacts.hidden` via `PUT /crm/contacts/{id}/hidden`.+ * Hidden contacts disappear from the parent company's contact list+ * (non-admin view) and from any soup surface that filters them.+ *+ * Returns the invalidation promise from `onSuccess` so the mutation+ * stays pending until both the contact query and the soup queries+ * refetch — the toggle state and any dependent UI all flip in one beat.+ */+export function useSetContactHiddenMutation() {+ return useMutation(() => ({+ mutationFn: ({+ contactId,+ hidden,+ }: {+ contactId: string;+ hidden: boolean;+ }) =>+ throwOnErr(() =>+ storageServiceClient.setContactHidden({ contactId, hidden })+ ),+ onSuccess: (_data, { contactId }) =>+ Promise.all([+ queryClient.invalidateQueries({ queryKey: soupKeys._def }),+ queryClient.invalidateQueries({+ queryKey: crmKeys.contact(contactId).queryKey,+ }),+ ]),+ }));+}diff --git a/js/app/packages/queries/crm/keys.ts b/js/app/packages/queries/crm/keys.tsnew file mode 100644index 0000000000..3b84246fa8--- /dev/null+++ b/js/app/packages/queries/crm/keys.ts@@ -0,0 +1,11 @@+import { createQueryKeys } from '@lukemorales/query-key-factory';+import type { CrmCommentEntityType } from '@service-storage/generated/schemas/crmCommentEntityType';++export const crmKeys = createQueryKeys('crm', {+ company: (companyId: string) => [companyId],+ contact: (contactId: string) => [contactId],+ comments: (entityType: CrmCommentEntityType, entityId: string) => [+ entityType,+ entityId,+ ],+});diff --git a/js/app/packages/queries/history/history.ts b/js/app/packages/queries/history/history.tsindex 2c762da979..a0b75490c9 100644--- a/js/app/packages/queries/history/history.ts+++ b/js/app/packages/queries/history/history.ts@@ -1,7 +1,6 @@import { catchToResult, throwOnErr } from '@core/util/result';import { type MutationCallbacks, withCallbacks } from '@queries/utils';-import { storageServiceClient } from '@service-storage/client';-import type { CloudStorageItemType } from '@service-storage/generated/schemas/cloudStorageItemType';+import { type ItemType, storageServiceClient } from '@service-storage/client';import {type QueryClient,queryOptions,@@ -98,7 +97,7 @@ export function refetchHistory() {type UpsertToHistoryParams = {itemId: string;- itemType: CloudStorageItemType;+ itemType: ItemType;};type UpsertToHistoryContext = {@@ -164,7 +163,7 @@ export function useUpsertToHistoryMutation(* Prefer `useUpsertToHistoryMutation` when inside a component.*/export async function postNewHistoryItem(- itemType: CloudStorageItemType,+ itemType: ItemType,itemId: string): Promise<boolean> {const maybeAdded = await storageServiceClient.upsertItemToUserHistory({@@ -179,7 +178,7 @@ export async function postNewHistoryItem(/** Standalone function to remove an item from history. */export async function removeHistoryItem(- itemType: CloudStorageItemType,+ itemType: ItemType,itemId: string): Promise<boolean> {setHistoryData((old) => {diff --git a/js/app/packages/queries/preview/fetchers.ts b/js/app/packages/queries/preview/fetchers.tsindex d007671471..b7b34987d8 100644--- a/js/app/packages/queries/preview/fetchers.ts+++ b/js/app/packages/queries/preview/fetchers.ts@@ -228,6 +228,53 @@ async function fetchProjectPreviews(});}+/**+ * Fetches CRM company previews via `GET /crm/companies/{id}`. Mirrors the+ * email preview fetcher's shape — N parallel REST calls rather than a+ * batch endpoint, since the CRM REST surface is per-id today and+ * companies are a smaller cardinality than mentions in flight.+ *+ * The backend already gates hidden visibility by role (admin/owner sees+ * hidden, non-admin 404s), so the fetcher doesn't need to repeat that+ * logic.+ */+async function fetchCrmCompanyPreviews(+ companyIds: string[]+): Promise<PreviewItem[]> {+ return await Promise.all(+ companyIds.map(async (id) => {+ const base = { id, type: 'crm_company' as const };+ const result = await storageServiceClient.getCompany({ companyId: id });++ if (result.isErr()) {+ // The backend returns 404 for every unreachable reason (wrong+ // team, hidden+member, doesn't exist) — deliberate, so existence+ // can't be probed across teams. Maps to "No Access" for parity+ // with the email fetcher's per-id convention; "Deleted" would be+ // misleading since we can't actually tell.+ return {+ ...base,+ access: 'no_access' as const,+ loading: false as const,+ };+ }++ const company = result.value;+ const displayName =+ company.name ?? company.domains[0]?.domain ?? 'Unknown Company';++ return {+ ...base,+ access: 'access' as const,+ loading: false as const,+ rawName: displayName,+ name: displayName,+ updatedAt: company.updatedAt,+ };+ })+ );+}+async function fetchEmailPreviews(threadIds: string[]): Promise<PreviewItem[]> {const results = await Promise.all(threadIds.map(async (threadId) => {@@ -293,6 +340,7 @@ export async function fetchPreviewBatch(doFetch(fetchDocumentPreviews, filterMapToId(items, 'document')),doFetch(fetchProjectPreviews, filterMapToId(items, 'project')),doFetch(fetchEmailPreviews, filterMapToId(items, 'email')),+ doFetch(fetchCrmCompanyPreviews, filterMapToId(items, 'crm_company')),]);const resultMap = new Map<string, PreviewItem>();results.flat().forEach((result) => {diff --git a/js/app/packages/queries/soup/quick-access-crm-companies.ts b/js/app/packages/queries/soup/quick-access-crm-companies.tsnew file mode 100644index 0000000000..4aea19cf51--- /dev/null+++ b/js/app/packages/queries/soup/quick-access-crm-companies.ts@@ -0,0 +1,50 @@+import { NIL_UUID } from '@app/component/next-soup/filters/filter-store';+import { ENABLE_CRM } from '@core/constant/featureFlags';+import { type CrmCompanyEntity, isCrmCompanyEntity } from '@entity';+import { useSoupItemsQuery } from '@queries/soup/items';+import { createMemo } from 'solid-js';++const QUICK_ACCESS_COMPANIES_LIMIT = 500;+const STALE_TIME = 5 * 60 * 1000;++/**+ * Quick Access feed of the team's CRM companies, sorted so the user's+ * recently-opened ones bubble to the top (`viewed_updated` =+ * `COALESCE(UserHistory."updatedAt", crm_companies.last_interaction)`).+ *+ * This is the parallel live source feeding the `'crm_company'` bucket+ * — the recently-viewed soup query covers viewed companies with their+ * `viewedAt`, this one widens the pool to all team companies up to a+ * cap so users can `@`-mention companies they've never opened.+ *+ * Every other entity type is filtered out via the nil-uuid sentinel+ * pattern — that's the established way to scope a soup call to a+ * single entity type (see `use-company-query.ts`).+ */+export function useQuickAccessCrmCompaniesQuery() {+ const query = useSoupItemsQuery(+ () => ({+ params: {+ limit: QUICK_ACCESS_COMPANIES_LIMIT,+ sort_method: 'viewed_updated',+ },+ body: {+ call_filters: { call_ids: [NIL_UUID] },+ channel_filters: { channel_ids: [NIL_UUID] },+ chat_filters: { chat_ids: [NIL_UUID] },+ document_filters: { document_ids: [NIL_UUID] },+ email_filters: { email_thread_ids: [NIL_UUID] },+ foreign_entity_filters: { ids: [NIL_UUID] },+ project_filters: { project_ids: [NIL_UUID] },+ // crm_company_filters intentionally omitted = all visible companies+ },+ }),+ () => ({ staleTime: STALE_TIME, enabled: ENABLE_CRM })+ );++ const companies = createMemo<CrmCompanyEntity[]>(+ () => query.data?.filter(isCrmCompanyEntity) ?? []+ );++ return { query, companies };+}diff --git a/js/app/packages/queries/soup/recently-viewed.ts b/js/app/packages/queries/soup/recently-viewed.tsindex e35aa5c434..725775c945 100644--- a/js/app/packages/queries/soup/recently-viewed.ts+++ b/js/app/packages/queries/soup/recently-viewed.ts@@ -1,4 +1,5 @@import { NIL_UUID } from '@app/component/next-soup/filters/filter-store';+import { ENABLE_CRM } from '@core/constant/featureFlags';import { throwOnErr } from '@core/util/result';import { storageServiceClient } from '@service-storage/client';import { useQuery } from '@tanstack/solid-query';@@ -20,15 +21,15 @@ const RECENTLY_VIEWED_GC_TIME = 10 * 60 * 1000; // 10 minutesconst recentlyViewedArgs: SoupItemsQueryArgs = {params: { sort_method: 'viewed_at', limit: RECENTLY_VIEWED_LIMIT },body: {+ // No viewed_at signal on calls — exclude.call_filters: {call_ids: [NIL_UUID],},- crm_company_filters: {- company_ids: [NIL_UUID],- },foreign_entity_filters: {ids: [NIL_UUID],},+ // CRM companies only surface in recently-viewed when the feature is enabled.+ ...(ENABLE_CRM ? {} : { crm_company_filters: { company_ids: [NIL_UUID] } }),},};@@ -49,11 +50,7 @@ export function useRecentlyViewedSoupQuery() {}));return page.items.flatMap((item): RecentlyViewedItem[] => {- if (- item.tag === 'call' ||- item.tag === 'crmCompany' ||- item.tag === 'foreignEntity'- ) {+ if (item.tag === 'call' || item.tag === 'foreignEntity') {return [];}diff --git a/js/app/packages/queries/soup/transform-utils.ts b/js/app/packages/queries/soup/transform-utils.tsindex 0e058050ae..ee5ab1d70f 100644--- a/js/app/packages/queries/soup/transform-utils.ts+++ b/js/app/packages/queries/soup/transform-utils.ts@@ -15,6 +15,7 @@ import type {ChannelMessageEntity,ChatEntity,ContentHitData,+ CrmCompanyEntity,DocumentEntity,EmailEntity,EntityData,@@ -50,10 +51,9 @@ type InnerSearchResult =| ProjectSearchResult| CallRecordSearchResult;-type DisplayableSoupItem = Exclude<- SoupPage['items'][number],- { tag: 'crmCompany' }->;+// Every soup tag is handled by the map below (companies and foreign/GitHub-PR+// entities included), so nothing is excluded here.+type DisplayableSoupItem = SoupPage['items'][number];type SoupEntity =| DocumentEntity@@ -62,6 +62,7 @@ type SoupEntity =| EmailEntity| ChannelEntity| CallEntity+ | CrmCompanyEntity| ForeignEntity;type TypedInnerSearchResult =@@ -285,11 +286,41 @@ export const useSearchResponseItemMapper = () => {searchQuery: string): (WithSearch<EntityData> | undefined)[] => {switch (result.type) {- // CRM companies are opt-in via `include_crm`, which soup search does- // not set, so this is never hit at runtime. Handle it as a no-op to- // keep the union exhaustive; soup doesn't render CRM companies yet.- case 'company':- return [];+ case 'company': {+ const primaryDomain = result.domains[0]?.domain;+ const nameHighlight = result.nameHighlighted+ ? mergeAdjacentMacroEmTags(result.nameHighlighted)+ : null;+ return [+ {+ type: 'crm_company',+ id: result.id,+ teamId: result.teamId,+ name: result.name || primaryDomain || 'Unknown Company',+ ownerId: result.teamId,+ description: result.description ?? undefined,+ // Not returned by search — left undefined ("not loaded") so+ // consumers don't mistake it for a real `false`.+ emailSync: undefined,+ hidden: result.hidden,+ createdAt: result.createdAt,+ updatedAt: result.updatedAt,+ sortTs: result.updatedAt,+ domains: result.domains.map((d) => ({+ id: d.id,+ companyId: d.companyId,+ domain: d.domain,+ createdAt: d.createdAt,+ })),+ search: {+ nameHighlight,+ senderHighlightTerms: null,+ contentHitData: null,+ source: 'service',+ },+ },+ ];+ }case 'document': {if (!result.metadata || result.metadata.deleted_at) return [];const searchFileType =@@ -497,8 +528,6 @@ export const mapSoupPageToEntityList: ();}- if (item.tag === 'crmCompany') return false;-return (item.tag !== 'document' ||!options.instructionsIdQuery.isSuccess ||@@ -671,6 +700,30 @@ export const mapSoupPageToEntityList: (return out;}+ if (item.tag === 'crmCompany') {+ const primaryDomain = item.data.domains[0]?.domain;+ return {+ type: 'crm_company',+ id: item.data.id,+ teamId: item.data.teamId,+ name: item.data.name || primaryDomain || 'Unknown Company',+ ownerId: item.data.teamId,+ description: item.data.description ?? undefined,+ emailSync: item.data.emailSync,+ hidden: item.data.hidden,+ createdAt: item.data.createdAt,+ updatedAt: item.data.updatedAt,+ sortTs: item.data.updatedAt,+ frecencyScore: item.frecency_score,+ domains: item.data.domains.map((d) => ({+ id: d.id,+ companyId: d.companyId,+ domain: d.domain,+ createdAt: d.createdAt,+ })),+ } satisfies CrmCompanyEntity;+ }+return {...item.data,createdAt: item.data.createdAt,diff --git a/js/app/packages/queries/team/keys.ts b/js/app/packages/queries/team/keys.tsindex ff32786a6b..ae60001b19 100644--- a/js/app/packages/queries/team/keys.ts+++ b/js/app/packages/queries/team/keys.ts@@ -3,6 +3,7 @@ import { createQueryKeys } from '@lukemorales/query-key-factory';export const teamKeys = createQueryKeys('team', {userTeams: null,userInvites: null,+ currentTeam: null,detail: (teamId: string) => [teamId],invites: (teamId: string) => [teamId],});diff --git a/js/app/packages/queries/team/teams.ts b/js/app/packages/queries/team/teams.tsindex 87fc77aa6e..240a69b8b9 100644--- a/js/app/packages/queries/team/teams.ts+++ b/js/app/packages/queries/team/teams.ts@@ -1,9 +1,11 @@import { toast } from '@core/component/Toast/Toast';+import { useUserId } from '@core/context/user';import { throwOnErr } from '@core/util/result';import { authServiceClient } from '@service-auth/client';import type { CreateTeamRequest } from '@service-auth/generated/schemas/createTeamRequest';import type { PatchTeamRequest } from '@service-auth/generated/schemas/patchTeamRequest';import type { Team } from '@service-auth/generated/schemas/team';+import { TeamRole } from '@service-auth/generated/schemas/teamRole';import { useMutation, useQuery } from '@tanstack/solid-query';import type { Accessor } from 'solid-js';@@ -29,6 +31,30 @@ export function useTeamQuery(teamId: Accessor<string>) {}));}+/** The current user's team (`getTeam()` always returns it). */+export function useCurrentTeamQuery() {+ return useQuery(() => ({+ queryKey: teamKeys.currentTeam.queryKey,+ queryFn: async () => await throwOnErr(() => authServiceClient.getTeam()),+ }));+}++/**+ * Reactive boolean: true iff the current user has admin or owner team+ * role. Drives admin-gated UI (e.g. the companies → hidden tab and the+ * detail-page Hide button).+ */+export function useIsTeamAdmin(): Accessor<boolean> {+ const userId = useUserId();+ const teamQuery = useCurrentTeamQuery();+ return () => {+ const uid = userId();+ if (!uid) return false;+ const member = teamQuery.data?.members.find((m) => m.user_id === uid);+ return member?.role === TeamRole.admin || member?.role === TeamRole.owner;+ };+}+export function invalidateUserTeams() {return queryClient.invalidateQueries({queryKey: teamKeys.userTeams.queryKey,diff --git a/js/app/packages/service-clients/service-storage/client.ts b/js/app/packages/service-clients/service-storage/client.tsindex f9e50fa1e1..3ed471587a 100644--- a/js/app/packages/service-clients/service-storage/client.ts+++ b/js/app/packages/service-clients/service-storage/client.ts@@ -55,6 +55,7 @@ import {import type { CreateChannelRequest } from './generated/schemas/createChannelRequest';import type { CreateChannelResponse } from './generated/schemas/createChannelResponse';import type { CreateCommentResponse } from './generated/schemas/createCommentResponse';+import type { CreateCrmCommentRequest } from './generated/schemas/createCrmCommentRequest';import type { CreateDocument200 as CreateDocumentResponse } from './generated/schemas/createDocument200';import type { CreateDocumentRequest } from './generated/schemas/createDocumentRequest';import type { CreateEntityMentionRequest } from './generated/schemas/createEntityMentionRequest';@@ -66,7 +67,13 @@ import type { CreateProjectResponse } from './generated/schemas/createProjectResimport type { CreateTaskHandler200 } from './generated/schemas/createTaskHandler200';import type { CreateTaskRequest } from './generated/schemas/createTaskRequest';import type { CreateUnthreadedAnchorResponse } from './generated/schemas/createUnthreadedAnchorResponse';+import type { CrmComment } from './generated/schemas/crmComment';+import type { CrmCommentEntityType } from './generated/schemas/crmCommentEntityType';+import type { CrmCommentThread } from './generated/schemas/crmCommentThread';+import type { CrmCompanyResponse } from './generated/schemas/crmCompanyResponse';+import type { CrmContactResponse } from './generated/schemas/crmContactResponse';import type { DeleteCommentResponse } from './generated/schemas/deleteCommentResponse';+import type { DeleteCrmCommentResult } from './generated/schemas/deleteCrmCommentResult';import type { DeleteEntityMentionResponse } from './generated/schemas/deleteEntityMentionResponse';import type { DeleteUnthreadedAnchorResponse } from './generated/schemas/deleteUnthreadedAnchorResponse';import type { DocumentMetadata } from './generated/schemas/documentMetadata';@@ -74,6 +81,7 @@ import type { DocumentPreview } from './generated/schemas/documentPreview';import type { DocumentResponseMetadataWithContent } from './generated/schemas/documentResponseMetadataWithContent';import type { EditAnchorResponse } from './generated/schemas/editAnchorResponse';import type { EditCommentResponse } from './generated/schemas/editCommentResponse';+import type { EditCrmCommentRequest } from './generated/schemas/editCrmCommentRequest';import type { ExportDocumentResponse } from './generated/schemas/exportDocumentResponse';import type { GetAttachmentReferencesResponse } from './generated/schemas/getAttachmentReferencesResponse';import type { GetBatchChannelPreviewRequest } from './generated/schemas/getBatchChannelPreviewRequest';@@ -164,7 +172,9 @@ export type ItemType =| 'channel_message'| 'call'| 'automation'- | 'foreign';+ | 'foreign'+ | 'crm_company'+ | 'crm_contact';export const DEFAULT_ITEM_TYPE: ItemType = 'document';@@ -228,6 +238,8 @@ const itemTypeSet = new Set(['call','automation','thread',+ 'crm_company',+ 'crm_contact',]);function _isItemType(str: string): str is ItemType {@@ -250,6 +262,10 @@ export function blockNameToItemType(return 'email';case 'automation':return 'automation';+ case 'company':+ return 'crm_company';+ case 'contact':+ return 'crm_contact';default:return DEFAULT_ITEM_TYPE;}@@ -1881,6 +1897,104 @@ export const storageServiceClient = {})).map((result) => result.data);},+ async getCompany({ companyId }: { companyId: string }) {+ return await dssFetch<CrmCompanyResponse>(`/crm/companies/${companyId}`, {+ method: 'GET',+ });+ },+ async getCompanyContacts({ companyId }: { companyId: string }) {+ return await dssFetch<CrmContactResponse[]>(+ `/crm/companies/${companyId}/contacts`,+ { method: 'GET' }+ );+ },+ async getContact({ contactId }: { contactId: string }) {+ return await dssFetch<CrmContactResponse>(`/crm/contacts/${contactId}`, {+ method: 'GET',+ });+ },+ async setContactHidden({+ contactId,+ hidden,+ }: {+ contactId: string;+ hidden: boolean;+ }) {+ return await dssFetch(`/crm/contacts/${contactId}/hidden`, {+ method: 'PUT',+ body: JSON.stringify({ hidden }),+ });+ },+ async setCompanyHidden({+ companyId,+ hidden,+ }: {+ companyId: string;+ hidden: boolean;+ }) {+ return await dssFetch(`/crm/companies/${companyId}/hidden`, {+ method: 'PUT',+ body: JSON.stringify({ hidden }),+ });+ },+ async setEmailSync({+ companyId,+ emailSync,+ }: {+ companyId: string;+ emailSync: boolean;+ }) {+ return await dssFetch(`/crm/companies/${companyId}/email-sync`, {+ method: 'PUT',+ body: JSON.stringify({ email_sync: emailSync }),+ });+ },+ crmComments: {+ async list({+ entityType,+ entityId,+ }: {+ entityType: CrmCommentEntityType;+ entityId: string;+ }) {+ return await dssFetch<CrmCommentThread[]>(+ `/crm/comments/${entityType}/${entityId}`,+ { method: 'GET' }+ );+ },+ async create({+ entityType,+ entityId,+ body,+ }: {+ entityType: CrmCommentEntityType;+ entityId: string;+ body: CreateCrmCommentRequest;+ }) {+ return await dssFetch<CrmCommentThread>(+ `/crm/comments/${entityType}/${entityId}`,+ { method: 'POST', body: JSON.stringify(body) }+ );+ },+ async edit({+ commentId,+ body,+ }: {+ commentId: string;+ body: EditCrmCommentRequest;+ }) {+ return await dssFetch<CrmComment>(`/crm/comment/${commentId}`, {+ method: 'PATCH',+ body: JSON.stringify(body),+ });+ },+ async delete({ commentId }: { commentId: string }) {+ return await dssFetch<DeleteCrmCommentResult>(+ `/crm/comment/${commentId}`,+ { method: 'DELETE' }+ );+ },+ },} satisfies StorageServiceClient &typeof enhancements &Record<string, unknown>;diff --git a/js/app/packages/ui/components/Checkbox.tsx b/js/app/packages/ui/components/Checkbox.tsxindex 96cd59fe22..d2084882a9 100644--- a/js/app/packages/ui/components/Checkbox.tsx+++ b/js/app/packages/ui/components/Checkbox.tsx@@ -89,3 +89,22 @@ export const SingleSelectCheck = (props: { active: boolean }) => (class={cn('size-3 text-accent shrink-0', !props.active && 'hidden')}/>);++/**+ * Inline checkbox affordance — a small square that fills accent when checked+ * and shows an outlined empty box when not. Matches the soup-menu checkbox+ * pattern. Visual-only; pair with a clickable parent for the actual toggle.+ */+export const InlineCheckbox = (props: { checked: boolean }) => (+ <span+ aria-hidden+ class={cn(+ 'inline-flex items-center justify-center size-3.5 shrink-0 rounded-sm',+ props.checked+ ? 'bg-accent text-surface'+ : 'bg-transparent border border-edge-muted text-transparent'+ )}+ >+ <CheckIcon class="size-2.5" />+ </span>+);diff --git a/js/app/packages/ui/index.ts b/js/app/packages/ui/index.tsindex 74662084a0..d980d57748 100644--- a/js/app/packages/ui/index.ts+++ b/js/app/packages/ui/index.ts@@ -13,7 +13,11 @@ export { Button } from './components/Button';export { ButtonGroup } from './components/ButtonGroup';export type { ChatInputProps, ChatInputRows } from './components/ChatInput';export type { CheckboxProps } from './components/Checkbox';-export { Checkbox, SingleSelectCheck } from './components/Checkbox';+export {+ Checkbox,+ InlineCheckbox,+ SingleSelectCheck,+} from './components/Checkbox';export type { DialogProps } from './components/Dialog';export { Dialog } from './components/Dialog';export { Dropdown } from './components/Dropdown';diff --git a/js/app/tsconfig.json b/js/app/tsconfig.jsonindex 390b24d108..07d6463c18 100644--- a/js/app/tsconfig.json+++ b/js/app/tsconfig.json@@ -138,6 +138,18 @@"@channel/*": ["./packages/channel/*"],+ "@companies/*": [+ "./packages/companies/*"+ ],+ "@block-company/*": [+ "./packages/block-company/*"+ ],+ "@contacts/*": [+ "./packages/contacts/*"+ ],+ "@block-contact/*": [+ "./packages/block-contact/*"+ ],"@block-email/*": ["./packages/block-email/*"],diff --git a/js/bun.lock b/js/bun.lockindex c1b5aff31b..7810b68cf6 100644--- a/js/bun.lock+++ b/js/bun.lock@@ -178,6 +178,12 @@"app/packages/block-code": {"name": "block-code",},+ "app/packages/block-company": {+ "name": "block-company",+ },+ "app/packages/block-contact": {+ "name": "block-contact",+ },"app/packages/block-image": {"name": "block-image",},@@ -207,6 +213,12 @@"app/packages/channel": {"name": "channel",},+ "app/packages/companies": {+ "name": "companies",+ },+ "app/packages/contacts": {+ "name": "contacts",+ },"app/packages/core": {"name": "core",},@@ -1650,6 +1662,10 @@"block-code": ["block-code@workspace:app/packages/block-code"],+ "block-company": ["block-company@workspace:app/packages/block-company"],++ "block-contact": ["block-contact@workspace:app/packages/block-contact"],+"block-image": ["block-image@workspace:app/packages/block-image"],"block-markdown": ["block-markdown@workspace:app/packages/block-md"],@@ -1736,12 +1752,16 @@"commondir": ["[email protected]", "", {}, "sha512-W9pAhw0ja1Edb5GVdIF1mjZw/ASI0AlShXM83UUGe2DVr5TdAPEA1OA8m/g8zWp9x6On7gqufY+FatDbC3MDQg=="],+ "companies": ["companies@workspace:app/packages/companies"],+"compare-versions": ["[email protected]", "", {}, "sha512-4hm4VPpIecmlg59CHXnRDnqGplJFrbLG4aFEl5vl6cK1u76ws3LLvX7ikFnTDl5vo39sjWD6AaDPYodJp/NNHg=="],"component-emitter": ["[email protected]", "", {}, "sha512-T0+barUSQRTUQASh8bx02dl+DhF54GtIDY13Y3m9oWTklKbb3Wv974meRpeZ3lp1JpLVECWWNHC4vaG2XHXouQ=="],"concurrently": ["[email protected]", "", { "dependencies": { "chalk": "4.1.2", "rxjs": "7.8.2", "shell-quote": "1.8.3", "supports-color": "8.1.1", "tree-kill": "1.2.2", "yargs": "17.7.2" }, "bin": { "conc": "dist/bin/concurrently.js", "concurrently": "dist/bin/concurrently.js" } }, "sha512-fsfrO0MxV64Znoy8/l1vVIjjHa29SZyyqPgQBwhiDcaW8wJc2W3XWVOGx4M3oJBnv/zdUZIIp1gDeS98GzP8Ng=="],+ "contacts": ["contacts@workspace:app/packages/contacts"],+"convert-source-map": ["[email protected]", "", {}, "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg=="],"cookie": ["[email protected]", "", {}, "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ=="],