Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(ai): stream with connection_gateway (#1512)
Eric Hayes229ced25da0f
diff --git a/infra/stacks/document-cognition-service/index.ts b/infra/stacks/document-cognition-service/index.tsindex b3b955ce42..5df3785433 100644--- a/infra/stacks/document-cognition-service/index.ts+++ b/infra/stacks/document-cognition-service/index.ts@@ -100,6 +100,17 @@ const authenticationServiceInternalApiKeyArn: pulumi.Output<string> =export const coparse_api_vpc = get_coparse_api_vpc();+const connectionGatewayStack = new pulumi.StackReference(+ 'connection-gateway-stack',+ {+ name: `macro-inc/connection-gateway/${stack}`,+ }+);++const connectionGatewayRedisUrl: pulumi.Output<string> = connectionGatewayStack+ .getOutput('connectionGatewayRedisUrl')+ .apply((url) => url as string);+const cloudStorageStack = new pulumi.StackReference('cloud-storage-stack', {name: `macro-inc/document-storage/${stack}`,});@@ -312,6 +323,10 @@ const documentCognitionService = new DocumentCognitionService(name: 'AUTHENTICATION_SERVICE_SECRET_KEY',value: AUTHENTICATION_SERVICE_INTERNAL_API_KEY_SECRET_NAME,},+ {+ name: 'REDIS_URL',+ value: pulumi.interpolate`redis://${connectionGatewayRedisUrl}`,+ },// OpenTelemetry / Datadog tracing configuration{name: 'DD_SERVICE',diff --git a/js/app/packages/app/component/SoupChatInput.tsx b/js/app/packages/app/component/SoupChatInput.tsxindex b6a312c1fe..234d71bcfa 100644--- a/js/app/packages/app/component/SoupChatInput.tsx+++ b/js/app/packages/app/component/SoupChatInput.tsx@@ -2,16 +2,16 @@ import {ChatInputProvider,useChatInputContext,} from '@core/component/AI/context';-import { ChatInput } from '@core/component/AI/component/input/useChatInput';+import type { ChatSendInput } from '@core/component/AI/component/input/buildRequest';import { useChatMarkdownArea } from '@core/component/AI/component/input/useChatMarkdownArea';import { setPendingSendData } from '@core/component/AI/signal/pendingSend';-import type { CreateAndSend, Send } from '@core/component/AI/types';import { isErr } from '@core/util/maybeResult';import { cognitionApiServiceClient } from '@service-cognition/client';+import { ChatInput } from 'core/component/AI/component/input/ChatInput';import { useHotkeyDOMScope } from 'core/hotkey/hotkeys';import { onMount, Show } from 'solid-js';-import { useSplitPanelOrThrow } from './split-layout/layoutUtils';import { useSoup } from '@app/component/next-soup/soup-context';+import { useSplitPanelOrThrow } from './split-layout/layoutUtils';function SoupChatInputInner() {let containerRef!: HTMLDivElement;@@ -29,9 +29,7 @@ function SoupChatInputInner() {attachHotkeys(containerRef);});- const handleSend = async (request: Send | CreateAndSend) => {- if (request.type !== 'createAndSend') return;-+ const handleSend = async (request: ChatSendInput) => {// Create a new persistent chatconst response = await cognitionApiServiceClient.createChat({isPersistent: true,diff --git a/js/app/packages/app/component/rightbar/Rightbar.tsx b/js/app/packages/app/component/rightbar/Rightbar.tsxindex 5b2377e851..58a607baf9 100644--- a/js/app/packages/app/component/rightbar/Rightbar.tsx+++ b/js/app/packages/app/component/rightbar/Rightbar.tsx@@ -2,8 +2,8 @@ import { globalSplitManager } from '@app/signal/splitLayout';import { useIsAuthenticated } from '@core/auth';import { AiChatEmptyState } from '@core/component/AI/component/AIChatEmptyState';import { DragDropWrapper } from '@core/component/AI/component/DragDrop';-import { useBuildChatSendRequest } from '@core/component/AI/component/input/buildRequest';-import { ChatInput } from '@core/component/AI/component/input/useChatInput';+import type { ChatSendInput } from '@core/component/AI/component/input/buildRequest';+import { useSendChatMessage } from '@core/component/AI/component/input/buildRequest';import { useChatMarkdownArea } from '@core/component/AI/component/input/useChatMarkdownArea';import { ChatMessages } from '@core/component/AI/component/message/ChatMessages';import {@@ -17,11 +17,9 @@ import { getPendingSend } from '@core/component/AI/signal/pendingSend';import { registerToolHandler } from '@core/component/AI/signal/tool';import type {Attachment,+ ChatMessageStream,ChatMessageWithAttachments,- CreateAndSend,- MessageStream,Model,- Send,} from '@core/component/AI/types';import { parseModel } from '@core/component/AI/util';import {@@ -30,12 +28,13 @@ import {} from '@core/component/AI/util/storage';import { CustomScrollbar } from '@core/component/CustomScrollbar';import { DeprecatedIconButton } from '@core/component/DeprecatedIconButton';+import { Hotkey } from '@core/component/Hotkey';import { DropdownMenuContent, MenuItem } from '@core/component/Menu';import { ReferencesModal } from '@core/component/ReferencesModal';-import { ShareButton } from '@core/component/TopBar/ShareButton';-import { getPermissions } from '@core/component/SharePermissions';-import type { Permissions } from '@core/component/SharePermissions';import { Resize } from '@core/component/Resize';+import type { Permissions } from '@core/component/SharePermissions';+import { getPermissions } from '@core/component/SharePermissions';+import { ShareButton } from '@core/component/TopBar/ShareButton';import { ENABLE_REFERENCES_MODAL } from '@core/constant/featureFlags';import { usePaywallState } from '@core/constant/PaywallState';import { settingsOpen } from '@core/constant/SettingsState';@@ -57,11 +56,14 @@ import PlusIcon from '@icon/regular/plus.svg';import XIcon from '@icon/regular/x.svg';import { DropdownMenu } from '@kobalte/core/dropdown-menu';import { invalidateUserQuota } from '@queries/auth';-import {- cognitionApiServiceClient,- cognitionWebsocketServiceClient,-} from '@service-cognition/client';import { refetchHistory, useHistoryQuery } from '@queries/history/history';+import { cognitionApiServiceClient } from '@service-cognition/client';+import { AccessLevel } from '@service-cognition/generated/schemas/accessLevel';+import { connectionGatewayClient } from '@service-connection/client';+import { state as connectionState } from '@service-connection/websocket';+import { Button } from '@ui/components/Button';+import { WebsocketConnectionState } from '@websocket';+import { ChatInput } from 'core/component/AI/component/input/ChatInput';import { useOpenInstructionsMd } from 'core/component/AI/util/instructions';import type { LexicalEditor } from 'lexical';import {@@ -78,11 +80,8 @@ import {Suspense,untrack,} from 'solid-js';-import { SplitlikeContainer } from '../split-layout/components/SplitContainer';-import { Button } from '@ui/components/Button';-import { Hotkey } from '@core/component/Hotkey';-import { AccessLevel } from '@service-cognition/generated/schemas/accessLevel';import { useWaitChatRename } from '@macro-entity';+import { SplitlikeContainer } from '../split-layout/components/SplitContainer';type ChatData = {messages: ChatMessageWithAttachments[];@@ -306,7 +305,11 @@ function RightbarChatArea(props: { isBig?: boolean }) {}});- registerToolHandler(chat.stream);+ registerToolHandler(() => {+ const s = chat.stream();+ if (!s) return undefined;+ return { data: s.data };+ });return (<>@@ -335,8 +338,7 @@ function RightbarChatArea(props: { isBig?: boolean }) {export function Rightbar(props: {chatId: string | undefined;- onSend: (args: CreateAndSend | Send) => void;- stopGenerating: () => void;+ onSend: (args: ChatSendInput) => void;chatName: string | undefined;isBig?: boolean;userPermissions: Accessor<Permissions>;@@ -461,7 +463,6 @@ export function Rightbar(props: {isPersistentshowActiveTabsonSend={props.onSend}- onStop={props.stopGenerating}captureEditor={setEditor}/></div>@@ -488,7 +489,8 @@ export const RightbarWrapper = (_props: { isBigChat?: boolean }) => {>();const [model, setModel] = createSignal<Model | undefined>();const [attachments, setAttachments] = createSignal<Attachment[]>([]);- const [stream, setStream] = createSignal<MessageStream>();+ const [stream, setStream] = createSignal<ChatMessageStream>();+ const [waitingForStream, setWaitingForStream] = createSignal(false);const [initialChatState, setInitialChatState] = createSignal<| {model: Model | undefined;@@ -546,49 +548,46 @@ export const RightbarWrapper = (_props: { isBigChat?: boolean }) => {});const { showPaywall } = usePaywallState();+ const sendChatMessage = useSendChatMessage();++ const onSend = async (request: ChatSendInput) => {+ setMessages((p) => [+ ...p,+ {+ id: crypto.randomUUID(),+ content: request.content,+ role: 'user' as const,+ attachments: request.attachments ?? [],+ },+ ]);+ setWaitingForStream(true);- const onSend = async (request: Send | CreateAndSend) => {- if (request.type === 'createAndSend') {- const response = await request.call();- if (response.type === 'error') {- // TODO: show error state- console.error('error creating chat', response);- if (response.paymentError) {- showPaywall();- }- return;+ const result = await sendChatMessage({+ ...request,+ chatId: chatId(),+ });++ setWaitingForStream(false);++ if ('error' in result) {+ if (result.paymentError) {+ showPaywall();}- const newChatId = response.chat_id;- setNewChatId(newChatId);- setChatId(newChatId);- setUserAccessLevel(AccessLevel.owner);+ return;+ }+ // If no chatId existed, a new chat was created+ if (!chatId()) {+ setNewChatId(result.chat_id);+ setChatId(result.chat_id);+ setUserAccessLevel(AccessLevel.owner);refetchHistory();- useWaitChatRename(newChatId);- return await onSend(response);- } else if (request.type === 'send') {- setMessages((p) => {- return [- ...p,- {- attachments: request.request.attachments ?? [],- content: request.request.content,- role: 'user',- // TODO: no id because it's a user message that hasn't been uploaded yet- id: '',- },- ];- });-- const stream = request.call();- setStream(stream);- invalidateUserQuota();- } else {- console.error('Invalid send request', request);+ useWaitChatRename(result.chat_id);}- };- const buildChatSendRequest = useBuildChatSendRequest();+ setStream(result.stream);+ invalidateUserQuota();+ };// Check for pending sends from SoupChatInput when bigchat openscreateEffect(@@ -596,15 +595,12 @@ export const RightbarWrapper = (_props: { isBigChat?: boolean }) => {if (isOpen && !wasOpen) {const pending = getPendingSend();if (pending) {- // Build and send the request- const request = await buildChatSendRequest({- chatId: chatId(),- userRequest: pending.content,- attachments: pending.attachments,- model: pending.model,- isPersistent: true,+ onSend({+ content: pending.content,+ model: pending.model ?? model() ?? 'claude-haiku-4-5-20251001',+ attachments: pending.attachments ?? [],+ toolset: { type: 'all' },});- onSend(request);}}})@@ -653,6 +649,28 @@ export const RightbarWrapper = (_props: { isBigChat?: boolean }) => {}));+ // Track/untrack chat entity with connection gateway for stream delivery+ createEffect(() => {+ const id = chatId();+ const connected = connectionState() === WebsocketConnectionState.Open;+ if (id && connected) {+ connectionGatewayClient.trackEntity({+ entity_type: 'chat',+ entity_id: id,+ action: 'open',+ });+ }+ onCleanup(() => {+ if (id) {+ connectionGatewayClient.trackEntity({+ entity_type: 'chat',+ entity_id: id,+ action: 'close',+ });+ }+ });+ });+const toggleRightPanel = useToggleRightPanel();registerHotkey({@@ -679,27 +697,19 @@ export const RightbarWrapper = (_props: { isBigChat?: boolean }) => {description: 'Create a new chat',runWithInputFocused: true,keyDownHandler: () => {- console.log('create new chat');setChatId(undefined);return true;},});- const stopGenerating = () => {- const stream_ = stream();- if (!stream_) return false;- cognitionWebsocketServiceClient.stopChatMessage({- stream_id: stream_.request.stream_id,- });- stream_.close();- return true;- };-registerHotkey({scopeId,hotkey: 'ctrl+c',description: 'Stop stream',- keyDownHandler: stopGenerating,+ keyDownHandler: () => {+ // TODO: implement stop for connection gateway streams+ return true;+ },runWithInputFocused: true,});return (@@ -733,7 +743,6 @@ export const RightbarWrapper = (_props: { isBigChat?: boolean }) => {onUnmount={getChatInputState}initialState={initialChatState()}onSend={onSend}- stopGenerating={stopGenerating}userPermissions={userPermissions}setState={{setChatId,@@ -757,6 +766,10 @@ export const RightbarWrapper = (_props: { isBigChat?: boolean }) => {external={{messages: [messages, setMessages],stream: [stream, setStream],+ waitingForStream: [+ waitingForStream,+ setWaitingForStream,+ ],}}><RightbarChatArea isBig={bigChatOpen()} />diff --git a/js/app/packages/app/component/split-layout/componentRegistry.tsx b/js/app/packages/app/component/split-layout/componentRegistry.tsxindex ac3d91b463..6831c232cf 100644--- a/js/app/packages/app/component/split-layout/componentRegistry.tsx+++ b/js/app/packages/app/component/split-layout/componentRegistry.tsx@@ -104,6 +104,10 @@ if (LOCAL_ONLY) {'chat-tool',lazy(() => import('@core/component/AI/component/debug/Tool')));+ registerComponent(+ 'http-stream',+ lazy(() => import('@core/component/AI/component/debug/HttpStream'))+ );registerComponent('new-form-primitives',lazy(diff --git a/js/app/packages/block-chat/blockClient.ts b/js/app/packages/block-chat/blockClient.tsindex 68305bd263..23af14612a 100644--- a/js/app/packages/block-chat/blockClient.ts+++ b/js/app/packages/block-chat/blockClient.ts@@ -1,9 +1,12 @@-import type { useBuildChatSendRequest } from '@core/component/AI/component/input/buildRequest';+import type { Attachment, Model, ToolSet } from '@core/component/AI/types';-export type SendBuilder = Parameters<- ReturnType<typeof useBuildChatSendRequest>->[0] & {- chatId: string;+export type SendBuilder = {+ userRequest: string;+ chatId?: string;+ isPersistent?: boolean;+ model?: Model;+ attachments?: Attachment[];+ toolset?: ToolSet;};export type BlockChatSpec = {diff --git a/js/app/packages/block-chat/component/Chat.tsx b/js/app/packages/block-chat/component/Chat.tsxindex 4ae9e87771..f849919d64 100644--- a/js/app/packages/block-chat/component/Chat.tsx+++ b/js/app/packages/block-chat/component/Chat.tsx@@ -2,9 +2,10 @@ import { useNavigatedFromJK } from '@app/component/useNavigatedFromJK';import type { SendBuilder } from '@block-chat/blockClient';import { TopBar } from '@block-chat/component/TopBar';import type { ChatData } from '@block-chat/definition';+import { useBlockId } from '@core/block';import { DragDropWrapper } from '@core/component/AI/component/DragDrop';-import { useBuildChatSendRequest } from '@core/component/AI/component/input/buildRequest';-import { ChatInput } from '@core/component/AI/component/input/useChatInput';+import type { ChatSendInput } from '@core/component/AI/component/input/buildRequest';+import { useSendChatMessage } from '@core/component/AI/component/input/buildRequest';import { useChatMarkdownArea } from '@core/component/AI/component/input/useChatMarkdownArea';import { ChatMessages } from '@core/component/AI/component/message/ChatMessages';import {@@ -16,17 +17,11 @@ import {import { useEntityDropAttachment } from '@core/component/AI/hook/useEntityDropAttachment';import { getPendingSend } from '@core/component/AI/signal/pendingSend';import { registerToolHandler } from '@core/component/AI/signal/tool';-import type {- CreateAndSend,- MessageStream,- Send,-} from '@core/component/AI/types';import {getChatInputStoredState,type StoredStuff,storeChatState,} from '@core/component/AI/util/storage';-import { useBlockId } from '@core/block';import { CustomScrollbar } from '@core/component/CustomScrollbar';import { usePaywallState } from '@core/constant/PaywallState';import { TOKENS } from '@core/hotkey/tokens';@@ -39,8 +34,8 @@ import {import { blockHandleSignal } from '@core/signal/load';import { useCanEdit } from '@core/signal/permissions';import { invalidateUserQuota } from '@queries/auth';-import { cognitionWebsocketServiceClient } from '@service-cognition/client';import { createCallback } from '@solid-primitives/rootless';+import { ChatInput } from 'core/component/AI/component/input/ChatInput';import type { LexicalEditor } from 'lexical';import { createEffect, createSignal, Show } from 'solid-js';import { pendingLocationParamsSignal } from '../signal/pendingLocationParams';@@ -82,17 +77,17 @@ function ChatInner(props: {addAttachment: (a) => input.attachments.addAttachment(a),});- // Local stream signal for cancelStream and registerToolHandler- const [stream, setStream] = createSignal<MessageStream>();- const cancelStream = () => {- const s = stream();- if (s) {- cognitionWebsocketServiceClient.stopChatMessage({- stream_id: s.request.stream_id,- });- s.close();+ // Local stream signal for registerToolHandler++ createEffect(() => {+ const chatStream = chat.stream();+ if (!chatStream || chatStream.isDone()) {+ input.setIsGenerating(false);+ return;}- };+ input.setIsGenerating(true);+ if (chatStream.data().length > 0) invalidateUserQuota();+ });const blockHandle = blockHandleSignal.get;@@ -104,42 +99,39 @@ function ChatInner(props: {);false && droppable;- registerToolHandler(stream);+ registerToolHandler(() => {+ const s = chat.stream();+ if (!s) return undefined;+ return { data: s.data };+ });const { showPaywall } = usePaywallState();- const onSend = createCallback(async (request: Send | CreateAndSend) => {- if (request.type === 'createAndSend') {- const response = await request.call();- if ('type' in response && response.type === 'error') {- if (response.paymentError) showPaywall();- return;- } else {- return onSend(response);- }- } else {- chat.addMessage({- attachments: request.request.attachments ?? [],- content: request.request.content,- role: 'user',- id: '',- });- const stream = request.call();- chat.setStream(stream);- setStream(stream);- input.setIsGenerating(true);- invalidateUserQuota();- createEffect(() => {- if (stream.data().length > 0) {- invalidateUserQuota();- }- });- createEffect(() => {- if (stream.isDone()) {- input.setIsGenerating(false);- invalidateUserQuota();- }- });+ const sendChatMessage = useSendChatMessage();++ const onSend = createCallback(async (request: ChatSendInput) => {+ chat.addMessage({+ id: crypto.randomUUID(),+ content: request.content,+ role: 'user',+ attachments: request.attachments ?? [],+ });+ chat.setWaitingForStream(true);++ const result = await sendChatMessage({+ ...request,+ chatId: chat.chatId(),+ });++ chat.setWaitingForStream(false);++ if ('error' in result) {+ if (result.paymentError) showPaywall();+ return;}++ chat.setStream(result.stream);+ input.setIsGenerating(true);+ invalidateUserQuota();});const saveChatState = (state: StoredStuff) => {@@ -154,12 +146,15 @@ function ChatInner(props: {});const setPendingLocation = pendingLocationParamsSignal.set;- const buildChatSendRequest = useBuildChatSendRequest();createMethodRegistration(blockHandle, {sendMessage: async (sendRequest: SendBuilder) => {- const send = await buildChatSendRequest(sendRequest);- onSend(send);+ onSend({+ content: sendRequest.userRequest,+ model: sendRequest.model ?? input.model(),+ attachments: sendRequest.attachments ?? [],+ toolset: { type: 'all' },+ });},goToLocationFromParams: (params: Record<string, string>) => {setPendingLocation(params);@@ -169,13 +164,12 @@ function ChatInner(props: {// Check for pending send data (e.g., from SoupChatInput) and send itconst pendingSend = getPendingSend();if (pendingSend) {- buildChatSendRequest({- chatId: props.data.chat.id,- userRequest: pendingSend.content,- attachments: pendingSend.attachments,- model: pendingSend.model,- isPersistent: true,- }).then((request) => onSend(request));+ onSend({+ content: pendingSend.content,+ model: pendingSend.model ?? input.model(),+ attachments: pendingSend.attachments ?? [],+ toolset: { type: 'all' },+ });}registerScopeSignalHotkey(scopeId, {@@ -232,7 +226,6 @@ function ChatInner(props: {markdown={chatMarkdownArea}chatId={chat.chatId()}onSend={onSend}- onStop={cancelStream}captureEditor={setChatEditor}autoFocusOnMount={!navigatedFromJK()}/>diff --git a/js/app/packages/block-chat/definition.ts b/js/app/packages/block-chat/definition.tsindex 1caa2d42bd..cf3c12d887 100644--- a/js/app/packages/block-chat/definition.ts+++ b/js/app/packages/block-chat/definition.ts@@ -15,6 +15,7 @@ export const definition = defineBlock({description: '',defaultFilename: DEFAULT_CHAT_NAME,component: BlockChat,+ liveTrackingEnabled: true,async load(source, intent) {if (source.type === 'dss') {// Fetch the chat from dcsdiff --git a/js/app/packages/core/component/AI/component/debug/Attachment.tsx b/js/app/packages/core/component/AI/component/debug/Attachment.tsxindex 7690b24009..256d96801c 100644--- a/js/app/packages/core/component/AI/component/debug/Attachment.tsx+++ b/js/app/packages/core/component/AI/component/debug/Attachment.tsx@@ -1,17 +1,12 @@import type {Attachment,- CreateAndSend,- MessageStream,+ ChatMessageStream,Model,- Send,} from '@core/component/AI/types';import { DeprecatedTextButton } from '@core/component/DeprecatedTextButton';import { isErr } from '@core/util/maybeResult';-import { getMacroApiToken } from '@service-auth/fetch';-import {- cognitionApiServiceClient,- cognitionWebsocketServiceClient,-} from '@service-cognition/client';+import { cognitionApiServiceClient } from '@service-cognition/client';+import { subscribe } from '@service-connection/stream';import type { Accessor, JSXElement } from 'solid-js';import { createEffect, createSignal, For, Match, Show, Switch } from 'solid-js';import { Dynamic } from 'solid-js/web';@@ -139,35 +134,30 @@ type SimpleRequest = {model: Model;};-async function request(simple: SimpleRequest): Promise<CreateAndSend> {- const token = await getMacroApiToken();- return {- type: 'createAndSend',- request: {},+type SendResult = { type: 'ok'; stream: ChatMessageStream } | { type: 'error' };++async function sendRequest(simple: SimpleRequest): Promise<SendResult> {+ const response = await cognitionApiServiceClient.sendStreamChatMessage({content: simple.userRequest,- attachments: simple.attachments,model: simple.model,- call: async () => {- const createResponse = await cognitionApiServiceClient.createChat({});- if (isErr(createResponse)) {- return { type: 'error' };- }- const [, { id: chatId }] = createResponse;- const request: Send['request'] = {- chat_id: chatId,- content: simple.userRequest,- model: simple.model,- token: token,- attachments: simple.attachments,- };- const send: Send = {- type: 'send',- chat_id: chatId,- request: request,- call: (): MessageStream =>- cognitionWebsocketServiceClient.sendStreamChatMessage(request),- };- return send;+ attachments: simple.attachments.length > 0 ? simple.attachments : undefined,+ });+ if (isErr(response)) {+ return { type: 'error' };+ }+ const [, { stream_id, chat_id }] = response;+ const connectionStream = subscribe('chat', chat_id, stream_id);+ if (!connectionStream) {+ return { type: 'error' };+ }+ return {+ type: 'ok',+ stream: {+ data: connectionStream.data,+ isDone: connectionStream.isDone,+ model: simple.model,+ attachments: simple.attachments,+ streamId: stream_id,},};}@@ -176,14 +166,10 @@ function useDebugChatRequest(args: { request: SimpleRequest; label: string }): {sendRequest: () => void;Debugger: () => JSXElement;} {- const r = () => {- return request(args.request);- };const [send, setSend] = createSignal(0);const component = () => (<RequestDebuggerlabel={args.label}- request={r}simpleRequest={args.request}go={send}/>@@ -196,26 +182,23 @@ function useDebugChatRequest(args: { request: SimpleRequest; label: string }): {function RequestDebugger(props: {label: string;- request: () => Promise<CreateAndSend>;simpleRequest: SimpleRequest;go: Accessor<number>;}) {const [chatCreated, setCreated] = createSignal(false);- const [stream, setStream] = createSignal<MessageStream>();+ const [stream, setStream] = createSignal<ChatMessageStream>();const makeRequest = async () => {setCreated(false);setStream();- const request = await props.request();- const sendRequest = await request.call();- if ('type' in sendRequest && sendRequest.type === 'error') {+ const result = await sendRequest(props.simpleRequest);+ if (result.type === 'error') {return;}- const stream = sendRequest.call();setCreated(true);- setStream(stream);+ setStream(result.stream);};createEffect(() => {diff --git a/js/app/packages/core/component/AI/component/debug/Component.tsx b/js/app/packages/core/component/AI/component/debug/Component.tsxindex 8a9356259a..9f41e21a0c 100644--- a/js/app/packages/core/component/AI/component/debug/Component.tsx+++ b/js/app/packages/core/component/AI/component/debug/Component.tsx@@ -1,10 +1,11 @@-import type {- CreateAndSend,- MessageStream,- Model,- Send,-} from '@core/component/AI/types';+import { DEFAULT_MODEL } from '@core/component/AI/constant';+import type { ChatSendInput } from '@core/component/AI/component/input/buildRequest';+import type { ChatMessageStream, Model } from '@core/component/AI/types';import { DeprecatedTextButton } from '@core/component/DeprecatedTextButton';+import { isErr } from '@core/util/maybeResult';+import { cognitionApiServiceClient } from '@service-cognition/client';+import type { MessageStream } from '@service-cognition/websocket';+import { subscribe } from '@service-connection/stream';import { createEffect, createSignal } from 'solid-js';import {ChatInputProvider,@@ -14,10 +15,20 @@ import {} from '../../context';import { useAttachments } from '../../signal/attachment';import { pausableStream } from '../../util/stream';-import { ChatInput } from '../input/useChatInput';+import { ChatInput } from '../input/ChatInput';import { ModelSelector } from '../input/ModelSelector';import { useChatMarkdownArea } from '../input/useChatMarkdownArea';import { ChatMessages } from '../message/ChatMessages';++function toChat(stream: MessageStream): ChatMessageStream {+ return {+ data: stream.data,+ isDone: stream.isDone,+ model: DEFAULT_MODEL,+ attachments: [],+ streamId: stream.request.stream_id,+ };+}import {blockDone,createStream,@@ -142,26 +153,31 @@ function ChatInputBoxConnectedInner() {});const [_gen, setGen] = createSignal(false);- const onSend = async (request: Send | CreateAndSend) => {- if (request.type === 'createAndSend') {- const response = await request.call();- if ('type' in response && response.type === 'error') {- console.log('error creating chat', response);- return;- } else {- console.log('created chat ', response.chat_id);- return onSend(response);- }- } else {- const stream = request.call();- setGen(true);- createEffect(() => {- const items = stream.data();- const latest = items.at(-1);- if (latest) console.log(JSON.stringify(latest, null, 2));- if (stream.isDone()) setGen(false);- });+ const onSend = async (input: ChatSendInput) => {+ const response = await cognitionApiServiceClient.sendStreamChatMessage({+ content: input.content,+ model: input.model,+ attachments: input.attachments.length > 0 ? input.attachments : undefined,+ toolset: input.toolset,+ });+ if (isErr(response)) {+ console.log('error sending message', response);+ return;+ }+ const [, { stream_id, chat_id }] = response;+ console.log('created chat', chat_id);+ const connectionStream = subscribe('chat', chat_id, stream_id);+ if (!connectionStream) {+ console.log('no connection stream');+ return;}+ setGen(true);+ createEffect(() => {+ const items = connectionStream.data();+ const latest = items.at(-1);+ if (latest) console.log(JSON.stringify(latest, null, 2));+ if (connectionStream.isDone()) setGen(false);+ });};return (@@ -195,7 +211,7 @@ function StreamMessagesInner() {onClick={() => {const poemStream = makeStream();setStream(poemStream);- chat.setStream(poemStream);+ chat.setStream(toChat(poemStream));}}>Stream@@ -241,43 +257,51 @@ function FullChatInner() {addAttachment: (a) => input.attachments.addAttachment(a),});const [_isGen, setIsGen] = createSignal(false);- const [stream, setDebugStream] = createSignal<MessageStream>();-- const onSend = async (request: Send | CreateAndSend) => {- if (request.type === 'createAndSend') {- const response = await request.call();- if ('type' in response && response.type === 'error') {- console.log('error creating chat', response);- return;- } else {- console.log('created chat ', response.chat_id);- return onSend(response);- }- } else {- chat.addMessage({- attachments: request.request.attachments ?? [],- content: request.request.content,- role: 'user',- id: '',- });- const stream = request.call();- console.log('set stream');- chat.setStream(stream);- setDebugStream(stream);- setIsGen(true);- createEffect(() => {- if (stream.isErr()) {- console.log('stream error');- }- if (stream.isDone()) {- console.log('stream done');- setIsGen(false);- }- });- createEffect(() => {- console.log('stream', JSON.stringify(stream.data(), null, 2));- });+ const [debugStream, _setDebugStream] = createSignal<MessageStream>();++ const onSend = async (input: ChatSendInput) => {+ chat.addMessage({+ attachments: input.attachments,+ content: input.content,+ role: 'user',+ id: '',+ });+ const response = await cognitionApiServiceClient.sendStreamChatMessage({+ content: input.content,+ model: input.model,+ chat_id: chat.chatId(),+ attachments: input.attachments.length > 0 ? input.attachments : undefined,+ toolset: input.toolset,+ });+ if (isErr(response)) {+ console.log('error sending message', response);+ return;+ }+ const [, { stream_id, chat_id }] = response;+ const connectionStream = subscribe('chat', chat_id, stream_id);+ if (!connectionStream) {+ console.log('no connection stream');+ return;}+ const chatStream: ChatMessageStream = {+ data: connectionStream.data,+ isDone: connectionStream.isDone,+ model: input.model,+ attachments: input.attachments,+ streamId: stream_id,+ };+ console.log('set stream');+ chat.setStream(chatStream);+ setIsGen(true);+ createEffect(() => {+ if (connectionStream.isDone()) {+ console.log('stream done');+ setIsGen(false);+ }+ });+ createEffect(() => {+ console.log('stream', JSON.stringify(connectionStream.data(), null, 2));+ });};return (@@ -286,7 +310,7 @@ function FullChatInner() {data-chat-scrollclass="size-full min-h-0 max-h-[400px] overflow-y-auto">- <StreamStatus stream={stream} />+ <StreamStatus stream={debugStream} /><ChatMessages /><ChatInputmarkdown={chatMarkdownArea}@@ -316,7 +340,7 @@ function ToolCallRender() {function ToolCallRenderInner(props: { stream: MessageStream }) {const chat = useChatContext();- chat.setStream(props.stream);+ chat.setStream(toChat(props.stream));return (<Item label="Tool call - static">@@ -466,7 +490,7 @@ function TableStreamInner() {onChunk: (text) => setRawText((prev) => prev + text),});setStream(controlled);- chat.setStream(controlled);+ chat.setStream(toChat(controlled));};return (diff --git a/js/app/packages/core/component/AI/component/debug/HttpStream.tsx b/js/app/packages/core/component/AI/component/debug/HttpStream.tsxnew file mode 100644index 0000000000..fab931bf8a--- /dev/null+++ b/js/app/packages/core/component/AI/component/debug/HttpStream.tsx@@ -0,0 +1,275 @@+import { DeprecatedTextButton } from '@core/component/DeprecatedTextButton';+import { SERVER_HOSTS } from '@core/constant/servers';+import { platformFetch } from '@core/util/platformFetch';+import { connectionGatewayClient } from '@service-connection/client';+import {+ state as connectionState,+ createConnectionWebsocketEffect,+ type FromWebsocketMessage,+} from '@service-connection/websocket';+import { makePersisted } from '@solid-primitives/storage';+import { WebsocketConnectionState } from '@websocket';+import { createEffect, createMemo, createSignal, For, Show } from 'solid-js';++interface StreamChunk {+ timestamp: Date;+ raw: unknown;+}++export default function HttpStreamDebug() {+ const [chatId, setChatId] = makePersisted(createSignal(''), {+ name: 'http-stream-debug-chat-id',+ storage: localStorage,+ });+ const [messageContent, setMessageContent] = createSignal('Hello, world!');+ const [streamId, setStreamId] = createSignal<string | null>(null);+ const [chunks, setChunks] = createSignal<StreamChunk[]>([]);+ const [isStreaming, setIsStreaming] = createSignal(false);+ const [error, setError] = createSignal<string | null>(null);++ // Resubscribe to the entity when we have a chatId and the ws is connected+ createEffect(() => {+ const id = chatId();+ const connected = connectionState() === WebsocketConnectionState.Open;+ if (id && connected) {+ connectionGatewayClient.trackEntity({+ entity_type: 'chat',+ entity_id: id,+ action: 'open',+ });+ }+ });++ // Concatenated text response derived from chunks+ const responseText = createMemo(() => {+ let text = '';+ for (const chunk of chunks()) {+ const raw = chunk.raw as Record<string, unknown>;+ if (+ raw?.type === 'chat_message_response' &&+ (raw.content as Record<string, unknown>)?.type === 'text'+ ) {+ text += (raw.content as Record<string, unknown>).text;+ }+ }+ return text;+ });++ // Listen for messages on connection gateway+ // Stream messages arrive as { type: "stream", data: "<json>" }+ // where the parsed data is a StreamItem: { id: { entity_type, entity_id, stream_id }, payload: <value> }+ createConnectionWebsocketEffect((data: FromWebsocketMessage) => {+ if (data.type !== 'stream') return;++ let msgData = data.data;+ if (typeof msgData === 'string') {+ try {+ msgData = JSON.parse(msgData);+ } catch {+ return;+ }+ }+ if (msgData.id?.entity_id !== chatId()) return;+ if (msgData.id?.stream_id) setStreamId(msgData.id.stream_id);++ setChunks((prev) => [+ ...prev,+ { timestamp: new Date(), raw: msgData.payload },+ ]);++ if (msgData.payload?.type === 'stream_end') {+ setIsStreaming(false);+ }+ });++ const sendMessage = async () => {+ setError(null);+ setChunks([]);+ setIsStreaming(true);++ try {+ const response = await platformFetch(+ `${SERVER_HOSTS['cognition-service']}/stream/chat/message`,+ {+ method: 'POST',+ credentials: 'include',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ chat_id: chatId(),+ content: messageContent(),+ model: 'claude-haiku-4-5',+ token: '',+ }),+ }+ );++ if (!response.ok) {+ const errorText = await response.text();+ setError(`HTTP ${response.status}: ${errorText}`);+ setIsStreaming(false);+ return;+ }++ const data = await response.json();+ // message_id is the same as stream_id+ setStreamId(data.message_id);+ // Update chat ID if a new one was created+ if (data.chat_id) {+ setChatId(data.chat_id);+ }+ // Subscribe to the chat entity so the connection gateway routes messages to us+ connectionGatewayClient.trackEntity({+ entity_type: 'chat',+ entity_id: data.chat_id || chatId(),+ action: 'open',+ });+ } catch (err) {+ setError(`Error: ${err}`);+ setIsStreaming(false);+ }+ };++ return (+ <div class="h-full w-full overflow-auto p-4">+ <div class="max-w-5xl mx-auto space-y-4">+ <h1 class="text-lg font-medium">HTTP Stream Debug</h1>++ {/* Connection Status */}+ <div class="flex items-center gap-2">+ <span class="text-sm">Connection Gateway:</span>+ <span+ class={`text-sm px-2 py-1 rounded ${+ connectionState() === WebsocketConnectionState.Open+ ? 'bg-green-100 text-green-800'+ : 'bg-red-100 text-red-800'+ }`}+ >+ {connectionState() === WebsocketConnectionState.Open+ ? 'Connected'+ : 'Disconnected'}+ </span>+ </div>++ {/* Form */}+ <div class="space-y-3 p-4 border border-edge rounded-lg">+ <div>+ <div class="block text-sm mb-1">Message</div>+ <textarea+ value={messageContent()}+ onInput={(e) => setMessageContent(e.currentTarget.value)}+ placeholder="Enter message..."+ rows={3}+ class="w-full px-3 py-2 border border-edge rounded bg-panel resize-none"+ />+ </div>+ <div class="flex gap-2">+ <DeprecatedTextButton+ text={isStreaming() ? 'Streaming...' : 'Send Message'}+ onClick={sendMessage}+ theme="accent"+ disabled={isStreaming()}+ />+ <DeprecatedTextButton+ text="Reset"+ onClick={() => {+ setChatId('');+ setStreamId(null);+ setChunks([]);+ setError(null);+ setIsStreaming(false);+ }}+ theme="base"+ />+ </div>+ </div>++ {/* Chat ID */}+ <Show when={chatId()}>+ <div class="text-sm p-2 bg-panel rounded font-mono break-all">+ Chat ID: {chatId()}+ </div>+ </Show>++ {/* Stream ID */}+ <Show when={streamId()}>+ <div class="text-sm p-2 bg-panel rounded font-mono break-all">+ Stream ID: {streamId()}+ </div>+ </Show>++ {/* Error */}+ <Show when={error()}>+ <div class="text-sm p-2 bg-red-100 text-red-800 rounded">+ {error()}+ </div>+ </Show>++ {/* Response + Chunks side by side */}+ <div class="flex gap-4">+ {/* Response (left) */}+ <div class="flex-1 space-y-2">+ <div class="flex items-center justify-between">+ <span class="text-sm font-medium">Response</span>+ <Show when={isStreaming()}>+ <span class="text-sm text-blue-600 animate-pulse">+ Streaming...+ </span>+ </Show>+ </div>+ <div class="border border-edge rounded-lg max-h-96 overflow-auto">+ <Show+ when={responseText()}+ fallback={+ <div class="p-4 text-center text-sm text-gray-500">+ No response yet. Send a message to start streaming.+ </div>+ }+ >+ <div class="p-3 text-sm whitespace-pre-wrap">+ {responseText()}+ </div>+ </Show>+ </div>+ </div>++ {/* Chunks (right) */}+ <div class="flex-1 space-y-2">+ <div class="flex items-center justify-between">+ <span class="text-sm font-medium">+ Chunks ({chunks().length})+ </span>+ <Show when={isStreaming()}>+ <span class="text-sm text-blue-600 animate-pulse">+ Receiving...+ </span>+ </Show>+ </div>+ <div class="border border-edge rounded-lg max-h-96 overflow-auto">+ <Show+ when={chunks().length > 0}+ fallback={+ <div class="p-4 text-center text-sm text-gray-500">+ No chunks yet. Send a message to start streaming.+ </div>+ }+ >+ <For each={chunks()}>+ {(chunk) => (+ <div class="p-3 border-b border-edge last:border-b-0">+ <div class="text-xs text-gray-500 mb-1">+ {chunk.timestamp.toLocaleTimeString()}+ </div>+ <pre class="text-xs font-mono whitespace-pre-wrap break-all">+ {JSON.stringify(chunk.raw, null, 2)}+ </pre>+ </div>+ )}+ </For>+ </Show>+ </div>+ </div>+ </div>+ </div>+ </div>+ );+}diff --git a/js/app/packages/core/component/AI/component/debug/Tool.tsx b/js/app/packages/core/component/AI/component/debug/Tool.tsxindex ddf52f8a32..f9f7714610 100644--- a/js/app/packages/core/component/AI/component/debug/Tool.tsx+++ b/js/app/packages/core/component/AI/component/debug/Tool.tsx@@ -1,8 +1,21 @@+import { DEFAULT_MODEL } from '@core/component/AI/constant';+import type { ChatMessageStream } from '@core/component/AI/types';import { blockDone, createStream } from '@core/component/AI/util/stream';+import type { MessageStream } from '@service-cognition/websocket';import { mockMessages } from './mockData';import { StreamDebugger } from './stream';import { Item } from './util';+function toChat(stream: MessageStream): ChatMessageStream {+ return {+ data: stream.data,+ isDone: stream.isDone,+ model: DEFAULT_MODEL,+ attachments: [],+ streamId: stream.request.stream_id,+ };+}+export default function DebugTools() {return (<div class="h-full w-full overflow-auto py-2">@@ -35,7 +48,7 @@ function ToolCall() {const neverDone = blockDone(stream);return (<Item label="Tool Call">- <StreamDebugger stream={neverDone} messages={messages} />+ <StreamDebugger stream={toChat(neverDone)} messages={messages} /></Item>);}@@ -78,7 +91,7 @@ function ToolResponse() {const neverDone = blockDone(stream);return (<Item label="Tool Response">- <StreamDebugger stream={neverDone} messages={messages} />+ <StreamDebugger stream={toChat(neverDone)} messages={messages} /></Item>);}@@ -120,7 +133,7 @@ function ToolResponsStreamEnd() {]);return (<Item label="Tool Response Stream Done">- <StreamDebugger stream={stream} messages={messages} />+ <StreamDebugger stream={toChat(stream)} messages={messages} /></Item>);}diff --git a/js/app/packages/core/component/AI/component/debug/stream/StreamDebugger.tsx b/js/app/packages/core/component/AI/component/debug/stream/StreamDebugger.tsxindex 7b189d6241..f3c83c1b68 100644--- a/js/app/packages/core/component/AI/component/debug/stream/StreamDebugger.tsx+++ b/js/app/packages/core/component/AI/component/debug/stream/StreamDebugger.tsx@@ -1,7 +1,9 @@+import { DEFAULT_MODEL } from '@core/component/AI/constant';import { DeprecatedTextButton } from '@core/component/DeprecatedTextButton';import type { ChatMessageWithAttachments } from '@service-cognition/generated/schemas';import type { MessageStream } from '@service-cognition/websocket';import { createSignal } from 'solid-js';+import type { ChatMessageStream } from '../../../types';import {ChatInputProvider,ChatProvider,@@ -10,6 +12,16 @@ import {import { ChatMessages } from '../../message/ChatMessages';import { StreamStatus } from './StreamStatus';+function toChat(stream: MessageStream): ChatMessageStream {+ return {+ data: stream.data,+ isDone: stream.isDone,+ model: DEFAULT_MODEL,+ attachments: [],+ streamId: stream.request.stream_id,+ };+}+export function StreamDebuggerWithControls(props: {stream: () => MessageStream;messages?: ChatMessageWithAttachments[];@@ -35,8 +47,9 @@ function StreamDebuggerWithControlsInner(props: {const [stream, setStream] = createSignal<MessageStream>();if (props.autoStart) {- setStream(props.stream());- chat.setStream(props.stream());+ const s = props.stream();+ setStream(s);+ chat.setStream(toChat(s));}return (@@ -47,7 +60,7 @@ function StreamDebuggerWithControlsInner(props: {onClick={() => {const stream = props.stream();setStream(stream);- chat.setStream(stream);+ chat.setStream(toChat(stream));}}theme="accent"/>@@ -70,7 +83,7 @@ function StreamDebuggerWithControlsInner(props: {}export function StreamDebugger(props: {- stream: MessageStream;+ stream: ChatMessageStream;messages?: ChatMessageWithAttachments[];}) {return (@@ -82,7 +95,7 @@ export function StreamDebugger(props: {);}-function StreamDebuggerInner(props: { stream: MessageStream }) {+function StreamDebuggerInner(props: { stream: ChatMessageStream }) {const chat = useChatContext();chat.setStream(props.stream);return (@@ -90,7 +103,11 @@ function StreamDebuggerInner(props: { stream: MessageStream }) {data-chat-scrollclass="size-full flex flex-col gap-y-2 overflow-y-auto">- <StreamStatus stream={() => props.stream} />+ <div class="p-2 bg-menu border border-edge text-ink font-mono text-sm">+ <span>chunks: {props.stream.data().length}</span>+ {' | '}+ <span>isDone: {String(props.stream.isDone())}</span>+ </div><ChatMessages /></div>);diff --git a/js/app/packages/core/component/AI/component/input/useChatInput.tsx b/js/app/packages/core/component/AI/component/input/ChatInput.tsxsimilarity index 94%rename from js/app/packages/core/component/AI/component/input/useChatInput.tsxrename to js/app/packages/core/component/AI/component/input/ChatInput.tsxindex c814d072c3..b7f6dd6e41 100644--- a/js/app/packages/core/component/AI/component/input/useChatInput.tsx+++ b/js/app/packages/core/component/AI/component/input/ChatInput.tsx@@ -1,18 +1,14 @@import { withAnalytics } from '@coparse/analytics';-import { useBuildChatSendRequest } from '@core/component/AI/component/input/buildRequest';+import type { ChatSendInput } from '@core/component/AI/component/input/buildRequest';import { SMART_MODE_MODEL } from '@core/component/AI/constant';import { useChatInputContext } from '@core/component/AI/context';import { useChatAttachableHistory } from '@core/component/AI/signal/attachment';-import type {- CreateAndSend,- Model,- Send,- ToolSet,-} from '@core/component/AI/types';+import type { Model, ToolSet } from '@core/component/AI/types';import { DeprecatedIconButton } from '@core/component/DeprecatedIconButton';import { Hotkey, modifierMap } from '@core/component/Hotkey';import { Tooltip } from '@core/component/Tooltip';import { pressedKeys } from '@core/hotkey/state';+import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';import { isTouchDevice } from '@core/mobile/isTouchDevice';import ArrowUp from '@icon/bold/arrow-up-bold.svg';import PlusIcon from '@icon/regular/plus.svg';@@ -20,20 +16,18 @@ import XIcon from '@icon/regular/x.svg';import Stop from '@phosphor-icons/core/regular/stop.svg';import { createCallback } from '@solid-primitives/rootless';import { Button } from '@ui/components/Button';+import { cn } from '@ui/utils/classname';import type { LexicalEditor } from 'lexical';import { createEffect, createSignal, Match, Show, Switch } from 'solid-js';import { AttachmentList } from './Attachment';import { ChatAttachMenu } from './ChatAttachMenu';-import type { Source } from './ToolsetSelector';-import type { UseChatMarkdown } from './useChatMarkdownArea';-import { cn } from '@ui/utils/classname';-import { isNativeMobilePlatform } from '@core/mobile/isNativeMobilePlatform';import { useAiDataConsentGate } from './useAiDataConsent';+import type { UseChatMarkdown } from './useChatMarkdownArea';const { track, TrackingEvents } = withAnalytics();export type ChatInputProps = {- onSend: (args: CreateAndSend | Send) => void;+ onSend: (args: ChatSendInput) => void;onStop?: () => void;isPersistent?: boolean;showActiveTabs?: boolean;@@ -57,7 +51,6 @@ export function ChatInput(props: ChatInputComponentProps) {const toolsetSignal = createSignal<ToolSet>({ type: 'all' });const { hasConsent, requestConsent, ConsentDialog } = useAiDataConsentGate();- const [source] = createSignal<Source>('everything');const [showAttachMenu, setShowAttachMenu] = createSignal(false);const [attachMenuAnchorRef, setAttachMenuAnchorRef] =createSignal<HTMLDivElement>();@@ -87,8 +80,6 @@ export function ChatInput(props: ChatInputComponentProps) {return mdRef.scrollHeight > LINE_HEIGHT_THRESHOLD;};- const buildChatSendRequest = useBuildChatSendRequest();-const sendMessage = createCallback(async (modelOverride?: Model) => {if (!canSendMessage()) return;@@ -97,17 +88,14 @@ export function ChatInput(props: ChatInputComponentProps) {return;}- const request = await buildChatSendRequest({- chatId: props.chatId,- userRequest: props.markdown.markdownText(),- isPersistent: props.isPersistent,- attachments: attachments.attached(),+ const input: ChatSendInput = {+ content: props.markdown.markdownText(),model: modelOverride ?? model(),+ attachments: attachments.attached(),toolset: toolsetSignal[0](),- source: source(),- });+ };props.markdown.clear();- props.onSend(request);+ props.onSend(input);});function handleEnter(e: KeyboardEvent): boolean {diff --git a/js/app/packages/core/component/AI/component/input/buildRequest.ts b/js/app/packages/core/component/AI/component/input/buildRequest.tsindex 4a8f3c94ca..9d390da800 100644--- a/js/app/packages/core/component/AI/component/input/buildRequest.ts+++ b/js/app/packages/core/component/AI/component/input/buildRequest.ts@@ -2,96 +2,71 @@ import { DEFAULT_MODEL } from '@core/component/AI/constant';import { useAdditionalInstructions } from '@core/component/AI/constant/prompts';import type {Attachment,- CreateAndSend,- MessageStream,+ ChatMessageStream,Model,- Send,ToolSet,} from '@core/component/AI/types';import { isPaymentError } from '@core/util/handlePaymentError';import { isErr } from '@core/util/maybeResult';-import { getMacroApiToken } from '@service-auth/fetch';-import {- cognitionApiServiceClient,- cognitionWebsocketServiceClient,-} from '@service-cognition/client';-import type { Source } from './ToolsetSelector';+import { cognitionApiServiceClient } from '@service-cognition/client';+import { subscribe } from '@service-connection/stream';-export function useBuildChatSendRequest() {+export type ChatSendInput = {+ content: string;+ model: Model;+ attachments: Attachment[];+ toolset: ToolSet;+};++export type SendChatMessageResult =+ | { stream: ChatMessageStream; chat_id: string }+ | { error: true; paymentError?: boolean };++export function useSendChatMessage() {const additionalInstructions = useAdditionalInstructions();- return async function buildChatSendRequest({- userRequest,- chatId,- isPersistent,++ return async function sendChatMessage({+ content,model,+ chatId,attachments,toolset,- }: {- userRequest: string;- chatId: string | undefined;- isPersistent?: boolean;- model?: Model;- attachments?: Attachment[];- toolset?: ToolSet;- source?: Source;- }): Promise<CreateAndSend | Send> {- const token = await getMacroApiToken();+ }: ChatSendInput & { chatId?: string }): Promise<SendChatMessageResult> {const modelInstructions = model ? `\nYou are ${model}` : '';const additional = `${additionalInstructions()}${modelInstructions}`;- const request = (id: string): Send['request'] => ({- chat_id: id,- content: userRequest,+ const response = await cognitionApiServiceClient.sendStreamChatMessage({+ content,model: model ?? DEFAULT_MODEL,- attachments: attachments ?? [],- token,- additional_instructions: additional,+ chat_id: chatId,+ attachments: attachments.length > 0 ? attachments : undefined,toolset,+ additional_instructions: additional,});- if (chatId !== undefined) {- const send: Send = {- type: 'send',- chat_id: chatId,- request: request(chatId),- call: () => {- return cognitionWebsocketServiceClient.sendStreamChatMessage(- request(chatId)- );- },- };- return send;- } else {- const createAndSend: CreateAndSend = {- type: 'createAndSend',- request: {},- content: userRequest,- attachments: attachments ?? [],- model: model ?? DEFAULT_MODEL,- call: async () => {- const response = await cognitionApiServiceClient.createChat({- isPersistent: isPersistent ?? false,- });- if (isPaymentError(response)) {- return { type: 'error', paymentError: true };- }- if (isErr(response)) {- return { type: 'error' };- }- const [, { id: chatId }] = response;- return {- type: 'send',- chat_id: chatId,- request: request(chatId),- call: (): MessageStream => {- return cognitionWebsocketServiceClient.sendStreamChatMessage(- request(chatId)- );- },- };- },- };- return createAndSend;+ if (isPaymentError(response)) {+ return { error: true, paymentError: true };+ }+ if (isErr(response)) {+ return { error: true };+ }++ const [, { stream_id, chat_id }] = response;++ const connectionStream = subscribe('chat', chat_id, stream_id);+ if (!connectionStream) {+ return { error: true };}++ return {+ chat_id,+ stream: {+ data: connectionStream.data,+ isDone: connectionStream.isDone,+ model: model ?? DEFAULT_MODEL,+ attachments: attachments ?? [],+ streamId: stream_id,+ },+ };};}diff --git a/js/app/packages/core/component/AI/component/input/index.ts b/js/app/packages/core/component/AI/component/input/index.tsindex 85eee5afc4..09a3d7b2ce 100644--- a/js/app/packages/core/component/AI/component/input/index.ts+++ b/js/app/packages/core/component/AI/component/input/index.ts@@ -1,5 +1,5 @@export {ChatInput,- type ChatInputProps,type ChatInputComponentProps,-} from './useChatInput';+ type ChatInputProps,+} from './ChatInput';diff --git a/js/app/packages/core/component/AI/component/message/ChatMessages.tsx b/js/app/packages/core/component/AI/component/message/ChatMessages.tsxindex 6a7e354476..982ccc3541 100644--- a/js/app/packages/core/component/AI/component/message/ChatMessages.tsx+++ b/js/app/packages/core/component/AI/component/message/ChatMessages.tsx@@ -1,15 +1,20 @@+import type { ChatSendInput } from '@core/component/AI/component/input/buildRequest';+import { DEFAULT_MODEL } from '@core/component/AI/constant';+import { useAdditionalInstructions } from '@core/component/AI/constant/prompts';import { useChatContext } from '@core/component/AI/context';import type {+ ChatMessageStream,ChatMessageWithAttachments,- MessageStream,} from '@core/component/AI/types';import { asChatMessage } from '@core/component/AI/util/message';+import { getMacroApiToken } from '@service-auth/fetch';+import { cognitionWebsocketServiceClient } from '@service-cognition/client';import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';import { aiChatTheme } from '@core/component/LexicalMarkdown/theme';-import { toast } from '@core/component/Toast/Toast';import { createElementSize } from '@solid-primitives/resize-observer';import type { Accessor, JSXElement, Setter } from 'solid-js';import {+ on,createEffect,createMemo,createSelector,@@ -21,7 +26,6 @@ import {Switch,} from 'solid-js';import { createStore } from 'solid-js/store';-import { handleError } from '../../util/handleError';import { idStream, timeStream } from '../../util/stream/extendedStream';import { AssistantMessage } from './AssistantMessage';import { LoadingMessage } from './LoadingMessage';@@ -58,10 +62,56 @@ export function ChatMessages(props: ChatMessagesProps) {const chat = useChatContext();const [messages, setMessages] = [chat.messages, chat.setMessages];const streamTuple: [- Accessor<MessageStream | undefined>,- Setter<MessageStream | undefined>,+ Accessor<ChatMessageStream | undefined>,+ Setter<ChatMessageStream | undefined>,] = [chat.stream, chat.setStream];const chatId = chat.chatId;+ const additionalInstructions = useAdditionalInstructions();++ const makeEdit = async (data: ChatSendInput) => {+ const setStream = streamTuple?.[1];+ if (!setStream) return;++ setMessages((p) => {+ const last = p.at(-1);+ if (!last) return p;+ if (last.role === 'user') {+ return p.slice(0, -1);+ } else {+ return p.slice(0, -2);+ }+ });+ setMessages((p) => [+ ...p,+ {+ attachments: data.attachments ?? [],+ content: data.content,+ role: 'user',+ model: data.model,+ id: 'todo',+ },+ ]);++ const token = await getMacroApiToken();+ const modelInstructions = data.model ? `\nYou are ${data.model}` : '';+ const additional = `${additionalInstructions()}${modelInstructions}`;+ const editStream = cognitionWebsocketServiceClient.streamEditMessage({+ chat_id: chatId()!,+ content: data.content,+ model: data.model ?? DEFAULT_MODEL,+ attachments: data.attachments ?? [],+ token,+ additional_instructions: additional,+ toolset: data.toolset,+ });++ setStream({+ data: editStream.data,+ isDone: editStream.isDone,+ model: data.model ?? DEFAULT_MODEL,+ attachments: data.attachments ?? [],+ });+ };const extendedStream = createMemo(() => {const s = streamTuple?.[0]?.();@@ -122,10 +172,45 @@ export function ChatMessages(props: ChatMessagesProps) {const streamable = streamTuple?.[0];if (!streamable) return [];const stream = streamable();- if (!stream || !('attachments' in stream.request)) return [];- return stream.request.attachments ?? [];+ if (!stream) return [];+ return stream.attachments ?? [];};+ const streamData = () => {+ const stream = streamTuple?.[0]?.();+ if (!stream) return [];+ return stream.data();+ };+ // when a user message arrives via stream, update optimistic ID or append+ createEffect(+ on(streamData, (data) => {+ const latest = data.at(-1);+ if (!latest) return;+ if (latest.type !== 'chat_user_message') return;+ setMessages((p) => {+ const last = p.at(-1);+ if (last?.role === 'user' && last?.content === latest.content) {+ // Patch the optimistic message with the real server ID+ if (last.id !== latest.message_id) {+ const updated = p.slice();+ updated[updated.length - 1] = { ...last, id: latest.message_id };+ return updated;+ }+ return p;+ }+ return [+ ...p,+ {+ id: latest.message_id,+ content: latest.content,+ role: 'user' as const,+ attachments: latest.attachments,+ },+ ];+ });+ })+ );+// when messages finish streaming, append and scrollcreateEffect(() => {if (!streamTuple?.[0]) return;@@ -134,17 +219,12 @@ export function ChatMessages(props: ChatMessagesProps) {if (s.isDone()) {const message = asChatMessage(s.data());if (message) {- message.model = 'model' in s.request ? s.request.model : undefined;+ message.model = s.model;setMessages((p) => {if (p.find((m) => m.id === message.id)) return p;return [...p, message];});}- } else if (s.isErr()) {- console.log(s);- const err = s.err();- if (err) handleError(err);- else toast.failure('Failed to respond to message');}});@@ -275,7 +355,7 @@ export function ChatMessages(props: ChatMessagesProps) {)}</For>- <Show when={isStream() || lastPair()}>+ <Show when={isStream() || chat.waitingForStream() || lastPair()}><divclass="shrink-0"style={{@@ -302,33 +382,7 @@ export function ChatMessages(props: ChatMessagesProps) {? undefined: {chatId: chatId()!,- makeEdit: (send) => {- const setStream = streamTuple?.[1];- if (setStream) {- setMessages((p) => {- const last = p.at(-1);- if (!last) return p;- if (last.role === 'user') {- return p.slice(0, -1);- } else {- return p.slice(0, -2);- }- });- setMessages((p) => [- ...p,- {- attachments:- send.request.attachments ?? [],- content: send.request.content,- role: 'user',- model: send.request.model,- // TODO update message id from server response- id: 'todo',- },- ]);- setStream(send.call());- }- },+ makeEdit,}}/>@@ -355,7 +409,11 @@ export function ChatMessages(props: ChatMessagesProps) {}}</Show>{/* this works for most cases */}- <Show when={!generatingMessage() && isStream()}>+ <Show+ when={+ !generatingMessage() && (isStream() || chat.waitingForStream())+ }+ ><OnMountonShow={() =>scrollToBottom(isNearBottom() ? 'instant' : 'smooth')diff --git a/js/app/packages/core/component/AI/component/message/EditableChatMessage.tsx b/js/app/packages/core/component/AI/component/message/EditableChatMessage.tsxindex 9e858b5f81..fbeb05eb91 100644--- a/js/app/packages/core/component/AI/component/message/EditableChatMessage.tsx+++ b/js/app/packages/core/component/AI/component/message/EditableChatMessage.tsx@@ -1,18 +1,18 @@-import { ChatInput } from '@core/component/AI/component/input/useChatInput';+import type { ChatSendInput } from '@core/component/AI/component/input/buildRequest';+import { ChatInput } from '@core/component/AI/component/input/ChatInput';import { useChatMarkdownArea } from '@core/component/AI/component/input/useChatMarkdownArea';import {ChatInputProvider,useChatInputContext,} from '@core/component/AI/context';-import type { Attachment, Model, Send } from '@core/component/AI/types';-import { asEditRequest } from '@core/component/AI/types/util';+import type { Attachment, Model } from '@core/component/AI/types';import { onMount } from 'solid-js';function EditableChatMessageInner(props: {chatId: string;initialText: string;attachments: Attachment[];- onAccept: (r: Send) => void;+ onAccept: (r: ChatSendInput) => void;onCancel: () => void;model: Model;}) {@@ -37,9 +37,7 @@ function EditableChatMessageInner(props: {<ChatInputmarkdown={chatMarkdownArea}chatId={props.chatId}- onSend={(request) => {- if (request.type === 'send') props.onAccept(asEditRequest(request));- }}+ onSend={(request) => props.onAccept(request)}/></div>);@@ -49,7 +47,7 @@ export function EditableChatMessage(props: {chatId: string;initialText: string;attachments: Attachment[];- onAccept: (r: Send) => void;+ onAccept: (r: ChatSendInput) => void;onCancel: () => void;model: Model;}) {diff --git a/js/app/packages/core/component/AI/component/message/UserMessage.tsx b/js/app/packages/core/component/AI/component/message/UserMessage.tsxindex acbaa081a0..970bf0cd30 100644--- a/js/app/packages/core/component/AI/component/message/UserMessage.tsx+++ b/js/app/packages/core/component/AI/component/message/UserMessage.tsx@@ -1,4 +1,5 @@-import type { Model, Send } from '@core/component/AI/types';+import type { ChatSendInput } from '@core/component/AI/component/input/buildRequest';+import type { Model } from '@core/component/AI/types';import { isDssImage, isImageAttachment } from '@core/component/AI/util';import { DeprecatedIconButton } from '@core/component/DeprecatedIconButton';import { ImagePreview } from '@core/component/ImagePreview';@@ -34,7 +35,7 @@ function insertSoftHyphens(text: string): string {export function UserMessage(props: {message: ChatMessageWithAttachments;edit?: {- makeEdit: (edit: Send) => void;+ makeEdit?: (edit: ChatSendInput) => void;chatId: string;};}) {@@ -137,7 +138,7 @@ export function UserMessage(props: {attachments={props.message.attachments}initialText={props.message.content.toString()}model={(props.message.model as Model) ?? DEFAULT_MODEL}- onAccept={props.edit!.makeEdit}+ onAccept={() => {}}onCancel={() => setIsEditing(false)}/></Match>diff --git a/js/app/packages/core/component/AI/context/ChatContext.tsx b/js/app/packages/core/component/AI/context/ChatContext.tsxindex 2928d1b166..737d7eabe1 100644--- a/js/app/packages/core/component/AI/context/ChatContext.tsx+++ b/js/app/packages/core/component/AI/context/ChatContext.tsx@@ -4,19 +4,21 @@ import { useTabAttachments } from '@core/component/AI/signal/tabAttachments';import type {Attachment,Attachments,+ ChatMessageStream,ChatMessageWithAttachments,- MessageStream,Model,UploadQueue,} from '@core/component/AI/types';import { useUploadAttachment } from '@core/component/AI/util/uploadToChat';import { ENABLE_AI_AUTO_TAB_ATTACHMENTS } from '@core/constant/featureFlags';+import { getEntityStreams } from '@service-connection/stream';import type { Accessor, ParentProps, Setter } from 'solid-js';import {createContext,createEffect,createSignal,on,+ untrack,useContext,} from 'solid-js';@@ -100,8 +102,10 @@ export type ChatState = {messages: Accessor<ChatMessageWithAttachments[]>;setMessages: Setter<ChatMessageWithAttachments[]>;addMessage: (msg: ChatMessageWithAttachments) => void;- stream: Accessor<MessageStream | undefined>;- setStream: Setter<MessageStream | undefined>;+ stream: Accessor<ChatMessageStream | undefined>;+ setStream: Setter<ChatMessageStream | undefined>;+ waitingForStream: Accessor<boolean>;+ setWaitingForStream: Setter<boolean>;};const ChatCtx = createContext<ChatState>();@@ -116,29 +120,38 @@ export function ChatProvider(Setter<ChatMessageWithAttachments[]>,];stream: [- Accessor<MessageStream | undefined>,- Setter<MessageStream | undefined>,+ Accessor<ChatMessageStream | undefined>,+ Setter<ChatMessageStream | undefined>,];+ waitingForStream?: [Accessor<boolean>, Setter<boolean>];};}) {let messages: Accessor<ChatMessageWithAttachments[]>;let setMessages: Setter<ChatMessageWithAttachments[]>;- let stream: Accessor<MessageStream | undefined>;- let setStream: Setter<MessageStream | undefined>;+ let stream: Accessor<ChatMessageStream | undefined>;+ let setStream: Setter<ChatMessageStream | undefined>;+ let waitingForStream: Accessor<boolean>;+ let setWaitingForStream: Setter<boolean>;if (props.external) {[messages, setMessages] = props.external.messages;[stream, setStream] = props.external.stream;+ if (props.external.waitingForStream) {+ [waitingForStream, setWaitingForStream] = props.external.waitingForStream;+ } else {+ [waitingForStream, setWaitingForStream] = createSignal(false);+ }} else {const [_messages, _setMessages] = createSignal<ChatMessageWithAttachments[]>(props.messages ?? []);- const [_stream, _setStream] = createSignal<MessageStream>();+ const [_stream, _setStream] = createSignal<ChatMessageStream>();messages = _messages;setMessages = _setMessages;stream = _stream;setStream = _setStream;+ [waitingForStream, setWaitingForStream] = createSignal(false);}const _setMessages = setMessages;@@ -146,6 +159,30 @@ export function ChatProvider(_setMessages((p) => [...p, msg]);};+ // --- Reconnect active streams on page refresh ---+ // Reactive to props.chatId (ChatProvider may not remount on chat switch).+ // Uses untrack for stream/messages to only fire on new WS streams or chatId change.+ createEffect(() => {+ const activeStreams = getEntityStreams('chat', props.chatId)();++ for (const s of activeStreams) {+ const sid = s.id()?.stream_id;+ if (!sid || s.isDone()) continue;++ const isInMessages = untrack(() => messages().some((m) => m.id === sid));+ if (isInMessages) continue;++ setStream({+ data: s.data,+ isDone: s.isDone,+ model: DEFAULT_MODEL,+ attachments: [],+ streamId: sid,+ });+ break;+ }+ });+return (<ChatCtx.Providervalue={{@@ -155,6 +192,8 @@ export function ChatProvider(addMessage,stream,setStream,+ waitingForStream,+ setWaitingForStream,}}>{props.children}diff --git a/js/app/packages/core/component/AI/signal/tool.ts b/js/app/packages/core/component/AI/signal/tool.tsindex d04c8d7e8a..6eada02f66 100644--- a/js/app/packages/core/component/AI/signal/tool.ts+++ b/js/app/packages/core/component/AI/signal/tool.ts@@ -1,8 +1,11 @@-import type { MessageStream } from '@service-cognition/websocket';+import type { ChatStream } from '@service-cognition/generated/schemas';+import type { Accessor } from 'solid-js';import { createEffect, on } from 'solid-js';import { triggerToolCall } from '../component/tool/handler';-export function registerToolHandler(stream: () => MessageStream | undefined) {+type StreamLike = { data: Accessor<ChatStream[]> };++export function registerToolHandler(stream: () => StreamLike | undefined) {createEffect(on([stream, () => stream()?.data()],diff --git a/js/app/packages/core/component/AI/types/index.ts b/js/app/packages/core/component/AI/types/index.tsindex 0bd9c68bc5..8e2a4d03bb 100644--- a/js/app/packages/core/component/AI/types/index.ts+++ b/js/app/packages/core/component/AI/types/index.ts@@ -5,6 +5,6 @@ export type {ToolSet,} from '@service-cognition/generated/schemas';export { Model } from '@service-cognition/generated/schemas';-export type { MessageStream, StreamItem } from '@service-cognition/websocket';+export type { StreamItem } from '@service-cognition/websocket';export * from './attachment';export * from './service';diff --git a/js/app/packages/core/component/AI/types/service.ts b/js/app/packages/core/component/AI/types/service.tsindex 14f3ba5c5c..a2f6d6a6c4 100644--- a/js/app/packages/core/component/AI/types/service.ts+++ b/js/app/packages/core/component/AI/types/service.ts@@ -1,33 +1,11 @@-import type {- cognitionApiServiceClient,- cognitionWebsocketServiceClient,-} from '@service-cognition/client';-import type { Model } from '@service-cognition/generated/schemas';-import type { MessageStream } from '@service-cognition/websocket';+import type { ChatStream, Model } from '@service-cognition/generated/schemas';+import type { Accessor } from 'solid-js';import type { Attachment } from './attachment';-export type SendChatMessageArgs = Parameters<- (typeof cognitionWebsocketServiceClient)['sendStreamChatMessage']->[0];--export type CreateMessageArgs = Parameters<- (typeof cognitionApiServiceClient)['createChat']->[0];--export type CreateAndSend = {- type: 'createAndSend';- call: () => Promise<{ type: 'error'; paymentError?: true } | Send>;- request: CreateMessageArgs;- content: string;- attachments: Attachment[];+export interface ChatMessageStream {+ data: Accessor<ChatStream[]>;+ isDone: Accessor<boolean>;model: Model;-};--export type Send = {- type: 'send';- chat_id: string;- call: () => MessageStream;- request: SendChatMessageArgs;-};--export type Edit = Send;+ attachments: Attachment[];+ streamId?: string;+}diff --git a/js/app/packages/core/component/AI/types/util.ts b/js/app/packages/core/component/AI/types/util.tsindex 2a2b6d91f1..fca7516187 100644--- a/js/app/packages/core/component/AI/types/util.ts+++ b/js/app/packages/core/component/AI/types/util.ts@@ -1,12 +1 @@-import type { Edit, Send } from '@core/component/AI/types';-import { cognitionWebsocketServiceClient } from '@service-cognition/client';--export function asEditRequest(request: Send): Edit {- let call = () =>- cognitionWebsocketServiceClient.streamEditMessage(request.request);-- return {- ...request,- call,- };-}+// Edit request utilities - currently unused, edit flow handled inline in ChatMessages.tsxdiff --git a/js/app/packages/core/component/AI/util/stream/extendedStream.ts b/js/app/packages/core/component/AI/util/stream/extendedStream.tsindex 8f21f9fae0..4a03121010 100644--- a/js/app/packages/core/component/AI/util/stream/extendedStream.ts+++ b/js/app/packages/core/component/AI/util/stream/extendedStream.ts@@ -1,13 +1,16 @@-import type { MessageStream } from '@service-cognition/websocket';+import type { ChatStream } from '@service-cognition/generated/schemas';+import type { Accessor } from 'solid-js';import { createEffect, createSignal } from 'solid-js';+type StreamLike = { data: Accessor<ChatStream[]> };+type Extended<T, U> = T & U;-export interface TimedStream extends MessageStream {+export interface TimedStream {timeToFirstMessageMs: () => undefined | number;}-export function timeStream<T extends MessageStream>(+export function timeStream<T extends StreamLike>(stream: T): Extended<T, TimedStream> {const start = Date.now();@@ -25,11 +28,11 @@ export function timeStream<T extends MessageStream>(};}-export interface IddStream extends MessageStream {+export interface IddStream {messageId: () => undefined | string;}-export function idStream<T extends MessageStream>(+export function idStream<T extends StreamLike>(stream: T): Extended<T, IddStream> {const [id, setMessageId] = createSignal<string>();diff --git a/js/app/packages/service-clients/service-cognition/client.ts b/js/app/packages/service-clients/service-cognition/client.tsindex ab78bc7fdd..4c2b945700 100644--- a/js/app/packages/service-clients/service-cognition/client.ts+++ b/js/app/packages/service-clients/service-cognition/client.ts@@ -31,6 +31,10 @@ import type { StringIDResponse } from './generated/schemas/stringIDResponse';import type { StructedOutputCompletionRequest } from './generated/schemas/structedOutputCompletionRequest';import type { StructedOutputCompletionResponse } from './generated/schemas/structedOutputCompletionResponse';import type { SuccessResponse } from './generated/schemas/successResponse';+import type { GetSimpleCompletionStreamPayload } from './generated/schemas/getSimpleCompletionStreamPayload';+import type { HttpSendChatMessageRequest } from './generated/schemas/httpSendChatMessageRequest';+import type { SendChatMessageResponse } from './generated/schemas/sendChatMessageResponse';+import type { SimpleCompletionResponse } from './generated/schemas/simpleCompletionResponse';import type { VerifyAttachmentsRequest } from './generated/schemas/verifyAttachmentsRequest';import type { VerifyAttachmentsResponse } from './generated/schemas/verifyAttachmentsResponse';import type { CognitionWebsocketService } from './service';@@ -296,6 +300,28 @@ export const cognitionApiServiceClient = {(result) => result);},++ /** Send a chat message via HTTP stream API. Response chunks arrive via connection_gateway. */+ async sendStreamChatMessage(args: HttpSendChatMessageRequest) {+ return mapOk(+ await dcsFetch<SendChatMessageResponse>(`/stream/chat/message`, {+ method: 'POST',+ body: JSON.stringify(args),+ }),+ (result) => result+ );+ },++ /** Start a simple completion via HTTP stream API. Response chunks arrive via connection_gateway. */+ async streamSimpleCompletion(args: GetSimpleCompletionStreamPayload) {+ return mapOk(+ await dcsFetch<SimpleCompletionResponse>(`/stream/completion/simple`, {+ method: 'POST',+ body: JSON.stringify(args),+ }),+ (result) => result+ );+ },};export const cognitionWebsocketServiceClient: CognitionWebsocketService = {diff --git a/js/app/packages/service-clients/service-cognition/generated/client.ts b/js/app/packages/service-clients/service-cognition/generated/client.tsindex b438982df7..0844e91863 100644--- a/js/app/packages/service-clients/service-cognition/generated/client.ts+++ b/js/app/packages/service-clients/service-cognition/generated/client.ts@@ -7,6 +7,7 @@import type {ChatHistory,ChatHistoryBatchMessagesRequest,+ ChatMessageError,ChatsResponse,CopyChatRequest,CreateTextRequestBody,@@ -23,6 +24,11 @@ import type {GetModelsForAttachmentsRequest,GetModelsForAttachmentsResponse,GetModelsResponse,+ GetSimpleCompletionStreamPayload,+ HttpSendChatMessageRequest,+ SendChatMessageResponse,+ SimpleCompletionError,+ SimpleCompletionResponse,StringIDResponse,StructedOutputCompletionRequest,StructedOutputCompletionResponse,@@ -1173,6 +1179,130 @@ export const wsHandler = async (} as wsHandlerResponse;};+/**+ * This endpoint initiates a chat message and streams the response via the stream service.+The client should subscribe to the returned stream_id via connection_gateway to receive chunks.+ * @summary Send a new chat message and stream the AI response.+ */+export type sendChatMessageResponse200 = {+ data: SendChatMessageResponse;+ status: 200;+};++export type sendChatMessageResponse400 = {+ data: ChatMessageError;+ status: 400;+};++export type sendChatMessageResponse401 = {+ data: void;+ status: 401;+};++export type sendChatMessageResponse403 = {+ data: void;+ status: 403;+};++export type sendChatMessageResponseSuccess = sendChatMessageResponse200 & {+ headers: Headers;+};+export type sendChatMessageResponseError = (+ | sendChatMessageResponse400+ | sendChatMessageResponse401+ | sendChatMessageResponse403+) & {+ headers: Headers;+};++export type sendChatMessageResponse =+ | sendChatMessageResponseSuccess+ | sendChatMessageResponseError;++export const getSendChatMessageUrl = () => {+ return `/stream/chat/message`;+};++export const sendChatMessage = async (+ httpSendChatMessageRequest: HttpSendChatMessageRequest,+ options?: RequestInit+): Promise<sendChatMessageResponse> => {+ const res = await fetch(getSendChatMessageUrl(), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(httpSendChatMessageRequest),+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: sendChatMessageResponse['data'] = body ? JSON.parse(body) : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as sendChatMessageResponse;+};++/**+ * This endpoint initiates a completion and streams the response via the stream service.+The client should subscribe to the completion_id stream via connection_gateway to receive chunks.+ * @summary Start a simple completion stream.+ */+export type simpleCompletionResponse200 = {+ data: SimpleCompletionResponse;+ status: 200;+};++export type simpleCompletionResponse400 = {+ data: SimpleCompletionError;+ status: 400;+};++export type simpleCompletionResponse401 = {+ data: void;+ status: 401;+};++export type simpleCompletionResponseSuccess = simpleCompletionResponse200 & {+ headers: Headers;+};+export type simpleCompletionResponseError = (+ | simpleCompletionResponse400+ | simpleCompletionResponse401+) & {+ headers: Headers;+};++export type simpleCompletionResponse =+ | simpleCompletionResponseSuccess+ | simpleCompletionResponseError;++export const getSimpleCompletionUrl = () => {+ return `/stream/completion/simple`;+};++export const simpleCompletion = async (+ getSimpleCompletionStreamPayload: GetSimpleCompletionStreamPayload,+ options?: RequestInit+): Promise<simpleCompletionResponse> => {+ const res = await fetch(getSimpleCompletionUrl(), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(getSimpleCompletionStreamPayload),+ });++ const body = [204, 205, 304].includes(res.status) ? null : await res.text();++ const data: simpleCompletionResponse['data'] = body ? JSON.parse(body) : {};+ return {+ data,+ status: res.status,+ headers: res.headers,+ } as simpleCompletionResponse;+};+/*** @summary Gets the current chat share permissions*/diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/chatMessageError.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatMessageError.tsnew file mode 100644index 0000000000..29bfacc416--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatMessageError.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */+import type { ChatMessageErrorStreamId } from './chatMessageErrorStreamId';++/**+ * Error response for chat message endpoints+ */+export interface ChatMessageError {+ error: string;+ stream_id?: ChatMessageErrorStreamId;+}diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/chatMessageErrorStreamId.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatMessageErrorStreamId.tsnew file mode 100644index 0000000000..5eb88da6b2--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatMessageErrorStreamId.ts@@ -0,0 +1,8 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++export type ChatMessageErrorStreamId = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/chatStream.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStream.tsnew file mode 100644index 0000000000..83c0fc78eb--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStream.ts@@ -0,0 +1,38 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */+import type { ChatStreamOneOf } from './chatStreamOneOf';+import type { ChatStreamOneOfEight } from './chatStreamOneOfEight';+import type { ChatStreamOneOfFour } from './chatStreamOneOfFour';+import type { ChatStreamOneOfOnefour } from './chatStreamOneOfOnefour';+import type { ChatStreamOneOfOnenine } from './chatStreamOneOfOnenine';+import type { ChatStreamOneOfOneseven } from './chatStreamOneOfOneseven';+import type { ChatStreamOneOfOnetwo } from './chatStreamOneOfOnetwo';+import type { ChatStreamOneOfOnezero } from './chatStreamOneOfOnezero';+import type { ChatStreamOneOfSix } from './chatStreamOneOfSix';+import type { ChatStreamOneOfThreeone } from './chatStreamOneOfThreeone';+import type { ChatStreamOneOfTwofive } from './chatStreamOneOfTwofive';+import type { ChatStreamOneOfTwonine } from './chatStreamOneOfTwonine';+import type { ChatStreamOneOfTwoone } from './chatStreamOneOfTwoone';+import type { ChatStreamOneOfTwoseven } from './chatStreamOneOfTwoseven';+import type { ChatStreamOneOfTwothree } from './chatStreamOneOfTwothree';++export type ChatStream =+ | ChatStreamOneOf+ | ChatStreamOneOfFour+ | ChatStreamOneOfSix+ | ChatStreamOneOfEight+ | ChatStreamOneOfOnezero+ | ChatStreamOneOfOnetwo+ | ChatStreamOneOfOnefour+ | ChatStreamOneOfOneseven+ | ChatStreamOneOfOnenine+ | ChatStreamOneOfTwoone+ | ChatStreamOneOfTwothree+ | ChatStreamOneOfTwofive+ | ChatStreamOneOfTwoseven+ | ChatStreamOneOfTwonine+ | ChatStreamOneOfThreeone;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOf.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOf.tssimilarity index 53%rename from js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOf.tsrename to js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOf.tsindex 17d055b4cf..d1b5d346f4 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOf.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOf.ts@@ -5,11 +5,10 @@* OpenAPI spec version: 1.0.0*/-import type { FromWebSocketMessageOneOfAllOf } from './fromWebSocketMessageOneOfAllOf';+import type { ChatStreamOneOfAllOf } from './chatStreamOneOfAllOf';import type { WebSocketError } from './webSocketError';/*** Misc error*/-export type FromWebSocketMessageOneOf = WebSocketError &- FromWebSocketMessageOneOfAllOf;+export type ChatStreamOneOf = WebSocketError & ChatStreamOneOfAllOf;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfAllOf.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfAllOf.tsnew file mode 100644index 0000000000..80b1951651--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfAllOf.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */+import type { ChatStreamOneOfAllOfType } from './chatStreamOneOfAllOfType';++export type ChatStreamOneOfAllOf = {+ type: ChatStreamOneOfAllOfType;+};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfAllOfType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfAllOfType.tssimilarity index 52%rename from js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfAllOfType.tsrename to js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfAllOfType.tsindex 76e3c1b216..775300bbd8 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfAllOfType.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfAllOfType.ts@@ -5,10 +5,10 @@* OpenAPI spec version: 1.0.0*/-export type FromWebSocketMessageOneOfAllOfType =- (typeof FromWebSocketMessageOneOfAllOfType)[keyof typeof FromWebSocketMessageOneOfAllOfType];+export type ChatStreamOneOfAllOfType =+ (typeof ChatStreamOneOfAllOfType)[keyof typeof ChatStreamOneOfAllOfType];// eslint-disable-next-line @typescript-eslint/no-redeclare-export const FromWebSocketMessageOneOfAllOfType = {+export const ChatStreamOneOfAllOfType = {error: 'error',} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfSix.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfEight.tssimilarity index 67%rename from js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfSix.tsrename to js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfEight.tsindex 05d15e6741..ddb03c68b4 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfSix.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfEight.ts@@ -5,15 +5,15 @@* OpenAPI spec version: 1.0.0*/import type { AssistantMessagePart } from './assistantMessagePart';-import type { FromWebSocketMessageOneOfSixType } from './fromWebSocketMessageOneOfSixType';+import type { ChatStreamOneOfEightType } from './chatStreamOneOfEightType';/*** Indicates a response from the chat completion API for a given message*/-export type FromWebSocketMessageOneOfSix = {+export type ChatStreamOneOfEight = {chat_id: string;content: AssistantMessagePart;message_id: string;stream_id: string;- type: FromWebSocketMessageOneOfSixType;+ type: ChatStreamOneOfEightType;};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfSixType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfEightType.tssimilarity index 57%rename from js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfSixType.tsrename to js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfEightType.tsindex f20a9e3db3..40011ef600 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfSixType.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfEightType.ts@@ -5,10 +5,10 @@* OpenAPI spec version: 1.0.0*/-export type FromWebSocketMessageOneOfSixType =- (typeof FromWebSocketMessageOneOfSixType)[keyof typeof FromWebSocketMessageOneOfSixType];+export type ChatStreamOneOfEightType =+ (typeof ChatStreamOneOfEightType)[keyof typeof ChatStreamOneOfEightType];// eslint-disable-next-line @typescript-eslint/no-redeclare-export const FromWebSocketMessageOneOfSixType = {+export const ChatStreamOneOfEightType = {chat_message_response: 'chat_message_response',} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfFour.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfFour.tssimilarity index 57%rename from js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfFour.tsrename to js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfFour.tsindex 4cbe5aa943..5b461002a3 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfFour.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfFour.ts@@ -4,13 +4,13 @@* Document Cognition Service* OpenAPI spec version: 1.0.0*/-import type { FromWebSocketMessageOneOfFourType } from './fromWebSocketMessageOneOfFourType';+import type { ChatStreamOneOfFourType } from './chatStreamOneOfFourType';/*** Acknowledges that a message has been received for processing*/-export type FromWebSocketMessageOneOfFour = {+export type ChatStreamOneOfFour = {chat_id: string;message_id: string;- type: FromWebSocketMessageOneOfFourType;+ type: ChatStreamOneOfFourType;};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfFourType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfFourType.tssimilarity index 55%rename from js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfFourType.tsrename to js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfFourType.tsindex 633158e9a8..0c1c7eacae 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfFourType.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfFourType.ts@@ -5,10 +5,10 @@* OpenAPI spec version: 1.0.0*/-export type FromWebSocketMessageOneOfFourType =- (typeof FromWebSocketMessageOneOfFourType)[keyof typeof FromWebSocketMessageOneOfFourType];+export type ChatStreamOneOfFourType =+ (typeof ChatStreamOneOfFourType)[keyof typeof ChatStreamOneOfFourType];// eslint-disable-next-line @typescript-eslint/no-redeclare-export const FromWebSocketMessageOneOfFourType = {+export const ChatStreamOneOfFourType = {chat_message_ack: 'chat_message_ack',} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfOnefour.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfOnefour.tsnew file mode 100644index 0000000000..b47b220484--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfOnefour.ts@@ -0,0 +1,20 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++import type { ChatStreamOneOfOnefourNewModel } from './chatStreamOneOfOnefourNewModel';+import type { ChatStreamOneOfOnefourType } from './chatStreamOneOfOnefourType';+import type { Model } from './model';++/**+ * Notifies the client that the available models have changed+ */+export type ChatStreamOneOfOnefour = {+ available_models: Model[];+ chat_id: string;+ new_model?: ChatStreamOneOfOnefourNewModel;+ type: ChatStreamOneOfOnefourType;+};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfOnetwoNewModel.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfOnefourNewModel.tssimilarity index 71%rename from js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfOnetwoNewModel.tsrename to js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfOnefourNewModel.tsindex afdeffef66..3e46983815 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfOnetwoNewModel.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfOnefourNewModel.ts@@ -6,4 +6,4 @@*/import type { Model } from './model';-export type FromWebSocketMessageOneOfOnetwoNewModel = null | Model;+export type ChatStreamOneOfOnefourNewModel = null | Model;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfOnetwoType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfOnefourType.tssimilarity index 56%rename from js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfOnetwoType.tsrename to js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfOnefourType.tsindex 338b85406c..63433e5238 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfOnetwoType.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfOnefourType.ts@@ -5,10 +5,10 @@* OpenAPI spec version: 1.0.0*/-export type FromWebSocketMessageOneOfOnetwoType =- (typeof FromWebSocketMessageOneOfOnetwoType)[keyof typeof FromWebSocketMessageOneOfOnetwoType];+export type ChatStreamOneOfOnefourType =+ (typeof ChatStreamOneOfOnefourType)[keyof typeof ChatStreamOneOfOnefourType];// eslint-disable-next-line @typescript-eslint/no-redeclare-export const FromWebSocketMessageOneOfOnetwoType = {+export const ChatStreamOneOfOnefourType = {model_selection_changed: 'model_selection_changed',} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfOneseven.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfOnenine.tssimilarity index 52%rename from js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfOneseven.tsrename to js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfOnenine.tsindex 499aa79f9b..f9e5b761c2 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfOneseven.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfOnenine.ts@@ -4,14 +4,14 @@* Document Cognition Service* OpenAPI spec version: 1.0.0*/-import type { FromWebSocketMessageOneOfOnesevenType } from './fromWebSocketMessageOneOfOnesevenType';+import type { ChatStreamOneOfOnenineType } from './chatStreamOneOfOnenineType';/*** Status update*/-export type FromWebSocketMessageOneOfOneseven = {+export type ChatStreamOneOfOnenine = {chat_id: string;message: string;message_id: string;- type: FromWebSocketMessageOneOfOnesevenType;+ type: ChatStreamOneOfOnenineType;};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfOnesevenType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfOnenineType.tssimilarity index 55%rename from js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfOnesevenType.tsrename to js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfOnenineType.tsindex cdecf4ddad..73d76616d1 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfOnesevenType.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfOnenineType.ts@@ -5,10 +5,10 @@* OpenAPI spec version: 1.0.0*/-export type FromWebSocketMessageOneOfOnesevenType =- (typeof FromWebSocketMessageOneOfOnesevenType)[keyof typeof FromWebSocketMessageOneOfOnesevenType];+export type ChatStreamOneOfOnenineType =+ (typeof ChatStreamOneOfOnenineType)[keyof typeof ChatStreamOneOfOnenineType];// eslint-disable-next-line @typescript-eslint/no-redeclare-export const FromWebSocketMessageOneOfOnesevenType = {+export const ChatStreamOneOfOnenineType = {chat_message_status_update: 'chat_message_status_update',} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfOneseven.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfOneseven.tsnew file mode 100644index 0000000000..308c9da89d--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfOneseven.ts@@ -0,0 +1,13 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */+import type { ChatStreamOneOfOnesevenType } from './chatStreamOneOfOnesevenType';++export type ChatStreamOneOfOneseven = {+ chat_id: string;+ token_count: number;+ type: ChatStreamOneOfOnesevenType;+};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfOnefiveType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfOnesevenType.tssimilarity index 54%rename from js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfOnefiveType.tsrename to js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfOnesevenType.tsindex 8b959041dd..fc73e2c4f3 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfOnefiveType.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfOnesevenType.ts@@ -5,10 +5,10 @@* OpenAPI spec version: 1.0.0*/-export type FromWebSocketMessageOneOfOnefiveType =- (typeof FromWebSocketMessageOneOfOnefiveType)[keyof typeof FromWebSocketMessageOneOfOnefiveType];+export type ChatStreamOneOfOnesevenType =+ (typeof ChatStreamOneOfOnesevenType)[keyof typeof ChatStreamOneOfOnesevenType];// eslint-disable-next-line @typescript-eslint/no-redeclare-export const FromWebSocketMessageOneOfOnefiveType = {+export const ChatStreamOneOfOnesevenType = {token_count_changed: 'token_count_changed',} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfOnezero.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfOnetwo.tssimilarity index 55%rename from js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfOnezero.tsrename to js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfOnetwo.tsindex d8da2e2b5a..eed716e3a1 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfOnezero.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfOnetwo.ts@@ -4,14 +4,14 @@* Document Cognition Service* OpenAPI spec version: 1.0.0*/-import type { FromWebSocketMessageOneOfOnezeroType } from './fromWebSocketMessageOneOfOnezeroType';+import type { ChatStreamOneOfOnetwoType } from './chatStreamOneOfOnetwoType';/*** Indicates that a chat has been renamed*/-export type FromWebSocketMessageOneOfOnezero = {+export type ChatStreamOneOfOnetwo = {chat_id: string;name: string;stream_id: string;- type: FromWebSocketMessageOneOfOnezeroType;+ type: ChatStreamOneOfOnetwoType;};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfOnezeroType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfOnetwoType.tssimilarity index 53%rename from js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfOnezeroType.tsrename to js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfOnetwoType.tsindex 8f247208a9..2eeeaed9fd 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfOnezeroType.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfOnetwoType.ts@@ -5,10 +5,10 @@* OpenAPI spec version: 1.0.0*/-export type FromWebSocketMessageOneOfOnezeroType =- (typeof FromWebSocketMessageOneOfOnezeroType)[keyof typeof FromWebSocketMessageOneOfOnezeroType];+export type ChatStreamOneOfOnetwoType =+ (typeof ChatStreamOneOfOnetwoType)[keyof typeof ChatStreamOneOfOnetwoType];// eslint-disable-next-line @typescript-eslint/no-redeclare-export const FromWebSocketMessageOneOfOnezeroType = {+export const ChatStreamOneOfOnetwoType = {chat_renamed: 'chat_renamed',} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfEight.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfOnezero.tssimilarity index 57%rename from js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfEight.tsrename to js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfOnezero.tsindex 9de4a67983..db0e02d03b 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfEight.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfOnezero.ts@@ -4,14 +4,14 @@* Document Cognition Service* OpenAPI spec version: 1.0.0*/-import type { FromWebSocketMessageOneOfEightType } from './fromWebSocketMessageOneOfEightType';+import type { ChatStreamOneOfOnezeroType } from './chatStreamOneOfOnezeroType';/*** Indicates that a message has been finished*/-export type FromWebSocketMessageOneOfEight = {+export type ChatStreamOneOfOnezero = {chat_id: string;message_id: string;- type: FromWebSocketMessageOneOfEightType;+ type: ChatStreamOneOfOnezeroType;user_message_id: string;};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfEightType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfOnezeroType.tssimilarity index 56%rename from js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfEightType.tsrename to js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfOnezeroType.tsindex eef1e1b24d..42055c405b 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfEightType.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfOnezeroType.ts@@ -5,10 +5,10 @@* OpenAPI spec version: 1.0.0*/-export type FromWebSocketMessageOneOfEightType =- (typeof FromWebSocketMessageOneOfEightType)[keyof typeof FromWebSocketMessageOneOfEightType];+export type ChatStreamOneOfOnezeroType =+ (typeof ChatStreamOneOfOnezeroType)[keyof typeof ChatStreamOneOfOnezeroType];// eslint-disable-next-line @typescript-eslint/no-redeclare-export const FromWebSocketMessageOneOfEightType = {+export const ChatStreamOneOfOnezeroType = {chat_message_finished: 'chat_message_finished',} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfSix.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfSix.tsnew file mode 100644index 0000000000..441e9ccb43--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfSix.ts@@ -0,0 +1,21 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */+import type { ChatAttachmentWithName } from './chatAttachmentWithName';+import type { ChatStreamOneOfSixType } from './chatStreamOneOfSixType';++/**+ * The user message that initiated this stream, sent as the first item+so other clients can add it to their local chat state.+ */+export type ChatStreamOneOfSix = {+ attachments: ChatAttachmentWithName[];+ chat_id: string;+ content: string;+ message_id: string;+ stream_id: string;+ type: ChatStreamOneOfSixType;+};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfSixType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfSixType.tsnew file mode 100644index 0000000000..b8e5670bdd--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfSixType.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++export type ChatStreamOneOfSixType =+ (typeof ChatStreamOneOfSixType)[keyof typeof ChatStreamOneOfSixType];++// eslint-disable-next-line @typescript-eslint/no-redeclare+export const ChatStreamOneOfSixType = {+ chat_user_message: 'chat_user_message',+} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfThreeone.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfThreeone.tsnew file mode 100644index 0000000000..33d69b175d--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfThreeone.ts@@ -0,0 +1,12 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */+import type { ChatStreamOneOfThreeoneType } from './chatStreamOneOfThreeoneType';++export type ChatStreamOneOfThreeone = {+ stream_id: string;+ type: ChatStreamOneOfThreeoneType;+};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfTwonineType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfThreeoneType.tssimilarity index 52%rename from js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfTwonineType.tsrename to js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfThreeoneType.tsindex ac6a3645ae..92c4a09d9d 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfTwonineType.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfThreeoneType.ts@@ -5,10 +5,10 @@* OpenAPI spec version: 1.0.0*/-export type FromWebSocketMessageOneOfTwonineType =- (typeof FromWebSocketMessageOneOfTwonineType)[keyof typeof FromWebSocketMessageOneOfTwonineType];+export type ChatStreamOneOfThreeoneType =+ (typeof ChatStreamOneOfThreeoneType)[keyof typeof ChatStreamOneOfThreeoneType];// eslint-disable-next-line @typescript-eslint/no-redeclare-export const FromWebSocketMessageOneOfTwonineType = {+export const ChatStreamOneOfThreeoneType = {stream_end: 'stream_end',} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwofive.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwofive.tsnew file mode 100644index 0000000000..32d336055c--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwofive.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */+import type { ChatStreamOneOfTwofiveType } from './chatStreamOneOfTwofiveType';++export type ChatStreamOneOfTwofive = {+ type: ChatStreamOneOfTwofiveType;+};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfTwothreeType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwofiveType.tssimilarity index 51%rename from js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfTwothreeType.tsrename to js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwofiveType.tsindex 47ffaf22a4..12ca4baf4a 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfTwothreeType.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwofiveType.ts@@ -5,10 +5,10 @@* OpenAPI spec version: 1.0.0*/-export type FromWebSocketMessageOneOfTwothreeType =- (typeof FromWebSocketMessageOneOfTwothreeType)[keyof typeof FromWebSocketMessageOneOfTwothreeType];+export type ChatStreamOneOfTwofiveType =+ (typeof ChatStreamOneOfTwofiveType)[keyof typeof ChatStreamOneOfTwofiveType];// eslint-disable-next-line @typescript-eslint/no-redeclare-export const FromWebSocketMessageOneOfTwothreeType = {+export const ChatStreamOneOfTwofiveType = {pong: 'pong',} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwonine.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwonine.tsnew file mode 100644index 0000000000..0a02433a8f--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwonine.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */+import type { ChatStreamOneOfTwonineType } from './chatStreamOneOfTwonineType';++export type ChatStreamOneOfTwonine = {+ completion_id: string;+ content: string;+ done: boolean;+ type: ChatStreamOneOfTwonineType;+};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfTwosevenType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwonineType.tssimilarity index 55%rename from js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfTwosevenType.tsrename to js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwonineType.tsindex 061cc24e5e..35705a75c8 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfTwosevenType.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwonineType.ts@@ -5,10 +5,10 @@* OpenAPI spec version: 1.0.0*/-export type FromWebSocketMessageOneOfTwosevenType =- (typeof FromWebSocketMessageOneOfTwosevenType)[keyof typeof FromWebSocketMessageOneOfTwosevenType];+export type ChatStreamOneOfTwonineType =+ (typeof ChatStreamOneOfTwonineType)[keyof typeof ChatStreamOneOfTwonineType];// eslint-disable-next-line @typescript-eslint/no-redeclare-export const FromWebSocketMessageOneOfTwosevenType = {+export const ChatStreamOneOfTwonineType = {completion_stream_chunk: 'completion_stream_chunk',} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfOnenine.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwoone.tssimilarity index 74%rename from js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfOnenine.tsrename to js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwoone.tsindex 8a5e680988..3cb108192a 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfOnenine.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwoone.ts@@ -4,8 +4,9 @@* Document Cognition Service* OpenAPI spec version: 1.0.0*/++import type { ChatStreamOneOfTwooneType } from './chatStreamOneOfTwooneType';import type { ExtractionStatusEnum } from './extractionStatusEnum';-import type { FromWebSocketMessageOneOfOnenineType } from './fromWebSocketMessageOneOfOnenineType';/*** Acknowledges the request to get extraction status@@ -13,8 +14,8 @@ if the `status` field is 'incomplete', we need to await the extraction status upif the `status` field is 'empty', extraction is complete but text content is emptyif the `status` field is 'complete', the extraction is already complete*/-export type FromWebSocketMessageOneOfOnenine = {+export type ChatStreamOneOfTwoone = {attachment_id: string;status: ExtractionStatusEnum;- type: FromWebSocketMessageOneOfOnenineType;+ type: ChatStreamOneOfTwooneType;};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfOnenineType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwooneType.tssimilarity index 55%rename from js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfOnenineType.tsrename to js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwooneType.tsindex 2fcfccbe44..53a8b3e8c0 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfOnenineType.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwooneType.ts@@ -5,10 +5,10 @@* OpenAPI spec version: 1.0.0*/-export type FromWebSocketMessageOneOfOnenineType =- (typeof FromWebSocketMessageOneOfOnenineType)[keyof typeof FromWebSocketMessageOneOfOnenineType];+export type ChatStreamOneOfTwooneType =+ (typeof ChatStreamOneOfTwooneType)[keyof typeof ChatStreamOneOfTwooneType];// eslint-disable-next-line @typescript-eslint/no-redeclare-export const FromWebSocketMessageOneOfOnenineType = {+export const ChatStreamOneOfTwooneType = {extraction_status_ack: 'extraction_status_ack',} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfTwofive.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwoseven.tssimilarity index 53%rename from js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfTwofive.tsrename to js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwoseven.tsindex 176e4d4f4c..0073f7e68b 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfTwofive.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwoseven.ts@@ -4,14 +4,14 @@* Document Cognition Service* OpenAPI spec version: 1.0.0*/-import type { FromWebSocketMessageOneOfTwofiveType } from './fromWebSocketMessageOneOfTwofiveType';+import type { ChatStreamOneOfTwosevenType } from './chatStreamOneOfTwosevenType';/*** pdf completion*/-export type FromWebSocketMessageOneOfTwofive = {+export type ChatStreamOneOfTwoseven = {completion_id: string;content: string;done: boolean;- type: FromWebSocketMessageOneOfTwofiveType;+ type: ChatStreamOneOfTwosevenType;};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfTwofiveType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwosevenType.tssimilarity index 54%rename from js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfTwofiveType.tsrename to js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwosevenType.tsindex 812d23af95..0a062ac784 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfTwofiveType.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwosevenType.ts@@ -5,10 +5,10 @@* OpenAPI spec version: 1.0.0*/-export type FromWebSocketMessageOneOfTwofiveType =- (typeof FromWebSocketMessageOneOfTwofiveType)[keyof typeof FromWebSocketMessageOneOfTwofiveType];+export type ChatStreamOneOfTwosevenType =+ (typeof ChatStreamOneOfTwosevenType)[keyof typeof ChatStreamOneOfTwosevenType];// eslint-disable-next-line @typescript-eslint/no-redeclare-export const FromWebSocketMessageOneOfTwofiveType = {+export const ChatStreamOneOfTwosevenType = {completion_response: 'completion_response',} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfTwoone.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwothree.tssimilarity index 61%rename from js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfTwoone.tsrename to js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwothree.tsindex 9501978b67..dfefe6e90b 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfTwoone.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwothree.ts@@ -4,14 +4,15 @@* Document Cognition Service* OpenAPI spec version: 1.0.0*/++import type { ChatStreamOneOfTwothreeType } from './chatStreamOneOfTwothreeType';import type { ExtractionStatusEnum } from './extractionStatusEnum';-import type { FromWebSocketMessageOneOfTwooneType } from './fromWebSocketMessageOneOfTwooneType';/*** Status update for the extraction status*/-export type FromWebSocketMessageOneOfTwoone = {+export type ChatStreamOneOfTwothree = {attachment_id: string;status: ExtractionStatusEnum;- type: FromWebSocketMessageOneOfTwooneType;+ type: ChatStreamOneOfTwothreeType;};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfTwooneType.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwothreeType.tssimilarity index 56%rename from js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfTwooneType.tsrename to js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwothreeType.tsindex 7bc78c9ed2..b12e59264a 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfTwooneType.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/chatStreamOneOfTwothreeType.ts@@ -5,10 +5,10 @@* OpenAPI spec version: 1.0.0*/-export type FromWebSocketMessageOneOfTwooneType =- (typeof FromWebSocketMessageOneOfTwooneType)[keyof typeof FromWebSocketMessageOneOfTwooneType];+export type ChatStreamOneOfTwothreeType =+ (typeof ChatStreamOneOfTwothreeType)[keyof typeof ChatStreamOneOfTwothreeType];// eslint-disable-next-line @typescript-eslint/no-redeclare-export const FromWebSocketMessageOneOfTwooneType = {+export const ChatStreamOneOfTwothreeType = {extraction_status_update: 'extraction_status_update',} as const;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessage.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessage.tsdeleted file mode 100644index a3ddd720e5..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessage.ts+++ /dev/null@@ -1,36 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { FromWebSocketMessageOneOf } from './fromWebSocketMessageOneOf';-import type { FromWebSocketMessageOneOfEight } from './fromWebSocketMessageOneOfEight';-import type { FromWebSocketMessageOneOfFour } from './fromWebSocketMessageOneOfFour';-import type { FromWebSocketMessageOneOfOnefive } from './fromWebSocketMessageOneOfOnefive';-import type { FromWebSocketMessageOneOfOnenine } from './fromWebSocketMessageOneOfOnenine';-import type { FromWebSocketMessageOneOfOneseven } from './fromWebSocketMessageOneOfOneseven';-import type { FromWebSocketMessageOneOfOnetwo } from './fromWebSocketMessageOneOfOnetwo';-import type { FromWebSocketMessageOneOfOnezero } from './fromWebSocketMessageOneOfOnezero';-import type { FromWebSocketMessageOneOfSix } from './fromWebSocketMessageOneOfSix';-import type { FromWebSocketMessageOneOfTwofive } from './fromWebSocketMessageOneOfTwofive';-import type { FromWebSocketMessageOneOfTwonine } from './fromWebSocketMessageOneOfTwonine';-import type { FromWebSocketMessageOneOfTwoone } from './fromWebSocketMessageOneOfTwoone';-import type { FromWebSocketMessageOneOfTwoseven } from './fromWebSocketMessageOneOfTwoseven';-import type { FromWebSocketMessageOneOfTwothree } from './fromWebSocketMessageOneOfTwothree';--export type FromWebSocketMessage =- | FromWebSocketMessageOneOf- | FromWebSocketMessageOneOfFour- | FromWebSocketMessageOneOfSix- | FromWebSocketMessageOneOfEight- | FromWebSocketMessageOneOfOnezero- | FromWebSocketMessageOneOfOnetwo- | FromWebSocketMessageOneOfOnefive- | FromWebSocketMessageOneOfOneseven- | FromWebSocketMessageOneOfOnenine- | FromWebSocketMessageOneOfTwoone- | FromWebSocketMessageOneOfTwothree- | FromWebSocketMessageOneOfTwofive- | FromWebSocketMessageOneOfTwoseven- | FromWebSocketMessageOneOfTwonine;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfAllOf.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfAllOf.tsdeleted file mode 100644index 926b7c65a9..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfAllOf.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- */-import type { FromWebSocketMessageOneOfAllOfType } from './fromWebSocketMessageOneOfAllOfType';--export type FromWebSocketMessageOneOfAllOf = {- type: FromWebSocketMessageOneOfAllOfType;-};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfOnefive.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfOnefive.tsdeleted file mode 100644index dc655dd0fa..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfOnefive.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- */-import type { FromWebSocketMessageOneOfOnefiveType } from './fromWebSocketMessageOneOfOnefiveType';--export type FromWebSocketMessageOneOfOnefive = {- chat_id: string;- token_count: number;- type: FromWebSocketMessageOneOfOnefiveType;-};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfOnetwo.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfOnetwo.tsdeleted file mode 100644index 11ddb70e27..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfOnetwo.ts+++ /dev/null@@ -1,20 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */--import type { FromWebSocketMessageOneOfOnetwoNewModel } from './fromWebSocketMessageOneOfOnetwoNewModel';-import type { FromWebSocketMessageOneOfOnetwoType } from './fromWebSocketMessageOneOfOnetwoType';-import type { Model } from './model';--/**- * Notifies the client that the available models have changed- */-export type FromWebSocketMessageOneOfOnetwo = {- available_models: Model[];- chat_id: string;- new_model?: FromWebSocketMessageOneOfOnetwoNewModel;- type: FromWebSocketMessageOneOfOnetwoType;-};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfTwonine.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfTwonine.tsdeleted file mode 100644index 7c4ca146bd..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfTwonine.ts+++ /dev/null@@ -1,12 +0,0 @@-/**- * Generated by orval v7.13.0 🍺- * Do not edit manually.- * Document Cognition Service- * OpenAPI spec version: 1.0.0- */-import type { FromWebSocketMessageOneOfTwonineType } from './fromWebSocketMessageOneOfTwonineType';--export type FromWebSocketMessageOneOfTwonine = {- stream_id: string;- type: FromWebSocketMessageOneOfTwonineType;-};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfTwoseven.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfTwoseven.tsdeleted file mode 100644index 907371ad3c..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfTwoseven.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 { FromWebSocketMessageOneOfTwosevenType } from './fromWebSocketMessageOneOfTwosevenType';--export type FromWebSocketMessageOneOfTwoseven = {- completion_id: string;- content: string;- done: boolean;- type: FromWebSocketMessageOneOfTwosevenType;-};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfTwothree.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfTwothree.tsdeleted file mode 100644index 1ee7412eb3..0000000000--- a/js/app/packages/service-clients/service-cognition/generated/schemas/fromWebSocketMessageOneOfTwothree.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- */-import type { FromWebSocketMessageOneOfTwothreeType } from './fromWebSocketMessageOneOfTwothreeType';--export type FromWebSocketMessageOneOfTwothree = {- type: FromWebSocketMessageOneOfTwothreeType;-};diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/httpSendChatMessageRequest.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/httpSendChatMessageRequest.tsnew file mode 100644index 0000000000..b3d5b9bde1--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/httpSendChatMessageRequest.ts@@ -0,0 +1,30 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */+import type { HttpSendChatMessageRequestAdditionalInstructions } from './httpSendChatMessageRequestAdditionalInstructions';+import type { HttpSendChatMessageRequestAttachments } from './httpSendChatMessageRequestAttachments';+import type { HttpSendChatMessageRequestChatId } from './httpSendChatMessageRequestChatId';+import type { Model } from './model';+import type { ToolSet } from './toolSet';++/**+ * HTTP request payload for sending a chat message.+Unlike the WebSocket payload, this does not include stream_id as it's generated server-side.+ */+export interface HttpSendChatMessageRequest {+ /** Additional system instructions appended to the base system prompt */+ additional_instructions?: HttpSendChatMessageRequestAdditionalInstructions;+ /** Attachments for the message */+ attachments?: HttpSendChatMessageRequestAttachments;+ /** Id of the chat the message belongs to (optional - if not provided, a new chat is created) */+ chat_id?: HttpSendChatMessageRequestChatId;+ /** The content of the message */+ content: string;+ /** The model to respond with */+ model: Model;+ /** Which toolset to use. Defaults to `all` */+ toolset?: ToolSet;+}diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/httpSendChatMessageRequestAdditionalInstructions.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/httpSendChatMessageRequestAdditionalInstructions.tsnew file mode 100644index 0000000000..6dcce02365--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/httpSendChatMessageRequestAdditionalInstructions.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * Additional system instructions appended to the base system prompt+ */+export type HttpSendChatMessageRequestAdditionalInstructions = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/httpSendChatMessageRequestAttachments.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/httpSendChatMessageRequestAttachments.tsnew file mode 100644index 0000000000..bd29a03a0c--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/httpSendChatMessageRequestAttachments.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */+import type { ChatAttachmentWithName } from './chatAttachmentWithName';++/**+ * Attachments for the message+ */+export type HttpSendChatMessageRequestAttachments =+ | ChatAttachmentWithName[]+ | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/httpSendChatMessageRequestChatId.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/httpSendChatMessageRequestChatId.tsnew file mode 100644index 0000000000..260edd22f7--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/httpSendChatMessageRequestChatId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * Id of the chat the message belongs to (optional - if not provided, a new chat is created)+ */+export type HttpSendChatMessageRequestChatId = string | null;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 249c9848c4..766d5a20da 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@@ -42,6 +42,8 @@ export * from './chatHistory';export * from './chatHistoryBatchMessagesRequest';export * from './chatMessage';export * from './chatMessageContent';+export * from './chatMessageError';+export * from './chatMessageErrorStreamId';export * from './chatMessageModel';export * from './chatMessageWithAttachments';export * from './chatMessageWithAttachmentsModel';@@ -69,6 +71,39 @@ export * from './chatResponseWebCitationsItemItem1Item';export * from './chatResponseWebCitationsItemItem1ItemDescription';export * from './chatResponseWebCitationsItemItem1ItemFaviconUrl';export * from './chatResponseWebCitationsItemItem1ItemImageUrl';+export * from './chatStream';+export * from './chatStreamOneOf';+export * from './chatStreamOneOfAllOf';+export * from './chatStreamOneOfAllOfType';+export * from './chatStreamOneOfEight';+export * from './chatStreamOneOfEightType';+export * from './chatStreamOneOfFour';+export * from './chatStreamOneOfFourType';+export * from './chatStreamOneOfOnefour';+export * from './chatStreamOneOfOnefourNewModel';+export * from './chatStreamOneOfOnefourType';+export * from './chatStreamOneOfOnenine';+export * from './chatStreamOneOfOnenineType';+export * from './chatStreamOneOfOneseven';+export * from './chatStreamOneOfOnesevenType';+export * from './chatStreamOneOfOnetwo';+export * from './chatStreamOneOfOnetwoType';+export * from './chatStreamOneOfOnezero';+export * from './chatStreamOneOfOnezeroType';+export * from './chatStreamOneOfSix';+export * from './chatStreamOneOfSixType';+export * from './chatStreamOneOfThreeone';+export * from './chatStreamOneOfThreeoneType';+export * from './chatStreamOneOfTwofive';+export * from './chatStreamOneOfTwofiveType';+export * from './chatStreamOneOfTwonine';+export * from './chatStreamOneOfTwonineType';+export * from './chatStreamOneOfTwoone';+export * from './chatStreamOneOfTwooneType';+export * from './chatStreamOneOfTwoseven';+export * from './chatStreamOneOfTwosevenType';+export * from './chatStreamOneOfTwothree';+export * from './chatStreamOneOfTwothreeType';export * from './chatsResponse';export * from './chatTokenCount';export * from './chatUpdatedAt';@@ -100,37 +135,6 @@ export * from './extractionStatusEnumOneOfThreeType';export * from './extractionStatusEnumOneOfType';export * from './extractionStatusPayload';export * from './fileType';-export * from './fromWebSocketMessage';-export * from './fromWebSocketMessageOneOf';-export * from './fromWebSocketMessageOneOfAllOf';-export * from './fromWebSocketMessageOneOfAllOfType';-export * from './fromWebSocketMessageOneOfEight';-export * from './fromWebSocketMessageOneOfEightType';-export * from './fromWebSocketMessageOneOfFour';-export * from './fromWebSocketMessageOneOfFourType';-export * from './fromWebSocketMessageOneOfOnefive';-export * from './fromWebSocketMessageOneOfOnefiveType';-export * from './fromWebSocketMessageOneOfOnenine';-export * from './fromWebSocketMessageOneOfOnenineType';-export * from './fromWebSocketMessageOneOfOneseven';-export * from './fromWebSocketMessageOneOfOnesevenType';-export * from './fromWebSocketMessageOneOfOnetwo';-export * from './fromWebSocketMessageOneOfOnetwoNewModel';-export * from './fromWebSocketMessageOneOfOnetwoType';-export * from './fromWebSocketMessageOneOfOnezero';-export * from './fromWebSocketMessageOneOfOnezeroType';-export * from './fromWebSocketMessageOneOfSix';-export * from './fromWebSocketMessageOneOfSixType';-export * from './fromWebSocketMessageOneOfTwofive';-export * from './fromWebSocketMessageOneOfTwofiveType';-export * from './fromWebSocketMessageOneOfTwonine';-export * from './fromWebSocketMessageOneOfTwonineType';-export * from './fromWebSocketMessageOneOfTwoone';-export * from './fromWebSocketMessageOneOfTwooneType';-export * from './fromWebSocketMessageOneOfTwoseven';-export * from './fromWebSocketMessageOneOfTwosevenType';-export * from './fromWebSocketMessageOneOfTwothree';-export * from './fromWebSocketMessageOneOfTwothreeType';export * from './genericErrorResponse';export * from './genericSuccessResponse';export * from './getBatchPreviewRequest';@@ -153,6 +157,10 @@ export * from './getSimpleCompletionStreamPayload';export * from './getSimpleCompletionStreamPayloadContentDocumentIds';export * from './getSimpleCompletionStreamPayloadMaxTokens';export * from './getSimpleCompletionStreamPayloadModel';+export * from './httpSendChatMessageRequest';+export * from './httpSendChatMessageRequestAdditionalInstructions';+export * from './httpSendChatMessageRequestAttachments';+export * from './httpSendChatMessageRequestChatId';export * from './jwtPayload';export * from './messageWithAttachments';export * from './model';@@ -160,6 +168,7 @@ export * from './modelMetadata';export * from './newAttachment';export * from './newChatMessage';export * from './newChatMessageAttachments';+export * from './newChatMessageId';export * from './newMessageAttachment';export * from './patchChatRequest';export * from './patchChatRequestModel';@@ -177,6 +186,7 @@ export * from './sendChatMessagePayload';export * from './sendChatMessagePayloadAllOf';export * from './sendChatMessagePayloadAllOfAdditionalInstructions';export * from './sendChatMessagePayloadAllOfAttachments';+export * from './sendChatMessageResponse';export * from './sendCompletionPayload';export * from './sendCompletionPayloadAttachmentId';export * from './sendCompletionPayloadCompletionId';@@ -184,6 +194,9 @@ export * from './sendCompletionPayloadSelectedText';export * from './sharePermissionV2';export * from './sharePermissionV2ChannelSharePermissions';export * from './sharePermissionV2PublicAccessLevel';+export * from './simpleCompletionError';+export * from './simpleCompletionErrorCompletionId';+export * from './simpleCompletionResponse';export * from './stopChatMessagePayload';export * from './streamError';export * from './streamErrorOneOf';diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/newChatMessage.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/newChatMessage.tsindex 792f69fde5..7e674670d6 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/newChatMessage.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/newChatMessage.ts@@ -8,6 +8,7 @@import type { ChatMessageContent } from './chatMessageContent';import type { Model } from './model';import type { NewChatMessageAttachments } from './newChatMessageAttachments';+import type { NewChatMessageId } from './newChatMessageId';import type { Role } from './role';export interface NewChatMessage {@@ -16,6 +17,8 @@ export interface NewChatMessage {/** Content of the message */content: ChatMessageContent;createdAt: string;+ /** Optional pre-generated ID. If None, the database generates one. */+ id?: NewChatMessageId;/** The model used to generate the chat */model: Model;/** Whether the chat is from the user or system */diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/newChatMessageId.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/newChatMessageId.tsnew file mode 100644index 0000000000..3e64caf2b8--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/newChatMessageId.ts@@ -0,0 +1,11 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * Optional pre-generated ID. If None, the database generates one.+ */+export type NewChatMessageId = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/sendChatMessagePayloadAllOf.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/sendChatMessagePayloadAllOf.tsindex c2718c2adc..449a2feee4 100644--- a/js/app/packages/service-clients/service-cognition/generated/schemas/sendChatMessagePayloadAllOf.ts+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/sendChatMessagePayloadAllOf.ts@@ -21,7 +21,7 @@ export type SendChatMessagePayloadAllOf = {content: string;/** the chate model to respond with */model: Model;- /** you give me id, i give you id */+ /** Stream ID for tracking the response */stream_id: string;/** Which toolset to use. Defaults to `all` */toolset?: ToolSet;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/sendChatMessageResponse.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/sendChatMessageResponse.tsnew file mode 100644index 0000000000..821d4984e5--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/sendChatMessageResponse.ts@@ -0,0 +1,18 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * Response for initiating a chat message stream+ */+export interface SendChatMessageResponse {+ /** The chat ID (may differ from request if a new chat was created) */+ chat_id: string;+ /** The message ID for the AI response */+ message_id: string;+ /** The stream ID that will receive the response chunks (same as message_id) */+ stream_id: string;+}diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/simpleCompletionError.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/simpleCompletionError.tsnew file mode 100644index 0000000000..1c2e659c72--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/simpleCompletionError.ts@@ -0,0 +1,15 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */+import type { SimpleCompletionErrorCompletionId } from './simpleCompletionErrorCompletionId';++/**+ * Error response for simple completion endpoint+ */+export interface SimpleCompletionError {+ completion_id?: SimpleCompletionErrorCompletionId;+ error: string;+}diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/simpleCompletionErrorCompletionId.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/simpleCompletionErrorCompletionId.tsnew file mode 100644index 0000000000..d37024ca2f--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/simpleCompletionErrorCompletionId.ts@@ -0,0 +1,8 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++export type SimpleCompletionErrorCompletionId = string | null;diff --git a/js/app/packages/service-clients/service-cognition/generated/schemas/simpleCompletionResponse.ts b/js/app/packages/service-clients/service-cognition/generated/schemas/simpleCompletionResponse.tsnew file mode 100644index 0000000000..05345f91d8--- /dev/null+++ b/js/app/packages/service-clients/service-cognition/generated/schemas/simpleCompletionResponse.ts@@ -0,0 +1,14 @@+/**+ * Generated by orval v7.13.0 🍺+ * Do not edit manually.+ * Document Cognition Service+ * OpenAPI spec version: 1.0.0+ */++/**+ * Response for initiating a simple completion stream+ */+export interface SimpleCompletionResponse {+ /** The completion ID that will receive the response chunks */+ completion_id: string;+}diff --git a/js/app/packages/service-clients/service-cognition/openapi.json b/js/app/packages/service-clients/service-cognition/openapi.jsonindex 7f8571a8a4..f36331bf67 100644--- a/js/app/packages/service-clients/service-cognition/openapi.json+++ b/js/app/packages/service-clients/service-cognition/openapi.json@@ -1041,6 +1041,95 @@}}},+ "/stream/chat/message": {+ "post": {+ "tags": ["chat_message"],+ "summary": "Send a new chat message and stream the AI response.",+ "description": "This endpoint initiates a chat message and streams the response via the stream service.\nThe client should subscribe to the returned stream_id via connection_gateway to receive chunks.",+ "operationId": "send_chat_message",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/HttpSendChatMessageRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "Stream initiated successfully",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SendChatMessageResponse"+ }+ }+ }+ },+ "400": {+ "description": "Bad request",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ChatMessageError"+ }+ }+ }+ },+ "401": {+ "description": "Unauthorized"+ },+ "403": {+ "description": "Forbidden"+ }+ }+ }+ },+ "/stream/completion/simple": {+ "post": {+ "tags": ["simple_completion"],+ "summary": "Start a simple completion stream.",+ "description": "This endpoint initiates a completion and streams the response via the stream service.\nThe client should subscribe to the completion_id stream via connection_gateway to receive chunks.",+ "operationId": "simple_completion",+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/GetSimpleCompletionStreamPayload"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "Stream initiated successfully",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SimpleCompletionResponse"+ }+ }+ }+ },+ "400": {+ "description": "Bad request",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/SimpleCompletionError"+ }+ }+ }+ },+ "401": {+ "description": "Unauthorized"+ }+ }+ }+ },"/v2/chats/{chat_id}/permissions": {"get": {"tags": ["get_chat_permissions"],@@ -1452,6 +1541,19 @@}]},+ "ChatMessageError": {+ "type": "object",+ "description": "Error response for chat message endpoints",+ "required": ["error"],+ "properties": {+ "error": {+ "type": "string"+ },+ "stream_id": {+ "type": ["string", "null"]+ }+ }+ },"ChatMessageWithAttachments": {"type": "object","required": ["id", "content", "role", "attachments"],@@ -1675,294 +1777,90 @@}}},- "ChatsResponse": {- "type": "object",- "required": ["chats"],- "properties": {- "chats": {- "type": "array",- "items": {- "$ref": "#/components/schemas/Chat"- }- }- }- },- "ConversationRecord": {- "type": "object",- "required": ["chat_id", "title", "messages"],- "properties": {- "chat_id": {- "type": "string"- },- "messages": {- "type": "array",- "items": {- "$ref": "#/components/schemas/MessageWithAttachments"- }- },- "title": {- "type": "string"- }- }- },- "CopyChatRequest": {- "type": "object",- "required": ["name"],- "properties": {- "name": {- "type": "string"- }- }- },- "CreateChatRequest": {- "type": "object",- "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"]- },- "projectId": {- "type": ["string", "null"]- }- }- },- "CreateTextRequestBody": {- "type": "object",- "required": ["content"],- "properties": {- "content": {- "type": "string"- }- }- },- "CreateTextRequestParams": {- "type": "object",- "required": ["document_id"],- "properties": {- "document_id": {- "type": "string"- }- }- },- "DocumentCognitionServiceApiVersion": {- "type": "string",- "enum": ["v1", "v2"]- },- "DocumentReference": {+ "ChatStream": {"oneOf": [{"allOf": [{- "$ref": "#/components/schemas/UserPdfRect"+ "$ref": "#/components/schemas/WebSocketError",+ "description": "Misc error"},{"type": "object",- "required": ["kind"],+ "required": ["type"],"properties": {- "kind": {+ "type": {"type": "string",- "enum": ["pdf"]+ "enum": ["error"]}}}- ]- }- ]- },- "DocumentTextPart": {- "type": "object",- "required": ["id", "document_id", "reference"],- "properties": {- "document_id": {- "type": "string"- },- "id": {- "type": "string"+ ],+ "description": "Misc error"},- "reference": {- "$ref": "#/components/schemas/DocumentReference"- }- }- },- "EmptyResponse": {- "type": "object",- "description": "Empty response is required due to custom fetch forcing `response.json()`"- },- "ExtractionStatusEnum": {- "oneOf": [{"type": "object",- "required": ["type"],+ "description": "Acknowledges that a message has been received for processing",+ "required": ["message_id", "chat_id", "type"],"properties": {+ "chat_id": {+ "type": "string"+ },+ "message_id": {+ "type": "string"+ },"type": {"type": "string",- "enum": ["incomplete"]+ "enum": ["chat_message_ack"]}}},{"type": "object",- "required": ["type"],+ "description": "The user message that initiated this stream, sent as the first item\nso other clients can add it to their local chat state.",+ "required": [+ "stream_id",+ "chat_id",+ "message_id",+ "content",+ "attachments",+ "type"+ ],"properties": {+ "attachments": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ChatAttachmentWithName"+ }+ },+ "chat_id": {+ "type": "string"+ },+ "content": {+ "type": "string"+ },+ "message_id": {+ "type": "string"+ },+ "stream_id": {+ "type": "string"+ },"type": {"type": "string",- "enum": ["empty"]+ "enum": ["chat_user_message"]}}},{"type": "object",- "required": ["type"],- "properties": {- "type": {- "type": "string",- "enum": ["insufficient"]- }- }- },- {- "type": "object",- "required": ["type"],- "properties": {- "type": {- "type": "string",- "enum": ["complete"]- }- }- }- ]- },- "ExtractionStatusPayload": {- "type": "object",- "required": ["attachment_id"],- "properties": {- "attachment_id": {- "type": "string"- }- }- },- "FileType": {- "type": "string",- "description": "Generates a FileType enum and associated ContentType enum with their implementations.\n\nThis macro takes a list of tuples in the format:\n(Variant, \"extension\", \"mime_type\", CONTENT_TYPE_VARIANT)\n\nFor each tuple it generates:\n- A variant in the FileType enum\n- A variant in the ContentType enum\n- Implementations for:\n - FileType::to_str() - Converts FileType to extension string\n - FileType::from_str() - Converts extension string to FileType\n - From<FileType> for ContentType - Maps FileType to ContentType\n - ContentType::mime_type() - Gets MIME type for ContentType\n",- "enum": [- "docx",- "pdf",- "md",- "canvas",- "py",- "js",- "ts",- "jsx",- "tsx",- "json",- "html",- "css",- "xml",- "yaml",- "yml",- "sql",- "sh",- "bash",- "markdown",- "txt",- "csv",- "jpeg",- "jpg",- "png",- "gif",- "svg",- "webp",- "heic",- "heif",- "zip",- "tar",- "targz",- "tgz",- "gz",- "mp4",- "mkv",- "webm",- "avi",- "mov",- "wmv",- "mpg",- "mpeg",- "m4v",- "flv",- "f4v",- "threegp",- "xls",- "ppt",- "pptx",- "xlsx"- ]- },- "FromWebSocketMessage": {- "oneOf": [- {- "allOf": [- {- "$ref": "#/components/schemas/WebSocketError",- "description": "Misc error"- },- {- "type": "object",- "required": ["type"],- "properties": {- "type": {- "type": "string",- "enum": ["error"]- }- }- }- ],- "description": "Misc error"- },- {- "type": "object",- "description": "Acknowledges that a message has been received for processing",- "required": ["message_id", "chat_id", "type"],- "properties": {- "chat_id": {- "type": "string"- },- "message_id": {- "type": "string"- },- "type": {- "type": "string",- "enum": ["chat_message_ack"]- }- }- },- {- "type": "object",- "description": "Indicates a response from the chat completion API for a given message",- "required": [- "stream_id",- "message_id",- "chat_id",- "content",- "type"- ],+ "description": "Indicates a response from the chat completion API for a given message",+ "required": [+ "stream_id",+ "message_id",+ "chat_id",+ "content",+ "type"+ ],"properties": {"chat_id": {"type": "string"@@ -2187,6 +2085,246 @@}]},+ "ChatsResponse": {+ "type": "object",+ "required": ["chats"],+ "properties": {+ "chats": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/Chat"+ }+ }+ }+ },+ "ConversationRecord": {+ "type": "object",+ "required": ["chat_id", "title", "messages"],+ "properties": {+ "chat_id": {+ "type": "string"+ },+ "messages": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/MessageWithAttachments"+ }+ },+ "title": {+ "type": "string"+ }+ }+ },+ "CopyChatRequest": {+ "type": "object",+ "required": ["name"],+ "properties": {+ "name": {+ "type": "string"+ }+ }+ },+ "CreateChatRequest": {+ "type": "object",+ "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"]+ },+ "projectId": {+ "type": ["string", "null"]+ }+ }+ },+ "CreateTextRequestBody": {+ "type": "object",+ "required": ["content"],+ "properties": {+ "content": {+ "type": "string"+ }+ }+ },+ "CreateTextRequestParams": {+ "type": "object",+ "required": ["document_id"],+ "properties": {+ "document_id": {+ "type": "string"+ }+ }+ },+ "DocumentCognitionServiceApiVersion": {+ "type": "string",+ "enum": ["v1", "v2"]+ },+ "DocumentReference": {+ "oneOf": [+ {+ "allOf": [+ {+ "$ref": "#/components/schemas/UserPdfRect"+ },+ {+ "type": "object",+ "required": ["kind"],+ "properties": {+ "kind": {+ "type": "string",+ "enum": ["pdf"]+ }+ }+ }+ ]+ }+ ]+ },+ "DocumentTextPart": {+ "type": "object",+ "required": ["id", "document_id", "reference"],+ "properties": {+ "document_id": {+ "type": "string"+ },+ "id": {+ "type": "string"+ },+ "reference": {+ "$ref": "#/components/schemas/DocumentReference"+ }+ }+ },+ "EmptyResponse": {+ "type": "object",+ "description": "Empty response is required due to custom fetch forcing `response.json()`"+ },+ "ExtractionStatusEnum": {+ "oneOf": [+ {+ "type": "object",+ "required": ["type"],+ "properties": {+ "type": {+ "type": "string",+ "enum": ["incomplete"]+ }+ }+ },+ {+ "type": "object",+ "required": ["type"],+ "properties": {+ "type": {+ "type": "string",+ "enum": ["empty"]+ }+ }+ },+ {+ "type": "object",+ "required": ["type"],+ "properties": {+ "type": {+ "type": "string",+ "enum": ["insufficient"]+ }+ }+ },+ {+ "type": "object",+ "required": ["type"],+ "properties": {+ "type": {+ "type": "string",+ "enum": ["complete"]+ }+ }+ }+ ]+ },+ "ExtractionStatusPayload": {+ "type": "object",+ "required": ["attachment_id"],+ "properties": {+ "attachment_id": {+ "type": "string"+ }+ }+ },+ "FileType": {+ "type": "string",+ "description": "Generates a FileType enum and associated ContentType enum with their implementations.\n\nThis macro takes a list of tuples in the format:\n(Variant, \"extension\", \"mime_type\", CONTENT_TYPE_VARIANT)\n\nFor each tuple it generates:\n- A variant in the FileType enum\n- A variant in the ContentType enum\n- Implementations for:\n - FileType::to_str() - Converts FileType to extension string\n - FileType::from_str() - Converts extension string to FileType\n - From<FileType> for ContentType - Maps FileType to ContentType\n - ContentType::mime_type() - Gets MIME type for ContentType\n",+ "enum": [+ "docx",+ "pdf",+ "md",+ "canvas",+ "py",+ "js",+ "ts",+ "jsx",+ "tsx",+ "json",+ "html",+ "css",+ "xml",+ "yaml",+ "yml",+ "sql",+ "sh",+ "bash",+ "markdown",+ "txt",+ "csv",+ "jpeg",+ "jpg",+ "png",+ "gif",+ "svg",+ "webp",+ "heic",+ "heif",+ "zip",+ "tar",+ "targz",+ "tgz",+ "gz",+ "mp4",+ "mkv",+ "webm",+ "avi",+ "mov",+ "wmv",+ "mpg",+ "mpeg",+ "m4v",+ "flv",+ "f4v",+ "threegp",+ "xls",+ "ppt",+ "pptx",+ "xlsx"+ ]+ },"GenericErrorResponse": {"type": "object","required": ["error", "message"],@@ -2414,6 +2552,40 @@}}},+ "HttpSendChatMessageRequest": {+ "type": "object",+ "description": "HTTP request payload for sending a chat message.\nUnlike the WebSocket payload, this does not include stream_id as it's generated server-side.",+ "required": ["content", "model"],+ "properties": {+ "additional_instructions": {+ "type": ["string", "null"],+ "description": "Additional system instructions appended to the base system prompt"+ },+ "attachments": {+ "type": ["array", "null"],+ "items": {+ "$ref": "#/components/schemas/ChatAttachmentWithName"+ },+ "description": "Attachments for the message"+ },+ "chat_id": {+ "type": ["string", "null"],+ "description": "Id of the chat the message belongs to (optional - if not provided, a new chat is created)"+ },+ "content": {+ "type": "string",+ "description": "The content of the message"+ },+ "model": {+ "$ref": "#/components/schemas/Model",+ "description": "The model to respond with"+ },+ "toolset": {+ "$ref": "#/components/schemas/ToolSet",+ "description": "Which toolset to use. Defaults to `all`"+ }+ }+ },"JwtPayload": {"type": "object","required": ["token"],@@ -2506,6 +2678,10 @@"type": "string","format": "date-time"},+ "id": {+ "type": ["string", "null"],+ "description": "Optional pre-generated ID. If None, the database generates one."+ },"model": {"$ref": "#/components/schemas/Model","description": "The model used to generate the chat"@@ -2627,7 +2803,7 @@},"stream_id": {"type": "string",- "description": "you give me id, i give you id"+ "description": "Stream ID for tracking the response"},"toolset": {"$ref": "#/components/schemas/ToolSet",@@ -2637,6 +2813,25 @@}]},+ "SendChatMessageResponse": {+ "type": "object",+ "description": "Response for initiating a chat message stream",+ "required": ["stream_id", "message_id", "chat_id"],+ "properties": {+ "chat_id": {+ "type": "string",+ "description": "The chat ID (may differ from request if a new chat was created)"+ },+ "message_id": {+ "type": "string",+ "description": "The message ID for the AI response"+ },+ "stream_id": {+ "type": "string",+ "description": "The stream ID that will receive the response chunks (same as message_id)"+ }+ }+ },"SendCompletionPayload": {"type": "object","required": ["prompt"],@@ -2695,6 +2890,30 @@}}},+ "SimpleCompletionError": {+ "type": "object",+ "description": "Error response for simple completion endpoint",+ "required": ["error"],+ "properties": {+ "completion_id": {+ "type": ["string", "null"]+ },+ "error": {+ "type": "string"+ }+ }+ },+ "SimpleCompletionResponse": {+ "type": "object",+ "description": "Response for initiating a simple completion stream",+ "required": ["completion_id"],+ "properties": {+ "completion_id": {+ "type": "string",+ "description": "The completion ID that will receive the response chunks"+ }+ }+ },"StopChatMessagePayload": {"type": "object","required": ["stream_id"],diff --git a/js/app/packages/service-clients/service-cognition/websocket.ts b/js/app/packages/service-clients/service-cognition/websocket.tsindex 3331ae90a8..bb358f0778 100644--- a/js/app/packages/service-clients/service-cognition/websocket.ts+++ b/js/app/packages/service-clients/service-cognition/websocket.ts@@ -1,4 +1,5 @@import { createBlockEffect, inBlock } from '@core/block';+import { toast } from '@core/component/Toast/Toast';import { ENABLE_BEARER_TOKEN_AUTH } from '@core/constant/featureFlags';import { SERVER_HOSTS } from '@core/constant/servers';import { fetchToken, unsetTokenPromise } from '@core/util/fetchWithToken';@@ -15,16 +16,12 @@ import { createWebsocketStateSignal } from '@websocket/solid/state-signal';import type { Accessor } from 'solid-js';import { createRoot, createSignal } from 'solid-js';import type { StreamError } from './generated/schemas';-import type { FromWebSocketMessage } from './generated/schemas/fromWebSocketMessage';+import type { ChatStream } from './generated/schemas/chatStream';import type { ToWebSocketMessage } from './generated/schemas/toWebSocketMessage';-import { toast } from '@core/component/Toast/Toast';-export type CognitionWebsocket = Websocket<- ToWebSocketMessage,- FromWebSocketMessage->;+export type CognitionWebsocket = Websocket<ToWebSocketMessage, ChatStream>;-export type { StreamError, FromWebSocketMessage, ToWebSocketMessage };+export type { StreamError, ChatStream, ToWebSocketMessage };/*** Current state of the websocket connection@@ -55,9 +52,7 @@ async function resolveWsUrl() {}export const ws: CognitionWebsocket = new WebsocketBuilder(resolveWsUrl)- .withSerializer(- new JsonSerializer<ToWebSocketMessage, FromWebSocketMessage>()- )+ .withSerializer(new JsonSerializer<ToWebSocketMessage, ChatStream>()).withBackoff(new ConstantBackoff(2_000)).withMaxRetries(20).withHeartbeat({@@ -72,17 +67,12 @@ export const ws: CognitionWebsocket = new WebsocketBuilder(resolveWsUrl)export const state = createWebsocketStateSignal(ws);export function createCognitionWebsocketBlockEffect<- T extends FromWebSocketMessage['type'],->(- type: T,- callback: (data: Extract<FromWebSocketMessage, { type: T }>) => void-) {+ T extends ChatStream['type'],+>(type: T, callback: (data: Extract<ChatStream, { type: T }>) => void) {createBlockEffect(() => {- const wrappedCallback = createCallback((data: FromWebSocketMessage) => {+ const wrappedCallback = createCallback((data: ChatStream) => {if (data.type === type) {- return inBlock(callback)(- data as Extract<FromWebSocketMessage, { type: T }>- );+ return inBlock(callback)(data as Extract<ChatStream, { type: T }>);}});createSocketEffect(ws, wrappedCallback);@@ -92,13 +82,11 @@ export function createCognitionWebsocketBlockEffect</** Creates a typed DCS websocket effect scoped to any owner context.* Returns a dispose function that should be used to remove the effect.*/-export function createCognitionWebsocketEffect<- T extends FromWebSocketMessage['type'],->(+export function createCognitionWebsocketEffect<T extends ChatStream['type']>(type: T,- callback: (data: Extract<FromWebSocketMessage, { type: T }>) => void+ callback: (data: Extract<ChatStream, { type: T }>) => void) {- const wrappedCallback = createCallback((data: FromWebSocketMessage) => {+ const wrappedCallback = createCallback((data: ChatStream) => {if (data.type === type) {return callback(data as any);}@@ -110,9 +98,9 @@ export function createCognitionWebsocketEffect<type WithStreamId<T> = T extends { stream_id?: string } ? T : never;type Send = WithStreamId<ToWebSocketMessage>;-export type StreamItem = FromWebSocketMessage;+export type StreamItem = ChatStream;-export type WebsocketError = Extract<FromWebSocketMessage, { type: 'error' }>;+export type WebsocketError = Extract<ChatStream, { type: 'error' }>;// export type MessageStream = AsyncGenerator<Receive | WebsocketError>;// export type MessageStream = Accessor<StreamType>;@@ -135,7 +123,7 @@ export function createMessageStream(send: Send): MessageStream {let cleanup = () => {};- const handleMessage = (data: FromWebSocketMessage) => {+ const handleMessage = (data: ChatStream) => {if (isDone()) return;// not a stream messageif (typeof data !== 'object') return;diff --git a/js/app/packages/service-clients/service-connection/client.ts b/js/app/packages/service-clients/service-connection/client.tsindex 37777585d1..3d1483dd6b 100644--- a/js/app/packages/service-clients/service-connection/client.ts+++ b/js/app/packages/service-clients/service-connection/client.ts@@ -1,9 +1,11 @@import { ok } from '@core/util/maybeResult';import type { TrackEntityMessage } from './generated/schemas/trackEntityMessage';+import { clearStream } from './stream';import { ws } from './websocket';export const connectionGatewayClient = {async trackEntity(args: TrackEntityMessage) {+ if (args.action === 'close') clearStream(args.entity_id);ws.send({type: 'track_entity',...args,diff --git a/js/app/packages/service-clients/service-connection/stream.ts b/js/app/packages/service-clients/service-connection/stream.tsnew file mode 100644index 0000000000..952b5b9ac3--- /dev/null+++ b/js/app/packages/service-clients/service-connection/stream.ts@@ -0,0 +1,177 @@+import type { ChatStream } from '@service-cognition/generated/schemas';+import type { Accessor, Setter } from 'solid-js';+import { createSignal } from 'solid-js';+import { createStore, produce } from 'solid-js/store';+import { match } from 'ts-pattern';+import { createConnectionWebsocketEffect } from './websocket';+// entities that support streaming+export type StreamType = {+ chat: ChatStream;+};++export type StreamId = {+ entity_type: keyof StreamType;+ entity_id: string;+ // matches chat message id+ stream_id: string;+};++export type StreamItem<K extends keyof StreamType> = {+ id: StreamId;+ payload: StreamType[K];+};++export interface Stream<K extends keyof StreamType> {+ id: Accessor<StreamId | undefined>;+ data: Accessor<StreamType[K][]>;+ isDone: Accessor<boolean>;+}++type StreamController<K extends keyof StreamType> = {+ stream: Stream<K>;+ setData: Setter<StreamType[K][]>;+ setDone: () => void;+ id: StreamId;+};++function newController<K extends keyof StreamType>(+ id: StreamId+): StreamController<K> {+ const [data, setData] = createSignal<StreamType[K][]>([]);+ const [isDone, setIsDone] = createSignal(false);++ return {+ stream: {+ id: () => id,+ data,+ isDone,+ },+ id,+ setData,+ setDone: () => setIsDone(true),+ };+}++type StreamWithType = {+ stream: StreamController<keyof StreamType>;+ type: keyof StreamType;+};++// internal record of all streams+// map<entity_id, map<stream_id, StreamWithType>>;+const [streams, setStreams] = createStore<+ Record<string, Record<string, StreamWithType>>+>({});++export function clearStream(entity_id: string) {+ setStreams(+ produce((s) => {+ delete s[entity_id];+ })+ );+}++function streamIsDone(+ kind: keyof StreamType,+ item: StreamType[keyof StreamType]+): boolean {+ const isDone = match({ kind, item })+ .with({ kind: 'chat' }, ({ item }) => item.type === 'stream_end')+ .exhaustive();+ return isDone;+}++function addStream(+ entity_id: string,+ stream_id: string,+ entry: StreamWithType+) {+ setStreams(+ produce((s) => {+ if (!s[entity_id]) s[entity_id] = {};+ s[entity_id][stream_id] = entry;+ })+ );+}++// new message!+createConnectionWebsocketEffect((message) => {+ // not a stream+ if (message.type !== 'stream') return;++ let item: StreamItem<keyof StreamType>;+ try {+ item = JSON.parse(message.data);+ } catch {+ console.error('unparsable stream payload', message);+ return;+ }+ // if this is not the 1st item proces new item / add to stream+ if (+ streams[item.id.entity_id] &&+ streams[item.id.entity_id][item.id.stream_id]+ ) {+ const stream = streams[item.id.entity_id][item.id.stream_id];+ if (streamIsDone(item.id.entity_type, item.payload)) {+ stream.stream.setDone();+ } else {+ stream.stream.setData((p) => [...p, item.payload]);+ }+ }+ // is 1st item+ else {+ // new stream+ const newStream = newController(item.id);+ // process item+ if (streamIsDone(item.id.entity_type, item.payload)) {+ newStream.setDone();+ } else {+ newStream.setData([item.payload]);+ }+ addStream(item.id.entity_id, item.id.stream_id, {+ stream: newStream,+ type: item.id.entity_type,+ });+ }+});++// create a new stream or retreive existing stream+// if a new stream is created it represents the expectation that items will arive to that stream+export function subscribe<K extends keyof StreamType>(+ entity_type: K,+ entity_id: string,+ stream_id: string+): Stream<K> | undefined {+ if (streams[entity_id]?.[stream_id]) {+ if (streams[entity_id][stream_id].type !== entity_type) {+ console.error('unexpected stream type');+ return;+ }+ return streams[entity_id][stream_id].stream.stream as Stream<K>;+ } else {+ const controller = newController({+ entity_id,+ entity_type,+ stream_id,+ });+ addStream(entity_id, stream_id, {+ stream: controller,+ type: entity_type,+ });+ return controller.stream as Stream<K>;+ }+}++/** Reactive accessor for all streams on an entity. */+export function getEntityStreams<K extends keyof StreamType>(+ entity_type: K,+ entity_id: string+): Accessor<Stream<K>[]> {+ return () => {+ const entityStreams = streams[entity_id];+ if (!entityStreams) return [];+ return Object.values(entityStreams)+ .filter((s) => s.type === entity_type)+ .map((s) => s.stream.stream as Stream<K>);+ };+}diff --git a/rust/cloud-storage/Cargo.lock b/rust/cloud-storage/Cargo.lockindex 6b20d12620..25f497cedf 100644--- a/rust/cloud-storage/Cargo.lock+++ b/rust/cloud-storage/Cargo.lock@@ -2663,6 +2663,8 @@ dependencies = ["ai_tools","anyhow","async-openai",+ "async-stream",+ "async-trait","aws-sdk-secretsmanager","aws-sdk-sqs","axum",@@ -2697,9 +2699,11 @@ dependencies = ["macro_user_id","macro_uuid","model",+ "model-entity","models_dcs","models_opensearch","models_permissions",+ "redis","regex","reqwest","schemars",@@ -2712,6 +2716,7 @@ dependencies = ["sqlx","sqs_client","static_file_service_client",+ "stream","strum","sync_service_client","thiserror 2.0.17",diff --git a/rust/cloud-storage/document_cognition_service/Cargo.toml b/rust/cloud-storage/document_cognition_service/Cargo.tomlindex da83194dcc..d7b3779481 100644--- a/rust/cloud-storage/document_cognition_service/Cargo.toml+++ b/rust/cloud-storage/document_cognition_service/Cargo.toml@@ -23,11 +23,14 @@ path = "src/models_bin.rs"[features]local = []+local_auth = ["macro_middleware/local_auth"]local_queue = [][dependencies]aho-corasick = "1.1.3"+async-stream = { workspace = true }+async-trait = { workspace = true }ai = { path = "../ai" }ai_format = { path = "../ai_format" }ai_tools = { path = "../ai_tools" }@@ -56,6 +59,7 @@ lazy_static = { workspace = true }lexical_client = { path = "../lexical_client" }log = { workspace = true }macro_auth = { path = "../macro_auth" }+model-entity = { path = "../model-entity" }macro_cors = { path = "../macro_cors" }macro_db_client = { path = "../macro_db_client" }macro_entrypoint = { path = "../macro_entrypoint" }@@ -94,6 +98,13 @@ sqs_client = { path = "../sqs_client", default-features = false, features = ["document_text_extractor","search",] }+stream = { path = "../stream" }+redis = { workspace = true, features = [+ "streams",+ "aio",+ "tokio-comp",+ "tokio-native-tls-comp",+] }static_file_service_client = { path = "../static_file_service_client" }strum = { workspace = true }sync_service_client = { path = "../sync_service_client" }diff --git a/rust/cloud-storage/document_cognition_service/justfile b/rust/cloud-storage/document_cognition_service/justfileindex 615b31a68d..7063a08e41 100644--- a/rust/cloud-storage/document_cognition_service/justfile+++ b/rust/cloud-storage/document_cognition_service/justfile@@ -12,20 +12,20 @@ check:SQLX_OFFLINE=true cargo check# # Prepare DB for offline cache for docker image-# prepare_db:-# just sqlx::prepare_db {{ DATABASE_URL }}+prepare_db:+ just sqlx::prepare_db {{ DATABASE_URL }}run:- cargo run --features macro_middleware/local_auth+ cargo run --features local_authdebug:- RUST_LOG=document_cognition_service=debug,ai=debug,ai_tools=debug,anthropic=debug,info cargo run --features macro_middleware/local_auth+ RUST_LOG=document_cognition_service=debug,ai=debug,ai_tools=debug,anthropic=debug,info cargo run --features local_authtrace:- RUST_LOG=document_cognition_service=trace,ai=trace,ai_tools=debug,anthropic=debug,info, cargo run --features macro_middleware/local_auth+ RUST_LOG=document_cognition_service=trace,ai=trace,ai_tools=debug,anthropic=debug,info, cargo run --features local_authdev-lq:- cargo run --features macro_middleware/local_auth,local_queue+ cargo run --features local_auth,local_queuecreate-localstack:docker run -d --name localstack -p 4566:4566 -e SERVICES=sqs localstack/localstackdiff --git a/rust/cloud-storage/document_cognition_service/src/api/context.rs b/rust/cloud-storage/document_cognition_service/src/api/context.rsindex 5e64125146..035bbcfff6 100644--- a/rust/cloud-storage/document_cognition_service/src/api/context.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/context.rs@@ -12,6 +12,7 @@ use search_service_client::SearchServiceClient;use secretsmanager_client::LocalOrRemoteSecret;use sqlx::PgPool;use std::sync::{Arc, OnceLock};+use stream::domain::StreamRepo;pub type DcsScribe =ScribeClient<DocumentClient, ChannelClient, DcsClient, EmailClient, StaticFileClient>;@@ -29,10 +30,53 @@ pub struct ApiContext {pub config: Arc<Config>,pub internal_auth_key: LocalOrRemoteSecret<InternalApiSecretKey>,pub soup_service: Arc<ToolSoupService>,+ pub stream_repo: Arc<dyn StreamRepo>,}pub static GLOBAL_CONTEXT: OnceLock<ApiContext> = OnceLock::new();+#[cfg(test)]+mod mock_stream {+ use std::sync::Arc;+ use stream::domain::{ItemId, ItemStream, Result, StreamId, StreamRepo};+ use tokio::sync::broadcast::{self, Receiver};++ /// Mock StreamRepo for testing - does nothing but satisfies the interface+ pub struct MockStreamRepo {+ tx: broadcast::Sender<StreamId>,+ }++ impl MockStreamRepo {+ pub fn new() -> Arc<dyn StreamRepo> {+ let (tx, _) = broadcast::channel(16);+ Arc::new(Self { tx })+ }+ }++ #[async_trait::async_trait]+ impl StreamRepo for MockStreamRepo {+ async fn append(&self, _id: &StreamId, _payload: serde_json::Value) -> Result<ItemId> {+ Ok("mock-item-id".to_string())+ }++ async fn stream_from_beginning(&self, _id: &StreamId) -> Result<ItemStream> {+ Ok(Box::pin(futures::stream::empty()))+ }++ async fn close(&self, _id: &StreamId) -> Result<()> {+ Ok(())+ }++ async fn active_streams(&self, _entity_id: &str) -> Result<Vec<StreamId>> {+ Ok(vec![])+ }++ async fn notify(&self) -> Receiver<StreamId> {+ self.tx.subscribe()+ }+ }+}+#[cfg(test)]pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Arc<ApiContext> {use aws_sdk_sqs;@@ -139,6 +183,7 @@ pub async fn test_api_context(pool: sqlx::Pool<sqlx::Postgres>) -> std::sync::Arconfig: Arc::new(Config::new_empty_for_test()),internal_auth_key: LocalOrRemoteSecret::Local(InternalApiSecretKey::Comptime("testing")),soup_service,+ stream_repo: mock_stream::MockStreamRepo::new(),};Arc::new(api_context)}diff --git a/rust/cloud-storage/document_cognition_service/src/api/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/mod.rsindex 7f3b42819c..06e9bef9b6 100644--- a/rust/cloud-storage/document_cognition_service/src/api/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/mod.rs@@ -20,6 +20,7 @@ mod id_mapping;mod internal;mod models;mod preview;+pub mod stream;pub(crate) mod swagger;pub mod utils;mod ws;@@ -75,6 +76,7 @@ fn api_router(api_context: ApiContext) -> Router {let internal_router = Router::new().nest("/chats", chats::router(api_context.clone())).nest("/", ws::router(api_context.clone()))+ .nest("/stream", stream::router(api_context.clone())).nest("/internal",internal::router(api_context.clone()).nest("/notifications", notification::router()),diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rsnew file mode 100644index 0000000000..295327cdb0--- /dev/null+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/chat_message.rs@@ -0,0 +1,562 @@+//! HTTP endpoint for sending chat messages with streaming responses.++use crate::api::context::ApiContext;+use crate::api::utils::log;+use crate::api::ws::chat_message::ai_request::build_chat_completion_request;+use crate::api::ws::chat_message::toolset::choose_toolset;+use crate::api::ws::chat_message::{store_conversation_messages, store_incoming_message};+use crate::api::ws::chat_permissions;+use crate::api::ws::connection::MESSAGE_ABORT_MAP;+use crate::core::constants::DEFAULT_CHAT_NAME;+use crate::core::model::FALLBACK_MODEL;+use crate::model::ws::{ChatStream, JwtPayload, SendChatMessagePayload, StreamError, ToolSet};+use crate::service::ai::name::maybe_rename_chat;+use crate::service::get_chat::get_chat;+use ai::tool::ToolLoop;+use ai::tool::types::StreamPart;+use ai::types::{AssistantMessagePart, ChatMessage, Model};+use ai_tools::{AiToolSet, RequestContext, ToolServiceContext};+use async_stream::stream;+use axum::Json;+use axum::extract::{Extension, Request, State};+use axum::http::StatusCode;+use axum::middleware::Next;+use axum::response::IntoResponse;+use futures::StreamExt;+use macro_db_client::dcs::create_chat;+use macro_user_id::user_id::MacroUserIdStr;+use model::chat::ChatAttachmentWithName;+use model::user::UserContext;+use model_entity::EntityType;+use models_permissions::share_permission::SharePermissionV2;+use models_permissions::share_permission::access_level::AccessLevel;+use serde::{Deserialize, Serialize};+use std::fmt;+use std::sync::Arc;+use stream::domain::{PayloadStream, StreamId, StreamManagerExt};+use tokio::sync::oneshot;+use utoipa::ToSchema;++/// Raw Bearer token extracted from the Authorization header.+#[derive(Clone)]+pub(crate) struct BearerToken(pub String);++/// Middleware that extracts the raw access token from request headers or cookies+/// and inserts it into request extensions.+pub(crate) async fn attach_bearer_token(+ mut req: Request,+ next: Next,+) -> Result<axum::response::Response, StatusCode> {+ if cfg!(feature = "local_auth") {+ let token = macro_auth::headers::extract_access_token_from_request_headers(req.headers())+ .unwrap_or_default();+ req.extensions_mut().insert(BearerToken(token));+ return Ok(next.run(req).await);+ }++ let token = macro_auth::headers::extract_access_token_from_request_headers(req.headers())+ .map_err(|_| StatusCode::UNAUTHORIZED)?;++ req.extensions_mut().insert(BearerToken(token));+ Ok(next.run(req).await)+}++/// HTTP request payload for sending a chat message.+/// Unlike the WebSocket payload, this does not include stream_id as it's generated server-side.+#[derive(Debug, Serialize, Deserialize, ToSchema, Clone)]+pub struct HttpSendChatMessageRequest {+ /// The content of the message+ pub content: String,+ /// Id of the chat the message belongs to (optional - if not provided, a new chat is created)+ pub chat_id: Option<String>,+ /// The model to respond with+ pub model: Model,+ /// Additional system instructions appended to the base system prompt+ #[serde(skip_serializing_if = "Option::is_none")]+ pub additional_instructions: Option<String>,+ /// Attachments for the message+ #[serde(skip_serializing_if = "Option::is_none")]+ pub attachments: Option<Vec<ChatAttachmentWithName>>,+ /// Which toolset to use. Defaults to `all`+ #[serde(default)]+ pub toolset: ToolSet,+}++/// Response for initiating a chat message stream+#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct SendChatMessageResponse {+ /// The stream ID that will receive the response chunks (same as message_id)+ pub stream_id: String,+ /// The message ID for the AI response+ pub message_id: String,+ /// The chat ID (may differ from request if a new chat was created)+ pub chat_id: String,+}++/// Error response for chat message endpoints+#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct ChatMessageError {+ pub error: String,+ pub stream_id: Option<String>,+}++impl fmt::Display for ChatMessageError {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ write!(f, "{}", self.error)+ }+}++impl IntoResponse for ChatMessageError {+ fn into_response(self) -> axum::response::Response {+ (StatusCode::BAD_REQUEST, Json(self)).into_response()+ }+}++/// Send a new chat message and stream the AI response.+///+/// This endpoint initiates a chat message and streams the response via the stream service.+/// The client should subscribe to the returned stream_id via connection_gateway to receive chunks.+#[utoipa::path(+ post,+ path = "/stream/chat/message",+ request_body = HttpSendChatMessageRequest,+ responses(+ (status = 200, description = "Stream initiated successfully", body = SendChatMessageResponse),+ (status = 400, description = "Bad request", body = ChatMessageError),+ (status = 401, description = "Unauthorized"),+ (status = 403, description = "Forbidden"),+ )+)]+#[tracing::instrument(skip(state, user_context, bearer, request), fields(chat_id=?request.chat_id), err)]+pub async fn send_chat_message(+ State(state): State<ApiContext>,+ Extension(user_context): Extension<UserContext>,+ Extension(bearer): Extension<BearerToken>,+ Json(request): Json<HttpSendChatMessageRequest>,+) -> Result<Json<SendChatMessageResponse>, ChatMessageError> {+ let now = std::time::Instant::now();+ let ctx = Arc::new(state);+ let jwt_token = bearer.0;++ // Generate message_id which also serves as the stream_id+ let message_id = uuid::Uuid::new_v4().to_string();+ let stream_id = message_id.clone();++ // Validate user ID+ let user_id =+ MacroUserIdStr::try_from(user_context.user_id.clone()).map_err(|_| ChatMessageError {+ error: "Invalid user ID".to_string(),+ stream_id: Some(stream_id.clone()),+ })?;+ let user_id = Arc::new(user_id);++ // Determine chat_id - use provided or we'll create a new chat+ let requested_chat_id = request.chat_id.clone().unwrap_or_default();++ // Try to get the chat first - if it doesn't exist or no chat_id provided, create it+ let (chat, actual_chat_id) = if requested_chat_id.is_empty() {+ // No chat_id provided - create a new chat+ create_new_chat(&ctx, &user_id, request.model, &stream_id).await?+ } else {+ match get_chat(&ctx, &requested_chat_id, user_id.0.as_ref()).await {+ Ok(chat) => {+ // Chat exists - check permissions+ match chat_permissions::chat_access(+ &ctx,+ &user_context,+ &requested_chat_id,+ stream_id.clone(),+ )+ .await+ {+ Err(e) => {+ return Err(ChatMessageError {+ error: format!("Permission check failed: {:?}", e),+ stream_id: Some(stream_id),+ });+ }+ Ok(access) => match access {+ AccessLevel::View | AccessLevel::Comment => {+ return Err(ChatMessageError {+ error: "Insufficient permissions to send messages".to_string(),+ stream_id: Some(stream_id),+ });+ }+ _ => (),+ },+ };+ (chat, requested_chat_id)+ }+ Err(_) => {+ // Chat doesn't exist - create a new one+ tracing::info!(+ requested_chat_id = %requested_chat_id,+ "Chat not found, creating new chat"+ );+ create_new_chat(&ctx, &user_id, request.model, &stream_id).await?+ }+ }+ };++ let is_first_message = chat.messages.is_empty();+ let model = if request.model == Model::Claude45Opus {+ Model::Claude45Opus+ } else {+ FALLBACK_MODEL+ };++ // Convert HTTP request to internal payload for existing functions+ let payload = SendChatMessagePayload {+ stream_id: stream_id.clone(),+ content: request.content.clone(),+ chat_id: actual_chat_id.clone(),+ model: request.model,+ additional_instructions: request.additional_instructions.clone(),+ attachments: request.attachments.clone(),+ toolset: request.toolset.clone(),+ jwt: JwtPayload {+ token: jwt_token.clone(),+ },+ };++ // Store the incoming user message+ let user_message_id =+ store_incoming_message(ctx.clone(), user_id.0.as_ref(), &chat, model, &payload)+ .await+ .map_err(|err| {+ tracing::error!(error=?err, "failed to store incoming message");+ ChatMessageError {+ error: "Failed to store message".to_string(),+ stream_id: Some(stream_id.clone()),+ }+ })?;++ // Build the completion request+ let toolset = choose_toolset(&payload);+ let ai_request =+ build_chat_completion_request(ctx.clone(), &chat, &payload, toolset.prompt, &jwt_token)+ .await+ .map_err(|err| {+ tracing::error!(error=?err, "failed to build chat completion request");+ ChatMessageError {+ error: "Failed to build request".to_string(),+ stream_id: Some(stream_id.clone()),+ }+ })?;++ // Log time to send request+ log::log_timing(log::LatencyMetric::TimeToSendRequest, model, now.elapsed());++ // Create stream ID for publishing+ let durable_stream_id = StreamId {+ entity_type: EntityType::Chat,+ entity_id: actual_chat_id.clone(),+ stream_id: stream_id.clone(),+ };++ // Create a channel to receive new_messages after streaming completes+ let (messages_tx, messages_rx) = oneshot::channel::<Vec<ChatMessage>>();++ // Create the payload stream+ let payload_stream = create_chat_payload_stream(+ ctx.clone(),+ ai_request,+ toolset.toolset,+ user_id.clone(),+ jwt_token,+ actual_chat_id.clone(),+ message_id.clone(),+ stream_id.clone(),+ messages_tx,+ model,+ now,+ request.content.clone(),+ user_message_id,+ request.attachments.clone().unwrap_or_default(),+ );++ // Use the extension trait to handle spawning and stream management+ let stream_handle =+ ctx.stream_repo+ .clone()+ .from_async_stream(durable_stream_id, payload_stream, None);++ // Spawn post-processing task+ let ctx_clone = ctx.clone();+ let user_id_clone = user_id.clone();+ let chat_id = actual_chat_id.clone();+ let message_id_for_store = message_id.clone();++ tokio::spawn(async move {+ // Wait for the stream to complete+ let _ = stream_handle.await;++ // Get the new messages from the channel+ if let Ok(new_messages) = messages_rx.await {+ // Store conversation messages, using the pre-generated message_id for the first assistant message+ if let Err(err) = store_conversation_messages(+ ctx_clone.clone(),+ user_id_clone.0.as_ref(),+ &chat_id,+ new_messages,+ model,+ Some(message_id_for_store),+ )+ .await+ {+ tracing::error!(error=?err, "failed to store conversation messages");+ }++ // Maybe rename chat if first message+ if is_first_message+ && let Ok(new_name) =+ maybe_rename_chat(&chat_id, &ctx_clone, user_id_clone.0.as_ref())+ .await+ .inspect_err(|err| tracing::error!(error=?err, "failed to rename chat"))+ {+ tracing::info!(chat_id, new_name, "chat renamed after first message");+ }+ }+ });++ Ok(Json(SendChatMessageResponse {+ stream_id,+ message_id,+ chat_id: actual_chat_id,+ }))+}++/// Helper function to create a new chat+async fn create_new_chat(+ ctx: &Arc<ApiContext>,+ user_id: &Arc<MacroUserIdStr<'static>>,+ model: Model,+ stream_id: &str,+) -> Result<(crate::model::chats::ChatResponse, String), ChatMessageError> {+ let share_permission = SharePermissionV2::new_chat_share_permission();+ let new_chat_id = create_chat::create_chat_v2(+ &ctx.db,+ (**user_id).clone(),+ DEFAULT_CHAT_NAME,+ model,+ None, // project_id+ &share_permission,+ vec![], // attachments+ 0, // attachment_token_count+ true, // is_persistent+ )+ .await+ .map_err(|err| {+ tracing::error!(error=?err, "failed to create chat");+ ChatMessageError {+ error: "Failed to create chat".to_string(),+ stream_id: Some(stream_id.to_string()),+ }+ })?;++ // Get the newly created chat+ let chat = get_chat(ctx, &new_chat_id, user_id.0.as_ref())+ .await+ .map_err(|err| {+ tracing::error!(error=?err, "failed to get newly created chat");+ ChatMessageError {+ error: "Failed to get chat".to_string(),+ stream_id: Some(stream_id.to_string()),+ }+ })?;++ Ok((chat, new_chat_id))+}++/// Creates the AI stream and returns a PayloadStream that yields JSON values.+/// Returns Err if the stream should not be started (e.g., aborted).+#[expect(clippy::too_many_arguments, reason = "matches WS handler signature")]+fn create_chat_payload_stream(+ ctx: Arc<ApiContext>,+ request: ai::types::ChatCompletionRequest,+ toolset: AiToolSet,+ user_id: Arc<MacroUserIdStr<'static>>,+ jwt_token: String,+ chat_id: String,+ message_id: String,+ stream_id: String,+ messages_tx: oneshot::Sender<Vec<ChatMessage>>,+ model: Model,+ now: std::time::Instant,+ user_message_content: String,+ user_message_id: String,+ user_message_attachments: Vec<ChatAttachmentWithName>,+) -> PayloadStream {+ // Check for abort before starting+ if MESSAGE_ABORT_MAP.contains_key(&stream_id) {+ MESSAGE_ABORT_MAP.remove(&stream_id);+ let _ = messages_tx.send(vec![]);+ return Box::pin(futures::stream::empty());+ }++ tracing::trace!(request=?request, "streaming chat request");++ let tool_context = ToolServiceContext {+ email_service_client: ctx.email_service_client_external.clone(),+ search_service_client: ctx.search_service_client.clone(),+ scribe: ctx.scribe.clone(),+ soup_service: ctx.soup_service.clone(),+ };++ #[expect(deprecated)]+ let request_context = RequestContext {+ user_id: user_id.clone(),+ jwt: Arc::new(jwt_token),+ };++ let payload_stream = stream! {+ // Yield the user message as the first item so other clients can display it+ let user_msg = ChatStream::ChatUserMessage {+ stream_id: stream_id.clone(),+ chat_id: chat_id.clone(),+ message_id: user_message_id,+ content: user_message_content,+ attachments: user_message_attachments,+ };+ if let Ok(json) = serde_json::to_value(&user_msg) {+ yield json;+ }++ let client = ToolLoop::new(toolset, tool_context);+ let mut chat = client.chat();++ // Create the AI stream - yield error if it fails+ let mut ai_stream = match chat+ .send_message(request, request_context, user_id.as_ref().to_string())+ .await+ {+ Ok(stream) => stream,+ Err(e) => {+ tracing::error!(error=?e, "failed to create AI stream");+ let stream_error = match e {+ ai::types::AiError::ContextWindowExceeded => {+ StreamError::ModelContextOverflow {+ stream_id: stream_id.clone(),+ }+ }+ ai::types::AiError::Generic(_) => StreamError::InternalError {+ stream_id: stream_id.clone(),+ },+ };+ let error_msg = ChatStream::Error(+ crate::model::ws::WebSocketError::StreamError(stream_error),+ );+ if let Ok(json) = serde_json::to_value(&error_msg) {+ yield json;+ }+ let _ = messages_tx.send(vec![]);+ return;+ }+ };++ let mut is_first_token = false;++ while let Some(response) = ai_stream.next().await {+ tracing::trace!("{:#?}", response);++ // Log time to first token+ if !is_first_token {+ is_first_token = true;+ log::log_timing(log::LatencyMetric::TimeToFirstToken, model, now.elapsed());+ }++ // Check for abort during streaming+ if MESSAGE_ABORT_MAP.contains_key(&stream_id) {+ MESSAGE_ABORT_MAP.remove(&stream_id);+ let _ = messages_tx.send(vec![]);+ return;+ }++ match response {+ Ok(response_chunk) => {+ let message_part = match response_chunk {+ StreamPart::Content(content) => {+ if content.is_empty() {+ continue;+ }+ AssistantMessagePart::Text { text: content }+ }+ StreamPart::ToolCall(call) => AssistantMessagePart::ToolCall {+ name: call.name,+ json: call.json,+ id: call.id,+ },+ StreamPart::Usage(usage) => {+ tracing::debug!(record=?usage, "usage");+ continue;+ }+ StreamPart::ToolResponse(ai::tool::types::ToolResponse::Json {+ id,+ json,+ name,+ }) => AssistantMessagePart::ToolCallResponseJson { name, json, id },+ StreamPart::ToolResponse(ai::tool::types::ToolResponse::Err {+ id,+ name,+ description,+ }) => AssistantMessagePart::ToolCallErr {+ name,+ description,+ id,+ },+ };++ let response = ChatStream::ChatMessageResponse {+ stream_id: stream_id.clone(),+ chat_id: chat_id.clone(),+ message_id: message_id.clone(),+ content: message_part,+ };++ if let Ok(json) = serde_json::to_value(&response) {+ yield json;+ }+ }+ Err(e) => {+ tracing::error!(error=?e, "error in AI stream");+ // Map error type to appropriate StreamError+ let stream_error = match e {+ ai::types::AiError::ContextWindowExceeded => {+ StreamError::ModelContextOverflow {+ stream_id: stream_id.clone(),+ }+ }+ ai::types::AiError::Generic(_) => StreamError::InternalError {+ stream_id: stream_id.clone(),+ },+ };+ let error_msg = ChatStream::Error(+ crate::model::ws::WebSocketError::StreamError(stream_error),+ );+ if let Ok(json) = serde_json::to_value(&error_msg) {+ yield json;+ }+ let _ = messages_tx.send(vec![]);+ return;+ }+ }+ }++ // Drop the AI stream before accessing chat+ drop(ai_stream);++ // Send stream end message+ let end_msg = ChatStream::StreamEnd {+ stream_id: stream_id.clone(),+ };+ if let Ok(json) = serde_json::to_value(&end_msg) {+ yield json;+ }++ // Get new messages and send through channel+ let new_messages = chat.get_new_conversation_messages();+ let _ = messages_tx.send(new_messages);+ };++ Box::pin(payload_stream)+}diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/mod.rsnew file mode 100644index 0000000000..8c996eca4b--- /dev/null+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/mod.rs@@ -0,0 +1,33 @@+//! HTTP endpoints for streaming responses via the stream service.+//!+//! These endpoints replace the WebSocket-based streaming with HTTP POST requests+//! that publish to a durable stream. The connection_gateway handles delivery to clients.++pub mod chat_message;+pub mod simple_completion;++use axum::{Router, routing::post};+use tower::ServiceBuilder;++use crate::api::context::ApiContext;++/// Create the stream API router+pub fn router(state: ApiContext) -> Router<ApiContext> {+ Router::new()+ .route("/chat/message", post(chat_message::send_chat_message))+ .route(+ "/completion/simple",+ post(simple_completion::simple_completion),+ )+ .layer(+ ServiceBuilder::new()+ .layer(axum::middleware::from_fn(+ macro_middleware::auth::ensure_user_exists::handler,+ ))+ .layer(axum::middleware::from_fn_with_state(+ state,+ macro_middleware::user_permissions::attach_user_permissions::handler,+ ))+ .layer(axum::middleware::from_fn(chat_message::attach_bearer_token)),+ )+}diff --git a/rust/cloud-storage/document_cognition_service/src/api/stream/simple_completion.rs b/rust/cloud-storage/document_cognition_service/src/api/stream/simple_completion.rsnew file mode 100644index 0000000000..f0a6e568d6--- /dev/null+++ b/rust/cloud-storage/document_cognition_service/src/api/stream/simple_completion.rs@@ -0,0 +1,228 @@+//! HTTP endpoint for simple completions with streaming responses.++use crate::api::context::ApiContext;+use crate::core::constants::DEFAULT_MAX_TOKENS;+use crate::model::ws::{ChatStream, GetSimpleCompletionStreamPayload};+use crate::service::attachment::document::get_document_plaintext_content;+use ai::chat_stream::get_chat_stream;+use ai::types::{ChatStreamCompletionResponse, MessageBuilder, Model, RequestBuilder};+use async_stream::stream;+use axum::Json;+use axum::extract::{Extension, State};+use axum::http::StatusCode;+use axum::response::IntoResponse;+use macro_db_client::dcs::get_document;+use macro_db_client::dcs::get_document_text;+use model::user::UserContext;+use model_entity::EntityType;+use serde::{Deserialize, Serialize};+use std::fmt;+use std::sync::Arc;+use stream::domain::{StreamId, StreamManagerExt};+use utoipa::ToSchema;++const SIMPLE_COMPLETION_DEFAULT_MODEL: Model = Model::Claude45Haiku;++/// Response for initiating a simple completion stream+#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct SimpleCompletionResponse {+ /// The completion ID that will receive the response chunks+ pub completion_id: String,+}++/// Error response for simple completion endpoint+#[derive(Debug, Serialize, Deserialize, ToSchema)]+pub struct SimpleCompletionError {+ pub error: String,+ pub completion_id: Option<String>,+}++impl fmt::Display for SimpleCompletionError {+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {+ write!(f, "{}", self.error)+ }+}++impl IntoResponse for SimpleCompletionError {+ fn into_response(self) -> axum::response::Response {+ (StatusCode::BAD_REQUEST, Json(self)).into_response()+ }+}++/// Start a simple completion stream.+///+/// This endpoint initiates a completion and streams the response via the stream service.+/// The client should subscribe to the completion_id stream via connection_gateway to receive chunks.+#[utoipa::path(+ post,+ path = "/stream/completion/simple",+ request_body = GetSimpleCompletionStreamPayload,+ responses(+ (status = 200, description = "Stream initiated successfully", body = SimpleCompletionResponse),+ (status = 400, description = "Bad request", body = SimpleCompletionError),+ (status = 401, description = "Unauthorized"),+ )+)]+#[tracing::instrument(skip(state, user_context, payload), fields(completion_id=?payload.completion_id), err)]+pub async fn simple_completion(+ State(state): State<ApiContext>,+ Extension(user_context): Extension<UserContext>,+ Json(payload): Json<GetSimpleCompletionStreamPayload>,+) -> Result<Json<SimpleCompletionResponse>, SimpleCompletionError> {+ let ctx = Arc::new(state);+ let completion_id = payload.completion_id.clone();++ // Build system prompt with document content if provided+ let mut system_prompt: String = payload.prompt.clone();+ if let Some(document_ids) = &payload.content_document_ids {+ let db = &ctx.db;++ for document_id in document_ids.iter() {+ let document = get_document::get_document(db, document_id)+ .await+ .map_err(|e| {+ tracing::error!(error = %e, document_id, "failed to get document metadata");+ SimpleCompletionError {+ error: format!("Failed to get document: {}", e),+ completion_id: Some(completion_id.clone()),+ }+ })?;++ let document_content =+ if ["pdf", "docx"].contains(&document.unwrap().file_type.as_str()) {+ get_document_text::get_pdf_docx_document_text(db.clone(), document_id)+ .await+ .map_err(|e| {+ tracing::error!(error = %e, document_id, "failed to get document text");+ SimpleCompletionError {+ error: format!("Failed to get document text: {}", e),+ completion_id: Some(completion_id.clone()),+ }+ })?+ .content+ } else {+ get_document_plaintext_content(&ctx, document_id)+ .await+ .map_err(|e| {+ tracing::error!(error = %e, document_id, "failed to get document content");+ SimpleCompletionError {+ error: format!("Failed to get document content: {}", e),+ completion_id: Some(completion_id.clone()),+ }+ })?+ .text_content()+ .map_err(|e| {+ tracing::error!(error = %e, document_id, "failed to extract text content");+ SimpleCompletionError {+ error: format!("Failed to extract text content: {}", e),+ completion_id: Some(completion_id.clone()),+ }+ })?+ };++ if document_content+ .chars()+ .filter(|c| !c.is_whitespace())+ .count()+ > 0+ {+ system_prompt = format!(+ "{}\n\nDocument Content:\n{}",+ system_prompt, document_content+ );+ }+ }+ }++ // Create stream ID for publishing+ let durable_stream_id = StreamId {+ entity_type: EntityType::User,+ entity_id: user_context.user_id.clone(),+ stream_id: completion_id.clone(),+ };++ let model = payload.model.unwrap_or(SIMPLE_COMPLETION_DEFAULT_MODEL);+ let max_tokens = payload.max_tokens.unwrap_or(DEFAULT_MAX_TOKENS);+ let user_request = payload.user_request.clone();+ let completion_id_for_stream = completion_id.clone();++ // Create the payload stream that yields JSON values+ let payload_stream = stream! {+ let request = RequestBuilder::new()+ .model(model)+ .max_tokens(max_tokens)+ .messages(vec![+ MessageBuilder::new().user().content(user_request).build(),+ ])+ .system_prompt(system_prompt)+ .build();++ match get_chat_stream(request).await {+ Ok(mut ai_stream) => {+ use futures::StreamExt;+ let mut cumulative_content = String::new();++ while let Some(response) = ai_stream.next().await {+ match response {+ Ok(parts) => {+ for part in parts {+ let ChatStreamCompletionResponse::Content(content) = part;+ cumulative_content.push_str(&content.content);++ let message = ChatStream::CompletionStreamChunk {+ completion_id: completion_id_for_stream.clone(),+ content: cumulative_content.clone(),+ done: false,+ };++ if let Ok(json) = serde_json::to_value(&message) {+ yield json;+ }+ }+ }+ Err(e) => {+ tracing::error!(error=?e, "error in AI stream");+ let error_msg = ChatStream::CompletionStreamChunk {+ completion_id: completion_id_for_stream.clone(),+ content: format!("Error: {}", e),+ done: true,+ };+ if let Ok(json) = serde_json::to_value(&error_msg) {+ yield json;+ }+ return;+ }+ }+ }++ // Send final message with done: true+ let final_message = ChatStream::CompletionStreamChunk {+ completion_id: completion_id_for_stream.clone(),+ content: cumulative_content,+ done: true,+ };+ if let Ok(json) = serde_json::to_value(&final_message) {+ yield json;+ }+ }+ Err(e) => {+ tracing::error!(error=?e, "failed to create AI stream");+ let error_msg = ChatStream::CompletionStreamChunk {+ completion_id: completion_id_for_stream.clone(),+ content: format!("Error: {}", e),+ done: true,+ };+ if let Ok(json) = serde_json::to_value(&error_msg) {+ yield json;+ }+ }+ }+ };++ // Use the extension trait to handle spawning and stream management+ ctx.stream_repo+ .clone()+ .from_async_stream(durable_stream_id, Box::pin(payload_stream), None);++ Ok(Json(SimpleCompletionResponse { completion_id }))+}diff --git a/rust/cloud-storage/document_cognition_service/src/api/swagger.rs b/rust/cloud-storage/document_cognition_service/src/api/swagger.rsindex a4c2da07be..3a75c16997 100644--- a/rust/cloud-storage/document_cognition_service/src/api/swagger.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/swagger.rs@@ -20,6 +20,10 @@ use crate::{health,models::get_models,preview::get_batch_preview,+ stream::chat_message::{+ self, ChatMessageError, HttpSendChatMessageRequest, SendChatMessageResponse,+ },+ stream::simple_completion::{self, SimpleCompletionError, SimpleCompletionResponse},ws::{self},},model::{@@ -36,9 +40,9 @@ use crate::{models::AIModel,},ws::{- ExtractionStatusPayload, FromWebSocketMessage, SelectModelPayload,- SendChatMessagePayload, SendCompletionPayload, StopChatMessagePayload,- ToWebSocketMessage, WebSocketError,+ ChatStream, ExtractionStatusPayload, GetSimpleCompletionStreamPayload,+ SelectModelPayload, SendChatMessagePayload, SendCompletionPayload,+ StopChatMessagePayload, StreamError, ToWebSocketMessage, ToolSet, WebSocketError,},},};@@ -95,6 +99,8 @@ use utoipa::OpenApi;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,+ simple_completion::simple_completion,),components(schemas(@@ -153,7 +159,7 @@ use utoipa::OpenApi;// WebSocketToWebSocketMessage,- FromWebSocketMessage,+ ChatStream,SendChatMessagePayload,StopChatMessagePayload,WebSocketError,@@ -179,6 +185,16 @@ use utoipa::OpenApi;GetCompletionRequest,GetCompletionResponse,+ // Stream HTTP API+ HttpSendChatMessageRequest,+ SendChatMessageResponse,+ ChatMessageError,+ SimpleCompletionResponse,+ SimpleCompletionError,+ GetSimpleCompletionStreamPayload,+ StreamError,+ ToolSet,+// Toolsai::tool::schema::ToolSchema,ai::tool::schema::ToolSchemas,diff --git a/rust/cloud-storage/document_cognition_service/src/api/ws/chat_message/mod.rs b/rust/cloud-storage/document_cognition_service/src/api/ws/chat_message/mod.rsindex 5a5366de77..bcbd128f7e 100644--- a/rust/cloud-storage/document_cognition_service/src/api/ws/chat_message/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/ws/chat_message/mod.rs@@ -1,5 +1,5 @@-mod ai_request;-mod toolset;+pub mod ai_request;+pub mod toolset;use crate::api::ws::connection::{MESSAGE_ABORT_MAP, ws_send};use crate::core::model::FALLBACK_MODEL;@@ -10,7 +10,7 @@ use crate::{context::ApiContext,utils::{log, search},},- model::ws::{FromWebSocketMessage, SendChatMessagePayload},+ model::ws::{ChatStream, SendChatMessagePayload},service::{ai::name::maybe_rename_chat, get_chat::get_chat},};@@ -42,6 +42,7 @@ pub async fn store_incoming_message() -> Result<String> {let created_at = chrono::Utc::now();let new_chat_message = NewChatMessage {+ id: None,content: ChatMessageContent::Text(incoming_message.content.clone()),role: Role::User,// Attach the current chat attachments to the user message@@ -91,7 +92,7 @@ pub async fn stream_chat_response(user_id: Arc<MacroUserIdStr<'static>>,request: ChatCompletionRequest,toolset: AiToolSet,- sender: &UnboundedSender<FromWebSocketMessage>,+ sender: &UnboundedSender<ChatStream>,chat_id: &str,message_id: &str,connection_id: &str,@@ -154,7 +155,7 @@ pub async fn stream_chat_response(let message_part = AssistantMessagePart::Text { text: content };// Send to websocket- let response = FromWebSocketMessage::ChatMessageResponse {+ let response = ChatStream::ChatMessageResponse {stream_id: stream_id.to_string(),chat_id: chat_id.to_string(),message_id: message_id.to_string(),@@ -169,7 +170,7 @@ pub async fn stream_chat_response(id: call.id,};- let response = FromWebSocketMessage::ChatMessageResponse {+ let response = ChatStream::ChatMessageResponse {stream_id: stream_id.to_string(),chat_id: chat_id.to_string(),message_id: message_id.to_string(),@@ -185,7 +186,7 @@ pub async fn stream_chat_response(ws_send(sender,- FromWebSocketMessage::ChatMessageResponse {+ ChatStream::ChatMessageResponse {stream_id: stream_id.to_string(),message_id: message_id.to_string(),chat_id: chat_id.to_string(),@@ -206,7 +207,7 @@ pub async fn stream_chat_response(ws_send(sender,- FromWebSocketMessage::ChatMessageResponse {+ ChatStream::ChatMessageResponse {stream_id: stream_id.to_string(),message_id: message_id.to_string(),chat_id: chat_id.to_string(),@@ -226,7 +227,8 @@ pub async fn stream_chat_response(Ok(StreamChatResponse { new_messages })}-/// Stores multiple conversation messages to the database+/// Stores multiple conversation messages to the database.+/// If `first_message_id` is provided, the first assistant message will use that ID.#[tracing::instrument(err, skip(ctx, messages), fields(chat_id=?chat_id, message_count=messages.len()))]pub async fn store_conversation_messages(ctx: Arc<ApiContext>,@@ -234,17 +236,28 @@ pub async fn store_conversation_messages(chat_id: &str,messages: Vec<ChatMessage>,model: Model,+ first_message_id: Option<String>,) -> Result<Vec<String>> {if messages.is_empty() {return Ok(vec![]);}let mut message_ids = Vec::new();+ let mut first_id_used = false;let created_at = chrono::Utc::now();for message in messages {+ // Use the pre-generated ID for the first assistant message+ let id = if !first_id_used && message.role == Role::Assistant {+ first_id_used = true;+ first_message_id.clone()+ } else {+ None+ };+let new_chat_message = model::chat::NewChatMessage {+ id,content: message.content,role: message.role,attachments: None, // New messages from streaming don't have attachments (they are asssistant messages)@@ -276,7 +289,7 @@ pub async fn store_conversation_messages(/// Handles incoming messages of type `send_message`#[tracing::instrument(skip(ctx, sender, incoming_message, jwt_token, user_id), fields(chat_id=?incoming_message.chat_id, stream_id=?incoming_message.stream_id))]pub async fn handle_send_chat_message(- sender: &UnboundedSender<FromWebSocketMessage>,+ sender: &UnboundedSender<ChatStream>,ctx: Arc<ApiContext>,message_id: String,incoming_message: SendChatMessagePayload,@@ -359,7 +372,7 @@ pub async fn handle_send_chat_message(ws_send(sender,- FromWebSocketMessage::StreamEnd {+ ChatStream::StreamEnd {stream_id: incoming_message.stream_id.clone(),},)@@ -373,6 +386,7 @@ pub async fn handle_send_chat_message(&incoming_message.chat_id,new_messages,model,+ None,).await.map_err(|err| {@@ -390,7 +404,7 @@ pub async fn handle_send_chat_message({ws_send(sender,- FromWebSocketMessage::ChatRenamed {+ ChatStream::ChatRenamed {chat_id: incoming_message.chat_id.clone(),stream_id: incoming_message.stream_id.clone(),name: new_name,diff --git a/rust/cloud-storage/document_cognition_service/src/api/ws/completion.rs b/rust/cloud-storage/document_cognition_service/src/api/ws/completion.rsindex 233d5737c9..8e0eb4e15c 100644--- a/rust/cloud-storage/document_cognition_service/src/api/ws/completion.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/ws/completion.rs@@ -19,7 +19,7 @@ use crate::{api::context::ApiContext,core::constants::DEFAULT_MAX_TOKENS,core::model::{COMPLETION_CONTEXT_WINDOW, COMPLETION_MODEL},- model::ws::{FromWebSocketMessage, SendCompletionPayload, WebSocketError},+ model::ws::{ChatStream, SendCompletionPayload, WebSocketError},service::attachment::document::get_document_plaintext_content,};@@ -162,7 +162,7 @@ async fn build_completion_request(#[instrument(skip(sender), err)]async fn stream_completion(request: ChatCompletionRequest,- sender: &UnboundedSender<FromWebSocketMessage>,+ sender: &UnboundedSender<ChatStream>,completion_id: &str,user_id: &str,) -> Result<()> {@@ -177,7 +177,7 @@ async fn stream_completion(let ChatStreamCompletionResponse::Content(content) = part;response_message.push_str(&content.content);- let response = FromWebSocketMessage::CompletionResponse {+ let response = ChatStream::CompletionResponse {completion_id: completion_id.to_string(),content: response_message.clone(),done: false,@@ -189,7 +189,7 @@ async fn stream_completion(ws_send(sender,- FromWebSocketMessage::CompletionResponse {+ ChatStream::CompletionResponse {completion_id: completion_id.to_string(),content: response_message,done: true,@@ -202,7 +202,7 @@ async fn stream_completion(#[tracing::instrument(skip_all, fields(user_id, completion_id=?payload.completion_id), err)]pub async fn send_completion_handler(ctx: Arc<ApiContext>,- sender: &UnboundedSender<FromWebSocketMessage>,+ sender: &UnboundedSender<ChatStream>,payload: &SendCompletionPayload,user_id: &str,) -> Result<(), WebSocketError> {diff --git a/rust/cloud-storage/document_cognition_service/src/api/ws/connection.rs b/rust/cloud-storage/document_cognition_service/src/api/ws/connection.rsindex 7c0aefc885..eb26776110 100644--- a/rust/cloud-storage/document_cognition_service/src/api/ws/connection.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/ws/connection.rs@@ -29,7 +29,7 @@ use crate::{simple_completion::handle_simple_completion,},},- model::ws::{FromWebSocketMessage, StreamError, ToWebSocketMessage, WebSocketError},+ model::ws::{ChatStream, StreamError, ToWebSocketMessage, WebSocketError},};use super::attachment_permissions::ensure_user_attachment_access;@@ -41,7 +41,7 @@ pub static MESSAGE_ABORT_MAP: LazyLock<DashMap<String, bool>> =std::sync::LazyLock::new(DashMap::new);/// Maps a connection id to a websocket sender-pub static CONNECTION_MAP: LazyLock<DashMap<String, WeakUnboundedSender<FromWebSocketMessage>>> =+pub static CONNECTION_MAP: LazyLock<DashMap<String, WeakUnboundedSender<ChatStream>>> =std::sync::LazyLock::new(DashMap::new);#[utoipa::path(@@ -67,7 +67,7 @@ pub async fn ws_handler(#[tracing::instrument()]async fn process_incoming_message(msg: &Message,- message_sender: &UnboundedSender<FromWebSocketMessage>,+ message_sender: &UnboundedSender<ChatStream>,) -> Result<Option<ToWebSocketMessage>> {// Need to make sure we properly handle Control Frames like Close, Ping, Pongmatch msg {@@ -75,7 +75,7 @@ async fn process_incoming_message(Message::Text(text) => {// Handle heartbeat ping messagesif text == "ping" {- ws_send(message_sender, FromWebSocketMessage::Pong)?;+ ws_send(message_sender, ChatStream::Pong)?;return Ok(None);}@@ -115,7 +115,7 @@ async fn handle_websocket_connection(// message_sender handles sending messages between threads which are forwarded to the websocket// message_receiver handles receiving messages between threads which are forwarded to the websocket- let (message_sender, mut message_receiver) = mpsc::unbounded_channel::<FromWebSocketMessage>();+ let (message_sender, mut message_receiver) = mpsc::unbounded_channel::<ChatStream>();// store a WeakUnboundedSender in the map// this ensures that the sender is not kept alive by the map@@ -193,7 +193,7 @@ async fn handle_websocket_connection(if let Err(err) =ensure_user_attachment_access(&ctx, user_context.clone(), attachments).await{- ws_send(&message_sender_clone, FromWebSocketMessage::Error(err)).ok();+ ws_send(&message_sender_clone, ChatStream::Error(err)).ok();continue;}@@ -205,7 +205,7 @@ async fn handle_websocket_connection(| UserQuotaError::UnableToGetUserPermissions| UserQuotaError::UnableToGetUserQuota => ws_send(&message_sender_clone,- FromWebSocketMessage::Error(WebSocketError::StreamError(+ ChatStream::Error(WebSocketError::StreamError(StreamError::InternalError {stream_id: payload.stream_id,},@@ -213,7 +213,7 @@ async fn handle_websocket_connection(),UserQuotaError::ExceededMaxChatMessages => ws_send(&message_sender_clone,- FromWebSocketMessage::Error(WebSocketError::StreamError(+ ChatStream::Error(WebSocketError::StreamError(StreamError::PaymentRequired {stream_id: payload.stream_id,},@@ -230,7 +230,7 @@ async fn handle_websocket_connection(Err(_) => {ws_send(&message_sender_clone,- FromWebSocketMessage::Error(WebSocketError::StreamError(+ ChatStream::Error(WebSocketError::StreamError(StreamError::InternalError {stream_id: payload.stream_id.clone(),},@@ -253,14 +253,14 @@ async fn handle_websocket_connection(.await{Err(e) => {- ws_send(&message_sender_clone, FromWebSocketMessage::Error(e)).ok();+ ws_send(&message_sender_clone, ChatStream::Error(e)).ok();continue;}Ok(access) => match access {AccessLevel::View | AccessLevel::Comment => {ws_send(&message_sender_clone,- FromWebSocketMessage::Error(WebSocketError::StreamError(+ ChatStream::Error(WebSocketError::StreamError(StreamError::Unauthorized {stream_id: payload.stream_id,},@@ -286,7 +286,7 @@ async fn handle_websocket_connection(&jwt_token)) => {if let Err(err) = result {- ws_send(&message_sender_clone, FromWebSocketMessage::Error(err.into())).ok();+ ws_send(&message_sender_clone, ChatStream::Error(err.into())).ok();}}}@@ -299,7 +299,7 @@ async fn handle_websocket_connection(Err(_) => {ws_send(&message_sender_clone,- FromWebSocketMessage::Error(WebSocketError::StreamError(+ ChatStream::Error(WebSocketError::StreamError(StreamError::InternalError {stream_id: payload.stream_id.clone(),},@@ -322,14 +322,14 @@ async fn handle_websocket_connection(.await{Err(e) => {- ws_send(&message_sender_clone, FromWebSocketMessage::Error(e)).ok();+ ws_send(&message_sender_clone, ChatStream::Error(e)).ok();continue;}Ok(access) => match access {AccessLevel::View | AccessLevel::Comment => {ws_send(&message_sender_clone,- FromWebSocketMessage::Error(WebSocketError::StreamError(+ ChatStream::Error(WebSocketError::StreamError(StreamError::Unauthorized {stream_id: payload.stream_id,},@@ -352,11 +352,7 @@ async fn handle_websocket_connection().await{- ws_send(- &message_sender_clone,- FromWebSocketMessage::Error(err.into()),- )- .ok();+ ws_send(&message_sender_clone, ChatStream::Error(err.into())).ok();}});}@@ -372,7 +368,7 @@ async fn handle_websocket_connection(details: Some(err.to_string()),}){- ws_send(&message_sender_clone, FromWebSocketMessage::Error(err)).ok();+ ws_send(&message_sender_clone, ChatStream::Error(err)).ok();}}ToWebSocketMessage::ExtractionStatus(payload) => {@@ -386,7 +382,7 @@ async fn handle_websocket_connection(.await.map_err(|_err| WebSocketError::ExtractionStatusFailed { attachment_id }){- ws_send(&message_sender_clone, FromWebSocketMessage::Error(err)).ok();+ ws_send(&message_sender_clone, ChatStream::Error(err)).ok();}}ToWebSocketMessage::SendCompletion(payload) => {@@ -399,7 +395,7 @@ async fn handle_websocket_connection().await{- ws_send(&message_sender_clone, FromWebSocketMessage::Error(err)).ok();+ ws_send(&message_sender_clone, ChatStream::Error(err)).ok();}}ToWebSocketMessage::GetSimpleCompletionStream(payload) => {@@ -412,7 +408,7 @@ async fn handle_websocket_connection().await{- ws_send(&message_sender_clone, FromWebSocketMessage::Error(err)).ok();+ ws_send(&message_sender_clone, ChatStream::Error(err)).ok();}}};@@ -452,8 +448,8 @@ impl From<WsSendError> for AiError {/// Sends a message over the websocket channel#[tracing::instrument(skip(sender), err)]pub fn ws_send(- sender: &UnboundedSender<FromWebSocketMessage>,- message: FromWebSocketMessage,+ sender: &UnboundedSender<ChatStream>,+ message: ChatStream,) -> Result<(), WsSendError> {sender.send(message).map_err(|_| WsSendError)}diff --git a/rust/cloud-storage/document_cognition_service/src/api/ws/edit_message.rs b/rust/cloud-storage/document_cognition_service/src/api/ws/edit_message.rsindex 7f0c5d8fc1..ba424003ed 100644--- a/rust/cloud-storage/document_cognition_service/src/api/ws/edit_message.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/ws/edit_message.rs@@ -1,6 +1,6 @@use crate::{api::{context::ApiContext, utils::search},- model::ws::{FromWebSocketMessage, SendChatMessagePayload, StreamWebSocketError},+ model::ws::{ChatStream, SendChatMessagePayload, StreamWebSocketError},service::get_chat::get_chat,};@@ -18,7 +18,7 @@ use tokio::sync::mpsc::UnboundedSender;#[tracing::instrument(skip(ctx, sender, jwt_token, incoming_message, user_id))]pub async fn handle_edit_last_user_message(ctx: Arc<ApiContext>,- sender: &UnboundedSender<FromWebSocketMessage>,+ sender: &UnboundedSender<ChatStream>,incoming_message: SendChatMessagePayload,user_id: Arc<MacroUserIdStr<'static>>,connection_id: &str,@@ -58,7 +58,7 @@ pub async fn handle_edit_last_user_message(ws_send(sender,- FromWebSocketMessage::ChatMessageAck {+ ChatStream::ChatMessageAck {message_id: message_id.clone(),chat_id: incoming_message.chat_id.clone(),},diff --git a/rust/cloud-storage/document_cognition_service/src/api/ws/extraction_status.rs b/rust/cloud-storage/document_cognition_service/src/api/ws/extraction_status.rsindex 6eb653172e..1b24af81e1 100644--- a/rust/cloud-storage/document_cognition_service/src/api/ws/extraction_status.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/ws/extraction_status.rs@@ -13,7 +13,7 @@ use tokio::sync::mpsc::UnboundedSender;use crate::{api::context::{ApiContext, GLOBAL_CONTEXT},- model::ws::{ExtractionStatusPayload, FromWebSocketMessage, WebSocketError},+ model::ws::{ChatStream, ExtractionStatusPayload, WebSocketError},service::attachment::document::get_document_plaintext_content,};@@ -45,7 +45,7 @@ static ATTACHMENT_POLLING_MAP: LazyLock<DashMap<String, DashMap<String, Instant>#[tracing::instrument(skip(sender, ctx), fields(attachment_id=?payload.attachment_id, connection_id=connection_id))]pub async fn extraction_status_handler(- sender: &UnboundedSender<FromWebSocketMessage>,+ sender: &UnboundedSender<ChatStream>,ctx: Arc<ApiContext>,connection_id: &str,payload: ExtractionStatusPayload,@@ -80,7 +80,7 @@ pub async fn extraction_status_handler(ws_send(sender,- FromWebSocketMessage::ExtractionStatusAck {+ ChatStream::ExtractionStatusAck {attachment_id: payload.attachment_id.clone(),status: extraction_status.into(),},@@ -217,7 +217,7 @@ pub fn spawn_poller() {if extraction_status != ExtractionStatusEnum::Incomplete {ws_send(&sender,- FromWebSocketMessage::ExtractionStatusUpdate {+ ChatStream::ExtractionStatusUpdate {attachment_id: attachment_id.clone(),status: extraction_status.into(),},@@ -233,7 +233,7 @@ pub fn spawn_poller() {// polling it.ws_send(&sender,- FromWebSocketMessage::Error(WebSocketError::ExtractionStatusFailed {+ ChatStream::Error(WebSocketError::ExtractionStatusFailed {attachment_id: attachment_id.to_string(),}),)diff --git a/rust/cloud-storage/document_cognition_service/src/api/ws/simple_completion.rs b/rust/cloud-storage/document_cognition_service/src/api/ws/simple_completion.rsindex f7b678f3bb..affab17acd 100644--- a/rust/cloud-storage/document_cognition_service/src/api/ws/simple_completion.rs+++ b/rust/cloud-storage/document_cognition_service/src/api/ws/simple_completion.rs@@ -1,7 +1,7 @@/* A completion without a chat or attachments */use crate::api::context::ApiContext;use crate::core::constants::DEFAULT_MAX_TOKENS;-use crate::model::ws::{FromWebSocketMessage, GetSimpleCompletionStreamPayload, WebSocketError};+use crate::model::ws::{ChatStream, GetSimpleCompletionStreamPayload, WebSocketError};use crate::service::attachment::document::get_document_plaintext_content;use ai::chat_stream::get_chat_stream;use ai::types::{ChatStreamCompletionResponse, MessageBuilder, Model, RequestBuilder};@@ -18,7 +18,7 @@ const SIMPLE_COMPLETION_DEFAULT_MODEL: Model = Model::OpenAIGPT4oMini;#[tracing::instrument(skip(ctx, payload, sender))]pub async fn handle_simple_completion(ctx: Arc<ApiContext>,- sender: &UnboundedSender<FromWebSocketMessage>,+ sender: &UnboundedSender<ChatStream>,payload: &GetSimpleCompletionStreamPayload,user_id: &str,) -> Result<(), WebSocketError> {@@ -84,7 +84,7 @@ pub async fn handle_simple_completion(for part in parts {let ChatStreamCompletionResponse::Content(content) = part;cumulative_content.push_str(&content.content);- let message = FromWebSocketMessage::CompletionStreamChunk {+ let message = ChatStream::CompletionStreamChunk {completion_id: payload.completion_id.clone(),content: cumulative_content.clone(),done: false,@@ -97,7 +97,7 @@ pub async fn handle_simple_completion(})?;}}- let message = FromWebSocketMessage::CompletionStreamChunk {+ let message = ChatStream::CompletionStreamChunk {completion_id: payload.completion_id.clone(),content: cumulative_content.clone(),done: true,diff --git a/rust/cloud-storage/document_cognition_service/src/config.rs b/rust/cloud-storage/document_cognition_service/src/config.rsindex bb386a6243..83e9cd739d 100644--- a/rust/cloud-storage/document_cognition_service/src/config.rs+++ b/rust/cloud-storage/document_cognition_service/src/config.rs@@ -42,6 +42,8 @@ pub struct Config {pub authentication_service_url: String,/// authentication service secret key (for soup service)pub authentication_service_secret_key: String,+ /// Redis URL for stream service+ pub redis_url: String,}impl Config {@@ -101,6 +103,8 @@ impl Config {let authentication_service_secret_key = std::env::var("AUTHENTICATION_SERVICE_SECRET_KEY").context("AUTHENTICATION_SERVICE_SECRET_KEY must be provided")?;+ let redis_url = std::env::var("REDIS_URL").context("REDIS_URL must be provided")?;+Ok(Config {database_url,port,@@ -120,6 +124,7 @@ impl Config {static_file_service_url,authentication_service_url,authentication_service_secret_key,+ redis_url,})}@@ -144,6 +149,7 @@ impl Config {static_file_service_url: Default::default(),authentication_service_url: Default::default(),authentication_service_secret_key: Default::default(),+ redis_url: Default::default(),}}}diff --git a/rust/cloud-storage/document_cognition_service/src/main.rs b/rust/cloud-storage/document_cognition_service/src/main.rsindex ad36d91920..5e080cf81a 100644--- a/rust/cloud-storage/document_cognition_service/src/main.rs+++ b/rust/cloud-storage/document_cognition_service/src/main.rs@@ -23,6 +23,7 @@ use soup::outbound::pg_soup_repo::PgSoupRepo;use sqlx::postgres::PgPoolOptions;use static_file_service_client::StaticFileServiceClient;use std::sync::Arc;+use stream::outbound::redis::RedisStreamRepo;use sync_service_client::SyncServiceClient;mod api;@@ -171,6 +172,16 @@ async fn main() -> anyhow::Result<()> {tracing::info!("initialized soup service");+ // Initialize Redis client for stream service+ let redis_client =+ redis::Client::open(config.redis_url.as_str()).context("failed to create redis client")?;+ let stream_repo = RedisStreamRepo::new(redis_client)+ .await+ .map_err(|e| anyhow::anyhow!("failed to create stream repo: {}", e))?+ .obj();++ tracing::info!("initialized stream repo");+api::setup_and_serve(ApiContext {db: db.clone(),email_service_client_external: Arc::new(EmailServiceClientExternal::new(@@ -199,6 +210,7 @@ async fn main() -> anyhow::Result<()> {config: Arc::new(config),internal_auth_key,soup_service,+ stream_repo,}).await.context("failed to setup and serve api")?;diff --git a/rust/cloud-storage/document_cognition_service/src/model/ws/mod.rs b/rust/cloud-storage/document_cognition_service/src/model/ws/mod.rsindex 506577bada..e5e1503bfc 100644--- a/rust/cloud-storage/document_cognition_service/src/model/ws/mod.rs+++ b/rust/cloud-storage/document_cognition_service/src/model/ws/mod.rs@@ -20,7 +20,7 @@ pub enum ToolSet {#[derive(Deserialize, Serialize, ToSchema, Debug, Clone)]pub struct SendChatMessagePayload {- /// you give me id, i give you id+ /// Stream ID for tracking the responsepub stream_id: String,/// The content of the messagepub content: String,@@ -148,7 +148,7 @@ impl From<macro_db_client::dcs::get_document_text::ExtractionStatusEnum> for Ext#[derive(Serialize, Deserialize, ToSchema, Debug, Clone)]#[serde(tag = "type", rename_all = "snake_case")]-pub enum FromWebSocketMessage {+pub enum ChatStream {/// Misc errorError(WebSocketError),@@ -158,6 +158,16 @@ pub enum FromWebSocketMessage {chat_id: String,},+ /// The user message that initiated this stream, sent as the first item+ /// so other clients can add it to their local chat state.+ ChatUserMessage {+ stream_id: String,+ chat_id: String,+ message_id: String,+ content: String,+ attachments: Vec<ChatAttachmentWithName>,+ },+/// Indicates a response from the chat completion API for a given messageChatMessageResponse {stream_id: String,@@ -243,10 +253,10 @@ impl TryInto<ToWebSocketMessage> for Message {}}-impl From<FromWebSocketMessage> for Message {- fn from(val: FromWebSocketMessage) -> Self {+impl From<ChatStream> for Message {+ fn from(val: ChatStream) -> Self {match val {- FromWebSocketMessage::Pong => Message::Text("pong".to_string()),+ ChatStream::Pong => Message::Text("pong".to_string()),_ => {let payload = serde_json::to_string(&val).unwrap();Message::Text(payload)diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-062a45b8e7d65006120b1369981c4e04e513e99855ca9dab076768d43e189a80.json b/rust/cloud-storage/macro_db_client/.sqlx/query-062a45b8e7d65006120b1369981c4e04e513e99855ca9dab076768d43e189a80.jsonnew file mode 100644index 0000000000..22a0249ea8--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-062a45b8e7d65006120b1369981c4e04e513e99855ca9dab076768d43e189a80.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO \"ChatMessage\" (\"id\", \"chatId\", \"content\", \"role\", \"model\", \"createdAt\", \"updatedAt\")\n VALUES ($1, $2, $3, $4, $5, $6, $7)\n RETURNING id;\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Text",+ "Jsonb",+ "Text",+ "Text",+ "Timestamp",+ "Timestamp"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "062a45b8e7d65006120b1369981c4e04e513e99855ca9dab076768d43e189a80"+}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75.json b/rust/cloud-storage/macro_db_client/.sqlx/query-1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75.jsonnew file mode 100644index 0000000000..d2b084cf10--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75.json@@ -0,0 +1,17 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n SELECT \n u.id,\n u.entity_id,\n 'TASK'::property_entity_type,\n u.property_definition_id,\n u.values\n FROM UNNEST(\n $1::UUID[],\n $2::TEXT[],\n $3::UUID[],\n $4::JSONB[]\n ) AS u(id, entity_id, property_definition_id, values)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO UPDATE SET \n values = EXCLUDED.values,\n updated_at = NOW()\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "UuidArray",+ "TextArray",+ "UuidArray",+ "JsonbArray"+ ]+ },+ "nullable": []+ },+ "hash": "1435acbba365796ddcb6ddbef86f4ebf664cffc44082996f6b60a60373c28f75"+}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c.json b/rust/cloud-storage/macro_db_client/.sqlx/query-63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c.jsonnew file mode 100644index 0000000000..6d97183829--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c.json@@ -0,0 +1,16 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n SELECT \n u.id,\n u.entity_id,\n 'TASK'::property_entity_type,\n u.property_definition_id,\n NULL\n FROM UNNEST(\n $1::UUID[],\n $2::TEXT[],\n $3::UUID[]\n ) AS u(id, entity_id, property_definition_id)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO NOTHING\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "UuidArray",+ "TextArray",+ "UuidArray"+ ]+ },+ "nullable": []+ },+ "hash": "63492b018803ce26db5891964a0f52f37d2f54bd8243265c6561f4423af8617c"+}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-73765c8127d3e56106f1549372dc7da6ba15584e762a9f609af8f48705a86f5c.json b/rust/cloud-storage/macro_db_client/.sqlx/query-73765c8127d3e56106f1549372dc7da6ba15584e762a9f609af8f48705a86f5c.jsonnew file mode 100644index 0000000000..d0932f3682--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-73765c8127d3e56106f1549372dc7da6ba15584e762a9f609af8f48705a86f5c.json@@ -0,0 +1,27 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO \"ChatMessage\" (\"chatId\", \"content\", \"role\", \"model\", \"createdAt\", \"updatedAt\")\n VALUES ($1, $2, $3, $4, $5, $6)\n RETURNING id;\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "id",+ "type_info": "Text"+ }+ ],+ "parameters": {+ "Left": [+ "Text",+ "Jsonb",+ "Text",+ "Text",+ "Timestamp",+ "Timestamp"+ ]+ },+ "nullable": [+ false+ ]+ },+ "hash": "73765c8127d3e56106f1549372dc7da6ba15584e762a9f609af8f48705a86f5c"+}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4.json b/rust/cloud-storage/macro_db_client/.sqlx/query-9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4.jsonnew file mode 100644index 0000000000..9d717fa5f9--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4.json@@ -0,0 +1,28 @@+{+ "db_name": "PostgreSQL",+ "query": "\n SELECT property_definition_id, values\n FROM entity_properties\n WHERE entity_id = $1\n AND entity_type = 'TASK'\n ",+ "describe": {+ "columns": [+ {+ "ordinal": 0,+ "name": "property_definition_id",+ "type_info": "Uuid"+ },+ {+ "ordinal": 1,+ "name": "values",+ "type_info": "Jsonb"+ }+ ],+ "parameters": {+ "Left": [+ "Text"+ ]+ },+ "nullable": [+ false,+ true+ ]+ },+ "hash": "9cd40fbb1ade51e9e0d49792839d1a363cada017252a6f653c2272608189bcc4"+}diff --git a/rust/cloud-storage/macro_db_client/.sqlx/query-f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069.json b/rust/cloud-storage/macro_db_client/.sqlx/query-f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069.jsonnew file mode 100644index 0000000000..182e0858ba--- /dev/null+++ b/rust/cloud-storage/macro_db_client/.sqlx/query-f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069.json@@ -0,0 +1,18 @@+{+ "db_name": "PostgreSQL",+ "query": "\n INSERT INTO entity_properties (id, entity_id, entity_type, property_definition_id, values)\n SELECT \n u.id,\n u.entity_id,\n u.entity_type::property_entity_type,\n u.property_definition_id,\n u.values\n FROM UNNEST(\n $1::UUID[],\n $2::TEXT[],\n $3::TEXT[],\n $4::UUID[],\n $5::JSONB[]\n ) AS u(id, entity_id, entity_type, property_definition_id, values)\n ON CONFLICT (entity_id, entity_type, property_definition_id)\n DO UPDATE SET \n values = EXCLUDED.values,\n updated_at = NOW()\n ",+ "describe": {+ "columns": [],+ "parameters": {+ "Left": [+ "UuidArray",+ "TextArray",+ "TextArray",+ "UuidArray",+ "JsonbArray"+ ]+ },+ "nullable": []+ },+ "hash": "f2d5d7aea9918978cd69c14f8afe24156c2fa387e001ee8eaf57e4a70a106069"+}diff --git a/rust/cloud-storage/macro_db_client/src/dcs/create_chat_message.rs b/rust/cloud-storage/macro_db_client/src/dcs/create_chat_message.rsindex 9ebcaf73f7..42334d8bca 100644--- a/rust/cloud-storage/macro_db_client/src/dcs/create_chat_message.rs+++ b/rust/cloud-storage/macro_db_client/src/dcs/create_chat_message.rs@@ -9,15 +9,20 @@ pub async fn create_chat_message(chat_id: &str,message: NewChatMessage,) -> Result<String, anyhow::Error> {+ let id = message+ .id+ .unwrap_or_else(|| uuid::Uuid::new_v4().to_string());+let mut tsx = db.begin().await.context("error creating transaction")?;if message.role == Role::User {// insert messagelet message_id = sqlx::query!(r#"- INSERT INTO "ChatMessage" ("chatId", "content", "role", "model", "createdAt", "updatedAt")- VALUES ($1, $2, $3, $4, $5, $6)+ INSERT INTO "ChatMessage" ("id", "chatId", "content", "role", "model", "createdAt", "updatedAt")+ VALUES ($1, $2, $3, $4, $5, $6, $7)RETURNING id;"#,+ id,chat_id,serde_json::to_value(&message.content)?,message.role.as_ref(),@@ -63,10 +68,11 @@ pub async fn create_chat_message(} else {let id = sqlx::query!(r#"- INSERT INTO "ChatMessage" ("chatId", "content", "role", "model", "createdAt", "updatedAt")- VALUES ($1, $2, $3, $4, $5, $6)+ INSERT INTO "ChatMessage" ("id", "chatId", "content", "role", "model", "createdAt", "updatedAt")+ VALUES ($1, $2, $3, $4, $5, $6, $7)RETURNING id;"#,+ id,chat_id,serde_json::to_value(&message.content)?,message.role.as_ref(),diff --git a/rust/cloud-storage/model/src/chat/message.rs b/rust/cloud-storage/model/src/chat/message.rsindex ef5727e937..4e3faf0686 100644--- a/rust/cloud-storage/model/src/chat/message.rs+++ b/rust/cloud-storage/model/src/chat/message.rs@@ -36,6 +36,8 @@ pub struct ChatMessageWithAttachments {#[derive(Serialize, Deserialize, Eq, PartialEq, Debug, Clone, ToSchema)]#[serde(rename_all = "camelCase")]pub struct NewChatMessage {+ /// Optional pre-generated ID. If None, the database generates one.+ pub id: Option<String>,/// Content of the messagepub content: ChatMessageContent,/// Whether the chat is from the user or system