diff --git a/bun.lock b/bun.lock index f887893598..4b77fe18f8 100644 --- a/bun.lock +++ b/bun.lock @@ -453,6 +453,7 @@ "@types/jest": "^29.5.2", "@types/react": "^18.2.11", "babel-plugin-replace-ts-export-assignment": "^0.0.2", + "i18next": "^24.2.2", "jest": "^30.2.0", "jest-environment-jsdom": "^30.2.0", "jotai": "^2.12.5", @@ -461,6 +462,7 @@ "lucide-react": "^0.528.0", "react": "^18.2.0", "react-dom": "^18.2.0", + "react-i18next": "^15.4.0", "rimraf": "^6.1.3", "tsdown": "0.22.2", "typescript": "^5.9.3", diff --git a/package-lock.json b/package-lock.json index bb2e070a45..e1a544fdd6 100644 --- a/package-lock.json +++ b/package-lock.json @@ -41458,6 +41458,7 @@ "@types/jest": "^29.5.2", "@types/react": "^18.2.11", "babel-plugin-replace-ts-export-assignment": "^0.0.2", + "i18next": "^24.2.2", "jest": "^30.2.0", "jest-environment-jsdom": "^30.2.0", "jotai": "^2.12.5", @@ -41466,6 +41467,7 @@ "lucide-react": "^0.528.0", "react": "^18.2.0", "react-dom": "^18.2.0", + "react-i18next": "^15.4.0", "rimraf": "^6.1.3", "tsdown": "0.22.2", "typescript": "^5.9.3", diff --git a/packages/chat/jest.config.js b/packages/chat/jest.config.js index eae6f812d3..e3941e18d6 100644 --- a/packages/chat/jest.config.js +++ b/packages/chat/jest.config.js @@ -13,6 +13,12 @@ module.exports = { ], // The component library's resolver: its ESM-only @ariakit packages need the `import` condition. resolver: '/../client/jest.resolver.cjs', + // `test/` imports the package by its published entry names, as a consumer would; this points + // those names at the sources so the suite needs no package build. + moduleNameMapper: { + '^@librechat/chat$': '/src/index.ts', + '^@librechat/chat/(react|components)$': '/src/$1.ts', + }, // The core runs without a DOM; a React spec opts into jsdom with a docblock. testEnvironment: 'node', setupFilesAfterEnv: ['@testing-library/jest-dom/extend-expect'], diff --git a/packages/chat/package.json b/packages/chat/package.json index f714138d0d..f689509692 100644 --- a/packages/chat/package.json +++ b/packages/chat/package.json @@ -53,7 +53,7 @@ "build": "npm run clean && tsdown", "b:build": "bun run b:clean && bun run tsdown", "build:watch": "tsdown --watch", - "typecheck": "node ../../scripts/typecheck.mts", + "typecheck": "node ../../scripts/typecheck.mts && node ../../scripts/typecheck.mts -p test/tsconfig.json", "test": "jest", "test:ci": "jest --ci" }, @@ -81,6 +81,7 @@ "@types/jest": "^29.5.2", "@types/react": "^18.2.11", "babel-plugin-replace-ts-export-assignment": "^0.0.2", + "i18next": "^24.2.2", "jest": "^30.2.0", "jest-environment-jsdom": "^30.2.0", "jotai": "^2.12.5", @@ -89,6 +90,7 @@ "lucide-react": "^0.528.0", "react": "^18.2.0", "react-dom": "^18.2.0", + "react-i18next": "^15.4.0", "rimraf": "^6.1.3", "tsdown": "0.22.2", "typescript": "^5.9.3", diff --git a/packages/chat/test/consumer.spec.tsx b/packages/chat/test/consumer.spec.tsx new file mode 100644 index 0000000000..64c39d72c1 --- /dev/null +++ b/packages/chat/test/consumer.spec.tsx @@ -0,0 +1,304 @@ +/** + * @jest-environment jsdom + */ +import { useEffect, useMemo, useState, useSyncExternalStore } from 'react'; +import { Chat } from '@librechat/chat'; +import { createInstance } from 'i18next'; +import { ContentTypes } from 'librechat-data-provider'; +import { Part, Text } from '@librechat/chat/components'; +import { initReactI18next, I18nextProvider } from 'react-i18next'; +import { act, fireEvent, render, screen, within } from '@testing-library/react'; +import { Button, Textarea, ThemeProvider, clickHouseTheme } from '@librechat/client'; +import { MessageContext, MessagePartIndex, MessagePartsHostProvider } from '@librechat/chat/react'; +import type { ChatEvent, TMessage, TMessageContentParts } from 'librechat-data-provider'; +import type { ChatState, ChatStream, ChatTransport } from '@librechat/chat'; +import type { PartRenderers } from '@librechat/chat/components'; +import type { MessagePartsHost } from '@librechat/chat/react'; +import type { ReactElement } from 'react'; + +/** + * An outside consumer of the package: it reaches LibreChat's chat only through the published + * entries (`@librechat/chat`, `/react`, `/components`) and the `@librechat/client` theme, with an + * in-memory transport in place of a server. It grows as the session, message list and composer + * move into the package. + */ + +/** A stream the test feeds frame by frame. */ +function createStream(): ChatStream & { push(event: ChatEvent): void } { + const queued: ChatEvent[] = []; + let wake: (() => void) | undefined; + let closed = false; + return { + push(event) { + queued.push(event); + wake?.(); + }, + close() { + closed = true; + wake?.(); + }, + async *[Symbol.asyncIterator]() { + while (true) { + while (queued.length > 0) { + yield queued.shift() as ChatEvent; + } + if (closed) { + return; + } + await new Promise((resolve) => { + wake = resolve; + }); + } + }, + }; +} + +/** Serves each turn from a stream the test drives. */ +function createMemoryTransport(): ChatTransport & { stream?: ReturnType } { + const transport: ChatTransport & { stream?: ReturnType } = { + async sendMessages() { + transport.stream = createStream(); + return { status: 'stream', stream: transport.stream }; + }, + async reconnectToStream() { + return null; + }, + async abort() { + return { success: true }; + }, + }; + return transport; +} + +function createState(): ChatState { + let messages: TMessage[] = []; + return { + status: 'ready', + error: undefined, + connection: 'idle', + get messages() { + return messages; + }, + replaceMessages(next) { + messages = next; + }, + }; +} + +let ids = 0; + +/** The consumer's own turn building: the request plus its optimistic user message and reply. */ +function createChat(transport: ChatTransport): Chat { + return new Chat({ + id: 'convo', + state: createState(), + transport, + prepareRequest({ input, messages }) { + const text = input?.parts.map((part) => part.text).join('') ?? ''; + const parentMessageId = messages[messages.length - 1]?.messageId ?? null; + const messageId = `user-${++ids}`; + const responseMessageId = `reply-${ids}`; + const base = { conversationId: 'convo' }; + const user: TMessage = { ...base, messageId, parentMessageId, isCreatedByUser: true, text }; + const reply: TMessage = { + ...base, + messageId: responseMessageId, + parentMessageId: messageId, + isCreatedByUser: false, + text: '', + }; + return { + payload: { + ...base, + text, + messageId, + parentMessageId, + isContinued: false, + isTemporary: true, + }, + messages: (current) => [...current, user, reply], + responseMessageId, + }; + }, + /** Cumulative `text` frames fill the reply as it streams; the `final` frame settles it. */ + applyEvent(event, context) { + if (event.type === 'text') { + const text = event.data.text ?? event.data.response ?? ''; + context.write( + context.messages.map((message) => + message.messageId === event.data.messageId ? { ...message, text } : message, + ), + ); + } + const response = event.type === 'final' ? event.data.responseMessage : undefined; + if (response) { + context.write( + context.messages.map((message) => + message.messageId === response.messageId ? { ...message, ...response } : message, + ), + ); + } + }, + }); +} + +const host: MessagePartsHost = { + useMessage: () => ({ messageId: '' }), + renderMarkdown: ({ content }) =>

