Skip to content

armgit / macro

Public Imported from GitHub
0

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

feat(crm): tasks, email, calls, and notes tabs/views (#8093)

dev-rba94c696f3a76
diff --git a/.agents/rules/web/startup-bundle.md b/.agents/rules/web/startup-bundle.md
index 32d6ed1087..ec7ffe2924 100644
--- a/.agents/rules/web/startup-bundle.md
+++ b/.agents/rules/web/startup-bundle.md
@@ -18,9 +18,10 @@ alwaysApply: false
- Each top-level route picks its shell in `app-router-view.tsx`
(`routes/shells.tsx`): `authRoute` pages and booking links render without app
chrome, and `appRoute` renders `AppShell` — the app's providers
- (`AppProviders`), chrome (`AppChrome` in `Layout.tsx`), and the split layout.
- Put state only the app's views use in `AppProviders`, not `Root`; `Root` keeps
- what every page or a call needs.
+ (`AppProviders`), layout/context owner (`SplitLayoutProvider`), chrome
+ (`AppChrome` in `Layout.tsx`), and split content. Compose these in the route
+ shell; keep `AppChrome` independent of page selection. Put state only the app's
+ views use in `AppProviders`, not `Root`; `Root` keeps what every page or call needs.
- `index.html` paints a boot shell before any JS runs: the saved theme's
background, the rail column, and the desktop app's content card — no app
content. The first shell to mount dismisses it (`dismissBootShell`). Keep its
diff --git a/apps/web/src/components/app/Layout.tsx b/apps/web/src/components/app/Layout.tsx
index c1c97c9d89..5cb5cb1566 100644
--- a/apps/web/src/components/app/Layout.tsx
+++ b/apps/web/src/components/app/Layout.tsx
@@ -65,7 +65,6 @@ import {
Show,
Suspense,
} from 'solid-js';
-import { AppProviders } from './AppProviders';
import { BundleUpdateProgressBar } from './BundleUpdateProgressBar';
import { DesktopTitleBar } from './DesktopTitleBar';
import GlobalShortcuts from './GlobalHotkeys';
@@ -232,9 +231,9 @@ function useNewOnboardingRedirect() {
}
/**
- * The app's providers and chrome — rail, hotkeys, command menu, launcher,
- * global modals, and the mobile dock — around a page. The split layout and
- * signed-in form pages render in it; auth, booking, and meeting pages don't.
+ * The app's chrome — rail, hotkeys, command menu, launcher, global modals,
+ * and the mobile dock — around a page. Route shells supply the providers and
+ * content; auth, booking, and meeting pages render without this chrome.
*/
export function AppChrome(props: ParentProps) {
const isAuthenticated = useIsAuthenticated();
@@ -255,100 +254,95 @@ export function AppChrome(props: ParentProps) {
);
return (
- <AppProviders>
- <SidebarVisibilityContext.Provider value={sidebarVisible}>
- <Show when={isAuthenticated() === true}>
- <ShowFeatureFlag flag={enableDatabases}>
- <Suspense>
- <StarterDatabase />
- </Suspense>
- </ShowFeatureFlag>
- </Show>
- <Suspense>
- <Show when={isAuthenticated()}>
- <GithubReauthenticationPrompt />
- <GmailReauthenticationPrompt />
- <CalendarPermissionPrompt />
- <GlobalShortcuts />
- <Show when={!isTouchDevice()}>
- <GoToHotkeys />
- <Suspense>
- <FavoritesCommands />
- <CommandMenu />
- </Suspense>
- </Show>
+ <SidebarVisibilityContext.Provider value={sidebarVisible}>
+ <Show when={isAuthenticated() === true}>
+ <ShowFeatureFlag flag={enableDatabases}>
+ <Suspense>
+ <StarterDatabase />
+ </Suspense>
+ </ShowFeatureFlag>
+ </Show>
+ <Suspense>
+ <Show when={isAuthenticated()}>
+ <GithubReauthenticationPrompt />
+ <GmailReauthenticationPrompt />
+ <CalendarPermissionPrompt />
+ <GlobalShortcuts />
+ <Show when={!isTouchDevice()}>
+ <GoToHotkeys />
<Suspense>
- <PropertyEditorModal />
+ <FavoritesCommands />
+ <CommandMenu />
</Suspense>
- <GlobalBulkEditEntityModal />
- <NativeShareSheet />
- <MacroMcpSetupModal />
- <CreateChannelModal />
- <Show when={companyDialogUsed()}>
- <Suspense>
- <CreateCompanyModal />
- </Suspense>
- </Show>
- <Show when={contactDialogUsed()}>
- <Suspense>
- <CreateContactModal />
- </Suspense>
- </Show>
- <Show when={isAddInboxDialogOpen()}>
- <AddInboxDialog />
- </Show>
</Show>
- <Show when={isAuthenticated() === false}>
- <Show when={hasLoginCookie()} fallback={<Banner />}>
- <SessionExpiredRedirect />
- </Show>
- </Show>
- </Suspense>
- <div class="min-h-0 flex-1 flex">
- <ItemDndProvider>
- <Show when={isSidebarVisible()}>
- <SidebarRail />
- </Show>
- <PageContent>
- {/* Route loading must not detach the chrome or mobile navigation;
- the route draws its own loading state. */}
- <Suspense>{props.children}</Suspense>
- </PageContent>
- </ItemDndProvider>
- </div>
- <Show when={isTouchDevice() && isAuthenticated()}>
- <FloatRegionHost />
<Suspense>
- <UserCardDrawer />
+ <PropertyEditorModal />
</Suspense>
- <Show when={isMobile()}>
+ <GlobalBulkEditEntityModal />
+ <NativeShareSheet />
+ <MacroMcpSetupModal />
+ <CreateChannelModal />
+ <Show when={companyDialogUsed()}>
+ <Suspense>
+ <CreateCompanyModal />
+ </Suspense>
+ </Show>
+ <Show when={contactDialogUsed()}>
<Suspense>
- <MobileSettings />
+ <CreateContactModal />
</Suspense>
</Show>
- {/* Search owns its filters at the top; suppress background composers. */}
- <FloatRegion
- region="accessory"
- priority={100}
- active={SearchState.isOpen}
- />
- <FloatRegion
- region="dock"
- active={() => !virtualKeyboardVisible() || SearchState.isOpen()}
- >
- <MobileDockRow />
- </FloatRegion>
+ <Show when={isAddInboxDialogOpen()}>
+ <AddInboxDialog />
+ </Show>
</Show>
- <InitialInteractiveOnboardingModal />
- <Suspense>
- <Show when={isAuthenticated()}>
- <Launcher
- open={createMenuOpen()}
- onOpenChange={setCreateMenuOpen}
- />
+ <Show when={isAuthenticated() === false}>
+ <Show when={hasLoginCookie()} fallback={<Banner />}>
+ <SessionExpiredRedirect />
</Show>
+ </Show>
+ </Suspense>
+ <div class="min-h-0 flex-1 flex">
+ <ItemDndProvider>
+ <Show when={isSidebarVisible()}>
+ <SidebarRail />
+ </Show>
+ <PageContent>
+ {/* Route loading must not detach the chrome or mobile navigation;
+ the route draws its own loading state. */}
+ <Suspense>{props.children}</Suspense>
+ </PageContent>
+ </ItemDndProvider>
+ </div>
+ <Show when={isTouchDevice() && isAuthenticated()}>
+ <FloatRegionHost />
+ <Suspense>
+ <UserCardDrawer />
</Suspense>
- </SidebarVisibilityContext.Provider>
- </AppProviders>
+ <Show when={isMobile()}>
+ <Suspense>
+ <MobileSettings />
+ </Suspense>
+ </Show>
+ {/* Search owns its filters at the top; suppress background composers. */}
+ <FloatRegion
+ region="accessory"
+ priority={100}
+ active={SearchState.isOpen}
+ />
+ <FloatRegion
+ region="dock"
+ active={() => !virtualKeyboardVisible() || SearchState.isOpen()}
+ >
+ <MobileDockRow />
+ </FloatRegion>
+ </Show>
+ <InitialInteractiveOnboardingModal />
+ <Suspense>
+ <Show when={isAuthenticated()}>
+ <Launcher open={createMenuOpen()} onOpenChange={setCreateMenuOpen} />
+ </Show>
+ </Suspense>
+ </SidebarVisibilityContext.Provider>
);
}
diff --git a/apps/web/src/components/app/split-layout/SplitLayout.tsx b/apps/web/src/components/app/split-layout/SplitLayout.tsx
index 525dbdd582..4be855e0fd 100644
--- a/apps/web/src/components/app/split-layout/SplitLayout.tsx
+++ b/apps/web/src/components/app/split-layout/SplitLayout.tsx
@@ -1,3 +1,4 @@
+import { CreateContextProvider } from '@app/features/command/context/create-context';
import { useSplitRouter } from '@app/lib/split-router';
import { setGlobalSplitManager } from '@app/signal/splitLayout';
import { useGlobalBlockOrchestrator } from '@components/app/GlobalAppState';
@@ -12,8 +13,10 @@ import {
createSelector,
For,
onCleanup,
+ type ParentProps,
Show,
Suspense,
+ useContext,
} from 'solid-js';
import { PopoverSplitRenderer } from './components/PopoverSplitRenderer';
import { SplitPanel } from './components/SplitPanel';
@@ -28,8 +31,8 @@ import {
import { DEFAULT_SPLIT_MIN_WIDTH } from './splitContentSizing';
import { createSplitFocusTracker } from './splitFocusTracker';
-/** The app route's view: the split manager, and one panel per pane. */
-export function SplitLayout() {
+/** Own the layout and creation context above both app chrome and pane content. */
+export function SplitLayoutProvider(props: ParentProps) {
const router = useSplitRouter();
const blockOrchestrator = useGlobalBlockOrchestrator();
@@ -39,6 +42,23 @@ export function SplitLayout() {
toContent: splitContentFromLocation,
stacked: isNativeMobilePlatform,
});
+ createEffect(() => setGlobalSplitManager(splitManager));
+ onCleanup(() => setGlobalSplitManager(undefined));
+
+ return (
+ <SplitLayoutContext.Provider value={{ manager: splitManager }}>
+ <CreateContextProvider focusedPaneId={splitManager.activeSplitId}>
+ {props.children}
+ </CreateContextProvider>
+ </SplitLayoutContext.Provider>
+ );
+}
+
+/** The app route's view: one panel per pane in the owning layout. */
+export function SplitLayout() {
+ const layout = useContext(SplitLayoutContext);
+ if (!layout) throw new Error('SplitLayout requires SplitLayoutProvider');
+ const splitManager = layout.manager;
const paneStack = isNativeMobilePlatform()
? createMobilePaneStack(splitManager)
: undefined;
@@ -71,11 +91,9 @@ export function SplitLayout() {
const ids = createMemo(() => splits().map(({ id }) => id));
createSplitFocusTracker({ splitManager, panelRefs, splits });
- createEffect(() => setGlobalSplitManager(splitManager));
- onCleanup(() => setGlobalSplitManager(undefined));
return (
- <SplitLayoutContext.Provider value={{ manager: splitManager }}>
+ <>
<Show
when={paneStack}
fallback={
@@ -135,6 +153,6 @@ export function SplitLayout() {
popover?.close();
}}
/>
- </SplitLayoutContext.Provider>
+ </>
);
}
diff --git a/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx b/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx
index 1944cbc4d7..c3defd7c97 100644
--- a/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx
+++ b/apps/web/src/components/app/split-layout/tests/activity-registration.test.tsx
@@ -1,5 +1,12 @@
-import { cleanup, render, screen } from '@solidjs/testing-library';
-import { createSignal, Suspense } from 'solid-js';
+import {
+ CreateContextProvider,
+ useCreateContext,
+} from '@app/features/command/context/create-context';
+import { crmTaskComposerContext } from '@app/features/crm/task-composer';
+import { SYSTEM_PROPERTY_IDS } from '@property/identifiers';
+import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
+import { type Accessor, createSignal, Suspense } from 'solid-js';
+import { Dynamic } from 'solid-js/web';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { resolveComponent } from '../componentRegistry';
@@ -13,8 +20,12 @@ const state = vi.hoisted(() => ({
track: vi.fn(),
mountActivity: vi.fn(),
mountProjects: vi.fn(),
+ saveTask: vi.fn(),
isPopover: false,
close: vi.fn(),
+ split: undefined as { id: string } | undefined,
+ managerPublished: true,
+ unregister: [] as (() => void)[],
}));
vi.mock('@service-storage/websocket', () => ({
@@ -41,6 +52,17 @@ vi.mock('@app/lib/analytics/posthog', () => ({
loading: !state.flagsLoaded(),
}),
}));
+vi.mock('@core/constant/featureFlags', async (importOriginal) => {
+ const original =
+ await importOriginal<typeof import('@core/constant/featureFlags')>();
+ return {
+ ...original,
+ isFeatureEnabled: (flag: typeof original.enableCrmActivity) =>
+ flag === original.enableCrmActivity
+ ? state.enabled()
+ : original.isFeatureEnabled(flag),
+ };
+});
vi.mock('@app/lib/analytics/analytics-context', () => ({
useAnalytics: () => ({ pageView: state.pageView, track: state.track }),
}));
@@ -123,11 +145,57 @@ vi.mock('@app/features/tasks-view/tasks-view', () => ({}));
vi.mock('@app/features/tasks-view/components/TasksDetailView', () => ({
TasksDetailRouteView: () => null,
}));
-vi.mock('@app/signal/splitLayout', () => ({}));
+vi.mock('@app/signal/splitLayout', () => {
+ const manager = { activeSplit: () => state.split };
+ return {
+ globalSplitManager: () => (state.managerPublished ? manager : undefined),
+ };
+});
vi.mock('@block-calendar/components/EventComposerSplit', () => ({}));
vi.mock('@block-channel/component/Compose', () => ({}));
vi.mock('@block-md/component/ComposeSkill', () => ({}));
-vi.mock('@block-md/component/ComposeTask', () => ({}));
+vi.mock('@block-md/component/ComposeTask', () => ({
+ ComposeTask: (props: {
+ composerContext?: {
+ key: string;
+ initialPropertyValues?: Record<string, unknown>;
+ };
+ initialTitle?: string;
+ }) => {
+ const [title, setTitle] = createSignal(props.initialTitle ?? '');
+ const [content, setContent] = createSignal('');
+ return (
+ <div>
+ <div>
+ {props.composerContext?.key ?? 'Standard'} composer:{' '}
+ {props.initialTitle}
+ </div>
+ <input
+ aria-label="Task title"
+ value={title()}
+ onInput={(event) => setTitle(event.currentTarget.value)}
+ />
+ <textarea
+ aria-label="Task description"
+ value={content()}
+ onInput={(event) => setContent(event.currentTarget.value)}
+ />
+ <button
+ type="button"
+ onClick={() =>
+ state.saveTask({
+ title: title(),
+ content: content(),
+ properties: props.composerContext?.initialPropertyValues,
+ })
+ }
+ >
+ Save task
+ </button>
+ </div>
+ );
+ },
+}));
vi.mock('@app/features/crm/queries/saved-views', () => ({}));
vi.mock('@core/context/user', () => ({}));
vi.mock('@core/mobile/isTouchDevice', () => ({
@@ -145,8 +213,13 @@ beforeEach(() => {
state.enabled = () => false;
state.flagsLoaded = () => true;
state.touch = () => false;
+ state.split = undefined;
+ state.managerPublished = true;
+});
+afterEach(() => {
+ cleanup();
+ for (const unregister of state.unregister.splice(0)) unregister();
});
-afterEach(cleanup);
/** Registry views are lazy chunks; settle the chunk so assertions see the view. */
async function renderActivity() {
@@ -231,6 +304,329 @@ describe('activity registration', () => {
});
});
+describe('contextual task composer registration', () => {
+ it.each([false, true])(
+ 'opens immediately while flags load and keeps its opening mode (enabled after load: %s)',
+ async (enabled) => {
+ const [flagEnabled, setFlagEnabled] = createSignal(false);
+ const [flagsLoaded, setFlagsLoaded] = createSignal(false);
+ state.enabled = flagEnabled;
+ state.flagsLoaded = flagsLoaded;
+ const component = resolveComponent('task-compose', {
+ initialTitle: 'Follow up',
+ composerContext: { key: 'crm:company:acme', visiblePropertyIds: [] },
+ });
+ render(() => (
+ <Suspense>
+ <Dynamic component={component.element} />
+ </Suspense>
+ ));
+ expect(
+ await screen.findByText('crm:company:acme composer: Follow up')
+ ).toBeTruthy();
+ const title = screen.getByRole('textbox', { name: 'Task title' });
+ fireEvent.input(title, { target: { value: 'Draft saved' } });
+
+ setFlagEnabled(enabled);
+ setFlagsLoaded(true);
+ expect(
+ screen.getByText('crm:company:acme composer: Follow up')
+ ).toBeTruthy();
+ expect(screen.getByRole('textbox', { name: 'Task title' })).toBe(title);
+ expect(title).toHaveProperty('value', 'Draft saved');
+
+ const next = resolveComponent('task-compose', {
+ initialTitle: 'Next',
+ composerContext: { key: 'crm:company:acme', visiblePropertyIds: [] },
+ });
+ render(() => (
+ <Suspense>
+ <Dynamic component={next.element} />
+ </Suspense>
+ ));
+ expect(
+ await screen.findByText('crm:company:acme composer: Next')
+ ).toBeTruthy();
+ }
+ );
+
+ it('opens standard tasks without waiting for the CRM rollout', async () => {
+ state.flagsLoaded = () => false;
+ const component = resolveComponent('task-compose', {
+ initialTitle: 'Plan',
+ });
+ render(() => (
+ <Suspense>
+ <Dynamic component={component.element} />
+ </Suspense>
+ ));
+ expect(await screen.findByText('Standard composer: Plan')).toBeTruthy();
+ });
+
+ it.each([true, false])(
+ 'preserves an open draft and its associations when the rollout changes (initial: %s)',
+ async (initiallyEnabled) => {
+ const [enabled, setEnabled] = createSignal(initiallyEnabled);
+ state.enabled = enabled;
+ const properties = {
+ companies: {
+ valueType: 'ENTITY',
+ refs: [{ entity_id: 'acme', entity_type: 'COMPANY' }],
+ },
+ };
+ const component = resolveComponent('task-compose', {
+ composerContext: {
+ key: 'CRM',
+ visiblePropertyIds: ['companies'],
+ initialPropertyValues: properties,
+ },
+ });
+ render(() => (
+ <Suspense>
+ <Dynamic component={component.element} />
+ </Suspense>
+ ));
+ const title = await screen.findByRole('textbox', { name: 'Task title' });
+ const description = screen.getByRole('textbox', {
+ name: 'Task description',
+ });
+ fireEvent.input(title, { target: { value: 'Follow up with Acme' } });
+ fireEvent.input(description, {
+ target: { value: 'Discuss the renewal' },
+ });
+ setEnabled(!initiallyEnabled);
+ expect(screen.getByRole('textbox', { name: 'Task title' })).toBe(title);
+ expect(screen.getByRole('textbox', { name: 'Task description' })).toBe(
+ description
+ );
+ fireEvent.click(screen.getByRole('button', { name: 'Save task' }));
+ expect(state.saveTask).toHaveBeenCalledExactlyOnceWith({
+ title: 'Follow up with Acme',
+ content: 'Discuss the renewal',
+ properties,
+ });
+ const next = resolveComponent('task-compose', {
+ initialTitle: 'New draft',
+ composerContext: { key: 'CRM', initialPropertyValues: properties },
+ });
+ render(() => (
+ <Suspense>
+ <Dynamic component={next.element} />
+ </Suspense>
+ ));
+ expect(await screen.findByText('CRM composer: New draft')).toBeTruthy();
+ }
+ );
+
+ it.each([true, false])(
+ 'uses supplied context when flags change before mounting (enabled at launch: %s)',
+ async (initiallyEnabled) => {
+ const [enabled, setEnabled] = createSignal(initiallyEnabled);
+ state.enabled = enabled;
+ const properties = {
+ companies: {
+ valueType: 'ENTITY',
+ refs: [{ entity_id: 'acme', entity_type: 'COMPANY' }],
+ },
+ };
+ const component = resolveComponent('task-compose', {
+ initialTitle: 'Follow up',
+ composerContext: { key: 'CRM', initialPropertyValues: properties },
+ });
+ setEnabled(!initiallyEnabled);
+ render(() => (
+ <Suspense>
+ <Dynamic component={component.element} />
+ </Suspense>
+ ));
+ await screen.findByRole('textbox', { name: 'Task title' });
+ fireEvent.click(screen.getByRole('button', { name: 'Save task' }));
+ expect(state.saveTask).toHaveBeenCalledExactlyOnceWith({
+ title: 'Follow up',
+ content: '',
+ properties,
+ });
+ }
+ );
+});
+
+function mountCreateContext(focusedPaneId: Accessor<string | undefined>) {
+ let context!: ReturnType<typeof useCreateContext>;
+ render(() => (
+ <CreateContextProvider focusedPaneId={focusedPaneId}>
+ {(() => {
+ context = useCreateContext();
+ return null;
+ })()}
+ </CreateContextProvider>
+ ));
+ return context;
+}
+
+describe('pane create context registration', () => {
+ it('reads the focused pane and supports explicit pane selection', () => {
+ const [paneId, setPaneId] = createSignal<string | undefined>('one');
+ const context = mountCreateContext(paneId);
+ state.unregister.push(
+ context.register('one', () => ({ task: { key: 'first' } })),
+ context.register('two', () => ({ task: { key: 'second' } }))
+ );
+ expect(context.read('task')?.key).toBe('first');
+ expect(context.snapshot('task')?.key).toBe('first');
+ setPaneId('two');
+ expect(context.read('task')?.key).toBe('second');
+ expect(context.snapshot('task', 'one')?.key).toBe('first');
+ expect(context.read('task', 'one')?.key).toBe('first');
+ setPaneId(undefined);
+ expect(context.read('task')).toBeUndefined();
+ expect(context.snapshot('task')).toBeUndefined();
+ });
+
+ it('isolates providers with identical pane IDs', () => {
+ const first = mountCreateContext(() => 'pane');
+ const second = mountCreateContext(() => 'pane');
+ state.unregister.push(
+ first.register('pane', () => ({ task: { key: 'first' } })),
+ second.register('pane', () => ({ task: { key: 'second' } }))
+ );
+ expect(first.snapshot('task')?.key).toBe('first');
+ expect(second.snapshot('task')?.key).toBe('second');
+ });
+
+ it('works without a published global split manager', () => {
+ state.managerPublished = false;
+ const context = mountCreateContext(() => 'pane');
+ state.unregister.push(
+ context.register('pane', () => ({ task: { key: 'mounted' } }))
+ );
+ expect(context.snapshot('task')?.key).toBe('mounted');
+ });
+
+ it('restores the parent after nested cleanup and tolerates repeated teardown', () => {
+ const context = mountCreateContext(() => 'pane');
+ const removeParent = context.register('pane', () => ({
+ task: { key: 'parent' },
+ }));
+ const removeChild = context.register('pane', () => ({
+ task: { key: 'child' },
+ }));
+ state.unregister.push(removeParent, removeChild);
+ expect(context.snapshot('task')?.key).toBe('child');
+ removeChild();
+ expect(context.snapshot('task')?.key).toBe('parent');
+ removeChild();
+ expect(context.snapshot('task')?.key).toBe('parent');
+ removeParent();
+ expect(context.snapshot('task')).toBeUndefined();
+ });
+
+ it('keeps the child when its parent unmounts first', () => {
+ const context = mountCreateContext(() => 'pane');
+ const removeParent = context.register('pane', () => ({
+ task: { key: 'parent' },
+ }));
+ const removeChild = context.register('pane', () => ({
+ task: { key: 'child' },
+ }));
+ state.unregister.push(removeParent, removeChild);
+ removeParent();
+ expect(context.snapshot('task')?.key).toBe('child');
+ removeChild();
+ expect(context.snapshot('task')).toBeUndefined();
+ });
+
+ it('reads loaded associations at launch and leaves an earlier snapshot unchanged', () => {
+ const context = mountCreateContext(() => 'pane');
+ const [companyId, setCompanyId] = createSignal<string>();
+ state.unregister.push(
+ context.register('pane', () => ({
+ task: crmTaskComposerContext({
+ type: 'contact',
+ id: 'maya',
+ companyId: companyId(),
+ }),
+ }))
+ );
+ const first = context.snapshot('task');
+ expect(
+ first?.initialPropertyValues?.[SYSTEM_PROPERTY_IDS.COMPANIES]
+ ).toBeUndefined();
+ setCompanyId('acme');
+ const next = context.snapshot('task');
+ expect(next?.initialPropertyValues?.[SYSTEM_PROPERTY_IDS.CONTACTS]).toEqual(
+ {
+ valueType: 'ENTITY',
+ refs: [{ entity_id: 'maya', entity_type: 'CONTACT' }],
+ }
+ );
+ expect(
+ next?.initialPropertyValues?.[SYSTEM_PROPERTY_IDS.COMPANIES]
+ ).toEqual({
+ valueType: 'ENTITY',
+ refs: [{ entity_id: 'acme', entity_type: 'COMPANY' }],
+ });
+ expect(
+ first?.initialPropertyValues?.[SYSTEM_PROPERTY_IDS.COMPANIES]
+ ).toBeUndefined();
+ });
+
+ it('isolates snapshots from mutable provider values', () => {
+ const context = mountCreateContext(() => 'pane');
+ const preset = crmTaskComposerContext({ type: 'company', id: 'acme' });
+ state.unregister.push(context.register('pane', () => ({ task: preset })));
+ const snapshot = context.snapshot('task');
+ preset.visiblePropertyIds?.push('new-property');
+ expect(snapshot?.visiblePropertyIds).not.toContain('new-property');
+ });
+
+ it('suppresses a parent with null and responds to reactive source changes', () => {
+ const context = mountCreateContext(() => 'pane');
+ const [enabled, setEnabled] = createSignal(false);
+ state.unregister.push(
+ context.register('pane', () => ({ task: { key: 'parent' } })),
+ context.register('pane', () => ({
+ task: enabled() ? { key: 'child' } : null,
+ }))
+ );
+ expect(context.read('task')).toBeUndefined();
+ expect(context.snapshot('task')).toBeUndefined();
+ setEnabled(true);
+ const snapshot = context.snapshot('task');
+ expect(snapshot?.key).toBe('child');
+ setEnabled(false);
+ expect(context.read('task')).toBeUndefined();
+ expect(snapshot?.key).toBe('child');
+ });
+
+ it('inherits the parent action when the child omits it', () => {
+ const context = mountCreateContext(() => 'pane');
+ state.unregister.push(
+ context.register('pane', () => ({ task: { key: 'parent' } })),
+ context.register('pane', () => ({}))
+ );
+ expect(context.read('task')?.key).toBe('parent');
+ expect(context.snapshot('task')?.key).toBe('parent');
+ });
+
+ it('updates reads when registrations change', () => {
+ const context = mountCreateContext(() => 'pane');
+ const removeParent = context.register('pane', () => ({
+ task: { key: 'parent' },
+ }));
+ state.unregister.push(removeParent);
+ expect(context.read('task')?.key).toBe('parent');
+ const removeChild = context.register('pane', () => ({
+ task: { key: 'child' },
+ }));
+ state.unregister.push(removeChild);
+ expect(context.read('task')?.key).toBe('child');
+ removeChild();
+ expect(context.read('task')?.key).toBe('parent');
+ removeParent();
+ expect(context.read('task')).toBeUndefined();
+ });
+});
+
describe('project registration', () => {
const routes = [
['tasks-projects', 'Project collection'],
diff --git a/apps/web/src/features/block-md/component/ComposeTask.tsx b/apps/web/src/features/block-md/component/ComposeTask.tsx
index 7f638983a8..1ea352eb00 100644
--- a/apps/web/src/features/block-md/component/ComposeTask.tsx
+++ b/apps/web/src/features/block-md/component/ComposeTask.tsx
@@ -73,9 +73,11 @@ import {
} from 'solid-js';
import { reconcile, unwrap } from 'solid-js/store';
import { tabbable } from 'tabbable';
+import type { TaskComposerContext } from '../../task-composer/core/context';
import {
createTaskComposerProperties,
createTaskWithProperties,
+ DEFAULT_TASK_COMPOSER_PROPERTY_IDS,
defaultTaskPropertyValues,
taskComposerProjectValue,
} from '../util/taskComposerProperties';
@@ -83,10 +85,11 @@ import {
clearTaskComposerDraft,
loadTaskComposerDraft,
saveTaskComposerDraft,
- updateDraftTimestamp,
+ taskComposerContextStorage,
} from '../util/taskComposerStorage';
import { EditorSystemMessage } from './EditorSystemMessage';
import { InlinePropertyValue } from './InlinePropertyValue';
+import { TaskComposerPropertyEditor } from './TaskComposerPropertyEditor';
import { SimilarTasksSection } from './TaskDuplicateList';
type ComposerTagLayoutMode = 'bottom' | 'title';
@@ -351,6 +354,7 @@ export interface ComposeTaskProps {
initialAssigneeIds?: string[];
/** Start in this project, e.g. when composing from the project's page. */
initialProjectId?: string;
+ composerContext?: TaskComposerContext;
/** Prefill the visible Due Date control when creating from a timeline. */
initialDueDate?: Date;
/**
@@ -375,6 +379,9 @@ export function ComposeTask(props: ComposeTaskProps) {
const splitPanel = useSplitPanelOrThrow();
const { popoverSplit, openWithSplit } = useSplitLayout();
const currentUserId = useUserId();
+ const draftStorage = props.composerContext
+ ? taskComposerContextStorage(props.composerContext.key)
+ : undefined;
const getDefaultPropertyValues = (): Record<string, PropertyApiValues> => {
const ids = (() => {
@@ -384,7 +391,10 @@ export function ComposeTask(props: ComposeTaskProps) {
const id = currentUserId();
return id ? [id] : [];
})();
- return defaultTaskPropertyValues(ids);
+ return {
+ ...defaultTaskPropertyValues(ids),
+ ...props.composerContext?.initialPropertyValues,
+ };
};
// Contextual project and date values apply without discarding a restored draft.
@@ -413,13 +423,16 @@ export function ComposeTask(props: ComposeTaskProps) {
!props.initialContent &&
!props.initialAssigneeIds?.length
) {
- const draft = loadTaskComposerDraft();
+ const draft = loadTaskComposerDraft(draftStorage);
if (draft) {
return {
title: draft.title,
content: draft.content,
editorState: draft.editorState,
propertyValues: withInitialProperties(draft.propertyValues),
+ visiblePropertyIds:
+ draft.visiblePropertyIds ??
+ props.composerContext?.visiblePropertyIds,
isDraftLoaded: true,
};
}
@@ -429,6 +442,7 @@ export function ComposeTask(props: ComposeTaskProps) {
content: props.initialContent ?? '',
editorState: undefined,
propertyValues: withInitialProperties(getDefaultPropertyValues()),
+ visiblePropertyIds: props.composerContext?.visiblePropertyIds,
isDraftLoaded: false,
};
};
@@ -495,20 +509,57 @@ export function ComposeTask(props: ComposeTaskProps) {
propertyValues,
setPropertyValues,
properties,
+ visiblePropertyIds,
+ setVisiblePropertyIds,
+ availableProperties,
+ addProperty,
saveHandler,
composerTags,
clearComposerTags,
createDefinitions,
} = createTaskComposerProperties({
initialValues: initialState.propertyValues,
+ initialVisiblePropertyIds: initialState.visiblePropertyIds,
+ allDefinitions: true,
});
+ let baselinePropertyValues = JSON.stringify(initialState.propertyValues);
+ let baselineVisiblePropertyIds = JSON.stringify(visiblePropertyIds());
+ const hasDraftChanges = () =>
+ !!title() ||
+ !!content() ||
+ isDraftLoaded() ||
+ JSON.stringify(propertyValues) !== baselinePropertyValues ||
+ JSON.stringify(visiblePropertyIds()) !== baselineVisiblePropertyIds;
// History upsert mutation
const upsertToHistoryMutation = useUpsertToHistoryMutation();
// draft saving logic
let hasInitializedFromDraft = isDraftLoaded();
- const debouncedSave = debounce(saveTaskComposerDraft, 300);
+ let skipNextDraftSave = false;
+ const debouncedSave = debounce(
+ (draft: Parameters<typeof saveTaskComposerDraft>[0]) =>
+ saveTaskComposerDraft(draft, draftStorage),
+ 300
+ );
+ const draftSnapshot = () => ({
+ title: title(),
+ content: content(),
+ editorState: bodyEditor()?.getEditorState().toJSON(),
+ propertyValues: structuredClone(unwrap(propertyValues)),
+ visiblePropertyIds: [...visiblePropertyIds()],
+ });
+ onCleanup(() => {
+ debouncedSave.clear();
+ // Escape and backdrop dismissal bypass the close button. Flush before disposal.
+ if (!isCreating() && hasDraftChanges()) {
+ saveTaskComposerDraft(draftSnapshot(), draftStorage);
+ }
+ });
+ const clearDraft = () => {
+ debouncedSave.clear();
+ clearTaskComposerDraft(draftStorage);
+ };
createEffect(() => {
const currentTitle = title();
@@ -517,8 +568,13 @@ export function ComposeTask(props: ComposeTaskProps) {
// change (e.g. setting a due date). unwrap()'d access doesn't subscribe,
// so without this the draft only saved when title/content changed.
JSON.stringify(propertyValues);
+ visiblePropertyIds();
const currentProperties = structuredClone(unwrap(propertyValues));
+ if (skipNextDraftSave) {
+ skipNextDraftSave = false;
+ return;
+ }
if (hasInitializedFromDraft) {
hasInitializedFromDraft = false;
return;
@@ -529,6 +585,7 @@ export function ComposeTask(props: ComposeTaskProps) {
content: currentContent,
editorState: bodyEditor()?.getEditorState().toJSON(),
propertyValues: currentProperties,
+ visiblePropertyIds: [...visiblePropertyIds()],
});
});
@@ -594,12 +651,16 @@ export function ComposeTask(props: ComposeTaskProps) {
});
};
- // A retry keeps how this composer creates tasks, not its one-shot callbacks.
+ // A retry keeps its host context and creation policy, not one-shot editor callbacks.
const reopenForRetry = () =>
popoverSplit({
type: 'component',
id: 'task-compose',
- params: { createTask: props.createTask },
+ params: {
+ createTask: props.createTask,
+ composerContext: props.composerContext,
+ initialProjectId: props.initialProjectId,
+ },
});
const handleCreateTask = async () => {
@@ -618,7 +679,8 @@ export function ComposeTask(props: ComposeTaskProps) {
const properties = structuredClone(Object.entries(unwrap(propertyValues)));
const resetTitleAndBody = () => {
- clearTaskComposerDraft();
+ clearDraft();
+ skipNextDraftSave = true;
setTitle('');
setContent('');
setIsDraftLoaded(false);
@@ -630,12 +692,8 @@ export function ComposeTask(props: ComposeTaskProps) {
if (!createMore()) {
// Snapshot the draft locally, then clear localStorage so a new dialog
// opened while this creation is in flight starts blank.
- const draftSnapshot = {
- title: taskTitle,
- content: taskContent,
- propertyValues: structuredClone(unwrap(propertyValues)),
- };
- clearTaskComposerDraft();
+ const snapshot = draftSnapshot();
+ clearDraft();
const createdTask = await (props.createTask ?? createTaskWithProperties)(
taskTitle,
taskContent,
@@ -657,7 +715,8 @@ export function ComposeTask(props: ComposeTaskProps) {
if (!createdTask) {
props.onCreateFailure?.();
// Restore the draft and re-open so the user can retry
- saveTaskComposerDraft(draftSnapshot);
+ debouncedSave.clear();
+ saveTaskComposerDraft(snapshot, draftStorage);
reopenForRetry();
return;
}
@@ -695,7 +754,7 @@ export function ComposeTask(props: ComposeTaskProps) {
}
// Success: clear draft and notify
- clearTaskComposerDraft();
+ clearDraft();
const { documentId, initialSnapshot } = createdTask;
if (props.onSuccess) {
props.onSuccess({ documentId, title: taskTitle, content: taskContent });
@@ -718,12 +777,8 @@ export function ComposeTask(props: ComposeTaskProps) {
setIsCreating(true);
const properties = structuredClone(Object.entries(unwrap(propertyValues)));
- const draftSnapshot = {
- title: taskTitle,
- content: taskContent,
- propertyValues: structuredClone(unwrap(propertyValues)),
- };
- clearTaskComposerDraft();
+ const snapshot = draftSnapshot();
+ clearDraft();
let split: ReturnType<typeof openWithSplit>['split'];
@@ -750,7 +805,8 @@ export function ComposeTask(props: ComposeTaskProps) {
if (!createdTask) {
split?.goBack();
- saveTaskComposerDraft(draftSnapshot);
+ debouncedSave.clear();
+ saveTaskComposerDraft(snapshot, draftStorage);
reopenForRetry();
return;
}
@@ -780,12 +836,6 @@ export function ComposeTask(props: ComposeTaskProps) {
};
const handleClose = () => {
- const currentTitle = title();
- const currentContent = content();
-
- if (currentTitle || currentContent) {
- updateDraftTimestamp();
- }
splitPanel.handle.close();
props.onClose?.();
};
@@ -802,14 +852,21 @@ export function ComposeTask(props: ComposeTaskProps) {
};
const handleClearDraft = () => {
- clearTaskComposerDraft();
+ clearDraft();
+ skipNextDraftSave = true;
setTitle('');
setContent('');
setPropertyValues(
reconcile(withInitialProperties(getDefaultPropertyValues()))
);
+ setVisiblePropertyIds(
+ props.composerContext?.visiblePropertyIds ??
+ DEFAULT_TASK_COMPOSER_PROPERTY_IDS
+ );
setTagLayoutMode('bottom');
setIsDraftLoaded(false);
+ baselinePropertyValues = JSON.stringify(unwrap(propertyValues));
+ baselineVisiblePropertyIds = JSON.stringify(visiblePropertyIds());
const ed = bodyEditor();
ed && initializeEditorEmpty(ed);
};
@@ -915,7 +972,7 @@ export function ComposeTask(props: ComposeTaskProps) {
</Button>
</Show>
</div>
- <Show when={content().trim() || title()}>
+ <Show when={hasDraftChanges()}>
<Button
onMouseDown={handleClearDraft}
tabIndex={-1}
@@ -1067,6 +1124,13 @@ export function ComposeTask(props: ComposeTaskProps) {
<Show when={tagLayoutMode() === 'bottom'}>
<InlineTagsPill docTags={composerTags} showPlaceholder />
</Show>
+ <TaskComposerPropertyEditor
+ name={title()}
+ definitions={availableProperties()}
+ properties={properties()}
+ onAdd={addProperty}
+ onSave={(id, value) => setPropertyValues(id, value)}
+ />
</EntityComposer.Properties>
<Modals />
</PropertiesProvider>
diff --git a/apps/web/src/features/block-md/component/InlineTaskProperties.test.tsx b/apps/web/src/features/block-md/component/InlineTaskProperties.test.tsx
index b407d09996..b3feaa9282 100644
--- a/apps/web/src/features/block-md/component/InlineTaskProperties.test.tsx
+++ b/apps/web/src/features/block-md/component/InlineTaskProperties.test.tsx
@@ -2,9 +2,17 @@ import {
$getPinnedProperties,
pinnedPropertiesPlugin,
} from '@core/component/LexicalMarkdown/plugins/pinned-properties/pinnedPropertiesPlugin';
-import { usePropertiesContext } from '@property/context/PropertiesContext';
+import {
+ PropertiesProvider,
+ usePropertiesContext,
+} from '@property/context/PropertiesContext';
import type { openPropertyEditor } from '@property/editor/state/propertyEditor';
-import type { Property } from '@property/types';
+import type {
+ Property,
+ PropertyApiValues,
+ PropertyDefinitionDomain,
+} from '@property/types';
+import type { PropertyDefinition } from '@service-properties/generated/schemas/propertyDefinition';
import {
cleanup,
fireEvent,
@@ -19,8 +27,10 @@ import {
type LexicalEditor,
} from 'lexical';
import { createSignal } from 'solid-js';
-import { afterEach, expect, it, vi } from 'vitest';
+import { createStore } from 'solid-js/store';
+import { afterEach, beforeEach, expect, it, vi } from 'vitest';
import { InlineTaskProperties } from './InlineTaskProperties';
+import { TaskComposerPropertyEditor } from './TaskComposerPropertyEditor';
const mocks = vi.hoisted(() => ({
editor: undefined as LexicalEditor | undefined,
@@ -30,9 +40,27 @@ const mocks = vi.hoisted(() => ({
kind: 'document' as 'document' | 'task',
projectsEnabled: false,
}));
+const entityWrite = vi.fn();
+
+beforeEach(() => {
+ vi.spyOn(window, 'scrollTo').mockImplementation(() => {});
+});
+
+vi.mock('@service-storage/websocket', () => ({
+ storageWS: { reconnectIfDisconnected: vi.fn() },
+ createWebSocketJob: vi.fn(),
+}));
+vi.mock('@service-connection/websocket', () => ({
+ ws: { addEventListener: vi.fn(), send: vi.fn() },
+ createConnectionWebsocketEffect: vi.fn(),
+}));
vi.mock('@app/lib/analytics/posthog', () => ({
useFeatureFlag: () => () => ({ enabled: mocks.projectsEnabled }),
}));
+vi.mock('@entity', () => ({
+ InlineEntity: () => null,
+ isTaskEntity: () => false,
+}));
vi.mock('@entity/extractors-property', () => ({
buildTaskProjectDefaultProperty: () => ({
propertyId: 'pending:project',
@@ -50,7 +78,35 @@ vi.mock('@property/editor/state/propertyEditor', () => ({
openPropertyEditor: mocks.open,
}));
vi.mock('@property/component/modal', () => ({ Modals: () => null }));
-vi.mock('@property/hooks', () => ({
+vi.mock('@property/component/modal/CreatePropertyModal', () => ({
+ CreatePropertyModal: (props: {
+ initialName: string;
+ autoPinOnCreate: boolean;
+ onPropertyCreated: (id: string, definition: PropertyDefinition) => void;
+ }) => (
+ <button
+ onClick={() =>
+ props.onPropertyCreated('created-notes', {
+ id: 'created-notes',
+ display_name: props.initialName,
+ data_type: 'STRING',
+ is_multi_select: false,
+ is_metadata: false,
+ is_system: false,
+ owner: { scope: 'system' },
+ specific_entity_type: null,
+ created_at: '2026-01-01',
+ updated_at: '2026-01-01',
+ })
+ }
+ >
+ Create {props.initialName}
+ </button>
+ ),
+}));
+vi.mock('@property/hooks', async () => ({
+ usePropertySelection: (await import('@property/hooks/usePropertySelection'))
+ .usePropertySelection,
useEntityProperties: () => ({
properties: () => mocks.properties(),
refetch: vi.fn(),
@@ -59,11 +115,16 @@ vi.mock('@property/hooks', () => ({
}),
}));
vi.mock('@property/tags', () => ({ InlineFetchedEntityTagsPill: () => null }));
+vi.mock('@queries/properties/definitions', () => ({
+ useListPropertiesQuery: () => ({ isSuccess: false }),
+ fetchPropertyDefinitionWithOptions: vi.fn(async () => null),
+}));
vi.mock('@queries/properties/tags', () => ({
useTagsQuery: () => ({ isSuccess: true, data: [] }),
}));
vi.mock('@queries/properties/entity', () => ({
- useBulkSaveEntityPropertiesMutation: () => ({ mutateAsync: vi.fn() }),
+ useBulkSaveEntityPropertiesMutation: () => ({ mutateAsync: entityWrite }),
+ useEntityPropertiesQuery: () => ({ data: [] }),
}));
vi.mock('@core/component/LexicalMarkdown/component/status/Progress', () => ({
ProgressChip: () => null,
@@ -94,6 +155,7 @@ vi.mock('./InlinePropertyValue', () => ({
afterEach(() => {
cleanup();
vi.clearAllMocks();
+ vi.restoreAllMocks();
mocks.kind = 'document';
mocks.projectsEnabled = false;
});
@@ -110,6 +172,18 @@ const property: Property = {
updatedAt: '2026-01-01',
};
+const draftDefinition: PropertyDefinitionDomain = {
+ id: 'draft-notes',
+ displayName: 'Draft notes',
+ valueType: 'STRING',
+ isMultiSelect: false,
+ isMetadata: false,
+ isSystem: false,
+ owner: { scope: 'system' },
+ createdAt: '2026-01-01',
+ updatedAt: '2026-01-01',
+};
+
function setup(initial: Property[] = []) {
const editor = createEditor({
onError: (error) => {
@@ -181,3 +255,115 @@ it("shows a task's Project with the other task properties, through the same pill
setup();
expect(screen.queryByRole('button', { name: 'Unpin Project' })).toBeNull();
});
+
+it('selects a shared property and edits its draft value without an entity write', async () => {
+ const onAdd = vi.fn(async () => {});
+ const [values, setValues] = createStore<Record<string, PropertyApiValues>>(
+ {}
+ );
+ render(() => (
+ <PropertiesProvider
+ entityType="TASK"
+ canEdit
+ properties={() => []}
+ onRefresh={() => {}}
+ onPropertyAdded={() => {}}
+ onPropertyDeleted={() => {}}
+ saveHandler={{ saveProperty: async () => {}, saveDate: async () => {} }}
+ >
+ <TaskComposerPropertyEditor
+ name="New task"
+ definitions={[draftDefinition]}
+ properties={[]}
+ onAdd={onAdd}
+ onSave={(id, value) => setValues(id, value)}
+ />
+ </PropertiesProvider>
+ ));
+
+ await fireEvent.click(screen.getByRole('button', { name: 'Add property' }));
+ await fireEvent.click(screen.getByText('Draft notes'));
+ await waitFor(() => expect(onAdd).toHaveBeenCalledWith('draft-notes'));
+ await fireEvent.input(screen.getByPlaceholderText('Enter Draft notes'), {
+ target: { value: 'Remember this' },
+ });
+ await fireEvent.click(screen.getByText('Set Draft notes', { exact: false }));
+ await waitFor(() =>
+ expect(screen.queryByPlaceholderText('Enter Draft notes')).toBeNull()
+ );
+ expect(values['draft-notes']).toEqual({
+ valueType: 'STRING',
+ value: 'Remember this',
+ });
+ expect(entityWrite).not.toHaveBeenCalled();
+
+ await fireEvent.click(screen.getByRole('button', { name: 'Add property' }));
+ await fireEvent.click(screen.getByText('Draft notes'));
+ await fireEvent.keyDown(document, { key: 'Escape' });
+ await waitFor(() =>
+ expect(screen.queryByPlaceholderText('Enter Draft notes')).toBeNull()
+ );
+ await fireEvent.click(screen.getByRole('button', { name: 'Add property' }));
+ expect(screen.getByText('Draft notes')).toBeTruthy();
+ expect(values['draft-notes']).toEqual({
+ valueType: 'STRING',
+ value: 'Remember this',
+ });
+ expect(entityWrite).not.toHaveBeenCalled();
+});
+
+it('creates a property through the shared dialog and saves its value into the draft', async () => {
+ const onAdd = vi.fn(async () => {});
+ const [values, setValues] = createStore<Record<string, PropertyApiValues>>(
+ {}
+ );
+ render(() => (
+ <PropertiesProvider
+ entityType="TASK"
+ canEdit
+ properties={() => []}
+ onRefresh={() => {}}
+ onPropertyAdded={() => {}}
+ onPropertyDeleted={() => {}}
+ saveHandler={{ saveProperty: async () => {}, saveDate: async () => {} }}
+ >
+ <TaskComposerPropertyEditor
+ name="New task"
+ definitions={[]}
+ properties={[]}
+ onAdd={onAdd}
+ onSave={(id, value) => setValues(id, value)}
+ />
+ </PropertiesProvider>
+ ));
+
+ await fireEvent.click(screen.getByRole('button', { name: 'Add property' }));
+ await fireEvent.input(screen.getByPlaceholderText('Choose a property...'), {
+ target: { value: 'New notes' },
+ });
+ await fireEvent.click(screen.getByText('Create property "New notes"'));
+ await fireEvent.click(
+ screen.getByRole('button', { name: 'Create New notes' })
+ );
+ await waitFor(() =>
+ expect(onAdd).toHaveBeenCalledWith(
+ 'created-notes',
+ expect.objectContaining({
+ definition: expect.objectContaining({
+ id: 'created-notes',
+ is_multi_select: false,
+ }),
+ property_options: [],
+ })
+ )
+ );
+ await fireEvent.input(await screen.findByPlaceholderText('Enter New notes'), {
+ target: { value: 'Created value' },
+ });
+ await fireEvent.click(screen.getByText('Set New notes', { exact: false }));
+ expect(values['created-notes']).toEqual({
+ valueType: 'STRING',
+ value: 'Created value',
+ });
+ expect(entityWrite).not.toHaveBeenCalled();
+});
diff --git a/apps/web/src/features/block-md/component/TaskComposerPropertyEditor.tsx b/apps/web/src/features/block-md/component/TaskComposerPropertyEditor.tsx
new file mode 100644
index 0000000000..2fb51234fe
--- /dev/null
+++ b/apps/web/src/features/block-md/component/TaskComposerPropertyEditor.tsx
@@ -0,0 +1,62 @@
+import { AddPropertyButton } from '@property/component/AddPropertyButton';
+import { PropertyEditorDialog } from '@property/editor/PropertyEditorModal';
+import type { PropertyEditorState } from '@property/editor/state/propertyEditor';
+import type {
+ Property,
+ PropertyApiValues,
+ PropertyDefinitionDomain,
+} from '@property/types';
+import type { PropertyDefinitionWithOptions } from '@service-properties/generated/schemas/propertyDefinitionWithOptions';
+import { createSignal, Show } from 'solid-js';
+import { createStore } from 'solid-js/store';
+
+/** Use the same property flow as the side panel, with writes owned by the draft. */
+export function TaskComposerPropertyEditor(props: {
+ name: string;
+ definitions: PropertyDefinitionDomain[];
+ properties: Property[];
+ onAdd: (id: string, created?: PropertyDefinitionWithOptions) => Promise<void>;
+ onSave: (id: string, value: PropertyApiValues) => void;
+}) {
+ const [open, setOpen] = createSignal(false);
+ const [state, setState] = createStore<PropertyEditorState>({
+ mode: 'selector',
+ selectedEntities: [],
+ });
+ const close = () => {
+ setOpen(false);
+ setState({ mode: 'selector', targetProperty: undefined });
+ };
+
+ return (
+ <>
+ <AddPropertyButton onClick={() => setOpen(true)} />
+ <Show when={open()}>
+ <PropertyEditorDialog
+ isOpen={open()}
+ state={state}
+ onModeChange={(mode) => setState('mode', mode)}
+ onTargetChange={(property) => setState('targetProperty', property)}
+ onClose={close}
+ onPropertyAdded={async (ids) => {
+ for (const id of ids ?? []) await props.onAdd(id);
+ }}
+ onPropertyCreated={(created) =>
+ props.onAdd(created.definition.id, created)
+ }
+ onSave={(property, value) =>
+ props.onSave(
+ 'propertyDefinitionId' in property
+ ? property.propertyDefinitionId
+ : property.id,
+ value
+ )
+ }
+ availableProperties={props.definitions}
+ properties={props.properties}
+ name={props.name || 'New task'}
+ />
+ </Show>
+ </>
+ );
+}
diff --git a/apps/web/src/features/block-md/util/taskComposerProperties.test.ts b/apps/web/src/features/block-md/util/taskComposerProperties.test.ts
index b97b13fdca..5982050615 100644
--- a/apps/web/src/features/block-md/util/taskComposerProperties.test.ts
+++ b/apps/web/src/features/block-md/util/taskComposerProperties.test.ts
@@ -1,10 +1,15 @@
import { SYSTEM_PROPERTY_IDS } from '@property/constants';
+import { usePropertySelection } from '@property/hooks/usePropertySelection';
+import { toPropertyDefinitionDomain } from '@property/utils/transforms';
+import { createRoot, createSignal } from 'solid-js';
import { afterEach, expect, it, vi } from 'vitest';
const mock = vi.hoisted(() => ({
create: vi.fn(),
properties: vi.fn(),
failure: vi.fn(),
+ listProperties: vi.fn(),
+ refetch: vi.fn(),
}));
vi.mock('@core/util/create', () => ({
createTaskWithInitialSnapshot: mock.create,
@@ -19,10 +24,15 @@ vi.mock('@app/lib/analytics/posthog', () => ({
useFeatureFlag: () => () => ({ enabled: true }),
}));
vi.mock('@property/tags', () => ({ useLocalDocTags: vi.fn() }));
-vi.mock('@queries/properties/definitions', () => ({}));
-vi.mock('@queries/properties/tags', () => ({}));
+vi.mock('@queries/properties/definitions', () => ({
+ useListPropertiesQuery: mock.listProperties,
+}));
+vi.mock('@queries/properties/tags', () => ({
+ useTagsQuery: () => ({ isSuccess: true, data: [] }),
+}));
import {
+ createTaskComposerProperties,
createTaskWithProperties,
taskComposerProjectValue,
} from './taskComposerProperties';
@@ -95,3 +105,206 @@ it('skips the check without a project', async () => {
await create();
expect(mock.properties).not.toHaveBeenCalled();
});
+
+import type { PropertyDefinition } from '@service-properties/generated/schemas/propertyDefinition';
+import {
+ taskComposerVisiblePropertyIds,
+ taskComposerWritableDefinitions,
+ withoutTaskComposerTags,
+} from './taskComposerProperties';
+
+function definition(
+ id: string,
+ overrides: Partial<PropertyDefinition> = {}
+): PropertyDefinition {
+ return {
+ id,
+ display_name: id,
+ data_type: 'STRING',
+ is_metadata: false,
+ is_system: false,
+ is_multi_select: false,
+ specific_entity_type: null,
+ owner: { scope: 'system' },
+ created_at: '',
+ updated_at: '',
+ ...overrides,
+ };
+}
+
+it('keeps entity-reference targets while excluding metadata, tags, and database columns', () => {
+ const definitions = [
+ definition('assignees', {
+ data_type: 'ENTITY',
+ specific_entity_type: 'USER',
+ }),
+ definition('companies', {
+ data_type: 'ENTITY',
+ specific_entity_type: 'COMPANY',
+ }),
+ definition('contacts', {
+ data_type: 'ENTITY',
+ specific_entity_type: 'CONTACT',
+ }),
+ definition('project', {
+ data_type: 'ENTITY',
+ specific_entity_type: 'INITIATIVE',
+ }),
+ definition('metadata', { is_metadata: true }),
+ definition('tag', { data_type: 'TAG' }),
+ definition('tag-set'),
+ definition('column', { owner: { scope: 'database', database_id: 'db' } }),
+ ];
+ expect(
+ taskComposerWritableDefinitions(definitions, new Set(['tag-set'])).map(
+ (d) => d.id
+ )
+ ).toEqual(['assignees', 'companies', 'contacts', 'project']);
+});
+
+it('keeps context order, ignores unavailable ids and deduplicates selected properties', () => {
+ const definitions = [definition('a'), definition('b')];
+ expect(
+ taskComposerVisiblePropertyIds(
+ ['b', 'missing', 'b', 'a'],
+ definitions,
+ true
+ )
+ ).toEqual(['b', 'a']);
+ expect(taskComposerVisiblePropertyIds([], definitions, true)).toEqual([]);
+});
+
+it('keeps Project behind its feature flag', () => {
+ const definitions = [definition(SYSTEM_PROPERTY_IDS.PROJECT)];
+ expect(
+ taskComposerVisiblePropertyIds(
+ [SYSTEM_PROPERTY_IDS.PROJECT],
+ definitions,
+ false
+ )
+ ).toEqual([]);
+});
+
+it('clears tag sets without clearing arbitrary single-select values', () => {
+ const values = {
+ tag: { valueType: 'SELECT_STRING' as const, values: ['red'] },
+ custom: { valueType: 'SELECT_STRING' as const, values: ['active'] },
+ };
+ expect(withoutTaskComposerTags(values, new Set(['tag']))).toEqual({
+ custom: values.custom,
+ });
+ expect(values.tag.values).toEqual(['red']);
+});
+
+it('lets a draft add Project when its preset omits it without changing entity panels', () => {
+ createRoot((dispose) => {
+ const project = toPropertyDefinitionDomain(
+ definition(SYSTEM_PROPERTY_IDS.PROJECT)
+ );
+ const [existingIds, setExistingIds] = createSignal<string[]>([]);
+ const draft = usePropertySelection(
+ existingIds,
+ () => [project],
+ undefined,
+ () => true
+ );
+ const panel = usePropertySelection(
+ () => [],
+ () => [project]
+ );
+ expect(draft.filteredProperties()).toEqual([project]);
+ expect(panel.filteredProperties()).toEqual([]);
+ setExistingIds([project.id]);
+ expect(draft.filteredProperties()).toEqual([]);
+ dispose();
+ });
+});
+
+it('converts an arbitrary added single-select property with its definition', async () => {
+ mock.create.mockResolvedValue({ documentId: 'task' });
+ await createTaskWithProperties(
+ 'Task',
+ '',
+ [['custom', { valueType: 'SELECT_STRING', values: ['chosen'] }]],
+ new Map([['custom', definition('custom', { data_type: 'SELECT_STRING' })]]),
+ vi.fn()
+ );
+ expect(mock.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ propertyValues: [
+ {
+ propertyId: 'custom',
+ value: { type: 'select_option', option_id: 'chosen' },
+ },
+ ],
+ })
+ );
+});
+
+it('retains a created single-select definition when the definition query fails', async () => {
+ mock.create.mockResolvedValue({ documentId: 'task' });
+ mock.refetch.mockResolvedValue({
+ isError: true,
+ error: new Error('Definition refresh failed'),
+ });
+ mock.listProperties.mockReturnValue({
+ isSuccess: false,
+ data: [],
+ refetch: mock.refetch,
+ });
+ const created = {
+ definition: definition('created-select', { data_type: 'SELECT_STRING' }),
+ property_options: [
+ {
+ id: 'chosen',
+ property_definition_id: 'created-select',
+ value: { type: 'string' as const, value: 'Chosen' },
+ display_order: 0,
+ color: null,
+ created_at: '',
+ updated_at: '',
+ },
+ ],
+ };
+ const { composer, dispose } = createRoot((dispose) => ({
+ composer: createTaskComposerProperties({
+ initialValues: {},
+ initialVisiblePropertyIds: [],
+ allDefinitions: true,
+ }),
+ dispose,
+ }));
+
+ try {
+ await composer.addProperty(created.definition.id, created);
+ composer.setPropertyValues(created.definition.id, {
+ valueType: 'SELECT_STRING',
+ values: ['chosen'],
+ });
+ expect(composer.properties()[0]).toMatchObject({
+ propertyDefinitionId: 'created-select',
+ value: ['chosen'],
+ isMultiSelect: false,
+ });
+ await createTaskWithProperties(
+ 'Task',
+ '',
+ Object.entries(composer.propertyValues),
+ composer.createDefinitions(),
+ vi.fn()
+ );
+ expect(mock.create).toHaveBeenCalledWith(
+ expect.objectContaining({
+ propertyValues: [
+ {
+ propertyId: 'created-select',
+ value: { type: 'select_option', option_id: 'chosen' },
+ },
+ ],
+ })
+ );
+ expect(mock.refetch).not.toHaveBeenCalled();
+ } finally {
+ dispose();
+ }
+});
diff --git a/apps/web/src/features/block-md/util/taskComposerProperties.ts b/apps/web/src/features/block-md/util/taskComposerProperties.ts
index 47cb529aa2..b2273ae6a5 100644
--- a/apps/web/src/features/block-md/util/taskComposerProperties.ts
+++ b/apps/web/src/features/block-md/util/taskComposerProperties.ts
@@ -15,25 +15,67 @@ import type {
PropertyApiValues,
PropertyOption,
} from '@property/types';
+import { toPropertyDefinitionDomain } from '@property/utils/transforms';
import { useListPropertiesQuery } from '@queries/properties/definitions';
import { fetchEntityProperties } from '@queries/properties/entity';
import { useTagsQuery } from '@queries/properties/tags';
import type { PropertyDefinition } from '@service-properties/generated/schemas/propertyDefinition';
import type { PropertyDefinitionDetailResponse } from '@service-properties/generated/schemas/propertyDefinitionDetailResponse';
+import type { PropertyDefinitionWithOptions } from '@service-properties/generated/schemas/propertyDefinitionWithOptions';
+import { createSignal } from 'solid-js';
import { createStore, reconcile, type Store, unwrap } from 'solid-js/store';
/**
* Props shown in the composer (Linear-style left-to-right order). Project
* shows only while Projects is enabled.
*/
-const COMPOSER_PROPERTIES = [
+export const DEFAULT_TASK_COMPOSER_PROPERTY_IDS = [
SYSTEM_PROPERTY_IDS.STATUS,
SYSTEM_PROPERTY_IDS.PRIORITY,
SYSTEM_PROPERTY_IDS.ASSIGNEES,
SYSTEM_PROPERTY_IDS.DUE_DATE,
SYSTEM_PROPERTY_IDS.PROJECT,
];
-const COMPOSER_PROPERTY_SET = new Set<string>(COMPOSER_PROPERTIES);
+const COMPOSER_PROPERTY_SET = new Set<string>(
+ DEFAULT_TASK_COMPOSER_PROPERTY_IDS
+);
+
+/** Exclude definitions that cannot be edited on a task or belong to Tags. */
+export function taskComposerWritableDefinitions(
+ definitions: PropertyDefinition[],
+ tagSetIds: ReadonlySet<string> = new Set()
+): PropertyDefinition[] {
+ return definitions.filter(
+ (definition) =>
+ !definition.is_metadata &&
+ definition.data_type !== 'TAG' &&
+ definition.owner.scope !== 'database' &&
+ !tagSetIds.has(definition.id)
+ );
+}
+
+/** Keep the default order unless a host supplies its own visible property list. */
+export function taskComposerVisiblePropertyIds(
+ requested: readonly string[] | undefined,
+ available: readonly PropertyDefinition[],
+ projectsEnabled: boolean
+): string[] {
+ const ids = new Set(available.map((definition) => definition.id));
+ return [...new Set(requested ?? DEFAULT_TASK_COMPOSER_PROPERTY_IDS)].filter(
+ (id) =>
+ ids.has(id) && (id !== SYSTEM_PROPERTY_IDS.PROJECT || projectsEnabled)
+ );
+}
+
+/** Only Tags owns tag-set values; clearing tags must leave custom selects alone. */
+export function withoutTaskComposerTags(
+ values: Record<string, PropertyApiValues>,
+ tagSetIds: ReadonlySet<string>
+): Record<string, PropertyApiValues> {
+ const next = structuredClone(values);
+ for (const id of tagSetIds) delete next[id];
+ return next;
+}
/** The Project value naming `projectId`. */
export function taskComposerProjectValue(projectId: string): PropertyApiValues {
@@ -213,34 +255,66 @@ function extractPropertyValue(
*/
export function createTaskComposerProperties(args: {
initialValues: Record<string, PropertyApiValues>;
+ initialVisiblePropertyIds?: string[];
+ allDefinitions?: boolean;
}) {
const [propertyValues, setPropertyValues] = createStore<
Record<string, PropertyApiValues>
>(args.initialValues);
+ const [visiblePropertyIds, setVisiblePropertyIds] = createSignal(
+ args.initialVisiblePropertyIds ?? DEFAULT_TASK_COMPOSER_PROPERTY_IDS
+ );
const systemPropertiesQuery = useListPropertiesQuery(() => ({
- scope: 'system',
+ scope: args.allDefinitions ? 'all' : 'system',
includeOptions: true,
+ forEntityType: args.allDefinitions ? 'TASK' : undefined,
}));
const tagsQuery = useTagsQuery();
+ const [createdProperties, setCreatedProperties] = createSignal<
+ PropertyDefinitionWithOptions[]
+ >([]);
+ const propertyDefinitions = () => {
+ const fetched = systemPropertiesQuery.isSuccess
+ ? systemPropertiesQuery.data
+ : [];
+ return [
+ ...fetched,
+ ...createdProperties().filter(
+ (created) =>
+ !fetched.some(
+ (item) =>
+ ('definition' in item ? item.definition.id : item.id) ===
+ created.definition.id
+ )
+ ),
+ ];
+ };
- const definitions = () => {
- if (!systemPropertiesQuery.isSuccess) return new Map();
- const data = systemPropertiesQuery.data;
- return new Map(
- data.map((p) => {
- const definition = 'definition' in p ? p.definition : p;
- return [definition.id, definition];
- })
+ const availableDefinitions = () => {
+ const tagSetIds = new Set(
+ (tagsQuery.isSuccess ? tagsQuery.data : []).flatMap((tagSet) =>
+ tagSet.definition ? [tagSet.definition.id] : []
+ )
+ );
+ return taskComposerWritableDefinitions(
+ propertyDefinitions().map((item) =>
+ 'definition' in item ? item.definition : item
+ ),
+ tagSetIds
);
};
+ const definitions = () =>
+ new Map(
+ availableDefinitions().map((definition) => [definition.id, definition])
+ );
const createDefinitions = () => {
const map = new Map<
PropertyDefinition['id'],
PropertyDefinition | PropertyDefinitionDetailResponse
>(definitions());
- for (const tagSet of tagsQuery.data ?? []) {
+ for (const tagSet of tagsQuery.isSuccess ? tagsQuery.data : []) {
if (tagSet.definition) {
map.set(tagSet.definition.id, tagSet.definition);
}
@@ -249,8 +323,7 @@ export function createTaskComposerProperties(args: {
};
const options = () => {
- if (!systemPropertiesQuery.isSuccess) return new Map();
- const data = systemPropertiesQuery.data;
+ const data = propertyDefinitions();
return new Map(
data.map((p) => {
const definition = 'definition' in p ? p.definition : p;
@@ -262,9 +335,44 @@ export function createTaskComposerProperties(args: {
const projects = useFeatureFlag(enableProjects);
+ const visibleIds = () =>
+ taskComposerVisiblePropertyIds(
+ visiblePropertyIds(),
+ availableDefinitions(),
+ projects().enabled
+ );
+ const addableDefinitions = () =>
+ availableDefinitions().filter(
+ (definition) =>
+ !visibleIds().includes(definition.id) &&
+ (definition.id !== SYSTEM_PROPERTY_IDS.PROJECT || projects().enabled)
+ );
+ const addProperty = async (
+ id: string,
+ created?: PropertyDefinitionWithOptions
+ ) => {
+ if (created) {
+ setCreatedProperties((current) => [
+ ...current.filter((property) => property.definition.id !== id),
+ created,
+ ]);
+ }
+ if (!addableDefinitions().some((definition) => definition.id === id))
+ return;
+ setVisiblePropertyIds((current) => [...current, id]);
+ };
+ const availableProperties = () =>
+ availableDefinitions()
+ .filter(
+ (definition) =>
+ definition.id !== SYSTEM_PROPERTY_IDS.PROJECT || projects().enabled
+ )
+ .map((definition) =>
+ toPropertyDefinitionDomain(definition, options().get(definition.id))
+ );
+
const properties = (): Property[] => {
- return filterMap(COMPOSER_PROPERTIES, (id) => {
- if (id === SYSTEM_PROPERTY_IDS.PROJECT && !projects().enabled) return;
+ return filterMap(visibleIds(), (id) => {
const definition = definitions().get(id);
if (!definition) return;
return {
@@ -310,24 +418,26 @@ export function createTaskComposerProperties(args: {
}
);
- /** Drops every applied tag value, keeping the composer's system props. */
+ /** Drops applied tags without clearing other select properties. */
const clearComposerTags = () => {
- const next = structuredClone(unwrap(propertyValues));
- for (const [definitionId, value] of Object.entries(next)) {
- if (
- value.valueType === 'SELECT_STRING' &&
- !COMPOSER_PROPERTY_SET.has(definitionId)
- ) {
- delete next[definitionId];
- }
- }
- setPropertyValues(reconcile(next));
+ const tagSetIds = new Set(
+ (tagsQuery.isSuccess ? tagsQuery.data : []).flatMap((tagSet) =>
+ tagSet.definition ? [tagSet.definition.id] : []
+ )
+ );
+ setPropertyValues(
+ reconcile(withoutTaskComposerTags(unwrap(propertyValues), tagSetIds))
+ );
};
return {
propertyValues,
setPropertyValues,
properties,
+ visiblePropertyIds,
+ setVisiblePropertyIds,
+ availableProperties,
+ addProperty,
saveHandler,
composerTags,
clearComposerTags,
diff --git a/apps/web/src/features/block-md/util/taskComposerStorage.test.ts b/apps/web/src/features/block-md/util/taskComposerStorage.test.ts
index 28dc8ab978..0e0689a2e5 100644
--- a/apps/web/src/features/block-md/util/taskComposerStorage.test.ts
+++ b/apps/web/src/features/block-md/util/taskComposerStorage.test.ts
@@ -8,6 +8,7 @@ import {
loadTaskComposerDraft,
saveTaskComposerDraft,
type TaskComposerDraft,
+ taskComposerContextStorage,
} from './taskComposerStorage';
const DEFAULT_KEY = 'task-composer-draft';
@@ -95,3 +96,30 @@ describe('taskComposerStorage', () => {
expect(due.value).toBeInstanceOf(Date);
});
});
+
+describe('context drafts', () => {
+ beforeEach(() => localStorage.clear());
+
+ it('isolates context keys and persists visible property ids without touching the global draft', () => {
+ const company = taskComposerContextStorage('crm:company:one');
+ const contact = taskComposerContextStorage('crm:contact:two');
+ saveTaskComposerDraft(
+ { ...draft, visiblePropertyIds: ['company'] },
+ company
+ );
+ saveTaskComposerDraft(
+ { ...draft, title: 'Contact', visiblePropertyIds: [] },
+ contact
+ );
+ saveTaskComposerDraft(draft);
+
+ expect(company.storageKey).toBe('task-composer-draft:crm:company:one');
+ expect(loadTaskComposerDraft(company)?.visiblePropertyIds).toEqual([
+ 'company',
+ ]);
+ expect(loadTaskComposerDraft(contact)?.visiblePropertyIds).toEqual([]);
+ clearTaskComposerDraft(company);
+ expect(loadTaskComposerDraft(contact)?.title).toBe('Contact');
+ expect(loadTaskComposerDraft()?.title).toBe('A task');
+ });
+});
diff --git a/apps/web/src/features/block-md/util/taskComposerStorage.ts b/apps/web/src/features/block-md/util/taskComposerStorage.ts
index 90c013ecc4..4fed5242e8 100644
--- a/apps/web/src/features/block-md/util/taskComposerStorage.ts
+++ b/apps/web/src/features/block-md/util/taskComposerStorage.ts
@@ -2,6 +2,13 @@ import type { PropertyApiValues } from '@property/types';
import type { SerializedEditorState } from 'lexical';
const STORAGE_KEY = 'task-composer-draft';
+
+/** Context drafts use their own key; the global composer retains its original key. */
+export function taskComposerContextStorage(
+ key: string
+): TaskComposerDraftStorage {
+ return { storageKey: `${STORAGE_KEY}:${key}` };
+}
const EXPIRY_TIME_MS = 2 * 60 * 1000; // 2 minutes
/**
@@ -23,6 +30,7 @@ export interface TaskComposerDraft {
/** Markdown text fallback (used by older drafts and for the createTask API) */
content: string;
propertyValues: Record<string, PropertyApiValues>;
+ visiblePropertyIds?: string[];
timestamp: number;
}
diff --git a/apps/web/src/features/command/Launcher.test.tsx b/apps/web/src/features/command/Launcher.test.tsx
index 5f36dbbda4..978bb7fdd8 100644
--- a/apps/web/src/features/command/Launcher.test.tsx
+++ b/apps/web/src/features/command/Launcher.test.tsx
@@ -3,6 +3,10 @@ import { cleanup, fireEvent, render } from '@solidjs/testing-library';
import { ok } from 'neverthrow';
import { createSignal } from 'solid-js';
import { afterEach, beforeEach, expect, it, vi } from 'vitest';
+import {
+ CreateContextProvider,
+ useCreateContext,
+} from './context/create-context';
const host = vi.hoisted(() => ({
popoverSplit: vi.fn(),
@@ -98,6 +102,8 @@ import {
type LauncherInnerProps,
runCreateAction,
setCreateMenuOpen,
+ useCreateAction,
+ useCreateCommands,
useCreateMenuBlocks,
} from './Launcher';
@@ -167,9 +173,11 @@ it('reactively adds and removes Project while retaining Task and Folder', () =>
);
};
const view = render(() => (
- <MemoryRouter>
- <Route path="/" component={Menu} />
- </MemoryRouter>
+ <CreateContextProvider focusedPaneId={() => undefined}>
+ <MemoryRouter>
+ <Route path="/" component={Menu} />
+ </MemoryRouter>
+ </CreateContextProvider>
));
expect(view.container.textContent).not.toContain('Project');
expect(view.container.textContent).toContain('Task');
@@ -302,3 +310,76 @@ it('opens the Folder composer without creating a folder immediately', () => {
expect(host.createFolder).not.toHaveBeenCalled();
expect(host.openWithSplit).not.toHaveBeenCalled();
});
+
+it('binds create-menu and shortcut actions to the provider and snapshots before focus changes', () => {
+ const [focusedPane, setFocusedPane] = createSignal('first');
+ const first = { key: 'first', visiblePropertyIds: ['company'] };
+ const Menu = () => {
+ const context = useCreateContext();
+ context.register('first', () => ({ task: first }));
+ context.register('second', () => ({ task: { key: 'second' } }));
+ const task = useCreateCommands().find((item) => item.blockName === 'task');
+ return <button onClick={() => task?.keyDownHandler()}>New task</button>;
+ };
+ const view = render(() => (
+ <CreateContextProvider focusedPaneId={focusedPane}>
+ <MemoryRouter>
+ <Route path="/" component={Menu} />
+ </MemoryRouter>
+ </CreateContextProvider>
+ ));
+ host.popoverSplit.mockImplementationOnce(() => setFocusedPane('second'));
+ fireEvent.click(view.getByText('New task'));
+ first.visiblePropertyIds.push('changed');
+ expect(host.popoverSplit).toHaveBeenNthCalledWith(1, {
+ type: 'component',
+ id: 'task-compose',
+ params: {
+ composerContext: { key: 'first', visiblePropertyIds: ['company'] },
+ },
+ });
+ fireEvent.click(view.getByText('New task'));
+ expect(host.popoverSplit).toHaveBeenNthCalledWith(2, {
+ type: 'component',
+ id: 'task-compose',
+ params: { composerContext: { key: 'second' } },
+ });
+});
+
+it('lets explicit creation defaults override or suppress the focused preset', () => {
+ const Action = () => {
+ useCreateContext().register('pane', () => ({ task: { key: 'focused' } }));
+ const create = useCreateAction();
+ return (
+ <>
+ <button
+ onClick={() =>
+ create('task', { context: { task: { key: 'explicit' } } })
+ }
+ >
+ Explicit
+ </button>
+ <button onClick={() => create('task', { context: { task: null } })}>
+ Standard
+ </button>
+ </>
+ );
+ };
+ const view = render(() => (
+ <CreateContextProvider focusedPaneId={() => 'pane'}>
+ <Action />
+ </CreateContextProvider>
+ ));
+ fireEvent.click(view.getByText('Explicit'));
+ expect(host.popoverSplit).toHaveBeenLastCalledWith({
+ type: 'component',
+ id: 'task-compose',
+ params: { composerContext: { key: 'explicit' } },
+ });
+ fireEvent.click(view.getByText('Standard'));
+ expect(host.popoverSplit).toHaveBeenLastCalledWith({
+ type: 'component',
+ id: 'task-compose',
+ params: { composerContext: undefined },
+ });
+});
diff --git a/apps/web/src/features/command/Launcher.tsx b/apps/web/src/features/command/Launcher.tsx
index 0558ec2abb..6b705c4968 100644
--- a/apps/web/src/features/command/Launcher.tsx
+++ b/apps/web/src/features/command/Launcher.tsx
@@ -84,6 +84,10 @@ import {
} from 'solid-js';
import { createStore } from 'solid-js/store';
import { Dynamic } from 'solid-js/web';
+import {
+ type PaneCreateContext,
+ useCreateContext,
+} from './context/create-context';
import type { CreateMenuSection } from './core/create-menu-details';
import {
launcherItemKey,
@@ -224,7 +228,6 @@ const createBlock = async (spec: {
const reportCreateBlockError = (error: unknown) =>
Telemetry.error(error, { surface: 'launcher' });
-
const createComponent = (spec: {
componentId: string;
shouldInsert?: boolean;
@@ -265,6 +268,8 @@ export function runCreateAction(
destination?: string;
/** Creatables that open a composer instead ignore it. */
openCreated?: OpenCreatedItem;
+ /** Plain defaults supplied by the caller, never resolved from global state. */
+ context?: PaneCreateContext;
} = {}
) {
const shouldInsert = options.shouldInsert ?? false;
@@ -374,6 +379,7 @@ export function runCreateAction(
createComponent({
componentId: 'task-compose',
asPopover: true,
+ params: { composerContext: options.context?.task ?? undefined },
});
return;
case 'initiative':
@@ -559,9 +565,22 @@ export function runCreateAction(
}
}
+/** Capture the provider during setup; snapshot only when the action runs. */
+export function useCreateAction(): typeof runCreateAction {
+ const context = useCreateContext();
+ return (name, options = {}) =>
+ runCreateAction(name, {
+ ...options,
+ context:
+ options.context ??
+ (name === 'task' ? { task: context.snapshot('task') } : undefined),
+ });
+}
export type { CreatableBlock, CreatableName } from './types';
-export const CREATABLE_BLOCKS: CreatableBlock[] = [
+const createBlocks = (
+ createAction: typeof runCreateAction
+): CreatableBlock[] => [
{
label: 'Email',
icon: getIconConfig('email').icon,
@@ -572,7 +591,7 @@ export const CREATABLE_BLOCKS: CreatableBlock[] = [
altHotkeyToken: TOKENS.create.emailNewSplit,
hotkey: 'e',
keyDownHandler: () => {
- runCreateAction('email', { shouldInsert: pressedKeys().has('shift') });
+ createAction('email', { shouldInsert: pressedKeys().has('shift') });
return true;
},
},
@@ -595,7 +614,7 @@ export const CREATABLE_BLOCKS: CreatableBlock[] = [
registrationType: 'add',
enabled: () => !isFeatureEnabled(enableChatV3Agents),
keyDownHandler: () => {
- runCreateAction('chat', { shouldInsert: pressedKeys().has('shift') });
+ createAction('chat', { shouldInsert: pressedKeys().has('shift') });
return true;
},
},
@@ -609,7 +628,7 @@ export const CREATABLE_BLOCKS: CreatableBlock[] = [
hotkeyToken: TOKENS.create.routine,
hotkey: 'u',
keyDownHandler: () => {
- runCreateAction('routine');
+ createAction('routine');
return true;
},
},
@@ -626,7 +645,7 @@ export const CREATABLE_BLOCKS: CreatableBlock[] = [
registrationType: 'add',
enabled: () => isFeatureEnabled(enableChatV3Agents),
keyDownHandler: () => {
- runCreateAction('agent', { shouldInsert: pressedKeys().has('shift') });
+ createAction('agent', { shouldInsert: pressedKeys().has('shift') });
return true;
},
},
@@ -642,7 +661,7 @@ export const CREATABLE_BLOCKS: CreatableBlock[] = [
altHotkeyToken: TOKENS.create.databaseNewSplit,
hotkey: 'l',
keyDownHandler: () => {
- runCreateAction('database', { shouldInsert: pressedKeys().has('shift') });
+ createAction('database', { shouldInsert: pressedKeys().has('shift') });
return true;
},
},
@@ -658,7 +677,7 @@ export const CREATABLE_BLOCKS: CreatableBlock[] = [
altHotkeyToken: TOKENS.create.formNewSplit,
hotkey: 'q',
keyDownHandler: () => {
- runCreateAction('form', { shouldInsert: pressedKeys().has('shift') });
+ createAction('form', { shouldInsert: pressedKeys().has('shift') });
return true;
},
},
@@ -672,7 +691,7 @@ export const CREATABLE_BLOCKS: CreatableBlock[] = [
hotkeyToken: TOKENS.create.skill,
hotkey: 'k',
keyDownHandler: () => {
- runCreateAction('skill');
+ createAction('skill');
return true;
},
},
@@ -686,7 +705,7 @@ export const CREATABLE_BLOCKS: CreatableBlock[] = [
altHotkeyToken: TOKENS.create.noteNewSplit,
hotkey: 'd',
keyDownHandler: () => {
- runCreateAction('md', { shouldInsert: pressedKeys().has('shift') });
+ createAction('md', { shouldInsert: pressedKeys().has('shift') });
return true;
},
},
@@ -700,7 +719,7 @@ export const CREATABLE_BLOCKS: CreatableBlock[] = [
altHotkeyToken: TOKENS.create.taskNewSplit,
hotkey: 't' as const,
keyDownHandler: () => {
- runCreateAction('task');
+ createAction('task');
return true;
},
},
@@ -714,7 +733,7 @@ export const CREATABLE_BLOCKS: CreatableBlock[] = [
hotkeyToken: TOKENS.create.initiative,
hotkey: 'p',
keyDownHandler: () => {
- runCreateAction('initiative');
+ createAction('initiative');
return true;
},
},
@@ -729,7 +748,7 @@ export const CREATABLE_BLOCKS: CreatableBlock[] = [
altHotkeyToken: TOKENS.create.snippetNewSplit,
hotkey: 's' as const,
keyDownHandler: () => {
- runCreateAction('snippet', { shouldInsert: pressedKeys().has('shift') });
+ createAction('snippet', { shouldInsert: pressedKeys().has('shift') });
return true;
},
},
@@ -744,7 +763,7 @@ export const CREATABLE_BLOCKS: CreatableBlock[] = [
altHotkeyToken: TOKENS.create.messageNewSplit,
hotkey: 'm',
keyDownHandler: () => {
- runCreateAction('channel', { shouldInsert: pressedKeys().has('shift') });
+ createAction('channel', { shouldInsert: pressedKeys().has('shift') });
return true;
},
},
@@ -773,7 +792,7 @@ export const CREATABLE_BLOCKS: CreatableBlock[] = [
altHotkeyToken: TOKENS.create.canvasNewSplit,
hotkey: 'n',
keyDownHandler: () => {
- runCreateAction('canvas', {
+ createAction('canvas', {
shouldInsert: pressedKeys().has('shift'),
});
return true;
@@ -791,7 +810,7 @@ export const CREATABLE_BLOCKS: CreatableBlock[] = [
altHotkeyToken: TOKENS.create.photoshopNewSplit,
hotkey: 'h',
keyDownHandler: () => {
- runCreateAction('psd', { shouldInsert: pressedKeys().has('shift') });
+ createAction('psd', { shouldInsert: pressedKeys().has('shift') });
return true;
},
},
@@ -807,7 +826,7 @@ export const CREATABLE_BLOCKS: CreatableBlock[] = [
altHotkeyToken: TOKENS.create.designNewSplit,
hotkey: 'i',
keyDownHandler: () => {
- runCreateAction('fig', { shouldInsert: pressedKeys().has('shift') });
+ createAction('fig', { shouldInsert: pressedKeys().has('shift') });
return true;
},
},
@@ -831,7 +850,7 @@ export const CREATABLE_BLOCKS: CreatableBlock[] = [
altHotkeyToken: TOKENS.create.illustrationNewSplit,
hotkey: 'v',
keyDownHandler: () => {
- runCreateAction('ai', { shouldInsert: pressedKeys().has('shift') });
+ createAction('ai', { shouldInsert: pressedKeys().has('shift') });
return true;
},
},
@@ -847,7 +866,7 @@ export const CREATABLE_BLOCKS: CreatableBlock[] = [
altHotkeyToken: TOKENS.create.spreadsheetNewSplit,
hotkey: 'b',
keyDownHandler: () => {
- runCreateAction('spreadsheet', {
+ createAction('spreadsheet', {
shouldInsert: pressedKeys().has('shift'),
});
return true;
@@ -863,7 +882,7 @@ export const CREATABLE_BLOCKS: CreatableBlock[] = [
altHotkeyToken: TOKENS.create.projectNewSplit,
hotkey: 'f',
keyDownHandler: () => {
- runCreateAction('project', { shouldInsert: pressedKeys().has('shift') });
+ createAction('project', { shouldInsert: pressedKeys().has('shift') });
return true;
},
},
@@ -877,18 +896,20 @@ export const CREATABLE_BLOCKS: CreatableBlock[] = [
altHotkeyToken: TOKENS.create.codeNewSplit,
hotkey: 'o',
keyDownHandler: () => {
- runCreateAction('code', { shouldInsert: pressedKeys().has('shift') });
+ createAction('code', { shouldInsert: pressedKeys().has('shift') });
return true;
},
},
];
+export const CREATABLE_BLOCKS = createBlocks(runCreateAction);
+
/** Router-backed commands are bound once in each host's component owner. */
export function useCreateCommands(): CreatableBlock[] {
const navigate = useNavigate();
const quickCalls = useQuickCallsFlag();
return [
- ...CREATABLE_BLOCKS,
+ ...createBlocks(useCreateAction()),
createCallCommand({
navigate,
close: () => setCreateMenuOpen(false, false),
diff --git a/apps/web/src/features/command/context/create-context.tsx b/apps/web/src/features/command/context/create-context.tsx
new file mode 100644
index 0000000000..2371fd2b4d
--- /dev/null
+++ b/apps/web/src/features/command/context/create-context.tsx
@@ -0,0 +1,89 @@
+import type { TaskComposerContext } from '@app/features/task-composer/core/context';
+import {
+ type Accessor,
+ createContext,
+ createSignal,
+ type ParentProps,
+ untrack,
+ useContext,
+} from 'solid-js';
+
+/** Each create action owns its plain, cloneable defaults. */
+export type CreateContextByAction = {
+ task: TaskComposerContext;
+};
+
+/** Omitted actions inherit; null explicitly clears an inherited preset. */
+export type PaneCreateContext = {
+ [Action in keyof CreateContextByAction]?:
+ | CreateContextByAction[Action]
+ | null;
+};
+
+type CreateContext = {
+ register: (paneId: string, source: Accessor<PaneCreateContext>) => () => void;
+ read: <Action extends keyof CreateContextByAction>(
+ action: Action,
+ paneId?: string
+ ) => CreateContextByAction[Action] | undefined;
+ snapshot: <Action extends keyof CreateContextByAction>(
+ action: Action,
+ paneId?: string
+ ) => CreateContextByAction[Action] | undefined;
+};
+
+type Registration = {
+ paneId: string;
+ source: Accessor<PaneCreateContext>;
+};
+
+const CreateContext = createContext<CreateContext>();
+
+/** Own registrations locally; the host supplies its existing focus accessor. */
+export function CreateContextProvider(
+ props: ParentProps<{ focusedPaneId: Accessor<string | undefined> }>
+) {
+ const [registrations, setRegistrations] = createSignal<Registration[]>([]);
+
+ const context: CreateContext = {
+ register(paneId, source) {
+ const registration = { paneId, source };
+ setRegistrations((entries) => [...entries, registration]);
+ return () => {
+ setRegistrations((entries) =>
+ entries.filter((entry) => entry !== registration)
+ );
+ };
+ },
+ read(action, paneId) {
+ const id = paneId ?? props.focusedPaneId();
+ if (id === undefined) return;
+ const entries = registrations();
+ for (let index = entries.length - 1; index >= 0; index--) {
+ const entry = entries[index];
+ if (entry.paneId !== id) continue;
+ const value = entry.source()[action];
+ if (value !== undefined) return value ?? undefined;
+ }
+ },
+ snapshot(action, paneId) {
+ return untrack(() => {
+ const value = context.read(action, paneId);
+ return value === undefined ? undefined : structuredClone(value);
+ });
+ },
+ };
+
+ return (
+ <CreateContext.Provider value={context}>
+ {props.children}
+ </CreateContext.Provider>
+ );
+}
+
+export function useCreateContext(): CreateContext {
+ const context = useContext(CreateContext);
+ if (!context)
+ throw new Error('useCreateContext requires CreateContextProvider');
+ return context;
+}
diff --git a/apps/web/src/features/crm/README.md b/apps/web/src/features/crm/README.md
index db2a603fdb..c88677b26d 100644
--- a/apps/web/src/features/crm/README.md
+++ b/apps/web/src/features/crm/README.md
@@ -32,6 +32,8 @@ The root adapters construct production dependencies. `context` defines the
capabilities; it does not import their implementations. Views consume these
capabilities, primitives receive narrow inputs, and components render props.
Core modules remain independent of Solid, service clients, and app state.
+UI rollout gates read `useFeatureFlag` directly where used; do not pass rollout
+booleans through component props or the CRM source contract.
Shared entity representations, transport clients, property editors, and
collection mechanics remain shared. CRM owns its record queries and cache updates.
@@ -39,6 +41,43 @@ CRM supplies row/header/empty state slots, filter choices, grouping policy, and
its own collection state to the shared collection renderer. Shared collection code must not acquire CRM hooks or
CRM-specific state again.
+`task-composer.ts` owns the CRM task preset: Companies/Contacts are visible,
+Status remains a task default but is not initially shown. CRM registers live
+`{ task: TaskComposerContext }` values with the provider in
+`command/context/create-context.tsx`, scoped to its pane. The app shell owns the
+provider and supplies the layout's focus accessor; no global registry or manager
+key is involved. The workspace registers the unassociated preset; nested record
+getters override it and include already-loaded associations. Teardown restores
+the parent getter. Omitted action entries inherit; `task: null` explicitly
+suppresses a parent preset when CRM's rollout is disabled.
+The selected-record fallback survives detail query errors until the record closes.
+Global task creation snapshots the focused pane's getter before opening, without
+fetching details or capturing navigation history. Record contexts isolate drafts.
+
+`enable-crm-activity` gates workspace activity tabs and whether CRM supplies its
+composer context. It defaults off everywhere and can be overridden locally with
+`VITE_ENABLE_CRM_ACTIVITY=true`. Off hides activity navigation and skips activity
+queries; saved activity links wait for flag loading, then fall back to Companies.
+The standard record task action still associates the task with its record.
+The shared composer, registry and launcher never read this flag. With no supplied
+context, the standard composer opens immediately. Each opening snapshots its
+context; later flag, focus or record changes leave the open draft unchanged.
+The Soup and email SQL optimizations are independent of this frontend gate.
+
+The workspace activity feeds are CRM-linked, not unfiltered app shortcuts.
+`queries/activity.ts` loads all authorized companies and contacts before
+building the feed filters; the capped Quick Access suggestions are not a
+complete scope. Notes means Markdown documents excluding task, snippet, and
+skill subtypes. Email uses the viewer's mailbox, without team-scope widening.
+This reuses existing endpoints without a schema change. Keep the scope complete:
+never cap association IDs or fall back to an unfiltered feed. The activity query
+memoizes its large filter AST between scope/tab changes. SQL generation batches
+OR-ed references into set-membership predicates rather than emitting thousands
+of separate subqueries. Email similarly batches participant lists with identical
+sender/recipient roles in both candidate and message queries, and omits exact
+addresses already covered by a company domain. These backend optimizations must
+be deployed to resolve large-scope request stalls.
+
When changing behavior, test the responsible primitive or pure function. When
moving behavior, retain query keys, persistence keys, mutation ordering, loading
boundaries, routes, and markup. Run CRM tests plus affected shared collection and
diff --git a/apps/web/src/features/crm/architecture.test.ts b/apps/web/src/features/crm/architecture.test.ts
index 91bb4a62fd..c9b5640b15 100644
--- a/apps/web/src/features/crm/architecture.test.ts
+++ b/apps/web/src/features/crm/architecture.test.ts
@@ -57,6 +57,8 @@ describe('CRM ownership boundaries', () => {
/^(?:@queries\/|@service-|@core\/context\/|@app\/lib\/analytics)/.test(
path
);
+ // UI rollout gates read flags directly rather than threading boolean props.
+ const uiFlagReader = path === '@app/lib/analytics/posthog';
const rootAdapter =
target && !target.includes('/') && /adapter|^crm(?:-|$)/.test(target);
const otherLayer = target?.split('/')[0];
@@ -71,9 +73,11 @@ describe('CRM ownership boundaries', () => {
rootAdapter ||
['queries', 'views', 'components'].includes(otherLayer ?? '')
: layer === 'views'
- ? concrete || rootAdapter || otherLayer === 'queries'
+ ? (concrete && !uiFlagReader) ||
+ rootAdapter ||
+ otherLayer === 'queries'
: layer === 'components'
- ? concrete ||
+ ? (concrete && !uiFlagReader) ||
rootAdapter ||
['queries', 'views', 'primitives'].includes(
otherLayer ?? ''
diff --git a/apps/web/src/features/crm/browser-test/mobile-insets.browser.e2e.ts b/apps/web/src/features/crm/browser-test/mobile-insets.browser.e2e.ts
index 6b4da9ef66..8bef60a4ef 100644
--- a/apps/web/src/features/crm/browser-test/mobile-insets.browser.e2e.ts
+++ b/apps/web/src/features/crm/browser-test/mobile-insets.browser.e2e.ts
@@ -75,7 +75,7 @@ for (const device of [
name: 'People',
exact: true,
});
- await expect(button).toBeVisible();
+ await expect(button).toBeVisible({ timeout: 30000 });
const box = await button.boundingBox();
const top = device.hasTouch ? (surface === 'reviews' ? 100 : 55) : 16;
expect(box!.y).toBeGreaterThanOrEqual(top);
diff --git a/apps/web/src/features/crm/browser-test/mobile-insets.tsx b/apps/web/src/features/crm/browser-test/mobile-insets.tsx
index 0d7b2b5859..e7d484f0e3 100644
--- a/apps/web/src/features/crm/browser-test/mobile-insets.tsx
+++ b/apps/web/src/features/crm/browser-test/mobile-insets.tsx
@@ -1,6 +1,8 @@
import '@app/index.css';
import { EntityDetailTopBar } from '@app/components/entity-detail/EntityDetailTopBar';
import { ViewBreadcrumbs, ViewShell } from '@app/components/view-shell';
+import { AnalyticsContextProvider } from '@app/lib/analytics/analytics-context';
+import { PosthogProvider } from '@app/lib/analytics/posthog';
import { SidePanel } from '@components/app/side-panel';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { Button } from '@ui';
@@ -100,4 +102,14 @@ function Fixture() {
);
}
const root = document.getElementById('root');
-if (root) render(() => <Fixture />, root);
+if (root)
+ render(
+ () => (
+ <AnalyticsContextProvider>
+ <PosthogProvider>
+ <Fixture />
+ </PosthogProvider>
+ </AnalyticsContextProvider>
+ ),
+ root
+ );
diff --git a/apps/web/src/features/crm/components/crm-mobile-tabs.tsx b/apps/web/src/features/crm/components/crm-mobile-tabs.tsx
index c0404ec5bc..0006fff6a0 100644
--- a/apps/web/src/features/crm/components/crm-mobile-tabs.tsx
+++ b/apps/web/src/features/crm/components/crm-mobile-tabs.tsx
@@ -1,6 +1,12 @@
+import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { type PillTabItem, PillTabs } from '@components/app/mobile/PillTabs';
+import { enableCrmActivity } from '@core/constant/featureFlags';
import type { JSX } from 'solid-js';
-import { CRM_RECORDS, pipelineTab } from '../core/navigation';
+import {
+ CRM_ACTIVITY_TABS,
+ CRM_RECORDS,
+ pipelineTab,
+} from '../core/navigation';
export function CrmMobileTabs(props: {
active: string;
@@ -9,8 +15,12 @@ export function CrmMobileTabs(props: {
leading?: JSX.Element;
onNavigate(id: string): void;
}) {
+ const activityFlag = useFeatureFlag(enableCrmActivity);
const items = (): PillTabItem[] => [
- ...CRM_RECORDS.map((record) => ({
+ ...[
+ ...CRM_RECORDS,
+ ...(activityFlag().enabled ? CRM_ACTIVITY_TABS : []),
+ ].map((record) => ({
value: record.id,
label: record.label,
})),
diff --git a/apps/web/src/features/crm/components/crm-sidebar.test.tsx b/apps/web/src/features/crm/components/crm-sidebar.test.tsx
index 356e93e0d2..0eadc24fc5 100644
--- a/apps/web/src/features/crm/components/crm-sidebar.test.tsx
+++ b/apps/web/src/features/crm/components/crm-sidebar.test.tsx
@@ -3,6 +3,9 @@ import { cleanup, fireEvent, render, screen } from '@solidjs/testing-library';
import { afterEach, expect, it, vi } from 'vitest';
import { CrmSidebar } from './crm-sidebar';
+vi.mock('@app/lib/analytics/posthog', () => ({
+ useFeatureFlag: () => () => ({ enabled: false, loading: false }),
+}));
vi.mock('@core/mobile/isTouchDevice', () => ({ isTouchDevice: () => false }));
vi.mock('@solid-primitives/resize-observer', () => ({
createResizeObserver: () => {},
diff --git a/apps/web/src/features/crm/components/crm-sidebar.tsx b/apps/web/src/features/crm/components/crm-sidebar.tsx
index 782096c7f5..55683c55d9 100644
--- a/apps/web/src/features/crm/components/crm-sidebar.tsx
+++ b/apps/web/src/features/crm/components/crm-sidebar.tsx
@@ -1,4 +1,7 @@
import { CollapsibleSection, ViewSidebar } from '@app/components/view-shell';
+import { useFeatureFlag } from '@app/lib/analytics/posthog';
+import { getIconConfig } from '@core/component/EntityIcon';
+import { enableCrmActivity } from '@core/constant/featureFlags';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import BuildingsIcon from '@phosphor/buildings.svg';
import ExportIcon from '@phosphor/download-simple.svg';
@@ -12,11 +15,18 @@ import { Button, Tooltip } from '@ui';
import { tourTarget } from '@ui/components/Tour';
import { createSignal, For, type JSX, Show } from 'solid-js';
import { Dynamic } from 'solid-js/web';
-import { CRM_RECORDS } from '../core/navigation';
+import { CRM_ACTIVITY_TABS, CRM_RECORDS } from '../core/navigation';
import { COMPANIES_TOUR } from '../tour';
import { CrmCreateMenu } from './crm-create-menu';
-const RECORD_ICONS = { active: BuildingsIcon, people: UsersIcon };
+const RECORD_ICONS = {
+ active: BuildingsIcon,
+ people: UsersIcon,
+ tasks: getIconConfig('task').icon,
+ email: getIconConfig('email').icon,
+ notes: getIconConfig('md').icon,
+ calls: getIconConfig('call').icon,
+};
export function CrmSidebar(props: {
/** The highlighted record type, list, pipeline, or `settings`. */
@@ -42,6 +52,7 @@ export function CrmSidebar(props: {
*/
onCollapse?: () => void;
}) {
+ const activityFlag = useFeatureFlag(enableCrmActivity);
const [recordsOpen, setRecordsOpen] = createSignal(true);
const [listsOpen, setListsOpen] = createSignal(true);
return (
@@ -91,7 +102,12 @@ export function CrmSidebar(props: {
aria-label="CRM records"
ref={tourTarget(COMPANIES_TOUR.records)}
>
- <For each={CRM_RECORDS}>
+ <For
+ each={[
+ ...CRM_RECORDS,
+ ...(activityFlag().enabled ? CRM_ACTIVITY_TABS : []),
+ ]}
+ >
{(record) => (
<ViewSidebar.Item
active={props.active === record.id}
diff --git a/apps/web/src/features/crm/components/record-tabs.tsx b/apps/web/src/features/crm/components/record-tabs.tsx
index bd5dfe51e8..02dc542241 100644
--- a/apps/web/src/features/crm/components/record-tabs.tsx
+++ b/apps/web/src/features/crm/components/record-tabs.tsx
@@ -1,8 +1,5 @@
+import { getIconConfig } from '@core/component/EntityIcon';
import { TabsInset } from '@core/component/TabsInset';
-import CheckSquareIcon from '@phosphor/check-square.svg';
-import EnvelopeIcon from '@phosphor/envelope.svg';
-import FilesIcon from '@phosphor/files.svg';
-import PhoneIcon from '@phosphor/phone.svg';
import SquaresFourIcon from '@phosphor/squares-four.svg';
import UsersIcon from '@phosphor/users.svg';
import type { Component, JSX } from 'solid-js';
@@ -17,10 +14,10 @@ const SECTION_ICONS: Record<
> = {
overview: SquaresFourIcon,
team: UsersIcon,
- emails: EnvelopeIcon,
- files: FilesIcon,
- tasks: CheckSquareIcon,
- calls: PhoneIcon,
+ emails: getIconConfig('email').icon,
+ files: getIconConfig('files').icon,
+ tasks: getIconConfig('task').icon,
+ calls: getIconConfig('call').icon,
};
/**
diff --git a/apps/web/src/features/crm/context/crm-context.tsx b/apps/web/src/features/crm/context/crm-context.tsx
index 067483b207..ce547a1cf1 100644
--- a/apps/web/src/features/crm/context/crm-context.tsx
+++ b/apps/web/src/features/crm/context/crm-context.tsx
@@ -9,8 +9,9 @@ import type {
CrmDisplayOptions,
CrmListColumnId,
} from '../core/display-options';
+import type { CrmActivityTab } from '../core/navigation';
import type { Pipeline } from '../core/pipeline';
-import type { CrmRecordScope } from '../core/record';
+import type { CrmRecordScope, CrmTaskRecord } from '../core/record';
import type {
CompanyImporter,
CompanySource,
@@ -80,6 +81,13 @@ export type CrmContext = {
scope: Accessor<CrmEmailScope>,
signal: Accessor<CrmEmailSignal>
): ItemListSource;
+ /** Paged CRM-wide activity, limited to associated records. */
+ createActivity(tab: Accessor<CrmActivityTab>): ItemListSource;
+ openTaskComposer(): void;
+ /** Newest mounted record source wins; cleanup restores the parent record source. */
+ registerTaskComposerRecord(
+ source: Accessor<CrmTaskRecord | undefined>
+ ): () => void;
/** Files associated with the record or attached to its emails. */
createRecordFiles(
scope: Accessor<CrmRecordScope | undefined>
diff --git a/apps/web/src/features/crm/core/navigation.ts b/apps/web/src/features/crm/core/navigation.ts
index fc27dd1ea9..a1d9a5c858 100644
--- a/apps/web/src/features/crm/core/navigation.ts
+++ b/apps/web/src/features/crm/core/navigation.ts
@@ -4,6 +4,19 @@ export const CRM_RECORDS = [
{ id: 'people', label: 'People' },
] as const;
+/** Workspace feeds scoped to CRM-linked content, rather than one record. */
+export const CRM_ACTIVITY_TABS = [
+ { id: 'tasks', label: 'Tasks' },
+ { id: 'email', label: 'Email' },
+ { id: 'notes', label: 'Notes' },
+ { id: 'calls', label: 'Calls' },
+] as const;
+
+export type CrmActivityTab = (typeof CRM_ACTIVITY_TABS)[number]['id'];
+
+export function isCrmActivityTab(value: string): value is CrmActivityTab {
+ return CRM_ACTIVITY_TABS.some((tab) => tab.id === value);
+}
const PIPELINE_TAB_PREFIX = 'pipeline:';
/** The workspace tab that shows a pipeline. */
diff --git a/apps/web/src/features/crm/core/record.ts b/apps/web/src/features/crm/core/record.ts
index b313e921fd..2f5694dbbe 100644
--- a/apps/web/src/features/crm/core/record.ts
+++ b/apps/web/src/features/crm/core/record.ts
@@ -1,3 +1,9 @@
+/** Identity of a company or contact, independent of its loaded details. */
+export type CrmRecordTarget = { type: 'company' | 'contact'; id: string };
+/** Record identity and already-loaded associations for a new task. */
+export type CrmTaskRecord =
+ | { type: 'company'; id: string }
+ | { type: 'contact'; id: string; companyId?: string };
/** A CRM record whose associated files, tasks and calls a record tab lists. */
export type CrmRecordScope =
| { type: 'company'; id: string; domains: string[] }
diff --git a/apps/web/src/features/crm/crm-adapter.ts b/apps/web/src/features/crm/crm-adapter.ts
index d5723f1bf1..cff3050a0e 100644
--- a/apps/web/src/features/crm/crm-adapter.ts
+++ b/apps/web/src/features/crm/crm-adapter.ts
@@ -1,9 +1,13 @@
+import { useCreateContext } from '@app/features/command/context/create-context';
import { useQuickAccessCrmCompaniesQuery } from '@app/features/crm/crm-search';
import { withEntityNotifications } from '@app/features/soup/entity-notifications';
import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { useGlobalNotificationSource } from '@components/app/GlobalAppState';
+import { useSplitLayout } from '@components/app/split-layout/layout';
+import { useSplitPanel } from '@components/app/split-layout/layoutUtils';
import { toast } from '@core/component/Toast/Toast';
import {
+ enableCrmActivity,
enableCrmLists,
enableCrmPipelines,
} from '@core/constant/featureFlags';
@@ -46,6 +50,7 @@ import {
import { PipelineDatabaseEditor, PipelineShare } from './pipeline-adapter';
import { createCrmPipelineEntries } from './pipeline-entries-adapter';
import { createCrmPermissions } from './primitives/team-config';
+import { useCrmActivityQuery } from './queries/activity';
import {
createCompanyImporter,
useCompanyQuery,
@@ -81,6 +86,7 @@ import {
import { useTeamCrmConfig } from './queries/team-config';
import { useQuickAccessCrmContactsQuery } from './record-adapter';
import { createAppDealStages } from './stage-adapter';
+import { crmTaskComposerContext } from './task-composer';
// Loaded on demand: the Tasks list imports soup, which imports CRM entry points.
const CrmRecordTasks = lazy(async () => ({
@@ -166,8 +172,18 @@ export function createAppCrmContext(): CrmContext {
feedback: toast,
};
const userId = useUserId();
+ const layout = useSplitLayout();
+ const panel = useSplitPanel();
+ const createContext = useCreateContext();
+ const activityFlag = useFeatureFlag(enableCrmActivity);
const createSettings = () => useTeamCrmConfig(deps);
return {
+ registerTaskComposerRecord(source) {
+ if (!panel) return () => {};
+ return createContext.register(panel.handle.id, () => ({
+ task: activityFlag().enabled ? crmTaskComposerContext(source()) : null,
+ }));
+ },
createPipelines: (teamId) => createPipelinesSource(deps, teamId),
PipelineEditor: PipelineDatabaseEditor,
PipelineEntries: createCrmPipelineEntries({
@@ -203,6 +219,20 @@ export function createAppCrmContext(): CrmContext {
withRowNotifications(
useContactEmailsQuery(useSoupAstItemsQuery, ...args)
),
+ createActivity: (tab) =>
+ withRowNotifications(
+ useCrmActivityQuery(deps, useSoupAstItemsQuery, tab, userId)
+ ),
+ openTaskComposer: () =>
+ layout.popoverSplit({
+ type: 'component',
+ id: 'task-compose',
+ params: {
+ composerContext: panel
+ ? createContext.snapshot('task', panel.handle.id)
+ : undefined,
+ },
+ }),
createRecordFiles: (scope) =>
withRowNotifications(useRecordFilesQuery(useSoupAstItemsQuery, scope)),
createRecordCalls: (scope) =>
diff --git a/apps/web/src/features/crm/crm-route.test.ts b/apps/web/src/features/crm/crm-route.test.ts
index ba2cc21e90..617644461d 100644
--- a/apps/web/src/features/crm/crm-route.test.ts
+++ b/apps/web/src/features/crm/crm-route.test.ts
@@ -74,21 +74,28 @@ const leafOf = (path: string) => {
};
describe('crm tab search params', () => {
- it.each(['active', 'people', 'hidden', 'list:favorites'])(
- 'keeps the %s tab through the URL',
- (tab) => {
- const params = crmSearchCodec.serialize({ tab });
- if (tab === 'active') {
- expect(params).toBeUndefined();
- } else {
- expect(params).toEqual({ tab: [tab] });
- }
- expect(crmSearchCodec.parse(params)).toEqual({
- value: { tab },
- valid: true,
- });
+ it.each([
+ 'active',
+ 'people',
+ 'tasks',
+ 'email',
+ 'notes',
+ 'calls',
+ 'hidden',
+ pipelineTab(pipelineId),
+ 'list:favorites',
+ ])('keeps the %s tab through the URL', (tab) => {
+ const params = crmSearchCodec.serialize({ tab });
+ if (tab === 'active') {
+ expect(params).toBeUndefined();
+ } else {
+ expect(params).toEqual({ tab: [tab] });
}
- );
+ expect(crmSearchCodec.parse(params)).toEqual({
+ value: { tab },
+ valid: true,
+ });
+ });
});
describe('record and pipeline URLs', () => {
diff --git a/apps/web/src/features/crm/crm.tsx b/apps/web/src/features/crm/crm.tsx
index a123772e58..d6a08c15fa 100644
--- a/apps/web/src/features/crm/crm.tsx
+++ b/apps/web/src/features/crm/crm.tsx
@@ -1,4 +1,4 @@
-import { Show } from 'solid-js';
+import { onCleanup, Show } from 'solid-js';
import { SoupViewStateProvider } from '../next-soup/soup-view/soup-view-context';
import { ViewTour } from '../tours/ViewTour';
import { CrmProvider } from './context/crm-context';
@@ -15,6 +15,7 @@ import { createCrmWorkspace } from './workspace-adapter';
export function Crm(props: { initialView?: CrmViewConfig; route: CrmRoute }) {
const crm = createAppCrmContext();
+ onCleanup(crm.registerTaskComposerRecord(() => undefined));
const workspace = createCrmWorkspace(crm, props.route, props.initialView);
return (
<CrmProvider value={crm}>
diff --git a/apps/web/src/features/crm/queries/activity-filter.ts b/apps/web/src/features/crm/queries/activity-filter.ts
new file mode 100644
index 0000000000..777e999ad1
--- /dev/null
+++ b/apps/web/src/features/crm/queries/activity-filter.ts
@@ -0,0 +1,79 @@
+import { SYSTEM_PROPERTY_IDS } from '@property/identifiers';
+import { NIL_UUID } from '../../next-soup/filters/filter-store';
+import type { CrmActivityTab } from '../core/navigation';
+import { emailFilterForAddress, emailFilterForDomains } from './email-filter';
+
+export type CrmActivityScope = {
+ companyIds: string[];
+ contactIds: string[];
+ domains: string[];
+ emails: string[];
+};
+
+type AstNode = Record<string, unknown>;
+const leaf = (value: AstNode): AstNode => ({ l: value });
+export const NO_CRM_ACTIVITY = {
+ calf: leaf({ id: NIL_UUID }),
+ df: leaf({ id: NIL_UUID }),
+ chanf: leaf({ ChannelId: NIL_UUID }),
+ cthf: leaf({ ThreadId: NIL_UUID }),
+ cf: leaf({ cid: NIL_UUID }),
+ pf: leaf({ pid: NIL_UUID }),
+ callf: leaf({ CallId: NIL_UUID }),
+ ccf: leaf({ id: NIL_UUID }),
+ fef: leaf({ id: NIL_UUID }),
+ ef: leaf({ ThreadId: NIL_UUID }),
+};
+
+// A balanced expression avoids excessive recursion for large CRMs.
+function anyOf(nodes: unknown[]): unknown {
+ if (nodes.length === 0) return undefined;
+ if (nodes.length === 1) return nodes[0];
+ const middle = Math.floor(nodes.length / 2);
+ return { '|': [anyOf(nodes.slice(0, middle)), anyOf(nodes.slice(middle))] };
+}
+
+/** Never use an omitted scope as an unfiltered query. */
+export function crmActivityBody(tab: CrmActivityTab, scope: CrmActivityScope) {
+ if (tab === 'email') {
+ const emails = anyOf(
+ [
+ ...scope.domains.map((domain) => emailFilterForDomains([domain])),
+ ...scope.emails.map(emailFilterForAddress),
+ ].filter((value) => value !== undefined)
+ );
+ return emails
+ ? { ...NO_CRM_ACTIVITY, ef: emails, emailView: 'all' }
+ : NO_CRM_ACTIVITY;
+ }
+ const associations = anyOf([
+ ...scope.companyIds.map((id) =>
+ leaf({ pd: SYSTEM_PROPERTY_IDS.COMPANIES, v: { er: id } })
+ ),
+ ...scope.contactIds.map((id) =>
+ leaf({ pd: SYSTEM_PROPERTY_IDS.CONTACTS, v: { er: id } })
+ ),
+ ]);
+ if (!associations) return NO_CRM_ACTIVITY;
+ if (tab === 'calls') {
+ const { callf: _calls, ...others } = NO_CRM_ACTIVITY;
+ return { ...others, propf: associations };
+ }
+ return {
+ ...NO_CRM_ACTIVITY,
+ propf: associations,
+ df:
+ tab === 'tasks'
+ ? leaf({ dst: 'task' })
+ : {
+ '&': [
+ leaf({ ft: 'md' }),
+ {
+ '!': anyOf(
+ ['task', 'snippet', 'skill'].map((dst) => leaf({ dst }))
+ ),
+ },
+ ],
+ },
+ };
+}
diff --git a/apps/web/src/features/crm/queries/activity-scope.ts b/apps/web/src/features/crm/queries/activity-scope.ts
new file mode 100644
index 0000000000..029e586fad
--- /dev/null
+++ b/apps/web/src/features/crm/queries/activity-scope.ts
@@ -0,0 +1,56 @@
+import type { CrmActivityScope } from './activity-filter';
+
+type Company = { id: string; domains: { domain: string }[] };
+type Contact = { id: string; email: string };
+type ContactPage = { contacts: Contact[]; nextCursor: string | null };
+
+/** Read every authorized record before constructing an association filter. */
+export async function loadCrmActivityScope(
+ sources: {
+ companies(): Promise<Company[]>;
+ contacts(cursor: string | null): Promise<ContactPage>;
+ },
+ signal: AbortSignal
+): Promise<CrmActivityScope> {
+ async function contacts() {
+ const records = new Map<string, Contact>();
+ const cursors: string[] = [];
+ let cursor: string | null = null;
+ do {
+ signal.throwIfAborted();
+ const page = await sources.contacts(cursor);
+ signal.throwIfAborted();
+ for (const contact of page.contacts) records.set(contact.id, contact);
+ cursor = page.nextCursor;
+ if (cursor && cursors.includes(cursor)) {
+ throw new Error('CRM pagination did not advance.');
+ }
+ if (cursor) cursors.push(cursor);
+ } while (cursor);
+ return [...records.values()];
+ }
+ const [companies, people] = await Promise.all([
+ sources.companies(),
+ contacts(),
+ ]);
+ signal.throwIfAborted();
+ const domains = [
+ ...new Set(
+ companies.flatMap((company) =>
+ company.domains.map(({ domain }) => domain.toLowerCase())
+ )
+ ),
+ ];
+ const domainSet = new Set(domains);
+ // A domain already matches every contact at that domain in every direction.
+ // Omitting those redundant addresses keeps the email AST much smaller.
+ const emails = [
+ ...new Set(people.map(({ email }) => email.toLowerCase())),
+ ].filter((email) => !domainSet.has(email.slice(email.lastIndexOf('@') + 1)));
+ return {
+ companyIds: companies.map((company) => company.id),
+ contactIds: people.map((contact) => contact.id),
+ domains,
+ emails,
+ };
+}
diff --git a/apps/web/src/features/crm/queries/activity.ts b/apps/web/src/features/crm/queries/activity.ts
new file mode 100644
index 0000000000..5e5f0ae746
--- /dev/null
+++ b/apps/web/src/features/crm/queries/activity.ts
@@ -0,0 +1,90 @@
+import { queryReadyGate } from '@queries/gate';
+import type {
+ SoupAstItemsQuery,
+ useSoupAstItemsQuery,
+} from '@queries/soup/items';
+import { soupKeys } from '@queries/soup/keys';
+import { fetchCrmContacts } from '@service-storage/crm-contacts';
+import { queryOptions, useQuery } from '@tanstack/solid-query';
+import { type Accessor, createMemo, mergeProps } from 'solid-js';
+import type { CrmActivityTab } from '../core/navigation';
+import { crmActivityBody, NO_CRM_ACTIVITY } from './activity-filter';
+import { loadCrmActivityScope } from './activity-scope';
+import type { CrmRecordDependencies } from './dependencies';
+import { fetchCrmExportCompanies } from './export';
+import { crmKeys } from './keys';
+
+function activityScopeOptions(
+ deps: CrmRecordDependencies,
+ userId: string | undefined
+) {
+ return queryOptions({
+ // Company/contact mutations invalidate Soup, so rebuild this scope with it.
+ queryKey: [...soupKeys._def, ...crmKeys.activityScope(userId).queryKey],
+ enabled: !!userId,
+ staleTime: 60_000,
+ queryFn: ({ signal }) =>
+ loadCrmActivityScope(
+ {
+ companies: () =>
+ fetchCrmExportCompanies(deps.storage, signal, () => {}),
+ contacts: (cursor) =>
+ fetchCrmContacts({ cursor, limit: 500, signal }),
+ },
+ signal
+ ),
+ });
+}
+
+/** Load the complete authorized CRM scope, not the capped Quick Access cache. */
+export function useCrmActivityQuery(
+ deps: CrmRecordDependencies,
+ createQuery: typeof useSoupAstItemsQuery,
+ tab: Accessor<CrmActivityTab>,
+ userId: Accessor<string | undefined>
+): SoupAstItemsQuery {
+ const scope = useQuery(
+ () => activityScopeOptions(deps, userId()),
+ () => deps.client
+ );
+ // The scope can contain thousands of records. Build the AST once per scope
+ // or tab change, not on every read by the Soup transport and query observers.
+ const body = createMemo(() =>
+ queryReadyGate(scope) ? crmActivityBody(tab(), scope.data) : NO_CRM_ACTIVITY
+ );
+ const query = createQuery(
+ () => ({
+ params: { limit: 100, sort_method: 'updated_at' },
+ body: body(),
+ }),
+ () => ({ enabled: scope.isSuccess })
+ );
+ return mergeProps(query, {
+ get isPending() {
+ return scope.isPending || query.isPending;
+ },
+ get isEnabled() {
+ return !!userId();
+ },
+ get isLoading() {
+ return scope.isLoading || query.isLoading;
+ },
+ get isFetching() {
+ return scope.isFetching || query.isFetching;
+ },
+ get isFetchNextPageError() {
+ return !scope.error && query.isFetchNextPageError;
+ },
+ get error() {
+ return scope.error ?? query.error;
+ },
+ async refetch() {
+ await scope.refetch({ throwOnError: true });
+ await query.refetch();
+ },
+ async refresh() {
+ await scope.refetch({ throwOnError: true });
+ await query.refresh();
+ },
+ });
+}
diff --git a/apps/web/src/features/crm/queries/keys.ts b/apps/web/src/features/crm/queries/keys.ts
index 03f2e1f38e..5b729daf53 100644
--- a/apps/web/src/features/crm/queries/keys.ts
+++ b/apps/web/src/features/crm/queries/keys.ts
@@ -2,6 +2,7 @@ import { createQueryKeys } from '@lukemorales/query-key-factory';
export const crmKeys = createQueryKeys('crm', {
lists: null,
+ activityScope: (userId: string | undefined) => [userId],
pipelines: (teamId: string | undefined) => [teamId],
pipelineTable: (id: string) => [id],
pipelineRows: (id: string) => [id],
diff --git a/apps/web/src/features/crm/record-tasks-adapter.tsx b/apps/web/src/features/crm/record-tasks-adapter.tsx
index 522e6450bc..6854bd79c8 100644
--- a/apps/web/src/features/crm/record-tasks-adapter.tsx
+++ b/apps/web/src/features/crm/record-tasks-adapter.tsx
@@ -7,15 +7,17 @@ import {
} from '@app/features/tasks-view/tasks-view-context';
import { createTaskWithProperties } from '@block-md/util/taskComposerProperties';
import { useSplitLayout } from '@components/app/split-layout/layout';
+import {
+ enableCrmActivity,
+ isFeatureEnabled,
+} from '@core/constant/featureFlags';
import PlusIcon from '@phosphor/plus.svg';
-import { SYSTEM_PROPERTY_IDS } from '@property/identifiers';
import { TagSetsQueryProvider } from '@property/tags/tag-sets-context';
-import type { PropertyApiValues } from '@property/types';
import { Button } from '@ui';
import { Show } from 'solid-js';
-import { match } from 'ts-pattern';
import { RecordSection } from './components/record-section';
import type { CrmRecordScope } from './core/record';
+import { crmTaskComposerContext } from './task-composer';
/**
* The record's Tasks tab: the production Tasks list, scoped to tasks
@@ -56,59 +58,39 @@ export function CrmRecordTasks(props: { scope: CrmRecordScope }) {
);
}
-const reference = (
- propertyId: string,
- entityId: string,
- entityType: 'COMPANY' | 'CONTACT'
-): [string, PropertyApiValues] => [
- propertyId,
- {
- valueType: 'ENTITY',
- refs: [{ entity_id: entityId, entity_type: entityType }],
- },
-];
-
-/**
- * Properties a task created from the record starts with, like project tasks
- * start in their project. A contact's tasks also join its company.
- */
-function taskAssociations(
- scope: CrmRecordScope
-): [string, PropertyApiValues][] {
- return match(scope)
- .with({ type: 'company' }, ({ id }) => [
- reference(SYSTEM_PROPERTY_IDS.COMPANIES, id, 'COMPANY'),
- ])
- .with({ type: 'contact' }, ({ id, companyId }) => [
- reference(SYSTEM_PROPERTY_IDS.CONTACTS, id, 'CONTACT'),
- reference(SYSTEM_PROPERTY_IDS.COMPANIES, companyId, 'COMPANY'),
- ])
- .exhaustive();
-}
-
function RecordTasksBody(props: { scope: CrmRecordScope }) {
const { state, setState } = useTasksView();
const layout = useSplitLayout();
let listElement: HTMLDivElement | undefined;
- const composeTask = () =>
+ const composeTask = () => {
+ const context = crmTaskComposerContext(props.scope);
+ const adaptive = isFeatureEnabled(enableCrmActivity);
layout.popoverSplit({
type: 'component',
id: 'task-compose',
params: {
- createTask: (
- ...[title, content, properties, ...rest]: Parameters<
- typeof createTaskWithProperties
- >
- ) =>
- createTaskWithProperties(
- title,
- content,
- [...properties, ...taskAssociations(props.scope)],
- ...rest
- ),
+ composerContext: adaptive ? context : undefined,
+ // Keep the existing record associations with the standard composer.
+ createTask: adaptive
+ ? undefined
+ : (
+ ...[title, content, properties, ...rest]: Parameters<
+ typeof createTaskWithProperties
+ >
+ ) =>
+ createTaskWithProperties(
+ title,
+ content,
+ [
+ ...properties,
+ ...Object.entries(context.initialPropertyValues ?? {}),
+ ],
+ ...rest
+ ),
},
});
+ };
return (
<RecordSection
diff --git a/apps/web/src/features/crm/task-composer.ts b/apps/web/src/features/crm/task-composer.ts
new file mode 100644
index 0000000000..fbf60d799e
--- /dev/null
+++ b/apps/web/src/features/crm/task-composer.ts
@@ -0,0 +1,47 @@
+import { SYSTEM_PROPERTY_IDS } from '@property/identifiers';
+import type { PropertyApiValues } from '@property/types';
+import type { TaskComposerContext } from '../task-composer/core/context';
+import type { CrmTaskRecord } from './core/record';
+
+const reference = (
+ entityId: string,
+ entityType: 'COMPANY' | 'CONTACT'
+): PropertyApiValues => ({
+ valueType: 'ENTITY',
+ refs: [{ entity_id: entityId, entity_type: entityType }],
+});
+
+/** CRM owns its composer preset; the shared composer has no CRM-specific behavior. */
+export function crmTaskComposerContext(
+ record?: CrmTaskRecord
+): TaskComposerContext {
+ const initialPropertyValues: Record<string, PropertyApiValues> = {};
+ if (record?.type === 'company') {
+ initialPropertyValues[SYSTEM_PROPERTY_IDS.COMPANIES] = reference(
+ record.id,
+ 'COMPANY'
+ );
+ } else if (record?.type === 'contact') {
+ initialPropertyValues[SYSTEM_PROPERTY_IDS.CONTACTS] = reference(
+ record.id,
+ 'CONTACT'
+ );
+ if (record.companyId) {
+ initialPropertyValues[SYSTEM_PROPERTY_IDS.COMPANIES] = reference(
+ record.companyId,
+ 'COMPANY'
+ );
+ }
+ }
+ return {
+ key: record ? `crm:${record.type}:${record.id}` : 'crm',
+ visiblePropertyIds: [
+ SYSTEM_PROPERTY_IDS.COMPANIES,
+ SYSTEM_PROPERTY_IDS.CONTACTS,
+ SYSTEM_PROPERTY_IDS.ASSIGNEES,
+ SYSTEM_PROPERTY_IDS.DUE_DATE,
+ SYSTEM_PROPERTY_IDS.PRIORITY,
+ ],
+ initialPropertyValues,
+ };
+}
diff --git a/apps/web/src/features/crm/views/activity.tsx b/apps/web/src/features/crm/views/activity.tsx
new file mode 100644
index 0000000000..ea54164dc3
--- /dev/null
+++ b/apps/web/src/features/crm/views/activity.tsx
@@ -0,0 +1,71 @@
+import { fireAndForget } from '@core/util/fireAndForget';
+import PlusIcon from '@phosphor/plus.svg';
+import { Button } from '@ui';
+import { createSignal, Show } from 'solid-js';
+import { useCrmContext } from '../context/crm-context';
+import type { CrmActivityTab } from '../core/navigation';
+import { RecordItemList } from './record-item-list';
+
+const DESCRIPTIONS: Record<CrmActivityTab, string> = {
+ tasks: 'Tasks linked to your CRM companies and people.',
+ email: 'Email in your mailbox exchanged with your CRM companies and people.',
+ notes: 'Notes linked to your CRM companies and people.',
+ calls: 'Calls linked to your CRM companies and people.',
+};
+
+/** The workspace-wide feed uses the same paged rows as a record's activity. */
+export function CrmActivityView(props: { tab: CrmActivityTab }) {
+ const crm = useCrmContext();
+ const source = crm.createActivity(() => props.tab);
+ const [retrying, setRetrying] = createSignal(false);
+ const retry = async () => {
+ if (!source.refetch || retrying()) return;
+ setRetrying(true);
+ try {
+ await source.refetch();
+ } catch {
+ // Keep the source's error state and retry action visible.
+ } finally {
+ setRetrying(false);
+ }
+ };
+ return (
+ <div class="flex min-h-0 flex-1 flex-col">
+ <div class="flex items-center justify-between gap-3 border-b border-edge-muted px-4 py-3">
+ <p class="text-sm text-ink-muted">{DESCRIPTIONS[props.tab]}</p>
+ <Show when={props.tab === 'tasks'}>
+ <Button
+ variant="outline"
+ class="shrink-0"
+ onClick={crm.openTaskComposer}
+ >
+ <PlusIcon class="size-4" />
+ New task
+ </Button>
+ </Show>
+ </div>
+ <div class="min-h-0 flex-1 overflow-y-auto p-4">
+ <Show
+ when={!source.isError}
+ fallback={
+ <div class="flex flex-col items-start gap-3 text-sm text-ink-muted">
+ <p>Could not load CRM {props.tab}.</p>
+ <Button
+ variant="outline"
+ disabled={retrying()}
+ onClick={() => fireAndForget(retry(), 'crm')}
+ >
+ {retrying() ? 'Retrying…' : 'Try again'}
+ </Button>
+ </div>
+ }
+ >
+ <RecordItemList
+ source={source}
+ empty={`No ${props.tab} linked to your CRM companies or people yet.`}
+ />
+ </Show>
+ </div>
+ </div>
+ );
+}
diff --git a/apps/web/src/features/crm/views/company-detail.tsx b/apps/web/src/features/crm/views/company-detail.tsx
index 6d4a748b86..599d9babe3 100644
--- a/apps/web/src/features/crm/views/company-detail.tsx
+++ b/apps/web/src/features/crm/views/company-detail.tsx
@@ -1,7 +1,7 @@
import { SidePanel } from '@components/app/side-panel';
import PlusIcon from '@phosphor/plus.svg';
import { Button } from '@ui';
-import { createMemo, Match, Show, Suspense, Switch } from 'solid-js';
+import { createMemo, Match, onCleanup, Show, Suspense, Switch } from 'solid-js';
import { RecordOverview } from '../components/record-overview';
import { useCrmContext } from '../context/crm-context';
import type { CrmContact as CompanyContact } from '../core/contact';
@@ -40,6 +40,12 @@ export function Company(props: {
onOpenPipeline?: (pipelineId: string) => void;
}) {
const context = useCrmContext();
+ onCleanup(
+ context.registerTaskComposerRecord(() => ({
+ type: 'company',
+ id: props.companyId,
+ }))
+ );
const openCreateContactModal = context.openCreateContact;
const listsEnabled = context.listsEnabled();
const pipelinesEnabled = context.pipelinesEnabled();
diff --git a/apps/web/src/features/crm/views/contact-detail.tsx b/apps/web/src/features/crm/views/contact-detail.tsx
index 2f95aee0fb..a8bef4e140 100644
--- a/apps/web/src/features/crm/views/contact-detail.tsx
+++ b/apps/web/src/features/crm/views/contact-detail.tsx
@@ -1,5 +1,5 @@
import { SidePanel } from '@components/app/side-panel';
-import { createMemo, Match, Show, Suspense, Switch } from 'solid-js';
+import { createMemo, Match, onCleanup, Show, Suspense, Switch } from 'solid-js';
import { RecordOverview } from '../components/record-overview';
import { useCrmContext } from '../context/crm-context';
import {
@@ -35,6 +35,13 @@ export function Contact(props: {
const pipelinesEnabled = context.pipelinesEnabled();
const contactQuery = useContactQuery(() => props.contactId);
const contact = () => contactQuery.data;
+ onCleanup(
+ context.registerTaskComposerRecord(() => ({
+ type: 'contact',
+ id: props.contactId,
+ companyId: contact()?.companyId,
+ }))
+ );
const isTeamAdmin = useIsTeamAdmin();
const section = () => props.section ?? 'overview';
const scope = createMemo(
diff --git a/apps/web/src/features/crm/views/crm-workspace.test.tsx b/apps/web/src/features/crm/views/crm-workspace.test.tsx
index 30e01d376f..fd5ccd050a 100644
--- a/apps/web/src/features/crm/views/crm-workspace.test.tsx
+++ b/apps/web/src/features/crm/views/crm-workspace.test.tsx
@@ -17,9 +17,13 @@ const fixture = vi.hoisted(() => ({
touch: true,
narrow: false,
openWithSplit: vi.fn(),
+ activityFlag: () => ({ enabled: true, loading: false }),
setCollapsed: vi.fn(),
}));
+vi.mock('@app/lib/analytics/posthog', () => ({
+ useFeatureFlag: () => () => fixture.activityFlag(),
+}));
vi.mock('@app/components/view-shell', () => ({
ViewShell: {
Root: (props: ParentProps) => props.children,
@@ -185,6 +189,9 @@ vi.mock('../components/pipeline-sidebar', () => ({
vi.mock('../components/pipeline-dialog', () => ({
PipelineDialog: () => null,
}));
+vi.mock('./activity', () => ({
+ CrmActivityView: (props: { tab: string }) => <div>{props.tab} feed</div>,
+}));
vi.mock('./record-detail', () => ({
CrmRecordDetail: (props: {
viewName: string;
@@ -272,7 +279,12 @@ afterEach(() => {
});
/** A workspace whose route shows another tab's list when the tab changes. */
-function setup(initialTab = 'active') {
+function setup(
+ initialTab = 'active',
+ initialActivityFlag = { enabled: true, loading: false }
+) {
+ const [activityFlag, setActivityFlag] = createSignal(initialActivityFlag);
+ fixture.activityFlag = activityFlag;
const [activeTab, setTab] = createSignal<string | undefined>(initialTab);
const [records, setRecords] = createSignal<
readonly { type: 'company' | 'contact'; id: string; name: string }[]
@@ -309,7 +321,7 @@ function setup(initialTab = 'active') {
render(() => (
<CrmWorkspaceView>{() => <div>Record list</div>}</CrmWorkspaceView>
));
- return { activeTab, record, captureEntryState };
+ return { activeTab, record, captureEntryState, setActivityFlag };
}
it('keeps sidebar destinations in the mobile header when switching records, pipelines and lists', () => {
@@ -347,9 +359,59 @@ it('omits pipelines and lists when those features are disabled', () => {
const tabs = within(screen.getByRole('navigation', { name: 'CRM views' }));
expect(
tabs.getAllByRole('button').map((button) => button.textContent)
- ).toEqual(['Companies', 'People']);
+ ).toEqual(['Companies', 'People', 'Tasks', 'Email', 'Notes', 'Calls']);
+});
+
+it('opens each CRM activity feed instead of the company list', () => {
+ const { activeTab } = setup();
+ const tabs = within(screen.getByRole('navigation', { name: 'CRM views' }));
+ for (const label of ['Tasks', 'Email', 'Notes', 'Calls']) {
+ fireEvent.click(tabs.getByRole('button', { name: label }));
+ expect(activeTab()).toBe(label.toLowerCase());
+ expect(screen.getByText(`${label.toLowerCase()} feed`)).toBeTruthy();
+ expect(screen.queryByText('Record list')).toBeNull();
+ }
+ fireEvent.click(tabs.getByRole('button', { name: 'Companies' }));
+ expect(screen.getByText('Record list')).toBeTruthy();
+});
+
+it('waits for the rollout before resolving a cold activity link', () => {
+ const { activeTab, setActivityFlag } = setup('tasks', {
+ enabled: false,
+ loading: true,
+ });
+ expect(activeTab()).toBe('tasks');
+ expect(screen.getByText('Loading CRM activity…')).toBeTruthy();
+ expect(screen.queryByText('tasks feed')).toBeNull();
+ expect(screen.queryByText('Record list')).toBeNull();
+ setActivityFlag({ enabled: true, loading: false });
+ expect(activeTab()).toBe('tasks');
+ expect(screen.getByText('tasks feed')).toBeTruthy();
+});
+
+it('hides activity navigation and leaves its feed when the rollout turns off', () => {
+ const { activeTab, setActivityFlag } = setup('email');
+ expect(screen.getByText('email feed')).toBeTruthy();
+ setActivityFlag({ enabled: false, loading: false });
+ expect(activeTab()).toBe('active');
+ expect(screen.queryByText('email feed')).toBeNull();
+ expect(screen.getByText('Record list')).toBeTruthy();
+ const tabs = within(screen.getByRole('navigation', { name: 'CRM views' }));
+ for (const name of ['Tasks', 'Email', 'Notes', 'Calls']) {
+ expect(tabs.queryByRole('button', { name })).toBeNull();
+ }
});
+it.each(['tasks', 'email', 'notes', 'calls'])(
+ 'returns an unavailable %s deep link to Companies without mounting activity',
+ (tab) => {
+ const { activeTab } = setup(tab, { enabled: false, loading: false });
+ expect(activeTab()).toBe('active');
+ expect(screen.queryByText(`${tab} feed`)).toBeNull();
+ expect(screen.getByText('Record list')).toBeTruthy();
+ }
+);
+
it('opens the company of a pipeline row through the route on desktop', () => {
fixture.touch = false;
const { record, captureEntryState } = setup('pipeline:sales');
@@ -443,6 +505,23 @@ it('shows CRM settings in place of an open record and returns to it', () => {
expect(record.close).not.toHaveBeenCalled();
});
+it.each([false, true])(
+ 'returns to the activity feed after closing CRM settings (touch: %s)',
+ (touch) => {
+ fixture.touch = touch;
+ const { activeTab } = setup('tasks');
+ expect(screen.getByText('tasks feed')).toBeTruthy();
+ fireEvent.click(screen.getByRole('button', { name: 'CRM settings' }));
+ expect(screen.getByText('Stage settings')).toBeTruthy();
+ expect(screen.queryByText('tasks feed')).toBeNull();
+ expect(screen.queryByText('Record list')).toBeNull();
+ expect(activeTab()).toBe('tasks');
+ fireEvent.click(screen.getByRole('button', { name: 'Close CRM settings' }));
+ expect(screen.getByText('tasks feed')).toBeTruthy();
+ expect(screen.queryByText('Stage settings')).toBeNull();
+ expect(screen.queryByText('Record list')).toBeNull();
+ }
+);
it('leaves CRM settings for the list picked in the sidebar, including the current one', () => {
fixture.touch = false;
const { activeTab } = setup();
diff --git a/apps/web/src/features/crm/views/crm-workspace.tsx b/apps/web/src/features/crm/views/crm-workspace.tsx
index 03bd4d5ff0..ed01670184 100644
--- a/apps/web/src/features/crm/views/crm-workspace.tsx
+++ b/apps/web/src/features/crm/views/crm-workspace.tsx
@@ -14,8 +14,10 @@ import { SoupViewContextGroup } from '@app/features/next-soup/soup-view/filters-
import { SoupViewContextSort } from '@app/features/next-soup/soup-view/filters-bar/soup-view-context-sort';
import { UnifiedFilterDropdown } from '@app/features/next-soup/soup-view/filters-bar/unified-filter-dropdown';
import { useFilterRefinements } from '@app/features/next-soup/soup-view/filters-bar/use-filter-refinements';
+import { useFeatureFlag } from '@app/lib/analytics/posthog';
import { usePreference } from '@app/preferences/use-preference';
import { SplitPanel } from '@components/app/split-panel';
+import { enableCrmActivity } from '@core/constant/featureFlags';
import { isTouchDevice } from '@core/mobile/isTouchDevice';
import { debounce } from '@core/util/debounce';
import { fireAndForget } from '@core/util/fireAndForget';
@@ -33,6 +35,7 @@ import {
createEffect,
createSignal,
type JSX,
+ on,
onCleanup,
onMount,
Show,
@@ -45,9 +48,16 @@ import { PipelineDialog } from '../components/pipeline-dialog';
import { PipelineSidebar } from '../components/pipeline-sidebar';
import { useCrmContext } from '../context/crm-context';
import { useCrmWorkspace } from '../context/workspace-context';
-import { CRM_RECORDS, pipelineIdOfTab, pipelineTab } from '../core/navigation';
+import {
+ CRM_ACTIVITY_TABS,
+ CRM_RECORDS,
+ isCrmActivityTab,
+ pipelineIdOfTab,
+ pipelineTab,
+} from '../core/navigation';
import type { CrmRecordRef } from '../core/record';
import { createCrmExportLoader } from '../primitives/export-source';
+import { CrmActivityView } from './activity';
import { useApplyCrmView } from './apply-view';
import { Crm as CrmSettings } from './crm-settings';
import { CrmExport } from './export-companies';
@@ -211,6 +221,7 @@ export function CrmWorkspaceView(props: {
onOpenEntity?: (entity: EntityData) => boolean;
}) => JSX.Element;
}) {
+ const activityFlag = useFeatureFlag(enableCrmActivity);
const {
openCreateCompany: openCreateCompanyModal,
openCreateContact: openCreateContactModal,
@@ -284,6 +295,12 @@ export function CrmWorkspaceView(props: {
const [importing, setImporting] = createSignal(false);
const active = () => view.activeTab() ?? 'active';
const peopleActive = () => active() === 'people';
+ const activityTab = () => {
+ const tab = active();
+ return activityFlag().enabled && isCrmActivityTab(tab) ? tab : undefined;
+ };
+ const activityPending = () =>
+ isCrmActivityTab(active()) && activityFlag().loading;
const [exporting, setExporting] = createSignal(false);
const activeList = () =>
lists.lists().find((list) => `list:${list.id}` === active());
@@ -312,17 +329,27 @@ export function CrmWorkspaceView(props: {
const activeRecord = () => {
const id = pipelineId();
if (id) return pipelineTab(id);
- return active().startsWith('list:') || peopleActive() ? active() : 'active';
+ return active().startsWith('list:') || peopleActive() || activityTab()
+ ? active()
+ : 'active';
};
const title = () =>
activeList()?.name ??
- CRM_RECORDS.find((record) => record.id === activeRecord())?.label ??
+ [...CRM_RECORDS, ...CRM_ACTIVITY_TABS].find(
+ (record) => record.id === activeRecord()
+ )?.label ??
'Companies';
const navigate = (id: string) => {
settings.close();
if (!listsEnabled() && id.startsWith('list:')) id = 'active';
- if (id !== 'people' && !id.startsWith('list:')) id = 'active';
+ if (!activityFlag().enabled && isCrmActivityTab(id)) id = 'active';
+ if (id !== 'people' && !id.startsWith('list:') && !isCrmActivityTab(id))
+ id = 'active';
if (id === active()) view.host.record.close();
+ if (isCrmActivityTab(id)) {
+ view.setActiveTab(id);
+ return;
+ }
if (id === 'people') {
// Re-applying would clear a search the People search bar still shows.
if (peopleActive()) return;
@@ -356,6 +383,15 @@ export function CrmWorkspaceView(props: {
onMount(() => {
if (!listsEnabled() && active().startsWith('list:')) navigate('active');
});
+ // Keep cold activity links intact until PostHog resolves; off falls back to Companies.
+ createEffect(
+ on(
+ () => [activityFlag().loading, activityFlag().enabled, active()] as const,
+ ([loading, enabled, tab]) => {
+ if (!loading && !enabled && isCrmActivityTab(tab)) navigate('active');
+ }
+ )
+ );
const sidebar = (onCollapse?: () => void) => (
<CrmSidebar
pipelines={
@@ -451,7 +487,9 @@ export function CrmWorkspaceView(props: {
else navigate(id);
}}
leading={
- <Show when={!peopleActive() && !pipelineId()}>
+ <Show
+ when={!peopleActive() && !pipelineId() && !activityTab()}
+ >
<Suspense>
<MobileFilterDrawer />
</Suspense>
@@ -459,7 +497,7 @@ export function CrmWorkspaceView(props: {
}
/>
</ViewShell.Header>
- <Show when={!peopleActive() && !pipelineId()}>
+ <Show when={!peopleActive() && !pipelineId() && !activityTab()}>
<Suspense>
<SoupFiltersBar />
</Suspense>
@@ -526,7 +564,42 @@ export function CrmWorkspaceView(props: {
</Button>
</div>
</Show>
- <Show when={!recordOpen() && !pipelineId()}>
+ <Show when={!recordOpen() && !pipelineId() && activityPending()}>
+ <div class="p-4 text-sm text-ink-muted">Loading CRM activity…</div>
+ </Show>
+ <Show when={!recordOpen() && !pipelineId() && activityTab()} keyed>
+ {(tab) => (
+ <>
+ <Show when={!isTouchDevice()}>
+ <div class="flex h-12 shrink-0 items-center gap-3 px-4">
+ <NavigationToggle onExpand={() => setCollapsed(false)}>
+ <Suspense>{sidebar()}</Suspense>
+ </NavigationToggle>
+ <h1 class="flex h-7 min-w-0 flex-1 items-center px-1 text-sm font-semibold tracking-[-0.03em]">
+ {title()}
+ </h1>
+ </div>
+ </Show>
+ <Suspense
+ fallback={
+ <div class="p-4 text-sm text-ink-muted">
+ Loading CRM activity…
+ </div>
+ }
+ >
+ <CrmActivityView tab={tab} />
+ </Suspense>
+ </>
+ )}
+ </Show>
+ <Show
+ when={
+ !recordOpen() &&
+ !pipelineId() &&
+ !activityTab() &&
+ !activityPending()
+ }
+ >
<Show when={!isTouchDevice() || peopleActive()}>
<Show when={!isTouchDevice()}>
<div class="flex h-12 shrink-0 items-center gap-3 px-4">
diff --git a/apps/web/src/features/crm/views/record-detail.test.tsx b/apps/web/src/features/crm/views/record-detail.test.tsx
index 6625fc6a73..de5986dd5d 100644
--- a/apps/web/src/features/crm/views/record-detail.test.tsx
+++ b/apps/web/src/features/crm/views/record-detail.test.tsx
@@ -9,15 +9,45 @@ import {
createSignal,
ErrorBoundary,
type JSX,
+ onCleanup,
type ParentProps,
Show,
} from 'solid-js';
import { afterEach, expect, it, vi } from 'vitest';
+import { useCrmContext } from '../context/crm-context';
import type { CrmCommentTarget } from '../context/workspace-context';
import type { CrmContact } from '../core/contact';
-import type { CrmRecordRef, CrmRecordSection } from '../core/record';
+import type {
+ CrmRecordRef,
+ CrmRecordSection,
+ CrmTaskRecord,
+} from '../core/record';
import { CrmRecordDetail } from './record-detail';
+const taskContext = vi.hoisted(() => ({
+ records: [] as (() => CrmTaskRecord)[],
+ get record() {
+ return this.records.at(-1);
+ },
+ contactCompanyId: undefined as string | undefined,
+ recordError: (): boolean => false,
+}));
+vi.mock('../context/crm-context', () => ({
+ useCrmContext: () => ({
+ listsEnabled: () => () => false,
+ pipelinesEnabled: () => () => false,
+ isTeamAdmin: () => () => false,
+ openCreateContact: vi.fn(),
+ registerTaskComposerRecord: (source: () => CrmTaskRecord) => {
+ taskContext.records.push(source);
+ return () => {
+ const index = taskContext.records.indexOf(source);
+ if (index !== -1) taskContext.records.splice(index, 1);
+ };
+ },
+ }),
+}));
+
vi.mock('@ui', async () => ({
...(await import('../../../components/ui/utils/classname')),
Tooltip: (props: ParentProps) => <>{props.children}</>,
@@ -28,6 +58,8 @@ vi.mock('@ui', async () => ({
vi.mock('@components/app/side-panel', () => ({
SidePanel: {
Root: (props: ParentProps) => <>{props.children}</>,
+ Layout: (props: ParentProps) => <>{props.children}</>,
+ Section: (props: ParentProps) => <>{props.children}</>,
Toggle: () => null,
},
}));
@@ -42,10 +74,24 @@ vi.mock('../components/record-tabs', () => ({
}));
vi.mock('./use-crm', () => ({
useCompanyQuery: () => ({
- query: { isError: false },
+ query: {
+ get isError() {
+ return taskContext.recordError();
+ },
+ },
company: () => undefined,
+ contacts: () => [],
+ }),
+ useContactQuery: () => ({
+ isSuccess: !!taskContext.contactCompanyId,
+ get isError() {
+ return taskContext.recordError();
+ },
+ data: taskContext.contactCompanyId
+ ? { companyId: taskContext.contactCompanyId }
+ : undefined,
}),
- useContactQuery: () => ({ isSuccess: false, isError: false }),
+ useIsTeamAdmin: () => () => false,
}));
vi.mock('@solidjs/router', () => ({ useSearchParams: () => [{}] }));
vi.mock('./company-detail', async () => {
@@ -54,7 +100,16 @@ vi.mock('./company-detail', async () => {
);
return {
// Reads its linked message the way the Discussion does.
- Company: (props: { onOpenContact(contact: CrmContact): void }) => {
+ Company: (props: {
+ companyId: string;
+ onOpenContact(contact: CrmContact): void;
+ }) => {
+ onCleanup(
+ useCrmContext().registerTaskComposerRecord(() => ({
+ type: 'company',
+ id: props.companyId,
+ }))
+ );
const params = useUrlParams({ commentId: 'comment_id' });
const navigations = useParamNavigationCount('comment_id');
return (
@@ -88,16 +143,66 @@ vi.mock('./contact-detail', () => ({
Contact: (props: {
contactId: string;
onOpenCompany(companyId: string): boolean;
- }) => (
- <div>
- Contact content: {props.contactId}
- <button onClick={() => props.onOpenCompany('company-1')}>
- Open contact company
- </button>
- </div>
- ),
+ }) => {
+ onCleanup(
+ useCrmContext().registerTaskComposerRecord(() => ({
+ type: 'contact',
+ id: props.contactId,
+ companyId: taskContext.contactCompanyId,
+ }))
+ );
+ return (
+ <div>
+ Contact content: {props.contactId}
+ <button onClick={() => props.onOpenCompany('company-1')}>
+ Open contact company
+ </button>
+ </div>
+ );
+ },
+}));
+// The breadcrumb test replaces detail views, while registration tests load their real roots.
+vi.mock('./company-contacts-section', () => ({
+ CompanyContactsSection: () => null,
+}));
+vi.mock('./company-discussion-section', () => ({
+ CompanyDiscussionSection: () => null,
+}));
+vi.mock('./company-emails-section', () => ({
+ CompanyEmailsSection: () => null,
+}));
+vi.mock('./company-header', () => ({ CompanyHeader: () => null }));
+vi.mock('./company-list-membership', () => ({
+ CompanyListsSection: () => null,
+}));
+vi.mock('./company-properties-section', () => ({
+ CompanyPropertiesSection: () => null,
+}));
+vi.mock('./company-sharing-section', () => ({
+ CompanySharingSection: () => null,
+}));
+vi.mock('./contact-discussion-section', () => ({
+ ContactDiscussionSection: () => null,
+}));
+vi.mock('./contact-emails-section', () => ({
+ ContactEmailsSection: () => null,
+}));
+vi.mock('./contact-header', () => ({ ContactHeader: () => null }));
+vi.mock('./contact-sharing-section', () => ({
+ ContactSharingSection: () => null,
+}));
+vi.mock('./record-associations', () => ({
+ RecordCallsSection: () => null,
+ RecordFilesSection: () => null,
+ RecordReferencesSection: () => null,
}));
-afterEach(cleanup);
+
+afterEach(() => {
+ cleanup();
+ taskContext.records.length = 0;
+ taskContext.contactCompanyId = undefined;
+ taskContext.recordError = () => false;
+});
/** Stands in for the route: each open hands the detail a new trail. */
function renderDetail(record: CrmRecordRef, viewName: string) {
@@ -186,6 +291,69 @@ it('opens a People contact in place and follows its company without duplicating
expect(close).toHaveBeenCalledOnce();
});
+it('registers the actual company detail while mounted and clears it on unmount', async () => {
+ const { Company } =
+ await vi.importActual<typeof import('./company-detail')>(
+ './company-detail'
+ );
+ const result = render(() => (
+ <Company companyId="company-1" section="files" />
+ ));
+ expect(taskContext.record?.()).toEqual({ type: 'company', id: 'company-1' });
+ result.unmount();
+ expect(taskContext.record).toBeUndefined();
+});
+
+it('registers the actual contact detail with its loaded company', async () => {
+ const { Contact } =
+ await vi.importActual<typeof import('./contact-detail')>(
+ './contact-detail'
+ );
+ taskContext.contactCompanyId = 'company-1';
+ const result = render(() => (
+ <Contact contactId="contact-1" section="files" />
+ ));
+ expect(taskContext.record?.()).toEqual({
+ type: 'contact',
+ id: 'contact-1',
+ companyId: 'company-1',
+ });
+ result.unmount();
+ expect(taskContext.record).toBeUndefined();
+});
+
+it('registers an unloaded contact without an unrelated company', async () => {
+ const { Contact } =
+ await vi.importActual<typeof import('./contact-detail')>(
+ './contact-detail'
+ );
+ const result = render(() => (
+ <Contact contactId="contact-2" section="files" />
+ ));
+ expect(taskContext.record?.()).toEqual({
+ type: 'contact',
+ id: 'contact-2',
+ companyId: undefined,
+ });
+ result.unmount();
+ expect(taskContext.record).toBeUndefined();
+});
+
+it.each(['company', 'contact'] as const)(
+ 'keeps the selected %s association when the detail query fails',
+ (type) => {
+ const [error, setError] = createSignal(false);
+ taskContext.recordError = error;
+ taskContext.contactCompanyId = 'company-1';
+ renderDetail({ type, id: 'record-1', name: 'Selected record' }, 'Records');
+ expect(taskContext.record?.()).toMatchObject({ type, id: 'record-1' });
+ setError(true);
+ expect(screen.getByText(`This ${type} couldn’t be loaded.`)).toBeTruthy();
+ expect(taskContext.record?.()).toMatchObject({ type, id: 'record-1' });
+ fireEvent.click(screen.getByRole('button', { name: 'Back to view' }));
+ expect(taskContext.record).toBeUndefined();
+ }
+);
it('keeps the shown record mounted while the route only changes its tab', () => {
renderDetail({ type: 'contact', id: 'contact-1', name: 'Maya' }, 'People');
const content = screen.getByText('Contact content: contact-1');
diff --git a/apps/web/src/features/crm/views/record-detail.tsx b/apps/web/src/features/crm/views/record-detail.tsx
index e358f53f10..5d5e921510 100644
--- a/apps/web/src/features/crm/views/record-detail.tsx
+++ b/apps/web/src/features/crm/views/record-detail.tsx
@@ -16,12 +16,14 @@ import {
For,
type JSX,
on,
+ onCleanup,
onMount,
Show,
Suspense,
untrack,
} from 'solid-js';
import { RecordTabs } from '../components/record-tabs';
+import { useCrmContext } from '../context/crm-context';
import type { CrmCommentTarget } from '../context/workspace-context';
import {
COMPANY_SECTIONS,
@@ -81,6 +83,8 @@ export function CrmRecordDetail(props: {
const current = createMemo(() => trail()[trail().length - 1]!, undefined, {
equals: (left, right) => recordKey(left) === recordKey(right),
});
+ // Keep the selected identity available even if the detail body shows an error.
+ onCleanup(useCrmContext().registerTaskComposerRecord(current));
const companySection = (): CompanySection =>
sectionOf(COMPANY_SECTIONS, props.section);
const contactSection = (): ContactSection =>
diff --git a/apps/web/src/features/next-soup/soup-view/empty-states.test.tsx b/apps/web/src/features/next-soup/soup-view/empty-states.test.tsx
index 0fe72989b8..eadc0ceec8 100644
--- a/apps/web/src/features/next-soup/soup-view/empty-states.test.tsx
+++ b/apps/web/src/features/next-soup/soup-view/empty-states.test.tsx
@@ -6,7 +6,7 @@ import { describe, expect, it, vi } from 'vitest';
import { shouldShowLoadError } from './empty-states';
vi.mock('@app/features/command/Launcher', () => ({
- runCreateAction: vi.fn(),
+ useCreateAction: () => vi.fn(),
}));
vi.mock('@channel/CreateChannelModal', () => ({
openNewChannelModal: vi.fn(),
diff --git a/apps/web/src/features/next-soup/soup-view/empty-states.tsx b/apps/web/src/features/next-soup/soup-view/empty-states.tsx
index f276954ee0..6e94f115a9 100644
--- a/apps/web/src/features/next-soup/soup-view/empty-states.tsx
+++ b/apps/web/src/features/next-soup/soup-view/empty-states.tsx
@@ -2,8 +2,8 @@ import { DOCS_BASE } from '@app/constants/docs-links';
import type { ListView } from '@app/constants/list-views';
import {
type CreatableName,
- runCreateAction,
useCreatableEnabled,
+ useCreateAction,
} from '@app/features/command/Launcher';
import { openNewChannelModal } from '@channel/CreateChannelModal';
import { useAddInboxFlow, useEmailLinksStatus } from '@core/email-link';
@@ -81,6 +81,7 @@ export function EmptyState(props: {
hasHiddenItems?: boolean;
onClearFilters?: () => void;
}) {
+ const runCreateAction = useCreateAction();
const emailActive = useEmailLinksStatus();
const startAddInbox = useAddInboxFlow();
const soup = useSoupView();
diff --git a/apps/web/src/features/next-soup/soup-view/soup-view-create-button.tsx b/apps/web/src/features/next-soup/soup-view/soup-view-create-button.tsx
index a36691bff2..4def04690f 100644
--- a/apps/web/src/features/next-soup/soup-view/soup-view-create-button.tsx
+++ b/apps/web/src/features/next-soup/soup-view/soup-view-create-button.tsx
@@ -2,8 +2,8 @@ import { isListViewID, type ListView } from '@app/constants/list-views';
import {
CREATABLE_BLOCKS,
type CreatableName,
- runCreateAction,
useCreatableEnabled,
+ useCreateAction,
} from '@app/features/command/Launcher';
import { openCreateCompanyModal } from '@app/features/crm/creation-adapter';
import { useHandleFileUpload } from '@app/util/handleFileUpload';
@@ -127,6 +127,7 @@ function CreateOptionIcon(props: { id: CreateOption['id'] }) {
}
export const SoupViewCreateButton = () => {
+ const runCreateAction = useCreateAction();
const panel = useSplitPanelOrThrow();
const handleFileUpload = useHandleFileUpload();
const isCreatableEnabled = useCreatableEnabled();
diff --git a/apps/web/src/features/property/component/AddPropertyButton.tsx b/apps/web/src/features/property/component/AddPropertyButton.tsx
index 3bd24a9108..9d3a3886e3 100644
--- a/apps/web/src/features/property/component/AddPropertyButton.tsx
+++ b/apps/web/src/features/property/component/AddPropertyButton.tsx
@@ -2,12 +2,15 @@ import PlusIcon from '@phosphor/plus.svg';
import { badgeTriggerClasses } from '@ui';
import { usePropertiesContext } from '../context/PropertiesContext';
-export function AddPropertyButton(props: { class?: string }) {
+export function AddPropertyButton(props: {
+ class?: string;
+ onClick?: () => void;
+}) {
const { openPropertySelector } = usePropertiesContext();
return (
<button
type="button"
- onClick={openPropertySelector}
+ onClick={() => (props.onClick ?? openPropertySelector)()}
class={badgeTriggerClasses({
variant: 'outline',
size: 'sm',
diff --git a/apps/web/src/features/property/editor/PropertyEditorModal.tsx b/apps/web/src/features/property/editor/PropertyEditorModal.tsx
index 715e777abf..df92ab4aa0 100644
--- a/apps/web/src/features/property/editor/PropertyEditorModal.tsx
+++ b/apps/web/src/features/property/editor/PropertyEditorModal.tsx
@@ -50,6 +50,7 @@ import type { EntityReference } from '@service-properties/generated/schemas/enti
import type { EntityType } from '@service-properties/generated/schemas/entityType';
import type { PropertyDefinition } from '@service-properties/generated/schemas/propertyDefinition';
import type { PropertyDefinitionDetailResponse } from '@service-properties/generated/schemas/propertyDefinitionDetailResponse';
+import type { PropertyDefinitionWithOptions } from '@service-properties/generated/schemas/propertyDefinitionWithOptions';
import type { PropertyOptionResponse } from '@service-properties/generated/schemas/propertyOptionResponse';
import type { TagScope } from '@service-properties/generated/schemas/tagScope';
import { mergeRefs } from '@solid-primitives/refs';
@@ -85,11 +86,11 @@ import {
hasPropertyEditorPropertyAddedHandler,
notifyPropertyEditorPropertyAdded,
type PropertyEditorEntity,
+ type PropertyEditorState,
propertyEditorOpen,
propertyEditorState,
setPropertyEditorMode,
setPropertyEditorTarget,
- togglePropertyEditor,
} from './state/propertyEditor';
type TagOptionItem = {
@@ -209,22 +210,8 @@ function propertyEditorEntityName(entity: PropertyEditorEntity): string {
}
export function PropertyEditorModal() {
- const [dialogRef, setDialogRef] = createSignal<HTMLElement | undefined>();
- const [attach, hotkeyScope] = useHotkeyDOMScope('property-editor');
- const [searchValue, setSearchValue] = createSignal('');
- const [selectedIndex, setSelectedIndex] = createSignal(0);
- const [inputType, setInputType] = createSignal<'text' | 'number'>('text');
- const [createPropertyInitialName, setCreatePropertyInitialName] =
- createSignal<string | null>(null);
-
- const defaultPlaceholder = 'Choose a property...';
- const [placeholder, setPlaceholder] = createSignal('');
-
const saveProperties = useSavePropertyForMultiEntitites();
- const handlePropertySave = (
- value: PropertyApiValues,
- event?: KeyboardEvent | MouseEvent
- ) => {
+ const handlePropertySave = (value: PropertyApiValues) => {
const { selectedEntities, targetProperty } = propertyEditorState;
if (!selectedEntities.length || !targetProperty) return;
@@ -244,7 +231,67 @@ export function PropertyEditorModal() {
),
'property-editor'
);
- if (!event?.shiftKey) closePropertyEditor();
+ };
+
+ return (
+ <PropertyEditorDialog
+ isOpen={propertyEditorOpen()}
+ state={propertyEditorState}
+ onModeChange={setPropertyEditorMode}
+ onTargetChange={setPropertyEditorTarget}
+ onClose={closePropertyEditor}
+ onSave={(_property, value) => handlePropertySave(value)}
+ onPropertyAdded={
+ propertyEditorOpen() &&
+ propertyEditorState.selectedEntities.length === 1 &&
+ hasPropertyEditorPropertyAddedHandler()
+ ? notifyPropertyEditorPropertyAdded
+ : undefined
+ }
+ />
+ );
+}
+
+/** Shared property selection, creation and value editing for entities and drafts. */
+export function PropertyEditorDialog(props: {
+ isOpen: boolean;
+ state: PropertyEditorState;
+ onModeChange: (mode: PropertyEditorState['mode']) => void;
+ onTargetChange: (property: Property | PropertyDefinitionDomain) => void;
+ onClose: () => void;
+ onSave: (
+ property: Property | PropertyDefinitionDomain,
+ value: PropertyApiValues,
+ event?: KeyboardEvent | MouseEvent
+ ) => void;
+ onPropertyAdded?: (ids?: string[]) => void | Promise<void>;
+ onPropertyCreated?: (
+ property: PropertyDefinitionWithOptions
+ ) => void | Promise<void>;
+ availableProperties?: PropertyDefinitionDomain[];
+ properties?: Property[];
+ name?: string;
+}) {
+ const [dialogRef, setDialogRef] = createSignal<HTMLElement | undefined>();
+ const [attach, hotkeyScope] = useHotkeyDOMScope('property-editor');
+ const [searchValue, setSearchValue] = createSignal('');
+ const [selectedIndex, setSelectedIndex] = createSignal(0);
+ const [inputType, setInputType] = createSignal<'text' | 'number'>('text');
+ const [createPropertyInitialName, setCreatePropertyInitialName] =
+ createSignal<string | null>(null);
+ const defaultPlaceholder = 'Choose a property...';
+ const [placeholder, setPlaceholder] = createSignal('');
+ let editorRevision = 0;
+ onCleanup(() => editorRevision++);
+
+ const handlePropertySave = (
+ value: PropertyApiValues,
+ event?: KeyboardEvent | MouseEvent
+ ) => {
+ const property = props.state.targetProperty;
+ if (!property) return;
+ props.onSave(property, value, event);
+ if (!event?.shiftKey) props.onClose();
};
const openCreateProperty = (initialName: string) => {
@@ -258,47 +305,47 @@ export function PropertyEditorModal() {
setCreatePropertyInitialName(null);
if (!propertyDefinition) return;
+ const revision = editorRevision;
const createdDefinitionId = propertyDefinition.id;
- const shouldNotifySelectedEntity = Boolean(
- hasPropertyEditorPropertyAddedHandler() &&
- propertyEditorState.selectedEntities.length === 1
- );
+ const shouldNotifySelectedEntity =
+ !props.onPropertyCreated && Boolean(props.onPropertyAdded);
if (shouldNotifySelectedEntity) {
try {
- await notifyPropertyEditorPropertyAdded([createdDefinitionId]);
+ await props.onPropertyAdded?.([createdDefinitionId]);
} catch (error) {
console.error('Failed to add created property to entity', error);
}
}
+ let created: PropertyDefinitionWithOptions = {
+ definition: propertyDefinition,
+ property_options: [],
+ };
try {
const propertyWithOptions =
await fetchPropertyDefinitionWithOptions(createdDefinitionId);
-
if (propertyWithOptions && 'definition' in propertyWithOptions) {
- setPropertyEditorMode('direct');
- setPropertyEditorTarget(
- toPropertyDefinitionDomain(
- propertyWithOptions.definition,
- propertyWithOptions.property_options
- )
- );
- return;
+ created = propertyWithOptions;
}
} catch (error) {
console.error('Failed to fetch created property options', error);
}
- setPropertyEditorMode('direct');
- setPropertyEditorTarget(toPropertyDefinitionDomain(propertyDefinition));
+ if (!props.isOpen || revision !== editorRevision) return;
+ await props.onPropertyCreated?.(created);
+ if (!props.isOpen || revision !== editorRevision) return;
+ props.onTargetChange(
+ toPropertyDefinitionDomain(created.definition, created.property_options)
+ );
+ props.onModeChange('direct');
};
const { dispose: disposeHotkey } = registerHotkey({
hotkey: ['escape'],
description: 'Close property editor',
keyDownHandler: () => {
- closePropertyEditor();
+ props.onClose();
return true;
},
scopeId: hotkeyScope,
@@ -306,7 +353,8 @@ export function PropertyEditorModal() {
onCleanup(disposeHotkey);
createEffect(
- on([() => propertyEditorState.mode, propertyEditorOpen], () => {
+ on([() => props.state.mode, () => props.isOpen], () => {
+ editorRevision++;
setSelectedIndex(0);
setSearchValue('');
setPlaceholder('');
@@ -318,8 +366,10 @@ export function PropertyEditorModal() {
return (
<Dialog
- open={propertyEditorOpen()}
- onOpenChange={togglePropertyEditor}
+ open={props.isOpen}
+ onOpenChange={(open) => {
+ if (!open) props.onClose();
+ }}
contentRef={mergeRefs(attach, setDialogRef)}
>
<CommandMenuShell depth={2} class="rounded-xl max-h-108 text-sm">
@@ -337,13 +387,18 @@ export function PropertyEditorModal() {
/>
</CommandMenuShell.Header>
<CommandMenuShell.Toolbar class="p-3 py-2 border-b-0">
- <EditingEntityPreview
- entities={propertyEditorState.selectedEntities}
- />
+ <Show
+ when={props.name}
+ fallback={
+ <EditingEntityPreview entities={props.state.selectedEntities} />
+ }
+ >
+ <span class="truncate text-ink-muted">{props.name}</span>
+ </Show>
</CommandMenuShell.Toolbar>
<CommandMenuShell.Body>
<Switch>
- <Match when={propertyEditorState.mode === 'selector'}>
+ <Match when={props.state.mode === 'selector'}>
<div class="overflow-scroll scrollbar-hidden">
<PropertyList
searchTerm={searchValue()}
@@ -351,22 +406,30 @@ export function PropertyEditorModal() {
setFocusedIndex={setSelectedIndex}
setKeybindings={keybindings}
onCreateProperty={openCreateProperty}
+ properties={props.availableProperties}
+ existingPropertyIds={props.properties?.map(
+ (p) => p.propertyDefinitionId
+ )}
+ onTagSelected={
+ !props.onPropertyAdded &&
+ props.state.selectedEntities.length > 0 &&
+ props.state.selectedEntities.every(canTagEntity)
+ ? () => props.onModeChange('tag')
+ : undefined
+ }
onPropertySelected={async (property) => {
- if (
- hasPropertyEditorPropertyAddedHandler() &&
- propertyEditorState.selectedEntities.length === 1
- ) {
- await notifyPropertyEditorPropertyAdded([
- propertyIdentity(property),
- ]);
- }
+ const revision = editorRevision;
+ await props.onPropertyAdded?.([propertyIdentity(property)]);
+ if (!props.isOpen || revision !== editorRevision) return;
+ props.onTargetChange(property);
+ props.onModeChange('direct');
}}
/>
</div>
</Match>
- <Match when={propertyEditorState.mode === 'direct'}>
+ <Match when={props.state.mode === 'direct'}>
<PropertyValueEditor
- property={propertyEditorState.targetProperty}
+ property={props.state.targetProperty}
searchValue={searchValue}
setSearchValue={setSearchValue}
selectedIndex={selectedIndex}
@@ -375,12 +438,13 @@ export function PropertyEditorModal() {
setPlaceholder={setPlaceholder}
setInputType={setInputType}
onSave={handlePropertySave}
- selectedEntities={propertyEditorState.selectedEntities}
+ selectedEntities={props.state.selectedEntities}
+ properties={props.properties}
/>
</Match>
- <Match when={propertyEditorState.mode === 'tag'}>
+ <Match when={props.state.mode === 'tag'}>
<TagAssignmentEditor
- entities={propertyEditorState.selectedEntities}
+ entities={props.state.selectedEntities}
searchValue={searchValue}
selectedIndex={selectedIndex}
setSelectedIndex={setSelectedIndex}
@@ -445,26 +509,28 @@ function PropertyList(props: {
setFocusedIndex: Setter<number>;
setKeybindings: (navAction: ListNavActions) => void;
onCreateProperty: (initialName: string) => void;
- onPropertySelected?: (
+ onPropertySelected: (
property: Property | PropertyDefinitionDomain
) => void | Promise<void>;
+ onTagSelected?: () => void;
+ properties?: PropertyDefinitionDomain[];
+ existingPropertyIds?: string[];
}) {
- const properties = useAllProperties();
+ const allProperties = useAllProperties(() => !props.properties);
+ const properties = () => props.properties ?? allProperties();
const { filteredProperties } = usePropertySelection(
- () => [],
+ () => props.existingPropertyIds ?? [],
properties,
- () => props.searchTerm
+ () => props.searchTerm,
+ () => props.properties !== undefined
);
const showTagAssignmentOption = createMemo(() => {
- if (hasPropertyEditorPropertyAddedHandler()) return false;
+ if (!props.onTagSelected) return false;
const query = props.searchTerm.toLowerCase().trim();
- return (
- propertyEditorState.selectedEntities.every(canTagEntity) &&
- (!query || 'tags'.includes(query) || 'label'.includes(query))
- );
+ return !query || 'tags'.includes(query) || 'label'.includes(query);
});
const createPropertyName = () => props.searchTerm.trim();
const exactPropertyMatchExists = () => {
@@ -510,12 +576,6 @@ function PropertyList(props: {
props.setFocusedIndex(0);
});
- const setProperty = async (property: Property | PropertyDefinitionDomain) => {
- await props.onPropertySelected?.(property);
- setPropertyEditorMode('direct');
- setPropertyEditorTarget(property);
- };
-
const selectRow = async (row: PropertyListRow) => {
if (row.type === 'create') {
props.onCreateProperty(row.name);
@@ -523,11 +583,11 @@ function PropertyList(props: {
}
if (row.type === 'tags') {
- setPropertyEditorMode('tag');
+ props.onTagSelected?.();
return;
}
- await setProperty(row.property);
+ await props.onPropertySelected(row.property);
};
const listController = createCommandListController({
@@ -1270,6 +1330,7 @@ function PropertyValueEditor(props: {
event?: KeyboardEvent | MouseEvent
) => void;
selectedEntities: PropertyEditorEntity[];
+ properties?: Property[];
}) {
const propertyType = () => props.property?.valueType;
const singleEntity = () =>
@@ -1289,8 +1350,9 @@ function PropertyValueEditor(props: {
if (!property) return undefined;
if ('value' in property) return property;
+ const properties = props.properties ?? entityPropertiesQuery.data ?? [];
return (
- entityPropertiesQuery.data?.find(
+ properties.find(
(entityProperty) => entityProperty.propertyDefinitionId === property.id
) ?? property
);
@@ -1322,7 +1384,9 @@ function PropertyValueEditor(props: {
onSubmit={handleSubmit}
setKeybindings={props.setKeybindings}
setPlaceholder={props.setPlaceholder}
- selectedEntityCount={props.selectedEntities.length}
+ selectedEntityCount={
+ props.properties ? 1 : props.selectedEntities.length
+ }
onSave={props.onSave}
/>
</Match>
@@ -1336,7 +1400,9 @@ function PropertyValueEditor(props: {
onSubmit={handleSubmit}
setKeybindings={props.setKeybindings}
setPlaceholder={props.setPlaceholder}
- selectedEntityCount={props.selectedEntities.length}
+ selectedEntityCount={
+ props.properties ? 1 : props.selectedEntities.length
+ }
onSave={props.onSave}
/>
</Match>
diff --git a/apps/web/src/features/property/editor/hooks/useAllProperties.ts b/apps/web/src/features/property/editor/hooks/useAllProperties.ts
index 92ccd349cd..759fd19619 100644
--- a/apps/web/src/features/property/editor/hooks/useAllProperties.ts
+++ b/apps/web/src/features/property/editor/hooks/useAllProperties.ts
@@ -1,16 +1,16 @@
import type { PropertyDefinitionDomain } from '@property/types';
-import { toPropertyDefinitionDomain } from '@property/utils';
+import { toPropertyDefinitionDomain } from '@property/utils/transforms';
import { useListPropertiesQuery } from '@queries/properties/definitions';
-import { createMemo } from 'solid-js';
+import { type Accessor, createMemo } from 'solid-js';
-export function useAllProperties() {
- const query = useListPropertiesQuery(() => ({
- scope: 'all',
- includeOptions: true,
- }));
+export function useAllProperties(enabled: Accessor<boolean> = () => true) {
+ const query = useListPropertiesQuery(
+ () => ({ scope: 'all', includeOptions: true }),
+ enabled
+ );
return createMemo<PropertyDefinitionDomain[]>(() => {
- if (query.isLoading || query.isError || !query.data) {
+ if (!query.isSuccess) {
return [];
}
diff --git a/apps/web/src/features/property/editor/state/propertyEditor.ts b/apps/web/src/features/property/editor/state/propertyEditor.ts
index cdf74fe63f..714cd88ed2 100644
--- a/apps/web/src/features/property/editor/state/propertyEditor.ts
+++ b/apps/web/src/features/property/editor/state/propertyEditor.ts
@@ -18,7 +18,7 @@ export type PropertyEditorEntity =
export const [propertyEditorOpen, setPropertyEditorOpen] =
createControlledOpenSignal(false, { id: 'property-edit' });
-interface PropertyEditorState {
+export interface PropertyEditorState {
mode: PropertyEditorMode;
selectedEntities: PropertyEditorEntity[];
targetProperty?: Property | PropertyDefinitionDomain;
diff --git a/apps/web/src/features/property/hooks/usePropertySelection.ts b/apps/web/src/features/property/hooks/usePropertySelection.ts
index 7eec48363d..b210dfedbe 100644
--- a/apps/web/src/features/property/hooks/usePropertySelection.ts
+++ b/apps/web/src/features/property/hooks/usePropertySelection.ts
@@ -5,7 +5,8 @@ import type { PropertyDefinitionDomain } from '../types';
export function usePropertySelection(
existingPropertyIds: () => string[],
availableProperties: Accessor<PropertyDefinitionDomain[]>,
- searchQuery?: () => string
+ searchQuery?: () => string,
+ includeProject: Accessor<boolean> = () => false
) {
const [selectedPropertyIds, setSelectedPropertyIds] = createSignal<
Set<string>
@@ -27,8 +28,8 @@ export function usePropertySelection(
// Tag definitions are managed through the dedicated Tags UI, never the
// generic property pickers.
property.valueType !== 'TAG' &&
- // A task always lists Project, and nothing else can carry it.
- property.id !== SYSTEM_PROPERTY_IDS.PROJECT
+ // Entity panels show Project separately; explicit draft catalogs can include it.
+ (property.id !== SYSTEM_PROPERTY_IDS.PROJECT || includeProject())
);
// Then apply search filter
diff --git a/apps/web/src/features/task-composer/core/context.ts b/apps/web/src/features/task-composer/core/context.ts
new file mode 100644
index 0000000000..23a1d04c98
--- /dev/null
+++ b/apps/web/src/features/task-composer/core/context.ts
@@ -0,0 +1,8 @@
+import type { PropertyApiValues } from '@property/types';
+
+/** Plain, cloneable preset data supplied by the originating view. */
+export type TaskComposerContext = {
+ key: string;
+ visiblePropertyIds?: string[];
+ initialPropertyValues?: Record<string, PropertyApiValues>;
+};
diff --git a/apps/web/src/lib/core/constant/featureFlags.ts b/apps/web/src/lib/core/constant/featureFlags.ts
index 09bbb89f54..6cbbc59d91 100644
--- a/apps/web/src/lib/core/constant/featureFlags.ts
+++ b/apps/web/src/lib/core/constant/featureFlags.ts
@@ -457,6 +457,12 @@ export const enableCrm = defineFlag({
default: onInDev,
});
+/** CRM activity tabs and context-aware task composition. Off until opted in. */
+export const enableCrmActivity = defineFlag({
+ key: 'enable-crm-activity',
+ env: 'ENABLE_CRM_ACTIVITY',
+});
+
// Company collections are paused until ready; preserve stored lists while off.
export const enableCrmLists = defineFlag({
key: 'enable-crm-lists',
diff --git a/apps/web/src/lib/queries/soup/graphql/grouped-local-projection.test.ts b/apps/web/src/lib/queries/soup/graphql/grouped-local-projection.test.ts
index c365c61bdb..2ae5c856fa 100644
--- a/apps/web/src/lib/queries/soup/graphql/grouped-local-projection.test.ts
+++ b/apps/web/src/lib/queries/soup/graphql/grouped-local-projection.test.ts
@@ -88,6 +88,26 @@ describe('loaded grouped pages', () => {
});
describe('local grouped Soup projection', () => {
+ it('retains server membership for an unknown grouping field', () => {
+ const futureInput: GroupedSoupInitialInput = JSON.parse(
+ '{"groupBy":{"field":"FUTURE"},"sortMethod":"UPDATED_AT"}'
+ );
+ const item = groupedDocument('a');
+ const baseline = [
+ { key: 'server-group', items: [item], totalCount: 1, nextCursor: null },
+ ];
+
+ expect(localSoupGroupKeys(item, futureInput, now)).toBeUndefined();
+ expect(
+ projectLocalGroupedSoup(
+ baseline,
+ new Map(),
+ snapshot([item]),
+ futureInput,
+ now
+ )
+ ).toEqual(baseline);
+ });
it('moves normalized rows and removes filter nonmatches without losing unknown rows', () => {
const a = groupedDocument('a');
const b = groupedDocument('b');
diff --git a/apps/web/src/routes/shells.tsx b/apps/web/src/routes/shells.tsx
index 8edc4ef1b8..037f8d9d33 100644
--- a/apps/web/src/routes/shells.tsx
+++ b/apps/web/src/routes/shells.tsx
@@ -1,7 +1,12 @@
+import { CreateContextProvider } from '@app/features/command/context/create-context';
import { SplitRouter } from '@app/lib/split-router';
+import { AppProviders } from '@components/app/AppProviders';
import { dismissBootShell } from '@components/app/boot-shell';
import { AppChrome, PageContent } from '@components/app/Layout';
-import { SplitLayout } from '@components/app/split-layout/SplitLayout';
+import {
+ SplitLayout,
+ SplitLayoutProvider,
+} from '@components/app/split-layout/SplitLayout';
import { useIsAuthenticated } from '@core/auth';
import { ImperativeDialogHost } from '@ui';
import { type JSX, onCleanup, onMount, type ParentProps, Show } from 'solid-js';
@@ -62,9 +67,13 @@ export function withFormRespondShell(Page: () => JSX.Element) {
</FocusedPage>
}
>
- <AppPage>
- <Page />
- </AppPage>
+ <AppProviders>
+ <CreateContextProvider focusedPaneId={() => undefined}>
+ <AppPage>
+ <Page />
+ </AppPage>
+ </CreateContextProvider>
+ </AppProviders>
</Show>
);
};
@@ -139,8 +148,12 @@ function warmRouteViews(views: readonly PreloadableView[]): void {
export function AppShell(): JSX.Element {
warmRouteViews(LIKELY_NEXT_VIEWS);
return (
- <AppPage>
- <SplitLayout />
- </AppPage>
+ <AppProviders>
+ <SplitLayoutProvider>
+ <AppPage>
+ <SplitLayout />
+ </AppPage>
+ </SplitLayoutProvider>
+ </AppProviders>
);
}
diff --git a/crates/email/src/outbound/email_pg_repo/dynamic.rs b/crates/email/src/outbound/email_pg_repo/dynamic.rs
index 1e57de347a..761f27a126 100644
--- a/crates/email/src/outbound/email_pg_repo/dynamic.rs
+++ b/crates/email/src/outbound/email_pg_repo/dynamic.rs
@@ -27,6 +27,7 @@ enum SqlSegment {
Raw(String),
BindViewer,
BindString(String),
+ BindStringArray(Vec<String>),
BindUuid(Uuid),
BindUuidArray(Vec<Uuid>),
}
@@ -58,6 +59,12 @@ impl SqlFragment {
}
}
+ fn bind_string_array(values: Vec<String>) -> Self {
+ Self {
+ segments: vec![SqlSegment::BindStringArray(values)],
+ }
+ }
+
fn bind_uuid(u: Uuid) -> Self {
Self {
segments: vec![SqlSegment::BindUuid(u)],
@@ -128,6 +135,9 @@ impl SqlFragment {
SqlSegment::BindString(s) => {
builder.push_bind(s);
}
+ SqlSegment::BindStringArray(values) => {
+ builder.push_bind(values);
+ }
SqlSegment::BindUuid(u) => {
builder.push_bind(u);
}
@@ -155,6 +165,10 @@ impl SqlFragment {
bind_idx += 1;
result.push_str(&format!("${bind_idx}[str={s}]"));
}
+ SqlSegment::BindStringArray(values) => {
+ bind_idx += 1;
+ result.push_str(&format!("${bind_idx}[str_array={values:?}]"));
+ }
SqlSegment::BindUuid(u) => {
bind_idx += 1;
result.push_str(&format!("${bind_idx}[uuid={u}]"));
@@ -174,9 +188,11 @@ impl SqlFragment {
}
fn has_bind_string(&self, expected: &str) -> bool {
- self.segments
- .iter()
- .any(|s| matches!(s, SqlSegment::BindString(v) if v == expected))
+ self.segments.iter().any(|segment| match segment {
+ SqlSegment::BindString(value) => value == expected,
+ SqlSegment::BindStringArray(values) => values.iter().any(|value| value == expected),
+ _ => false,
+ })
}
/// True if `expected` is bound somewhere in this fragment — either as a
diff --git a/crates/email/src/outbound/email_pg_repo/dynamic/filters.rs b/crates/email/src/outbound/email_pg_repo/dynamic/filters.rs
index 5712fbc0e5..47caa9f498 100644
--- a/crates/email/src/outbound/email_pg_repo/dynamic/filters.rs
+++ b/crates/email/src/outbound/email_pg_repo/dynamic/filters.rs
@@ -1,3 +1,4 @@
+mod address_groups;
use super::SqlFragment;
use super::resolve::ResolvedFilters;
use crate::domain::models::{PreviewView, PreviewViewStandardLabel};
@@ -273,6 +274,9 @@ fn build_candidate_pair_predicate(
sort_ts_field: &str,
resolved: &ResolvedFilters,
) -> SqlFragment {
+ if let Some(literals) = flatten_or_tree_of_address_literals(ast) {
+ return address_groups::message_predicate(literals, resolved);
+ }
ast.collapse_frames(|frame| match frame {
filter_ast::ExprFrame::And(a, b) => SqlFragment::and(a, b),
filter_ast::ExprFrame::Or(a, b) => SqlFragment::or(a, b),
@@ -324,6 +328,9 @@ pub(super) fn build_message_email_filter(
resolved: &ResolvedFilters,
sort_ts_field: &str,
) -> SqlFragment {
+ if let Some(literals) = flatten_or_tree_of_address_literals(ast) {
+ return address_groups::message_predicate(literals, resolved).with_and_prefix();
+ }
let fragment = ast.collapse_frames(|frame| match frame {
filter_ast::ExprFrame::And(a, b) => SqlFragment::and(a, b),
filter_ast::ExprFrame::Or(a, b) => SqlFragment::or(a, b),
@@ -403,6 +410,9 @@ fn build_address_message_predicate(
expr: &Expr<EmailLiteral>,
resolved: &ResolvedFilters,
) -> SqlFragment {
+ if let Some(literals) = flatten_or_tree_of_address_literals(expr) {
+ return address_groups::message_predicate(literals, resolved);
+ }
expr.collapse_frames(|frame| match frame {
filter_ast::ExprFrame::And(a, b) => SqlFragment::and(a, b),
filter_ast::ExprFrame::Or(a, b) => SqlFragment::or(a, b),
@@ -532,7 +542,7 @@ fn flatten_or_tree_of_address_literals(
/// Which roles (sender / TO / CC / BCC) one address predicate was requested
/// in across the OR-tree. Merging roles lets the CTE emit a single recipient
/// branch per address instead of one per role.
-#[derive(Default)]
+#[derive(Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
struct AddressKinds {
sender: bool,
to: bool,
@@ -576,34 +586,6 @@ impl AddressKinds {
}
}
-/// Identity of an address predicate for grouping OR'd literals: two literals
-/// with equal keys match the same contact rows, so their branches can share
-/// contact-resolution work.
-#[derive(PartialEq)]
-enum AddressGroupKey<'a> {
- /// Complete email resolved to contact ids.
- Contacts(&'a [Uuid]),
- /// Partial text match (source string of the ILIKE pattern).
- Partial(&'a str),
- /// Bare domain, lowercased.
- Domain(String),
-}
-
-/// Returns `None` for unresolved Complete emails — they can't match
-/// anything, so the literal is dropped rather than emitting a `WHERE FALSE`
-/// branch.
-fn address_group_key<'a>(
- email: &'a Email,
- resolved: &'a ResolvedFilters,
-) -> Option<AddressGroupKey<'a>> {
- match (resolved.contact_ids_for(email), email) {
- (Some(ids), _) => Some(AddressGroupKey::Contacts(ids)),
- (None, Email::Complete(_)) => None,
- (None, Email::Partial(s)) => Some(AddressGroupKey::Partial(s)),
- (None, Email::Domain(s)) => Some(AddressGroupKey::Domain(s.to_ascii_lowercase())),
- }
-}
-
/// Sender branch over resolved contact ids — probes
/// `idx_email_messages_from_contact_id`.
fn contacts_sender_branch(contact_ids: &[Uuid], resolved: &ResolvedFilters) -> SqlFragment {
@@ -707,9 +689,8 @@ fn text_recipient_branch(
/// Emits one text-matched group: a hoisted contacts CTE plus the branches
/// that consume it.
-fn push_text_group(
- predicate_prefix: &str,
- bind_value: String,
+fn push_contact_group(
+ contact_query: SqlFragment,
kinds: &AddressKinds,
resolved: &ResolvedFilters,
link_scope: Option<&[Uuid]>,
@@ -717,10 +698,7 @@ fn push_text_group(
branches: &mut Vec<SqlFragment>,
) {
let cte_name = format!("matching_contacts_{}", contact_ctes.len());
- contact_ctes.push((
- cte_name.clone(),
- matching_contacts_cte_body(predicate_prefix, bind_value, link_scope),
- ));
+ contact_ctes.push((cte_name.clone(), contact_query));
if kinds.sender {
branches.push(text_sender_branch(&cte_name, resolved, link_scope));
}
@@ -748,16 +726,11 @@ pub(super) struct MatchingThreadsCtes {
/// 1. **UNION-of-branches** (preferred): when the candidate filter is a
/// single conjunct that's a flat OR-tree of positive single-address
/// literals (e.g. `Sender(X) OR Cc(X) OR Bcc(X) OR Recipient(X)`),
-/// literals are grouped by address predicate and each group becomes at
-/// most two UNION branches: a sender branch and one merged recipient
-/// branch covering every requested recipient role (with no
-/// `recipient_type` filter at all when all three roles are present).
-/// Complete-email branches are index-driven via
-/// `idx_email_messages_from_contact_id` /
-/// `idx_email_message_recipients_contact_id`; Partial/Domain predicates
-/// resolve contacts once in a hoisted `matching_contacts_N` CTE (riding
-/// the trigram / domain expression index) that both branches consume,
-/// instead of re-scanning `email_contacts` per branch.
+/// predicates first collect their requested roles. Complete addresses and
+/// domains with identical role sets then share membership branches, keeping
+/// query size bounded for large CRMs. Complete-email branches use the
+/// contact-id indexes; domains resolve contacts once per role set in a
+/// hoisted `matching_contacts_N` CTE. Partial matches remain independent.
/// 2. **Combined predicate**: for everything else (multiple AND conjuncts,
/// NOT inside a conjunct, mixed nested operators) we emit a single
/// `SELECT DISTINCT m.thread_id FROM email_messages m WHERE …` whose
@@ -786,61 +759,7 @@ pub(super) fn build_matching_threads_ctes(
if conjuncts.len() == 1
&& let Some(literals) = flatten_or_tree_of_address_literals(conjuncts[0])
{
- // Group literals by address predicate so one address requested in
- // several roles (the common "this address anywhere" case) shares
- // branches and contact-resolution work.
- let mut groups: Vec<(AddressGroupKey, AddressKinds)> = Vec::new();
- for (kind, email) in literals {
- let Some(key) = address_group_key(email, resolved) else {
- continue;
- };
- match groups.iter_mut().find(|(k, _)| *k == key) {
- Some((_, kinds)) => kinds.add(kind),
- None => {
- let mut kinds = AddressKinds::default();
- kinds.add(kind);
- groups.push((key, kinds));
- }
- }
- }
-
- let mut contact_ctes: Vec<(String, SqlFragment)> = Vec::new();
- let mut branches: Vec<SqlFragment> = Vec::new();
- for (key, kinds) in &groups {
- match key {
- AddressGroupKey::Contacts(ids) => {
- if kinds.sender {
- branches.push(contacts_sender_branch(ids, resolved));
- }
- if kinds.any_recipient() {
- branches.push(contacts_recipient_branch(ids, kinds, resolved));
- }
- }
- AddressGroupKey::Partial(s) => {
- let pattern = format!("%{}%", escape_like_pattern(s));
- push_text_group(
- "c.email_address ILIKE ",
- pattern,
- kinds,
- resolved,
- link_scope,
- &mut contact_ctes,
- &mut branches,
- );
- }
- AddressGroupKey::Domain(domain) => {
- push_text_group(
- "LOWER(SPLIT_PART(c.email_address, '@', 2)) = ",
- domain.clone(),
- kinds,
- resolved,
- link_scope,
- &mut contact_ctes,
- &mut branches,
- );
- }
- }
- }
+ let (contact_ctes, branches) = address_groups::build(literals, resolved, link_scope);
if !branches.is_empty() {
let mut iter = branches.into_iter();
diff --git a/crates/email/src/outbound/email_pg_repo/dynamic/filters/address_groups.rs b/crates/email/src/outbound/email_pg_repo/dynamic/filters/address_groups.rs
new file mode 100644
index 0000000000..67b9317069
--- /dev/null
+++ b/crates/email/src/outbound/email_pg_repo/dynamic/filters/address_groups.rs
@@ -0,0 +1,224 @@
+//! Compact membership branches for positive OR-only address filters.
+
+use std::collections::BTreeMap;
+
+use item_filters::ast::email::Email;
+use uuid::Uuid;
+
+use super::{
+ AddressKind, AddressKinds, ResolvedFilters, SqlFragment, build_address_predicate_on_m,
+ contacts_recipient_branch, contacts_sender_branch, escape_like_pattern, link_scope_fragment,
+ matching_contacts_cte_body, push_contact_group,
+};
+
+#[derive(PartialEq, Eq, PartialOrd, Ord)]
+enum AddressKey<'a> {
+ Contacts(&'a [Uuid]),
+ Partial(&'a str),
+ Domain(String),
+}
+
+fn address_key<'a>(email: &'a Email, resolved: &'a ResolvedFilters) -> Option<AddressKey<'a>> {
+ match (resolved.contact_ids_for(email), email) {
+ (Some(ids), _) => Some(AddressKey::Contacts(ids)),
+ (None, Email::Complete(_)) => None,
+ (None, Email::Partial(value)) => Some(AddressKey::Partial(value)),
+ (None, Email::Domain(value)) => Some(AddressKey::Domain(value.to_ascii_lowercase())),
+ }
+}
+
+#[derive(Default)]
+struct Members {
+ contact_ids: Vec<Uuid>,
+ domains: Vec<String>,
+}
+
+#[derive(Default)]
+struct Groups<'a> {
+ memberships: BTreeMap<AddressKinds, Members>,
+ partials: Vec<(&'a str, AddressKinds)>,
+}
+
+fn group<'a>(literals: Vec<(AddressKind, &'a Email)>, resolved: &'a ResolvedFilters) -> Groups<'a> {
+ // First merge roles for the same predicate. A tree with thousands of
+ // addresses must not perform a linear scan of earlier addresses per leaf.
+ let mut groups = BTreeMap::<AddressKey, AddressKinds>::new();
+ for (kind, email) in literals {
+ if let Some(key) = address_key(email, resolved) {
+ groups.entry(key).or_default().add(kind);
+ }
+ }
+
+ let mut result = Groups::default();
+ for (key, kinds) in groups {
+ match key {
+ AddressKey::Contacts(ids) => result
+ .memberships
+ .entry(kinds)
+ .or_default()
+ .contact_ids
+ .extend_from_slice(ids),
+ AddressKey::Domain(domain) => {
+ result
+ .memberships
+ .entry(kinds)
+ .or_default()
+ .domains
+ .push(domain);
+ }
+ AddressKey::Partial(value) => result.partials.push((value, kinds)),
+ }
+ }
+ for members in result.memberships.values_mut() {
+ members.contact_ids.sort_unstable();
+ members.contact_ids.dedup();
+ }
+ result
+}
+
+pub(super) fn build(
+ literals: Vec<(AddressKind, &Email)>,
+ resolved: &ResolvedFilters,
+ link_scope: Option<&[Uuid]>,
+) -> (Vec<(String, SqlFragment)>, Vec<SqlFragment>) {
+ let Groups {
+ memberships,
+ partials,
+ } = group(literals, resolved);
+ let mut contact_ctes = Vec::new();
+ let mut branches = Vec::new();
+ for (value, kinds) in partials {
+ push_contact_group(
+ matching_contacts_cte_body(
+ "c.email_address ILIKE ",
+ format!("%{}%", escape_like_pattern(value)),
+ link_scope,
+ ),
+ &kinds,
+ resolved,
+ link_scope,
+ &mut contact_ctes,
+ &mut branches,
+ );
+ }
+
+ // Only identical role sets share a membership list: combining Sender(A)
+ // with Cc(B) must not admit Sender(B) or Cc(A).
+ for (kinds, members) in memberships {
+ if !members.contact_ids.is_empty() {
+ if kinds.sender {
+ branches.push(contacts_sender_branch(&members.contact_ids, resolved));
+ }
+ if kinds.any_recipient() {
+ branches.push(contacts_recipient_branch(
+ &members.contact_ids,
+ &kinds,
+ resolved,
+ ));
+ }
+ }
+ if !members.domains.is_empty() {
+ let contact_query = domain_contacts(members.domains, link_scope);
+ push_contact_group(
+ contact_query,
+ &kinds,
+ resolved,
+ link_scope,
+ &mut contact_ctes,
+ &mut branches,
+ );
+ }
+ }
+ (contact_ctes, branches)
+}
+
+fn domain_contacts(domains: Vec<String>, link_scope: Option<&[Uuid]>) -> SqlFragment {
+ if let [domain] = domains.as_slice() {
+ return matching_contacts_cte_body(
+ "LOWER(SPLIT_PART(c.email_address, '@', 2)) = ",
+ domain.clone(),
+ link_scope,
+ );
+ }
+ let mut query = SqlFragment::raw(
+ "SELECT c.id FROM email_contacts c \
+ WHERE LOWER(SPLIT_PART(c.email_address, '@', 2)) = ANY(",
+ );
+ query.extend(SqlFragment::bind_string_array(domains));
+ query.push_raw(")");
+ query.extend(link_scope_fragment("c", link_scope));
+ query
+}
+
+/// Match the particular message selected by the LATERAL, not just its thread.
+/// Reusing only the matching_threads CTE here would admit unrelated messages.
+pub(super) fn message_predicate(
+ literals: Vec<(AddressKind, &Email)>,
+ resolved: &ResolvedFilters,
+) -> SqlFragment {
+ let Groups {
+ memberships,
+ partials,
+ } = group(literals, resolved);
+ let mut predicates = Vec::new();
+ for (value, kinds) in partials {
+ let email = Email::Partial(value.to_owned());
+ for (enabled, kind) in [
+ (kinds.sender, AddressKind::Sender),
+ (kinds.to, AddressKind::Recipient),
+ (kinds.cc, AddressKind::Cc),
+ (kinds.bcc, AddressKind::Bcc),
+ ] {
+ if enabled {
+ predicates.push(build_address_predicate_on_m(kind, &email, resolved));
+ }
+ }
+ }
+ for (kinds, members) in memberships {
+ if !members.contact_ids.is_empty() {
+ if kinds.sender {
+ let mut predicate = SqlFragment::raw("m.from_contact_id = ANY(");
+ predicate.extend(SqlFragment::bind_uuid_array(members.contact_ids.clone()));
+ predicate.push_raw(")");
+ predicates.push(predicate);
+ }
+ if kinds.any_recipient() {
+ let mut predicate = SqlFragment::raw(format!(
+ "EXISTS (SELECT 1 FROM email_message_recipients mr WHERE mr.message_id = m.id{} AND mr.contact_id = ANY(",
+ kinds.recipient_type_sql()
+ ));
+ predicate.extend(SqlFragment::bind_uuid_array(members.contact_ids));
+ predicate.push_raw("))");
+ predicates.push(predicate);
+ }
+ }
+ if !members.domains.is_empty() {
+ if kinds.sender {
+ predicates.push(message_domains(&members.domains, None));
+ }
+ if kinds.any_recipient() {
+ predicates.push(message_domains(&members.domains, Some(kinds)));
+ }
+ }
+ }
+ predicates
+ .into_iter()
+ .reduce(SqlFragment::or)
+ .unwrap_or_else(|| SqlFragment::raw("FALSE"))
+}
+
+fn message_domains(domains: &[String], recipients: Option<AddressKinds>) -> SqlFragment {
+ let mut predicate = match recipients {
+ None => SqlFragment::raw(
+ "EXISTS (SELECT 1 FROM email_contacts c WHERE c.id = m.from_contact_id AND ",
+ ),
+ Some(kinds) => SqlFragment::raw(format!(
+ "EXISTS (SELECT 1 FROM email_message_recipients mr JOIN email_contacts c ON c.id = mr.contact_id WHERE mr.message_id = m.id{} AND ",
+ kinds.recipient_type_sql()
+ )),
+ };
+ predicate.push_raw("LOWER(SPLIT_PART(c.email_address, '@', 2)) = ANY(");
+ predicate.extend(SqlFragment::bind_string_array(domains.to_vec()));
+ predicate.push_raw("))");
+ predicate
+}
diff --git a/crates/email/src/outbound/email_pg_repo/dynamic/tests.rs b/crates/email/src/outbound/email_pg_repo/dynamic/tests.rs
index b7e4ea0257..dbfb13ba0f 100644
--- a/crates/email/src/outbound/email_pg_repo/dynamic/tests.rs
+++ b/crates/email/src/outbound/email_pg_repo/dynamic/tests.rs
@@ -438,7 +438,8 @@ fn test_build_message_email_filter_or() {
let result = build_message_email_filter(&expr, &resolved);
let debug = result.to_debug_sql();
- assert!(debug.contains("OR"));
+ assert!(debug.contains("ANY("));
+ assert!(!debug.contains(" OR "));
assert!(result.has_bind_uuid(&id1));
assert!(result.has_bind_uuid(&id2));
assert!(result.has_no_raw_containing("[email protected]"));
@@ -1328,7 +1329,7 @@ fn test_matching_threads_ctes_domain_all_roles_share_one_contact_scan() {
}
#[test]
-fn test_matching_threads_ctes_distinct_domains_get_separate_contact_ctes() {
+fn test_matching_threads_ctes_distinct_domains_share_a_contact_cte() {
let expr = Expr::or(
Expr::Literal(EmailLiteral::Sender(Email::Domain("acme.com".into()))),
Expr::Literal(EmailLiteral::Sender(Email::Domain("globex.com".into()))),
@@ -1338,7 +1339,8 @@ fn test_matching_threads_ctes_distinct_domains_get_separate_contact_ctes() {
let debug = body.to_debug_sql();
assert!(debug.contains("matching_contacts_0 AS MATERIALIZED"));
- assert!(debug.contains("matching_contacts_1 AS MATERIALIZED"));
+ assert!(!debug.contains("matching_contacts_1 AS MATERIALIZED"));
+ assert!(debug.contains("= ANY("));
assert!(body.has_bind_string("acme.com"));
assert!(body.has_bind_string("globex.com"));
}
diff --git a/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs b/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs
index 8c22943075..a7709ac781 100644
--- a/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs
+++ b/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic.rs
@@ -7,6 +7,7 @@ mod test;
mod database_row;
mod document_ids;
mod initiative;
+mod property_filter;
use database_row::{build_database_row_filter, database_row_opted_in, database_row_top_clause};
pub(in crate::outbound::pg_soup_repo) use document_ids::DocumentIdArrays;
@@ -1121,14 +1122,7 @@ pub(in crate::outbound::pg_soup_repo) fn build_properties_filter(
let Some(expr) = ast else {
return String::new();
};
- let formatting = expr.collapse_frames(|frame| match frame {
- filter_ast::ExprFrame::And(a, b) => format!("({a} AND {b})"),
- filter_ast::ExprFrame::Or(a, b) => format!("({a} OR {b})"),
- filter_ast::ExprFrame::Not(a) => format!("(NOT {a})"),
- filter_ast::ExprFrame::Literal(literal) => {
- property_literal_predicate(&literal, entity_id_sql)
- }
- });
+ let formatting = property_filter::predicate(expr, entity_id_sql);
if formatting.is_empty() {
String::new()
} else {
diff --git a/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic/property_filter.rs b/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic/property_filter.rs
new file mode 100644
index 0000000000..24321433e3
--- /dev/null
+++ b/crates/soup/src/outbound/pg_soup_repo/expanded/dynamic/property_filter.rs
@@ -0,0 +1,140 @@
+//! Batch positive OR membership without changing the property-filter AST.
+
+use std::collections::BTreeMap;
+
+use filter_ast::{Expr, ExprFrame};
+use item_filters::ast::properties::{EntityRefId, PropertiesLiteral, PropertyMatchValue};
+use recursion::CollapsibleExt;
+use uuid::Uuid;
+
+use super::{property_literal_predicate, sql_string_literal};
+
+pub(super) fn predicate(expr: &Expr<PropertiesLiteral>, entity_id_sql: &str) -> String {
+ // Fold once, retaining each maximal OR region until AND/NOT requires SQL.
+ // Re-scanning subtrees for eligible leaves is quadratic on mixed skew trees.
+ expr.collapse_frames(
+ |frame: ExprFrame<Disjunction, PropertiesLiteral>| match frame {
+ ExprFrame::And(left, right) => Disjunction::sql(format!(
+ "({} AND {})",
+ left.render(entity_id_sql),
+ right.render(entity_id_sql)
+ )),
+ ExprFrame::Or(left, right) => left.merge(right),
+ ExprFrame::Not(inner) => {
+ Disjunction::sql(format!("(NOT {})", inner.render(entity_id_sql)))
+ }
+ ExprFrame::Literal(literal) => Disjunction::literal(literal, entity_id_sql),
+ },
+ )
+ .render(entity_id_sql)
+}
+
+struct ReferenceGroup {
+ first: PropertiesLiteral,
+ ids: Vec<EntityRefId>,
+}
+
+#[derive(Default)]
+struct Disjunction {
+ references: BTreeMap<(Uuid, Option<String>), ReferenceGroup>,
+ others: Vec<String>,
+ terms: usize,
+}
+
+impl Disjunction {
+ fn sql(sql: String) -> Self {
+ Self {
+ others: vec![sql],
+ terms: 1,
+ ..Self::default()
+ }
+ }
+
+ fn literal(literal: PropertiesLiteral, entity_id_sql: &str) -> Self {
+ let PropertyMatchValue::EntityRef(id) = &literal.value else {
+ return Self::sql(property_literal_predicate(&literal, entity_id_sql));
+ };
+ let key = (
+ literal.property_definition_id,
+ literal.entity_type.map(|value| value.to_string()),
+ );
+ let group = ReferenceGroup {
+ ids: vec![id.clone()],
+ first: literal,
+ };
+ Self {
+ references: BTreeMap::from([(key, group)]),
+ others: Vec::new(),
+ terms: 1,
+ }
+ }
+
+ fn merge(mut self, mut other: Self) -> Self {
+ // Move the smaller side into the larger side, including skew OR trees.
+ if self.terms < other.terms {
+ std::mem::swap(&mut self, &mut other);
+ }
+ for (key, mut group) in other.references {
+ match self.references.entry(key) {
+ std::collections::btree_map::Entry::Occupied(mut entry) => {
+ entry.get_mut().ids.append(&mut group.ids);
+ }
+ std::collections::btree_map::Entry::Vacant(entry) => {
+ entry.insert(group);
+ }
+ }
+ }
+ self.others.append(&mut other.others);
+ self.terms += other.terms;
+ self
+ }
+
+ fn render(self, entity_id_sql: &str) -> String {
+ let mut predicates = self.others;
+ predicates.extend(self.references.into_values().map(|group| {
+ // Singleton groups retain their indexable JSON containment checks.
+ if group.ids.len() == 1 {
+ property_literal_predicate(&group.first, entity_id_sql)
+ } else {
+ membership_predicate(&group, entity_id_sql)
+ }
+ }));
+ if predicates.len() == 1 {
+ return predicates.pop().expect("one predicate");
+ }
+ format!("({})", predicates.join(" OR "))
+ }
+}
+
+fn membership_predicate(group: &ReferenceGroup, entity_id_sql: &str) -> String {
+ let ids = group
+ .ids
+ .iter()
+ .map(|id| sql_string_literal(&id.to_string()))
+ .collect::<Vec<_>>()
+ .join(", ");
+ let entity_type_clause = group
+ .first
+ .entity_type
+ .map(|value| format!("AND ep_prop.entity_type = '{value}'"))
+ .unwrap_or_default();
+ let definition = group.first.property_definition_id;
+ // The AST carries a variable-size set. Keep one membership predicate per
+ // definition/type, rather than one correlated EXISTS per reference.
+ // Guard both JSON kinds to retain @>'s behavior for non-array properties
+ // and non-string entity IDs (->> alone would also match JSON numbers).
+ format!(
+ r#"EXISTS (
+ SELECT 1 FROM entity_properties ep_prop
+ CROSS JOIN LATERAL jsonb_array_elements(
+ CASE WHEN jsonb_typeof(ep_prop.values->'value') = 'array'
+ THEN ep_prop.values->'value' ELSE '[]'::jsonb END
+ ) ep_ref(value)
+ WHERE ep_prop.entity_id = {entity_id_sql}
+ {entity_type_clause}
+ AND ep_prop.property_definition_id = '{definition}'
+ AND jsonb_typeof(ep_ref.value->'entity_id') = 'string'
+ AND ep_ref.value->>'entity_id' = ANY(ARRAY[{ids}]::text[])
+ )"#
+ )
+}
diff --git a/docs/agent-guide/crm.md b/docs/agent-guide/crm.md
index 8caf7fd3e9..668906e2a7 100644
--- a/docs/agent-guide/crm.md
+++ b/docs/agent-guide/crm.md
@@ -1,22 +1,59 @@
# Customers (CRM)
-## Customers (CRM) — `/app/component/companies`
+## Customers (CRM) — `/app/companies`
On desktop, the local sidebar uses the same navigation primitives as Email and Tasks.
Its **New** menu creates a **Company**, a **Contact**, or a **Pipeline** (Pipeline
only when pipelines are enabled; disabled until the team's CRM is enabled). The
-**Records** section lists **Companies** and **People**; Pipelines and Lists follow.
+**Records** section lists **Companies**, **People**, **Tasks**, **Email**, **Notes**,
+and **Calls**, in that order; Pipelines and Lists follow.
There are no built-in company views or Board/List layout. Companies and People
are plain soup lists with the shared pagination. Existing personal/team saved
views stay in the toolbar's Views menu.
+**Rollout:** Tasks, Email, Notes and Calls require PostHog `enable-crm-activity`
+(off by default; local override: `VITE_ENABLE_CRM_ACTIVITY=true`). CRM also uses
+this flag to decide whether to supply its task-composer preset; the shared
+composer itself is not feature-flagged. With it off, only Companies and People
+appear in Records, activity queries do not run, and activity deep links return to
+Companies after flags finish loading. Global task creation uses the standard
+composer; record-level New task still associates the new task with that record.
+With it on, the activity and contextual composer behavior below applies.
+Task creation opens immediately from the focused pane's registered preset,
+without fetching record details. Contact company prefills use already-loaded
+details. If CRM's flag is still loading, CRM supplies no preset. Later flag,
+focus or record changes do not reset an open composer; reopen to use the new
+context. If an embedded record shows a loading error, global task creation still
+targets the selected record until you close its details.
+
The selected Customers list is stored on the pane as `sN.crm.tab`. People uses
-`people`, a list uses `list:<uuid>`, and hidden companies use `hidden`.
-Companies is the default and omits the key. A pipeline has its own path,
-`/app/companies/pipeline/<uuid>`; older `sN.crm.tab=pipeline:<uuid>` URLs and
-shared `crmView` links that show a pipeline redirect there. Choosing Companies,
-People, a pipeline, or a list updates the URL, and browser Back and Forward
-restore it.
+`people`, activity tabs use `tasks`, `email`, `notes`, or `calls`, a list uses
+`list:<uuid>`, and hidden companies use `hidden`. Companies is the default and
+omits the key. A pipeline has its own path, `/app/companies/pipeline/<uuid>`;
+older `sN.crm.tab=pipeline:<uuid>` URLs and shared `crmView` links that show a
+pipeline redirect there. Choosing Companies, People, an activity tab, a pipeline,
+or a list updates the URL, and browser Back and Forward restore it.
+
+The four activity tabs show CRM-linked content, not the whole app: Tasks and
+Calls require a Companies or Contacts reference; Notes are linked Markdown
+documents (excluding tasks, snippets, and skills); Email is your own mailbox's
+threads with CRM company domains or contact addresses. Lists page as you scroll.
+Empty CRM scope never falls back to all content. A loading failure offers
+**Try again**. Tasks has **New task**, with Companies and Contacts visible in
+place of Status. Choose a CRM association when creating a task from this feed.
+Opening Task through the global Create menu while Customers is focused uses the
+same preset. With an embedded company or contact detail open, global Create
+prefills the current breadcrumb record; a contact also includes its company.
+Closing the detail returns global Create to the unassociated CRM preset.
+
+Verify activity loading with a CRM containing thousands of companies and
+contacts, not only an empty fixture. Opening a tab must settle without repeated
+requests; switching tabs must preserve filtering and scrolling must load older
+matching items. A frontend preview still needs the Soup/email SQL optimizations
+deployed on its backend to verify large-scope request performance.
+
+Record-level **New task** also prefills the current record.
+**Add property** can reveal Status or another supported property.
Companies lists every visible company, grouped by Stage by default, with Owner,
Revenue and Last Interaction columns. A Stage column is off by default; turn it
@@ -42,7 +79,8 @@ below, and a **Create …** button that also submits on Command-Enter.
Command-F focuses it, `Clear search` resets it, and Escape leaves the field.
On touch devices, CRM uses the same scrollable pill tabs as Tasks in the top
-header: Companies, People, available pipelines, and enabled lists. Swipe the
+header: Companies, People, Tasks, Email, Notes, Calls, available pipelines, and
+enabled lists. Swipe the
strip horizontally to reach every destination; the selected tab stays visible.
The tabs remain available inside pipelines, with no hamburger button. Company
filters lead the strip when available. On mobile, pipelines omit their title
diff --git a/docs/agent-guide/tasks.md b/docs/agent-guide/tasks.md
index eb04dac711..9d406d7196 100644
--- a/docs/agent-guide/tasks.md
+++ b/docs/agent-guide/tasks.md
@@ -523,6 +523,30 @@ filter sheets. Desktop uses the centered composer dialog.
enables once there is a title). Dialog also offers `Continue editing in split` to open the
task as a full document.
+The property row adapts when the launching pane supplies a task-composer preset.
+The app shell's creation-context provider snapshots the focused pane's preset
+before the composer opens. It reads the layout's existing focus accessor, not a
+global context registry; no detail fetch or navigation-state capture is needed.
+Without a preset, the standard property row and draft are used. The shared
+composer is not feature-flagged. Create-menu actions, shortcuts, and pane buttons
+capture the provider during setup and read the preset when invoked.
+
+Customers supplies its preset when PostHog `enable-crm-activity` is enabled:
+**Companies** and **Contacts** replace Status in the initial row; Status still
+starts as Not Started on the saved task. Record-level task creation prefills the
+company or contact, including the contact's company when already loaded. With the
+CRM flag off or loading, CRM supplies no preset; record-level creation still
+associates the task with its record. **Add property** opens the same property
+editor as the document/task side panel: search by name or type, select a property
+and enter its value, or create a property from an unmatched search. Assignments
+and values stay in the task draft until creation; opening or closing the editor
+preserves other draft values. Tag selection continues through its separate Tags
+picker. CRM drafts are isolated from the ordinary task draft and from other CRM
+records; reopening restores added properties as well as their values. **Clear Draft**
+restores that view's preset.
+Later flag, focus or record changes leave the open draft and associations intact,
+even between launch and mount. The next opening uses the current context.
+
Tasks are documents under the hood (creation hits `POST /dss/documents/create_task`), so they
also show up in Files/`All` and in AI-chat document listings.