742 lines
28 KiB
Python
742 lines
28 KiB
Python
import json
|
|
import re
|
|
import threading
|
|
import time
|
|
|
|
import customtkinter as ctk
|
|
from tkinter import filedialog, messagebox
|
|
|
|
from .base import ViewBase
|
|
from ..theme import c, mono_font, ui_font
|
|
from ..components.controls import IconButton
|
|
from ..core.mcp.manager import MCPManager
|
|
|
|
|
|
class ChatView(ViewBase):
|
|
def __init__(self, master, **kwargs):
|
|
super().__init__(master, **kwargs)
|
|
self.title_text = "Чат"
|
|
self.configure(fg_color="transparent")
|
|
self._busy = False
|
|
self._labels = [] # [(CTkLabel, is_user), ...] — для пересчёта переноса строк
|
|
self._stream_label = None
|
|
self._stream_text = ""
|
|
self._agent_mode = False
|
|
try:
|
|
self.mcp = MCPManager(self.app)
|
|
except Exception:
|
|
self.mcp = None
|
|
self._column_pad = 24
|
|
|
|
# центральная колонка чата (не даём растягиваться на весь экран)
|
|
self.column = ctk.CTkFrame(self, fg_color="transparent", corner_radius=0)
|
|
self.column.pack(fill="both", expand=True, padx=self._column_pad, pady=0)
|
|
self.bind("<Configure>", self._on_view_resize)
|
|
|
|
# --- история сообщений ---
|
|
self.messages = ctk.CTkScrollableFrame(self.column, fg_color="transparent", corner_radius=0)
|
|
self.messages.pack(fill="both", expand=True, pady=(18, 6))
|
|
self.messages.bind("<Configure>", self._on_resize)
|
|
|
|
# --- строка над вводом: действия слева, контекст справа ---
|
|
meta_row = ctk.CTkFrame(self.column, fg_color="transparent")
|
|
meta_row.pack(fill="x", padx=2, pady=(0, 6))
|
|
|
|
self._ghost(meta_row, "Экспорт", self.export_chat, width=66).pack(side="left")
|
|
self._ghost(meta_row, "Очистить", self.clear_chat, width=72).pack(side="left", padx=(4, 0))
|
|
|
|
self.agent_switch = ctk.CTkSwitch(
|
|
meta_row, text="Файлы", width=64, switch_width=28, switch_height=14,
|
|
font=ui_font(11), text_color=c("text_dim"),
|
|
command=self._toggle_agent,
|
|
)
|
|
self.agent_switch.pack(side="left", padx=(10, 0))
|
|
|
|
self.status_label = ctk.CTkLabel(meta_row, text="", font=ui_font(11), text_color=c("text_faint"), anchor="w")
|
|
self.status_label.pack(side="left", padx=(10, 0))
|
|
|
|
self.context_label = ctk.CTkLabel(meta_row, text="Контекст —", font=mono_font(10), text_color=c("text_faint"))
|
|
self.context_label.pack(side="right")
|
|
|
|
# --- карточка ввода ---
|
|
card = ctk.CTkFrame(self.column, fg_color=c("input"), corner_radius=12, border_width=1, border_color=c("border"))
|
|
card.pack(fill="x", pady=(0, 18))
|
|
|
|
self.input_box = ctk.CTkTextbox(
|
|
card,
|
|
height=54,
|
|
corner_radius=8,
|
|
border_width=0,
|
|
fg_color="transparent",
|
|
text_color=c("text"),
|
|
font=ui_font(13),
|
|
wrap="word",
|
|
)
|
|
self.input_box.pack(fill="x", padx=8, pady=(8, 0))
|
|
self.input_box.bind("<Return>", self._on_enter)
|
|
self.input_box.bind("<KeyRelease>", self._update_placeholder)
|
|
|
|
self.placeholder = ctk.CTkLabel(
|
|
card,
|
|
text="Сообщение",
|
|
font=ui_font(13),
|
|
text_color=c("text_faint"),
|
|
)
|
|
self.placeholder.place(x=18, y=14)
|
|
self.placeholder.bind("<Button-1>", lambda e: self.input_box.focus_set())
|
|
|
|
actions = ctk.CTkFrame(card, fg_color="transparent")
|
|
actions.pack(fill="x", padx=10, pady=(4, 8))
|
|
|
|
ctk.CTkLabel(
|
|
actions,
|
|
text="Enter — отправить · Shift+Enter — новая строка",
|
|
font=ui_font(10),
|
|
text_color=c("text_faint"),
|
|
).pack(side="left")
|
|
|
|
self.send_btn = IconButton(
|
|
actions,
|
|
"arrow_up",
|
|
self.send_message,
|
|
size=36,
|
|
icon_size=18,
|
|
radius=9,
|
|
bg=c("action_bg"),
|
|
hover=c("action_hover"),
|
|
icon_color=c("action_fg"),
|
|
hover_icon_color=c("action_fg"),
|
|
)
|
|
self.send_btn.pack(side="right")
|
|
|
|
self.render_history()
|
|
self.update_context_indicator()
|
|
self.after(1500, self._tick_context)
|
|
|
|
# ---------- helpers ----------
|
|
def _ghost(self, parent, text, command, width=72):
|
|
return ctk.CTkButton(
|
|
parent,
|
|
text=text,
|
|
command=command,
|
|
width=width,
|
|
height=24,
|
|
corner_radius=6,
|
|
fg_color="transparent",
|
|
hover_color=c("card_hover"),
|
|
font=ui_font(11),
|
|
text_color=c("text_dim"),
|
|
)
|
|
|
|
def _max_text_width(self):
|
|
try:
|
|
w = self.column.winfo_width()
|
|
except Exception:
|
|
w = 0
|
|
if w <= 10:
|
|
w = 760
|
|
return max(280, min(900, int(w * 0.92)))
|
|
|
|
def _on_view_resize(self, event=None):
|
|
# Держим колонку чата по центру и не даём ей растягиваться на весь экран.
|
|
try:
|
|
width = self.winfo_width()
|
|
except Exception:
|
|
return
|
|
pad = max(24, int((width - 1040) / 2))
|
|
if pad != self._column_pad:
|
|
self._column_pad = pad
|
|
try:
|
|
self.column.pack_configure(padx=(pad, pad))
|
|
except Exception:
|
|
pass
|
|
self._on_resize()
|
|
|
|
def _on_resize(self, event=None):
|
|
wrap = self._max_text_width()
|
|
for label, is_user in self._labels:
|
|
try:
|
|
label.configure(wraplength=min(wrap, int(self._max_text_width() * 0.78)) if is_user else wrap)
|
|
except Exception:
|
|
pass
|
|
|
|
def _tick_context(self):
|
|
if not getattr(self, "_alive", True):
|
|
return
|
|
try:
|
|
if self.winfo_ismapped():
|
|
self.update_context_indicator()
|
|
except Exception:
|
|
pass
|
|
try:
|
|
self.after(1500, self._tick_context)
|
|
except Exception:
|
|
pass
|
|
|
|
def _update_placeholder(self, event=None):
|
|
try:
|
|
empty = not self.input_box.get("1.0", "end").strip()
|
|
except Exception:
|
|
empty = True
|
|
try:
|
|
if empty:
|
|
self.placeholder.place(x=18, y=14)
|
|
self.placeholder.lift()
|
|
else:
|
|
self.placeholder.place_forget()
|
|
except Exception:
|
|
pass
|
|
|
|
def set_busy(self, busy: bool):
|
|
self._busy = busy
|
|
state = "disabled" if busy else "normal"
|
|
try:
|
|
self.input_box.configure(state=state)
|
|
self.send_btn.set_enabled(not busy)
|
|
except Exception:
|
|
pass
|
|
self.status_label.configure(text="Генерация" if busy else "")
|
|
|
|
# ---------- оценка контекста ----------
|
|
def _estimate_text_tokens(self, text: str) -> int:
|
|
if not text:
|
|
return 0
|
|
return max(1, len(str(text)) // 4)
|
|
|
|
def _estimate_context_used(self):
|
|
if not self.app_state or not self.app_state.chat_history:
|
|
return 0
|
|
chars = 0
|
|
for msg in self.app_state.chat_history:
|
|
chars += len(str(msg.get("content", "")))
|
|
return max(0, chars // 4)
|
|
|
|
def _get_context_info(self):
|
|
"""Возвращает (used, limit, estimated). used/limit могут быть None."""
|
|
if not self.engine or not (self.app_state and self.app_state.model_loaded):
|
|
return None, None, False
|
|
used = limit = None
|
|
estimated = True
|
|
try:
|
|
used, limit, estimated = self.engine.context_info()
|
|
except Exception:
|
|
pass
|
|
if used is None:
|
|
used = self._estimate_context_used()
|
|
estimated = True
|
|
return used, limit, estimated
|
|
|
|
def update_context_indicator(self, extra_text: str = ""):
|
|
if not hasattr(self, "context_label"):
|
|
return
|
|
|
|
if not self.engine or not (self.app_state and self.app_state.model_loaded):
|
|
self.context_label.configure(text="Контекст —", text_color=c("text_faint"))
|
|
return
|
|
|
|
used, limit, estimated = self._get_context_info()
|
|
if used is None:
|
|
used = 0
|
|
|
|
extra = self._estimate_text_tokens(extra_text) if extra_text else 0
|
|
projected = used + extra
|
|
|
|
if limit and limit > 0:
|
|
display_used = min(projected, limit)
|
|
pct = max(0.0, min(100.0, display_used / limit * 100.0))
|
|
warn = ""
|
|
if extra_text and extra > limit:
|
|
warn = " · сообщение > контекста"
|
|
display_used = projected
|
|
elif projected > limit:
|
|
warn = " · лимит"
|
|
approx = "~" if (estimated or extra_text) else ""
|
|
color = c("danger") if projected >= limit else (c("warn") if projected >= limit * 0.9 else c("text_faint"))
|
|
self.context_label.configure(
|
|
text=f"Контекст {approx}{display_used} / {limit} ({pct:.0f}%){warn}",
|
|
text_color=color,
|
|
)
|
|
else:
|
|
suffix = " (примерно)" if estimated or extra_text else ""
|
|
self.context_label.configure(text=f"Контекст {projected}{suffix}", text_color=c("text_faint"))
|
|
|
|
# ---------- рендер сообщений ----------
|
|
def _clear_messages(self):
|
|
for w in self.messages.winfo_children():
|
|
w.destroy()
|
|
self._labels = []
|
|
self._stream_label = None
|
|
self._stream_text = ""
|
|
self._agent_mode = False
|
|
try:
|
|
self.mcp = MCPManager(self.app)
|
|
except Exception:
|
|
self.mcp = None
|
|
|
|
def _add_empty_state(self):
|
|
loaded = bool(self.app_state and self.app_state.model_loaded)
|
|
box = ctk.CTkFrame(self.messages, fg_color="transparent")
|
|
box.pack(fill="both", expand=True, pady=(96, 0))
|
|
ctk.CTkLabel(
|
|
box,
|
|
text="Локальная модель загружена" if loaded else "Модель не загружена",
|
|
font=ui_font(15),
|
|
text_color=c("text"),
|
|
).pack(anchor="center")
|
|
ctk.CTkLabel(
|
|
box,
|
|
text="Спросите что-нибудь или попросите код" if loaded else "Откройте «Модели» и загрузите .xnh",
|
|
font=ui_font(13),
|
|
text_color=c("text_dim"),
|
|
).pack(anchor="center", pady=(6, 0))
|
|
if not loaded:
|
|
ctk.CTkButton(
|
|
box,
|
|
text="Открыть модели",
|
|
width=140,
|
|
height=32,
|
|
corner_radius=8,
|
|
fg_color=c("control"),
|
|
hover_color=c("card_hover"),
|
|
font=ui_font(12),
|
|
text_color=c("text"),
|
|
command=lambda: self.app.switch_view("models") if self.app else None,
|
|
).pack(anchor="center", pady=(14, 0))
|
|
|
|
def _append_message(self, role: str, content: str):
|
|
is_user = role == "user"
|
|
wrap = self._max_text_width()
|
|
|
|
row = ctk.CTkFrame(self.messages, fg_color="transparent")
|
|
row.pack(fill="x", pady=(0, 16))
|
|
|
|
if is_user:
|
|
bubble = ctk.CTkFrame(row, fg_color=c("user_bubble"), corner_radius=12, border_width=0)
|
|
bubble.pack(side="right", anchor="e")
|
|
label = ctk.CTkLabel(
|
|
bubble,
|
|
text=content,
|
|
justify="left",
|
|
anchor="w",
|
|
font=ui_font(13),
|
|
text_color=c("user_text"),
|
|
wraplength=int(wrap * 0.72),
|
|
)
|
|
label.pack(padx=12, pady=10)
|
|
self._labels.append((label, True))
|
|
else:
|
|
bubble = ctk.CTkFrame(row, fg_color="transparent")
|
|
bubble.pack(side="left", fill="x", expand=True, anchor="w")
|
|
ctk.CTkLabel(bubble, text="Xenith", font=ui_font(11), text_color=c("text_dim")).pack(
|
|
anchor="w", padx=2, pady=(0, 4)
|
|
)
|
|
self._render_assistant_body(bubble, content, wrap)
|
|
|
|
def _text_label(self, parent, text: str, wrap: int):
|
|
label = ctk.CTkLabel(
|
|
parent,
|
|
text=text,
|
|
justify="left",
|
|
anchor="w",
|
|
font=ui_font(13),
|
|
text_color=c("text"),
|
|
wraplength=wrap,
|
|
)
|
|
label.pack(anchor="w", padx=2, pady=(0, 2))
|
|
self._labels.append((label, False))
|
|
return label
|
|
|
|
def _code_block(self, parent, code: str, language: str):
|
|
box = ctk.CTkFrame(parent, fg_color=c("code_bg"), corner_radius=10, border_width=1, border_color=c("border"))
|
|
box.pack(fill="x", anchor="w", padx=2, pady=(6, 8))
|
|
if language:
|
|
ctk.CTkLabel(box, text=language.lower(), font=mono_font(10), text_color=c("text_faint")).pack(
|
|
anchor="w", padx=12, pady=(8, 0)
|
|
)
|
|
label = ctk.CTkLabel(
|
|
box,
|
|
text=code,
|
|
justify="left",
|
|
anchor="w",
|
|
font=mono_font(11),
|
|
text_color=c("code_text"),
|
|
wraplength=max(240, self._max_text_width() - 40),
|
|
)
|
|
label.pack(anchor="w", padx=12, pady=(4 if language else 10, 10))
|
|
self._labels.append((label, False))
|
|
|
|
def _render_assistant_body(self, parent, content: str, wrap: int):
|
|
pattern = re.compile(r"```[ \t]*([A-Za-z0-9_+\-]*)\n(.*?)```", re.S)
|
|
pos = 0
|
|
found = False
|
|
for m in pattern.finditer(content):
|
|
before = content[pos:m.start()].strip("\n")
|
|
if before.strip():
|
|
self._text_label(parent, before, wrap)
|
|
self._code_block(parent, m.group(2).rstrip("\n"), m.group(1))
|
|
pos = m.end()
|
|
found = True
|
|
tail = content[pos:].strip("\n")
|
|
if tail.strip() or not found:
|
|
self._text_label(parent, tail if found else content, wrap)
|
|
self._scroll_bottom()
|
|
|
|
def _scroll_bottom(self):
|
|
def _do():
|
|
if not getattr(self, "_alive", True):
|
|
return
|
|
try:
|
|
self.messages._parent_canvas.yview_moveto(1.0)
|
|
except Exception:
|
|
pass
|
|
try:
|
|
self.after(10, _do)
|
|
except Exception:
|
|
pass
|
|
|
|
def append_to_box(self, text: str):
|
|
"""Совместимость со старым кодом."""
|
|
self._append_message("assistant", text)
|
|
|
|
def render_history(self):
|
|
self._clear_messages()
|
|
history = self.app_state.chat_history if self.app_state else []
|
|
if not history:
|
|
self._add_empty_state()
|
|
else:
|
|
for msg in history:
|
|
role = msg.get("role", "assistant")
|
|
content = msg.get("content", "")
|
|
if role not in ("user", "assistant"):
|
|
content = f"{role}: {content}"
|
|
role = "assistant"
|
|
self._append_message(role, content)
|
|
self.update_context_indicator()
|
|
|
|
# ---------- действия ----------
|
|
def _on_enter(self, event=None):
|
|
# Shift+Enter — перенос строки (стандартное поведение Text), Enter — отправка.
|
|
if event is not None and (event.state & 0x0001):
|
|
return None
|
|
self.send_message()
|
|
return "break"
|
|
|
|
def export_chat(self):
|
|
if not self.app_state or not self.app_state.chat_history:
|
|
self.status_label.configure(text="Нет сообщений для экспорта")
|
|
return
|
|
path = filedialog.asksaveasfilename(
|
|
title="Экспорт чата",
|
|
defaultextension=".md",
|
|
filetypes=[("Markdown", "*.md"), ("Text", "*.txt"), ("JSON", "*.json"), ("All files", "*.*")],
|
|
initialfile=f"chat_{time.strftime('%Y%m%d_%H%M%S')}.md",
|
|
)
|
|
if not path:
|
|
return
|
|
try:
|
|
ext = path.lower().rsplit(".", 1)[-1] if "." in path else "md"
|
|
if ext == "json":
|
|
with open(path, "w", encoding="utf-8") as f:
|
|
json.dump(self.app_state.chat_history, f, ensure_ascii=False, indent=2)
|
|
else:
|
|
lines = []
|
|
for msg in self.app_state.chat_history:
|
|
role = msg.get("role", "?")
|
|
content = msg.get("content", "")
|
|
if ext == "md":
|
|
title = "Вы" if role == "user" else ("Xenith" if role == "assistant" else role)
|
|
lines.append(f"## {title}\n\n{content}\n")
|
|
else:
|
|
prefix = "Вы" if role == "user" else ("Xenith" if role == "assistant" else role)
|
|
lines.append(f"{prefix}: {content}\n")
|
|
with open(path, "w", encoding="utf-8") as f:
|
|
f.write("\n".join(lines).strip() + "\n")
|
|
self.app_state.log(f"Чат экспортирован: {path}")
|
|
self.status_label.configure(text=f"Экспортировано: {path}")
|
|
except Exception as e:
|
|
self.status_label.configure(text=f"Ошибка экспорта: {e}")
|
|
|
|
def clear_chat(self):
|
|
if self.app_state:
|
|
self.app_state.chat_history.clear()
|
|
self.app_state.log("Чат очищен")
|
|
if self.engine and hasattr(self.engine, "reset_chat"):
|
|
try:
|
|
self.engine.reset_chat()
|
|
except Exception:
|
|
pass
|
|
self.render_history()
|
|
self.set_busy(False)
|
|
self.update_context_indicator()
|
|
self._update_placeholder()
|
|
try:
|
|
self.input_box.focus_set()
|
|
except Exception:
|
|
pass
|
|
|
|
def send_message(self):
|
|
if self._busy:
|
|
return
|
|
|
|
text = self.input_box.get("1.0", "end").strip()
|
|
if not text:
|
|
return
|
|
if self.app_state is None:
|
|
return
|
|
|
|
# Не запускаем генерацию, пока идёт обучение/загрузка другой модели.
|
|
try:
|
|
if self.app is not None and self.app.any_busy(exclude=self):
|
|
self.status_label.configure(text="Дождитесь завершения обучения/загрузки модели")
|
|
return
|
|
except Exception:
|
|
pass
|
|
|
|
# Контроль контекста: не даём истории выйти за пределы лимита модели.
|
|
used, limit, _ = self._get_context_info()
|
|
if used is None:
|
|
used = self._estimate_context_used()
|
|
msg_tokens = self._estimate_text_tokens(text)
|
|
if limit and limit > 0:
|
|
if msg_tokens <= limit and (used + msg_tokens) > limit:
|
|
self.app_state.chat_history.clear()
|
|
if self.engine and hasattr(self.engine, "reset_chat"):
|
|
try:
|
|
self.engine.reset_chat()
|
|
except Exception:
|
|
pass
|
|
self.render_history()
|
|
self.status_label.configure(text="Контекст переполнен — история сброшена")
|
|
self.app_state.log("Контекст переполнен: история чата сброшена перед отправкой")
|
|
used = 0
|
|
elif msg_tokens > limit:
|
|
self.status_label.configure(text="Внимание: сообщение больше контекста модели")
|
|
|
|
self.app_state.chat_history.append({"role": "user", "content": text})
|
|
self._append_message("user", text)
|
|
self.input_box.delete("1.0", "end")
|
|
self._update_placeholder()
|
|
self.set_busy(True)
|
|
self.update_context_indicator()
|
|
self._append_assistant_shell()
|
|
|
|
params = dict(self.app_state.gen_params) if self.app_state.gen_params else {}
|
|
messages = list(self.app_state.chat_history)
|
|
|
|
if self._agent_mode:
|
|
self._start_agent(messages, params)
|
|
return
|
|
|
|
def on_result(result_text: str):
|
|
self.ui(lambda t=result_text: self._on_result(t))
|
|
|
|
def on_token(piece: str):
|
|
self.ui(lambda p=piece: self._on_token(p))
|
|
|
|
if self.engine is None:
|
|
self._on_result("[ОШИБКА] Движок недоступен.")
|
|
return
|
|
|
|
try:
|
|
self.engine.chat(messages, params=params, on_result=on_result, on_token=on_token)
|
|
except Exception as e:
|
|
self.set_busy(False)
|
|
self.status_label.configure(text=f"[ОШИБКА] {e}")
|
|
|
|
def _append_assistant_shell(self):
|
|
row = ctk.CTkFrame(self.messages, fg_color="transparent")
|
|
row.pack(fill="x", pady=(0, 16))
|
|
bubble = ctk.CTkFrame(row, fg_color="transparent")
|
|
bubble.pack(side="left", fill="x", expand=True, anchor="w")
|
|
ctk.CTkLabel(bubble, text="Xenith", font=ui_font(11),
|
|
text_color=c("text_dim")).pack(anchor="w", padx=2, pady=(0, 4))
|
|
label = ctk.CTkLabel(
|
|
bubble, text="", justify="left", anchor="w", font=ui_font(13),
|
|
text_color=c("text"), wraplength=self._max_text_width(),
|
|
)
|
|
label.pack(anchor="w", padx=2)
|
|
self._labels.append((label, False))
|
|
self._stream_label = label
|
|
self._stream_text = ""
|
|
self._scroll_bottom()
|
|
|
|
def _on_token(self, piece: str):
|
|
if not piece or self._stream_label is None:
|
|
return
|
|
self._stream_text += str(piece)
|
|
try:
|
|
if self._stream_label.winfo_exists():
|
|
self._stream_label.configure(text=self._stream_text)
|
|
except Exception:
|
|
pass
|
|
self._scroll_bottom()
|
|
|
|
# ---------- агентный режим / MCP ----------
|
|
def _toggle_agent(self):
|
|
try:
|
|
on = bool(self.agent_switch.get())
|
|
except Exception:
|
|
on = False
|
|
if on and (self.mcp is None or not self.mcp.enabled()):
|
|
try:
|
|
self.agent_switch.deselect()
|
|
except Exception:
|
|
pass
|
|
self._agent_mode = False
|
|
self.status_label.configure(text="Укажите папки в настройках MCP")
|
|
try:
|
|
if self.app:
|
|
self.app.open_settings("mcp")
|
|
except Exception:
|
|
pass
|
|
return
|
|
self._agent_mode = on
|
|
self.status_label.configure(text="Файлы включены" if on else "")
|
|
|
|
def _parse_tool_call(self, text: str):
|
|
m = re.search(r"```tool\s*(\{.*?\})\s*```", text or "", re.S)
|
|
raw = m.group(1) if m else None
|
|
if raw is None:
|
|
m2 = re.search(r'(\{\s*"tool"\s*:.*?\})', text or "", re.S)
|
|
raw = m2.group(1) if m2 else None
|
|
if not raw:
|
|
return None
|
|
try:
|
|
data = json.loads(raw)
|
|
except Exception:
|
|
return None
|
|
if not isinstance(data, dict):
|
|
return None
|
|
name = data.get("tool") or data.get("name")
|
|
args = data.get("arguments") or data.get("args") or {}
|
|
if not name or not isinstance(args, dict):
|
|
return None
|
|
return str(name), args
|
|
|
|
def _append_tool_note(self, title: str, body: str = "", ok: bool = True):
|
|
row = ctk.CTkFrame(self.messages, fg_color="transparent")
|
|
row.pack(fill="x", pady=(0, 8))
|
|
box = ctk.CTkFrame(row, fg_color=c("code_bg"), corner_radius=8,
|
|
border_width=1, border_color=c("border"))
|
|
box.pack(anchor="w", fill="x", padx=2)
|
|
ctk.CTkLabel(box, text=title, font=mono_font(10),
|
|
text_color=(c("text_dim") if ok else c("danger"))).pack(
|
|
anchor="w", padx=10, pady=(8, 2))
|
|
if body:
|
|
label = ctk.CTkLabel(
|
|
box, text=body, font=mono_font(10), justify="left", anchor="w",
|
|
text_color=(c("text_faint") if ok else c("danger")),
|
|
wraplength=max(240, self._max_text_width() - 36),
|
|
)
|
|
label.pack(anchor="w", padx=10, pady=(0, 8))
|
|
self._labels.append((label, False))
|
|
self._scroll_bottom()
|
|
|
|
def _ask_tool(self, name: str, args: dict) -> bool:
|
|
event = threading.Event()
|
|
box = {"ok": False}
|
|
|
|
def ask_ui():
|
|
try:
|
|
preview = json.dumps(args, ensure_ascii=False, indent=2)[:900]
|
|
box["ok"] = messagebox.askyesno(
|
|
"MCP: подтверждение",
|
|
f"Разрешить инструмент «{name}»?\n\n{preview}",
|
|
parent=self,
|
|
)
|
|
finally:
|
|
event.set()
|
|
|
|
try:
|
|
self.ui(ask_ui)
|
|
except Exception:
|
|
return False
|
|
event.wait(timeout=180)
|
|
return bool(box.get("ok"))
|
|
|
|
def _flatten_history(self, messages, limit=10):
|
|
lines = []
|
|
for m in messages[-limit:]:
|
|
role = m.get("role", "user")
|
|
content = str(m.get("content", ""))
|
|
who = "Пользователь" if role == "user" else ("Ассистент" if role == "assistant" else role)
|
|
lines.append(f"{who}: {content}")
|
|
return "\n".join(lines)
|
|
|
|
def _start_agent(self, messages, params):
|
|
if self.mcp is None or not self.mcp.enabled():
|
|
self._on_result("[ОШИБКА] MCP не настроен: укажите папки в настройках")
|
|
return
|
|
try:
|
|
tools_prompt = self.mcp.tool_prompt()
|
|
except Exception as e:
|
|
self._on_result(f"[ОШИБКА] MCP: {e}")
|
|
return
|
|
system = (getattr(self.app_state, "system_prompt", "") or "").strip()
|
|
base = (
|
|
(system + "\n\n" if system else "") +
|
|
"Ты — Xenith, локальный ассистент с доступом к файловым инструментам.\n" +
|
|
tools_prompt + "\n\n"
|
|
)
|
|
transcript = self._flatten_history(messages, limit=10)
|
|
|
|
def worker():
|
|
final = ""
|
|
prompt = base + "Диалог:\n" + transcript + "\nАссистент:"
|
|
try:
|
|
for step in range(4):
|
|
out = self.engine.generate_sync(prompt, params)
|
|
call = self._parse_tool_call(out)
|
|
if not call:
|
|
final = (out or "").strip()
|
|
break
|
|
name, args = call
|
|
self.ui(lambda n=name, a=args: self._append_tool_note(
|
|
f"tool: {n}", json.dumps(a, ensure_ascii=False)[:700], True))
|
|
ok, result = self.mcp.call_tool(name, args, ask=self._ask_tool)
|
|
preview = str(result)
|
|
if len(preview) > 1400:
|
|
preview = preview[:1400] + "…"
|
|
self.ui(lambda n=name, r=preview, o=ok: self._append_tool_note(
|
|
f"{'ok' if o else 'ошибка'}: {n}", r, o))
|
|
prompt += (
|
|
f"\n{out}\nРезультат инструмента {name}:\n{result[:4000]}\n"
|
|
"Продолжи ответ пользователю. Если инструмент больше не нужен — ответь обычным текстом."
|
|
)
|
|
final = (out or "").strip()
|
|
except Exception as e:
|
|
final = f"[ОШИБКА] {e}"
|
|
self.ui(lambda t=final: self._on_result(t))
|
|
|
|
threading.Thread(target=worker, daemon=True).start()
|
|
|
|
def destroy(self):
|
|
try:
|
|
if getattr(self, "mcp", None) is not None:
|
|
self.mcp.close()
|
|
except Exception:
|
|
pass
|
|
super().destroy()
|
|
|
|
def _on_result(self, result_text: str):
|
|
if self.app_state is not None:
|
|
self.app_state.chat_history.append({"role": "assistant", "content": result_text})
|
|
if self._stream_label is not None:
|
|
label = self._stream_label
|
|
self._stream_label = None
|
|
final = result_text or self._stream_text
|
|
try:
|
|
if label.winfo_exists():
|
|
label.configure(text=final)
|
|
except Exception:
|
|
pass
|
|
self._stream_text = ""
|
|
else:
|
|
self._append_message("assistant", result_text)
|
|
self.set_busy(False)
|
|
self.update_context_indicator()
|
|
try:
|
|
self.input_box.focus_set()
|
|
except Exception:
|
|
pass
|