Buf fix (emit new chat also for ChatView)

This commit is contained in:
dimitrievgs 2025-09-14 20:37:31 +03:00
parent 04a19b2508
commit dfe27f79ef
5 changed files with 255 additions and 314 deletions

70
main.js

File diff suppressed because one or more lines are too long

View File

@ -30,17 +30,15 @@ import { Handle, Position } from 'reactflow';
// Простой компонент для узла типа 'user'
// Это базовый пример. Ты можешь стилизовать его по своему усмотрению.
const UserNode: React.FC<any> = ({ data, isConnectable }) => {
return React.createElement('div', {
className: 'react-flow__node-user'
},
return React.createElement(React.Fragment, null, // Используем React.Fragment для возврата нескольких элементов без лишнего div
React.createElement(Handle, {
type: "source",
position: Position.Bottom,
position: Position.Bottom,
isConnectable: isConnectable,
}),
React.createElement(Handle, {
type: "target",
position: Position.Top,
position: Position.Top,
isConnectable: isConnectable,
}),
data.label
@ -49,9 +47,7 @@ const UserNode: React.FC<any> = ({ data, isConnectable }) => {
// Простой компонент для узла типа 'llm'
const LLMNode: React.FC<any> = ({ data, isConnectable }) => {
return React.createElement('div', {
className: 'react-flow__node-llm'
},
return React.createElement(React.Fragment, null,
React.createElement(Handle, {
type: "source",
position: Position.Bottom,
@ -68,15 +64,13 @@ const LLMNode: React.FC<any> = ({ data, isConnectable }) => {
// Простой компонент для узла типа 'tool'
const ToolNode: React.FC<any> = ({ data, isConnectable }) => {
return React.createElement('div', {
className: 'react-flow__node-tool'
},
return React.createElement(React.Fragment, null,
React.createElement(Handle, {
type: "source",
position: Position.Bottom,
isConnectable: isConnectable,
}),
React.createElement(Handle, {
React.createElement(Handle, {
type: "target",
position: Position.Top,
isConnectable: isConnectable,
@ -87,27 +81,7 @@ const ToolNode: React.FC<any> = ({ data, isConnectable }) => {
// Простой компонент для узла типа 'error'
const ErrorNode: React.FC<any> = ({ data, isConnectable }) => {
return React.createElement('div', {
className: 'react-flow__node-error'
},
React.createElement(Handle, {
type: "source",
position: Position.Bottom,
isConnectable: isConnectable,
}),
React.createElement(Handle, {
type: "target",
position: Position.Top,
isConnectable: isConnectable,
}),
data.label
);
};
const AssistantNode: React.FC<any> = ({ data, isConnectable }) => {
return React.createElement('div', {
className: 'react-flow__node-assistant' // Используем CSS класс для узла assistant
},
return React.createElement(React.Fragment, null,
React.createElement(Handle, {
type: "source",
position: Position.Bottom,
@ -128,7 +102,6 @@ const nodeTypes = {
llm: LLMNode,
tool: ToolNode,
error: ErrorNode,
assistant: AssistantNode,
// Если у тебя есть node.type === 'default', то можешь его тоже определить,
// либо использовать встроенный 'default' React Flow.
};

View File

@ -3,12 +3,14 @@
* прошлых разговоров, начала новых чатов и удаления записей графов.
*/
import { EventBus } from '../utils/EventBus';
export class HistoryPanel {
container: HTMLElement;
props: {
graphs: any[];
onGraphSelect: (graphId: string) => void;
onNewChat: () => void;
eventBus: EventBus;
};
graphs: any[];
newChatButton: HTMLButtonElement;
@ -22,7 +24,7 @@ export class HistoryPanel {
props: {
graphs: any[];
onGraphSelect: (graphId: string) => void;
onNewChat: () => void;
eventBus: EventBus;
}
) {
this.container = container;
@ -57,9 +59,7 @@ export class HistoryPanel {
setupEventListeners(): void {
this.newChatButton.addEventListener('click', () => {
if (this.props.onNewChat) {
this.props.onNewChat();
}
this.props.eventBus.emit('new-chat');
});
this.deleteButton.addEventListener('click', () => {

View File

@ -55,10 +55,10 @@ export class ChatView extends ItemView {
});
// Подписываемся на события
this.plugin.eventBus.on('node-selected', this.handleNodeSelected.bind(this));
this.plugin.eventBus.on('new-chat', this.handleNewChat.bind(this));
this.plugin.eventBus.on('graph-selected', this.handleGraphSelected.bind(this));
}
this.plugin.eventBus.on('node-selected', this.handleNodeSelected.bind(this));
this.plugin.eventBus.on('new-chat', this.handleNewChat.bind(this));
this.plugin.eventBus.on('graph-selected', this.handleGraphSelected.bind(this));
}
async onClose(): Promise<void> {
if (this.chatPanel) {

View File

@ -12,70 +12,70 @@ export const GRAPH_VIEW_TYPE = 'llm-agent-graph-view';
// ----------------------------------------------- Graph View ---------------------------------------------------------------
export class GraphView extends ItemView {
plugin: LLMAgentPlugin;
graphData: { nodes: any[], edges: any[] };
currentNode: string | null;
graphsList: any[];
selectedGraphId: string | null;
plugin: LLMAgentPlugin;
graphData: { nodes: any[]; edges: any[] };
currentNode: string | null;
graphsList: any[];
selectedGraphId: string | null;
// UI Elements
historyPanel: HistoryPanel | null;
historyContainer: HTMLDivElement;
graphContainer: HTMLDivElement;
reactRoot: ReactDOM.Root | null; // <-- ИСПРАВЛЕНО: Указываем тип для reactRoot
// UI Elements
historyPanel: HistoryPanel | null;
historyContainer: HTMLDivElement;
graphContainer: HTMLDivElement;
reactRoot: ReactDOM.Root | null; // <-- ИСПРАВЛЕНО: Указываем тип для reactRoot
constructor(leaf: WorkspaceLeaf, plugin: LLMAgentPlugin) {
super(leaf);
this.plugin = plugin;
this.graphData = { nodes: [], edges: [] };
this.currentNode = null;
this.graphsList = [];
this.selectedGraphId = null;
this.historyPanel = null;
this.reactRoot = null; // Инициализируем null
}
constructor(leaf: WorkspaceLeaf, plugin: LLMAgentPlugin) {
super(leaf);
this.plugin = plugin;
this.graphData = { nodes: [], edges: [] };
this.currentNode = null;
this.graphsList = [];
this.selectedGraphId = null;
this.historyPanel = null;
this.reactRoot = null; // Инициализируем null
}
/**
* @returns {string} Тип представления.
*/
getViewType(): string {
return GRAPH_VIEW_TYPE;
}
/**
* @returns {string} Тип представления.
*/
getViewType(): string {
return GRAPH_VIEW_TYPE;
}
/**
* @returns {string} Отображаемое имя представления.
*/
getDisplayText(): string {
return 'LLM Agent Graph';
}
/**
* @returns {string} Отображаемое имя представления.
*/
getDisplayText(): string {
return 'LLM Agent Graph';
}
/**
* @returns {string} Иконка представления.
*/
getIcon(): string {
return 'brain-circuit';
}
/**
* @returns {string} Иконка представления.
*/
getIcon(): string {
return 'brain-circuit';
}
/**
* Вызывается при открытии представления. Инициализирует UI и загружает данные.
* @returns {Promise<void>}
*/
async onOpen(): Promise<void> {
const container = this.containerEl.children[1] as HTMLElement;
container.empty();
/**
* Вызывается при открытии представления. Инициализирует UI и загружает данные.
* @returns {Promise<void>}
*/
async onOpen(): Promise<void> {
const container = this.containerEl.children[1] as HTMLElement;
container.empty();
// Создаем основной контейнер с flexbox layout
const mainContainer = container.createDiv('llm-agent-graph-main');
mainContainer.style.cssText = `
// Создаем основной контейнер с flexbox layout
const mainContainer = container.createDiv('llm-agent-graph-main');
mainContainer.style.cssText = `
display: flex;
height: 100%;
width: 100%;
background-color: var(--background-primary); /* Убедимся, что фон установлен */
`;
// Левая панель для истории
this.historyContainer = mainContainer.createDiv('llm-agent-history-sidebar') as HTMLDivElement;
this.historyContainer.style.cssText = `
// Левая панель для истории
this.historyContainer = mainContainer.createDiv('llm-agent-history-sidebar') as HTMLDivElement;
this.historyContainer.style.cssText = `
width: 300px;
min-width: 300px;
border-right: 1px solid var(--background-modifier-border); /* ИСПРАВЛЕНО: Использование переменной Obsidian */
@ -83,198 +83,196 @@ export class GraphView extends ItemView {
background-color: var(--background-secondary); /* Убедимся, что фон установлен */
`;
// Правая панель для графа
this.graphContainer = mainContainer.createDiv('llm-agent-graph-container') as HTMLDivElement;
this.graphContainer.style.cssText = `
// Правая панель для графа
this.graphContainer = mainContainer.createDiv('llm-agent-graph-container') as HTMLDivElement;
this.graphContainer.style.cssText = `
flex: 1;
position: relative;
background-color: var(--background-primary); /* Убедимся, что фон установлен */
`;
// Инициализируем панель истории
this.historyPanel = new HistoryPanel(this.historyContainer, {
graphs: this.graphsList,
onGraphSelect: this.handleGraphSelect.bind(this),
onNewChat: this.handleNewChat.bind(this)
});
// Инициализируем панель истории
this.historyPanel = new HistoryPanel(this.historyContainer, {
graphs: this.graphsList,
onGraphSelect: this.handleGraphSelect.bind(this),
eventBus: this.plugin.eventBus
});
// Инициализируем React Flow
this.initializeGraphPanel();
// Инициализируем React Flow
this.initializeGraphPanel();
// Подписываемся на события
this.plugin.eventBus.on('graph-updated', this.handleGraphUpdate.bind(this));
this.plugin.eventBus.on('new-chat', this.handleNewChat.bind(this));
// Подписываемся на события
this.plugin.eventBus.on('graph-updated', this.handleGraphUpdate.bind(this));
this.plugin.eventBus.on('new-chat', this.handleNewChat.bind(this));
// Загружаем список графов
await this.fetchGraphsList();
}
// Загружаем список графов
await this.fetchGraphsList();
}
/**
* Вызывается при закрытии представления. Очищает ресурсы.
* @returns {Promise<void>}
*/
async onClose(): Promise<void> {
if (this.historyPanel) {
this.historyPanel.destroy();
this.historyPanel = null;
}
/**
* Вызывается при закрытии представления. Очищает ресурсы.
* @returns {Promise<void>}
*/
async onClose(): Promise<void> {
if (this.historyPanel) {
this.historyPanel.destroy();
this.historyPanel = null;
}
// Отмонтируем React-компонент
if (this.reactRoot) {
this.reactRoot.unmount();
this.reactRoot = null;
}
// Отмонтируем React-компонент
if (this.reactRoot) {
this.reactRoot.unmount();
this.reactRoot = null;
}
this.plugin.eventBus.off('graph-updated', this.handleGraphUpdate);
this.plugin.eventBus.off('new-chat', this.handleNewChat);
}
this.plugin.eventBus.off('graph-updated', this.handleGraphUpdate);
this.plugin.eventBus.off('new-chat', this.handleNewChat);
}
// ----------------------------------------------- Graph Panel Integration --------------------------------------------------
// ----------------------------------------------- Graph Panel Integration --------------------------------------------------
/**
* Инициализирует GraphPanelComponent (React компонент) в graphContainer.
* Использует ReactDOM.createRoot для React 18.
*/
initializeGraphPanel(): void {
// Создаем контейнер для React Flow
// Убедимся, что id уникален или используем ref для React 18
this.graphContainer.empty(); // Очищаем контейнер перед добавлением нового элемента
const wrapper = this.graphContainer.createDiv();
wrapper.style.cssText = 'width: 100%; height: 100%;';
/**
* Инициализирует GraphPanelComponent (React компонент) в graphContainer.
* Использует ReactDOM.createRoot для React 18.
*/
initializeGraphPanel(): void {
// Создаем контейнер для React Flow
// Убедимся, что id уникален или используем ref для React 18
this.graphContainer.empty(); // Очищаем контейнер перед добавлением нового элемента
const wrapper = this.graphContainer.createDiv();
wrapper.style.cssText = 'width: 100%; height: 100%;';
if (!wrapper) {
console.error('Не удалось создать wrapper для монтирования React Flow.');
return;
}
if (!wrapper) {
console.error('Не удалось создать wrapper для монтирования React Flow.');
return;
}
// Создаем корневой элемент React 18
if (ReactDOM && typeof ReactDOM.createRoot === 'function') {
this.reactRoot = ReactDOM.createRoot(wrapper);
this.renderGraphPanel();
} else {
console.error('ReactDOM.createRoot не определен. Убедитесь, что "react-dom/client" правильно импортирован.');
}
}
// Создаем корневой элемент React 18
if (ReactDOM && typeof ReactDOM.createRoot === 'function') {
this.reactRoot = ReactDOM.createRoot(wrapper);
this.renderGraphPanel();
} else {
console.error('ReactDOM.createRoot не определен. Убедитесь, что "react-dom/client" правильно импортирован.');
}
}
/**
* Рендерит или обновляет GraphPanelComponent в DOM.
*/
renderGraphPanel(): void {
if (this.reactRoot) {
this.reactRoot.render(
React.createElement(GraphPanelComponent, {
graphData: {
nodes: this.graphData.nodes,
edges: this.graphData.edges
},
onNodeClick: this.handleNodeClick.bind(this)
})
);
} else {
console.warn('React root не инициализирован для рендера GraphPanelComponent.');
}
}
// ... (остальные методы API и Event Handlers без изменений)
// ----------------------------------------------- API Methods ---------------------------------------------------------------
/**
* Рендерит или обновляет GraphPanelComponent в DOM.
*/
renderGraphPanel(): void {
if (this.reactRoot) {
this.reactRoot.render(
React.createElement(GraphPanelComponent, {
graphData: {
nodes: this.graphData.nodes,
edges: this.graphData.edges
},
onNodeClick: this.handleNodeClick.bind(this)
})
);
} else {
console.warn('React root не инициализирован для рендера GraphPanelComponent.');
}
}
// ... (остальные методы API и Event Handlers без изменений)
// ----------------------------------------------- API Methods ---------------------------------------------------------------
/**
* Загружает список всех графов с бэкенда.
* @returns {Promise<void>}
*/
async fetchGraphsList(): Promise<void> {
try {
const response = await fetch(`${this.plugin.settings.apiBaseUrl}/graphs`);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Ошибка загрузки списка графов: ${response.status} - ${errorText}`);
}
const data = await response.json();
this.graphsList = data;
if (this.historyPanel) {
this.historyPanel.updateGraphs(this.graphsList);
}
} catch (error) {
console.error('Ошибка загрузки списка графов:', error);
// Optionally: show a notice to the user
// new Notice(`Ошибка загрузки списка графов: ${error.message}`);
}
}
/**
* Загружает список всех графов с бэкенда.
* @returns {Promise<void>}
*/
async fetchGraphsList(): Promise<void> {
try {
const response = await fetch(`${this.plugin.settings.apiBaseUrl}/graphs`);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Ошибка загрузки списка графов: ${response.status} - ${errorText}`);
}
const data = await response.json();
this.graphsList = data;
if (this.historyPanel) {
this.historyPanel.updateGraphs(this.graphsList);
}
} catch (error) {
console.error('Ошибка загрузки списка графов:', error);
// Optionally: show a notice to the user
// new Notice(`Ошибка загрузки списка графов: ${error.message}`);
}
}
/**
* Загружает данные конкретного графа по его ID.
* @param {string} graphId - ID графа для загрузки.
* @returns {Promise<void>}
*/
async fetchGraphData(graphId: string): Promise<void> {
try {
const response = await fetch(`${this.plugin.settings.apiBaseUrl}/graphs/${graphId}`);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Ошибка загрузки данных графа: ${response.status} - ${errorText}`);
}
const data = await response.json();
/**
* Загружает данные конкретного графа по его ID.
* @param {string} graphId - ID графа для загрузки.
* @returns {Promise<void>}
*/
async fetchGraphData(graphId: string): Promise<void> {
try {
const response = await fetch(`${this.plugin.settings.apiBaseUrl}/graphs/${graphId}`);
if (!response.ok) {
const errorText = await response.text();
throw new Error(`Ошибка загрузки данных графа: ${response.status} - ${errorText}`);
}
const data = await response.json();
this.graphData = {
nodes: data.graph_nodes || [],
edges: data.graph_edges || []
};
this.currentNode = data.current_node_id;
this.graphData = {
nodes: data.graph_nodes || [],
edges: data.graph_edges || []
};
this.currentNode = data.current_node_id;
// Перерендериваем граф
this.renderGraphPanel();
} catch (error) {
console.error('Ошибка загрузки данных графа:', error);
// Optionally: show a notice to the user
// new Notice(`Ошибка загрузки данных графа: ${error.message}`);
}
}
// Перерендериваем граф
this.renderGraphPanel();
// ----------------------------------------------- Event Handlers ------------------------------------------------------------
} catch (error) {
console.error('Ошибка загрузки данных графа:', error);
// Optionally: show a notice to the user
// new Notice(`Ошибка загрузки данных графа: ${error.message}`);
}
}
/**
* Обработчик клика по узлу графа.
* Устанавливает текущий узел и генерирует событие 'node-selected'.
* @param {string} nodeId - ID выбранного узла.
*/
handleNodeClick(nodeId: string): void {
this.currentNode = nodeId;
this.plugin.eventBus.emit('node-selected', { nodeId });
}
// ----------------------------------------------- Event Handlers ------------------------------------------------------------
/**
* Обработчик обновления данных графа (например, после нового сообщения).
* Обновляет `graphData` и перерендеривает граф.
* @param {{ graphData: { nodes: any[], edges: any[] }, currentNode: string | null }} data - Обновленные данные графа.
*/
handleGraphUpdate(data: { graphData: { nodes: any[]; edges: any[] }; currentNode: string | null }): void {
this.graphData = data.graphData;
this.currentNode = data.currentNode;
this.renderGraphPanel();
}
/**
* Обработчик клика по узлу графа.
* Устанавливает текущий узел и генерирует событие 'node-selected'.
* @param {string} nodeId - ID выбранного узла.
*/
handleNodeClick(nodeId: string): void {
this.currentNode = nodeId;
this.plugin.eventBus.emit('node-selected', { nodeId });
}
/**
* Обработчик начала нового чата.
* Очищает текущие данные графа и перерендеривает его.
*/
handleNewChat(): void {
this.graphData = { nodes: [], edges: [] };
this.currentNode = null;
this.selectedGraphId = null;
this.renderGraphPanel();
this.fetchGraphsList(); // Обновить список графов, чтобы показать новый пустой чат
}
/**
* Обработчик обновления данных графа (например, после нового сообщения).
* Обновляет `graphData` и перерендеривает граф.
* @param {{ graphData: { nodes: any[], edges: any[] }, currentNode: string | null }} data - Обновленные данные графа.
*/
handleGraphUpdate(data: { graphData: { nodes: any[], edges: any[] }, currentNode: string | null }): void {
this.graphData = data.graphData;
this.currentNode = data.currentNode;
this.renderGraphPanel();
}
/**
* Обработчик начала нового чата.
* Очищает текущие данные графа и перерендеривает его.
*/
handleNewChat(): void {
this.graphData = { nodes: [], edges: [] };
this.currentNode = null;
this.selectedGraphId = null;
this.renderGraphPanel();
this.fetchGraphsList(); // Обновить список графов, чтобы показать новый пустой чат
}
/**
* Обработчик выбора графа из панели истории.
* Устанавливает выбранный граф и загружает его данные.
* @param {string} graphId - ID выбранного графа.
*/
async handleGraphSelect(graphId: string): Promise<void> {
this.selectedGraphId = graphId;
await this.fetchGraphData(graphId);
// Также сообщаем ChatView, что выбран новый граф и он должен обновить свою историю
this.plugin.eventBus.emit('graph-selected', { graphId, currentNode: this.currentNode });
}
}
/**
* Обработчик выбора графа из панели истории.
* Устанавливает выбранный граф и загружает его данные.
* @param {string} graphId - ID выбранного графа.
*/
async handleGraphSelect(graphId: string): Promise<void> {
this.selectedGraphId = graphId;
await this.fetchGraphData(graphId);
// Также сообщаем ChatView, что выбран новый граф и он должен обновить свою историю
this.plugin.eventBus.emit('graph-selected', { graphId, currentNode: this.currentNode });
}
}