-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathdulus_gui.py
More file actions
387 lines (308 loc) · 13.5 KB
/
dulus_gui.py
File metadata and controls
387 lines (308 loc) · 13.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
"""Dulus GUI Entry Point — professional desktop interface.
Usage:
python dulus_gui.py
python dulus.py --gui
"""
from __future__ import annotations
import datetime
import json
import queue
import sys
import threading
import traceback
from pathlib import Path
from typing import Callable
sys.path.insert(0, str(Path(__file__).parent))
try:
import customtkinter as ctk
except ImportError:
print("Error: customtkinter is required. Install: pip install customtkinter")
sys.exit(1)
from config import load_config
from gui import DulusMainWindow, DulusBridge
from gui.themes import get_theme, set_theme
from gui.session_utils import scan_sessions
# Session directories
from config import SESSIONS_DIR, DAILY_DIR
# ── Helpers ───────────────────────────────────────────────────────────────────
def _center_on_parent(dialog: ctk.CTkToplevel, parent: ctk.CTk) -> None:
"""Center a Toplevel over its parent window."""
dialog.update_idletasks()
pw, ph = parent.winfo_width(), parent.winfo_height()
px, py = parent.winfo_x(), parent.winfo_y()
dw, dh = dialog.winfo_width(), dialog.winfo_height()
x = px + (pw - dw) // 2
y = py + (ph - dh) // 2
dialog.geometry(f"+{x}+{y}")
class _PermissionDialog(ctk.CTkToplevel):
"""Modal permission request dialog centered on the parent."""
def __init__(self, parent: ctk.CTk, description: str, on_resolve: Callable[[bool], None]):
super().__init__(parent)
self._on_resolve = on_resolve
self._create_ui(description)
self._setup_window(parent)
def _create_ui(self, description: str) -> None:
t = get_theme()
self.configure(fg_color=t["bg"])
ctk.CTkLabel(
self,
text="🔒 Permission Required",
font=("Segoe UI", 16, "bold"),
text_color=t["accent"],
).pack(pady=(20, 10))
ctk.CTkLabel(
self,
text=description,
font=("Segoe UI", 12),
text_color=t["text"],
wraplength=450,
).pack(pady=10, padx=20)
btn_frame = ctk.CTkFrame(self, fg_color="transparent")
btn_frame.pack(pady=15)
ctk.CTkButton(
btn_frame,
text="Deny",
font=("Segoe UI", 12, "bold"),
fg_color=t["border"],
hover_color=t["error"],
width=100,
command=self._deny,
).pack(side="left", padx=10)
ctk.CTkButton(
btn_frame,
text="Allow",
font=("Segoe UI", 12, "bold"),
fg_color=t["accent"],
hover_color=t["accent_hover"],
width=100,
command=self._allow,
).pack(side="left", padx=10)
def _setup_window(self, parent: ctk.CTk) -> None:
self.title("Permission Required")
self.geometry("500x220")
self.transient(parent)
self.grab_set()
self.resizable(False, False)
_center_on_parent(self, parent)
def _allow(self) -> None:
self.destroy()
self._on_resolve(True)
def _deny(self) -> None:
self.destroy()
self._on_resolve(False)
# ── Main launcher ─────────────────────────────────────────────────────────────
# _scan_sessions refactored to gui/session_utils.py
def launch_gui(config: dict | None = None, initial_prompt: str | None = None) -> None:
"""Launch the Dulus desktop GUI.
Args:
config: Dulus configuration dict (loaded from disk if None).
initial_prompt: Optional initial user message to send on startup.
"""
cfg = config or load_config()
# ── Ensure MemPalace is initialized for fresh installs ──────────────────
try:
from pathlib import Path as _Path
import subprocess as _sp, sys as _sys, os as _os
_mp_cfg = _Path.home() / ".mempalace" / "config.json"
if not _mp_cfg.exists():
_mem_dir = _Path.home() / ".dulus" / "memory"
_mem_dir.mkdir(parents=True, exist_ok=True)
_env = {**_os.environ, "PYTHONIOENCODING": "utf-8", "PYTHONUTF8": "1"}
_sp.run(
[_sys.executable, "-X", "utf8", "-m", "mempalace", "init",
str(_mem_dir), "--yes", "--no-llm"],
stdout=_sp.DEVNULL, stderr=_sp.DEVNULL,
env=_env,
creationflags=getattr(_sp, "CREATE_NO_WINDOW", 0),
check=False,
)
except Exception:
pass # best-effort; don't block GUI startup
# Theme
ctk.set_appearance_mode(cfg.get("appearance", "dark"))
ctk.set_default_color_theme("dark-blue")
set_theme(cfg.get("theme", "midnight"))
t = get_theme()
# Create GUI window FIRST so user sees something immediately
app = DulusMainWindow()
app.set_model(cfg.get("model", "default"))
# Create bridge (but don't start yet)
bridge = DulusBridge(config=cfg)
# Wire bridge into sidebar so context bar / model list work
app.sidebar.bridge = bridge
# ── Sidebar refresh (non-blocking) ────────────────────────────────────────
_sidebar_refresh_pending = False
def _refresh_sidebar_async() -> None:
"""Run scan_sessions in a background thread so the UI never freezes."""
nonlocal _sidebar_refresh_pending
if _sidebar_refresh_pending:
return
_sidebar_refresh_pending = True
def _do_scan():
try:
data = scan_sessions()
# Update UI from main thread
app.after(0, lambda: app.set_sessions(data))
finally:
nonlocal _sidebar_refresh_pending
_sidebar_refresh_pending = False
threading.Thread(target=_do_scan, daemon=True).start()
def _load_session_messages(path: str) -> list[dict]:
"""Load messages directly from a session file."""
try:
data = json.loads(Path(path).read_text(encoding="utf-8", errors="replace"))
return data.get("messages", [])
except Exception:
return []
# ── Wire callbacks ────────────────────────────────────────────────────────
def _on_send(text: str) -> None:
if text.strip():
# NOTE: message bubble is already added by main_window._on_send_click
app.show_thinking()
bridge.send_message(text)
def _on_new_chat() -> None:
# Save current session if active (it will return a new ID if it was new)
sid = bridge.save_current_session()
if sid:
# If a new session was created, refresh sidebar to show it
_refresh_sidebar_async()
app.hide_thinking()
app.chat.clear_chat()
bridge.clear_session()
app.set_active_session(None)
app.sidebar.update_context_bar()
app.set_status("Listo", t["success"])
def _on_session_select(session_id: str) -> None:
# Save current session before switching to ensure no loss
sid = bridge.save_current_session()
# If we were in a new chat that just got saved, refresh sidebar to show it
if sid:
_refresh_sidebar_async()
app.hide_thinking()
# 1. Find the session file path (from cache or scan)
session_path = None
cached = app.sidebar._session_cache.get(session_id)
if cached:
session_path = cached.get("path")
if not session_path:
for s in scan_sessions():
if s["id"] == session_id:
session_path = s.get("path")
break
if not session_path:
return
# 2. Load messages directly from disk (avoids keeping all messages in memory)
messages = _load_session_messages(session_path)
app.chat.load_messages(messages)
# 3. Defer bridge loading until first message (user request)
bridge.pending_history = messages
bridge.session_id = session_id
# Important: clear actual AI state so it's fresh until sync
from agent import AgentState
bridge.state = AgentState()
app.set_active_session(session_id)
app.sidebar.update_context_bar()
app.set_status("Sesión lista (Contexto diferido)", t["success"])
def _on_settings() -> None:
from gui.settings_dialog import SettingsDialog
SettingsDialog(app, cfg)
def _on_model_change(model: str) -> None:
bridge.set_model(model)
app.set_model(model)
app.on_send = _on_send
app.on_new_chat = _on_new_chat
app.sidebar.on_settings = _on_settings
app.on_model_change = _on_model_change
app.on_session_select = _on_session_select
# Load existing sessions into sidebar (async so GUI shows immediately)
_refresh_sidebar_async()
app.sidebar._refresh_model_list()
app.sidebar.update_context_bar()
# ── Permission dialog handling ────────────────────────────────────────────
_perm_dialog: _PermissionDialog | None = None
def _close_perm() -> None:
nonlocal _perm_dialog
if _perm_dialog is not None:
_perm_dialog.destroy()
_perm_dialog = None
def _resolve_perm(granted: bool) -> None:
_close_perm()
bridge.grant_permission(granted)
def _show_perm(description: str) -> None:
nonlocal _perm_dialog
_close_perm()
_perm_dialog = _PermissionDialog(app, description, _resolve_perm)
# ── Event polling loop ────────────────────────────────────────────────────
def _poll_events() -> None:
if not app.winfo_exists():
return # App destroyed, stop polling
try:
while True:
event = bridge.event_queue.get_nowait()
etype = event.get("type")
if etype == "text":
app.add_assistant_chunk(event.get("text", ""))
elif etype == "thinking":
app.show_thinking()
elif etype == "tool_start":
app.add_tool_call(event.get("name", "tool"), "running")
elif etype == "tool_end":
app.add_tool_call(event.get("name", ""), "done")
elif etype == "turn_done":
app.hide_thinking()
itok = event.get("input_tokens", 0)
otok = event.get("output_tokens", 0)
app.set_status(f"Listo (+{itok}/{otok} tok)", t["success"])
# Only rebuild sidebar if this is a brand-new session not yet in the list.
# Rebuilding after every message causes annoying flicker.
sid = event.get("session_id")
if sid and sid not in app.sidebar._session_buttons:
_refresh_sidebar_async()
if sid:
app.set_active_session(sid)
elif etype == "permission":
_show_perm(event.get("description", ""))
elif etype == "error":
app.hide_thinking()
app.chat.add_assistant_message(
f"**Error:** {event.get('message', 'Unknown error')}"
)
app.set_status("Error", t["error"])
except queue.Empty:
pass
except Exception as exc:
# Log to file so we know what crashed the UI
try:
with open("gui_error.log", "a", encoding="utf-8") as f:
f.write(f"\n[{datetime.datetime.now()}] POLL ERROR: {exc}\n")
traceback.print_exc(file=f)
except Exception:
pass
finally:
# ALWAYS reschedule — if we don't, the GUI stops responding
if app.winfo_exists():
app.after(50, _poll_events)
app.after(50, _poll_events)
# ── Start bridge AFTER UI is ready ────────────────────────────────────────
try:
bridge.start()
except Exception as exc:
app.chat.add_assistant_message(f"**Fatal:** Could not start Dulus bridge: {exc}")
app.set_status("Fatal error", t["error"])
# ── Initial prompt ────────────────────────────────────────────────────────
if initial_prompt:
app.chat.add_user_message(initial_prompt)
bridge.send_message(initial_prompt)
app.show_thinking()
# ── Cleanup ───────────────────────────────────────────────────────────────
def _on_close() -> None:
bridge.stop()
app.destroy()
app.protocol("WM_DELETE_WINDOW", _on_close)
app.run()
def main() -> None:
"""CLI entry point."""
cfg = load_config()
launch_gui(config=cfg)
if __name__ == "__main__":
main()