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
chore: hexify dcs (chat crud) (#1541)
Eric Hayes43fb45b1fea6
diff --git a/js/app/packages/app/component/SoupChatInput.tsx b/js/app/packages/app/component/SoupChatInput.tsxindex 9d850f63c2..a04aa2151e 100644--- a/js/app/packages/app/component/SoupChatInput.tsx+++ b/js/app/packages/app/component/SoupChatInput.tsx@@ -163,6 +163,10 @@ function SoupChatInputInner() {);}+document.addEventListener('focusin', (f) => console.log('focus changed', f));+document.addEventListener('focusout', (f) => console.log('focus changed', f));+document.addEventListener('focus', (f) => console.log('focus changed', f));+export function SoupChatInput() {return (<ChatInputProvider autoAttach={false}>diff --git a/js/app/packages/block-chat/client.ts b/js/app/packages/block-chat/client.tsindex 224be4a175..e4d9fbcec2 100644--- a/js/app/packages/block-chat/client.ts+++ b/js/app/packages/block-chat/client.ts@@ -32,15 +32,7 @@ export function useOpenChatForAttachment() {(!recent_id || !data?.recent_chat?.isPersistent) &&callerBlock?.name === 'image') {- const res = await cognitionApiServiceClient.createChat({- attachments: [- {- attachment_type: 'image',- attachment_id: attachmentId,- },- ],- isPersistent: true,- });+ const res = await cognitionApiServiceClient.createChat({});if (isPaymentError(res)) {showPaywall();@@ -52,15 +44,7 @@ export function useOpenChatForAttachment() {const [, data] = res;recent_id = data?.id;} else if (!recent_id || !data?.recent_chat?.isPersistent) {- const res = await cognitionApiServiceClient.createChat({- attachments: [- {- attachment_type: 'document',- attachment_id: attachmentId,- },- ],- isPersistent: true,- });+ const res = await cognitionApiServiceClient.createChat({});if (isPaymentError(res)) {showPaywall();diff --git a/js/app/packages/service-clients/service-cognition/client.ts b/js/app/packages/service-clients/service-cognition/client.tsindex 47e8295132..4ea6f3f625 100644--- a/js/app/packages/service-clients/service-cognition/client.ts+++ b/js/app/packages/service-clients/service-cognition/client.ts@@ -19,17 +19,15 @@ import type { SafeFetchInit } from '@core/util/safeFetch';import type { DocumentTextPart } from '@service-cognition/generated/schemas/documentTextPart';import type OpenAI from 'openai';import type { CreateChatRequest } from './generated/schemas/createChatRequest';-import type { EmptyResponse } from './generated/schemas/emptyResponse';import type { GetBatchPreviewRequest } from './generated/schemas/getBatchPreviewRequest';import type { GetBatchPreviewResponse } from './generated/schemas/getBatchPreviewResponse';-import type { GetChatPermissionsResponseV2 } from './generated/schemas/getChatPermissionsResponseV2';+import type { GetChatPermissionsResponse } from './generated/schemas/getChatPermissionsResponse';import type { GetChatResponse } from './generated/schemas/getChatResponse';import type { GetChatsForAttachmentResponse } from './generated/schemas/getChatsForAttachmentResponse';import type { HttpSendChatMessageRequest } from './generated/schemas/httpSendChatMessageRequest';-import type { PatchChatRequestV2 } from './generated/schemas/patchChatRequestV2';+import type { PatchChatRequest } from './generated/schemas/patchChatRequest';import type { SendChatMessageResponse } from './generated/schemas/sendChatMessageResponse';import type { StringIDResponse } from './generated/schemas/stringIDResponse';-import type { SuccessResponse } from './generated/schemas/successResponse';const dcsHost: string = SERVER_HOSTS['cognition-service'];@@ -109,7 +107,7 @@ export const cognitionApiServiceClient = {);},- async updateChatPermissions(args: PatchChatRequestV2 & WithChatId) {+ async updateChatPermissions(args: PatchChatRequest & WithChatId) {const { chat_id, sharePermission } = args;return await dcsFetch(`/chats/${chat_id}`, {method: 'PATCH',@@ -148,10 +146,7 @@ export const cognitionApiServiceClient = {method: 'POST',body: JSON.stringify({name: args.name,- model: args.model,projectId: args.projectId,- attachments: args.attachments,- isPersistent: args.isPersistent,}),}),(result) => result@@ -175,7 +170,7 @@ export const cognitionApiServiceClient = {async getChatPermissions(args: { id: string }) {const { id } = args;return mapOk(- await dcsFetch<GetChatPermissionsResponseV2>(`/chats/${id}/permissions`, {+ await dcsFetch<GetChatPermissionsResponse>(`/chats/${id}/permissions`, {method: 'GET',}),(result) => result.permissions@@ -186,17 +181,14 @@ export const cognitionApiServiceClient = {setCachedInputStore(chat_id, undefined);- return mapOk(- await dcsFetch<EmptyResponse>(`/chats/${chat_id}/permanent`, {- method: 'DELETE',- }),- () => ({})- );+ return await dcsFetch(`/chats/${chat_id}/permanent`, {+ method: 'DELETE',+ });},async revertDeleteChat(args: WithChatId) {const { chat_id } = args;return mapOk(- await dcsFetch<SuccessResponse>(`/chats/${chat_id}/revert_delete`, {+ await dcsFetch<Success>(`/chats/${chat_id}/revert_delete`, {method: 'PUT',}),(result) => resultdiff --git a/js/app/packages/service-clients/service-cognition/generated/client.ts b/js/app/packages/service-clients/service-cognition/generated/client.tsindex 88c1f4c86f..1f7e0ba93b 100644--- a/js/app/packages/service-clients/service-cognition/generated/client.ts+++ b/js/app/packages/service-clients/service-cognition/generated/client.ts@@ -8,21 +8,18 @@ import type {ChatHistory,ChatHistoryBatchMessagesRequest,ChatMessageError,- CopyChatRequest,+ CreateChatRequest,DocumentTextPart,- EmptyResponse,- GenericErrorResponse,GetBatchPreviewRequest,GetBatchPreviewResponse,- GetChatPermissionsResponseV2,+ GetChatPermissionsResponse,GetChatResponse,GetChatsForAttachmentResponse,GetModelsResponse,HttpSendChatMessageRequest,- PatchChatRequestV2,+ PatchChatRequest,SendChatMessageResponse,StringIDResponse,- SuccessResponse,} from './schemas';export type getChatsForAttachmentHandlerResponse200 = {@@ -86,516 +83,539 @@ export const getChatsForAttachmentHandler = async (} as getChatsForAttachmentHandlerResponse;};-export type createChatHandlerResponse201 = {- data: StringIDResponse;- status: 201;+/**+ * @summary Soft-delete a chat.+ */+export type deleteChatResponse200 = {+ data: void;+ status: 200;};-export type createChatHandlerResponse401 = {+export type deleteChatResponse401 = {data: string;status: 401;};-export type createChatHandlerResponse404 = {+export type deleteChatResponse500 = {data: string;- status: 404;+ status: 500;+};++export type deleteChatResponseSuccess = deleteChatResponse200 & {+ headers: Headers;+};+export type deleteChatResponseError = (+ | deleteChatResponse401+ | deleteChatResponse500+) & {+ headers: Headers;+};++export type deleteChatResponse =+ | deleteChatResponseSuccess+ | deleteChatResponseError;++export const getDeleteChatUrl = (chatId: string) => {+ return `/chat/${chatId}`;+};++export const deleteChat = async (+ chatId: string,+ options?: RequestInit+): Promise<deleteChatResponse> => {+ const res = await fetch(getDeleteChatUrl(chatId), {+ ...options,+ method: 'DELETE',+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: deleteChatResponse['data'] = body ? JSON.parse(body) : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as deleteChatResponse;+};++/**+ * @summary Patch a chat's name, project, or share permissions.+ */+export type patchChatResponse200 = {+ data: void;+ status: 200;};-export type createChatHandlerResponse500 = {+export type patchChatResponse401 = {+ data: string;+ status: 401;+};++export type patchChatResponse500 = {data: string;status: 500;};-export type createChatHandlerResponseSuccess = createChatHandlerResponse201 & {+export type patchChatResponseSuccess = patchChatResponse200 & {headers: Headers;};-export type createChatHandlerResponseError = (- | createChatHandlerResponse401- | createChatHandlerResponse404- | createChatHandlerResponse500+export type patchChatResponseError = (+ | patchChatResponse401+ | patchChatResponse500) & {headers: Headers;};-export type createChatHandlerResponse =- | createChatHandlerResponseSuccess- | createChatHandlerResponseError;+export type patchChatResponse =+ | patchChatResponseSuccess+ | patchChatResponseError;-export const getCreateChatHandlerUrl = () => {- return `/chats`;+export const getPatchChatUrl = (chatId: string) => {+ return `/chat/${chatId}`;};-export const createChatHandler = async (+export const patchChat = async (+ chatId: string,+ patchChatRequest: PatchChatRequest,options?: RequestInit-): Promise<createChatHandlerResponse> => {- const res = await fetch(getCreateChatHandlerUrl(), {+): Promise<patchChatResponse> => {+ const res = await fetch(getPatchChatUrl(chatId), {...options,- method: 'POST',+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(patchChatRequest),});const body = [204, 205, 304].includes(res.status) ? null : await res.text();- const data: createChatHandlerResponse['data'] = body ? JSON.parse(body) : {};+ const data: patchChatResponse['data'] = body ? JSON.parse(body) : {};return {data,status: res.status,headers: res.headers,- } as createChatHandlerResponse;+ } as patchChatResponse;};/**- * @summary Retrieves chat history for a specific chat ID+ * @summary Permanently delete a chat and all associated data.*/-export type getChatHistoryHandlerResponse200 = {- data: ChatHistory;+export type permanentlyDeleteChatResponse200 = {+ data: void;status: 200;};-export type getChatHistoryHandlerResponse404 = {+export type permanentlyDeleteChatResponse401 = {data: string;- status: 404;+ status: 401;};-export type getChatHistoryHandlerResponse500 = {+export type permanentlyDeleteChatResponse500 = {data: string;status: 500;};-export type getChatHistoryHandlerResponseSuccess =- getChatHistoryHandlerResponse200 & {+export type permanentlyDeleteChatResponseSuccess =+ permanentlyDeleteChatResponse200 & {headers: Headers;};-export type getChatHistoryHandlerResponseError = (- | getChatHistoryHandlerResponse404- | getChatHistoryHandlerResponse500+export type permanentlyDeleteChatResponseError = (+ | permanentlyDeleteChatResponse401+ | permanentlyDeleteChatResponse500) & {headers: Headers;};-export type getChatHistoryHandlerResponse =- | getChatHistoryHandlerResponseSuccess- | getChatHistoryHandlerResponseError;+export type permanentlyDeleteChatResponse =+ | permanentlyDeleteChatResponseSuccess+ | permanentlyDeleteChatResponseError;-export const getGetChatHistoryHandlerUrl = (chatId: string) => {- return `/chats/history/${chatId}`;+export const getPermanentlyDeleteChatUrl = (chatId: string) => {+ return `/chat/${chatId}/permanent`;};-export const getChatHistoryHandler = async (+export const permanentlyDeleteChat = async (chatId: string,options?: RequestInit-): Promise<getChatHistoryHandlerResponse> => {- const res = await fetch(getGetChatHistoryHandlerUrl(chatId), {+): Promise<permanentlyDeleteChatResponse> => {+ const res = await fetch(getPermanentlyDeleteChatUrl(chatId), {...options,- method: 'GET',+ method: 'DELETE',});const body = [204, 205, 304].includes(res.status) ? null : await res.text();- const data: getChatHistoryHandlerResponse['data'] = body+ const data: permanentlyDeleteChatResponse['data'] = body? JSON.parse(body): {};return {data,status: res.status,headers: res.headers,- } as getChatHistoryHandlerResponse;+ } as permanentlyDeleteChatResponse;};/**- * @summary Retrieves chat history for multiple message IDs+ * @summary Create a new chat.*/-export type getChatHistoryBatchMessagesHandlerResponse200 = {- data: ChatHistory;+export type createChatResponse200 = {+ data: StringIDResponse;status: 200;};-export type getChatHistoryBatchMessagesHandlerResponse403 = {+export type createChatResponse401 = {data: string;- status: 403;-};--export type getChatHistoryBatchMessagesHandlerResponse404 = {- data: string;- status: 404;+ status: 401;};-export type getChatHistoryBatchMessagesHandlerResponse500 = {+export type createChatResponse500 = {data: string;status: 500;};-export type getChatHistoryBatchMessagesHandlerResponseSuccess =- getChatHistoryBatchMessagesHandlerResponse200 & {- headers: Headers;- };-export type getChatHistoryBatchMessagesHandlerResponseError = (- | getChatHistoryBatchMessagesHandlerResponse403- | getChatHistoryBatchMessagesHandlerResponse404- | getChatHistoryBatchMessagesHandlerResponse500+export type createChatResponseSuccess = createChatResponse200 & {+ headers: Headers;+};+export type createChatResponseError = (+ | createChatResponse401+ | createChatResponse500) & {headers: Headers;};-export type getChatHistoryBatchMessagesHandlerResponse =- | getChatHistoryBatchMessagesHandlerResponseSuccess- | getChatHistoryBatchMessagesHandlerResponseError;+export type createChatResponse =+ | createChatResponseSuccess+ | createChatResponseError;-export const getGetChatHistoryBatchMessagesHandlerUrl = () => {- return `/chats/history_batch_messages`;+export const getCreateChatUrl = () => {+ return `/chats`;};-export const getChatHistoryBatchMessagesHandler = async (- chatHistoryBatchMessagesRequest: ChatHistoryBatchMessagesRequest,+export const createChat = async (+ createChatRequest: CreateChatRequest,options?: RequestInit-): Promise<getChatHistoryBatchMessagesHandlerResponse> => {- const res = await fetch(getGetChatHistoryBatchMessagesHandlerUrl(), {+): Promise<createChatResponse> => {+ const res = await fetch(getCreateChatUrl(), {...options,method: 'POST',headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(chatHistoryBatchMessagesRequest),+ body: JSON.stringify(createChatRequest),});const body = [204, 205, 304].includes(res.status) ? null : await res.text();- const data: getChatHistoryBatchMessagesHandlerResponse['data'] = body- ? JSON.parse(body)- : {};+ const data: createChatResponse['data'] = body ? JSON.parse(body) : {};return {data,status: res.status,headers: res.headers,- } as getChatHistoryBatchMessagesHandlerResponse;+ } as createChatResponse;};/**- * @summary Gets a particular chat by its id+ * @summary Retrieves chat history for a specific chat ID*/-export type getChatHandlerResponse200 = {- data: GetChatResponse;+export type getChatHistoryHandlerResponse200 = {+ data: ChatHistory;status: 200;};-export type getChatHandlerResponse401 = {- data: string;- status: 401;-};--export type getChatHandlerResponse404 = {+export type getChatHistoryHandlerResponse404 = {data: string;status: 404;};-export type getChatHandlerResponse500 = {+export type getChatHistoryHandlerResponse500 = {data: string;status: 500;};-export type getChatHandlerResponseSuccess = getChatHandlerResponse200 & {- headers: Headers;-};-export type getChatHandlerResponseError = (- | getChatHandlerResponse401- | getChatHandlerResponse404- | getChatHandlerResponse500+export type getChatHistoryHandlerResponseSuccess =+ getChatHistoryHandlerResponse200 & {+ headers: Headers;+ };+export type getChatHistoryHandlerResponseError = (+ | getChatHistoryHandlerResponse404+ | getChatHistoryHandlerResponse500) & {headers: Headers;};-export type getChatHandlerResponse =- | getChatHandlerResponseSuccess- | getChatHandlerResponseError;+export type getChatHistoryHandlerResponse =+ | getChatHistoryHandlerResponseSuccess+ | getChatHistoryHandlerResponseError;-export const getGetChatHandlerUrl = (chatId: string) => {- return `/chats/${chatId}`;+export const getGetChatHistoryHandlerUrl = (chatId: string) => {+ return `/chats/history/${chatId}`;};-export const getChatHandler = async (+export const getChatHistoryHandler = async (chatId: string,options?: RequestInit-): Promise<getChatHandlerResponse> => {- const res = await fetch(getGetChatHandlerUrl(chatId), {+): Promise<getChatHistoryHandlerResponse> => {+ const res = await fetch(getGetChatHistoryHandlerUrl(chatId), {...options,method: 'GET',});const body = [204, 205, 304].includes(res.status) ? null : await res.text();- const data: getChatHandlerResponse['data'] = body ? JSON.parse(body) : {};+ const data: getChatHistoryHandlerResponse['data'] = body+ ? JSON.parse(body)+ : {};return {data,status: res.status,headers: res.headers,- } as getChatHandlerResponse;+ } as getChatHistoryHandlerResponse;};/**- * @summary Deletes a particular chat by its id.-Soft deletes the chat.+ * @summary Retrieves chat history for multiple message IDs*/-export type deleteChatHandlerResponse200 = {- data: EmptyResponse;+export type getChatHistoryBatchMessagesHandlerResponse200 = {+ data: ChatHistory;status: 200;};-export type deleteChatHandlerResponse401 = {+export type getChatHistoryBatchMessagesHandlerResponse403 = {data: string;- status: 401;+ status: 403;};-export type deleteChatHandlerResponse404 = {+export type getChatHistoryBatchMessagesHandlerResponse404 = {data: string;status: 404;};-export type deleteChatHandlerResponse500 = {+export type getChatHistoryBatchMessagesHandlerResponse500 = {data: string;status: 500;};-export type deleteChatHandlerResponseSuccess = deleteChatHandlerResponse200 & {- headers: Headers;-};-export type deleteChatHandlerResponseError = (- | deleteChatHandlerResponse401- | deleteChatHandlerResponse404- | deleteChatHandlerResponse500+export type getChatHistoryBatchMessagesHandlerResponseSuccess =+ getChatHistoryBatchMessagesHandlerResponse200 & {+ headers: Headers;+ };+export type getChatHistoryBatchMessagesHandlerResponseError = (+ | getChatHistoryBatchMessagesHandlerResponse403+ | getChatHistoryBatchMessagesHandlerResponse404+ | getChatHistoryBatchMessagesHandlerResponse500) & {headers: Headers;};-export type deleteChatHandlerResponse =- | deleteChatHandlerResponseSuccess- | deleteChatHandlerResponseError;+export type getChatHistoryBatchMessagesHandlerResponse =+ | getChatHistoryBatchMessagesHandlerResponseSuccess+ | getChatHistoryBatchMessagesHandlerResponseError;-export const getDeleteChatHandlerUrl = (chatId: string) => {- return `/chats/${chatId}`;+export const getGetChatHistoryBatchMessagesHandlerUrl = () => {+ return `/chats/history_batch_messages`;};-export const deleteChatHandler = async (- chatId: string,+export const getChatHistoryBatchMessagesHandler = async (+ chatHistoryBatchMessagesRequest: ChatHistoryBatchMessagesRequest,options?: RequestInit-): Promise<deleteChatHandlerResponse> => {- const res = await fetch(getDeleteChatHandlerUrl(chatId), {+): Promise<getChatHistoryBatchMessagesHandlerResponse> => {+ const res = await fetch(getGetChatHistoryBatchMessagesHandlerUrl(), {...options,- method: 'DELETE',+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(chatHistoryBatchMessagesRequest),});const body = [204, 205, 304].includes(res.status) ? null : await res.text();- const data: deleteChatHandlerResponse['data'] = body ? JSON.parse(body) : {};+ const data: getChatHistoryBatchMessagesHandlerResponse['data'] = body+ ? JSON.parse(body)+ : {};return {data,status: res.status,headers: res.headers,- } as deleteChatHandlerResponse;+ } as getChatHistoryBatchMessagesHandlerResponse;};-export type patchChatHandlerResponse200 = {- data: void;+/**+ * @summary Get a chat by ID with messages and web citations.+ */+export type getChatResponse200 = {+ data: GetChatResponse;status: 200;};-export type patchChatHandlerResponse400 = {+export type getChatResponse401 = {data: string;- status: 400;+ status: 401;};-export type patchChatHandlerResponse401 = {+export type getChatResponse404 = {data: string;- status: 401;+ status: 404;};-export type patchChatHandlerResponse500 = {+export type getChatResponse500 = {data: string;status: 500;};-export type patchChatHandlerResponseSuccess = patchChatHandlerResponse200 & {+export type getChatResponseSuccess = getChatResponse200 & {headers: Headers;};-export type patchChatHandlerResponseError = (- | patchChatHandlerResponse400- | patchChatHandlerResponse401- | patchChatHandlerResponse500+export type getChatResponseError = (+ | getChatResponse401+ | getChatResponse404+ | getChatResponse500) & {headers: Headers;};-export type patchChatHandlerResponse =- | patchChatHandlerResponseSuccess- | patchChatHandlerResponseError;+export type getChatResponse = getChatResponseSuccess | getChatResponseError;-export const getPatchChatHandlerUrl = (chatId: string) => {+export const getGetChatUrl = (chatId: string) => {return `/chats/${chatId}`;};-export const patchChatHandler = async (+export const getChat = async (chatId: string,- patchChatRequestV2: PatchChatRequestV2,options?: RequestInit-): Promise<patchChatHandlerResponse> => {- const res = await fetch(getPatchChatHandlerUrl(chatId), {+): Promise<getChatResponse> => {+ const res = await fetch(getGetChatUrl(chatId), {...options,- method: 'PATCH',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(patchChatRequestV2),+ method: 'GET',});const body = [204, 205, 304].includes(res.status) ? null : await res.text();- const data: patchChatHandlerResponse['data'] = body ? JSON.parse(body) : {};- return {- data,- status: res.status,- headers: res.headers,- } as patchChatHandlerResponse;+ const data: getChatResponse['data'] = body ? JSON.parse(body) : {};+ return { data, status: res.status, headers: res.headers } as getChatResponse;};-export type copyChatHandlerResponse201 = {+/**+ * @summary Copy a chat and its messages into a new chat.+ */+export type copyChatResponse200 = {data: StringIDResponse;- status: 201;+ status: 200;};-export type copyChatHandlerResponse401 = {+export type copyChatResponse401 = {data: string;status: 401;};-export type copyChatHandlerResponse404 = {+export type copyChatResponse404 = {data: string;status: 404;};-export type copyChatHandlerResponse500 = {+export type copyChatResponse500 = {data: string;status: 500;};-export type copyChatHandlerResponseSuccess = copyChatHandlerResponse201 & {+export type copyChatResponseSuccess = copyChatResponse200 & {headers: Headers;};-export type copyChatHandlerResponseError = (- | copyChatHandlerResponse401- | copyChatHandlerResponse404- | copyChatHandlerResponse500+export type copyChatResponseError = (+ | copyChatResponse401+ | copyChatResponse404+ | copyChatResponse500) & {headers: Headers;};-export type copyChatHandlerResponse =- | copyChatHandlerResponseSuccess- | copyChatHandlerResponseError;+export type copyChatResponse = copyChatResponseSuccess | copyChatResponseError;-export const getCopyChatHandlerUrl = (chatId: string) => {+export const getCopyChatUrl = (chatId: string) => {return `/chats/${chatId}/copy`;};-export const copyChatHandler = async (+export const copyChat = async (chatId: string,- copyChatRequest: CopyChatRequest,options?: RequestInit-): Promise<copyChatHandlerResponse> => {- const res = await fetch(getCopyChatHandlerUrl(chatId), {+): Promise<copyChatResponse> => {+ const res = await fetch(getCopyChatUrl(chatId), {...options,method: 'POST',- headers: { 'Content-Type': 'application/json', ...options?.headers },- body: JSON.stringify(copyChatRequest),});const body = [204, 205, 304].includes(res.status) ? null : await res.text();- const data: copyChatHandlerResponse['data'] = body ? JSON.parse(body) : {};- return {- data,- status: res.status,- headers: res.headers,- } as copyChatHandlerResponse;+ const data: copyChatResponse['data'] = body ? JSON.parse(body) : {};+ return { data, status: res.status, headers: res.headers } as copyChatResponse;};/**- * @summary Permanently deletes a chat.+ * @summary Get the share permissions for a chat.*/-export type permanentlyDeleteChatResponse200 = {- data: EmptyResponse;+export type getChatPermissionsResponse200 = {+ data: GetChatPermissionsResponse;status: 200;};-export type permanentlyDeleteChatResponse401 = {+export type getChatPermissionsResponse401 = {data: string;status: 401;};-export type permanentlyDeleteChatResponse404 = {- data: string;- status: 404;-};--export type permanentlyDeleteChatResponse500 = {+export type getChatPermissionsResponse500 = {data: string;status: 500;};-export type permanentlyDeleteChatResponseSuccess =- permanentlyDeleteChatResponse200 & {+export type getChatPermissionsResponseSuccess =+ getChatPermissionsResponse200 & {headers: Headers;};-export type permanentlyDeleteChatResponseError = (- | permanentlyDeleteChatResponse401- | permanentlyDeleteChatResponse404- | permanentlyDeleteChatResponse500+export type getChatPermissionsResponseError = (+ | getChatPermissionsResponse401+ | getChatPermissionsResponse500) & {headers: Headers;};-export type permanentlyDeleteChatResponse =- | permanentlyDeleteChatResponseSuccess- | permanentlyDeleteChatResponseError;+export type getChatPermissionsResponse =+ | getChatPermissionsResponseSuccess+ | getChatPermissionsResponseError;-export const getPermanentlyDeleteChatUrl = (chatId: string) => {- return `/chats/${chatId}/permanent`;+export const getGetChatPermissionsUrl = (chatId: string) => {+ return `/chats/${chatId}/permissions`;};-export const permanentlyDeleteChat = async (+export const getChatPermissions = async (chatId: string,options?: RequestInit-): Promise<permanentlyDeleteChatResponse> => {- const res = await fetch(getPermanentlyDeleteChatUrl(chatId), {+): Promise<getChatPermissionsResponse> => {+ const res = await fetch(getGetChatPermissionsUrl(chatId), {...options,- method: 'DELETE',+ method: 'GET',});const body = [204, 205, 304].includes(res.status) ? null : await res.text();- const data: permanentlyDeleteChatResponse['data'] = body- ? JSON.parse(body)- : {};+ const data: getChatPermissionsResponse['data'] = body ? JSON.parse(body) : {};return {data,status: res.status,headers: res.headers,- } as permanentlyDeleteChatResponse;+ } as getChatPermissionsResponse;};/**- * @summary Deletes a specific document+ * @summary Revert a soft-deleted chat.*/export type revertDeleteChatResponse200 = {- data: SuccessResponse;+ data: void;status: 200;};export type revertDeleteChatResponse401 = {- data: GenericErrorResponse;+ data: string;status: 401;};-export type revertDeleteChatResponse404 = {- data: GenericErrorResponse;- status: 404;-};-export type revertDeleteChatResponse500 = {- data: GenericErrorResponse;+ data: string;status: 500;};@@ -604,7 +624,6 @@ export type revertDeleteChatResponseSuccess = revertDeleteChatResponse200 & {};export type revertDeleteChatResponseError = (| revertDeleteChatResponse401- | revertDeleteChatResponse404| revertDeleteChatResponse500) & {headers: Headers;@@ -880,61 +899,3 @@ export const sendChatMessage = async (headers: res.headers,} as sendChatMessageResponse;};--/**- * @summary Gets the current chat share permissions- */-export type getChatPermissionsHandlerV2Response200 = {- data: GetChatPermissionsResponseV2;- status: 200;-};--export type getChatPermissionsHandlerV2Response404 = {- data: string;- status: 404;-};--export type getChatPermissionsHandlerV2Response500 = {- data: string;- status: 500;-};--export type getChatPermissionsHandlerV2ResponseSuccess =- getChatPermissionsHandlerV2Response200 & {- headers: Headers;- };-export type getChatPermissionsHandlerV2ResponseError = (- | getChatPermissionsHandlerV2Response404- | getChatPermissionsHandlerV2Response500-) & {- headers: Headers;-};--export type getChatPermissionsHandlerV2Response =- | getChatPermissionsHandlerV2ResponseSuccess- | getChatPermissionsHandlerV2ResponseError;--export const getGetChatPermissionsHandlerV2Url = (chatId: string) => {- return `/v2/chats/${chatId}/permissions`;-};--export const getChatPermissionsHandlerV2 = async (- chatId: string,- options?: RequestInit-): Promise<getChatPermissionsHandlerV2Response> => {- const res = await fetch(getGetChatPermissionsHandlerV2Url(chatId), {- ...options,- method: 'GET',- });-- const body = [204, 205, 304].includes(res.status) ? null : await res.text();-- const data: getChatPermissionsHandlerV2Response['data'] = body- ? JSON.parse(body)- : {};- return {- data,- status: res.status,- headers: res.headers,- } as getChatPermissionsHandlerV2Response;-};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponse.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponse.tsindex 581533c87d..11fe8d4439 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponse.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponse.ts@@ -14,33 +14,36 @@ import type { ChatResponseUpdatedAt } from './chatResponseUpdatedAt';import type { ChatResponseWebCitationsItemItem1Item } from './chatResponseWebCitationsItemItem1Item';import type { Model } from './model';+/**+ * The full chat response, matching the DCS API response shape.+ */export interface ChatResponse {/**- * attachment context - attachments not attached to messages+ * Attachment context — attachments not attached to messages.* @deprecated*/attachments: ChatAttachmentWithName[];- /** Available models for the chat */+ /** Available models for the chat. */availableModels: Model[];- /** The time the chat was created */+ /** The time the chat was created. */createdAt?: ChatResponseCreatedAt;- /** The chat uuid */+ /** The chat uuid. */id: string;- /** whether the chat is persistent or not */+ /** Whether the chat is persistent or not. */isPersistent: boolean;- /** The messages in the chat */+ /** The messages in the chat. */messages: ChatMessageWithAttachments[];model?: ChatResponseModel;- /** The name of the Chat */+ /** The name of the chat. */name: string;- /** The project id the chat belongs to */+ /** The project id the chat belongs to. */projectId?: ChatResponseProjectId;- /** Current number of tokens in the chat */+ /** Current number of tokens in the chat. */tokenCount?: ChatResponseTokenCount;- /** The time the chat was last updated */+ /** The time the chat was last updated. */updatedAt?: ChatResponseUpdatedAt;- /** Who the chat belongs to */+ /** Who the chat belongs to. */userId: string;- /** message_id - web citation list */+ /** Message ID to web citation list. */webCitations: [string, ChatResponseWebCitationsItemItem1Item[]][];}diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseCreatedAt.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseCreatedAt.tsindex c96b24539e..219c368514 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseCreatedAt.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseCreatedAt.ts@@ -6,6 +6,6 @@*//**- * The time the chat was created+ * The time the chat was created.*/export type ChatResponseCreatedAt = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseProjectId.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseProjectId.tsindex 0988d7c1b6..7917824e14 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseProjectId.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseProjectId.ts@@ -6,6 +6,6 @@*//**- * The project id the chat belongs to+ * The project id the chat belongs to.*/export type ChatResponseProjectId = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseTokenCount.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseTokenCount.tsindex 650bfe6b27..8fb6c535cb 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseTokenCount.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseTokenCount.ts@@ -6,6 +6,6 @@*//**- * Current number of tokens in the chat+ * Current number of tokens in the chat.*/export type ChatResponseTokenCount = number | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseUpdatedAt.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseUpdatedAt.tsindex c6bd1cd090..6d15e1273d 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseUpdatedAt.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseUpdatedAt.ts@@ -6,6 +6,6 @@*//**- * The time the chat was last updated+ * The time the chat was last updated.*/export type ChatResponseUpdatedAt = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseWebCitationsItemItem1Item.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseWebCitationsItemItem1Item.tsindex bcffcdb4bd..7eebaf66a4 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseWebCitationsItemItem1Item.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseWebCitationsItemItem1Item.ts@@ -8,10 +8,18 @@ import type { ChatResponseWebCitationsItemItem1ItemDescription } from './chatResimport type { ChatResponseWebCitationsItemItem1ItemFaviconUrl } from './chatResponseWebCitationsItemItem1ItemFaviconUrl';import type { ChatResponseWebCitationsItemItem1ItemImageUrl } from './chatResponseWebCitationsItemItem1ItemImageUrl';+/**+ * A web citation associated with a chat message.+ */export type ChatResponseWebCitationsItemItem1Item = {+ /** A description of the cited page. */description?: ChatResponseWebCitationsItemItem1ItemDescription;+ /** The URL of the page's favicon. */favicon_url?: ChatResponseWebCitationsItemItem1ItemFaviconUrl;+ /** The URL of the page's image. */image_url?: ChatResponseWebCitationsItemItem1ItemImageUrl;+ /** The title of the cited page. */title: string;+ /** The URL of the citation. */url: string;};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseWebCitationsItemItem1ItemDescription.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseWebCitationsItemItem1ItemDescription.tsindex bc02f0518b..d318558a9f 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseWebCitationsItemItem1ItemDescription.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseWebCitationsItemItem1ItemDescription.ts@@ -5,4 +5,7 @@* OpenAPI spec version: 1.0.0*/+/**+ * A description of the cited page.+ */export type ChatResponseWebCitationsItemItem1ItemDescription = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseWebCitationsItemItem1ItemFaviconUrl.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseWebCitationsItemItem1ItemFaviconUrl.tsindex b78d790c17..4ec407a969 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseWebCitationsItemItem1ItemFaviconUrl.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseWebCitationsItemItem1ItemFaviconUrl.ts@@ -5,4 +5,7 @@* OpenAPI spec version: 1.0.0*/+/**+ * The URL of the page's favicon.+ */export type ChatResponseWebCitationsItemItem1ItemFaviconUrl = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseWebCitationsItemItem1ItemImageUrl.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseWebCitationsItemItem1ItemImageUrl.tsindex da28df9beb..7af3a3a1c6 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseWebCitationsItemItem1ItemImageUrl.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatResponseWebCitationsItemItem1ItemImageUrl.ts@@ -5,4 +5,7 @@* OpenAPI spec version: 1.0.0*/+/**+ * The URL of the page's image.+ */export type ChatResponseWebCitationsItemItem1ItemImageUrl = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/createChatRequest.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/createChatRequest.tsindex 0cd39120c6..4a50e6dae8 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/createChatRequest.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/createChatRequest.ts@@ -4,16 +4,15 @@* Document Cognition Service* OpenAPI spec version: 1.0.0*/-import type { CreateChatRequestAttachments } from './createChatRequestAttachments';-import type { CreateChatRequestIsPersistent } from './createChatRequestIsPersistent';-import type { CreateChatRequestModel } from './createChatRequestModel';import type { CreateChatRequestName } from './createChatRequestName';import type { CreateChatRequestProjectId } from './createChatRequestProjectId';+/**+ * Request body for creating a chat.+ */export interface CreateChatRequest {- attachments?: CreateChatRequestAttachments;- isPersistent?: CreateChatRequestIsPersistent;- model?: CreateChatRequestModel;+ /** Optional name for the chat. */name?: CreateChatRequestName;+ /** Optional project to associate the chat with. */projectId?: CreateChatRequestProjectId;}diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/createChatRequestAttachments.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/createChatRequestAttachments.tsdeleted file mode 100644index 96f86dc1eb..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/createChatRequestAttachments.ts+++ /dev/null@@ -1,9 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { NewAttachment } from './newAttachment';--export type CreateChatRequestAttachments = NewAttachment[] | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/createChatRequestModel.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/createChatRequestModel.tsdeleted file mode 100644index 5fc7aa6286..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/createChatRequestModel.ts+++ /dev/null@@ -1,9 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { Model } from './model';--export type CreateChatRequestModel = null | Model;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/createChatRequestName.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/createChatRequestName.tsindex 4354d127c7..8da93e3c0f 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/createChatRequestName.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/createChatRequestName.ts@@ -5,4 +5,7 @@* OpenAPI spec version: 1.0.0*/+/**+ * Optional name for the chat.+ */export type CreateChatRequestName = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/createChatRequestProjectId.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/createChatRequestProjectId.tsindex 15aa1faf9d..19c6f03aff 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/createChatRequestProjectId.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/createChatRequestProjectId.ts@@ -5,4 +5,7 @@* OpenAPI spec version: 1.0.0*/+/**+ * Optional project to associate the chat with.+ */export type CreateChatRequestProjectId = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/emptyResponse.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/emptyResponse.tsdeleted file mode 100644index a1a7a719a6..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/emptyResponse.ts+++ /dev/null@@ -1,13 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--/**- * Empty response is required due to custom fetch forcing `response.json()`- */-export interface EmptyResponse {- [key: string]: unknown;-}diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/genericSuccessResponse.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/genericSuccessResponse.tsdeleted file mode 100644index 66899dd877..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/genericSuccessResponse.ts+++ /dev/null@@ -1,11 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export interface GenericSuccessResponse {- /** Indicates if the request was successful */- success: boolean;-}diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/getChatPermissionsResponseV2.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/getChatPermissionsResponse.tssimilarity index 61%rename from js/app/packages/service-clients/service-cognition/generated/schemas/getChatPermissionsResponseV2.tsrename to js/app/packages/service-clients/service-cognition/generated/schemas/getChatPermissionsResponse.tsindex 4010b23559..7009292813 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/getChatPermissionsResponseV2.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/getChatPermissionsResponse.ts@@ -6,6 +6,10 @@*/import type { SharePermissionV2 } from './sharePermissionV2';-export interface GetChatPermissionsResponseV2 {+/**+ * Response body for get chat permissions.+ */+export interface GetChatPermissionsResponse {+ /** The share permissions for the chat. */permissions: SharePermissionV2;}diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/getChatResponse.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/getChatResponse.tsindex 1f79089344..4ad914374a 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/getChatResponse.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/getChatResponse.ts@@ -8,7 +8,12 @@import type { AccessLevel } from './accessLevel';import type { ChatResponse } from './chatResponse';+/**+ * Wrapper response for get_chat, matching the DCS API response shape.+ */export interface GetChatResponse {+ /** The full chat data. */chat: ChatResponse;+ /** The requesting user's access level on this chat. */userAccessLevel: AccessLevel;}diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/index.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/index.tsindex 3c872e25b5..93e97bde6a 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/index.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/index.ts@@ -105,11 +105,7 @@ export * from './chatStreamOneOfTwothreeType';export * from './chatTokenCount';export * from './chatUpdatedAt';export * from './conversationRecord';-export * from './copyChatRequest';export * from './createChatRequest';-export * from './createChatRequestAttachments';-export * from './createChatRequestIsPersistent';-export * from './createChatRequestModel';export * from './createChatRequestName';export * from './createChatRequestProjectId';export * from './documentCognitionServiceApiVersion';@@ -118,7 +114,6 @@ export * from './documentReferenceOneOf';export * from './documentReferenceOneOfAllOf';export * from './documentReferenceOneOfAllOfKind';export * from './documentTextPart';-export * from './emptyResponse';export * from './extractionStatusEnum';export * from './extractionStatusEnumOneOf';export * from './extractionStatusEnumOneOfFive';@@ -130,11 +125,9 @@ export * from './extractionStatusEnumOneOfThreeType';export * from './extractionStatusEnumOneOfType';export * from './fileType';export * from './genericErrorResponse';-export * from './genericSuccessResponse';export * from './getBatchPreviewRequest';export * from './getBatchPreviewResponse';-export * from './getChatPathParams';-export * from './getChatPermissionsResponseV2';+export * from './getChatPermissionsResponse';export * from './getChatResponse';export * from './getChatsForAttachmentResponse';export * from './getChatsForAttachmentResponseRecentChat';@@ -153,14 +146,9 @@ export * from './newChatMessageAttachments';export * from './newChatMessageId';export * from './newMessageAttachment';export * from './patchChatRequest';-export * from './patchChatRequestModel';export * from './patchChatRequestName';export * from './patchChatRequestProjectId';-export * from './patchChatRequestV2';-export * from './patchChatRequestV2Model';-export * from './patchChatRequestV2Name';-export * from './patchChatRequestV2ProjectId';-export * from './patchChatRequestV2SharePermission';+export * from './patchChatRequestSharePermission';export * from './provider';export * from './role';export * from './sendChatMessagePayload';@@ -179,7 +167,6 @@ export * from './streamErrorOneOfStreamError';export * from './streamErrorOneOfThree';export * from './streamErrorOneOfThreeStreamError';export * from './stringIDResponse';-export * from './successResponse';export * from './toolSchema';export * from './toolSchemas';export * from './toolSet';@@ -195,4 +182,8 @@ export * from './updateSharePermissionRequestV2ChannelSharePermissions';export * from './updateSharePermissionRequestV2IsPublic';export * from './updateSharePermissionRequestV2PublicAccessLevel';export * from './userPdfRect';+export * from './webCitation';+export * from './webCitationDescription';+export * from './webCitationFaviconUrl';+export * from './webCitationImageUrl';export * from './withChatId';diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/patchChatRequest.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/patchChatRequest.tsindex 63dd25ef7e..c99ca9872b 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/patchChatRequest.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/patchChatRequest.ts@@ -4,12 +4,17 @@* Document Cognition Service* OpenAPI spec version: 1.0.0*/-import type { PatchChatRequestModel } from './patchChatRequestModel';import type { PatchChatRequestName } from './patchChatRequestName';import type { PatchChatRequestProjectId } from './patchChatRequestProjectId';+import type { PatchChatRequestSharePermission } from './patchChatRequestSharePermission';+/**+ * Request body for patching a chat.+ */export interface PatchChatRequest {- model?: PatchChatRequestModel;+ /** New name for the chat. */name?: PatchChatRequestName;+ /** New project ID for the chat. Empty string clears the project. */projectId?: PatchChatRequestProjectId;+ sharePermission?: PatchChatRequestSharePermission;}diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/patchChatRequestModel.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/patchChatRequestModel.tsdeleted file mode 100644index bc03a48d48..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/patchChatRequestModel.ts+++ /dev/null@@ -1,8 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export type PatchChatRequestModel = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/patchChatRequestName.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/patchChatRequestName.tsindex 996329195f..8a3fa99240 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/patchChatRequestName.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/patchChatRequestName.ts@@ -5,4 +5,7 @@* OpenAPI spec version: 1.0.0*/+/**+ * New name for the chat.+ */export type PatchChatRequestName = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/patchChatRequestProjectId.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/patchChatRequestProjectId.tsindex 8a213d5b2c..41796532b1 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/patchChatRequestProjectId.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/patchChatRequestProjectId.ts@@ -5,4 +5,7 @@* OpenAPI spec version: 1.0.0*/+/**+ * New project ID for the chat. Empty string clears the project.+ */export type PatchChatRequestProjectId = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/patchChatRequestV2SharePermission.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/patchChatRequestSharePermission.tssimilarity index 84%rename from js/app/packages/service-clients/service-cognition/generated/schemas/patchChatRequestV2SharePermission.tsrename to js/app/packages/service-clients/service-cognition/generated/schemas/patchChatRequestSharePermission.tsindex e69df5ec97..bc4de43e51 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/patchChatRequestV2SharePermission.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/patchChatRequestSharePermission.ts@@ -6,5 +6,5 @@*/import type { UpdateSharePermissionRequestV2 } from './updateSharePermissionRequestV2';-export type PatchChatRequestV2SharePermission =+export type PatchChatRequestSharePermission =null | UpdateSharePermissionRequestV2;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/patchChatRequestV2.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/patchChatRequestV2.tsdeleted file mode 100644index 2d91035454..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/patchChatRequestV2.ts+++ /dev/null@@ -1,17 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { PatchChatRequestV2Model } from './patchChatRequestV2Model';-import type { PatchChatRequestV2Name } from './patchChatRequestV2Name';-import type { PatchChatRequestV2ProjectId } from './patchChatRequestV2ProjectId';-import type { PatchChatRequestV2SharePermission } from './patchChatRequestV2SharePermission';--export interface PatchChatRequestV2 {- model?: PatchChatRequestV2Model;- name?: PatchChatRequestV2Name;- projectId?: PatchChatRequestV2ProjectId;- sharePermission?: PatchChatRequestV2SharePermission;-}diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/patchChatRequestV2Model.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/patchChatRequestV2Model.tsdeleted file mode 100644index 6ea97fe0d6..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/patchChatRequestV2Model.ts+++ /dev/null@@ -1,8 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export type PatchChatRequestV2Model = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/patchChatRequestV2Name.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/patchChatRequestV2Name.tsdeleted file mode 100644index 13bc29ca36..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/patchChatRequestV2Name.ts+++ /dev/null@@ -1,8 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export type PatchChatRequestV2Name = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/patchChatRequestV2ProjectId.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/patchChatRequestV2ProjectId.tsdeleted file mode 100644index 228072ebda..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/patchChatRequestV2ProjectId.ts+++ /dev/null@@ -1,8 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--export type PatchChatRequestV2ProjectId = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/successResponse.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/successResponse.tsdeleted file mode 100644index a1bd46bbf0..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/successResponse.ts+++ /dev/null@@ -1,14 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { GenericSuccessResponse } from './genericSuccessResponse';--export interface SuccessResponse {- /** Data to be returned */- data: GenericSuccessResponse;- /** Indicates if an error occurred */- error: boolean;-}diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/webCitation.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webCitation.tsnew file mode 100644index 0000000000..f3dcadc928--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/webCitation.ts@@ -0,0 +1,25 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */+import type { WebCitationDescription } from './webCitationDescription';+import type { WebCitationFaviconUrl } from './webCitationFaviconUrl';+import type { WebCitationImageUrl } from './webCitationImageUrl';++/**+ * A web citation associated with a chat message.+ */+export interface WebCitation {+ /** A description of the cited page. */+ description?: WebCitationDescription;+ /** The URL of the page's favicon. */+ favicon_url?: WebCitationFaviconUrl;+ /** The URL of the page's image. */+ image_url?: WebCitationImageUrl;+ /** The title of the cited page. */+ title: string;+ /** The URL of the citation. */+ url: string;+}diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/createChatRequestIsPersistent.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webCitationDescription.tssimilarity index 57%rename from js/app/packages/service-clients/service-cognition/generated/schemas/createChatRequestIsPersistent.tsrename to js/app/packages/service-clients/service-cognition/generated/schemas/webCitationDescription.tsindex 2c90135475..f2c301c207 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/createChatRequestIsPersistent.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/webCitationDescription.ts@@ -5,4 +5,7 @@* OpenAPI spec version: 1.0.0*/-export type CreateChatRequestIsPersistent = boolean | null;+/**+ * A description of the cited page.+ */+export type WebCitationDescription = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/getChatPathParams.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webCitationFaviconUrl.tssimilarity index 58%rename from js/app/packages/service-clients/service-cognition/generated/schemas/getChatPathParams.tsrename to js/app/packages/service-clients/service-cognition/generated/schemas/webCitationFaviconUrl.tsindex 9cc6f0de27..8fc3c9d558 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/getChatPathParams.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/webCitationFaviconUrl.ts@@ -5,6 +5,7 @@* OpenAPI spec version: 1.0.0*/-export interface GetChatPathParams {- chat_id: string;-}+/**+ * The URL of the page's favicon.+ */+export type WebCitationFaviconUrl = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/copyChatRequest.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/webCitationImageUrl.tssimilarity index 59%rename from js/app/packages/service-clients/service-cognition/generated/schemas/copyChatRequest.tsrename to js/app/packages/service-clients/service-cognition/generated/schemas/webCitationImageUrl.tsindex 34a6388011..52fda09b67 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/copyChatRequest.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/webCitationImageUrl.ts@@ -5,6 +5,7 @@* OpenAPI spec version: 1.0.0*/-export interface CopyChatRequest {- name: string;-}+/**+ * The URL of the page's image.+ */+export type WebCitationImageUrl = string | null;diff --git a/js/app/packages/service-clients/service-cognition/openapi.json b/js/app/packages/service-clients/service-cognition/openapi.jsonindex 07ddb370fe..76f8c43d56 100644--- a/js/app/packages/service-clients/service-cognition/openapi.json+++ b/js/app/packages/service-clients/service-cognition/openapi.json@@ -70,22 +70,37 @@}}},- "/chats": {- "post": {- "tags": ["create_user_chat"],- "operationId": "create_chat_handler",+ "/chat/{chat_id}": {+ "delete": {+ "tags": ["chats"],+ "summary": "Soft-delete a chat.",+ "operationId": "delete_chat",+ "parameters": [+ {+ "name": "chat_id",+ "in": "path",+ "description": "ID of the chat",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],"responses": {- "201": {+ "200": {+ "description": ""+ },+ "401": {"description": "","content": {- "application/json": {+ "text/plain": {"schema": {- "$ref": "#/components/schemas/StringIDResponse"+ "type": "string"}}}},- "401": {+ "500": {"description": "","content": {"text/plain": {@@ -94,8 +109,39 @@}}}+ }+ }+ },+ "patch": {+ "tags": ["chats"],+ "summary": "Patch a chat's name, project, or share permissions.",+ "operationId": "patch_chat",+ "parameters": [+ {+ "name": "chat_id",+ "in": "path",+ "description": "ID of the chat",+ "required": true,+ "schema": {+ "type": "string"+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/PatchChatRequest"+ }+ }},- "404": {+ "required": true+ },+ "responses": {+ "200": {+ "description": ""+ },+ "401": {"description": "","content": {"text/plain": {@@ -118,16 +164,16 @@}}},- "/chats/history/{chat_id}": {- "get": {- "tags": ["chat_history"],- "summary": "Retrieves chat history for a specific chat ID",- "operationId": "get_chat_history_handler",+ "/chat/{chat_id}/permanent": {+ "delete": {+ "tags": ["chats"],+ "summary": "Permanently delete a chat and all associated data.",+ "operationId": "permanently_delete_chat","parameters": [{"name": "chat_id","in": "path",- "description": "Chat ID to retrieve history for",+ "description": "ID of the chat","required": true,"schema": {"type": "string"@@ -136,17 +182,10 @@],"responses": {"200": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/ChatHistory"- }- }- }+ "description": ""},- "404": {- "description": "Chat not found",+ "401": {+ "description": "","content": {"text/plain": {"schema": {@@ -156,7 +195,7 @@}},"500": {- "description": "Internal server error",+ "description": "","content": {"text/plain": {"schema": {@@ -168,16 +207,16 @@}}},- "/chats/history_batch_messages": {+ "/chats": {"post": {- "tags": ["chat_history_batch_messages"],- "summary": "Retrieves chat history for multiple message IDs",- "operationId": "get_chat_history_batch_messages_handler",+ "tags": ["chats"],+ "summary": "Create a new chat.",+ "operationId": "create_chat","requestBody": {"content": {"application/json": {"schema": {- "$ref": "#/components/schemas/ChatHistoryBatchMessagesRequest"+ "$ref": "#/components/schemas/CreateChatRequest"}}},@@ -189,23 +228,13 @@"content": {"application/json": {"schema": {- "$ref": "#/components/schemas/ChatHistory"- }- }- }- },- "403": {- "description": "Access denied to chat",- "content": {- "text/plain": {- "schema": {- "type": "string"+ "$ref": "#/components/schemas/StringIDResponse"}}}},- "404": {- "description": "Messages not found",+ "401": {+ "description": "","content": {"text/plain": {"schema": {@@ -215,7 +244,7 @@}},"500": {- "description": "Internal server error",+ "description": "","content": {"text/plain": {"schema": {@@ -227,16 +256,16 @@}}},- "/chats/{chat_id}": {+ "/chats/history/{chat_id}": {"get": {- "tags": ["get_chat"],- "summary": "Gets a particular chat by its id",- "operationId": "get_chat_handler",+ "tags": ["chat_history"],+ "summary": "Retrieves chat history for a specific chat ID",+ "operationId": "get_chat_history_handler","parameters": [{"name": "chat_id","in": "path",- "description": "id of the chat",+ "description": "Chat ID to retrieve history for","required": true,"schema": {"type": "string"@@ -249,23 +278,13 @@"content": {"application/json": {"schema": {- "$ref": "#/components/schemas/GetChatResponse"- }- }- }- },- "401": {- "description": "",- "content": {- "text/plain": {- "schema": {- "type": "string"+ "$ref": "#/components/schemas/ChatHistory"}}}},"404": {- "description": "",+ "description": "Chat not found","content": {"text/plain": {"schema": {@@ -275,7 +294,7 @@}},"500": {- "description": "",+ "description": "Internal server error","content": {"text/plain": {"schema": {@@ -285,35 +304,36 @@}}}- },- "delete": {- "tags": ["delete_chat"],- "summary": "Deletes a particular chat by its id.\nSoft deletes the chat.",- "operationId": "delete_chat_handler",- "parameters": [- {- "name": "chat_id",- "in": "path",- "description": "Chat id",- "required": true,- "schema": {- "type": "string"+ }+ },+ "/chats/history_batch_messages": {+ "post": {+ "tags": ["chat_history_batch_messages"],+ "summary": "Retrieves chat history for multiple message IDs",+ "operationId": "get_chat_history_batch_messages_handler",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ChatHistoryBatchMessagesRequest"+ }}- }- ],+ },+ "required": true+ },"responses": {"200": {"description": "","content": {"application/json": {"schema": {- "$ref": "#/components/schemas/EmptyResponse"+ "$ref": "#/components/schemas/ChatHistory"}}}},- "401": {- "description": "",+ "403": {+ "description": "Access denied to chat","content": {"text/plain": {"schema": {@@ -323,7 +343,7 @@}},"404": {- "description": "",+ "description": "Messages not found","content": {"text/plain": {"schema": {@@ -333,7 +353,7 @@}},"500": {- "description": "",+ "description": "Internal server error","content": {"text/plain": {"schema": {@@ -343,37 +363,37 @@}}}- },- "patch": {- "tags": ["patch_chat"],- "operationId": "patch_chat_handler",+ }+ },+ "/chats/{chat_id}": {+ "get": {+ "tags": ["chats"],+ "summary": "Get a chat by ID with messages and web citations.",+ "operationId": "get_chat","parameters": [{"name": "chat_id","in": "path",- "description": "Chat ID",+ "description": "ID of the chat","required": true,"schema": {"type": "string"}}],- "requestBody": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/PatchChatRequestV2"- }- }- },- "required": true- },"responses": {"200": {- "description": "Chat patched successfully"+ "description": "",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/GetChatResponse"+ }+ }+ }},- "400": {- "description": "Cannot modify deleted chat",+ "401": {+ "description": "","content": {"text/plain": {"schema": {@@ -382,7 +402,7 @@}}},- "401": {+ "404": {"description": "","content": {"text/plain": {@@ -407,31 +427,22 @@},"/chats/{chat_id}/copy": {"post": {- "tags": ["copy_chat"],- "operationId": "copy_chat_handler",+ "tags": ["chats"],+ "summary": "Copy a chat and its messages into a new chat.",+ "operationId": "copy_chat","parameters": [{"name": "chat_id","in": "path",- "description": "Chat id",+ "description": "ID of the chat to copy","required": true,"schema": {"type": "string"}}],- "requestBody": {- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/CopyChatRequest"- }- }- },- "required": true- },"responses": {- "201": {+ "200": {"description": "","content": {"application/json": {@@ -474,16 +485,16 @@}}},- "/chats/{chat_id}/permanent": {- "delete": {- "tags": ["delete_chat"],- "summary": "Permanently deletes a chat.",- "operationId": "permanently_delete_chat",+ "/chats/{chat_id}/permissions": {+ "get": {+ "tags": ["chats"],+ "summary": "Get the share permissions for a chat.",+ "operationId": "get_chat_permissions","parameters": [{"name": "chat_id","in": "path",- "description": "Chat id",+ "description": "ID of the chat","required": true,"schema": {"type": "string"@@ -496,7 +507,7 @@"content": {"application/json": {"schema": {- "$ref": "#/components/schemas/EmptyResponse"+ "$ref": "#/components/schemas/GetChatPermissionsResponse"}}}@@ -511,16 +522,6 @@}}},- "404": {- "description": "",- "content": {- "text/plain": {- "schema": {- "type": "string"- }- }- }- },"500": {"description": "","content": {@@ -536,14 +537,14 @@},"/chats/{chat_id}/revert_delete": {"put": {- "tags": ["chat"],- "summary": "Deletes a specific document",+ "tags": ["chats"],+ "summary": "Revert a soft-deleted chat.","operationId": "revert_delete_chat","parameters": [{"name": "chat_id","in": "path",- "description": "Chat ID",+ "description": "ID of the chat to restore","required": true,"schema": {"type": "string"@@ -552,31 +553,14 @@],"responses": {"200": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/SuccessResponse"- }- }- }+ "description": ""},"401": {"description": "","content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/GenericErrorResponse"- }- }- }- },- "404": {- "description": "",- "content": {- "application/json": {+ "text/plain": {"schema": {- "$ref": "#/components/schemas/GenericErrorResponse"+ "type": "string"}}}@@ -584,9 +568,9 @@"500": {"description": "","content": {- "application/json": {+ "text/plain": {"schema": {- "$ref": "#/components/schemas/GenericErrorResponse"+ "type": "string"}}}@@ -774,56 +758,6 @@}}}- },- "/v2/chats/{chat_id}/permissions": {- "get": {- "tags": ["get_chat_permissions"],- "summary": "Gets the current chat share permissions",- "operationId": "get_chat_permissions_handler_v2",- "parameters": [- {- "name": "chat_id",- "in": "path",- "description": "id of the chat",- "required": true,- "schema": {- "type": "string"- }- }- ],- "responses": {- "200": {- "description": "",- "content": {- "application/json": {- "schema": {- "$ref": "#/components/schemas/GetChatPermissionsResponseV2"- }- }- }- },- "404": {- "description": "",- "content": {- "text/plain": {- "schema": {- "type": "string"- }- }- }- },- "500": {- "description": "",- "content": {- "text/plain": {- "schema": {- "type": "string"- }- }- }- }- }- }}},"components": {@@ -1304,6 +1238,7 @@},"ChatResponse": {"type": "object",+ "description": "The full chat response, matching the DCS API response shape.","required": ["id","userId",@@ -1320,7 +1255,7 @@"items": {"$ref": "#/components/schemas/ChatAttachmentWithName"},- "description": "attachment context - attachments not attached to messages",+ "description": "Attachment context — attachments not attached to messages.","deprecated": true},"availableModels": {@@ -1328,27 +1263,27 @@"items": {"$ref": "#/components/schemas/Model"},- "description": "Available models for the chat"+ "description": "Available models for the chat."},"createdAt": {"type": ["string", "null"],"format": "date-time",- "description": "The time the chat was created"+ "description": "The time the chat was created."},"id": {"type": "string",- "description": "The chat uuid"+ "description": "The chat uuid."},"isPersistent": {"type": "boolean",- "description": "whether the chat is persistent or not"+ "description": "Whether the chat is persistent or not."},"messages": {"type": "array","items": {"$ref": "#/components/schemas/ChatMessageWithAttachments"},- "description": "The messages in the chat"+ "description": "The messages in the chat."},"model": {"oneOf": [@@ -1357,31 +1292,31 @@},{"$ref": "#/components/schemas/Model",- "description": "The model used to generate the chat"+ "description": "The model used to generate the chat."}]},"name": {"type": "string",- "description": "The name of the Chat"+ "description": "The name of the chat."},"projectId": {"type": ["string", "null"],- "description": "The project id the chat belongs to"+ "description": "The project id the chat belongs to."},"tokenCount": {"type": ["integer", "null"],"format": "int64",- "description": "Current number of tokens in the chat"+ "description": "Current number of tokens in the chat."},"updatedAt": {"type": ["string", "null"],"format": "date-time",- "description": "The time the chat was last updated"+ "description": "The time the chat was last updated."},"userId": {"type": "string",- "description": "Who the chat belongs to"+ "description": "Who the chat belongs to."},"webCitations": {"type": "array",@@ -1396,29 +1331,35 @@"type": "array","items": {"type": "object",+ "description": "A web citation associated with a chat message.","required": ["url", "title"],"properties": {"description": {- "type": ["string", "null"]+ "type": ["string", "null"],+ "description": "A description of the cited page."},"favicon_url": {- "type": ["string", "null"]+ "type": ["string", "null"],+ "description": "The URL of the page's favicon."},"image_url": {- "type": ["string", "null"]+ "type": ["string", "null"],+ "description": "The URL of the page's image."},"title": {- "type": "string"+ "type": "string",+ "description": "The title of the cited page."},"url": {- "type": "string"+ "type": "string",+ "description": "The URL of the citation."}}}}]},- "description": "message_id - web citation list"+ "description": "Message ID to web citation list."}}},@@ -1738,42 +1679,17 @@}}},- "CopyChatRequest": {- "type": "object",- "required": ["name"],- "properties": {- "name": {- "type": "string"- }- }- },"CreateChatRequest": {"type": "object",+ "description": "Request body for creating a chat.","properties": {- "attachments": {- "type": ["array", "null"],- "items": {- "$ref": "#/components/schemas/NewAttachment"- }- },- "isPersistent": {- "type": ["boolean", "null"]- },- "model": {- "oneOf": [- {- "type": "null"- },- {- "$ref": "#/components/schemas/Model"- }- ]- },"name": {- "type": ["string", "null"]+ "type": ["string", "null"],+ "description": "Optional name for the chat."},"projectId": {- "type": ["string", "null"]+ "type": ["string", "null"],+ "description": "Optional project to associate the chat with."}}},@@ -1817,10 +1733,6 @@}}},- "EmptyResponse": {- "type": "object",- "description": "Empty response is required due to custom fetch forcing `response.json()`"- },"ExtractionStatusEnum": {"oneOf": [{@@ -2307,16 +2219,6 @@}}},- "GenericSuccessResponse": {- "type": "object",- "required": ["success"],- "properties": {- "success": {- "type": "boolean",- "description": "Indicates if the request was successful"- }- }- },"GetBatchPreviewRequest": {"type": "object","required": ["chat_ids"],@@ -2341,33 +2243,29 @@}}},- "GetChatPathParams": {- "type": "object",- "required": ["chat_id"],- "properties": {- "chat_id": {- "type": "string"- }- }- },- "GetChatPermissionsResponseV2": {+ "GetChatPermissionsResponse": {"type": "object",+ "description": "Response body for get chat permissions.","required": ["permissions"],"properties": {"permissions": {- "$ref": "#/components/schemas/SharePermissionV2"+ "$ref": "#/components/schemas/SharePermissionV2",+ "description": "The share permissions for the chat."}}},"GetChatResponse": {"type": "object",+ "description": "Wrapper response for get_chat, matching the DCS API response shape.","required": ["chat", "userAccessLevel"],"properties": {"chat": {- "$ref": "#/components/schemas/ChatResponse"+ "$ref": "#/components/schemas/ChatResponse",+ "description": "The full chat data."},"userAccessLevel": {- "$ref": "#/components/schemas/AccessLevel"+ "$ref": "#/components/schemas/AccessLevel",+ "description": "The requesting user's access level on this chat."}}},@@ -2566,29 +2464,15 @@},"PatchChatRequest": {"type": "object",+ "description": "Request body for patching a chat.","properties": {- "model": {- "type": ["string", "null"]- },"name": {- "type": ["string", "null"]- },- "projectId": {- "type": ["string", "null"]- }- }- },- "PatchChatRequestV2": {- "type": "object",- "properties": {- "model": {- "type": ["string", "null"]- },- "name": {- "type": ["string", "null"]+ "type": ["string", "null"],+ "description": "New name for the chat."},"projectId": {- "type": ["string", "null"]+ "type": ["string", "null"],+ "description": "New project ID for the chat. Empty string clears the project."},"sharePermission": {"oneOf": [@@ -2596,7 +2480,8 @@"type": "null"},{- "$ref": "#/components/schemas/UpdateSharePermissionRequestV2"+ "$ref": "#/components/schemas/UpdateSharePermissionRequestV2",+ "description": "Share permission updates."}]}@@ -2764,20 +2649,6 @@}}},- "SuccessResponse": {- "type": "object",- "required": ["error", "data"],- "properties": {- "data": {- "$ref": "#/components/schemas/GenericSuccessResponse",- "description": "Data to be returned"- },- "error": {- "type": "boolean",- "description": "Indicates if an error occurred"- }- }- },"ToolSchema": {"type": "object","description": "Schema information for a single tool, serializable for API responses.",@@ -2917,6 +2788,33 @@}}},+ "WebCitation": {+ "type": "object",+ "description": "A web citation associated with a chat message.",+ "required": ["url", "title"],+ "properties": {+ "description": {+ "type": ["string", "null"],+ "description": "A description of the cited page."+ },+ "favicon_url": {+ "type": ["string", "null"],+ "description": "The URL of the page's favicon."+ },+ "image_url": {+ "type": ["string", "null"],+ "description": "The URL of the page's image."+ },+ "title": {+ "type": "string",+ "description": "The title of the cited page."+ },+ "url": {+ "type": "string",+ "description": "The URL of the citation."+ }+ }+ },"WithChatId": {"type": "object","required": ["chat_id"],diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 0feca9162c..da8bffd93b 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -1817,6 +1817,33 @@ dependencies = ["encoding_rs",]+[[package]]+name = "chat"+version = "0.1.0"+dependencies = [+ "ai",+ "anyhow",+ "axum",+ "chrono",+ "entity_access",+ "http-body-util",+ "macro_db_migrator",+ "macro_share_permissions",+ "macro_user_id",+ "macro_uuid",+ "model",+ "model_user",+ "models_permissions",+ "serde",+ "serde_json",+ "sqlx",+ "thiserror 2.0.17",+ "tokio",+ "tower 0.5.2",+ "tracing",+ "utoipa",+]+[[package]]name = "chrono"version = "0.4.42"@@ -2872,6 +2899,7 @@ dependencies = ["aws-sdk-sqs","axum","base64 0.22.1",+ "chat","chrono","comms","comms_service_client",diff --git a/rust/cloud-storage/Cargo.toml b/rust/cloud-storage/Cargo.tomlindex 9fec5f2b2a..a845bfa0c4 100644--- a/rust/cloud-storage/Cargo.toml+++ b/rust/cloud-storage/Cargo.toml@@ -10,7 +10,7 @@ members = ["anthropic","authentication_service","authentication_service_client",- "channels",+ "channels", "chat","comms_db_client","comms_service","comms_service_client",diff --git a/rust/cloud-storage/chat/.sqlx/query-0a09ebd68d563695e964576ff60f6a415013c83185c3c325f6b82f44877c8465.json b/rust/cloud-storage/chat/.sqlx/query-0a09ebd68d563695e964576ff60f6a415013c83185c3c325f6b82f44877c8465.jsonnew file mode 100644index 0000000000..8d162160b9--- /dev/null+++ b/rust/cloud-storage/chat/.sqlx/query-0a09ebd68d563695e964576ff60f6a415013c83185c3c325f6b82f44877c8465.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT \"access_level\"::text\n FROM \"UserItemAccess\"\n WHERE \"user_id\" = $1 AND \"item_id\" = $2 AND \"item_type\" = 'chat'\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "access_level",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Text"+ ]+ },+ "nullable": [+ null+ ]+ },+ "hash": "0a09ebd68d563695e964576ff60f6a415013c83185c3c325f6b82f44877c8465"+}diff --git a/rust/cloud-storage/chat/.sqlx/query-205c24d0647adde8fd03d37aa37fce4a37f75e0b9796a77bb45d0ebb3264928a.json b/rust/cloud-storage/chat/.sqlx/query-205c24d0647adde8fd03d37aa37fce4a37f75e0b9796a77bb45d0ebb3264928a.jsonnew file mode 100644index 0000000000..044d5bf983--- /dev/null+++ b/rust/cloud-storage/chat/.sqlx/query-205c24d0647adde8fd03d37aa37fce4a37f75e0b9796a77bb45d0ebb3264928a.json@@ -0,0 +1,52 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n \"messageId\" as \"message_id\",\n \"url\",\n \"title\",\n \"description\",\n \"favicon_url\",\n \"image_url\"\n FROM \"WebAnnotations\" wa\n INNER JOIN \"ChatMessage\" cm ON cm.id = wa.\"messageId\"\n WHERE cm.\"chatId\" = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "message_id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "url",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "title",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "description",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "favicon_url",+ "type_info": "Text"+ },+ {+ "ordinal": 5,+ "name": "image_url",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ true,+ false,+ false,+ true,+ true,+ true+ ]+ },+ "hash": "205c24d0647adde8fd03d37aa37fce4a37f75e0b9796a77bb45d0ebb3264928a"+}diff --git a/rust/cloud-storage/chat/.sqlx/query-34cf0289f36241df424661c22080748ca056ffa883a4cdba1652b7b8500ba179.json b/rust/cloud-storage/chat/.sqlx/query-34cf0289f36241df424661c22080748ca056ffa883a4cdba1652b7b8500ba179.jsonnew file mode 100644index 0000000000..e59236c0f1--- /dev/null+++ b/rust/cloud-storage/chat/.sqlx/query-34cf0289f36241df424661c22080748ca056ffa883a4cdba1652b7b8500ba179.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO \"ChatMessage\" (\"chatId\", \"createdAt\", \"updatedAt\", \"content\", \"role\", \"model\")\n SELECT $1, \"createdAt\", \"updatedAt\", \"content\", \"role\", \"model\"\n FROM \"ChatMessage\"\n WHERE \"chatId\" = $2\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "34cf0289f36241df424661c22080748ca056ffa883a4cdba1652b7b8500ba179"+}diff --git a/rust/cloud-storage/chat/.sqlx/query-34e06c7ad5a9ddb12ac9bdfb86a0ab6388547e69762533e204f39af71d0e68ee.json b/rust/cloud-storage/chat/.sqlx/query-34e06c7ad5a9ddb12ac9bdfb86a0ab6388547e69762533e204f39af71d0e68ee.jsonnew file mode 100644index 0000000000..201e76778f--- /dev/null+++ b/rust/cloud-storage/chat/.sqlx/query-34e06c7ad5a9ddb12ac9bdfb86a0ab6388547e69762533e204f39af71d0e68ee.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO \"UserHistory\" (\"userId\", \"itemId\", \"itemType\", \"createdAt\", \"updatedAt\")\n VALUES ($1, $2, 'chat', NOW(), NOW())\n ON CONFLICT (\"userId\", \"itemId\", \"itemType\") DO UPDATE\n SET \"updatedAt\" = NOW()\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "34e06c7ad5a9ddb12ac9bdfb86a0ab6388547e69762533e204f39af71d0e68ee"+}diff --git a/rust/cloud-storage/chat/.sqlx/query-38100c858a13cb36daa9ab6dce62d5d8755152a4d61877318d709aeee6d7a7cc.json b/rust/cloud-storage/chat/.sqlx/query-38100c858a13cb36daa9ab6dce62d5d8755152a4d61877318d709aeee6d7a7cc.jsonnew file mode 100644index 0000000000..c3966b8c2d--- /dev/null+++ b/rust/cloud-storage/chat/.sqlx/query-38100c858a13cb36daa9ab6dce62d5d8755152a4d61877318d709aeee6d7a7cc.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM \"UserItemAccess\" WHERE \"item_id\" = $1 AND \"item_type\" = 'chat'",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "38100c858a13cb36daa9ab6dce62d5d8755152a4d61877318d709aeee6d7a7cc"+}diff --git a/rust/cloud-storage/chat/.sqlx/query-3aefae84fc5944abc5595794391ccac5a746205e3c1bbd0bd37b114a67b40bb0.json b/rust/cloud-storage/chat/.sqlx/query-3aefae84fc5944abc5595794391ccac5a746205e3c1bbd0bd37b114a67b40bb0.jsonnew file mode 100644index 0000000000..96144043c3--- /dev/null+++ b/rust/cloud-storage/chat/.sqlx/query-3aefae84fc5944abc5595794391ccac5a746205e3c1bbd0bd37b114a67b40bb0.json@@ -0,0 +1,46 @@+{+ "db_name": "PostgreSQL",+ "query": "\n WITH attachment_info AS (\n SELECT\n ca.id,\n ca.\"attachmentType\",\n ca.\"attachmentId\",\n ca.\"messageId\",\n CASE\n WHEN ca.\"attachmentType\" = 'document' THEN d.name\n WHEN ca.\"attachmentType\" = 'chat' THEN c.name\n WHEN ca.\"attachmentType\" = 'project' THEN p.name\n WHEN ca.\"attachmentType\" = 'image' THEN d.name\n ELSE NULL\n END AS document_name,\n CASE\n WHEN ca.\"attachmentType\" = 'document' THEN d.\"fileType\"\n WHEN ca.\"attachmentType\" = 'image' THEN d.\"fileType\"\n ELSE NULL\n END as document_type\n FROM\n \"ChatAttachment\" ca\n LEFT JOIN\n \"Document\" d ON (\n (ca.\"attachmentType\" = 'document' AND ca.\"attachmentId\" = d.id)\n OR\n (ca.\"attachmentType\" = 'image' AND ca.\"attachmentId\" = d.id)\n )\n LEFT JOIN\n \"Chat\" c ON ca.\"attachmentType\" = 'chat' AND ca.\"attachmentId\" = c.id\n LEFT JOIN\n \"Project\" p ON ca.\"attachmentType\" = 'project' AND ca.\"attachmentId\" = p.id\n )\n SELECT\n cm.id AS \"id!\",\n cm.content,\n cm.role,\n cm.model,\n COALESCE(\n (\n SELECT json_agg(\n json_build_object(\n 'id', attachment_info.\"attachmentId\",\n 'attachmentType', attachment_info.\"attachmentType\",\n 'attachmentId', attachment_info.\"attachmentId\",\n 'documentName', attachment_info.document_name,\n 'documentType', attachment_info.document_type\n )\n )\n FROM attachment_info\n WHERE attachment_info.\"messageId\" = cm.id\n ),\n '[]'::json\n ) AS attachments\n FROM\n \"ChatMessage\" cm\n WHERE\n cm.\"chatId\" = $1\n ORDER BY\n cm.\"createdAt\" ASC\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id!",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "content",+ "type_info": "Jsonb"+ },+ {+ "ordinal": 2,+ "name": "role",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "model",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "attachments",+ "type_info": "Json"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ true,+ null+ ]+ },+ "hash": "3aefae84fc5944abc5595794391ccac5a746205e3c1bbd0bd37b114a67b40bb0"+}diff --git a/rust/cloud-storage/chat/.sqlx/query-3e333cb74dc40b2af8d6f9ed74105709ccaeca68b0ff0906e2f6be307963b49f.json b/rust/cloud-storage/chat/.sqlx/query-3e333cb74dc40b2af8d6f9ed74105709ccaeca68b0ff0906e2f6be307963b49f.jsonnew file mode 100644index 0000000000..3f1f35a9f8--- /dev/null+++ b/rust/cloud-storage/chat/.sqlx/query-3e333cb74dc40b2af8d6f9ed74105709ccaeca68b0ff0906e2f6be307963b49f.json@@ -0,0 +1,23 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO \"SharePermission\" (\"isPublic\", \"publicAccessLevel\", \"createdAt\", \"updatedAt\")\n VALUES ($1, $2, NOW(), NOW())\n RETURNING id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Bool",+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "3e333cb74dc40b2af8d6f9ed74105709ccaeca68b0ff0906e2f6be307963b49f"+}diff --git a/rust/cloud-storage/chat/.sqlx/query-3f518302c857be0e5aa9180c4cb50a316694bb9210e88c664c4f998fd5759fb3.json b/rust/cloud-storage/chat/.sqlx/query-3f518302c857be0e5aa9180c4cb50a316694bb9210e88c664c4f998fd5759fb3.jsonnew file mode 100644index 0000000000..c10bb1161a--- /dev/null+++ b/rust/cloud-storage/chat/.sqlx/query-3f518302c857be0e5aa9180c4cb50a316694bb9210e88c664c4f998fd5759fb3.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO \"ItemLastAccessed\" (\"item_id\", \"item_type\", \"last_accessed\")\n VALUES ($1, 'chat', NOW())\n ON CONFLICT (\"item_id\", \"item_type\") DO UPDATE\n SET \"last_accessed\" = NOW()\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "3f518302c857be0e5aa9180c4cb50a316694bb9210e88c664c4f998fd5759fb3"+}diff --git a/rust/cloud-storage/chat/.sqlx/query-411177d8b75b7150971074b41fd825873d729e28915a0fd36335b36494a93c53.json b/rust/cloud-storage/chat/.sqlx/query-411177d8b75b7150971074b41fd825873d729e28915a0fd36335b36494a93c53.jsonnew file mode 100644index 0000000000..c832a3e0d2--- /dev/null+++ b/rust/cloud-storage/chat/.sqlx/query-411177d8b75b7150971074b41fd825873d729e28915a0fd36335b36494a93c53.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE \"Chat\" SET \"projectId\" = $1 WHERE id = $2",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "411177d8b75b7150971074b41fd825873d729e28915a0fd36335b36494a93c53"+}diff --git a/rust/cloud-storage/chat/.sqlx/query-42e46f8f1c2cbf80383f65dd19d4efa3ae9c2697363d56278789de68b2295366.json b/rust/cloud-storage/chat/.sqlx/query-42e46f8f1c2cbf80383f65dd19d4efa3ae9c2697363d56278789de68b2295366.jsonnew file mode 100644index 0000000000..018330cc92--- /dev/null+++ b/rust/cloud-storage/chat/.sqlx/query-42e46f8f1c2cbf80383f65dd19d4efa3ae9c2697363d56278789de68b2295366.json@@ -0,0 +1,24 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO \"Chat\" (\"userId\", name, \"projectId\")\n VALUES ($1, $2, $3)\n RETURNING id\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "42e46f8f1c2cbf80383f65dd19d4efa3ae9c2697363d56278789de68b2295366"+}diff --git a/rust/cloud-storage/chat/.sqlx/query-45063eedc20b7eb86019e69545c2e8b441f1e9e067086b05617437b6f43bc329.json b/rust/cloud-storage/chat/.sqlx/query-45063eedc20b7eb86019e69545c2e8b441f1e9e067086b05617437b6f43bc329.jsonnew file mode 100644index 0000000000..6a8b3392e5--- /dev/null+++ b/rust/cloud-storage/chat/.sqlx/query-45063eedc20b7eb86019e69545c2e8b441f1e9e067086b05617437b6f43bc329.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE \"Chat\"\n SET \"deletedAt\" = NULL\n WHERE id = $1\n RETURNING \"userId\" as owner\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "owner",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "45063eedc20b7eb86019e69545c2e8b441f1e9e067086b05617437b6f43bc329"+}diff --git a/rust/cloud-storage/chat/.sqlx/query-4e9e26869da9b5473f0876a70c68dd69f6539902e580bdeaeaabdbf4d72793ef.json b/rust/cloud-storage/chat/.sqlx/query-4e9e26869da9b5473f0876a70c68dd69f6539902e580bdeaeaabdbf4d72793ef.jsonnew file mode 100644index 0000000000..ad1c3e2279--- /dev/null+++ b/rust/cloud-storage/chat/.sqlx/query-4e9e26869da9b5473f0876a70c68dd69f6539902e580bdeaeaabdbf4d72793ef.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n UPDATE \"Chat\" SET \"projectId\" = NULL WHERE \"id\" = $1\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "4e9e26869da9b5473f0876a70c68dd69f6539902e580bdeaeaabdbf4d72793ef"+}diff --git a/rust/cloud-storage/chat/.sqlx/query-58bf14acad4a08a6fa2da18e244676169f0bc6f606b04b1e8e3080fe95717b41.json b/rust/cloud-storage/chat/.sqlx/query-58bf14acad4a08a6fa2da18e244676169f0bc6f606b04b1e8e3080fe95717b41.jsonnew file mode 100644index 0000000000..2a861ab825--- /dev/null+++ b/rust/cloud-storage/chat/.sqlx/query-58bf14acad4a08a6fa2da18e244676169f0bc6f606b04b1e8e3080fe95717b41.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT \"deletedAt\" as deleted_at FROM \"Project\" WHERE \"id\" = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "deleted_at",+ "type_info": "Timestamp"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ true+ ]+ },+ "hash": "58bf14acad4a08a6fa2da18e244676169f0bc6f606b04b1e8e3080fe95717b41"+}diff --git a/rust/cloud-storage/chat/.sqlx/query-6ce4faf9e5f20226d7e2fad64816fe432ac1128af2df592077c848e75009509d.json b/rust/cloud-storage/chat/.sqlx/query-6ce4faf9e5f20226d7e2fad64816fe432ac1128af2df592077c848e75009509d.jsonnew file mode 100644index 0000000000..8022a373f9--- /dev/null+++ b/rust/cloud-storage/chat/.sqlx/query-6ce4faf9e5f20226d7e2fad64816fe432ac1128af2df592077c848e75009509d.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE \"Chat\" SET \"deletedAt\" = NOW() WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "6ce4faf9e5f20226d7e2fad64816fe432ac1128af2df592077c848e75009509d"+}diff --git a/rust/cloud-storage/chat/.sqlx/query-72c4ec37d0b5c963e6061e040ab7184e2e6623e487afc52358f77f57d236a255.json b/rust/cloud-storage/chat/.sqlx/query-72c4ec37d0b5c963e6061e040ab7184e2e6623e487afc52358f77f57d236a255.jsonnew file mode 100644index 0000000000..c4a9e7a6ed--- /dev/null+++ b/rust/cloud-storage/chat/.sqlx/query-72c4ec37d0b5c963e6061e040ab7184e2e6623e487afc52358f77f57d236a255.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM \"UserHistory\" WHERE \"itemId\" = $1 AND \"itemType\" = 'chat'",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "72c4ec37d0b5c963e6061e040ab7184e2e6623e487afc52358f77f57d236a255"+}diff --git a/rust/cloud-storage/chat/.sqlx/query-79ac6b0966afc0c5472e3d5589e940bf0d6d2c4280e69b09b4f7c8839b5ad658.json b/rust/cloud-storage/chat/.sqlx/query-79ac6b0966afc0c5472e3d5589e940bf0d6d2c4280e69b09b4f7c8839b5ad658.jsonnew file mode 100644index 0000000000..4b480ba3d9--- /dev/null+++ b/rust/cloud-storage/chat/.sqlx/query-79ac6b0966afc0c5472e3d5589e940bf0d6d2c4280e69b09b4f7c8839b5ad658.json@@ -0,0 +1,76 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n id,\n name,\n model,\n \"userId\" as \"user_id\",\n \"createdAt\"::timestamptz as \"created_at\",\n \"updatedAt\"::timestamptz as \"updated_at\",\n \"deletedAt\"::timestamptz as \"deleted_at\",\n \"projectId\" as \"project_id\",\n \"tokenCount\" as \"token_count\",\n \"isPersistent\" as \"is_persistent\"\n FROM \"Chat\"\n WHERE id = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "name",+ "type_info": "Text"+ },+ {+ "ordinal": 2,+ "name": "model",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "user_id",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "created_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 5,+ "name": "updated_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 6,+ "name": "deleted_at",+ "type_info": "Timestamptz"+ },+ {+ "ordinal": 7,+ "name": "project_id",+ "type_info": "Text"+ },+ {+ "ordinal": 8,+ "name": "token_count",+ "type_info": "Int8"+ },+ {+ "ordinal": 9,+ "name": "is_persistent",+ "type_info": "Bool"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ false,+ false,+ null,+ null,+ null,+ true,+ true,+ false+ ]+ },+ "hash": "79ac6b0966afc0c5472e3d5589e940bf0d6d2c4280e69b09b4f7c8839b5ad658"+}diff --git a/rust/cloud-storage/chat/.sqlx/query-a4daed99335672e203439ce74d8697936821511404ffb49c7ca4b8134e9c9147.json b/rust/cloud-storage/chat/.sqlx/query-a4daed99335672e203439ce74d8697936821511404ffb49c7ca4b8134e9c9147.jsonnew file mode 100644index 0000000000..4ca3ec3920--- /dev/null+++ b/rust/cloud-storage/chat/.sqlx/query-a4daed99335672e203439ce74d8697936821511404ffb49c7ca4b8134e9c9147.json@@ -0,0 +1,46 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT\n sp.id as id,\n sp.\"isPublic\" as is_public,\n sp.\"publicAccessLevel\" as \"public_access_level?\",\n c.\"userId\" as owner,\n COALESCE(\n json_agg(json_build_object(\n 'channel_id', csp.\"channel_id\",\n 'access_level', csp.\"access_level\"\n )) FILTER (WHERE csp.\"channel_id\" IS NOT NULL),\n '[]'\n ) as \"channel_share_permissions?\"\n FROM\n \"ChatPermission\" cp\n JOIN \"SharePermission\" sp ON cp.\"sharePermissionId\" = sp.id\n JOIN \"Chat\" c ON cp.\"chatId\" = c.id\n LEFT JOIN \"ChannelSharePermission\" csp ON csp.\"share_permission_id\" = sp.id\n WHERE\n cp.\"chatId\" = $1\n GROUP BY\n sp.id, c.\"userId\"\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Text"+ },+ {+ "ordinal": 1,+ "name": "is_public",+ "type_info": "Bool"+ },+ {+ "ordinal": 2,+ "name": "public_access_level?",+ "type_info": "Text"+ },+ {+ "ordinal": 3,+ "name": "owner",+ "type_info": "Text"+ },+ {+ "ordinal": 4,+ "name": "channel_share_permissions?",+ "type_info": "Json"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ false,+ true,+ false,+ null+ ]+ },+ "hash": "a4daed99335672e203439ce74d8697936821511404ffb49c7ca4b8134e9c9147"+}diff --git a/rust/cloud-storage/chat/.sqlx/query-aae2ef0d294ae7736898e9b32be12cfabedfb8164af00cdb4a52c9d1f98229af.json b/rust/cloud-storage/chat/.sqlx/query-aae2ef0d294ae7736898e9b32be12cfabedfb8164af00cdb4a52c9d1f98229af.jsonnew file mode 100644index 0000000000..f0aa53f429--- /dev/null+++ b/rust/cloud-storage/chat/.sqlx/query-aae2ef0d294ae7736898e9b32be12cfabedfb8164af00cdb4a52c9d1f98229af.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM \"Chat\" WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "aae2ef0d294ae7736898e9b32be12cfabedfb8164af00cdb4a52c9d1f98229af"+}diff --git a/rust/cloud-storage/chat/.sqlx/query-b08f21bc79644b7ae980ef17ea38f60be7749e48143ad40a164b236e977157f3.json b/rust/cloud-storage/chat/.sqlx/query-b08f21bc79644b7ae980ef17ea38f60be7749e48143ad40a164b236e977157f3.jsonnew file mode 100644index 0000000000..4327d95754--- /dev/null+++ b/rust/cloud-storage/chat/.sqlx/query-b08f21bc79644b7ae980ef17ea38f60be7749e48143ad40a164b236e977157f3.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO \"ChannelSharePermission\" (\"share_permission_id\", \"channel_id\", \"access_level\")\n SELECT $1, channel_id, access_level::\"AccessLevel\"\n FROM UNNEST($2::text[], $3::text[]) AS t(channel_id, access_level)\n ON CONFLICT (\"share_permission_id\", \"channel_id\")\n DO UPDATE SET \"access_level\" = EXCLUDED.\"access_level\"\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "TextArray",+ "TextArray"+ ]+ },+ "nullable": []+ },+ "hash": "b08f21bc79644b7ae980ef17ea38f60be7749e48143ad40a164b236e977157f3"+}diff --git a/rust/cloud-storage/chat/.sqlx/query-b43285d8bb2b9758fcc84c13979c3a54ffc28abf61e66e354667d26ef3c40739.json b/rust/cloud-storage/chat/.sqlx/query-b43285d8bb2b9758fcc84c13979c3a54ffc28abf61e66e354667d26ef3c40739.jsonnew file mode 100644index 0000000000..7fae9257bc--- /dev/null+++ b/rust/cloud-storage/chat/.sqlx/query-b43285d8bb2b9758fcc84c13979c3a54ffc28abf61e66e354667d26ef3c40739.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO \"ChatPermission\" (\"chatId\", \"sharePermissionId\")\n VALUES ($1, $2)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "b43285d8bb2b9758fcc84c13979c3a54ffc28abf61e66e354667d26ef3c40739"+}diff --git a/rust/cloud-storage/chat/.sqlx/query-b46b2b51f07ec4fc65cd158b210ce262e9ab44f10825969072c01a8fe3022a23.json b/rust/cloud-storage/chat/.sqlx/query-b46b2b51f07ec4fc65cd158b210ce262e9ab44f10825969072c01a8fe3022a23.jsonnew file mode 100644index 0000000000..93348ea121--- /dev/null+++ b/rust/cloud-storage/chat/.sqlx/query-b46b2b51f07ec4fc65cd158b210ce262e9ab44f10825969072c01a8fe3022a23.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM \"ChannelSharePermission\"\n WHERE \"share_permission_id\" = $1\n AND \"channel_id\" = ANY($2)\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "TextArray"+ ]+ },+ "nullable": []+ },+ "hash": "b46b2b51f07ec4fc65cd158b210ce262e9ab44f10825969072c01a8fe3022a23"+}diff --git a/rust/cloud-storage/chat/.sqlx/query-b805dc1d8b2143dbf9adc0e5478b204219a94105e0ba590db0a97f2c384a4192.json b/rust/cloud-storage/chat/.sqlx/query-b805dc1d8b2143dbf9adc0e5478b204219a94105e0ba590db0a97f2c384a4192.jsonnew file mode 100644index 0000000000..6cf702fd3f--- /dev/null+++ b/rust/cloud-storage/chat/.sqlx/query-b805dc1d8b2143dbf9adc0e5478b204219a94105e0ba590db0a97f2c384a4192.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO \"UserHistory\" (\"userId\", \"itemId\", \"itemType\", \"createdAt\", \"updatedAt\")\n VALUES ($1, $2, $3, NOW(), NOW())\n ON CONFLICT (\"userId\", \"itemId\", \"itemType\") DO UPDATE\n SET \"updatedAt\" = NOW();\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "b805dc1d8b2143dbf9adc0e5478b204219a94105e0ba590db0a97f2c384a4192"+}diff --git a/rust/cloud-storage/chat/.sqlx/query-b8284f96e44ea8442487dd5c99733eab3722a94e49bf01605f69c78919d8bff7.json b/rust/cloud-storage/chat/.sqlx/query-b8284f96e44ea8442487dd5c99733eab3722a94e49bf01605f69c78919d8bff7.jsonnew file mode 100644index 0000000000..5c523361fb--- /dev/null+++ b/rust/cloud-storage/chat/.sqlx/query-b8284f96e44ea8442487dd5c99733eab3722a94e49bf01605f69c78919d8bff7.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "\n DELETE FROM \"SharePermission\"\n WHERE id IN (\n SELECT \"sharePermissionId\"\n FROM \"ChatPermission\"\n WHERE \"chatId\" = $1\n )\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "b8284f96e44ea8442487dd5c99733eab3722a94e49bf01605f69c78919d8bff7"+}diff --git a/rust/cloud-storage/chat/.sqlx/query-ba3ab3dc338552f6b794ab5405655fe673e71f02106e9792cc4cac40f69b9176.json b/rust/cloud-storage/chat/.sqlx/query-ba3ab3dc338552f6b794ab5405655fe673e71f02106e9792cc4cac40f69b9176.jsonnew file mode 100644index 0000000000..2c166c9c2a--- /dev/null+++ b/rust/cloud-storage/chat/.sqlx/query-ba3ab3dc338552f6b794ab5405655fe673e71f02106e9792cc4cac40f69b9176.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "DELETE FROM \"Pin\" WHERE \"pinnedItemId\" = $1 AND \"pinnedItemType\" = 'chat'",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "ba3ab3dc338552f6b794ab5405655fe673e71f02106e9792cc4cac40f69b9176"+}diff --git a/rust/cloud-storage/chat/.sqlx/query-c78296b868c8a8657e5c2296049fa4809abee07e9fd473a5e9ae00ad8625a108.json b/rust/cloud-storage/chat/.sqlx/query-c78296b868c8a8657e5c2296049fa4809abee07e9fd473a5e9ae00ad8625a108.jsonnew file mode 100644index 0000000000..5cd49428ff--- /dev/null+++ b/rust/cloud-storage/chat/.sqlx/query-c78296b868c8a8657e5c2296049fa4809abee07e9fd473a5e9ae00ad8625a108.json@@ -0,0 +1,15 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE \"Chat\" SET \"name\" = $1 WHERE id = $2",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text",+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "c78296b868c8a8657e5c2296049fa4809abee07e9fd473a5e9ae00ad8625a108"+}diff --git a/rust/cloud-storage/chat/.sqlx/query-c9ff8e2deb86a25e4e0e16c9de66a5c116b68362ec45ffea5e2b25d86cfccf01.json b/rust/cloud-storage/chat/.sqlx/query-c9ff8e2deb86a25e4e0e16c9de66a5c116b68362ec45ffea5e2b25d86cfccf01.jsonnew file mode 100644index 0000000000..186691e7f3--- /dev/null+++ b/rust/cloud-storage/chat/.sqlx/query-c9ff8e2deb86a25e4e0e16c9de66a5c116b68362ec45ffea5e2b25d86cfccf01.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE \"Chat\" SET \"updatedAt\" = NOW() WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "c9ff8e2deb86a25e4e0e16c9de66a5c116b68362ec45ffea5e2b25d86cfccf01"+}diff --git a/rust/cloud-storage/chat/.sqlx/query-cc0889c0d1cb757fce4cbfbb58eaefb065d608c3866d2707edfec8e907c460c1.json b/rust/cloud-storage/chat/.sqlx/query-cc0889c0d1cb757fce4cbfbb58eaefb065d608c3866d2707edfec8e907c460c1.jsonnew file mode 100644index 0000000000..d0c38172a9--- /dev/null+++ b/rust/cloud-storage/chat/.sqlx/query-cc0889c0d1cb757fce4cbfbb58eaefb065d608c3866d2707edfec8e907c460c1.json@@ -0,0 +1,14 @@+{+ "db_name": "PostgreSQL",+ "query": "UPDATE \"Chat\" SET \"projectId\" = NULL WHERE id = $1",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": []+ },+ "hash": "cc0889c0d1cb757fce4cbfbb58eaefb065d608c3866d2707edfec8e907c460c1"+}diff --git a/rust/cloud-storage/chat/.sqlx/query-d3f415b0ff9b73a69fae932e99e3a2b24145f15e940d79721f00b76864fee3da.json b/rust/cloud-storage/chat/.sqlx/query-d3f415b0ff9b73a69fae932e99e3a2b24145f15e940d79721f00b76864fee3da.jsonnew file mode 100644index 0000000000..f77b255645--- /dev/null+++ b/rust/cloud-storage/chat/.sqlx/query-d3f415b0ff9b73a69fae932e99e3a2b24145f15e940d79721f00b76864fee3da.json@@ -0,0 +1,29 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO \"UserItemAccess\" (\n \"id\",\n \"user_id\",\n \"item_id\",\n \"item_type\",\n \"access_level\",\n \"created_at\",\n \"updated_at\"\n )\n VALUES ($1, $2, $3, 'chat', $4, NOW(), NOW())\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "Uuid",+ "Text",+ "Text",+ {+ "Custom": {+ "name": "\"AccessLevel\"",+ "kind": {+ "Enum": [+ "view",+ "edit",+ "owner",+ "comment"+ ]+ }+ }+ }+ ]+ },+ "nullable": []+ },+ "hash": "d3f415b0ff9b73a69fae932e99e3a2b24145f15e940d79721f00b76864fee3da"+}diff --git a/rust/cloud-storage/chat/.sqlx/query-e792f05e8ff1bba6124255b61ae57b1429cb22745012c396910f2fa549aedf79.json b/rust/cloud-storage/chat/.sqlx/query-e792f05e8ff1bba6124255b61ae57b1429cb22745012c396910f2fa549aedf79.jsonnew file mode 100644index 0000000000..bfb19c8735--- /dev/null+++ b/rust/cloud-storage/chat/.sqlx/query-e792f05e8ff1bba6124255b61ae57b1429cb22745012c396910f2fa549aedf79.json@@ -0,0 +1,22 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT cp.\"sharePermissionId\" as share_permission_id\n FROM \"ChatPermission\" cp\n WHERE cp.\"chatId\" = $1\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "share_permission_id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "e792f05e8ff1bba6124255b61ae57b1429cb22745012c396910f2fa549aedf79"+}diff --git a/rust/cloud-storage/chat/Cargo.toml b/rust/cloud-storage/chat/Cargo.tomlnew file mode 100644index 0000000000..db0bb40482--- /dev/null+++ b/rust/cloud-storage/chat/Cargo.toml@@ -0,0 +1,44 @@+[package]+name = "chat"+version = "0.1.0"+edition = "2024"+publish = false++[features]+default = ["ports", "inbound", "outbound"]+ports = []+inbound = ["ports", "dep:axum", "dep:model_user", "entity_access/inbound"]+outbound = ["ports", "dep:sqlx", "dep:macro_share_permissions", "dep:macro_uuid"]++[dependencies]+# Domain (always included)+ai = { path = "../ai" }+anyhow = { workspace = true }+entity_access = { path = "../entity_access", default-features = false }+chrono = { workspace = true }+macro_user_id = { path = "../macro_user_id" }+model = { path = "../model" }+models_permissions = { path = "../models_permissions" }+serde = { workspace = true }+serde_json = { workspace = true }+thiserror = { workspace = true }+tokio = { workspace = true }+tracing = { workspace = true }++# Inbound (HTTP handlers)+axum = { workspace = true, optional = true }+model_user = { path = "../model_user", optional = true }+utoipa = { workspace = true }++# Outbound (database adapters)+macro_share_permissions = { path = "../macro_share_permissions", optional = true }+sqlx = { workspace = true, optional = true }++macro_uuid = { path = "../macro_uuid", optional = true }++[dev-dependencies]+http-body-util = { workspace = true }+macro_db_migrator = { path = "../macro_db_migrator" }+serde_json = { workspace = true }+tokio = { workspace = true }+tower = { workspace = true }diff --git a/rust/cloud-storage/chat/src/domain.rs b/rust/cloud-storage/chat/src/domain.rsnew file mode 100644index 0000000000..cdf30c531c--- /dev/null+++ b/rust/cloud-storage/chat/src/domain.rs@@ -0,0 +1,6 @@+/// Types used by the chat domain ports.+pub mod models;+/// Port traits defining the chat domain boundaries.+pub mod ports;+/// Default service implementation.+pub mod service;diff --git a/rust/cloud-storage/chat/src/domain/models.rs b/rust/cloud-storage/chat/src/domain/models.rsnew file mode 100644index 0000000000..5ea6dc4a5c--- /dev/null+++ b/rust/cloud-storage/chat/src/domain/models.rs@@ -0,0 +1,110 @@+//! Types and errors used by the chat domain ports.++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),+}++/// Arguments for creating a new chat.+#[derive(Debug)]+pub struct CreateChatArgs {+ /// The name of the chat.+ pub name: String,+ /// The project to associate the chat with.+ pub project_id: Option<String>,+}++/// Arguments for copying a chat.+#[derive(Debug)]+pub struct CopyChatArgs {+ /// The name for the new (copied) chat.+ pub name: String,+ /// The project to place the copy in (may differ from the source).+ pub project_id: Option<String>,+}++/// Arguments for patching a chat.+#[derive(Debug)]+pub struct PatchChatArgs {+ /// New name for the chat, if changing.+ pub name: Option<String>,+ /// New project ID for the chat, if moving. Empty string clears the project.+ pub project_id: Option<String>,+ /// Share permission updates, if changing.+ pub share_permission:+ 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")]+pub struct GetChatResponse {+ /// The full chat data.+ pub chat: ChatResponse,+ /// The requesting user's access level on this chat.+ pub user_access_level: AccessLevel,+}++/// The full chat response, matching the DCS API response shape.+#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct ChatResponse {+ /// The chat uuid.+ pub id: String,+ /// Who the chat belongs to.+ pub user_id: String,+ /// The project id the chat belongs to.+ pub project_id: Option<String>,+ /// The name of the chat.+ pub name: String,+ /// The messages in the chat.+ pub messages: Vec<ChatMessageWithAttachments>,+ /// The model used to generate the chat.+ pub model: Option<Model>,+ /// The time the chat was created.+ pub created_at: Option<chrono::DateTime<chrono::Utc>>,+ /// The time the chat was last updated.+ pub updated_at: Option<chrono::DateTime<chrono::Utc>>,+ /// Attachment context — attachments not attached to messages.+ #[deprecated(note = "Attachments are now stateless and no longer float until message send")]+ pub attachments: Vec<ChatAttachmentWithName>,+ /// Current number of tokens in the chat.+ pub token_count: Option<i64>,+ /// Available models for the chat.+ pub available_models: Vec<Model>,+ /// Message ID to web citation list.+ pub web_citations: Vec<(String, Vec<WebCitation>)>,+ /// Whether the chat is persistent or not.+ pub is_persistent: bool,+}diff --git a/rust/cloud-storage/chat/src/domain/ports.rs b/rust/cloud-storage/chat/src/domain/ports.rsnew file mode 100644index 0000000000..ae1c9b45da--- /dev/null+++ b/rust/cloud-storage/chat/src/domain/ports.rs@@ -0,0 +1,136 @@+use crate::domain::models::{+ ChatErr, ChatResponse, CopyChatArgs, CreateChatArgs, GetChatResponse, PatchChatArgs,+};+use entity_access::domain::models::{+ EditAccessLevel, EntityAccessReceipt, OwnerAccessLevel, ViewAccessLevel,+};+use macro_user_id::user_id::MacroUserIdStr;+use model::chat::Chat;+use models_permissions::share_permission::SharePermissionV2;+use models_permissions::share_permission::access_level::AccessLevel;++/// Repository trait for low-level chat data access.+pub trait ChatRepo: Send + Sync + 'static {+ /// Create a new chat, returning the chat ID.+ fn create(+ &self,+ user_id: MacroUserIdStr<'static>,+ args: CreateChatArgs,+ ) -> impl std::future::Future<Output = Result<String, ChatErr>> + 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;++ /// Get a chat metadata by its ID.+ fn get_metadata(+ &self,+ chat_id: &str,+ ) -> impl std::future::Future<Output = Result<Chat, ChatErr>> + 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;++ /// Copy a chat (create a new chat and duplicate its messages), returning the new chat ID.+ fn copy_chat(+ &self,+ user_id: MacroUserIdStr<'static>,+ source_chat_id: &str,+ args: CopyChatArgs,+ ) -> impl std::future::Future<Output = Result<String, ChatErr>> + 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;++ /// Get the share permissions for a chat.+ fn get_permissions(+ &self,+ chat_id: &str,+ ) -> impl std::future::Future<Output = Result<SharePermissionV2, ChatErr>> + 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;++ /// Permanently delete a chat and all associated data.+ fn permanently_delete(+ &self,+ chat_id: &str,+ ) -> impl std::future::Future<Output = Result<(), ChatErr>> + Send;++ /// Patch a chat's metadata (name, project, share permissions).+ fn patch(+ &self,+ user_id: MacroUserIdStr<'static>,+ chat_id: &str,+ args: PatchChatArgs,+ ) -> impl std::future::Future<Output = Result<(), ChatErr>> + Send;+}++/// Service trait for chat business logic.+///+/// Handlers depend on this trait rather than [`ChatRepo`] directly.+/// The default implementation is [`super::service::ChatServiceImpl`].+pub trait ChatService: Send + Sync + 'static {+ /// Create a new chat, returning the chat ID.+ fn create(+ &self,+ user_id: MacroUserIdStr<'static>,+ args: CreateChatArgs,+ ) -> impl std::future::Future<Output = Result<String, ChatErr>> + 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;++ /// 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;++ /// Soft-delete a chat.+ fn delete(+ &self,+ entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,+ ) -> impl std::future::Future<Output = Result<(), ChatErr>> + 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;++ /// 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;++ /// Revert a soft-deleted chat.+ fn revert_delete(+ &self,+ entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,+ ) -> impl std::future::Future<Output = Result<(), ChatErr>> + 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;+}diff --git a/rust/cloud-storage/chat/src/domain/service.rs b/rust/cloud-storage/chat/src/domain/service.rsnew file mode 100644index 0000000000..b5671a2264--- /dev/null+++ b/rust/cloud-storage/chat/src/domain/service.rs@@ -0,0 +1,134 @@+//! Default [`ChatService`] implementation backed by a [`ChatRepo`].++use crate::domain::{+ models::{ChatErr, CopyChatArgs, CreateChatArgs, GetChatResponse, PatchChatArgs},+ ports::{ChatRepo, ChatService},+};+use entity_access::domain::models::{+ EditAccessLevel, EntityAccessAuth, EntityAccessReceipt, OwnerAccessLevel, ViewAccessLevel,+};+use macro_user_id::user_id::MacroUserIdStr;+use models_permissions::share_permission::SharePermissionV2;++/// Concrete service implementation that delegates to a [`ChatRepo`].+pub struct ChatServiceImpl<R> {+ repo: R,+}++impl<R: ChatRepo> ChatServiceImpl<R> {+ /// Create a new [`ChatServiceImpl`] wrapping the given repo.+ pub fn new(repo: R) -> Self {+ Self { repo }+ }+}++/// Extract an authenticated user ID from an [`EntityAccessReceipt`], or return an error.+fn extract_user_id<T: entity_access::domain::models::RequiredPermission>(+ receipt: &EntityAccessReceipt<T>,+) -> Result<MacroUserIdStr<'static>, ChatErr> {+ match receipt.auth() {+ EntityAccessAuth::Authenticated(id) => Ok(id.clone()),+ _ => Err(ChatErr::Unknown(anyhow::anyhow!("unauthenticated"))),+ }+}++impl<R: ChatRepo> ChatService for ChatServiceImpl<R> {+ #[tracing::instrument(err, skip(self))]+ async fn create(+ &self,+ user_id: MacroUserIdStr<'static>,+ args: CreateChatArgs,+ ) -> Result<String, ChatErr> {+ self.repo.create(user_id, args).await+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_chat(+ &self,+ entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,+ ) -> Result<GetChatResponse, ChatErr> {+ let user_id = extract_user_id(&entity_access_receipt)?;+ let chat_id = &entity_access_receipt.entity().entity_id;++ let (chat, access_level) = tokio::join!(+ self.repo.get_chat(chat_id),+ self.repo.get_access_level(user_id, chat_id),+ );++ Ok(GetChatResponse {+ chat: chat?,+ user_access_level: access_level?,+ })+ }++ #[tracing::instrument(err, skip(self))]+ async fn copy_chat(+ &self,+ entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,+ ) -> Result<String, ChatErr> {+ let user_id = extract_user_id(&entity_access_receipt)?;+ let chat_id = &entity_access_receipt.entity().entity_id;++ let chat = self.repo.get_metadata(chat_id).await?;+ self.repo+ .copy_chat(+ user_id,+ chat_id,+ CopyChatArgs {+ name: format!("{} Copy", chat.name),+ project_id: None,+ },+ )+ .await+ }++ #[tracing::instrument(err, skip(self))]+ async fn delete(+ &self,+ entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,+ ) -> Result<(), ChatErr> {+ let chat_id = &entity_access_receipt.entity().entity_id;+ self.repo.delete(chat_id).await+ }++ #[tracing::instrument(err, skip(self))]+ async fn permanently_delete(+ &self,+ entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,+ ) -> Result<(), ChatErr> {+ let chat_id = &entity_access_receipt.entity().entity_id;+ self.repo.permanently_delete(chat_id).await+ }++ #[tracing::instrument(err, skip(self))]+ async fn patch(+ &self,+ entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,+ args: PatchChatArgs,+ ) -> Result<(), ChatErr> {+ let user_id = extract_user_id(&entity_access_receipt)?;+ let chat_id = &entity_access_receipt.entity().entity_id;+ self.repo.patch(user_id, chat_id, args).await+ }++ #[tracing::instrument(err, skip(self))]+ async fn revert_delete(+ &self,+ entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,+ ) -> Result<(), ChatErr> {+ let chat_id = &entity_access_receipt.entity().entity_id;+ let chat = self.repo.get_metadata(chat_id).await?;+ self.repo+ .revert_delete(chat_id, chat.project_id.as_deref())+ .await+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_permissions(+ &self,+ entity_access_receipt: EntityAccessReceipt<EditAccessLevel>,+ ) -> Result<SharePermissionV2, ChatErr> {+ let chat_id = &entity_access_receipt.entity().entity_id;+ self.repo.get_permissions(chat_id).await+ }+}diff --git a/rust/cloud-storage/chat/src/inbound/mod.rs b/rust/cloud-storage/chat/src/inbound/mod.rsnew file mode 100644index 0000000000..69872539cd--- /dev/null+++ b/rust/cloud-storage/chat/src/inbound/mod.rs@@ -0,0 +1,380 @@+//! HTTP handlers and router for the chat API.++#[cfg(test)]+mod test;++use std::sync::Arc;++use axum::{+ Json, Router,+ extract::{FromRef, Path, State},+ http::StatusCode,+ response::IntoResponse,+ routing::{delete, get, post, put},+};+use entity_access::domain::models::{EditAccessLevel, OwnerAccessLevel, ViewAccessLevel};+use entity_access::domain::ports::EntityAccessService;+use entity_access::inbound::axum_extractors::ChatAccessLevelExtractor;+use model::response::StringIDResponse;+use model_user::axum_extractor::MacroUserExtractor;+use models_permissions::share_permission::SharePermissionV2;+use serde::Deserialize;+use utoipa::ToSchema;++use crate::domain::models::{ChatErr, CreateChatArgs, GetChatResponse, PatchChatArgs};+use crate::domain::ports::ChatService;++/// Shared state for the chat router, wrapping a [`ChatService`] implementation+/// and an [`EntityAccessService`] for authorization.+pub struct ChatRouterState<S, Svc> {+ inner: Arc<S>,+ access_service: Arc<Svc>,+}++impl<S, Svc> Clone for ChatRouterState<S, Svc> {+ fn clone(&self) -> Self {+ Self {+ inner: Arc::clone(&self.inner),+ access_service: Arc::clone(&self.access_service),+ }+ }+}++impl<S, Svc> FromRef<ChatRouterState<S, Svc>> for Arc<Svc> {+ fn from_ref(state: &ChatRouterState<S, Svc>) -> Self {+ state.access_service.clone()+ }+}++impl<S: ChatService, Svc: EntityAccessService> ChatRouterState<S, Svc> {+ /// Create a new [`ChatRouterState`] from a service and access service.+ pub fn new(service: S, access_service: Svc) -> Self {+ Self {+ inner: Arc::new(service),+ access_service: Arc::new(access_service),+ }+ }+}++/// Build the router for the `POST /` create-chat route.+///+/// This is separated so that DCS can apply different middleware+/// (e.g. `ensure_user_exists` + quota checks) without `ensure_chat_exists`.+pub fn chat_create_router<S: ChatService, Svc: EntityAccessService, T: Send + Sync + 'static>(+ state: ChatRouterState<S, Svc>,+) -> Router<T> {+ Router::new()+ .route("/", post(create_chat_handler::<S, Svc>))+ .with_state(state)+}++/// Build the router for all `/{chat_id}` routes.+///+/// These routes require `ensure_chat_exists` middleware to populate+/// `ChatBasic` in extensions before the [`ChatAccessLevelExtractor`] runs.+pub fn chat_id_router<S: ChatService, Svc: EntityAccessService, T: Send + Sync + 'static>(+ state: ChatRouterState<S, Svc>,+) -> Router<T> {+ Router::new()+ .route(+ "/{chat_id}",+ get(get_chat_handler::<S, Svc>)+ .delete(delete_chat_handler::<S, Svc>)+ .patch(patch_chat_handler::<S, Svc>),+ )+ .route(+ "/{chat_id}/permanent",+ delete(permanently_delete_chat_handler::<S, Svc>),+ )+ .route("/{chat_id}/copy", post(copy_chat_handler::<S, Svc>))+ .route(+ "/{chat_id}/revert_delete",+ put(revert_delete_handler::<S, Svc>),+ )+ .route(+ "/{chat_id}/permissions",+ get(get_chat_permissions_handler::<S, Svc>),+ )+ .with_state(state)+}++/// HTTP error type for chat handlers, mapped from [`ChatErr`].+#[derive(Debug)]+pub enum ChatHandlerErr {+ /// Something went wrong internally.+ Internal,+ /// The requested resource was not found.+ NotFound,+}++impl From<ChatErr> for ChatHandlerErr {+ fn from(err: ChatErr) -> Self {+ match err {+ ChatErr::NotFound => ChatHandlerErr::NotFound,+ ChatErr::Unknown(e) => {+ tracing::error!(error=?e, "chat handler error");+ ChatHandlerErr::Internal+ }+ }+ }+}++impl IntoResponse for ChatHandlerErr {+ fn into_response(self) -> axum::response::Response {+ let (status, msg) = match self {+ ChatHandlerErr::Internal => {+ (StatusCode::INTERNAL_SERVER_ERROR, "Internal server error")+ }+ ChatHandlerErr::NotFound => (StatusCode::NOT_FOUND, "Not found"),+ };+ (status, msg).into_response()+ }+}++/// Request body for creating a chat.+#[derive(Debug, Deserialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct CreateChatRequest {+ /// Optional name for the chat.+ pub name: Option<String>,+ /// Optional project to associate the chat with.+ pub project_id: Option<String>,+}++#[utoipa::path(+ post,+ path = "/chats",+ tag = "chats",+ operation_id = "create_chat",+ responses(+ (status = 200, body = StringIDResponse),+ (status = 401, body = String),+ (status = 500, body = String),+ )+)]+/// Create a new chat.+#[tracing::instrument(skip(state, user, req), fields(user_id = %user.macro_user_id))]+pub async fn create_chat_handler<S: ChatService, Svc: EntityAccessService>(+ State(state): State<ChatRouterState<S, Svc>>,+ user: MacroUserExtractor,+ Json(req): Json<CreateChatRequest>,+) -> Result<Json<StringIDResponse>, ChatHandlerErr> {+ let id = state+ .inner+ .create(+ user.macro_user_id,+ CreateChatArgs {+ name: req.name.unwrap_or_else(|| "New Chat".to_string()),+ project_id: req.project_id,+ },+ )+ .await?;++ Ok(Json(StringIDResponse { id }))+}++#[utoipa::path(+ get,+ path = "/chats/{chat_id}",+ tag = "chats",+ operation_id = "get_chat",+ params(("chat_id" = String, Path, description = "ID of the chat")),+ responses(+ (status = 200, body = GetChatResponse),+ (status = 401, body = String),+ (status = 404, body = String),+ (status = 500, body = String),+ )+)]+/// Get a chat by ID with messages and web citations.+#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id))]+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>,+) -> Result<Json<GetChatResponse>, ChatHandlerErr> {+ let response = state.inner.get_chat(access.entity_access_receipt).await?;++ Ok(Json(response))+}++#[utoipa::path(+ delete,+ path = "/chat/{chat_id}",+ tag = "chats",+ operation_id = "delete_chat",+ params(("chat_id" = String, Path, description = "ID of the chat")),+ responses(+ (status = 200),+ (status = 401, body = String),+ (status = 500, body = String),+ )+)]+/// Soft-delete a chat.+#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id))]+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>,+) -> Result<StatusCode, ChatHandlerErr> {+ state.inner.delete(access.entity_access_receipt).await?;+ Ok(StatusCode::OK)+}++#[utoipa::path(+ delete,+ path = "/chat/{chat_id}/permanent",+ tag = "chats",+ operation_id = "permanently_delete_chat",+ params(("chat_id" = String, Path, description = "ID of the chat")),+ responses(+ (status = 200),+ (status = 401, body = String),+ (status = 500, body = String),+ )+)]+/// Permanently delete a chat and all associated data.+#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id))]+pub async fn permanently_delete_chat_handler<S: ChatService, Svc: EntityAccessService>(+ access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc>,+ State(state): State<ChatRouterState<S, Svc>>,+ Path(chat_id): Path<String>,+) -> Result<StatusCode, ChatHandlerErr> {+ state+ .inner+ .permanently_delete(access.entity_access_receipt)+ .await?;+ Ok(StatusCode::OK)+}++/// Request body for patching a chat.+#[derive(Debug, Deserialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct PatchChatRequest {+ /// New name for the chat.+ pub name: Option<String>,+ /// New project ID for the chat. Empty string clears the project.+ pub project_id: Option<String>,+ /// Share permission updates.+ pub share_permission:+ Option<models_permissions::share_permission::UpdateSharePermissionRequestV2>,+}++#[utoipa::path(+ patch,+ path = "/chat/{chat_id}",+ tag = "chats",+ operation_id = "patch_chat",+ params(("chat_id" = String, Path, description = "ID of the chat")),+ responses(+ (status = 200),+ (status = 401, body = String),+ (status = 500, body = String),+ )+)]+/// Patch a chat's name, project, or share permissions.+#[tracing::instrument(skip(state, access, req), fields(chat_id = %chat_id))]+pub async fn patch_chat_handler<S: ChatService, Svc: EntityAccessService>(+ access: ChatAccessLevelExtractor<OwnerAccessLevel, Svc>,+ State(state): State<ChatRouterState<S, Svc>>,+ Path(chat_id): Path<String>,+ Json(req): Json<PatchChatRequest>,+) -> Result<StatusCode, ChatHandlerErr> {+ state+ .inner+ .patch(+ access.entity_access_receipt,+ PatchChatArgs {+ name: req.name,+ project_id: req.project_id,+ share_permission: req.share_permission,+ },+ )+ .await?;++ Ok(StatusCode::OK)+}++#[utoipa::path(+ post,+ path = "/chats/{chat_id}/copy",+ tag = "chats",+ operation_id = "copy_chat",+ params(("chat_id" = String, Path, description = "ID of the chat to copy")),+ responses(+ (status = 200, body = StringIDResponse),+ (status = 401, body = String),+ (status = 404, body = String),+ (status = 500, body = String),+ )+)]+/// Copy a chat and its messages into a new chat.+#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id))]+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>,+) -> Result<Json<StringIDResponse>, ChatHandlerErr> {+ let id = state.inner.copy_chat(access.entity_access_receipt).await?;+ Ok(Json(StringIDResponse { id }))+}++#[utoipa::path(+ put,+ path = "/chats/{chat_id}/revert_delete",+ tag = "chats",+ operation_id = "revert_delete_chat",+ params(("chat_id" = String, Path, description = "ID of the chat to restore")),+ responses(+ (status = 200),+ (status = 401, body = String),+ (status = 500, body = String),+ )+)]+/// Revert a soft-deleted chat.+#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id))]+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>,+) -> Result<StatusCode, ChatHandlerErr> {+ state+ .inner+ .revert_delete(access.entity_access_receipt)+ .await?;+ Ok(StatusCode::OK)+}++/// Response body for get chat permissions.+#[derive(Debug, serde::Serialize, ToSchema)]+#[serde(rename_all = "camelCase")]+pub struct GetChatPermissionsResponse {+ /// The share permissions for the chat.+ pub permissions: SharePermissionV2,+}++#[utoipa::path(+ get,+ path = "/chats/{chat_id}/permissions",+ tag = "chats",+ operation_id = "get_chat_permissions",+ params(("chat_id" = String, Path, description = "ID of the chat")),+ responses(+ (status = 200, body = GetChatPermissionsResponse),+ (status = 401, body = String),+ (status = 500, body = String),+ )+)]+/// Get the share permissions for a chat.+#[tracing::instrument(skip(state, access), fields(chat_id = %chat_id))]+pub async fn get_chat_permissions_handler<S: ChatService, Svc: EntityAccessService>(+ access: ChatAccessLevelExtractor<EditAccessLevel, Svc>,+ State(state): State<ChatRouterState<S, Svc>>,+ Path(chat_id): Path<String>,+) -> Result<Json<GetChatPermissionsResponse>, ChatHandlerErr> {+ let permissions = state+ .inner+ .get_permissions(access.entity_access_receipt)+ .await?;+ Ok(Json(GetChatPermissionsResponse { permissions }))+}diff --git a/rust/cloud-storage/chat/src/inbound/test.rs b/rust/cloud-storage/chat/src/inbound/test.rsnew file mode 100644index 0000000000..8d577801aa--- /dev/null+++ b/rust/cloud-storage/chat/src/inbound/test.rs@@ -0,0 +1,591 @@+use axum::Extension;+use axum::body::Body;+use axum::http::{Request, StatusCode};+use http_body_util::BodyExt;+use macro_user_id::user_id::MacroUserIdStr;+use model::chat::ChatBasic;+use model::response::StringIDResponse;+use model_user::UserContext;+use tower::util::ServiceExt;++use super::*;+use crate::domain::models::{+ ChatErr, ChatResponse, CreateChatArgs, GetChatResponse, PatchChatArgs,+};+use crate::domain::ports::ChatService;+use entity_access::domain::models::{+ AccessError, AccessLevel, EditAccessLevel, EntityAccessReceipt, EntityPermission, EntityType,+ OwnerAccessLevel, ViewAccessLevel,+};+use entity_access::domain::ports::EntityAccessService;+use macro_user_id::lowercased::Lowercase;+use macro_user_id::user_id::MacroUserId;++struct MockService;++impl ChatService for MockService {+ async fn create(+ &self,+ _user_id: macro_user_id::user_id::MacroUserIdStr<'static>,+ _args: CreateChatArgs,+ ) -> Result<String, ChatErr> {+ Ok("test-chat-id".to_string())+ }++ #[allow(deprecated)]+ async fn get_chat(+ &self,+ entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,+ ) -> Result<GetChatResponse, ChatErr> {+ let chat_id = entity_access_receipt.entity().entity_id.clone();+ Ok(GetChatResponse {+ chat: ChatResponse {+ id: chat_id,+ user_id: "macro|[email protected]".to_string(),+ project_id: None,+ name: "Mock Chat".to_string(),+ messages: Vec::new(),+ model: None,+ created_at: None,+ updated_at: None,+ attachments: Vec::new(),+ token_count: None,+ available_models: Vec::new(),+ web_citations: Vec::new(),+ is_persistent: false,+ },+ user_access_level: AccessLevel::Owner,+ })+ }++ async fn copy_chat(+ &self,+ _entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,+ ) -> Result<String, ChatErr> {+ Ok("copied-chat-id".to_string())+ }++ async fn delete(+ &self,+ _entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,+ ) -> Result<(), ChatErr> {+ Ok(())+ }++ async fn permanently_delete(+ &self,+ _entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,+ ) -> Result<(), ChatErr> {+ Ok(())+ }++ async fn patch(+ &self,+ _entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,+ _args: PatchChatArgs,+ ) -> Result<(), ChatErr> {+ Ok(())+ }++ async fn revert_delete(+ &self,+ _entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,+ ) -> Result<(), ChatErr> {+ Ok(())+ }++ async fn get_permissions(+ &self,+ _entity_access_receipt: EntityAccessReceipt<EditAccessLevel>,+ ) -> Result<models_permissions::share_permission::SharePermissionV2, ChatErr> {+ Err(ChatErr::Unknown(anyhow::anyhow!("not implemented")))+ }+}++struct ErrorService;++impl ChatService for ErrorService {+ async fn create(+ &self,+ _user_id: macro_user_id::user_id::MacroUserIdStr<'static>,+ _args: CreateChatArgs,+ ) -> Result<String, ChatErr> {+ Err(ChatErr::Unknown(anyhow::anyhow!("db error")))+ }++ async fn get_chat(+ &self,+ _entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,+ ) -> Result<GetChatResponse, ChatErr> {+ Err(ChatErr::Unknown(anyhow::anyhow!("db error")))+ }++ async fn copy_chat(+ &self,+ _entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,+ ) -> Result<String, ChatErr> {+ Err(ChatErr::Unknown(anyhow::anyhow!("db error")))+ }++ async fn delete(+ &self,+ _entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,+ ) -> Result<(), ChatErr> {+ Err(ChatErr::Unknown(anyhow::anyhow!("db error")))+ }++ async fn permanently_delete(+ &self,+ _entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,+ ) -> Result<(), ChatErr> {+ Err(ChatErr::Unknown(anyhow::anyhow!("db error")))+ }++ async fn patch(+ &self,+ _entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,+ _args: PatchChatArgs,+ ) -> Result<(), ChatErr> {+ Err(ChatErr::Unknown(anyhow::anyhow!("db error")))+ }++ async fn revert_delete(+ &self,+ _entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,+ ) -> Result<(), ChatErr> {+ Err(ChatErr::Unknown(anyhow::anyhow!("db error")))+ }++ async fn get_permissions(+ &self,+ _entity_access_receipt: EntityAccessReceipt<EditAccessLevel>,+ ) -> Result<models_permissions::share_permission::SharePermissionV2, ChatErr> {+ Err(ChatErr::Unknown(anyhow::anyhow!("db error")))+ }+}++struct NotFoundService;++impl ChatService for NotFoundService {+ async fn create(+ &self,+ _user_id: macro_user_id::user_id::MacroUserIdStr<'static>,+ _args: CreateChatArgs,+ ) -> Result<String, ChatErr> {+ Err(ChatErr::Unknown(anyhow::anyhow!("db error")))+ }++ async fn get_chat(+ &self,+ _entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,+ ) -> Result<GetChatResponse, ChatErr> {+ Err(ChatErr::NotFound)+ }++ async fn copy_chat(+ &self,+ _entity_access_receipt: EntityAccessReceipt<ViewAccessLevel>,+ ) -> Result<String, ChatErr> {+ Err(ChatErr::NotFound)+ }++ async fn delete(+ &self,+ _entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,+ ) -> Result<(), ChatErr> {+ Err(ChatErr::Unknown(anyhow::anyhow!("db error")))+ }++ async fn permanently_delete(+ &self,+ _entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,+ ) -> Result<(), ChatErr> {+ Err(ChatErr::Unknown(anyhow::anyhow!("db error")))+ }++ async fn patch(+ &self,+ _entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,+ _args: PatchChatArgs,+ ) -> Result<(), ChatErr> {+ Err(ChatErr::Unknown(anyhow::anyhow!("db error")))+ }++ async fn revert_delete(+ &self,+ _entity_access_receipt: EntityAccessReceipt<OwnerAccessLevel>,+ ) -> Result<(), ChatErr> {+ Err(ChatErr::Unknown(anyhow::anyhow!("db error")))+ }++ async fn get_permissions(+ &self,+ _entity_access_receipt: EntityAccessReceipt<EditAccessLevel>,+ ) -> Result<models_permissions::share_permission::SharePermissionV2, ChatErr> {+ Err(ChatErr::Unknown(anyhow::anyhow!("db error")))+ }+}++#[derive(Clone)]+struct MockAccessService;++impl EntityAccessService for MockAccessService {+ async fn generate_entity_access_receipt<+ T: entity_access::domain::models::RequiredPermission,+ >(+ &self,+ _user_id: &MacroUserId<Lowercase<'_>>,+ _user_org_id: Option<i64>,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<entity_access::domain::models::EntityAccessReceipt<T>, AccessError> {+ unreachable!("not used by ChatAccessLevelExtractor")+ }++ async fn get_access_level(+ &self,+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<Option<AccessLevel>, AccessError> {+ Ok(Some(AccessLevel::Owner))+ }++ async fn check_access(+ &self,+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,+ _entity_id: &str,+ _entity_type: EntityType,+ _required_level: AccessLevel,+ ) -> Result<AccessLevel, AccessError> {+ Ok(AccessLevel::Owner)+ }++ async fn check_public_access(+ &self,+ _entity_id: &str,+ _entity_type: EntityType,+ _required_level: AccessLevel,+ ) -> Result<AccessLevel, AccessError> {+ Ok(AccessLevel::Owner)+ }++ async fn get_entity_permission(+ &self,+ _user_id: Option<&MacroUserId<Lowercase<'_>>>,+ _entity_id: &str,+ _entity_type: EntityType,+ _user_org_id: Option<i64>,+ ) -> Result<EntityPermission, AccessError> {+ Ok(EntityPermission::AccessLevel {+ access_level: AccessLevel::Owner,+ })+ }++ async fn get_users_by_entity(+ &self,+ _entity_id: &str,+ _entity_type: EntityType,+ ) -> Result<Vec<MacroUserIdStr<'static>>, AccessError> {+ Ok(vec![])+ }+}++fn user_extension() -> Extension<UserContext> {+ Extension(UserContext {+ user_id: "macro|[email protected]".to_string(),+ fusion_user_id: "1234".to_string(),+ permissions: None,+ organization_id: None,+ })+}++fn chat_basic_extension() -> Extension<ChatBasic> {+ Extension(ChatBasic {+ id: "some-chat-id".to_string(),+ name: "Mock Chat".to_string(),+ user_id: macro_user_id::user_id::MacroUserIdStr::try_from(+ "macro|[email protected]".to_string(),+ )+ .unwrap(),+ project_id: None,+ deleted_at: None,+ })+}++fn mock_create_router() -> Router {+ chat_create_router(ChatRouterState::new(MockService, MockAccessService)).layer(user_extension())+}++fn mock_id_router() -> Router {+ chat_id_router(ChatRouterState::new(MockService, MockAccessService))+ .layer(chat_basic_extension())+ .layer(user_extension())+}++fn error_id_router() -> Router {+ chat_id_router(ChatRouterState::new(ErrorService, MockAccessService))+ .layer(chat_basic_extension())+ .layer(user_extension())+}++fn not_found_id_router() -> Router {+ chat_id_router(ChatRouterState::new(NotFoundService, MockAccessService))+ .layer(chat_basic_extension())+ .layer(user_extension())+}++fn error_create_router() -> Router {+ chat_create_router(ChatRouterState::new(ErrorService, MockAccessService))+ .layer(user_extension())+}++// -- create_chat tests --++#[tokio::test]+async fn create_chat_returns_id() {+ let req = Request::builder()+ .method("POST")+ .uri("/")+ .header("content-type", "application/json")+ .body(Body::from(r#"{"name": "My Chat"}"#))+ .unwrap();++ let res = mock_create_router().oneshot(req).await.unwrap();+ assert_eq!(res.status(), StatusCode::OK);++ let body = res.into_body().collect().await.unwrap().to_bytes();+ let response: StringIDResponse = serde_json::from_slice(&body).unwrap();+ assert_eq!(response.id, "test-chat-id");+}++#[tokio::test]+async fn create_chat_with_default_name() {+ let req = Request::builder()+ .method("POST")+ .uri("/")+ .header("content-type", "application/json")+ .body(Body::from(r#"{}"#))+ .unwrap();++ let res = mock_create_router().oneshot(req).await.unwrap();+ assert_eq!(res.status(), StatusCode::OK);+}++#[tokio::test]+async fn create_chat_repo_error_returns_500() {+ let req = Request::builder()+ .method("POST")+ .uri("/")+ .header("content-type", "application/json")+ .body(Body::from(r#"{"name": "My Chat"}"#))+ .unwrap();++ let res = error_create_router().oneshot(req).await.unwrap();+ assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);+}++#[tokio::test]+async fn create_chat_without_auth_returns_401() {+ let router: Router = chat_create_router(ChatRouterState::new(MockService, MockAccessService));++ let req = Request::builder()+ .method("POST")+ .uri("/")+ .header("content-type", "application/json")+ .body(Body::from(r#"{"name": "My Chat"}"#))+ .unwrap();++ let res = router.oneshot(req).await.unwrap();+ assert_eq!(res.status(), StatusCode::UNAUTHORIZED);+}++// -- get_chat tests --++#[tokio::test]+async fn get_chat_returns_chat() {+ let req = Request::builder()+ .uri("/some-chat-id")+ .body(Body::empty())+ .unwrap();++ let res = mock_id_router().oneshot(req).await.unwrap();+ assert_eq!(res.status(), StatusCode::OK);++ let body = res.into_body().collect().await.unwrap().to_bytes();+ let response: GetChatResponse = serde_json::from_slice(&body).unwrap();+ assert_eq!(response.chat.id, "some-chat-id");+ assert_eq!(response.chat.name, "Mock Chat");+ assert_eq!(response.user_access_level, AccessLevel::Owner);+}++#[tokio::test]+async fn get_chat_not_found_returns_404() {+ let req = Request::builder()+ .uri("/nonexistent")+ .body(Body::empty())+ .unwrap();++ let res = not_found_id_router().oneshot(req).await.unwrap();+ assert_eq!(res.status(), StatusCode::NOT_FOUND);+}++#[tokio::test]+async fn get_chat_repo_error_returns_500() {+ let req = Request::builder()+ .uri("/some-chat-id")+ .body(Body::empty())+ .unwrap();++ let res = error_id_router().oneshot(req).await.unwrap();+ assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);+}++// -- delete_chat tests --++#[tokio::test]+async fn delete_chat_returns_ok() {+ let req = Request::builder()+ .method("DELETE")+ .uri("/some-chat-id")+ .body(Body::empty())+ .unwrap();++ let res = mock_id_router().oneshot(req).await.unwrap();+ assert_eq!(res.status(), StatusCode::OK);+}++#[tokio::test]+async fn delete_chat_repo_error_returns_500() {+ let req = Request::builder()+ .method("DELETE")+ .uri("/some-chat-id")+ .body(Body::empty())+ .unwrap();++ let res = error_id_router().oneshot(req).await.unwrap();+ assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);+}++// -- permanently_delete_chat tests --++#[tokio::test]+async fn permanently_delete_chat_returns_ok() {+ let req = Request::builder()+ .method("DELETE")+ .uri("/some-chat-id/permanent")+ .body(Body::empty())+ .unwrap();++ let res = mock_id_router().oneshot(req).await.unwrap();+ assert_eq!(res.status(), StatusCode::OK);+}++#[tokio::test]+async fn permanently_delete_chat_repo_error_returns_500() {+ let req = Request::builder()+ .method("DELETE")+ .uri("/some-chat-id/permanent")+ .body(Body::empty())+ .unwrap();++ let res = error_id_router().oneshot(req).await.unwrap();+ assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);+}++// -- patch_chat tests --++#[tokio::test]+async fn patch_chat_returns_ok() {+ let req = Request::builder()+ .method("PATCH")+ .uri("/some-chat-id")+ .header("content-type", "application/json")+ .body(Body::from(r#"{"name": "Renamed"}"#))+ .unwrap();++ let res = mock_id_router().oneshot(req).await.unwrap();+ assert_eq!(res.status(), StatusCode::OK);+}++#[tokio::test]+async fn patch_chat_repo_error_returns_500() {+ let req = Request::builder()+ .method("PATCH")+ .uri("/some-chat-id")+ .header("content-type", "application/json")+ .body(Body::from(r#"{"name": "Renamed"}"#))+ .unwrap();++ let res = error_id_router().oneshot(req).await.unwrap();+ assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);+}++// -- copy_chat tests --++#[tokio::test]+async fn copy_chat_returns_id() {+ let req = Request::builder()+ .method("POST")+ .uri("/some-chat-id/copy")+ .body(Body::empty())+ .unwrap();++ let res = mock_id_router().oneshot(req).await.unwrap();+ assert_eq!(res.status(), StatusCode::OK);++ let body = res.into_body().collect().await.unwrap().to_bytes();+ let response: StringIDResponse = serde_json::from_slice(&body).unwrap();+ assert_eq!(response.id, "copied-chat-id");+}++#[tokio::test]+async fn copy_chat_repo_error_returns_500() {+ let req = Request::builder()+ .method("POST")+ .uri("/some-chat-id/copy")+ .body(Body::empty())+ .unwrap();++ let res = error_id_router().oneshot(req).await.unwrap();+ assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);+}++// -- revert_delete tests --++#[tokio::test]+async fn revert_delete_returns_ok() {+ let req = Request::builder()+ .method("PUT")+ .uri("/some-chat-id/revert_delete")+ .body(Body::empty())+ .unwrap();++ let res = mock_id_router().oneshot(req).await.unwrap();+ assert_eq!(res.status(), StatusCode::OK);+}++#[tokio::test]+async fn revert_delete_repo_error_returns_500() {+ let req = Request::builder()+ .method("PUT")+ .uri("/some-chat-id/revert_delete")+ .body(Body::empty())+ .unwrap();++ let res = error_id_router().oneshot(req).await.unwrap();+ assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);+}++// -- get_chat_permissions tests --++#[tokio::test]+async fn get_permissions_repo_error_returns_500() {+ let req = Request::builder()+ .uri("/some-chat-id/permissions")+ .body(Body::empty())+ .unwrap();++ let res = error_id_router().oneshot(req).await.unwrap();+ assert_eq!(res.status(), StatusCode::INTERNAL_SERVER_ERROR);+}diff --git a/rust/cloud-storage/chat/src/lib.rs b/rust/cloud-storage/chat/src/lib.rsnew file mode 100644index 0000000000..096189196b--- /dev/null+++ b/rust/cloud-storage/chat/src/lib.rs@@ -0,0 +1,11 @@+#![deny(missing_docs)]+//! Chat domain crate — hex-architecture abstraction over the Chat and ChatMessage tables.++/// Chat domain layer — ports, models, and service logic.+pub mod domain;+/// Inbound HTTP handlers.+#[cfg(feature = "inbound")]+pub mod inbound;+/// Outbound adapters (database, etc.).+#[cfg(feature = "outbound")]+pub mod outbound;diff --git a/rust/cloud-storage/chat/src/outbound.rs b/rust/cloud-storage/chat/src/outbound.rsnew file mode 100644index 0000000000..c205b492a6--- /dev/null+++ b/rust/cloud-storage/chat/src/outbound.rs@@ -0,0 +1,4 @@+//! Outbound adapters for the chat domain.++/// Postgres-backed implementation of [`crate::domain::ports::ChatRepo`].+pub mod postgres;diff --git a/rust/cloud-storage/chat/src/outbound/postgres/fixtures/users.sql b/rust/cloud-storage/chat/src/outbound/postgres/fixtures/users.sqlnew file mode 100644index 0000000000..7fb4a51218--- /dev/null+++ b/rust/cloud-storage/chat/src/outbound/postgres/fixtures/users.sql@@ -0,0 +1,11 @@+INSERT INTO public."Organization" ("id","name")+(SELECT 1, 'organization-one');++INSERT INTO public."macro_user" ("id", "username", "email", "stripe_customer_id")+(SELECT 'a1111111-1111-1111-1111-111111111111', '[email protected]', '[email protected]', 'stripe_test');++INSERT INTO public."User" ("id","email","stripeCustomerId","macro_user_id")+(SELECT 'macro|[email protected]', '[email protected]','stripe_test','a1111111-1111-1111-1111-111111111111');++INSERT INTO public."Project" ("id", "name", "userId")+VALUES ('project-123', 'Test Project', 'macro|[email protected]');diff --git a/rust/cloud-storage/chat/src/outbound/postgres/mod.rs b/rust/cloud-storage/chat/src/outbound/postgres/mod.rsnew file mode 100644index 0000000000..d3ee1cff7c--- /dev/null+++ b/rust/cloud-storage/chat/src/outbound/postgres/mod.rs@@ -0,0 +1,309 @@+//! Postgres-backed [`ChatRepo`] implementation.++mod queries;+#[cfg(test)]+mod test;++use crate::domain::models::{+ ChatErr, ChatResponse, CopyChatArgs, CreateChatArgs, PatchChatArgs, WebCitation,+};+use crate::domain::ports::ChatRepo;+use ai::types::Model;+use macro_user_id::cowlike::CowLike;+use macro_user_id::user_id::MacroUserIdStr;+use model::chat::ChatMessageWithAttachments;+use models_permissions::share_permission::SharePermissionV2;+use models_permissions::share_permission::access_level::AccessLevel;+use sqlx::PgPool;++/// The default model used when no model is set on a chat.+const FALLBACK_MODEL: Model = Model::Claude45Haiku;++/// Convert an [`anyhow::Error`] to a [`ChatErr`], detecting `sqlx::RowNotFound`.+fn to_chat_err(e: anyhow::Error) -> ChatErr {+ if e.downcast_ref::<sqlx::Error>()+ .is_some_and(|e| matches!(e, sqlx::Error::RowNotFound))+ {+ ChatErr::NotFound+ } else {+ ChatErr::Unknown(e)+ }+}++/// Postgres adapter for chat repository operations.+pub struct PgChatRepo {+ pool: PgPool,+}++impl PgChatRepo {+ /// Create a new [`PgChatRepo`] with the given connection pool.+ pub fn new(pool: PgPool) -> Self {+ Self { pool }+ }++ async fn get_messages(&self, chat_id: &str) -> anyhow::Result<Vec<ChatMessageWithAttachments>> {+ queries::get_messages::get_messages(&self.pool, chat_id).await+ }++ async fn get_web_citations(+ &self,+ chat_id: &str,+ ) -> anyhow::Result<Vec<(String, Vec<WebCitation>)>> {+ queries::get_web_citations::get_web_citations(&self.pool, chat_id).await+ }+}++impl ChatRepo for PgChatRepo {+ #[tracing::instrument(err, skip(self))]+ async fn create(+ &self,+ user_id: MacroUserIdStr<'static>,+ args: CreateChatArgs,+ ) -> Result<String, ChatErr> {+ let mut tx = self+ .pool+ .begin()+ .await+ .map_err(|e| ChatErr::Unknown(e.into()))?;++ let chat_id = queries::insert_chat::insert_chat(+ &mut tx,+ &user_id,+ &args.name,+ args.project_id.as_deref(),+ )+ .await+ .map_err(to_chat_err)?;++ let share_permission = SharePermissionV2::new_chat_share_permission();+ queries::create_chat_permission::create_chat_permission(+ &mut tx,+ &chat_id,+ &share_permission,+ )+ .await+ .map_err(to_chat_err)?;++ queries::upsert_user_history::upsert_user_history(&mut tx, user_id.copied(), &chat_id)+ .await+ .map_err(to_chat_err)?;++ queries::upsert_item_last_accessed::upsert_item_last_accessed(&mut tx, &chat_id)+ .await+ .map_err(to_chat_err)?;++ queries::insert_user_item_access::insert_user_item_access(+ &mut tx,+ user_id.copied(),+ &chat_id,+ AccessLevel::Owner,+ )+ .await+ .map_err(to_chat_err)?;++ tx.commit().await.map_err(|e| {+ tracing::error!(error=?e, "create_chat transaction error");+ ChatErr::Unknown(e.into())+ })?;++ Ok(chat_id)+ }++ #[tracing::instrument(err, skip(self))]+ #[allow(deprecated)]+ async fn get_chat(&self, chat_id: &str) -> Result<ChatResponse, ChatErr> {+ 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);+ let web_citations = self.get_web_citations(chat_id).await.unwrap_or_default();++ Ok(ChatResponse {+ id: chat.id,+ user_id: chat.user_id,+ name: chat.name,+ model: Some(FALLBACK_MODEL),+ messages,+ project_id: chat.project_id,+ created_at: chat.created_at,+ updated_at: chat.updated_at,+ attachments: Vec::new(),+ token_count: chat.token_count,+ available_models: vec![FALLBACK_MODEL],+ web_citations,+ is_persistent: chat.is_persistent,+ })+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_metadata(&self, chat_id: &str) -> Result<model::chat::Chat, ChatErr> {+ queries::get_chat::get_chat(&self.pool, chat_id)+ .await+ .map_err(to_chat_err)+ }++ #[tracing::instrument(err, skip(self))]+ async fn get_access_level(+ &self,+ user_id: MacroUserIdStr<'_>,+ chat_id: &str,+ ) -> Result<AccessLevel, ChatErr> {+ queries::get_access_level::get_access_level(&self.pool, user_id.as_ref(), chat_id)+ .await+ .map_err(to_chat_err)+ }++ #[tracing::instrument(err, skip(self))]+ async fn copy_chat(+ &self,+ user_id: MacroUserIdStr<'static>,+ source_chat_id: &str,+ args: CopyChatArgs,+ ) -> Result<String, ChatErr> {+ let mut tx = self+ .pool+ .begin()+ .await+ .map_err(|e| ChatErr::Unknown(e.into()))?;++ let chat_id = queries::insert_chat::insert_chat(+ &mut tx,+ &user_id,+ &args.name,+ args.project_id.as_deref(),+ )+ .await+ .map_err(to_chat_err)?;++ let share_permission = SharePermissionV2::new_chat_share_permission();+ queries::create_chat_permission::create_chat_permission(+ &mut tx,+ &chat_id,+ &share_permission,+ )+ .await+ .map_err(to_chat_err)?;++ queries::upsert_user_history::upsert_user_history(&mut tx, user_id.copied(), &chat_id)+ .await+ .map_err(to_chat_err)?;++ queries::upsert_item_last_accessed::upsert_item_last_accessed(&mut tx, &chat_id)+ .await+ .map_err(to_chat_err)?;++ queries::insert_user_item_access::insert_user_item_access(+ &mut tx,+ user_id.copied(),+ &chat_id,+ AccessLevel::Owner,+ )+ .await+ .map_err(to_chat_err)?;++ queries::copy_messages::copy_messages(&mut tx, source_chat_id, &chat_id)+ .await+ .map_err(to_chat_err)?;++ tx.commit().await.map_err(|e| {+ tracing::error!(error=?e, "copy_chat transaction error");+ ChatErr::Unknown(e.into())+ })?;++ Ok(chat_id)+ }++ #[tracing::instrument(err, skip(self))]+ async fn revert_delete(&self, chat_id: &str, project_id: Option<&str>) -> Result<(), ChatErr> {+ let mut tx = self+ .pool+ .begin()+ .await+ .map_err(|e| ChatErr::Unknown(e.into()))?;+ queries::revert_delete_chat::revert_delete_chat(&mut tx, chat_id, project_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_permissions(&self, chat_id: &str) -> Result<SharePermissionV2, ChatErr> {+ 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> {+ let mut tx = self+ .pool+ .begin()+ .await+ .map_err(|e| ChatErr::Unknown(e.into()))?;+ queries::soft_delete_chat::soft_delete_chat(&mut tx, 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 permanently_delete(&self, chat_id: &str) -> Result<(), ChatErr> {+ let mut tx = self+ .pool+ .begin()+ .await+ .map_err(|e| ChatErr::Unknown(e.into()))?;+ queries::permanently_delete_chat::permanently_delete_chat(&mut tx, 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 patch(+ &self,+ user_id: MacroUserIdStr<'static>,+ chat_id: &str,+ args: PatchChatArgs,+ ) -> Result<(), ChatErr> {+ let mut tx = self+ .pool+ .begin()+ .await+ .map_err(|e| ChatErr::Unknown(e.into()))?;++ queries::patch_chat::patch_chat(+ &mut tx,+ chat_id,+ args.name.as_deref(),+ args.project_id.as_deref(),+ )+ .await+ .map_err(to_chat_err)?;++ if let Some(ref share_permission) = args.share_permission {+ queries::edit_share_permission::edit_chat_permission(+ &mut tx,+ chat_id,+ share_permission,+ )+ .await+ .map_err(to_chat_err)?;++ macro_share_permissions::user_item_access::update_user_item_access(+ &mut tx,+ user_id.as_ref(),+ chat_id,+ "chat",+ share_permission,+ )+ .await+ .map_err(to_chat_err)?;+ }++ tx.commit().await.map_err(|e| ChatErr::Unknown(e.into()))?;+ Ok(())+ }+}diff --git a/rust/cloud-storage/chat/src/outbound/postgres/queries/copy_messages.rs b/rust/cloud-storage/chat/src/outbound/postgres/queries/copy_messages.rsnew file mode 100644index 0000000000..9ab100add4--- /dev/null+++ b/rust/cloud-storage/chat/src/outbound/postgres/queries/copy_messages.rs@@ -0,0 +1,24 @@+//! Copy all messages from one chat to another.++/// Copy all messages from `source_chat_id` into `dest_chat_id`.+#[tracing::instrument(err, skip(tx))]+pub(crate) async fn copy_messages(+ tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,+ source_chat_id: &str,+ dest_chat_id: &str,+) -> anyhow::Result<()> {+ sqlx::query!(+ r#"+ INSERT INTO "ChatMessage" ("chatId", "createdAt", "updatedAt", "content", "role", "model")+ SELECT $1, "createdAt", "updatedAt", "content", "role", "model"+ FROM "ChatMessage"+ WHERE "chatId" = $2+ "#,+ dest_chat_id,+ source_chat_id,+ )+ .execute(&mut **tx)+ .await?;++ Ok(())+}diff --git a/rust/cloud-storage/chat/src/outbound/postgres/queries/create_chat_permission.rs b/rust/cloud-storage/chat/src/outbound/postgres/queries/create_chat_permission.rsnew file mode 100644index 0000000000..3511ba056d--- /dev/null+++ b/rust/cloud-storage/chat/src/outbound/postgres/queries/create_chat_permission.rs@@ -0,0 +1,41 @@+//! Create a share permission and link it to a chat.++use models_permissions::share_permission::SharePermissionV2;+use sqlx::{Postgres, Transaction};++/// Create a share permission row and associate it with the given chat.+#[tracing::instrument(err, skip(tx))]+pub(crate) async fn create_chat_permission(+ tx: &mut Transaction<'_, Postgres>,+ chat_id: &str,+ share_permission: &SharePermissionV2,+) -> anyhow::Result<()> {+ let permission_id = sqlx::query_scalar!(+ r#"+ INSERT INTO "SharePermission" ("isPublic", "publicAccessLevel", "createdAt", "updatedAt")+ VALUES ($1, $2, NOW(), NOW())+ RETURNING id+ "#,+ share_permission.is_public,+ share_permission+ .public_access_level+ .as_ref()+ .map(|s| s.to_string()),+ )+ .fetch_one(tx.as_mut())+ .await?;++ sqlx::query!(+ r#"+ INSERT INTO "ChatPermission" ("chatId", "sharePermissionId")+ VALUES ($1, $2)+ "#,+ chat_id,+ permission_id,+ )+ .execute(tx.as_mut())+ .await+ .inspect_err(|e| tracing::error!(error=?e, "unable to create chat permission"))?;++ Ok(())+}diff --git a/rust/cloud-storage/chat/src/outbound/postgres/queries/edit_share_permission.rs b/rust/cloud-storage/chat/src/outbound/postgres/queries/edit_share_permission.rsnew file mode 100644index 0000000000..5f5e55f72c--- /dev/null+++ b/rust/cloud-storage/chat/src/outbound/postgres/queries/edit_share_permission.rs@@ -0,0 +1,169 @@+//! Edit share permissions for a chat.++use models_permissions::share_permission::UpdateSharePermissionRequestV2;+use models_permissions::share_permission::channel_share_permission::{+ ChannelSharePermission, UpdateChannelSharePermission, UpdateOperation,+};+use sqlx::{Postgres, Transaction};++/// Helper enum for dynamic query parameter binding.+enum Parameter {+ /// A string value.+ String(String),+ /// A boolean value.+ Bool(bool),+}++/// Edit a chat's share permission by looking up its `SharePermission` row.+#[tracing::instrument(err, skip(tx))]+pub(crate) async fn edit_chat_permission(+ tx: &mut Transaction<'_, Postgres>,+ chat_id: &str,+ share_permission: &UpdateSharePermissionRequestV2,+) -> anyhow::Result<()> {+ let share_id: String = sqlx::query!(+ r#"+ SELECT cp."sharePermissionId" as share_permission_id+ FROM "ChatPermission" cp+ WHERE cp."chatId" = $1+ "#,+ chat_id,+ )+ .map(|row| row.share_permission_id)+ .fetch_one(tx.as_mut())+ .await?;++ edit_share_permission(tx, &share_id, share_permission).await+}++/// Update a `SharePermission` row and its channel share permissions.+#[tracing::instrument(err, skip(tx))]+async fn edit_share_permission(+ tx: &mut Transaction<'_, Postgres>,+ share_permission_id: &str,+ share_permission: &UpdateSharePermissionRequestV2,+) -> anyhow::Result<()> {+ let mut query = "UPDATE \"SharePermission\" SET ".to_string();+ let mut parameters: Vec<Parameter> = Vec::new();+ let mut set_parts = Vec::new();++ let mut ignore_public_access_level = false;+ if let Some(is_public) = share_permission.is_public {+ set_parts.push("\"isPublic\" = $".to_string() + &(set_parts.len() + 2).to_string());+ parameters.push(Parameter::Bool(is_public));++ if is_public && share_permission.public_access_level.is_none() {+ tracing::warn!(+ "is_public was set to true but public access level was not provided, setting to view"+ );+ set_parts+ .push("\"publicAccessLevel\" = $".to_string() + &(set_parts.len() + 2).to_string());+ parameters.push(Parameter::String("view".to_string()));+ }++ if !is_public {+ ignore_public_access_level = true;+ set_parts.push("\"publicAccessLevel\" = NULL".to_string());+ }+ }++ if let Some(public_access_level) = share_permission.public_access_level+ && !ignore_public_access_level+ {+ set_parts+ .push("\"publicAccessLevel\" = $".to_string() + &(set_parts.len() + 2).to_string());+ parameters.push(Parameter::String(public_access_level.to_string()));+ }++ query += &set_parts.join(", ");+ if !set_parts.is_empty() {+ query += ", ";+ }++ query += "\"updatedAt\" = NOW() WHERE id = $1";++ let mut query = sqlx::query(&query);+ query = query.bind(share_permission_id.to_string());++ for param in parameters {+ match param {+ Parameter::String(s) => {+ query = query.bind(s);+ }+ Parameter::Bool(b) => {+ query = query.bind(b);+ }+ }+ }++ query.execute(tx.as_mut()).await?;++ if let Some(channel_share_permissions) = share_permission.channel_share_permissions.as_ref() {+ edit_channel_share_permissions(tx, share_permission_id, channel_share_permissions).await?;+ }++ Ok(())+}++/// Process channel share permission add/replace/remove operations.+#[tracing::instrument(err, skip(tx))]+async fn edit_channel_share_permissions(+ tx: &mut Transaction<'_, Postgres>,+ share_permission_id: &str,+ channel_share_permissions: &[UpdateChannelSharePermission],+) -> anyhow::Result<()> {+ let to_upsert: Vec<ChannelSharePermission> = channel_share_permissions+ .iter()+ .filter_map(|csp| match csp.operation {+ UpdateOperation::Add | UpdateOperation::Replace => Some(csp.into()),+ _ => None,+ })+ .collect();++ let to_remove: Vec<String> = channel_share_permissions+ .iter()+ .filter_map(|csp| match csp.operation {+ UpdateOperation::Remove => Some(csp.channel_id.clone()),+ _ => None,+ })+ .collect();++ if !to_remove.is_empty() {+ sqlx::query!(+ r#"+ DELETE FROM "ChannelSharePermission"+ WHERE "share_permission_id" = $1+ AND "channel_id" = ANY($2)+ "#,+ share_permission_id,+ &to_remove,+ )+ .execute(tx.as_mut())+ .await?;+ }++ if !to_upsert.is_empty() {+ let channel_ids: Vec<String> = to_upsert.iter().map(|csp| csp.channel_id.clone()).collect();+ let access_levels: Vec<String> = to_upsert+ .iter()+ .map(|csp| csp.access_level.to_string())+ .collect();++ sqlx::query!(+ r#"+ INSERT INTO "ChannelSharePermission" ("share_permission_id", "channel_id", "access_level")+ SELECT $1, channel_id, access_level::"AccessLevel"+ FROM UNNEST($2::text[], $3::text[]) AS t(channel_id, access_level)+ ON CONFLICT ("share_permission_id", "channel_id")+ DO UPDATE SET "access_level" = EXCLUDED."access_level"+ "#,+ share_permission_id,+ &channel_ids,+ &access_levels,+ )+ .execute(tx.as_mut())+ .await?;+ }++ Ok(())+}diff --git a/rust/cloud-storage/chat/src/outbound/postgres/queries/get_access_level.rs b/rust/cloud-storage/chat/src/outbound/postgres/queries/get_access_level.rsnew file mode 100644index 0000000000..567298fedf--- /dev/null+++ b/rust/cloud-storage/chat/src/outbound/postgres/queries/get_access_level.rs@@ -0,0 +1,27 @@+//! Fetch a user's access level on a chat.++use models_permissions::share_permission::access_level::AccessLevel;+use std::str::FromStr;++/// Get the user's access level on a chat from the `UserItemAccess` table.+#[tracing::instrument(err, skip(pool))]+pub(crate) async fn get_access_level(+ pool: &sqlx::PgPool,+ user_id: &str,+ chat_id: &str,+) -> anyhow::Result<AccessLevel> {+ let level = sqlx::query_scalar!(+ r#"+ SELECT "access_level"::text+ FROM "UserItemAccess"+ WHERE "user_id" = $1 AND "item_id" = $2 AND "item_type" = 'chat'+ "#,+ user_id,+ chat_id,+ )+ .fetch_one(pool)+ .await?+ .unwrap_or_default();++ Ok(AccessLevel::from_str(&level).unwrap_or(AccessLevel::View))+}diff --git a/rust/cloud-storage/chat/src/outbound/postgres/queries/get_chat.rs b/rust/cloud-storage/chat/src/outbound/postgres/queries/get_chat.rsnew file mode 100644index 0000000000..fbfa343567--- /dev/null+++ b/rust/cloud-storage/chat/src/outbound/postgres/queries/get_chat.rs@@ -0,0 +1,32 @@+//! Fetch a chat by ID.++use model::chat::Chat;+use sqlx::PgPool;++/// Fetch a single chat row by its ID.+#[tracing::instrument(err, skip(pool))]+pub(crate) async fn get_chat(pool: &PgPool, chat_id: &str) -> anyhow::Result<Chat> {+ let chat = sqlx::query_as!(+ Chat,+ r#"+ SELECT+ id,+ name,+ model,+ "userId" as "user_id",+ "createdAt"::timestamptz as "created_at",+ "updatedAt"::timestamptz as "updated_at",+ "deletedAt"::timestamptz as "deleted_at",+ "projectId" as "project_id",+ "tokenCount" as "token_count",+ "isPersistent" as "is_persistent"+ FROM "Chat"+ WHERE id = $1+ "#,+ chat_id,+ )+ .fetch_one(pool)+ .await?;++ Ok(chat)+}diff --git a/rust/cloud-storage/chat/src/outbound/postgres/queries/get_messages.rs b/rust/cloud-storage/chat/src/outbound/postgres/queries/get_messages.rsnew file mode 100644index 0000000000..18389183a5--- /dev/null+++ b/rust/cloud-storage/chat/src/outbound/postgres/queries/get_messages.rs@@ -0,0 +1,166 @@+//! Fetch all messages for a chat with their attachments.++use ai::types::{ChatMessageContent, Role};+use model::chat::{+ AttachmentMetadata, AttachmentType, ChatAttachmentWithName, ChatMessageWithAttachments,+};+use sqlx::PgPool;++#[derive(serde::Deserialize, Debug)]+#[serde(rename_all = "camelCase")]+struct RawAttachment {+ attachment_id: String,+ attachment_type: String,+ document_name: Option<String>,+ document_type: Option<model::document::FileType>,+}++/// Fetch all messages for a chat, with inline attachment metadata from DB joins.+#[tracing::instrument(err, skip(pool))]+pub(crate) async fn get_messages(+ pool: &PgPool,+ chat_id: &str,+) -> anyhow::Result<Vec<ChatMessageWithAttachments>> {+ let records = sqlx::query!(+ r#"+ WITH attachment_info AS (+ SELECT+ ca.id,+ ca."attachmentType",+ ca."attachmentId",+ ca."messageId",+ CASE+ WHEN ca."attachmentType" = 'document' THEN d.name+ WHEN ca."attachmentType" = 'chat' THEN c.name+ WHEN ca."attachmentType" = 'project' THEN p.name+ WHEN ca."attachmentType" = 'image' THEN d.name+ ELSE NULL+ END AS document_name,+ CASE+ WHEN ca."attachmentType" = 'document' THEN d."fileType"+ WHEN ca."attachmentType" = 'image' THEN d."fileType"+ ELSE NULL+ END as document_type+ FROM+ "ChatAttachment" ca+ LEFT JOIN+ "Document" d ON (+ (ca."attachmentType" = 'document' AND ca."attachmentId" = d.id)+ OR+ (ca."attachmentType" = 'image' AND ca."attachmentId" = d.id)+ )+ LEFT JOIN+ "Chat" c ON ca."attachmentType" = 'chat' AND ca."attachmentId" = c.id+ LEFT JOIN+ "Project" p ON ca."attachmentType" = 'project' AND ca."attachmentId" = p.id+ )+ SELECT+ cm.id AS "id!",+ cm.content,+ cm.role,+ cm.model,+ COALESCE(+ (+ SELECT json_agg(+ json_build_object(+ 'id', attachment_info."attachmentId",+ 'attachmentType', attachment_info."attachmentType",+ 'attachmentId', attachment_info."attachmentId",+ 'documentName', attachment_info.document_name,+ 'documentType', attachment_info.document_type+ )+ )+ FROM attachment_info+ WHERE attachment_info."messageId" = cm.id+ ),+ '[]'::json+ ) AS attachments+ FROM+ "ChatMessage" cm+ WHERE+ cm."chatId" = $1+ ORDER BY+ cm."createdAt" ASC+ "#,+ chat_id+ )+ .fetch_all(pool)+ .await?;++ let messages = records+ .into_iter()+ .map(|record| {+ let attachments = record+ .attachments+ .and_then(|raw_json| {+ serde_json::from_value::<Vec<RawAttachment>>(raw_json)+ .inspect_err(|e| tracing::error!(error=?e, "Error parsing attachments"))+ .ok()+ })+ .map(|raws| raws.into_iter().filter_map(parse_raw_attachment).collect())+ .unwrap_or_default();++ let content =+ serde_json::from_value::<ChatMessageContent>(record.content).expect("content");+ let role = Role::try_from(record.role.as_str()).unwrap_or(Role::User);++ ChatMessageWithAttachments {+ id: record.id,+ content,+ role,+ attachments,+ model: record.model,+ }+ })+ .collect();++ Ok(messages)+}++fn parse_raw_attachment(raw: RawAttachment) -> Option<ChatAttachmentWithName> {+ match raw.attachment_type.as_str() {+ "document" => Some(ChatAttachmentWithName {+ id: raw.attachment_id.clone(),+ attachment_id: raw.attachment_id,+ attachment_type: AttachmentType::Document,+ metadata: raw.document_name.zip(raw.document_type).map(|(name, ft)| {+ AttachmentMetadata::Document {+ document_type: ft,+ document_name: name,+ }+ }),+ }),+ "image" => Some(ChatAttachmentWithName {+ id: raw.attachment_id.clone(),+ attachment_id: raw.attachment_id,+ attachment_type: AttachmentType::Image,+ metadata: raw.document_name.zip(raw.document_type).map(|(name, ft)| {+ AttachmentMetadata::Image {+ image_extension: ft,+ image_name: name,+ }+ }),+ }),+ "project" => Some(ChatAttachmentWithName {+ id: raw.attachment_id.clone(),+ attachment_id: raw.attachment_id,+ attachment_type: AttachmentType::Project,+ metadata: raw+ .document_name+ .map(|name| AttachmentMetadata::Project { project_name: name }),+ }),+ "channel" => Some(ChatAttachmentWithName {+ id: raw.attachment_id.clone(),+ attachment_id: raw.attachment_id,+ attachment_type: AttachmentType::Channel,+ metadata: None,+ }),+ "email" => Some(ChatAttachmentWithName {+ id: raw.attachment_id.clone(),+ attachment_id: raw.attachment_id,+ attachment_type: AttachmentType::Email,+ metadata: None,+ }),+ _ => None,+ }+}diff --git a/rust/cloud-storage/chat/src/outbound/postgres/queries/get_permissions.rs b/rust/cloud-storage/chat/src/outbound/postgres/queries/get_permissions.rsnew file mode 100644index 0000000000..ce83b1c785--- /dev/null+++ b/rust/cloud-storage/chat/src/outbound/postgres/queries/get_permissions.rs@@ -0,0 +1,67 @@+//! Fetch share permissions for a chat.++use models_permissions::share_permission::SharePermissionV2;+use models_permissions::share_permission::access_level::AccessLevel;+use models_permissions::share_permission::channel_share_permission::ChannelSharePermission;+use std::str::FromStr;++/// Get the [`SharePermissionV2`] for a chat.+#[tracing::instrument(err, skip(pool))]+pub(crate) async fn get_chat_share_permission(+ pool: &sqlx::PgPool,+ chat_id: &str,+) -> anyhow::Result<SharePermissionV2> {+ let result = sqlx::query!(+ r#"+ SELECT+ sp.id as id,+ sp."isPublic" as is_public,+ sp."publicAccessLevel" as "public_access_level?",+ c."userId" as owner,+ COALESCE(+ json_agg(json_build_object(+ 'channel_id', csp."channel_id",+ 'access_level', csp."access_level"+ )) FILTER (WHERE csp."channel_id" IS NOT NULL),+ '[]'+ ) as "channel_share_permissions?"+ FROM+ "ChatPermission" cp+ JOIN "SharePermission" sp ON cp."sharePermissionId" = sp.id+ JOIN "Chat" c ON cp."chatId" = c.id+ LEFT JOIN "ChannelSharePermission" csp ON csp."share_permission_id" = sp.id+ WHERE+ cp."chatId" = $1+ GROUP BY+ sp.id, c."userId"+ "#,+ chat_id,+ )+ .fetch_one(pool)+ .await?;++ let channel_share_permissions: Option<Vec<ChannelSharePermission>> =+ if let Some(channel_share_permissions) = result.channel_share_permissions {+ let parsed: Vec<ChannelSharePermission> =+ serde_json::from_value(channel_share_permissions)?;+ if parsed.is_empty() {+ None+ } else {+ Some(parsed)+ }+ } else {+ None+ };++ let public_access_level: Option<AccessLevel> = result+ .public_access_level+ .map(|s| AccessLevel::from_str(&s).unwrap());++ Ok(SharePermissionV2 {+ id: result.id,+ is_public: result.is_public,+ public_access_level,+ owner: result.owner,+ channel_share_permissions,+ })+}diff --git a/rust/cloud-storage/chat/src/outbound/postgres/queries/get_web_citations.rs b/rust/cloud-storage/chat/src/outbound/postgres/queries/get_web_citations.rsnew file mode 100644index 0000000000..6315d0ff1c--- /dev/null+++ b/rust/cloud-storage/chat/src/outbound/postgres/queries/get_web_citations.rs@@ -0,0 +1,46 @@+//! Fetch web citations for a chat.++use crate::domain::models::WebCitation;+use sqlx::PgPool;+use std::collections::HashMap;++/// Fetch web citations grouped by message ID.+#[tracing::instrument(err, skip(pool))]+pub(crate) async fn get_web_citations(+ pool: &PgPool,+ chat_id: &str,+) -> anyhow::Result<Vec<(String, Vec<WebCitation>)>> {+ let records = sqlx::query!(+ r#"+ SELECT+ "messageId" as "message_id",+ "url",+ "title",+ "description",+ "favicon_url",+ "image_url"+ FROM "WebAnnotations" wa+ INNER JOIN "ChatMessage" cm ON cm.id = wa."messageId"+ WHERE cm."chatId" = $1+ "#,+ chat_id+ )+ .fetch_all(pool)+ .await?;++ let mut citations: HashMap<String, Vec<WebCitation>> = HashMap::new();+ for record in records {+ let citation = WebCitation {+ url: record.url,+ title: record.title,+ description: record.description,+ image_url: record.image_url,+ favicon_url: record.favicon_url,+ };+ if let Some(id) = record.message_id {+ citations.entry(id).or_default().push(citation);+ }+ }++ Ok(citations.into_iter().collect())+}diff --git a/rust/cloud-storage/chat/src/outbound/postgres/queries/insert_chat.rs b/rust/cloud-storage/chat/src/outbound/postgres/queries/insert_chat.rsnew file mode 100644index 0000000000..31b1e8e9f8--- /dev/null+++ b/rust/cloud-storage/chat/src/outbound/postgres/queries/insert_chat.rs@@ -0,0 +1,28 @@+//! Insert a new chat row.++use macro_user_id::user_id::MacroUserIdStr;+use sqlx::{Postgres, Transaction};++/// Insert a new chat and return the generated chat ID.+#[tracing::instrument(err, skip(tx))]+pub(crate) async fn insert_chat(+ tx: &mut Transaction<'_, Postgres>,+ user_id: &MacroUserIdStr<'_>,+ name: &str,+ project_id: Option<&str>,+) -> anyhow::Result<String> {+ let row = sqlx::query_scalar!(+ r#"+ INSERT INTO "Chat" ("userId", name, "projectId")+ VALUES ($1, $2, $3)+ RETURNING id+ "#,+ user_id.as_ref(),+ name,+ project_id,+ )+ .fetch_one(tx.as_mut())+ .await?;++ Ok(row)+}diff --git a/rust/cloud-storage/chat/src/outbound/postgres/queries/insert_user_item_access.rs b/rust/cloud-storage/chat/src/outbound/postgres/queries/insert_user_item_access.rsnew file mode 100644index 0000000000..57ee59dbcb--- /dev/null+++ b/rust/cloud-storage/chat/src/outbound/postgres/queries/insert_user_item_access.rs@@ -0,0 +1,39 @@+//! Grant a user access to a chat.++use macro_user_id::user_id::MacroUserIdStr;+use models_permissions::share_permission::access_level::AccessLevel;+use sqlx::{Postgres, Transaction};++/// Insert an access record granting the user the given access level on a chat.+#[tracing::instrument(err, skip(tx))]+pub(crate) async fn insert_user_item_access(+ tx: &mut Transaction<'_, Postgres>,+ user_id: MacroUserIdStr<'_>,+ chat_id: &str,+ access_level: AccessLevel,+) -> anyhow::Result<()> {+ let id = macro_uuid::generate_uuid_v7();++ sqlx::query!(+ r#"+ INSERT INTO "UserItemAccess" (+ "id",+ "user_id",+ "item_id",+ "item_type",+ "access_level",+ "created_at",+ "updated_at"+ )+ VALUES ($1, $2, $3, 'chat', $4, NOW(), NOW())+ "#,+ id,+ user_id.as_ref(),+ chat_id,+ access_level as _,+ )+ .execute(tx.as_mut())+ .await?;++ Ok(())+}diff --git a/rust/cloud-storage/chat/src/outbound/postgres/queries/mod.rs b/rust/cloud-storage/chat/src/outbound/postgres/queries/mod.rsnew file mode 100644index 0000000000..c9df3f517d--- /dev/null+++ b/rust/cloud-storage/chat/src/outbound/postgres/queries/mod.rs@@ -0,0 +1,18 @@+//! Individual SQL queries for chat operations.++pub(crate) mod copy_messages;+pub(crate) mod create_chat_permission;+pub(crate) mod edit_share_permission;+pub(crate) mod get_access_level;+pub(crate) mod get_chat;+pub(crate) mod get_messages;+pub(crate) mod get_permissions;+pub(crate) mod get_web_citations;+pub(crate) mod insert_chat;+pub(crate) mod insert_user_item_access;+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 upsert_item_last_accessed;+pub(crate) mod upsert_user_history;diff --git a/rust/cloud-storage/chat/src/outbound/postgres/queries/patch_chat.rs b/rust/cloud-storage/chat/src/outbound/postgres/queries/patch_chat.rsnew file mode 100644index 0000000000..ee60b423e5--- /dev/null+++ b/rust/cloud-storage/chat/src/outbound/postgres/queries/patch_chat.rs@@ -0,0 +1,50 @@+//! Patch a chat's metadata.++use sqlx::{Postgres, Transaction};++/// Update a chat's `updatedAt`, and optionally its `name` and `projectId`.+#[tracing::instrument(err, skip(tx))]+pub(crate) async fn patch_chat(+ tx: &mut Transaction<'_, Postgres>,+ chat_id: &str,+ name: Option<&str>,+ project_id: Option<&str>,+) -> anyhow::Result<()> {+ sqlx::query!(+ r#"UPDATE "Chat" SET "updatedAt" = NOW() WHERE id = $1"#,+ chat_id,+ )+ .execute(tx.as_mut())+ .await?;++ if let Some(name) = name {+ sqlx::query!(+ r#"UPDATE "Chat" SET "name" = $1 WHERE id = $2"#,+ name,+ chat_id,+ )+ .execute(tx.as_mut())+ .await?;+ }++ if let Some(project_id) = project_id {+ if project_id.is_empty() {+ sqlx::query!(+ r#"UPDATE "Chat" SET "projectId" = NULL WHERE id = $1"#,+ chat_id,+ )+ .execute(tx.as_mut())+ .await?;+ } else {+ sqlx::query!(+ r#"UPDATE "Chat" SET "projectId" = $1 WHERE id = $2"#,+ project_id,+ chat_id,+ )+ .execute(tx.as_mut())+ .await?;+ }+ }++ Ok(())+}diff --git a/rust/cloud-storage/chat/src/outbound/postgres/queries/permanently_delete_chat.rs b/rust/cloud-storage/chat/src/outbound/postgres/queries/permanently_delete_chat.rsnew file mode 100644index 0000000000..0551189a31--- /dev/null+++ b/rust/cloud-storage/chat/src/outbound/postgres/queries/permanently_delete_chat.rs@@ -0,0 +1,52 @@+//! Permanently delete a chat and all associated data.++use sqlx::{Postgres, Transaction};++/// Hard-delete a chat: remove pins, history, permissions, access, and the chat row.+#[tracing::instrument(err, skip(tx))]+pub(crate) async fn permanently_delete_chat(+ tx: &mut Transaction<'_, Postgres>,+ chat_id: &str,+) -> anyhow::Result<()> {+ sqlx::query!(+ r#"DELETE FROM "Pin" WHERE "pinnedItemId" = $1 AND "pinnedItemType" = 'chat'"#,+ chat_id,+ )+ .execute(tx.as_mut())+ .await?;++ sqlx::query!(+ r#"DELETE FROM "UserHistory" WHERE "itemId" = $1 AND "itemType" = 'chat'"#,+ chat_id,+ )+ .execute(tx.as_mut())+ .await?;++ // Delete share permission (cascades ChatPermission)+ sqlx::query!(+ r#"+ DELETE FROM "SharePermission"+ WHERE id IN (+ SELECT "sharePermissionId"+ FROM "ChatPermission"+ WHERE "chatId" = $1+ )+ "#,+ chat_id,+ )+ .execute(tx.as_mut())+ .await?;++ sqlx::query!(+ r#"DELETE FROM "UserItemAccess" WHERE "item_id" = $1 AND "item_type" = 'chat'"#,+ chat_id,+ )+ .execute(tx.as_mut())+ .await?;++ sqlx::query!(r#"DELETE FROM "Chat" WHERE id = $1"#, chat_id,)+ .execute(tx.as_mut())+ .await?;++ Ok(())+}diff --git a/rust/cloud-storage/chat/src/outbound/postgres/queries/revert_delete_chat.rs b/rust/cloud-storage/chat/src/outbound/postgres/queries/revert_delete_chat.rsnew file mode 100644index 0000000000..318cce0c6a--- /dev/null+++ b/rust/cloud-storage/chat/src/outbound/postgres/queries/revert_delete_chat.rs@@ -0,0 +1,66 @@+//! Revert a soft-deleted chat.++use anyhow::Context;++/// Clear `deleted_at`, restore the chat to user history, and detach from a+/// deleted project if necessary.+#[tracing::instrument(err, skip(tx))]+pub(crate) async fn revert_delete_chat(+ tx: &mut sqlx::Transaction<'_, sqlx::Postgres>,+ chat_id: &str,+ project_id: Option<&str>,+) -> anyhow::Result<()> {+ let chat_owner = sqlx::query!(+ r#"+ UPDATE "Chat"+ SET "deletedAt" = NULL+ WHERE id = $1+ RETURNING "userId" as owner+ "#,+ chat_id,+ )+ .map(|row| row.owner)+ .fetch_one(&mut **tx)+ .await+ .context("unable to update chat")?;++ sqlx::query!(+ r#"+ INSERT INTO "UserHistory" ("userId", "itemId", "itemType", "createdAt", "updatedAt")+ VALUES ($1, $2, $3, NOW(), NOW())+ ON CONFLICT ("userId", "itemId", "itemType") DO UPDATE+ SET "updatedAt" = NOW();+ "#,+ chat_owner,+ chat_id,+ "chat",+ )+ .execute(&mut **tx)+ .await+ .context("unable to add chat to history")?;++ if let Some(project_id) = project_id {+ let is_deleted = sqlx::query!(+ r#"+ SELECT "deletedAt" as deleted_at FROM "Project" WHERE "id" = $1+ "#,+ project_id+ )+ .map(|row| row.deleted_at)+ .fetch_one(&mut **tx)+ .await?;++ if is_deleted.is_some() {+ sqlx::query!(+ r#"+ UPDATE "Chat" SET "projectId" = NULL WHERE "id" = $1+ "#,+ chat_id+ )+ .execute(&mut **tx)+ .await?;+ }+ }++ Ok(())+}diff --git a/rust/cloud-storage/chat/src/outbound/postgres/queries/soft_delete_chat.rs b/rust/cloud-storage/chat/src/outbound/postgres/queries/soft_delete_chat.rsnew file mode 100644index 0000000000..8fc1bfdcf4--- /dev/null+++ b/rust/cloud-storage/chat/src/outbound/postgres/queries/soft_delete_chat.rs@@ -0,0 +1,33 @@+//! Soft-delete a chat.++use sqlx::{Postgres, Transaction};++/// Soft-delete a chat: remove pins and history, then set `deletedAt`.+#[tracing::instrument(err, skip(tx))]+pub(crate) async fn soft_delete_chat(+ tx: &mut Transaction<'_, Postgres>,+ chat_id: &str,+) -> anyhow::Result<()> {+ sqlx::query!(+ r#"DELETE FROM "Pin" WHERE "pinnedItemId" = $1 AND "pinnedItemType" = 'chat'"#,+ chat_id,+ )+ .execute(tx.as_mut())+ .await?;++ sqlx::query!(+ r#"DELETE FROM "UserHistory" WHERE "itemId" = $1 AND "itemType" = 'chat'"#,+ chat_id,+ )+ .execute(tx.as_mut())+ .await?;++ sqlx::query!(+ r#"UPDATE "Chat" SET "deletedAt" = NOW() WHERE id = $1"#,+ chat_id,+ )+ .execute(tx.as_mut())+ .await?;++ Ok(())+}diff --git a/rust/cloud-storage/chat/src/outbound/postgres/queries/upsert_item_last_accessed.rs b/rust/cloud-storage/chat/src/outbound/postgres/queries/upsert_item_last_accessed.rsnew file mode 100644index 0000000000..10173d6fb4--- /dev/null+++ b/rust/cloud-storage/chat/src/outbound/postgres/queries/upsert_item_last_accessed.rs@@ -0,0 +1,24 @@+//! Track when a chat was last accessed.++use sqlx::{Postgres, Transaction};++/// Record the last-accessed timestamp for this chat.+#[tracing::instrument(err, skip(tx))]+pub(crate) async fn upsert_item_last_accessed(+ tx: &mut Transaction<'_, Postgres>,+ chat_id: &str,+) -> anyhow::Result<()> {+ sqlx::query!(+ r#"+ INSERT INTO "ItemLastAccessed" ("item_id", "item_type", "last_accessed")+ VALUES ($1, 'chat', NOW())+ ON CONFLICT ("item_id", "item_type") DO UPDATE+ SET "last_accessed" = NOW()+ "#,+ chat_id,+ )+ .execute(tx.as_mut())+ .await?;++ Ok(())+}diff --git a/rust/cloud-storage/chat/src/outbound/postgres/queries/upsert_user_history.rs b/rust/cloud-storage/chat/src/outbound/postgres/queries/upsert_user_history.rsnew file mode 100644index 0000000000..b023e4d03f--- /dev/null+++ b/rust/cloud-storage/chat/src/outbound/postgres/queries/upsert_user_history.rs@@ -0,0 +1,27 @@+//! Upsert a chat entry in the user's history.++use macro_user_id::user_id::MacroUserIdStr;+use sqlx::{Postgres, Transaction};++/// Record that the user accessed this chat in their history.+#[tracing::instrument(err, skip(tx))]+pub(crate) async fn upsert_user_history(+ tx: &mut Transaction<'_, Postgres>,+ user_id: MacroUserIdStr<'_>,+ chat_id: &str,+) -> anyhow::Result<()> {+ sqlx::query!(+ r#"+ INSERT INTO "UserHistory" ("userId", "itemId", "itemType", "createdAt", "updatedAt")+ VALUES ($1, $2, 'chat', NOW(), NOW())+ ON CONFLICT ("userId", "itemId", "itemType") DO UPDATE+ SET "updatedAt" = NOW()+ "#,+ user_id.as_ref(),+ chat_id,+ )+ .execute(tx.as_mut())+ .await?;++ Ok(())+}diff --git a/rust/cloud-storage/chat/src/outbound/postgres/test.rs b/rust/cloud-storage/chat/src/outbound/postgres/test.rsnew file mode 100644index 0000000000..ecbfb2e162--- /dev/null+++ b/rust/cloud-storage/chat/src/outbound/postgres/test.rs@@ -0,0 +1,702 @@+use macro_db_migrator::MACRO_DB_MIGRATIONS;+use macro_user_id::cowlike::CowLike;+use macro_user_id::user_id::MacroUserIdStr;+use sqlx::{Pool, Postgres, Row};++use super::PgChatRepo;+use crate::domain::models::{ChatErr, CopyChatArgs, CreateChatArgs, PatchChatArgs};+use crate::domain::ports::ChatRepo;++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "fixtures", scripts("users"))+)]+async fn create_chat_returns_id(pool: Pool<Postgres>) {+ let repo = PgChatRepo::new(pool.clone());+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned();++ let chat_id = repo+ .create(+ user_id,+ CreateChatArgs {+ name: "Test Chat".to_string(),+ project_id: None,+ },+ )+ .await+ .unwrap();++ assert!(!chat_id.is_empty());++ // verify the chat row exists+ let row = sqlx::query(r#"SELECT "userId", name FROM "Chat" WHERE id = $1"#)+ .bind(&chat_id)+ .fetch_one(&pool)+ .await+ .unwrap();++ assert_eq!(row.get::<String, _>("name"), "Test Chat");+ assert_eq!(row.get::<String, _>("userId"), "macro|[email protected]");+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "fixtures", scripts("users"))+)]+async fn create_chat_creates_permission(pool: Pool<Postgres>) {+ let repo = PgChatRepo::new(pool.clone());+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned();++ let chat_id = repo+ .create(+ user_id,+ CreateChatArgs {+ name: "Perm Chat".to_string(),+ project_id: None,+ },+ )+ .await+ .unwrap();++ let row =+ sqlx::query(r#"SELECT "sharePermissionId" FROM "ChatPermission" WHERE "chatId" = $1"#)+ .bind(&chat_id)+ .fetch_one(&pool)+ .await+ .unwrap();++ let share_permission_id: String = row.get("sharePermissionId");+ assert!(!share_permission_id.is_empty());+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "fixtures", scripts("users"))+)]+async fn create_chat_creates_user_item_access(pool: Pool<Postgres>) {+ let repo = PgChatRepo::new(pool.clone());+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned();++ let chat_id = repo+ .create(+ user_id,+ CreateChatArgs {+ name: "Access Chat".to_string(),+ project_id: None,+ },+ )+ .await+ .unwrap();++ let row = sqlx::query(+ r#"+ SELECT "access_level"::text as "access_level"+ FROM "UserItemAccess"+ WHERE "user_id" = $1 AND "item_id" = $2 AND "item_type" = 'chat'+ "#,+ )+ .bind("macro|[email protected]")+ .bind(&chat_id)+ .fetch_one(&pool)+ .await+ .unwrap();++ assert_eq!(+ row.get::<Option<String>, _>("access_level"),+ Some("owner".to_string())+ );+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "fixtures", scripts("users"))+)]+async fn create_chat_creates_user_history(pool: Pool<Postgres>) {+ let repo = PgChatRepo::new(pool.clone());+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned();++ let chat_id = repo+ .create(+ user_id,+ CreateChatArgs {+ name: "History Chat".to_string(),+ project_id: None,+ },+ )+ .await+ .unwrap();++ let row = sqlx::query(+ r#"+ SELECT "itemType" FROM "UserHistory"+ WHERE "userId" = $1 AND "itemId" = $2+ "#,+ )+ .bind("macro|[email protected]")+ .bind(&chat_id)+ .fetch_one(&pool)+ .await+ .unwrap();++ assert_eq!(row.get::<String, _>("itemType"), "chat");+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "fixtures", scripts("users"))+)]+async fn create_chat_with_project_id(pool: Pool<Postgres>) {+ let repo = PgChatRepo::new(pool.clone());+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned();++ let chat_id = repo+ .create(+ user_id,+ CreateChatArgs {+ name: "Project Chat".to_string(),+ project_id: Some("project-123".to_string()),+ },+ )+ .await+ .unwrap();++ let row = sqlx::query(r#"SELECT "projectId" FROM "Chat" WHERE id = $1"#)+ .bind(&chat_id)+ .fetch_one(&pool)+ .await+ .unwrap();++ assert_eq!(+ row.get::<Option<String>, _>("projectId"),+ Some("project-123".to_string())+ );+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "fixtures", scripts("users"))+)]+async fn get_chat_returns_chat(pool: Pool<Postgres>) {+ let repo = PgChatRepo::new(pool.clone());+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned();++ let chat_id = repo+ .create(+ user_id,+ CreateChatArgs {+ name: "Get Me".to_string(),+ project_id: None,+ },+ )+ .await+ .unwrap();++ let chat = repo.get_metadata(&chat_id).await.unwrap();++ assert_eq!(chat.id, chat_id);+ assert_eq!(chat.name, "Get Me");+ assert_eq!(chat.user_id, "macro|[email protected]");+ assert!(chat.created_at.is_some());+ assert!(chat.updated_at.is_some());+ assert!(chat.deleted_at.is_none());+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "fixtures", scripts("users"))+)]+async fn get_chat_not_found(pool: Pool<Postgres>) {+ let repo = PgChatRepo::new(pool);++ let result = repo.get_metadata("nonexistent-id").await;+ assert!(matches!(result, Err(ChatErr::NotFound)));+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "fixtures", scripts("users"))+)]+async fn soft_delete_chat_sets_deleted_at(pool: Pool<Postgres>) {+ let repo = PgChatRepo::new(pool.clone());+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned();++ let chat_id = repo+ .create(+ user_id,+ CreateChatArgs {+ name: "Delete Me".to_string(),+ project_id: None,+ },+ )+ .await+ .unwrap();++ repo.delete(&chat_id).await.unwrap();++ let row = sqlx::query(r#"SELECT "deletedAt" FROM "Chat" WHERE id = $1"#)+ .bind(&chat_id)+ .fetch_one(&pool)+ .await+ .unwrap();++ let deleted_at: Option<chrono::NaiveDateTime> = row.get("deletedAt");+ assert!(deleted_at.is_some());+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "fixtures", scripts("users"))+)]+async fn soft_delete_chat_removes_history(pool: Pool<Postgres>) {+ let repo = PgChatRepo::new(pool.clone());+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned();++ let chat_id = repo+ .create(+ user_id,+ CreateChatArgs {+ name: "History Delete".to_string(),+ project_id: None,+ },+ )+ .await+ .unwrap();++ repo.delete(&chat_id).await.unwrap();++ let count: (i64,) = sqlx::query_as(+ r#"SELECT COUNT(*) FROM "UserHistory" WHERE "itemId" = $1 AND "itemType" = 'chat'"#,+ )+ .bind(&chat_id)+ .fetch_one(&pool)+ .await+ .unwrap();++ assert_eq!(count.0, 0);+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "fixtures", scripts("users"))+)]+async fn permanently_delete_chat_removes_row(pool: Pool<Postgres>) {+ let repo = PgChatRepo::new(pool.clone());+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned();++ let chat_id = repo+ .create(+ user_id,+ CreateChatArgs {+ name: "Perm Delete".to_string(),+ project_id: None,+ },+ )+ .await+ .unwrap();++ repo.permanently_delete(&chat_id).await.unwrap();++ let count: (i64,) = sqlx::query_as(r#"SELECT COUNT(*) FROM "Chat" WHERE id = $1"#)+ .bind(&chat_id)+ .fetch_one(&pool)+ .await+ .unwrap();++ assert_eq!(count.0, 0);+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "fixtures", scripts("users"))+)]+async fn permanently_delete_chat_removes_permissions(pool: Pool<Postgres>) {+ let repo = PgChatRepo::new(pool.clone());+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned();++ let chat_id = repo+ .create(+ user_id,+ CreateChatArgs {+ name: "Perm Delete Perms".to_string(),+ project_id: None,+ },+ )+ .await+ .unwrap();++ repo.permanently_delete(&chat_id).await.unwrap();++ let count: (i64,) =+ sqlx::query_as(r#"SELECT COUNT(*) FROM "ChatPermission" WHERE "chatId" = $1"#)+ .bind(&chat_id)+ .fetch_one(&pool)+ .await+ .unwrap();++ assert_eq!(count.0, 0);+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "fixtures", scripts("users"))+)]+async fn permanently_delete_chat_removes_user_item_access(pool: Pool<Postgres>) {+ let repo = PgChatRepo::new(pool.clone());+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned();++ let chat_id = repo+ .create(+ user_id,+ CreateChatArgs {+ name: "Perm Delete Access".to_string(),+ project_id: None,+ },+ )+ .await+ .unwrap();++ repo.permanently_delete(&chat_id).await.unwrap();++ let count: (i64,) = sqlx::query_as(+ r#"SELECT COUNT(*) FROM "UserItemAccess" WHERE "item_id" = $1 AND "item_type" = 'chat'"#,+ )+ .bind(&chat_id)+ .fetch_one(&pool)+ .await+ .unwrap();++ assert_eq!(count.0, 0);+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "fixtures", scripts("users"))+)]+async fn patch_chat_updates_name(pool: Pool<Postgres>) {+ let repo = PgChatRepo::new(pool.clone());+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned();++ let chat_id = repo+ .create(+ user_id,+ CreateChatArgs {+ name: "Original".to_string(),+ project_id: None,+ },+ )+ .await+ .unwrap();++ let patch_user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned();+ repo.patch(+ patch_user_id,+ &chat_id,+ PatchChatArgs {+ name: Some("Renamed".to_string()),+ project_id: None,+ share_permission: None,+ },+ )+ .await+ .unwrap();++ let chat = repo.get_metadata(&chat_id).await.unwrap();+ assert_eq!(chat.name, "Renamed");+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "fixtures", scripts("users"))+)]+async fn patch_chat_updates_project(pool: Pool<Postgres>) {+ let repo = PgChatRepo::new(pool.clone());+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned();++ let chat_id = repo+ .create(+ user_id,+ CreateChatArgs {+ name: "Project Chat".to_string(),+ project_id: None,+ },+ )+ .await+ .unwrap();++ let patch_user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned();+ repo.patch(+ patch_user_id,+ &chat_id,+ PatchChatArgs {+ name: None,+ project_id: Some("project-123".to_string()),+ share_permission: None,+ },+ )+ .await+ .unwrap();++ let row = sqlx::query(r#"SELECT "projectId" FROM "Chat" WHERE id = $1"#)+ .bind(&chat_id)+ .fetch_one(&pool)+ .await+ .unwrap();++ assert_eq!(+ row.get::<Option<String>, _>("projectId"),+ Some("project-123".to_string())+ );+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "fixtures", scripts("users"))+)]+async fn patch_chat_clears_project(pool: Pool<Postgres>) {+ let repo = PgChatRepo::new(pool.clone());+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned();++ let chat_id = repo+ .create(+ user_id,+ CreateChatArgs {+ name: "Clear Project".to_string(),+ project_id: Some("project-123".to_string()),+ },+ )+ .await+ .unwrap();++ let patch_user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned();+ repo.patch(+ patch_user_id,+ &chat_id,+ PatchChatArgs {+ name: None,+ project_id: Some("".to_string()),+ share_permission: None,+ },+ )+ .await+ .unwrap();++ let row = sqlx::query(r#"SELECT "projectId" FROM "Chat" WHERE id = $1"#)+ .bind(&chat_id)+ .fetch_one(&pool)+ .await+ .unwrap();++ assert_eq!(row.get::<Option<String>, _>("projectId"), None::<String>);+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "fixtures", scripts("users"))+)]+async fn get_chat_returns_full_response(pool: Pool<Postgres>) {+ let repo = PgChatRepo::new(pool.clone());+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned();++ let chat_id = repo+ .create(+ user_id,+ CreateChatArgs {+ name: "Full Chat".to_string(),+ project_id: None,+ },+ )+ .await+ .unwrap();++ let response = repo.get_chat(&chat_id).await.unwrap();++ assert_eq!(response.id, chat_id);+ assert_eq!(response.name, "Full Chat");+ assert_eq!(response.user_id, "macro|[email protected]");+ assert!(response.model.is_some());+ assert!(response.messages.is_empty());+ assert!(response.web_citations.is_empty());+ assert!(!response.available_models.is_empty());+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "fixtures", scripts("users"))+)]+async fn get_chat_not_found_returns_error(pool: Pool<Postgres>) {+ let repo = PgChatRepo::new(pool);++ let result = repo.get_chat("nonexistent-id").await;+ assert!(matches!(result, Err(ChatErr::NotFound)));+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "fixtures", scripts("users"))+)]+async fn copy_chat_creates_new_chat_with_same_messages(pool: Pool<Postgres>) {+ let repo = PgChatRepo::new(pool.clone());+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned();++ let source_id = repo+ .create(+ user_id.clone(),+ CreateChatArgs {+ name: "Source Chat".to_string(),+ project_id: None,+ },+ )+ .await+ .unwrap();++ // Insert a message into the source chat+ sqlx::query(+ r#"+ INSERT INTO "ChatMessage" ("chatId", "content", "role")+ VALUES ($1, '"hello"', 'user')+ "#,+ )+ .bind(&source_id)+ .execute(&pool)+ .await+ .unwrap();++ let copied_id = repo+ .copy_chat(+ user_id,+ &source_id,+ CopyChatArgs {+ name: "Copied Chat".to_string(),+ project_id: None,+ },+ )+ .await+ .unwrap();++ assert_ne!(source_id, copied_id);++ // Verify the copy has the right name+ let copy = repo.get_metadata(&copied_id).await.unwrap();+ assert_eq!(copy.name, "Copied Chat");++ // Verify the message was copied+ let msg_count: (i64,) =+ sqlx::query_as(r#"SELECT COUNT(*) FROM "ChatMessage" WHERE "chatId" = $1"#)+ .bind(&copied_id)+ .fetch_one(&pool)+ .await+ .unwrap();++ assert_eq!(msg_count.0, 1);+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "fixtures", scripts("users"))+)]+async fn revert_delete_restores_chat(pool: Pool<Postgres>) {+ let repo = PgChatRepo::new(pool.clone());+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned();++ let chat_id = repo+ .create(+ user_id,+ CreateChatArgs {+ name: "Revert Me".to_string(),+ project_id: None,+ },+ )+ .await+ .unwrap();++ repo.delete(&chat_id).await.unwrap();++ // Confirm it's deleted+ let chat = repo.get_metadata(&chat_id).await.unwrap();+ assert!(chat.deleted_at.is_some());++ repo.revert_delete(&chat_id, None).await.unwrap();++ // Confirm it's restored+ let chat = repo.get_metadata(&chat_id).await.unwrap();+ assert!(chat.deleted_at.is_none());++ // Confirm history was re-added+ let count: (i64,) = sqlx::query_as(+ r#"SELECT COUNT(*) FROM "UserHistory" WHERE "itemId" = $1 AND "itemType" = 'chat'"#,+ )+ .bind(&chat_id)+ .fetch_one(&pool)+ .await+ .unwrap();++ assert_eq!(count.0, 1);+}++#[sqlx::test(+ migrator = "MACRO_DB_MIGRATIONS",+ fixtures(path = "fixtures", scripts("users"))+)]+async fn get_permissions_returns_share_permission(pool: Pool<Postgres>) {+ let repo = PgChatRepo::new(pool.clone());+ let user_id = MacroUserIdStr::parse_from_str("macro|[email protected]")+ .unwrap()+ .into_owned();++ let chat_id = repo+ .create(+ user_id,+ CreateChatArgs {+ name: "Perms Chat".to_string(),+ project_id: None,+ },+ )+ .await+ .unwrap();++ let perms = repo.get_permissions(&chat_id).await.unwrap();++ assert!(!perms.id.is_empty());+ assert_eq!(perms.owner, "macro|[email protected]");+ assert!(perms.is_public);+}diff --git a/rust/cloud-storage/document_cognition_service/Cargo.toml b/rust/cloud-storage/document_cognition_service/Cargo.tomlindex 9070c0f14e..d008913bb9 100644--- a/rust/cloud-storage/document_cognition_service/Cargo.toml+++ b/rust/cloud-storage/document_cognition_service/Cargo.toml@@ -48,6 +48,7 @@ aws-sdk-s3 = { workspace = true }aws-sdk-sqs = { workspace = true }axum = { workspace = true, features = ["tower-log", "ws"] }base64 = { workspace = true }+chat = { path = "../chat" }chrono = { workspace = true }comms = { path = "../comms", features = ["outbound"] }comms_service_client = { path = "../comms_service_client" }@@ -57,8 +58,8 @@ dashmap = { 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"] }-entity_access = { path = "../entity_access" }doppleganger = { workspace = true }+entity_access = { path = "../entity_access" }email = { path = "../email", features = ["outbound"] }email_service_client = { path = "../email_service_client" }frecency = { path = "../frecency", features = ["outbound", "postgres"] }diff --git a/rust/cloud-storage/document_cognition_service/src/api/chats/copy_chat.rs b/rust/cloud-storage/document_cognition_service/src/api/chats/copy_chat.rsdeleted file mode 100644index 11c7ae3cac..0000000000--- a/rust/cloud-storage/document_cognition_service/src/api/chats/copy_chat.rs+++ /dev/null@@ -1,126 +0,0 @@-use crate::{- api::context::ApiContext, core::model::FALLBACK_MODEL, model::request::chats::CopyChatRequest,- service::get_chat::get_chat,-};-use macro_db_client::dcs::copy_messages::copy_messages;-use macro_db_client::dcs::create_chat::create_chat_v2;--use axum::{- Json,- extract::{self, Path, State},- http::StatusCode,- response::{IntoResponse, Response},-};-use macro_middleware::cloud_storage::ensure_access::chat::ChatAccessLevelExtractor;-use model::{response::StringIDResponse, user::axum_extractor::MacroUserExtractor};-use models_permissions::share_permission::SharePermissionV2;-use models_permissions::share_permission::access_level::ViewAccessLevel;--#[derive(serde::Deserialize)]-pub struct Params {- pub chat_id: String,-}--#[utoipa::path(- post,- path = "/chats/{chat_id}/copy",- responses(- (status = 201, body=StringIDResponse),- (status = 401, body=String),- (status = 404, body=String),- (status = 500, body=String),- ),- params(- ("chat_id" = String, Path, description = "Chat id")- )- )]-pub async fn copy_chat_handler(- _access: ChatAccessLevelExtractor<ViewAccessLevel>,- State(state): State<ApiContext>,- user_context: MacroUserExtractor,- Path(Params { chat_id }): Path<Params>,- extract::Json(req): extract::Json<CopyChatRequest>,-) -> Result<Response, Response> {- let string_id_response = copy_chat_v2(&state, user_context, chat_id, req)- .await- .map_err(|(status_code, err)| (status_code, err).into_response())?;-- Ok((StatusCode::OK, Json(string_id_response)).into_response())-}--#[tracing::instrument(skip(state, user_context, req), fields(user_id=?user_context.macro_user_id, chat_id))]-pub async fn copy_chat_v2(- state: &ApiContext,- user_context: MacroUserExtractor,- chat_id: String,- req: CopyChatRequest,-) -> Result<StringIDResponse, (StatusCode, String)> {- // 1. create share permission- let share_permission = SharePermissionV2::new_chat_share_permission();- // 2. create new chat- let old_chat = get_chat(state, &chat_id, &user_context.user_context.user_id)- .await- .map_err(|e| {- tracing::error!(error=?e, "failed to get chat");- (- StatusCode::NOT_FOUND,- "could not find chat to copy".to_string(),- )- })?;-- let project_id = if let Some(project_id) = old_chat.project_id {- // Depending on if you are the project owner, we should copy the project id- let project = macro_db_client::projects::get_project::get_basic_project::get_basic_project(- &state.db,- &project_id,- )- .await- .map_err(|e| {- tracing::error!(error=?e, project_id, "failed to get project");- (- StatusCode::INTERNAL_SERVER_ERROR,- "unable to get project".to_string(),- )- })?;-- if !project.user_id.eq(&user_context.macro_user_id) {- None- } else {- Some(project.id)- }- } else {- None- };-- let model = old_chat.model.unwrap_or(FALLBACK_MODEL);- let chat_id = create_chat_v2(- &state.db,- user_context.macro_user_id,- req.name.as_str(),- model,- project_id.as_deref(),- &share_permission,- vec![],- 0,- false, // copied chats are not persistent- )- .await- .map_err(|e| {- tracing::error!(error=?e, "failed to create chat");- (- StatusCode::INTERNAL_SERVER_ERROR,- "unable to copy chat".to_string(),- )- })?;- // 3. rename and copy messages- let new_id = copy_messages(state.db.clone(), old_chat.id.as_str(), chat_id.as_str())- .await- .map_err(|e| {- tracing::error!(error=?e, old_chat_id=?old_chat.id, new_chat_id=?chat_id, "failed to copy messages");- (- StatusCode::INTERNAL_SERVER_ERROR,- "unable to copy chat".to_string(),- )- })?;- Ok(StringIDResponse { id: new_id })-}diff --git a/rust/cloud-storage/document_cognition_service/src/api/chats/create_user_chat.rs b/rust/cloud-storage/document_cognition_service/src/api/chats/create_user_chat.rsdeleted file mode 100644index 72fe42f900..0000000000--- a/rust/cloud-storage/document_cognition_service/src/api/chats/create_user_chat.rs+++ /dev/null@@ -1,179 +0,0 @@-use crate::{- api::context::ApiContext,- core::{- constants::{- DEFAULT_CHANNEL_TOKENS, DEFAULT_CHAT_NAME, DEFAULT_EMAIL_TOKENS, DEFAULT_IMAGE_TOKENS,- DEFAULT_PROJECT_TOKENS,- },- model::FALLBACK_MODEL,- },- model::request::chats::CreateChatRequest,- service::attachment::document::get_document_token_count,-};-use anyhow::Context;-use axum::{- Json,- extract::State,- http::StatusCode,- response::{IntoResponse, Response},-};-use macro_db_client::dcs::create_chat;-use macro_middleware::cloud_storage::ensure_access::{- get_users_access_level_v2, project::ProjectBodyAccessLevelExtractor,-};-use model::{chat::AttachmentType, response::StringIDResponse};-use model::{chat::NewChatAttachment, user::axum_extractor::MacroUserExtractor};-use models_permissions::share_permission::SharePermissionV2;-use models_permissions::share_permission::access_level::EditAccessLevel;--#[utoipa::path(- post,- path = "/chats",- responses(- (status = 201, body=StringIDResponse),- (status = 401, body=String),- (status = 404, body=String),- (status = 500, body=String),- )- )]-#[tracing::instrument(skip(state, user_context), fields(user_id=%user_context.macro_user_id))]-pub(in crate::api) async fn create_chat_handler(- State(state): State<ApiContext>,- user_context: MacroUserExtractor,- project: ProjectBodyAccessLevelExtractor<EditAccessLevel, CreateChatRequest>,-) -> Result<Response, Response> {- let req = project.into_inner();-- for attachment in req.attachments.as_ref().unwrap_or(&vec![]) {- if attachment.attachment_type == AttachmentType::Document {- get_users_access_level_v2(- &state.db,- user_context.macro_user_id.as_ref(),- &attachment.attachment_id,- "document",- )- .await- .map_err(|err| {- tracing::error!(- error = ?err,- user_id = %user_context.macro_user_id,- attachment_id = %attachment.attachment_id,- "failed to verify document access"- );- (- StatusCode::UNAUTHORIZED,- "No access to document".to_string(),- )- .into_response()- })?- .ok_or_else(|| {- tracing::error!(- user_id = %user_context.macro_user_id,- attachment_id = %attachment.attachment_id,- "user has no access to document"- );- (- StatusCode::UNAUTHORIZED,- "No access to document".to_string(),- )- .into_response()- })?;- }- }-- let string_id_response = create_user_chat_v2(&state, user_context, req)- .await- .map_err(|(status_code, err)| (status_code, err).into_response())?;-- Ok((StatusCode::OK, Json(string_id_response)).into_response())-}--#[tracing::instrument(- skip(ctx, user_context, req),- fields(- user_id = %user_context.macro_user_id,- project_id = ?req.project_id,- model = ?req.model,- attachment_count = req.attachments.as_ref().map(|a| a.len()).unwrap_or(0),- )-)]-pub async fn create_user_chat_v2(- ctx: &ApiContext,- user_context: MacroUserExtractor,- req: CreateChatRequest,-) -> Result<StringIDResponse, (StatusCode, String)> {- let chat_name = req.name.unwrap_or(DEFAULT_CHAT_NAME.to_string());- let share_permission = SharePermissionV2::new_chat_share_permission();-- let attachment_token_count =- futures::future::try_join_all(req.attachments.as_ref().into_iter().flatten().map(- |attachment| {- let ctx = ctx.clone();- async move {- match &attachment.attachment_type {- AttachmentType::Document => {- get_document_token_count(&ctx, &attachment.attachment_id)- .await- .context("failed to get document token count")- }-- AttachmentType::Image => Ok(DEFAULT_IMAGE_TOKENS),- AttachmentType::Channel => Ok(DEFAULT_CHANNEL_TOKENS),- AttachmentType::Email => Ok(DEFAULT_EMAIL_TOKENS),- AttachmentType::Project => Ok(DEFAULT_PROJECT_TOKENS),- }- }- },- ))- .await- .map_err(|err| {- tracing::error!(error = %err, "failed to calculate attachment token count");- (- StatusCode::BAD_REQUEST,- "unsupported attachment type".to_string(),- )- })?- .iter()- .sum();-- let chat = create_chat::create_chat_v2(- &ctx.db,- user_context.macro_user_id.clone(),- &chat_name,- req.model.unwrap_or(FALLBACK_MODEL),- req.project_id.as_deref(),- &share_permission,- req.attachments- .unwrap_or_default()- .into_iter()- .map(|attachment| NewChatAttachment {- attachment_id: attachment.attachment_id,- attachment_type: attachment.attachment_type,- // this is only known after creating the row in the db so it mutated in the inner function. Yes this type should be refactored,- chat_id: "cope".into(),- })- .collect(),- attachment_token_count,- req.is_persistent.unwrap_or(false),- )- .await- .map_err(|err| {- tracing::error!(error = %err, "failed to create chat in database");- (- StatusCode::INTERNAL_SERVER_ERROR,- "unable to create chat".to_string(),- )- })?;-- macro_project_utils::update_project_modified(- &ctx.db,- macro_project_utils::ProjectModifiedArgs {- project_id: req.project_id.clone(),- old_project_id: None,- user_id: user_context.macro_user_id.to_string(),- },- )- .await;-- Ok(StringIDResponse { id: chat })-}diff --git a/rust/cloud-storage/document_cognition_service/src/api/chats/delete_chat.rs b/rust/cloud-storage/document_cognition_service/src/api/chats/delete_chat.rsdeleted file mode 100644index da43140049..0000000000--- a/rust/cloud-storage/document_cognition_service/src/api/chats/delete_chat.rs+++ /dev/null@@ -1,123 +0,0 @@-use crate::api::context::ApiContext;-use anyhow::Context;-use axum::{- Extension, Json,- extract::{Path, State},- http::StatusCode,- response::{IntoResponse, Response},-};-use macro_middleware::cloud_storage::ensure_access::chat::ChatAccessLevelExtractor;-use model::{chat::ChatBasic, response::EmptyResponse, user::UserContext};-use models_permissions::share_permission::access_level::OwnerAccessLevel;-use sqs_client::search::{SearchQueueMessage, chat::RemoveChatMessage};--#[derive(serde::Deserialize)]-pub struct Params {- pub chat_id: String,-}--/// Deletes a particular chat by its id.-/// Soft deletes the chat.-#[utoipa::path(- delete,- path = "/chats/{chat_id}",- responses(- (status = 200, body=EmptyResponse),- (status = 401, body=String),- (status = 404, body=String),- (status = 500, body=String),- ),- params(- ("chat_id" = String, Path, description = "Chat id"))- )]-#[tracing::instrument(skip(state, user_context, _access), fields(user_id=?user_context.user_id))]-pub async fn delete_chat_handler(- _access: ChatAccessLevelExtractor<OwnerAccessLevel>,- State(state): State<ApiContext>,- user_context: Extension<UserContext>,- Path(Params { chat_id }): Path<Params>,- chat: Extension<ChatBasic>,-) -> Result<Response, Response> {- // soft delete- if let Err(err) = macro_db_client::chat::delete::soft_delete_chat(&state.db, &chat_id)- .await- .context("soft deleting chat")- {- tracing::error!(- error = %err,- chat_id = %chat_id,- user_id = %user_context.user_id,- "unable to mark chat for delete"- );- let status_code = StatusCode::INTERNAL_SERVER_ERROR;- return Err((status_code, "unable to mark for delete").into_response());- }-- macro_project_utils::update_project_modified(- &state.db,- macro_project_utils::ProjectModifiedArgs {- project_id: chat.project_id.clone(),- old_project_id: None,- user_id: user_context.user_id.clone(),- },- )- .await;-- Ok((StatusCode::OK, Json(EmptyResponse::default())).into_response())-}--/// Permanently deletes a chat.-#[utoipa::path(- delete,- operation_id = "permanently_delete_chat",- path = "/chats/{chat_id}/permanent",- responses(- (status = 200, body=EmptyResponse),- (status = 401, body=String),- (status = 404, body=String),- (status = 500, body=String),- ),- params(- ("chat_id" = String, Path, description = "Chat id"))- )]-#[tracing::instrument(skip(state, user_context, _access), fields(user_id=?user_context.user_id))]-pub async fn permanently_delete_chat_handler(- _access: ChatAccessLevelExtractor<OwnerAccessLevel>,- State(state): State<ApiContext>,- user_context: Extension<UserContext>,- Path(Params { chat_id }): Path<Params>,-) -> impl IntoResponse {- if let Err(e) = macro_db_client::chat::delete::delete_chat(&state.db, &chat_id)- .await- .context("permanently deleting chat")- {- tracing::error!(- error = %e,- chat_id = %chat_id,- user_id = %user_context.user_id,- "unable to permanently delete chat"- );- return Err((StatusCode::INTERNAL_SERVER_ERROR, "unable to delete chat").into_response());- }-- if let Err(e) = state- .sqs_client- .send_message_to_search_event_queue(SearchQueueMessage::RemoveChatMessage(- RemoveChatMessage {- chat_id: chat_id.clone(),- message_id: None,- },- ))- .await- .context("enqueuing search remove chat message")- {- tracing::error!(- error = %e,- chat_id = %chat_id,- user_id = %user_context.user_id,- "unable to enqueue search remove chat message"- );- }-- Ok((StatusCode::OK, Json(EmptyResponse::default())).into_response())-}diff --git a/rust/cloud-storage/document_cognition_service/src/api/chats/get_chat.rs b/rust/cloud-storage/document_cognition_service/src/api/chats/get_chat.rsdeleted file mode 100644index e3e6ff3ade..0000000000--- a/rust/cloud-storage/document_cognition_service/src/api/chats/get_chat.rs+++ /dev/null@@ -1,69 +0,0 @@-use crate::{- api::context::ApiContext, model::response::chats::GetChatResponse, service::get_chat::get_chat,-};-use ai::types::Role;-use axum::{- Extension, Json,- extract::{Path, State},- http::StatusCode,- response::IntoResponse,-};-use macro_middleware::cloud_storage::ensure_access::chat::ChatAccessLevelExtractor;-use model::user::UserContext;-use models_permissions::share_permission::access_level::ViewAccessLevel;-use std::sync::Arc;--#[derive(serde::Deserialize)]-pub struct Params {- pub chat_id: String,-}--/// Gets a particular chat by its id-#[utoipa::path(- get,- path = "/chats/{chat_id}",- responses(- (status = 200, body=GetChatResponse),- (status = 401, body=String),- (status = 404, body=String),- (status = 500, body=String),- ),- params( ("chat_id" = String, Path, description = "id of the chat"))- )]-#[tracing::instrument(skip(ctx, user_context, access_level), fields(user_id=?user_context.user_id))]-pub async fn get_chat_handler(- ChatAccessLevelExtractor { access_level, .. }: ChatAccessLevelExtractor<ViewAccessLevel>,- State(ctx): State<ApiContext>,- user_context: Extension<UserContext>,- Path(Params { chat_id }): Path<Params>,-) -> impl IntoResponse {- let mut chat = match get_chat(&Arc::new(ctx.clone()), &chat_id, &user_context.user_id).await {- Ok(chat) => chat,- Err(err) => {- let mut status_code = StatusCode::INTERNAL_SERVER_ERROR;- if err- .to_string()- .contains("no rows returned by a query that expected to return at least one row")- {- status_code = StatusCode::NOT_FOUND;- }- tracing::error!(- error = %err,- chat_id = %chat_id,- user_id = %user_context.user_id,- status_code = ?status_code,- "failed to get chat"- );- return Err((status_code, "unable to get chat permissions"));- }- };-- chat.messages.retain(|m| m.role != Role::System);-- let get_chat_response = GetChatResponse {- chat,- user_access_level: access_level,- };-- Ok((StatusCode::OK, Json(get_chat_response)))-}diff --git a/rust/cloud-storage/document_cognition_service/src/api/chats/get_chat_permissions.rs b/rust/cloud-storage/document_cognition_service/src/api/chats/get_chat_permissions.rsdeleted file mode 100644index f89e9a6e66..0000000000--- a/rust/cloud-storage/document_cognition_service/src/api/chats/get_chat_permissions.rs+++ /dev/null@@ -1,71 +0,0 @@-use crate::model::response::chats::GetChatPermissionsResponseV2;--use axum::{- Extension, Json,- extract::{Path, State},- http::StatusCode,- response::{IntoResponse, Response},-};-use macro_middleware::cloud_storage::ensure_access::chat::ChatAccessLevelExtractor;-use model::user::UserContext;-use models_permissions::share_permission::access_level::EditAccessLevel;-use sqlx::PgPool;--#[derive(serde::Deserialize)]-pub struct Params {- pub chat_id: String,-}--/// Gets the current chat share permissions-#[utoipa::path(- get,- path = "/v2/chats/{chat_id}/permissions",- responses(- (status = 200, body=GetChatPermissionsResponseV2),- (status = 404, body=String),- (status = 500, body=String),- ),- params( ("chat_id" = String, Path, description = "id of the chat"))- )]-#[allow(dead_code, unused_variables)]-pub(in crate::api) async fn get_chat_permissions_handler_v2(- user_context: Extension<UserContext>,- Path(Params { chat_id }): Path<Params>,-) -> impl IntoResponse {- // TODO: implement- StatusCode::OK-}--#[tracing::instrument(skip(db, _access), fields(user_id=?_user_context.user_id))]-pub async fn get_chat_permissions_handler(- _access: ChatAccessLevelExtractor<EditAccessLevel>,- State(db): State<PgPool>,- _user_context: Extension<UserContext>,- Path(Params { chat_id }): Path<Params>,-) -> impl IntoResponse {- get_chat_permissions_v2(&db, &chat_id).await-}--#[tracing::instrument(skip(db))]-async fn get_chat_permissions_v2(- db: &sqlx::Pool<sqlx::Postgres>,- chat_id: &str,-) -> Result<Response, Response> {- let chat_permissions =- macro_db_client::share_permission::get::get_chat_share_permission(db, chat_id)- .await- .map_err(|e| {- tracing::error!(error = ?e, chat_id, "Failed to fetch chat share permission");- (- StatusCode::INTERNAL_SERVER_ERROR,- "unable to get chat permissions",- )- .into_response()- })?;-- let res = GetChatPermissionsResponseV2 {- permissions: chat_permissions,- };-- Ok((StatusCode::OK, Json(res)).into_response())-}diff --git a/rust/cloud-storage/document_cognition_service/src/api/chats/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/chats/mod.rsindex 3e176ea885..166a117e5b 100644--- a/rust/cloud-storage/document_cognition_service/src/api/chats/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/chats/mod.rs@@ -1,31 +1,35 @@pub mod chat_history;pub mod chat_history_batch_messages;-pub mod copy_chat;-pub mod create_user_chat;-pub mod delete_chat;-pub mod get_chat;-pub mod get_chat_permissions;-pub mod patch_chat;-pub mod revert_delete_chat;pub mod tool;use super::context::ApiContext;use axum::{Router,- routing::{delete, get, patch, post, put},+ routing::{get, post},};+use chat::domain::service::ChatServiceImpl;+use chat::inbound::{ChatRouterState, chat_create_router, chat_id_router};+use chat::outbound::postgres::PgChatRepo;+use entity_access::domain::service::EntityAccessServiceImpl;+use entity_access::outbound::PgAccessRepository;use tower::ServiceBuilder;pub fn router(state: ApiContext) -> Router<ApiContext> {+ let access_repo = PgAccessRepository::new(state.db.clone());+ let access_service = EntityAccessServiceImpl::new(access_repo);+ let chat_repo = PgChatRepo::new(state.db.clone());+ let chat_service = ChatServiceImpl::new(chat_repo);+ let chat_state = ChatRouterState::new(chat_service, access_service);+let ensure_chat_exists = axum::middleware::from_fn_with_state(state.clone(),macro_middleware::cloud_storage::chat::ensure_chat_exists::handler,);Router::new()- .route(- "/",- post(create_user_chat::create_chat_handler).layer(+ // Create route — needs ensure_user_exists + quota middleware, no ensure_chat_exists+ .merge(+ chat_create_router(chat_state.clone()).layer(ServiceBuilder::new().layer(axum::middleware::from_fn_with_state(state.clone(),@@ -41,64 +45,9 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {)),),)- .route(- "/{chat_id}/copy",- post(copy_chat::copy_chat_handler).layer(- ServiceBuilder::new()- .layer(axum::middleware::from_fn(- macro_middleware::auth::ensure_user_exists::handler,- ))- .layer(ensure_chat_exists.clone()),- ),- )- .route(- "/{chat_id}",- get(get_chat::get_chat_handler)- .layer(ServiceBuilder::new().layer(ensure_chat_exists.clone())),- )- .route(- "/{chat_id}/revert_delete",- put(revert_delete_chat::handler).layer(- ServiceBuilder::new()- .layer(axum::middleware::from_fn(- macro_middleware::auth::ensure_user_exists::handler,- ))- .layer(ensure_chat_exists.clone()),- ),- )- .route(- "/{chat_id}",- delete(delete_chat::delete_chat_handler).layer(- ServiceBuilder::new()- .layer(axum::middleware::from_fn(- macro_middleware::auth::ensure_user_exists::handler,- ))- .layer(ensure_chat_exists.clone()),- ),- )- .route(- "/{chat_id}/permanent",- delete(delete_chat::permanently_delete_chat_handler).layer(- ServiceBuilder::new()- .layer(axum::middleware::from_fn(- macro_middleware::auth::ensure_user_exists::handler,- ))- .layer(ensure_chat_exists.clone()),- ),- )- .route(- "/{chat_id}",- patch(patch_chat::patch_chat_handler).layer(- ServiceBuilder::new()- .layer(axum::middleware::from_fn(- macro_middleware::auth::ensure_user_exists::handler,- ))- .layer(ensure_chat_exists.clone()),- ),- )- .route(- "/{chat_id}/permissions",- get(get_chat_permissions::get_chat_permissions_handler).layer(+ // All /{chat_id} routes — need ensure_chat_exists for ChatAccessLevelExtractor+ .merge(+ chat_id_router(chat_state).layer(ServiceBuilder::new().layer(axum::middleware::from_fn(macro_middleware::auth::ensure_user_exists::handler,@@ -116,6 +65,7 @@ pub fn router(state: ApiContext) -> Router<ApiContext> {.layer(ensure_chat_exists.clone()),),)+ // History routes — remain in DCS.route("/history/{chat_id}",get(chat_history::get_chat_history_handler).layer(diff --git a/rust/cloud-storage/document_cognition_service/src/api/chats/patch_chat.rs b/rust/cloud-storage/document_cognition_service/src/api/chats/patch_chat.rsdeleted file mode 100644index 50bd671f5e..0000000000--- a/rust/cloud-storage/document_cognition_service/src/api/chats/patch_chat.rs+++ /dev/null@@ -1,184 +0,0 @@-use crate::{api::context::ApiContext, model::request::chats::PatchChatRequestV2};-use anyhow::{Context, Result};-use axum::{- Extension, Json,- extract::{Path, State},- http::StatusCode,- response::{IntoResponse, Response},-};-use macro_middleware::cloud_storage::ensure_access::{- chat::ChatAccessLevelExtractor, project::ProjectBodyAccessLevelExtractor,-};-use macro_share_permissions::user_item_access::update_user_item_access;-use model::{chat::ChatBasic, response::ErrorResponse, user::UserContext};-use models_permissions::share_permission::access_level::{- AccessLevel, EditAccessLevel, OwnerAccessLevel,-};--#[derive(serde::Deserialize)]-pub struct Params {- pub chat_id: String,-}--#[utoipa::path(- patch,- path = "/chats/{chat_id}",- request_body = PatchChatRequestV2,- params(- ("chat_id" = String, Path, description = "Chat ID")- ),- responses(- (status = 200, description = "Chat patched successfully"),- (status = 400, body = String, description = "Cannot modify deleted chat"),- (status = 401, body = String),- (status = 500, body = String),- )-)]-#[tracing::instrument(skip(user_context, state), fields(user_id=?user_context.user_id))]-pub async fn patch_chat_handler(- ChatAccessLevelExtractor { access_level, .. }: ChatAccessLevelExtractor<OwnerAccessLevel>,- State(state): State<ApiContext>,- user_context: Extension<UserContext>,- chat_context: Extension<ChatBasic>,- Path(Params { chat_id }): Path<Params>,- project: ProjectBodyAccessLevelExtractor<EditAccessLevel, PatchChatRequestV2>,-) -> Result<Response, Response> {- let req = project.into_inner();- if chat_context.deleted_at.is_some() {- return Err((- StatusCode::BAD_REQUEST,- Json(ErrorResponse {- message: "cannot modify deleted chat",- }),- )- .into_response());- }-- patch_chat_v2(- &state,- user_context,- chat_context,- access_level,- chat_id,- req,- )- .await- .map_err(|_| {- (- StatusCode::INTERNAL_SERVER_ERROR,- Json(ErrorResponse {- message: "unable to patch chat",- }),- )- .into_response()- })?;-- Ok((StatusCode::OK).into_response())-}--#[tracing::instrument(skip(ctx, user_context, chat_context, req), fields(user_id = %user_context.user_id, chat_id = %chat_id))]-async fn patch_chat_v2(- ctx: &ApiContext,- user_context: Extension<UserContext>,- chat_context: Extension<ChatBasic>,- users_access_level: AccessLevel,- chat_id: String,- req: PatchChatRequestV2,-) -> Result<(), (StatusCode, String)> {- if req.project_id.is_some() && users_access_level != AccessLevel::Owner {- return Err((- StatusCode::UNAUTHORIZED,- "you do not have valid permissions to move this item".to_string(),- ));- }-- if req.share_permission.is_some() && users_access_level != AccessLevel::Owner {- return Err((- StatusCode::UNAUTHORIZED,- "you do not have valid permission to modify share permissions".to_string(),- ));- }-- let share_permission: Option<- models_permissions::share_permission::UpdateSharePermissionRequestV2,- > = req.share_permission;-- patch_chat_transaction(- ctx,- &user_context,- &chat_id,- req.name.as_deref(),- req.model.as_deref(),- req.project_id.as_deref(),- share_permission.as_ref(),- )- .await- .map_err(|_e| {- (- StatusCode::INTERNAL_SERVER_ERROR,- "unable to patch chat".to_string(),- )- })?;-- macro_project_utils::update_project_modified(- &ctx.db,- macro_project_utils::ProjectModifiedArgs {- project_id: req.project_id.clone(),- old_project_id: chat_context.project_id.clone(),- user_id: user_context.user_id.clone(),- },- )- .await;-- Ok(())-}--#[tracing::instrument(err, skip(ctx, user_context, share_permission), fields(user_id = %user_context.user_id))]-async fn patch_chat_transaction(- ctx: &ApiContext,- user_context: &UserContext,- chat_id: &str,- name: Option<&str>,- model: Option<&str>,- project_id: Option<&str>,- share_permission: Option<&models_permissions::share_permission::UpdateSharePermissionRequestV2>,-) -> anyhow::Result<()> {- let mut transaction = ctx- .db- .begin()- .await- .context("failed to begin transaction")?;-- // Update chat metadata- macro_db_client::chat::patch::patch_chat(- &mut transaction,- chat_id,- name,- model,- None,- share_permission,- project_id,- )- .await- .context("failed to patch chat")?;-- // Update user access if share permissions are provided- if let Some(share_permission) = share_permission {- update_user_item_access(- &mut transaction,- &user_context.user_id,- chat_id,- "chat",- share_permission,- )- .await- .context("failed to update user item access")?;- }-- transaction- .commit()- .await- .context("failed to commit transaction")?;-- Ok(())-}diff --git a/rust/cloud-storage/document_cognition_service/src/api/chats/revert_delete_chat.rs b/rust/cloud-storage/document_cognition_service/src/api/chats/revert_delete_chat.rsdeleted file mode 100644index 0d5cd9835e..0000000000--- a/rust/cloud-storage/document_cognition_service/src/api/chats/revert_delete_chat.rs+++ /dev/null@@ -1,65 +0,0 @@-use axum::extract::State;-use axum::{Extension, extract::Path, http::StatusCode, response::IntoResponse};-#[allow(unused_imports)]-use futures::stream::TryStreamExt;-use macro_middleware::cloud_storage::ensure_access::chat::ChatAccessLevelExtractor;-use model::chat::ChatBasic;-use model::response::{- GenericErrorResponse, GenericResponse, GenericSuccessResponse, SuccessResponse,-};-use model::user::UserContext;-use models_permissions::share_permission::access_level::OwnerAccessLevel;-use serde::Deserialize;-use sqlx::PgPool;--#[derive(Deserialize)]-pub struct Params {- pub chat_id: String,-}--/// Deletes a specific document-#[utoipa::path(- tag = "chat",- put,- operation_id = "revert_delete_chat",- path = "/chats/{chat_id}/revert_delete",- params(- ("chat_id" = String, Path, description = "Chat ID")- ),- responses(- (status = 200, body=SuccessResponse),- (status = 401, body=GenericErrorResponse),- (status = 404, body=GenericErrorResponse),- (status = 500, body=GenericErrorResponse),- )- )]-#[tracing::instrument(skip(db, user_context, chat_context, _access), fields(user_id=?user_context.user_id))]-pub async fn handler(- _access: ChatAccessLevelExtractor<OwnerAccessLevel>,- State(db): State<PgPool>,- user_context: Extension<UserContext>,- chat_context: Extension<ChatBasic>,- Path(Params { chat_id }): Path<Params>,-) -> impl IntoResponse {- tracing::trace!("revert_delete document");-- if let Err(e) = macro_db_client::chat::revert_delete::revert_delete_chat(- &db,- &chat_id,- chat_context.project_id.as_deref(),- )- .await- {- tracing::error!(error = %e, chat_id = %chat_id, project_id = ?chat_context.project_id, "Failed to revert chat deletion");- return GenericResponse::builder()- .message("unable to revert chat")- .is_error(true)- .send(StatusCode::INTERNAL_SERVER_ERROR);- }-- let response_data = GenericSuccessResponse { success: true };-- GenericResponse::builder()- .data(&response_data)- .send(StatusCode::OK)-}diff --git a/rust/cloud-storage/document_cognition_service/src/api/swagger.rs b/rust/cloud-storage/document_cognition_service/src/api/swagger.rsindex c4a48f95f3..7878e63f27 100644--- a/rust/cloud-storage/document_cognition_service/src/api/swagger.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/swagger.rs@@ -1,42 +1,34 @@-use crate::{- api::{- attachments::get_chats_for_attachment,- chats::{- chat_history, chat_history_batch_messages, copy_chat, create_user_chat, delete_chat,- get_chat, get_chat_permissions, patch_chat, revert_delete_chat,- },- citations, health,- models::get_models,- preview::get_batch_preview,- stream::chat_message::{- self, ChatMessageError, HttpSendChatMessageRequest, SendChatMessageResponse,- },+use crate::api::{+ attachments::get_chats_for_attachment,+ chats::{chat_history, chat_history_batch_messages},+ citations, health,+ models::get_models,+ preview::get_batch_preview,+ stream::chat_message::{+ self, ChatMessageError, HttpSendChatMessageRequest, SendChatMessageResponse,},- model::{- request::chats::{- CopyChatRequest, CreateChatRequest, GetChatPathParams, NewAttachment, PatchChatRequest,- PatchChatRequestV2,- },- response::{- attachments::GetChatsForAttachmentResponse,- chats::{GetChatPermissionsResponseV2, GetChatResponse, GetModelsResponse},- models::AIModel,- },- stream::{ChatStream, SendChatMessagePayload, StreamError, ToolSet},+};+use crate::model::{+ response::{+ attachments::GetChatsForAttachmentResponse, models::AIModel, models::GetModelsResponse,},+ stream::{ChatStream, SendChatMessagePayload, StreamError, ToolSet},};use crate::api::preview::get_batch_preview::{GetBatchPreviewRequest, GetBatchPreviewResponse};use ai::types::{ModelMetadata, Provider};-use crate::model::chats::ChatResponse;+use chat::domain::models::{ChatResponse, GetChatResponse, WebCitation};+use chat::inbound::{+ self as chat_inbound, CreateChatRequest, GetChatPermissionsResponse, PatchChatRequest,+};use model::{chat::{AttachmentMetadata, AttachmentType, Chat, ChatAttachment, ChatAttachmentWithName,ChatHistory, ChatMessage, ChatMessageWithAttachments, ConversationRecord,- MessageWithAttachments, NewChatMessage, NewMessageAttachment,+ MessageWithAttachments, NewAttachment, NewChatMessage, NewMessageAttachment,},response::{GenericErrorResponse, StringIDResponse},version::DocumentCognitionServiceApiVersion,@@ -58,21 +50,21 @@ use utoipa::OpenApi;),paths(health::health_handler,- get_chat::get_chat_handler,- create_user_chat::create_chat_handler,- copy_chat::copy_chat_handler,- get_chat_permissions::get_chat_permissions_handler_v2,- delete_chat::delete_chat_handler,- delete_chat::permanently_delete_chat_handler,+ chat_inbound::get_chat_handler,+ chat_inbound::create_chat_handler,+ chat_inbound::copy_chat_handler,+ chat_inbound::get_chat_permissions_handler,+ chat_inbound::delete_chat_handler,+ chat_inbound::permanently_delete_chat_handler,+ chat_inbound::patch_chat_handler,+ chat_inbound::revert_delete_handler,get_models::get_models_handler,get_chats_for_attachment::get_chats_for_attachment_handler,citations::get_citation_handler,get_batch_preview::handler,- revert_delete_chat::handler,chat_history::get_chat_history_handler,chat_history_batch_messages::get_chat_history_batch_messages_handler,- chat_message::send_chat_message,- patch_chat::patch_chat_handler+ chat_message::send_chat_message),components(schemas(@@ -102,6 +94,7 @@ use utoipa::OpenApi;ChatResponse,NewChatMessage,NewMessageAttachment,+ WebCitation,// Chat HistoryChatHistoryBatchMessagesRequest,@@ -111,13 +104,10 @@ use utoipa::OpenApi;// Chat RequestCreateChatRequest,- GetChatPathParams,PatchChatRequest,- PatchChatRequestV2,AttachmentMetadata,- CopyChatRequest,// Chat Response- GetChatPermissionsResponseV2,+ GetChatPermissionsResponse,GetChatResponse,// Share Permissiondiff --git a/rust/cloud-storage/document_cognition_service/src/core/constants.rs b/rust/cloud-storage/document_cognition_service/src/core/constants.rsindex 90e0fe9b9d..b846be74e2 100644--- a/rust/cloud-storage/document_cognition_service/src/core/constants.rs+++ b/rust/cloud-storage/document_cognition_service/src/core/constants.rs@@ -5,16 +5,6 @@ pub const DEFAULT_MAX_TOKENS: u32 = 16000;/// Default batch size for querying documents from rdspub const DEFAULT_DOCUMENT_BATCH_LIMIT: i64 = 1000;-/// max token size openai image-pub const DEFAULT_IMAGE_TOKENS: i64 = 1105;--// these are computer virust-// we're estimating tokens of attachments for some reason but the estimates are not used-// todo: remove estimates-pub const DEFAULT_CHANNEL_TOKENS: i64 = 5000;-pub const DEFAULT_EMAIL_TOKENS: i64 = 3000;-pub const DEFAULT_PROJECT_TOKENS: 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)diff --git a/rust/cloud-storage/document_cognition_service/src/model/mod.rs b/rust/cloud-storage/document_cognition_service/src/model/mod.rsindex f15f451161..61d3da9ee2 100644--- a/rust/cloud-storage/document_cognition_service/src/model/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/model/mod.rs@@ -1,4 +1,3 @@pub mod chats;-pub mod request;pub mod response;pub mod stream;diff --git a/rust/cloud-storage/document_cognition_service/src/model/request/chats.rs b/rust/cloud-storage/document_cognition_service/src/model/request/chats.rsdeleted file mode 100644index e19710a9f5..0000000000--- a/rust/cloud-storage/document_cognition_service/src/model/request/chats.rs+++ /dev/null@@ -1,43 +0,0 @@-use ai::types::Model;-pub use model::chat::NewAttachment;-use serde::{Deserialize, Serialize};-use utoipa::ToSchema;--#[derive(Serialize, Deserialize, Debug, ToSchema)]-#[serde(rename_all = "camelCase")]-pub struct CreateChatRequest {- pub name: Option<String>,- pub model: Option<Model>,- pub project_id: Option<String>,- pub attachments: Option<Vec<NewAttachment>>,- pub is_persistent: Option<bool>,-}--#[derive(Serialize, Deserialize, Debug, ToSchema)]-#[serde(rename_all = "camelCase")]-pub struct CopyChatRequest {- pub name: String,-}--#[derive(Serialize, Deserialize, Debug, ToSchema)]-pub struct GetChatPathParams {- pub chat_id: String,-}--#[derive(Serialize, Deserialize, Debug, ToSchema)]-#[serde(rename_all = "camelCase")]-pub struct PatchChatRequest {- pub name: Option<String>,- pub model: Option<String>,- pub project_id: Option<String>,-}--#[derive(Serialize, Deserialize, Debug, ToSchema)]-#[serde(rename_all = "camelCase")]-pub struct PatchChatRequestV2 {- pub name: Option<String>,- pub model: Option<String>,- pub project_id: Option<String>,- pub share_permission:- Option<models_permissions::share_permission::UpdateSharePermissionRequestV2>,-}diff --git a/rust/cloud-storage/document_cognition_service/src/model/request/mod.rs b/rust/cloud-storage/document_cognition_service/src/model/request/mod.rsdeleted file mode 100644index cf49dac7aa..0000000000--- a/rust/cloud-storage/document_cognition_service/src/model/request/mod.rs+++ /dev/null@@ -1 +0,0 @@-pub mod chats;diff --git a/rust/cloud-storage/document_cognition_service/src/model/response/chats.rs b/rust/cloud-storage/document_cognition_service/src/model/response/chats.rsdeleted file mode 100644index 2281c2fac9..0000000000--- a/rust/cloud-storage/document_cognition_service/src/model/response/chats.rs+++ /dev/null@@ -1,25 +0,0 @@-use crate::model::chats::ChatResponse;-use ai::types::Model;-use serde::{Deserialize, Serialize};-use utoipa::ToSchema;--use models_permissions::share_permission::access_level::AccessLevel;--#[derive(serde::Serialize, serde::Deserialize, Debug, ToSchema)]-#[serde(rename_all = "camelCase")]-pub struct GetChatPermissionsResponseV2 {- pub permissions: models_permissions::share_permission::SharePermissionV2,-}--#[derive(Serialize, Deserialize, Debug, ToSchema)]-#[serde(rename_all = "camelCase")]-pub struct GetChatResponse {- pub chat: ChatResponse,- pub user_access_level: AccessLevel,-}--#[derive(Serialize, Deserialize, Debug, ToSchema)]-#[serde(rename_all = "camelCase")]-pub struct GetModelsResponse {- pub models: Vec<Model>,-}diff --git a/rust/cloud-storage/document_cognition_service/src/model/response/mod.rs b/rust/cloud-storage/document_cognition_service/src/model/response/mod.rsindex e99f3d0875..136534e98c 100644--- a/rust/cloud-storage/document_cognition_service/src/model/response/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/model/response/mod.rs@@ -1,3 +1,2 @@pub mod attachments;-pub mod chats;pub mod models;diff --git a/rust/cloud-storage/document_cognition_service/src/service/attachment/document/mod.rs b/rust/cloud-storage/document_cognition_service/src/service/attachment/document/mod.rsdeleted file mode 100644index 488f9c6c30..0000000000--- a/rust/cloud-storage/document_cognition_service/src/service/attachment/document/mod.rs+++ /dev/null@@ -1,3 +0,0 @@-mod token_count;--pub use token_count::*;diff --git a/rust/cloud-storage/document_cognition_service/src/service/attachment/document/token_count.rs b/rust/cloud-storage/document_cognition_service/src/service/attachment/document/token_count.rsdeleted file mode 100644index b192083ddc..0000000000--- a/rust/cloud-storage/document_cognition_service/src/service/attachment/document/token_count.rs+++ /dev/null@@ -1,40 +0,0 @@-use crate::api::context::ApiContext;-use ai::tokens::count_tokens;-use anyhow::{Context, Error};-use macro_db_client::dcs::get_document_text::get_pdf_docx_token_count;-use model::document::FileType;--#[tracing::instrument(err, skip(ctx))]-pub async fn get_document_token_count(ctx: &ApiContext, document_id: &str) -> Result<i64, Error> {- let document_basic = ctx- .document_storage_client- .get_document_basic(document_id)- .await- .context("Failed to fetch document basic info")?- .ok_or_else(|| anyhow::anyhow!("document not found"))?;-- let file_type = document_basic- .try_file_type()- .ok_or_else(|| anyhow::anyhow!("file type not found"))?;-- if file_type == FileType::Pdf || file_type == FileType::Docx {- return get_pdf_docx_token_count(&ctx.db, document_id)- .await- .context("Failed to get PDF/DOCX token count");- }-- let document_text = ctx- .scribe- .document- .fetch(document_id)- .document_content()- .await- .context("Failed to fetch document content")?- .content- .text_content()- .context("Failed to extract text content")?;-- let count = count_tokens(&document_text).context("Failed to count tokens")?;-- Ok(count)-}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.rsindex 9c3c4a50f2..0e40308b0a 100644--- a/rust/cloud-storage/document_cognition_service/src/service/attachment/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/service/attachment/mod.rs@@ -1,2 +1 @@-pub mod document;pub mod fetch;diff --git a/rust/cloud-storage/justfile b/rust/cloud-storage/justfileindex ced148a20d..31cc921df8 100644--- a/rust/cloud-storage/justfile+++ b/rust/cloud-storage/justfile@@ -86,6 +86,7 @@ setup_test_envs:echo "DATABASE_URL={{ MACRODB }}" >> ./entity_access/.envecho "DATABASE_URL={{ MACRODB }}" >> ./github/.envecho "DATABASE_URL={{ MACRODB }}" >> ./referral/.env+ echo "DATABASE_URL={{ MACRODB }}" >> ./chat/.envsetup_macrodb:just macro_db_client/create_dbdiff --git a/rust/cloud-storage/models_permissions/src/share_permission/mod.rs b/rust/cloud-storage/models_permissions/src/share_permission/mod.rsindex f5c18cae60..6d696e2cd1 100644--- a/rust/cloud-storage/models_permissions/src/share_permission/mod.rs+++ b/rust/cloud-storage/models_permissions/src/share_permission/mod.rs@@ -48,7 +48,7 @@ impl SharePermissionV2 {/// Creates a new share permission object for an ai chatpub fn new_chat_share_permission() -> Self {- Self::new(false, None)+ Self::new(true, Some(AccessLevel::View))}/// Creates a new share permission object for a project