From 91221f6471580bb799585162a1628e4b6478f3ff Mon Sep 17 00:00:00 2001 From: Nicolas Brichet Date: Thu, 29 Feb 2024 11:30:56 +0100 Subject: [PATCH 1/6] Uses a chat model, and provides a webSocket handler as one of the implementation --- jupyter_chat/handlers.py | 8 +- jupyter_chat/models.py | 3 +- package.json | 3 + src/components/chat.tsx | 28 ++- src/{ => handlers}/handler.ts | 0 .../websocket-handler.ts} | 103 ++++------ src/index.ts | 3 +- src/model.ts | 191 ++++++++++++++++++ src/services.ts | 5 +- src/widgets/chat-sidebar.tsx | 6 +- 10 files changed, 256 insertions(+), 94 deletions(-) rename src/{ => handlers}/handler.ts (100%) rename src/{chat-handler.ts => handlers/websocket-handler.ts} (60%) create mode 100644 src/model.ts diff --git a/jupyter_chat/handlers.py b/jupyter_chat/handlers.py index 11d3144..4a7ef55 100644 --- a/jupyter_chat/handlers.py +++ b/jupyter_chat/handlers.py @@ -150,11 +150,13 @@ async def on_message(self, message): return # message broadcast to chat clients - chat_message_id = str(uuid.uuid4()) + if not chat_request.id: + chat_request.id = str(uuid.uuid4()) + chat_message = ChatMessage( - id=chat_message_id, + id=chat_request.id, time=time.time(), - body=chat_request.prompt, + body=chat_request.body, sender=self.chat_client, ) diff --git a/jupyter_chat/models.py b/jupyter_chat/models.py index 64ea2ab..95cff48 100644 --- a/jupyter_chat/models.py +++ b/jupyter_chat/models.py @@ -8,7 +8,8 @@ # the type of message used to chat with the agent class ChatRequest(BaseModel): - prompt: str + body: str + id: str class ChatUser(BaseModel): diff --git a/package.json b/package.json index 95f4cf0..42b3653 100644 --- a/package.json +++ b/package.json @@ -60,6 +60,9 @@ "@jupyterlab/rendermime": "^4.0.5", "@jupyterlab/services": "^7.0.5", "@jupyterlab/ui-components": "^4.0.5", + "@lumino/coreutils": "2.1.2", + "@lumino/disposable": "2.1.2", + "@lumino/signaling": "2.1.2", "@mui/icons-material": "5.11.0", "@mui/material": "^5.11.0", "react": "^18.2.0", diff --git a/src/components/chat.tsx b/src/components/chat.tsx index 06434c2..eaaac71 100644 --- a/src/components/chat.tsx +++ b/src/components/chat.tsx @@ -10,17 +10,17 @@ import { JlThemeProvider } from './jl-theme-provider'; import { ChatMessages } from './chat-messages'; import { ChatInput } from './chat-input'; import { ChatSettings } from './chat-settings'; -import { ChatHandler } from '../chat-handler'; import { ScrollContainer } from './scroll-container'; +import { IChatModel } from '../model'; import { ChatService } from '../services'; type ChatBodyProps = { - chatHandler: ChatHandler; + chatModel: IChatModel; rmRegistry: IRenderMimeRegistry; }; function ChatBody({ - chatHandler, + chatModel, rmRegistry: renderMimeRegistry }: ChatBodyProps): JSX.Element { const [messages, setMessages] = useState([]); @@ -34,7 +34,8 @@ function ChatBody({ async function fetchHistory() { try { const [history, config] = await Promise.all([ - chatHandler.getHistory(), + chatModel.getHistory?.() ?? + new Promise(r => r({ messages: [] })), ChatService.getConfig() ]); setSendWithShiftEnter(config.send_with_shift_enter ?? false); @@ -45,13 +46,13 @@ function ChatBody({ } fetchHistory(); - }, [chatHandler]); + }, [chatModel]); /** * Effect: listen to chat messages */ useEffect(() => { - function handleChatEvents(message: ChatService.IMessage) { + function handleChatEvents(_: IChatModel, message: ChatService.IMessage) { if (message.type === 'connection') { return; } else if (message.type === 'clear') { @@ -62,11 +63,11 @@ function ChatBody({ setMessages(messageGroups => [...messageGroups, message]); } - chatHandler.addListener(handleChatEvents); + chatModel.incomingMessage.connect(handleChatEvents); return function cleanup() { - chatHandler.removeListener(handleChatEvents); + chatModel.incomingMessage.disconnect(handleChatEvents); }; - }, [chatHandler]); + }, [chatModel]); // no need to append to messageGroups imperatively here. all of that is // handled by the listeners registered in the effect hooks above. @@ -74,7 +75,7 @@ function ChatBody({ setInput(''); // send message to backend - chatHandler.sendMessage({ prompt: input }); + chatModel.sendMessage({ body: input }); }; return ( @@ -100,7 +101,7 @@ function ChatBody({ } export type ChatProps = { - chatHandler: ChatHandler; + chatModel: IChatModel; themeManager: IThemeManager | null; rmRegistry: IRenderMimeRegistry; chatView?: ChatView; @@ -147,10 +148,7 @@ export function Chat(props: ChatProps): JSX.Element { {/* body */} {view === ChatView.Chat && ( - + )} {view === ChatView.Settings && } diff --git a/src/handler.ts b/src/handlers/handler.ts similarity index 100% rename from src/handler.ts rename to src/handlers/handler.ts diff --git a/src/chat-handler.ts b/src/handlers/websocket-handler.ts similarity index 60% rename from src/chat-handler.ts rename to src/handlers/websocket-handler.ts index 04cfe98..0cc0403 100644 --- a/src/chat-handler.ts +++ b/src/handlers/websocket-handler.ts @@ -1,27 +1,27 @@ import { URLExt } from '@jupyterlab/coreutils'; -import { IDisposable } from '@lumino/disposable'; import { ServerConnection } from '@jupyterlab/services'; +import { UUID } from '@lumino/coreutils'; import { requestAPI } from './handler'; -import { ChatService } from './services'; +import { ChatModel, IChatModel } from '../model'; +import { ChatService } from '../services'; const CHAT_SERVICE_URL = 'api/chat'; -export class ChatHandler implements IDisposable { +/** + * An implementation of the chat model based on websocket handler. + */ +export class WebSocketHandler extends ChatModel { /** * The server settings used to make API requests. */ readonly serverSettings: ServerConnection.ISettings; - /** - * ID of the connection. Requires `await initialize()`. - */ - id = ''; - /** * Create a new chat handler. */ - constructor(options: ChatHandler.IOptions = {}) { + constructor(options: WebSocketHandler.IOptions = {}) { + super(options); this.serverSettings = options.serverSettings ?? ServerConnection.makeSettings(); } @@ -31,7 +31,7 @@ export class ChatHandler implements IDisposable { * resolved when server acknowledges connection and sends the client ID. This * must be awaited before calling any other method. */ - public async initialize(): Promise { + async initialize(): Promise { await this._initialize(); } @@ -39,27 +39,15 @@ export class ChatHandler implements IDisposable { * Sends a message across the WebSocket. Promise resolves to the message ID * when the server sends the same message back, acknowledging receipt. */ - public sendMessage(message: ChatService.ChatRequest): Promise { + sendMessage(message: ChatService.ChatRequest): Promise { + message.id = UUID.uuid4(); return new Promise(resolve => { this._socket?.send(JSON.stringify(message)); - this._sendResolverQueue.push(resolve); + this._sendResolverQueue.set(message.id!, resolve); }); } - public addListener(handler: (message: ChatService.IMessage) => void): void { - this._listeners.push(handler); - } - - public removeListener( - handler: (message: ChatService.IMessage) => void - ): void { - const index = this._listeners.indexOf(handler); - if (index > -1) { - this._listeners.splice(index, 1); - } - } - - public async getHistory(): Promise { + async getHistory(): Promise { let data: ChatService.ChatHistory = { messages: [] }; try { data = await requestAPI('history', { @@ -71,22 +59,11 @@ export class ChatHandler implements IDisposable { return data; } - /** - * Whether the chat handler is disposed. - */ - get isDisposed(): boolean { - return this._isDisposed; - } - /** * Dispose the chat handler. */ dispose(): void { - if (this.isDisposed) { - return; - } - this._isDisposed = true; - this._listeners = []; + super.dispose(); // Clean up socket. const socket = this._socket; @@ -100,35 +77,15 @@ export class ChatHandler implements IDisposable { } } - /** - * A function called before transferring the message to the panel(s). - * Can be useful if some actions are required on the message. - */ - protected formatChatMessage( - message: ChatService.IChatMessage - ): ChatService.IChatMessage { - return message; - } - - private _onMessage(message: ChatService.IMessage): void { + onMessage(message: ChatService.IMessage): void { // resolve promise from `sendMessage()` if (message.type === 'msg' && message.sender.id === this.id) { - this._sendResolverQueue.shift()?.(message.id); + this._sendResolverQueue.get(message.id)?.(true); } - if (message.type === 'msg') { - message = this.formatChatMessage(message as ChatService.IChatMessage); - } - - // call listeners in serial - this._listeners.forEach(listener => listener(message)); + super.onMessage(message); } - /** - * Queue of Promise resolvers pushed onto by `send()` - */ - private _sendResolverQueue: ((value: string) => void)[] = []; - private _onClose(e: CloseEvent, reject: any) { reject(new Error('Chat UI websocket disconnected')); console.error('Chat UI websocket disconnected'); @@ -156,31 +113,39 @@ export class ChatHandler implements IDisposable { socket.onclose = e => this._onClose(e, reject); socket.onerror = e => reject(e); socket.onmessage = msg => - msg.data && this._onMessage(JSON.parse(msg.data)); + msg.data && this.onMessage(JSON.parse(msg.data)); - const listenForConnection = (message: ChatService.IMessage) => { + const listenForConnection = ( + _: IChatModel, + message: ChatService.IMessage + ) => { if (message.type !== 'connection') { return; } this.id = message.client_id; resolve(); - this.removeListener(listenForConnection); + this.incomingMessage.disconnect(listenForConnection); }; - this.addListener(listenForConnection); + this.incomingMessage.connect(listenForConnection); }); } - private _isDisposed = false; private _socket: WebSocket | null = null; - private _listeners: ((msg: any) => void)[] = []; + /** + * Queue of Promise resolvers pushed onto by `send()` + */ + private _sendResolverQueue = new Map void>(); } -export namespace ChatHandler { +/** + * The websocket namespace. + */ +export namespace WebSocketHandler { /** * The instantiation options for a data registry handler. */ - export interface IOptions { + export interface IOptions extends ChatModel.IOptions { serverSettings?: ServerConnection.ISettings; } } diff --git a/src/index.ts b/src/index.ts index 263e4aa..6127c09 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,4 +1,5 @@ -export * from './chat-handler'; +export * from './handlers/websocket-handler'; +export * from './model'; export * from './services'; export * from './widgets/chat-error'; export * from './widgets/chat-sidebar'; diff --git a/src/model.ts b/src/model.ts new file mode 100644 index 0000000..3a1aaa4 --- /dev/null +++ b/src/model.ts @@ -0,0 +1,191 @@ +import { IDisposable } from '@lumino/disposable'; +import { ISignal, Signal } from '@lumino/signaling'; + +import { ChatService } from './services'; + +export interface IChatModel extends IDisposable { + /** + * The chat model ID. + */ + id: string; + + /** + * The signal emitted when a new message is received. + */ + get incomingMessage(): ISignal; + + /** + * The signal emitted when a message is updated. + */ + get messageUpdated(): ISignal; + + /** + * The signal emitted when a message is updated. + */ + get messageDeleted(): ISignal; + + /** + * Send a message, to be defined depending on the chosen technology. + * Default to no-op. + * + * @param message - the message to send. + * @returns whether the message has been sent or not, or nothing if not needed. + */ + sendMessage( + message: ChatService.ChatRequest + ): Promise | boolean | void; + + /** + * Optional, to update a message from the chat. + * + * @param id - the unique ID of the message. + * @param message - the message to update. + */ + updateMessage?( + id: string, + message: ChatService.ChatRequest + ): Promise | boolean | void; + + /** + * Optional, to get messages history. + */ + getHistory?(): Promise; + + /** + * Dispose the chat model. + */ + dispose(): void; + + /** + * Whether the chat handler is disposed. + */ + isDisposed: boolean; + + /** + * Function to call when a message is received. + * + * @param message - the new message, containing user information and body. + */ + onMessage(message: ChatService.IMessage): void; + + /** + * Function to call when a message is updated. + * + * @param message - the message updated, containing user information and body. + */ + onMessageUpdated?(message: ChatService.IMessage): void; +} + +/** + * The default chat model implementation. + * It is not able to send or update a message by itself, since it depends on the + * chosen technology. + */ +export class ChatModel implements IChatModel { + /** + * Create a new chat model. + */ + constructor(options: ChatModel.IOptions = {}) {} + + /** + * The chat model ID. + */ + get id(): string { + return this._id; + } + set id(value: string) { + this._id = value; + } + + /** + * The signal emitted when a new message is received. + */ + get incomingMessage(): ISignal { + return this._incomingMessage; + } + + /** + * The signal emitted when a message is updated. + */ + get messageUpdated(): ISignal { + return this._messageUpdated; + } + + /** + * The signal emitted when a message is updated. + */ + get messageDeleted(): ISignal { + return this._messageDeleted; + } + + /** + * Send a message, to be defined depending on the chosen technology. + * Default to no-op. + * + * @param message - the message to send. + * @returns whether the message has been sent or not. + */ + sendMessage( + message: ChatService.ChatRequest + ): Promise | boolean | void {} + + /** + * Dispose the chat model. + */ + dispose(): void { + if (this.isDisposed) { + return; + } + this._isDisposed = true; + } + + /** + * Whether the chat handler is disposed. + */ + get isDisposed(): boolean { + return this._isDisposed; + } + + /** + * A function called before transferring the message to the panel(s). + * Can be useful if some actions are required on the message. + */ + protected formatChatMessage( + message: ChatService.IChatMessage + ): ChatService.IChatMessage { + return message; + } + + /** + * Function to call when a message is received. + * + * @param message - the message with user information and body. + */ + onMessage(message: ChatService.IMessage): void { + if (message.type === 'msg') { + message = this.formatChatMessage(message as ChatService.IChatMessage); + } + + this._incomingMessage.emit(message); + } + + private _id: string = ''; + private _isDisposed = false; + private _incomingMessage = new Signal(this); + private _messageUpdated = new Signal( + this + ); + private _messageDeleted = new Signal( + this + ); +} + +/** + * The chat model namespace. + */ +export namespace ChatModel { + /** + * The instantiation options for a ChatModel. + */ + export interface IOptions {} +} diff --git a/src/services.ts b/src/services.ts index f92212f..d63381a 100644 --- a/src/services.ts +++ b/src/services.ts @@ -1,4 +1,4 @@ -import { requestAPI } from './handler'; +import { requestAPI } from './handlers/handler'; export namespace ChatService { export interface IUser { @@ -35,7 +35,8 @@ export namespace ChatService { }; export type ChatRequest = { - prompt: string; + body: string; + id?: string; }; export type DescribeConfigResponse = { diff --git a/src/widgets/chat-sidebar.tsx b/src/widgets/chat-sidebar.tsx index 6e12259..17e7b0c 100644 --- a/src/widgets/chat-sidebar.tsx +++ b/src/widgets/chat-sidebar.tsx @@ -3,17 +3,17 @@ import { IRenderMimeRegistry } from '@jupyterlab/rendermime'; import React from 'react'; import { Chat } from '../components/chat'; -import { ChatHandler } from '../chat-handler'; import { chatIcon } from '../icons'; +import { IChatModel } from '../model'; export function buildChatSidebar( - chatHandler: ChatHandler, + chatModel: IChatModel, themeManager: IThemeManager | null, rmRegistry: IRenderMimeRegistry ): ReactWidget { const ChatWidget = ReactWidget.create( From cb6c9453ad21c238bb032553671d6eb0fe2ed298 Mon Sep 17 00:00:00 2001 From: Nicolas Brichet Date: Mon, 4 Mar 2024 11:02:38 +0100 Subject: [PATCH 2/6] Do not pin dependencies --- package.json | 8 ++++---- yarn.lock | 17 ++++++++++------- 2 files changed, 14 insertions(+), 11 deletions(-) diff --git a/package.json b/package.json index 42b3653..25a00c4 100644 --- a/package.json +++ b/package.json @@ -60,10 +60,10 @@ "@jupyterlab/rendermime": "^4.0.5", "@jupyterlab/services": "^7.0.5", "@jupyterlab/ui-components": "^4.0.5", - "@lumino/coreutils": "2.1.2", - "@lumino/disposable": "2.1.2", - "@lumino/signaling": "2.1.2", - "@mui/icons-material": "5.11.0", + "@lumino/coreutils": "^2.1.2", + "@lumino/disposable": "^2.1.2", + "@lumino/signaling": "^2.1.2", + "@mui/icons-material": "^5.11.0", "@mui/material": "^5.11.0", "react": "^18.2.0", "react-dom": "^18.2.0" diff --git a/yarn.lock b/yarn.lock index 3c73bea..14b1092 100644 --- a/yarn.lock +++ b/yarn.lock @@ -1310,7 +1310,7 @@ __metadata: languageName: node linkType: hard -"@babel/runtime@npm:^7.12.5, @babel/runtime@npm:^7.18.3, @babel/runtime@npm:^7.20.6, @babel/runtime@npm:^7.23.9, @babel/runtime@npm:^7.5.5, @babel/runtime@npm:^7.8.4, @babel/runtime@npm:^7.8.7": +"@babel/runtime@npm:^7.12.5, @babel/runtime@npm:^7.18.3, @babel/runtime@npm:^7.23.9, @babel/runtime@npm:^7.5.5, @babel/runtime@npm:^7.8.4, @babel/runtime@npm:^7.8.7": version: 7.23.9 resolution: "@babel/runtime@npm:7.23.9" dependencies: @@ -2253,7 +2253,10 @@ __metadata: "@jupyterlab/services": ^7.0.5 "@jupyterlab/testutils": ^4.0.0 "@jupyterlab/ui-components": ^4.0.5 - "@mui/icons-material": 5.11.0 + "@lumino/coreutils": ^2.1.2 + "@lumino/disposable": ^2.1.2 + "@lumino/signaling": ^2.1.2 + "@mui/icons-material": ^5.11.0 "@mui/material": ^5.11.0 "@types/jest": ^29.2.0 "@types/json-schema": ^7.0.11 @@ -3564,11 +3567,11 @@ __metadata: languageName: node linkType: hard -"@mui/icons-material@npm:5.11.0": - version: 5.11.0 - resolution: "@mui/icons-material@npm:5.11.0" +"@mui/icons-material@npm:^5.11.0": + version: 5.15.11 + resolution: "@mui/icons-material@npm:5.15.11" dependencies: - "@babel/runtime": ^7.20.6 + "@babel/runtime": ^7.23.9 peerDependencies: "@mui/material": ^5.0.0 "@types/react": ^17.0.0 || ^18.0.0 @@ -3576,7 +3579,7 @@ __metadata: peerDependenciesMeta: "@types/react": optional: true - checksum: 764c1185b3432f0228f3c5217b0e218b10f106fa96d305dfc62c0ef5afd2a7a087b0d664fd0a8171282e195c18d3ee073d5f037901a2bed1a1519a70fbb0501c + checksum: 4403988af419b0ebdbcc61413f58f12fe44dc069d3245cf80aec05fd31fb2f5d38f0d87799aa538f5441c36d87df2f5fbc1168aa03e2704dd423ccd4febf864b languageName: node linkType: hard From ba2c3e504d4ac0a90bf55d3c8899bdbfe2d9ce52 Mon Sep 17 00:00:00 2001 From: Nicolas Brichet Date: Mon, 4 Mar 2024 11:09:18 +0100 Subject: [PATCH 3/6] Replace 'sendMessage' by 'addMessage' for genericity --- src/components/chat.tsx | 2 +- src/handlers/websocket-handler.ts | 2 +- src/model.ts | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/components/chat.tsx b/src/components/chat.tsx index eaaac71..ae148ac 100644 --- a/src/components/chat.tsx +++ b/src/components/chat.tsx @@ -75,7 +75,7 @@ function ChatBody({ setInput(''); // send message to backend - chatModel.sendMessage({ body: input }); + chatModel.addMessage({ body: input }); }; return ( diff --git a/src/handlers/websocket-handler.ts b/src/handlers/websocket-handler.ts index 0cc0403..aedba8c 100644 --- a/src/handlers/websocket-handler.ts +++ b/src/handlers/websocket-handler.ts @@ -39,7 +39,7 @@ export class WebSocketHandler extends ChatModel { * Sends a message across the WebSocket. Promise resolves to the message ID * when the server sends the same message back, acknowledging receipt. */ - sendMessage(message: ChatService.ChatRequest): Promise { + addMessage(message: ChatService.ChatRequest): Promise { message.id = UUID.uuid4(); return new Promise(resolve => { this._socket?.send(JSON.stringify(message)); diff --git a/src/model.ts b/src/model.ts index 3a1aaa4..0a9abf7 100644 --- a/src/model.ts +++ b/src/model.ts @@ -31,7 +31,7 @@ export interface IChatModel extends IDisposable { * @param message - the message to send. * @returns whether the message has been sent or not, or nothing if not needed. */ - sendMessage( + addMessage( message: ChatService.ChatRequest ): Promise | boolean | void; @@ -125,7 +125,7 @@ export class ChatModel implements IChatModel { * @param message - the message to send. * @returns whether the message has been sent or not. */ - sendMessage( + addMessage( message: ChatService.ChatRequest ): Promise | boolean | void {} From 4adc59dccbc66f59105f631142334a2d2b81561f Mon Sep 17 00:00:00 2001 From: Nicolas Brichet Date: Tue, 5 Mar 2024 14:45:21 +0100 Subject: [PATCH 4/6] Add a widget with the chat (in addition of the side panel widget) --- src/index.ts | 1 + src/widgets/chat-widget.tsx | 43 +++++++++++++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 src/widgets/chat-widget.tsx diff --git a/src/index.ts b/src/index.ts index 6127c09..27b40d8 100644 --- a/src/index.ts +++ b/src/index.ts @@ -3,3 +3,4 @@ export * from './model'; export * from './services'; export * from './widgets/chat-error'; export * from './widgets/chat-sidebar'; +export * from './widgets/chat-widget'; diff --git a/src/widgets/chat-widget.tsx b/src/widgets/chat-widget.tsx new file mode 100644 index 0000000..08d278e --- /dev/null +++ b/src/widgets/chat-widget.tsx @@ -0,0 +1,43 @@ +import { IThemeManager, ReactWidget } from '@jupyterlab/apputils'; +import { IRenderMimeRegistry } from '@jupyterlab/rendermime'; +import React from 'react'; + +import { Chat } from '../components/chat'; +import { chatIcon } from '../icons'; +import { IChatModel } from '../model'; + +export class ChatWidget extends ReactWidget { + constructor(options: ChatWidget.IOptions) { + super(); + + this.id = 'jupyter-chat::widget'; + this.title.icon = chatIcon; + this.title.caption = 'Jupyter Chat'; // TODO: i18n + + this._chatModel = options.chatModel; + this._themeManager = options.themeManager; + this._rmRegistry = options.rmRegistry; + } + + render() { + return ( + + ); + } + + private _chatModel: IChatModel; + private _themeManager: IThemeManager | null; + private _rmRegistry: IRenderMimeRegistry; +} + +export namespace ChatWidget { + export interface IOptions { + chatModel: IChatModel; + themeManager: IThemeManager | null; + rmRegistry: IRenderMimeRegistry; + } +} From 99559bdc182dbc060f877612c77fe9ce16f4d7ec Mon Sep 17 00:00:00 2001 From: Nicolas Brichet Date: Thu, 7 Mar 2024 21:39:01 +0100 Subject: [PATCH 5/6] Do not fetch history if the function is not provided --- src/components/chat.tsx | 26 +++++++++++++++----------- 1 file changed, 15 insertions(+), 11 deletions(-) diff --git a/src/components/chat.tsx b/src/components/chat.tsx index ae148ac..e593f42 100644 --- a/src/components/chat.tsx +++ b/src/components/chat.tsx @@ -31,20 +31,25 @@ function ChatBody({ * Effect: fetch history and config on initial render */ useEffect(() => { + async function getConfig() { + ChatService.getConfig() + .then(config => + setSendWithShiftEnter(config.send_with_shift_enter ?? false) + ) + .catch(e => console.error(e)); + } + async function fetchHistory() { - try { - const [history, config] = await Promise.all([ - chatModel.getHistory?.() ?? - new Promise(r => r({ messages: [] })), - ChatService.getConfig() - ]); - setSendWithShiftEnter(config.send_with_shift_enter ?? false); - setMessages(history.messages); - } catch (e) { - console.error(e); + if (!chatModel.getHistory) { + return; } + chatModel + .getHistory() + .then(history => setMessages(history.messages)) + .catch(e => console.error(e)); } + getConfig(); fetchHistory(); }, [chatModel]); @@ -59,7 +64,6 @@ function ChatBody({ setMessages([]); return; } - setMessages(messageGroups => [...messageGroups, message]); } From 0cf32e69ae3af8b758daa179f50aeb43df89d469 Mon Sep 17 00:00:00 2001 From: Nicolas Brichet Date: Fri, 15 Mar 2024 15:16:10 +0100 Subject: [PATCH 6/6] Remove the settings panel, but keep the option to add one if necessary from an extension, and remove everything related to socket handler in the core --- src/__tests__/chat-settings.spec.ts | 63 -------- src/components/chat-input.tsx | 26 ++-- src/components/chat-messages.tsx | 6 +- src/components/chat-settings.tsx | 158 --------------------- src/components/chat.tsx | 100 +++++++------ src/components/settings/minify.ts | 56 -------- src/components/settings/use-server-info.ts | 86 ----------- src/components/settings/validator.ts | 3 - src/handlers/websocket-handler.ts | 22 +-- src/index.ts | 2 +- src/model.ts | 85 +++++++---- src/services.ts | 64 --------- src/types.ts | 57 ++++++++ src/widgets/chat-widget.tsx | 8 +- 14 files changed, 207 insertions(+), 529 deletions(-) delete mode 100644 src/__tests__/chat-settings.spec.ts delete mode 100644 src/components/chat-settings.tsx delete mode 100644 src/components/settings/minify.ts delete mode 100644 src/components/settings/use-server-info.ts delete mode 100644 src/components/settings/validator.ts delete mode 100644 src/services.ts create mode 100644 src/types.ts diff --git a/src/__tests__/chat-settings.spec.ts b/src/__tests__/chat-settings.spec.ts deleted file mode 100644 index d265c77..0000000 --- a/src/__tests__/chat-settings.spec.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { minifyPatchObject } from '../components/settings/minify'; - -const COMPLEX_OBJECT = { - primitive: 0, - array: ['a'], - object: { nested: { field: 0 } } -}; - -describe('minifyPatchObject', () => { - test('returns empty object if patch is identical', () => { - const obj = COMPLEX_OBJECT; - const patch = JSON.parse(JSON.stringify(obj)); - - expect(minifyPatchObject(obj, patch)).toEqual({}); - }); - - test('returns empty object if patch is empty', () => { - expect(minifyPatchObject(COMPLEX_OBJECT, {})).toEqual({}); - }); - - test('returns patch if object is empty', () => { - expect(minifyPatchObject({}, COMPLEX_OBJECT)).toEqual(COMPLEX_OBJECT); - }); - - test('should remove unchanged props from patch', () => { - const obj = { - unchanged: 'foo', - changed: 'bar', - nested: { - unchanged: 'foo', - changed: 'bar' - } - }; - const patch = { - unchanged: 'foo', - changed: 'baz', - nested: { - unchanged: 'foo', - changed: 'baz' - } - }; - - expect(minifyPatchObject(obj, patch)).toEqual({ - changed: 'baz', - nested: { - changed: 'baz' - } - }); - }); - - test('defers to patch object when property types mismatch', () => { - const obj = { - api_keys: ['ANTHROPIC_API_KEY'] - }; - const patch = { - api_keys: { - OPENAI_API_KEY: 'foobar' - } - }; - - expect(minifyPatchObject(obj, patch)).toEqual(patch); - }); -}); diff --git a/src/components/chat-input.tsx b/src/components/chat-input.tsx index 22fe899..cd66ce6 100644 --- a/src/components/chat-input.tsx +++ b/src/components/chat-input.tsx @@ -10,15 +10,7 @@ import { } from '@mui/material'; import SendIcon from '@mui/icons-material/Send'; -type ChatInputProps = { - value: string; - onChange: (newValue: string) => unknown; - onSend: () => unknown; - sendWithShiftEnter: boolean; - sx?: SxProps; -}; - -export function ChatInput(props: ChatInputProps): JSX.Element { +export function ChatInput(props: ChatInput.IProps): JSX.Element { function handleKeyDown(event: React.KeyboardEvent) { if ( event.key === 'Enter' && @@ -77,3 +69,19 @@ export function ChatInput(props: ChatInputProps): JSX.Element { ); } + +/** + * The chat input namespace. + */ +export namespace ChatInput { + /** + * The properties of the react element. + */ + export interface IProps { + value: string; + onChange: (newValue: string) => unknown; + onSend: () => unknown; + sendWithShiftEnter: boolean; + sx?: SxProps; + } +} diff --git a/src/components/chat-messages.tsx b/src/components/chat-messages.tsx index 02953dc..880388f 100644 --- a/src/components/chat-messages.tsx +++ b/src/components/chat-messages.tsx @@ -4,14 +4,14 @@ import type { SxProps, Theme } from '@mui/material'; import React, { useState, useEffect } from 'react'; import { RendermimeMarkdown } from './rendermime-markdown'; -import { ChatService } from '../services'; +import { IChatMessage, IUser } from '../types'; type ChatMessagesProps = { rmRegistry: IRenderMimeRegistry; - messages: ChatService.IChatMessage[]; + messages: IChatMessage[]; }; -export type ChatMessageHeaderProps = ChatService.IUser & { +export type ChatMessageHeaderProps = IUser & { timestamp: string; sx?: SxProps; }; diff --git a/src/components/chat-settings.tsx b/src/components/chat-settings.tsx deleted file mode 100644 index 0949882..0000000 --- a/src/components/chat-settings.tsx +++ /dev/null @@ -1,158 +0,0 @@ -import { Box } from '@mui/system'; -import { - Alert, - Button, - FormControl, - FormControlLabel, - FormLabel, - Radio, - RadioGroup, - CircularProgress -} from '@mui/material'; -import React, { useEffect, useState } from 'react'; - -import { useStackingAlert } from './mui-extras/stacking-alert'; -import { ServerInfoState, useServerInfo } from './settings/use-server-info'; -import { minifyUpdate } from './settings/minify'; -import { ChatService } from '../services'; - -/** - * Component that returns the settings view in the chat panel. - */ -export function ChatSettings(): JSX.Element { - // state fetched on initial render - const server = useServerInfo(); - - // initialize alert helper - const alert = useStackingAlert(); - - const [sendWse, setSendWse] = useState(false); - - // whether the form is currently saving - const [saving, setSaving] = useState(false); - - /** - * Effect: initialize inputs after fetching server info. - */ - useEffect(() => { - if (server.state !== ServerInfoState.Ready) { - return; - } - setSendWse(server.config.send_with_shift_enter); - }, [server]); - - const handleSave = async () => { - // compress fields with JSON values - if (server.state !== ServerInfoState.Ready) { - return; - } - - let updateRequest: ChatService.UpdateConfigRequest = { - send_with_shift_enter: sendWse - }; - updateRequest = minifyUpdate(server.config, updateRequest); - updateRequest.last_read = server.config.last_read; - - setSaving(true); - try { - await ChatService.updateConfig(updateRequest); - } catch (e) { - console.error(e); - const msg = - e instanceof Error || typeof e === 'string' - ? e.toString() - : 'An unknown error occurred. Check the console for more details.'; - alert.show('error', msg); - return; - } finally { - setSaving(false); - } - await server.refetchAll(); - alert.show('success', 'Settings saved successfully.'); - }; - - if (server.state === ServerInfoState.Loading) { - return ( - - - - ); - } - - if (server.state === ServerInfoState.Error) { - return ( - - - {server.error || - 'An unknown error occurred. Check the console for more details.'} - - - ); - } - - return ( - - {/* Input */} -