{content}

, + useSmoothStreaming: () => false, + useAgent: () => undefined, + renderAgentIcon: () => null, + useFontSize: () => 'text-base', + useShowThinking: () => false, + useAutoExpandTools: () => false, + useLaTeXParsing: () => false, + useChatDirection: () => 'auto', + useUserTextPreferences: () => ({ + enableUserMsgMarkdown: false, + collapseLongUserMessages: false, + usernameDisplay: false, + }), + useUser: () => undefined, + useFileMap: () => undefined, + useToast: () => () => undefined, + useSandboxStarting: () => false, + useToolArtifactClaim: () => [null, () => undefined], + useSteerEscalating: () => false, + usePaneConversationId: () => null, + useLiveAppliedSteer: () => [false, () => undefined], +}; + +const renderers: PartRenderers = { + parts: { + [ContentTypes.TEXT]: ({ part, showCursor, isCreatedByUser }) => ( + + ), + }, + tools: {}, + defaultTool: () => null, +}; + +const partsOf = (message: TMessage): TMessageContentParts[] => + message.content?.length + ? message.content + : [{ type: ContentTypes.TEXT, text: message.text ?? '' }]; + +function ChatView({ chat }: { chat: Chat }): ReactElement { + const subscribe = useMemo(() => chat.subscribe.bind(chat), [chat]); + const messages = useSyncExternalStore(subscribe, () => chat.messages); + const status = useSyncExternalStore(subscribe, () => chat.status); + const [text, setText] = useState(''); + const send = () => { + setText(''); + void chat.sendMessage({ parts: [{ type: 'text', text }] }); + }; + return ( + +
    + {messages.map((message) => ( +
  1. + + {partsOf(message).map((part, index) => ( + + + + ))} + +
  2. + ))} +
+

{status}

+ +