Skip to content

Commit 1a197eb

Browse files
committed
fixed connectio nand spamming on deepresearch
1 parent ba3cd75 commit 1a197eb

File tree

6 files changed

+205
-76
lines changed

6 files changed

+205
-76
lines changed

lib/AIAssistant/AIAssistant-Backend.js

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1513,6 +1513,15 @@ When user asks for something, generate creative, compact p5.js code that creates
15131513
}
15141514

15151515
async generateContent(prompt, type = 'creative') {
1516+
// Validate that AI session is properly established
1517+
if (!this.aiSession) {
1518+
throw new Error('AI session not established. Please connect to an AI provider first.');
1519+
}
1520+
1521+
if (!this.aiSession.provider) {
1522+
throw new Error('AI session is missing provider information. Please reconnect to your AI provider.');
1523+
}
1524+
15161525
if (type === 'research' || type === 'general') {
15171526
// For research and general generation, use general context instead of creative
15181527
this.setChatMode('general');
@@ -1529,6 +1538,11 @@ When user asks for something, generate creative, compact p5.js code that creates
15291538
let content = '';
15301539

15311540
if (this.aiSession.provider === 'ollama') {
1541+
// Validate Ollama session has required properties
1542+
if (!this.aiSession.baseURL || !this.aiSession.model) {
1543+
throw new Error('Ollama session is incomplete. Missing baseURL or model. Please reconnect.');
1544+
}
1545+
15321546
// Use simple chat format for general/RAG responses
15331547
const chatPrompt = `<|im_start|>system
15341548
You are a helpful AI assistant. Provide clear, accurate, and informative responses based on the given context. Always respond in plain text format.<|im_end|>
@@ -1570,7 +1584,7 @@ ${userMessage}<|im_end|>
15701584
content = data.response || '';
15711585

15721586
} else {
1573-
throw new Error('Only Ollama provider is currently supported for general/research generation');
1587+
throw new Error(`Provider '${this.aiSession.provider}' is not currently supported for general/research generation`);
15741588
}
15751589

15761590
return content.trim();

lib/Pages/DeepResearch/deepresearch.js

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -696,9 +696,7 @@ class DeepResearchApp {
696696
const connectionAge = Date.now() - connectionData.timestamp;
697697
hasAI = connectionData.connected && connectionAge < (30 * 60 * 1000);
698698

699-
if (hasAI) {
700-
console.log('🔄 Using stored AI connection state as fallback');
701-
}
699+
// Using stored AI connection state as fallback (logged once)
702700
}
703701
} catch (error) {
704702
console.warn('⚠️ Failed to check stored AI connection state:', error);

lib/Pages/Playground/playground.js

Lines changed: 67 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@ class PlaygroundApp {
1111
this.search = null; // Will be initialized with PlaygroundSearch
1212
this.isConnected = false;
1313
this.isResearching = false;
14+
this.sharedListenerSetup = false;
15+
this.lastConnectionMessageTime = 0;
1416

1517
this.init();
1618
}
@@ -136,7 +138,12 @@ class PlaygroundApp {
136138
this.isConnected = true;
137139
this.updateStatus('aiStatus', `Connected (${currentProvider.provider})`, 'success');
138140
this.updateConnectButtonText();
139-
this.addChatMessage('system', `🤖 Using existing AI connection (${currentProvider.provider}). Ready to help!`);
141+
142+
// Only add message if we don't already have a recent connection message
143+
if (!this.hasRecentConnectionMessage()) {
144+
this.addChatMessage('system', `🤖 Using existing AI connection (${currentProvider.provider}). Ready to help!`);
145+
this.lastConnectionMessageTime = Date.now();
146+
}
140147
}
141148
} else {
142149
console.log('🔍 No active shared connection found after restoration check');
@@ -170,7 +177,7 @@ class PlaygroundApp {
170177
}
171178

172179
setupSharedConnectionListener() {
173-
if (window.SharedAIConnection) {
180+
if (window.SharedAIConnection && !this.sharedListenerSetup) {
174181
// Listen for connection changes from other pages
175182
window.SharedAIConnection.addConnectionListener((event, data) => {
176183
console.log('🔄 Playground received shared connection event:', event, data);
@@ -183,7 +190,12 @@ class PlaygroundApp {
183190
this.isConnected = true;
184191
this.updateStatus('aiStatus', `Connected (${providerInfo.provider})`, 'success');
185192
this.updateConnectButtonText();
186-
this.addChatMessage('system', `🤖 AI connected via ${providerInfo.provider}. Ready to help!`);
193+
194+
// Only add message if we don't already have a recent connection message
195+
if (!this.hasRecentConnectionMessage()) {
196+
this.addChatMessage('system', `🤖 AI connected via ${providerInfo.provider}. Ready to help!`);
197+
this.lastConnectionMessageTime = Date.now();
198+
}
187199
} else if (event === 'disconnected') {
188200
this.isConnected = false;
189201
this.updateStatus('aiStatus', 'Ready to Connect', 'info');
@@ -196,6 +208,8 @@ class PlaygroundApp {
196208
this.addChatMessage('system', `❌ AI connection error: ${data.message}`);
197209
}
198210
});
211+
212+
this.sharedListenerSetup = true;
199213
}
200214
}
201215

@@ -229,7 +243,12 @@ class PlaygroundApp {
229243
this.isConnected = true;
230244
this.updateStatus('aiStatus', `Connected (${currentProvider.provider})`, 'success');
231245
this.updateConnectButtonText();
232-
this.addChatMessage('system', `🤖 Using existing AI connection (${currentProvider.provider}). Ready to help!`);
246+
247+
// Only add message if we don't already have a recent connection message
248+
if (!this.hasRecentConnectionMessage()) {
249+
this.addChatMessage('system', `🤖 Using existing AI connection (${currentProvider.provider}). Ready to help!`);
250+
this.lastConnectionMessageTime = Date.now();
251+
}
233252

234253
connectButton.disabled = false;
235254
return;
@@ -250,7 +269,12 @@ class PlaygroundApp {
250269
this.isConnected = true;
251270
this.updateStatus('aiStatus', `Connected (${window.SharedAIConnection.currentProvider})`, 'success');
252271
this.updateConnectButtonText();
253-
this.addChatMessage('system', `🤖 AI Assistant connected using ${window.SharedAIConnection.currentProvider}. Ready to help!`);
272+
273+
// Only add message if we don't already have a recent connection message
274+
if (!this.hasRecentConnectionMessage()) {
275+
this.addChatMessage('system', `🤖 AI Assistant connected using ${window.SharedAIConnection.currentProvider}. Ready to help!`);
276+
this.lastConnectionMessageTime = Date.now();
277+
}
254278

255279
connectButton.disabled = false;
256280
} else if (event === 'error') {
@@ -323,7 +347,12 @@ class PlaygroundApp {
323347
this.isConnected = true;
324348
this.updateStatus('aiStatus', `Connected (${status.provider})`, 'success');
325349
this.updateConnectButtonText();
326-
this.addChatMessage('system', `🤖 AI Assistant connected using ${status.provider}. Ready to help!`);
350+
351+
// Only add message if we don't already have a recent connection message
352+
if (!this.hasRecentConnectionMessage()) {
353+
this.addChatMessage('system', `🤖 AI Assistant connected using ${status.provider}. Ready to help!`);
354+
this.lastConnectionMessageTime = Date.now();
355+
}
327356
} else if (status.error) {
328357
this.isConnected = false;
329358
this.updateStatus('aiStatus', 'Connection Issue', 'error');
@@ -491,19 +520,43 @@ Based on the research, here are the key recommendations:
491520
input.value = '';
492521
input.style.height = 'auto';
493522

494-
// Check if AI is connected
495-
if (!this.isConnected || !this.aiAssistant) {
523+
// Enhanced AI connection validation
524+
let aiAssistant = this.aiAssistant;
525+
526+
// If local AI assistant is null, try to get from shared connection
527+
if (!aiAssistant && window.SharedAIConnection && window.SharedAIConnection.isAIConnected()) {
528+
console.log('🔍 Local AI assistant is null, trying shared connection...');
529+
aiAssistant = window.SharedAIConnection.getAIAssistant();
530+
if (aiAssistant) {
531+
// Update our local reference
532+
this.aiAssistant = aiAssistant;
533+
this.aiAssistant.onStatusChange = (status) => this.handleAIStatusChange(status);
534+
this.isConnected = true;
535+
console.log('✅ Successfully retrieved AI assistant from shared connection');
536+
}
537+
}
538+
539+
// Final validation - ensure we have both connection state and valid assistant
540+
if (!this.isConnected || !aiAssistant) {
496541
this.addChatMessage('system', '⚠️ Please connect AI assistant first');
542+
console.error('❌ Chat blocked: isConnected =', this.isConnected, ', aiAssistant =', !!aiAssistant);
497543
return;
498544
}
499545

546+
// Additional validation for AI assistant object
547+
if (!aiAssistant.generateContent || typeof aiAssistant.generateContent !== 'function') {
548+
this.addChatMessage('system', '❌ AI assistant is not properly initialized. Please reconnect.');
549+
console.error('❌ AI assistant missing generateContent method:', aiAssistant);
550+
return;
551+
}
552+
500553
try {
501554
// Check for document-related queries (RAG) using search module
502555
let response;
503556
if (this.search && this.search.isDocumentQuery(message)) {
504557
response = await this.search.handleRAGQuery(message);
505558
} else {
506-
response = await this.aiAssistant.generateContent(message, 'general');
559+
response = await aiAssistant.generateContent(message, 'general');
507560
}
508561

509562
this.addChatMessage('assistant', response);
@@ -725,6 +778,11 @@ Based on the research, here are the key recommendations:
725778
return providerSelect ? providerSelect.value : 'AI';
726779
}
727780

781+
hasRecentConnectionMessage() {
782+
// Check if we've added a connection message in the last 5 seconds
783+
return (Date.now() - this.lastConnectionMessageTime) < 5000;
784+
}
785+
728786
clearSuccessMessages() {
729787
// Clear any success banners
730788
const displayContent = document.getElementById('displayContent');

lib/Pages/Playground/search.js

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -61,7 +61,32 @@ class PlaygroundSearch {
6161
return "❌ RAG system not available. Please initialize the document store first.";
6262
}
6363

64-
return await this.sharedRAG.generateRAGResponse(query, this.app.aiAssistant);
64+
// Enhanced AI assistant validation
65+
let aiAssistant = this.app.aiAssistant;
66+
67+
// If local AI assistant is null, try to get from shared connection
68+
if (!aiAssistant && window.SharedAIConnection && window.SharedAIConnection.isAIConnected()) {
69+
console.log('🔍 RAG: Local AI assistant is null, trying shared connection...');
70+
aiAssistant = window.SharedAIConnection.getAIAssistant();
71+
if (aiAssistant) {
72+
// Update the app's local reference
73+
this.app.aiAssistant = aiAssistant;
74+
this.app.isConnected = true;
75+
console.log('✅ RAG: Successfully retrieved AI assistant from shared connection');
76+
}
77+
}
78+
79+
// Final validation
80+
if (!aiAssistant) {
81+
return "❌ AI assistant not available for document queries. Please connect an AI provider first.";
82+
}
83+
84+
// Additional validation for AI assistant object
85+
if (!aiAssistant.generateContent || typeof aiAssistant.generateContent !== 'function') {
86+
return "❌ AI assistant is not properly initialized. Please reconnect your AI provider.";
87+
}
88+
89+
return await this.sharedRAG.generateRAGResponse(query, aiAssistant);
6590
}
6691

6792
/**

0 commit comments

Comments
 (0)