codis 1.1.1__py3-none-any.whl

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.
Files changed (329) hide show
  1. codis-1.1.1.dist-info/METADATA +194 -0
  2. codis-1.1.1.dist-info/RECORD +329 -0
  3. codis-1.1.1.dist-info/WHEEL +5 -0
  4. codis-1.1.1.dist-info/entry_points.txt +5 -0
  5. codis-1.1.1.dist-info/licenses/LICENSE +21 -0
  6. codis-1.1.1.dist-info/top_level.txt +2 -0
  7. run.py +190 -0
  8. src/__init__.py +1 -0
  9. src/__main__.py +81 -0
  10. src/_app_build.py +1507 -0
  11. src/_app_editor.py +1274 -0
  12. src/_app_kui.py +825 -0
  13. src/_app_lsp.py +625 -0
  14. src/_app_recovery.py +189 -0
  15. src/_app_settings.py +1385 -0
  16. src/_app_tools.py +2471 -0
  17. src/_app_webpreview.py +126 -0
  18. src/_font_safety.py +127 -0
  19. src/_shells.py +172 -0
  20. src/app.py +1488 -0
  21. src/chat/__init__.py +1 -0
  22. src/chat/adapters/__init__.py +33 -0
  23. src/chat/adapters/base.py +209 -0
  24. src/chat/adapters/discord.py +190 -0
  25. src/chat/adapters/http.py +78 -0
  26. src/chat/adapters/irc.py +360 -0
  27. src/chat/adapters/matrix.py +219 -0
  28. src/chat/adapters/mattermost.py +178 -0
  29. src/chat/adapters/mqtt.py +165 -0
  30. src/chat/adapters/slack.py +204 -0
  31. src/chat/adapters/telegram.py +117 -0
  32. src/chat/adapters/ws.py +154 -0
  33. src/chat/adapters/xmpp.py +337 -0
  34. src/chat/history.py +76 -0
  35. src/chat/models.py +207 -0
  36. src/chat/probe.py +79 -0
  37. src/chat/session.py +446 -0
  38. src/chat/util.py +125 -0
  39. src/collab/__init__.py +1 -0
  40. src/collab/net.py +411 -0
  41. src/collab/ot.py +311 -0
  42. src/collab/session.py +141 -0
  43. src/collab/tk_adapter.py +134 -0
  44. src/config.py +335 -0
  45. src/constants.py +2552 -0
  46. src/dep_catalog.py +446 -0
  47. src/diff/__init__.py +1 -0
  48. src/diff/engine.py +247 -0
  49. src/dpi.py +30 -0
  50. src/editor/__init__.py +1 -0
  51. src/editor/_pane_lsp.py +2937 -0
  52. src/editor/_pane_utils.py +171 -0
  53. src/editor/autocomplete.py +607 -0
  54. src/editor/code_folding.py +836 -0
  55. src/editor/color_preview.py +382 -0
  56. src/editor/complexity_lens.py +281 -0
  57. src/editor/diff_pane.py +623 -0
  58. src/editor/file_watcher.py +144 -0
  59. src/editor/focus_block.py +236 -0
  60. src/editor/heatmap.py +141 -0
  61. src/editor/inlay_hints.py +366 -0
  62. src/editor/inline_blame.py +429 -0
  63. src/editor/kdocs.py +3376 -0
  64. src/editor/large_file.py +488 -0
  65. src/editor/ligatures.py +180 -0
  66. src/editor/line_numbers.py +598 -0
  67. src/editor/minimap.py +691 -0
  68. src/editor/multi_cursor.py +269 -0
  69. src/editor/pane.py +2082 -0
  70. src/editor/rhythm.py +206 -0
  71. src/editor/save_hooks.py +43 -0
  72. src/editor/smart_selection.py +425 -0
  73. src/editor/smart_tips.py +719 -0
  74. src/editor/snippets.py +411 -0
  75. src/editor/sticky_note_gutter.py +410 -0
  76. src/editor/sticky_scroll.py +385 -0
  77. src/editor/suggest.py +464 -0
  78. src/editor/text_transforms.py +310 -0
  79. src/editor/vim_mode.py +1074 -0
  80. src/events/__init__.py +84 -0
  81. src/events/bus.py +427 -0
  82. src/events/correlator.py +244 -0
  83. src/events/kinds.py +125 -0
  84. src/events/pipeline.py +264 -0
  85. src/events/stream.py +416 -0
  86. src/events/window.py +204 -0
  87. src/extcompat/__init__.py +19 -0
  88. src/extcompat/code/__init__.py +13 -0
  89. src/extcompat/code/consent.py +162 -0
  90. src/extcompat/code/host.py +353 -0
  91. src/extcompat/code/hosts/py_host.py +763 -0
  92. src/extcompat/code/locate.py +105 -0
  93. src/extcompat/code/manager.py +325 -0
  94. src/extcompat/code/permissions.py +154 -0
  95. src/extcompat/code/sandbox.py +60 -0
  96. src/extcompat/colors.py +131 -0
  97. src/extcompat/common.py +184 -0
  98. src/extcompat/cson.py +269 -0
  99. src/extcompat/formats/__init__.py +22 -0
  100. src/extcompat/formats/_tm.py +189 -0
  101. src/extcompat/formats/_util.py +31 -0
  102. src/extcompat/formats/base16.py +66 -0
  103. src/extcompat/formats/brackets.py +172 -0
  104. src/extcompat/formats/eclipse.py +193 -0
  105. src/extcompat/formats/emacs.py +361 -0
  106. src/extcompat/formats/geany.py +147 -0
  107. src/extcompat/formats/generic.py +184 -0
  108. src/extcompat/formats/gtksource.py +117 -0
  109. src/extcompat/formats/helix.py +91 -0
  110. src/extcompat/formats/jetbrains.py +343 -0
  111. src/extcompat/formats/kate.py +130 -0
  112. src/extcompat/formats/micro.py +131 -0
  113. src/extcompat/formats/nano.py +111 -0
  114. src/extcompat/formats/notepadpp.py +140 -0
  115. src/extcompat/formats/pulsar.py +165 -0
  116. src/extcompat/formats/pyides.py +163 -0
  117. src/extcompat/formats/sublime.py +340 -0
  118. src/extcompat/jsonc.py +65 -0
  119. src/extcompat/lessish.py +128 -0
  120. src/extcompat/manager.py +122 -0
  121. src/extcompat/market/__init__.py +63 -0
  122. src/extcompat/market/sources.py +211 -0
  123. src/extcompat/model.py +88 -0
  124. src/extcompat/net.py +228 -0
  125. src/extcompat/openvsx.py +63 -0
  126. src/extcompat/readers.py +362 -0
  127. src/extcompat/registry.py +73 -0
  128. src/extcompat/safexml.py +63 -0
  129. src/extcompat/sexp.py +187 -0
  130. src/extcompat/sources.py +105 -0
  131. src/extcompat/store.py +276 -0
  132. src/extcompat/textmate.py +214 -0
  133. src/extcompat/themes.py +487 -0
  134. src/extcompat/yamlite.py +294 -0
  135. src/fileio.py +94 -0
  136. src/fs_ops.py +106 -0
  137. src/i18n.py +233 -0
  138. src/ia/__init__.py +1 -0
  139. src/ia/actions.py +295 -0
  140. src/ia/approval_gate.py +672 -0
  141. src/ia/checkpoints.py +308 -0
  142. src/ia/context_builder.py +921 -0
  143. src/ia/dialdiff.py +408 -0
  144. src/ia/iaspace.py +2078 -0
  145. src/ia/pair.py +296 -0
  146. src/ia/providers.py +954 -0
  147. src/ia/session.py +335 -0
  148. src/ia/toolbox.py +2524 -0
  149. src/launcher_actions.py +204 -0
  150. src/lint/__init__.py +1 -0
  151. src/lint/manager.py +1058 -0
  152. src/locales/.translate_manifest.json +64170 -0
  153. src/locales/de.json +4936 -0
  154. src/locales/en.json +4936 -0
  155. src/locales/es.json +4936 -0
  156. src/locales/fr.json +4936 -0
  157. src/locales/it.json +4936 -0
  158. src/locales/ja.json +4936 -0
  159. src/locales/ko.json +4936 -0
  160. src/locales/nl.json +4936 -0
  161. src/locales/pl.json +4936 -0
  162. src/locales/pt-BR.json +4936 -0
  163. src/locales/ru.json +4936 -0
  164. src/locales/tr.json +4936 -0
  165. src/locales/uk.json +4936 -0
  166. src/locales/zh-CN.json +4936 -0
  167. src/lsp/__init__.py +26 -0
  168. src/lsp/client.py +2300 -0
  169. src/lsp/dap_client.py +480 -0
  170. src/lsp/edits.py +84 -0
  171. src/lsp/framing.py +73 -0
  172. src/lsp/protocol.py +931 -0
  173. src/main.py +260 -0
  174. src/memtrim.py +91 -0
  175. src/plugins/__init__.py +1 -0
  176. src/plugins/api.py +1761 -0
  177. src/plugins/loader.py +571 -0
  178. src/plugins/process_runner.py +519 -0
  179. src/plugins/registry.py +342 -0
  180. src/plugins/safety.py +367 -0
  181. src/plugins/startup.py +195 -0
  182. src/plugins/store.py +1178 -0
  183. src/proc_registry.py +278 -0
  184. src/pyexec.py +394 -0
  185. src/recovery.py +259 -0
  186. src/stall_trace.py +92 -0
  187. src/standalone.py +1070 -0
  188. src/startup_profile.py +35 -0
  189. src/syntax/__init__.py +1 -0
  190. src/syntax/highlighter.py +776 -0
  191. src/syntax/patterns.py +584 -0
  192. src/system_profile.py +430 -0
  193. src/terminal/backends.py +658 -0
  194. src/terminal/internal.py +346 -0
  195. src/terminal/keys.py +138 -0
  196. src/terminal/palette.py +67 -0
  197. src/terminal/session.py +283 -0
  198. src/terminal/shells.py +79 -0
  199. src/terminal/view.py +489 -0
  200. src/terminal/vt.py +870 -0
  201. src/textfmt.py +22 -0
  202. src/theme/__init__.py +1 -0
  203. src/theme/base.py +1281 -0
  204. src/theme/colors.py +49 -0
  205. src/theme/manager.py +602 -0
  206. src/theme/utils.py +312 -0
  207. src/toolbox.py +329 -0
  208. src/trash_core.py +531 -0
  209. src/ui/__init__.py +1 -0
  210. src/ui/_perf_utils.py +285 -0
  211. src/ui/_persistence_utils.py +93 -0
  212. src/ui/accessibility.py +843 -0
  213. src/ui/activity_bar.py +860 -0
  214. src/ui/app_embed.py +434 -0
  215. src/ui/archive_panel.py +608 -0
  216. src/ui/bookmarks.py +314 -0
  217. src/ui/breadcrumb.py +383 -0
  218. src/ui/calculator_panel.py +982 -0
  219. src/ui/calendar_panel.py +1218 -0
  220. src/ui/chat_panel.py +1271 -0
  221. src/ui/chat_profile_dialog.py +278 -0
  222. src/ui/chat_render.py +128 -0
  223. src/ui/clock_panel.py +810 -0
  224. src/ui/code_outline.py +364 -0
  225. src/ui/code_runner.py +729 -0
  226. src/ui/code_stats.py +546 -0
  227. src/ui/collab_panel.py +1009 -0
  228. src/ui/color_picker.py +547 -0
  229. src/ui/command_palette.py +452 -0
  230. src/ui/cursor_manager.py +750 -0
  231. src/ui/custom_keywords_panel.py +413 -0
  232. src/ui/debug_panel.py +1037 -0
  233. src/ui/dependency_graph.py +692 -0
  234. src/ui/diff_panel.py +381 -0
  235. src/ui/docs_panel.py +514 -0
  236. src/ui/doom_embed.py +349 -0
  237. src/ui/dropdown.py +321 -0
  238. src/ui/easter_eggs.py +979 -0
  239. src/ui/env_manager.py +666 -0
  240. src/ui/extcode_bridge.py +215 -0
  241. src/ui/extcode_dialogs.py +412 -0
  242. src/ui/extcompat_dialog.py +583 -0
  243. src/ui/file_timeline.py +319 -0
  244. src/ui/file_tree.py +1208 -0
  245. src/ui/find_in_files.py +1355 -0
  246. src/ui/flowchart_panel.py +727 -0
  247. src/ui/formatter_panel.py +490 -0
  248. src/ui/git_auth.py +763 -0
  249. src/ui/git_clone_dialog.py +487 -0
  250. src/ui/git_panel.py +1483 -0
  251. src/ui/grab_safe.py +84 -0
  252. src/ui/internal_python_dialog.py +98 -0
  253. src/ui/k_ui/__init__.py +1305 -0
  254. src/ui/k_ui/_bgrenderer.py +317 -0
  255. src/ui/k_ui/_colors.py +213 -0
  256. src/ui/k_ui/_dock.py +545 -0
  257. src/ui/k_ui/_easter.py +290 -0
  258. src/ui/k_ui/_engine.py +5448 -0
  259. src/ui/k_ui/_perf.py +333 -0
  260. src/ui/k_ui/_tkutil.py +7 -0
  261. src/ui/k_ui/_tooltip.py +365 -0
  262. src/ui/k_ui/_widgets.py +1204 -0
  263. src/ui/k_ui/_world.py +837 -0
  264. src/ui/key_remapper.py +856 -0
  265. src/ui/launcher.py +1252 -0
  266. src/ui/lazy_panel.py +73 -0
  267. src/ui/macro_recorder.py +610 -0
  268. src/ui/menu_bar.py +898 -0
  269. src/ui/output_panel.py +321 -0
  270. src/ui/paint_canvas.py +1000 -0
  271. src/ui/paint_engine.py +535 -0
  272. src/ui/paint_panel.py +888 -0
  273. src/ui/panel_detach.py +112 -0
  274. src/ui/performance_panel.py +861 -0
  275. src/ui/pip_manager.py +1758 -0
  276. src/ui/plugin_panel.py +1586 -0
  277. src/ui/pomodoro_panel.py +447 -0
  278. src/ui/problems.py +566 -0
  279. src/ui/process_manager.py +1657 -0
  280. src/ui/project_templates.py +775 -0
  281. src/ui/recovery_dialog.py +122 -0
  282. src/ui/regex_playground.py +304 -0
  283. src/ui/remote_adapters.py +1398 -0
  284. src/ui/remote_browser.py +1224 -0
  285. src/ui/remote_profile_dialog.py +342 -0
  286. src/ui/render_panel.py +1293 -0
  287. src/ui/rest_client.py +549 -0
  288. src/ui/scratchpad.py +548 -0
  289. src/ui/search_bar.py +1274 -0
  290. src/ui/settings_editor.py +3349 -0
  291. src/ui/settings_window.py +1554 -0
  292. src/ui/snippets_panel.py +597 -0
  293. src/ui/sql_studio.py +1815 -0
  294. src/ui/status_bar.py +438 -0
  295. src/ui/tab_bar.py +654 -0
  296. src/ui/task_manager.py +1773 -0
  297. src/ui/terminal.py +525 -0
  298. src/ui/theme_preview_panel.py +851 -0
  299. src/ui/thread_safe_tk.py +152 -0
  300. src/ui/time_tracker.py +574 -0
  301. src/ui/tkbind.py +43 -0
  302. src/ui/todo_panel.py +358 -0
  303. src/ui/toolbox_panels.py +658 -0
  304. src/ui/trash_manager.py +657 -0
  305. src/ui/ui_scale.py +294 -0
  306. src/ui/ux_enhancements.py +41 -0
  307. src/ui/web_preview.py +397 -0
  308. src/ui/webdev.py +630 -0
  309. src/ui/welcome.py +567 -0
  310. src/ui/window_embed.py +1500 -0
  311. src/ui/wizard.py +1550 -0
  312. src/ui/workspace_switcher.py +418 -0
  313. src/ui/workspace_trust.py +370 -0
  314. src/ui/zen_audio.py +354 -0
  315. src/ui/zen_media.py +2271 -0
  316. src/ui/zen_media_client.py +303 -0
  317. src/ui/zen_media_host.py +329 -0
  318. src/ui/zen_player.py +907 -0
  319. src/ui/zen_player_widgets.py +700 -0
  320. src/updater/__init__.py +11 -0
  321. src/updater/assets.py +145 -0
  322. src/updater/backup.py +101 -0
  323. src/updater/channel.py +221 -0
  324. src/updater/dialog.py +492 -0
  325. src/updater/integrity.py +111 -0
  326. src/updater/manager.py +727 -0
  327. src/updater/result.py +114 -0
  328. src/venv_runtime.py +531 -0
  329. src/workspace_state.py +25 -0
