Compare commits

..
2 Commits
7 changed files with 514 additions and 33 deletions

No files matched your search

+11
View File
@@ -69,6 +69,17 @@ Flash Attention. Настройки по умолчанию и свои папк
«Настройки → Модели». Кнопка модели в верхней панели открывает быстрый выбор
локальной модели.
### Файловый агент
В «Настройки → MCP → Рабочие папки» задаются каталоги, внутри которых
файловый агент может читать и изменять файлы. Папки можно добавить,
создать, открыть, удалить и проверить. Пути с пробелами и Unicode
поддерживаются; для папок только с правом чтения показывается
предупреждение.
Свободное место контролируется при скачивании моделей и смене папки
загрузок: приложение заранее сообщает, если места недостаточно.
### Поиск моделей и прокси
Вкладка «Поиск» ищет GGUF-модели на Hugging Face и скачивает выбранный файл
+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
+256 -25
View File
@@ -3,9 +3,10 @@
import os
import threading
import time
import shutil
import tkinter as tk
import webbrowser
from tkinter import filedialog, messagebox
from tkinter import filedialog, messagebox, simpledialog
import customtkinter as ctk
@@ -1213,6 +1214,9 @@ class SettingsWindow(ctk.CTkToplevel):
self.model_download_dir.pack(side="left", fill="x", expand=True)
ctk.CTkButton(row, text="Обзор", width=74, height=32,
command=self._browse_download_dir).pack(side="left", padx=(8, 0))
self.models_space_label = ctk.CTkLabel(
body, text="", font=ui_font(9), text_color=c("text_faint"), anchor="w")
self.models_space_label.pack(fill="x", padx=20, pady=(0, 8))
self._section_title(body, "Параметры загрузки по умолчанию",
"Используются, пока для модели не сохранён свой пресет")
@@ -1300,6 +1304,7 @@ class SettingsWindow(ctk.CTkToplevel):
self.model_download_dir.insert(
0, str(conf.get("download_dir")
or os.path.expanduser("~/.local/share/xenith-studio/models")))
self._refresh_models_space()
if hasattr(self, "hf_token_entry"):
self.hf_token_entry.delete(0, "end")
self.hf_token_entry.insert(0, str(conf.get("hf_token") or ""))
@@ -1408,10 +1413,39 @@ class SettingsWindow(ctk.CTkToplevel):
threading.Thread(target=task, daemon=True).start()
def _refresh_models_space(self):
if not hasattr(self, "models_space_label"):
return
path = (self.model_download_dir.get().strip()
or os.path.expanduser("~/.local/share/xenith-studio/models"))
path = os.path.abspath(os.path.expanduser(path))
try:
usage = shutil.disk_usage(path)
free = usage.free / (1024 ** 3)
total = usage.total / (1024 ** 3)
self.models_space_label.configure(
text=f"Свободно {free:.1f} ГБ из {total:.1f} ГБ",
text_color=(c("warn") if free < 2 else c("text_faint")),
)
except Exception as e:
self.models_space_label.configure(text=f"Папка недоступна: {e}",
text_color=c("danger"))
def _add_model_dir(self):
path = filedialog.askdirectory(title="Папка с GGUF-моделями")
try:
path = filedialog.askdirectory(title="Папка с GGUF-моделями",
parent=self, mustexist=True)
except Exception as e:
self.models_status.configure(text=f"Не удалось выбрать папку: {e}",
text_color=c("danger"))
return
if not path:
return
path = os.path.abspath(path)
if not os.access(path, os.R_OK):
self.models_status.configure(text="Нет прав на чтение этой папки",
text_color=c("danger"))
return
current = self.model_dirs_box.get("1.0", "end").strip()
if path not in [p.strip() for p in current.splitlines() if p.strip()]:
if current:
@@ -1420,11 +1454,18 @@ class SettingsWindow(ctk.CTkToplevel):
self.model_dirs_box.insert("1.0", path)
def _browse_download_dir(self):
path = filedialog.askdirectory(title="Каталог загрузок моделей")
try:
path = filedialog.askdirectory(title="Каталог загрузок моделей",
parent=self, mustexist=True)
except Exception as e:
self.models_status.configure(text=f"Не удалось выбрать папку: {e}",
text_color=c("danger"))
return
if not path:
return
self.model_download_dir.delete(0, "end")
self.model_download_dir.insert(0, path)
self.model_download_dir.insert(0, os.path.abspath(path))
self._refresh_models_space()
def _open_download_dir(self):
path = os.path.expanduser(self.model_download_dir.get().strip())
@@ -1462,8 +1503,22 @@ class SettingsWindow(ctk.CTkToplevel):
except Exception:
defaults["threads"] = 0
defaults["flash_attn"] = bool(self.model_flash.get())
conf["download_dir"] = (self.model_download_dir.get().strip()
or os.path.expanduser("~/.local/share/xenith-studio/models"))
download_dir = (self.model_download_dir.get().strip()
or os.path.expanduser("~/.local/share/xenith-studio/models"))
download_dir = os.path.abspath(os.path.expanduser(download_dir))
try:
os.makedirs(download_dir, exist_ok=True)
if not os.path.isdir(download_dir):
raise OSError("это не каталог")
if not os.access(download_dir, os.W_OK):
raise OSError("нет прав на запись")
except Exception as e:
self.models_status.configure(
text=f"Папка загрузок недоступна: {e}", text_color=c("danger"))
return
conf["download_dir"] = download_dir
self.model_download_dir.delete(0, "end")
self.model_download_dir.insert(0, download_dir)
conf["hf_token"] = self.hf_token_entry.get().strip()
mode = self.hf_proxy_mode.get()
if mode == "Напрямую":
@@ -1474,7 +1529,14 @@ class SettingsWindow(ctk.CTkToplevel):
conf["hf_proxy"] = "auto"
try:
self.app.engine.save_config()
self.models_status.configure(text="Сохранено", text_color=c("success"))
free = ""
try:
usage = shutil.disk_usage(download_dir)
free = f" · свободно {usage.free / (1024 ** 3):.1f} ГБ"
except Exception:
pass
self.models_status.configure(text="Сохранено" + free, text_color=c("success"))
self._refresh_models_space()
except Exception as e:
self.models_status.configure(text=f"Ошибка: {e}", text_color=c("danger"))
return
@@ -1512,15 +1574,39 @@ class SettingsWindow(ctk.CTkToplevel):
wraplength=560)
self.mcp_hint.pack(anchor="w", padx=20, pady=(0, 10))
ctk.CTkLabel(frame, text="Разрешённые папки", font=ui_font(11),
text_color=c("text_dim")).pack(anchor="w", padx=20, pady=(8, 4))
self.roots_box = ctk.CTkTextbox(frame, height=120, wrap="none", font=mono_font(10))
self.roots_box.pack(fill="x", padx=20, pady=(0, 8))
ctk.CTkLabel(frame, text="Рабочие папки", font=ui_font(11),
text_color=c("text_dim")).pack(anchor="w", padx=20, pady=(8, 2))
ctk.CTkLabel(
frame,
text="Агент может читать и изменять файлы только внутри этих папок. "
"Пути можно вводить вручную, по одному в строке.",
font=ui_font(10), text_color=c("text_faint"), anchor="w",
justify="left", wraplength=600,
).pack(anchor="w", padx=20, pady=(0, 4))
self.roots_box = ctk.CTkTextbox(frame, height=110, wrap="none", font=mono_font(10))
self.roots_box.pack(fill="x", padx=20, pady=(0, 4))
self.mcp_folders_status = ctk.CTkLabel(
frame, text="", font=ui_font(9), text_color=c("text_faint"),
anchor="w", justify="left", wraplength=600,
)
self.mcp_folders_status.pack(fill="x", padx=20, pady=(0, 8))
row = ctk.CTkFrame(frame, fg_color="transparent")
row.pack(fill="x", padx=20, pady=(0, 16))
ctk.CTkButton(row, text="Добавить папку", height=32,
row.pack(fill="x", padx=20, pady=(0, 4))
ctk.CTkButton(row, text="Добавить папку", height=30,
command=self._add_mcp_root).pack(side="left")
ctk.CTkButton(row, text="Сохранить", height=32,
ctk.CTkButton(row, text="Создать папку", height=30,
command=self._create_mcp_root).pack(side="left", padx=6)
ctk.CTkButton(row, text="Открыть", height=30, width=92,
command=self._open_mcp_root).pack(side="left")
ctk.CTkButton(row, text="Удалить", height=30, width=92,
command=self._remove_mcp_root).pack(side="left", padx=6)
row2 = ctk.CTkFrame(frame, fg_color="transparent")
row2.pack(fill="x", padx=20, pady=(0, 16))
ctk.CTkButton(row2, text="Проверить папки", height=30, width=140,
command=self._validate_mcp_roots).pack(side="left")
ctk.CTkButton(row2, text="Сохранить", height=30, width=120,
fg_color=c("action_bg"), hover_color=c("action_hover"),
text_color=c("action_fg"), font=ui_font(12),
command=self._save_mcp).pack(side="left", padx=8)
@@ -1543,37 +1629,182 @@ class SettingsWindow(ctk.CTkToplevel):
}
self.mcp_hint.configure(text=hints.get(mode, ""))
roots = conf.get("roots") or []
self.roots_box.configure(state="normal")
self.roots_box.delete("1.0", "end")
self.roots_box.insert("1.0", "\n".join(str(r) for r in roots))
self.roots_box.configure(state="disabled")
self._validate_mcp_roots(show=False)
except Exception:
pass
def _mcp_root_lines(self):
return [line.strip() for line in
self.roots_box.get("1.0", "end").splitlines() if line.strip()]
def _append_mcp_root(self, path):
path = os.path.abspath(os.path.expanduser(str(path)))
current = [os.path.abspath(os.path.expanduser(p))
for p in self._mcp_root_lines()]
if path in current:
self.mcp_folders_status.configure(text="Эта папка уже добавлена",
text_color=c("text_faint"))
return
text = self.roots_box.get("1.0", "end").strip()
if text:
self.roots_box.insert("end", "\n" + path)
else:
self.roots_box.insert("1.0", path)
self._save_mcp()
def _add_mcp_root(self):
d = filedialog.askdirectory(title="Разрешённая папка для MCP", parent=self)
try:
d = filedialog.askdirectory(title="Рабочая папка для файлового агента",
parent=self, mustexist=True)
except Exception as e:
self.mcp_folders_status.configure(text=f"Не удалось открыть выбор папки: {e}",
text_color=c("danger"))
return
if not d:
return
d = os.path.abspath(d)
conf = self.app.engine.config.setdefault("mcp", {})
roots = conf.setdefault("roots", [])
if d not in roots:
roots.append(d)
if not os.access(d, os.R_OK):
self.mcp_folders_status.configure(text="Нет прав на чтение этой папки",
text_color=c("danger"))
return
self._append_mcp_root(d)
def _create_mcp_root(self):
try:
parent = filedialog.askdirectory(title="Где создать рабочую папку",
parent=self, mustexist=True)
if not parent:
return
name = simpledialog.askstring("Новая рабочая папка", "Имя папки:",
initialvalue="XenithWorkspace",
parent=self)
if not name:
return
name = name.strip().replace("/", "").replace("\\", "")
if not name:
return
path = os.path.join(parent, name)
os.makedirs(path, exist_ok=True)
except Exception as e:
self.mcp_folders_status.configure(text=f"Не удалось создать папку: {e}",
text_color=c("danger"))
return
self._append_mcp_root(path)
def _selected_mcp_root(self):
try:
textbox = getattr(self.roots_box, "_textbox", None)
if textbox is not None:
ranges = textbox.tag_ranges("sel")
if ranges:
value = textbox.get("sel.first", "sel.last").strip()
if value:
return value.splitlines()[0].strip()
index = textbox.index("insert")
line = int(str(index).split(".")[0])
value = textbox.get(f"{line}.0", f"{line}.end").strip()
if value:
return value
except Exception:
pass
return ""
def _remove_mcp_root(self):
target = self._selected_mcp_root()
lines = self._mcp_root_lines()
if not lines:
return
if not target:
target = lines[-1]
remaining = [p for p in lines
if os.path.abspath(os.path.expanduser(p)) !=
os.path.abspath(os.path.expanduser(target))]
if len(remaining) == len(lines):
remaining = lines[:-1]
self.roots_box.delete("1.0", "end")
self.roots_box.insert("1.0", "\n".join(remaining))
self._save_mcp()
def _open_mcp_root(self):
target = self._selected_mcp_root() or (self._mcp_root_lines() or [""])[0]
if not target:
return
path = os.path.abspath(os.path.expanduser(target))
try:
import subprocess
subprocess.Popen(["xdg-open", path])
except Exception as e:
self.mcp_folders_status.configure(text=f"Не удалось открыть: {e}",
text_color=c("danger"))
def _validate_mcp_roots(self, show=True):
roots = []
errors = []
warnings = []
for raw in self._mcp_root_lines():
path = os.path.abspath(os.path.expanduser(raw))
if path in roots:
continue
if not os.path.exists(path):
errors.append(f"нет папки: {raw}")
continue
if not os.path.isdir(path):
errors.append(f"не каталог: {raw}")
continue
if not os.access(path, os.R_OK):
errors.append(f"нет чтения: {raw}")
continue
if not os.access(path, os.W_OK):
warnings.append(f"только чтение: {raw}")
roots.append(path)
if not self._mcp_root_lines():
text = "Папки не выбраны — файловый агент выключен."
color = c("warn")
elif errors:
text = "Ошибки: " + "; ".join(errors[:3])
color = c("danger")
elif warnings:
text = "Можно читать, но не записывать: " + "; ".join(warnings[:2])
color = c("warn")
else:
text = f"Проверено папок: {len(roots)} · запись разрешена"
color = c("success")
if show:
self.mcp_folders_status.configure(text=text, text_color=color)
else:
self.mcp_folders_status.configure(
text=text, text_color=color if color != c("success") else c("text_faint"))
return roots, errors, warnings
def _save_mcp(self, *_):
try:
roots, errors, warnings = self._validate_mcp_roots(show=True)
if errors:
self.mcp_folders_status.configure(
text="Не сохранено: " + "; ".join(errors[:2]),
text_color=c("danger"))
return
for label, key in MCP_MODES.items():
if label == self.mcp_mode.get():
self.app.engine.config.setdefault("mcp", {})["mode"] = key
break
roots = [line.strip() for line in self.roots_box.get("1.0", "end").splitlines() if line.strip()]
self.app.engine.config.setdefault("mcp", {})["roots"] = roots
self.app.engine.save_config()
self.roots_box.delete("1.0", "end")
self.roots_box.insert("1.0", "\n".join(roots))
self._refresh_mcp()
self.engine_status.configure(text="MCP сохранён", text_color=c("text_faint"))
if warnings:
self.mcp_folders_status.configure(
text="Сохранено, но часть папок доступна только для чтения",
text_color=c("warn"))
else:
self.mcp_folders_status.configure(
text=f"Сохранено · папок: {len(roots)}",
text_color=c("success"))
except Exception as e:
self.engine_status.configure(text=f"Ошибка MCP: {e}", text_color=c("danger"))
self.mcp_folders_status.configure(text=f"Ошибка сохранения: {e}",
text_color=c("danger"))
# ==================================================================
# Обновления
+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:
+15
View File
@@ -38,6 +38,7 @@ from __future__ import annotations
import json
import os
import re
import shutil
import threading
from contextlib import contextmanager
from functools import wraps
@@ -858,6 +859,20 @@ def _download_once(
done = base_done
mode = "ab" if resume else "wb"
if total > 0:
try:
free = shutil.disk_usage(os.path.dirname(part_path) or ".").free
needed = max(0, int(total) - int(done))
if free < needed + 16 * 1024 * 1024:
raise HfHubError(
"Недостаточно места на диске для загрузки модели: "
f"нужно {needed / (1024 ** 3):.1f} ГБ, "
f"свободно {free / (1024 ** 3):.1f} ГБ"
)
except HfHubError:
raise
except OSError:
pass
_notify(on_progress, done, total)
try:
+1 -1
View File
@@ -1 +1 @@
__version__ = "0.2.0"
__version__ = "0.2.1"
+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