Skip to content

fix: sent chatCompletion message correctly #351

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Apr 8, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions src/components/input/baseInput/baseInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ import { type ForwardedRef, forwardRef, useRef, useState } from 'react'
import React from 'react'
import { v4 as getUUID } from 'uuid'

import { toChatRequest } from '../../helper'
import Icon from '../../icon/icon'
import type { BaseInputProps, Message, Participant } from '../../types'
import Emoji from '../emoji/emoji'
Expand Down Expand Up @@ -281,7 +280,7 @@ function BaseInputElement(
sender: props.sender,
conversationId: props.conversationId,
format: 'chatCompletionRequest',
data: toChatRequest(messageText),
data: { text: messageText },
}

props.send(formattedMessage)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,9 @@ describe('Input', () => {
const videoFile = 'public/videoExamples/videoCaptions.mp4'

beforeEach(() => {
const sendStub = cy.stub().as('sendMessage')
const mockWsClient = {
send: cy.stub(),
send: sendStub,
close: cy.stub(),
reconnect: cy.stub(),
}
Expand Down Expand Up @@ -135,6 +136,63 @@ describe('Input', () => {
.should('equal', '')
})

it(`should send message with correct content on ${viewport} screen`, () => {
cy.viewport(viewport)

cy.intercept(
{
method: 'POST',
url: '/upload?message-id=*',
},
{
statusCode: 200,
body: {
url: 'http://test-url.com/image-component-example.png',
name: 'image-component-example.png',
},
}
).as('upload')
cy.get('input[type=file]').selectFile([imageFile], {
force: true,
})
cy.wait('@upload')
const testMessage = 'Hello, World!'
cy.get(textField).type(testMessage)
cy.get(sendButton).click()
cy.get('@sendMessage').then((stub) => {
const sendStub = stub as unknown as sinon.SinonStub
const sentMessage = sendStub.args[0][0]
expect(sentMessage).to.deep.include({
sender: testUser,
conversationId: '1',
format: 'chatCompletionRequest',
data: {
messages: [
{
content: [
{
type: 'text',
text: testMessage,
},
{
type: 'file_url',
file_url: {
url: 'http://test-url.com/image-component-example.png',
name: 'image-component-example.png',
},
},
],
role: 'user',
},
],
},
})

expect(sentMessage.id).to.be.a('string')
expect(sentMessage.timestamp).to.be.a('string')
})
})

it(`can add and delete files on ${viewport} screen`, () => {
cy.viewport(viewport)
cy.intercept(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,8 @@ import axios from 'axios'
import React from 'react'
import { v4 as getUUID } from 'uuid'

import {
conversationIdDescription,
getMembersDescription,
} from '../../../sharedDescription'
import type { FileData, Message } from '../../../types'
import { textInputDescription } from '../../../sharedDescription'
import type { Message } from '../../../types'
import meta from '../../textInput/textInput.stories'
import MultimodalInput from './multimodalInput'

Expand Down Expand Up @@ -85,7 +82,7 @@ const multiModalInputMeta: Meta<React.ComponentProps<typeof MultimodalInput>> =

multiModalInputMeta.argTypes = {
...meta.argTypes,
conversationId: conversationIdDescription,
...textInputDescription,
uploadFileEndpoint: {
description:
'The API endpoint for sending a POST multipart-form request. If the JSON response includes a `fileId` property, it can be used to delete the file later. Path placeholders like `fileName` and `messageId`, will be automatically replaced with the actual file name and message ID.',
Expand All @@ -107,47 +104,6 @@ multiModalInputMeta.argTypes = {
type: { summary: 'string' },
},
},
label: {
description:
'Optional label text to be displayed in the input, which will then move to the top when the input is focused on. If both label and placeholder are provided, the placeholder will only be visible once the input is focused on.',
table: {
type: { summary: 'string' },
},
},
placeholder: {
description:
'Optional Placeholder text to be displayed in the input before user starts typing.',
table: {
type: { summary: 'string' },
},
},
multiline: {
description:
'Optional boolean that dictates whether `TextInput` can expand to be multiline.',
table: {
type: { summary: 'boolean' },
},
},
maxRows: {
description: 'Optional maximum number of rows to be displayed.',
table: {
type: { summary: 'number' },
},
},
fullWidth: {
description:
'Optional boolean that dictates whether `TextInput` takes up 100% width of the parent container.',
table: {
type: { summary: 'boolean' },
},
},
enableSpeechToText: {
description:
'Optional boolean to enable speech-to-text. See which browsers are supported [here](https://developer.mozilla.org/en-US/docs/Web/API/SpeechRecognition#browser_compatibility).',
table: {
type: { summary: 'boolean' },
},
},
maxFileCount: {
description:
'Optional props. Maximum number of files that can be uploaded in one message.',
Expand Down Expand Up @@ -212,15 +168,6 @@ multiModalInputMeta.argTypes = {
},
},
},
maximumEmojiSearchResults: {
description:
'Specifies the maximum number of emoji search results to display when the user enters a search query. The search query is triggered when the user types in a format like `:text`.',
table: {
type: { summary: 'number' },
defaultValue: { summary: '5' },
},
},
getMembers: getMembersDescription,
}

export default multiModalInputMeta
Expand All @@ -234,24 +181,17 @@ export const Default = {
placeholder: 'Type your message',
ws: {
send: (message: Message) => {
let fileMessage = ''
let textMessage = ''
if (message.data.files && message.data.files.length > 0) {
const fileNames = message.data.files
.map((file: FileData) => file.name)
.join(', ')
fileMessage = `File(s): ${fileNames}`
}
if (message.data.text) {
textMessage = `Text content: ${message.data.text}`
}
alert(
'Message sent!' +
'\n' +
textMessage +
`${textMessage.length > 0 ? '\n' : ''}` +
fileMessage
)
const messages: string[] = []

message.data.messages[0].content.forEach((content: any) => {
if (content.type === 'text') {
messages.push(`Text content: ${content.text}`)
} else if (content.type === 'file_url') {
messages.push(`File: ${content.file_url.name}`)
}
})

alert('Message sent!\n' + messages.join('\n'))
},
},
listFiles: () => {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,16 +107,13 @@ export default function MultimodalInput({
})

function handleSendMessage(formattedMessage: Message): void {
if (isUploadFinished) {
formattedMessage.id = messageId
formattedMessage.format = 'chatCompletionRequest'
formattedMessage.data = toChatRequest(
formattedMessage.data.text,
filesInfo.uploaded.map((file) => {
return { url: file.url, name: file.name }
})
)
}
formattedMessage.data = toChatRequest(
formattedMessage.data.text,
filesInfo.uploaded.map((file) => {
return { url: file.url, name: file.name }
})
)
formattedMessage.id = messageId

props.ws.send(formattedMessage)
setMessageId(getUUID())
Expand Down
36 changes: 35 additions & 1 deletion src/components/input/textInput/textInput.cy.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,9 @@ describe('TextInput', () => {
const emojiTestWaitTime = 20
context('Regular', () => {
beforeEach(() => {
const sendStub = cy.stub().as('sendMessage')
const mockWsClient = {
send: cy.stub(),
send: sendStub,
close: cy.stub(),
reconnect: cy.stub(),
}
Expand Down Expand Up @@ -118,6 +119,39 @@ describe('TextInput', () => {
cy.get(textInput).type(':polpo:')
cy.get('textarea').invoke('val').should('equal', '🐙')
})
it(`should send message with correct content on ${viewport} screen`, () => {
cy.viewport(viewport)

const testMessage = 'Hello, World!'
cy.get(textInput).type(testMessage)
cy.get(sendButton).click()

cy.get('@sendMessage').then((stub) => {
const sendStub = stub as unknown as sinon.SinonStub
const sentMessage = sendStub.args[0][0]
expect(sentMessage).to.deep.include({
sender: testUser,
conversationId: '1',
format: 'chatCompletionRequest',
data: {
messages: [
{
content: [
{
type: 'text',
text: testMessage,
},
],
role: 'user',
},
],
},
})

expect(sentMessage.id).to.be.a('string')
expect(sentMessage.timestamp).to.be.a('string')
})
})
})
})

Expand Down
61 changes: 12 additions & 49 deletions src/components/input/textInput/textInput.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import type { Meta, StoryFn } from '@storybook/react'
import React from 'react'

import { getMembersDescription, wsDescription } from '../../sharedDescription'
import { textInputDescription } from '../../sharedDescription'
import type { BaseInputProps, WebSocketClient } from '../../types'
import type { Message } from '../../types'
import BaseInput from '../baseInput/baseInput'
import TextInput from './textInput'

interface InputProps extends BaseInputProps {
Expand All @@ -13,29 +12,10 @@ interface InputProps extends BaseInputProps {

const meta: Meta<React.FC<InputProps>> = {
title: 'Rustic UI/Input/Text Input',
component: BaseInput,
component: TextInput,
tags: ['autodocs'],
parameters: {
layout: 'centered',
docs: {
argTypes: {
exclude: ['send', 'isSendEnabled'],
},
source: {
transform: (code: string) => {
let textInputCode = code.replaceAll('BaseInput', 'TextInput')
textInputCode = textInputCode.replaceAll(
' component={() => {}}\n',
''
)
textInputCode = textInputCode.replaceAll(
'send={() => {}}',
'ws:{send: (message: Message) => alert(`Message sent: ${message.data.messages[0].content[0].text}`)}'
)
return textInputCode
},
},
},
},
decorators: [
(Story: StoryFn) => (
Expand All @@ -48,31 +28,7 @@ const meta: Meta<React.FC<InputProps>> = {

meta.argTypes = {
...meta.argTypes,
ws: wsDescription,
getMembers: getMembersDescription,
emojiDataSource: {
description:
'URL to fetch the emoji data from. You need to host the emoji data by yourself. If not provided, the default url will be used.',
table: {
type: { summary: 'string' },
defaultValue: {
summary:
'https://cdn.jsdelivr.net/npm/emoji-picker-element-data@^1/en/emojibase/data.json',
},
},
},
sender: {
description: 'The sender of the message.',
type: { name: 'object', required: true, value: {} },
table: {
type: {
summary: 'Sender',
detail:
'id: String representing sender id.\n' +
'name: Optional string of sender name.',
},
},
},
...textInputDescription,
}

export default meta
Expand All @@ -85,8 +41,15 @@ export const Default = {
placeholder: 'Type your message',
emojiDataSource:
'node_modules/emoji-picker-element-data/en/emojibase/data.json',
send: (message: Message) =>
alert(`Message sent: ${message.data.messages[0].content[0].text}`),
ws: {
send: (message: Message) => {
alert(
'Message sent!' +
'\n' +
`Text content: ${message.data.messages[0].content[0].text}`
)
},
},
getMembers: () =>
Promise.resolve([
{
Expand Down
2 changes: 2 additions & 0 deletions src/components/input/textInput/textInput.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import React from 'react'

import { toChatRequest } from '../../helper'
import type { Message, TextInputProps } from '../../types'
import BaseInput from '../baseInput/baseInput'

export default function TextInput(props: TextInputProps) {
const { ws, ...baseInputProps } = props

function handleSendMessage(message: Message): void {
message.data = toChatRequest(message.data.text)
ws.send(message)
}

Expand Down
Loading