src/ia/iaspace.py ADDED
@@ -0,0 +1,2078 @@
1
+ """Codis IA - PainelIA: Assistente de IA com controle total sobre o workspace.
2
+
3
+ Funcionalidades
4
+ ---------------
5
+ * Seletor de provedor e modelo
6
+ * Contexto de código: arquivo ativo, seleção, trecho manual
7
+ * Ações rápidas via skills
8
+ * Aprovação granular de ações (read/write/exec/critical)
9
+ * Painel de aprovação bloqueante: IA pausa e aguarda decisão do usuário
10
+ * Modo agente: IA planeja e executa tarefas multi-passo autonomamente
11
+ * 38+ ferramentas (leitura, escrita, exec, git, init de projeto, install deps)
12
+ * Copiar resposta / inserir no editor com diálogo de diff
13
+ * Streaming com indicador de carregamento e cancelamento
14
+ * Configuração inline de provedores (chave, modelo, URL)
15
+ * Abrir aba de terminal diretamente da IA
16
+ """
17
+
18
+ from __future__ import annotations
19
+
20
+ import contextlib
21
+ import inspect
22
+ import json
23
+ import logging
24
+ import threading
25
+ import time
26
+ import tkinter as tk
27
+ from collections.abc import Callable
28
+ from pathlib import Path
29
+ from tkinter import filedialog, messagebox, simpledialog, ttk
30
+ from typing import Any
31
+
32
+ from src.constants import CONFIG_DIR, FONT_MONO, FONT_UI
33
+ from src.i18n import _t
34
+ from src.ia.actions import list_skills
35
+ from src.ia.approval_gate import (
36
+ ActionHistoryEntry,
37
+ ActionHistoryPanel,
38
+ ActionRisk,
39
+ ApprovalGate,
40
+ _ApprovalPanel,
41
+ classify_action,
42
+ )
43
+ from src.ia.context_builder import build_context_block
44
+ from src.ia.dialdiff import confirm_and_apply
45
+ from src.ia.pair import (
46
+ ContextSources,
47
+ EditTracker,
48
+ build_system_prompt,
49
+ resolve_mentions,
50
+ tools_for_mode,
51
+ )
52
+ from src.ia.providers import (
53
+ PROVIDERS,
54
+ WARNING_LOCAL_LIB,
55
+ BaseProvider,
56
+ LocalLibProvider,
57
+ OpenAICompatibleProvider,
58
+ create_provider,
59
+ )
60
+ from src.ia.session import MODES, ChatSession, SessionStore, estimate_tokens, middle_truncate
61
+ from src.ia.toolbox import (
62
+ TOOL_SCHEMA,
63
+ ToolExecutor,
64
+ extract_code_blocks,
65
+ )
66
+ from src.ui.grab_safe import safe_grab_set
67
+
68
+ logger = logging.getLogger("Codis.IA")
69
+
70
+ _SKILLS_ID_ORDER = [
71
+ "ask",
72
+ "generate",
73
+ "explain",
74
+ "fix",
75
+ "refactor",
76
+ "review",
77
+ "document",
78
+ "tests",
79
+ "optimize",
80
+ "translate",
81
+ "commit",
82
+ "security",
83
+ "sql",
84
+ "regex",
85
+ "architecture",
86
+ ]
87
+
88
+
89
+ def _get_quick_actions() -> list[tuple[str, str]]:
90
+ """Retorna lista de (chave_i18n, prefixo_de_prompt) para o seletor de ação rápida."""
91
+ skills_by_id = {s.id: s for s in list_skills()}
92
+ items: list[tuple[str, str]] = []
93
+ for sid in _SKILLS_ID_ORDER:
94
+ skill = skills_by_id.get(sid)
95
+ if skill:
96
+ items.append((skill.i18n_key, skill.prompt_prefix))
97
+ for skill in list_skills():
98
+ if skill.id not in _SKILLS_ID_ORDER:
99
+ items.append((skill.i18n_key, skill.prompt_prefix))
100
+ return items or [("ia.skill_ask", "")]
101
+
102
+
103
+ _CONTEXT_OPTIONS: list[tuple[str, str]] = [
104
+ ("ia.ctx_none", "none"),
105
+ ("ia.ctx_file", "file"),
106
+ ("ia.ctx_selection", "selection"),
107
+ ("ia.ctx_manual", "manual"),
108
+ ]
109
+
110
+ _DEFAULT_SYSTEM_PROMPT = (
111
+ "You are an expert software engineering assistant integrated into Codis IDE. "
112
+ "You have access to powerful tools to read, write, and execute code in the user's workspace. "
113
+ "\n\n"
114
+ "## Core Guidelines\n"
115
+ "- Always read the relevant code before suggesting changes\n"
116
+ "- Use apply_edit for surgical changes; use write_file only for new files or full rewrites\n"
117
+ "- Use patch_files when changing multiple files simultaneously\n"
118
+ "- Before running commands, explain what they do\n"
119
+ "- When asked to build a project from scratch, use init_project first, then scaffold the code\n"
120
+ "- Prefer incremental changes with clear checkpoints\n"
121
+ "- For any destructive action (delete, reset), confirm explicitly with the user\n"
122
+ "\n\n"
123
+ "## Tool Usage\n"
124
+ "- Use get_cursor_context when the user says 'here', 'this', 'at my cursor'\n"
125
+ "- Use get_project_summary when opening a new project\n"
126
+ "- Use read_file_tree to understand project structure\n"
127
+ "- Use check_dependency before installing to avoid duplicates\n"
128
+ "- Use preview_rename before any large refactor\n"
129
+ "- Use run_tests after making code changes\n"
130
+ "\n\n"
131
+ "## Agent Mode\n"
132
+ "When given a complex task, break it into steps, execute each step, and report progress. "
133
+ "Always verify each step succeeded before moving to the next."
134
+ )
135
+
136
+
137
+ class _MessageBubble(tk.Frame):
138
+ """Exibe uma mensagem do chat como bolha visual."""
139
+
140
+ def __init__(
141
+ self,
142
+ parent: tk.Widget,
143
+ tmgr: Any,
144
+ role: str,
145
+ content: str,
146
+ on_insert: Callable[[str], None] | None = None,
147
+ on_copy: Callable[[str], None] | None = None,
148
+ ) -> None:
149
+ """Cria a bolha com cabeçalho de role, corpo de texto e botões de ação.
150
+
151
+ Args:
152
+ role: 'user' ou 'assistant'.
153
+ content: Texto da mensagem.
154
+ on_insert: Callback para inserir código no editor ativo.
155
+ on_copy: Callback para copiar texto para o clipboard.
156
+ """
157
+ t = tmgr.theme
158
+ is_user = role == "user"
159
+ bg = getattr(t, "sel_bg", t.input_bg) if is_user else t.panel_bg
160
+ super().__init__(parent, bg=t.editor_bg, pady=3)
161
+ self._tmgr = tmgr
162
+ self._content = content
163
+
164
+ header = tk.Frame(self, bg=t.editor_bg)
165
+ header.pack(fill="x", padx=8)
166
+ icon = ">" if is_user else "[AI]"
167
+ label = _t("ia.you") if is_user else _t("ia.assistant")
168
+ tk.Label(
169
+ header,
170
+ text=f"{icon} {label}",
171
+ bg=t.editor_bg,
172
+ fg=t.fg_muted,
173
+ font=(FONT_UI, 8, "bold"),
174
+ ).pack(side="left")
175
+
176
+ if not is_user and on_copy:
177
+ btn = tk.Label(
178
+ header,
179
+ text=_t("ia.copy"),
180
+ bg=t.editor_bg,
181
+ fg=t.fg_muted,
182
+ font=(FONT_UI, 7),
183
+ cursor="hand2",
184
+ )
185
+ btn.pack(side="right", padx=2)
186
+ btn.bind("<Button-1>", lambda _: on_copy(self._content))
187
+
188
+ if not is_user and on_insert:
189
+ btn = tk.Label(
190
+ header,
191
+ text=_t("ia.insert"),
192
+ bg=t.editor_bg,
193
+ fg=t.fg_muted,
194
+ font=(FONT_UI, 7),
195
+ cursor="hand2",
196
+ )
197
+ btn.pack(side="right", padx=2)
198
+ btn.bind("<Button-1>", lambda _: on_insert(self._content))
199
+
200
+ body = tk.Frame(self, bg=bg, highlightthickness=1,
201
+ highlightbackground=t.border)
202
+ body.pack(fill="x", padx=8, pady=(2, 0))
203
+ txt = tk.Text(
204
+ body,
205
+ bg=bg,
206
+ fg=t.fg,
207
+ font=(FONT_MONO, 9),
208
+ relief="flat",
209
+ bd=0,
210
+ wrap="word",
211
+ state="normal",
212
+ highlightthickness=0,
213
+ padx=8,
214
+ pady=6,
215
+ cursor="arrow",
216
+ )
217
+ txt.insert("1.0", content)
218
+ txt.config(state="disabled", height=min(content.count("\n") + 2, 30))
219
+ txt.pack(fill="x")
220
+
221
+ def update_content(self, new_content: str) -> None:
222
+ """Substitui o texto exibido na bolha; usado durante streaming."""
223
+ self._content = new_content
224
+ for widget in self.winfo_children():
225
+ if isinstance(widget, tk.Frame):
226
+ for child in widget.winfo_children():
227
+ if isinstance(child, tk.Text):
228
+ child.config(state="normal")
229
+ child.delete("1.0", "end")
230
+ child.insert("1.0", new_content)
231
+ child.config(
232
+ height=min(new_content.count("\n") + 2, 30),
233
+ state="disabled",
234
+ )
235
+ return
236
+
237
+
238
+ class _ProviderConfigDialog(tk.Toplevel):
239
+ """Janela modal para configurar credenciais e parâmetros de um provedor."""
240
+
241
+ def __init__(
242
+ self,
243
+ parent: tk.Widget,
244
+ tmgr: Any,
245
+ provider_name: str,
246
+ current_cfg: dict[str, Any],
247
+ on_save: Callable[[dict[str, Any]], None],
248
+ ) -> None:
249
+ """Abre o diálogo modal de configuração de provedor e bloqueia até fechar.
250
+
251
+ Args:
252
+ provider_name: Nome do provedor exibido no título.
253
+ current_cfg: Configuração já persistida (pré-popula os campos).
254
+ on_save: Callback com dict de configuração ao salvar.
255
+ """
256
+ super().__init__(parent)
257
+ t = tmgr.theme
258
+ self._tmgr = tmgr
259
+ self._on_save = on_save
260
+ self._fields: dict[str, tk.StringVar] = {}
261
+
262
+ self.title(_t("ia.cfg_title", name=provider_name))
263
+ self.configure(bg=t.panel_bg)
264
+ self.resizable(False, False)
265
+ self.transient(parent)
266
+ safe_grab_set(self)
267
+
268
+ cls = next((c for c in PROVIDERS if c.name == provider_name), None)
269
+
270
+ tk.Label(
271
+ self,
272
+ text=f" {provider_name} ",
273
+ bg=t.panel_bg,
274
+ fg=t.fg,
275
+ font=(FONT_UI, 11, "bold"),
276
+ ).pack(anchor="w", padx=12, pady=(10, 2))
277
+ if cls:
278
+ tk.Label(
279
+ self,
280
+ text=cls.description,
281
+ bg=t.panel_bg,
282
+ fg=t.fg_muted,
283
+ font=(FONT_UI, 8),
284
+ wraplength=380,
285
+ justify="left",
286
+ ).pack(anchor="w", padx=12, pady=(0, 8))
287
+ tk.Frame(self, bg=t.border, height=1).pack(fill="x")
288
+
289
+ form = tk.Frame(self, bg=t.panel_bg, padx=12, pady=8)
290
+ form.pack(fill="x")
291
+
292
+ if cls == LocalLibProvider:
293
+ fields_def = [
294
+ ("caminho_modelo", "ia.cfg_gguf", "", False),
295
+ ("n_gpu_layers", "ia.cfg_gpu_layers", "0", False),
296
+ ("n_ctx", "ia.cfg_ctx", "4096", False),
297
+ ("max_tokens", "ia.cfg_max_gen", "2048", False),
298
+ ]
299
+ elif cls and "Ollama" in cls.name:
300
+ fields_def = [
301
+ ("url", "ia.cfg_url", "http://localhost:11434/api/chat", False),
302
+ ("modelo", "ia.cfg_model", "llama3", False),
303
+ ]
304
+ elif cls == OpenAICompatibleProvider:
305
+ fields_def = [
306
+ (
307
+ "url",
308
+ "ia.cfg_url",
309
+ "http://localhost:1234/v1/chat/completions",
310
+ False,
311
+ ),
312
+ ("chave_api", "ia.cfg_api_optional", "", False),
313
+ ("modelo", "ia.cfg_model_optional", "", False),
314
+ ("max_tokens", "ia.cfg_max_tokens", "4096", False),
315
+ ("sistema", "ia.cfg_system", _DEFAULT_SYSTEM_PROMPT, False),
316
+ ]
317
+ else:
318
+ fields_def = [
319
+ ("chave_api", "ia.cfg_api_key", "", True),
320
+ ("modelo", "ia.cfg_model", "", False),
321
+ ("max_tokens", "ia.cfg_max_tokens", "4096", False),
322
+ ("sistema", "ia.cfg_system", _DEFAULT_SYSTEM_PROMPT, False),
323
+ ]
324
+ if cls and "OpenAI" in cls.name:
325
+ fields_def.insert(
326
+ 1,
327
+ (
328
+ "url_base",
329
+ "ia.cfg_url_base",
330
+ "https://api.openai.com/v1/chat/completions",
331
+ False,
332
+ ),
333
+ )
334
+
335
+ for field_key, label_key, default_val, is_password in fields_def:
336
+ tk.Label(
337
+ form,
338
+ text=_t(label_key) + ":",
339
+ bg=t.panel_bg,
340
+ fg=t.fg,
341
+ font=(FONT_UI, 9),
342
+ anchor="w",
343
+ ).pack(anchor="w")
344
+ var = tk.StringVar(value=current_cfg.get(field_key, default_val))
345
+ self._fields[field_key] = var
346
+ entry = tk.Entry(
347
+ form,
348
+ textvariable=var,
349
+ show="*" if is_password else "",
350
+ bg=t.input_bg,
351
+ fg=t.fg,
352
+ insertbackground=t.cursor,
353
+ relief="flat",
354
+ bd=0,
355
+ width=46,
356
+ font=(FONT_MONO if is_password else FONT_UI, 9),
357
+ highlightthickness=1,
358
+ highlightbackground=t.border,
359
+ )
360
+ entry.pack(fill="x", pady=(0, 6))
361
+ if field_key == "caminho_modelo":
362
+
363
+ def _browse(v: tk.StringVar = var) -> None:
364
+ path = filedialog.askopenfilename(
365
+ title=_t("ia.cfg_browse_title"),
366
+ filetypes=[("GGUF", "*.gguf"), ("Todos", "*.*")],
367
+ parent=self,
368
+ )
369
+ if path:
370
+ v.set(path)
371
+
372
+ lbl = tk.Label(
373
+ form,
374
+ text=_t("ia.cfg_browse"),
375
+ bg=t.panel_bg,
376
+ fg=t.accent,
377
+ font=(FONT_UI, 8),
378
+ cursor="hand2",
379
+ )
380
+ lbl.pack(anchor="w", pady=(0, 6))
381
+ lbl.bind("<Button-1>", lambda _, b=_browse: b())
382
+
383
+ tk.Frame(self, bg=t.border, height=1).pack(fill="x")
384
+ btns = tk.Frame(self, bg=t.panel_bg, padx=12, pady=8)
385
+ btns.pack(fill="x")
386
+ tk.Button(
387
+ btns,
388
+ text=_t("ia.cfg_cancel"),
389
+ command=self.destroy,
390
+ bg=t.btn_bg,
391
+ fg=t.fg,
392
+ relief="flat",
393
+ padx=10,
394
+ pady=4,
395
+ font=(FONT_UI, 9),
396
+ cursor="hand2",
397
+ ).pack(side="right", padx=4)
398
+ tk.Button(
399
+ btns,
400
+ text=_t("ia.cfg_save"),
401
+ command=self._save,
402
+ bg=getattr(t, "accent", "#4fc3f7"),
403
+ fg="#ffffff",
404
+ relief="flat",
405
+ padx=10,
406
+ pady=4,
407
+ font=(FONT_UI, 9, "bold"),
408
+ cursor="hand2",
409
+ ).pack(side="right")
410
+
411
+ self.update_idletasks()
412
+ pw = parent.winfo_rootx() + parent.winfo_width() // 2
413
+ ph = parent.winfo_rooty() + parent.winfo_height() // 2
414
+ w, h = self.winfo_width(), self.winfo_height()
415
+ self.geometry(f"+{pw - w // 2}+{ph - h // 2}")
416
+ self.wait_window()
417
+
418
+ def _save(self) -> None:
419
+ """Coleta os valores dos campos, chama on_save e fecha o diálogo."""
420
+ self._on_save({k: v.get() for k, v in self._fields.items()})
421
+ self.destroy()
422
+
423
+
424
+ class _PermissionsPanel(tk.Toplevel):
425
+ """Diálogo modal de configuração de níveis de risco aprovados automaticamente pela IA."""
426
+
427
+ _RISK_KEY_MAP = {
428
+ ActionRisk.SAFE: ("ia.perm_safe_label", "ia.perm_safe_desc"),
429
+ ActionRisk.LOW: ("ia.perm_low_label", "ia.perm_low_desc"),
430
+ ActionRisk.MEDIUM: ("ia.perm_medium_label", "ia.perm_medium_desc"),
431
+ ActionRisk.HIGH: ("ia.perm_high_label", "ia.perm_high_desc"),
432
+ ActionRisk.CRITICAL: ("ia.perm_critical_label", "ia.perm_critical_desc"),
433
+ }
434
+
435
+ def __init__(
436
+ self,
437
+ parent: tk.Widget,
438
+ tmgr: Any,
439
+ auto_levels: set[ActionRisk],
440
+ on_save: Callable[[set[ActionRisk]], None],
441
+ ) -> None:
442
+ """Abre o diálogo modal de permissões e bloqueia até o usuário fechar.
443
+
444
+ Args:
445
+ auto_levels: Conjunto de ActionRisk aprovados automaticamente no momento.
446
+ on_save: Callback com o novo conjunto de níveis ao salvar.
447
+ """
448
+ super().__init__(parent)
449
+ t = tmgr.theme
450
+ self.title(_t("ia.perm_title"))
451
+ self.configure(bg=t.panel_bg)
452
+ self.resizable(False, False)
453
+ self.transient(parent)
454
+ safe_grab_set(self)
455
+
456
+ tk.Label(
457
+ self,
458
+ text=_t("ia.perm_heading"),
459
+ bg=t.panel_bg,
460
+ fg=t.fg,
461
+ font=(FONT_UI, 11, "bold"),
462
+ ).pack(anchor="w", padx=16, pady=(12, 4))
463
+ tk.Label(
464
+ self,
465
+ text=_t("ia.perm_subtitle"),
466
+ bg=t.panel_bg,
467
+ fg=t.fg_muted,
468
+ font=(FONT_UI, 8),
469
+ wraplength=380,
470
+ ).pack(anchor="w", padx=16, pady=(0, 8))
471
+
472
+ tk.Frame(self, bg=t.border, height=1).pack(fill="x")
473
+
474
+ self._vars: dict[ActionRisk, tk.BooleanVar] = {}
475
+ form = tk.Frame(self, bg=t.panel_bg, padx=16, pady=8)
476
+ form.pack(fill="x")
477
+ for risk, (label_key, desc_key) in self._RISK_KEY_MAP.items():
478
+ var = tk.BooleanVar(value=risk in auto_levels)
479
+ self._vars[risk] = var
480
+ row = tk.Frame(form, bg=t.panel_bg)
481
+ row.pack(fill="x", pady=3)
482
+ tk.Checkbutton(
483
+ row,
484
+ variable=var,
485
+ text=_t(label_key),
486
+ bg=t.panel_bg,
487
+ fg=t.fg,
488
+ activebackground=t.panel_bg,
489
+ selectcolor=t.sel_bg,
490
+ font=(FONT_UI, 9, "bold"),
491
+ cursor="hand2",
492
+ ).pack(anchor="w")
493
+ tk.Label(
494
+ row,
495
+ text=f" {_t(desc_key)}",
496
+ bg=t.panel_bg,
497
+ fg=t.fg_muted,
498
+ font=(FONT_UI, 8),
499
+ justify="left",
500
+ wraplength=360,
501
+ ).pack(anchor="w")
502
+
503
+ tk.Frame(self, bg=t.border, height=1).pack(fill="x")
504
+
505
+ preset_row = tk.Frame(self, bg=t.panel_bg, padx=16, pady=6)
506
+ preset_row.pack(fill="x")
507
+ tk.Label(
508
+ preset_row,
509
+ text=_t("ia.perm_preset"),
510
+ bg=t.panel_bg,
511
+ fg=t.fg_muted,
512
+ font=(FONT_UI, 8),
513
+ ).pack(side="left")
514
+
515
+ def _preset_readonly() -> None:
516
+ for risk, var in self._vars.items():
517
+ var.set(risk == ActionRisk.SAFE)
518
+
519
+ def _preset_trusted() -> None:
520
+ for risk, var in self._vars.items():
521
+ var.set(risk in (ActionRisk.SAFE,
522
+ ActionRisk.LOW, ActionRisk.MEDIUM))
523
+
524
+ def _preset_full_auto() -> None:
525
+ for _, var in self._vars.items():
526
+ var.set(True)
527
+
528
+ for key, fn in [
529
+ ("ia.perm_preset_readonly", _preset_readonly),
530
+ ("ia.perm_preset_trusted", _preset_trusted),
531
+ ("ia.perm_preset_full", _preset_full_auto),
532
+ ]:
533
+ tk.Button(
534
+ preset_row,
535
+ text=_t(key),
536
+ command=fn,
537
+ bg=t.btn_bg,
538
+ fg=t.fg,
539
+ relief="flat",
540
+ padx=6,
541
+ pady=2,
542
+ font=(FONT_UI, 8),
543
+ cursor="hand2",
544
+ ).pack(side="left", padx=3)
545
+
546
+ btns = tk.Frame(self, bg=t.panel_bg, padx=16, pady=8)
547
+ btns.pack(fill="x")
548
+ tk.Button(
549
+ btns,
550
+ text=_t("ia.perm_cancel"),
551
+ command=self.destroy,
552
+ bg=t.btn_bg,
553
+ fg=t.fg,
554
+ relief="flat",
555
+ padx=10,
556
+ pady=4,
557
+ font=(FONT_UI, 9),
558
+ cursor="hand2",
559
+ ).pack(side="right", padx=4)
560
+ tk.Button(
561
+ btns,
562
+ text=_t("ia.perm_save"),
563
+ command=self._save,
564
+ bg=getattr(t, "accent", "#4fc3f7"),
565
+ fg="#ffffff",
566
+ relief="flat",
567
+ padx=10,
568
+ pady=4,
569
+ font=(FONT_UI, 9, "bold"),
570
+ cursor="hand2",
571
+ ).pack(side="right")
572
+
573
+ self.update_idletasks()
574
+ pw = parent.winfo_rootx() + parent.winfo_width() // 2
575
+ ph = parent.winfo_rooty() + parent.winfo_height() // 2
576
+ self.geometry(
577
+ f"+{pw - self.winfo_width() // 2}+{ph - self.winfo_height() // 2}"
578
+ )
579
+ self._on_save = on_save
580
+ self.wait_window()
581
+
582
+ def _save(self) -> None:
583
+ """Coleta checkboxes marcados, chama on_save e fecha o diálogo."""
584
+ approved = {risk for risk, var in self._vars.items() if var.get()}
585
+ self._on_save(approved)
586
+ self.destroy()
587
+
588
+
589
+ class PainelIA(tk.Frame):
590
+ """
591
+ Painel lateral de assistente de IA integrado ao Codis.
592
+
593
+ Integra-se a barra de atividades via ActivityBar.
594
+ Suporta múltiplos provedores, aprovação granular de ações,
595
+ modo agente e 38+ ferramentas.
596
+
597
+ Uso:
598
+ painel = PainelIA(
599
+ parent,
600
+ tmgr = self._tmgr,
601
+ cfg = self._cfg,
602
+ get_editor = self._active_editor,
603
+ on_open_new_tab = self._criar_aba_com_texto,
604
+ get_workspace = lambda: self._workspace,
605
+ on_open_terminal = self._open_terminal_tab,
606
+ )
607
+ """
608
+
609
+ def __init__(
610
+ self,
611
+ parent: tk.Widget,
612
+ tmgr: Any,
613
+ cfg: Any,
614
+ get_editor: Callable[[], Any] | None = None,
615
+ on_open_new_tab: Callable[[str], None] | None = None,
616
+ get_workspace: Callable[[], Any] | None = None,
617
+ on_open_terminal: Callable[[str, str], None] | None = None,
618
+ get_open_editors: Callable[[], Any] | None = None,
619
+ ) -> None:
620
+ """Inicializa o painel de IA com todas as dependências e constrói a UI.
621
+
622
+ Args:
623
+ tmgr: ThemeManager.
624
+ cfg: ConfigManager para persistir preferências.
625
+ get_editor: Callable que retorna o editor ativo.
626
+ on_open_new_tab: Callback para abrir novo arquivo no editor.
627
+ get_workspace: Callable que retorna o path do workspace.
628
+ on_open_terminal: Callback para abrir aba no terminal integrado.
629
+ get_open_editors: Callable que retorna todos os editores abertos
630
+ (habilita @tabs, rastreio das suas edições e proteção de
631
+ alterações não salvas).
632
+ """
633
+ t = tmgr.theme
634
+ super().__init__(parent, bg=t.panel_bg)
635
+ self._tmgr = tmgr
636
+ self._cfg = cfg
637
+ self._get_editor = get_editor
638
+ self._on_new_tab = on_open_new_tab
639
+ self._get_workspace = get_workspace
640
+ self._get_open_editors = get_open_editors
641
+
642
+ _saved_mode = self._cfg.get("ia_mode", "edit")
643
+ self._mode = tk.StringVar(value=_saved_mode if _saved_mode in MODES else "edit")
644
+ self._store = SessionStore(CONFIG_DIR / "ia_sessions")
645
+ self._session = ChatSession(self._ws_key(), self._mode.get())
646
+ self._tracker = EditTracker()
647
+ self._turn_id = 0
648
+ self._turn_actions: list[str] = []
649
+ self._turn_editing = False
650
+ self._stream_shown = ""
651
+ self._provider: BaseProvider | None = None
652
+ self._provider_name = tk.StringVar()
653
+ self._generating = False
654
+ self._current_bubble: _MessageBubble | None = None
655
+ self._stream_buffer = ""
656
+ self._last_ai_text = ""
657
+ self._provider_cfgs: dict[str, dict[str, Any]
658
+ ] = self._load_provider_cfgs()
659
+ self._tools_enabled = tk.BooleanVar(value=True)
660
+
661
+ saved_auto: list[str] = self._cfg.get(
662
+ "ia_auto_approve_levels", ["SAFE"])
663
+ self._auto_approve_levels: set[ActionRisk] = {
664
+ ActionRisk[n] for n in saved_auto if n in ActionRisk.__members__
665
+ }
666
+
667
+ self._gate = ApprovalGate(
668
+ root=self,
669
+ tmgr=tmgr,
670
+ on_action_log=self._on_action_logged,
671
+ auto_approve_safe=True,
672
+ )
673
+
674
+ self._tool_executor = ToolExecutor(
675
+ get_editor=get_editor,
676
+ get_workspace=get_workspace or (lambda: None),
677
+ on_open_terminal=on_open_terminal,
678
+ get_root_widget=lambda: self,
679
+ get_open_editors=self._editors,
680
+ )
681
+ self._tool_executor.set_session(self._session.id)
682
+
683
+ self._build()
684
+ self._mode.trace_add("write", lambda *_: self._on_mode_change())
685
+ self._select_provider(self._provider_name.get())
686
+ self._update_meter()
687
+ self._update_undo_btn()
688
+
689
+ def _load_provider_cfgs(self) -> dict[str, dict[str, Any]]:
690
+ """Carrega as configurações de todos os providers a partir do arquivo de config."""
691
+ return self._cfg.get("ia_provedores_cfg", {})
692
+
693
+ def _save_provider_cfgs(self) -> None:
694
+ """Persiste as configurações de provedores no ConfigManager."""
695
+ self._cfg.set("ia_provedores_cfg", self._provider_cfgs)
696
+ self._cfg.save()
697
+
698
+ def _build(self) -> None:
699
+ """Constrói os widgets do painel de IA: cabeçalho, chat, entrada e controles."""
700
+ t = self._tmgr.theme
701
+
702
+ hdr = tk.Frame(self, bg=t.panel_bg, height=36)
703
+ hdr.pack(fill="x")
704
+ hdr.pack_propagate(False)
705
+ tk.Label(
706
+ hdr,
707
+ text=" " + _t("ia.panel_title"),
708
+ bg=t.panel_bg,
709
+ fg=getattr(t, "sidebar_header_fg", t.fg),
710
+ font=(FONT_UI, 9, "bold"),
711
+ ).pack(side="left", padx=4)
712
+
713
+ for text, cmd in [
714
+ (_t("ia.clear"), self._clear_chat),
715
+ ("💬", lambda: self._open_sessions_menu()),
716
+ ("+", self._new_session),
717
+ ]:
718
+ lbl = tk.Label(
719
+ hdr,
720
+ text=text,
721
+ bg=t.panel_bg,
722
+ fg=t.fg_muted,
723
+ font=(FONT_UI, 8),
724
+ cursor="hand2",
725
+ )
726
+ lbl.pack(side="right", padx=6)
727
+ lbl.bind("<Button-1>", lambda _, c=cmd: c())
728
+
729
+ perm_btn = tk.Label(
730
+ hdr,
731
+ text="🔐",
732
+ bg=t.panel_bg,
733
+ fg=t.fg_muted,
734
+ font=(FONT_UI, 10),
735
+ cursor="hand2",
736
+ )
737
+ perm_btn.pack(side="right", padx=2)
738
+ perm_btn.bind("<Button-1>", lambda _: self._open_permissions())
739
+
740
+ prov_row = tk.Frame(self, bg=t.panel_bg)
741
+ prov_row.pack(fill="x", padx=6, pady=(2, 0))
742
+ names = [cls.name for cls in PROVIDERS]
743
+ saved = self._cfg.get("ia_provedor", names[0])
744
+ self._provider_name.set(saved if saved in names else names[0])
745
+
746
+ self._combo_provider = tk.OptionMenu(
747
+ prov_row,
748
+ self._provider_name,
749
+ *names,
750
+ command=lambda _: self._select_provider(self._provider_name.get()),
751
+ )
752
+ self._combo_provider.config(
753
+ bg=t.input_bg,
754
+ fg=t.fg,
755
+ activebackground=t.sel_bg,
756
+ activeforeground=t.sel_fg,
757
+ highlightthickness=0,
758
+ relief="flat",
759
+ font=(FONT_UI, 9),
760
+ bd=0,
761
+ cursor="hand2",
762
+ )
763
+ self._combo_provider["menu"].config(
764
+ bg=t.input_bg,
765
+ fg=t.fg,
766
+ activebackground=t.sel_bg,
767
+ activeforeground=t.sel_fg,
768
+ font=(FONT_UI, 9),
769
+ bd=0,
770
+ relief="flat",
771
+ )
772
+ self._combo_provider.pack(
773
+ side="left", fill="x", expand=True, padx=(0, 4))
774
+
775
+ cfg_btn = tk.Label(
776
+ prov_row,
777
+ text="⚙",
778
+ bg=t.panel_bg,
779
+ fg=t.fg,
780
+ font=(FONT_UI, 11),
781
+ cursor="hand2",
782
+ )
783
+ cfg_btn.pack(side="right")
784
+ cfg_btn.bind("<Button-1>", lambda _: self._open_provider_config())
785
+
786
+ self._lbl_status = tk.Label(
787
+ self,
788
+ text="",
789
+ bg=t.panel_bg,
790
+ fg=t.fg_muted,
791
+ font=(FONT_UI, 7),
792
+ anchor="w",
793
+ )
794
+ self._lbl_status.pack(fill="x", padx=8, pady=(1, 0))
795
+
796
+ action_row = tk.Frame(self, bg=t.panel_bg)
797
+ action_row.pack(fill="x", padx=6, pady=(3, 0))
798
+ tk.Label(
799
+ action_row,
800
+ text=_t("ia.action"),
801
+ bg=t.panel_bg,
802
+ fg=t.fg_muted,
803
+ font=(FONT_UI, 8),
804
+ ).pack(side="left")
805
+ _qa = _get_quick_actions()
806
+ self._action_var = tk.StringVar(value=_t(_qa[0][0]) if _qa else "")
807
+ _qa_labels = [_t(key) for key, _ in _qa]
808
+ self._combo_action = tk.OptionMenu(
809
+ action_row, self._action_var, *(_qa_labels or [""])
810
+ )
811
+ self._combo_action.config(
812
+ bg=t.input_bg,
813
+ fg=t.fg,
814
+ activebackground=t.sel_bg,
815
+ activeforeground=t.sel_fg,
816
+ highlightthickness=0,
817
+ relief="flat",
818
+ font=(FONT_UI, 8),
819
+ bd=0,
820
+ cursor="hand2",
821
+ )
822
+ self._combo_action["menu"].config(
823
+ bg=t.input_bg,
824
+ fg=t.fg,
825
+ activebackground=t.sel_bg,
826
+ activeforeground=t.sel_fg,
827
+ font=(FONT_UI, 8),
828
+ bd=0,
829
+ relief="flat",
830
+ )
831
+ self._combo_action.pack(side="left", fill="x",
832
+ expand=True, padx=(4, 0))
833
+
834
+ ctx_row = tk.Frame(self, bg=t.panel_bg)
835
+ ctx_row.pack(fill="x", padx=6, pady=(3, 0))
836
+ tk.Label(
837
+ ctx_row,
838
+ text=_t("ia.context"),
839
+ bg=t.panel_bg,
840
+ fg=t.fg_muted,
841
+ font=(FONT_UI, 8),
842
+ ).pack(side="left")
843
+ self._ctx_var = tk.StringVar(value="none")
844
+ for label_key, value in _CONTEXT_OPTIONS:
845
+ rb = tk.Radiobutton(
846
+ ctx_row,
847
+ text=_t(label_key),
848
+ variable=self._ctx_var,
849
+ value=value,
850
+ bg=t.panel_bg,
851
+ fg=t.fg,
852
+ activebackground=t.panel_bg,
853
+ selectcolor=t.sel_bg,
854
+ font=(FONT_UI, 8),
855
+ cursor="hand2",
856
+ )
857
+ rb.pack(side="left", padx=3)
858
+
859
+ self._frame_manual_ctx = tk.Frame(self, bg=t.panel_bg)
860
+ tk.Label(
861
+ self._frame_manual_ctx,
862
+ text=_t("ia.ctx_manual_label"),
863
+ bg=t.panel_bg,
864
+ fg=t.fg_muted,
865
+ font=(FONT_UI, 8),
866
+ ).pack(anchor="w", padx=6)
867
+ self._txt_ctx = tk.Text(
868
+ self._frame_manual_ctx,
869
+ height=5,
870
+ bg=t.input_bg,
871
+ fg=t.fg,
872
+ insertbackground=t.cursor,
873
+ relief="flat",
874
+ font=(FONT_MONO, 8),
875
+ highlightthickness=1,
876
+ highlightbackground=t.border,
877
+ wrap="none",
878
+ )
879
+ self._txt_ctx.pack(fill="x", padx=6, pady=(0, 4))
880
+ self._ctx_var.trace_add("write", self._on_ctx_mode_change)
881
+
882
+ tk.Frame(self, bg=t.border, height=1).pack(fill="x", pady=(4, 0))
883
+
884
+ self._approval_panel = _ApprovalPanel(self, self._tmgr)
885
+ self._gate.attach_panel(self._approval_panel)
886
+
887
+ self._notebook = ttk.Notebook(self)
888
+ self._notebook.pack(fill="both", expand=True)
889
+
890
+ chat_outer = tk.Frame(self._notebook, bg=t.editor_bg)
891
+ self._notebook.add(chat_outer, text=_t(
892
+ "ia.tab_chat", default="💬 Chat"))
893
+
894
+ scrollbar = ttk.Scrollbar(chat_outer, orient="vertical")
895
+ scrollbar.pack(side="right", fill="y")
896
+ self._canvas = tk.Canvas(
897
+ chat_outer,
898
+ bg=t.editor_bg,
899
+ highlightthickness=0,
900
+ yscrollcommand=scrollbar.set,
901
+ )
902
+ self._canvas.pack(side="left", fill="both", expand=True)
903
+ scrollbar.config(command=self._canvas.yview)
904
+
905
+ self._chat_frame = tk.Frame(self._canvas, bg=t.editor_bg)
906
+ self._canvas_item = self._canvas.create_window(
907
+ (0, 0), window=self._chat_frame, anchor="nw"
908
+ )
909
+ self._chat_frame.bind("<Configure>", self._on_chat_configure)
910
+ self._canvas.bind("<Configure>", self._on_canvas_configure)
911
+ for evt in ("<MouseWheel>", "<Button-4>", "<Button-5>"):
912
+ self._canvas.bind(evt, self._on_scroll)
913
+
914
+ self._show_welcome()
915
+
916
+ self._history_panel = ActionHistoryPanel(self._notebook, self._tmgr)
917
+ self._notebook.add(
918
+ self._history_panel, text=_t("ia.tab_actions", default="📋 Ações")
919
+ )
920
+
921
+ self._frame_generating = tk.Frame(self, bg=t.panel_bg)
922
+ tk.Label(
923
+ self._frame_generating,
924
+ text=_t("ia.generating"),
925
+ bg=t.panel_bg,
926
+ fg=t.fg_muted,
927
+ font=(FONT_UI, 8),
928
+ ).pack(side="left", padx=8)
929
+ self._agent_lbl = tk.Label(
930
+ self._frame_generating,
931
+ text="",
932
+ bg=t.panel_bg,
933
+ fg=getattr(t, "accent", "#4fc3f7"),
934
+ font=(FONT_UI, 7, "italic"),
935
+ )
936
+ self._agent_lbl.pack(side="left")
937
+ cancel_btn = tk.Label(
938
+ self._frame_generating,
939
+ text=_t("ia.cancel"),
940
+ bg=t.panel_bg,
941
+ fg=getattr(t, "err_fg", "#f44336"),
942
+ font=(FONT_UI, 8),
943
+ cursor="hand2",
944
+ )
945
+ cancel_btn.pack(side="right", padx=8)
946
+ cancel_btn.bind("<Button-1>", lambda _: self._cancel())
947
+
948
+ tk.Frame(self, bg=t.border, height=1).pack(fill="x")
949
+
950
+ entry_outer = tk.Frame(
951
+ self, bg=t.input_bg, highlightthickness=1, highlightbackground=t.border
952
+ )
953
+ entry_outer.pack(fill="x", padx=6, pady=4)
954
+ self._entry = tk.Text(
955
+ entry_outer,
956
+ height=3,
957
+ bg=t.input_bg,
958
+ fg=t.fg,
959
+ insertbackground=t.cursor,
960
+ relief="flat",
961
+ bd=0,
962
+ font=(FONT_UI, 9),
963
+ wrap="word",
964
+ highlightthickness=0,
965
+ )
966
+ self._entry.pack(fill="x", padx=6, pady=4)
967
+ self._entry.bind("<Return>", self._on_enter)
968
+ self._entry.bind("<Shift-Return>", lambda _e: None)
969
+
970
+ btns_row = tk.Frame(self, bg=t.panel_bg)
971
+ btns_row.pack(fill="x", padx=6, pady=(0, 6))
972
+
973
+ self._btn_send = tk.Label(
974
+ btns_row,
975
+ text=" " + _t("ia.send") + " ",
976
+ bg=getattr(t, "accent", "#4fc3f7"),
977
+ fg="#ffffff",
978
+ font=(FONT_UI, 9, "bold"),
979
+ cursor="hand2",
980
+ relief="flat",
981
+ )
982
+ self._btn_send.pack(side="right")
983
+ self._btn_send.bind("<Button-1>", lambda _: self._send())
984
+
985
+ self._btn_apply = tk.Label(
986
+ btns_row,
987
+ text=_t("ia.apply_code"),
988
+ bg=t.btn_bg,
989
+ fg=t.fg,
990
+ font=(FONT_UI, 8),
991
+ cursor="hand2",
992
+ relief="flat",
993
+ padx=6,
994
+ )
995
+ self._btn_apply.pack(side="right", padx=4)
996
+ self._btn_apply.bind("<Button-1>", lambda _: self._apply_last_code())
997
+
998
+ self._btn_undo = tk.Label(
999
+ btns_row, text=_t("ia.undo_ai", default="↶ Desfazer IA"), bg=t.btn_bg, fg=t.fg,
1000
+ font=(FONT_UI, 8), cursor="hand2", relief="flat", padx=6,
1001
+ )
1002
+ self._btn_undo.pack(side="left")
1003
+ self._btn_undo.bind("<Button-1>", lambda _: self._undo_last_ai())
1004
+ self._btn_regen = tk.Label(
1005
+ btns_row, text=_t("ia.regenerate", default="↻"), bg=t.btn_bg, fg=t.fg,
1006
+ font=(FONT_UI, 8), cursor="hand2", relief="flat", padx=6,
1007
+ )
1008
+ self._btn_regen.pack(side="left", padx=4)
1009
+ self._btn_regen.bind("<Button-1>", lambda _: self._regenerate())
1010
+ self._lbl_tokens = tk.Label(btns_row, text="", bg=t.panel_bg, fg=t.fg_muted, font=(FONT_UI, 7))
1011
+ self._lbl_tokens.pack(side="left", padx=4)
1012
+
1013
+ opts_row = tk.Frame(self, bg=t.panel_bg)
1014
+ opts_row.pack(fill="x", padx=6, pady=(0, 2))
1015
+
1016
+ tk.Checkbutton(
1017
+ opts_row,
1018
+ text=_t("ia.tools_toggle"),
1019
+ variable=self._tools_enabled,
1020
+ bg=t.panel_bg,
1021
+ fg=t.fg_muted,
1022
+ activebackground=t.panel_bg,
1023
+ selectcolor=t.sel_bg,
1024
+ font=(FONT_UI, 7),
1025
+ cursor="hand2",
1026
+ ).pack(side="left")
1027
+
1028
+ for _mval, _mkey, _mdef in (("ask", "ia.mode_ask", "Perguntar"),
1029
+ ("edit", "ia.mode_edit", "Editar"),
1030
+ ("agent", "ia.mode_agent", "Agente")):
1031
+ tk.Radiobutton(
1032
+ opts_row,
1033
+ text=_t(_mkey, default=_mdef),
1034
+ variable=self._mode,
1035
+ value=_mval,
1036
+ bg=t.panel_bg,
1037
+ fg=t.fg_muted,
1038
+ activebackground=t.panel_bg,
1039
+ selectcolor=t.sel_bg,
1040
+ font=(FONT_UI, 7),
1041
+ cursor="hand2",
1042
+ indicatoron=False,
1043
+ padx=5,
1044
+ ).pack(side="left", padx=1)
1045
+
1046
+ init_btn = tk.Label(
1047
+ opts_row,
1048
+ text=_t("ia.new_project_btn"),
1049
+ bg=t.btn_bg,
1050
+ fg=t.fg,
1051
+ font=(FONT_UI, 7),
1052
+ cursor="hand2",
1053
+ relief="flat",
1054
+ padx=4,
1055
+ )
1056
+ init_btn.pack(side="right")
1057
+ init_btn.bind(
1058
+ "<Button-1>", lambda _: self._start_init_project_dialog())
1059
+
1060
+ def _on_chat_configure(self, _event: Any = None) -> None:
1061
+ """Atualiza a scrollregion do canvas quando o frame interno muda de tamanho."""
1062
+ self._canvas.configure(scrollregion=self._canvas.bbox("all"))
1063
+
1064
+ def _on_canvas_configure(self, event: Any) -> None:
1065
+ """Ajusta a largura do chat_frame para preencher o canvas horizontalmente."""
1066
+ self._canvas.itemconfig(self._canvas_item, width=event.width)
1067
+
1068
+ def _on_scroll(self, event: tk.Event) -> None:
1069
+ """Trata eventos de scroll do mouse no canvas do chat (Linux e Windows/macOS)."""
1070
+ if event.num == 4:
1071
+ self._canvas.yview_scroll(-1, "units")
1072
+ elif event.num == 5:
1073
+ self._canvas.yview_scroll(1, "units")
1074
+ else:
1075
+ self._canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
1076
+
1077
+ def _on_ctx_mode_change(self, *_: Any) -> None:
1078
+ """Exibe ou oculta o campo de contexto manual conforme o modo selecionado."""
1079
+ if self._ctx_var.get() == "manual":
1080
+ self._frame_manual_ctx.pack(
1081
+ fill="x", after=self._combo_action.master)
1082
+ else:
1083
+ self._frame_manual_ctx.pack_forget()
1084
+
1085
+ def _select_provider(self, name: str) -> None:
1086
+ """Instancia o provedor `name`, persiste a escolha e atualiza o status."""
1087
+ self._cfg.set("ia_provedor", name)
1088
+ self._cfg.save()
1089
+ self._provider = create_provider(name)
1090
+ if self._provider:
1091
+ self._provider.configure(self._provider_cfgs.get(name, {}))
1092
+ self._update_status()
1093
+
1094
+ def _open_provider_config(self) -> None:
1095
+ """Abre o diálogo de configuração do provedor atualmente selecionado."""
1096
+ prov_name = self._provider_name.get()
1097
+ cls = next((c for c in PROVIDERS if c.name == prov_name), None)
1098
+ if (
1099
+ cls
1100
+ and cls == LocalLibProvider
1101
+ and not messagebox.askyesno(
1102
+ _t("ia.heavy_warning_title"), WARNING_LOCAL_LIB, parent=self
1103
+ )
1104
+ ):
1105
+ return
1106
+
1107
+ def _on_save(data: dict[str, Any]) -> None:
1108
+ self._provider_cfgs[prov_name] = data
1109
+ self._save_provider_cfgs()
1110
+ if self._provider:
1111
+ self._provider.configure(data)
1112
+ self._update_status()
1113
+
1114
+ _ProviderConfigDialog(
1115
+ self,
1116
+ self._tmgr,
1117
+ prov_name,
1118
+ self._provider_cfgs.get(prov_name, {}),
1119
+ _on_save,
1120
+ )
1121
+
1122
+ def _update_status(self) -> None:
1123
+ """Atualiza o label de status com o estado atual do provedor (pronto/erro)."""
1124
+ if not self._provider:
1125
+ self._lbl_status.config(
1126
+ text=_t("ia.status_unavailable"), fg="#f0a500")
1127
+ return
1128
+ error_msg = self._provider.check()
1129
+ if error_msg:
1130
+ self._lbl_status.config(
1131
+ text=_t("ia.status_error", error=error_msg), fg="#f0a500"
1132
+ )
1133
+ else:
1134
+ self._lbl_status.config(
1135
+ text=_t("ia.status_ready", name=self._provider.name),
1136
+ fg=getattr(self._tmgr.theme, "accent", "#4fc3f7"),
1137
+ )
1138
+
1139
+ def _open_permissions(self) -> None:
1140
+ """Abre o diálogo de configuração de permissões automáticas da IA."""
1141
+
1142
+ def _on_save(levels: set[ActionRisk]) -> None:
1143
+ self._auto_approve_levels = levels
1144
+ self._gate._auto_safe = ActionRisk.SAFE in levels
1145
+ self._cfg.set("ia_auto_approve_levels", [r.name for r in levels])
1146
+ self._cfg.save()
1147
+
1148
+ _PermissionsPanel(self, self._tmgr,
1149
+ self._auto_approve_levels, _on_save)
1150
+
1151
+ def _show_welcome(self) -> None:
1152
+ """Exibe mensagem de boas-vindas e dicas no chat vazio."""
1153
+ t = self._tmgr.theme
1154
+ tk.Label(
1155
+ self._chat_frame,
1156
+ text=_t("ia.welcome"),
1157
+ bg=t.editor_bg,
1158
+ fg=t.fg_muted,
1159
+ font=(FONT_UI, 9),
1160
+ justify="center",
1161
+ wraplength=280,
1162
+ ).pack(pady=20)
1163
+
1164
+ tips = [
1165
+ _t("ia.tip_agent"),
1166
+ "Novo Projeto cria um projeto do zero",
1167
+ _t("ia.tip_permissions"),
1168
+ _t("ia.tip_approval"),
1169
+ ]
1170
+ for tip in tips:
1171
+ tk.Label(
1172
+ self._chat_frame,
1173
+ text=tip,
1174
+ bg=t.editor_bg,
1175
+ fg=t.fg_muted,
1176
+ font=(FONT_UI, 8),
1177
+ justify="left",
1178
+ anchor="w",
1179
+ ).pack(fill="x", padx=16, pady=1)
1180
+
1181
+ def _clear_chat(self) -> None:
1182
+ """Apaga a conversa atual (inclusive do disco) e começa uma nova."""
1183
+ if self._generating:
1184
+ return
1185
+ self._store.delete(self._session.id)
1186
+ self._start_fresh_session()
1187
+
1188
+ def _on_enter(self, event: tk.Event) -> str:
1189
+ """Trata Enter (envia) e Shift+Enter (nova linha) no campo de entrada."""
1190
+ if not event.state & 0x1:
1191
+ self._send()
1192
+ return "break"
1193
+ return ""
1194
+
1195
+ def _ws_key(self) -> str | None:
1196
+ ws = self._get_workspace() if self._get_workspace else None
1197
+ return str(ws) if ws else None
1198
+
1199
+ def _budget(self) -> int:
1200
+ try:
1201
+ return max(4000, int(self._cfg.get("ia_context_tokens", 24000) or 24000))
1202
+ except (TypeError, ValueError):
1203
+ return 24000
1204
+
1205
+ def _editors(self) -> list[Any]:
1206
+ """Todos os editores abertos (ou só o ativo, se o app não informou a lista)."""
1207
+ try:
1208
+ if self._get_open_editors:
1209
+ return [e for e in self._get_open_editors() if e is not None]
1210
+ ed = self._get_editor() if self._get_editor else None
1211
+ return [ed] if ed is not None else []
1212
+ except Exception:
1213
+ logger.debug("listagem de editores falhou", exc_info=True)
1214
+ return []
1215
+
1216
+ def _open_buffers(self) -> dict[str, str]:
1217
+ """Conteúdo (inclusive não salvo) dos arquivos abertos, por caminho absoluto."""
1218
+ out: dict[str, str] = {}
1219
+ for ed in self._editors():
1220
+ p = getattr(ed, "path", None)
1221
+ if not p:
1222
+ continue
1223
+ try:
1224
+ txt = ed.text.get("1.0", "end-1c")
1225
+ if len(txt) <= 200_000:
1226
+ out[str(Path(p).resolve())] = txt
1227
+ except (tk.TclError, OSError, AttributeError):
1228
+ continue
1229
+ return out
1230
+
1231
+ def _make_sources(self) -> ContextSources:
1232
+ ws = self._get_workspace() if self._get_workspace else None
1233
+
1234
+ def active() -> tuple[Path | None, str, str] | None:
1235
+ ed = self._get_editor() if self._get_editor else None
1236
+ if ed is None:
1237
+ return None
1238
+ p = getattr(ed, "path", None)
1239
+ return (Path(p) if p else None, getattr(ed, "lang", ""), ed.text.get("1.0", "end-1c"))
1240
+
1241
+ def selection() -> tuple[Path | None, str, int] | None:
1242
+ ed = self._get_editor() if self._get_editor else None
1243
+ if ed is None:
1244
+ return None
1245
+ try:
1246
+ body = ed.text.get(tk.SEL_FIRST, tk.SEL_LAST)
1247
+ first = int(str(ed.text.index(tk.SEL_FIRST)).split(".")[0])
1248
+ except tk.TclError:
1249
+ return None
1250
+ p = getattr(ed, "path", None)
1251
+ return (Path(p) if p else None, body, first)
1252
+
1253
+ def tabs() -> list[tuple[Path | None, bool]]:
1254
+ return [(Path(e.path) if getattr(e, "path", None) else None, bool(getattr(e, "modified", False)))
1255
+ for e in self._editors()]
1256
+
1257
+ run = self._tool_executor.execute
1258
+ return ContextSources(
1259
+ workspace=lambda: Path(ws) if ws else None,
1260
+ active_file=active,
1261
+ selection=selection,
1262
+ open_tabs=tabs,
1263
+ diagnostics=lambda: run("read_diagnostics", {}),
1264
+ git_diff=lambda: run("read_git_diff", {}),
1265
+ file_tree=lambda: run("read_file_tree", {}),
1266
+ open_buffers=self._open_buffers,
1267
+ )
1268
+
1269
+ def _skill_prefix(self) -> str:
1270
+ action_label = self._action_var.get()
1271
+ return next((p for key, p in _get_quick_actions() if _t(key) == action_label), "")
1272
+
1273
+ def _build_attachment(self, user_text: str) -> tuple[str, list[str], list[str]]:
1274
+ """Contexto *fresco* desta mensagem: seletor de contexto + @menções + suas edições.
1275
+
1276
+ Retorna ``(anexo, nomes, avisos)``. Nada disso é repetido nos turnos seguintes.
1277
+ """
1278
+ budget = self._budget() // 2
1279
+ blocks: list[str] = []
1280
+ names: list[str] = []
1281
+ ctx_mode = self._ctx_var.get()
1282
+ ed = self._get_editor() if self._get_editor else None
1283
+ lang = getattr(ed, "lang", "") if ed else ""
1284
+ code, label = "", ""
1285
+ if ctx_mode == "file" and ed:
1286
+ code, label = ed.text.get("1.0", "end-1c"), _t("ia.ctx_file_name", default="arquivo ativo")
1287
+ elif ctx_mode == "selection" and ed:
1288
+ with contextlib.suppress(tk.TclError):
1289
+ code, label = ed.text.get(tk.SEL_FIRST, tk.SEL_LAST), _t("ia.ctx_sel_name", default="seleção")
1290
+ elif ctx_mode == "manual":
1291
+ code, label = self._txt_ctx.get("1.0", "end-1c").strip(), _t("ia.ctx_manual_name", default="trecho manual")
1292
+ elif ctx_mode == "none" and ed:
1293
+ with contextlib.suppress(tk.TclError, ValueError):
1294
+ row = int(str(ed.text.index("insert")).split(".")[0])
1295
+ lines = ed.text.get("1.0", "end-1c").splitlines()
1296
+ region = lines[max(0, row - 21): min(len(lines), row + 20)]
1297
+ if len(region) > 3:
1298
+ code, label = "\n".join(region), _t("ia.ctx_cursor_name", default="trecho ao redor do cursor")
1299
+ if code:
1300
+ blocks.append(f"### {label}\n```{lang}\n{middle_truncate(code, budget)}\n```")
1301
+ names.append(label)
1302
+
1303
+ res = resolve_mentions(user_text, self._make_sources(), budget_tokens=budget)
1304
+ if res.attachment:
1305
+ blocks.append(res.attachment)
1306
+ names += res.names
1307
+
1308
+ changes = self._tracker.changes_since(self._open_buffers())
1309
+ if changes:
1310
+ blocks.append(changes)
1311
+ names.append(_t("ia.ctx_user_edits", default="suas edições recentes"))
1312
+ return "\n\n".join(blocks), names, res.warnings
1313
+
1314
+ def _persist_session(self) -> None:
1315
+ with contextlib.suppress(OSError):
1316
+ self._store.save(self._session)
1317
+
1318
+ def _start_fresh_session(self) -> None:
1319
+ self._session = ChatSession(self._ws_key(), self._mode.get())
1320
+ self._tracker.reset()
1321
+ self._tool_executor.set_session(self._session.id)
1322
+ self._last_ai_text = ""
1323
+ self._render_session()
1324
+
1325
+ def _new_session(self) -> None:
1326
+ if self._generating:
1327
+ return
1328
+ self._persist_session()
1329
+ self._start_fresh_session()
1330
+
1331
+ def _render_session(self) -> None:
1332
+ """Redesenha o chat a partir da sessão atual."""
1333
+ for w in self._chat_frame.winfo_children():
1334
+ w.destroy()
1335
+ if not self._session.turns:
1336
+ self._show_welcome()
1337
+ for turn in self._session.turns:
1338
+ self._add_bubble(turn.role, turn.content)
1339
+ if turn.role == "assistant":
1340
+ self._last_ai_text = turn.content
1341
+ self._update_meter()
1342
+ self._update_undo_btn()
1343
+
1344
+ def _load_session(self, sid: str) -> None:
1345
+ if self._generating or sid == self._session.id:
1346
+ return
1347
+ loaded = self._store.load(sid)
1348
+ if loaded is None:
1349
+ return
1350
+ self._persist_session()
1351
+ self._session = loaded
1352
+ self._mode.set(loaded.mode if loaded.mode in MODES else self._mode.get())
1353
+ self._tracker.reset()
1354
+ self._tool_executor.set_session(loaded.id)
1355
+ self._render_session()
1356
+
1357
+ def _open_sessions_menu(self, event: Any = None) -> None:
1358
+ t = self._tmgr.theme
1359
+ menu = tk.Menu(self, tearoff=False, bg=t.input_bg, fg=t.fg, activebackground=t.sel_bg,
1360
+ activeforeground=t.sel_fg, relief="flat")
1361
+ self._persist_session()
1362
+ for info in self._store.list(self._ws_key())[:15]:
1363
+ when = time.strftime("%d/%m %H:%M", time.localtime(info.updated))
1364
+ mark = "● " if info.id == self._session.id else " "
1365
+ menu.add_command(label=f"{mark}{info.title[:42] or '…'} ({when})",
1366
+ command=lambda i=info.id: self._load_session(i))
1367
+ menu.add_separator()
1368
+ menu.add_command(label=_t("ia.session_rename", default="Renomear conversa…"), command=self._rename_session)
1369
+ menu.add_command(label=_t("ia.session_new", default="Nova conversa"), command=self._new_session)
1370
+ try:
1371
+ x, y = (event.x_root, event.y_root) if event is not None else (self.winfo_pointerx(), self.winfo_pointery())
1372
+ menu.tk_popup(x, y)
1373
+ finally:
1374
+ menu.grab_release()
1375
+
1376
+ def _rename_session(self) -> None:
1377
+ name = simpledialog.askstring(_t("ia.session_rename", default="Renomear conversa…"), "",
1378
+ initialvalue=self._session.title, parent=self)
1379
+ if name and name.strip():
1380
+ self._session.title = name.strip()[:80]
1381
+ self._persist_session()
1382
+
1383
+ def _on_mode_change(self) -> None:
1384
+ mode = self._mode.get()
1385
+ self._session.mode = mode
1386
+ self._cfg.set("ia_mode", mode)
1387
+ with contextlib.suppress(Exception):
1388
+ self._cfg.save()
1389
+
1390
+ def _update_meter(self) -> None:
1391
+ with contextlib.suppress(tk.TclError):
1392
+ tokens = self._session.messages_for_model(self._budget()).tokens
1393
+ self._lbl_tokens.config(text=f"≈ {tokens:,} / {self._budget():,} tok".replace(",", "."))
1394
+
1395
+ def _has_undo(self) -> bool:
1396
+ cps = self._tool_executor.checkpoints
1397
+ return bool(cps and any(not c.undone for c in cps.list()))
1398
+
1399
+ def _update_undo_btn(self) -> None:
1400
+ with contextlib.suppress(tk.TclError, AttributeError):
1401
+ self._btn_undo.config(fg=self._tmgr.theme.fg if self._has_undo() else self._tmgr.theme.fg_muted)
1402
+
1403
+ def _set_turn_buttons(self, enabled: bool) -> None:
1404
+ state_fg = self._tmgr.theme.fg if enabled else self._tmgr.theme.fg_muted
1405
+ with contextlib.suppress(tk.TclError):
1406
+ self._btn_regen.config(fg=state_fg)
1407
+ if enabled:
1408
+ self._update_undo_btn()
1409
+ else:
1410
+ self._btn_undo.config(fg=state_fg)
1411
+
1412
+ def _add_note(self, text: str) -> None:
1413
+ t = self._tmgr.theme
1414
+ tk.Label(self._chat_frame, text=text, bg=t.editor_bg, fg=t.fg_muted, font=(FONT_UI, 8, "italic"),
1415
+ anchor="w", justify="left", wraplength=300).pack(fill="x", padx=12, pady=1)
1416
+ self._canvas.update_idletasks()
1417
+ self._on_chat_configure()
1418
+ self._canvas.yview_moveto(1.0)
1419
+
1420
+ def _undo_last_ai(self) -> None:
1421
+ if self._generating or not self._has_undo():
1422
+ return
1423
+ rep = self._tool_executor.undo_turn()
1424
+ if rep is None:
1425
+ return
1426
+ if rep.conflicts and messagebox.askyesno(
1427
+ _t("ia.undo_ai", default="↶ Desfazer IA"),
1428
+ _t("ia.undo_conflict", default="Você editou estes arquivos depois da IA:\n\n{files}\n\n"
1429
+ "Desfazer mesmo assim e perder as suas alterações neles?",
1430
+ files="\n".join(Path(c).name for c in rep.conflicts[:10])),
1431
+ icon="warning", parent=self,
1432
+ ):
1433
+ rep2 = self._tool_executor.undo_turn(force=True)
1434
+ if rep2 is not None:
1435
+ rep = rep2
1436
+ self._add_note("↶ " + rep.summary())
1437
+ self._update_undo_btn()
1438
+
1439
+ def _send(self) -> None:
1440
+ """Valida a entrada e inicia um turno de conversa."""
1441
+ if self._generating:
1442
+ return
1443
+ user_text = self._entry.get("1.0", "end-1c").strip()
1444
+ if not user_text:
1445
+ return
1446
+ if not self._provider:
1447
+ messagebox.showwarning("IA", _t("ia.no_provider"), parent=self)
1448
+ return
1449
+
1450
+ if not self._cfg.get("ia_privacy_warning_shown", False):
1451
+ msg = (
1452
+ "⚠️ Aviso de Privacidade\n\n"
1453
+ f"Provedor atual: {self._provider.name}\n\n"
1454
+ "Não envie senhas, tokens, chaves de API ou dados pessoais sensíveis.\n\n"
1455
+ "Deseja continuar?"
1456
+ )
1457
+ if not messagebox.askyesno(_t("ia.privacy_warning_title"), msg, parent=self):
1458
+ return
1459
+ self._cfg.set("ia_privacy_warning_shown", True)
1460
+ self._cfg.save()
1461
+
1462
+ self._entry.delete("1.0", "end")
1463
+ attachment, names, warnings = self._build_attachment(user_text)
1464
+ sess = self._session
1465
+ sess.mode = self._mode.get()
1466
+ sess.provider = self._provider.name
1467
+ sess.model = str(getattr(self._provider, "_cfg", {}).get("modelo", ""))
1468
+ if not sess.title:
1469
+ sess.title = " ".join(user_text.split())[:60]
1470
+ sess.add_user(user_text, attachment=attachment, attached=names, lead=self._skill_prefix())
1471
+ self._add_bubble("user", user_text)
1472
+ if names:
1473
+ self._add_note("📎 " + ", ".join(names))
1474
+ for w in warnings:
1475
+ self._add_note("⚠ " + w)
1476
+ self._begin_generation(sess.mode)
1477
+
1478
+ @staticmethod
1479
+ def _summarize_action(name: str, args: dict[str, Any]) -> str:
1480
+ key = next((str(args[k]) for k in ("path", "command", "pattern", "query", "src", "name") if args.get(k)), "")
1481
+ if not key and args.get("patches"):
1482
+ key = ", ".join(str(p.get("path", "")) for p in args["patches"][:3] if isinstance(p, dict))
1483
+ return f"{name} {key[:60]}".strip()
1484
+
1485
+ _MAIN_THREAD_TOOLS = frozenset({"read_active_file", "get_cursor_context", "read_diagnostics", "read_symbols"})
1486
+
1487
+ def _call_on_main(self, fn: Callable[[], Any]) -> Any:
1488
+ """Executa *fn* na thread da UI e espera o resultado (chamado de threads de IA)."""
1489
+ if threading.current_thread() is threading.main_thread():
1490
+ return fn()
1491
+ box: dict[str, Any] = {}
1492
+ done = threading.Event()
1493
+
1494
+ def run() -> None:
1495
+ try:
1496
+ box["v"] = fn()
1497
+ except BaseException as exc:
1498
+ box["e"] = exc
1499
+ finally:
1500
+ done.set()
1501
+
1502
+ self.after(0, run)
1503
+ if not done.wait(timeout=30):
1504
+ return "[Erro] a interface não respondeu a tempo."
1505
+ if "e" in box:
1506
+ raise box["e"]
1507
+ return box.get("v")
1508
+
1509
+ def _run_tool(self, name: str, args: dict[str, Any]) -> str:
1510
+ if name in self._MAIN_THREAD_TOOLS:
1511
+ return self._call_on_main(lambda: self._tool_executor.execute(name, args))
1512
+ return self._tool_executor.execute(name, args)
1513
+
1514
+ def _send_to_provider(self, msgs: list[dict[str, str]], on_chunk: Callable, on_done: Callable,
1515
+ on_error: Callable, options: dict[str, Any]) -> None:
1516
+ """Envia com ``options`` por requisição (sem mexer na config compartilhada).
1517
+
1518
+ Provedores de plugin antigos, sem o parâmetro, recebem a config temporária
1519
+ e a restauração só acontece quando a resposta termina (nunca antes, o que
1520
+ causava perda aleatória de system prompt e ferramentas).
1521
+ """
1522
+ prov = self._provider
1523
+ assert prov is not None
1524
+ try:
1525
+ params = inspect.signature(prov.send).parameters
1526
+ except (TypeError, ValueError):
1527
+ params = {}
1528
+ if "options" in params or any(p.kind is inspect.Parameter.VAR_KEYWORD for p in params.values()):
1529
+ prov.send(msgs, on_chunk, on_done, on_error, options=options)
1530
+ return
1531
+ original = dict(getattr(prov, "_cfg", {}))
1532
+ prov.configure({**original, **options})
1533
+
1534
+ def restore_then(cb: Callable) -> Callable:
1535
+ def inner(*a: Any) -> None:
1536
+ prov.configure(original)
1537
+ cb(*a)
1538
+ return inner
1539
+
1540
+ prov.send(msgs, on_chunk, restore_then(on_done), restore_then(on_error))
1541
+
1542
+ def _begin_generation(self, mode: str) -> None:
1543
+ """Inicia a resposta da IA para a última mensagem do usuário da sessão."""
1544
+ sess = self._session
1545
+ self._turn_id += 1
1546
+ tid = self._turn_id
1547
+ self._turn_actions = []
1548
+ self._stream_buffer = ""
1549
+ self._stream_shown = ""
1550
+ self._current_bubble = self._add_bubble("assistant", "")
1551
+ self._generating = True
1552
+ self._frame_generating.pack(fill="x", before=self._notebook)
1553
+ self._agent_lbl.config(text=_t("ia.agent_label") if mode == "agent" else "")
1554
+ self._btn_send.config(state="disabled")
1555
+ self._set_turn_buttons(False)
1556
+ self._turn_editing = False
1557
+ try:
1558
+ tools = tools_for_mode(mode, TOOL_SCHEMA) if self._tools_enabled.get() else None
1559
+ self._turn_editing = bool(tools) and mode != "ask"
1560
+ if self._turn_editing:
1561
+ self._tool_executor.set_session(sess.id)
1562
+ self._tool_executor.begin_turn(sess.last_user_text() or "")
1563
+
1564
+ try:
1565
+ ws_key = self._ws_key()
1566
+ ctx_block = build_context_block(
1567
+ get_editor=self._get_editor,
1568
+ get_workspace=lambda: Path(ws_key) if ws_key else None,
1569
+ )
1570
+ except Exception:
1571
+ logger.debug("build_context_block falhou silenciosamente", exc_info=True)
1572
+ ctx_block = ""
1573
+ user_sys = str(getattr(self._provider, "_cfg", {}).get("sistema", ""))
1574
+ system = build_system_prompt(mode, user_system=user_sys, skill_prompt=self._get_action_system_prompt(),
1575
+ project_context=ctx_block)
1576
+ reserve = estimate_tokens(system) + (estimate_tokens(json.dumps(tools)) if tools else 0)
1577
+ view = sess.messages_for_model(self._budget(), reserve)
1578
+ if view.condensed_turns or view.truncated:
1579
+ self._add_note(_t("ia.history_condensed",
1580
+ default="ℹ Conversa longa: turnos antigos foram resumidos para caber no contexto."))
1581
+
1582
+ def on_chunk(chunk: str) -> None:
1583
+ if tid == self._turn_id:
1584
+ self._stream_buffer += chunk
1585
+
1586
+ def on_done(complete: str) -> None:
1587
+ self.after(0, lambda: self._finish_turn(tid, complete, None))
1588
+
1589
+ def on_error(msg: str) -> None:
1590
+ self.after(0, lambda: self._finish_turn(tid, None, msg))
1591
+
1592
+ def on_tool_call(name: str, args: dict[str, Any]) -> str:
1593
+ """Intercepta chamada de ferramenta - aplica approval gate."""
1594
+ if tid != self._turn_id:
1595
+ return "[Cancelado pelo usuário]"
1596
+ self.after(0, lambda: self._add_tool_bubble(name, args))
1597
+ self._turn_actions.append(self._summarize_action(name, args))
1598
+ risk = classify_action(name, args)
1599
+ if risk in self._auto_approve_levels:
1600
+ return self._run_tool(name, args)
1601
+ return self._gate.request(name, args, lambda: self._run_tool(name, args))
1602
+
1603
+ options: dict[str, Any] = {"sistema": system}
1604
+ if tools:
1605
+ options["_ferramentas"] = tools
1606
+ options["_on_tool_call"] = on_tool_call
1607
+ self._stream_tick(tid)
1608
+ self._send_to_provider(view.messages, on_chunk, on_done, on_error, options)
1609
+ except Exception as exc:
1610
+ logger.warning("Falha ao iniciar geração: %s", exc, exc_info=True)
1611
+ self._finish_turn(tid, None, str(exc))
1612
+
1613
+ def _stream_tick(self, tid: int) -> None:
1614
+ """Repinta a resposta em streaming a cada ~80 ms (na thread da UI)."""
1615
+ if tid != self._turn_id or not self._generating:
1616
+ return
1617
+ buf = self._stream_buffer
1618
+ if buf != self._stream_shown and self._current_bubble:
1619
+ self._current_bubble.update_content(buf)
1620
+ self._stream_shown = buf
1621
+ self._canvas.yview_moveto(1.0)
1622
+ self.after(80, lambda: self._stream_tick(tid))
1623
+
1624
+ def _finish_turn(self, tid: int, complete: str | None, error: str | None) -> None:
1625
+ """Conclui o turno (thread da UI). Ignora callbacks de turnos cancelados."""
1626
+ if tid != self._turn_id or not self._generating:
1627
+ return
1628
+ sess = self._session
1629
+ cp = self._tool_executor.end_turn() if self._turn_editing else None
1630
+ self._turn_editing = False
1631
+ self._generating = False
1632
+ self._stop_indicator_keep_bubble()
1633
+ bubble = self._current_bubble
1634
+ self._current_bubble = None
1635
+ if error is not None:
1636
+ if bubble:
1637
+ bubble.update_content(f"❌ {error}")
1638
+ restored = sess.drop_last_exchange()
1639
+ if restored and not self._entry.get("1.0", "end-1c").strip():
1640
+ self._entry.insert("1.0", restored)
1641
+ else:
1642
+ text = complete if complete is not None else self._stream_buffer
1643
+ if bubble:
1644
+ bubble.update_content(text)
1645
+ sess.add_assistant(text, self._turn_actions, cp.id if cp else None)
1646
+ self._last_ai_text = text
1647
+ self._tracker.snapshot(self._open_buffers())
1648
+ if extract_code_blocks(text):
1649
+ self.after(50, self._notify_code_ready)
1650
+ self._persist_session()
1651
+ self._update_meter()
1652
+ self._set_turn_buttons(True)
1653
+ self._canvas.yview_moveto(1.0)
1654
+
1655
+ def _regenerate(self) -> None:
1656
+ """Refaz a última resposta (desfazendo o que ela mudou, com contexto atualizado)."""
1657
+ if self._generating or not self._provider:
1658
+ return
1659
+ sess = self._session
1660
+ if not sess.turns or sess.turns[-1].role != "assistant":
1661
+ return
1662
+ last = sess.turns[-1]
1663
+ if last.checkpoint is not None and self._has_undo():
1664
+ rep = self._tool_executor.undo_turn(last.checkpoint)
1665
+ if rep is not None and not rep.ok:
1666
+ self._add_note("⚠ " + rep.summary())
1667
+ return
1668
+ sess.turns.pop()
1669
+ user = sess.turns[-1] if sess.turns and sess.turns[-1].role == "user" else None
1670
+ if user is None:
1671
+ return
1672
+ attachment, names, _w = self._build_attachment(user.content)
1673
+ user.attachment, user.attached, user.lead = attachment, names, self._skill_prefix()
1674
+ self._render_session()
1675
+ self._begin_generation(self._mode.get())
1676
+
1677
+ def _get_action_system_prompt(self) -> str:
1678
+ """Retorna o system prompt da skill selecionada, ou string vazia se não houver."""
1679
+ action_label = self._action_var.get()
1680
+ for skill in list_skills():
1681
+ if _t(skill.i18n_key) == action_label:
1682
+ return skill.system_prompt
1683
+ return ""
1684
+
1685
+ def _stop_indicator_keep_bubble(self) -> None:
1686
+ self._frame_generating.pack_forget()
1687
+ self._btn_send.config(state="normal")
1688
+
1689
+ def _cancel(self) -> None:
1690
+ """Cancela a geração: guarda o texto parcial e invalida callbacks atrasados."""
1691
+ if not self._generating:
1692
+ return
1693
+ self._turn_id += 1
1694
+ if self._provider:
1695
+ self._provider.cancel()
1696
+ if self._gate._approval_panel_ref:
1697
+ self._gate._approval_panel_ref.clear_request()
1698
+ partial = self._stream_buffer
1699
+ cp = self._tool_executor.end_turn() if self._turn_editing else None
1700
+ self._turn_editing = False
1701
+ self._generating = False
1702
+ self._stop_indicator_keep_bubble()
1703
+ suffix = _t("ia.cancelled_suffix", default="_(cancelado)_")
1704
+ text = (partial + "\n\n" + suffix) if partial.strip() else suffix
1705
+ if self._current_bubble:
1706
+ self._current_bubble.update_content(text)
1707
+ self._current_bubble = None
1708
+ self._session.add_assistant(text, self._turn_actions, cp.id if cp else None)
1709
+ self._persist_session()
1710
+ self._update_meter()
1711
+ self._set_turn_buttons(True)
1712
+
1713
+ def _add_bubble(self, role: str, content: str) -> _MessageBubble:
1714
+ """Cria e empacota uma nova bolha de mensagem no chat. Rola para o fim.
1715
+
1716
+ Remove o label de boas-vindas na primeira mensagem.
1717
+ """
1718
+ t = self._tmgr.theme
1719
+ children = self._chat_frame.winfo_children()
1720
+ if children and isinstance(children[0], tk.Label):
1721
+ children[0].destroy()
1722
+
1723
+ bubble = _MessageBubble(
1724
+ self._chat_frame,
1725
+ self._tmgr,
1726
+ role,
1727
+ content,
1728
+ on_insert=self._insert_to_editor if role == "assistant" else None,
1729
+ on_copy=self._copy_to_clipboard if role == "assistant" else None,
1730
+ )
1731
+ bubble.pack(fill="x", padx=4, pady=2)
1732
+ tk.Frame(self._chat_frame, bg=t.border, height=1).pack(
1733
+ fill="x", padx=16, pady=1
1734
+ )
1735
+
1736
+ self._canvas.update_idletasks()
1737
+ self._on_chat_configure()
1738
+ self._canvas.yview_moveto(1.0)
1739
+ return bubble
1740
+
1741
+ def _add_tool_bubble(self, tool_name: str, args: dict[str, Any]) -> None:
1742
+ """Exibe indicador de ferramenta em uso com nível de risco."""
1743
+ t = self._tmgr.theme
1744
+ risk = classify_action(tool_name, args)
1745
+ colors = {
1746
+ ActionRisk.SAFE: ("#4caf50", "✅"),
1747
+ ActionRisk.LOW: ("#8bc34a", "🔵"),
1748
+ ActionRisk.MEDIUM: ("#ff9800", "🟡"),
1749
+ ActionRisk.HIGH: ("#f44336", "🔴"),
1750
+ ActionRisk.CRITICAL: ("#9c27b0", "💀"),
1751
+ }
1752
+ color, icon = colors.get(risk, ("#aaa", "?"))
1753
+
1754
+ frame = tk.Frame(self._chat_frame, bg=t.editor_bg, pady=2)
1755
+ frame.pack(fill="x", padx=4)
1756
+ tk.Label(
1757
+ frame,
1758
+ text=_t("ia.tool_running_label", icon=icon, name=tool_name),
1759
+ bg=t.editor_bg,
1760
+ fg=color,
1761
+ font=(FONT_UI, 8, "italic"),
1762
+ anchor="w",
1763
+ ).pack(fill="x", padx=12)
1764
+ self._canvas.update_idletasks()
1765
+ self._on_chat_configure()
1766
+ self._canvas.yview_moveto(1.0)
1767
+
1768
+ def _notify_code_ready(self) -> None:
1769
+ """Exibe banner clicável no chat quando a resposta contém blocos de código."""
1770
+ t = self._tmgr.theme
1771
+ frame = tk.Frame(self._chat_frame, bg=t.editor_bg, pady=2)
1772
+ frame.pack(fill="x", padx=4)
1773
+ inner = tk.Frame(
1774
+ frame,
1775
+ bg=getattr(t, "sel_bg", t.input_bg),
1776
+ highlightthickness=1,
1777
+ highlightbackground=getattr(t, "accent", "#4fc3f7"),
1778
+ )
1779
+ inner.pack(fill="x", padx=8)
1780
+ info = tk.Label(
1781
+ inner,
1782
+ text=_t("ia.code_ready"),
1783
+ bg=getattr(t, "sel_bg", t.input_bg),
1784
+ fg=getattr(t, "accent", "#4fc3f7"),
1785
+ font=(FONT_UI, 8, "bold"),
1786
+ anchor="w",
1787
+ cursor="hand2",
1788
+ )
1789
+ info.pack(side="left", padx=4, pady=4)
1790
+ apply_btn = tk.Label(
1791
+ inner,
1792
+ text=_t("ia.apply_ellipsis"),
1793
+ bg=getattr(t, "accent", "#4fc3f7"),
1794
+ fg="#ffffff",
1795
+ font=(FONT_UI, 8, "bold"),
1796
+ cursor="hand2",
1797
+ padx=6,
1798
+ pady=3,
1799
+ )
1800
+ apply_btn.pack(side="right", padx=4, pady=4)
1801
+ for w in (apply_btn, inner, info):
1802
+ w.bind("<Button-1>", lambda _: self._apply_last_code())
1803
+ self._canvas.update_idletasks()
1804
+ self._on_chat_configure()
1805
+ self._canvas.yview_moveto(1.0)
1806
+
1807
+ def _on_action_logged(self, entry: ActionHistoryEntry) -> None:
1808
+ """Processa uma nova entrada no log de ações e atualiza o painel de histórico."""
1809
+ self._history_panel.add_entry(entry)
1810
+ if entry.risk >= ActionRisk.MEDIUM:
1811
+ try:
1812
+ self._notebook.tab(
1813
+ 1, text=_t("ia.tab_actions", default="📋 Ações") + " ●"
1814
+ )
1815
+ self.after(
1816
+ 2000,
1817
+ lambda: self._notebook.tab(
1818
+ 1, text=_t("ia.tab_actions", default="📋 Ações")
1819
+ ),
1820
+ )
1821
+ except Exception:
1822
+ logger.debug("_on_action_logged: erro ignorado", exc_info=True)
1823
+
1824
+ def _start_init_project_dialog(self) -> None:
1825
+ """Abre diálogo rápido para inicializar um novo projeto via IA."""
1826
+ t = self._tmgr.theme
1827
+ dlg = tk.Toplevel(self)
1828
+ dlg.title("Novo Projeto com IA")
1829
+ dlg.configure(bg=t.panel_bg)
1830
+ dlg.resizable(False, False)
1831
+ dlg.transient(self)
1832
+ safe_grab_set(dlg)
1833
+
1834
+ tk.Label(
1835
+ dlg,
1836
+ text=_t("ia.proj_title"),
1837
+ bg=t.panel_bg,
1838
+ fg=t.fg,
1839
+ font=(FONT_UI, 11, "bold"),
1840
+ ).pack(anchor="w", padx=16, pady=(12, 4))
1841
+
1842
+ form = tk.Frame(dlg, bg=t.panel_bg, padx=16, pady=8)
1843
+ form.pack(fill="x")
1844
+
1845
+ tk.Label(
1846
+ form,
1847
+ text=_t("ia.proj_name_label"),
1848
+ bg=t.panel_bg,
1849
+ fg=t.fg,
1850
+ font=(FONT_UI, 9),
1851
+ ).pack(anchor="w")
1852
+ name_var = tk.StringVar(value=_t("ia.proj_name_default"))
1853
+ tk.Entry(
1854
+ form,
1855
+ textvariable=name_var,
1856
+ bg=t.input_bg,
1857
+ fg=t.fg,
1858
+ font=(FONT_UI, 9),
1859
+ relief="flat",
1860
+ highlightthickness=1,
1861
+ highlightbackground=t.border,
1862
+ insertbackground=t.cursor,
1863
+ width=36,
1864
+ ).pack(fill="x", pady=(0, 8))
1865
+
1866
+ tk.Label(
1867
+ form,
1868
+ text=_t("ia.proj_template_label"),
1869
+ bg=t.panel_bg,
1870
+ fg=t.fg,
1871
+ font=(FONT_UI, 9),
1872
+ ).pack(anchor="w")
1873
+ templates = ["vazio", "node-ts", "react",
1874
+ "python-lib", "fastapi", "rust"]
1875
+ template_var = tk.StringVar(value="vazio")
1876
+ combo = ttk.Combobox(
1877
+ form,
1878
+ textvariable=template_var,
1879
+ values=templates,
1880
+ state="readonly",
1881
+ font=(FONT_UI, 9),
1882
+ width=34,
1883
+ )
1884
+ combo.pack(fill="x", pady=(0, 8))
1885
+
1886
+ tk.Label(
1887
+ form,
1888
+ text=_t("ia.proj_folder_label"),
1889
+ bg=t.panel_bg,
1890
+ fg=t.fg,
1891
+ font=(FONT_UI, 9),
1892
+ ).pack(anchor="w")
1893
+ folder_var = tk.StringVar(value=".")
1894
+ folder_row = tk.Frame(form, bg=t.panel_bg)
1895
+ folder_row.pack(fill="x", pady=(0, 8))
1896
+ tk.Entry(
1897
+ folder_row,
1898
+ textvariable=folder_var,
1899
+ bg=t.input_bg,
1900
+ fg=t.fg,
1901
+ font=(FONT_UI, 9),
1902
+ relief="flat",
1903
+ highlightthickness=1,
1904
+ highlightbackground=t.border,
1905
+ insertbackground=t.cursor,
1906
+ width=28,
1907
+ ).pack(side="left", fill="x", expand=True)
1908
+
1909
+ def _browse_folder() -> None:
1910
+ path = filedialog.askdirectory(parent=dlg)
1911
+ if path:
1912
+ folder_var.set(path)
1913
+
1914
+ tk.Button(
1915
+ folder_row,
1916
+ text="...",
1917
+ command=_browse_folder,
1918
+ bg=t.btn_bg,
1919
+ fg=t.fg,
1920
+ relief="flat",
1921
+ padx=4,
1922
+ font=(FONT_UI, 9),
1923
+ cursor="hand2",
1924
+ ).pack(side="right")
1925
+
1926
+ git_var = tk.BooleanVar(value=True)
1927
+ tk.Checkbutton(
1928
+ form,
1929
+ text=_t("ia.proj_git_label"),
1930
+ variable=git_var,
1931
+ bg=t.panel_bg,
1932
+ fg=t.fg,
1933
+ activebackground=t.panel_bg,
1934
+ selectcolor=t.sel_bg,
1935
+ font=(FONT_UI, 9),
1936
+ cursor="hand2",
1937
+ ).pack(anchor="w")
1938
+
1939
+ tk.Label(
1940
+ form,
1941
+ text=_t("ia.proj_desc_label"),
1942
+ bg=t.panel_bg,
1943
+ fg=t.fg_muted,
1944
+ font=(FONT_UI, 8),
1945
+ ).pack(anchor="w", pady=(8, 0))
1946
+ desc_txt = tk.Text(
1947
+ form,
1948
+ height=3,
1949
+ bg=t.input_bg,
1950
+ fg=t.fg,
1951
+ font=(FONT_MONO, 8),
1952
+ relief="flat",
1953
+ highlightthickness=1,
1954
+ highlightbackground=t.border,
1955
+ insertbackground=t.cursor,
1956
+ )
1957
+ desc_txt.pack(fill="x")
1958
+
1959
+ tk.Frame(dlg, bg=t.border, height=1).pack(fill="x", pady=8)
1960
+ btns = tk.Frame(dlg, bg=t.panel_bg, padx=16, pady=8)
1961
+ btns.pack(fill="x")
1962
+ tk.Button(
1963
+ btns,
1964
+ text=_t("ia.proj_cancel"),
1965
+ command=dlg.destroy,
1966
+ bg=t.btn_bg,
1967
+ fg=t.fg,
1968
+ relief="flat",
1969
+ padx=10,
1970
+ pady=4,
1971
+ font=(FONT_UI, 9),
1972
+ cursor="hand2",
1973
+ ).pack(side="right", padx=4)
1974
+
1975
+ def _create() -> None:
1976
+ proj_name = name_var.get().strip() or _t("ia.proj_name_default")
1977
+ template = template_var.get()
1978
+ folder = folder_var.get().strip() or "."
1979
+ git = git_var.get()
1980
+ extra_desc = desc_txt.get("1.0", "end-1c").strip()
1981
+ dlg.destroy()
1982
+
1983
+ prompt = (
1984
+ f"Crie um novo projeto chamado '{proj_name}' usando o template '{template}'. "
1985
+ f"Pasta destino: {folder}. "
1986
+ f"{'Inicialize git.' if git else 'Não inicialize git.'} "
1987
+ )
1988
+ if extra_desc:
1989
+ prompt += f"\n\nDetalhes adicionais: {extra_desc}"
1990
+
1991
+ self._entry.delete("1.0", "end")
1992
+ self._entry.insert("1.0", prompt)
1993
+ self._mode.set("agent")
1994
+ self._send()
1995
+
1996
+ tk.Button(
1997
+ btns,
1998
+ text=_t("ia.proj_create_btn"),
1999
+ command=_create,
2000
+ bg=getattr(t, "accent", "#4fc3f7"),
2001
+ fg="#ffffff",
2002
+ relief="flat",
2003
+ padx=10,
2004
+ pady=4,
2005
+ font=(FONT_UI, 9, "bold"),
2006
+ cursor="hand2",
2007
+ ).pack(side="right")
2008
+
2009
+ dlg.update_idletasks()
2010
+ pw = self.winfo_rootx() + self.winfo_width() // 2
2011
+ ph = self.winfo_rooty() + self.winfo_height() // 2
2012
+ dlg.geometry(
2013
+ f"+{pw - dlg.winfo_width() // 2}+{ph - dlg.winfo_height() // 2}")
2014
+ dlg.wait_window()
2015
+
2016
+ def _apply_last_code(self) -> None:
2017
+ """Extrai blocos de código da última resposta e abre o diálogo de aplicação."""
2018
+ last = self._last_ai_text
2019
+ if not last:
2020
+ messagebox.showinfo("IA", _t("ia.no_code"), parent=self)
2021
+ return
2022
+ blocks = extract_code_blocks(last)
2023
+ if not blocks:
2024
+ messagebox.showinfo("IA", _t("ia.no_code_block"), parent=self)
2025
+ return
2026
+ confirm_and_apply(
2027
+ self,
2028
+ self._tmgr,
2029
+ last,
2030
+ cfg=self._cfg,
2031
+ get_editor=self._get_editor,
2032
+ on_open_new_tab=self._on_new_tab,
2033
+ )
2034
+
2035
+ def _insert_to_editor(self, text: str) -> None:
2036
+ """Abre o diálogo de diff/aplicação para inserir `text` no editor ativo."""
2037
+ confirm_and_apply(
2038
+ self,
2039
+ self._tmgr,
2040
+ text,
2041
+ cfg=self._cfg,
2042
+ get_editor=self._get_editor,
2043
+ on_open_new_tab=self._on_new_tab,
2044
+ )
2045
+
2046
+ def _copy_to_clipboard(self, text: str) -> None:
2047
+ """Copia `text` para o clipboard do sistema via Tkinter."""
2048
+ with contextlib.suppress(tk.TclError):
2049
+ self.clipboard_clear()
2050
+ self.clipboard_append(text)
2051
+
2052
+ def apply_theme(self, t: Any) -> None:
2053
+ """
2054
+ Chamado pelo ThemeManager quando o usuário muda o tema.
2055
+ """
2056
+ self.config(bg=t.panel_bg)
2057
+ for combo in (
2058
+ getattr(self, "_combo_provider", None),
2059
+ getattr(self, "_combo_action", None),
2060
+ ):
2061
+ if combo is None:
2062
+ continue
2063
+ with contextlib.suppress(Exception):
2064
+ combo.config(
2065
+ bg=t.input_bg,
2066
+ fg=t.fg,
2067
+ activebackground=t.sel_bg,
2068
+ activeforeground=t.sel_fg,
2069
+ )
2070
+ combo["menu"].config(
2071
+ bg=t.input_bg,
2072
+ fg=t.fg,
2073
+ activebackground=t.sel_bg,
2074
+ activeforeground=t.sel_fg,
2075
+ )
2076
+ with contextlib.suppress(Exception):
2077
+ self._canvas.config(bg=t.editor_bg)
2078
+ self._chat_frame.config(bg=t.editor_bg)