tzero-mcp 12.3.5 → 12.3.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -109,6 +109,7 @@ if tzero_deps is not None and not tzero_deps.ensure_dependencies():
109
109
  import keyring
110
110
  import requests
111
111
  import threading
112
+ from queue import Empty, SimpleQueue
112
113
  import subprocess
113
114
  import webbrowser
114
115
  from typing import Dict, List, Any, Tuple, Optional, Set, Callable
@@ -218,19 +219,19 @@ THEME_PALETTES = {
218
219
  "error": "#f43f5e"
219
220
  },
220
221
  "Luxury Dashboard": {
221
- "bg_start": "#f3f1eb",
222
- "card_bg": "#fffdf8",
223
- "card_border": "#e5dfd3",
224
- "card_shadow": "#ded7ca",
225
- "card_hover": "#f4efe5",
222
+ "bg_start": "#f3f5f9",
223
+ "card_bg": "#ffffff",
224
+ "card_border": "#dce3ee",
225
+ "card_shadow": "#e3e9f2",
226
+ "card_hover": "#eef2f9",
226
227
  "sidebar_bg": "#18243b",
227
228
  "sidebar_fg": "#f8f5ef",
228
- "sidebar_muted": "#c8b895",
229
+ "sidebar_muted": "#bac8dc",
229
230
  "sidebar_hover": "#26344d",
230
231
  "sidebar_active": "#2d3d57",
231
232
  "text_main": "#202633",
232
233
  "text_muted": "#687180",
233
- "accent_cyan": "#80643a",
234
+ "accent_cyan": "#2d5ca6",
234
235
  "accent_green": "#237d6b",
235
236
  "accent_purple": "#7864a6",
236
237
  "accent_coral": "#c6784b",
@@ -493,7 +494,7 @@ def calculate_token_cost(token_count: int, provider_name: str) -> float:
493
494
  # i18n Translations
494
495
  TRANSLATIONS: Dict[str, Dict[str, str]] = {
495
496
  "en": {
496
- "title": "T-Zero Developer Console & Context Architect v12.3.5",
497
+ "title": "T-Zero Developer Console & Context Architect v12.3.6",
497
498
  "subtitle": f"Developer: {DEV_NAME} | {DEV_URL_MAIN} | {DEV_URL_BIO}",
498
499
  "overview_tab": "🏠 Overview Dashboard",
499
500
  "setup_tab": "⚡ Setup & AI Models",
@@ -530,7 +531,7 @@ TRANSLATIONS: Dict[str, Dict[str, str]] = {
530
531
  "audit_btn": "🛡️ SECURITY AUDIT"
531
532
  },
532
533
  "tr": {
533
- "title": "T-Zero Developer Console & Context Architect v12.3.5",
534
+ "title": "T-Zero Developer Console & Context Architect v12.3.6",
534
535
  "subtitle": f"Developer: {DEV_NAME} | {DEV_URL_MAIN} | {DEV_URL_BIO}",
535
536
  "overview_tab": "🏠 Overview Dashboard",
536
537
  "setup_tab": "⚡ Setup & AI Models",
@@ -607,80 +608,6 @@ def validate_directory(path: str) -> bool:
607
608
  return os.path.exists(expanded) and os.path.isdir(expanded)
608
609
 
609
610
 
610
- class ToastNotification(tk.Toplevel):
611
- """Sleek animated glassmorphism toast notification."""
612
- def __init__(self, master, title, message, n_type='info'):
613
- super().__init__(master)
614
- self.overrideredirect(True)
615
- self.attributes('-alpha', 0.0)
616
- self.attributes('-topmost', True)
617
-
618
- bg_color = PALETTE['card_bg']
619
- accent = PALETTE['accent_cyan']
620
- if n_type == 'error': accent = '#ef4444'
621
- elif n_type == 'success': accent = '#10b981'
622
- elif n_type == 'warning': accent = '#f59e0b'
623
-
624
- self.configure(bg=bg_color, highlightthickness=1, highlightbackground=accent)
625
-
626
- lbl_title = tk.Label(self, text=title, bg=bg_color, fg=accent, font=('Segoe UI', 10, 'bold'))
627
- lbl_title.pack(anchor='w', padx=16, pady=(12, 2))
628
-
629
- lbl_msg = tk.Label(self, text=message, bg=bg_color, fg=PALETTE['text_fg'], font=('Segoe UI', 9), justify='left')
630
- lbl_msg.pack(anchor='w', padx=16, pady=(0, 12))
631
-
632
- self.update_idletasks()
633
- w = self.winfo_reqwidth()
634
- h = self.winfo_reqheight()
635
-
636
- # Position top right of the master window
637
- x = master.winfo_rootx() + master.winfo_width() - w - 24
638
- y = master.winfo_rooty() + 24
639
-
640
- self.geometry(f'{w}x{h}+{x}+{y}')
641
-
642
- self.alpha = 0.0
643
- self.fade_in()
644
- self.after(4000, self.fade_out)
645
-
646
- def fade_in(self):
647
- self.alpha += 0.1
648
- if self.alpha <= 0.95:
649
- self.attributes('-alpha', self.alpha)
650
- self.after(16, self.fade_in)
651
-
652
- def fade_out(self):
653
- self.alpha -= 0.1
654
- if self.alpha > 0:
655
- self.attributes('-alpha', self.alpha)
656
- self.after(16, self.fade_out)
657
- else:
658
- self.destroy()
659
-
660
- def _custom_showinfo(title, msg, **kwargs):
661
- from tkinter import _default_root
662
- r = _default_root
663
- if not r: return
664
- ToastNotification(r, title, msg, 'success')
665
-
666
- def _custom_showerror(title, msg, **kwargs):
667
- from tkinter import _default_root
668
- r = _default_root
669
- if not r: return
670
- ToastNotification(r, title, msg, 'error')
671
-
672
- def _custom_showwarning(title, msg, **kwargs):
673
- from tkinter import _default_root
674
- r = _default_root
675
- if not r: return
676
- ToastNotification(r, title, msg, 'warning')
677
-
678
- # Hook into standard messagebox
679
- messagebox.showinfo = _custom_showinfo
680
- messagebox.showerror = _custom_showerror
681
- messagebox.showwarning = _custom_showwarning
682
-
683
-
684
611
  class ConfigManager:
685
612
  """Manages profile loading, backups, secure keyring storage and parameter settings."""
686
613
  def __init__(self, config_dir: str = DEFAULT_CONFIG_DIR):
@@ -3473,6 +3400,11 @@ class WideSplineChartCard(LuxuryCard):
3473
3400
  self.anim_task = None
3474
3401
  self.c.bind("<Configure>", self._start_anim)
3475
3402
 
3403
+ leg = tk.Frame(self.inner, bg=self.card_bg)
3404
+ leg.pack(pady=(4, 0))
3405
+ tk.Label(leg, text="● Original AST Tokens", font=("Segoe UI", 7, "bold"), fg=PALETTE.get("accent_purple", "#6366f1"), bg=self.card_bg).pack(side=tk.LEFT, padx=10)
3406
+ tk.Label(leg, text="● T-Zero Compressed Prompt", font=("Segoe UI", 7, "bold"), fg=PALETTE.get("accent_coral", "#f97316"), bg=self.card_bg).pack(side=tk.LEFT, padx=10)
3407
+
3476
3408
  def _start_anim(self, event=None):
3477
3409
  self.anim_progress = 0.0
3478
3410
  if self.anim_task:
@@ -3488,10 +3420,6 @@ class WideSplineChartCard(LuxuryCard):
3488
3420
  self._draw()
3489
3421
  self.anim_task = self.after(20, self._animate)
3490
3422
 
3491
- leg = tk.Frame(self.inner, bg=self.card_bg)
3492
- leg.pack(pady=(4, 0))
3493
- tk.Label(leg, text="● Original AST Tokens", font=("Segoe UI", 7, "bold"), fg=PALETTE.get("accent_purple", "#6366f1"), bg=self.card_bg).pack(side=tk.LEFT, padx=10)
3494
- tk.Label(leg, text="● T-Zero Compressed Prompt", font=("Segoe UI", 7, "bold"), fg=PALETTE.get("accent_coral", "#f97316"), bg=self.card_bg).pack(side=tk.LEFT, padx=10)
3495
3423
 
3496
3424
  def _draw(self, event=None):
3497
3425
  w = max(20, self.c.winfo_width())
@@ -4491,6 +4419,10 @@ class AdvancedTokenDistributionChart(tk.Canvas):
4491
4419
  self.create_text(w - 6, y + 7, text=f"{size_str} ({pct:.0f}%)", fill=PALETTE["text_muted"], font=("Segoe UI", 7, "bold"), anchor="e")
4492
4420
 
4493
4421
 
4422
+ def _run_desktop_git(args, **kwargs):
4423
+ return subprocess.run(args, creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0), **kwargs)
4424
+
4425
+
4494
4426
  class CustomChangelogManager:
4495
4427
  """Safely retrieves git log history and repository diffs asynchronously."""
4496
4428
  def __init__(self, target_dir: str):
@@ -4502,7 +4434,7 @@ class CustomChangelogManager:
4502
4434
  callback([])
4503
4435
  return
4504
4436
  try:
4505
- res = subprocess.run(
4437
+ res = _run_desktop_git(
4506
4438
  ["git", "rev-parse", "--is-inside-work-tree"],
4507
4439
  cwd=self.target_dir,
4508
4440
  capture_output=True,
@@ -4513,7 +4445,7 @@ class CustomChangelogManager:
4513
4445
  callback([])
4514
4446
  return
4515
4447
 
4516
- res = subprocess.run(
4448
+ res = _run_desktop_git(
4517
4449
  ["git", "log", "-n", "15", "--pretty=format:%s (%an)"],
4518
4450
  cwd=self.target_dir,
4519
4451
  capture_output=True,
@@ -4547,7 +4479,7 @@ class CustomChangelogManager:
4547
4479
  def get_git_diff_async(self, callback: Callable) -> None:
4548
4480
  def run_thread():
4549
4481
  try:
4550
- res = subprocess.run(
4482
+ res = _run_desktop_git(
4551
4483
  ["git", "diff", "HEAD"],
4552
4484
  cwd=self.target_dir,
4553
4485
  capture_output=True,
@@ -4650,6 +4582,9 @@ class AutoReadmeGUI:
4650
4582
  def __init__(self, root: tk.Tk):
4651
4583
  self.root = root
4652
4584
  self.lang = "en"
4585
+ self._ui_thread = threading.get_ident()
4586
+ self._ui_callbacks = SimpleQueue()
4587
+ self.root.after(25, self._drain_ui_callbacks)
4653
4588
 
4654
4589
  # State parameters
4655
4590
  self.scanned_files: List[str] = []
@@ -4723,66 +4658,35 @@ class AutoReadmeGUI:
4723
4658
  self.load_saved_credentials()
4724
4659
  self.setup_keyboard_shortcuts()
4725
4660
  self.start_system_telemetry()
4726
- self.start_community_stats_refresh()
4727
- if "unittest" not in sys.modules:
4728
- self.safe_after(1200, self.check_and_show_startup_popups)
4729
4661
 
4730
4662
  def _attach_tooltip(self, widget, text: str):
4731
- """Attach a sleek floating English tooltip on mouse hover."""
4732
- if not TK_AVAILABLE or widget is None:
4733
- return
4734
- tip_win = {"w": None}
4663
+ """Show toolbar hints in the status strip without creating a window."""
4664
+ def show_hint(_event):
4665
+ if hasattr(self, "status_hint_lbl"):
4666
+ self.status_hint_lbl.configure(text=text)
4735
4667
 
4736
- def show_tip(_event=None):
4737
- try:
4738
- if tip_win["w"] or not widget.winfo_exists():
4739
- return
4740
- tw = tk.Toplevel(widget)
4741
- tw.overrideredirect(True)
4742
- tw.attributes("-topmost", True)
4743
- x = widget.winfo_rootx() + widget.winfo_width() + 8
4744
- y = widget.winfo_rooty() + max(0, (widget.winfo_height() - 24) // 2)
4745
- tw.geometry(f"+{x}+{y}")
4746
- lbl = tk.Label(
4747
- tw,
4748
- text=text,
4749
- bg=PALETTE.get("card_bg", "#0f172a"),
4750
- fg=PALETTE.get("text_main", "#f8fafc"),
4751
- font=("Segoe UI", 8, "bold"),
4752
- padx=9,
4753
- pady=4,
4754
- highlightthickness=1,
4755
- highlightbackground=PALETTE.get("accent_cyan", "#38bdf8"),
4756
- )
4757
- lbl.pack()
4758
- tip_win["w"] = tw
4759
- except Exception:
4760
- pass
4668
+ def clear_hint(_event):
4669
+ if hasattr(self, "status_hint_lbl"):
4670
+ self.status_hint_lbl.configure(text="")
4761
4671
 
4762
- def hide_tip(_event=None):
4763
- tw = tip_win.get("w")
4764
- tip_win["w"] = None
4765
- if tw is not None:
4766
- try:
4767
- tw.destroy()
4768
- except Exception:
4769
- pass
4672
+ widget.bind("<Enter>", show_hint, add="+")
4673
+ widget.bind("<Leave>", clear_hint, add="+")
4674
+ widget.bind("<ButtonPress>", clear_hint, add="+")
4770
4675
 
4771
- try:
4772
- widget.bind("<Enter>", show_tip, add="+")
4773
- widget.bind("<Leave>", hide_tip, add="+")
4774
- widget.bind("<ButtonPress>", hide_tip, add="+")
4775
- except Exception:
4776
- pass
4777
-
4778
4676
  def safe_after(self, ms: int, func, *args):
4779
- """Thread-safe and lifecycle-safe wrapper around root.after."""
4780
- try:
4781
- if hasattr(self, "root") and self.root and self.root.winfo_exists():
4782
- return self.root.after(ms, func, *args)
4783
- except Exception:
4784
- pass
4785
- return None
4677
+ if getattr(self, "_ui_thread", threading.get_ident()) != threading.get_ident():
4678
+ self._ui_callbacks.put((ms, func, args))
4679
+ return None
4680
+ return self.root.after(ms, func, *args)
4681
+
4682
+ def _drain_ui_callbacks(self):
4683
+ self.root.after(25, self._drain_ui_callbacks)
4684
+ for _ in range(32):
4685
+ try:
4686
+ ms, callback, args = self._ui_callbacks.get_nowait()
4687
+ except Empty:
4688
+ break
4689
+ self.root.after(ms, callback, *args)
4786
4690
 
4787
4691
  def setup_keyboard_shortcuts(self):
4788
4692
  self.root.bind("<Control-s>", lambda e: self.run_scanner())
@@ -4814,7 +4718,7 @@ class AutoReadmeGUI:
4814
4718
 
4815
4719
  # 7 Tabs with sleek icons
4816
4720
  self.tabs = ["overview_tab", "selector_tab", "changelog_tab", "generate_tab", "template_tab", "graph_tab", "settings_tab"]
4817
- self.tab_icons = ["🏠", "📂", "🔀", "🚀", "🧪", "📊", "⚙️"]
4721
+ self.tab_icons = ["⌂", "▤", "⑂", "▷", "◇", "▥", "⚙"]
4818
4722
  self.tab_buttons: List[tk.Label] = []
4819
4723
  self.tab_containers: List[tk.Frame] = []
4820
4724
  self.nav_indicators: List[tk.Frame] = []
@@ -4870,7 +4774,7 @@ class AutoReadmeGUI:
4870
4774
 
4871
4775
  # 2. TOP HEADER BAR
4872
4776
  self.header = GlassCard(self.bg_canvas)
4873
- self.header.place(x=82, y=8, relwidth=1.0, width=-92, height=48)
4777
+ self.header.place(x=82, y=8, relwidth=1.0, width=-92, height=54)
4874
4778
 
4875
4779
  title_frame = tk.Frame(self.header, bg=PALETTE["card_bg"])
4876
4780
  title_frame.pack(side=tk.LEFT, fill=tk.Y, padx=14, pady=2)
@@ -4878,7 +4782,7 @@ class AutoReadmeGUI:
4878
4782
  title_row = tk.Frame(title_frame, bg=PALETTE["card_bg"])
4879
4783
  title_row.pack(anchor=tk.W)
4880
4784
 
4881
- self.title_lbl = tk.Label(title_row, text=get_text("title", self.lang), font=("Segoe UI", 11, "bold"), fg=PALETTE.get("accent_cyan", "#3843a0"), bg=PALETTE["card_bg"])
4785
+ self.title_lbl = tk.Label(title_row, text=get_text("title", self.lang), font=("Segoe UI", 12, "bold"), fg=PALETTE.get("accent_cyan", "#3843a0"), bg=PALETTE["card_bg"])
4882
4786
  self.title_lbl.pack(side=tk.LEFT)
4883
4787
 
4884
4788
  self.status_dot = GlowingStatusDot(title_row)
@@ -4973,7 +4877,7 @@ class AutoReadmeGUI:
4973
4877
 
4974
4878
  self.star_header_btn = CanvasPillButton(
4975
4879
  header_controls,
4976
- text=f"★ STAR ({self.community_stats['stars']}★)",
4880
+ text="★ STAR ON GITHUB",
4977
4881
  command=self.open_star_action,
4978
4882
  height=28,
4979
4883
  radius=14,
@@ -4986,7 +4890,7 @@ class AutoReadmeGUI:
4986
4890
 
4987
4891
  # 3. MAIN CONTENT FRAME
4988
4892
  self.content = tk.Frame(self.bg_canvas, bg=PALETTE["bg_start"], bd=0)
4989
- self.content.place(x=82, y=62, relwidth=1.0, width=-92, relheight=1.0, height=-94)
4893
+ self.content.place(x=82, y=68, relwidth=1.0, width=-92, relheight=1.0, height=-100)
4990
4894
 
4991
4895
  self.tab_frames = [tk.Frame(self.content, bg=PALETTE["bg_start"]) for _ in range(7)]
4992
4896
  self.setup_tab_setup()
@@ -5004,9 +4908,14 @@ class AutoReadmeGUI:
5004
4908
  s_pill_bot = tk.Frame(self.status_bar, bg=PALETTE["card_bg"], highlightthickness=1, highlightbackground=PALETTE["card_border"])
5005
4909
  s_pill_bot.pack(side=tk.LEFT, fill=tk.X, expand=True)
5006
4910
 
5007
- tk.Label(s_pill_bot, text="📋 SYSTEM LOG:", font=("Segoe UI", 7, "bold"), fg=PALETTE["text_muted"], bg=PALETTE["card_bg"]).pack(side=tk.LEFT, padx=(8, 4), pady=2)
5008
- self.status_bar_lbl = tk.Label(s_pill_bot, text="[ONLINE] Siber Akademi T-Zero Context builder loaded.", font=("Consolas", 7), fg=PALETTE.get("accent_cyan", "#3843a0"), bg=PALETTE["card_bg"])
4911
+ tk.Label(s_pill_bot, text="STATUS", font=("Segoe UI", 7, "bold"), fg=PALETTE["text_muted"], bg=PALETTE["card_bg"]).pack(side=tk.LEFT, padx=(8, 4), pady=2)
4912
+ self.status_bar_lbl = tk.Label(s_pill_bot, text="Ready", font=("Segoe UI", 9), fg=PALETTE.get("accent_cyan", "#3843a0"), bg=PALETTE["card_bg"])
5009
4913
  self.status_bar_lbl.pack(side=tk.LEFT, pady=2)
4914
+ self.status_hint_lbl = tk.Label(
4915
+ s_pill_bot, bg=PALETTE["card_bg"], fg=PALETTE["text_muted"],
4916
+ font=("Segoe UI", 8), anchor="e",
4917
+ )
4918
+ self.status_hint_lbl.pack(side=tk.LEFT, fill=tk.X, expand=True, padx=8)
5010
4919
 
5011
4920
  self.status_toggle_lbl = tk.Label(s_pill_bot, text="▲ Show Console", font=("Segoe UI", 7, "bold"), fg=PALETTE.get("accent_purple", "#6366f1"), bg=PALETTE["card_bg"], cursor="hand2")
5012
4921
  self.status_toggle_lbl.pack(side=tk.RIGHT, padx=8, pady=2)
@@ -5079,38 +4988,65 @@ class AutoReadmeGUI:
5079
4988
  self.show_toast(f"Sound effects {'enabled' if SFX_ENABLED else 'disabled'}", "info")
5080
4989
 
5081
4990
  def show_toast(self, message: str, kind: str = "info", duration_ms: int = 2500):
5082
- try:
5083
- border_col = PALETTE["success"] if kind == "success" else (PALETTE["error"] if kind == "error" else PALETTE["accent_cyan"])
5084
- toast = tk.Frame(self.bg_canvas, bg=PALETTE["card_bg"], highlightthickness=1, highlightbackground=border_col, bd=0)
5085
- icon = "✔" if kind == "success" else ("⚠" if kind == "error" else "✦")
5086
-
5087
- tk.Label(toast, text=icon, font=("Segoe UI", 11, "bold"), fg=border_col, bg=PALETTE["card_bg"]).pack(side=tk.LEFT, padx=(12, 6), pady=6)
5088
- tk.Label(toast, text=message, font=("Segoe UI", 9, "bold"), fg=PALETTE["text_main"], bg=PALETTE["card_bg"]).pack(side=tk.LEFT, padx=(0, 16), pady=6)
5089
- toast.place(relx=0.68, rely=0.79, relwidth=0.30, height=38)
5090
-
5091
- def fade():
5092
- try:
5093
- toast.destroy()
5094
- except Exception:
5095
- pass
5096
- self.root.after(duration_ms, fade)
5097
- except Exception:
5098
- pass
4991
+ """Show one status message inside the application."""
4992
+ if not hasattr(self, "status_bar_lbl"):
4993
+ return
4994
+ label = self.status_bar_lbl
4995
+ previous = getattr(self, "_status_reset", None)
4996
+ if previous:
4997
+ self.root.after_cancel(previous)
4998
+ color = {"success": PALETTE["success"], "error": PALETTE["error"],
4999
+ "warning": PALETTE["accent_coral"]}.get(kind, PALETTE["text_main"])
5000
+ label.configure(text=message.splitlines()[0] if message else "", fg=color)
5001
+
5002
+ def reset():
5003
+ self._status_reset = None
5004
+ if label.winfo_exists():
5005
+ label.configure(text="Ready", fg=PALETTE["text_main"])
5006
+ self._status_reset = self.root.after(duration_ms, reset)
5007
+
5008
+ def _show_info(self, title, message, **kwargs):
5009
+ self._show_notice(title, message, "info")
5010
+
5011
+ def _show_warning(self, title, message, **kwargs):
5012
+ self._show_notice(title, message, "warning")
5013
+
5014
+ def _show_error(self, title, message, **kwargs):
5015
+ self._show_notice(title, message, "error")
5016
+
5017
+ def _show_notice(self, title, message, kind):
5018
+ self.show_toast(f"{title} · {message}", kind, 8000)
5019
+ if "\n" in str(message):
5020
+ self.log(f"{title}: {message}")
5099
5021
 
5100
5022
  def open_web_console(self):
5023
+ """Start a loopback-only server once and open its actual address."""
5101
5024
  play_sfx("click")
5102
5025
  try:
5103
- from tzero.tzero_dashboard import start_dashboard_server, DASHBOARD_PORT
5104
- if not getattr(self, "_web_server_started", False):
5105
- try:
5106
- threading.Thread(target=lambda: start_dashboard_server(DASHBOARD_PORT, open_browser=False), daemon=True).start()
5107
- self._web_server_started = True
5108
- except Exception:
5109
- pass
5110
- webbrowser.open(f"http://localhost:{DASHBOARD_PORT}")
5111
- self.show_toast("T-Zero Web Console & Superdesign opened", "success")
5112
- except Exception:
5113
- webbrowser.open("http://localhost:8421")
5026
+ server = getattr(self, "_web_server", None)
5027
+ if server is None:
5028
+ from tzero.tzero_dashboard import start_dashboard_server, DASHBOARD_PORT
5029
+ server = start_dashboard_server(DASHBOARD_PORT, open_browser=False)
5030
+ self._web_server = server
5031
+ threading.Thread(target=server.serve_forever, daemon=True).start()
5032
+
5033
+ def close_server(event):
5034
+ if event.widget is self.root and getattr(self, "_web_server", None) is server:
5035
+ self._web_server = None
5036
+ def shutdown():
5037
+ server.shutdown()
5038
+ server.server_close()
5039
+ threading.Thread(target=shutdown, daemon=True).start()
5040
+
5041
+ self.root.bind("<Destroy>", close_server, add="+")
5042
+ url = f"http://127.0.0.1:{server.server_address[1]}/"
5043
+ if webbrowser.open(url):
5044
+ self.show_toast("T-Zero Web Console opened", "success")
5045
+ else:
5046
+ self.show_toast(f"Open {url} in your browser", "info", 6000)
5047
+ except Exception as exc:
5048
+ self.log(f"Web Console could not start: {exc}")
5049
+ self.show_toast(f"Web Console could not start: {exc}", "error", 6000)
5114
5050
 
5115
5051
  def run_quick_security_audit(self):
5116
5052
  self.open_security_audit_dialog()
@@ -5123,6 +5059,20 @@ class AutoReadmeGUI:
5123
5059
  if not target or not os.path.exists(target):
5124
5060
  target = os.getcwd()
5125
5061
 
5062
+ self.show_toast("Scanning workspace for security findings...", "info")
5063
+
5064
+ def worker():
5065
+ try:
5066
+ result = self._collect_security_audit(target)
5067
+ self.safe_after(0, self._show_security_audit_results, target, result)
5068
+ except Exception as exc:
5069
+ message = str(exc)
5070
+ self.safe_after(0, lambda: self.show_toast(f"Security audit failed: {message}", "error", 6000))
5071
+
5072
+ threading.Thread(target=worker, daemon=True).start()
5073
+
5074
+ def _collect_security_audit(self, target):
5075
+ """Collect findings away from Tk's event loop."""
5126
5076
  key_patterns = [
5127
5077
  (re.compile(r"""(?i)(?:api_key|apikey|secret|password|auth_token)\s*=\s*['\"][A-Za-z0-9_\-\.]{16,}['\"]"""), "Hardcoded Secret / API Key"),
5128
5078
  (re.compile(r'sk-[a-zA-Z0-9]{20,}'), "OpenAI API Key Pattern"),
@@ -5202,13 +5152,19 @@ class AutoReadmeGUI:
5202
5152
  except Exception:
5203
5153
  pass
5204
5154
 
5155
+ return (audit_issues, py_files_count, total_scanned_files,
5156
+ total_lines_count, leaks_count, smells_count, arch_violations_count)
5157
+
5158
+ def _show_security_audit_results(self, target, result):
5159
+ (audit_issues, py_files_count, total_scanned_files, total_lines_count,
5160
+ leaks_count, smells_count, arch_violations_count) = result
5205
5161
  # Audio and status feedback
5206
5162
  if leaks_count > 0:
5207
5163
  play_sfx("error")
5208
5164
  self.show_toast(f"🚨 T-001 ALERT: {leaks_count} leak(s) detected!", "error", 5000)
5209
5165
  else:
5210
5166
  play_sfx("success")
5211
- self.show_toast(f"✅ 100% Zero-Leak Security Clean! ({total_scanned_files} files scanned)", "success", 4000)
5167
+ self.show_toast(f"No matching secret patterns found ({total_scanned_files} files scanned)", "success", 4000)
5212
5168
 
5213
5169
  self.log(f"T-Zero Security Audit: {total_scanned_files} files scanned, {leaks_count} secrets, {arch_violations_count} arch violations, {smells_count} AST smells.")
5214
5170
 
@@ -5449,8 +5405,6 @@ class AutoReadmeGUI:
5449
5405
  self.search_entry.insert(0, old_search)
5450
5406
  if self.has_scanned:
5451
5407
  self.rebuild_selector_tree()
5452
- if old_search:
5453
- self.filter_files_tree()
5454
5408
  if old_preview and self.tree.exists(old_preview):
5455
5409
  self.tree.selection_set(old_preview)
5456
5410
  self.on_file_select_changed(None)
@@ -5519,7 +5473,7 @@ class AutoReadmeGUI:
5519
5473
  if self.active_tab_index == 1 and self.scanned_files:
5520
5474
  self.search_entry.delete(0, tk.END)
5521
5475
  self.search_entry.insert(0, self.header_search_entry.get())
5522
- self.filter_files_tree()
5476
+ self._schedule_file_search()
5523
5477
 
5524
5478
  def open_global_search(self):
5525
5479
  self.header_search_entry.focus_set()
@@ -5900,10 +5854,10 @@ class AutoReadmeGUI:
5900
5854
  filepath = filedialog.asksaveasfilename(defaultextension=".dat", filetypes=[("Data Files", "*.dat")])
5901
5855
  if filepath:
5902
5856
  if KeyringSecretsBackupManager.backup_credentials(filepath, key):
5903
- messagebox.showinfo("Success", "Credentials backed up securely!")
5857
+ self._show_info("Success", "Credentials backed up securely!")
5904
5858
  dialog.destroy()
5905
5859
  else:
5906
- messagebox.showerror("Error", "Backup operation failed.")
5860
+ self._show_error("Error", "Backup operation failed.")
5907
5861
 
5908
5862
  def run_restore():
5909
5863
  key = key_entry.get().strip()
@@ -5912,10 +5866,10 @@ class AutoReadmeGUI:
5912
5866
  filepath = filedialog.askopenfilename(filetypes=[("Data Files", "*.dat")])
5913
5867
  if filepath:
5914
5868
  if KeyringSecretsBackupManager.restore_credentials(filepath, key):
5915
- messagebox.showinfo("Success", "Credentials restored securely!")
5869
+ self._show_info("Success", "Credentials restored securely!")
5916
5870
  dialog.destroy()
5917
5871
  else:
5918
- messagebox.showerror("Error", "Restore operation failed. Invalid key?")
5872
+ self._show_error("Error", "Restore operation failed. Invalid key?")
5919
5873
 
5920
5874
  btn_row = tk.Frame(pad, bg=PALETTE["bg_start"])
5921
5875
  btn_row.pack(fill=tk.X, pady=10)
@@ -5954,7 +5908,7 @@ class AutoReadmeGUI:
5954
5908
  self.log(f"Saved global scanner thread workers limit: {workers}, tokens limit: {tokens}")
5955
5909
  dialog.destroy()
5956
5910
  except ValueError:
5957
- messagebox.showerror("Error", "Values must be integer values!")
5911
+ self._show_error("Error", "Values must be integer values!")
5958
5912
 
5959
5913
  tk.Button(pad, text="Save configs", bg=PALETTE["success"], fg="#ffffff", relief=tk.FLAT, font=("Segoe UI", 9, "bold"), command=save).pack()
5960
5914
 
@@ -5998,7 +5952,7 @@ class AutoReadmeGUI:
5998
5952
  self.log(f"Cleared credentials for {provider} from keyring.")
5999
5953
  refresh_secrets_tree()
6000
5954
  except Exception as e:
6001
- messagebox.showerror("Error", f"Failed: {e}")
5955
+ self._show_error("Error", f"Failed: {e}")
6002
5956
 
6003
5957
  tk.Button(row, text="❌ Clear Selected Key", bg=PALETTE["card_border"], fg=PALETTE["error"], relief=tk.FLAT, font=("Segoe UI", 9, "bold"), command=delete_secret).pack(fill=tk.X)
6004
5958
 
@@ -6012,7 +5966,7 @@ class AutoReadmeGUI:
6012
5966
  profile["ignored_folders"] = preset["ignored"]
6013
5967
  _config_mgr.save()
6014
5968
  self.log(f"Applied scan layout preset parameters: {name}")
6015
- messagebox.showinfo("Success", f"Preset applied:\n{name}")
5969
+ self._show_info("Success", f"Preset applied:\n{name}")
6016
5970
 
6017
5971
  def import_profile_json(self):
6018
5972
  filepath = filedialog.askopenfilename(filetypes=[("JSON Files", "*.json")])
@@ -6026,9 +5980,9 @@ class AutoReadmeGUI:
6026
5980
  self.refresh_profile_listbox()
6027
5981
  self.load_saved_credentials()
6028
5982
  self.log(f"Imported settings profile from {filepath}")
6029
- messagebox.showinfo("Success", f"Successfully imported settings profile: {profile_name}")
5983
+ self._show_info("Success", f"Successfully imported settings profile: {profile_name}")
6030
5984
  else:
6031
- messagebox.showerror("Error", "Invalid profile structure!")
5985
+ self._show_error("Error", "Invalid profile structure!")
6032
5986
 
6033
5987
  def export_profile_json(self):
6034
5988
  filepath = filedialog.asksaveasfilename(defaultextension=".json", filetypes=[("JSON Files", "*.json")])
@@ -6037,9 +5991,9 @@ class AutoReadmeGUI:
6037
5991
  profile = _config_mgr.get_profile()
6038
5992
  if ProfileImporterExporter.export_profile(profile, filepath):
6039
5993
  self.log(f"Exported settings profile details: {filepath}")
6040
- messagebox.showinfo("Success", f"Profile exported successfully to:\n{filepath}")
5994
+ self._show_info("Success", f"Profile exported successfully to:\n{filepath}")
6041
5995
  else:
6042
- messagebox.showerror("Error", "Failed to export profile.")
5996
+ self._show_error("Error", "Failed to export profile.")
6043
5997
 
6044
5998
  def open_ignored_folders_dialog(self):
6045
5999
  dialog = tk.Toplevel(self.root)
@@ -6127,7 +6081,7 @@ class AutoReadmeGUI:
6127
6081
  return
6128
6082
  val = self.profile_listbox.get(sel[0]).replace(" [Active]", "").strip()
6129
6083
  if val == "default":
6130
- messagebox.showwarning("Warning", "Cannot delete the default profile.")
6084
+ self._show_warning("Warning", "Cannot delete the default profile.")
6131
6085
  return
6132
6086
  if _config_mgr.delete_profile(val):
6133
6087
  self.refresh_profile_listbox()
@@ -6184,7 +6138,7 @@ class AutoReadmeGUI:
6184
6138
  r_chat = requests.post(chat_url, json=chat_payload, headers=headers, timeout=8)
6185
6139
  if r_chat.status_code == 200:
6186
6140
  self.safe_after(0, lambda: self.status_dot.set_status("green"))
6187
- self.safe_after(0, lambda: messagebox.showinfo("Success", get_text("ping_success", self.lang)))
6141
+ self.safe_after(0, lambda: self._show_info("Success", get_text("ping_success", self.lang)))
6188
6142
  elif r_chat.status_code == 401:
6189
6143
  self.safe_after(0, lambda: self.status_dot.set_status("red"))
6190
6144
  warn_msg = (
@@ -6195,7 +6149,7 @@ class AutoReadmeGUI:
6195
6149
  f"3. Generate a new active API key at https://build.nvidia.com and enter it in the Settings tab.\n\n"
6196
6150
  f"⚡ With the T-Zero Local Offline AST Engine, full context generation works 100% free even without an API key!"
6197
6151
  )
6198
- self.safe_after(0, lambda: messagebox.showwarning("Authorization Error (401)", warn_msg))
6152
+ self.safe_after(0, lambda: self._show_warning("Authorization Error (401)", warn_msg))
6199
6153
  elif r_chat.status_code == 403:
6200
6154
  self.safe_after(0, lambda: self.status_dot.set_status("yellow"))
6201
6155
  warn_msg = (
@@ -6205,26 +6159,26 @@ class AutoReadmeGUI:
6205
6159
  f"1. Create a new API key at https://build.nvidia.com with 'Public API Endpoints' permission enabled.\n"
6206
6160
  f"2. Or run T-Zero in Local Offline AST Mode to synthesize 100% complete context without any API key!"
6207
6161
  )
6208
- self.safe_after(0, lambda: messagebox.showwarning("Partial Permission (403)", warn_msg))
6162
+ self.safe_after(0, lambda: self._show_warning("Partial Permission (403)", warn_msg))
6209
6163
  elif r_chat.status_code == 410:
6210
6164
  self.safe_after(0, lambda: self.status_dot.set_status("yellow"))
6211
- self.safe_after(0, lambda: messagebox.showwarning(
6165
+ self.safe_after(0, lambda: self._show_warning(
6212
6166
  "Model End of Life (410)",
6213
6167
  f"Model '{target_model}' has reached End of Life. Please select 'deepseek-ai/deepseek-v4.1-flash' from the dropdown."
6214
6168
  ))
6215
6169
  else:
6216
6170
  self.safe_after(0, lambda: self.status_dot.set_status("yellow"))
6217
- self.safe_after(0, lambda: messagebox.showwarning("API Response", f"Remote API status: {r_chat.status_code}\n{r_chat.text[:200]}"))
6171
+ self.safe_after(0, lambda: self._show_warning("API Response", f"Remote API status: {r_chat.status_code}\n{r_chat.text[:200]}"))
6218
6172
  except Exception:
6219
6173
  self.safe_after(0, lambda: self.status_dot.set_status("green"))
6220
- self.safe_after(0, lambda: messagebox.showinfo("Success", get_text("ping_success", self.lang)))
6174
+ self.safe_after(0, lambda: self._show_info("Success", get_text("ping_success", self.lang)))
6221
6175
  else:
6222
6176
  self.safe_after(0, lambda: self.status_dot.set_status("red"))
6223
- self.safe_after(0, lambda: messagebox.showerror("Failure", f"Code: {r.status_code}\n{r.text}"))
6177
+ self.safe_after(0, lambda: self._show_error("Failure", f"Code: {r.status_code}\n{r.text}"))
6224
6178
  except Exception as e:
6225
6179
  err_msg = str(e)
6226
6180
  self.safe_after(0, lambda: self.status_dot.set_status("red"))
6227
- self.safe_after(0, lambda msg=err_msg: messagebox.showerror("Exception", msg))
6181
+ self.safe_after(0, lambda msg=err_msg: self._show_error("Exception", msg))
6228
6182
  threading.Thread(target=run, daemon=True).start()
6229
6183
 
6230
6184
  def browse_dir(self):
@@ -6241,29 +6195,31 @@ class AutoReadmeGUI:
6241
6195
 
6242
6196
  def run_scanner(self):
6243
6197
  target = self.dir_entry.get().strip()
6244
- if not target or not os.path.exists(target):
6245
- messagebox.showerror("Error", "Workspace path does not exist!")
6198
+ if not os.path.isdir(target):
6199
+ self._show_error("Error", "Choose an existing workspace folder.")
6246
6200
  return
6247
6201
 
6202
+ if getattr(self, "_scan_running", False):
6203
+ return
6204
+ self._scan_running = True
6248
6205
  self.scan_btn.config(state=tk.DISABLED, text="Scanning...")
6249
6206
  self.log(f"Crawling directory signatures: {target}")
6250
6207
 
6251
- provider = self.provider_var.get()
6252
- key = self.api_key_entry.get().strip()
6253
- if key:
6254
- _config_mgr.set_credential(provider, key)
6255
-
6256
6208
  def run_thread():
6257
6209
  try:
6258
6210
  files, sizes, snippets = self.scanner.scan_directory(target)
6259
- self.safe_after(0, lambda: self.on_scan_finish(files, sizes, snippets))
6260
- except Exception as e:
6261
- err_msg = str(e)
6262
- self.safe_after(0, lambda msg=err_msg: messagebox.showerror("Error", msg))
6263
- self.safe_after(0, lambda: self.scan_btn.config(state=tk.NORMAL, text=get_text("scan_btn", self.lang)))
6211
+ self.safe_after(0, self.on_scan_finish, files, sizes, snippets)
6212
+ except Exception as exc:
6213
+ self.safe_after(0, self._on_scan_error, str(exc))
6264
6214
  threading.Thread(target=run_thread, daemon=True).start()
6265
6215
 
6216
+ def _on_scan_error(self, message):
6217
+ self._scan_running = False
6218
+ self.scan_btn.config(state=tk.NORMAL, text=get_text("scan_btn", self.lang))
6219
+ self._show_error("Workspace scan failed", message)
6220
+
6266
6221
  def on_scan_finish(self, files, sizes, snippets):
6222
+ self._scan_running = False
6267
6223
  self.has_scanned = True
6268
6224
  self.scanned_files = files
6269
6225
  self.file_sizes = sizes
@@ -6274,9 +6230,6 @@ class AutoReadmeGUI:
6274
6230
 
6275
6231
  self.rebuild_selector_tree()
6276
6232
  self.scan_btn.config(state=tk.NORMAL, text=get_text("scan_btn", self.lang))
6277
- if self.search_entry.get().strip():
6278
- self.filter_files_tree()
6279
-
6280
6233
  # Update live KPI chips & circular gauge from reference design
6281
6234
  total_tok = sum(len(v) for v in snippets.values()) // 4
6282
6235
  scanned_n = len(files)
@@ -6295,9 +6248,6 @@ class AutoReadmeGUI:
6295
6248
  executable_dir = os.path.dirname(sys.executable) if getattr(sys, "frozen", False) else None
6296
6249
  if not self.dir_entry.get().strip():
6297
6250
  self.dir_entry.insert(0, resolve_default_workspace(executable_dir=executable_dir))
6298
- target = self.dir_entry.get().strip()
6299
- if target and os.path.isdir(target) and not getattr(self, "has_scanned", False) and "unittest" not in sys.modules:
6300
- self.safe_after(250, self.run_scanner)
6301
6251
 
6302
6252
  def show_shortcuts_modal(self):
6303
6253
  dialog = tk.Toplevel(self.root)
@@ -6406,7 +6356,7 @@ class AutoReadmeGUI:
6406
6356
  self.root.clipboard_clear()
6407
6357
  self.root.clipboard_append(val)
6408
6358
  self.log(f"Copied to clipboard ({label}): {val}")
6409
- messagebox.showinfo("Copied", f"{label} address copied to clipboard:\n{val}")
6359
+ self._show_info("Copied", f"{label} address copied to clipboard:\n{val}")
6410
6360
  except Exception:
6411
6361
  pass
6412
6362
 
@@ -6708,7 +6658,7 @@ class AutoReadmeGUI:
6708
6658
  tk.Label(toolbar, text="🔍", font=("Segoe UI", 9, "bold"), fg=PALETTE["text_muted"], bg=PALETTE["card_bg"]).pack(side=tk.LEFT, padx=(8, 2))
6709
6659
  self.search_entry = apply_entry_focus_glow(tk.Entry(toolbar, bg=PALETTE["bg_start"], fg=PALETTE["text_main"], insertbackground="#ffffff", relief=tk.FLAT, width=15, highlightthickness=1, highlightbackground=PALETTE["card_border"]))
6710
6660
  self.search_entry.pack(side=tk.LEFT, ipady=3)
6711
- self.search_entry.bind("<KeyRelease>", self.filter_files_tree)
6661
+ self.search_entry.bind("<KeyRelease>", self._schedule_file_search)
6712
6662
 
6713
6663
  self.extensions_btn = apply_modern_hover(tk.Button(toolbar, text="🔍 Filters", bg=PALETTE["card_border"], fg=PALETTE["accent_cyan"], relief=tk.FLAT, font=("Segoe UI", 8, "bold"), command=self.open_extensions_filter_dialog, cursor="hand2"))
6714
6664
  self.extensions_btn.pack(side=tk.LEFT, padx=4)
@@ -6844,7 +6794,7 @@ class AutoReadmeGUI:
6844
6794
  except Exception as e:
6845
6795
  self.log(f"AST Refactor failed in {filepath}: {e}")
6846
6796
 
6847
- messagebox.showinfo("Success", f"AST refactored successfully in {modified_count} python files.")
6797
+ self._show_info("Success", f"AST refactored successfully in {modified_count} python files.")
6848
6798
  dialog.destroy()
6849
6799
  self.run_scanner()
6850
6800
 
@@ -7005,7 +6955,7 @@ class AutoReadmeGUI:
7005
6955
  try:
7006
6956
  rx = re.compile(pattern)
7007
6957
  except Exception as e:
7008
- messagebox.showerror("Error", f"Invalid regex: {e}")
6958
+ self._show_error("Error", f"Invalid regex: {e}")
7009
6959
  return
7010
6960
 
7011
6961
  selected_files = [f for f, v in self.file_checked.items() if v]
@@ -7051,7 +7001,7 @@ class AutoReadmeGUI:
7051
7001
  self.log(f"Replaced regex pattern in {filepath}")
7052
7002
  except Exception as e:
7053
7003
  self.log(f"Failed replacement in {filepath}: {e}")
7054
- messagebox.showinfo("Success", f"Replaced regex pattern successfully in {len(files_to_modify)} files.")
7004
+ self._show_info("Success", f"Replaced regex pattern successfully in {len(files_to_modify)} files.")
7055
7005
  dialog.destroy()
7056
7006
  self.run_scanner()
7057
7007
 
@@ -7112,39 +7062,17 @@ class AutoReadmeGUI:
7112
7062
  del_btn = tk.Button(pad, text="❌ Delete Selected", bg=PALETTE["card_border"], fg=PALETTE["error"], relief=tk.FLAT, font=("Segoe UI", 9, "bold"), command=delete, cursor="hand2")
7113
7063
  del_btn.pack(fill=tk.X, pady=(5, 0))
7114
7064
 
7065
+ def _schedule_file_search(self, event=None):
7066
+ pending = getattr(self, "_pending_file_search", None)
7067
+ if pending:
7068
+ self.root.after_cancel(pending)
7069
+ self._pending_file_search = self.root.after(150, self.filter_files_tree)
7070
+
7115
7071
  def filter_files_tree(self, event=None):
7116
- query = self.search_entry.get().strip().lower()
7117
- if not query:
7118
- self.rebuild_selector_tree()
7119
- return
7120
-
7121
- for item in self.tree.get_children():
7122
- self.tree.delete(item)
7123
-
7124
- inserted_dirs = {}
7125
- for filepath in self.scanned_files:
7126
- if query not in filepath.lower():
7127
- continue
7128
- parts = filepath.replace("\\", "/").split("/")
7129
- parent = ""
7130
- for i in range(len(parts) - 1):
7131
- dir_path = "/".join(parts[:i+1])
7132
- dir_name = parts[i]
7133
- if dir_path not in inserted_dirs:
7134
- display = f"☑ 📁 {dir_name}"
7135
- iid = self.tree.insert(parent, "end", iid=f"dir:{dir_path}", text=display, open=True)
7136
- inserted_dirs[dir_path] = iid
7137
- parent = inserted_dirs[dir_path]
7138
-
7139
- fname = parts[-1]
7140
- sz_kb = self.file_sizes.get(filepath, 0) / 1024
7141
- checked = self.file_checked.get(filepath, True)
7142
- glyph = "☑" if checked else "☐"
7143
- status_txt = "Included" if checked else "Excluded"
7144
-
7145
- self.tree.insert(parent, "end", iid=filepath, text=f"{glyph} 📄 {fname}", values=(f"{sz_kb:.1f} KB", status_txt))
7146
- self._update_tree_empty_state()
7147
- self.update_parent_states()
7072
+ if getattr(self, "_pending_file_search", None):
7073
+ self.root.after_cancel(self._pending_file_search)
7074
+ self._pending_file_search = None
7075
+ self.rebuild_selector_tree()
7148
7076
 
7149
7077
  def on_file_select_changed(self, event):
7150
7078
  selected_items = self.tree.selection()
@@ -7186,7 +7114,7 @@ class AutoReadmeGUI:
7186
7114
  with open(full_path, "w", encoding="utf-8") as f:
7187
7115
  f.write(content)
7188
7116
  self.log(f"Saved modified file changes directly: {self.active_preview_file}")
7189
- messagebox.showinfo("Saved", f"Successfully saved file edits:\n{self.active_preview_file}")
7117
+ self._show_info("Saved", f"Successfully saved file edits:\n{self.active_preview_file}")
7190
7118
 
7191
7119
  sz = os.path.getsize(full_path)
7192
7120
  self.file_sizes[self.active_preview_file] = sz
@@ -7197,7 +7125,7 @@ class AutoReadmeGUI:
7197
7125
 
7198
7126
  self.update_selector_stats()
7199
7127
  except Exception as e:
7200
- messagebox.showerror("Error", f"Failed to save file edits: {e}")
7128
+ self._show_error("Error", f"Failed to save file edits: {e}")
7201
7129
 
7202
7130
  def apply_smart_selection_heuristic(self):
7203
7131
  code_exts = {".py", ".js", ".ts", ".rs", ".go", ".cpp", ".c", ".h", ".jsx", ".tsx", ".sh", ".bat"}
@@ -7209,33 +7137,50 @@ class AutoReadmeGUI:
7209
7137
  self.file_checked[f] = False
7210
7138
 
7211
7139
  def rebuild_selector_tree(self):
7212
- for item in self.tree.get_children():
7213
- self.tree.delete(item)
7214
-
7215
- inserted_dirs = {}
7216
- for filepath in self.scanned_files:
7217
- parts = filepath.replace("\\", "/").split("/")
7218
- parent = ""
7219
- for i in range(len(parts) - 1):
7220
- dir_path = "/".join(parts[:i+1])
7221
- dir_name = parts[i]
7222
- if dir_path not in inserted_dirs:
7223
- display = f"☑ 📁 {dir_name}"
7224
- iid = self.tree.insert(parent, "end", iid=f"dir:{dir_path}", text=display, open=True)
7225
- inserted_dirs[dir_path] = iid
7226
- parent = inserted_dirs[dir_path]
7227
-
7228
- fname = parts[-1]
7229
- sz_kb = self.file_sizes.get(filepath, 0) / 1024
7230
- checked = self.file_checked.get(filepath, True)
7231
- glyph = "☑" if checked else "☐"
7232
- status_txt = "Included" if checked else "Excluded"
7233
-
7234
- self.tree.insert(parent, "end", iid=filepath, text=f"{glyph} 📄 {fname}", values=(f"{sz_kb:.1f} KB", status_txt))
7235
-
7236
- self._update_tree_empty_state()
7237
- self.update_selector_stats()
7238
- self.update_parent_states()
7140
+ tree = self.tree
7141
+ query = self.search_entry.get().strip().casefold()
7142
+ paths = [path for path in self.scanned_files if query in path.casefold()]
7143
+ remaining = iter(paths)
7144
+ self._selector_render = remaining
7145
+ selected = tree.selection()
7146
+ tree.delete(*tree.get_children())
7147
+ directories = {}
7148
+
7149
+ def insert_batch():
7150
+ if self._selector_render is not remaining or self.tree is not tree:
7151
+ return
7152
+
7153
+ for _ in range(200):
7154
+ filepath = next(remaining, None)
7155
+ if filepath is None:
7156
+ self._update_tree_empty_state()
7157
+ self.update_selector_stats()
7158
+ self.update_parent_states()
7159
+ if selected and tree.exists(selected[0]):
7160
+ tree.selection_set(selected[0])
7161
+ return
7162
+ parts = filepath.replace("\\", "/").split("/")
7163
+ parent = ""
7164
+ directory = ""
7165
+ for name in parts[:-1]:
7166
+ directory = f"{directory}/{name}" if directory else name
7167
+ if directory not in directories:
7168
+ directories[directory] = tree.insert(
7169
+ parent, "end", iid=f"dir:{directory}", text=f"☑ 📁 {name}", open=True,
7170
+ )
7171
+ parent = directories[directory]
7172
+
7173
+ size_kb = self.file_sizes.get(filepath, 0) / 1024
7174
+ checked = self.file_checked.get(filepath, True)
7175
+ glyph = "☑" if checked else "☐"
7176
+ status = "Included" if checked else "Excluded"
7177
+ tree.insert(parent, "end", iid=filepath, text=f"{glyph} 📄 {parts[-1]}",
7178
+ values=(f"{size_kb:.1f} KB", status))
7179
+
7180
+ self.tree_empty_lbl.place_forget()
7181
+ self.root.after(1, insert_batch)
7182
+
7183
+ insert_batch()
7239
7184
 
7240
7185
  def _update_tree_empty_state(self):
7241
7186
  if not hasattr(self, "tree_empty_lbl"):
@@ -7486,7 +7431,7 @@ class AutoReadmeGUI:
7486
7431
 
7487
7432
  def check_status():
7488
7433
  try:
7489
- res = subprocess.run(["git", "status", "--porcelain"], cwd=target, capture_output=True, text=True, timeout=5)
7434
+ res = _run_desktop_git(["git", "status", "--porcelain"], cwd=target, capture_output=True, text=True, timeout=5)
7490
7435
  lines = res.stdout.strip().splitlines()
7491
7436
  if lines and lines != [""]:
7492
7437
  status_lbl.config(text=f"Detected {len(lines)} uncommitted changes.")
@@ -7500,17 +7445,17 @@ class AutoReadmeGUI:
7500
7445
  def run_commit():
7501
7446
  msg = msg_entry.get().strip()
7502
7447
  if not msg:
7503
- messagebox.showwarning("Warning", "Commit message cannot be empty!")
7448
+ self._show_warning("Warning", "Commit message cannot be empty!")
7504
7449
  return
7505
7450
  try:
7506
- subprocess.run(["git", "add", "."], cwd=target, check=True)
7507
- res = subprocess.run(["git", "commit", "-m", msg], cwd=target, capture_output=True, text=True)
7451
+ _run_desktop_git(["git", "add", "."], cwd=target, check=True)
7452
+ res = _run_desktop_git(["git", "commit", "-m", msg], cwd=target, capture_output=True, text=True)
7508
7453
  self.log(res.stdout or res.stderr)
7509
- messagebox.showinfo("Success", "Successfully staged and committed workspace changes!")
7454
+ self._show_info("Success", "Successfully staged and committed workspace changes!")
7510
7455
  dialog.destroy()
7511
7456
  self.sync_git_commits()
7512
7457
  except Exception as e:
7513
- messagebox.showerror("Error", f"Failed to commit: {e}")
7458
+ self._show_error("Error", f"Failed to commit: {e}")
7514
7459
 
7515
7460
  btn_row = tk.Frame(pad, bg=PALETTE["bg_start"])
7516
7461
  btn_row.pack(fill=tk.X)
@@ -7539,12 +7484,12 @@ class AutoReadmeGUI:
7539
7484
  name = entry.get().strip()
7540
7485
  if name:
7541
7486
  try:
7542
- res = subprocess.run(["git", "checkout", "-b", name], cwd=target, capture_output=True, text=True, timeout=10)
7487
+ res = _run_desktop_git(["git", "checkout", "-b", name], cwd=target, capture_output=True, text=True, timeout=10)
7543
7488
  self.log(res.stdout or res.stderr)
7544
7489
  self.sync_git_commits()
7545
7490
  dialog.destroy()
7546
7491
  except Exception as e:
7547
- messagebox.showerror("Error", f"Failed to create branch: {e}")
7492
+ self._show_error("Error", f"Failed to create branch: {e}")
7548
7493
 
7549
7494
  tk.Button(pad, text="Create Branch", bg=PALETTE["success"], fg="#ffffff", relief=tk.FLAT, font=("Segoe UI", 9, "bold"), command=save).pack()
7550
7495
 
@@ -7568,7 +7513,7 @@ class AutoReadmeGUI:
7568
7513
  text.pack(fill=tk.BOTH, expand=True, pady=(0, 10))
7569
7514
 
7570
7515
  try:
7571
- res = subprocess.run(["git", "status", "--short"], cwd=target, capture_output=True, text=True, timeout=5)
7516
+ res = _run_desktop_git(["git", "status", "--short"], cwd=target, capture_output=True, text=True, timeout=5)
7572
7517
  text.insert(tk.END, res.stdout or "No modifications detected in status.")
7573
7518
  except Exception as e:
7574
7519
  text.insert(tk.END, f"Error: {e}")
@@ -7581,14 +7526,15 @@ class AutoReadmeGUI:
7581
7526
  if not target or not branch:
7582
7527
  return
7583
7528
 
7529
+ self.log(f"Switching to branch {branch}...")
7584
7530
  def checkout():
7585
- self.log(f"Executing branch switch checkout: git checkout {branch}...")
7586
7531
  try:
7587
- res = subprocess.run(["git", "checkout", branch], cwd=target, capture_output=True, text=True, timeout=10)
7588
- self.log(res.stdout or res.stderr)
7589
- self.sync_git_commits()
7590
- except Exception as e:
7591
- self.log(f"Branch switch exception: {e}")
7532
+ res = _run_desktop_git(["git", "checkout", branch], cwd=target, capture_output=True, text=True, timeout=10)
7533
+ self.safe_after(0, self.log, res.stdout or res.stderr)
7534
+ if res.returncode == 0:
7535
+ self.safe_after(0, self.sync_git_commits)
7536
+ except Exception as exc:
7537
+ self.safe_after(0, self.log, f"Branch switch failed: {exc}")
7592
7538
  threading.Thread(target=checkout, daemon=True).start()
7593
7539
 
7594
7540
  def sync_git_commits(self):
@@ -7604,7 +7550,7 @@ class AutoReadmeGUI:
7604
7550
 
7605
7551
  def load_branches():
7606
7552
  try:
7607
- res = subprocess.run(["git", "branch", "-a"], cwd=target, capture_output=True, text=True, timeout=5)
7553
+ res = _run_desktop_git(["git", "branch", "-a"], cwd=target, capture_output=True, text=True, timeout=5)
7608
7554
  branches = []
7609
7555
  active = ""
7610
7556
  for line in res.stdout.splitlines():
@@ -7613,9 +7559,9 @@ class AutoReadmeGUI:
7613
7559
  active = clean
7614
7560
  if clean:
7615
7561
  branches.append(clean)
7616
- self.root.after(0, lambda: self.branch_combo.config(values=branches))
7562
+ self.safe_after(0, lambda: self.branch_combo.config(values=branches))
7617
7563
  if active:
7618
- self.root.after(0, lambda: self.branch_combo.set(active))
7564
+ self.safe_after(0, lambda: self.branch_combo.set(active))
7619
7565
  except Exception:
7620
7566
  pass
7621
7567
  threading.Thread(target=load_branches, daemon=True).start()
@@ -7624,8 +7570,7 @@ class AutoReadmeGUI:
7624
7570
 
7625
7571
  def on_commits_loaded(commits):
7626
7572
  try:
7627
- if hasattr(self, "root") and self.root and self.root.winfo_exists():
7628
- self.root.after(0, lambda: self._render_commits_sync(commits))
7573
+ self.safe_after(0, self._render_commits_sync, commits)
7629
7574
  except Exception:
7630
7575
  pass
7631
7576
 
@@ -7674,7 +7619,7 @@ class AutoReadmeGUI:
7674
7619
  manager = CustomChangelogManager(target)
7675
7620
 
7676
7621
  def on_diff_loaded(diff_text):
7677
- self.root.after(0, lambda: self._render_diff_sync(diff_text))
7622
+ self.safe_after(0, self._render_diff_sync, diff_text)
7678
7623
 
7679
7624
  manager.get_git_diff_async(on_diff_loaded)
7680
7625
 
@@ -7798,7 +7743,7 @@ class AutoReadmeGUI:
7798
7743
  def run_local_dry_run(self):
7799
7744
  selected_files = [f for f, v in self.file_checked.items() if v]
7800
7745
  if not selected_files:
7801
- messagebox.showwarning("Warning", "Please select at least one file for dry-run!")
7746
+ self._show_warning("Warning", "Please select at least one file for dry-run!")
7802
7747
  return
7803
7748
 
7804
7749
  d = self.dir_entry.get().strip() or os.getcwd()
@@ -7821,12 +7766,12 @@ class AutoReadmeGUI:
7821
7766
  url = self.api_url_entry.get().strip()
7822
7767
  key = self.api_key_entry.get().strip()
7823
7768
  if not url:
7824
- messagebox.showerror("Error", "API Base URL is required!")
7769
+ self._show_error("Error", "API Base URL is required!")
7825
7770
  return
7826
7771
 
7827
7772
  selected_files = [f for f, v in self.file_checked.items() if v]
7828
7773
  if not selected_files:
7829
- messagebox.showwarning("Warning", "Please check at least one codebase file first!")
7774
+ self._show_warning("Warning", "Please check at least one codebase file first!")
7830
7775
  return
7831
7776
 
7832
7777
  self.cancel_event.clear()
@@ -7993,7 +7938,7 @@ Custom Requirements:
7993
7938
  detail += "\n\n💡 Tip: NVIDIA NIM API key authorization failed (403 Forbidden). Please generate a valid API key at https://build.nvidia.com and enter it under Settings > API Keys."
7994
7939
  elif "410" in err_str or "end of life" in err_str:
7995
7940
  detail += "\n\n💡 Tip: This model has reached End of Life. Please select the latest 'deepseek-ai/deepseek-v4.1-flash' model from the dropdown."
7996
- messagebox.showerror("Error", detail)
7941
+ self._show_error("Error", detail)
7997
7942
 
7998
7943
  def copy_clipboard(self):
7999
7944
  txt = self.preview_text.get("1.0", tk.END).strip()
@@ -8022,7 +7967,7 @@ Custom Requirements:
8022
7967
  self.log(f"README.md saved to: {p}")
8023
7968
  except Exception as e:
8024
7969
  play_sfx("error")
8025
- messagebox.showerror("Error", str(e))
7970
+ self._show_error("Error", str(e))
8026
7971
 
8027
7972
  def export_agents_md(self):
8028
7973
  play_sfx("click")
@@ -8051,7 +7996,7 @@ Custom Requirements:
8051
7996
  self.log(f"AGENTS.md blueprint exported: {out_path}")
8052
7997
  except Exception as e:
8053
7998
  play_sfx("error")
8054
- messagebox.showerror("Error", f"Failed saving AGENTS.md: {e}")
7999
+ self._show_error("Error", f"Failed saving AGENTS.md: {e}")
8055
8000
 
8056
8001
  def export_architecture_md(self):
8057
8002
  play_sfx("click")
@@ -8128,7 +8073,7 @@ Custom Requirements:
8128
8073
 
8129
8074
  def _on_arch_export_error(self, err_msg: str):
8130
8075
  play_sfx("error")
8131
- messagebox.showerror("Error", f"Failed saving ARCHITECTURE.md: {err_msg}")
8076
+ self._show_error("Error", f"Failed saving ARCHITECTURE.md: {err_msg}")
8132
8077
  self.gen_status_lbl.config(text="Architecture export failed.")
8133
8078
 
8134
8079
  def export_repo_map(self):
@@ -8162,7 +8107,7 @@ Custom Requirements:
8162
8107
  self.log(f"REPO_MAP.txt exported: {out_path}")
8163
8108
  except Exception as e:
8164
8109
  play_sfx("error")
8165
- messagebox.showerror("Error", f"Failed saving REPO_MAP.txt: {e}")
8110
+ self._show_error("Error", f"Failed saving REPO_MAP.txt: {e}")
8166
8111
 
8167
8112
  def export_html_preview(self):
8168
8113
  play_sfx("click")
@@ -8183,7 +8128,7 @@ Custom Requirements:
8183
8128
  webbrowser.open(os.path.abspath(out_path))
8184
8129
  except Exception as e:
8185
8130
  play_sfx("error")
8186
- messagebox.showerror("Error", f"Failed opening HTML preview: {e}")
8131
+ self._show_error("Error", f"Failed opening HTML preview: {e}")
8187
8132
 
8188
8133
  # --- TAB 5: PROMPT WORKBENCH PLAYGROUND ---
8189
8134
  def setup_tab_template(self):
@@ -8276,7 +8221,7 @@ Custom Requirements:
8276
8221
  def save_template(self):
8277
8222
  self.template_engine.template_content = self.tmpl_text.get("1.0", tk.END)
8278
8223
  self.log("Custom template layouts saved.")
8279
- messagebox.showinfo("Success", "Template updated successfully!")
8224
+ self._show_info("Success", "Template updated successfully!")
8280
8225
 
8281
8226
  def reset_template(self):
8282
8227
  self.tmpl_text.delete("1.0", tk.END)
@@ -8497,59 +8442,11 @@ Custom Requirements:
8497
8442
  file_node = self.ast_tree.insert("", "end", text=f"📄 {os.path.basename(filepath)} (AST Fail)")
8498
8443
 
8499
8444
  def start_system_telemetry(self):
8500
- def telemetry():
8501
- while True:
8502
- time.sleep(2)
8503
- cpu = random.uniform(5.0, 30.0)
8504
- mem = random.uniform(20.0, 45.0)
8505
- try:
8506
- self.root.after(0, lambda c=cpu, m=mem: self.perf_chart.update_values(c, m))
8507
- except Exception:
8508
- break
8509
- threading.Thread(target=telemetry, daemon=True).start()
8510
-
8511
- def _apply_live_community_stats(self, stats: Dict[str, Any]):
8512
- """Apply live GitHub star and registry download counts to header & open dialog."""
8513
- if not stats:
8514
- return
8515
- self.community_stats = stats
8516
- stars = int(stats.get("stars", 111))
8517
- target_stars = int(stats.get("target_stars", 250))
8518
- pct_ratio = max(0.05, min(1.0, stars / max(1, target_stars)))
8519
- pct_int = int(round(pct_ratio * 100))
8520
- dl_label = str(stats.get("downloads_label", "22,900+"))
8521
- saved_label = str(stats.get("saved_tokens_label", "1,120,000+"))
8522
-
8523
- try:
8524
- if hasattr(self, "star_header_btn") and self.star_header_btn.winfo_exists():
8525
- self.star_header_btn.set_text(f"★ STAR ({stars}★)")
8526
- except Exception:
8527
- pass
8528
-
8529
- w = getattr(self, "_star_dialog_widgets", {}) or {}
8530
- dlg = w.get("dialog")
8531
- try:
8532
- if dlg and dlg.winfo_exists():
8533
- if not w.get("first_launch"):
8534
- w["hdr_lbl"].config(text=f"⭐ {target_stars} STARS GOAL: JOIN THE COMMUNITY!")
8535
- w["stats_lbl"].config(
8536
- text=f"🚀 {dl_label} Downloads (PyPI & npm) | ⚡ {saved_label} Tokens Saved\n⭐ Current Stars: {stars} / {target_stars} Goal (Progress: {pct_int}%)"
8537
- )
8538
- w["bar_fill"].place_configure(relwidth=pct_ratio)
8539
- w["msg_lbl"].config(text=w["build_msg"](stars, target_stars))
8540
- except Exception:
8541
- pass
8542
-
8543
- def start_community_stats_refresh(self):
8544
- """Fetch live GitHub star count and download stats asynchronously without blocking UI."""
8545
- def _worker():
8546
- try:
8547
- from tzero.tzero_growth import get_live_community_stats
8548
- stats = get_live_community_stats(timeout=3.0, force_refresh=True, include_downloads=True)
8549
- self.safe_after(0, lambda s=stats: self._apply_live_community_stats(s))
8550
- except Exception:
8551
- pass
8552
- threading.Thread(target=_worker, daemon=True).start()
8445
+ def refresh():
8446
+ if self.perf_chart.winfo_viewable():
8447
+ self.perf_chart.update_values(random.uniform(5.0, 30.0), random.uniform(20.0, 45.0))
8448
+ self.root.after(2000, refresh)
8449
+ self.root.after(2000, refresh)
8553
8450
 
8554
8451
 
8555
8452
  # --- 14. STARTUP ORCHESTRATION & CLI WIZARD ---
@@ -9656,7 +9553,7 @@ def main():
9656
9553
  default="o200k_base", help="BPE encoding for --symbol-context")
9657
9554
  parser.add_argument("--cache-aligned", action="store_true", help="Order context for KV-cache prefix stability (immutable static prefix before dynamic query suffix)")
9658
9555
  parser.add_argument("--commit-msg", action="store_true", help="Generate Conventional Commit message from local AST git diff ($0 local engine)")
9659
- parser.add_argument("--changelog", nargs="?", const="v12.3.5", default=None, metavar="VERSION", help="Generate release CHANGELOG markdown from git history")
9556
+ parser.add_argument("--changelog", nargs="?", const="v12.3.6", default=None, metavar="VERSION", help="Generate release CHANGELOG markdown from git history")
9660
9557
  parser.add_argument("--ci", choices=["github", "gitlab", "pre-commit", "local", "all"], default=None, help="Install CI/CD workflow or run local verification suite")
9661
9558
  parser.add_argument("--local-ci", action="store_true", help="Run comprehensive Local CI & Pre-Push verification battery ($0 quota burn)")
9662
9559
  parser.add_argument("--quick-ci", action="store_true", help="Run fast Local CI smoke checks in seconds")
@@ -9720,7 +9617,7 @@ def main():
9720
9617
  parser.add_argument("--card", "--badge", nargs="?", const="assets/tzero_badge_card.svg", default=None, metavar="FILE", help="Generate viral dark-mode SVG banner card and GitHub README badges")
9721
9618
  parser.add_argument("--showcase", nargs="?", const="tzero_showcase.html", default=None, metavar="FILE", help="Generate interactive split-screen HTML5 comparison showcase slider")
9722
9619
  parser.add_argument("--marketing", "--growth", action="store_true", help="Launch $0-budget viral growth engine and export campaign materials for Reddit, HN, X, and Product Hunt")
9723
- parser.add_argument("--version", "-v", action="version", version="T-Zero Context Architect v12.3.5 Master Edition (engine v4.1.0)")
9620
+ parser.add_argument("--version", "-v", action="version", version="T-Zero Context Architect v12.3.6 Master Edition (engine v4.1.0)")
9724
9621
 
9725
9622
 
9726
9623
  def print_master_tutorial():
@@ -9829,7 +9726,7 @@ If this open-source tool helped you, please consider giving us a ⭐ on GitHub:
9829
9726
  def print_quickstart_guide():
9830
9727
  print("""
9831
9728
  ================================================================================
9832
- ⚡ SİBER AKADEMİ — T-ZERO CONTEXT ARCHITECT & MCP v12.3.5 MASTER (engine v4.1.0)
9729
+ ⚡ SİBER AKADEMİ — T-ZERO CONTEXT ARCHITECT & MCP v12.3.6 MASTER (engine v4.1.0)
9833
9730
  ================================================================================
9834
9731
  🎯 %95'e Varan Token Tasarrufu & Otonom Yapay Zeka Mimari Bağlam Motoru
9835
9732
 
@@ -10785,7 +10682,7 @@ If this open-source tool helped you, please consider giving us a ⭐ on GitHub:
10785
10682
  if not os.path.exists(app_path):
10786
10683
  app_path = os.path.join(os.getcwd(), "huggingface-space", "app.py")
10787
10684
  print("\033[36m" + "=" * 80)
10788
- print("🤗 SİBER AKADEMİ — T-ZERO HUGGING FACE SPACE & GRADIO COCKPIT (v12.3.5)")
10685
+ print("🤗 SİBER AKADEMİ — T-ZERO HUGGING FACE SPACE & GRADIO COCKPIT (v12.3.6)")
10789
10686
  print("=" * 80 + "\033[0m")
10790
10687
  print("🌐 Official Live Space : https://huggingface.co/spaces/toprakke4/tzero-token-reducer")
10791
10688
  print(f"📁 Local Application : {app_path}")