Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(mentions): mention projects through Quick Access (#7184)
teod192e387d7cd
diff --git a/apps/web/src/components/app/split-layout/layoutManager.ts b/apps/web/src/components/app/split-layout/layoutManager.tsindex 2a56aebb19..588d7b6536 100644--- a/apps/web/src/components/app/split-layout/layoutManager.ts+++ b/apps/web/src/components/app/split-layout/layoutManager.ts@@ -1417,7 +1417,10 @@ export function createSplitLayout(type: SplitContentType,id: string): SplitHandle | undefined {- const instance = contentInstances.find(contentIdentity({ type, id }));+ // A union of more than 25 content types no longer narrows per member.+ const instance = contentInstances.find(+ contentIdentity({ type, id } as SplitContent)+ );const match = state.splits.find((s) =>(s.id === instance?.owner ||diff --git a/apps/web/src/components/app/split-layout/split-router/app-middleware.ts b/apps/web/src/components/app/split-layout/split-router/app-middleware.tsindex 1c54b77873..a3814d5088 100644--- a/apps/web/src/components/app/split-layout/split-router/app-middleware.ts+++ b/apps/web/src/components/app/split-layout/split-router/app-middleware.ts@@ -95,6 +95,14 @@ function redirectLegacyRoutes(({ id }) => `/channels/${encodeURIComponent(id)}`).with({ type: 'task' }, ({ id }) => `/tasks/${encodeURIComponent(id)}`)+ // Like a task, a project opens in Tasks, under its Projects tab.+ .with({ type: 'initiative' }, ({ id }) => {+ const query = new URLSearchParams();+ replaceSplitSearchParams(query, [+ { location: { search: { tasks: { tab: ['projects'] } } } },+ ]);+ return `/tasks/projects/${encodeURIComponent(id)}/overview?${query}`;+ }).otherwise((content) => {const document = driveDocumentFromContent(content);return documentdiff --git a/apps/web/src/components/app/split-layout/tests/app-route-search.test.ts b/apps/web/src/components/app/split-layout/tests/app-route-search.test.tsindex ad183d92bd..89dde187c2 100644--- a/apps/web/src/components/app/split-layout/tests/app-route-search.test.ts+++ b/apps/web/src/components/app/split-layout/tests/app-route-search.test.ts@@ -1,4 +1,7 @@-import { createRoutesManifest } from '@app/lib/split-router/routes';+import {+ createRoutesManifest,+ getRouteClaim,+} from '@app/lib/split-router/routes';import {decodeSplitRouterLocation,serializeSplitRouterLocation,@@ -150,6 +153,24 @@ describe('application route mentions', () => {).toBeUndefined();});+ it('treats a routed project and the initiative block as one entity', () => {+ const claim = (pathname: string) => {+ const { entries } = decodeSplitRouterLocation({+ routes,+ location: { pathname, search: '', hash: '' },+ });+ return getRouteClaim(routes, entries[0]!.location.route);+ };+ expect(claim(`/tasks/projects/${projectId}/overview`)).toEqual(+ claim(`/initiative/${projectId}`)+ );+ expect(+ resolveMention(+ `https://dev.macro.com/app/tasks/projects/${projectId}/overview`+ )+ ).toEqual({ id: projectId, block: 'initiative', params: {} });+ });+it('leaves unsupported and invalid destinations as links', () => {expect(resolveMention('https://dev.macro.com/app/reviews')).toBeUndefined();expect(diff --git a/apps/web/src/components/app/split-layout/tests/layoutManager.test.ts b/apps/web/src/components/app/split-layout/tests/layoutManager.test.tsindex 89f4e64d13..e7aa801036 100644--- a/apps/web/src/components/app/split-layout/tests/layoutManager.test.ts+++ b/apps/web/src/components/app/split-layout/tests/layoutManager.test.ts@@ -1014,15 +1014,12 @@ describe('layoutManager', () => {const onApplied = vi.fn();const source = manager.getSplit(manager.splits()[0].id)!;const sourceRoute = router.route(source.id);- manager.openWithSplit(- { type, id: 'entity' },- {- handle: source,- preferNewSplit: true,- search: searchLocationUpdates('entity', target),- onApplied,- }- );+ manager.openWithSplit({ type, id: 'entity' } as SplitContent, {+ handle: source,+ preferNewSplit: true,+ search: searchLocationUpdates('entity', target),+ onApplied,+ });await router.settled();expect(manager.splits()).toHaveLength(2);const owner = manager.splits().find((split) => split.id !== source.id)!;@@ -1033,15 +1030,12 @@ describe('layoutManager', () => {expect(location.read().pathname).toContain(path);expect(onApplied).toHaveBeenCalledOnce();const firstRequest = router.search(owner.id, namespace)?.seek;- manager.openWithSplit(- { type, id: 'entity' },- {- handle: source,- preferNewSplit: true,- search: searchLocationUpdates('entity', target),- onApplied,- }- );+ manager.openWithSplit({ type, id: 'entity' } as SplitContent, {+ handle: source,+ preferNewSplit: true,+ search: searchLocationUpdates('entity', target),+ onApplied,+ });await router.settled();expect(manager.splits()).toHaveLength(2);expect(router.route(source.id)).toEqual(sourceRoute);@@ -1768,6 +1762,44 @@ describe('layoutManager', () => {dispose();});+ it('opens a project like a task: in Tasks, under its Projects tab', async () => {+ const projectId = '019507e8-14a3-7bc1-8610-419f16bd03a9';+ const { manager, location, router, dispose } = ingressRouter('/search');+ await router.settled();++ manager.openWithSplit(+ { type: 'initiative', id: projectId } as SplitContent,+ { activate: true }+ );+ await router.settled();++ expect(location.read().pathname).toBe(+ `/tasks/projects/${projectId}/overview`+ );+ expect(router.search(manager.splits()[0].id, 'tasks')).toMatchObject({+ tab: ['projects'],+ });+ router.dispose();+ dispose();+ });++ it('keeps a project block on touch, like tasks', async () => {+ const projectId = '019507e8-14a3-7bc1-8610-419f16bd03a9';+ const { manager, location, router, dispose } = ingressRouter(+ `/initiative/${projectId}`,+ { touch: true }+ );+ await router.settled();++ expect(location.read().pathname).toBe(`/initiative/${projectId}`);+ expect(manager.splits()[0].content).toMatchObject({+ type: 'initiative',+ id: projectId,+ });+ router.dispose();+ dispose();+ });+it('upgrades the legacy Calendar block URL to the preferred period route', async () => {localStorage.setItem(CALENDAR_PREFERENCES_KEY,diff --git a/apps/web/src/features/block-initiative/component/InitiativeBlock.test.tsx b/apps/web/src/features/block-initiative/component/InitiativeBlock.test.tsxnew file mode 100644index 0000000000..d9455dab7f--- /dev/null+++ b/apps/web/src/features/block-initiative/component/InitiativeBlock.test.tsx@@ -0,0 +1,112 @@+import { LoadErrors } from '@core/block';+import { render, screen } from '@solidjs/testing-library';+import type { JSX } from 'solid-js';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const projectId = '019507e8-14a3-7bc1-8610-419f16bd03a9';+const mocks = vi.hoisted(() => ({+ detail: vi.fn(),+ flag: { enabled: true, loading: false },+}));+vi.mock('@core/block', async (importOriginal) => ({+ ...(await importOriginal<typeof import('@core/block')>()),+ useBlockId: () => projectId,+}));+vi.mock('@app/features/projects/project-detail', async () => {+ const { ViewBreadcrumbs } = await import('@app/components/view-shell');+ const { useTagSets } = await import('@property/tags/tag-sets-context');+ return {+ // Throws, as the real view's top bar and task list do, without the+ // breadcrumb root and tag sets the Tasks view normally supplies.+ ProjectDetail: (props: unknown) => {+ mocks.detail(props);+ useTagSets();+ return (+ <>+ <ViewBreadcrumbs.Outlet />+ <p>project detail</p>+ </>+ );+ },+ };+});+vi.mock('@queries/properties/tags', () => ({+ useTagsQuery: () => ({ isPending: false, isFetched: true, data: [] }),+}));+vi.mock('@app/lib/analytics/posthog', () => ({+ useFeatureFlag: () => () => mocks.flag,+}));+vi.mock('@components/app/side-panel', () => ({+ SidePanel: { Root: (props: { children: JSX.Element }) => props.children },+}));+vi.mock('@components/app/split-layout/split-router/app-route-shell', () => ({+ RedirectSplit: (props: { to: { id: string } }) => (+ <p>redirect to {props.to.id}</p>+ ),+}));+vi.mock('@core/component/LoadingBlock', () => ({+ LoadingBlock: () => <p>loading</p>,+}));+// The block definitions open the storage and connection-gateway sockets.+vi.mock('@service-storage/websocket', () => ({+ storageWS: { reconnectIfDisconnected: vi.fn() },+ createWebSocketJob: vi.fn(),+}));+vi.mock('@service-connection/websocket', () => ({+ ws: { addEventListener: vi.fn(), send: vi.fn() },+ state: () => 'closed',+ createConnectionBlockWebsocketEffect: vi.fn(),+ createConnectionWebsocketEffect: vi.fn(),+}));++import { definition } from '../definition';+import InitiativeBlock from './InitiativeBlock';++beforeEach(() => {+ mocks.detail.mockClear();+ mocks.flag = { enabled: true, loading: false };+});++describe('initiative block', () => {+ it('loads the project id from the storage source', async () => {+ const loaded = await definition.load(+ { type: 'dss', id: projectId },+ 'initial'+ );+ expect(loaded.isOk() && loaded.value).toEqual({ id: projectId });+ expect(await definition.load({ type: 'unset' }, 'initial')).toBe(+ LoadErrors.MISSING+ );+ });++ it('renders the project view the Tasks route renders', () => {+ render(() => <InitiativeBlock />);++ expect(screen.getByText('project detail')).toBeTruthy();+ expect(mocks.detail).toHaveBeenCalledWith({+ route: { id: projectId, section: 'overview' },+ breadcrumb: {+ entry: {+ value: `initiative:${projectId}`,+ data: { type: 'initiative', id: projectId },+ },+ order: 0,+ },+ });+ });++ it('sends a disabled project to Tasks once flags have loaded', () => {+ mocks.flag = { enabled: false, loading: false };+ render(() => <InitiativeBlock />);++ expect(screen.getByText('redirect to tasks')).toBeTruthy();+ expect(mocks.detail).not.toHaveBeenCalled();+ });++ it('waits for flags before deciding', () => {+ mocks.flag = { enabled: false, loading: true };+ render(() => <InitiativeBlock />);++ expect(screen.getByText('loading')).toBeTruthy();+ });+});diff --git a/apps/web/src/features/block-initiative/component/InitiativeBlock.tsx b/apps/web/src/features/block-initiative/component/InitiativeBlock.tsxnew file mode 100644index 0000000000..630b3b1e13--- /dev/null+++ b/apps/web/src/features/block-initiative/component/InitiativeBlock.tsx@@ -0,0 +1,53 @@+import { ViewBreadcrumbs } from '@app/components/view-shell';+import { ProjectDetail } from '@app/features/projects/project-detail';+import { useFeatureFlag } from '@app/lib/analytics/posthog';+import { SidePanel } from '@components/app/side-panel';+import { RedirectSplit } from '@components/app/split-layout/split-router/app-route-shell';+import { useBlockId } from '@core/block';+import { LoadingBlock } from '@core/component/LoadingBlock';+import { enableProjects } from '@core/constant/featureFlags';+import { ListEntityMetadataQueryProvider } from '@entity';+import { Show } from 'solid-js';++/** The block adapter: the only place that reads the block id. */+export default function InitiativeBlock() {+ return <InitiativeProject id={useBlockId()} />;+}++/**+ * The same project view the Tasks route renders, behind the Projects flag,+ * with the tag sets and breadcrumb root the Tasks view supplies there.+ */+export function InitiativeProject(props: { id: string }) {+ const flag = useFeatureFlag(enableProjects);+ const value = () => `initiative:${props.id}`;+ return (+ <Show+ when={flag().enabled}+ fallback={+ <Show when={!flag().loading} fallback={<LoadingBlock />}>+ <RedirectSplit to={{ type: 'component', id: 'tasks' }} />+ </Show>+ }+ >+ <ListEntityMetadataQueryProvider>+ <ViewBreadcrumbs.Root value={value()} onChange={() => {}}>+ <SidePanel.Root>+ <div class="flex size-full min-h-0 min-w-0 flex-col overflow-hidden">+ <ProjectDetail+ route={{ id: props.id, section: 'overview' }}+ breadcrumb={{+ entry: {+ value: value(),+ data: { type: 'initiative', id: props.id },+ },+ order: 0,+ }}+ />+ </div>+ </SidePanel.Root>+ </ViewBreadcrumbs.Root>+ </ListEntityMetadataQueryProvider>+ </Show>+ );+}diff --git a/apps/web/src/features/block-initiative/definition.ts b/apps/web/src/features/block-initiative/definition.tsnew file mode 100644index 0000000000..d2ee539649--- /dev/null+++ b/apps/web/src/features/block-initiative/definition.ts@@ -0,0 +1,19 @@+import { defineBlock, type ExtractLoadType, LoadErrors } from '@core/block';+import { ok } from 'neverthrow';+import { lazy } from 'solid-js';++/** A task project (initiative); `project` is a folder block. */+export const definition = defineBlock({+ name: 'initiative',+ description: 'View a task project',+ component: lazy(() => import('./component/InitiativeBlock')),+ async load(source, _intent) {+ if (source.type === 'dss') {+ return ok({ id: source.id });+ }+ return LoadErrors.MISSING;+ },+ accepted: {},+});++export type InitiativeData = ExtractLoadType<(typeof definition)['load']>;diff --git a/apps/web/src/features/command/useCommandItems.ts b/apps/web/src/features/command/useCommandItems.tsindex 195fcd5a6d..d02a8e27a8 100644--- a/apps/web/src/features/command/useCommandItems.ts+++ b/apps/web/src/features/command/useCommandItems.ts@@ -345,9 +345,10 @@ function useCommandsList(const QUICK_ACCESS_BUCKETS_BY_CATEGORY: Partial<Record<CategoryFilter, Bucket[]>> = {- // CRM contacts have no view history, so a no-query list would surface the- // whole team's contacts; they are reached through their company instead.- all: exclude('person', 'crm_contact'),+ // Projects come from the command menu's own server search. CRM contacts+ // have no view history, so a no-query list would surface the whole team's+ // contacts; they are reached through their company instead.+ all: exclude('person', 'initiative', 'crm_contact'),channels: ['channel'],dms: ['dm'],documents: ['note', 'document', 'snippet', 'project'],diff --git a/apps/web/src/features/entity/utils/buildEntityData.ts b/apps/web/src/features/entity/utils/buildEntityData.tsindex 16409d7161..d1e6111de2 100644--- a/apps/web/src/features/entity/utils/buildEntityData.ts+++ b/apps/web/src/features/entity/utils/buildEntityData.ts@@ -184,8 +184,8 @@ export function buildEntityData(})// The singleton calendar block has no entity-shaped block id..with('calendar', (): undefined => undefined)- // CRM companies/contacts aren't constructed from block args; soup is the source.- .with('company', 'contact', (): undefined => undefined)+ // CRM companies/contacts and projects aren't constructed from block args; soup is the source.+ .with('company', 'contact', 'initiative', (): undefined => undefined)// PRs are virtual blocks backed by GitHub, not Macro entities..with('pr', (): undefined => undefined).with('agent', (): EntityData | undefined =>diff --git a/apps/web/src/features/notifications/notification-navigation.ts b/apps/web/src/features/notifications/notification-navigation.tsindex 5979718ce4..87ad7093ab 100644--- a/apps/web/src/features/notifications/notification-navigation.ts+++ b/apps/web/src/features/notifications/notification-navigation.ts@@ -7,6 +7,7 @@ import {} from '@block-channel/utils/link';import type {OpenSplitResult,+ SplitContent,SplitHandle,SplitManager,} from '@components/app/split-layout/layoutManager';@@ -84,7 +85,8 @@ function openSplitIfNotOpen(reportApplied();} else {const result = layoutManager.openWithSplit(- { type, id },+ // A union of more than 25 content types no longer narrows per member.+ { type, id } as SplitContent,{activate: true,referredFrom: null,diff --git a/apps/web/src/features/property/editors/selectors/entityUtils.ts b/apps/web/src/features/property/editors/selectors/entityUtils.tsindex ac3244a279..83e907b396 100644--- a/apps/web/src/features/property/editors/selectors/entityUtils.ts+++ b/apps/web/src/features/property/editors/selectors/entityUtils.ts@@ -15,6 +15,7 @@ import type {DocumentEntity,EmailEntity,EntityData,+ InitiativeEntity,ProjectEntity,TaskEntity,} from '@entity';@@ -32,8 +33,7 @@ export type EntityTypeItemMap = {THREAD: EntityItem<EmailEntity>;COMPANY: EntityItem<CrmCompanyEntity>;CONTACT: EntityItem<CrmContactEntity>;- // Native projects use the initiative picker, separate from folder quick access.- INITIATIVE: never;+ INITIATIVE: EntityItem<InitiativeEntity>;// Call records aren't entity-reference targets in quickAccess.CALL_RECORD: never;CALENDAR_EVENT: never;@@ -51,7 +51,7 @@ function entityTypeToBuckets(entityType: EntityType): readonly Bucket[] {.with('CHAT', () => ['chat'] as const).with('TASK', () => ['task'] as const).with('THREAD', () => ['email'] as const) // Note: emails aren't in quickAccess yet, handled separately- .with('INITIATIVE', () => [] as const)+ .with('INITIATIVE', () => ['initiative'] as const).with('COMPANY', () => ['crm_company'] as const).with('CONTACT', () => ['crm_contact'] as const).with('CALL_RECORD', () => [] as const) // Call records aren't in quickAccessdiff --git a/apps/web/src/features/tasks-view/route.test.tsx b/apps/web/src/features/tasks-view/route.test.tsxindex dbbdd335d0..d79214a51d 100644--- a/apps/web/src/features/tasks-view/route.test.tsx+++ b/apps/web/src/features/tasks-view/route.test.tsx@@ -48,10 +48,15 @@ describe('project routes in Tasks', () => {'tasks-project',]);expect(routeParams(entry.location.route)).toEqual({ projectId, section });+ // The same claim as the initiative block, so either view is reused.expect(getRouteClaim(manifest, entry.location.route)).toEqual({- namespace: 'initiative',- id: projectId,+ namespace: 'block',+ id: `initiative:${projectId}`,});+ const leaf = entry.location.route.matches.at(-1)!;+ expect(+ manifest.byId.get(leaf.id)?.definition.toReference?.(leaf.params)+ ).toEqual({ type: 'initiative', id: projectId });});diff --git a/apps/web/src/features/tasks-view/route.tsx b/apps/web/src/features/tasks-view/route.tsxindex 205bb3d871..5fa87df782 100644--- a/apps/web/src/features/tasks-view/route.tsx+++ b/apps/web/src/features/tasks-view/route.tsx@@ -195,7 +195,11 @@ export const projectDetailRoute = defineRoute({}),component: ProjectDetailRouteView,remountKey: ({ projectId }) => projectId,- claim: ({ projectId }) => ({ namespace: 'initiative', id: projectId }),+ claim: ({ projectId }) => ({+ namespace: 'block',+ id: `initiative:${projectId}`,+ }),+ toReference: ({ projectId }) => uuidRouteReference(projectId, 'initiative'),children: [projectTaskRoute],});diff --git a/apps/web/src/lib/constants/block-registry.ts b/apps/web/src/lib/constants/block-registry.tsindex 6ce17b26d3..004e027906 100644--- a/apps/web/src/lib/constants/block-registry.ts+++ b/apps/web/src/lib/constants/block-registry.ts@@ -20,6 +20,8 @@ export const BlockRegistry = ['automation','pr','agent',+ // A task project (`project` is a folder).+ 'initiative',] as const;/** Aliases for block types that share a concrete block implementation. */diff --git a/apps/web/src/lib/core/block.ts b/apps/web/src/lib/core/block.tsindex 98416cda5c..f1af4b580e 100644--- a/apps/web/src/lib/core/block.ts+++ b/apps/web/src/lib/core/block.ts@@ -88,6 +88,7 @@ export const NonDocumentBlockTypes = ['automation','pr','agent',+ 'initiative',] as const as (BlockName | BlockAlias)[];/**@@ -147,6 +148,7 @@ const _ValidBlockCombinations: BlockCombinationRules = {csv: allBlockNames,pr: allBlockNames,agent: allBlockNames,+ initiative: allBlockNames,} as const;// maps block name to valid parents@@ -175,6 +177,7 @@ export const ValidNestingCombinations: BlockCombinationRules = {csv: new Set([]),pr: new Set([]),agent: new Set([]),+ initiative: new Set([]),};export const LoadErrors = {diff --git a/apps/web/src/lib/core/blockMethodRegistry.ts b/apps/web/src/lib/core/blockMethodRegistry.tsindex 387c871eb7..4d70890c06 100644--- a/apps/web/src/lib/core/blockMethodRegistry.ts+++ b/apps/web/src/lib/core/blockMethodRegistry.ts@@ -41,6 +41,7 @@ export interface BlockMethodRegistry {automation: EmptySpec;pr: EmptySpec;agent: EmptySpec;+ initiative: EmptySpec;}// Type helper to get the method spec for a block namediff --git a/apps/web/src/lib/core/component/FileList/constants.tsx b/apps/web/src/lib/core/component/FileList/constants.tsxindex 10ca5c4920..39f1cf535c 100644--- a/apps/web/src/lib/core/component/FileList/constants.tsx+++ b/apps/web/src/lib/core/component/FileList/constants.tsx@@ -82,4 +82,5 @@ const _fileTypeColors: Record<BlockName | BlockAlias | 'default', string> = {automation: 'bg-chat/20 group/item',pr: defaultFileColor,agent: defaultFileColor,+ initiative: defaultFileColor,};diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsxindex a5c4600fe4..358dbff15a 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx@@ -5,7 +5,11 @@ import { useMaybeBlockId, useMaybeBlockName } from '@core/block';import { SUPPORTED_CHAT_ATTACHMENT_BLOCKS } from '@core/component/AI/constant/fileType';import { type PortalScope, ScopedPortal } from '@core/component/ScopedPortal';import { enableCrm, isFeatureEnabled } from '@core/constant/featureFlags';-import { type EntityItem, useQuickAccess } from '@core/context/quickAccess';+import {+ type EntityBucket,+ type EntityItem,+ useQuickAccess,+} from '@core/context/quickAccess';import clickOutside from '@core/directive/clickOutside';import { isMobile } from '@core/mobile/isMobile';import type { ChannelWithParticipants, IUser } from '@core/user';@@ -93,6 +97,17 @@ export function MentionsMenu(props: MentionsMenuProps) {);}+/** The entity buckets listed under "Documents, Agents, & Tasks". */+const DOCUMENT_MENTION_BUCKETS: EntityBucket[] = [+ 'note',+ 'task',+ 'snippet',+ 'document',+ 'project',+ 'chat',+ 'initiative',+];+function MentionsMenuInner(props: MentionsMenuProps) {const analytics = useAnalytics();@@ -132,7 +147,7 @@ function MentionsMenuInner(props: MentionsMenuProps) {const customDocs = props.entities? useEntityMentionFromList({items: props.entities,- buckets: ['note', 'task', 'snippet', 'document', 'project', 'chat'],+ buckets: DOCUMENT_MENTION_BUCKETS,searchTerm,}): undefined;@@ -157,7 +172,7 @@ function MentionsMenuInner(props: MentionsMenuProps) {const docsMention =customDocs ??useEntityMention({- buckets: ['note', 'task', 'snippet', 'document', 'project', 'chat'],+ buckets: DOCUMENT_MENTION_BUCKETS,searchTerm: activeSearchTerm,});const docs = docsMention.entities;diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/entityUtils.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/entityUtils.tsindex 5fcd9f3b84..81a05bbd09 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/entityUtils.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/entityUtils.ts@@ -22,6 +22,7 @@ export function getBlockNameFromEntity(.with('skill', () => 'skill' as const).with('note', () => 'md' as const).with('crm_company', () => 'company' as const)+ .with('initiative', () => 'initiative' as const).otherwise(() => {const entity = item.data;if ('fileType' in entity && typeof entity.fileType === 'string') {diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/initiative-selection.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/initiative-selection.test.tsnew file mode 100644index 0000000000..36a05f3e87--- /dev/null+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/initiative-selection.test.ts@@ -0,0 +1,72 @@+import type { EntityItem } from '@core/context/quickAccess';+import type { InitiativeEntity } from '@entity';+import type { LexicalEditor } from 'lexical';+import { beforeEach, describe, expect, it, vi } from 'vitest';++const { trackMention } = vi.hoisted(() => ({ trackMention: vi.fn() }));+vi.mock('@core/signal/mention', () => ({ trackMention }));+// The block table loads every block module; entities here never need it.+vi.mock('@core/constant/allBlocks', () => ({ fileTypeToBlockName: vi.fn() }));+vi.mock('../../../../plugins', () => ({+ REMOVE_INLINE_SEARCH_COMMAND: 'remove-search',+}));+vi.mock('../../../../plugins/mentions', () => ({+ INSERT_AGENT_SESSION_MENTION_COMMAND: 'insert-session',+ INSERT_DOCUMENT_MENTION_COMMAND: 'insert-document',+ INSERT_DATE_MENTION_COMMAND: 'insert-date',+ INSERT_GROUP_MENTION_COMMAND: 'insert-group',+}));+vi.mock('../../../../utils/mentionsUtils', () => ({+ handleUserMention: vi.fn(),+}));++import { createItemHandler } from './mentionHandlers';++const item: EntityItem<InitiativeEntity> = {+ kind: 'entity',+ bucket: 'initiative',+ id: 'initiative-1',+ searchText: 'Roadmap',+ sortTimestamp: 0,+ timestamps: {},+ data: {+ type: 'initiative',+ id: 'initiative-1',+ name: 'Roadmap',+ ownerId: 'owner',+ descriptionDocumentId: 'description-1',+ },+};++describe('task project menu selection', () => {+ beforeEach(() => {+ trackMention.mockReset();+ });++ it('inserts an initiative block mention tracked against the project', async () => {+ trackMention.mockResolvedValue('mention-uuid');+ const dispatchCommand = vi.fn();+ const onDocumentMention = vi.fn();+ const handler = createItemHandler({+ editor: { dispatchCommand } as unknown as LexicalEditor,+ blockId: 'doc-1',+ blockName: 'md',+ onDocumentMention,+ });+ await handler(item);+ expect(trackMention).toHaveBeenCalledWith(+ 'doc-1',+ 'initiative',+ 'initiative-1'+ );+ expect(dispatchCommand).toHaveBeenNthCalledWith(2, 'insert-document', {+ documentId: 'initiative-1',+ documentName: 'Roadmap',+ blockName: 'initiative',+ mentionUuid: 'mention-uuid',+ channelType: undefined,+ });+ // Composers share or attach mentioned files; a project is neither.+ expect(onDocumentMention).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mentionHandlers.ts b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mentionHandlers.tsindex 87c46c36eb..49fcb50981 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mentionHandlers.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mentionHandlers.ts@@ -86,13 +86,16 @@ async function handleEntityMention(const trackType =item.bucket === 'channel' || item.bucket === 'dm'? 'channel'- : 'document';+ : item.bucket === 'initiative'+ ? 'initiative'+ : 'document';mentionId = await trackMention(blockId, trackType, entity.id);}if (item.bucket === 'email') {onEmailMention?.(entity as unknown as EmailEntity);- } else {+ } else if (item.bucket !== 'initiative') {+ // Callers share or attach mentioned files; a project is neither.onDocumentMention?.(entity as unknown as any);}diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.tsindex 135d3eb7e5..f39f903fad 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/mentions/mentionsPlugin.ts@@ -147,6 +147,7 @@ export type ItemMention = {| 'call'| 'calendar_event'| 'agent_session'+ | 'initiative'| 'foreign'| 'group'| 'automation'@@ -211,6 +212,10 @@ function $mentionItemFromNode(node: MentionNode): ItemMention {} else if (blockName === 'project') {fileType = 'project';itemType = 'project';+ } else if (blockName === 'initiative') {+ // A task project, never a document id.+ fileType = 'initiative';+ itemType = 'initiative';} else if (blockName === 'chat') {fileType = 'chat';itemType = 'chat';@@ -320,6 +325,7 @@ const getDocumentMentionItemType = (.with('chat', () => 'chat').with('channel', () => 'channel').with('project', () => 'project')+ .with('initiative', () => 'initiative').with('channel_message', () => 'channel').with('channel_thread', () => 'channel').with('automation', () => 'automation')diff --git a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.test.ts b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.test.tsindex a8c6cf6437..4a12a8791c 100644--- a/apps/web/src/lib/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.test.ts+++ b/apps/web/src/lib/core/component/LexicalMarkdown/plugins/text-paste/textPastePlugin.test.ts@@ -25,7 +25,7 @@ describe('parseMacroAppUrl', () => {});- it.each(['md', 'channel', 'task', 'pr'])(+ it.each(['md', 'channel', 'task', 'pr', 'initiative'])('preserves existing %s links',(block) => {expect(diff --git a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.tsindex 31d8902ad4..3d93340a63 100644--- a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts+++ b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.test.ts@@ -1,4 +1,8 @@-import type { CrmCompanyEntity, CrmContactEntity } from '@entity';+import type {+ CrmCompanyEntity,+ CrmContactEntity,+ InitiativeEntity,+} from '@entity';import type {CacheChangeListener,CacheChangeOptions,@@ -52,6 +56,7 @@ const mocks = vi.hoisted(() => ({readRecordsByKeys: vi.fn(),companies: [] as CrmCompanyEntity[],crmContacts: [] as CrmContactEntity[],+ initiatives: [] as InitiativeEntity[],crmEnabled: (): boolean => true,cacheEnabled: true,queries: {} as Partial<@@ -131,6 +136,12 @@ vi.mock('@queries/history/graphql', () => ({vi.mock('@queries/soup/quick-access-agent-sessions', () => ({useQuickAccessAgentSessionsQuery: () => ({ query: {}, sessions: () => [] }),}));+vi.mock('@queries/soup/quick-access-initiatives', () => ({+ useQuickAccessInitiativesQuery: () => ({+ query: { refetch: vi.fn() },+ initiatives: () => mocks.initiatives,+ }),+}));vi.mock('@app/features/crm/crm-search', async () => ({...(await import('@app/features/crm/queries/graphql')),useQuickAccessCrmCompaniesQuery: () => ({@@ -207,6 +218,7 @@ beforeEach(() => {mocks.projectedChannels = [];mocks.companies = [];mocks.crmContacts = [];+ mocks.initiatives = [];mocks.crmEnabled = () => true;mocks.cacheEnabled = true;mocks.queries = {};@@ -1058,6 +1070,51 @@ describe('Quick Access source integration', () => {).toEqual(['folder', 'note', 'task']);});+ it('lists task projects with document search hits without searching the cache for them', async () => {+ mocks.initiatives = [+ {+ type: 'initiative',+ id: 'initiative-1',+ name: 'Roadmap',+ ownerId: 'owner',+ descriptionDocumentId: 'description-1',+ updatedAt: '2025-01-02T00:00:00.000Z',+ },+ ];+ mocks.search.mockResolvedValue({+ documents: [+ {+ profile: 'quick-access-v1',+ recordKey: 'GraphqlSoupDocument:note-1',+ bucket: 'note',+ searchText: 'Roadmap notes',+ timestampMs: 1,+ sourceHash: 'hash',+ },+ ],+ nextCursor: null,+ });+ const list = setup((source) =>+ source.useList({+ buckets: BUCKET_COMBINATIONS.documents,+ searchTerm: () => 'roadmap',+ })+ );+ await vi.waitFor(() =>+ expect(list.items().map((item) => item.id)).toEqual(+ expect.arrayContaining(['note-1', 'initiative-1'])+ )+ );+ expect(+ list.items().find((item) => item.id === 'initiative-1')+ ).toMatchObject({ bucket: 'initiative', data: { type: 'initiative' } });+ expect(mocks.search).toHaveBeenCalledWith(+ expect.objectContaining({+ buckets: expect.not.arrayContaining(['initiative']),+ })+ );+ });+it('ignores email hydration and refreshes only the affected open list and source', async () => {const lists = setup((source) => ({notes: source.useList({ buckets: ['note'] }),diff --git a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsxindex 0057e463a5..f90470cd56 100644--- a/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx+++ b/apps/web/src/lib/core/context/quickAccess/QuickAccessSource.tsx@@ -32,6 +32,7 @@ import { queryReadyGate } from '@queries/gate';import { materializeCachedGraphqlHistoryItems } from '@queries/history/graphql';import { type HistoryItem, useHistoryQuery } from '@queries/history/history';import { useQuickAccessAgentSessionsQuery } from '@queries/soup/quick-access-agent-sessions';+import { useQuickAccessInitiativesQuery } from '@queries/soup/quick-access-initiatives';import { useQuickAccessSkillsQuery } from '@queries/soup/quick-access-skills';import { useQuickAccessSnippetsQuery } from '@queries/soup/quick-access-snippets';import { useRecentlyViewedSoupQuery } from '@queries/soup/recently-viewed';@@ -347,6 +348,7 @@ const RECORD_TYPE_BY_BUCKET: Record<Bucket, string> = {project: 'GraphqlSoupProject',person: 'GraphqlUser',agent_session: 'AgentSession',+ initiative: 'GraphqlSoupInitiative',};function compareRecency(a: IndexEntry, b: IndexEntry): number {@@ -407,6 +409,8 @@ export function createQuickAccessValue(): QuickAccessContextValue {const { query: agentSessionsQuery, sessions: agentSessionsAccessor } =useQuickAccessAgentSessionsQuery();+ const { query: initiativesQuery, initiatives: initiativesAccessor } =+ useQuickAccessInitiativesQuery();// globally hidden idsconst [hiddenIds, setHiddenIds] = createSignal<Set<string>>(new Set());@@ -854,6 +858,41 @@ export function createQuickAccessValue(): QuickAccessContextValue {return sortIndexEntries(entries);});+ const initiativeEntries = createLazyMemo(() => {+ const viewedAtMap = soupViewedAtMap();+ const hidden = hiddenIds();+ const entries: IndexEntry[] = [];+ for (const initiative of initiativesAccessor()) {+ if (hidden.has(initiative.id)) continue;+ const viewedAt = viewedAtMap.get(initiative.id) ?? initiative.viewedAt;+ const sortTimestamp =+ toTimestamp(viewedAt) || toTimestamp(initiative.updatedAt);+ const entity = { ...initiative, viewedAt };+ const version = JSON.stringify(entity);+ const cached = itemCache.get(initiative.id);+ if (!cached || cached.version !== version) {+ itemCache.set(initiative.id, {+ version,+ item: {+ kind: 'entity',+ id: initiative.id,+ bucket: 'initiative',+ searchText: initiative.name,+ sortTimestamp,+ timestamps: {+ viewedAt,+ updatedAt: initiative.updatedAt,+ createdAt: initiative.createdAt,+ },+ data: entity,+ },+ });+ }+ entries.push({ id: initiative.id, bucket: 'initiative', sortTimestamp });+ }+ return sortIndexEntries(entries);+ });+const processedData = createLazyMemo(() => {const allEntries = mergeMultipleSortedIndices([historyEntries().entries,@@ -864,6 +903,7 @@ export function createQuickAccessValue(): QuickAccessContextValue {snippetEntries(),skillEntries(),agentSessionEntries(),+ initiativeEntries(),]);const seenIds = new Set(allEntries.map((entry) => entry.id));@@ -934,6 +974,7 @@ export function createQuickAccessValue(): QuickAccessContextValue {indices.get('skill') ?? [],indices.get('chat') ?? [],indices.get('project') ?? [],+ indices.get('initiative') ?? [],]),};});@@ -1168,6 +1209,7 @@ export function createQuickAccessValue(): QuickAccessContextValue {snippetsQuery.refetch();skillsQuery.refetch();void agentSessionsQuery.refetch();+ initiativesQuery.refetch();};return {diff --git a/apps/web/src/lib/core/context/quickAccess/types.ts b/apps/web/src/lib/core/context/quickAccess/types.tsindex 38f648e863..e3be3f19a1 100644--- a/apps/web/src/lib/core/context/quickAccess/types.ts+++ b/apps/web/src/lib/core/context/quickAccess/types.ts@@ -9,6 +9,7 @@ import type {DocumentEntity,EmailEntity,EntityData,+ InitiativeEntity,ProjectEntity,SkillEntity,SnippetEntity,@@ -35,7 +36,8 @@ export type Bucket =| 'crm_company'// CRM contacts, kept apart from 'person' (Macro users and email contacts).| 'crm_contact'- | 'agent_session';+ | 'agent_session'+ | 'initiative';export type EntityBucket = Exclude<Bucket, 'person'>;@@ -54,6 +56,7 @@ const ALL_BUCKETS: Bucket[] = ['crm_company','crm_contact','agent_session',+ 'initiative',];export type BucketCombination = 'all' | 'channels' | 'documents';@@ -69,6 +72,7 @@ export const BUCKET_COMBINATIONS: Record<BucketCombination, Bucket[]> = {'skill','chat','project',+ 'initiative',],};@@ -140,6 +144,7 @@ export type BucketItemMap = {crm_company: EntityItem<CrmCompanyEntity>;crm_contact: EntityItem<CrmContactEntity>;agent_session: EntityItem<AgentSessionEntity>;+ initiative: EntityItem<InitiativeEntity>;person: UserItem;};diff --git a/apps/web/src/lib/core/internal/trackBlockOpened.ts b/apps/web/src/lib/core/internal/trackBlockOpened.tsindex 77d906bc3f..517ab55b9a 100644--- a/apps/web/src/lib/core/internal/trackBlockOpened.ts+++ b/apps/web/src/lib/core/internal/trackBlockOpened.ts@@ -7,6 +7,7 @@ import {} from '@queries/soup/cache';import {blockNameToItemType,+ type HistoryItemType,type ItemType,isCloudStorageItem,} from '@service-storage/client';@@ -29,6 +30,7 @@ function isSoupEntityTag('foreign','crm_company','crm_contact',+ 'initiative',() => false).with('document', 'chat', 'project', 'channel', 'call', () => true)@@ -45,7 +47,9 @@ function isSoupEntityTag(// Foreign entities (GitHub PRs) are intentionally omitted: they are not// documents, and posting `/history/document/{id}` 401s because ACL looks// up a document that does not exist.-function shouldTrackInUserHistory(itemType: ItemType): boolean {+function shouldTrackInUserHistory(+ itemType: ItemType+): itemType is HistoryItemType {return (isCloudStorageItem(itemType) ||itemType === 'agent_session' ||diff --git a/apps/web/src/lib/queries/history/history.ts b/apps/web/src/lib/queries/history/history.tsindex 18bf418760..06aeafc115 100644--- a/apps/web/src/lib/queries/history/history.ts+++ b/apps/web/src/lib/queries/history/history.ts@@ -2,7 +2,11 @@ import { useFeatureFlag } from '@app/lib/analytics/posthog';import { enableGraphqlSoup } from '@core/constant/featureFlags';import { catchToResult, throwOnErr } from '@core/util/result';import { type MutationCallbacks, withCallbacks } from '@queries/utils';-import { type ItemType, storageServiceClient } from '@service-storage/client';+import {+ type HistoryItemType,+ type ItemType,+ storageServiceClient,+} from '@service-storage/client';import { getGraphqlSoupCacheHost } from '@service-storage/graphql-soup';import {type QueryClient,@@ -167,7 +171,7 @@ export async function refetchHistory(): Promise<void> {type UpsertToHistoryParams = {itemId: string;- itemType: ItemType;+ itemType: HistoryItemType;};type UpsertToHistoryContext = {@@ -233,7 +237,7 @@ export function useUpsertToHistoryMutation(* Prefer `useUpsertToHistoryMutation` when inside a component.*/export async function postNewHistoryItem(- itemType: ItemType,+ itemType: HistoryItemType,itemId: string): Promise<boolean> {const maybeAdded = await storageServiceClient.upsertItemToUserHistory({diff --git a/apps/web/src/lib/queries/preview/fetchers.ts b/apps/web/src/lib/queries/preview/fetchers.tsindex 43d063ba50..b00c013b97 100644--- a/apps/web/src/lib/queries/preview/fetchers.ts+++ b/apps/web/src/lib/queries/preview/fetchers.ts@@ -2,6 +2,7 @@ import {fetchCrmCompanyPreviews,fetchCrmContactPreviews,} from '@app/features/crm/preview-adapter';+import { QUERY_FILTERS_BASE } from '@app/features/next-soup/filters/query-filters';import { itemToSafeName } from '@core/constant/allBlocks';import {enableGraphqlSoup,@@ -255,6 +256,42 @@ async function fetchProjectPreviews(});}+/** Task projects through the authorized Soup list; absent ids have no access. */+async function fetchInitiativePreviews(+ initiativeIds: string[]+): Promise<PreviewItem[]> {+ const result = await storageServiceClient.getSoupItems({+ params: {},+ body: {+ ...QUERY_FILTERS_BASE,+ initiative_filters: { initiative_ids: initiativeIds },+ limit: initiativeIds.length,+ },+ });++ if (result.isErr()) {+ console.error('Failed to fetch project previews');+ return [];+ }++ return result.value.items.flatMap((item): PreviewItem[] =>+ item.tag === 'initiative'+ ? [+ {+ id: item.data.id,+ type: 'initiative',+ access: 'access',+ loading: false,+ rawName: item.data.name,+ name: item.data.name,+ owner: item.data.ownerId,+ updatedAt: item.data.updatedAt,+ },+ ]+ : []+ );+}+/*** Reuse the thread-messages query the email block fetches on open: returns* cached data (any staleness — previews tolerate 24h), or joins an in-flight@@ -402,6 +439,7 @@ export async function fetchRestPreviewBatch(doFetch(fetchChannelPreviews, filterMapToId(items, 'channel')),doFetch(fetchDocumentPreviews, filterMapToId(items, 'document')),doFetch(fetchProjectPreviews, filterMapToId(items, 'project')),+ doFetch(fetchInitiativePreviews, filterMapToId(items, 'initiative')),doFetch(fetchEmailPreviews, filterMapToId(items, 'email')),doFetch(fetchCrmCompanyPreviews, filterMapToId(items, 'crm_company')),doFetch(fetchCrmContactPreviews, filterMapToId(items, 'crm_contact')),diff --git a/apps/web/src/lib/queries/preview/graphql.ts b/apps/web/src/lib/queries/preview/graphql.tsindex 968b03b85f..7ebdc42dd9 100644--- a/apps/web/src/lib/queries/preview/graphql.ts+++ b/apps/web/src/lib/queries/preview/graphql.ts@@ -59,6 +59,7 @@ const GRAPHQL_TYPENAMES = {crm_company: 'GraphqlSoupCrmCompany',document: 'GraphqlSoupDocument',email: 'GraphqlSoupEmailThread',+ initiative: 'GraphqlSoupInitiative',project: 'GraphqlSoupProject',} as const;@@ -84,6 +85,8 @@ function graphqlEntityType(type: GraphqlPreviewType): EntityType {return 'CALL_RECORD';case 'crm_company':return 'COMPANY';+ case 'initiative':+ return 'INITIATIVE';}}@@ -224,6 +227,15 @@ export function graphqlRecordToPreview(owner: record.senderEmail ?? record.senderName ?? undefined,};}+ case 'GraphqlSoupInitiative':+ return {+ id: record.id,+ type: 'initiative',+ access: 'access',+ loading: false,+ rawName: record.displayName ?? '',+ name: record.displayName ?? '',+ };case 'GraphqlSoupChannel': {const name = record.displayName ?? record.channelDisplayName;if (@@ -423,6 +435,10 @@ export async function setGraphqlPreviewName(__typename: 'GraphqlSoupEmailThread' as const,emailName: name,}))+ .with('initiative', () => ({+ ...base,+ __typename: 'GraphqlSoupInitiative' as const,+ })).exhaustive();await writeGraphqlPreviewCache({query: stringifyDocument(ItemPreviewNameCacheWriteDocument),diff --git a/apps/web/src/lib/queries/preview/tests/graphql.test.ts b/apps/web/src/lib/queries/preview/tests/graphql.test.tsindex 9a78f39f7a..f556d63485 100644--- a/apps/web/src/lib/queries/preview/tests/graphql.test.ts+++ b/apps/web/src/lib/queries/preview/tests/graphql.test.ts@@ -328,6 +328,23 @@ describe('GraphQL item previews', () => {expect(graphqlRecordToPreview(record)).toBeUndefined();});+ it('maps an initiative record to a task project preview', () => {+ const record = {+ __typename: 'GraphqlSoupInitiative',+ id: 'initiative-1',+ displayName: 'Roadmap',+ } satisfies ItemPreviewFieldsFragment;++ expect(graphqlRecordToPreview(record)).toEqual({+ id: 'initiative-1',+ type: 'initiative',+ access: 'access',+ loading: false,+ rawName: 'Roadmap',+ name: 'Roadmap',+ });+ });+it('reads the exact normalized key through the minimal fragment', async () => {const readRecordsByKeys = vi.fn(async (args: ReadRecordsByKeysArgs) => [{diff --git a/apps/web/src/lib/queries/preview/tests/initiative-fetcher.test.ts b/apps/web/src/lib/queries/preview/tests/initiative-fetcher.test.tsnew file mode 100644index 0000000000..61e5ae45f3--- /dev/null+++ b/apps/web/src/lib/queries/preview/tests/initiative-fetcher.test.ts@@ -0,0 +1,56 @@+import { ok } from 'neverthrow';+import { expect, it, vi } from 'vitest';++const getSoupItems = vi.hoisted(() => vi.fn());+vi.mock('@service-storage/client', () => ({+ storageServiceClient: { getSoupItems },+}));+vi.mock('@core/constant/allBlocks', () => ({ itemToSafeName: () => '' }));+vi.mock('@service-cognition/client', () => ({ cognitionApiServiceClient: {} }));+vi.mock('@service-email/client', () => ({ emailClient: {} }));+vi.mock('@service-storage/messages', () => ({ entityMessagesClient: {} }));+vi.mock('../../email/thread', () => ({ threadQueryOptions: vi.fn() }));+vi.mock('../../client', () => ({ queryClient: {} }));+vi.mock('../../agent-session/mention-fetchers', () => ({+ fetchAgentSessionMentionPreviews: vi.fn(),+}));++import { fetchRestPreviewBatch } from '../fetchers';++it('previews task projects through Soup without a GraphQL record', async () => {+ getSoupItems.mockResolvedValueOnce(+ ok({+ items: [+ {+ tag: 'initiative',+ data: {+ id: 'initiative-1',+ name: 'Roadmap',+ ownerId: 'owner',+ createdAt: '2026-10-01T00:00:00Z',+ updatedAt: '2026-10-02T00:00:00Z',+ properties: [],+ },+ },+ ],+ })+ );+ const previews = await fetchRestPreviewBatch([+ { type: 'initiative', id: 'initiative-1' },+ { type: 'initiative', id: 'hidden' },+ ]);+ expect(getSoupItems).toHaveBeenCalledWith({+ params: {},+ body: expect.objectContaining({+ initiative_filters: { initiative_ids: ['initiative-1', 'hidden'] },+ limit: 2,+ }),+ });+ expect(previews.get('initiative-1')).toMatchObject({+ type: 'initiative',+ access: 'access',+ name: 'Roadmap',+ });+ // The loader reports ids Soup does not return as no access.+ expect(previews.has('hidden')).toBe(false);+});diff --git a/apps/web/src/lib/queries/soup/quick-access-initiatives.ts b/apps/web/src/lib/queries/soup/quick-access-initiatives.tsnew file mode 100644index 0000000000..37a9a7e56b--- /dev/null+++ b/apps/web/src/lib/queries/soup/quick-access-initiatives.ts@@ -0,0 +1,48 @@+import { QUERY_FILTERS_BASE } from '@app/features/next-soup/filters/query-filters';+import { useFeatureFlag } from '@app/lib/analytics/posthog';+import { enableProjects } from '@core/constant/featureFlags';+import type { InitiativeEntity } from '@entity';+import { queryReadyGate } from '@queries/gate';+import { useSoupItemsQuery } from '@queries/soup/items';+import { createMemo } from 'solid-js';++const QUICK_ACCESS_INITIATIVES_LIMIT = 500;+const STALE_TIME = 5 * 60 * 1000;++/**+ * Quick Access feed of the task projects (initiatives) the user can access.+ *+ * Projects never appear in history, so this is the only source feeding the+ * `'initiative'` bucket — mention menus and entity pickers list them like any+ * other entity.+ *+ * Every other entity type is filtered out by extending `QUERY_FILTERS_BASE`;+ * initiatives are opt-in.+ */+export function useQuickAccessInitiativesQuery() {+ const projectsFlag = useFeatureFlag(enableProjects);++ const query = useSoupItemsQuery(+ () => ({+ params: {+ limit: QUICK_ACCESS_INITIATIVES_LIMIT,+ sort_method: 'viewed_updated',+ },+ body: {+ ...QUERY_FILTERS_BASE,+ initiative_filters: { include: true },+ },+ }),+ () => ({ staleTime: STALE_TIME, enabled: projectsFlag().enabled })+ );++ const initiatives = createMemo<InitiativeEntity[]>(() =>+ queryReadyGate(query)+ ? query.data.filter(+ (entity): entity is InitiativeEntity => entity.type === 'initiative'+ )+ : []+ );++ return { query, initiatives };+}diff --git a/apps/web/src/lib/service-clients/service-storage/client.ts b/apps/web/src/lib/service-clients/service-storage/client.tsindex 9a587100af..54363e3656 100644--- a/apps/web/src/lib/service-clients/service-storage/client.ts+++ b/apps/web/src/lib/service-clients/service-storage/client.ts@@ -166,7 +166,7 @@ import type { ViewsResponse } from './generated/schemas/viewsResponse';import { saveDocumentHandlerResponse } from './generated/zod';import type { ItemType } from './itemType';-export type { ItemType } from './itemType';+export type { HistoryItemType, ItemType } from './itemType';export {blockNameToItemType,DEFAULT_ITEM_TYPE,diff --git a/apps/web/src/lib/service-clients/service-storage/itemType.test.ts b/apps/web/src/lib/service-clients/service-storage/itemType.test.tsindex 7f8683f3a0..e2d1023da1 100644--- a/apps/web/src/lib/service-clients/service-storage/itemType.test.ts+++ b/apps/web/src/lib/service-clients/service-storage/itemType.test.ts@@ -14,6 +14,12 @@ describe('itemTypeToReferenceEntityType', () => {'agent_session');});+ test('the initiative block names a task project, never a folder', () => {+ expect(blockNameToItemType('initiative')).toBe('initiative');+ expect(blockNameToItemType('project')).toBe('project');+ expect(stringToItemType('initiative')).toBe('initiative');+ expect(itemTypeToReferenceEntityType('initiative')).toBe('initiative');+ });test('maps email to the thread type used by referencium', () => {expect(itemTypeToReferenceEntityType('email')).toBe('thread');});@@ -49,6 +55,7 @@ describe('stringToItemType', () => {'project','channel','crm_company',+ 'initiative',])('parses %s as itself', (raw) => {expect(stringToItemType(raw)).toBe(raw);});diff --git a/apps/web/src/lib/service-clients/service-storage/itemType.ts b/apps/web/src/lib/service-clients/service-storage/itemType.tsindex ee1d901d8e..8da0fce729 100644--- a/apps/web/src/lib/service-clients/service-storage/itemType.ts+++ b/apps/web/src/lib/service-clients/service-storage/itemType.ts@@ -15,7 +15,8 @@ export type ItemType =| 'calendar_event'| 'foreign'| 'crm_company'- | 'crm_contact';+ | 'crm_contact'+ | 'initiative';/** Item type assumed when a surface has no better information. */export const DEFAULT_ITEM_TYPE: ItemType = 'document';@@ -50,6 +51,7 @@ export function stringToItemType(str: string): ItemType | undefined {'project','channel','crm_company',+ 'initiative',(itemType) => itemType).otherwise(() => undefined);@@ -59,7 +61,16 @@ export function blockNameToItemType(blockName: BlockName | BlockAlias): ItemType {return match<BlockName | BlockAlias, ItemType>(blockName)- .with('chat', 'call', 'channel', 'project', 'email', 'automation', (b) => b)+ .with(+ 'chat',+ 'call',+ 'channel',+ 'project',+ 'email',+ 'automation',+ 'initiative',+ (b) => b+ ).with('agent', () => 'agent_session').with('calendar', () => 'calendar_event').with('company', () => 'crm_company')@@ -68,6 +79,8 @@ export function blockNameToItemType(.otherwise(() => DEFAULT_ITEM_TYPE);}+export type HistoryItemType = (typeof ITEM_TYPES)[number];+/** Item types accepted by user history endpoints. */export const ITEM_TYPES = ['document',diff --git a/crates/prompt/src/lib.rs b/crates/prompt/src/lib.rsindex 1193ff4e6d..da4ca05b1c 100644--- a/crates/prompt/src/lib.rs+++ b/crates/prompt/src/lib.rs@@ -284,6 +284,7 @@ mod tests {assert!(instructions.contains("<m-user-mention>"));assert!(instructions.contains("\"expanded\":true"));assert!(instructions.contains("\"blockName\":\"skill\""));+ assert!(instructions.contains("\"blockName\":\"initiative\""));}#[test]diff --git a/crates/prompt/src/mentions.rs b/crates/prompt/src/mentions.rsindex 808feae6f5..b8c7ec35b1 100644--- a/crates/prompt/src/mentions.rs+++ b/crates/prompt/src/mentions.rs@@ -31,7 +31,8 @@ Use `<m-document-mention>` with the right `blockName` (and `blockParams` when ne- Channel mention: `<m-document-mention>{"documentId":"{id}","documentName":"","blockName":"channel","blockParams":{}}</m-document-mention>`- Channel message mention: `<m-document-mention>{"documentId":"{channel_id}","documentName":"","blockName":"channel","blockParams":{"channel_message_id":"{message_id}"}}</m-document-mention>`- Chat mention: `<m-document-mention>{"documentId":"{id}","documentName":"","blockName":"chat","blockParams":{}}</m-document-mention>`-- Project mention: `<m-document-mention>{"documentId":"{id}","documentName":"","blockName":"project","blockParams":{}}</m-document-mention>`+- Project mention (a task project, i.e. an initiative): `<m-document-mention>{"documentId":"{initiative_id}","documentName":"","blockName":"initiative","blockParams":{}}</m-document-mention>`+- Folder mention: `<m-document-mention>{"documentId":"{id}","documentName":"","blockName":"project","blockParams":{}}</m-document-mention>`- Task mention: `<m-document-mention>{"documentId":"{id}","documentName":"","blockName":"task","blockParams":{}}</m-document-mention>`- Email thread mention: `<m-document-mention>{"documentId":"{thread_id}","documentName":"","blockName":"email","blockParams":{}}</m-document-mention>`- Calendar event mention: `<m-document-mention>{"documentId":"{event_id}","documentName":"","blockName":"calendar","blockParams":{}}</m-document-mention>`@@ -42,6 +43,7 @@ Use `<m-document-mention>` with the right `blockName` (and `blockParams` when ne- Snippet mention: `<m-document-mention>{"documentId":"{id}","documentName":"","blockName":"snippet","blockParams":{}}</m-document-mention>`- CRM company mention: `<m-document-mention>{"documentId":"{id}","documentName":"","blockName":"company","blockParams":{}}</m-document-mention>`+The `blockName` for a project is always exactly `initiative`, with the initiative id from an initiative tool result (such as ListInitiatives or ReadInitiative); `project` is a folder.The `blockName` for an email thread is always exactly `email` — never `thread` or `email_thread`, which the frontend cannot resolve.The `blockName` for a calendar event is always exactly `calendar` — never `calendar_event`, which the frontend cannot resolve. `documentId` is the `eventId` a calendar tool returned. To point at one instance of a recurring event, pass that occurrence's `recurrenceId` from ListCalendarEvents as the `occurrenceKey` block param; otherwise omit it and the mention previews the nearest instance. A calendar event mention resolves only for users who have that event on their own calendar.When a tool returns both a channel id and a channel message id, link the specific message using the channel message mention format. Do not link only the channel unless you are referring to the whole channel.diff --git a/docs/AGENT_GUIDE/documents.md b/docs/AGENT_GUIDE/documents.mdindex b5497f48a1..bceb653082 100644--- a/docs/AGENT_GUIDE/documents.md+++ b/docs/AGENT_GUIDE/documents.md@@ -387,6 +387,31 @@ check that the inserted company mention points to the correct company. Also checsearching by domain and that an open picker updates when companies finish hydrating.Discard unsent test drafts rather than sending them.+## Project mentions++With Projects enabled, type `@` followed by a project name in an editor,+composer or spreadsheet cell. Projects (not folders) come from Quick Access, so+they appear alongside documents and tasks in the **Documents, Agents, & Tasks**+section and in entity property pickers that accept projects. The command menu+keeps its own project search. Selecting one inserts a document mention with the+project's icon and current name, like a channel mention. Clicking it or+pressing Enter on it opens the project the way a task mention opens a task:+in Tasks, under **Projects** › the project (on touch devices, as the project+view on its own). A project you cannot read shows **No Access**. Pasting+`/app/initiative/<id>` or a Tasks project link inserts the same mention.++The mention is stored as+`<m-document-mention>{"documentId":"<initiative id>","blockName":"initiative",…}</m-document-mention>`+(`project` is a folder). In a document it is tracked as a reference like other+entity mentions. It is deliberately not a channel-message reference, so+mentioning a project in a channel never shares the project with the channel's+members.++To verify, mention a project in a document and in a channel draft, check the+mention opens the right project, rename the project and reload to see the name+update, and delete the mention. Discard unsent test drafts rather than sending+them.+## CRM associationsWith CRM enabled, any task, document or call can point at CRM records through thediff --git a/packages/lexical-core/tests/channel-mentions.test.ts b/packages/lexical-core/tests/channel-mentions.test.tsindex 3ead81a584..90ed9b5fd6 100644--- a/packages/lexical-core/tests/channel-mentions.test.ts+++ b/packages/lexical-core/tests/channel-mentions.test.ts@@ -39,6 +39,16 @@ describe('extractChannelMentionsFromMarkdown', () => {}});+ it('never sends a project mention as a channel reference', () => {+ // A reference would share the project with the channel; nor is the+ // initiative id a document.+ expect(+ extractChannelMentionsFromMarkdown(+ `${documentMention('project-1', 'initiative')} ${documentMention('doc-1', 'md')}`+ )+ ).toEqual([{ entityType: 'document', entityId: 'doc-1' }]);+ });+it('extracts user mentions and re-tags bot principals', () => {const markdown ='<m-user-mention>{"userId":"macro|[email protected]","email":"[email protected]"}</m-user-mention> and ' +diff --git a/packages/lexical-core/utils/mentions.ts b/packages/lexical-core/utils/mentions.tsindex 855e11a6c1..e763eeaaec 100644--- a/packages/lexical-core/utils/mentions.ts+++ b/packages/lexical-core/utils/mentions.ts@@ -111,6 +111,9 @@ function documentMentionEntityType(blockName: string): string {return 'crm_company';case 'contact':return 'crm_contact';+ // A task project. Not a message reference type, so it is dropped below.+ case 'initiative':+ return 'initiative';default:return 'document';}@@ -121,7 +124,9 @@ function documentMentionEntityType(blockName: string): string {* the way the web editor tracks them while composing a channel message.* Document mentions map by block name; user mentions are re-tagged `bot`* when they target a bot principal. Contact, date, and PR mentions- * carry no referencable entity and are skipped. Authored group mentions are preserved. Duplicates are dropped.+ * carry no referencable entity and are skipped. Project (initiative) mentions+ * are skipped too: channel references auto-share their target with members.+ * Authored group mentions are preserved. Duplicates are dropped.*/export function $extractChannelMentions(): ChannelMention[] {const out: ChannelMention[] = [];diff --git a/services/ai-editing-worker/src/ai-editing/prompts/API_COMPLETE.md b/services/ai-editing-worker/src/ai-editing/prompts/API_COMPLETE.mdindex 5fd44cf0ca..82daf0cffb 100644--- a/services/ai-editing-worker/src/ai-editing/prompts/API_COMPLETE.md+++ b/services/ai-editing-worker/src/ai-editing/prompts/API_COMPLETE.md@@ -391,7 +391,7 @@ Existing chips in the document XML look like `<user-mention>`, `<date-mention>`,- `mentionUser(blockId, at, { userId, email })`- `mentionContact(blockId, at, { contactId, name, emailOrDomain, isCompany })`- `mentionGroup(blockId, at, { groupAlias })`-- `mentionDocument(blockId, at, { documentId, documentName, blockName, blockParams? })` — documents, channels, chats, projects, tasks, emails, calendar events, skills, calls, automations (`blockName` is `md`/`channel`/`chat`/`project`/`task`/`email`/`calendar`/`skill`/`call`/`automation`/…). `blockParams` is for channel messages (`channel_message_id`) and calendar occurrences (`occurrenceKey`).+- `mentionDocument(blockId, at, { documentId, documentName, blockName, blockParams? })` — documents, channels, chats, folders, projects, tasks, emails, calendar events, skills, calls, automations (`blockName` is `md`/`channel`/`chat`/`project`/`initiative`/`task`/`email`/`calendar`/`skill`/`call`/`automation`/…). A project (initiative) is `blockName: 'initiative'` with the initiative id as `documentId`; `project` is a folder. `blockParams` is for channel messages (`channel_message_id`) and calendar occurrences (`occurrenceKey`).- `mentionAgentSession(blockId, at, { id, label?, expanded? })` — existing agent session. `expanded: true` inserts the card that follows the session's latest turn.- `mentionPullRequest(blockId, at, { id, label? })`- `mentionTag(blockId, at, { optionId, propertyDefinitionId, scope, name, color? })`