Compare commits

..
1 Commits
3 changed files with 231 additions and 7 deletions

No files matched your search

+11
View File
@@ -83,6 +83,14 @@ class App(ctk.CTk):
# ---------- построение / перестроение интерфейса ----------
def _build_ui(self, initial_view: str = "chat"):
# Чистим глобальные wheel-обработчики от старых CTkScrollableFrame:
# иначе после смены темы они остаются на destroyed-виджетах и ломают
# прокрутку во всём приложении.
for sequence in ("<Button-4>", "<Button-5>", "<MouseWheel>"):
try:
self.unbind_all(sequence)
except Exception:
pass
self.sidebar = Sidebar(self, self)
self.sidebar.grid(row=0, column=0, sticky="ns")
@@ -495,6 +503,9 @@ class App(ctk.CTk):
engine_ok = bool(self.engine and self.engine.is_ready())
self.topbar.set_model(model, bool(state and state.model_loaded), engine_ok)
self.statusbar.refresh()
chat = self.views.get("chat")
if chat is not None and hasattr(chat, "_update_unload_btn"):
chat._update_unload_btn()
except Exception:
pass
+38
View File
@@ -509,6 +509,44 @@ class XenithEngine:
except Exception:
pass
def unload_model(self, engine_id: str = None) -> bool:
"""Выгружает модель из активного или указанного движка."""
eid = str(engine_id or self._active_id or "")
ad = self._adapters.get(eid)
if ad is None:
return False
if self._busy or self._training:
raise EngineError("Сначала дождитесь завершения генерации/обучения")
try:
ad.stop()
except Exception:
pass
try:
ad.unload_model()
except Exception as e:
self.log(f"Не удалось выгрузить модель {ad.name}: {e}")
conf = (self.config.get("engines") or {}).get(eid)
if isinstance(conf, dict):
conf.pop("model", None)
# llama.cpp-сервер держит веса в памяти: останавливаем его,
# чтобы действительно освободить VRAM/RAM.
if ad.type == "openai" and conf.get("installer_id"):
try:
self.runtime.stop(eid, timeout=4)
except Exception:
pass
if self.app_state is not None and eid == self._active_id:
self.app_state.model_loaded = False
self.app_state.current_model_name = ""
self.app_state.current_model_path = ""
try:
self.save_config()
except Exception:
pass
self.log(f"Модель выгружена: {ad.name}")
return True
def reset_chat(self):
ad = self.active()
if ad is not None:
+182 -7
View File
@@ -21,6 +21,10 @@ class ChatView(ViewBase):
self._labels = [] # [(CTkLabel, is_user), ...] — для пересчёта переноса строк
self._stream_label = None
self._stream_text = ""
self._typing_label = None
self._typing_job = None
self._typing_dots = 0
self._unloading = False
self._agent_mode = False
try:
self.mcp = MCPManager(self.app)
@@ -36,7 +40,9 @@ class ChatView(ViewBase):
# --- история сообщений ---
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)
# add="+" обязателен: CTkScrollableFrame сам обновляет scrollregion
# по <Configure>, нельзя перетирать его собственный обработчик.
self.messages.bind("<Configure>", self._on_resize, add="+")
# --- строка над вводом: действия слева, контекст справа ---
meta_row = ctk.CTkFrame(self.column, fg_color="transparent")
@@ -55,6 +61,8 @@ class ChatView(ViewBase):
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.unload_btn = self._ghost(meta_row, "Выгрузить", self.unload_model, width=88)
self.unload_btn.pack(side="right", padx=(0, 10))
self.context_label = ctk.CTkLabel(meta_row, text="Контекст —", font=mono_font(10), text_color=c("text_faint"))
self.context_label.pack(side="right")
@@ -75,6 +83,10 @@ class ChatView(ViewBase):
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)
try:
self.input_box._textbox.configure(insertbackground=c("text"), insertwidth=2)
except Exception:
pass
self.placeholder = ctk.CTkLabel(
card,
@@ -83,7 +95,15 @@ class ChatView(ViewBase):
text_color=c("text_faint"),
)
self.placeholder.place(x=18, y=14)
self.placeholder.bind("<Button-1>", lambda e: self.input_box.focus_set())
self.placeholder.bind("<Button-1>", self._focus_input)
try:
inner = getattr(self.placeholder, "_label", None)
if inner is not None:
inner.bind("<Button-1>", self._focus_input)
inner.configure(cursor="xterm", takefocus=0)
except Exception:
pass
card.bind("<Button-1>", self._focus_input)
actions = ctk.CTkFrame(card, fg_color="transparent")
actions.pack(fill="x", padx=10, pady=(4, 8))
@@ -111,6 +131,7 @@ class ChatView(ViewBase):
self.render_history()
self.update_context_indicator()
self._update_unload_btn()
self.after(1500, self._tick_context)
# ---------- helpers ----------
@@ -173,6 +194,35 @@ class ChatView(ViewBase):
except Exception:
pass
def _focus_input(self, event=None):
if self._busy:
return "break"
target = getattr(self.input_box, "_textbox", None) or self.input_box
try:
target.focus_force()
if hasattr(target, "mark_set"):
target.mark_set("insert", "end")
target.see("end")
except Exception:
pass
# Tk может вернуть фокус внутреннему Label после обработчика клика.
# Возвращаем его в поле ввода уже после завершения события.
def _again():
if self._busy:
return
try:
target.focus_force()
if hasattr(target, "mark_set"):
target.mark_set("insert", "end")
except Exception:
pass
try:
self.after(1, _again)
except Exception:
pass
return "break"
def _update_placeholder(self, event=None):
try:
empty = not self.input_box.get("1.0", "end").strip()
@@ -187,6 +237,59 @@ class ChatView(ViewBase):
except Exception:
pass
def _update_unload_btn(self):
loaded = bool(self.app_state and self.app_state.model_loaded)
enabled = loaded and not self._busy and not self._unloading
try:
self.unload_btn.configure(
state=("normal" if enabled else "disabled"),
text_color=(c("text_dim") if enabled else c("text_faint")),
)
except Exception:
pass
def _start_typing(self):
self._stop_typing()
self._typing_dots = 0
try:
self._typing_label = ctk.CTkLabel(
self._stream_parent, text="Печатает", font=ui_font(10),
text_color=c("text_faint"), anchor="w",
)
self._typing_label.pack(anchor="w", padx=2, pady=(0, 4))
self._typing_label.lift()
except Exception:
self._typing_label = None
return
self._animate_typing()
def _animate_typing(self):
if not getattr(self, "_alive", True) or self._typing_label is None:
return
try:
dots = "." * ((self._typing_dots % 3) + 1)
self._typing_label.configure(text="Печатает" + dots)
self._typing_dots += 1
self._typing_job = self.after(420, self._animate_typing)
except Exception:
pass
def _stop_typing(self):
job = self._typing_job
self._typing_job = None
if job is not None:
try:
self.after_cancel(job)
except Exception:
pass
label = self._typing_label
self._typing_label = None
if label is not None:
try:
label.destroy()
except Exception:
pass
def set_busy(self, busy: bool):
self._busy = busy
state = "disabled" if busy else "normal"
@@ -195,7 +298,49 @@ class ChatView(ViewBase):
self.send_btn.set_enabled(not busy)
except Exception:
pass
self.status_label.configure(text="Генерация" if busy else "")
self.status_label.configure(text="Генерация…" if busy else "")
self._update_unload_btn()
def on_show(self):
self._update_unload_btn()
self._update_placeholder()
def unload_model(self):
if self._busy:
self.status_label.configure(text="Сначала дождитесь завершения генерации")
return
if self._unloading or not (self.app_state and self.app_state.model_loaded):
return
self._unloading = True
self._update_unload_btn()
self.status_label.configure(text="Выгрузка модели…")
def task():
try:
ok = self.engine.unload_model() if self.engine else False
error = ""
except Exception as e:
ok, error = False, str(e)
self.ui(lambda: self._after_unload(ok, error))
threading.Thread(target=task, daemon=True).start()
def _after_unload(self, ok, error=""):
if not getattr(self, "_alive", True):
return
self._unloading = False
self._stop_typing()
if ok:
self.status_label.configure(text="Модель выгружена")
self.context_label.configure(text="Контекст —", text_color=c("text_faint"))
else:
self.status_label.configure(text=f"Не удалось выгрузить модель: {error}")
self._update_unload_btn()
try:
self.app._update_status_bar()
self.app.sidebar.update_status(self.app_state, True)
except Exception:
pass
# ---------- оценка контекста ----------
def _estimate_text_tokens(self, text: str) -> int:
@@ -267,6 +412,10 @@ class ChatView(ViewBase):
self._labels = []
self._stream_label = None
self._stream_text = ""
self._typing_label = None
self._typing_job = None
self._typing_dots = 0
self._unloading = False
self._agent_mode = False
try:
self.mcp = MCPManager(self.app)
@@ -382,12 +531,25 @@ class ChatView(ViewBase):
self._text_label(parent, tail if found else content, wrap)
self._scroll_bottom()
def _scroll_bottom(self):
def _refresh_scrollregion(self):
try:
canvas = self.messages._parent_canvas
canvas.configure(scrollregion=canvas.bbox("all"))
except Exception:
pass
def _scroll_bottom(self, force=False):
def _do():
if not getattr(self, "_alive", True):
return
try:
self.messages._parent_canvas.yview_moveto(1.0)
canvas = self.messages._parent_canvas
canvas.configure(scrollregion=canvas.bbox("all"))
_first, last = canvas.yview()
# Не выдёргиваем пользователя наверх/вниз, если он сам
# прокрутил историю. Принудительно — только после отправки.
if force or last >= 0.985:
canvas.yview_moveto(1.0)
except Exception:
pass
try:
@@ -413,6 +575,9 @@ class ChatView(ViewBase):
role = "assistant"
self._append_message(role, content)
self.update_context_indicator()
self._update_unload_btn()
self._refresh_scrollregion()
self._scroll_bottom(force=True)
# ---------- действия ----------
def _on_enter(self, event=None):
@@ -484,6 +649,9 @@ class ChatView(ViewBase):
return
if self.app_state is None:
return
if not self.app_state.model_loaded:
self.status_label.configure(text="Сначала загрузите модель")
return
# Не запускаем генерацию, пока идёт обучение/загрузка другой модели.
try:
@@ -515,6 +683,7 @@ class ChatView(ViewBase):
self.app_state.chat_history.append({"role": "user", "content": text})
self._append_message("user", text)
self._scroll_bottom(force=True)
self.input_box.delete("1.0", "end")
self._update_placeholder()
self.set_busy(True)
@@ -551,6 +720,7 @@ class ChatView(ViewBase):
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._stream_parent = bubble
label = ctk.CTkLabel(
bubble, text="", justify="left", anchor="w", font=ui_font(13),
text_color=c("text"), wraplength=self._max_text_width(),
@@ -559,11 +729,14 @@ class ChatView(ViewBase):
self._labels.append((label, False))
self._stream_label = label
self._stream_text = ""
self._scroll_bottom()
self._start_typing()
self._scroll_bottom(force=True)
def _on_token(self, piece: str):
if not piece or self._stream_label is None:
return
if self._typing_label is not None:
self._stop_typing()
self._stream_text += str(piece)
try:
if self._stream_label.winfo_exists():
@@ -720,6 +893,7 @@ class ChatView(ViewBase):
super().destroy()
def _on_result(self, result_text: str):
self._stop_typing()
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:
@@ -736,7 +910,8 @@ class ChatView(ViewBase):
self._append_message("assistant", result_text)
self.set_busy(False)
self.update_context_indicator()
self._update_unload_btn()
try:
self.input_box.focus_set()
self._focus_input()
except Exception:
pass