Input

- - - When writing a message, press Enter to: - - { - setSendWse(e.target.value === 'newline'); - }} - > - } - label="Send the message" - /> - } - label={ - <> - Start a new line (use Shift+Enter to send) - - } - /> - - - - - - {alert.jsx} -
- ); -} diff --git a/src/components/chat.tsx b/src/components/chat.tsx index e593f42..42a7ff6 100644 --- a/src/components/chat.tsx +++ b/src/components/chat.tsx @@ -1,4 +1,3 @@ -import type { IThemeManager } from '@jupyterlab/apputils'; import { IRenderMimeRegistry } from '@jupyterlab/rendermime'; import ArrowBackIcon from '@mui/icons-material/ArrowBack'; import SettingsIcon from '@mui/icons-material/Settings'; @@ -9,10 +8,10 @@ import React, { useState, useEffect } from 'react'; import { JlThemeProvider } from './jl-theme-provider'; import { ChatMessages } from './chat-messages'; import { ChatInput } from './chat-input'; -import { ChatSettings } from './chat-settings'; import { ScrollContainer } from './scroll-container'; import { IChatModel } from '../model'; -import { ChatService } from '../services'; +import { IChatMessage, IMessage } from '../types'; +import { IThemeManager } from '@jupyterlab/apputils'; type ChatBodyProps = { chatModel: IChatModel; @@ -23,22 +22,13 @@ function ChatBody({ chatModel, rmRegistry: renderMimeRegistry }: ChatBodyProps): JSX.Element { - const [messages, setMessages] = useState([]); + const [messages, setMessages] = useState([]); const [input, setInput] = useState(''); - const [sendWithShiftEnter, setSendWithShiftEnter] = useState(true); /** * Effect: fetch history and config on initial render */ useEffect(() => { - async function getConfig() { - ChatService.getConfig() - .then(config => - setSendWithShiftEnter(config.send_with_shift_enter ?? false) - ) - .catch(e => console.error(e)); - } - async function fetchHistory() { if (!chatModel.getHistory) { return; @@ -49,7 +39,6 @@ function ChatBody({ .catch(e => console.error(e)); } - getConfig(); fetchHistory(); }, [chatModel]); @@ -57,14 +46,13 @@ function ChatBody({ * Effect: listen to chat messages */ useEffect(() => { - function handleChatEvents(_: IChatModel, message: ChatService.IMessage) { - if (message.type === 'connection') { - return; - } else if (message.type === 'clear') { + function handleChatEvents(_: IChatModel, message: IMessage) { + if (message.type === 'clear') { setMessages([]); return; + } else if (message.type === 'msg') { + setMessages(messageGroups => [...messageGroups, message]); } - setMessages(messageGroups => [...messageGroups, message]); } chatModel.incomingMessage.connect(handleChatEvents); @@ -98,26 +86,16 @@ function ChatBody({ paddingBottom: 0, borderTop: '1px solid var(--jp-border-color1)' }} - sendWithShiftEnter={sendWithShiftEnter} + sendWithShiftEnter={chatModel.config.sendWithShiftEnter ?? false} /> ); } -export type ChatProps = { - chatModel: IChatModel; - themeManager: IThemeManager | null; - rmRegistry: IRenderMimeRegistry; - chatView?: ChatView; -}; - -enum ChatView { - Chat, - Settings -} - -export function Chat(props: ChatProps): JSX.Element { - const [view, setView] = useState(props.chatView || ChatView.Chat); +export function Chat(props: Chat.IOptions): JSX.Element { + const [view, setView] = useState( + props.chatView || Chat.ChatView.Chat + ); console.log('Instantiate a chat'); return ( @@ -135,15 +113,15 @@ export function Chat(props: ChatProps): JSX.Element { > {/* top bar */} - {view !== ChatView.Chat ? ( - setView(ChatView.Chat)}> + {view !== Chat.ChatView.Chat ? ( + setView(Chat.ChatView.Chat)}> ) : ( )} - {view === ChatView.Chat ? ( - setView(ChatView.Settings)}> + {view === Chat.ChatView.Chat && props.settingsPanel ? ( + setView(Chat.ChatView.Settings)}> ) : ( @@ -151,11 +129,53 @@ export function Chat(props: ChatProps): JSX.Element { )} {/* body */} - {view === ChatView.Chat && ( + {view === Chat.ChatView.Chat && ( )} - {view === ChatView.Settings && } + {view === Chat.ChatView.Settings && props.settingsPanel && ( + + )} ); } + +/** + * The chat UI namespace + */ +export namespace Chat { + /** + * The options to build the Chat UI. + */ + export interface IOptions { + /** + * The chat model. + */ + chatModel: IChatModel; + /** + * The theme manager. + */ + themeManager: IThemeManager | null; + /** + * The rendermime registry. + */ + rmRegistry: IRenderMimeRegistry; + /** + * The view to render. + */ + chatView?: ChatView; + /** + * A settings panel that can be used for dedicated settings (e.g. jupyter-ai) + */ + settingsPanel?: () => JSX.Element; + } + + /** + * The view to render. + * The settings view is available only if the settings panel is provided in options. + */ + export enum ChatView { + Chat, + Settings + } +} diff --git a/src/components/settings/minify.ts b/src/components/settings/minify.ts deleted file mode 100644 index daff8f1..0000000 --- a/src/components/settings/minify.ts +++ /dev/null @@ -1,56 +0,0 @@ -import { ChatService } from '../../services'; - -/** - * Function that minimizes the `UpdateConfigRequest` object prior to submission. - * Removes properties with values identical to those specified in the server - * configuration. - */ -export function minifyUpdate( - config: ChatService.DescribeConfigResponse, - update: ChatService.UpdateConfigRequest -): ChatService.UpdateConfigRequest { - return minifyPatchObject(config, update) as ChatService.UpdateConfigRequest; -} - -/** - * Function that removes all properties from `patch` that have identical values - * to `obj` recursively. - */ -export function minifyPatchObject( - obj: Record, - patch: Record -): Record { - const diffObj: Record = {}; - for (const key in patch) { - if (!(key in obj) || typeof obj[key] !== typeof patch[key]) { - // if key is not present in oldObj, or if the value types do not match, - // use the value of `patch`. - diffObj[key] = patch[key]; - continue; - } - - const objVal = obj[key]; - const patchVal = patch[key]; - if (Array.isArray(objVal) && Array.isArray(patchVal)) { - // if objects are both arrays but are not equal, then use the value - const areNotEqual = - objVal.length !== patchVal.length || - !objVal.every((objVal_i, i) => objVal_i === patchVal[i]); - if (areNotEqual) { - diffObj[key] = patchVal; - } - } else if (typeof patchVal === 'object') { - // if the value is an object, run `diffObjects` recursively. - const childPatch = minifyPatchObject(objVal, patchVal); - const isNonEmpty = !!Object.keys(childPatch)?.length; - if (isNonEmpty) { - diffObj[key] = childPatch; - } - } else if (objVal !== patchVal) { - // otherwise, use the value of `patch` only if it differs. - diffObj[key] = patchVal; - } - } - - return diffObj; -} diff --git a/src/components/settings/use-server-info.ts b/src/components/settings/use-server-info.ts deleted file mode 100644 index 204dcb6..0000000 --- a/src/components/settings/use-server-info.ts +++ /dev/null @@ -1,86 +0,0 @@ -import { useState, useEffect, useMemo, useCallback } from 'react'; -import { ChatService } from '../../services'; - -type ServerInfoProperties = { - config: ChatService.DescribeConfigResponse; -}; - -type ServerInfoMethods = { - refetchAll: () => Promise; -}; - -export enum ServerInfoState { - /** - * Server info is being fetched. - */ - Loading, - /** - * Unable to retrieve server info. - */ - Error, - /** - * Server info was loaded successfully. - */ - Ready -} - -type ServerInfoLoading = { state: ServerInfoState.Loading }; -type ServerInfoError = { - state: ServerInfoState.Error; - error: string; -}; -type ServerInfoReady = { state: ServerInfoState.Ready } & ServerInfoProperties & - ServerInfoMethods; - -type ServerInfo = ServerInfoLoading | ServerInfoError | ServerInfoReady; - -/** - * A hook that fetches the current configuration and provider lists from the - * server. Returns a `ServerInfo` object that includes methods. - */ -export function useServerInfo(): ServerInfo { - const [state, setState] = useState(ServerInfoState.Loading); - const [serverInfoProps, setServerInfoProps] = - useState(); - const [error, setError] = useState(''); - - const fetchServerInfo = useCallback(async () => { - try { - const config = await ChatService.getConfig(); - setServerInfoProps({ config }); - - setState(ServerInfoState.Ready); - } catch (e) { - console.error(e); - if (e instanceof Error) { - setError(e.toString()); - } else { - setError('An unknown error occurred.'); - } - setState(ServerInfoState.Error); - } - }, []); - - /** - * Effect: fetch server info on initial render - */ - useEffect(() => { - fetchServerInfo(); - }, []); - - return useMemo(() => { - if (state === ServerInfoState.Loading) { - return { state }; - } - - if (state === ServerInfoState.Error || !serverInfoProps) { - return { state: ServerInfoState.Error, error }; - } - - return { - state, - ...serverInfoProps, - refetchAll: fetchServerInfo - }; - }, [state, serverInfoProps, error]); -} diff --git a/src/components/settings/validator.ts b/src/components/settings/validator.ts deleted file mode 100644 index cea6ad8..0000000 --- a/src/components/settings/validator.ts +++ /dev/null @@ -1,3 +0,0 @@ -export class SettingsValidator { - constructor() {} -} diff --git a/src/handlers/websocket-handler.ts b/src/handlers/websocket-handler.ts index aedba8c..1d0d272 100644 --- a/src/handlers/websocket-handler.ts +++ b/src/handlers/websocket-handler.ts @@ -4,10 +4,17 @@ import { UUID } from '@lumino/coreutils'; import { requestAPI } from './handler'; import { ChatModel, IChatModel } from '../model'; -import { ChatService } from '../services'; +import { IChatHistory, IMessage, INewMessage } from '../types'; const CHAT_SERVICE_URL = 'api/chat'; +export type ConnectionMessage = { + type: 'connection'; + client_id: string; +}; + +type GenericMessage = IMessage | ConnectionMessage; + /** * An implementation of the chat model based on websocket handler. */ @@ -39,7 +46,7 @@ export class WebSocketHandler extends ChatModel { * Sends a message across the WebSocket. Promise resolves to the message ID * when the server sends the same message back, acknowledging receipt. */ - addMessage(message: ChatService.ChatRequest): Promise { + addMessage(message: INewMessage): Promise { message.id = UUID.uuid4(); return new Promise(resolve => { this._socket?.send(JSON.stringify(message)); @@ -47,8 +54,8 @@ export class WebSocketHandler extends ChatModel { }); } - async getHistory(): Promise { - let data: ChatService.ChatHistory = { messages: [] }; + async getHistory(): Promise { + let data: IChatHistory = { messages: [] }; try { data = await requestAPI('history', { method: 'GET' @@ -77,7 +84,7 @@ export class WebSocketHandler extends ChatModel { } } - onMessage(message: ChatService.IMessage): void { + onMessage(message: IMessage): void { // resolve promise from `sendMessage()` if (message.type === 'msg' && message.sender.id === this.id) { this._sendResolverQueue.get(message.id)?.(true); @@ -115,10 +122,7 @@ export class WebSocketHandler extends ChatModel { socket.onmessage = msg => msg.data && this.onMessage(JSON.parse(msg.data)); - const listenForConnection = ( - _: IChatModel, - message: ChatService.IMessage - ) => { + const listenForConnection = (_: IChatModel, message: GenericMessage) => { if (message.type !== 'connection') { return; } diff --git a/src/index.ts b/src/index.ts index 27b40d8..84630cf 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,6 +1,6 @@ export * from './handlers/websocket-handler'; export * from './model'; -export * from './services'; +export * from './types'; export * from './widgets/chat-error'; export * from './widgets/chat-sidebar'; export * from './widgets/chat-widget'; diff --git a/src/model.ts b/src/model.ts index 0a9abf7..482e8fb 100644 --- a/src/model.ts +++ b/src/model.ts @@ -1,28 +1,42 @@ import { IDisposable } from '@lumino/disposable'; import { ISignal, Signal } from '@lumino/signaling'; -import { ChatService } from './services'; +import { + IChatHistory, + INewMessage, + IChatMessage, + IConfig, + IMessage +} from './types'; +/** + * The chat model interface. + */ export interface IChatModel extends IDisposable { /** * The chat model ID. */ id: string; + /** + * The configuration for the chat panel. + */ + config: IConfig; + /** * The signal emitted when a new message is received. */ - get incomingMessage(): ISignal; + get incomingMessage(): ISignal; /** * The signal emitted when a message is updated. */ - get messageUpdated(): ISignal; + get messageUpdated(): ISignal; /** * The signal emitted when a message is updated. */ - get messageDeleted(): ISignal; + get messageDeleted(): ISignal; /** * Send a message, to be defined depending on the chosen technology. @@ -31,9 +45,7 @@ export interface IChatModel extends IDisposable { * @param message - the message to send. * @returns whether the message has been sent or not, or nothing if not needed. */ - addMessage( - message: ChatService.ChatRequest - ): Promise | boolean | void; + addMessage(message: INewMessage): Promise | boolean | void; /** * Optional, to update a message from the chat. @@ -43,13 +55,13 @@ export interface IChatModel extends IDisposable { */ updateMessage?( id: string, - message: ChatService.ChatRequest + message: INewMessage ): Promise | boolean | void; /** * Optional, to get messages history. */ - getHistory?(): Promise; + getHistory?(): Promise; /** * Dispose the chat model. @@ -66,14 +78,14 @@ export interface IChatModel extends IDisposable { * * @param message - the new message, containing user information and body. */ - onMessage(message: ChatService.IMessage): void; + onMessage(message: IMessage): void; /** * Function to call when a message is updated. * * @param message - the message updated, containing user information and body. */ - onMessageUpdated?(message: ChatService.IMessage): void; + onMessageUpdated?(message: IMessage): void; } /** @@ -85,7 +97,9 @@ export class ChatModel implements IChatModel { /** * Create a new chat model. */ - constructor(options: ChatModel.IOptions = {}) {} + constructor(options: ChatModel.IOptions = {}) { + this._config = options.config ?? {}; + } /** * The chat model ID. @@ -98,23 +112,34 @@ export class ChatModel implements IChatModel { } /** + * The chat settings. + */ + get config(): IConfig { + return this._config; + } + set config(value: Partial) { + this._config = { ...this._config, ...value }; + } + + /** + * * The signal emitted when a new message is received. */ - get incomingMessage(): ISignal { + get incomingMessage(): ISignal { return this._incomingMessage; } /** * The signal emitted when a message is updated. */ - get messageUpdated(): ISignal { + get messageUpdated(): ISignal { return this._messageUpdated; } /** * The signal emitted when a message is updated. */ - get messageDeleted(): ISignal { + get messageDeleted(): ISignal { return this._messageDeleted; } @@ -125,9 +150,7 @@ export class ChatModel implements IChatModel { * @param message - the message to send. * @returns whether the message has been sent or not. */ - addMessage( - message: ChatService.ChatRequest - ): Promise | boolean | void {} + addMessage(message: INewMessage): Promise | boolean | void {} /** * Dispose the chat model. @@ -150,9 +173,7 @@ export class ChatModel implements IChatModel { * A function called before transferring the message to the panel(s). * Can be useful if some actions are required on the message. */ - protected formatChatMessage( - message: ChatService.IChatMessage - ): ChatService.IChatMessage { + protected formatChatMessage(message: IChatMessage): IChatMessage { return message; } @@ -161,23 +182,20 @@ export class ChatModel implements IChatModel { * * @param message - the message with user information and body. */ - onMessage(message: ChatService.IMessage): void { + onMessage(message: IMessage): void { if (message.type === 'msg') { - message = this.formatChatMessage(message as ChatService.IChatMessage); + message = this.formatChatMessage(message as IChatMessage); } this._incomingMessage.emit(message); } private _id: string = ''; + private _config: IConfig; private _isDisposed = false; - private _incomingMessage = new Signal(this); - private _messageUpdated = new Signal( - this - ); - private _messageDeleted = new Signal( - this - ); + private _incomingMessage = new Signal(this); + private _messageUpdated = new Signal(this); + private _messageDeleted = new Signal(this); } /** @@ -187,5 +205,10 @@ export namespace ChatModel { /** * The instantiation options for a ChatModel. */ - export interface IOptions {} + export interface IOptions { + /** + * Initial config for the chat widget. + */ + config?: IConfig; + } } diff --git a/src/services.ts b/src/services.ts deleted file mode 100644 index d63381a..0000000 --- a/src/services.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { requestAPI } from './handlers/handler'; - -export namespace ChatService { - export interface IUser { - id: string; - username?: string; - name?: string; - display_name?: string; - initials?: string; - color?: string; - avatar_url?: string; - } - - export interface IChatMessage { - type: 'msg'; - body: string; - id: string; - time: number; - sender: IUser; - } - - export type ConnectionMessage = { - type: 'connection'; - client_id: string; - }; - - export type ClearMessage = { - type: 'clear'; - }; - - export type IMessage = IChatMessage | ConnectionMessage | ClearMessage; - - export type ChatHistory = { - messages: IChatMessage[]; - }; - - export type ChatRequest = { - body: string; - id?: string; - }; - - export type DescribeConfigResponse = { - send_with_shift_enter: boolean; - last_read: number; - }; - - export type UpdateConfigRequest = { - send_with_shift_enter?: boolean; - last_read?: number; - }; - - export async function getConfig(): Promise { - return requestAPI('config'); - } - - export async function updateConfig( - config: UpdateConfigRequest - ): Promise { - return requestAPI('config', { - method: 'POST', - body: JSON.stringify(config) - }); - } -} diff --git a/src/types.ts b/src/types.ts new file mode 100644 index 0000000..5a81a52 --- /dev/null +++ b/src/types.ts @@ -0,0 +1,57 @@ +/** + * The user description. + */ +export interface IUser { + id: string; + username?: string; + name?: string; + display_name?: string; + initials?: string; + color?: string; + avatar_url?: string; +} + +/** + * The configuration interface. + */ +export interface IConfig { + sendWithShiftEnter?: boolean; + lastRead?: number; +} + +/** + * The chat message decription. + */ +export interface IChatMessage { + type: 'msg'; + body: string; + id: string; + time: number; + sender: IUser; +} + +export type IClearMessage = { + type: 'clear'; +}; + +export type IMessage = IChatMessage | IClearMessage; + +/** + * The chat history interface. + */ +export interface IChatHistory { + messages: IChatMessage[]; +} + +/** + * The content of a new message. + */ +export interface INewMessage { + body: string; + id?: string; +} + +/** + * An empty interface to describe optional settings taht could be fetched from server. + */ +export interface ISettings {} diff --git a/src/widgets/chat-widget.tsx b/src/widgets/chat-widget.tsx index 08d278e..859aee1 100644 --- a/src/widgets/chat-widget.tsx +++ b/src/widgets/chat-widget.tsx @@ -7,7 +7,7 @@ import { chatIcon } from '../icons'; import { IChatModel } from '../model'; export class ChatWidget extends ReactWidget { - constructor(options: ChatWidget.IOptions) { + constructor(options: Chat.IOptions) { super(); this.id = 'jupyter-chat::widget'; @@ -35,9 +35,5 @@ export class ChatWidget extends ReactWidget { } export namespace ChatWidget { - export interface IOptions { - chatModel: IChatModel; - themeManager: IThemeManager | null; - rmRegistry: IRenderMimeRegistry; - } + export interface IOptions extends Chat.IOptions {} }