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(ai): Attachment dcs, chat, ai integration (#2870)
Eric Hayes943e23cd467d
diff --git a/js/app/packages/app/component/SoupChatInput.tsx b/js/app/packages/app/component/SoupChatInput.tsxindex c4a4322601..d9d11c89ae 100644--- a/js/app/packages/app/component/SoupChatInput.tsx+++ b/js/app/packages/app/component/SoupChatInput.tsx@@ -12,7 +12,6 @@ import { deriveChatName } from '@core/component/AI/util/deriveName';import { Hotkey } from '@core/component/Hotkey';import { Tooltip } from '@core/component/Tooltip';import { useHasPaidAccess } from '@core/auth/license';-import { ENABLE_SNAPSHOT_NODE } from '@core/constant/featureFlags';import { PaywallKey, usePaywallState } from '@core/constant/PaywallState';import { pressedKeys } from '@core/hotkey/state';import { TOKENS } from '@core/hotkey/tokens';@@ -43,7 +42,6 @@ function SoupChatInputInner() {},block: 'chat',showOpenTabs: true,- useSnapshotForDocuments: ENABLE_SNAPSHOT_NODE,});const [attachHotkeys] = useHotkeyDOMScope('soup.chatInput');diff --git a/js/app/packages/block-chat/component/Chat.tsx b/js/app/packages/block-chat/component/Chat.tsxindex 17b47d0c57..7142283ae9 100644--- a/js/app/packages/block-chat/component/Chat.tsx+++ b/js/app/packages/block-chat/component/Chat.tsx@@ -25,10 +25,7 @@ import {} from '@core/component/AI/util/storage';import { buildChatEditor } from '@core/component/AI/component/input/buildChatEditor';import { CustomScrollbar } from '@core/component/CustomScrollbar';-import {- DEV_MODE_ENV,- ENABLE_SNAPSHOT_NODE,-} from '@core/constant/featureFlags';+import { DEV_MODE_ENV } from '@core/constant/featureFlags';import { usePaywallState } from '@core/constant/PaywallState';import { TOKENS } from '@core/hotkey/tokens';import { registerScopeSignalHotkey } from '@core/hotkey/utils';@@ -100,7 +97,6 @@ function ChatInner(props: {},block: 'chat',showOpenTabs: true,- useSnapshotForDocuments: ENABLE_SNAPSHOT_NODE,});// Sync isGenerating from controller phasediff --git a/js/app/packages/core/component/AI/component/input/ChatInput.tsx b/js/app/packages/core/component/AI/component/input/ChatInput.tsxindex 6c131d2fc5..5e5ab2bd01 100644--- a/js/app/packages/core/component/AI/component/input/ChatInput.tsx+++ b/js/app/packages/core/component/AI/component/input/ChatInput.tsx@@ -103,6 +103,7 @@ export function ChatInput(props: ChatInputComponentProps) {metaKey: opts?.metaKey,};props.editor.controls.clear();+ attachments.setAttached([]);props.onSend(sendInput);});diff --git a/js/app/packages/core/component/AI/component/message/EditableChatMessage.tsx b/js/app/packages/core/component/AI/component/message/EditableChatMessage.tsxindex 1966172eca..0742c81be5 100644--- a/js/app/packages/core/component/AI/component/message/EditableChatMessage.tsx+++ b/js/app/packages/core/component/AI/component/message/EditableChatMessage.tsx@@ -7,7 +7,6 @@ import {import { useGetChatAttachmentInfo } from '@core/component/AI/signal/attachment';import type { Attachment, Model } from '@core/component/AI/types';import { buildChatEditor } from '@core/component/AI/component/input/buildChatEditor';-import { ENABLE_SNAPSHOT_NODE } from '@core/constant/featureFlags';import { onMount } from 'solid-js';import { useAnalytics } from '@app/component/analytics-context';@@ -32,7 +31,6 @@ function EditableChatMessageInner(props: {},block: 'chat',showOpenTabs: true,- useSnapshotForDocuments: ENABLE_SNAPSHOT_NODE,});onMount(() => {diff --git a/js/app/packages/core/component/LexicalMarkdown/builder/MarkdownShell.tsx b/js/app/packages/core/component/LexicalMarkdown/builder/MarkdownShell.tsxindex c43f5d3675..9ca0d3c05e 100644--- a/js/app/packages/core/component/LexicalMarkdown/builder/MarkdownShell.tsx+++ b/js/app/packages/core/component/LexicalMarkdown/builder/MarkdownShell.tsx@@ -238,9 +238,6 @@ export const MarkdownShell: Component<portalScope={props.portalScope}block={builderConfig.mentions?.block as any}showOpenTabs={builderConfig.mentions?.showOpenTabs}- useSnapshotForDocuments={- builderConfig.mentions?.useSnapshotForDocuments- }entities={builderConfig.mentions?.entities}users={builderConfig.mentions?.users}disableMentionTracking={diff --git a/js/app/packages/core/component/LexicalMarkdown/builder/types.ts b/js/app/packages/core/component/LexicalMarkdown/builder/types.tsindex 7e473d3805..b29d0764ff 100644--- a/js/app/packages/core/component/LexicalMarkdown/builder/types.ts+++ b/js/app/packages/core/component/LexicalMarkdown/builder/types.ts@@ -29,7 +29,6 @@ export interface MentionsOptions {onCreate?: (mention: ItemMention) => void;block?: string;showOpenTabs?: boolean;- useSnapshotForDocuments?: boolean;sourceDocumentId?: string;/** Override entity data source (e.g. sandbox data for onboarding). Bypasses quickAccess. */entities?: () => import('@core/context/quickAccess').EntityItem[];diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsxindex e2145964e7..b6651a37b0 100644--- a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/MentionsMenu.tsx@@ -90,7 +90,6 @@ export type MentionsMenuProps = {onDocumentMention?: (item: Item | ChannelWithParticipants) => void;onEmailMention?: (item: EmailEntity) => void;disableMentionTracking?: boolean;- useSnapshotForDocuments?: boolean;/** whether to show open tabs as a bucket in the menu */showOpenTabs?: boolean;/** restrict which mention source buckets to show (e.g. ['users'] for user-only mentions) */@@ -327,7 +326,6 @@ function MentionsMenuInner(props: MentionsMenuProps) {onDocumentMention: props.onDocumentMention,onEmailMention: props.onEmailMention,disableMentionTracking: props.disableMentionTracking,- useSnapshotNode: props.useSnapshotForDocuments,});const itemAction = async (item: MentionItem) => {diff --git a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mentionHandlers.ts b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mentionHandlers.tsindex 5baf04ecaf..3e3eec8387 100644--- a/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mentionHandlers.ts+++ b/js/app/packages/core/component/LexicalMarkdown/component/menu/MentionsMenu/utils/mentionHandlers.ts@@ -12,10 +12,6 @@ import type {MentionItem,} from '../../../../utils/mentionsUtils';import { handleUserMention } from '../../../../utils/mentionsUtils';-import {- handleSnapshotMention,- supportsSnapshotNode,-} from '../../../../utils/snapshotMention';import type { DateOption } from '@core/util/dateSearch/useDateSearch';import { getBlockNameFromEntity } from './entityUtils';@@ -40,24 +36,6 @@ export async function handleEntityMention(const blockNameForMention = getBlockNameFromEntity(item);const itemName = entity.name ?? (item.bucket === 'email' ? 'No Subject' : '');- // For document entities, check if snapshot insertion is requested and supported.- // This restores the behaviour that existed before the quick-access refactor where- // handleBasicMention (which calls handleSnapshotMention) was used for 'item' picks.- if (- dependencies.useSnapshotNode &&- item.bucket !== 'channel' &&- item.bucket !== 'dm' &&- item.bucket !== 'email' &&- supportsSnapshotNode(blockNameForMention)- ) {- // EntityBase is a superset of the fields DocumentHistoryItem needs, so the- // cast is safe for the document buckets we've already filtered to.- const historyLike = entity as unknown as Parameters<- typeof handleSnapshotMention- >[0];- return await handleSnapshotMention(historyLike, dependencies);- }-let mentionId: string | undefined;if (blockId &&diff --git a/js/app/packages/core/component/LexicalMarkdown/utils/mentionsUtils.ts b/js/app/packages/core/component/LexicalMarkdown/utils/mentionsUtils.tsindex 3dedccc93d..4cc1c2a928 100644--- a/js/app/packages/core/component/LexicalMarkdown/utils/mentionsUtils.ts+++ b/js/app/packages/core/component/LexicalMarkdown/utils/mentionsUtils.ts@@ -18,7 +18,6 @@ import {INSERT_GROUP_MENTION_COMMAND,INSERT_USER_MENTION_COMMAND,} from '../plugins/mentions';-import { handleSnapshotMention, supportsSnapshotNode } from './snapshotMention';export type GroupItem = {id: string;@@ -140,7 +139,6 @@ export type HandlerDependencies = {onDocumentMention?: (item: Item | ChannelWithParticipants) => void;disableMentionTracking?: boolean;onEmailMention?: (item: EmailEntity) => void;- useSnapshotNode?: boolean;};/**@@ -302,16 +300,12 @@ export async function handleBasicMention(const itemBlock = getCombinedEntityBlockName(itemEntity);const itemName = getItemName(itemEntity);onDocumentMention?.(item);- if (dependencies.useSnapshotNode && supportsSnapshotNode(itemBlock)) {- await handleSnapshotMention(item, dependencies);- } else {- editor.dispatchCommand(INSERT_DOCUMENT_MENTION_COMMAND, {- documentId: item.id,- documentName: itemName,- blockName: itemBlock,- mentionUuid: mentionId,- });- }+ editor.dispatchCommand(INSERT_DOCUMENT_MENTION_COMMAND, {+ documentId: item.id,+ documentName: itemName,+ blockName: itemBlock,+ mentionUuid: mentionId,+ });}/**diff --git a/js/app/packages/core/constant/featureFlags.ts b/js/app/packages/core/constant/featureFlags.tsindex 396c896e0e..41059fdbfb 100644--- a/js/app/packages/core/constant/featureFlags.ts+++ b/js/app/packages/core/constant/featureFlags.ts@@ -264,12 +264,6 @@ export const ENABLE_UNIFIED_LIST_AI_INPUT = resolveFeatureFlag(true);-// snapshot mention content inline for AI chat-export const ENABLE_SNAPSHOT_NODE = resolveFeatureFlag(- 'ENABLE_SNAPSHOT_NODE',- true-);-export const ENABLE_EMAIL_SCHEDULED_SEND = resolveFeatureFlag('ENABLE_EMAIL_SCHEDULED_SEND',truediff --git a/rust/cloud-storage/.sqlx/query-56322decea30dff649d294afbf0be6a894f1c511b957f6988b966d730d47bc59.json b/rust/cloud-storage/.sqlx/query-56322decea30dff649d294afbf0be6a894f1c511b957f6988b966d730d47bc59.jsonnew file mode 100644index 0000000000..40327ffc79--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-56322decea30dff649d294afbf0be6a894f1c511b957f6988b966d730d47bc59.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO resolved_message_content (\"messageId\", \"content\")\n VALUES ($1, $2)\n ON CONFLICT (\"messageId\") DO UPDATE SET \"content\" = $2\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Jsonb"+ ]+ },+ "nullable": []+ },+ "hash": "56322decea30dff649d294afbf0be6a894f1c511b957f6988b966d730d47bc59"+}diff --git a/rust/cloud-storage/.sqlx/query-57fc603adf83fd7c07968425c98f9a57924573692cf0529ad021b6eef00ce99e.json b/rust/cloud-storage/.sqlx/query-57fc603adf83fd7c07968425c98f9a57924573692cf0529ad021b6eef00ce99e.jsonnew file mode 100644index 0000000000..27b7d76a6f--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-57fc603adf83fd7c07968425c98f9a57924573692cf0529ad021b6eef00ce99e.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO \"ChatMessage\" (\"id\", \"chatId\", \"content\", \"role\", \"model\", \"createdAt\", \"updatedAt\")\n VALUES ($1, $2, $3, $4, $5, $6, $7)\n RETURNING id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Jsonb",+ "Text",+ "Text",+ "Timestamp",+ "Timestamp"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "57fc603adf83fd7c07968425c98f9a57924573692cf0529ad021b6eef00ce99e"+}diff --git a/rust/cloud-storage/.sqlx/query-663a12ade5ccf4613703c0ad368772673560741961c20f5c401b59b5c5f6027d.json b/rust/cloud-storage/.sqlx/query-663a12ade5ccf4613703c0ad368772673560741961c20f5c401b59b5c5f6027d.jsonnew file mode 100644index 0000000000..565892f3ba--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-663a12ade5ccf4613703c0ad368772673560741961c20f5c401b59b5c5f6027d.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM \"ChatMessage\"\n WHERE id = $1\n RETURNING id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "663a12ade5ccf4613703c0ad368772673560741961c20f5c401b59b5c5f6027d"+}diff --git a/rust/cloud-storage/.sqlx/query-8c9bf0696a9b0a0e1cab142290ecf2858a32311a07bca8ea0bb9f54ea507f8e3.json b/rust/cloud-storage/.sqlx/query-8c9bf0696a9b0a0e1cab142290ecf2858a32311a07bca8ea0bb9f54ea507f8e3.jsonnew file mode 100644index 0000000000..548c314aac--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-8c9bf0696a9b0a0e1cab142290ecf2858a32311a07bca8ea0bb9f54ea507f8e3.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT id FROM \"Project\" WHERE \"parentId\" = $1 AND \"deletedAt\" IS NULL",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "8c9bf0696a9b0a0e1cab142290ecf2858a32311a07bca8ea0bb9f54ea507f8e3"+}diff --git a/rust/cloud-storage/.sqlx/query-9021780763850e636cf944f6171ce2253c39d7532a38bcda72c8a6da965310f9.json b/rust/cloud-storage/.sqlx/query-9021780763850e636cf944f6171ce2253c39d7532a38bcda72c8a6da965310f9.jsonnew file mode 100644index 0000000000..215156fa55--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-9021780763850e636cf944f6171ce2253c39d7532a38bcda72c8a6da965310f9.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT \"content\"\n FROM resolved_message_content\n WHERE \"messageId\" = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "content",+ "type_info": "Jsonb"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "9021780763850e636cf944f6171ce2253c39d7532a38bcda72c8a6da965310f9"+}diff --git a/rust/cloud-storage/.sqlx/query-b9344b1ce39ffd607ab2862810afbd13c579e22b433553ba01719644a56ab816.json b/rust/cloud-storage/.sqlx/query-b9344b1ce39ffd607ab2862810afbd13c579e22b433553ba01719644a56ab816.jsonnew file mode 100644index 0000000000..02963800c8--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-b9344b1ce39ffd607ab2862810afbd13c579e22b433553ba01719644a56ab816.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "SELECT id FROM \"Document\" WHERE \"projectId\" = $1 AND \"deletedAt\" IS NULL",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "b9344b1ce39ffd607ab2862810afbd13c579e22b433553ba01719644a56ab816"+}diff --git a/rust/cloud-storage/.sqlx/query-c9f9b00be9d446b7d45cad5073e9d422689a29c2da56d6888ca37877bef372f0.json b/rust/cloud-storage/.sqlx/query-c9f9b00be9d446b7d45cad5073e9d422689a29c2da56d6888ca37877bef372f0.jsonnew file mode 100644index 0000000000..1537dcb194--- /dev/null+++ b/rust/cloud-storage/.sqlx/query-c9f9b00be9d446b7d45cad5073e9d422689a29c2da56d6888ca37877bef372f0.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO \"ChatAttachment\" (\"attachmentType\", \"attachmentId\", \"chatId\", \"messageId\")\n SELECT * FROM UNNEST($1::TEXT[], $2::TEXT[], $3::TEXT[], $4::TEXT[])\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "TextArray",+ "TextArray",+ "TextArray",+ "TextArray"+ ]+ },+ "nullable": []+ },+ "hash": "c9f9b00be9d446b7d45cad5073e9d422689a29c2da56d6888ca37877bef372f0"+}diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex c2dccc08bd..64cf315e48 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -52,11 +52,10 @@ dependencies = ["async-openai","async-stream","async-trait",- "base64 0.22.1",+ "attachment","chrono","const_format","futures",- "image","lazy_static","macro_user_id","model_file_type",@@ -68,11 +67,9 @@ dependencies = ["serde_json","strum","thiserror 2.0.17",- "tiktoken-rs","tokio","tracing","utoipa",- "webp",][[package]]@@ -93,6 +90,7 @@ dependencies = ["anthropic","anyhow","async-trait",+ "attachment","aws-sdk-secretsmanager","aws-sdk-sqs","axum",@@ -121,6 +119,7 @@ dependencies = ["macro_env_var","macro_user_id","model",+ "model-entity","model_notifications","models_dcs","models_email",@@ -128,6 +127,7 @@ dependencies = ["models_permissions","models_properties","models_search",+ "non_empty","notification","properties","rand 0.9.3",@@ -594,12 +594,17 @@ checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"name = "attachment"version = "0.1.0"dependencies = [- "ai","anyhow",+ "base64 0.22.1","futures",+ "image","macro_user_id",+ "model-entity",+ "model_file_type","non_empty",+ "serde","thiserror 2.0.17",+ "webp",][[package]]@@ -3080,6 +3085,7 @@ dependencies = ["async-openai","async-stream","async-trait",+ "attachment","aws-sdk-dynamodb","aws-sdk-s3","aws-sdk-secretsmanager",@@ -3127,6 +3133,7 @@ dependencies = ["models_dcs","models_opensearch","models_permissions",+ "non_empty","notification","properties","readonly_pool",@@ -3143,6 +3150,7 @@ dependencies = ["soup","sqlx","sqs_client",+ "static_file","static_file_service_client","stream","strum",@@ -3327,6 +3335,7 @@ dependencies = ["serde","serde_json","sqlx",+ "tiktoken-rs","tokio","tracing","urlencoding",@@ -4589,6 +4598,7 @@ dependencies = ["macro_uuid","mockall","model",+ "model-entity","model-error-response","models_permissions","redis",@@ -7203,6 +7213,9 @@ dependencies = [[[package]]name = "non_empty"version = "0.1.0"+dependencies = [+ "serde",+][[package]]name = "noop_proc_macro"@@ -9578,6 +9591,7 @@ dependencies = ["ai","ai_format","anyhow",+ "attachment","base64 0.22.1","bytes","chat",@@ -10708,6 +10722,21 @@ version = "1.2.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3"+[[package]]+name = "static_file"+version = "0.1.0"+dependencies = [+ "anyhow",+ "attachment",+ "futures",+ "macro_user_id",+ "mime",+ "model-entity",+ "non_empty",+ "reqwest",+ "tracing",+]+[[package]]name = "static_file_service"version = "0.1.0"diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex f87446b36a..4019acea3c 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -130,6 +130,7 @@ members = ["soup","sqs_client","sqs_worker",+ "static_file","static_file_service","static_file_service_client","sync_service_client",diff --git a/rust/cloud-storage/ai/Cargo.toml b/rust/cloud-storage/ai/Cargo.tomlindex 5f041da7b4..28fe832886 100644--- a/rust/cloud-storage/ai/Cargo.toml+++ b/rust/cloud-storage/ai/Cargo.toml@@ -27,15 +27,12 @@ serde = { workspace = true }serde_json = { workspace = true }strum = { workspace = true }thiserror = { workspace = true }-tiktoken-rs = "0.5.9"tokio.workspace = truetracing = { workspace = true }utoipa = { workspace = true }anthropic = { path = "../anthropic" }ai_toolset = { path = "../ai_toolset" }macro_user_id = { path = "../macro_user_id" }-base64 = { workspace = true }-image = { workspace = true }-webp = { version = "0.3.1" }model_file_type = { path = "../model_file_type"}-ai_format = {path = "../ai_format"}+ai_format = { path = "../ai_format" }+attachment = { path = "../attachment" }diff --git a/rust/cloud-storage/ai/src/lib.rs b/rust/cloud-storage/ai/src/lib.rsindex 6bfbdd9c6f..bfb795c054 100644--- a/rust/cloud-storage/ai/src/lib.rs+++ b/rust/cloud-storage/ai/src/lib.rs@@ -7,7 +7,6 @@ pub mod prompts;pub mod simple_completion;pub mod structured_output;pub mod structured_output_v2;-pub mod tokens;pub mod tool;pub mod traits;pub mod types;diff --git a/rust/cloud-storage/ai/src/tokens.rs b/rust/cloud-storage/ai/src/tokens.rsdeleted file mode 100644index eeac0a1ecc..0000000000--- a/rust/cloud-storage/ai/src/tokens.rs+++ /dev/null@@ -1,13 +0,0 @@-use anyhow::Result;-use tiktoken_rs::o200k_base;--/// Counts the number of tokens in a string-pub fn count_tokens(text: &str) -> Result<i64> {- let encoding = o200k_base()?;- let tokens = encoding.encode_with_special_tokens(text);- Ok(tokens.len() as i64)-}--pub trait TokenCount {- fn token_count(&self) -> Result<i64>;-}diff --git a/rust/cloud-storage/ai/src/tool/tool_loop/cli.rs b/rust/cloud-storage/ai/src/tool/tool_loop/cli.rsindex 0f1def59dd..686d4f76c9 100644--- a/rust/cloud-storage/ai/src/tool/tool_loop/cli.rs+++ b/rust/cloud-storage/ai/src/tool/tool_loop/cli.rs@@ -181,9 +181,18 @@ where.build(),);+ let request_messages = messages+ .iter()+ .map(|m| ChatMessage {+ content: m.content.clone(),+ role: m.role,+ attachments: None,+ })+ .collect();+let request = RequestBuilder::new().system_prompt(&self.system_prompt)- .messages(messages.clone())+ .messages(request_messages).model(self.model).build();diff --git a/rust/cloud-storage/ai/src/types/image/mod.rs b/rust/cloud-storage/ai/src/types/image/mod.rsdeleted file mode 100644index b5f62e152c..0000000000--- a/rust/cloud-storage/ai/src/types/image/mod.rs+++ /dev/null@@ -1,22 +0,0 @@-mod base_64_image;--pub use base_64_image::*;--#[derive(PartialEq, Eq, Clone)]-pub enum ImageData {- Base64(Base64Image),- StaticUrl(String),-}--impl ImageData {- /// convert image bytes into a downscaled webp- pub fn try_from_bytes(bytes: Vec<u8>) -> Result<Self, anyhow::Error> {- Base64Image::compress_and_reencode(bytes).map(Self::Base64)- }-- pub(crate) fn dangerously_try_from_string(s: String) -> Result<Self, anyhow::Error> {- Base64Image::try_from_string(&s)- .map(Self::Base64)- .or_else(|_| Ok(Self::StaticUrl(s)))- }-}diff --git a/rust/cloud-storage/ai/src/types/message/chat_message.rs b/rust/cloud-storage/ai/src/types/message/chat_message.rsindex ffe2d7f6f6..2ae3d64afb 100644--- a/rust/cloud-storage/ai/src/types/message/chat_message.rs+++ b/rust/cloud-storage/ai/src/types/message/chat_message.rs@@ -1,28 +1,17 @@use super::Role;-use crate::tokens::{TokenCount, count_tokens};-use crate::types::ImageData;-use anyhow::Result;-use async_openai::types::ChatCompletionRequestMessage;+use attachment::Attachments;use serde::{self, Deserialize, Serialize};use std::fmt::{Display, Write};use utoipa::ToSchema;-#[derive(Debug, Eq, PartialEq, Clone)]+#[derive(Debug)]pub struct ChatMessages(pub Vec<ChatMessage>);-#[derive(Debug, Eq, PartialEq, Clone)]+#[derive(Debug)]pub struct ChatMessage {pub content: ChatMessageContent,pub role: Role,- pub image_urls: Option<Vec<ImageData>>,-}--impl TokenCount for ChatMessage {- fn token_count(&self) -> Result<i64> {- let messages = Vec::<ChatCompletionRequestMessage>::from(self.clone());- let messages_str = serde_json::to_string(&messages)?;- count_tokens(&messages_str)- }+ pub attachments: Option<Attachments<'static>>,}#[derive(Serialize, Deserialize, Eq, PartialEq, Debug, Clone, ToSchema)]diff --git a/rust/cloud-storage/ai/src/types/message/message_builder.rs b/rust/cloud-storage/ai/src/types/message/message_builder.rsindex ff1eabbff9..12577dd289 100644--- a/rust/cloud-storage/ai/src/types/message/message_builder.rs+++ b/rust/cloud-storage/ai/src/types/message/message_builder.rs@@ -1,9 +1,10 @@-use crate::types::{ChatMessage, ChatMessageContent, ImageData, Role};+use crate::types::{ChatMessage, ChatMessageContent, Role};+use attachment::Attachments;pub struct MessageBuilder<R, C> {content: C,role: R,- image_urls: Option<Vec<ImageData>>,+ attachments: Option<Attachments<'static>>,}impl MessageBuilder<Role, ChatMessageContent> {@@ -11,7 +12,7 @@ impl MessageBuilder<Role, ChatMessageContent> {ChatMessage {content: self.content,role: self.role,- image_urls: self.image_urls,+ attachments: self.attachments,}}}@@ -33,7 +34,7 @@ impl MessageBuilder<(), ()> {Self {content: (),role: (),- image_urls: None,+ attachments: None,}}}@@ -44,7 +45,7 @@ impl<C> MessageBuilder<NoRole, C> {pub fn user(self) -> MessageBuilder<Role, C> {MessageBuilder {content: self.content,- image_urls: self.image_urls,+ attachments: self.attachments,role: Role::User,}}@@ -52,7 +53,7 @@ impl<C> MessageBuilder<NoRole, C> {pub fn assistant(self) -> MessageBuilder<Role, C> {MessageBuilder {content: self.content,- image_urls: self.image_urls,+ attachments: self.attachments,role: Role::Assistant,}}@@ -60,7 +61,7 @@ impl<C> MessageBuilder<NoRole, C> {pub fn system(self) -> MessageBuilder<Role, C> {MessageBuilder {content: self.content,- image_urls: self.image_urls,+ attachments: self.attachments,role: Role::System,}}@@ -68,7 +69,7 @@ impl<C> MessageBuilder<NoRole, C> {pub fn role(self, role: Role) -> MessageBuilder<Role, C> {MessageBuilder {content: self.content,- image_urls: self.image_urls,+ attachments: self.attachments,role,}}@@ -84,7 +85,7 @@ impl<R> MessageBuilder<R, NoContent> {{MessageBuilder {content: content.into(),- image_urls: self.image_urls,+ attachments: self.attachments,role: self.role,}}@@ -92,20 +93,15 @@ impl<R> MessageBuilder<R, NoContent> {pub fn text<T: Into<String>>(self, content: T) -> MessageBuilder<R, ChatMessageContent> {MessageBuilder {content: ChatMessageContent::Text(content.into()),- image_urls: self.image_urls,+ attachments: self.attachments,role: self.role,}}}impl<R, C> MessageBuilder<R, C> {- pub fn image_urls(mut self, image_urls: Vec<ImageData>) -> Self {- if image_urls.is_empty() {- self.image_urls = None;- self- } else {- self.image_urls = Some(image_urls);- self- }+ pub fn attachments(mut self, attachments: Attachments<'static>) -> Self {+ self.attachments = Some(attachments);+ self}}diff --git a/rust/cloud-storage/ai/src/types/message/system_prompt.rs b/rust/cloud-storage/ai/src/types/message/system_prompt.rsindex 7a249d8d31..4fa6512242 100644--- a/rust/cloud-storage/ai/src/types/message/system_prompt.rs+++ b/rust/cloud-storage/ai/src/types/message/system_prompt.rs@@ -1,6 +1,4 @@use super::prompt_attachments::PromptAttachments;-use crate::tokens::{TokenCount, count_tokens};-use anyhow::Result;#[derive(Debug, Clone)]pub struct SystemPrompt {@@ -8,12 +6,6 @@ pub struct SystemPrompt {pub attachments: PromptAttachments,}-impl TokenCount for SystemPrompt {- fn token_count(&self) -> Result<i64> {- count_tokens(&self.to_string())- }-}-impl std::fmt::Display for SystemPrompt {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {writeln!(f, "{}", self.instructions)?;diff --git a/rust/cloud-storage/ai/src/types/mod.rs b/rust/cloud-storage/ai/src/types/mod.rsindex 7ec6a48091..aff1b02e5a 100644--- a/rust/cloud-storage/ai/src/types/mod.rs+++ b/rust/cloud-storage/ai/src/types/mod.rs@@ -1,6 +1,5 @@mod client;mod error;-mod image;mod message;mod model;mod providers;@@ -10,7 +9,6 @@ mod response;pub use client::*;pub use error::*;-pub use image::*;pub use message::*;pub use model::*;pub(crate) use providers::*;diff --git a/rust/cloud-storage/ai/src/types/providers/openai/message.rs b/rust/cloud-storage/ai/src/types/providers/openai/message.rsindex ec37a7bec6..730afde6e5 100644--- a/rust/cloud-storage/ai/src/types/providers/openai/message.rs+++ b/rust/cloud-storage/ai/src/types/providers/openai/message.rs@@ -8,25 +8,22 @@ use async_openai::types::{ChatCompletionRequestUserMessageContentPart, FunctionCall, ImageDetail, ImageUrl,};-use crate::types::{- AssistantMessagePart, ChatMessage, ChatMessageContent, ChatMessages, ImageData, Role,-};+use crate::types::{AssistantMessagePart, ChatMessage, ChatMessageContent, ChatMessages, Role};+use attachment::{Attachable, TextOrImage, image::ImageData};use std::collections::HashMap;const IMAGE_PROCESS_QUALITY: Option<ImageDetail> = Some(ImageDetail::High);-impl From<ImageData> for ImageUrl {- fn from(value: ImageData) -> Self {- match value {- ImageData::StaticUrl(url) => Self {- url,- detail: IMAGE_PROCESS_QUALITY,- },- ImageData::Base64(base_64_image) => Self {- url: base_64_image.to_string(),- detail: IMAGE_PROCESS_QUALITY,- },- }+fn image_into_openai_image_url(image: ImageData) -> ImageUrl {+ match image {+ ImageData::StaticUrl(url) => ImageUrl {+ url,+ detail: IMAGE_PROCESS_QUALITY,+ },+ ImageData::Base64(base_64_image) => ImageUrl {+ url: base_64_image.to_string(),+ detail: IMAGE_PROCESS_QUALITY,+ },}}@@ -46,20 +43,35 @@ impl From<ChatMessage> for Vec<ChatCompletionRequestMessage> {)]}Role::User => {- // For user messages with images, we need to use array format- if let Some(images) = value.image_urls {+ if let Some(attachments) = value.attachments {+ let formatted = attachments.into_formatted_parts().compact();let mut user_message_content =vec![ChatCompletionRequestUserMessageContentPart::Text(ChatCompletionRequestMessageContentPartText { text },)];- user_message_content.extend(images.into_iter().map(|url| {- ChatCompletionRequestUserMessageContentPart::ImageUrl(- ChatCompletionRequestMessageContentPartImage {- image_url: url.into(),- },- )- }));+ for part in formatted.into_parts().into_inner() {+ match part {+ TextOrImage::Text(attachment_text) => {+ user_message_content.push(+ ChatCompletionRequestUserMessageContentPart::Text(+ ChatCompletionRequestMessageContentPartText {+ text: attachment_text,+ },+ ),+ );+ }+ TextOrImage::Image(image) => {+ user_message_content.push(+ ChatCompletionRequestUserMessageContentPart::ImageUrl(+ ChatCompletionRequestMessageContentPartImage {+ image_url: image_into_openai_image_url(image),+ },+ ),+ );+ }+ }+ }vec![ChatCompletionRequestMessage::User(ChatCompletionRequestUserMessage {@@ -70,7 +82,6 @@ impl From<ChatMessage> for Vec<ChatCompletionRequestMessage> {},)]} else {- // Text-only user messagevec![ChatCompletionRequestMessage::User(ChatCompletionRequestUserMessage {name: None,@@ -215,64 +226,31 @@ pub fn convert_message(ChatMessageContent::Text(text_parts.join(" "))}},- image_urls: None,+ attachments: None,},ChatCompletionRequestMessage::User(user_msg) => {- let (content, image_urls) = match user_msg.content {+ let content = match user_msg.content {ChatCompletionRequestUserMessageContent::Text(text) => {- (ChatMessageContent::Text(text), None)+ ChatMessageContent::Text(text)}ChatCompletionRequestUserMessageContent::Array(parts) => {- let mut text_parts = Vec::new();- let mut images = Vec::new();-- for part in parts {- match part {+ let text_parts: Vec<String> = parts+ .into_iter()+ .filter_map(|part| match part {ChatCompletionRequestUserMessageContentPart::Text(text_part) => {- text_parts.push(text_part.text.clone());- }- ChatCompletionRequestUserMessageContentPart::ImageUrl(image_part) => {- images.push(image_part.image_url.url.clone());- }- ChatCompletionRequestUserMessageContentPart::InputAudio(_) => {- // Audio input is not supported in our internal format, skip it+ Some(text_part.text)}- }- }-- let content = ChatMessageContent::Text(text_parts.join(" "));- let image_urls = if images.is_empty() {- None- } else {- Some(images)- };- (content, image_urls)- }- };-- let image_urls = match image_urls- .unwrap_or_default()- .into_iter()- .map(ImageData::dangerously_try_from_string)- .collect::<Result<Vec<_>, _>>()- {- Ok(urls) => {- if urls.is_empty() {- None- } else {- Some(urls)- }- }- Err(e) => {- tracing::error!(error=?e,"failed to convert images");- None+ _ => None,+ })+ .collect();+ ChatMessageContent::Text(text_parts.join(" "))}};ChatMessage {role: Role::User,content,- image_urls,+ attachments: None,}}ChatCompletionRequestMessage::Assistant(assistant_msg) => {@@ -339,7 +317,7 @@ pub fn convert_message(ChatMessage {role: Role::Assistant,content,- image_urls: None,+ attachments: None,}}ChatCompletionRequestMessage::Tool(tool_msg) => {@@ -380,18 +358,18 @@ pub fn convert_message(ChatMessage {role: Role::Assistant,content: ChatMessageContent::AssistantMessageParts(vec![assistant_part]),- image_urls: None,+ attachments: None,}}ChatCompletionRequestMessage::Function(_) => ChatMessage {role: Role::Assistant,content: ChatMessageContent::Text(String::new()),- image_urls: None,+ attachments: None,},ChatCompletionRequestMessage::Developer(developer_msg) => ChatMessage {role: Role::System,content: ChatMessageContent::Text(format!("{:?}", developer_msg.content)),- image_urls: None,+ attachments: None,},}}@@ -442,74 +420,82 @@ mod tests {use super::*;use serde_json::json;+ fn assert_msg(msg: &ChatMessage, role: Role, content: ChatMessageContent) {+ assert_eq!(msg.role, role);+ assert_eq!(msg.content, content);+ assert!(msg.attachments.is_none());+ }+#[test]fn test_system_message_roundtrip() {- let original = ChatMessage {+ let msg = ChatMessage {role: Role::System,content: ChatMessageContent::Text("You are a helpful assistant.".to_string()),- image_urls: None,+ attachments: None,};- let openai_msgs: Vec<ChatCompletionRequestMessage> = original.clone().into();- let converted_back = convert_message(openai_msgs.into_iter().next().unwrap(), None);+ let openai_msgs: Vec<ChatCompletionRequestMessage> = msg.into();+ let converted = convert_message(openai_msgs.into_iter().next().unwrap(), None);- // assert_eq!(original.role, converted_back.role);- // assert_eq!(original.content, converted_back.content);- // assert_eq!(original.image_urls, converted_back.image_urls);- assert_eq!(original, converted_back);+ assert_msg(+ &converted,+ Role::System,+ ChatMessageContent::Text("You are a helpful assistant.".to_string()),+ );}#[test]fn test_user_text_message_roundtrip() {- let original = ChatMessage {+ let msg = ChatMessage {role: Role::User,content: ChatMessageContent::Text("Hello, how are you?".to_string()),- image_urls: None,- };-- let openai_msgs: Vec<ChatCompletionRequestMessage> = original.clone().into();- let converted_back = convert_message(openai_msgs.into_iter().next().unwrap(), None);-- assert_eq!(original.role, converted_back.role);- assert_eq!(original.content, converted_back.content);- assert_eq!(original.image_urls, converted_back.image_urls);- }-- #[test]- fn test_user_message_with_images_roundtrip() {- let original = ChatMessage {- role: Role::User,- content: ChatMessageContent::Text("What's in this image?".to_string()),- image_urls: Some(vec![ImageData::StaticUrl(- "https://example.com/image.jpg".to_string(),- )]),+ attachments: None,};- let openai_msgs: Vec<ChatCompletionRequestMessage> = original.clone().into();- let converted_back = convert_message(openai_msgs.into_iter().next().unwrap(), None);+ let openai_msgs: Vec<ChatCompletionRequestMessage> = msg.into();+ let converted = convert_message(openai_msgs.into_iter().next().unwrap(), None);- assert_eq!(original, converted_back);+ assert_msg(+ &converted,+ Role::User,+ ChatMessageContent::Text("Hello, how are you?".to_string()),+ );}#[test]fn test_assistant_text_message_roundtrip() {- let original = ChatMessage {+ let msg = ChatMessage {role: Role::Assistant,content: ChatMessageContent::Text("I'm doing well, thank you!".to_string()),- image_urls: None,+ attachments: None,};- let openai_msgs: Vec<ChatCompletionRequestMessage> = original.clone().into();- let converted_back = convert_message(openai_msgs.into_iter().next().unwrap(), None);+ let openai_msgs: Vec<ChatCompletionRequestMessage> = msg.into();+ let converted = convert_message(openai_msgs.into_iter().next().unwrap(), None);- assert_eq!(original, converted_back);+ assert_msg(+ &converted,+ Role::Assistant,+ ChatMessageContent::Text("I'm doing well, thank you!".to_string()),+ );}#[test]fn test_assistant_with_tool_call_roundtrip() {let tool_call_id = "call_123".to_string();let tool_name = "get_weather".to_string();- let original = ChatMessage {+ let expected_content = ChatMessageContent::AssistantMessageParts(vec![+ AssistantMessagePart::Text {+ text: "Let me check the weather for you.".to_string(),+ },+ AssistantMessagePart::ToolCall {+ name: tool_name.clone(),+ json: json!({"location": "San Francisco"}),+ id: tool_call_id.clone(),+ },+ ]);++ let msg = ChatMessage {role: Role::Assistant,content: ChatMessageContent::AssistantMessageParts(vec![AssistantMessagePart::Text {@@ -521,12 +507,11 @@ mod tests {id: tool_call_id.clone(),},]),- image_urls: None,+ attachments: None,};- let openai_msgs: Vec<ChatCompletionRequestMessage> = original.clone().into();+ let openai_msgs: Vec<ChatCompletionRequestMessage> = msg.into();- // Create tool call mapping for conversion backlet mut tool_mapping = HashMap::new();tool_mapping.insert(tool_call_id, tool_name);@@ -535,18 +520,26 @@ mod tests {.map(|msg| convert_message(msg, Some(&tool_mapping))).collect();- // Convert back to ChatMessages to merge assistant messageslet chat_messages = ChatMessages::from(converted_messages);- let converted_back = &chat_messages.0[0];+ let converted = &chat_messages.0[0];- assert_eq!(&original, converted_back);+ assert_eq!(converted.role, Role::Assistant);+ assert_eq!(converted.content, expected_content);}#[test]fn test_assistant_with_tool_response_roundtrip() {let tool_call_id = "call_123".to_string();let tool_name = "get_weather".to_string();- let original = ChatMessage {+ let expected_content = ChatMessageContent::AssistantMessageParts(vec![+ AssistantMessagePart::ToolCallResponseJson {+ name: tool_name.clone(),+ json: json!({"temperature": "72°F", "condition": "sunny"}),+ id: tool_call_id.clone(),+ },+ ]);++ let msg = ChatMessage {role: Role::Assistant,content: ChatMessageContent::AssistantMessageParts(vec![AssistantMessagePart::ToolCallResponseJson {@@ -555,26 +548,33 @@ mod tests {id: tool_call_id.clone(),},]),- image_urls: None,+ attachments: None,};- let openai_msgs: Vec<ChatCompletionRequestMessage> = original.clone().into();+ let openai_msgs: Vec<ChatCompletionRequestMessage> = msg.into();- // Create tool call mapping for conversion backlet mut tool_mapping = HashMap::new();tool_mapping.insert(tool_call_id, tool_name);- let converted_back =+ let converted =convert_message(openai_msgs.into_iter().next().unwrap(), Some(&tool_mapping));- assert_eq!(original, converted_back);+ assert_eq!(converted.role, Role::Assistant);+ assert_eq!(converted.content, expected_content);}#[test]fn test_assistant_with_tool_error_roundtrip() {let tool_call_id = "call_123".to_string();let tool_name = "get_weather".to_string();- let original = ChatMessage {+ let expected_content =+ ChatMessageContent::AssistantMessageParts(vec![AssistantMessagePart::ToolCallErr {+ name: tool_name.clone(),+ description: "<Error message here>".to_string(),+ id: tool_call_id.clone(),+ }]);++ let msg = ChatMessage {role: Role::Assistant,content: ChatMessageContent::AssistantMessageParts(vec![AssistantMessagePart::ToolCallErr {@@ -583,27 +583,45 @@ mod tests {id: tool_call_id.clone(),},]),- image_urls: None,+ attachments: None,};- let openai_msgs: Vec<ChatCompletionRequestMessage> = original.clone().into();+ let openai_msgs: Vec<ChatCompletionRequestMessage> = msg.into();- // Create tool call mapping for conversion backlet mut tool_mapping = HashMap::new();tool_mapping.insert(tool_call_id, tool_name);- let converted_back =+ let converted =convert_message(openai_msgs.into_iter().next().unwrap(), Some(&tool_mapping));- println!("original {:#?}", original);- println!("original {:#?}", converted_back);- assert_eq!(original, converted_back);++ assert_eq!(converted.role, Role::Assistant);+ assert_eq!(converted.content, expected_content);}#[test]fn test_complex_assistant_message_roundtrip() {let tool_call_id = "call_123".to_string();let tool_name = "calculate".to_string();- let original = ChatMessage {+ let expected_content = ChatMessageContent::AssistantMessageParts(vec![+ AssistantMessagePart::Text {+ text: "Let me calculate that for you.".to_string(),+ },+ AssistantMessagePart::ToolCall {+ name: tool_name.clone(),+ json: json!({"expression": "2 + 2"}),+ id: tool_call_id.clone(),+ },+ AssistantMessagePart::ToolCallResponseJson {+ name: tool_name.clone(),+ json: json!({"result": 4}),+ id: tool_call_id.clone(),+ },+ AssistantMessagePart::Text {+ text: "The answer is 4.".to_string(),+ },+ ]);++ let msg = ChatMessage {role: Role::Assistant,content: ChatMessageContent::AssistantMessageParts(vec![AssistantMessagePart::Text {@@ -623,12 +641,11 @@ mod tests {text: "The answer is 4.".to_string(),},]),- image_urls: None,+ attachments: None,};- let openai_msgs: Vec<ChatCompletionRequestMessage> = original.clone().into();+ let openai_msgs: Vec<ChatCompletionRequestMessage> = msg.into();- // Create tool call mapping for conversion backlet mut tool_mapping = HashMap::new();tool_mapping.insert(tool_call_id, tool_name);@@ -637,31 +654,10 @@ mod tests {.map(|msg| convert_message(msg, Some(&tool_mapping))).collect();- // Convert back to ChatMessages to merge assistant messageslet chat_messages = ChatMessages::from(converted_messages);- let converted_back = &chat_messages.0[0];-- assert_eq!(original.role, converted_back.role);- assert_eq!(original.content, converted_back.content);- assert_eq!(original.image_urls, converted_back.image_urls);- }-- #[test]- fn test_multiple_images_roundtrip() {- let original = ChatMessage {- role: Role::User,- content: ChatMessageContent::Text("Compare these images".to_string()),- image_urls: Some(vec![- ImageData::StaticUrl("https://example.com/image1.jpg".to_string()),- ImageData::StaticUrl("https://example.com/image2.jpg".to_string()),- ]),- };-- let openai_msgs: Vec<ChatCompletionRequestMessage> = original.clone().into();- let converted_back = convert_message(openai_msgs.into_iter().next().unwrap(), None);+ let converted = &chat_messages.0[0];- assert_eq!(original.role, converted_back.role);- assert_eq!(original.content, converted_back.content);- assert_eq!(original.image_urls, converted_back.image_urls);+ assert_eq!(converted.role, Role::Assistant);+ assert_eq!(converted.content, expected_content);}}diff --git a/rust/cloud-storage/ai/src/types/providers/openai/request.rs b/rust/cloud-storage/ai/src/types/providers/openai/request.rsindex fe70d81ddc..a06aa21e45 100644--- a/rust/cloud-storage/ai/src/types/providers/openai/request.rs+++ b/rust/cloud-storage/ai/src/types/providers/openai/request.rs@@ -10,9 +10,7 @@ use schemars::{JsonSchema, schema_for};use serde::Deserialize;impl ChatCompletionRequest {- pub fn openai_messages(&self) -> Vec<ChatCompletionRequestMessage> {- let mut all_messages = vec![];-+ pub fn openai_messages(self) -> Vec<ChatCompletionRequestMessage> {let system_message =ChatCompletionRequestMessage::System(ChatCompletionRequestSystemMessage {content: ChatCompletionRequestSystemMessageContent::Text(@@ -21,15 +19,12 @@ impl ChatCompletionRequest {name: None,});- let messages: Vec<ChatCompletionRequestMessage> = self- .messages- .clone()- .into_iter()- .flat_map(Vec::<ChatCompletionRequestMessage>::from)- .collect();-- all_messages.push(system_message);- all_messages.extend(messages);+ let mut all_messages = vec![system_message];+ all_messages.extend(+ self.messages+ .into_iter()+ .flat_map(Vec::<ChatCompletionRequestMessage>::from),+ );all_messages}}diff --git a/rust/cloud-storage/ai/src/types/request.rs b/rust/cloud-storage/ai/src/types/request.rsindex 42221370e9..47e3ca2c8c 100644--- a/rust/cloud-storage/ai/src/types/request.rs+++ b/rust/cloud-storage/ai/src/types/request.rs@@ -1,6 +1,6 @@-use super::{ChatMessage, ImageData, SystemPrompt, model::Model};+use super::{ChatMessage, SystemPrompt, model::Model};-#[derive(Debug, Clone)]+#[derive(Debug)]pub struct ChatCompletionRequest {/// can either be openai or googlepub(crate) model: Model,@@ -10,17 +10,6 @@ pub struct ChatCompletionRequest {pub(crate) system_prompt: SystemPrompt,}-impl std::fmt::Debug for ImageData {- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- match self {- Self::Base64(base_64) => {- write!(f, "bytes {:?}", base_64)- }- Self::StaticUrl(url) => write!(f, "url {}", url),- }- }-}-impl ChatCompletionRequest {pub fn model(&self) -> Model {self.modeldiff --git a/rust/cloud-storage/ai/src/types/request_builder.rs b/rust/cloud-storage/ai/src/types/request_builder.rsindex 6e3f5cb056..d6c78c4b3d 100644--- a/rust/cloud-storage/ai/src/types/request_builder.rs+++ b/rust/cloud-storage/ai/src/types/request_builder.rs@@ -1,33 +1,7 @@-use crate::{- traits::TextAttachment,- types::{- ChatCompletionRequest, ChatMessage, ChatMessageContent, ImageData, Model, Role,- SystemPrompt,- },+use crate::types::{+ ChatCompletionRequest, ChatMessage, ChatMessageContent, Model, Role, SystemPrompt,};--#[derive(Default)]-pub struct Attachments(pub Vec<Attachment>);--impl From<Vec<Attachment>> for Attachments {- fn from(value: Vec<Attachment>) -> Self {- Attachments(value)- }-}--impl From<Vec<Box<dyn TextAttachment>>> for Attachments {- fn from(values: Vec<Box<dyn TextAttachment>>) -> Self {- Attachments(values.into_iter().map(Attachment::Text).collect())- }-}--pub enum Attachment {- /// A document, channel, project, or other thing that can be represented by text- /// These are inserted into the system prompt- Text(Box<dyn TextAttachment>),- /// a base64 or static url to a supported image type- Image(ImageData),-}+use attachment::Attachments;pub type NotSet = ();@@ -77,41 +51,27 @@ pub struct RequestBuilder<ChatModel, Messages, Prompt> {/// optional max tokens (input + output)max_tokens: Option<u32>,/// optional list of attachments (prefetched)- attachments: Option<Attachments>,+ attachments: Option<Attachments<'static>>,}/// the build method only works if we have model, messages, and system promptimpl RequestBuilder<Model, Vec<ChatMessage>, String> {pub fn build(mut self) -> ChatCompletionRequest {- let (image_attachments, prompt_attachments) = std::mem::take(&mut self.attachments)- .unwrap_or_default()- .0- .into_iter()- .map(|attachment| match attachment {- Attachment::Image(data) => (Some(data), None),- Attachment::Text(text_attachment) => (None, Some(text_attachment)),- })- .collect::<(Vec<_>, Vec<_>)>();-- let image_attachments = image_attachments.into_iter().flatten().collect::<Vec<_>>();- let prompt_attachments = prompt_attachments.into_iter().flatten().collect::<Vec<_>>();- let system_prompt = SystemPrompt {- attachments: prompt_attachments.into(),- instructions: std::mem::take(&mut self.system_prompt),- };- // insert images on the last user message :)- if !image_attachments.is_empty()+ if let Some(attachments) = self.attachments.take()&& let Some(message) = self.messages.iter_mut().rev().find(|message| message.role == Role::User){- message.image_urls = Some(image_attachments);+ message.attachments = Some(attachments);}ChatCompletionRequest {- system_prompt,+ system_prompt: SystemPrompt {+ attachments: Default::default(),+ instructions: self.system_prompt,+ },messages: self.messages,model: self.model,}@@ -158,35 +118,8 @@ impl<ChatModel, Messages, Prompt> RequestBuilder<ChatModel, Messages, Prompt> {}}- // set text attachments- pub fn attachments(mut self, attachments: impl Into<Attachments>) -> Self {- let attachments = attachments.into();- if attachments.0.is_empty() {- self.attachments = None;- self- } else {- self.attachments = Some(attachments);- self- }- }-- pub fn add_text_attachment(mut self, attachment: Box<dyn TextAttachment>) -> Self {- let wrapped = Attachment::Text(attachment);- if let Some(ref mut attachments) = self.attachments {- attachments.0.push(wrapped)- } else {- self.attachments = Some(vec![wrapped].into());- }- self- }-- pub fn add_image_attachment(mut self, data: ImageData) -> Self {- let wrapped = Attachment::Image(data);- if let Some(ref mut attachments) = self.attachments {- attachments.0.push(wrapped)- } else {- self.attachments = Some(vec![wrapped].into());- }+ pub fn attachments(mut self, attachments: Attachments<'static>) -> Self {+ self.attachments = Some(attachments);self}@@ -196,8 +129,8 @@ impl<ChatModel, Messages, Prompt> RequestBuilder<ChatModel, Messages, Prompt> {) -> RequestBuilder<ChatModel, Vec<ChatMessage>, Prompt> {self.messages(vec![ChatMessage {content: ChatMessageContent::Text(message.into()),- image_urls: None,role: Role::User,+ attachments: None,}])}@@ -267,11 +200,8 @@ mod test {// Verify messages countassert_eq!(request.messages.len(), 2);- // Verify no image attachments on any messagefor message in &request.messages {- assert!(- message.image_urls.is_none() || message.image_urls.as_ref().unwrap().is_empty()- );+ assert!(message.attachments.is_none());}}}diff --git a/rust/cloud-storage/ai_tools/Cargo.toml b/rust/cloud-storage/ai_tools/Cargo.tomlindex 127d2883eb..6f4b248b5e 100644--- a/rust/cloud-storage/ai_tools/Cargo.toml+++ b/rust/cloud-storage/ai_tools/Cargo.toml@@ -10,6 +10,8 @@ test-support = [][dependencies]ai = { path = "../ai" }ai_format = { path = "../ai_format" }+attachment = { path = "../attachment" }+non_empty = { path = "../non_empty" }ai_toolset = { path = "../ai_toolset" }anthropic = { path = "../anthropic" }anyhow.workspace = true@@ -41,6 +43,7 @@ macro_db_client = { path = "../macro_db_client" }macro_env_var = { path = "../macro_env_var" }macro_user_id = { path = "../macro_user_id" }model = { path = "../model" }+model-entity = { path = "../model-entity" }model_notifications = { path = "../model_notifications" }models_dcs = { path = "../models_dcs" }models_email = { path = "../models_email" }diff --git a/rust/cloud-storage/ai_tools/src/rewrite/tool.rs b/rust/cloud-storage/ai_tools/src/rewrite/tool.rsindex 0d7e15881f..d7c558d137 100644--- a/rust/cloud-storage/ai_tools/src/rewrite/tool.rs+++ b/rust/cloud-storage/ai_tools/src/rewrite/tool.rs@@ -2,7 +2,6 @@ use super::types::AIDiffResponse;use super::types::{PROMPT, REWRITE_MODEL};use crate::tool_context::ToolScribe;use ai::types::{MessageBuilder, RequestBuilder};-use ai_format::document::Document;use ai_toolset::{AsyncTool, RequestContext, ServiceContext, ToolCallError, ToolResult};use anyhow::Error;use async_trait::async_trait;@@ -71,20 +70,19 @@ pub async fn generate_patches(markdown_text: String,file_name: String,) -> Result<AIDiffResponse, Error> {+ let attachment_content = attachment::AttachmentContent {+ reference: model_entity::EntityType::Document.with_entity_string(request.markdown_file_id),+ name: Some(file_name),+ content: non_empty::NonEmpty::one(attachment::AttachmentPart::Content(markdown_text)),+ };+ let attachments =+ attachment::Attachments::new(non_empty::NonEmpty::one(Ok(attachment_content)));+let request = RequestBuilder::new().max_tokens(32_000).system_prompt(PROMPT).model(REWRITE_MODEL)- .add_text_attachment(- Document {- content: markdown_text,- file_type: "md".into(),- id: request.markdown_file_id,- name: file_name,- properties: None,- }- .boxed(),- )+ .attachments(attachments).messages(vec![MessageBuilder::new().content(request.instructions)diff --git a/rust/cloud-storage/attachment/Cargo.toml b/rust/cloud-storage/attachment/Cargo.tomlindex 412cb832aa..2b4c7e030d 100644--- a/rust/cloud-storage/attachment/Cargo.toml+++ b/rust/cloud-storage/attachment/Cargo.toml@@ -9,8 +9,13 @@ provider = ["dep:futures"][dependencies]anyhow = { workspace = true }+serde = { workspace = true }thiserror = { workspace = true }-ai = { path = "../ai" }macro_user_id = { path = "../macro_user_id" }non_empty = { path = "../non_empty" }futures = { workspace = true, optional = true }+base64 = { workspace = true }+image = { workspace = true }+model_file_type = { path = "../model_file_type" }+model-entity = { path = "../model-entity" }+webp = "0.3.1"diff --git a/rust/cloud-storage/attachment/src/attachable.rs b/rust/cloud-storage/attachment/src/attachable.rsindex 476db562e8..26a0f66adc 100644--- a/rust/cloud-storage/attachment/src/attachable.rs+++ b/rust/cloud-storage/attachment/src/attachable.rs@@ -1,11 +1,17 @@//! impls for Attachable-use crate::Attachable;+#[cfg(test)]+mod test;++use std::borrow::Cow;+use crate::fmt::{ClosedXmlTag, XmlTag};use crate::models::*;+use crate::{Attachable, Attributes};+use model_entity::Entity;use non_empty::NonEmpty;-impl Attachable for Attachments {+impl Attachable for Attachments<'_> {fn into_formatted_parts(self) -> FormattedParts {let parts = self.into_parts()@@ -27,15 +33,15 @@ impl Attachable for Attachments {impl Attachable for ResolutionError {fn into_formatted_parts(self) -> FormattedParts {XmlTag {- name: "unavailable_attachment",- attrs: &[("id", self.id.as_str())],+ name: "attachment",+ attrs: self.reference.attributes(),body: self.error,}.into_formatted_parts()}}-impl Attachable for AttachmentPart {+impl Attachable for AttachmentPart<'_> {fn into_formatted_parts(self) -> FormattedParts {match self {AttachmentPart::Content(text) => FormattedParts::one(TextOrImage::Text(text)),@@ -43,7 +49,10 @@ impl Attachable for AttachmentPart {AttachmentPart::ImageError(e) => e.into_formatted_parts(),AttachmentPart::Metadata { key, value } => ClosedXmlTag {name: "metadata",- attrs: &[("key", &key), ("value", &value)],+ attrs: vec![+ (Cow::Borrowed("key"), Cow::Owned(key)),+ (Cow::Borrowed("value"), Cow::Owned(value)),+ ],}.into_formatted_parts(),AttachmentPart::Child(child) => match *child {@@ -55,7 +64,7 @@ impl Attachable for AttachmentPart {}}-impl Attachable for NonEmpty<Vec<AttachmentPart>> {+impl Attachable for NonEmpty<Vec<AttachmentPart<'_>>> {fn into_formatted_parts(self) -> FormattedParts {let parts = self.into_inner()@@ -66,28 +75,26 @@ impl Attachable for NonEmpty<Vec<AttachmentPart>> {acc});- FormattedParts::new(NonEmpty::new(parts).expect("this will not be empty"))+ FormattedParts::new(NonEmpty::new(parts).expect("attachments is non empty"))}}-impl Attachable for AttachmentContent {+impl Attachable for AttachmentContent<'_> {fn into_formatted_parts(self) -> FormattedParts {- let attributes = self.reference.as_attributes();- let tag = XmlTag {- attrs: attributes.as_slice(),+ XmlTag {+ attrs: self.reference.attributes(),name: "attachment",body: self.content,- };- tag.into_formatted_parts()+ }+ .into_formatted_parts()}}-impl Attachable for AttachmentReference {+impl Attachable for Entity<'_> {fn into_formatted_parts(self) -> FormattedParts {- let attrs = self.as_attributes();ClosedXmlTag {name: "attachment_reference",- attrs: &attrs,+ attrs: self.attributes(),}.into_formatted_parts()}diff --git a/rust/cloud-storage/attachment/src/attachable/test.rs b/rust/cloud-storage/attachment/src/attachable/test.rsnew file mode 100644index 0000000000..3ec561f612--- /dev/null+++ b/rust/cloud-storage/attachment/src/attachable/test.rs@@ -0,0 +1,117 @@+use super::*;+use model_entity::EntityType;+use non_empty::NonEmpty;++fn to_text(parts: FormattedParts) -> String {+ parts+ .into_parts()+ .into_inner()+ .into_iter()+ .filter_map(|p| match p {+ TextOrImage::Text(t) => Some(t),+ _ => None,+ })+ .collect::<Vec<_>>()+ .join("\n")+}++fn make_error() -> AttachmentError {+ AttachmentError::PermissionDenied(Box::new(std::io::Error::new(+ std::io::ErrorKind::PermissionDenied,+ "User does not have access to the requested resource",+ )))+}++fn make_resolution_error() -> ResolutionError {+ ResolutionError::new(+ EntityType::Document.with_entity_string("019dd0ff-d8ee-7dc0-8580-e0ad1e706967".to_string()),+ make_error(),+ )+}++#[test]+fn successful_attachment_content() {+ let content = AttachmentContent {+ reference: EntityType::Document.with_entity_string("abc123".to_string()),+ name: Some("Test Doc".to_string()),+ content: NonEmpty::new(vec![AttachmentPart::Content("Hello world".to_string())]).unwrap(),+ };+ let output = to_text(content.into_formatted_parts());+ assert!(output.contains("kind=document"), "should have kind");+ assert!(output.contains("id=abc123"), "should have id");+ assert!(output.contains("Hello world"), "should have content");+}++#[test]+fn resolution_error_uses_attachment_tag() {+ let output = to_text(make_resolution_error().into_formatted_parts());+ println!("=== resolution_error ===\n{output}\n");+ assert!(+ output.contains("<attachment "),+ "errors should use <attachment> tag"+ );+ assert!(+ !output.contains("unavailable_attachment"),+ "should NOT use nested unavailable_attachment tag"+ );+ assert!(output.contains("kind=document"), "should have entity kind");+ assert!(output.contains("id=019dd0ff"), "should have entity id");+}++#[test]+fn attachment_with_child_error() {+ let content = AttachmentContent {+ reference: EntityType::Document.with_entity_string("parent-doc".to_string()),+ name: Some("Parent".to_string()),+ content: NonEmpty::new(vec![+ AttachmentPart::Content("Some text".to_string()),+ AttachmentPart::Child(Box::new(Err(make_resolution_error()))),+ ])+ .unwrap(),+ };+ let output = to_text(content.into_formatted_parts());+ println!("=== attachment_with_child_error ===\n{output}\n");+ assert!(+ output.contains(" Some text"),+ "body should be indented once"+ );+ assert!(+ output.contains(" User does not have access"),+ "nested error body should be double-indented"+ );+}++#[test]+fn mixed_success_and_failure() {+ let attachments = Attachments::new(+ NonEmpty::new(vec![+ Ok(AttachmentContent {+ reference: EntityType::Document.with_entity_string("doc-1".to_string()),+ name: Some("Good Doc".to_string()),+ content: NonEmpty::new(vec![AttachmentPart::Content(+ "Document content here".to_string(),+ )])+ .unwrap(),+ }),+ Err(make_resolution_error()),+ ])+ .unwrap(),+ );+ let output = to_text(attachments.into_formatted_parts());+ println!("=== mixed_success_and_failure ===\n{output}\n");+}++#[test]+fn xml_tag_produces_single_text_part() {+ let content = AttachmentContent {+ reference: EntityType::Document.with_entity_string("abc123".to_string()),+ name: Some("Test Doc".to_string()),+ content: NonEmpty::new(vec![AttachmentPart::Content("Hello world".to_string())]).unwrap(),+ };+ let parts: Vec<_> = content.into_formatted_parts().into_parts().into_inner();+ assert_eq!(+ parts.len(),+ 1,+ "XmlTag should produce a single compacted Text part"+ );+}diff --git a/rust/cloud-storage/attachment/src/attributes.rs b/rust/cloud-storage/attachment/src/attributes.rsnew file mode 100644index 0000000000..bc1f90ee8b--- /dev/null+++ b/rust/cloud-storage/attachment/src/attributes.rs@@ -0,0 +1,17 @@+//! impls for Attributes+use crate::Attributes;+use crate::fmt::Attr;+use model_entity::Entity;+use std::borrow::Cow;++impl Attributes for Entity<'_> {+ fn attributes(&self) -> Vec<Attr<'_>> {+ vec![+ (+ Cow::Borrowed("kind"),+ Cow::Borrowed(self.entity_type.as_ref()),+ ),+ (Cow::Borrowed("id"), Cow::Borrowed(&self.entity_id)),+ ]+ }+}diff --git a/rust/cloud-storage/attachment/src/fmt.rs b/rust/cloud-storage/attachment/src/fmt.rsindex 6639354e8f..97fdc7f5b4 100644--- a/rust/cloud-storage/attachment/src/fmt.rs+++ b/rust/cloud-storage/attachment/src/fmt.rs@@ -1,4 +1,5 @@//! Formatting utilities+use std::borrow::Cow;use std::fmt;use non_empty::NonEmpty;@@ -9,17 +10,27 @@ use crate::models::TextOrImage;const INDENT: &str = " ";+/// A key-value attribute pair for XML tags.+pub type Attr<'a> = (Cow<'a, str>, Cow<'a, str>);++/// Convert borrowed string pairs into [`Attr`]s.+pub fn attrs<'a>(pairs: &[(&'a str, &'a str)]) -> Vec<Attr<'a>> {+ pairs+ .iter()+ .map(|(k, v)| (Cow::Borrowed(*k), Cow::Borrowed(*v)))+ .collect()+}+/// Indentpub struct Indent<T>(pub T);/// XmlTag-pub struct XmlTag<'a, T: Sized> {+pub struct XmlTag<'a, T> {/// Tag name.pub name: &'a str,- /// Attributes as `(key, value)` pairs. Rendered in order, space-separated,- /// with double-quoted values. Values are not escaped — callers are- /// expected to pass attribute-safe text.- pub attrs: &'a [(&'a str, &'a str)],+ /// Attributes as `(key, value)` pairs. Rendered in order, space-separated.+ /// Values are not escaped — callers are expected to pass attribute-safe text.+ pub attrs: Vec<Attr<'a>>,/// Body content. Indented under the opening tag.pub body: T,}@@ -29,10 +40,10 @@ pub struct ClosedXmlTag<'a> {/// tag namepub name: &'a str,/// attributes- pub attrs: &'a [(&'a str, &'a str)],+ pub attrs: Vec<Attr<'a>>,}-fn format_attrs(attrs: &[(&str, &str)]) -> String {+fn format_attrs(attrs: &[Attr<'_>]) -> String {attrs.iter().map(|(k, v)| format!("{k}={v}"))@@ -40,7 +51,7 @@ fn format_attrs(attrs: &[(&str, &str)]) -> String {.join(" ")}-fn open_tag(name: &str, attrs: &[(&str, &str)]) -> String {+fn open_tag(name: &str, attrs: &[Attr<'_>]) -> String {format!("<{name} {}>", format_attrs(attrs))}@@ -48,20 +59,24 @@ fn close_tag(name: &str) -> String {format!("</{name}>")}-fn self_closing_tag(name: &str, attrs: &[(&str, &str)]) -> String {+fn self_closing_tag(name: &str, attrs: &[Attr<'_>]) -> String {format!("<{name} {}/>", format_attrs(attrs))}-fn indent_line(line: &str) -> String {- format!("{INDENT}{line}")+fn indent_text(text: &str) -> String {+ text.lines()+ .map(|line| format!("{INDENT}{line}"))+ .collect::<Vec<_>>()+ .join("\n")}impl<'a, T: Attachable> Attachable for XmlTag<'a, T> {fn into_formatted_parts(self) -> FormattedParts {Indent(self.body).into_formatted_parts()- .prepend(TextOrImage::Text(open_tag(self.name, self.attrs)))+ .prepend(TextOrImage::Text(open_tag(self.name, &self.attrs))).append(TextOrImage::Text(close_tag(self.name)))+ .compact()}}@@ -69,15 +84,15 @@ impl<T: Attachable> Attachable for Indent<T> {fn into_formatted_parts(self) -> FormattedParts {self.0.into_formatted_parts().map(|p| match p {img @ TextOrImage::Image(_) => img,- TextOrImage::Text(t) => TextOrImage::Text(indent_line(&t)),+ TextOrImage::Text(t) => TextOrImage::Text(indent_text(&t)),})}}-impl<'a> Attachable for ClosedXmlTag<'a> {+impl Attachable for ClosedXmlTag<'_> {fn into_formatted_parts(self) -> FormattedParts {- let tag = self_closing_tag(self.name, self.attrs);- FormattedParts::new(NonEmpty::new(vec![TextOrImage::Text(tag)]).expect("one tag"))+ let tag = self_closing_tag(self.name, &self.attrs);+ FormattedParts::new(NonEmpty::one(TextOrImage::Text(tag)))}}@@ -98,7 +113,7 @@ impl<T: fmt::Display> fmt::Display for Indent<T> {impl<'a, T: fmt::Display> fmt::Display for XmlTag<'a, T> {fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {- writeln!(f, "{}", open_tag(self.name, self.attrs))?;+ writeln!(f, "{}", open_tag(self.name, &self.attrs))?;writeln!(f, "{}", Indent(&self.body))?;write!(f, "{}", close_tag(self.name))}@@ -106,6 +121,6 @@ impl<'a, T: fmt::Display> fmt::Display for XmlTag<'a, T> {impl fmt::Display for ClosedXmlTag<'_> {fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {- write!(f, "{}", self_closing_tag(self.name, self.attrs))+ write!(f, "{}", self_closing_tag(self.name, &self.attrs))}}diff --git a/rust/cloud-storage/ai/src/types/image/base_64_image.rs b/rust/cloud-storage/attachment/src/image/base_64_image.rssimilarity index 83%rename from rust/cloud-storage/ai/src/types/image/base_64_image.rsrename to rust/cloud-storage/attachment/src/image/base_64_image.rsindex 7f84c9b6dd..e0cf7f3102 100644--- a/rust/cloud-storage/ai/src/types/image/base_64_image.rs+++ b/rust/cloud-storage/attachment/src/image/base_64_image.rs@@ -3,23 +3,33 @@ use base64::Engine;use base64::engine::general_purpose;use image::{DynamicImage, GenericImageView};use model_file_type::FileType;+use serde::{Deserialize, Serialize};use webp::Encoder;const ENCODING_QUALITY: f32 = 75.0;const MAX_SIZE_W: u32 = 1080;const MAX_SIZE_H: u32 = 720;-#[derive(Eq, PartialEq, Clone)]+/// A base64-encoded image with a known format.+///+/// Images are optionally downscaled to fit within 1080x720 and re-encoded as+/// WebP at 75% quality to reduce token cost when sent to an AI model.+#[derive(Eq, PartialEq, Clone, Serialize, Deserialize)]pub struct Base64Image {data: String,format: ImageFormat,}-#[derive(Clone, Debug, Copy, Eq, PartialEq)]+/// Supported image formats for base64 encoding.+#[derive(Clone, Debug, Copy, Eq, PartialEq, Serialize, Deserialize)]pub enum ImageFormat {+ /// WebP format.WebP,+ /// JPG format (three-letter extension).Jpg,+ /// JPEG format (four-letter extension).Jpeg,+ /// PNG format.Png,}@@ -37,8 +47,9 @@ impl TryFrom<FileType> for ImageFormat {}impl Base64Image {- pub fn compress_and_reencode(bytes: Vec<u8>) -> Result<Self, anyhow::Error> {- Self::make_compressed_base64_webp(bytes)+ /// Compress and re-encode raw image bytes into a base64 WebP.+ pub fn downscale_and_reencode(bytes: Vec<u8>) -> Result<Self, anyhow::Error> {+ Self::make_downscaled_base64_webp(bytes)}pub(crate) fn try_from_string(s: &str) -> Result<Self, anyhow::Error> {@@ -94,7 +105,7 @@ impl std::fmt::Debug for Base64Image {}impl Base64Image {- fn make_compressed_base64_webp(image_bytes: Vec<u8>) -> Result<Self, anyhow::Error> {+ fn make_downscaled_base64_webp(image_bytes: Vec<u8>) -> Result<Self, anyhow::Error> {let img = image::load_from_memory(&image_bytes)?;let resized_img = Self::resize_if_needed(img);let rgb_img = resized_img.to_rgb8();diff --git a/rust/cloud-storage/attachment/src/image/mod.rs b/rust/cloud-storage/attachment/src/image/mod.rsnew file mode 100644index 0000000000..526a16e607--- /dev/null+++ b/rust/cloud-storage/attachment/src/image/mod.rs@@ -0,0 +1,28 @@+//! Image types for encoding and compressing images for AI consumption.++mod base_64_image;++pub use base_64_image::*;++/// An image that can be included in an attachment.+#[derive(PartialEq, Eq, Clone, Debug, serde::Serialize, serde::Deserialize)]+pub enum ImageData {+ /// A base64-encoded image, potentially re-encoded as WebP.+ Base64(Base64Image),+ /// A publicly accessible URL pointing to the image.+ StaticUrl(String),+}++impl ImageData {+ /// Compress and re-encode raw image bytes into a downscaled WebP.+ pub fn try_from_bytes(bytes: Vec<u8>) -> Result<Self, anyhow::Error> {+ Base64Image::downscale_and_reencode(bytes).map(Self::Base64)+ }++ /// try to parse a string as a base64 image+ pub fn try_base64_from_string(s: String) -> Result<Self, anyhow::Error> {+ Base64Image::try_from_string(&s)+ .map(Self::Base64)+ .or_else(|_| Ok(Self::StaticUrl(s)))+ }+}diff --git a/rust/cloud-storage/attachment/src/lib.rs b/rust/cloud-storage/attachment/src/lib.rsindex dd6fb09660..e1d2a224ed 100644--- a/rust/cloud-storage/attachment/src/lib.rs+++ b/rust/cloud-storage/attachment/src/lib.rs@@ -1,13 +1,17 @@//! A lib crate to support AI attachment consumers and providers#![deny(missing_docs)]+use macro_user_id::user_id::MacroUserIdStr;+use model_entity::Entity;+pub use models::*;use non_empty::NonEmpty;mod attachable;+mod attributes;pub mod fmt;+pub mod image;mod macros;mod models;-pub use models::*;#[cfg(feature = "provider")]pub mod provider;@@ -22,11 +26,11 @@ pub trait AttachmentService: Send + Sync + 'static {/// failures never fail the batch — they surface as/// [`FailedAttachment`](super::models::FailedAttachment) entries in the/// returned [`AttachmentContents`](super::models::AttachmentContents).- fn resolve_attachments(+ fn resolve_attachments<'a>(&self,user_id: MacroUserIdStr<'_>,- ids: NonEmpty<&[&str]>,- ) -> impl Future<Output = Attachments> + Send;+ ids: NonEmpty<&[&'a Entity<'a>]>,+ ) -> impl Future<Output = Attachments<'a>> + Send;}/// An attachable is something that can be represented to AI as a [`FormattedAttachment`]@@ -34,3 +38,9 @@ pub trait Attachable {/// transform into formatted attachmentfn into_formatted_parts(self) -> FormattedParts;}++/// Produce key-value attributes for XML tag rendering via [`fmt::XmlTag`] / [`fmt::ClosedXmlTag`].+pub trait Attributes {+ /// Return attribute pairs for this value.+ fn attributes(&self) -> Vec<fmt::Attr<'_>>;+}diff --git a/rust/cloud-storage/attachment/src/macros.rs b/rust/cloud-storage/attachment/src/macros.rsindex ae9defe29e..93f88ae9f9 100644--- a/rust/cloud-storage/attachment/src/macros.rs+++ b/rust/cloud-storage/attachment/src/macros.rs@@ -3,27 +3,23 @@macro_rules! non_empty_collection {($(#[$meta:meta])*- $vis:vis struct $name:ident($item:ty);+ $vis:vis struct $name:ident $(<$lt:lifetime>)? ($item:ty);) => {$(#[$meta])*- $vis struct $name(NonEmpty<Vec<$item>>);-- impl $name {+ $vis struct $name $(<$lt>)? (NonEmpty<Vec<$item>>);+ impl $(<$lt>)? $name $(<$lt>)? {/// Wrap a non-empty vec.$vis fn new(parts: NonEmpty<Vec<$item>>) -> Self {Self(parts)}-/// Build from a single item.$vis fn one(part: $item) -> Self {- Self(NonEmpty::new(vec![part]).expect("single element is non-empty"))+ Self(NonEmpty::one(part))}-/// Borrow the underlying parts.$vis fn parts(&self) -> &NonEmpty<Vec<$item>> {&self.0}-/// Consume into the underlying parts.$vis fn into_parts(self) -> NonEmpty<Vec<$item>> {self.0@@ -40,7 +36,6 @@ macro_rules! non_empty_collection {inner.push(item);Self(NonEmpty::new(inner).expect("append cannot be empty"))}-/// Apply a function to each item.$vis fn map(self, f: impl FnMut($item) -> $item) -> Self {Self(NonEmpty::new(self.0diff --git a/rust/cloud-storage/attachment/src/models.rs b/rust/cloud-storage/attachment/src/models.rsindex 2466c2dbbb..1dc8a09bff 100644--- a/rust/cloud-storage/attachment/src/models.rs+++ b/rust/cloud-storage/attachment/src/models.rs@@ -1,77 +1,16 @@use std::fmt;-use ai::types::ImageData;+use crate::image::ImageData;+use model_entity::{Entity, EntityType};use non_empty::NonEmpty;use thiserror::Error;-/// A typed reference to an attachment source.-#[derive(Debug)]-pub enum AttachmentReference {- /// A file that lives in DSS (including MD)- DssFile {- /// Document ID- id: String,- },- /// An image that lives in static file service- SfsImage {- /// image url- url: String,- },- /// An email thread- EmailThread {- /// Thread ID- id: String,- },- /// An AI chat- Chat {- /// Chat ID- id: String,- },- /// Channels thread- Channel {- /// Channel ID- id: String,- },-}--impl AttachmentReference {- /// The entity ID for this reference, if it has one.- pub fn id(&self) -> Option<&str> {- match self {- Self::DssFile { id }- | Self::EmailThread { id }- | Self::Chat { id }- | Self::Channel { id } => Some(id),- Self::SfsImage { .. } => None,- }- }- /// Convert this reference into XML attribute pairs.- pub fn as_attributes(&self) -> Vec<(&'static str, &str)> {- let mut attrs = vec![];- if let Some(id) = self.id() {- attrs.push(("id", id));- }- match self {- AttachmentReference::Channel { .. } => attrs.push(("kind", "channel")),- AttachmentReference::Chat { .. } => attrs.push(("kind", "chat")),- AttachmentReference::DssFile { .. } => attrs.push(("kind", "file")),- AttachmentReference::EmailThread { .. } => attrs.push(("kind", "email-thread")),- AttachmentReference::SfsImage { .. } => attrs.push(("kind", "static-image")),- }-- attrs- }-}-/// Errors that can occur while resolving attachments.#[derive(Debug, Error)]pub enum AttachmentError {- /// The caller does not have read access to the referenced document.- #[error("no read access to document {id}")]- PermissionDenied {- /// The id of the document the user lacks access to.- id: String,- },+ /// The caller does not have access to the referenced entity.+ #[error(transparent)]+ PermissionDenied(Box<dyn std::error::Error + Send + Sync>),/// The referenced document has no file type recorded.#[error("unknown file type")]UnknownFileType,@@ -84,26 +23,29 @@ pub enum AttachmentError {/// An internal error occurred while resolving the attachment.#[error(transparent)]Internal(#[from] anyhow::Error),+ /// the wrong attachment service was used to resolve the attachment+ #[error("this service {0} does not provide this entity kind {1}")]+ RoutingError(String, EntityType),}-/// An attachment or attachment part that failed to resolve with its id+/// An attachment that failed to resolve.#[derive(Debug)]pub struct ResolutionError {- /// Id of attachment that failed to resolve- pub id: String,- /// Reason+ /// The entity that could not be resolved.+ pub reference: Entity<'static>,+ /// Reason for the failure.pub error: AttachmentError,}impl ResolutionError {/// Create a new resolution error.- pub fn new(id: String, error: AttachmentError) -> Self {- Self { id, error }+ pub fn new(reference: Entity<'static>, error: AttachmentError) -> Self {+ Self { reference, error }}}/// Rich representation of attachment content-pub enum AttachmentPart {+pub enum AttachmentPart<'a> {/// An image that failed to resolveImageError(ResolutionError),/// Attachment text@@ -111,9 +53,9 @@ pub enum AttachmentPart {/// Attachment image data.Image(ImageData),/// A resolved child attachment- Child(Box<Result<AttachmentContent, ResolutionError>>),+ Child(Box<Result<AttachmentContent<'static>, ResolutionError>>),/// A reference to a child attachment- ChildReference(AttachmentReference),+ ChildReference(Entity<'a>),/// KV metadataMetadata {/// key@@ -124,7 +66,7 @@ pub enum AttachmentPart {}// manual impl to prevent excessive logging-impl std::fmt::Debug for AttachmentPart {+impl<'a> std::fmt::Debug for AttachmentPart<'a> {fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {match self {Self::Content(s) => write!(f, "Content([{} chars])", s.chars().count()),@@ -139,13 +81,13 @@ impl std::fmt::Debug for AttachmentPart {/// A resolved attachment#[derive(Debug)]-pub struct AttachmentContent {+pub struct AttachmentContent<'a> {/// name + kind- pub reference: AttachmentReference,+ pub reference: Entity<'a>,/// namepub name: Option<String>,/// content- pub content: NonEmpty<Vec<AttachmentPart>>,+ pub content: NonEmpty<Vec<AttachmentPart<'static>>>,}crate::non_empty_collection! {@@ -154,10 +96,11 @@ crate::non_empty_collection! {/// Produced by [`Attachable`](super::ports::Attachable) implementations./// Guaranteed to contain at least one part via [`NonEmpty`].#[derive(Debug)]- pub struct Attachments(Result<AttachmentContent, ResolutionError>);+ pub struct Attachments<'a>(Result<AttachmentContent<'a>, ResolutionError>);}/// The primitive form of attachment data sent to AI providers+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]pub enum TextOrImage {/// All non-image dats is represented as textText(String),@@ -167,6 +110,7 @@ pub enum TextOrImage {crate::non_empty_collection! {/// A collection of attachment data constructed from one or more attachments+ #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]pub struct FormattedParts(TextOrImage);}diff --git a/rust/cloud-storage/attachment/src/provider.rs b/rust/cloud-storage/attachment/src/provider.rsindex 821ad2bd9d..51b6a0e05d 100644--- a/rust/cloud-storage/attachment/src/provider.rs+++ b/rust/cloud-storage/attachment/src/provider.rs@@ -1,64 +1,63 @@-//! Attachment provider — a router that dispatches [`AttachmentReference`]s-//! to the correct [`AttachmentService`] by variant.+//! Attachment provider — routes [`Entity`] references to the correct+//! [`AttachmentService`] by [`EntityType`].use macro_user_id::user_id::MacroUserIdStr;+use model_entity::{Entity, EntityType};use non_empty::NonEmpty;-use crate::{- AttachmentContent, AttachmentReference, AttachmentService, Attachments, ResolutionError,-};+use crate::{AttachmentContent, AttachmentService, Attachments, ResolutionError};-/// Routes [`AttachmentReference`]s to per-variant [`AttachmentService`] implementations.-pub struct AttachmentProvider<Dss, Sfs, Email, Chat, Chan> {- /// Resolves [`AttachmentReference::DssFile`] references.- pub dss_file: Dss,- /// Resolves [`AttachmentReference::SfsImage`] references.- pub sfs_image: Sfs,- /// Resolves [`AttachmentReference::EmailThread`] references.+/// Routes [`Entity`] references to per-type [`AttachmentService`] implementations.+pub struct AttachmentProvider<Doc, Email, Chat, Chan, Sf> {+ /// Resolves [`EntityType::Document`] references.+ pub document: Doc,+ /// Resolves [`EntityType::EmailThread`] references.pub email_thread: Email,- /// Resolves [`AttachmentReference::Chat`] references.+ /// Resolves [`EntityType::Chat`] references.pub chat: Chat,- /// Resolves [`AttachmentReference::Channel`] references.+ /// Resolves [`EntityType::Channel`] references.pub channel: Chan,+ /// Resolves [`EntityType::StaticFile`] references.+ pub static_file: Sf,}-impl<Dss, Sfs, Email, Chat, Chan> AttachmentProvider<Dss, Sfs, Email, Chat, Chan>+impl<Doc, Email, Chat, Chan, Sf> AttachmentService+ for AttachmentProvider<Doc, Email, Chat, Chan, Sf>where- Dss: AttachmentService,- Sfs: AttachmentService,+ Doc: AttachmentService,Email: AttachmentService,Chat: AttachmentService,Chan: AttachmentService,+ Sf: AttachmentService,{- /// Resolve a batch of references, routing each to the service for- /// its variant. Groups are dispatched concurrently.- pub async fn resolve(+ async fn resolve_attachments<'a>(&self,user_id: MacroUserIdStr<'_>,- references: NonEmpty<Vec<AttachmentReference>>,- ) -> Attachments {- let mut dss_ids = Vec::new();- let mut sfs_ids = Vec::new();- let mut email_ids = Vec::new();- let mut chat_ids = Vec::new();- let mut chan_ids = Vec::new();+ ids: NonEmpty<&[&'a Entity<'a>]>,+ ) -> Attachments<'a> {+ let mut doc = Vec::new();+ let mut email = Vec::new();+ let mut chat = Vec::new();+ let mut chan = Vec::new();+ let mut sf = Vec::new();- for r in references.into_inner() {- match r {- AttachmentReference::DssFile { id } => dss_ids.push(id),- AttachmentReference::SfsImage { url } => sfs_ids.push(url),- AttachmentReference::EmailThread { id } => email_ids.push(id),- AttachmentReference::Chat { id } => chat_ids.push(id),- AttachmentReference::Channel { id } => chan_ids.push(id),+ for &entity in ids.iter() {+ match entity.entity_type {+ EntityType::Document | EntityType::Project => doc.push(entity),+ EntityType::StaticFile => sf.push(entity),+ EntityType::EmailThread => email.push(entity),+ EntityType::Chat => chat.push(entity),+ EntityType::Channel => chan.push(entity),+ _ => {}}}let (a, b, c, d, e) = futures::join!(- dispatch(&self.dss_file, user_id.clone(), dss_ids),- dispatch(&self.sfs_image, user_id.clone(), sfs_ids),- dispatch(&self.email_thread, user_id.clone(), email_ids),- dispatch(&self.chat, user_id.clone(), chat_ids),- dispatch(&self.channel, user_id, chan_ids),+ dispatch(&self.document, user_id.clone(), &doc),+ dispatch(&self.email_thread, user_id.clone(), &email),+ dispatch(&self.chat, user_id.clone(), &chat),+ dispatch(&self.channel, user_id.clone(), &chan),+ dispatch(&self.static_file, user_id, &sf),);let mut results = Vec::with_capacity(a.len() + b.len() + c.len() + d.len() + e.len());@@ -68,20 +67,19 @@ whereresults.extend(d);results.extend(e);- Attachments::new(NonEmpty::new(results).expect("references was non-empty"))+ Attachments::new(NonEmpty::new(results).expect("entities was non-empty"))}}-async fn dispatch<S: AttachmentService>(+async fn dispatch<'a, S: AttachmentService>(service: &S,user_id: MacroUserIdStr<'_>,- ids: Vec<String>,-) -> Vec<Result<AttachmentContent, ResolutionError>> {- if ids.is_empty() {+ refs: &[&'a Entity<'a>],+) -> Vec<Result<AttachmentContent<'a>, ResolutionError>> {+ if refs.is_empty() {return Vec::new();}- let refs: Vec<&str> = ids.iter().map(|s| s.as_str()).collect();- let ne = NonEmpty::new(refs.as_slice()).expect("checked non-empty");+ let ne = NonEmpty::new(refs).expect("checked non-empty");service.resolve_attachments(user_id, ne).awaitdiff --git a/rust/cloud-storage/attachment/todo.md b/rust/cloud-storage/attachment/todo.mdnew file mode 100644index 0000000000..797a709399--- /dev/null+++ b/rust/cloud-storage/attachment/todo.md@@ -0,0 +1,11 @@+# do+- [x] remove debug println document::attachment+- [x] xml formatting wrong attachment::fmt+- [x] attachments aren't persistent+- [x] static images not working+- [x] kill snapshot node+- [] document::attachment is wrong. Needs to support projects++# punt+- [] kill scribe+- [] replace ChatAttachmentWithName with Entity + delete shimdiff --git a/rust/cloud-storage/chat/.sqlx/query-57fc603adf83fd7c07968425c98f9a57924573692cf0529ad021b6eef00ce99e.json b/rust/cloud-storage/chat/.sqlx/query-57fc603adf83fd7c07968425c98f9a57924573692cf0529ad021b6eef00ce99e.jsonnew file mode 100644index 0000000000..27b7d76a6f--- /dev/null+++ b/rust/cloud-storage/chat/.sqlx/query-57fc603adf83fd7c07968425c98f9a57924573692cf0529ad021b6eef00ce99e.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO \"ChatMessage\" (\"id\", \"chatId\", \"content\", \"role\", \"model\", \"createdAt\", \"updatedAt\")\n VALUES ($1, $2, $3, $4, $5, $6, $7)\n RETURNING id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Jsonb",+ "Text",+ "Text",+ "Timestamp",+ "Timestamp"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "57fc603adf83fd7c07968425c98f9a57924573692cf0529ad021b6eef00ce99e"+}diff --git a/rust/cloud-storage/chat/.sqlx/query-663a12ade5ccf4613703c0ad368772673560741961c20f5c401b59b5c5f6027d.json b/rust/cloud-storage/chat/.sqlx/query-663a12ade5ccf4613703c0ad368772673560741961c20f5c401b59b5c5f6027d.jsonnew file mode 100644index 0000000000..565892f3ba--- /dev/null+++ b/rust/cloud-storage/chat/.sqlx/query-663a12ade5ccf4613703c0ad368772673560741961c20f5c401b59b5c5f6027d.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM \"ChatMessage\"\n WHERE id = $1\n RETURNING id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "663a12ade5ccf4613703c0ad368772673560741961c20f5c401b59b5c5f6027d"+}diff --git a/rust/cloud-storage/chat/.sqlx/query-839330faa9e5b59992b4f681fcdc26eb2da189dedc9c076ca1bd306ee7d1a087.json b/rust/cloud-storage/chat/.sqlx/query-839330faa9e5b59992b4f681fcdc26eb2da189dedc9c076ca1bd306ee7d1a087.jsonnew file mode 100644index 0000000000..6cf9eec3b6--- /dev/null+++ b/rust/cloud-storage/chat/.sqlx/query-839330faa9e5b59992b4f681fcdc26eb2da189dedc9c076ca1bd306ee7d1a087.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT \"content\"\n FROM \"ResolvedMessageContent\"\n WHERE \"messageId\" = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "content",+ "type_info": "Jsonb"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "839330faa9e5b59992b4f681fcdc26eb2da189dedc9c076ca1bd306ee7d1a087"+}diff --git a/rust/cloud-storage/chat/.sqlx/query-976e4f3de2f4fa1320c674fa681d816ae9087070dc8bc88ed1620ea500f00758.json b/rust/cloud-storage/chat/.sqlx/query-976e4f3de2f4fa1320c674fa681d816ae9087070dc8bc88ed1620ea500f00758.jsonnew file mode 100644index 0000000000..2e92943742--- /dev/null+++ b/rust/cloud-storage/chat/.sqlx/query-976e4f3de2f4fa1320c674fa681d816ae9087070dc8bc88ed1620ea500f00758.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO \"ResolvedMessageContent\" (\"messageId\", \"content\")\n VALUES ($1, $2)\n ON CONFLICT (\"messageId\") DO UPDATE SET \"content\" = $2\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Jsonb"+ ]+ },+ "nullable": []+ },+ "hash": "976e4f3de2f4fa1320c674fa681d816ae9087070dc8bc88ed1620ea500f00758"+}diff --git a/rust/cloud-storage/chat/.sqlx/query-c9f9b00be9d446b7d45cad5073e9d422689a29c2da56d6888ca37877bef372f0.json b/rust/cloud-storage/chat/.sqlx/query-c9f9b00be9d446b7d45cad5073e9d422689a29c2da56d6888ca37877bef372f0.jsonnew file mode 100644index 0000000000..1537dcb194--- /dev/null+++ b/rust/cloud-storage/chat/.sqlx/query-c9f9b00be9d446b7d45cad5073e9d422689a29c2da56d6888ca37877bef372f0.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO \"ChatAttachment\" (\"attachmentType\", \"attachmentId\", \"chatId\", \"messageId\")\n SELECT * FROM UNNEST($1::TEXT[], $2::TEXT[], $3::TEXT[], $4::TEXT[])\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "TextArray",+ "TextArray",+ "TextArray",+ "TextArray"+ ]+ },+ "nullable": []+ },+ "hash": "c9f9b00be9d446b7d45cad5073e9d422689a29c2da56d6888ca37877bef372f0"+}diff --git a/rust/cloud-storage/chat/Cargo.toml b/rust/cloud-storage/chat/Cargo.tomlindex a6c539add3..aa010d0a4f 100644--- a/rust/cloud-storage/chat/Cargo.toml+++ b/rust/cloud-storage/chat/Cargo.toml@@ -8,7 +8,6 @@ version = "0.1.0"default = ["ai_tools", "inbound", "outbound", "ports"]ai_tools = ["dep:async-trait", "dep:schemars", "inbound", "ports"]attachment = [- "dep:attachment","dep:futures","inbound",]@@ -27,6 +26,7 @@ ports = []ai = { path = "../ai" }ai_toolset = { path = "../ai_toolset" }anyhow = { workspace = true }+attachment = { path = "../attachment" }chrono = { workspace = true }entity_access = { path = "../entity_access", default-features = false }entity_access_db_utils = { path = "../entity_access_db_utils", optional = true }@@ -48,7 +48,6 @@ unicode-segmentation = { workspace = true }uuid = { workspace = true }# Attachment (attachment provider)-attachment = { path = "../attachment", optional = true }futures = { workspace = true, optional = true }# AI tools (toolset adapter)diff --git a/rust/cloud-storage/chat/PLAN.md b/rust/cloud-storage/chat/PLAN.mdnew file mode 100644index 0000000000..a6277e98b1--- /dev/null+++ b/rust/cloud-storage/chat/PLAN.md@@ -0,0 +1,213 @@+# User-Level Resolved Attachments — Integration Plan++## Problem++- All explicit attachments are "system level" — they're fetched once at request time and injected into the system prompt or as images on the last user message. They die on detach, AI can't see changes on re-send.+- Attachment fetching uses the old scribe crate which should be killed in favor of the hex crates.+- AI can't see images in attached markdown docs or PDFs.++## What's Done++1. **`attachment` crate** — `Attachments`, `AttachmentContent`, `AttachmentPart`, `TextOrImage`, `Attachable` trait, `AttachmentService` trait, XML formatting.+2. **`ai` crate** — `ChatMessage.attachments: Option<Attachments>`, builders updated, OpenAI provider formats attachments via `Attachable::into_formatted_parts().compact()` into text+image content parts on the user message.++## What's Broken Right Now++`fetchium()` in DCS returns `Vec<ai::types::Attachment>` — a type that no longer exists. `ai_request.rs` calls `.attachments(attachments)` on `RequestBuilder` which now expects `attachment::Attachments`. DCS won't compile against the updated `ai` crate.++---++## Phase 1: DB Migration++Add a `ResolvedUserMessage` table that stores the AI-facing representation of user messages.++```sql+CREATE TABLE "ResolvedUserMessage" (+ "id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ "messageId" TEXT NOT NULL REFERENCES "ChatMessage"("id") ON DELETE CASCADE,+ "content" JSONB NOT NULL, -- Vec<UserMessageContent> serialized+ "createdAt" TIMESTAMPTZ NOT NULL DEFAULT NOW(),+ UNIQUE("messageId")+);+```++The `content` column stores resolved parts: `[{type: "text", ...}, {type: "image", ...}, {type: "attachment", name: "...", parts: [...]}]`.++---++## Phase 2: Domain Types in Chat Crate++Add resolved message content types to `chat/src/domain/models.rs`:++```rust+enum ImageContent {+ StaticUrl(String),+ Base64(String),+}++enum UserMessageContent {+ Text(String),+ Image(ImageContent),+ Attachment { name: String, parts: Vec<UserMessageContent> },+}++struct ResolvedUserMessage {+ message_id: String,+ content: Vec<UserMessageContent>,+}+```++These are the chat crate's own domain types. The chat crate defines `From<ResolvedUserMessage>` → `ai::types::ChatMessage` to bridge into the AI crate.++The conversion:+- `UserMessageContent::Text(s)` → text content part+- `UserMessageContent::Image(img)` → image content part+- `UserMessageContent::Attachment { name, parts }` → formatted as `<attachment><title>name</title><content>...</content></attachment>` text++---++## Phase 3: Attachment Resolution Port++Add a new port to the chat crate (or a standalone trait):++```rust+trait AttachmentResolver: Send + Sync + 'static {+ fn resolve(+ &self,+ user_id: MacroUserIdStr<'_>,+ message_text: &str,+ attachments: Vec<AttachmentReference>,+ ) -> impl Future<Output = Result<Vec<UserMessageContent>>> + Send;+}+```++This replaces `fetchium()`. The implementation:++1. For each attachment reference, dispatch by type (document, image, channel, email, project)+2. **Documents**: fetch content via the existing `AttachmentService` infra (the hex-pattern services built for `ReadTool`)+3. **Markdown documents**: call the lexical service's new `parseMdWithImages` endpoint → ordered `[text, image, text, ...]` parts+4. **Images in markdown**: fetch from SFS, downscale via `ImageData::try_from_bytes()`, encode as base64+5. **Standalone images**: same as above+6. **Channels/email/projects**: existing text-only resolution (same logic as current `fetchium`)+7. Return `Vec<UserMessageContent>` preserving part order++---++## Phase 4: Lexical Service — `parseMdWithImages`++New endpoint in the lexical (JS) service:++```typescript+type MdPart =+ | { type: "text"; content: string }+ | { type: "image"; id: string }+ | { type: "static_image"; url: string };++// POST /parse-md-with-images+function parseMdWithImages(document_id: string): MdPart[];+```++Parses the lexical document tree, extracts inline image nodes (with their document IDs or static URLs), returns an ordered list of text and image parts. Adjacent text nodes should be merged.++---++## Phase 5: Resolved Message Storage++Add to `ChatRepo`:++```rust+fn store_resolved_message(+ &self,+ message_id: &str,+ content: &[UserMessageContent],+) -> impl Future<Output = Result<(), ChatErr>> + Send;++fn get_resolved_message(+ &self,+ message_id: &str,+) -> impl Future<Output = Result<Option<Vec<UserMessageContent>>, ChatErr>> + Send;+```++Insert resolved content after attachment resolution completes. The resolved message is the source of truth for the AI provider — it contains all the text and base64 images inline.++---++## Phase 6: Wire Into DCS Message Send Flow++Update `send_chat_message()` in DCS:++```+1. Store user message (unchanged — raw text + attachment refs)+2. Resolve attachments → Vec<UserMessageContent>+3. Store resolved message in new table+4. Build AI request from resolved message (not from raw attachments)+5. Stream AI response (unchanged)+```++Replace `build_chat_completion_request()`:+- Remove `fetchium()` call+- Build the user message from the resolved content instead+- The resolved content already has text + images inline, so no system-prompt injection needed++---++## Phase 7: Re-Resolve on Message Edit++When a user edits a message, re-run attachment resolution and update the resolved message row. The cascade delete on the FK handles the case where the raw message is deleted.++---++## Phase 8: Kill `fetchium` + Old Types++Once the new flow is wired:++1. Delete `service/attachment/fetch.rs` (`fetchium`)+2. Remove `ai::traits::TextAttachment` re-export (update `ai_tools` rewrite tool)+3. Remove `PromptAttachments` if system prompt no longer carries attachment text+4. Remove scribe-based attachment fetching from DCS++---++## Phase 9: Frontend Changes++- Attachments from DND, upload, and `@` mention all append to an attachment list on the message+- DND/upload attachments show in the visible attachment bar above input+- `@` mentions are in the message text but also in the attachment list+- Frontend sends `attachments: [{type: "document", id: "..."}, ...]` alongside message content+- No more lexical service mention parsing on the backend — the frontend already knows what was mentioned+- Makes `snapshotNode` obsolete++---++## Phase 10: Backfill Script++For existing user messages that have no resolved counterpart:++```+for each user message without a ResolvedUserMessage row:+ insert ResolvedUserMessage with content = [{type: "text", content: message_text}]+```++This is lossy (old attachments were system-level and not preserved per-message), but correct — old messages get their text content as the resolved form. Run per-env: local, dev, prod.++---++## What This Makes Obsolete++- `fetchium()` / `service/attachment/fetch.rs`+- `ai::traits::TextAttachment` re-export+- `PromptAttachments` / system prompt attachment injection+- `snapshotNode` in the frontend+- The scribe-based attachment fetching pattern in DCS++## Implementation Order++```+Phase 2 (domain types) ─┐+Phase 1 (migration) ─┼─→ Phase 5 (storage) ─┐+Phase 4 (lexical parseMdImages) ─┤ ├─→ Phase 6 (wire DCS) ─→ Phase 7 (re-resolve)+Phase 3 (resolution port) ─┘ │ → Phase 8 (cleanup)+ │+Phase 10 (backfill) ←─────────────────────────┘+Phase 9 (frontend) ← can start after Phase 6, parallel with 7-8+```diff --git a/rust/cloud-storage/chat/src/domain/models.rs b/rust/cloud-storage/chat/src/domain/models/chat.rssimilarity index 52%rename from rust/cloud-storage/chat/src/domain/models.rsrename to rust/cloud-storage/chat/src/domain/models/chat.rsindex 6721fea82a..90f0abd4e9 100644--- a/rust/cloud-storage/chat/src/domain/models.rs+++ b/rust/cloud-storage/chat/src/domain/models/chat.rs@@ -1,52 +1,10 @@-//! Types and errors used by the chat domain ports.--use ai::types::{ChatMessageContent, Model};-use entity_access::domain::models::AccessError;+use ai::types::Model;use model::chat::{ChatAttachmentWithName, ChatMessageWithAttachments};use models_permissions::share_permission::access_level::AccessLevel;use serde::{Deserialize, Serialize};-use thiserror::Error;use utoipa::ToSchema;-/// Domain error type for chat operations.-#[derive(Debug, Error)]-pub enum ChatErr {- /// The requested chat was not found.- #[error("chat not found")]- NotFound,- /// An unexpected error occurred.- #[error(transparent)]- Unknown(#[from] anyhow::Error),- /// Bad request- #[error("bad request: {0}")]- BadRequest(String),- /// Access denied.- #[error(transparent)]- Access(#[from] AccessError),-}--#[cfg(feature = "inbound")]-impl axum::response::IntoResponse for ChatErr {- fn into_response(self) -> axum::response::Response {- use axum::http::StatusCode;-- let (status, msg) = match &self {- ChatErr::NotFound => (StatusCode::NOT_FOUND, "Not found"),- ChatErr::BadRequest(_) => (StatusCode::BAD_REQUEST, "Bad request"),- ChatErr::Access(- AccessError::Unauthorized | AccessError::UnauthorizedWithMessage(_),- ) => (StatusCode::FORBIDDEN, "Forbidden"),- ChatErr::Access(AccessError::NotFound(_)) => (StatusCode::NOT_FOUND, "Not found"),- ChatErr::Access(AccessError::BadRequest(_)) => (StatusCode::BAD_REQUEST, "Bad request"),- ChatErr::Unknown(_) | ChatErr::Access(_) => {- tracing::error!(error=?self, "chat handler error");- (StatusCode::INTERNAL_SERVER_ERROR, "Internal server error")- }- };-- (status, msg.to_string()).into_response()- }-}+use super::WebCitation;/// Arguments for creating a new chat.#[derive(Debug)]@@ -78,24 +36,6 @@ pub struct PatchChatArgs {Option<models_permissions::share_permission::UpdateSharePermissionRequestV2>,}-/// A web citation associated with a chat message.-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ToSchema, Default)]-pub struct WebCitation {- /// The URL of the citation.- pub url: String,- /// The title of the cited page.- pub title: String,- /// A description of the cited page.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub description: Option<String>,- /// The URL of the page's image.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub image_url: Option<String>,- /// The URL of the page's favicon.- #[serde(default, skip_serializing_if = "Option::is_none")]- pub favicon_url: Option<String>,-}-/// Wrapper response for get_chat, matching the DCS API response shape.#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, ToSchema)]#[serde(rename_all = "camelCase")]@@ -138,12 +78,3 @@ pub struct ChatResponse {/// Whether the chat is persistent or not.pub is_persistent: bool,}--/// Arguments for patching a chat message's content.-#[derive(Debug)]-pub struct PatchChatMessageArgs {- /// The message ID to patch.- pub message_id: String,- /// The new content for the message.- pub content: ChatMessageContent,-}diff --git a/rust/cloud-storage/chat/src/domain/models/error.rs b/rust/cloud-storage/chat/src/domain/models/error.rsnew file mode 100644index 0000000000..270f48aa2d--- /dev/null+++ b/rust/cloud-storage/chat/src/domain/models/error.rs@@ -0,0 +1,45 @@+use entity_access::domain::models::AccessError;+use thiserror::Error;++/// A `Result` alias where the error type is [`ChatErr`].+pub type Result<T> = std::result::Result<T, ChatErr>;++/// Domain error type for chat operations.+#[derive(Debug, Error)]+pub enum ChatErr {+ /// The requested chat was not found.+ #[error("chat not found")]+ NotFound,+ /// An unexpected error occurred.+ #[error(transparent)]+ Unknown(#[from] anyhow::Error),+ /// Bad request+ #[error("bad request: {0}")]+ BadRequest(String),+ /// Access denied.+ #[error(transparent)]+ Access(#[from] AccessError),+}++#[cfg(feature = "inbound")]+impl axum::response::IntoResponse for ChatErr {+ fn into_response(self) -> axum::response::Response {+ use axum::http::StatusCode;++ let (status, msg) = match &self {+ ChatErr::NotFound => (StatusCode::NOT_FOUND, "Not found"),+ ChatErr::BadRequest(_) => (StatusCode::BAD_REQUEST, "Bad request"),+ ChatErr::Access(+ AccessError::Unauthorized | AccessError::UnauthorizedWithMessage(_),+ ) => (StatusCode::FORBIDDEN, "Forbidden"),+ ChatErr::Access(AccessError::NotFound(_)) => (StatusCode::NOT_FOUND, "Not found"),+ ChatErr::Access(AccessError::BadRequest(_)) => (StatusCode::BAD_REQUEST, "Bad request"),+ ChatErr::Unknown(_) | ChatErr::Access(_) => {+ tracing::error!(error=?self, "chat handler error");+ (StatusCode::INTERNAL_SERVER_ERROR, "Internal server error")+ }+ };++ (status, msg.to_string()).into_response()+ }+}diff --git a/rust/cloud-storage/chat/src/domain/models/message.rs b/rust/cloud-storage/chat/src/domain/models/message.rsnew file mode 100644index 0000000000..6cfb71d0f1--- /dev/null+++ b/rust/cloud-storage/chat/src/domain/models/message.rs@@ -0,0 +1,40 @@+use ai::types::ChatMessageContent;+use attachment::FormattedParts;+use serde::{Deserialize, Serialize};+use utoipa::ToSchema;++/// Arguments for patching a chat message's content.+#[derive(Debug)]+pub struct PatchChatMessageArgs {+ /// The message ID to patch.+ pub message_id: String,+ /// The new content for the message.+ pub content: ChatMessageContent,+}++/// A web citation associated with a chat message.+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq, ToSchema, Default)]+pub struct WebCitation {+ /// The URL of the citation.+ pub url: String,+ /// The title of the cited page.+ pub title: String,+ /// A description of the cited page.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub description: Option<String>,+ /// The URL of the page's image.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub image_url: Option<String>,+ /// The URL of the page's favicon.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub favicon_url: Option<String>,+}++/// The AI-facing representation of a user message, stored alongside the raw message.+#[derive(Debug)]+pub struct ResolvedMessageContent {+ /// The ID of the raw `ChatMessage` this resolves.+ pub message_id: String,+ /// The resolved attachment content, if the message had attachments.+ pub parts: Option<FormattedParts>,+}diff --git a/rust/cloud-storage/chat/src/domain/models/mod.rs b/rust/cloud-storage/chat/src/domain/models/mod.rsnew file mode 100644index 0000000000..a403def502--- /dev/null+++ b/rust/cloud-storage/chat/src/domain/models/mod.rs@@ -0,0 +1,9 @@+//! Types and errors used by the chat domain ports.++mod chat;+mod error;+mod message;++pub use chat::*;+pub use error::*;+pub use message::*;diff --git a/rust/cloud-storage/chat/src/domain/ports.rs b/rust/cloud-storage/chat/src/domain/ports/chat.rssimilarity index 72%rename from rust/cloud-storage/chat/src/domain/ports.rsrename to rust/cloud-storage/chat/src/domain/ports/chat.rsindex 43f1134b12..db7789850b 100644--- a/rust/cloud-storage/chat/src/domain/ports.rs+++ b/rust/cloud-storage/chat/src/domain/ports/chat.rs@@ -1,9 +1,10 @@use crate::domain::models::{- ChatErr, ChatResponse, CopyChatArgs, CreateChatArgs, GetChatResponse, PatchChatArgs,- PatchChatMessageArgs,+ ChatResponse, CopyChatArgs, CreateChatArgs, GetChatResponse, PatchChatArgs,+ PatchChatMessageArgs, Result,};use ai::types::ChatMessageContent;use ai_toolset::tool_object::UserToolResponse;+use attachment::FormattedParts;use entity_access::domain::models::{EditAccessLevel, EntityAccessReceipt, OwnerAccessLevel, ViewAccessLevel,};@@ -19,26 +20,24 @@ pub trait ChatRepo: Send + Sync + 'static {&self,user_id: MacroUserIdStr<'static>,args: CreateChatArgs,- ) -> impl std::future::Future<Output = Result<String, ChatErr>> + Send;+ ) -> impl std::future::Future<Output = Result<String>> + Send;/// Get the full chat response (metadata, messages, web citations).fn get_chat(&self,chat_id: &str,- ) -> impl std::future::Future<Output = Result<ChatResponse, ChatErr>> + Send;+ ) -> impl std::future::Future<Output = Result<ChatResponse>> + Send;/// Get a chat metadata by its ID.- fn get_metadata(- &self,- chat_id: &str,- ) -> impl std::future::Future<Output = Result<Chat, ChatErr>> + Send;+ fn get_metadata(&self, chat_id: &str)+ -> impl std::future::Future<Output = Result<Chat>> + Send;/// Get the requesting user's access level on a chat.fn get_access_level(&self,user_id: MacroUserIdStr<'_>,chat_id: &str,- ) -> impl std::future::Future<Output = Result<AccessLevel, ChatErr>> + Send;+ ) -> impl std::future::Future<Output = Result<AccessLevel>> + Send;/// Copy a chat (create a new chat and duplicate its messages), returning the new chat ID.fn copy_chat(@@ -46,32 +45,29 @@ pub trait ChatRepo: Send + Sync + 'static {user_id: MacroUserIdStr<'static>,source_chat_id: &str,args: CopyChatArgs,- ) -> impl std::future::Future<Output = Result<String, ChatErr>> + Send;+ ) -> impl std::future::Future<Output = Result<String>> + Send;/// Revert a soft-deleted chat (clears `deleted_at`, restores history).fn revert_delete(&self,chat_id: &str,project_id: Option<&str>,- ) -> impl std::future::Future<Output = Result<(), ChatErr>> + Send;+ ) -> impl std::future::Future<Output = Result<()>> + Send;/// Get the share permissions for a chat.fn get_permissions(&self,chat_id: &str,- ) -> impl std::future::Future<Output = Result<SharePermissionV2, ChatErr>> + Send;+ ) -> impl std::future::Future<Output = Result<SharePermissionV2>> + Send;/// Soft-delete a chat (sets `deleted_at`, removes pins and history).- fn delete(- &self,- chat_id: &str,- ) -> impl std::future::Future<Output = Result<(), ChatErr>> + Send;+ fn delete(&self, chat_id: &str) -> impl std::future::Future<Output = Result<()>> + Send;/// Permanently delete a chat and all associated data.fn permanently_delete(&self,chat_id: &str,- ) -> impl std::future::Future<Output = Result<(), ChatErr>> + Send;+ ) -> impl std::future::Future<Output = Result<()>> + Send;/// Patch a chat's metadata (name, project, share permissions).fn patch(@@ -79,27 +75,27 @@ pub trait ChatRepo: Send + Sync + 'static {user_id: MacroUserIdStr<'static>,chat_id: &str,args: PatchChatArgs,- ) -> impl std::future::Future<Output = Result<(), ChatErr>> + Send;+ ) -> impl std::future::Future<Output = Result<()>> + Send;/// Update a project's `updatedAt` timestamp.fn update_project_modified(&self,project_id: &str,- ) -> impl std::future::Future<Output = Result<(), ChatErr>> + Send;+ ) -> impl std::future::Future<Output = Result<()>> + Send;/// Patch a message's content.fn patch_message(&self,chat_id: &str,args: PatchChatMessageArgs,- ) -> impl std::future::Future<Output = Result<(), ChatErr>> + Send;+ ) -> impl std::future::Future<Output = Result<()>> + Send;/// Get the content of a single message by IDfn get_message_content(&self,chat_id: &str,message_id: &str,- ) -> impl std::future::Future<Output = Result<ChatMessageContent, ChatErr>> + Send;+ ) -> impl std::future::Future<Output = Result<ChatMessageContent>> + Send;/// Update the content of a specific message.fn update_message_content(@@ -107,7 +103,20 @@ pub trait ChatRepo: Send + Sync + 'static {chat_id: &str,message_id: &str,content: &ChatMessageContent,- ) -> impl std::future::Future<Output = Result<(), ChatErr>> + Send;+ ) -> impl std::future::Future<Output = Result<()>> + Send;++ /// Store the resolved (AI-facing) representation of a user message.+ fn store_resolved_message(+ &self,+ message_id: &str,+ parts: FormattedParts,+ ) -> impl std::future::Future<Output = Result<()>> + Send;++ /// Get the resolved representation of a user message, if it exists.+ fn get_resolved_message(+ &self,+ message_id: &str,+ ) -> impl std::future::Future<Output = Result<FormattedParts>> + Send;}/// Service trait for chat business logic.@@ -120,50 +129,50 @@ pub trait ChatService: Send + Sync + 'static {&self,user_id: MacroUserIdStr<'static>,args: CreateChatArgs,- ) -> impl std::future::Future<Output = Result<String, ChatErr>> + Send;+ ) -> impl std::future::Future<Output = Result<String>> + Send;/// Get a chat with messages, web citations, and the user's access level.fn get_chat(&self,entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,- ) -> impl std::future::Future<Output = Result<GetChatResponse, ChatErr>> + Send;+ ) -> impl std::future::Future<Output = Result<GetChatResponse>> + Send;/// Copy a chat and its messages, returning the new chat ID.fn copy_chat(&self,entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,- ) -> impl std::future::Future<Output = Result<String, ChatErr>> + Send;+ ) -> impl std::future::Future<Output = Result<String>> + Send;/// Soft-delete a chat.fn delete(&self,entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,- ) -> impl std::future::Future<Output = Result<(), ChatErr>> + Send;+ ) -> impl std::future::Future<Output = Result<()>> + Send;/// Permanently delete a chat and all associated data.fn permanently_delete(&self,entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,- ) -> impl std::future::Future<Output = Result<(), ChatErr>> + Send;+ ) -> impl std::future::Future<Output = Result<()>> + Send;/// Patch a chat's metadata (name, project, share permissions).fn patch(&self,entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,args: PatchChatArgs,- ) -> impl std::future::Future<Output = Result<(), ChatErr>> + Send;+ ) -> impl std::future::Future<Output = Result<()>> + Send;/// Revert a soft-deleted chat.fn revert_delete(&self,entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,- ) -> impl std::future::Future<Output = Result<(), ChatErr>> + Send;+ ) -> impl std::future::Future<Output = Result<()>> + Send;/// Get the share permissions for a chat.fn get_permissions(&self,entity_access_receipt: EntityAccessReceipt<EditAccessLevel>,- ) -> impl std::future::Future<Output = Result<SharePermissionV2, ChatErr>> + Send;+ ) -> impl std::future::Future<Output = Result<SharePermissionV2>> + Send;/// Update a tool call's arguments after validation.fn update_tool_call(@@ -172,7 +181,7 @@ pub trait ChatService: Send + Sync + 'static {message_id: &str,tool_call_id: &str,new_args: serde_json::Value,- ) -> impl std::future::Future<Output = Result<(), ChatErr>> + Send;+ ) -> impl std::future::Future<Output = Result<()>> + Send;/// Update a tool response.fn update_tool_response(@@ -181,7 +190,7 @@ pub trait ChatService: Send + Sync + 'static {message_id: &str,tool_call_id: &str,response: UserToolResponse<serde_json::Value>,- ) -> impl std::future::Future<Output = Result<(), ChatErr>> + Send;+ ) -> impl std::future::Future<Output = Result<()>> + Send;/// Execute a pending tool call. Optionally update its arguments first.fn call_tool(@@ -190,7 +199,7 @@ pub trait ChatService: Send + Sync + 'static {message_id: &str,tool_call_id: &str,args: Option<serde_json::Value>,- ) -> impl std::future::Future<Output = Result<serde_json::Value, ChatErr>> + Send;+ ) -> impl std::future::Future<Output = Result<serde_json::Value>> + Send;/// Reject a pending tool call.fn reject_tool_call(@@ -198,5 +207,5 @@ pub trait ChatService: Send + Sync + 'static {entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,message_id: &str,tool_call_id: &str,- ) -> impl std::future::Future<Output = Result<(), ChatErr>> + Send;+ ) -> impl std::future::Future<Output = Result<()>> + Send;}diff --git a/rust/cloud-storage/chat/src/domain/ports/message.rs b/rust/cloud-storage/chat/src/domain/ports/message.rsnew file mode 100644index 0000000000..9f1ecad364--- /dev/null+++ b/rust/cloud-storage/chat/src/domain/ports/message.rs@@ -0,0 +1,119 @@+use ai::types::ChatMessageContent;+use attachment::FormattedParts;+use macro_user_id::user_id::MacroUserIdStr;+use model::chat::{ChatMessageWithAttachments, NewChatMessage};+use std::future::Future;++use crate::domain::models::{PatchChatMessageArgs, ResolvedMessageContent, Result, WebCitation};++/// Repository trait for low-level message data access.+pub trait MessageRepo: Send + Sync + 'static {+ /// Create a new message in a chat, returning the message ID.+ fn create(+ &self,+ chat_id: &str,+ message: NewChatMessage,+ ) -> impl Future<Output = Result<String>> + Send;++ /// Delete a message by ID.+ fn delete(&self, message_id: &str) -> impl Future<Output = Result<()>> + Send;++ /// Get all messages for a chat, with attachment metadata.+ fn get_messages(+ &self,+ chat_id: &str,+ ) -> impl Future<Output = Result<Vec<ChatMessageWithAttachments>>> + Send;++ /// Get the content of a single message by ID, scoped to a chat.+ fn get_message_content(+ &self,+ chat_id: &str,+ message_id: &str,+ ) -> impl Future<Output = Result<ChatMessageContent>> + Send;++ /// Update the content of a message.+ fn update_message_content(+ &self,+ chat_id: &str,+ message_id: &str,+ content: &ChatMessageContent,+ ) -> impl std::future::Future<Output = Result<()>> + Send;++ /// Patch a message's content.+ fn patch_message(+ &self,+ chat_id: &str,+ args: PatchChatMessageArgs,+ ) -> impl Future<Output = Result<()>> + Send;++ /// Copy all messages from one chat to another.+ fn copy_messages(+ &self,+ source_chat_id: &str,+ dest_chat_id: &str,+ ) -> impl Future<Output = Result<()>> + Send;++ /// Get web citations for a chat, grouped by message ID.+ fn get_web_citations(+ &self,+ chat_id: &str,+ ) -> impl Future<Output = Result<Vec<(String, Vec<WebCitation>)>>> + Send;++ /// Store the resolved (AI-facing) representation of a user message.+ fn store_resolved_message(+ &self,+ message_id: &str,+ parts: FormattedParts,+ ) -> impl Future<Output = Result<()>> + Send;++ /// Get the resolved representation of a user message, if it exists.+ fn get_resolved_message(+ &self,+ message_id: &str,+ ) -> impl Future<Output = Result<FormattedParts>> + Send;+}++/// Service trait for message business logic.+///+/// Handlers depend on this trait rather than [`MessageRepo`] directly.+/// Access control is the caller's responsibility.+pub trait MessageService: Send + Sync + 'static {+ /// Create a message, resolve its attachments, store both, and return the result.+ fn create(+ &self,+ user_id: &MacroUserIdStr<'_>,+ chat_id: &str,+ message: NewChatMessage,+ ) -> impl Future<Output = Result<ResolvedMessageContent>> + Send;++ /// Store a message without resolving attachments.+ fn store(+ &self,+ chat_id: &str,+ message: NewChatMessage,+ ) -> impl Future<Output = Result<String>> + Send;++ /// Update the content of a message.+ fn update(+ &self,+ user_id: &MacroUserIdStr<'_>,+ chat_id: &str,+ message_id: &str,+ content: &ChatMessageContent,+ ) -> impl Future<Output = Result<()>> + Send;++ /// Delete a message by ID.+ fn delete(&self, message_id: &str) -> impl Future<Output = Result<()>> + Send;++ /// Get the resolved (AI-facing) representation of a user message.+ fn get_resolved_message(+ &self,+ message_id: &str,+ ) -> impl Future<Output = Result<ResolvedMessageContent>> + Send;++ /// Get all resolved messages for a chat, in order.+ fn get_resolved_message_chain(+ &self,+ chat_id: &str,+ ) -> impl Future<Output = Result<Vec<ResolvedMessageContent>>> + Send;+}diff --git a/rust/cloud-storage/chat/src/domain/ports/mod.rs b/rust/cloud-storage/chat/src/domain/ports/mod.rsnew file mode 100644index 0000000000..ffd6d7b73f--- /dev/null+++ b/rust/cloud-storage/chat/src/domain/ports/mod.rs@@ -0,0 +1,5 @@+mod chat;+mod message;++pub use chat::*;+pub use message::*;diff --git a/rust/cloud-storage/chat/src/domain/service.rs b/rust/cloud-storage/chat/src/domain/service/chat.rssimilarity index 97%rename from rust/cloud-storage/chat/src/domain/service.rsrename to rust/cloud-storage/chat/src/domain/service/chat.rsindex 35bcbafae2..48a4c6c847 100644--- a/rust/cloud-storage/chat/src/domain/service.rs+++ b/rust/cloud-storage/chat/src/domain/service/chat.rs@@ -1,7 +1,7 @@//! Default [`ChatService`] implementation backed by a [`ChatRepo`].use crate::domain::{- models::{ChatErr, CopyChatArgs, CreateChatArgs, GetChatResponse, PatchChatArgs},+ models::{ChatErr, CopyChatArgs, CreateChatArgs, GetChatResponse, PatchChatArgs, Result},ports::{ChatRepo, ChatService},};use ai::types::{AssistantMessagePart, ChatMessageContent};@@ -59,7 +59,7 @@ where&self,user_id: MacroUserIdStr<'static>,args: CreateChatArgs,- ) -> Result<String, ChatErr> {+ ) -> Result<String> {if args.name.graphemes(true).count() > 100 {return Err(ChatErr::BadRequest("name too long".to_string()));}@@ -91,7 +91,7 @@ whereasync fn get_chat(&self,entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,- ) -> Result<GetChatResponse, ChatErr> {+ ) -> Result<GetChatResponse> {let user_id = entity_access_receipt.get_authenticated_user()?;let chat_id = &entity_access_receipt.entity().entity_id;@@ -110,7 +110,7 @@ whereasync fn copy_chat(&self,entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,- ) -> Result<String, ChatErr> {+ ) -> Result<String> {let user_id = entity_access_receipt.get_authenticated_user()?;let chat_id = &entity_access_receipt.entity().entity_id;@@ -131,7 +131,7 @@ whereasync fn delete(&self,entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,- ) -> Result<(), ChatErr> {+ ) -> Result<()> {let chat_id = &entity_access_receipt.entity().entity_id;let project_id = self.repo@@ -165,7 +165,7 @@ whereasync fn permanently_delete(&self,entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,- ) -> Result<(), ChatErr> {+ ) -> Result<()> {let chat_id = &entity_access_receipt.entity().entity_id;let project_id = self.repo@@ -200,7 +200,7 @@ where&self,entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,args: PatchChatArgs,- ) -> Result<(), ChatErr> {+ ) -> Result<()> {if let Some(name) = args.name.as_ref()&& name.graphemes(true).count() > 100{@@ -265,7 +265,7 @@ whereasync fn revert_delete(&self,entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,- ) -> Result<(), ChatErr> {+ ) -> Result<()> {let chat_id = &entity_access_receipt.entity().entity_id;let chat = self.repo.get_metadata(chat_id).await?;self.repo@@ -277,7 +277,7 @@ whereasync fn get_permissions(&self,entity_access_receipt: EntityAccessReceipt<EditAccessLevel>,- ) -> Result<SharePermissionV2, ChatErr> {+ ) -> Result<SharePermissionV2> {let chat_id = &entity_access_receipt.entity().entity_id;self.repo.get_permissions(chat_id).await}@@ -289,7 +289,7 @@ wheremessage_id: &str,tool_call_id: &str,new_args: serde_json::Value,- ) -> Result<(), ChatErr> {+ ) -> Result<()> {let chat_id = &entity_access_receipt.entity().entity_id;let mut parts = self@@ -319,7 +319,7 @@ wheremessage_id: &str,tool_call_id: &str,response: UserToolResponse<serde_json::Value>,- ) -> Result<(), ChatErr> {+ ) -> Result<()> {let chat_id = &entity_access_receipt.entity().entity_id;let mut parts = self.get_tool_call_parts(chat_id, message_id, tool_call_id)@@ -341,7 +341,7 @@ wheremessage_id: &str,tool_call_id: &str,args: Option<serde_json::Value>,- ) -> Result<serde_json::Value, ChatErr> {+ ) -> Result<serde_json::Value> {let user_id = entity_access_receipt.get_authenticated_user()?.to_owned();let chat_id = entity_access_receipt.entity().entity_id.clone();@@ -404,7 +404,7 @@ whereentity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,message_id: &str,tool_call_id: &str,- ) -> Result<(), ChatErr> {+ ) -> Result<()> {let rejected_json =serde_json::to_value(UserToolResponse::Rejected::<()>).map_err(anyhow::Error::from)?;@@ -434,7 +434,7 @@ wherechat_id: &str,message_id: &str,tool_call_id: &str,- ) -> Result<Vec<AssistantMessagePart>, ChatErr> {+ ) -> Result<Vec<AssistantMessagePart>> {let content = self.repo.get_message_content(chat_id, message_id).await?;match content {ChatMessageContent::AssistantMessageParts(parts) => {diff --git a/rust/cloud-storage/chat/src/domain/service/message.rs b/rust/cloud-storage/chat/src/domain/service/message.rsnew file mode 100644index 0000000000..f955560d16--- /dev/null+++ b/rust/cloud-storage/chat/src/domain/service/message.rs@@ -0,0 +1,169 @@+//! Default [`MessageService`] implementation.++use ai::types::ChatMessageContent;+use attachment::{Attachable, AttachmentService, FormattedParts};+use macro_user_id::user_id::MacroUserIdStr;+use model::chat::{AttachmentType, NewChatMessage};+use model_entity::{Entity, EntityType};+use non_empty::NonEmpty;++use crate::domain::models::{ChatErr, ResolvedMessageContent, Result};+use crate::domain::ports::{MessageRepo, MessageService};++/// Concrete [`MessageService`] backed by a [`MessageRepo`] and [`AttachmentService`].+pub struct MessageServiceImpl<R, A> {+ repo: R,+ attachment_service: A,+}++impl<R: MessageRepo, A: AttachmentService> MessageServiceImpl<R, A> {+ /// Create a new [`MessageServiceImpl`].+ pub fn new(repo: R, attachment_service: A) -> Self {+ Self {+ repo,+ attachment_service,+ }+ }++ async fn resolve_attachments(+ &self,+ user_id: &MacroUserIdStr<'_>,+ attachments: &[(AttachmentType, String)],+ ) -> Result<Option<FormattedParts>> {+ if attachments.is_empty() {+ return Ok(None);+ }++ let entities: Vec<Entity<'static>> = attachments+ .iter()+ .map(|(kind, id)| attachment_type_to_entity_type(kind).with_entity_string(id.clone()))+ .collect();+ let entity_refs: Vec<&Entity<'_>> = entities.iter().collect();+ let non_empty = NonEmpty::new(entity_refs.as_slice()).expect("checked non-empty above");++ let resolved = self+ .attachment_service+ .resolve_attachments(user_id.clone(), non_empty)+ .await;++ Ok(Some(resolved.into_formatted_parts()))+ }+}++impl<R: MessageRepo, A: AttachmentService> MessageService for MessageServiceImpl<R, A> {+ #[tracing::instrument(err, skip(self, message))]+ async fn create(+ &self,+ user_id: &MacroUserIdStr<'_>,+ chat_id: &str,+ message: NewChatMessage,+ ) -> Result<ResolvedMessageContent> {+ let attachment_pairs: Vec<_> = message+ .attachments+ .as_deref()+ .unwrap_or_default()+ .iter()+ .map(|a| (a.attachment_type.clone(), a.attachment_id.clone()))+ .collect();++ let resolved = self.resolve_attachments(user_id, &attachment_pairs).await?;++ let message_id = self.repo.create(chat_id, message).await?;++ if let Some(ref parts) = resolved {+ self.repo+ .store_resolved_message(&message_id, parts.clone())+ .await?;+ }++ Ok(ResolvedMessageContent {+ message_id,+ parts: resolved,+ })+ }++ #[tracing::instrument(err, skip(self, message))]+ async fn store(&self, chat_id: &str, message: NewChatMessage) -> Result<String> {+ self.repo.create(chat_id, message).await+ }++ #[tracing::instrument(err, skip(self, content))]+ async fn update(+ &self,+ user_id: &MacroUserIdStr<'_>,+ chat_id: &str,+ message_id: &str,+ content: &ChatMessageContent,+ ) -> Result<()> {+ let messages = self.repo.get_messages(chat_id).await?;+ let msg = messages+ .iter()+ .find(|m| m.id == message_id)+ .ok_or(ChatErr::NotFound)?;++ let attachment_pairs: Vec<_> = msg+ .attachments+ .iter()+ .map(|a| (a.attachment_type.clone(), a.attachment_id.clone()))+ .collect();++ let resolved = self.resolve_attachments(user_id, &attachment_pairs).await?;++ self.repo+ .update_message_content(chat_id, message_id, content)+ .await?;++ if let Some(parts) = resolved {+ self.repo.store_resolved_message(message_id, parts).await?;+ }++ Ok(())+ }++ #[tracing::instrument(err, skip(self))]+ async fn delete(&self, message_id: &str) -> Result<()> {+ self.repo.delete(message_id).await+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_resolved_message(&self, message_id: &str) -> Result<ResolvedMessageContent> {+ let parts = self.repo.get_resolved_message(message_id).await?;+ Ok(ResolvedMessageContent {+ message_id: message_id.to_owned(),+ parts: Some(parts),+ })+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_resolved_message_chain(+ &self,+ chat_id: &str,+ ) -> Result<Vec<ResolvedMessageContent>> {+ let messages = self.repo.get_messages(chat_id).await?;+ let mut chain = Vec::new();+ for msg in &messages {+ if msg.role != ai::types::Role::User || msg.attachments.is_empty() {+ continue;+ }+ match self.repo.get_resolved_message(&msg.id).await {+ Ok(parts) => chain.push(ResolvedMessageContent {+ message_id: msg.id.clone(),+ parts: Some(parts),+ }),+ Err(ChatErr::NotFound) => {}+ Err(e) => return Err(e),+ }+ }+ Ok(chain)+ }+}++fn attachment_type_to_entity_type(at: &AttachmentType) -> EntityType {+ match at {+ AttachmentType::Document => EntityType::Document,+ AttachmentType::Image => EntityType::StaticFile,+ AttachmentType::Channel => EntityType::Channel,+ AttachmentType::Email => EntityType::EmailThread,+ AttachmentType::Project => EntityType::Project,+ }+}diff --git a/rust/cloud-storage/chat/src/domain/service/mod.rs b/rust/cloud-storage/chat/src/domain/service/mod.rsnew file mode 100644index 0000000000..c1b31d8707--- /dev/null+++ b/rust/cloud-storage/chat/src/domain/service/mod.rs@@ -0,0 +1,7 @@+//! Service implementations for the chat domain.++mod chat;+mod message;++pub use chat::*;+pub use message::*;diff --git a/rust/cloud-storage/chat/src/inbound/attachment.rs b/rust/cloud-storage/chat/src/inbound/attachment.rsindex d3bb7ecc95..d52d5e915d 100644--- a/rust/cloud-storage/chat/src/inbound/attachment.rs+++ b/rust/cloud-storage/chat/src/inbound/attachment.rs@@ -3,14 +3,14 @@use std::sync::Arc;use attachment::{- AttachmentContent, AttachmentError, AttachmentPart, AttachmentReference, AttachmentService,- Attachments, ResolutionError, fmt::XmlTag,+ AttachmentContent, AttachmentError, AttachmentPart, AttachmentService, Attachments,+ ResolutionError, fmt::XmlTag,};use entity_access::domain::{models::ViewAccessLevel, ports::EntityAccessService};use futures::future::join_all;use macro_user_id::user_id::MacroUserIdStr;use model::chat::ChatMessageWithAttachments;-use model_entity::EntityType;+use model_entity::{Entity, EntityType};use non_empty::NonEmpty;use crate::domain::ports::ChatRepo;@@ -33,16 +33,21 @@ impl<R, ESvc> ChatAttachmentService<R, ESvc> {impl<R: ChatRepo, ESvc: EntityAccessService> AttachmentService for ChatAttachmentService<R, ESvc> {#[tracing::instrument(skip_all)]- async fn resolve_attachments(+ async fn resolve_attachments<'a>(&self,user_id: MacroUserIdStr<'_>,- ids: NonEmpty<&[&str]>,- ) -> Attachments {+ ids: NonEmpty<&[&'a Entity<'a>]>,+ ) -> Attachments<'a> {let user_id = &user_id;- let results = join_all(ids.iter().map(|id| async move {- self.resolve_one(user_id, id)- .await- .map_err(|error| ResolutionError::new(id.to_string(), error))+ let results = join_all(ids.iter().map(|entity| async move {+ self.resolve_one(user_id, entity).await.map_err(|error| {+ ResolutionError::new(+ entity+ .entity_type+ .with_entity_string(entity.entity_id.to_string()),+ error,+ )+ })})).await;@@ -52,35 +57,41 @@ impl<R: ChatRepo, ESvc: EntityAccessService> AttachmentService for ChatAttachmenimpl<R: ChatRepo, ESvc: EntityAccessService> ChatAttachmentService<R, ESvc> {#[tracing::instrument(skip(self), err)]- async fn resolve_one(+ async fn resolve_one<'a>(&self,user_id: &MacroUserIdStr<'_>,- id: &str,- ) -> Result<AttachmentContent, AttachmentError> {+ entity: &'a Entity<'a>,+ ) -> Result<AttachmentContent<'a>, AttachmentError> {self.entity_access_service- .generate_entity_access_receipt::<ViewAccessLevel>(user_id, None, id, EntityType::Chat)+ .generate_entity_access_receipt::<ViewAccessLevel>(+ user_id,+ None,+ &entity.entity_id,+ EntityType::Chat,+ ).await.map_err(|e| AttachmentError::Internal(e.into()))?;let chat = self.repo- .get_chat(id)+ .get_chat(&entity.entity_id).await.map_err(|e| AttachmentError::Internal(e.into()))?;- let parts: Vec<AttachmentPart> = chat.messages.iter().filter_map(format_message).collect();+ let parts: Vec<AttachmentPart<'static>> =+ chat.messages.iter().filter_map(format_message).collect();let content = NonEmpty::new(parts).map_err(|_| AttachmentError::NoContent)?;Ok(AttachmentContent {- reference: AttachmentReference::Chat { id: id.to_string() },+ reference: entity.clone(),name: Some(chat.name),content,})}}-fn format_message(msg: &ChatMessageWithAttachments) -> Option<AttachmentPart> {+fn format_message(msg: &ChatMessageWithAttachments) -> Option<AttachmentPart<'static>> {let text = msg.content_text()?;if text.is_empty() {return None;@@ -92,7 +103,7 @@ fn format_message(msg: &ChatMessageWithAttachments) -> Option<AttachmentPart> {};let formatted = XmlTag {name: "message",- attrs: &[("role", role)],+ attrs: attachment::fmt::attrs(&[("role", role)]),body: &text,}.to_string();diff --git a/rust/cloud-storage/chat/src/inbound/http/router.rs b/rust/cloud-storage/chat/src/inbound/http/router.rsindex c28a3bcc25..7e87d98569 100644--- a/rust/cloud-storage/chat/src/inbound/http/router.rs+++ b/rust/cloud-storage/chat/src/inbound/http/router.rs@@ -18,13 +18,10 @@ use models_permissions::share_permission::SharePermissionV2;use serde::{Deserialize, Serialize};use utoipa::ToSchema;-use crate::domain::models::{ChatErr, CreateChatArgs, GetChatResponse, PatchChatArgs};+use crate::domain::models::{CreateChatArgs, GetChatResponse, PatchChatArgs, Result};use crate::domain::ports::ChatService;use crate::inbound::http::extractors::ChatModelAccess;-/// Type alias for handler results using [`ChatErr`] as the error type.-type ChatResult<T> = Result<T, ChatErr>;-/// Shared state for the chat router, wrapping a [`ChatService`] implementation/// and an [`EntityAccessService`] for authorization.pub struct ChatRouterState<S, Svc> {@@ -141,7 +138,7 @@ pub async fn create_chat_handler<S: ChatService, Svc: EntityAccessService>(// 402 on no perms_model_access: ChatModelAccess,Json(req): Json<CreateChatRequest>,-) -> ChatResult<Json<StringIDResponse>> {+) -> Result<Json<StringIDResponse>> {let id = state.inner.create(@@ -175,7 +172,7 @@ pub async fn get_chat_handler<S: ChatService, Svc: EntityAccessService>(access: ChatAccessLevelExtractor<ViewAccessLevel, Svc>,State(state): State<ChatRouterState<S, Svc>>,Path(chat_id): Path<String>,-) -> ChatResult<Json<GetChatResponse>> {+) -> Result<Json<GetChatResponse>> {let response = state.inner.get_chat(access.entity_access_receipt).await?;Ok(Json(response))@@ -199,7 +196,7 @@ pub async fn delete_chat_handler<S: ChatService, Svc: EntityAccessService>(access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc>,State(state): State<ChatRouterState<S, Svc>>,Path(chat_id): Path<String>,-) -> ChatResult<StatusCode> {+) -> Result<StatusCode> {state.inner.delete(access.entity_access_receipt).await?;Ok(StatusCode::OK)}@@ -222,7 +219,7 @@ pub async fn permanently_delete_chat_handler<S: ChatService, Svc: EntityAccessSeaccess: ChatAccessLevelExtractor<OwnerAccessLevel, Svc>,State(state): State<ChatRouterState<S, Svc>>,Path(chat_id): Path<String>,-) -> ChatResult<StatusCode> {+) -> Result<StatusCode> {state.inner.permanently_delete(access.entity_access_receipt)@@ -262,7 +259,7 @@ pub async fn patch_chat_handler<S: ChatService, Svc: EntityAccessService>(State(state): State<ChatRouterState<S, Svc>>,Path(chat_id): Path<String>,Json(req): Json<PatchChatRequest>,-) -> ChatResult<StatusCode> {+) -> Result<StatusCode> {state.inner.patch(@@ -297,7 +294,7 @@ pub async fn copy_chat_handler<S: ChatService, Svc: EntityAccessService>(access: ChatAccessLevelExtractor<ViewAccessLevel, Svc>,State(state): State<ChatRouterState<S, Svc>>,Path(chat_id): Path<String>,-) -> ChatResult<Json<StringIDResponse>> {+) -> Result<Json<StringIDResponse>> {let id = state.inner.copy_chat(access.entity_access_receipt).await?;Ok(Json(StringIDResponse { id }))}@@ -320,7 +317,7 @@ pub async fn revert_delete_handler<S: ChatService, Svc: EntityAccessService>(access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc>,State(state): State<ChatRouterState<S, Svc>>,Path(chat_id): Path<String>,-) -> ChatResult<StatusCode> {+) -> Result<StatusCode> {state.inner.revert_delete(access.entity_access_receipt)@@ -354,7 +351,7 @@ pub async fn get_chat_permissions_handler<S: ChatService, Svc: EntityAccessServiaccess: ChatAccessLevelExtractor<EditAccessLevel, Svc>,State(state): State<ChatRouterState<S, Svc>>,Path(chat_id): Path<String>,-) -> ChatResult<Json<GetChatPermissionsResponse>> {+) -> Result<Json<GetChatPermissionsResponse>> {let permissions = state.inner.get_permissions(access.entity_access_receipt)@@ -442,7 +439,7 @@ pub async fn update_tool_call_handler<S: ChatService, Svc: EntityAccessService>(State(state): State<ChatRouterState<S, Svc>>,Path(chat_id): Path<String>,Json(req): Json<UpdateToolCallRequest>,-) -> ChatResult<StatusCode> {+) -> Result<StatusCode> {state.inner.update_tool_call(@@ -479,7 +476,7 @@ pub async fn update_tool_response_handler<S: ChatService, Svc: EntityAccessServiState(state): State<ChatRouterState<S, Svc>>,Path(chat_id): Path<String>,Json(req): Json<UpdateToolResponseRequest>,-) -> ChatResult<StatusCode> {+) -> Result<StatusCode> {state.inner.update_tool_response(@@ -517,7 +514,7 @@ pub async fn call_tool_handler<S: ChatService, Svc: EntityAccessService>(State(state): State<ChatRouterState<S, Svc>>,Path(chat_id): Path<String>,Json(req): Json<CallToolRequest>,-) -> ChatResult<Json<CallToolResponse>> {+) -> Result<Json<CallToolResponse>> {let result = state.inner.call_tool(@@ -554,7 +551,7 @@ pub async fn reject_tool_call_handler<S: ChatService, Svc: EntityAccessService>(State(state): State<ChatRouterState<S, Svc>>,Path(chat_id): Path<String>,Json(req): Json<RejectToolCallRequest>,-) -> ChatResult<StatusCode> {+) -> Result<StatusCode> {state.inner.reject_tool_call(diff --git a/rust/cloud-storage/chat/src/inbound/test.rs b/rust/cloud-storage/chat/src/inbound/test.rsindex f625e43260..6d4884e1bc 100644--- a/rust/cloud-storage/chat/src/inbound/test.rs+++ b/rust/cloud-storage/chat/src/inbound/test.rs@@ -11,7 +11,7 @@ use tower::util::ServiceExt;use super::*;use crate::domain::models::{- ChatErr, ChatResponse, CreateChatArgs, GetChatResponse, PatchChatArgs,+ ChatErr, ChatResponse, CreateChatArgs, GetChatResponse, PatchChatArgs, Result,};use crate::domain::ports::ChatService;use ai_toolset::tool_object::UserToolResponse;@@ -30,7 +30,7 @@ impl ChatService for MockService {&self,_user_id: macro_user_id::user_id::MacroUserIdStr<'static>,_args: CreateChatArgs,- ) -> Result<String, ChatErr> {+ ) -> Result<String> {Ok("test-chat-id".to_string())}@@ -38,7 +38,7 @@ impl ChatService for MockService {async fn get_chat(&self,entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,- ) -> Result<GetChatResponse, ChatErr> {+ ) -> Result<GetChatResponse> {let chat_id = entity_access_receipt.entity().entity_id.clone();Ok(GetChatResponse {chat: ChatResponse {@@ -63,21 +63,21 @@ impl ChatService for MockService {async fn copy_chat(&self,_entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,- ) -> Result<String, ChatErr> {+ ) -> Result<String> {Ok("copied-chat-id".to_string())}async fn delete(&self,_entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,- ) -> Result<(), ChatErr> {+ ) -> Result<()> {Ok(())}async fn permanently_delete(&self,_entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,- ) -> Result<(), ChatErr> {+ ) -> Result<()> {Ok(())}@@ -85,21 +85,21 @@ impl ChatService for MockService {&self,_entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,_args: PatchChatArgs,- ) -> Result<(), ChatErr> {+ ) -> Result<()> {Ok(())}async fn revert_delete(&self,_entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,- ) -> Result<(), ChatErr> {+ ) -> Result<()> {Ok(())}async fn get_permissions(&self,_entity_access_receipt: EntityAccessReceipt<EditAccessLevel>,- ) -> Result<models_permissions::share_permission::SharePermissionV2, ChatErr> {+ ) -> Result<models_permissions::share_permission::SharePermissionV2> {Err(ChatErr::Unknown(anyhow::anyhow!("not implemented")))}@@ -109,7 +109,7 @@ impl ChatService for MockService {_message_id: &str,_tool_call_id: &str,_new_args: serde_json::Value,- ) -> Result<(), ChatErr> {+ ) -> Result<()> {Ok(())}@@ -119,7 +119,7 @@ impl ChatService for MockService {_message_id: &str,_tool_call_id: &str,_response: UserToolResponse<serde_json::Value>,- ) -> Result<(), ChatErr> {+ ) -> Result<()> {Ok(())}@@ -129,7 +129,7 @@ impl ChatService for MockService {_message_id: &str,_tool_call_id: &str,_args: Option<serde_json::Value>,- ) -> Result<serde_json::Value, ChatErr> {+ ) -> Result<serde_json::Value> {Ok(serde_json::json!({"argsWasProvided": _args.is_some(),"args": _args,@@ -141,7 +141,7 @@ impl ChatService for MockService {_receipt: EntityAccessReceipt<OwnerAccessLevel>,_message_id: &str,_tool_call_id: &str,- ) -> Result<(), ChatErr> {+ ) -> Result<()> {Ok(())}}@@ -153,35 +153,35 @@ impl ChatService for ErrorService {&self,_user_id: macro_user_id::user_id::MacroUserIdStr<'static>,_args: CreateChatArgs,- ) -> Result<String, ChatErr> {+ ) -> Result<String> {Err(ChatErr::Unknown(anyhow::anyhow!("db error")))}async fn get_chat(&self,_entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,- ) -> Result<GetChatResponse, ChatErr> {+ ) -> Result<GetChatResponse> {Err(ChatErr::Unknown(anyhow::anyhow!("db error")))}async fn copy_chat(&self,_entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,- ) -> Result<String, ChatErr> {+ ) -> Result<String> {Err(ChatErr::Unknown(anyhow::anyhow!("db error")))}async fn delete(&self,_entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,- ) -> Result<(), ChatErr> {+ ) -> Result<()> {Err(ChatErr::Unknown(anyhow::anyhow!("db error")))}async fn permanently_delete(&self,_entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,- ) -> Result<(), ChatErr> {+ ) -> Result<()> {Err(ChatErr::Unknown(anyhow::anyhow!("db error")))}@@ -189,21 +189,21 @@ impl ChatService for ErrorService {&self,_entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,_args: PatchChatArgs,- ) -> Result<(), ChatErr> {+ ) -> Result<()> {Err(ChatErr::Unknown(anyhow::anyhow!("db error")))}async fn revert_delete(&self,_entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,- ) -> Result<(), ChatErr> {+ ) -> Result<()> {Err(ChatErr::Unknown(anyhow::anyhow!("db error")))}async fn get_permissions(&self,_entity_access_receipt: EntityAccessReceipt<EditAccessLevel>,- ) -> Result<models_permissions::share_permission::SharePermissionV2, ChatErr> {+ ) -> Result<models_permissions::share_permission::SharePermissionV2> {Err(ChatErr::Unknown(anyhow::anyhow!("db error")))}@@ -213,7 +213,7 @@ impl ChatService for ErrorService {_message_id: &str,_tool_call_id: &str,_new_args: serde_json::Value,- ) -> Result<(), ChatErr> {+ ) -> Result<()> {Err(ChatErr::Unknown(anyhow::anyhow!("db error")))}@@ -223,7 +223,7 @@ impl ChatService for ErrorService {_message_id: &str,_tool_call_id: &str,_response: UserToolResponse<serde_json::Value>,- ) -> Result<(), ChatErr> {+ ) -> Result<()> {Err(ChatErr::Unknown(anyhow::anyhow!("db error")))}@@ -233,7 +233,7 @@ impl ChatService for ErrorService {_message_id: &str,_tool_call_id: &str,_args: Option<serde_json::Value>,- ) -> Result<serde_json::Value, ChatErr> {+ ) -> Result<serde_json::Value> {Err(ChatErr::Unknown(anyhow::anyhow!("db error")))}@@ -242,7 +242,7 @@ impl ChatService for ErrorService {_receipt: EntityAccessReceipt<OwnerAccessLevel>,_message_id: &str,_tool_call_id: &str,- ) -> Result<(), ChatErr> {+ ) -> Result<()> {Err(ChatErr::Unknown(anyhow::anyhow!("db error")))}}@@ -254,35 +254,35 @@ impl ChatService for NotFoundService {&self,_user_id: macro_user_id::user_id::MacroUserIdStr<'static>,_args: CreateChatArgs,- ) -> Result<String, ChatErr> {+ ) -> Result<String> {Err(ChatErr::Unknown(anyhow::anyhow!("db error")))}async fn get_chat(&self,_entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,- ) -> Result<GetChatResponse, ChatErr> {+ ) -> Result<GetChatResponse> {Err(ChatErr::NotFound)}async fn copy_chat(&self,_entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,- ) -> Result<String, ChatErr> {+ ) -> Result<String> {Err(ChatErr::NotFound)}async fn delete(&self,_entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,- ) -> Result<(), ChatErr> {+ ) -> Result<()> {Err(ChatErr::Unknown(anyhow::anyhow!("db error")))}async fn permanently_delete(&self,_entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,- ) -> Result<(), ChatErr> {+ ) -> Result<()> {Err(ChatErr::Unknown(anyhow::anyhow!("db error")))}@@ -290,21 +290,21 @@ impl ChatService for NotFoundService {&self,_entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,_args: PatchChatArgs,- ) -> Result<(), ChatErr> {+ ) -> Result<()> {Err(ChatErr::Unknown(anyhow::anyhow!("db error")))}async fn revert_delete(&self,_entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,- ) -> Result<(), ChatErr> {+ ) -> Result<()> {Err(ChatErr::Unknown(anyhow::anyhow!("db error")))}async fn get_permissions(&self,_entity_access_receipt: EntityAccessReceipt<EditAccessLevel>,- ) -> Result<models_permissions::share_permission::SharePermissionV2, ChatErr> {+ ) -> Result<models_permissions::share_permission::SharePermissionV2> {Err(ChatErr::Unknown(anyhow::anyhow!("db error")))}@@ -314,7 +314,7 @@ impl ChatService for NotFoundService {_message_id: &str,_tool_call_id: &str,_new_args: serde_json::Value,- ) -> Result<(), ChatErr> {+ ) -> Result<()> {Err(ChatErr::NotFound)}@@ -324,7 +324,7 @@ impl ChatService for NotFoundService {_message_id: &str,_tool_call_id: &str,_response: UserToolResponse<serde_json::Value>,- ) -> Result<(), ChatErr> {+ ) -> Result<()> {Err(ChatErr::NotFound)}@@ -334,7 +334,7 @@ impl ChatService for NotFoundService {_message_id: &str,_tool_call_id: &str,_args: Option<serde_json::Value>,- ) -> Result<serde_json::Value, ChatErr> {+ ) -> Result<serde_json::Value> {Err(ChatErr::NotFound)}@@ -343,7 +343,7 @@ impl ChatService for NotFoundService {_receipt: EntityAccessReceipt<OwnerAccessLevel>,_message_id: &str,_tool_call_id: &str,- ) -> Result<(), ChatErr> {+ ) -> Result<()> {Err(ChatErr::NotFound)}}@@ -360,7 +360,8 @@ impl EntityAccessService for MockAccessService {_user_org_id: Option<i64>,_entity_id: &str,_entity_type: EntityType,- ) -> Result<entity_access::domain::models::EntityAccessReceipt<T>, AccessError> {+ ) -> std::result::Result<entity_access::domain::models::EntityAccessReceipt<T>, AccessError>+ {unreachable!("not used by ChatAccessLevelExtractor")}@@ -369,7 +370,7 @@ impl EntityAccessService for MockAccessService {_user_id: Option<&MacroUserId<Lowercase<'_>>>,_entity_id: &str,_entity_type: EntityType,- ) -> Result<Option<AccessLevel>, AccessError> {+ ) -> std::result::Result<Option<AccessLevel>, AccessError> {Ok(Some(AccessLevel::Owner))}@@ -379,7 +380,7 @@ impl EntityAccessService for MockAccessService {_entity_id: &str,_entity_type: EntityType,_required_level: AccessLevel,- ) -> Result<AccessLevel, AccessError> {+ ) -> std::result::Result<AccessLevel, AccessError> {Ok(AccessLevel::Owner)}@@ -388,7 +389,7 @@ impl EntityAccessService for MockAccessService {_entity_id: &str,_entity_type: EntityType,_required_level: AccessLevel,- ) -> Result<AccessLevel, AccessError> {+ ) -> std::result::Result<AccessLevel, AccessError> {Ok(AccessLevel::Owner)}@@ -398,7 +399,7 @@ impl EntityAccessService for MockAccessService {_entity_id: &str,_entity_type: EntityType,_user_org_id: Option<i64>,- ) -> Result<EntityPermission, AccessError> {+ ) -> std::result::Result<EntityPermission, AccessError> {Ok(EntityPermission::AccessLevel {access_level: AccessLevel::Owner,})@@ -408,21 +409,23 @@ impl EntityAccessService for MockAccessService {&self,_entity_id: &str,_entity_type: EntityType,- ) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {+ ) -> std::result::Result<Vec<MacroUserIdStr<'static>>, AccessError> {Ok(vec![])}async fn get_call_channel(&self,_call_id: &sqlx::types::Uuid,- ) -> Result<Option<entity_access::domain::models::CallChannelInfo>, AccessError> {+ ) -> std::result::Result<Option<entity_access::domain::models::CallChannelInfo>, AccessError>+ {unimplemented!()}async fn get_call_channel_by_channel_id(&self,_channel_id: &sqlx::types::Uuid,- ) -> Result<Option<entity_access::domain::models::CallChannelInfo>, AccessError> {+ ) -> std::result::Result<Option<entity_access::domain::models::CallChannelInfo>, AccessError>+ {unimplemented!()}}diff --git a/rust/cloud-storage/chat/src/outbound/postgres/mod.rs b/rust/cloud-storage/chat/src/outbound/postgres/mod.rsindex 65df9887d8..cc0ec588a0 100644--- a/rust/cloud-storage/chat/src/outbound/postgres/mod.rs+++ b/rust/cloud-storage/chat/src/outbound/postgres/mod.rs@@ -6,13 +6,15 @@ mod test;use crate::domain::models::{ChatErr, ChatResponse, CopyChatArgs, CreateChatArgs, PatchChatArgs, PatchChatMessageArgs,- WebCitation,+ Result, WebCitation,};-use crate::domain::ports::ChatRepo;+use crate::domain::ports::{ChatRepo, MessageRepo};use ai::types::{ChatMessageContent, Model};+use attachment::FormattedParts;use macro_user_id::cowlike::CowLike;use macro_user_id::user_id::MacroUserIdStr;use model::chat::ChatMessageWithAttachments;+use model::chat::NewChatMessage;use models_permissions::share_permission::SharePermissionV2;use models_permissions::share_permission::access_level::AccessLevel;use sqlx::PgPool;@@ -53,6 +55,15 @@ impl PgChatRepo {) -> anyhow::Result<Vec<(String, Vec<WebCitation>)>> {queries::get_web_citations::get_web_citations(&self.pool, chat_id).await}++ /// Store a resolved message without going through the trait.+ pub async fn store_resolved_message_static(+ &self,+ message_id: &str,+ parts: FormattedParts,+ ) -> anyhow::Result<()> {+ queries::store_resolved_message::store_resolved_message(&self.pool, message_id, parts).await+ }}impl ChatRepo for PgChatRepo {@@ -61,7 +72,7 @@ impl ChatRepo for PgChatRepo {&self,user_id: MacroUserIdStr<'static>,args: CreateChatArgs,- ) -> Result<String, ChatErr> {+ ) -> Result<String> {let mut tx = self.pool.begin()@@ -115,7 +126,7 @@ impl ChatRepo for PgChatRepo {#[tracing::instrument(err, skip(self))]#[allow(deprecated)]- async fn get_chat(&self, chat_id: &str) -> Result<ChatResponse, ChatErr> {+ async fn get_chat(&self, chat_id: &str) -> Result<ChatResponse> {let chat = self.get_metadata(chat_id).await?;let mut messages = self.get_messages(chat_id).await.map_err(to_chat_err)?;messages.retain(|m| m.role != ai::types::Role::System);@@ -139,7 +150,7 @@ impl ChatRepo for PgChatRepo {}#[tracing::instrument(err, skip(self))]- async fn get_metadata(&self, chat_id: &str) -> Result<model::chat::Chat, ChatErr> {+ async fn get_metadata(&self, chat_id: &str) -> Result<model::chat::Chat> {queries::get_chat::get_chat(&self.pool, chat_id).await.map_err(to_chat_err)@@ -150,7 +161,7 @@ impl ChatRepo for PgChatRepo {&self,user_id: MacroUserIdStr<'_>,chat_id: &str,- ) -> Result<AccessLevel, ChatErr> {+ ) -> Result<AccessLevel> {queries::get_access_level::get_access_level(&self.pool, user_id.as_ref(), chat_id).await.map_err(to_chat_err)@@ -162,7 +173,7 @@ impl ChatRepo for PgChatRepo {user_id: MacroUserIdStr<'static>,source_chat_id: &str,args: CopyChatArgs,- ) -> Result<String, ChatErr> {+ ) -> Result<String> {let mut tx = self.pool.begin()@@ -219,7 +230,7 @@ impl ChatRepo for PgChatRepo {}#[tracing::instrument(err, skip(self))]- async fn revert_delete(&self, chat_id: &str, project_id: Option<&str>) -> Result<(), ChatErr> {+ async fn revert_delete(&self, chat_id: &str, project_id: Option<&str>) -> Result<()> {let mut tx = self.pool.begin()@@ -233,14 +244,14 @@ impl ChatRepo for PgChatRepo {}#[tracing::instrument(err, skip(self))]- async fn get_permissions(&self, chat_id: &str) -> Result<SharePermissionV2, ChatErr> {+ async fn get_permissions(&self, chat_id: &str) -> Result<SharePermissionV2> {queries::get_permissions::get_chat_share_permission(&self.pool, chat_id).await.map_err(to_chat_err)}#[tracing::instrument(err, skip(self))]- async fn delete(&self, chat_id: &str) -> Result<(), ChatErr> {+ async fn delete(&self, chat_id: &str) -> Result<()> {let mut tx = self.pool.begin()@@ -254,7 +265,7 @@ impl ChatRepo for PgChatRepo {}#[tracing::instrument(err, skip(self))]- async fn permanently_delete(&self, chat_id: &str) -> Result<(), ChatErr> {+ async fn permanently_delete(&self, chat_id: &str) -> Result<()> {let mut tx = self.pool.begin()@@ -273,7 +284,7 @@ impl ChatRepo for PgChatRepo {user_id: MacroUserIdStr<'static>,chat_id: &str,args: PatchChatArgs,- ) -> Result<(), ChatErr> {+ ) -> Result<()> {let mut tx = self.pool.begin()@@ -304,18 +315,14 @@ impl ChatRepo for PgChatRepo {}#[tracing::instrument(err, skip(self))]- async fn update_project_modified(&self, project_id: &str) -> Result<(), ChatErr> {+ async fn update_project_modified(&self, project_id: &str) -> Result<()> {queries::update_project_modified::update_project_modified(&self.pool, project_id).await.map_err(to_chat_err)}#[tracing::instrument(err, skip(self))]- async fn patch_message(- &self,- chat_id: &str,- args: PatchChatMessageArgs,- ) -> Result<(), ChatErr> {+ async fn patch_message(&self, chat_id: &str, args: PatchChatMessageArgs) -> Result<()> {queries::update_message_content::update_message_content(&self.pool,chat_id,@@ -331,7 +338,69 @@ impl ChatRepo for PgChatRepo {&self,chat_id: &str,message_id: &str,- ) -> Result<ChatMessageContent, ChatErr> {+ ) -> Result<ChatMessageContent> {+ queries::get_message_content::get_message_content(&self.pool, chat_id, message_id)+ .await+ .map_err(to_chat_err)+ }++ #[tracing::instrument(err, skip(self, content))]+ async fn update_message_content(+ &self,+ chat_id: &str,+ message_id: &str,+ content: &ChatMessageContent,+ ) -> Result<()> {+ queries::update_message_content::update_message_content(+ &self.pool, chat_id, message_id, content,+ )+ .await+ .map_err(to_chat_err)+ }++ #[tracing::instrument(err, skip(self, parts))]+ async fn store_resolved_message(&self, message_id: &str, parts: FormattedParts) -> Result<()> {+ queries::store_resolved_message::store_resolved_message(&self.pool, message_id, parts)+ .await+ .map_err(to_chat_err)+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_resolved_message(&self, message_id: &str) -> Result<FormattedParts> {+ queries::get_resolved_message::get_resolved_message(&self.pool, message_id)+ .await+ .map_err(to_chat_err)+ }+}++impl MessageRepo for PgChatRepo {+ #[tracing::instrument(err, skip(self, message))]+ async fn create(&self, chat_id: &str, message: NewChatMessage) -> Result<String> {+ queries::create_message::create_message(&self.pool, chat_id, message)+ .await+ .map_err(to_chat_err)+ }++ #[tracing::instrument(err, skip(self))]+ async fn delete(&self, message_id: &str) -> Result<()> {+ queries::delete_message::delete_message(&self.pool, message_id)+ .await+ .map_err(to_chat_err)+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_messages(&self, chat_id: &str) -> Result<Vec<ChatMessageWithAttachments>> {+ queries::get_messages::get_messages(&self.pool, chat_id)+ .await+ .map_err(to_chat_err)+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_message_content(+ &self,+ chat_id: &str,+ message_id: &str,+ ) -> Result<ChatMessageContent> {queries::get_message_content::get_message_content(&self.pool, chat_id, message_id).await.map_err(to_chat_err)@@ -343,11 +412,58 @@ impl ChatRepo for PgChatRepo {chat_id: &str,message_id: &str,content: &ChatMessageContent,- ) -> Result<(), ChatErr> {+ ) -> Result<()> {queries::update_message_content::update_message_content(&self.pool, chat_id, message_id, content,).await.map_err(to_chat_err)}++ #[tracing::instrument(err, skip(self))]+ async fn patch_message(&self, chat_id: &str, args: PatchChatMessageArgs) -> Result<()> {+ queries::update_message_content::update_message_content(+ &self.pool,+ chat_id,+ &args.message_id,+ &args.content,+ )+ .await+ .map_err(to_chat_err)+ }++ #[tracing::instrument(err, skip(self))]+ async fn copy_messages(&self, source_chat_id: &str, dest_chat_id: &str) -> Result<()> {+ let mut tx = self+ .pool+ .begin()+ .await+ .map_err(|e| ChatErr::Unknown(e.into()))?;+ queries::copy_messages::copy_messages(&mut tx, source_chat_id, dest_chat_id)+ .await+ .map_err(to_chat_err)?;+ tx.commit().await.map_err(|e| ChatErr::Unknown(e.into()))?;+ Ok(())+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_web_citations(&self, chat_id: &str) -> Result<Vec<(String, Vec<WebCitation>)>> {+ queries::get_web_citations::get_web_citations(&self.pool, chat_id)+ .await+ .map_err(to_chat_err)+ }++ #[tracing::instrument(err, skip(self, parts))]+ async fn store_resolved_message(&self, message_id: &str, parts: FormattedParts) -> Result<()> {+ queries::store_resolved_message::store_resolved_message(&self.pool, message_id, parts)+ .await+ .map_err(to_chat_err)+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_resolved_message(&self, message_id: &str) -> Result<FormattedParts> {+ queries::get_resolved_message::get_resolved_message(&self.pool, message_id)+ .await+ .map_err(to_chat_err)+ }}diff --git a/rust/cloud-storage/chat/src/outbound/postgres/queries/create_message.rs b/rust/cloud-storage/chat/src/outbound/postgres/queries/create_message.rsnew file mode 100644index 0000000000..5f20f403fb--- /dev/null+++ b/rust/cloud-storage/chat/src/outbound/postgres/queries/create_message.rs@@ -0,0 +1,73 @@+//! Insert a new chat message with optional attachments.++use ai::types::Role;+use model::chat::NewChatMessage;+use sqlx::PgPool;++/// Insert a message into a chat, returning the message ID.+///+/// User messages also insert their attachments in the same transaction.+#[tracing::instrument(err, skip(pool, message))]+pub(crate) async fn create_message(+ pool: &PgPool,+ chat_id: &str,+ message: NewChatMessage,+) -> anyhow::Result<String> {+ let id = message+ .id+ .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());+ let content = serde_json::to_value(&message.content)?;+ let role = message.role.as_ref().to_string();+ let model = message.model.to_string();++ let mut tx = pool.begin().await?;++ let message_id = sqlx::query!(+ r#"+ INSERT INTO "ChatMessage" ("id", "chatId", "content", "role", "model", "createdAt", "updatedAt")+ VALUES ($1, $2, $3, $4, $5, $6, $7)+ RETURNING id+ "#,+ id,+ chat_id,+ content,+ role,+ model,+ message.created_at.naive_utc(),+ message.updated_at.naive_utc(),+ )+ .fetch_one(&mut *tx)+ .await+ .map(|r| r.id)?;++ if message.role == Role::User {+ let mut kinds = Vec::new();+ let mut ids = Vec::new();+ let mut chat_ids = Vec::new();+ let mut message_ids = Vec::new();+ for a in message.attachments.unwrap_or_default() {+ kinds.push(a.attachment_type.to_string());+ ids.push(a.attachment_id);+ chat_ids.push(chat_id.to_string());+ message_ids.push(message_id.clone());+ }++ if !kinds.is_empty() {+ sqlx::query!(+ r#"+ INSERT INTO "ChatAttachment" ("attachmentType", "attachmentId", "chatId", "messageId")+ SELECT * FROM UNNEST($1::TEXT[], $2::TEXT[], $3::TEXT[], $4::TEXT[])+ "#,+ &kinds,+ &ids,+ &chat_ids,+ &message_ids,+ )+ .execute(&mut *tx)+ .await?;+ }+ }++ tx.commit().await?;+ Ok(message_id)+}diff --git a/rust/cloud-storage/chat/src/outbound/postgres/queries/delete_message.rs b/rust/cloud-storage/chat/src/outbound/postgres/queries/delete_message.rsnew file mode 100644index 0000000000..6f4aa1d3d0--- /dev/null+++ b/rust/cloud-storage/chat/src/outbound/postgres/queries/delete_message.rs@@ -0,0 +1,20 @@+//! Delete a chat message by ID.++use sqlx::PgPool;++/// Delete a message, returning an error if it does not exist.+#[tracing::instrument(err, skip(pool))]+pub(crate) async fn delete_message(pool: &PgPool, message_id: &str) -> anyhow::Result<()> {+ sqlx::query!(+ r#"+ DELETE FROM "ChatMessage"+ WHERE id = $1+ RETURNING id+ "#,+ message_id+ )+ .fetch_one(pool)+ .await?;++ Ok(())+}diff --git a/rust/cloud-storage/chat/src/outbound/postgres/queries/get_resolved_message.rs b/rust/cloud-storage/chat/src/outbound/postgres/queries/get_resolved_message.rsnew file mode 100644index 0000000000..dc9a63e9e0--- /dev/null+++ b/rust/cloud-storage/chat/src/outbound/postgres/queries/get_resolved_message.rs@@ -0,0 +1,25 @@+//! Query to fetch a resolved user message.++use attachment::FormattedParts;+use sqlx::PgPool;++/// Fetch the resolved representation of a user message.+#[tracing::instrument(err, skip(pool))]+pub(crate) async fn get_resolved_message(+ pool: &PgPool,+ message_id: &str,+) -> anyhow::Result<FormattedParts> {+ let row = sqlx::query!(+ r#"+ SELECT "content"+ FROM resolved_message_content+ WHERE "messageId" = $1+ "#,+ message_id+ )+ .fetch_one(pool)+ .await?;++ let parts = serde_json::from_value::<FormattedParts>(row.content)?;+ Ok(parts)+}diff --git a/rust/cloud-storage/chat/src/outbound/postgres/queries/mod.rs b/rust/cloud-storage/chat/src/outbound/postgres/queries/mod.rsindex ea8df65a24..579f07a27f 100644--- a/rust/cloud-storage/chat/src/outbound/postgres/queries/mod.rs+++ b/rust/cloud-storage/chat/src/outbound/postgres/queries/mod.rs@@ -2,18 +2,22 @@pub(crate) mod copy_messages;pub(crate) mod create_chat_permission;+pub(crate) mod create_message;+pub(crate) mod delete_message;pub(crate) mod edit_share_permission;pub(crate) mod get_access_level;pub(crate) mod get_chat;pub(crate) mod get_message_content;pub(crate) mod get_messages;pub(crate) mod get_permissions;+pub(crate) mod get_resolved_message;pub(crate) mod get_web_citations;pub(crate) mod insert_chat;pub(crate) mod patch_chat;pub(crate) mod permanently_delete_chat;pub(crate) mod revert_delete_chat;pub(crate) mod soft_delete_chat;+pub(crate) mod store_resolved_message;pub(crate) mod update_message_content;pub(crate) mod update_project_modified;pub(crate) mod upsert_item_last_accessed;diff --git a/rust/cloud-storage/chat/src/outbound/postgres/queries/store_resolved_message.rs b/rust/cloud-storage/chat/src/outbound/postgres/queries/store_resolved_message.rsnew file mode 100644index 0000000000..d1b0086ccf--- /dev/null+++ b/rust/cloud-storage/chat/src/outbound/postgres/queries/store_resolved_message.rs@@ -0,0 +1,28 @@+//! Query to upsert a resolved message content.++use attachment::FormattedParts;+use sqlx::PgPool;++/// Upsert the resolved representation of a user message.+#[tracing::instrument(err, skip(pool, parts))]+pub(crate) async fn store_resolved_message(+ pool: &PgPool,+ message_id: &str,+ parts: FormattedParts,+) -> anyhow::Result<()> {+ let content = serde_json::to_value(&parts)?;++ sqlx::query!(+ r#"+ INSERT INTO resolved_message_content ("messageId", "content")+ VALUES ($1, $2)+ ON CONFLICT ("messageId") DO UPDATE SET "content" = $2+ "#,+ message_id,+ content+ )+ .execute(pool)+ .await?;++ Ok(())+}diff --git a/rust/cloud-storage/comms/src/inbound/attachment.rs b/rust/cloud-storage/comms/src/inbound/attachment.rsindex c417695b98..362b096651 100644--- a/rust/cloud-storage/comms/src/inbound/attachment.rs+++ b/rust/cloud-storage/comms/src/inbound/attachment.rs@@ -3,18 +3,15 @@use std::fmt::Write;use std::sync::Arc;-use attachment::fmt::XmlTag;+use attachment::fmt::{XmlTag, attrs};use attachment::{- AttachmentContent, AttachmentError, AttachmentPart, AttachmentReference, AttachmentService,- Attachments, ResolutionError,-};-use entity_access::domain::{- models::{AccessError, MemberParticipantRole},- ports::EntityAccessService,+ AttachmentContent, AttachmentError, AttachmentPart, AttachmentService, Attachments,+ ResolutionError,};+use entity_access::domain::{models::MemberParticipantRole, ports::EntityAccessService};use futures::future::join_all;use macro_user_id::user_id::MacroUserIdStr;-use model_entity::EntityType;+use model_entity::{Entity, EntityType};use models_comms::channel::{ChannelId, ChannelMessage};use non_empty::NonEmpty;@@ -40,16 +37,21 @@ impl<C, E> CommsAttachmentService<C, E> {impl<C: CommsRepo, E: EntityAccessService> AttachmentService for CommsAttachmentService<C, E> {#[tracing::instrument(skip_all)]- async fn resolve_attachments(+ async fn resolve_attachments<'a>(&self,user_id: MacroUserIdStr<'_>,- ids: NonEmpty<&[&str]>,- ) -> Attachments {+ ids: NonEmpty<&[&'a Entity<'a>]>,+ ) -> Attachments<'a> {let user_id = &user_id;- let results = join_all(ids.iter().map(|id| async move {- self.resolve_one(user_id, id)- .await- .map_err(|error| ResolutionError::new(id.to_string(), error))+ let results = join_all(ids.iter().map(|entity| async move {+ self.resolve_one(user_id, entity).await.map_err(|error| {+ ResolutionError::new(+ entity+ .entity_type+ .with_entity_string(entity.entity_id.to_string()),+ error,+ )+ })})).await;Attachments::new(NonEmpty::new(results).expect("ids was non-empty"))@@ -61,8 +63,9 @@ impl<C: CommsRepo, E: EntityAccessService> CommsAttachmentService<C, E> {async fn resolve_one(&self,user_id: &MacroUserIdStr<'_>,- id: &str,- ) -> Result<AttachmentContent, AttachmentError> {+ entity: &Entity<'_>,+ ) -> Result<AttachmentContent<'static>, AttachmentError> {+ let id = &*entity.entity_id;let channel_id =ChannelId(uuid::Uuid::parse_str(id).map_err(|e| AttachmentError::Internal(e.into()))?);@@ -74,12 +77,7 @@ impl<C: CommsRepo, E: EntityAccessService> CommsAttachmentService<C, E> {EntityType::Channel,).await- .map_err(|e| match e {- AccessError::Unauthorized | AccessError::UnauthorizedWithMessage(_) => {- AttachmentError::PermissionDenied { id: id.to_string() }- }- other => AttachmentError::Internal(anyhow::anyhow!("{other:#}")),- })?;+ .map_err(|e| AttachmentError::PermissionDenied(Box::new(e)))?;let (name, messages) = tokio::join!(self.comms_repo.get_channel_name(channel_id),@@ -95,10 +93,16 @@ impl<C: CommsRepo, E: EntityAccessService> CommsAttachmentService<C, E> {let parts = format_messages(&messages);Ok(AttachmentContent {- reference: AttachmentReference::Channel { id: id.to_string() },+ reference: EntityType::Channel.with_entity_string(id.to_string()),name,- content: NonEmpty::new(vec![AttachmentPart::Content(parts)])- .expect("single element is non-empty"),+ content: NonEmpty::new(vec![+ AttachmentPart::Metadata {+ key: "message-limit".into(),+ value: MESSAGE_LIMIT.to_string(),+ },+ AttachmentPart::Content(parts),+ ])+ .expect("single element is non-empty"),})}}@@ -110,13 +114,10 @@ fn format_messages(messages: &[ChannelMessage]) -> String {let mut body = String::new();for msg in messages {- let timestamp = msg.created_at.format("%Y-%m-%d %H:%M");+ let timestamp = msg.created_at.format("%Y-%m-%d %H:%M").to_string();let tag = XmlTag {name: "message",- attrs: &[- ("sender", &msg.sender_id),- ("timestamp", ×tamp.to_string()),- ],+ attrs: attrs(&[("sender", &msg.sender_id), ("timestamp", ×tamp)]),body: &msg.content,};writeln!(&mut body, "{tag}").expect("write to string");diff --git a/rust/cloud-storage/document_cognition_service/Cargo.toml b/rust/cloud-storage/document_cognition_service/Cargo.tomlindex fb71947967..4a44afba45 100644--- a/rust/cloud-storage/document_cognition_service/Cargo.toml+++ b/rust/cloud-storage/document_cognition_service/Cargo.toml@@ -27,6 +27,8 @@ local_queue = []aho-corasick = "1.1.3"ai = { path = "../ai" }ai_format = { path = "../ai_format" }+attachment = { path = "../attachment", features = ["provider"] }+non_empty = { path = "../non_empty" }ai_tools = { path = "../ai_tools" }ai_toolset = { path = "../ai_toolset" }anyhow = { workspace = true }@@ -39,17 +41,17 @@ aws-sdk-secretsmanager = { workspace = true }aws-sdk-sqs = { workspace = true }axum = { workspace = true, features = ["tower-log", "ws"] }call = { path = "../call", default-features = false, features = ["ports"] }-chat = { path = "../chat" }+chat = { path = "../chat", features = ["attachment"] }chrono = { workspace = true }-comms = { path = "../comms", features = ["outbound"] }+comms = { path = "../comms", features = ["outbound", "attachment"] }comms_service_client = { path = "../comms_service_client" }connection_gateway = { path = "../connection_gateway" }cookie = { workspace = true }document_cognition_service_client = { path = "../document_cognition_service_client" }document_storage_service_client = { path = "../document_storage_service_client" }-documents = { path = "../documents", features = ["ai_tools"] }+documents = { path = "../documents", features = ["ai_tools", "attachment"] }doppleganger = { workspace = true }-email = { path = "../email", features = ["outbound"] }+email = { path = "../email", features = ["outbound", "attachment"] }email_service_client = { path = "../email_service_client" }entity_access = { path = "../entity_access" }entity_access_management = { path = "../entity_access_management" }@@ -116,6 +118,7 @@ sqs_client = { path = "../sqs_client", default-features = false, features = ["gmail","search",] }+static_file = { path = "../static_file", features = ["attachment"] }static_file_service_client = { path = "../static_file_service_client" }stream = { path = "../stream" }strum = { workspace = true }diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/context/mod.rsindex ecc6271b87..74c605d167 100644--- a/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/context/mod.rs@@ -1,12 +1,21 @@use crate::config::Config;use crate::service::ai_stream_registry::AiStreamRegistry;use ai_tools::{- AiToolSet, ToolCallToolContext, ToolDocumentToolContext, ToolEmailService,- ToolEmailToolContext, ToolPropertiesToolContext, ToolServiceContext, ToolSoupService,+ AiToolSet, ToolCallToolContext, ToolDocumentService, ToolDocumentToolContext, ToolEmailService,+ ToolEmailToolContext, ToolEntityAccessService, ToolPropertiesToolContext, ToolServiceContext,+ ToolSoupService,};+use attachment::provider::AttachmentProvider;use axum::extract::FromRef;+use chat::domain::service::MessageServiceImpl;+use chat::inbound::attachment::ChatAttachmentService;+use chat::outbound::postgres::PgChatRepo;+use comms::inbound::attachment::CommsAttachmentService;+use comms::outbound::postgres::comms_repo::PgCommsRepo;use connection_gateway::service::connection::ConnectionRepo;use document_storage_service_client::DocumentStorageServiceClient;+use documents::inbound::attachment::DocumentAttachmentService;+use email::inbound::attachment::EmailAttachmentService;use entity_access::{domain::service::EntityAccessServiceImpl, outbound::PgAccessRepository};use macro_auth::middleware::decode_jwt::JwtValidationArgs;use macro_middleware::auth::internal_access::InternalApiSecretKey;@@ -19,12 +28,26 @@ use scribe::{use search_service_client::SearchServiceClient;use secretsmanager_client::LocalOrRemoteSecret;use sqlx::PgPool;+use static_file::inbound::attachment::StaticFileAttachmentService;+use static_file::outbound::CdnStaticFileRepo;use std::sync::{Arc, OnceLock};use stream::domain::StreamRepo;/// Type alias for the entity access service.pub type DcsEntityAccessService = EntityAccessServiceImpl<PgAccessRepository>;+/// Type alias for the attachment provider wired to concrete DCS services.+pub type DcsAttachmentProvider = AttachmentProvider<+ DocumentAttachmentService<ToolDocumentService, ToolEntityAccessService>,+ EmailAttachmentService<ToolEmailService, ToolEntityAccessService>,+ ChatAttachmentService<PgChatRepo, ToolEntityAccessService>,+ CommsAttachmentService<PgCommsRepo, ToolEntityAccessService>,+ StaticFileAttachmentService<CdnStaticFileRepo>,+>;++/// Type alias for the message service wired to concrete DCS services.+pub type DcsMessageService = MessageServiceImpl<PgChatRepo, DcsAttachmentProvider>;+#[cfg(test)]mod test;#[cfg(test)]@@ -64,6 +87,7 @@ pub struct ApiContext {pub all_tools: Arc<AiToolSet>,pub all_tools_prompt: &'static str,pub entity_access_service: Arc<DcsEntityAccessService>,+ pub message_service: Arc<DcsMessageService>,pub ai_stream_registry: AiStreamRegistry,}diff --git a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs b/rust/cloud-storage/document_cognition_service/src/api/context/test.rsindex 9f4870a4c3..2758f0bbf7 100644--- a/rust/cloud-storage/document_cognition_service/src/api/context/test.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/context/test.rs@@ -354,9 +354,9 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Arnotification_ingress_service,connection_repo: MockConnectionRepo::new(),soup_service,- email_service: email_service_for_tools,+ email_service: email_service_for_tools.clone(),stream_repo: MockStreamRepo::new(),- document_tool_context,+ document_tool_context: document_tool_context.clone(),memory_service,properties_tool_context,email_tool_context,@@ -364,7 +364,34 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Artool_service_context,all_tools: all_tools_toolset,all_tools_prompt,- entity_access_service,+ entity_access_service: entity_access_service.clone(),+ message_service: Arc::new(chat::domain::service::MessageServiceImpl::new(+ chat::outbound::postgres::PgChatRepo::new(pool.clone()),+ attachment::provider::AttachmentProvider {+ document: documents::inbound::attachment::DocumentAttachmentService::new(+ document_tool_context.service.clone(),+ document_tool_context.entity_access_service.clone(),+ document_tool_context.lexical_client.clone(),+ ),+ email_thread: email::inbound::attachment::EmailAttachmentService::new(+ email_service_for_tools.clone(),+ entity_access_service.clone(),+ ),+ chat: chat::inbound::attachment::ChatAttachmentService::new(+ Arc::new(chat::outbound::postgres::PgChatRepo::new(pool.clone())),+ entity_access_service.clone(),+ ),+ channel: comms::inbound::attachment::CommsAttachmentService::new(+ Arc::new(PgCommsRepo::new(readonly_pool::ReadOnlyPool(pool.clone()))),+ entity_access_service.clone(),+ ),+ static_file: static_file::inbound::attachment::StaticFileAttachmentService::new(+ Arc::new(static_file::outbound::CdnStaticFileRepo::new(+ "http://localhost".into(),+ )),+ ),+ },+ )),ai_stream_registry: crate::service::ai_stream_registry::AiStreamRegistry::new(Arc::new(redis::Client::open("redis://127.0.0.1:6379/").expect("valid redis url"),)),diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rsindex d932967fc7..dc0f150095 100644--- a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs@@ -15,11 +15,13 @@ use ai::tool::types::StreamPart;use ai::types::{AssistantMessagePart, ChatMessageContent, Model};use ai_tools::RequestContext;use async_stream::stream;+use attachment::FormattedParts;use axum::Json;use axum::extract::{Extension, Request, State};use axum::http::StatusCode;use axum::middleware::Next;use axum::response::IntoResponse;+use chat::domain::ports::MessageService;use chat::inbound::ChatModelAccess;use futures::StreamExt;use macro_auth::headers::AccessTokenExtractor;@@ -140,6 +142,23 @@ pub async fn send_chat_message(Extension(user_context): Extension<UserContext>,Extension(bearer): Extension<BearerToken>,Json(request): Json<HttpSendChatMessageRequest>,+) -> Result<Json<SendChatMessageResponse>, ChatMessageError> {+ Box::pin(send_chat_message_inner(+ state,+ model_access,+ user_context,+ bearer,+ request,+ ))+ .await+}++async fn send_chat_message_inner(+ state: ApiContext,+ model_access: ChatModelAccess,+ user_context: UserContext,+ bearer: BearerToken,+ request: HttpSendChatMessageRequest,) -> Result<Json<SendChatMessageResponse>, ChatMessageError> {let now = std::time::Instant::now();let ctx = Arc::new(state);@@ -224,18 +243,29 @@ pub async fn send_chat_message(},};- // Store the incoming user message- let user_message_id =- store_incoming_message(ctx.clone(), user_id.0.as_ref(), &chat, model, &payload)- .await- .map_err(|err| {- tracing::error!(error=?err, "failed to store incoming message");- ChatMessageError {- error: "Failed to store message".to_string(),- stream_id: Some(stream_id.clone()),- status: None,- }- })?;+ // Store the incoming user message and resolve its attachments+ let resolved = store_incoming_message(ctx.clone(), user_id.0.as_ref(), &chat, model, &payload)+ .await+ .map_err(|err| {+ tracing::error!(error=?err, "failed to store incoming message");+ ChatMessageError {+ error: "Failed to store message".to_string(),+ stream_id: Some(stream_id.clone()),+ status: None,+ }+ })?;+ let user_message_id = resolved.message_id;++ // Fetch all resolved attachment content for the chat (current + prior messages)+ let all_resolved_parts: Vec<FormattedParts> = ctx+ .message_service+ .get_resolved_message_chain(&actual_chat_id)+ .await+ .inspect_err(|e| tracing::error!(error=?e, "failed to fetch resolved message chain"))+ .unwrap_or_default()+ .into_iter()+ .filter_map(|r| r.parts)+ .collect();// Fetch user memory (triggers background generation if stale/missing)let user_memory = ctx@@ -249,15 +279,12 @@ pub async fn send_chat_message(// Build the completion requestlet tools_prompt = choose_tools_prompt(&payload, ctx.all_tools_prompt);let ai_request = build_chat_completion_request(- ctx.clone(),&chat,&payload,tools_prompt,- &jwt_token,user_memory.as_deref(),- (*user_id).clone(),+ all_resolved_parts,)- .await.map_err(|err| {tracing::error!(error=?err, "failed to build chat completion request");ChatMessageError {@@ -620,7 +647,7 @@ fn stream_and_save_message(vec![ai::types::ChatMessage {role: ai::types::Role::Assistant,content: ChatMessageContent::AssistantMessageParts(resolved_parts),- image_urls: None,+ attachments: None,}]}} else {diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/ai_request.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/ai_request.rsindex 3301e0e73e..5f9aa15fa0 100644--- a/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/ai_request.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/ai_request.rs@@ -1,34 +1,26 @@-use crate::{- api::context::ApiContext, core::constants::DEFAULT_MAX_TOKENS,- model::stream::SendChatMessagePayload, service::attachment::fetch,-};+use crate::{core::constants::DEFAULT_MAX_TOKENS, model::stream::SendChatMessagePayload};use crate::model::chats::ChatResponse;use ai::types::{ChatCompletionRequest, MessageBuilder, RequestBuilder};-use anyhow::{Context, Result};-use macro_user_id::user_id::MacroUserIdStr;-use std::sync::Arc;+use anyhow::Result;+use attachment::{AttachmentContent, AttachmentPart, Attachments, FormattedParts, TextOrImage};+use model_entity::EntityType;+use non_empty::NonEmpty;-// fetch documents then build request-#[tracing::instrument(skip(ctx, chat, incoming_message, static_system_prompt, jwt), err)]-pub async fn build_chat_completion_request(- ctx: Arc<ApiContext>,+#[tracing::instrument(+ skip(chat, incoming_message, static_system_prompt, resolved_parts),+ err+)]+pub fn build_chat_completion_request(chat: &ChatResponse,incoming_message: &SendChatMessagePayload,static_system_prompt: &str,- jwt: &str,user_memory: Option<&str>,- user_id: MacroUserIdStr<'static>,+ resolved_parts: Vec<FormattedParts>,) -> Result<ChatCompletionRequest> {- let attachments = fetch::fetchium(- ctx.scribe.clone(),- incoming_message.attachments.clone().unwrap_or_default(),- jwt,- user_id,- )- .await- .context("failed to fetch attachment content")?;+ let attachments = merge_formatted_parts_to_attachments(resolved_parts);+let mut messages = chat.messages.iter()@@ -60,11 +52,37 @@ pub async fn build_chat_completion_request(system_prompt.push_str("\n</user_memory>");}- Ok(RequestBuilder::new()- .attachments(attachments)+ let mut builder = RequestBuilder::new().model(incoming_message.model).messages(messages).system_prompt(system_prompt)- .max_tokens(DEFAULT_MAX_TOKENS)- .build())+ .max_tokens(DEFAULT_MAX_TOKENS);++ if let Some(attachments) = attachments {+ builder = builder.attachments(attachments);+ }++ Ok(builder.build())+}++fn merge_formatted_parts_to_attachments(+ all_parts: Vec<FormattedParts>,+) -> Option<Attachments<'static>> {+ let contents: Vec<_> = all_parts+ .into_iter()+ .flat_map(|parts| parts.into_parts().into_inner())+ .map(|part| {+ let (attachment_part, entity_type) = match part {+ TextOrImage::Text(text) => (AttachmentPart::Content(text), EntityType::Document),+ TextOrImage::Image(data) => (AttachmentPart::Image(data), EntityType::StaticFile),+ };+ Ok(AttachmentContent {+ reference: entity_type.with_entity_string(String::new()),+ name: None,+ content: NonEmpty::one(attachment_part),+ })+ })+ .collect();++ NonEmpty::new(contents).ok().map(Attachments::new)}diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/mod.rsindex 19991821a5..8ac439743b 100644--- a/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/util/chat_message/mod.rs@@ -7,16 +7,16 @@ use crate::{model::stream::SendChatMessagePayload,};-use macro_db_client::dcs::create_chat_message::create_chat_message;-use ai::types::Model;use ai::types::Role;use ai::types::{ChatMessage, ChatMessageContent};use anyhow::{Context, Result};+use chat::domain::models::ResolvedMessageContent;+use chat::domain::ports::MessageService;use model::chat::{NewAttachment, NewChatMessage};use std::sync::Arc;-// Stores the incoming user message in the database+/// Stores the incoming user message and resolves its attachments in one step.#[tracing::instrument(err, skip(ctx, chat, incoming_message), fields(chat_id=?incoming_message.chat_id))]pub async fn store_incoming_message(ctx: Arc<ApiContext>,@@ -24,13 +24,12 @@ pub async fn store_incoming_message(chat: &ChatResponse,model: Model,incoming_message: &SendChatMessagePayload,-) -> Result<String> {+) -> Result<ResolvedMessageContent> {let created_at = chrono::Utc::now();let new_chat_message = NewChatMessage {id: None,content: ChatMessageContent::Text(incoming_message.content.clone()),role: Role::User,- // Attach the current chat attachments to the user messageattachments: incoming_message.attachments.as_ref().map(|attachments| {attachments.iter()@@ -46,22 +45,24 @@ pub async fn store_incoming_message(model,};- let user_message_id =- create_chat_message(ctx.db.clone(), &incoming_message.chat_id, new_chat_message)- .await- .context("failed to create chat message")?;+ let user_id: macro_user_id::user_id::MacroUserIdStr<'static> =+ user_id.to_owned().try_into().map_err(anyhow::Error::msg)?;+ let resolved = ctx+ .message_service+ .create(&user_id, &incoming_message.chat_id, new_chat_message)+ .await+ .context("failed to create chat message")?;- // Send chat message for search processingsearch::send_chat_message_to_search(&ctx,&chat.id,- &user_message_id,- user_id,+ &resolved.message_id,+ user_id.as_ref(),+ created_at,created_at,- created_at, // updated_at = created_at);- Ok(user_message_id)+ Ok(resolved)}/// Stores multiple conversation messages to the database.@@ -85,7 +86,6 @@ pub async fn store_conversation_messages(let created_at = chrono::Utc::now();for message in messages {- // Use the pre-generated ID for the first assistant messagelet id = if !first_id_used && message.role == Role::Assistant {first_id_used = true;first_message_id.clone()@@ -93,30 +93,31 @@ pub async fn store_conversation_messages(None};- let new_chat_message = model::chat::NewChatMessage {+ let new_chat_message = NewChatMessage {id,content: message.content,role: message.role,- attachments: None, // New messages from streaming don't have attachments (they are asssistant messages)+ attachments: None,model,created_at,updated_at: created_at,};- let message_id = create_chat_message(ctx.db.clone(), chat_id, new_chat_message)+ let message_id = ctx+ .message_service+ .store(chat_id, new_chat_message).await.context("failed to create chat message")?;message_ids.push(message_id.clone());- // Send each message for search processingsearch::send_chat_message_to_search(&ctx,chat_id,&message_id,user_id,created_at,- created_at, // updated_at = created_at+ created_at,);}diff --git a/rust/cloud-storage/document_cognition_service/src/core/constants.rs b/rust/cloud-storage/document_cognition_service/src/core/constants.rsindex b846be74e2..db258dff9d 100644--- a/rust/cloud-storage/document_cognition_service/src/core/constants.rs+++ b/rust/cloud-storage/document_cognition_service/src/core/constants.rs@@ -4,8 +4,3 @@ pub const DEFAULT_MAX_TOKENS: u32 = 16000;/// Default batch size for querying documents from rdspub const DEFAULT_DOCUMENT_BATCH_LIMIT: i64 = 1000;--/// The transcript will include messages up to the smaller of-/// CHANNEL_TRANSCRIPT_MAX_MESSAGES or CHANNEL_TRANSCRIPT_MAX_DAYS-/// Maximum number of messages to include in a channel transcript (hard cap)-pub const CHANNEL_TRANSCRIPT_MAX_MESSAGES: i64 = 150;diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rsindex 2454828b69..0db194cf9e 100644--- a/rust/cloud-storage/document_cognition_service/src/main.rs+++ b/rust/cloud-storage/document_cognition_service/src/main.rs@@ -219,7 +219,7 @@ async fn main() -> anyhow::Result<()> {);let document_repo = PgDocumentRepo::new(db.clone());let cloudfront_private_key = match config.environment {- Environment::Local => config.cloudfront_signer_private_key.clone(),+ Environment::Local => config.cloudfront_signer_private_key.replace("\\n", "\n"),_ => secretsmanager_client.get_secret_value(&config.cloudfront_signer_private_key).await@@ -253,6 +253,35 @@ async fn main() -> anyhow::Result<()> {tracing::info!("initialized document tool context");+ let attachment_provider = attachment::provider::AttachmentProvider {+ document: documents::inbound::attachment::DocumentAttachmentService::new(+ document_tool_context.service.clone(),+ document_tool_context.entity_access_service.clone(),+ document_tool_context.lexical_client.clone(),+ ),+ email_thread: email::inbound::attachment::EmailAttachmentService::new(+ email_service_for_tools.clone(),+ entity_access_service.clone(),+ ),+ chat: chat::inbound::attachment::ChatAttachmentService::new(+ Arc::new(chat::outbound::postgres::PgChatRepo::new(db.clone())),+ entity_access_service.clone(),+ ),+ channel: comms::inbound::attachment::CommsAttachmentService::new(+ Arc::new(PgCommsRepo::new(ReadOnlyPool(db.clone()))),+ entity_access_service.clone(),+ ),+ static_file: static_file::inbound::attachment::StaticFileAttachmentService::new(Arc::new(+ static_file::outbound::CdnStaticFileRepo::new(config.static_file_service_url.clone()),+ )),+ };+ let message_service = Arc::new(chat::domain::service::MessageServiceImpl::new(+ chat::outbound::postgres::PgChatRepo::new(db.clone()),+ attachment_provider,+ ));++ tracing::info!("initialized attachment provider");+let email_service_client_external = Arc::new(EmailServiceClientExternal::new(email_service_client.url().to_owned(),));@@ -388,6 +417,7 @@ async fn main() -> anyhow::Result<()> {all_tools: all_tools_toolset,all_tools_prompt,entity_access_service,+ message_service,ai_stream_registry: service::ai_stream_registry::AiStreamRegistry::new(redis_client.clone(),),diff --git a/rust/cloud-storage/document_cognition_service/src/models_bin.rs b/rust/cloud-storage/document_cognition_service/src/models_bin.rsindex 32ed339dbd..86ad384769 100644--- a/rust/cloud-storage/document_cognition_service/src/models_bin.rs+++ b/rust/cloud-storage/document_cognition_service/src/models_bin.rs@@ -1,3 +1,4 @@+#![recursion_limit = "256"]#![allow(unused)]mod api;diff --git a/rust/cloud-storage/document_cognition_service/src/openapi.rs b/rust/cloud-storage/document_cognition_service/src/openapi.rsindex 6f819696a5..09b0b1c676 100644--- a/rust/cloud-storage/document_cognition_service/src/openapi.rs+++ b/rust/cloud-storage/document_cognition_service/src/openapi.rs@@ -1,3 +1,4 @@+#![recursion_limit = "256"]#![allow(unused)]mod api;diff --git a/rust/cloud-storage/document_cognition_service/src/service/attachment/fetch.rs b/rust/cloud-storage/document_cognition_service/src/service/attachment/fetch.rsdeleted file mode 100644index fe3465e86c..0000000000--- a/rust/cloud-storage/document_cognition_service/src/service/attachment/fetch.rs+++ /dev/null@@ -1,139 +0,0 @@-use crate::api::context::DcsScribe;-use crate::core::constants::CHANNEL_TRANSCRIPT_MAX_MESSAGES;-use ai::types::{Attachment, ImageData};-use ai_format::document::Document;-use macro_user_id::user_id::MacroUserIdStr;-use model::{- chat::{AttachmentType, ChatAttachmentWithName},- document::FileTypeExt,-};-use std::sync::Arc;--pub const EMAIL_THREAD_MESSAGE_LIMIT: i64 = 20;-// TODO: @ehayes2000 this needs to return an enumerated error (Not Found | Permission | Internal)-#[tracing::instrument(err, skip(scribe, attachments))]-pub async fn fetchium(- scribe: Arc<DcsScribe>,- attachments: Vec<ChatAttachmentWithName>,- jwt: &str,- user_id: MacroUserIdStr<'static>,-) -> Result<Vec<Attachment>, anyhow::Error> {- // --- closure to fetch single attachment ---- #[tracing::instrument(err, skip(scribe))]- async fn fetchington(- attachment: ChatAttachmentWithName,- scribe: Arc<DcsScribe>,- jwt: &str,- user_id: MacroUserIdStr<'static>,- ) -> Result<Attachment, anyhow::Error> {- match attachment.attachment_type {- AttachmentType::Project => {- // fetch id's of stuff in folder- let project_items = scribe- .document- .fetch_project(attachment.attachment_id.clone())- .content(scribe.document.db(), user_id)- .await?- .to_string();- Ok(Attachment::Text(- Document {- id: attachment.attachment_id.clone(),- file_type: "Project".into(),- name: attachment.name().unwrap_or_default().into(),- content: project_items,- properties: None,- }- .boxed(),- ))- }- AttachmentType::Image => {- let image = scribe- .static_file- .fetch(attachment.attachment_id.clone())- .file_content()- .await?- .content;-- Ok(Attachment::Image(ImageData::try_from(image)?))- }- AttachmentType::Channel => {- let transcript = scribe- .channel- .get_channel_transcript(- attachment.attachment_id.as_str(),- None,- Some(CHANNEL_TRANSCRIPT_MAX_MESSAGES),- )- .await?;-- Ok(Attachment::Text(- Document {- content: transcript,- file_type: "channel".into(),- id: attachment.attachment_id.clone(),- name: "unknown channel name".into(),- properties: None,- }- .boxed(),- ))- }- AttachmentType::Document => {- let document = scribe- .document- .fetch_with_auth(attachment.attachment_id.clone(), jwt.to_string())- .document_content()- .await?;- if document.file_type().is_image() {- Ok(Attachment::Image(ImageData::try_from(document.content)?))- } else {- document- .text_attachment()- .ok_or(anyhow::anyhow!("Expected text content found image"))- .map(Attachment::Text)- }- }- AttachmentType::Email => {- let thread = scribe- .get_email_messages_by_thread_id(- &attachment.attachment_id,- 0,- EMAIL_THREAD_MESSAGE_LIMIT,- )- .await?;-- let subject = thread- .first()- .and_then(|first| first.subject.as_deref())- .unwrap_or("No Subject")- .to_string();-- let content = thread- .iter()- .map(serde_json::to_string_pretty)- .collect::<Result<Vec<_>, _>>()?- .join("\n");-- Ok(Attachment::Text(- Document {- id: attachment.attachment_id,- name: subject.clone(),- file_type: "email".to_string(),- content,- properties: None,- }- .boxed(),- ))- }- }- }-- let futures = attachments- .into_iter()- .map(|attachment| fetchington(attachment, scribe.clone(), jwt, user_id.clone()));-- let results = futures::future::try_join_all(futures).await.inspect_err(- |err| tracing::error!(error=?err, "failed to fetch one or more attachments"),- )?;- Ok(results)-}diff --git a/rust/cloud-storage/document_cognition_service/src/service/attachment/mod.rs b/rust/cloud-storage/document_cognition_service/src/service/attachment/mod.rsdeleted file mode 100644index 0e40308b0a..0000000000--- a/rust/cloud-storage/document_cognition_service/src/service/attachment/mod.rs+++ /dev/null@@ -1 +0,0 @@-pub mod fetch;diff --git a/rust/cloud-storage/document_cognition_service/src/service/mod.rs b/rust/cloud-storage/document_cognition_service/src/service/mod.rsindex 7520c80e28..ae1221f7fd 100644--- a/rust/cloud-storage/document_cognition_service/src/service/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/service/mod.rs@@ -1,5 +1,4 @@pub mod ai_stream_registry;-pub mod attachment;pub mod get_chat;pub mod id_mapping;pub mod notification;diff --git a/rust/cloud-storage/document_text_extractor/Cargo.toml b/rust/cloud-storage/document_text_extractor/Cargo.tomlindex 9f7ef79563..df99c4bc44 100644--- a/rust/cloud-storage/document_text_extractor/Cargo.toml+++ b/rust/cloud-storage/document_text_extractor/Cargo.toml@@ -31,6 +31,7 @@ pdfium-render = { workspace = true }serde = { workspace = true }serde_json = { workspace = true }sqlx = { workspace = true }+tiktoken-rs = "0.5.9"tokio = { workspace = true }tracing = { workspace = true }urlencoding = { workspace = true }diff --git a/rust/cloud-storage/document_text_extractor/src/handler/extract_text_citations.rs b/rust/cloud-storage/document_text_extractor/src/handler/extract_text_citations.rsindex b2fd23f70b..55a5739d0a 100644--- a/rust/cloud-storage/document_text_extractor/src/handler/extract_text_citations.rs+++ b/rust/cloud-storage/document_text_extractor/src/handler/extract_text_citations.rs@@ -210,10 +210,12 @@ pub async fn extract_text_from_document(};let (references, extracted_text) = ref_id_extract_text(&file);- let token_count = ai::tokens::count_tokens(&extracted_text).map_err(|e| {- tracing::error!(error=?e, "unable to count tokens");- Error::from(e)- })?;+ let token_count = tiktoken_rs::o200k_base()+ .map(|enc| enc.encode_with_special_tokens(&extracted_text).len() as i64)+ .map_err(|e| {+ tracing::error!(error=?e, "unable to count tokens");+ Error::from(e)+ })?;db.create_document_text(document_id, &extracted_text, token_count).awaitdiff --git a/rust/cloud-storage/documents/fixtures/documents_test_data.sql b/rust/cloud-storage/documents/fixtures/documents_test_data.sqlindex ac8064c316..ac5acfb645 100644--- a/rust/cloud-storage/documents/fixtures/documents_test_data.sql+++ b/rust/cloud-storage/documents/fixtures/documents_test_data.sql@@ -120,3 +120,47 @@ INSERT INTO public."SharePermission" ("id", "isPublic", "createdAt", "updatedAt"INSERT INTO public."DocumentPermission" ("documentId", "sharePermissionId")(SELECT 'd0000000-0000-0000-0000-000000000002', 'sp-doc-two');++-- Document inside test project (for get_project_children tests)+INSERT INTO public."Document" ("id", "name", "fileType", "owner", "projectId") (+ SELECT+ 'd0000000-0000-0000-0000-000000000003',+ 'project_child_doc',+ 'txt',+ 'macro|[email protected]',+ 'd0000000-0000-0000-0000-100000000001'+);++INSERT INTO public."DocumentInstance" ("revisionName", "documentId", "sha") (+ SELECT 'project_child_doc', 'd0000000-0000-0000-0000-000000000003', 'sha-three'+);++INSERT INTO public."SharePermission" ("id", "isPublic", "createdAt", "updatedAt")+ (SELECT 'sp-doc-three', false, NOW(), NOW());++INSERT INTO public."DocumentPermission" ("documentId", "sharePermissionId")+ (SELECT 'd0000000-0000-0000-0000-000000000003', 'sp-doc-three');++-- Sub-project inside test project (for get_project_children tests)+INSERT INTO public."Project" ("id", "name", "userId", "parentId") (+ SELECT+ 'd0000000-0000-0000-0000-100000000002',+ 'child_project',+ 'macro|[email protected]',+ 'd0000000-0000-0000-0000-100000000001'+);++-- Deleted document inside test project (should be excluded from children)+INSERT INTO public."Document" ("id", "name", "fileType", "owner", "projectId", "deletedAt") (+ SELECT+ 'd0000000-0000-0000-0000-000000000004',+ 'deleted_project_doc',+ 'txt',+ 'macro|[email protected]',+ 'd0000000-0000-0000-0000-100000000001',+ NOW()+);++INSERT INTO public."DocumentInstance" ("revisionName", "documentId", "sha") (+ SELECT 'deleted_project_doc', 'd0000000-0000-0000-0000-000000000004', 'sha-four'+);diff --git a/rust/cloud-storage/documents/src/domain/ports.rs b/rust/cloud-storage/documents/src/domain/ports.rsindex e9d735554b..90960320d9 100644--- a/rust/cloud-storage/documents/src/domain/ports.rs+++ b/rust/cloud-storage/documents/src/domain/ports.rs@@ -15,6 +15,8 @@ use model::document::{ContentType, DocumentBasic, DocumentMetadata};use model::sync_service::SyncServiceVersionID;+use model_entity::Entity;+use super::models::{CommentThread, CopyDocumentRepoArgs, CreateDocumentRepoArgs, CreateTaskRequest,CreateTaskResponse, DocumentError, EditDocumentRepoArgs, EditDocumentServiceArgs,@@ -150,6 +152,18 @@ pub trait DocumentRepo: Send + Sync + 'static {project_id: &str,) -> impl Future<Output = Result<MacroUserIdStr<'static>, Self::Err>> + Send;+ /// Get the name of a project by ID.+ fn get_project_name(+ &self,+ project_id: &str,+ ) -> impl Future<Output = Result<String, Self::Err>> + Send;++ /// Get the top-level children (documents and sub-projects) of a project.+ fn get_project_children(+ &self,+ project_id: &str,+ ) -> impl Future<Output = Result<Vec<Entity<'static>>, Self::Err>> + Send;+/// Copy a document's DB records in a single transaction.////// Creates: Document row, version (DocumentBom or DocumentInstance),@@ -312,6 +326,18 @@ pub trait DocumentService: Send + Sync + 'static {sync_version_id: Option<SyncServiceVersionID>,) -> impl Future<Output = Result<model::document::response::DocumentResponse, DocumentError>> + Send;+ /// Get the name of a project by ID.+ fn get_project_name(+ &self,+ project_id: &str,+ ) -> impl Future<Output = Result<String, DocumentError>> + Send;++ /// Get the top-level children (documents and sub-projects) of a project.+ fn get_project_children(+ &self,+ project_id: &str,+ ) -> impl Future<Output = Result<Vec<Entity<'static>>, DocumentError>> + Send;+/// Create a task document and optionally set property values on it.fn create_task(&self,diff --git a/rust/cloud-storage/documents/src/domain/service.rs b/rust/cloud-storage/documents/src/domain/service.rsindex 288c559ce1..f5175b19f6 100644--- a/rust/cloud-storage/documents/src/domain/service.rs+++ b/rust/cloud-storage/documents/src/domain/service.rs@@ -489,6 +489,25 @@ impl<.map_err(|e| DocumentError::Internal(e.into()))}+ #[tracing::instrument(err, skip(self))]+ async fn get_project_name(&self, project_id: &str) -> Result<String, DocumentError> {+ self.repo+ .get_project_name(project_id)+ .await+ .map_err(|e| DocumentError::Internal(e.into()))+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_project_children(+ &self,+ project_id: &str,+ ) -> Result<Vec<model_entity::Entity<'static>>, DocumentError> {+ self.repo+ .get_project_children(project_id)+ .await+ .map_err(|e| DocumentError::Internal(e.into()))+ }+async fn get_short_id(&self,entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,diff --git a/rust/cloud-storage/documents/src/inbound/attachment/markdown.rs b/rust/cloud-storage/documents/src/inbound/attachment/markdown.rsindex b8c7102bc7..7ad996bc8c 100644--- a/rust/cloud-storage/documents/src/inbound/attachment/markdown.rs+++ b/rust/cloud-storage/documents/src/inbound/attachment/markdown.rs@@ -1,9 +1,7 @@//! Markdown document resolution via the lexical client.-use ai::types::ImageData;-use attachment::{- AttachmentContent, AttachmentError, AttachmentPart, AttachmentReference, ResolutionError,-};+use attachment::image::ImageData;+use attachment::{AttachmentContent, AttachmentError, AttachmentPart, ResolutionError};use entity_access::domain::ports::EntityAccessService;use futures::future::join_all;use lexical_client::types::NewMdNode;@@ -23,7 +21,7 @@ pub(super) async fn resolve_markdown<DSvc: DocumentService, ESvc: EntityAccessSeuser_id: &MacroUserIdStr<'_>,id: &str,document: &DocumentBasic,-) -> Result<AttachmentContent, AttachmentError> {+) -> Result<AttachmentContent<'static>, AttachmentError> {let response = svc.lexical_client.parse_cognition_v2(id)@@ -42,7 +40,7 @@ pub(super) async fn resolve_markdown<DSvc: DocumentService, ESvc: EntityAccessSelet content = NonEmpty::new(parts).map_err(|_| AttachmentError::NoContent)?;Ok(AttachmentContent {- reference: AttachmentReference::DssFile { id: id.to_string() },+ reference: EntityType::Document.with_entity_string(id.to_string()),name: Some(document.document_name.clone()),content,})@@ -52,18 +50,16 @@ async fn resolve_dss_image<DSvc: DocumentService, ESvc: EntityAccessService>(svc: &DocumentAttachmentService<DSvc, ESvc>,user_id: &MacroUserIdStr<'_>,image_id: &str,-) -> AttachmentPart {- let reference = AttachmentReference::DssFile {- id: image_id.to_string(),- };- let result = try_resolve_dss_image(svc, user_id, image_id)- .await- .map(|data| AttachmentContent {+) -> AttachmentPart<'static> {+ let reference = EntityType::Document.with_entity_string(image_id.to_string());+ let result = match try_resolve_dss_image(svc, user_id, image_id).await {+ Ok(data) => Ok(AttachmentContent {reference,name: None,- content: NonEmpty::new(vec![AttachmentPart::Image(data)]).expect("single element"),- })- .map_err(|error| ResolutionError::new(image_id.to_string(), error));+ content: NonEmpty::one(AttachmentPart::Image(data)),+ }),+ Err(error) => Err(ResolutionError::new(reference, error)),+ };AttachmentPart::Child(Box::new(result))}@@ -87,18 +83,16 @@ async fn try_resolve_dss_image<DSvc: DocumentService, ESvc: EntityAccessService>svc.get_image_from_location(&document, receipt).await}-async fn resolve_static_image(url: &str) -> AttachmentPart {- let reference = AttachmentReference::SfsImage {- url: url.to_string(),- };- let result = try_resolve_static_image(url)- .await- .map(|data| AttachmentContent {+async fn resolve_static_image(url: &str) -> AttachmentPart<'static> {+ let reference = EntityType::StaticFile.with_entity_string(url.to_string());+ let result = match try_resolve_static_image(url).await {+ Ok(data) => Ok(AttachmentContent {reference,name: None,- content: NonEmpty::new(vec![AttachmentPart::Image(data)]).expect("single element"),- })- .map_err(|error| ResolutionError::new(url.to_string(), error));+ content: NonEmpty::one(AttachmentPart::Image(data)),+ }),+ Err(error) => Err(ResolutionError::new(reference, error)),+ };AttachmentPart::Child(Box::new(result))}diff --git a/rust/cloud-storage/documents/src/inbound/attachment/service.rs b/rust/cloud-storage/documents/src/inbound/attachment/service.rsindex 361cc504bd..cc019a4759 100644--- a/rust/cloud-storage/documents/src/inbound/attachment/service.rs+++ b/rust/cloud-storage/documents/src/inbound/attachment/service.rs@@ -3,10 +3,10 @@use std::str::FromStr;use std::sync::Arc;-use ai::types::ImageData;+use attachment::image::ImageData;use attachment::{- AttachmentContent, AttachmentError, AttachmentPart, AttachmentReference, AttachmentService,- Attachments, ResolutionError,+ AttachmentContent, AttachmentError, AttachmentPart, AttachmentService, Attachments,+ ResolutionError,};use entity_access::domain::{models::{EntityAccessReceipt, ViewAccessLevel},@@ -16,7 +16,7 @@ use futures::future::join_all;use lexical_client::LexicalClient;use macro_user_id::user_id::MacroUserIdStr;use model::document::DocumentBasic;-use model_entity::EntityType;+use model_entity::{Entity, EntityType};use model_file_type::{FileAssociation, FileType};use non_empty::NonEmpty;@@ -50,30 +50,85 @@ impl<DSvc: DocumentService, ESvc: EntityAccessService> AttachmentServicefor DocumentAttachmentService<DSvc, ESvc>{#[tracing::instrument(skip_all)]- async fn resolve_attachments(+ async fn resolve_attachments<'a>(&self,user_id: MacroUserIdStr<'_>,- ids: NonEmpty<&[&str]>,- ) -> Attachments {+ ids: NonEmpty<&[&'a Entity<'a>]>,+ ) -> Attachments<'a> {let user_id = &user_id;- let results = join_all(ids.iter().map(|id| async move {- self.resolve_one(user_id, id)- .await- .map_err(|error| ResolutionError::new(id.to_string(), error))+ let results = join_all(ids.iter().map(|entity| async move {+ let owned_ref = entity+ .entity_type+ .with_entity_string(entity.entity_id.to_string());+ match entity.entity_type {+ EntityType::Document => self+ .resolve_document(user_id, &entity.entity_id)+ .await+ .map_err(|error| ResolutionError::new(owned_ref, error)),+ EntityType::Project => self+ .resolve_project(user_id, &entity.entity_id)+ .await+ .map_err(|error| ResolutionError::new(owned_ref, error)),+ other => Err(ResolutionError::new(+ owned_ref,+ AttachmentError::RoutingError("DocumentAttachmentService".to_string(), other),+ )),+ }})).await;-Attachments::new(NonEmpty::new(results).expect("ids was non-empty"))}}impl<DSvc: DocumentService, ESvc: EntityAccessService> DocumentAttachmentService<DSvc, ESvc> {#[tracing::instrument(skip(self), err)]- async fn resolve_one(+ async fn resolve_project(+ &self,+ user_id: &MacroUserIdStr<'_>,+ id: &str,+ ) -> Result<AttachmentContent<'static>, AttachmentError> {+ self.entity_access_service+ .generate_entity_access_receipt::<ViewAccessLevel>(+ user_id,+ None,+ id,+ EntityType::Project,+ )+ .await+ .map_err(|e| AttachmentError::PermissionDenied(Box::new(e)))?;++ let name = self+ .document_service+ .get_project_name(id)+ .await+ .map_err(|e| AttachmentError::Internal(e.into()))?;++ let children = self+ .document_service+ .get_project_children(id)+ .await+ .map_err(|e| AttachmentError::Internal(e.into()))?;++ let content: Vec<AttachmentPart<'static>> = children+ .into_iter()+ .map(AttachmentPart::ChildReference)+ .collect();++ let content = NonEmpty::new(content).map_err(|_| AttachmentError::NoContent)?;++ Ok(AttachmentContent {+ reference: EntityType::Project.with_entity_string(id.to_string()),+ name: Some(name),+ content,+ })+ }++ #[tracing::instrument(skip(self), err)]+ async fn resolve_document(&self,user_id: &MacroUserIdStr<'_>,id: &str,- ) -> Result<AttachmentContent, AttachmentError> {+ ) -> Result<AttachmentContent<'static>, AttachmentError> {let receipt = self.entity_access_service.generate_entity_access_receipt(user_id, None, id, EntityType::Document)@@ -84,7 +139,7 @@ impl<DSvc: DocumentService, ESvc: EntityAccessService> DocumentAttachmentService.document_service.internal_get_basic_document(id).await- .map_err(|e| AttachmentError::Internal(e.into()))?;+ .map_err(|e| AttachmentError::PermissionDenied(Box::new(e)))?;let file_type = document.file_type@@ -94,33 +149,33 @@ impl<DSvc: DocumentService, ESvc: EntityAccessService> DocumentAttachmentServiceFileType::from_str(ft).map_err(|_| AttachmentError::UnsupportedFileType(ft.clone()))})?;- let parts = match file_type.macro_app_path() {+ let content = match file_type.macro_app_path() {FileAssociation::Pdf(_) | FileAssociation::Write(_) => {let text = self.document_service.get_document_text(receipt).await.map_err(|e| AttachmentError::Internal(e.into()))?;- vec![AttachmentPart::Content(text)]+ NonEmpty::one(AttachmentPart::Content(text))}FileAssociation::Md(_) => {return markdown::resolve_markdown(self, user_id, id, &document).await;}FileAssociation::Code(_) | FileAssociation::Document(_) => {let text = self.get_text_from_location(&document, receipt).await?;- vec![AttachmentPart::Content(text)]+ NonEmpty::one(AttachmentPart::Content(text))}FileAssociation::Image(_) => {let data = self.get_image_from_location(&document, receipt).await?;- vec![AttachmentPart::Image(data)]+ NonEmpty::one(AttachmentPart::Image(data))}_ => return Err(AttachmentError::UnsupportedFileType(file_type.to_string())),};Ok(AttachmentContent {- reference: AttachmentReference::DssFile { id: id.to_string() },+ reference: EntityType::Document.with_entity_string(id.to_string()),name: Some(document.document_name.clone()),- content: NonEmpty::new(parts).expect("parts has one element"),+ content,})}diff --git a/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs b/rust/cloud-storage/documents/src/outbound/pg_document_repo.rsindex 235ec2e532..673e40296c 100644--- a/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs+++ b/rust/cloud-storage/documents/src/outbound/pg_document_repo.rs@@ -15,6 +15,8 @@ use macro_user_id::{cowlike::CowLike, user_id::MacroUserIdStr};use model::document::{DocumentBasic, DocumentMetadata};use sqlx::PgPool;+use model_entity::{Entity, EntityType};+use crate::domain::models::{Comment, CommentThread, CopyDocumentRepoArgs, CreateDocumentRepoArgs, EditDocumentRepoArgs,Thread,@@ -697,6 +699,44 @@ impl DocumentRepo for PgDocumentRepo {.map_err(|e| sqlx::Error::Decode(Box::new(e)))}+ #[tracing::instrument(err, skip(self))]+ async fn get_project_name(&self, project_id: &str) -> Result<String, Self::Err> {+ let row = sqlx::query!(r#"SELECT name FROM "Project" WHERE id = $1"#, project_id,)+ .fetch_one(&self.pool)+ .await?;+ Ok(row.name)+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_project_children(+ &self,+ project_id: &str,+ ) -> Result<Vec<Entity<'static>>, Self::Err> {+ let documents = sqlx::query!(+ r#"SELECT id FROM "Document" WHERE "projectId" = $1 AND "deletedAt" IS NULL"#,+ project_id,+ )+ .fetch_all(&self.pool)+ .await?;++ let sub_projects = sqlx::query!(+ r#"SELECT id FROM "Project" WHERE "parentId" = $1 AND "deletedAt" IS NULL"#,+ project_id,+ )+ .fetch_all(&self.pool)+ .await?;++ let mut children: Vec<Entity<'static>> =+ Vec::with_capacity(documents.len() + sub_projects.len());+ for row in documents {+ children.push(EntityType::Document.with_entity_string(row.id));+ }+ for row in sub_projects {+ children.push(EntityType::Project.with_entity_string(row.id));+ }+ Ok(children)+ }+#[tracing::instrument(err, skip(self, args))]async fn copy_document(&self,diff --git a/rust/cloud-storage/documents/src/outbound/pg_document_repo/tests.rs b/rust/cloud-storage/documents/src/outbound/pg_document_repo/tests.rsindex ebbeb225a3..e0e56b7cc1 100644--- a/rust/cloud-storage/documents/src/outbound/pg_document_repo/tests.rs+++ b/rust/cloud-storage/documents/src/outbound/pg_document_repo/tests.rs@@ -1,4 +1,5 @@use macro_db_migrator::MACRO_DB_MIGRATIONS;+use model_entity::EntityType;use models_permissions::share_permission::UpdateSharePermissionRequestV2;use models_permissions::share_permission::access_level::AccessLevel;use models_permissions::share_permission::channel_share_permission::{@@ -873,3 +874,62 @@ async fn test_comment_deletion(pool: Pool<Postgres>) -> anyhow::Result<()> {Ok(())}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))+)]+async fn test_get_project_name(pool: Pool<Postgres>) {+ let repo = PgDocumentRepo::new(pool);++ let name = repo+ .get_project_name("d0000000-0000-0000-0000-100000000001")+ .await+ .unwrap();+ assert_eq!(name, "test_project_name");++ let result = repo.get_project_name("nonexistent").await;+ assert!(result.is_err());+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))+)]+async fn test_get_project_children(pool: Pool<Postgres>) {+ let repo = PgDocumentRepo::new(pool);++ let children = repo+ .get_project_children("d0000000-0000-0000-0000-100000000001")+ .await+ .unwrap();++ assert_eq!(children.len(), 2);++ let has_doc = children.iter().any(|e| {+ e.entity_type == EntityType::Document+ && e.entity_id == "d0000000-0000-0000-0000-000000000003"+ });+ assert!(has_doc, "should include the child document");++ let has_sub_project = children.iter().any(|e| {+ e.entity_type == EntityType::Project+ && e.entity_id == "d0000000-0000-0000-0000-100000000002"+ });+ assert!(has_sub_project, "should include the sub-project");+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "../../../fixtures", scripts("documents_test_data"))+)]+async fn test_get_project_children_empty(pool: Pool<Postgres>) {+ let repo = PgDocumentRepo::new(pool);++ let children = repo+ .get_project_children("d0000000-0000-0000-0000-100000000002")+ .await+ .unwrap();++ assert!(children.is_empty());+}diff --git a/rust/cloud-storage/email/src/inbound/attachment.rs b/rust/cloud-storage/email/src/inbound/attachment.rsindex 2198232137..f13c13e8b9 100644--- a/rust/cloud-storage/email/src/inbound/attachment.rs+++ b/rust/cloud-storage/email/src/inbound/attachment.rs@@ -3,15 +3,13 @@use std::sync::Arc;use attachment::{- AttachmentContent, AttachmentError, AttachmentPart, AttachmentReference, AttachmentService,- Attachments, ResolutionError,-};-use entity_access::domain::{- models::{EntityType, ViewAccessLevel},- ports::EntityAccessService,+ AttachmentContent, AttachmentError, AttachmentPart, AttachmentService, Attachments,+ ResolutionError,};+use entity_access::domain::{models::ViewAccessLevel, ports::EntityAccessService};use futures::future::join_all;use macro_user_id::user_id::MacroUserIdStr;+use model_entity::{Entity, EntityType};use non_empty::NonEmpty;use uuid::Uuid;@@ -42,16 +40,21 @@ impl<Svc: EmailService, ESvc: EntityAccessService> AttachmentServicefor EmailAttachmentService<Svc, ESvc>{#[tracing::instrument(skip_all)]- async fn resolve_attachments(+ async fn resolve_attachments<'a>(&self,user_id: MacroUserIdStr<'_>,- ids: NonEmpty<&[&str]>,- ) -> Attachments {+ ids: NonEmpty<&[&'a Entity<'a>]>,+ ) -> Attachments<'a> {let user_id = &user_id;- let results = join_all(ids.iter().map(|id| async move {- self.resolve_one(user_id, id)- .await- .map_err(|error| ResolutionError::new(id.to_string(), error))+ let results = join_all(ids.iter().map(|entity| async move {+ self.resolve_one(user_id, entity).await.map_err(|error| {+ ResolutionError::new(+ entity+ .entity_type+ .with_entity_string(entity.entity_id.to_string()),+ error,+ )+ })})).await;@@ -64,8 +67,9 @@ impl<Svc: EmailService, ESvc: EntityAccessService> EmailAttachmentService<Svc, Easync fn resolve_one(&self,user_id: &MacroUserIdStr<'_>,- id: &str,- ) -> Result<AttachmentContent, AttachmentError> {+ entity: &Entity<'_>,+ ) -> Result<AttachmentContent<'static>, AttachmentError> {+ let id = &*entity.entity_id;let thread_id = Uuid::parse_str(id).map_err(|e| AttachmentError::Internal(anyhow::anyhow!("invalid thread ID: {e}")))?;@@ -78,7 +82,7 @@ impl<Svc: EmailService, ESvc: EntityAccessService> EmailAttachmentService<Svc, EEntityType::EmailThread,).await- .map_err(|_| AttachmentError::PermissionDenied { id: id.to_string() })?;+ .map_err(|e| AttachmentError::PermissionDenied(Box::new(e)))?;let thread = self.service@@ -93,25 +97,29 @@ impl<Svc: EmailService, ESvc: EntityAccessService> EmailAttachmentService<Svc, E}}-fn format_thread(id: &str, thread: &ParsedThread) -> Result<AttachmentContent, AttachmentError> {+fn format_thread(+ id: &str,+ thread: &ParsedThread,+) -> Result<AttachmentContent<'static>, AttachmentError> {let subject = thread.messages.first().and_then(|m| m.subject.as_deref()).map(String::from);- let parts: Vec<AttachmentPart> = thread.messages.iter().flat_map(format_message).collect();+ let parts: Vec<AttachmentPart<'static>> =+ thread.messages.iter().flat_map(format_message).collect();let content = NonEmpty::new(parts).map_err(|_| AttachmentError::NoContent)?;Ok(AttachmentContent {- reference: AttachmentReference::EmailThread { id: id.to_string() },+ reference: EntityType::EmailThread.with_entity_string(id.to_string()),name: subject,content,})}-fn format_message(msg: &ParsedMessage) -> Vec<AttachmentPart> {+fn format_message(msg: &ParsedMessage) -> Vec<AttachmentPart<'static>> {let mut parts = Vec::new();if let Some(subject) = &msg.subject {diff --git a/rust/cloud-storage/github/Cargo.toml b/rust/cloud-storage/github/Cargo.tomlindex ec16940ee4..c0665bba08 100644--- a/rust/cloud-storage/github/Cargo.toml+++ b/rust/cloud-storage/github/Cargo.toml@@ -56,6 +56,7 @@ tokio = { workspace = true, features = ["sync"], optional = true }axum = { workspace = true, optional = true }axum-extra = { workspace = true, optional = true }model-error-response = { path = "../model-error-response", optional = true }+model-entity = { path = "../model-entity"}utoipa = { workspace = true, optional = true }[dev-dependencies]diff --git a/rust/cloud-storage/github/src/domain/service/sync/test.rs b/rust/cloud-storage/github/src/domain/service/sync/test.rsindex dd982a96d8..2ae34d797f 100644--- a/rust/cloud-storage/github/src/domain/service/sync/test.rs+++ b/rust/cloud-storage/github/src/domain/service/sync/test.rs@@ -22,6 +22,7 @@ use model::document::{DocumentBasic, DocumentMetadata,response::{CreateDocumentResponseData, GetDocumentResponseData, LocationResponseV3},};+use model_entity::Entity;use models_permissions::share_permission::access_level::AccessLevel;use super::*;@@ -117,6 +118,15 @@ impl DocumentService for StubDocumentService {) -> Result<String, DocumentError> {unimplemented!()}+ async fn get_project_children(+ &self,+ project_id: &str,+ ) -> Result<Vec<Entity<'static>>, DocumentError> {+ unimplemented!()+ }+ async fn get_project_name(&self, project_id: &str) -> Result<String, DocumentError> {+ unimplemented!()+ }async fn get_document(&self,receipt: EntityAccessReceipt<ViewAccessLevel>,diff --git a/rust/cloud-storage/macro_db_client/migrations/20260425120000_resolved_message_content.down.sql b/rust/cloud-storage/macro_db_client/migrations/20260425120000_resolved_message_content.down.sqlnew file mode 100644index 0000000000..341dd574da--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260425120000_resolved_message_content.down.sql@@ -0,0 +1 @@+DROP TABLE IF EXISTS resolved_message_content;diff --git a/rust/cloud-storage/macro_db_client/migrations/20260425120000_resolved_message_content.up.sql b/rust/cloud-storage/macro_db_client/migrations/20260425120000_resolved_message_content.up.sqlnew file mode 100644index 0000000000..95610805da--- /dev/null+++ b/rust/cloud-storage/macro_db_client/migrations/20260425120000_resolved_message_content.up.sql@@ -0,0 +1,9 @@+CREATE TABLE IF NOT EXISTS resolved_message_content (+ "id" UUID PRIMARY KEY DEFAULT gen_random_uuid(),+ "messageId" TEXT NOT NULL UNIQUE REFERENCES "ChatMessage"("id") ON DELETE CASCADE,+ "content" JSONB NOT NULL,+ "createdAt" TIMESTAMPTZ NOT NULL DEFAULT NOW()+);++CREATE INDEX IF NOT EXISTS "idx_resolved_message_content_message_id"+ ON resolved_message_content ("messageId");diff --git a/rust/cloud-storage/macro_db_client/scripts/backfill_resolved_user_messages.sql b/rust/cloud-storage/macro_db_client/scripts/backfill_resolved_user_messages.sqlnew file mode 100644index 0000000000..7ed5a624e0--- /dev/null+++ b/rust/cloud-storage/macro_db_client/scripts/backfill_resolved_user_messages.sql@@ -0,0 +1,36 @@+-- Backfill ResolvedUserMessage for existing user messages.+--+-- For each user message that does not yet have a resolved counterpart,+-- insert a single text part containing the message content.+--+-- Usage:+-- psql $DATABASE_URL -f backfill_resolved_user_messages.sql++INSERT INTO "ResolvedUserMessage" ("messageId", "content")+SELECT+ cm."id",+ CASE+ -- ChatMessageContent::Text is stored as a JSON string directly+ WHEN jsonb_typeof(cm."content") = 'string' THEN+ jsonb_build_array(jsonb_build_object(+ 'type', 'text',+ 'content', cm."content" #>> '{}'+ ))+ -- ChatMessageContent::Text is stored as {"Text": "..."} (tagged enum)+ WHEN cm."content" ? 'Text' THEN+ jsonb_build_array(jsonb_build_object(+ 'type', 'text',+ 'content', cm."content" ->> 'Text'+ ))+ -- Fallback: stringify whatever is there+ ELSE+ jsonb_build_array(jsonb_build_object(+ 'type', 'text',+ 'content', cm."content"::text+ ))+ END+FROM "ChatMessage" cm+WHERE cm."role" = 'user'+ AND NOT EXISTS (+ SELECT 1 FROM "ResolvedUserMessage" rum WHERE rum."messageId" = cm."id"+ );diff --git a/rust/cloud-storage/non_empty/Cargo.toml b/rust/cloud-storage/non_empty/Cargo.tomlindex aada25b916..a90ef3e864 100644--- a/rust/cloud-storage/non_empty/Cargo.toml+++ b/rust/cloud-storage/non_empty/Cargo.toml@@ -5,3 +5,4 @@ edition = "2024"publish = false[dependencies]+serde = { workspace = true }diff --git a/rust/cloud-storage/non_empty/src/lib.rs b/rust/cloud-storage/non_empty/src/lib.rsindex 5671b8e970..c7efa3e5bc 100644--- a/rust/cloud-storage/non_empty/src/lib.rs+++ b/rust/cloud-storage/non_empty/src/lib.rs@@ -1,5 +1,6 @@//! Wrapper around types that implement IsEmpty trait to ensure they are non-empty.+use serde::{Deserialize, Serialize};use std::fmt;use std::ops::Deref;@@ -45,11 +46,19 @@ impl std::error::Error for EmptyError {}/// // Can use HashMap methods directly via Deref/// assert_eq!(non_empty_map["key"], "value");/// ```-#[derive(Debug, Clone, PartialEq, Eq)]+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(transparent)]pub struct NonEmpty<T> {inner: T,}+impl<T> NonEmpty<Vec<T>> {+ /// Create a new `NonEmpty` wrapper with one element+ pub fn one(value: T) -> Self {+ Self { inner: vec![value] }+ }+}+impl<T> NonEmpty<T>whereT: IsEmpty,diff --git a/rust/cloud-storage/scheduled_action/src/outbound/inprocess_executor/agent_task.rs b/rust/cloud-storage/scheduled_action/src/outbound/inprocess_executor/agent_task.rsindex beb858ecd5..9d41e439d2 100644--- a/rust/cloud-storage/scheduled_action/src/outbound/inprocess_executor/agent_task.rs+++ b/rust/cloud-storage/scheduled_action/src/outbound/inprocess_executor/agent_task.rs@@ -140,7 +140,7 @@ async fn run_tool_loop(.model(agent_task.model).messages(vec![ChatMessage {content: ChatMessageContent::Text(agent_task.user_prompt.clone()),- image_urls: None,+ attachments: None,role: Role::User,}]).system_prompt(system_prompt)diff --git a/rust/cloud-storage/scribe/Cargo.toml b/rust/cloud-storage/scribe/Cargo.tomlindex d21a3d597c..b9cd57494c 100644--- a/rust/cloud-storage/scribe/Cargo.toml+++ b/rust/cloud-storage/scribe/Cargo.toml@@ -47,6 +47,7 @@ uuid = { workspace = true }# Internal dependenciesai = { path = "../ai" }ai_format = { path = "../ai_format" }+attachment = { path = "../attachment" }macro_client_errors = { path = "../macro_client_errors" }model = { path = "../model" }models_dcs = { path = "../models_dcs" }diff --git a/rust/cloud-storage/scribe/src/document/types.rs b/rust/cloud-storage/scribe/src/document/types.rsindex b55830f74e..58fc930bae 100644--- a/rust/cloud-storage/scribe/src/document/types.rs+++ b/rust/cloud-storage/scribe/src/document/types.rs@@ -1,5 +1,5 @@-use ai::types::ImageData;use anyhow::{Error, bail};+use attachment::image::ImageData;use bytes::Bytes;use lexical_client::types::CognitionResponseData;use model::document::response::LocationResponseV3;diff --git a/rust/cloud-storage/scribe/src/static_file/types.rs b/rust/cloud-storage/scribe/src/static_file/types.rsindex 55277c3654..389ff09294 100644--- a/rust/cloud-storage/scribe/src/static_file/types.rs+++ b/rust/cloud-storage/scribe/src/static_file/types.rs@@ -1,5 +1,5 @@-use ai::types::ImageData;use anyhow::{Error, bail};+use attachment::image::ImageData;use model::document::{ContentType, ContentTypeExt};use models_sfs::FileMetadata;diff --git a/rust/cloud-storage/static_file/Cargo.toml b/rust/cloud-storage/static_file/Cargo.tomlnew file mode 100644index 0000000000..dc6f5fa25e--- /dev/null+++ b/rust/cloud-storage/static_file/Cargo.toml@@ -0,0 +1,27 @@+[package]+edition = "2024"+name = "static_file"+publish = false+version = "0.1.0"++[features]+default = ["outbound"]+attachment = ["dep:futures", "dep:attachment", "dep:model-entity"]+outbound = ["dep:reqwest"]++[dependencies]+anyhow = { workspace = true }+mime = "0.3"+tracing = { workspace = true }++# Domain+macro_user_id = { path = "../macro_user_id" }++# Attachment+attachment = { path = "../attachment", optional = true }+futures = { workspace = true, optional = true }+model-entity = { path = "../model-entity", optional = true }+non_empty = { path = "../non_empty" }++# Outbound+reqwest = { workspace = true, optional = true }diff --git a/rust/cloud-storage/static_file/src/domain/mod.rs b/rust/cloud-storage/static_file/src/domain/mod.rsnew file mode 100644index 0000000000..fca91f51d4--- /dev/null+++ b/rust/cloud-storage/static_file/src/domain/mod.rs@@ -0,0 +1,3 @@+//! Domain layer.++pub mod ports;diff --git a/rust/cloud-storage/static_file/src/domain/ports.rs b/rust/cloud-storage/static_file/src/domain/ports.rsnew file mode 100644index 0000000000..2435b9c5f3--- /dev/null+++ b/rust/cloud-storage/static_file/src/domain/ports.rs@@ -0,0 +1,15 @@+//! Domain ports for the static file service.++use std::future::Future;++/// Port for fetching static files.+pub trait StaticFileRepo: Send + Sync + 'static {+ /// Get the content type of a file without downloading the body.+ fn content_type(+ &self,+ file_id: &str,+ ) -> impl Future<Output = anyhow::Result<mime::Mime>> + Send;++ /// Download the file bytes.+ fn read(&self, file_id: &str) -> impl Future<Output = anyhow::Result<Vec<u8>>> + Send;+}diff --git a/rust/cloud-storage/static_file/src/inbound/attachment.rs b/rust/cloud-storage/static_file/src/inbound/attachment.rsnew file mode 100644index 0000000000..28d58aee1c--- /dev/null+++ b/rust/cloud-storage/static_file/src/inbound/attachment.rs@@ -0,0 +1,106 @@+//! [`AttachmentService`] implementation for static files.++use std::sync::Arc;++use attachment::{+ AttachmentContent, AttachmentError, AttachmentPart, AttachmentService, Attachments,+ ResolutionError, image::ImageData,+};+use futures::future::join_all;+use macro_user_id::user_id::MacroUserIdStr;+use model_entity::{Entity, EntityType};+use non_empty::NonEmpty;++use crate::domain::ports::StaticFileRepo;++/// Resolves [`EntityType::StaticFile`] references into [`Attachments`].+pub struct StaticFileAttachmentService<R> {+ repo: Arc<R>,+}++impl<R> StaticFileAttachmentService<R> {+ /// Create a new static file attachment service.+ pub fn new(repo: Arc<R>) -> Self {+ Self { repo }+ }+}++impl<R: StaticFileRepo> AttachmentService for StaticFileAttachmentService<R> {+ #[tracing::instrument(skip_all)]+ async fn resolve_attachments<'a>(+ &self,+ _user_id: MacroUserIdStr<'_>,+ ids: NonEmpty<&[&'a Entity<'a>]>,+ ) -> Attachments<'a> {+ let results = join_all(ids.iter().map(|entity| async move {+ self.resolve_one(entity).await.map_err(|error| {+ ResolutionError::new(+ entity+ .entity_type+ .with_entity_string(entity.entity_id.to_string()),+ error,+ )+ })+ }))+ .await;++ Attachments::new(NonEmpty::new(results).expect("ids was non-empty"))+ }+}++impl<R: StaticFileRepo> StaticFileAttachmentService<R> {+ #[tracing::instrument(skip(self), err)]+ async fn resolve_one<'a>(+ &self,+ entity: &'a Entity<'a>,+ ) -> Result<AttachmentContent<'a>, AttachmentError> {+ if entity.entity_type != EntityType::StaticFile {+ return Err(AttachmentError::RoutingError(+ "StaticFileAttachmentService".to_string(),+ entity.entity_type,+ ));+ }++ let file_id = &*entity.entity_id;++ let content_type = self+ .repo+ .content_type(file_id)+ .await+ .map_err(AttachmentError::Internal)?;++ let is_image = content_type.type_() == mime::IMAGE;+ let is_text = content_type.type_() == mime::TEXT;++ if !is_image && !is_text {+ return Err(AttachmentError::UnsupportedFileType(+ content_type.to_string(),+ ));+ }++ let bytes = self+ .repo+ .read(file_id)+ .await+ .map_err(AttachmentError::Internal)?;++ let part = if is_image {+ AttachmentPart::Image(+ ImageData::try_from_bytes(bytes).map_err(AttachmentError::Internal)?,+ )+ } else {+ let text = String::from_utf8(bytes).map_err(|e| {+ AttachmentError::Internal(anyhow::anyhow!(+ "static file content is not valid UTF-8: {e}"+ ))+ })?;+ AttachmentPart::Content(text)+ };++ Ok(AttachmentContent {+ reference: entity.clone(),+ name: None,+ content: NonEmpty::one(part),+ })+ }+}diff --git a/rust/cloud-storage/static_file/src/inbound/mod.rs b/rust/cloud-storage/static_file/src/inbound/mod.rsnew file mode 100644index 0000000000..9c7cd7373f--- /dev/null+++ b/rust/cloud-storage/static_file/src/inbound/mod.rs@@ -0,0 +1,3 @@+//! Inbound adapters.++pub mod attachment;diff --git a/rust/cloud-storage/static_file/src/lib.rs b/rust/cloud-storage/static_file/src/lib.rsnew file mode 100644index 0000000000..51aafeb849--- /dev/null+++ b/rust/cloud-storage/static_file/src/lib.rs@@ -0,0 +1,10 @@+//! Hex crate for static file resolution.+#![deny(missing_docs)]++pub mod domain;++#[cfg(feature = "attachment")]+pub mod inbound;++#[cfg(feature = "outbound")]+pub mod outbound;diff --git a/rust/cloud-storage/static_file/src/outbound/mod.rs b/rust/cloud-storage/static_file/src/outbound/mod.rsnew file mode 100644index 0000000000..a5744e8002--- /dev/null+++ b/rust/cloud-storage/static_file/src/outbound/mod.rs@@ -0,0 +1,5 @@+//! Outbound adapters.++mod sfs_client;++pub use sfs_client::CdnStaticFileRepo;diff --git a/rust/cloud-storage/static_file/src/outbound/sfs_client.rs b/rust/cloud-storage/static_file/src/outbound/sfs_client.rsnew file mode 100644index 0000000000..999cb2b3f0--- /dev/null+++ b/rust/cloud-storage/static_file/src/outbound/sfs_client.rs@@ -0,0 +1,52 @@+//! [`StaticFileRepo`] backed by a CDN base URL.++use crate::domain::ports::StaticFileRepo;++/// Fetches static files from `{base_url}/file/{file_id}`.+pub struct CdnStaticFileRepo {+ base_url: String,+ client: reqwest::Client,+}++impl CdnStaticFileRepo {+ /// Create a new repo pointing at the given CDN base URL.+ pub fn new(base_url: String) -> Self {+ Self {+ base_url,+ client: reqwest::Client::new(),+ }+ }++ fn url(&self, file_id: &str) -> String {+ format!("{}/file/{}", self.base_url, file_id)+ }+}++impl StaticFileRepo for CdnStaticFileRepo {+ async fn content_type(&self, file_id: &str) -> anyhow::Result<mime::Mime> {+ let response = self.client.head(self.url(file_id)).send().await?;++ if !response.status().is_success() {+ anyhow::bail!("static file HEAD failed: HTTP {}", response.status());+ }++ let mime = response+ .headers()+ .get(reqwest::header::CONTENT_TYPE)+ .and_then(|v| v.to_str().ok())+ .and_then(|s| s.parse().ok())+ .unwrap_or(mime::APPLICATION_OCTET_STREAM);++ Ok(mime)+ }++ async fn read(&self, file_id: &str) -> anyhow::Result<Vec<u8>> {+ let response = self.client.get(self.url(file_id)).send().await?;++ if !response.status().is_success() {+ anyhow::bail!("static file GET failed: HTTP {}", response.status());+ }++ Ok(response.bytes().await?.to_vec())+ }+}