102 lines
4.2 KiB
Python
102 lines
4.2 KiB
Python
import time
|
|
|
|
import customtkinter as ctk
|
|
|
|
from .base import ViewBase
|
|
from ..theme import c, mono_font, ui_font
|
|
|
|
|
|
class InteractionsView(ViewBase):
|
|
# Раньше на каждую запись создавалось несколько виджетов: на 500 записях
|
|
# «Обновить» занимало секунды, и весь UI в это время не отвечал на клики.
|
|
# Теперь журнал рендерится одним текстовым блоком — это на порядки быстрее.
|
|
MAX_SHOW = 250
|
|
|
|
def __init__(self, master, **kwargs):
|
|
super().__init__(master, **kwargs)
|
|
self.title_text = "Взаимодействия"
|
|
self.configure(fg_color="transparent")
|
|
|
|
self._rendered_key = None
|
|
|
|
actions = ctk.CTkFrame(self, fg_color="transparent")
|
|
actions.pack(fill="x", padx=24, pady=(16, 0))
|
|
|
|
ctk.CTkButton(actions, text="Обновить", command=self.refresh, width=120, height=34).pack(side="left")
|
|
ctk.CTkButton(actions, text="Очистить", command=self.clear, width=120, height=34).pack(side="left", padx=8)
|
|
|
|
self.summary_label = ctk.CTkLabel(self, text="", anchor="w", font=ui_font(11), text_color=c("text_faint"))
|
|
self.summary_label.pack(fill="x", padx=24, pady=(8, 0))
|
|
|
|
self.logbox = ctk.CTkTextbox(self, wrap="word")
|
|
self.logbox.pack(fill="both", expand=True, padx=24, pady=(10, 20))
|
|
|
|
self.refresh()
|
|
|
|
def _short(self, text: str, limit: int = 180) -> str:
|
|
text = (text or "").replace("\n", " ").strip()
|
|
if len(text) > limit:
|
|
return text[: limit - 1] + "…"
|
|
return text
|
|
|
|
def _entries_key(self):
|
|
st = self.app_state
|
|
if not st:
|
|
return (0, 0)
|
|
return (len(st.interactions), id(st.interactions))
|
|
|
|
def on_show(self):
|
|
# Обновляем только если журнал изменился, чтобы переключение вкладки было мгновенным.
|
|
if self._entries_key() != self._rendered_key:
|
|
self.refresh()
|
|
|
|
def refresh(self):
|
|
items = list(self.app_state.interactions) if self.app_state else []
|
|
total = len(items)
|
|
ok_count = sum(1 for i in items if i.get("ok"))
|
|
err_count = total - ok_count
|
|
|
|
shown = items[-self.MAX_SHOW:]
|
|
hidden = total - len(shown)
|
|
suffix = f" | показаны последние {len(shown)}" if hidden > 0 else ""
|
|
self.summary_label.configure(text=f"Всего {total} · успешно {ok_count} · ошибок {err_count}{suffix}")
|
|
|
|
lines = []
|
|
if not items:
|
|
lines.append("Пока нет записей")
|
|
else:
|
|
if hidden > 0:
|
|
lines.append(f"… ещё {hidden} записей скрыто (показаны последние {len(shown)})\n")
|
|
for item in reversed(shown):
|
|
ts = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(item.get("ts", 0)))
|
|
kind = item.get("kind", "?")
|
|
status = "OK" if item.get("ok") else "ОШИБКА"
|
|
model = item.get("model") or "—"
|
|
|
|
lines.append(f"{ts} · {kind} · {status} · {model}")
|
|
inp = self._short(item.get("input", ""))
|
|
if inp:
|
|
lines.append(f" Запрос: {inp}")
|
|
out_src = item.get("error") if (not item.get("ok") and item.get("error")) else item.get("output", "")
|
|
out = self._short(out_src)
|
|
if out:
|
|
lines.append(f" Ответ: {out}")
|
|
params = item.get("params") or {}
|
|
if params:
|
|
ptxt = ", ".join(f"{k}={v}" for k, v in list(params.items())[:8])
|
|
lines.append(f" Параметры: {ptxt}")
|
|
lines.append("")
|
|
|
|
self.logbox.configure(state="normal")
|
|
self.logbox.delete("1.0", "end")
|
|
self.logbox.insert("1.0", "\n".join(lines))
|
|
self.logbox.see("end")
|
|
self.logbox.configure(state="disabled")
|
|
|
|
self._rendered_key = self._entries_key()
|
|
|
|
def clear(self):
|
|
if self.app_state:
|
|
self.app_state.interactions.clear()
|
|
self.refresh()
|