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.

refactor(storage): one owner for entity-type dialect conversions (#6043)

teo0ac1c2471de7
diff --git a/apps/web/src/features/block-canvas/component/FileSelector.tsx b/apps/web/src/features/block-canvas/component/FileSelector.tsx
index e8c40f5bb4..678dee7801 100644
--- a/apps/web/src/features/block-canvas/component/FileSelector.tsx
+++ b/apps/web/src/features/block-canvas/component/FileSelector.tsx
@@ -59,7 +59,7 @@ function ItemOption(props: { file: FileItem; type: ItemType }) {
export function FileSelector() {
const [userFiles, setUserFiles] = createSignal<
- { file: FileItem; type: string }[]
+ { file: FileItem; type: ItemType }[]
>([]);
const historyQuery = useHistoryQuery();
const { focusCanvas } = useToolManager();
@@ -67,7 +67,7 @@ export function FileSelector() {
const [fileSelectorOpen, setFileSelectorOpen] = createSignal(false);
createEffect(async () => {
- const files: { file: FileItem; type: string }[] = [];
+ const files: { file: FileItem; type: ItemType }[] = [];
(historyQuery.data ?? []).forEach((item) => {
if (
item.type === 'document' &&
@@ -116,10 +116,7 @@ export function FileSelector() {
>
{(item) => (
<Dropdown.Item>
- <ItemOption
- file={item.file}
- type={item.type as ItemType}
- />
+ <ItemOption file={item.file} type={item.type} />
</Dropdown.Item>
)}
</VList>
diff --git a/apps/web/src/features/block-email/component/sidepanel/EmailSidePanelSections.tsx b/apps/web/src/features/block-email/component/sidepanel/EmailSidePanelSections.tsx
index 655409ac65..4e5d3e7281 100644
--- a/apps/web/src/features/block-email/component/sidepanel/EmailSidePanelSections.tsx
+++ b/apps/web/src/features/block-email/component/sidepanel/EmailSidePanelSections.tsx
@@ -6,7 +6,6 @@ import {
import { SidePanel } from '@components/app/side-panel';
import { References } from '@core/component/References';
import { useAttachmentReferencesQuery } from '@queries/storage/attachment-references';
-import type { ItemType } from '@service-storage/client';
import { Show, Suspense } from 'solid-js';
import { useEmailContext } from '../EmailContext';
@@ -54,15 +53,10 @@ export function EmailSidePanelSections(props: EmailSidePanelSectionsProps) {
);
}
-// Email threads are stored as the "thread" entity type in the references
-// system (ReferencedShareItemType::EmailThread -> "thread" and the mentions
-// plugin maps email -> thread), so query/render with "thread", not "email".
-const EMAIL_REFERENCE_ENTITY_TYPE = 'thread' as ItemType;
-
function ReferencesSectionConditional(props: { threadId: string }) {
const references = useAttachmentReferencesQuery(
() => props.threadId,
- () => EMAIL_REFERENCE_ENTITY_TYPE
+ () => 'email'
);
const count = () => references.data?.length ?? 0;
@@ -76,10 +70,7 @@ function ReferencesSectionConditional(props: { threadId: string }) {
>
<Suspense fallback={<SidePanel.Loading />}>
<div class="text-xs">
- <References
- documentId={props.threadId}
- entityType={EMAIL_REFERENCE_ENTITY_TYPE}
- />
+ <References documentId={props.threadId} entityType="email" />
</div>
</Suspense>
</SidePanel.Section>
diff --git a/apps/web/src/features/dynamic-ui/widgets/Timeline.tsx b/apps/web/src/features/dynamic-ui/widgets/Timeline.tsx
index fe40b93693..0835f827b7 100644
--- a/apps/web/src/features/dynamic-ui/widgets/Timeline.tsx
+++ b/apps/web/src/features/dynamic-ui/widgets/Timeline.tsx
@@ -2,6 +2,7 @@ import { ItemPreview } from '@core/component/ItemPreview';
import type { ItemType } from '@service-storage/client';
import { cn } from '@ui';
import { For, Show } from 'solid-js';
+import { match } from 'ts-pattern';
import type { EntityRef, WidgetOf } from '../schema';
import { TEXT } from '../tokens';
@@ -9,16 +10,20 @@ export type TimelineProps = Omit<WidgetOf<'timeline'>, 'type'>;
type TimelineEvent = TimelineProps['events'][number];
-/** Map a schema EntityType onto the ItemType string ItemPreview expects. */
-function toItemType(type: EntityRef['type']): string {
- switch (type) {
- case 'email_thread':
- return 'email';
- case 'foreign_entity':
- return 'foreign';
- default:
- return type;
- }
+function toItemType(type: EntityRef['type']): ItemType | undefined {
+ return match<EntityRef['type'], ItemType | undefined>(type)
+ .with('email_thread', () => 'email')
+ .with('foreign_entity', () => 'foreign')
+ .with(
+ 'user',
+ 'team',
+ 'static_file',
+ 'reminder',
+ 'skill',
+ 'agent_session',
+ () => undefined
+ )
+ .otherwise((itemType) => itemType);
}
/**
@@ -115,7 +120,7 @@ function TimeLineItem(props: {
<div class="mt-0.5 w-fit max-w-full">
<ItemPreview
id={entity().id}
- type={toItemType(entity().type) as ItemType}
+ type={toItemType(entity().type)}
class="ring-0"
/>
</div>
diff --git a/apps/web/src/features/entity/queries/dss.ts b/apps/web/src/features/entity/queries/dss.ts
index 0bcddc1f34..c7f79f4153 100644
--- a/apps/web/src/features/entity/queries/dss.ts
+++ b/apps/web/src/features/entity/queries/dss.ts
@@ -24,7 +24,6 @@ import { soupKeys } from '@queries/soup/keys';
import { ownTouchStamp } from '@queries/soup/normalized-cache/own-touch';
import { callServiceClient } from '@service-call/client';
import { scheduledActionClient } from '@service-scheduled-action/client';
-import type { ItemType } from '@service-storage/client';
import { storageServiceClient } from '@service-storage/client';
import { useMutation } from '@tanstack/solid-query';
import { type EntityData, getEntityProjectId } from '../types/entity';
@@ -64,7 +63,7 @@ export function createBulkDeleteDssItemsMutation() {
storageServiceClient.reminders.deleteReminder(e.id)
).then(() => true);
}
- return deleteItem({ id: e.id, itemType: e.type as ItemType });
+ return deleteItem({ id: e.id, itemType: e.type });
})
);
if (deletable.some((e) => e.type === 'call')) {
diff --git a/apps/web/src/features/property/component/propertyValue/PropertyTooltip.tsx b/apps/web/src/features/property/component/propertyValue/PropertyTooltip.tsx
index c3b167c05a..c8c100a4bf 100644
--- a/apps/web/src/features/property/component/propertyValue/PropertyTooltip.tsx
+++ b/apps/web/src/features/property/component/propertyValue/PropertyTooltip.tsx
@@ -17,7 +17,6 @@ import {
hasValue as propertyHasValue,
} from '@property/utils';
import type { EntityReference } from '@service-properties/generated/schemas/entityReference';
-import type { EntityType } from '@service-properties/generated/schemas/entityType';
import { proxyResource } from '@service-unfurl/client';
import {
createSignal,
@@ -240,7 +239,7 @@ const EntityTooltipContent = (props: {
const EntityValuePill = (props: { entity: EntityReference }) => {
const { name, icon } = usePropertyEntityDisplay(
() => props.entity.entity_id,
- () => props.entity.entity_type as EntityType,
+ () => props.entity.entity_type,
{ fallbackIcon: null }
);
@@ -255,7 +254,7 @@ const EntityValuePill = (props: { entity: EntityReference }) => {
const UserEntityItem = (props: { entity: EntityReference }) => {
const { name } = usePropertyEntityDisplay(
() => props.entity.entity_id,
- () => props.entity.entity_type as EntityType,
+ () => props.entity.entity_type,
{ fallbackIcon: null }
);
diff --git a/apps/web/src/features/property/utils/entityConversion.ts b/apps/web/src/features/property/utils/entityConversion.ts
index 7f47ec967d..de0fea1abf 100644
--- a/apps/web/src/features/property/utils/entityConversion.ts
+++ b/apps/web/src/features/property/utils/entityConversion.ts
@@ -49,18 +49,17 @@ export function updateEntityReferences(
return updatedRefs;
}
+/** `undefined` means the entity type has no item-preview surface. */
export function entityTypeToItemType(type: EntityType): ItemType | undefined {
- return match(type)
- .with('TASK', () => 'document' as ItemType)
- .with('DOCUMENT', () => 'document' as ItemType)
- .with('PROJECT', () => 'project' as ItemType)
- .with('CHANNEL', () => 'channel' as ItemType)
- .with('CHAT', () => 'chat' as ItemType)
- .with('CALL_RECORD', () => 'call' as ItemType)
- .with('COMPANY', () => undefined) // huh
- .with('USER', () => undefined) // huh
- .with('THREAD', () => 'email' as ItemType)
- .with('CALENDAR_EVENT', () => undefined) // no calendar item rendering yet
+ return match<EntityType, ItemType | undefined>(type)
+ .with('TASK', () => 'document')
+ .with('DOCUMENT', () => 'document')
+ .with('PROJECT', () => 'project')
+ .with('CHANNEL', () => 'channel')
+ .with('CHAT', () => 'chat')
+ .with('CALL_RECORD', () => 'call')
+ .with('THREAD', () => 'email')
+ .with('COMPANY', 'USER', 'CALENDAR_EVENT', () => undefined)
.exhaustive();
}
diff --git a/apps/web/src/lib/core/component/References.tsx b/apps/web/src/lib/core/component/References.tsx
index 15dfd1b3ea..515bd58736 100644
--- a/apps/web/src/lib/core/component/References.tsx
+++ b/apps/web/src/lib/core/component/References.tsx
@@ -18,6 +18,7 @@ import { useAttachmentReferencesQuery } from '@queries/storage/attachment-refere
import type { ItemType } from '@service-storage/client';
import type { ApiAttachmentEntityReference as EntityReference } from '@service-storage/generated/schemas/apiAttachmentEntityReference';
import type { ApiAttachmentGenericReference as GenericReference } from '@service-storage/generated/schemas/apiAttachmentGenericReference';
+import { stringToItemType } from '@service-storage/itemType';
import { createMemo, For, type JSX, Show } from 'solid-js';
import { InlineItemPreview } from './ItemPreview';
import { StaticMarkdown } from './LexicalMarkdown/component/core/StaticMarkdown';
@@ -186,9 +187,11 @@ function GenericReferenceRow(props: {
});
return parts.firstName || parts.fullName;
};
+ const sourceItemType = () =>
+ stringToItemType(props.reference.source_entity_type);
const [item] = useItemPreview(() => ({
id: props.reference.source_entity_id,
- type: props.reference.source_entity_type as ItemType,
+ type: sourceItemType(),
}));
return (
@@ -196,7 +199,7 @@ function GenericReferenceRow(props: {
source={
<InlineItemPreview
id={props.reference.source_entity_id}
- type={props.reference.source_entity_type as ItemType}
+ type={sourceItemType()}
/>
}
senderAvatar={
diff --git a/apps/web/src/lib/core/internal/App.tsx b/apps/web/src/lib/core/internal/App.tsx
index 245120eeb9..8d4632a623 100644
--- a/apps/web/src/lib/core/internal/App.tsx
+++ b/apps/web/src/lib/core/internal/App.tsx
@@ -27,7 +27,7 @@ const App: Component = () => {
'red',
] as const;
- const testIds = [
+ const testIds: { id: string; type: ItemType }[] = [
{ id: '15085bba-d188-4c80-aac6-657b15b255d8', type: 'document' },
{ id: '6f1ea347-fee1-4717-b118-89e7bda1eacd', type: 'document' },
{ id: 'dd2ec57b-0bce-4051-8522-cf8a5f0802d5', type: 'document' },
@@ -183,7 +183,7 @@ const App: Component = () => {
<div class="w-full flex gap-2 justify-center flex-wrap">
<For each={testIds}>
{(item) => {
- return <ItemPreview id={item.id} type={item.type as ItemType} />;
+ return <ItemPreview id={item.id} type={item.type} />;
}}
</For>
</div>
diff --git a/apps/web/src/lib/queries/storage/attachment-references.ts b/apps/web/src/lib/queries/storage/attachment-references.ts
index b6ab98ebd5..a050c7dd92 100644
--- a/apps/web/src/lib/queries/storage/attachment-references.ts
+++ b/apps/web/src/lib/queries/storage/attachment-references.ts
@@ -1,5 +1,9 @@
import { throwOnErr } from '@core/util/result';
-import { type ItemType, storageServiceClient } from '@service-storage/client';
+import {
+ type ItemType,
+ itemTypeToReferenceEntityType,
+ storageServiceClient,
+} from '@service-storage/client';
import type { ApiAttachmentEntityReference } from '@service-storage/generated/schemas/apiAttachmentEntityReference';
import { useQuery } from '@tanstack/solid-query';
import type { Accessor } from 'solid-js';
@@ -13,7 +17,7 @@ async function fetchAttachmentReferences(
): Promise<ApiAttachmentEntityReference[]> {
const response = await throwOnErr(() =>
storageServiceClient.attachmentReferences({
- entity_type: entityType,
+ entity_type: itemTypeToReferenceEntityType(entityType),
entity_id: entityId,
})
);
diff --git a/apps/web/src/lib/service-clients/service-storage/client.ts b/apps/web/src/lib/service-clients/service-storage/client.ts
index 9b6230950f..e6cf72a32e 100644
--- a/apps/web/src/lib/service-clients/service-storage/client.ts
+++ b/apps/web/src/lib/service-clients/service-storage/client.ts
@@ -6,7 +6,6 @@ import {
modificationDataReplacer,
type PdfSegment as TSegment,
} from '@coparse/document-processing-types';
-import type { BlockAlias, BlockName } from '@core/block';
import { ENABLE_DOCX_TO_PDF } from '@core/constant/featureFlags';
import { PaywallKey, usePaywallState } from '@core/constant/PaywallState';
import {
@@ -165,7 +164,12 @@ import { saveDocumentHandlerResponse } from './generated/zod';
import type { ItemType } from './itemType';
export type { ItemType } from './itemType';
-export { itemTypeToReferenceEntityType } from './itemType';
+export {
+ blockNameToItemType,
+ DEFAULT_ITEM_TYPE,
+ itemTypeToReferenceEntityType,
+ stringToItemType,
+} from './itemType';
import type {
CollabSurfaceResponse,
@@ -236,8 +240,6 @@ type Success = {
};
type SuccessResponse = { data: Success };
-export const DEFAULT_ITEM_TYPE: ItemType = 'document';
-
export type { ApiAttachmentChannelReference } from './generated/schemas/apiAttachmentChannelReference';
export type { ApiAttachmentEntityReference } from './generated/schemas/apiAttachmentEntityReference';
export type { ApiAttachmentGenericReference } from './generated/schemas/apiAttachmentGenericReference';
@@ -320,72 +322,6 @@ export const ChannelTypeEnum = {
Team: ChannelType.team,
} as const satisfies Record<string, ChannelType>;
-const itemTypeSet = new Set([
- 'document',
- 'chat',
- 'project',
- 'channel',
- 'email',
- 'channel_message',
- 'call',
- 'automation',
- 'calendar_event',
- 'thread',
- 'crm_company',
- 'crm_contact',
-]);
-
-function _isItemType(str: string): str is ItemType {
- return itemTypeSet.has(str);
-}
-
-export function blockNameToItemType(
- blockName: BlockName | BlockAlias
-): ItemType {
- switch (blockName) {
- case 'chat':
- return 'chat';
- case 'call':
- return 'call';
- case 'calendar':
- return 'calendar_event';
- case 'channel':
- return 'channel';
- case 'project':
- return 'project';
- case 'email':
- return 'email';
- case 'automation':
- return 'automation';
- case 'company':
- return 'crm_company';
- case 'contact':
- return 'crm_contact';
- default:
- return DEFAULT_ITEM_TYPE;
- }
-}
-
-export function stringToItemType(str: string): ItemType | undefined {
- switch (str) {
- case 'email':
- case 'thread':
- case 'email_thread': {
- return 'email';
- }
- case 'call':
- case 'calendar_event':
- case 'chat':
- case 'document':
- case 'project':
- case 'channel':
- case 'crm_company':
- return str;
- default:
- return undefined;
- }
-}
-
export function isCloudStorageItem(
item: ItemType
): item is CloudStorageItemType {
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.ts
index ecab2c3737..7b21887c63 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
@@ -1,5 +1,10 @@
import { describe, expect, test } from 'vitest';
-import { type ItemType, itemTypeToReferenceEntityType } from './itemType';
+import {
+ blockNameToItemType,
+ type ItemType,
+ itemTypeToReferenceEntityType,
+ stringToItemType,
+} from './itemType';
describe('itemTypeToReferenceEntityType', () => {
test('maps email to the thread type used by referencium', () => {
@@ -20,3 +25,72 @@ describe('itemTypeToReferenceEntityType', () => {
}
);
});
+
+describe('stringToItemType', () => {
+ test.each(['email', 'thread', 'email_thread'])(
+ 'parses the stored thread spelling %s as email',
+ (raw) => {
+ expect(stringToItemType(raw)).toBe('email');
+ }
+ );
+
+ test.each([
+ 'call',
+ 'calendar_event',
+ 'chat',
+ 'document',
+ 'project',
+ 'channel',
+ 'crm_company',
+ ])('parses %s as itself', (raw) => {
+ expect(stringToItemType(raw)).toBe(raw);
+ });
+
+ test.each(['crm_contact', 'automation', 'channel_message', 'bogus'])(
+ 'rejects %s',
+ (raw) => {
+ expect(stringToItemType(raw)).toBeUndefined();
+ }
+ );
+});
+
+describe('blockNameToItemType', () => {
+ test.each([
+ ['chat', 'chat'],
+ ['call', 'call'],
+ ['calendar', 'calendar_event'],
+ ['channel', 'channel'],
+ ['project', 'project'],
+ ['email', 'email'],
+ ['automation', 'automation'],
+ ['company', 'crm_company'],
+ ['contact', 'crm_contact'],
+ ] as const)('maps block %s to item type %s', (blockName, itemType) => {
+ expect(blockNameToItemType(blockName)).toBe(itemType);
+ });
+
+ test('maps document blocks to document', () => {
+ expect(blockNameToItemType('md')).toBe('document');
+ expect(blockNameToItemType('pdf')).toBe('document');
+ });
+});
+
+describe('reference entity type round trip', () => {
+ test.each([
+ 'document',
+ 'chat',
+ 'project',
+ 'channel',
+ 'call',
+ 'calendar_event',
+ 'crm_company',
+ 'email',
+ ] as const satisfies readonly ItemType[])(
+ '%s survives store and parse',
+ (itemType) => {
+ expect(stringToItemType(itemTypeToReferenceEntityType(itemType))).toBe(
+ itemType
+ );
+ }
+ );
+});
diff --git a/apps/web/src/lib/service-clients/service-storage/itemType.ts b/apps/web/src/lib/service-clients/service-storage/itemType.ts
index b9a668e7bd..11d603a3c4 100644
--- a/apps/web/src/lib/service-clients/service-storage/itemType.ts
+++ b/apps/web/src/lib/service-clients/service-storage/itemType.ts
@@ -1,3 +1,5 @@
+import type { BlockAlias, BlockName } from '@core/block';
+import { match } from 'ts-pattern';
import type { CloudStorageItemType } from './generated/schemas/cloudStorageItemType';
/** Item type accepted by user history endpoints. */
@@ -14,6 +16,9 @@ export type ItemType =
| 'crm_company'
| 'crm_contact';
+/** Item type assumed when a surface has no better information. */
+export const DEFAULT_ITEM_TYPE: ItemType = 'document';
+
/**
* Entity type stored on channel attachments, mentions, and referencium.
*
@@ -25,6 +30,40 @@ export function itemTypeToReferenceEntityType(itemType: ItemType): string {
return itemType === 'email' ? 'thread' : itemType;
}
+/**
+ * Parse a stored or transported entity-type string into an [`ItemType`].
+ *
+ * Referencium, mentions, and older rows spell email threads three ways
+ * (`email`, `thread`, `email_thread`); all of them parse to `email`.
+ * Never cast these strings to `ItemType` directly.
+ */
+export function stringToItemType(str: string): ItemType | undefined {
+ return match<string, ItemType | undefined>(str)
+ .with('email', 'thread', 'email_thread', () => 'email')
+ .with(
+ 'call',
+ 'calendar_event',
+ 'chat',
+ 'document',
+ 'project',
+ 'channel',
+ 'crm_company',
+ (itemType) => itemType
+ )
+ .otherwise(() => undefined);
+}
+
+export function blockNameToItemType(
+ blockName: BlockName | BlockAlias
+): ItemType {
+ return match<BlockName | BlockAlias, ItemType>(blockName)
+ .with('chat', 'call', 'channel', 'project', 'email', 'automation', (b) => b)
+ .with('calendar', () => 'calendar_event')
+ .with('company', () => 'crm_company')
+ .with('contact', () => 'crm_contact')
+ .otherwise(() => DEFAULT_ITEM_TYPE);
+}
+
/** Item types accepted by user history endpoints. */
export const ITEM_TYPES = [
'document',
diff --git a/crates/properties/src/domain/model.rs b/crates/properties/src/domain/model.rs
index de62426bba..e074bbbdbb 100644
--- a/crates/properties/src/domain/model.rs
+++ b/crates/properties/src/domain/model.rs
@@ -1,5 +1,8 @@
//! Domain models for properties.
+#[cfg(test)]
+mod test;
+
use entity_access::domain::models::{
EditAccessLevel, EntityAccessAuth, EntityAccessReceipt, EntityType as AccessEntityType,
RequiredPermission, ViewAccessLevel,
@@ -27,6 +30,33 @@ pub fn canonical_entity_type(entity_type: EntityType) -> AccessEntityType {
}
}
+/// Map a canonical entity type to its properties storage type.
+///
+/// Inverse of [`canonical_entity_type`]. `Document` covers task documents
+/// too; callers that need the task refinement resolve the document subtype
+/// themselves. `None` means the canonical type has no properties storage.
+pub fn storage_entity_type(entity_type: AccessEntityType) -> Option<EntityType> {
+ match entity_type {
+ AccessEntityType::CalendarEvent => Some(EntityType::CalendarEvent),
+ AccessEntityType::Document => Some(EntityType::Document),
+ AccessEntityType::Call => Some(EntityType::CallRecord),
+ AccessEntityType::Chat => Some(EntityType::Chat),
+ AccessEntityType::Project => Some(EntityType::Project),
+ AccessEntityType::EmailThread => Some(EntityType::Thread),
+ AccessEntityType::Channel => Some(EntityType::Channel),
+ AccessEntityType::CrmCompany => Some(EntityType::Company),
+ AccessEntityType::User => Some(EntityType::User),
+ AccessEntityType::ChannelMessage
+ | AccessEntityType::Team
+ | AccessEntityType::ForeignEntity
+ | AccessEntityType::StaticFile
+ | AccessEntityType::CrmContact
+ | AccessEntityType::Reminder
+ | AccessEntityType::Skill
+ | AccessEntityType::AgentSession => None,
+ }
+}
+
/// Proof of view (or better) access to one canonical entity.
pub type ViewReceipt = EntityAccessReceipt<ViewAccessLevel>;
/// Proof of edit (or better) access to one canonical entity.
diff --git a/crates/properties/src/domain/model/test.rs b/crates/properties/src/domain/model/test.rs
new file mode 100644
index 0000000000..c41753fcf7
--- /dev/null
+++ b/crates/properties/src/domain/model/test.rs
@@ -0,0 +1,57 @@
+use super::*;
+
+const STORAGE_TYPES: [EntityType; 10] = [
+ EntityType::CalendarEvent,
+ EntityType::CallRecord,
+ EntityType::Channel,
+ EntityType::Chat,
+ EntityType::Company,
+ EntityType::Document,
+ EntityType::Project,
+ EntityType::Task,
+ EntityType::Thread,
+ EntityType::User,
+];
+
+#[test]
+fn every_storage_type_round_trips_through_its_canonical_type() {
+ for storage in STORAGE_TYPES {
+ let expected = match storage {
+ EntityType::Task => EntityType::Document,
+ other => other,
+ };
+ assert_eq!(
+ storage_entity_type(canonical_entity_type(storage)),
+ Some(expected),
+ "{storage:?}"
+ );
+ }
+}
+
+#[test]
+fn email_thread_is_the_canonical_type_for_thread_storage() {
+ assert_eq!(
+ canonical_entity_type(EntityType::Thread),
+ AccessEntityType::EmailThread
+ );
+ assert_eq!(
+ storage_entity_type(AccessEntityType::EmailThread),
+ Some(EntityType::Thread)
+ );
+}
+
+#[test]
+fn canonical_types_without_properties_storage_map_to_none() {
+ for unsupported in [
+ AccessEntityType::ChannelMessage,
+ AccessEntityType::Team,
+ AccessEntityType::ForeignEntity,
+ AccessEntityType::StaticFile,
+ AccessEntityType::CrmContact,
+ AccessEntityType::Reminder,
+ AccessEntityType::Skill,
+ AccessEntityType::AgentSession,
+ ] {
+ assert_eq!(storage_entity_type(unsupported), None, "{unsupported:?}");
+ }
+}
diff --git a/crates/properties/src/domain/service_impl.rs b/crates/properties/src/domain/service_impl.rs
index aa75c83862..b5fc0d1124 100644
--- a/crates/properties/src/domain/service_impl.rs
+++ b/crates/properties/src/domain/service_impl.rs
@@ -290,7 +290,6 @@ where
.map(|receipt| {
let canonical_entity_type = receipt.entity_type();
let storage_entity_type = match canonical_entity_type {
- AccessEntityType::CalendarEvent => EntityType::CalendarEvent,
AccessEntityType::Document => Uuid::parse_str(receipt.entity_id())
.ok()
.and_then(|document_id| document_sub_types.get(&document_id))
@@ -300,18 +299,11 @@ where
EntityType::Document
}
}),
- AccessEntityType::EmailThread => EntityType::Thread,
- AccessEntityType::Call => EntityType::CallRecord,
- AccessEntityType::CrmCompany => EntityType::Company,
- AccessEntityType::Chat => EntityType::Chat,
- AccessEntityType::Channel => EntityType::Channel,
- AccessEntityType::Project => EntityType::Project,
- AccessEntityType::User => EntityType::User,
- unsupported => {
- return Err(PropertiesErr::Validation(format!(
- "Unsupported property target type: {unsupported}"
- )));
- }
+ other => super::model::storage_entity_type(other).ok_or_else(|| {
+ PropertiesErr::Validation(format!(
+ "Unsupported property target type: {other}"
+ ))
+ })?,
};
Ok(ResolvedPropertySubject {
diff --git a/crates/properties/src/outbound/permission_service.rs b/crates/properties/src/outbound/permission_service.rs
index a935313d79..3d41775b4d 100644
--- a/crates/properties/src/outbound/permission_service.rs
+++ b/crates/properties/src/outbound/permission_service.rs
@@ -95,18 +95,8 @@ fn caller_auth(user_id: Option<&MacroUserIdStr<'_>>) -> EntityAccessAuth {
}
fn storage_entity_type(entity_type: AccessEntityType) -> anyhow::Result<StorageEntityType> {
- Ok(match entity_type {
- AccessEntityType::CalendarEvent => StorageEntityType::CalendarEvent,
- AccessEntityType::Document => StorageEntityType::Document,
- AccessEntityType::Call => StorageEntityType::CallRecord,
- AccessEntityType::Chat => StorageEntityType::Chat,
- AccessEntityType::Project => StorageEntityType::Project,
- AccessEntityType::EmailThread => StorageEntityType::Thread,
- AccessEntityType::Channel => StorageEntityType::Channel,
- AccessEntityType::CrmCompany => StorageEntityType::Company,
- AccessEntityType::User => StorageEntityType::User,
- _ => anyhow::bail!("Unsupported property target type"),
- })
+ crate::domain::model::storage_entity_type(entity_type)
+ .ok_or_else(|| anyhow::anyhow!("Unsupported property target type"))
}
fn access_receipt<T: entity_access::domain::models::RequiredPermission>(
diff --git a/docs/STYLE_GUIDE.md b/docs/STYLE_GUIDE.md
index 55cd9b45d0..f9ec191e8c 100644
--- a/docs/STYLE_GUIDE.md
+++ b/docs/STYLE_GUIDE.md
@@ -242,3 +242,7 @@ TypeScript · `[ui]` UI / UX conventions
string can't carry structure, props, or behavior. Extract a component, or inline the
literal at its single use; styling variants are component props, not exported
strings. (enforced: ast-grep `tsx-no-class-string-consts`, warning)
+- **FE-31** `[ts]` Never cast a string to `ItemType` — parse it with `stringToItemType`
+ from `@service-storage/client`, the one owner of entity-type spellings (email
+ threads alone are stored as `email`, `thread`, and `email_thread`). (#6043 ·
+ enforced: ast-grep `ts-no-item-type-cast` + `tsx-no-item-type-cast`, CI error)
diff --git a/rules/ast-grep/ts-no-item-type-cast.yml b/rules/ast-grep/ts-no-item-type-cast.yml
new file mode 100644
index 0000000000..995f032133
--- /dev/null
+++ b/rules/ast-grep/ts-no-item-type-cast.yml
@@ -0,0 +1,16 @@
+id: ts-no-item-type-cast
+language: typescript
+# Twin of tsx-no-item-type-cast — ast-grep rules are single-language, and
+# `tsx` only scans .tsx files.
+severity: error
+message: Don't cast to ItemType — parse the string with stringToItemType from @service-storage/client.
+note: |-
+ Rule FE-31 in docs/STYLE_GUIDE.md. Entity-type strings arrive in several
+ stored spellings (email threads alone are `email`, `thread`, and
+ `email_thread`), so a cast smuggles a value no preview fetcher handles.
+ stringToItemType in src/lib/service-clients/service-storage/itemType.ts is
+ the one parser; extend it there if a spelling is missing.
+files:
+ - apps/web/src/**
+rule:
+ pattern: $EXPR as ItemType
diff --git a/rules/ast-grep/tsx-no-item-type-cast.yml b/rules/ast-grep/tsx-no-item-type-cast.yml
new file mode 100644
index 0000000000..d3bd0eedd3
--- /dev/null
+++ b/rules/ast-grep/tsx-no-item-type-cast.yml
@@ -0,0 +1,16 @@
+id: tsx-no-item-type-cast
+language: tsx
+# Twin of ts-no-item-type-cast — ast-grep rules are single-language, and
+# `typescript` only scans .ts files.
+severity: error
+message: Don't cast to ItemType — parse the string with stringToItemType from @service-storage/client.
+note: |-
+ Rule FE-31 in docs/STYLE_GUIDE.md. Entity-type strings arrive in several
+ stored spellings (email threads alone are `email`, `thread`, and
+ `email_thread`), so a cast smuggles a value no preview fetcher handles.
+ stringToItemType in src/lib/service-clients/service-storage/itemType.ts is
+ the one parser; extend it there if a spelling is missing.
+files:
+ - apps/web/src/**
+rule:
+ pattern: $EXPR as ItemType