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(channels): port attachment references endpoint to channels hex (#3611)
teoe4801b438976
diff --git a/js/app/packages/block-call/component/sidepanel/CallSidePanelSections.tsx b/js/app/packages/block-call/component/sidepanel/CallSidePanelSections.tsxindex a6e17c172c..2d30fd003c 100644--- a/js/app/packages/block-call/component/sidepanel/CallSidePanelSections.tsx+++ b/js/app/packages/block-call/component/sidepanel/CallSidePanelSections.tsx@@ -11,7 +11,7 @@ import {useSetCallRecordShareWithTeamMutation,useToggleShareWithTeamMutation,} from '@queries/call/call';-import { commsServiceClient } from '@service-comms/client';+import { storageServiceClient } from '@service-storage/client';import type { CallRecord } from '@service-storage/generated/schemas/callRecord';import { cn } from '@ui';import { type Accessor, createResource, Show, Suspense } from 'solid-js';@@ -196,7 +196,7 @@ function ReferencesSectionConditional(props: { callId: string }) {const [references] = createResource(() => props.callId,async (id) => {- const response = await commsServiceClient.attachmentReferences({+ const response = await storageServiceClient.attachmentReferences({entity_type: 'call',entity_id: id,});diff --git a/js/app/packages/block-md/component/sidepanel/MarkdownSidePanelSections.tsx b/js/app/packages/block-md/component/sidepanel/MarkdownSidePanelSections.tsxindex bdb838f047..be9efd8b96 100644--- a/js/app/packages/block-md/component/sidepanel/MarkdownSidePanelSections.tsx+++ b/js/app/packages/block-md/component/sidepanel/MarkdownSidePanelSections.tsx@@ -38,9 +38,11 @@ import { hasValue } from '@property/utils';import { useBulkSaveEntityPropertiesMutation } from '@queries/properties/entity';import { useDocumentMetadataQuery } from '@queries/storage/document-metadata';import { useDocumentGithubPullRequestsQuery } from '@queries/storage/github-pull-requests';-import { commsServiceClient } from '@service-comms/client';import type { EntityType as PropertiesEntityType } from '@service-properties/generated/schemas/entityType';-import { blockNameToItemType } from '@service-storage/client';+import {+ blockNameToItemType,+ storageServiceClient,+} from '@service-storage/client';import type { GithubPullRequest } from '@service-storage/generated/schemas';import { createCallback } from '@solid-primitives/rootless';import { cn } from '@ui/utils/classname';@@ -637,7 +639,7 @@ function ReferencesSectionConditional(props: { documentId: string }) {const [references] = createResource(() => props.documentId,async (id) => {- const response = await commsServiceClient.attachmentReferences({+ const response = await storageServiceClient.attachmentReferences({entity_type: 'document',entity_id: id,});diff --git a/js/app/packages/core/component/References.tsx b/js/app/packages/core/component/References.tsxindex e8cc5039a7..b065962496 100644--- a/js/app/packages/core/component/References.tsx+++ b/js/app/packages/core/component/References.tsx@@ -14,10 +14,9 @@ import {type PreviewItem,useItemPreview,} from '@queries/preview';-import { commsServiceClient } from '@service-comms/client';-import type { EntityReference } from '@service-comms/generated/models/entityReference';-import type { GenericReference } from '@service-comms/generated/models/genericReference';-import type { ItemType } from '@service-storage/client';+import { type ItemType, storageServiceClient } 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 { createMemo, createResource, For, type JSX, Show } from 'solid-js';import { InlineItemPreview } from './ItemPreview';import { StaticMarkdown } from './LexicalMarkdown/component/core/StaticMarkdown';@@ -220,7 +219,7 @@ function GenericReferenceRow(props: {export function References(props: ReferenceProps) {const [references] = createResource(async () => {const entityType = props.entityType ?? 'document';- const response = await commsServiceClient.attachmentReferences({+ const response = await storageServiceClient.attachmentReferences({entity_type: entityType,entity_id: props.documentId,});diff --git a/js/app/packages/core/component/ReferencesModal.tsx b/js/app/packages/core/component/ReferencesModal.tsxindex 7030dba27c..8c863e576e 100644--- a/js/app/packages/core/component/ReferencesModal.tsx+++ b/js/app/packages/core/component/ReferencesModal.tsx@@ -2,8 +2,7 @@ import { SplitDrawer } from '@app/component/split-layout/components/SplitDrawer'import { useDrawerControl } from '@app/component/split-layout/components/SplitDrawerContext';import clickOutside from '@core/directive/clickOutside';import Quotes from '@phosphor/quotes.svg';-import { commsServiceClient } from '@service-comms/client';-import type { ItemType } from '@service-storage/client';+import { type ItemType, storageServiceClient } from '@service-storage/client';import { Button, Tooltip } from '@ui';import { createResource, Suspense } from 'solid-js';import { References } from './References';@@ -86,7 +85,7 @@ function _ReferencesModal(props: ReferencesModalProps) {() => props.documentId,async (id) => {const entityType = props.entityType ?? 'document';- const response = await commsServiceClient.attachmentReferences({+ const response = await storageServiceClient.attachmentReferences({entity_type: entityType,entity_id: id,});diff --git a/js/app/packages/service-clients/service-storage/client.ts b/js/app/packages/service-clients/service-storage/client.tsindex 2300200ddf..705b521efa 100644--- a/js/app/packages/service-clients/service-storage/client.ts+++ b/js/app/packages/service-clients/service-storage/client.ts@@ -70,6 +70,7 @@ import type { DocumentResponseMetadataWithContent } from './generated/schemas/doimport type { EditAnchorResponse } from './generated/schemas/editAnchorResponse';import type { EditCommentResponse } from './generated/schemas/editCommentResponse';import type { ExportDocumentResponse } from './generated/schemas/exportDocumentResponse';+import type { GetAttachmentReferencesResponse } from './generated/schemas/getAttachmentReferencesResponse';import type { GetBatchProjectPreviewResponse } from './generated/schemas/getBatchProjectPreviewResponse';import type { GetDocumentPermissionsResponseDataV2 } from './generated/schemas/getDocumentPermissionsResponseDataV2';import type { GetDocumentProcessingResultResponse } from './generated/schemas/getDocumentProcessingResultResponse';@@ -158,6 +159,9 @@ export type ItemType =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';export type { ApiChannelAttachment } from './generated/schemas/apiChannelAttachment';export type { ApiChannelAttachmentsPage as ChannelAttachmentsPage } from './generated/schemas/apiChannelAttachmentsPage';export type { ApiChannelContextMessage } from './generated/schemas/apiChannelContextMessage';@@ -172,6 +176,7 @@ export type MessageResponse = { message: string };type WithChannelId = { channel_id: string };type WithMessageId = { message_id: string };+type WithEntity = { entity_type: string; entity_id: string };export type ChannelAttachmentType = 'static' | 'dss';export const ChannelTypeEnum = {@@ -647,6 +652,16 @@ export const storageServiceClient = {).map((result) => result);},+ async attachmentReferences(args: WithEntity) {+ const { entity_type, entity_id } = args;+ return (+ await dssFetch<GetAttachmentReferencesResponse>(+ `/channels/attachments/${entity_type}/${entity_id}/references`,+ { method: 'GET' }+ )+ ).map((result) => result);+ },+permissionsTokens: {// Uses SYNC_PERMISSION_TOKEN_DSS_HOST instead of dssFetch so that tokens are// always signed by the DSS whose JWT secret matches the sync service's secret.diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentChannelReference.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentChannelReference.tsnew file mode 100644index 0000000000..e613d2cff4--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentChannelReference.ts@@ -0,0 +1,30 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ApiAttachmentChannelReferenceChannelName } from './apiAttachmentChannelReferenceChannelName';+import type { ApiAttachmentChannelReferenceThreadId } from './apiAttachmentChannelReferenceThreadId';++/**+ * A reference to an attachment entity from a channel message.+ */+export interface ApiAttachmentChannelReference {+ /** When the attachment row was created. */+ attachment_created_at: string;+ /** Channel that contains the message. */+ channel_id: string;+ /** Optional channel name (DMs do not have a name). */+ channel_name?: ApiAttachmentChannelReferenceChannelName;+ /** Full message content (might be used for preview/snippet). */+ message_content: string;+ /** When the message itself was created. */+ message_created_at: string;+ /** Message that contains the attachment reference. */+ message_id: string;+ /** Sender of the message. */+ sender_id: string;+ /** If the message belongs to a thread this is the parent id. */+ thread_id?: ApiAttachmentChannelReferenceThreadId;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentChannelReferenceChannelName.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentChannelReferenceChannelName.tsnew file mode 100644index 0000000000..62188a72da--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentChannelReferenceChannelName.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * Optional channel name (DMs do not have a name).+ */+export type ApiAttachmentChannelReferenceChannelName = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentChannelReferenceThreadId.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentChannelReferenceThreadId.tsnew file mode 100644index 0000000000..8de1ef8381--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentChannelReferenceThreadId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * If the message belongs to a thread this is the parent id.+ */+export type ApiAttachmentChannelReferenceThreadId = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentEntityReference.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentEntityReference.tsnew file mode 100644index 0000000000..0ed041db5b--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentEntityReference.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ApiAttachmentEntityReferenceOneOf } from './apiAttachmentEntityReferenceOneOf';+import type { ApiAttachmentEntityReferenceOneOfFour } from './apiAttachmentEntityReferenceOneOfFour';++/**+ * An attachment reference, tagged by source kind.+ */+export type ApiAttachmentEntityReference =+ | ApiAttachmentEntityReferenceOneOf+ | ApiAttachmentEntityReferenceOneOfFour;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentEntityReferenceOneOf.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentEntityReferenceOneOf.tsnew file mode 100644index 0000000000..bc865ac9a9--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentEntityReferenceOneOf.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ApiAttachmentChannelReference } from './apiAttachmentChannelReference';+import type { ApiAttachmentEntityReferenceOneOfAllOf } from './apiAttachmentEntityReferenceOneOfAllOf';++/**+ * Referenced from a channel message.+ */+export type ApiAttachmentEntityReferenceOneOf = ApiAttachmentChannelReference &+ ApiAttachmentEntityReferenceOneOfAllOf;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentEntityReferenceOneOfAllOf.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentEntityReferenceOneOfAllOf.tsnew file mode 100644index 0000000000..26f717ea11--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentEntityReferenceOneOfAllOf.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ApiAttachmentEntityReferenceOneOfAllOfReferenceType } from './apiAttachmentEntityReferenceOneOfAllOfReferenceType';++export type ApiAttachmentEntityReferenceOneOfAllOf = {+ reference_type: ApiAttachmentEntityReferenceOneOfAllOfReferenceType;+};diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentEntityReferenceOneOfAllOfReferenceType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentEntityReferenceOneOfAllOfReferenceType.tsnew file mode 100644index 0000000000..76974854a8--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentEntityReferenceOneOfAllOfReferenceType.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type ApiAttachmentEntityReferenceOneOfAllOfReferenceType =+ (typeof ApiAttachmentEntityReferenceOneOfAllOfReferenceType)[keyof typeof ApiAttachmentEntityReferenceOneOfAllOfReferenceType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const ApiAttachmentEntityReferenceOneOfAllOfReferenceType = {+ channel: 'channel',+} as const;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentEntityReferenceOneOfFour.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentEntityReferenceOneOfFour.tsnew file mode 100644index 0000000000..7f88641688--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentEntityReferenceOneOfFour.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++import type { ApiAttachmentEntityReferenceOneOfFourAllOf } from './apiAttachmentEntityReferenceOneOfFourAllOf';+import type { ApiAttachmentGenericReference } from './apiAttachmentGenericReference';++/**+ * Referenced from any non-message source entity.+ */+export type ApiAttachmentEntityReferenceOneOfFour =+ ApiAttachmentGenericReference & ApiAttachmentEntityReferenceOneOfFourAllOf;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentEntityReferenceOneOfFourAllOf.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentEntityReferenceOneOfFourAllOf.tsnew file mode 100644index 0000000000..cfd3a355c6--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentEntityReferenceOneOfFourAllOf.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ApiAttachmentEntityReferenceOneOfFourAllOfReferenceType } from './apiAttachmentEntityReferenceOneOfFourAllOfReferenceType';++export type ApiAttachmentEntityReferenceOneOfFourAllOf = {+ reference_type: ApiAttachmentEntityReferenceOneOfFourAllOfReferenceType;+};diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentEntityReferenceOneOfFourAllOfReferenceType.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentEntityReferenceOneOfFourAllOfReferenceType.tsnew file mode 100644index 0000000000..23d8a7e85c--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentEntityReferenceOneOfFourAllOfReferenceType.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++export type ApiAttachmentEntityReferenceOneOfFourAllOfReferenceType =+ (typeof ApiAttachmentEntityReferenceOneOfFourAllOfReferenceType)[keyof typeof ApiAttachmentEntityReferenceOneOfFourAllOfReferenceType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const ApiAttachmentEntityReferenceOneOfFourAllOfReferenceType = {+ generic: 'generic',+} as const;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentGenericReference.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentGenericReference.tsnew file mode 100644index 0000000000..ddc4b92c7f--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentGenericReference.ts@@ -0,0 +1,25 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ApiAttachmentGenericReferenceUserId } from './apiAttachmentGenericReferenceUserId';++/**+ * A reference to an attachment entity from a non-message source.+ */+export interface ApiAttachmentGenericReference {+ /** When this reference was created. */+ created_at: string;+ /** ID of the referenced entity. */+ entity_id: string;+ /** Type of the referenced entity. */+ entity_type: string;+ /** ID of the source entity. */+ source_entity_id: string;+ /** Type of the source entity (e.g., "document", "chat", etc.). */+ source_entity_type: string;+ /** User who created this reference (optional for non-user sources). */+ user_id?: ApiAttachmentGenericReferenceUserId;+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentGenericReferenceUserId.ts b/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentGenericReferenceUserId.tsnew file mode 100644index 0000000000..4288340445--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/apiAttachmentGenericReferenceUserId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */++/**+ * User who created this reference (optional for non-user sources).+ */+export type ApiAttachmentGenericReferenceUserId = string | null;diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/getAttachmentReferencesResponse.ts b/js/app/packages/service-clients/service-storage/generated/schemas/getAttachmentReferencesResponse.tsnew file mode 100644index 0000000000..70332ccf29--- /dev/null+++ b/js/app/packages/service-clients/service-storage/generated/schemas/getAttachmentReferencesResponse.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.21.0 🍺+ * Do not edit manually.+ * document_storage_service+ * OpenAPI spec version: 0.1.0+ */+import type { ApiAttachmentEntityReference } from './apiAttachmentEntityReference';++/**+ * Response from the attachment-references endpoint.+ */+export interface GetAttachmentReferencesResponse {+ /** References to the requested entity, newest-first. */+ references: ApiAttachmentEntityReference[];+}diff --git a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts b/js/app/packages/service-clients/service-storage/generated/schemas/index.tsindex 957fb4ebc1..d1c2fa26aa 100644--- a/js/app/packages/service-clients/service-storage/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-storage/generated/schemas/index.ts@@ -40,6 +40,18 @@ export * from './annotationIncrementalUpdateOneOfSeven';export * from './annotationIncrementalUpdateOneOfSevenPayload';export * from './annotationIncrementalUpdateOneOfSevenUpdateType';export * from './annotationIncrementalUpdateOneOfUpdateType';+export * from './apiAttachmentChannelReference';+export * from './apiAttachmentChannelReferenceChannelName';+export * from './apiAttachmentChannelReferenceThreadId';+export * from './apiAttachmentEntityReference';+export * from './apiAttachmentEntityReferenceOneOf';+export * from './apiAttachmentEntityReferenceOneOfAllOf';+export * from './apiAttachmentEntityReferenceOneOfAllOfReferenceType';+export * from './apiAttachmentEntityReferenceOneOfFour';+export * from './apiAttachmentEntityReferenceOneOfFourAllOf';+export * from './apiAttachmentEntityReferenceOneOfFourAllOfReferenceType';+export * from './apiAttachmentGenericReference';+export * from './apiAttachmentGenericReferenceUserId';export * from './apiChannelAttachment';export * from './apiChannelAttachmentHeight';export * from './apiChannelAttachmentsPage';@@ -403,6 +415,7 @@ export * from './genericResponseMessage';export * from './genericSuccessResponse';export * from './getActivitiesResponse';export * from './getActivitiesResponseData';+export * from './getAttachmentReferencesResponse';export * from './getBatchCallRecordPreviewRequest';export * from './getBatchCallRecordPreviewResponse';export * from './getBatchPreviewRequest';diff --git a/js/app/packages/service-clients/service-storage/generated/zod.ts b/js/app/packages/service-clients/service-storage/generated/zod.tsindex ce82aaa129..facdeee4c7 100644--- a/js/app/packages/service-clients/service-storage/generated/zod.ts+++ b/js/app/packages/service-clients/service-storage/generated/zod.ts@@ -1266,6 +1266,102 @@ export const createChannelResponse = zod}).describe('Response returned after creating a channel.');+/**+ * @summary Handler for `GET /channels/attachments/{entity_type}/{entity_id}/references`.+ */+export const getAttachmentReferencesParams = zod.object({+ entity_type: zod.string().describe('Type of the attachment entity'),+ entity_id: zod.string().describe('Id of the attachment entity'),+});++export const getAttachmentReferencesResponse = zod+ .object({+ references: zod+ .array(+ zod+ .union([+ zod+ .object({+ attachment_created_at: zod.iso+ .datetime({})+ .describe('When the attachment row was created.'),+ channel_id: zod+ .uuid()+ .describe('Channel that contains the message.'),+ channel_name: zod+ .string()+ .nullish()+ .describe('Optional channel name (DMs do not have a name).'),+ message_content: zod+ .string()+ .describe(+ 'Full message content (might be used for preview\/snippet).'+ ),+ message_created_at: zod.iso+ .datetime({})+ .describe('When the message itself was created.'),+ message_id: zod+ .uuid()+ .describe('Message that contains the attachment reference.'),+ sender_id: zod.string().describe('Sender of the message.'),+ thread_id: zod+ .uuid()+ .nullish()+ .describe(+ 'If the message belongs to a thread this is the parent id.'+ ),+ })+ .describe(+ 'A reference to an attachment entity from a channel message.'+ )+ .and(+ zod.object({+ reference_type: zod.enum(['channel']),+ })+ )+ .describe('Referenced from a channel message.'),+ zod+ .object({+ created_at: zod.iso+ .datetime({})+ .describe('When this reference was created.'),+ entity_id: zod+ .string()+ .describe('ID of the referenced entity.'),+ entity_type: zod+ .string()+ .describe('Type of the referenced entity.'),+ source_entity_id: zod+ .string()+ .describe('ID of the source entity.'),+ source_entity_type: zod+ .string()+ .describe(+ 'Type of the source entity (e.g., \"document\", \"chat\", etc.).'+ ),+ user_id: zod+ .string()+ .nullish()+ .describe(+ 'User who created this reference (optional for non-user sources).'+ ),+ })+ .describe(+ 'A reference to an attachment entity from a non-message source.'+ )+ .and(+ zod.object({+ reference_type: zod.enum(['generic']),+ })+ )+ .describe('Referenced from any non-message source entity.'),+ ])+ .describe('An attachment reference, tagged by source kind.')+ )+ .describe('References to the requested entity, newest-first.'),+ })+ .describe('Response from the attachment-references endpoint.');+/*** @summary Handler for `POST /channels/get_or_create_dm`.*/diff --git a/js/app/packages/service-clients/service-storage/openapi.json b/js/app/packages/service-clients/service-storage/openapi.jsonindex 8cb6a19594..b33b481a70 100644--- a/js/app/packages/service-clients/service-storage/openapi.json+++ b/js/app/packages/service-clients/service-storage/openapi.json@@ -1295,6 +1295,75 @@}}},+ "/channels/attachments/{entity_type}/{entity_id}/references": {+ "get": {+ "tags": ["channels::inbound::axum_router"],+ "summary": "Handler for `GET /channels/attachments/{entity_type}/{entity_id}/references`.",+ "operationId": "get_attachment_references",+ "parameters": [+ {+ "name": "entity_type",+ "in": "path",+ "description": "Type of the attachment entity",+ "required": true,+ "schema": {+ "type": "string"+ }+ },+ {+ "name": "entity_id",+ "in": "path",+ "description": "Id of the attachment entity",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "responses": {+ "200": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/GetAttachmentReferencesResponse"+ }+ }+ }+ },+ "401": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "404": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ },+ "500": {+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }+ }+ }+ }+ },"/channels/get_or_create_dm": {"post": {"tags": ["channels"],@@ -7602,6 +7671,138 @@}]},+ "ApiAttachmentChannelReference": {+ "type": "object",+ "description": "A reference to an attachment entity from a channel message.",+ "required": [+ "channel_id",+ "message_id",+ "sender_id",+ "message_content",+ "message_created_at",+ "attachment_created_at"+ ],+ "properties": {+ "attachment_created_at": {+ "type": "string",+ "format": "date-time",+ "description": "When the attachment row was created."+ },+ "channel_id": {+ "type": "string",+ "format": "uuid",+ "description": "Channel that contains the message."+ },+ "channel_name": {+ "type": ["string", "null"],+ "description": "Optional channel name (DMs do not have a name)."+ },+ "message_content": {+ "type": "string",+ "description": "Full message content (might be used for preview/snippet)."+ },+ "message_created_at": {+ "type": "string",+ "format": "date-time",+ "description": "When the message itself was created."+ },+ "message_id": {+ "type": "string",+ "format": "uuid",+ "description": "Message that contains the attachment reference."+ },+ "sender_id": {+ "type": "string",+ "description": "Sender of the message."+ },+ "thread_id": {+ "type": ["string", "null"],+ "format": "uuid",+ "description": "If the message belongs to a thread this is the parent id."+ }+ }+ },+ "ApiAttachmentEntityReference": {+ "oneOf": [+ {+ "allOf": [+ {+ "$ref": "#/components/schemas/ApiAttachmentChannelReference",+ "description": "Referenced from a channel message."+ },+ {+ "type": "object",+ "required": ["reference_type"],+ "properties": {+ "reference_type": {+ "type": "string",+ "enum": ["channel"]+ }+ }+ }+ ],+ "description": "Referenced from a channel message."+ },+ {+ "allOf": [+ {+ "$ref": "#/components/schemas/ApiAttachmentGenericReference",+ "description": "Referenced from any non-message source entity."+ },+ {+ "type": "object",+ "required": ["reference_type"],+ "properties": {+ "reference_type": {+ "type": "string",+ "enum": ["generic"]+ }+ }+ }+ ],+ "description": "Referenced from any non-message source entity."+ }+ ],+ "description": "An attachment reference, tagged by source kind."+ },+ "ApiAttachmentGenericReference": {+ "type": "object",+ "description": "A reference to an attachment entity from a non-message source.",+ "required": [+ "source_entity_type",+ "source_entity_id",+ "entity_type",+ "entity_id",+ "created_at"+ ],+ "properties": {+ "created_at": {+ "type": "string",+ "format": "date-time",+ "description": "When this reference was created."+ },+ "entity_id": {+ "type": "string",+ "description": "ID of the referenced entity."+ },+ "entity_type": {+ "type": "string",+ "description": "Type of the referenced entity."+ },+ "source_entity_id": {+ "type": "string",+ "description": "ID of the source entity."+ },+ "source_entity_type": {+ "type": "string",+ "description": "Type of the source entity (e.g., \"document\", \"chat\", etc.)."+ },+ "user_id": {+ "type": ["string", "null"],+ "description": "User who created this reference (optional for non-user sources)."+ }+ }+ },"ApiChannelAttachment": {"type": "object","description": "A channel-level attachment.",@@ -11292,6 +11493,20 @@},"deprecated": true},+ "GetAttachmentReferencesResponse": {+ "type": "object",+ "description": "Response from the attachment-references endpoint.",+ "required": ["references"],+ "properties": {+ "references": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ApiAttachmentEntityReference"+ },+ "description": "References to the requested entity, newest-first."+ }+ }+ },"GetBatchCallRecordPreviewRequest": {"type": "object","description": "Request body for `POST /call/record/preview`.\n\nThe `call_ids` list is bounded at [`MAX_BATCH_CALL_IDS`]; the handler\nrejects anything larger with a 400 before touching the database.",diff --git a/rust/cloud-storage/channels/fixtures/channels_repo.sql b/rust/cloud-storage/channels/fixtures/channels_repo.sqlindex c0465e5721..b93b05deb3 100644--- a/rust/cloud-storage/channels/fixtures/channels_repo.sql+++ b/rust/cloud-storage/channels/fixtures/channels_repo.sql@@ -97,3 +97,16 @@ INSERT INTO comms_channel_participants (channel_id, user_id, role, joined_at, le('00000000-0000-0000-0000-000000000c01', 'macro|[email protected]', 'admin', '2024-01-01 00:01:00+00', NULL),('00000000-0000-0000-0000-000000000c01', 'macro|[email protected]', 'member', '2024-01-01 00:02:00+00', NULL),('00000000-0000-0000-0000-000000000c01', 'macro|[email protected]', 'member', '2024-01-01 00:03:00+00', '2024-01-05 00:00:00+00');++-- entity mentions (used by attachment-references tests)+-- doc-mention is mentioned inside msg3 (a message source → channel reference, gated by participation)+-- doc-generic is mentioned by a non-message source (doc → generic reference, not gated)+-- doc-2 already has a direct attachment on msg3 (a003, 12:00); this newer generic mention+-- lets the merge/sort test assert generic-before-channel ordering+INSERT INTO comms_entity_mentions (id, source_entity_type, source_entity_id, entity_type, entity_id, user_id, created_at) VALUES+ ('00000000-0000-0000-0000-00000000e001', 'message', '00000000-0000-0000-0000-000000000003',+ 'document', 'doc-mention', 'macro|[email protected]', '2024-01-01 12:00:00+00'),+ ('00000000-0000-0000-0000-00000000e002', 'doc', 'src-doc',+ 'document', 'doc-generic', 'macro|[email protected]', '2024-01-03 00:00:00+00'),+ ('00000000-0000-0000-0000-00000000e003', 'doc', 'src-doc-2',+ 'document', 'doc-2', 'macro|[email protected]', '2024-01-04 00:00:00+00');diff --git a/rust/cloud-storage/channels/src/domain/models.rs b/rust/cloud-storage/channels/src/domain/models.rsindex a79b49233f..c611ee3e70 100644--- a/rust/cloud-storage/channels/src/domain/models.rs+++ b/rust/cloud-storage/channels/src/domain/models.rs@@ -319,6 +319,53 @@ pub struct ChannelContextMessage {pub deleted_at: Option<DateTime<Utc>>,}+/// A reference to an attachment entity originating from a channel message.+#[derive(Debug, Clone, PartialEq)]+pub struct AttachmentChannelReference {+ /// Channel that contains the message.+ pub channel_id: Uuid,+ /// Optional channel name (DMs do not have a name).+ pub channel_name: Option<String>,+ /// Message that contains the attachment reference.+ pub message_id: Uuid,+ /// If the message belongs to a thread this is the parent id.+ pub thread_id: Option<Uuid>,+ /// Sender of the message.+ pub sender_id: String,+ /// Full message content (might be used for preview/snippet).+ pub message_content: String,+ /// When the message itself was created.+ pub message_created_at: DateTime<Utc>,+ /// When the attachment row was created.+ pub attachment_created_at: DateTime<Utc>,+}++/// A reference to an attachment entity from any non-message source entity.+#[derive(Debug, Clone, PartialEq)]+pub struct AttachmentGenericReference {+ /// Type of the source entity (e.g., "document", "chat", etc.).+ pub source_entity_type: String,+ /// ID of the source entity.+ pub source_entity_id: String,+ /// Type of the referenced entity.+ pub entity_type: String,+ /// ID of the referenced entity.+ pub entity_id: String,+ /// User who created this reference (optional for non-user sources).+ pub user_id: Option<String>,+ /// When this reference was created.+ pub created_at: DateTime<Utc>,+}++/// A reference to an attachment entity, tagged by source kind.+#[derive(Debug, Clone, PartialEq)]+pub enum AttachmentEntityReference {+ /// Referenced from a channel message.+ Channel(AttachmentChannelReference),+ /// Referenced from any non-message source entity.+ Generic(AttachmentGenericReference),+}+/// Raw row returned from the top-level messages query.#[derive(Debug, Clone)]pub struct TopLevelMessageRow {diff --git a/rust/cloud-storage/channels/src/domain/ports.rs b/rust/cloud-storage/channels/src/domain/ports.rsindex 24ec8a150f..7f0b1e09eb 100644--- a/rust/cloud-storage/channels/src/domain/ports.rs+++ b/rust/cloud-storage/channels/src/domain/ports.rs@@ -1,13 +1,14 @@use crate::domain::events::ChannelEvent;use crate::domain::models::{- AddParticipantsRequest, ChannelAttachment, ChannelAttachmentType, ChannelContextMessage,- ChannelInfo, ChannelMessageFilters, ChannelMetadata, ChannelParticipant, CountedReaction,- CreateChannelRequest, CreateChannelResponse, DeleteMessageQuery, GetOrCreateChannelResponse,- GetOrCreateDmRequest, GetOrCreatePrivateRequest, MessageAttachment, MessagePageDirection,- MutatedAttachment, MutatedMessage, NewChannelAttachment, PatchChannelRequest,- PatchMessageRequest, PostMessageRequest, PostMessageResponse, PostReactionRequest,- PostTypingRequest, ReferencedShareItem, RemoveParticipantsRequest, ResolvedChannelMessage,- SimpleMention, ThreadData, ThreadReply, ThreadReplyRow, TopLevelMessageRow,+ AddParticipantsRequest, AttachmentEntityReference, ChannelAttachment, ChannelAttachmentType,+ ChannelContextMessage, ChannelInfo, ChannelMessageFilters, ChannelMetadata, ChannelParticipant,+ CountedReaction, CreateChannelRequest, CreateChannelResponse, DeleteMessageQuery,+ GetOrCreateChannelResponse, GetOrCreateDmRequest, GetOrCreatePrivateRequest, MessageAttachment,+ MessagePageDirection, MutatedAttachment, MutatedMessage, NewChannelAttachment,+ PatchChannelRequest, PatchMessageRequest, PostMessageRequest, PostMessageResponse,+ PostReactionRequest, PostTypingRequest, ReferencedShareItem, RemoveParticipantsRequest,+ ResolvedChannelMessage, SimpleMention, ThreadData, ThreadReply, ThreadReplyRow,+ TopLevelMessageRow,};use crate::domain::side_effects::{ChannelDocumentMention, ChannelNotificationEffect, ChannelRealtimeEffect,@@ -87,6 +88,14 @@ pub trait ChannelRepo: Send + Sync + 'static {after: i64,) -> impl Future<Output = Result<Vec<ChannelContextMessage>, Self::Err>> + Send;+ /// Fetch attachment references for an entity, scoped to channels the user belongs to.+ fn get_attachment_references(+ &self,+ entity_type: &str,+ entity_id: &str,+ user_id: &str,+ ) -> impl Future<Output = Result<Vec<AttachmentEntityReference>, Self::Err>> + Send;+/// Resolve a message id to its top-level parent row. If the message is a thread reply,/// returns the parent; if already top-level, returns itself. Returns `None` if not found.fn resolve_top_level_parent(@@ -355,6 +364,14 @@ pub trait ChannelService: Send + Sync + 'static {async move { Err(ChannelMessagesErr::MessageNotFound(message_id)) }}+ /// Fetch attachment references for an entity visible to a user.+ fn get_attachment_references(+ &self,+ entity_type: String,+ entity_id: String,+ user_id: String,+ ) -> impl Future<Output = Result<Vec<AttachmentEntityReference>, ChannelMessagesErr>> + Send;+/// Fetch a centered window of messages around a specific message id.////// The result's `has_more_newer` reports whether newer messages exist outside thediff --git a/rust/cloud-storage/channels/src/domain/service.rs b/rust/cloud-storage/channels/src/domain/service.rsindex ca2dc137f8..5220f3d45c 100644--- a/rust/cloud-storage/channels/src/domain/service.rs+++ b/rust/cloud-storage/channels/src/domain/service.rs@@ -1,14 +1,14 @@use crate::domain::{events::ChannelEvent,models::{- AddParticipantsRequest, ChannelAttachmentType, ChannelContextMessage, ChannelMessage,- ChannelMessageFilters, ChannelParticipant, ChannelType, DeleteMessageQuery,- GetOrCreateAction, GetOrCreateChannelResponse, GetOrCreateDmRequest,- GetOrCreatePrivateRequest, MessagePageDirection, NewChannelAttachment, ParticipantRole,- PatchChannelRequest, PatchMessageRequest, PostMessageRequest, PostMessageResponse,- PostReactionRequest, PostTypingRequest, ReactionAction, ReferencedShareItem,- RemoveParticipantsRequest, ResolvedChannelMessage, SimpleMention, ThreadInfo, ThreadReply,- TopLevelMessageRow,+ AddParticipantsRequest, AttachmentEntityReference, ChannelAttachmentType,+ ChannelContextMessage, ChannelMessage, ChannelMessageFilters, ChannelParticipant,+ ChannelType, DeleteMessageQuery, GetOrCreateAction, GetOrCreateChannelResponse,+ GetOrCreateDmRequest, GetOrCreatePrivateRequest, MessagePageDirection,+ NewChannelAttachment, ParticipantRole, PatchChannelRequest, PatchMessageRequest,+ PostMessageRequest, PostMessageResponse, PostReactionRequest, PostTypingRequest,+ ReactionAction, ReferencedShareItem, RemoveParticipantsRequest, ResolvedChannelMessage,+ SimpleMention, ThreadInfo, ThreadReply, TopLevelMessageRow,},ports::{ChannelAttachmentsPage, ChannelEventDispatcher, ChannelMessagesErr,@@ -1226,6 +1226,20 @@ where.map_err(ChannelMessagesErr::Repo)}+ #[tracing::instrument(err, skip(self, user_id))]+ async fn get_attachment_references(+ &self,+ entity_type: String,+ entity_id: String,+ user_id: String,+ ) -> Result<Vec<AttachmentEntityReference>, ChannelMessagesErr> {+ self.repo+ .get_attachment_references(&entity_type, &entity_id, &user_id)+ .await+ .map_err(anyhow::Error::from)+ .map_err(ChannelMessagesErr::Repo)+ }+#[tracing::instrument(err, skip(self))]async fn get_channel_messages_around(&self,diff --git a/rust/cloud-storage/channels/src/domain/service/test.rs b/rust/cloud-storage/channels/src/domain/service/test.rsindex 805f947d77..e02eb05a5a 100644--- a/rust/cloud-storage/channels/src/domain/service/test.rs+++ b/rust/cloud-storage/channels/src/domain/service/test.rs@@ -313,6 +313,15 @@ impl ChannelRepo for FakeMutationRepo {Ok(vec![])}+ async fn get_attachment_references(+ &self,+ _entity_type: &str,+ _entity_id: &str,+ _user_id: &str,+ ) -> Result<Vec<crate::domain::models::AttachmentEntityReference>, Self::Err> {+ Ok(vec![])+ }+async fn resolve_top_level_parent(&self,_channel_id: Uuid,diff --git a/rust/cloud-storage/channels/src/inbound/axum_router.rs b/rust/cloud-storage/channels/src/inbound/axum_router.rsindex dfe0462da8..be9a546b74 100644--- a/rust/cloud-storage/channels/src/inbound/axum_router.rs+++ b/rust/cloud-storage/channels/src/inbound/axum_router.rs@@ -8,6 +8,7 @@ pub use crate::domain::models::{PostReactionRequest, PostTypingRequest, RemoveParticipantsRequest,};use crate::domain::models::{+ AttachmentChannelReference, AttachmentEntityReference, AttachmentGenericReference,ChannelAttachment, ChannelAttachmentType, ChannelContextMessage, ChannelMessage,ChannelMessageKind, ChannelParticipant, CountedReaction, MessageAttachment,MessagePageDirection, ParticipantRole, ResolvedChannelMessage, ThreadInfo, ThreadReply,@@ -171,6 +172,15 @@ pub struct ChannelPath {channel_id: Uuid,}+/// Path params for the attachment-references endpoint.+#[derive(Debug, Deserialize)]+pub struct AttachmentReferencesPath {+ /// Type of the attachment entity.+ entity_type: String,+ /// Id of the attachment entity.+ entity_id: String,+}+fn parse_messages_query(cursor: Option<BidirectionalCursor<Uuid, CreatedAt, ()>>,) -> (@@ -292,6 +302,10 @@ where"/{channel_id}/participants",get(get_channel_participants_handler::<S, Svc>),)+ .route(+ "/attachments/{entity_type}/{entity_id}/references",+ get(get_attachment_references_handler::<S, Svc>),+ ).with_state(state)}@@ -1118,6 +1132,52 @@ pub async fn get_channel_participants_handler<S: ChannelService, Svc: EntityAcce))}+/// Handler for `GET /channels/attachments/{entity_type}/{entity_id}/references`.+#[utoipa::path(+ get,+ operation_id = "get_attachment_references",+ path = "/channels/attachments/{entity_type}/{entity_id}/references",+ params(+ ("entity_type" = String, Path, description = "Type of the attachment entity"),+ ("entity_id" = String, Path, description = "Id of the attachment entity"),+ ),+ responses(+ (status = 200, body = GetAttachmentReferencesResponse),+ (status = 401, body = ErrorResponse),+ (status = 404, body = ErrorResponse),+ (status = 500, body = ErrorResponse),+ )+)]+#[tracing::instrument(+ err,+ skip_all,+ fields(+ entity_type = tracing::field::Empty,+ entity_id = tracing::field::Empty,+ )+)]+pub async fn get_attachment_references_handler<S: ChannelService, Svc: EntityAccessService>(+ State(state): State<ChannelsRouterState<S, Svc>>,+ Extension(user_context): Extension<UserContext>,+ Path(path): Path<AttachmentReferencesPath>,+) -> Result<Json<GetAttachmentReferencesResponse>, ChannelsHandlerErr> {+ let span = tracing::Span::current();+ span.record("entity_type", tracing::field::display(&path.entity_type));+ span.record("entity_id", tracing::field::display(&path.entity_id));++ let references = state+ .service+ .get_attachment_references(path.entity_type, path.entity_id, user_context.user_id)+ .await?;++ Ok(Json(GetAttachmentReferencesResponse {+ references: references+ .into_iter()+ .map(ApiAttachmentEntityReference::from)+ .collect(),+ }))+}+/// Paginated response of channel messages.#[derive(Debug, Serialize, utoipa::ToSchema)]pub struct ApiChannelMessagesPage {@@ -1228,6 +1288,102 @@ impl From<ChannelContextMessage> for ApiChannelContextMessage {}}+/// Response from the attachment-references endpoint.+#[derive(Debug, Serialize, utoipa::ToSchema)]+pub struct GetAttachmentReferencesResponse {+ /// References to the requested entity, newest-first.+ pub references: Vec<ApiAttachmentEntityReference>,+}++/// An attachment reference, tagged by source kind.+#[derive(Debug, Serialize, utoipa::ToSchema)]+#[serde(tag = "reference_type", rename_all = "snake_case")]+pub enum ApiAttachmentEntityReference {+ /// Referenced from a channel message.+ Channel(ApiAttachmentChannelReference),+ /// Referenced from any non-message source entity.+ Generic(ApiAttachmentGenericReference),+}++impl From<AttachmentEntityReference> for ApiAttachmentEntityReference {+ fn from(reference: AttachmentEntityReference) -> Self {+ match reference {+ AttachmentEntityReference::Channel(c) => {+ Self::Channel(ApiAttachmentChannelReference::from(c))+ }+ AttachmentEntityReference::Generic(g) => {+ Self::Generic(ApiAttachmentGenericReference::from(g))+ }+ }+ }+}++/// A reference to an attachment entity from a channel message.+#[derive(Debug, Serialize, utoipa::ToSchema)]+pub struct ApiAttachmentChannelReference {+ /// Channel that contains the message.+ pub channel_id: Uuid,+ /// Optional channel name (DMs do not have a name).+ pub channel_name: Option<String>,+ /// Message that contains the attachment reference.+ pub message_id: Uuid,+ /// If the message belongs to a thread this is the parent id.+ pub thread_id: Option<Uuid>,+ /// Sender of the message.+ pub sender_id: String,+ /// Full message content (might be used for preview/snippet).+ pub message_content: String,+ /// When the message itself was created.+ pub message_created_at: DateTime<Utc>,+ /// When the attachment row was created.+ pub attachment_created_at: DateTime<Utc>,+}++impl From<AttachmentChannelReference> for ApiAttachmentChannelReference {+ fn from(r: AttachmentChannelReference) -> Self {+ Self {+ channel_id: r.channel_id,+ channel_name: r.channel_name,+ message_id: r.message_id,+ thread_id: r.thread_id,+ sender_id: r.sender_id,+ message_content: r.message_content,+ message_created_at: r.message_created_at,+ attachment_created_at: r.attachment_created_at,+ }+ }+}++/// A reference to an attachment entity from a non-message source.+#[derive(Debug, Serialize, utoipa::ToSchema)]+pub struct ApiAttachmentGenericReference {+ /// Type of the source entity (e.g., "document", "chat", etc.).+ pub source_entity_type: String,+ /// ID of the source entity.+ pub source_entity_id: String,+ /// Type of the referenced entity.+ pub entity_type: String,+ /// ID of the referenced entity.+ pub entity_id: String,+ /// User who created this reference (optional for non-user sources).+ pub user_id: Option<String>,+ /// When this reference was created.+ pub created_at: DateTime<Utc>,+}++impl From<AttachmentGenericReference> for ApiAttachmentGenericReference {+ fn from(r: AttachmentGenericReference) -> Self {+ Self {+ source_entity_type: r.source_entity_type,+ source_entity_id: r.source_entity_id,+ entity_type: r.entity_type,+ entity_id: r.entity_id,+ user_id: r.user_id,+ created_at: r.created_at,+ }+ }+}+/// Thread metadata and preview replies.#[derive(Debug, Serialize, utoipa::ToSchema)]pub struct ApiThreadInfo {diff --git a/rust/cloud-storage/channels/src/inbound/axum_router/test.rs b/rust/cloud-storage/channels/src/inbound/axum_router/test.rsindex b72fd0c288..900ca017f4 100644--- a/rust/cloud-storage/channels/src/inbound/axum_router/test.rs+++ b/rust/cloud-storage/channels/src/inbound/axum_router/test.rs@@ -262,6 +262,39 @@ impl ChannelService for MockService {deleted_at: None,}])}++ async fn get_attachment_references(+ &self,+ entity_type: String,+ entity_id: String,+ _user_id: String,+ ) -> Result<Vec<crate::domain::models::AttachmentEntityReference>, ChannelMessagesErr> {+ let now = chrono::Utc::now();+ Ok(vec![+ crate::domain::models::AttachmentEntityReference::Channel(+ crate::domain::models::AttachmentChannelReference {+ channel_id: Uuid::new_v4(),+ channel_name: Some("test-channel".to_string()),+ message_id: Uuid::new_v4(),+ thread_id: None,+ sender_id: "macro|[email protected]".to_string(),+ message_content: "look at this".to_string(),+ message_created_at: now,+ attachment_created_at: now,+ },+ ),+ crate::domain::models::AttachmentEntityReference::Generic(+ crate::domain::models::AttachmentGenericReference {+ source_entity_type: "doc".to_string(),+ source_entity_id: "src-doc".to_string(),+ entity_type,+ entity_id,+ user_id: None,+ created_at: now,+ },+ ),+ ])+ }}struct ErrorService;@@ -312,6 +345,15 @@ impl ChannelService for ErrorService {) -> Result<Vec<crate::domain::models::ThreadReply>, ChannelMessagesErr> {Err(ChannelMessagesErr::Repo(anyhow::anyhow!("database error")))}++ async fn get_attachment_references(+ &self,+ _entity_type: String,+ _entity_id: String,+ _user_id: String,+ ) -> Result<Vec<crate::domain::models::AttachmentEntityReference>, ChannelMessagesErr> {+ Err(ChannelMessagesErr::Repo(anyhow::anyhow!("database error")))+ }}struct ParticipantsService;@@ -395,6 +437,15 @@ impl ChannelService for ParticipantsService {) -> Result<Vec<crate::domain::models::ThreadReply>, ChannelMessagesErr> {Ok(vec![])}++ async fn get_attachment_references(+ &self,+ _entity_type: String,+ _entity_id: String,+ _user_id: String,+ ) -> Result<Vec<crate::domain::models::AttachmentEntityReference>, ChannelMessagesErr> {+ Ok(vec![])+ }}#[derive(Clone, Default)]@@ -596,6 +647,15 @@ impl ChannelService for RecordingMutationService {) -> Result<(), ChannelMutationErr> {Ok(())}++ async fn get_attachment_references(+ &self,+ _entity_type: String,+ _entity_id: String,+ _user_id: String,+ ) -> Result<Vec<crate::domain::models::AttachmentEntityReference>, ChannelMessagesErr> {+ Ok(vec![])+ }}fn user_extension() -> Extension<UserContext> {@@ -917,6 +977,15 @@ impl ChannelService for NotFoundService {) -> Result<Vec<crate::domain::models::ThreadReply>, ChannelMessagesErr> {Err(ChannelMessagesErr::MessageNotFound(message_id))}++ async fn get_attachment_references(+ &self,+ _entity_type: String,+ _entity_id: String,+ _user_id: String,+ ) -> Result<Vec<crate::domain::models::AttachmentEntityReference>, ChannelMessagesErr> {+ Ok(vec![])+ }}struct AroundHasItemsService {@@ -1006,6 +1075,15 @@ impl ChannelService for AroundHasItemsService {) -> Result<Vec<crate::domain::models::ThreadReply>, ChannelMessagesErr> {Ok(vec![])}++ async fn get_attachment_references(+ &self,+ _entity_type: String,+ _entity_id: String,+ _user_id: String,+ ) -> Result<Vec<crate::domain::models::AttachmentEntityReference>, ChannelMessagesErr> {+ Ok(vec![])+ }}#[tokio::test]@@ -1190,6 +1268,15 @@ impl ChannelService for std::sync::Arc<CapturingService> {) -> Result<Vec<crate::domain::models::ThreadReply>, ChannelMessagesErr> {Ok(vec![])}++ async fn get_attachment_references(+ &self,+ _entity_type: String,+ _entity_id: String,+ _user_id: String,+ ) -> Result<Vec<crate::domain::models::AttachmentEntityReference>, ChannelMessagesErr> {+ Ok(vec![])+ }}#[tokio::test]@@ -1387,6 +1474,28 @@ async fn thread_replies_returns_404_when_not_found() {assert_eq!(json["message"], "Message not found");}+#[tokio::test]+async fn attachment_references_returns_tagged_references() {+ let router = mock_router();+ let request = Request::builder()+ .uri("/attachments/document/doc1/references")+ .body(axum::body::Body::empty())+ .unwrap();++ let res = router.oneshot(request).await.unwrap();+ assert_eq!(res.status(), StatusCode::OK);++ let bytes = res.into_body().collect().await.unwrap().to_bytes();+ let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();+ let references = json["references"].as_array().unwrap();+ assert_eq!(references.len(), 2);+ assert_eq!(references[0]["reference_type"], "channel");+ assert_eq!(references[0]["message_content"], "look at this");+ assert_eq!(references[1]["reference_type"], "generic");+ assert_eq!(references[1]["entity_id"], "doc1");+ assert_eq!(references[1]["source_entity_type"], "doc");+}+#[tokio::test]async fn message_context_returns_flat_context_response() {let router = mock_router();diff --git a/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs b/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rsindex d8b949de41..c9aac70eec 100644--- a/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs+++ b/rust/cloud-storage/channels/src/outbound/pg_channels_repo.rs@@ -3,6 +3,7 @@ mod tests;use crate::domain::{models::{+ AttachmentChannelReference, AttachmentEntityReference, AttachmentGenericReference,ChannelAttachment, ChannelAttachmentType, ChannelContextMessage, ChannelInfo,ChannelMessageFilters, ChannelMessageKind, ChannelMetadata, ChannelParticipant,ChannelType, CountedReaction, CreateChannelRequest, MessageAttachment,@@ -1234,6 +1235,137 @@ impl ChannelRepo for PgChannelsRepo {.collect())}+ #[tracing::instrument(err, skip(self, user_id))]+ async fn get_attachment_references(+ &self,+ entity_type: &str,+ entity_id: &str,+ user_id: &str,+ ) -> Result<Vec<AttachmentEntityReference>, Self::Err> {+ let attachment_references = sqlx::query_as!(+ AttachmentChannelReference,+ r#"+ SELECT+ a.channel_id AS "channel_id: uuid::Uuid",+ c.name AS "channel_name?", -- Option<String>+ a.message_id AS "message_id: uuid::Uuid",+ m.thread_id AS "thread_id?: uuid::Uuid",+ m.sender_id AS "sender_id!", -- String+ m.content AS "message_content!", -- String+ m.created_at AS "message_created_at!: chrono::DateTime<chrono::Utc>",+ a.created_at AS "attachment_created_at!: chrono::DateTime<chrono::Utc>"+ FROM comms_attachments a+ JOIN comms_messages m ON a.message_id = m.id+ JOIN comms_channels c ON a.channel_id = c.id+ JOIN comms_channel_participants cp ON cp.channel_id = c.id+ WHERE a.entity_type = $1+ AND a.entity_id = $2+ AND cp.user_id = $3+ AND cp.left_at IS NULL+ AND m.deleted_at IS NULL+ ORDER BY a.created_at DESC+ "#,+ entity_type,+ entity_id,+ user_id,+ )+ .fetch_all(&self.pool)+ .await+ .context("failed to get attachment references")?;++ let mention_references = sqlx::query_as!(+ AttachmentChannelReference,+ r#"+ SELECT+ m.channel_id AS "channel_id: uuid::Uuid",+ c.name AS "channel_name?", -- Option<String>+ m.id AS "message_id: uuid::Uuid",+ m.thread_id AS "thread_id?: uuid::Uuid",+ m.sender_id AS "sender_id!", -- String+ m.content AS "message_content!", -- String+ m.created_at AS "message_created_at!: chrono::DateTime<chrono::Utc>",+ em.created_at AS "attachment_created_at!: chrono::DateTime<chrono::Utc>"+ FROM comms_entity_mentions em+ JOIN comms_messages m ON (em.source_entity_id = m.id::text AND em.source_entity_type = 'message')+ JOIN comms_channels c ON m.channel_id = c.id+ JOIN comms_channel_participants cp ON cp.channel_id = c.id+ WHERE em.entity_type = $1+ AND em.entity_id = $2+ AND cp.user_id = $3+ AND cp.left_at IS NULL+ AND m.deleted_at IS NULL+ ORDER BY em.created_at DESC+ "#,+ entity_type,+ entity_id,+ user_id,+ )+ .fetch_all(&self.pool)+ .await+ .context("failed to get mention references")?;++ let generic_references = sqlx::query!(+ r#"+ SELECT+ em.source_entity_type,+ em.source_entity_id,+ em.entity_type,+ em.entity_id,+ em.user_id,+ em.created_at+ FROM comms_entity_mentions em+ WHERE em.entity_type = $1+ AND em.entity_id = $2+ AND em.source_entity_type != 'message'+ ORDER BY em.created_at DESC+ "#,+ entity_type,+ entity_id,+ )+ .fetch_all(&self.pool)+ .await+ .context("failed to get generic entity references")?+ .into_iter()+ .map(|row| AttachmentGenericReference {+ source_entity_type: row.source_entity_type,+ source_entity_id: row.source_entity_id,+ entity_type: row.entity_type,+ entity_id: row.entity_id,+ user_id: row.user_id,+ created_at: row.created_at,+ })+ .collect::<Vec<_>>();++ let mut references: Vec<AttachmentEntityReference> = attachment_references+ .into_iter()+ .map(AttachmentEntityReference::Channel)+ .collect();+ references.extend(+ mention_references+ .into_iter()+ .map(AttachmentEntityReference::Channel),+ );+ references.extend(+ generic_references+ .into_iter()+ .map(AttachmentEntityReference::Generic),+ );++ references.sort_by(|a, b| {+ let a_time = match a {+ AttachmentEntityReference::Channel(c) => c.attachment_created_at,+ AttachmentEntityReference::Generic(g) => g.created_at,+ };+ let b_time = match b {+ AttachmentEntityReference::Channel(c) => c.attachment_created_at,+ AttachmentEntityReference::Generic(g) => g.created_at,+ };+ b_time.cmp(&a_time)+ });++ Ok(references)+ }+#[tracing::instrument(err, skip(self))]async fn resolve_top_level_parent(&self,diff --git a/rust/cloud-storage/channels/src/outbound/pg_channels_repo/tests.rs b/rust/cloud-storage/channels/src/outbound/pg_channels_repo/tests.rsindex 9ba23db4e6..651adf8545 100644--- a/rust/cloud-storage/channels/src/outbound/pg_channels_repo/tests.rs+++ b/rust/cloud-storage/channels/src/outbound/pg_channels_repo/tests.rs@@ -1,5 +1,6 @@use crate::domain::models::{- ChannelMessageFilters, MessagePageDirection, NotificationFilters, ParticipantRole,+ AttachmentEntityReference, ChannelMessageFilters, MessagePageDirection, NotificationFilters,+ ParticipantRole,};use crate::domain::ports::ChannelRepo;use crate::outbound::pg_channels_repo::PgChannelsRepo;@@ -33,6 +34,8 @@ const REPLY5: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_00000000b005);const DELETED_MSG_ATTACHMENT: Uuid = Uuid::from_u128(0x00000000_0000_0000_0000_00000000a004);const USER_A: &str = "macro|[email protected]";const USER_B: &str = "macro|[email protected]";+const NON_MEMBER: &str = "macro|[email protected]";+const LEFT_USER: &str = "macro|[email protected]";fn repo(pool: Pool<Postgres>) -> PgChannelsRepo {PgChannelsRepo::new(pool)@@ -1170,3 +1173,145 @@ async fn notification_filter_requires_requesting_user(pool: Pool<Postgres>) -> a);Ok(())}++// --- get_attachment_references ---+//+// The query is a byte-identical port of comms_db_client::get_attachment_references;+// these cover the three source paths (direct attachment, message mention, generic+// mention), participation gating, deleted-message exclusion, and the merged sort —+// rather than re-porting the full original suite.++fn channel_refs(+ refs: &[AttachmentEntityReference],+) -> Vec<&crate::domain::models::AttachmentChannelReference> {+ refs.iter()+ .filter_map(|r| match r {+ AttachmentEntityReference::Channel(c) => Some(c),+ AttachmentEntityReference::Generic(_) => None,+ })+ .collect()+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn attachment_references_returns_channel_reference_for_participant(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let refs = repo(pool)+ .get_attachment_references("document", "doc-1", USER_A)+ .await?;++ assert_eq!(refs.len(), 1);+ let channel = channel_refs(&refs);+ assert_eq!(channel.len(), 1);+ assert_eq!(channel[0].channel_id, CH1);+ assert_eq!(channel[0].message_id, MSG1);+ assert_eq!(channel[0].message_content, "first message");+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn attachment_references_hidden_from_non_and_former_participants(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ let repo = repo(pool);++ // user never in the channel+ let refs = repo+ .get_attachment_references("document", "doc-1", NON_MEMBER)+ .await?;+ assert!(refs.is_empty());++ // user who left the channel (left_at IS NOT NULL)+ let refs = repo+ .get_attachment_references("document", "doc-1", LEFT_USER)+ .await?;+ assert!(refs.is_empty());+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn attachment_references_excludes_deleted_message(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ // img-deleted is attached to msg2, which is soft-deleted.+ let refs = repo(pool)+ .get_attachment_references("image", "img-deleted", USER_A)+ .await?;+ assert!(refs.is_empty());+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn attachment_references_returns_message_mention(pool: Pool<Postgres>) -> anyhow::Result<()> {+ // doc-mention is mentioned inside msg3 (source_entity_type = 'message').+ let refs = repo(pool)+ .get_attachment_references("document", "doc-mention", USER_A)+ .await?;++ assert_eq!(refs.len(), 1);+ let channel = channel_refs(&refs);+ assert_eq!(channel.len(), 1);+ assert_eq!(channel[0].channel_id, CH1);+ assert_eq!(channel[0].message_id, MSG3);+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn attachment_references_returns_generic_reference(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ // doc-generic is mentioned by a non-message source; generic refs are not gated+ // by channel participation, so any user resolves them.+ let refs = repo(pool)+ .get_attachment_references("document", "doc-generic", NON_MEMBER)+ .await?;++ assert_eq!(refs.len(), 1);+ let AttachmentEntityReference::Generic(generic) = &refs[0] else {+ anyhow::bail!("expected a generic reference");+ };+ assert_eq!(generic.source_entity_type, "doc");+ assert_eq!(generic.source_entity_id, "src-doc");+ assert_eq!(generic.entity_id, "doc-generic");+ Ok(())+}++#[sqlx::test(+ fixtures(path = "../../../fixtures", scripts("channels_repo")),+ migrator = "MACRO_DB_MIGRATIONS"+)]+async fn attachment_references_merges_channel_and_generic_newest_first(+ pool: Pool<Postgres>,+) -> anyhow::Result<()> {+ // doc-2 has a direct attachment on msg3 (12:00) and a newer generic mention+ // (2024-01-04); the merged result must be sorted newest-first.+ let refs = repo(pool)+ .get_attachment_references("document", "doc-2", USER_A)+ .await?;++ assert_eq!(refs.len(), 2);+ assert!(+ matches!(refs[0], AttachmentEntityReference::Generic(_)),+ "newer generic reference should come first"+ );+ assert!(+ matches!(refs[1], AttachmentEntityReference::Channel(_)),+ "older channel reference should come second"+ );+ Ok(())+}diff --git a/rust/cloud-storage/document_storage_service/src/api/swagger.rs b/rust/cloud-storage/document_storage_service/src/api/swagger.rsindex b9ca47d257..b2e58d9a3b 100644--- a/rust/cloud-storage/document_storage_service/src/api/swagger.rs+++ b/rust/cloud-storage/document_storage_service/src/api/swagger.rs@@ -63,10 +63,12 @@ use crate::{},};use channels::inbound::axum_router::{+ ApiAttachmentChannelReference, ApiAttachmentEntityReference, ApiAttachmentGenericReference,ApiChannelAttachment, ApiChannelAttachmentsPage, ApiChannelContextMessage, ApiChannelMessage,ApiChannelMessageKind, ApiChannelMessagesPage, ApiChannelParticipant, ApiCountedReaction,ApiMessageAttachment, ApiParticipantRole, ApiResolvedChannelMessage, ApiThreadInfo,- ApiThreadReply, ChannelMessageFilters, GetMessageWithContextResponse,+ ApiThreadReply, ChannelMessageFilters, GetAttachmentReferencesResponse,+ GetMessageWithContextResponse,};use document_sub_type::DocumentSubType;use documents_hex::inbound::axum_router::{@@ -214,6 +216,7 @@ use utoipa::OpenApi;channels::inbound::axum_router::resolve_channel_message_handler,channels::inbound::axum_router::get_channel_attachments_handler,channels::inbound::axum_router::get_channel_participants_handler,+ channels::inbound::axum_router::get_attachment_references_handler,// callscall::inbound::axum_router::get_or_create_call_handler,@@ -378,6 +381,10 @@ use utoipa::OpenApi;ApiChannelAttachment,ApiChannelParticipant,ApiParticipantRole,+ GetAttachmentReferencesResponse,+ ApiAttachmentEntityReference,+ ApiAttachmentChannelReference,+ ApiAttachmentGenericReference,ChannelMessageFilters,channels::domain::models::ChannelType,channels::domain::models::GetOrCreateAction,