Skip to content

Commit

Permalink
feat: allow chatting only with a valid configuration
Browse files Browse the repository at this point in the history
  • Loading branch information
provos committed Jan 30, 2025
1 parent f174eda commit f75ba6e
Show file tree
Hide file tree
Showing 5 changed files with 158 additions and 57 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,20 @@ Outgoing Events (sent):
import { messageBus } from '../stores/messageBus.svelte.js';
import { FontAwesomeIcon } from '@fortawesome/svelte-fontawesome';
import { faPaperPlane, faStop } from '@fortawesome/free-solid-svg-icons';
import { configState } from '../stores/configStore.svelte.js';
// Declare state variables properly
let currentSocket = $state(null);
let currentSessionId = $state(null);
let currentConnectionStatus = $state('disconnected');
// Subscribe to sessionState store with proper state updates
sessionState.subscribe((state) => {
if (state.socket != currentSocket) currentSocket = state.socket;
if (state.sessionId != currentSessionId) currentSessionId = state.sessionId;
if (state.connectionStatus != currentConnectionStatus)
currentConnectionStatus = state.connectionStatus;
});
// Replace props with state
let messages = $state([]);
Expand Down Expand Up @@ -91,7 +105,7 @@ Outgoing Events (sent):
content: payload.message,
timestamp: new Date()
}
]
];
break;
case 'thinkingUpdate':
console.log('Thinking update:', payload);
Expand All @@ -116,8 +130,8 @@ Outgoing Events (sent):
isLoading = false;
break;
case 'cleanup':
if (sessionState.socket) {
sessionState.socket.disconnect();
if (currentSocket) {
currentSocket.disconnect();
}
break;
}
Expand All @@ -128,7 +142,7 @@ Outgoing Events (sent):
// Existing functions
function handleSendMessage(message) {
if (!sessionState.sessionId || sessionState.connectionStatus !== 'connected') return;
if (!currentSessionId || currentConnectionStatus !== 'connected') return;
isLoading = true;
error = null;
Expand All @@ -142,26 +156,35 @@ Outgoing Events (sent):
messages = [...messages, userMessage];
// Convert messages to simplified format for backend
const messageHistory = messages.map(msg => ({
const messageHistory = messages.map((msg) => ({
role: msg.role,
content: msg.content
}));
sessionState.socket?.emit('chat_message', {
session_id: sessionState.sessionId,
currentSocket?.emit('chat_message', {
session_id: currentSessionId,
messages: messageHistory
});
}
$effect(() => {
console.log('ChatInterface connection status:', sessionState.connectionStatus);
console.log('ChatInterface connection status:', currentConnectionStatus);
});
let currentConfig = $state(null);
configState.subscribe(state => {
currentConfig = state;
});
function handleSend() {
if (sessionState.connectionStatus !== 'connected') {
if (currentConnectionStatus !== 'connected') {
error = 'Cannot send message while disconnected';
return;
}
if (!currentConfig.isValid) {
error = 'Please configure valid provider settings first';
return;
}
if (messageInput.trim()) {
handleSendMessage(messageInput);
messageInput = '';
Expand All @@ -176,9 +199,9 @@ Outgoing Events (sent):
function handleAbort() {
console.log('Aborting current request...');
if (sessionState.socket) {
sessionState.socket.emit('abort', {
session_id: sessionState.sessionId
if (currentSocket) {
currentSocket.emit('abort', {
session_id: currentSessionId
});
}
isLoading = false;
Expand All @@ -191,11 +214,11 @@ Outgoing Events (sent):
<div class="chat-wrapper">
<h1 class="chat-title">PlanAI Research</h1>
{#if sessionState.connectionStatus !== 'connected'}
<div class="connection-status {sessionState.connectionStatus}">
{sessionState.connectionStatus === 'reconnecting'
{#if currentConnectionStatus !== 'connected'}
<div class="connection-status {currentConnectionStatus}">
{currentConnectionStatus === 'reconnecting'
? 'Reconnecting...'
: sessionState.connectionStatus === 'failed'
: currentConnectionStatus === 'failed'
? 'Connection failed'
: 'Disconnected'}
</div>
Expand All @@ -208,9 +231,9 @@ Outgoing Events (sent):
<div
class="message-bubble {message.role === 'user'
? 'message-bubble-user'
: message.role === 'error'
? 'message-bubble-error'
: 'message-bubble-assistant'}"
: message.role === 'error'
? 'message-bubble-error'
: 'message-bubble-assistant'}"
>
{#if message.isMarkdown}
<div class="message-text prose prose-sm dark:prose-invert">
Expand Down Expand Up @@ -251,13 +274,13 @@ Outgoing Events (sent):
placeholder="Type your message..."
class="input-field"
onkeydown={handleKeyDown}
disabled={isLoading || sessionState.connectionStatus !== 'connected'}
disabled={isLoading || currentConnectionStatus !== 'connected'}
/>
<button
onclick={isLoading ? handleAbort : handleSend}
disabled={sessionState.connectionStatus !== 'connected'}
disabled={currentConnectionStatus !== 'connected' || !currentConfig.isValid}
class="{isLoading ? 'stop-button' : 'send-button'} {!isLoading &&
sessionState.connectionStatus !== 'connected'
(currentConnectionStatus !== 'connected' || !currentConfig.isValid)
? 'send-button-disabled'
: isLoading
? ''
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,12 @@ See the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
import { sessionState } from '../stores/sessionStore.svelte.js';
import { messageBus } from '../stores/messageBus.svelte.js';
// Subscribe to sessionState to get socket updates
let currentSocket = $state(null);
sessionState.subscribe(state => {
currentSocket = state.socket;
});
function loadStoredSession() {
const storedId = localStorage.getItem('chatSessionId');
if (storedId) {
Expand All @@ -27,17 +33,17 @@ See the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
function saveSessionId(id) {
localStorage.setItem('chatSessionId', id);
sessionState.sessionId = id;
sessionState.update(state => ({ ...state, sessionId: id }));
}
$effect(() => {
const unsubscribe = messageBus.subscribe(({ type, payload }) => {
if (type === 'loadSettings' && sessionState.socket) {
sessionState.socket.emit('load_settings');
} else if (type === 'saveSettings' && sessionState.socket) {
sessionState.socket.emit('save_settings', payload);
} else if (type === 'validateProvider' && sessionState.socket) {
sessionState.socket.emit('validate_provider', payload);
if (type === 'loadSettings' && currentSocket) {
currentSocket.emit('load_settings');
} else if (type === 'saveSettings' && currentSocket) {
currentSocket.emit('save_settings', payload);
} else if (type === 'validateProvider' && currentSocket) {
currentSocket.emit('validate_provider', payload);
}
});
return () => unsubscribe();
Expand All @@ -46,7 +52,7 @@ See the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
function initializeSocket() {
const storedSessionId = loadStoredSession();
if (storedSessionId) {
sessionState.sessionId = storedSessionId;
sessionState.update(state => ({ ...state, sessionId: storedSessionId }));
}
const socket = io('http://localhost:5050', {
Expand All @@ -60,8 +66,10 @@ See the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
socket.on('connect', () => {
console.log('Connected to chat server');
sessionState.connectionStatus = 'connected';
sessionState.update(state => ({ ...state, connectionStatus: 'connected' }));
messageBus.error(null);
// Load settings on initial connection
socket.emit('load_settings');
});
socket.on('session_id', (data) => {
Expand All @@ -76,17 +84,17 @@ See the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
socket.on('disconnect', () => {
console.log('Disconnected from server');
sessionState.connectionStatus = 'disconnected';
sessionState.update(state => ({ ...state, connectionStatus: 'disconnected' }));
messageBus.error('Connection lost. Attempting to reconnect...');
});
socket.on('reconnecting', (attemptNumber) => {
sessionState.connectionStatus = 'reconnecting';
sessionState.update(state => ({ ...state, connectionStatus: 'reconnecting' }));
messageBus.error(`Reconnecting... Attempt ${attemptNumber}`);
});
socket.on('reconnect_failed', () => {
sessionState.connectionStatus = 'failed';
sessionState.update(state => ({ ...state, connectionStatus: 'failed' }));
messageBus.error('Failed to reconnect. Please refresh the page.');
});
Expand Down Expand Up @@ -131,7 +139,7 @@ See the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
}
});
sessionState.socket = socket;
sessionState.update(state => ({ ...state, socket }));
}
onMount(() => {
Expand All @@ -141,8 +149,8 @@ See the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International
onDestroy(() => {
messageBus.cleanup();
if (sessionState.socket) {
sessionState.socket.disconnect();
if (currentSocket) {
currentSocket.disconnect();
}
});
</script>
Loading

0 comments on commit f75ba6e

Please sign in to comment.