bug fixes for correct loading of chat and graph panels

This commit is contained in:
dimitrievgs 2025-09-16 01:38:27 +03:00
parent 2bf5763eb1
commit 8bf1394e6f
4 changed files with 128 additions and 141 deletions

19
main.js

File diff suppressed because one or more lines are too long

View File

@ -9,7 +9,6 @@ export class HistoryPanel {
container: HTMLElement; container: HTMLElement;
props: { props: {
graphs: any[]; graphs: any[];
onGraphSelect: (data: { graphId: string; currentNode: string | null }) => void;
eventBus: EventBus; eventBus: EventBus;
}; };
graphs: any[]; graphs: any[];
@ -23,7 +22,6 @@ export class HistoryPanel {
container: HTMLElement, container: HTMLElement,
props: { props: {
graphs: any[]; graphs: any[];
onGraphSelect: (data: { graphId: string; currentNode: string | null }) => void;
eventBus: EventBus; eventBus: EventBus;
} }
) { ) {
@ -103,8 +101,8 @@ export class HistoryPanel {
item.addEventListener('click', (e) => { item.addEventListener('click', (e) => {
if (!(e.target as HTMLElement).classList.contains('chat-item-options-button')) { if (!(e.target as HTMLElement).classList.contains('chat-item-options-button')) {
const graphId = (item as HTMLElement).dataset.graphId; const graphId = (item as HTMLElement).dataset.graphId;
if (graphId && this.props.onGraphSelect) { if (graphId) {
this.props.onGraphSelect({ graphId: graphId, currentNode: null }); this.props.eventBus.emit('graph-selected', { graphId: graphId, currentNode: null });
} }
} }
}); });

View File

@ -79,21 +79,27 @@ export class ChatView extends ItemView {
* @param {string} nodeId - ID конечного узла для загрузки истории. * @param {string} nodeId - ID конечного узла для загрузки истории.
* @returns {Promise<void>} * @returns {Promise<void>}
*/ */
async fetchMessagesFromRootToNode(nodeId: string): Promise<void> { async fetchMessagesFromRootToNode(nodeId: string | null): Promise<void> {
try { try {
// Убедимся, что selectedGraphId установлен // Убедимся, что selectedGraphId установлен
if (!this.selectedGraphId) { if (!this.selectedGraphId) {
console.warn('selectedGraphId не установлен. Невозможно загрузить сообщения.'); console.warn('selectedGraphId не установлен. Невозможно загрузить сообщения.');
return; return;
} }
const response = await fetch(`${this.plugin.settings.apiBaseUrl}/messages/${this.selectedGraphId}/${nodeId}`);
const url = nodeId
? `${this.plugin.settings.apiBaseUrl}/messages/${this.selectedGraphId}/${nodeId}`
: `${this.plugin.settings.apiBaseUrl}/messages/${this.selectedGraphId}/last`;
const response = await fetch(url);
if (!response.ok) { if (!response.ok) {
const errorText = await response.text(); const errorText = await response.text();
throw new Error(`Ошибка загрузки сообщений: ${response.status} - ${errorText}`); throw new Error(`Ошибка загрузки сообщений: ${response.status} - ${errorText}`);
} }
const data = await response.json(); const data = await response.json();
// ИСПРАВЛЕНО: Убедиться, что type передается, если это возможно // ИСПРАВЛЕНО: Убедиться, что type передается, если это возможно
this.chatHistory = data.map((msg: any) => ({ this.chatHistory =
data.map((msg: any) => ({
...msg, ...msg,
type: msg.type || msg.role // Используем type, если есть, иначе role как fallback type: msg.type || msg.role // Используем type, если есть, иначе role как fallback
})) || []; })) || [];
@ -114,13 +120,13 @@ export class ChatView extends ItemView {
const response = await fetch(`${this.plugin.settings.apiBaseUrl}/chat`, { const response = await fetch(`${this.plugin.settings.apiBaseUrl}/chat`, {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json'
}, },
body: JSON.stringify({ body: JSON.stringify({
message: message, message: message,
graph_id: this.selectedGraphId, graph_id: this.selectedGraphId,
parent_node_id: this.currentNode, parent_node_id: this.currentNode
}), })
}); });
if (!response.ok) { if (!response.ok) {
@ -151,7 +157,6 @@ export class ChatView extends ItemView {
this.currentNode = null; // Сбрасываем, если no current_node_id this.currentNode = null; // Сбрасываем, если no current_node_id
this.fetchMessagesFromRootToNode(''); // Передаем пустую строку или null, чтобы очистить историю this.fetchMessagesFromRootToNode(''); // Передаем пустую строку или null, чтобы очистить историю
} }
} catch (error) { } catch (error) {
console.error('Ошибка отправки сообщения:', error); console.error('Ошибка отправки сообщения:', error);
} }
@ -190,15 +195,7 @@ export class ChatView extends ItemView {
*/ */
async handleGraphSelected(data: { graphId: string; currentNode: string | null }): Promise<void> { async handleGraphSelected(data: { graphId: string; currentNode: string | null }): Promise<void> {
this.selectedGraphId = data.graphId; this.selectedGraphId = data.graphId;
this.currentNode = data.currentNode; this.currentNode = data.currentNode; // Может быть пустым, но это не проблема
if (this.currentNode) { await this.fetchMessagesFromRootToNode(data.currentNode);
await this.fetchMessagesFromRootToNode(this.currentNode);
} else {
// Если текущего узла нет (например, пустой граф), очищаем историю
this.chatHistory = [];
if (this.chatPanel) {
this.chatPanel.updateHistory(this.chatHistory);
}
}
} }
} }

View File

@ -99,7 +99,6 @@ export class GraphView extends ItemView {
// Инициализируем панель истории // Инициализируем панель истории
this.historyPanel = new HistoryPanel(this.historyContainer, { this.historyPanel = new HistoryPanel(this.historyContainer, {
graphs: this.graphsList, graphs: this.graphsList,
onGraphSelect: this.handleGraphSelected.bind(this),
eventBus: this.plugin.eventBus eventBus: this.plugin.eventBus
}); });