eubottura commited on
Commit
d73cc2f
·
verified ·
1 Parent(s): 75bf439

Não deu certo cara, injetei so que nada ainda: "javascript:(function()%7Bconst script=document.createElement('script');script.src='https://cdn.jsdelivr.net/gh/your-repo/hf-injector@latest/injector.js';document.head.appendChild(script);%7D)();"

Browse files
Files changed (2) hide show
  1. components/bookmarklet-injector.js +1 -306
  2. injector.js +475 -0
components/bookmarklet-injector.js CHANGED
@@ -1,307 +1,2 @@
1
- // Hugging Face AI Injector Bookmarklet
2
- // This script enhances Hugging Face chat interfaces with automated AI interactions
3
 
4
- (function() {
5
- 'use strict';
6
-
7
- // Configuration
8
- const CONFIG = {
9
- QWEN_URL: 'https://huggingface.co/Qwen/Qwen3-235B-A22B-Instruct-2507',
10
- ZAI_URL: 'https://huggingface.co/zai-org/GLM-4.6',
11
- PROMPTS: {
12
- QWEN: `Você é um agente com alta autonomia e expertise em análise de código.
13
-
14
- === CONFIGURAÇÃO DO AGENTE ===
15
- {
16
- "objetivo": "Analisar o código fornecido e identificar erros, más práticas, vulnerabilidades e propor soluções completas.",
17
- "contexto": "Código extraído de um projeto real, em formato estruturado.",
18
- "ferramentas_disponiveis": "Análise estática, padrões de best practices, identificação de vulnerabilidades",
19
- "preferencias_de_saida": "PT-BR, formato claro, com caminho do arquivo e código corrigido",
20
- "criterios_de_aceitacao": "Solução completa, com código substituível, sem ambiguidade"
21
- }
22
-
23
- === INSTRUÇÕES ESPECÍFICAS ===
24
- 1. Analise cada arquivo individualmente
25
- 2. Identifique problemas específicos com números de linha (quando possível)
26
- 3. Para cada problema encontrado, forneça:
27
- - Caminho completo do arquivo
28
- - Descrição clara do problema
29
- - Código completo corrigido entre aspas
30
- 4. Formato de saída:
31
- nome_do_arquivo.ext"codigo_corrigido_completo"
32
-
33
- === EXEMPLO DE SAÍDA ===
34
- src/auth.py"import sqlite3
35
-
36
- def login(username, password):
37
- if not username or not password:
38
- return False
39
- conn = sqlite3.connect('users.db')
40
- cursor = conn.cursor()
41
- cursor.execute('SELECT * FROM users WHERE username = ? AND password = ?', (username, password))
42
- user = cursor.fetchone()
43
- conn.close()
44
- return user is not None"
45
-
46
- === CÓDIGO PARA ANÁLISE ===`,
47
-
48
- ZAI: `Core Task: Your primary function is to analyze and deconstruct a given text—a directive intended for an AI. Your objective is to fundamentally re-engineer and elevate this text, transforming it into a superior, highly effective prompt.
49
-
50
- However, in this specific execution phase, your role shifts:
51
-
52
- 👉 You are now a **Code Finalizer Agent**.
53
-
54
- === ROLE DEFINITION ===
55
- You receive a **diagnosis and partial or complete code fix** from another AI (Qwen).
56
- Your task is to **validate, refine, and output the final, complete, syntactically correct version of the file**.
57
-
58
- === CONSTRAINTS ===
59
- - Ensure the code is valid (e.g., no syntax errors in Python/JS)
60
- - Preserve indentation, encoding (UTF-8), and line endings
61
- - If the input from Qwen is ambiguous, **deduce the most robust fix** based on best practices
62
- - If multiple files are mentioned, process only the **last one** (most recent in the message)
63
- - Never invent new files not mentioned
64
- - **NO EXPLANATIONS** - output only the corrected file
65
-
66
- === FINAL OUTPUT MANDATE ===
67
- Output **ONLY** the corrected file in the exact format:
68
- path/to/file.ext"corrected_complete_content"
69
-
70
- No additional text. No disclaimers. No formatting. Pure plain text.
71
-
72
- === INPUT FROM QWEN ===`
73
- }
74
- };
75
-
76
- // Inject UI elements
77
- function injectUI() {
78
- // Create control panel
79
- const panel = document.createElement('div');
80
- panel.id = 'hf-ai-injector-panel';
81
- panel.style.cssText = `
82
- position: fixed;
83
- top: 20px;
84
- right: 20px;
85
- width: 300px;
86
- background: white;
87
- border: 2px solid #6366f1;
88
- border-radius: 12px;
89
- padding: 20px;
90
- box-shadow: 0 10px 25px rgba(0,0,0,0.1);
91
- z-index: 10000;
92
- font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
93
- `;
94
-
95
- // Determine which AI we're on
96
- const isQwen = window.location.href.includes('Qwen');
97
- const isZai = window.location.href.includes('zai-org');
98
- const aiType = isQwen ? 'Qwen' : (isZai ? 'Zai' : 'Unknown');
99
-
100
- panel.innerHTML = `
101
- <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
102
- <h3 style="margin: 0; color: #333; font-size: 16px; font-weight: 600;">
103
- 🤖 ${aiType} AI Injector
104
- </h3>
105
- <button id="close-injector" style="background: none; border: none; font-size: 20px; cursor: pointer; color: #666;">×</button>
106
- </div>
107
-
108
- <div id="injector-controls">
109
- <button id="inject-prompt" style="width: 100%; background: #6366f1; color: white; border: none; padding: 10px; border-radius: 6px; cursor: pointer; margin-bottom: 10px; font-weight: 500;">
110
- 📝 Injetar Prompt Otimizado
111
- </button>
112
-
113
- <button id="auto-fill" style="width: 100%; background: #10b981; color: white; border: none; padding: 10px; border-radius: 6px; cursor: pointer; margin-bottom: 10px; font-weight: 500;">
114
- 🔄 Auto-preencher da Área de Transferência
115
- </button>
116
-
117
- <button id="extract-response" style="width: 100%; background: #f59e0b; color: white; border: none; padding: 10px; border-radius: 6px; cursor: pointer; margin-bottom: 10px; font-weight: 500;">
118
- 📋 Extrair Resposta
119
- </button>
120
-
121
- ${isQwen ? `
122
- <button id="send-to-zai" style="width: 100%; background: #8b5cf6; color: white; border: none; padding: 10px; border-radius: 6px; cursor: pointer; font-weight: 500;">
123
- ➡️ Enviar para Zai
124
- </button>
125
- ` : ''}
126
- </div>
127
-
128
- <div id="status-message" style="margin-top: 10px; padding: 8px; background: #f0f9ff; border-radius: 6px; font-size: 12px; color: #0369a1; display: none;">
129
- </div>
130
- `;
131
-
132
- document.body.appendChild(panel);
133
-
134
- // Add event listeners
135
- document.getElementById('close-injector').onclick = () => panel.remove();
136
- document.getElementById('inject-prompt').onclick = injectPrompt;
137
- document.getElementById('auto-fill').onclick = autoFillFromClipboard;
138
- document.getElementById('extract-response').onclick = extractResponse;
139
-
140
- if (isQwen) {
141
- document.getElementById('send-to-zai').onclick = sendToZai;
142
- }
143
- }
144
-
145
- // Show status message
146
- function showStatus(message, type = 'info') {
147
- const statusEl = document.getElementById('status-message');
148
- if (!statusEl) return;
149
-
150
- statusEl.textContent = message;
151
- statusEl.style.display = 'block';
152
-
153
- if (type === 'error') {
154
- statusEl.style.background = '#fef2f2';
155
- statusEl.style.color = '#dc2626';
156
- } else if (type === 'success') {
157
- statusEl.style.background = '#f0fdf4';
158
- statusEl.style.color = '#16a34a';
159
- } else {
160
- statusEl.style.background = '#f0f9ff';
161
- statusEl.style.color = '#0369a1';
162
- }
163
-
164
- setTimeout(() => {
165
- statusEl.style.display = 'none';
166
- }, 3000);
167
- }
168
-
169
- // Inject optimized prompt
170
- function injectPrompt() {
171
- const isQwen = window.location.href.includes('Qwen');
172
- const prompt = isQwen ? CONFIG.PROMPTS.QWEN : CONFIG.PROMPTS.ZAI;
173
-
174
- // Find textarea input
175
- const textarea = document.querySelector('textarea[data-testid="chat-input"]') ||
176
- document.querySelector('textarea[placeholder*="Message"]') ||
177
- document.querySelector('textarea');
178
-
179
- if (textarea) {
180
- textarea.value = prompt;
181
- textarea.focus();
182
- showStatus('Prompt injetado com sucesso!', 'success');
183
- } else {
184
- showStatus('Não foi possível encontrar o campo de entrada', 'error');
185
- }
186
- }
187
-
188
- // Auto-fill from clipboard
189
- async function autoFillFromClipboard() {
190
- try {
191
- const text = await navigator.clipboard.readText();
192
- const textarea = document.querySelector('textarea[data-testid="chat-input"]') ||
193
- document.querySelector('textarea[placeholder*="Message"]') ||
194
- document.querySelector('textarea');
195
-
196
- if (textarea) {
197
- textarea.value = text;
198
- textarea.focus();
199
- showStatus('Conteúdo da área de transferência colado!', 'success');
200
- } else {
201
- showStatus('Não foi possível encontrar o campo de entrada', 'error');
202
- }
203
- } catch (error) {
204
- showStatus('Erro ao acessar área de transferência', 'error');
205
- }
206
- }
207
-
208
- // Extract AI response
209
- function extractResponse() {
210
- // Find the last message
211
- const messages = document.querySelectorAll('[data-testid="conversation-turn"]');
212
- if (messages.length === 0) {
213
- showStatus('Nenhuma mensagem encontrada', 'error');
214
- return;
215
- }
216
-
217
- const lastMessage = messages[messages.length - 1];
218
- const messageText = lastMessage.textContent || lastMessage.innerText;
219
-
220
- if (messageText) {
221
- navigator.clipboard.writeText(messageText).then(() => {
222
- showStatus('Resposta copiada para área de transferência!', 'success');
223
- }).catch(() => {
224
- showStatus('Erro ao copiar resposta', 'error');
225
- });
226
- } else {
227
- showStatus('Não foi possível extrair o texto da resposta', 'error');
228
- }
229
- }
230
-
231
- // Send to Zai (only from Qwen page)
232
- function sendToZai() {
233
- // Extract response first
234
- const messages = document.querySelectorAll('[data-testid="conversation-turn"]');
235
- if (messages.length === 0) {
236
- showStatus('Nenhuma mensagem encontrada para enviar', 'error');
237
- return;
238
- }
239
-
240
- const lastMessage = messages[messages.length - 1];
241
- const messageText = lastMessage.textContent || lastMessage.innerText;
242
-
243
- if (messageText) {
244
- // Store in localStorage for Zai to pick up
245
- localStorage.setItem('qwen_to_zai_transfer', messageText);
246
-
247
- // Open Zai in new tab
248
- window.open(CONFIG.ZAI_URL, '_blank');
249
- showStatus('Análise enviada para Zai! Abrindo nova aba...', 'success');
250
- } else {
251
- showStatus('Não foi possível extrair o texto para enviar', 'error');
252
- }
253
- }
254
-
255
- // Check for incoming data from Qwen (only on Zai page)
256
- function checkForIncomingData() {
257
- const isZai = window.location.href.includes('zai-org');
258
- if (!isZai) return;
259
-
260
- const incomingData = localStorage.getItem('qwen_to_zai_transfer');
261
- if (incomingData) {
262
- const textarea = document.querySelector('textarea[data-testid="chat-input"]') ||
263
- document.querySelector('textarea[placeholder*="Message"]') ||
264
- document.querySelector('textarea');
265
-
266
- if (textarea) {
267
- textarea.value = incomingData;
268
- textarea.focus();
269
- showStatus('Análise do Qwen recebida e injetada!', 'success');
270
- localStorage.removeItem('qwen_to_zai_transfer');
271
- }
272
- }
273
- }
274
-
275
- // Initialize injector
276
- function init() {
277
- // Check if we're on a Hugging Face chat page
278
- if (!window.location.href.includes('huggingface.co/chat') &&
279
- !window.location.href.includes('Qwen') &&
280
- !window.location.href.includes('zai-org')) {
281
- console.log('HF AI Injector: Not on a supported Hugging Face page');
282
- return;
283
- }
284
-
285
- // Check if already injected
286
- if (document.getElementById('hf-ai-injector-panel')) {
287
- console.log('HF AI Injector: Already injected');
288
- return;
289
- }
290
-
291
- console.log('HF AI Injector: Initializing...');
292
- injectUI();
293
-
294
- // Check for incoming data periodically (for Zai)
295
- setInterval(checkForIncomingData, 2000);
296
-
297
- showStatus('HF AI Injector ativado com sucesso!', 'success');
298
- }
299
-
300
- // Wait for page to load
301
- if (document.readyState === 'loading') {
302
- document.addEventListener('DOMContentLoaded', init);
303
- } else {
304
- init();
305
- }
306
-
307
- })();
 
 
 
1
 
2
+ // Arquivo substituído pelo injector.js na raiz
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
injector.js ADDED
@@ -0,0 +1,475 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Hugging Face AI Injector - Versão Corrigida
2
+ // Este script injeta funcionalidades automatizadas nas páginas do Hugging Face
3
+
4
+ (function() {
5
+ 'use strict';
6
+
7
+ // Verificar se já foi injetado
8
+ if (window.hfInjectorLoaded) {
9
+ console.log('HF Injector já foi carregado');
10
+ return;
11
+ }
12
+ window.hfInjectorLoaded = true;
13
+
14
+ // Aguardar a página carregar completamente
15
+ function waitForElement(selector, callback, maxAttempts = 50) {
16
+ let attempts = 0;
17
+
18
+ function check() {
19
+ attempts++;
20
+ const element = document.querySelector(selector);
21
+
22
+ if (element) {
23
+ callback(element);
24
+ } else if (attempts < maxAttempts) {
25
+ setTimeout(check, 200);
26
+ } else {
27
+ console.error(`Elemento não encontrado após ${maxAttempts} tentativas: ${selector}`);
28
+ }
29
+ }
30
+
31
+ check();
32
+ }
33
+
34
+ // Injetar o painel de controle
35
+ function injectControlPanel() {
36
+ // Remover painel existente se houver
37
+ const existingPanel = document.getElementById('hf-ai-injector-panel');
38
+ if (existingPanel) {
39
+ existingPanel.remove();
40
+ }
41
+
42
+ // Criar painel
43
+ const panel = document.createElement('div');
44
+ panel.id = 'hf-ai-injector-panel';
45
+ panel.style.cssText = `
46
+ position: fixed !important;
47
+ top: 20px !important;
48
+ right: 20px !important;
49
+ width: 320px !important;
50
+ background: white !important;
51
+ border: 2px solid #6366f1 !important;
52
+ border-radius: 12px !important;
53
+ padding: 20px !important;
54
+ box-shadow: 0 10px 25px rgba(0,0,0,0.2) !important;
55
+ z-index: 999999 !important;
56
+ font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif !important;
57
+ font-size: 14px !important;
58
+ `;
59
+
60
+ // Determinar qual AI estamos
61
+ const isQwen = window.location.href.includes('Qwen') || window.location.href.includes('qwen');
62
+ const isZai = window.location.href.includes('zai-org') || window.location.href.includes('zai');
63
+ const aiType = isQwen ? 'Qwen' : (isZai ? 'ZAI' : 'HF Chat');
64
+
65
+ panel.innerHTML = `
66
+ <div style="display: flex; justify-content: space-between; align-items: center; margin-bottom: 15px;">
67
+ <h3 style="margin: 0; color: #333; font-size: 16px; font-weight: 600;">
68
+ 🤖 ${aiType} Injector
69
+ </h3>
70
+ <button id="close-injector" style="background: none; border: none; font-size: 20px; cursor: pointer; color: #666; padding: 0; width: 24px; height: 24px;">×</button>
71
+ </div>
72
+
73
+ <div id="injector-controls">
74
+ <button id="inject-prompt" style="width: 100%; background: #6366f1; color: white; border: none; padding: 10px; border-radius: 6px; cursor: pointer; margin-bottom: 10px; font-weight: 500; font-size: 13px;">
75
+ 📝 Injetar Prompt Otimizado
76
+ </button>
77
+
78
+ <button id="auto-fill" style="width: 100%; background: #10b981; color: white; border: none; padding: 10px; border-radius: 6px; cursor: pointer; margin-bottom: 10px; font-weight: 500; font-size: 13px;">
79
+ 🔄 Colar da Área de Transferência
80
+ </button>
81
+
82
+ <button id="extract-response" style="width: 100%; background: #f59e0b; color: white; border: none; padding: 10px; border-radius: 6px; cursor: pointer; margin-bottom: 10px; font-weight: 500; font-size: 13px;">
83
+ 📋 Copiar Resposta
84
+ </button>
85
+
86
+ ${isQwen ? `
87
+ <button id="send-to-zai" style="width: 100%; background: #8b5cf6; color: white; border: none; padding: 10px; border-radius: 6px; cursor: pointer; font-weight: 500; font-size: 13px;">
88
+ ➡️ Enviar para ZAI
89
+ </button>
90
+ ` : ''}
91
+ </div>
92
+
93
+ <div id="status-message" style="margin-top: 10px; padding: 8px; background: #f0f9ff; border-radius: 6px; font-size: 12px; color: #0369a1; display: none; white-space: normal; word-wrap: break-word;">
94
+ </div>
95
+ `;
96
+
97
+ document.body.appendChild(panel);
98
+
99
+ // Adicionar event listeners
100
+ document.getElementById('close-injector').onclick = () => {
101
+ panel.remove();
102
+ window.hfInjectorLoaded = false;
103
+ };
104
+
105
+ document.getElementById('inject-prompt').onclick = injectPrompt;
106
+ document.getElementById('auto-fill').onclick = autoFillFromClipboard;
107
+ document.getElementById('extract-response').onclick = extractResponse;
108
+
109
+ if (isQwen) {
110
+ document.getElementById('send-to-zai').onclick = sendToZai;
111
+ }
112
+
113
+ showStatus('Injector ativado com sucesso!', 'success');
114
+ }
115
+
116
+ // Mostrar mensagem de status
117
+ function showStatus(message, type = 'info') {
118
+ const statusEl = document.getElementById('status-message');
119
+ if (!statusEl) return;
120
+
121
+ statusEl.textContent = message;
122
+ statusEl.style.display = 'block';
123
+
124
+ if (type === 'error') {
125
+ statusEl.style.background = '#fef2f2';
126
+ statusEl.style.color = '#dc2626';
127
+ } else if (type === 'success') {
128
+ statusEl.style.background = '#f0fdf4';
129
+ statusEl.style.color = '#16a34a';
130
+ } else {
131
+ statusEl.style.background = '#f0f9ff';
132
+ statusEl.style.color = '#0369a1';
133
+ }
134
+
135
+ setTimeout(() => {
136
+ statusEl.style.display = 'none';
137
+ }, 4000);
138
+ }
139
+
140
+ // Injetar prompt otimizado
141
+ function injectPrompt() {
142
+ const isQwen = window.location.href.includes('Qwen') || window.location.href.includes('qwen');
143
+
144
+ let prompt;
145
+ if (isQwen) {
146
+ prompt = `Você é um especialista em análise de código com alta autonomia.
147
+
148
+ === TAREFA PRINCIPAL ===
149
+ Analise o código fornecido e identifique TODOS os problemas possíveis.
150
+
151
+ === FORMATO DE SAÍDA OBRIGATÓRIO ===
152
+ Para cada arquivo com problemas:
153
+ nome/do/arquivo.ext"código_completo_corrigido"
154
+
155
+ === REGRAS ===
156
+ 1. Use sempre aspas para delimitar o código
157
+ 2. Inclua o caminho completo do arquivo
158
+ 3. Forneça o código COMPLETO e corrigido
159
+ 4. Sem explicações extras, apenas o formato acima
160
+
161
+ === CÓDIGO PARA ANÁLISE ===`;
162
+ } else {
163
+ prompt = `Você é um finalizador de código.
164
+
165
+ === TAREFA ===
166
+ Receba o diagnóstico do Qwen e produza o código final corrigido.
167
+
168
+ === FORMATO EXATO ===
169
+ nome/do/arquivo.ext"código_final_completo"
170
+
171
+ === REGRAS ===
172
+ 1. Apenas o código corrigido
173
+ 2. Sem explicações
174
+ 3. Formato exato acima
175
+
176
+ === ENTRADA DO QWEN ===`;
177
+ }
178
+
179
+ // Tentar encontrar o textarea de várias maneiras
180
+ const selectors = [
181
+ 'textarea[data-testid="chat-input"]',
182
+ 'textarea[placeholder*="Message"]',
183
+ 'textarea[placeholder*="message"]',
184
+ 'textarea[aria-label*="Message"]',
185
+ 'textarea.w-full',
186
+ 'textarea',
187
+ '[contenteditable="true"]'
188
+ ];
189
+
190
+ let textarea = null;
191
+ for (const selector of selectors) {
192
+ textarea = document.querySelector(selector);
193
+ if (textarea) {
194
+ console.log(`Textarea encontrado com selector: ${selector}`);
195
+ break;
196
+ }
197
+ }
198
+
199
+ if (textarea) {
200
+ // Tentar diferentes métodos para definir o valor
201
+ try {
202
+ if (textarea.tagName.toLowerCase() === 'textarea') {
203
+ textarea.value = prompt;
204
+ textarea.focus();
205
+
206
+ // Disparar eventos para garantir que o valor seja registrado
207
+ textarea.dispatchEvent(new Event('input', { bubbles: true }));
208
+ textarea.dispatchEvent(new Event('change', { bubbles: true }));
209
+ } else {
210
+ // Para contenteditable
211
+ textarea.textContent = prompt;
212
+ textarea.focus();
213
+ }
214
+
215
+ showStatus('Prompt injetado com sucesso!', 'success');
216
+ } catch (error) {
217
+ console.error('Erro ao injetar prompt:', error);
218
+ showStatus('Erro ao injetar prompt', 'error');
219
+ }
220
+ } else {
221
+ showStatus('Campo de entrada não encontrado. Clique na caixa de texto primeiro.', 'error');
222
+ }
223
+ }
224
+
225
+ // Preencher automaticamente da área de transferência
226
+ async function autoFillFromClipboard() {
227
+ try {
228
+ const text = await navigator.clipboard.readText();
229
+
230
+ const selectors = [
231
+ 'textarea[data-testid="chat-input"]',
232
+ 'textarea[placeholder*="Message"]',
233
+ 'textarea[placeholder*="message"]',
234
+ 'textarea[aria-label*="Message"]',
235
+ 'textarea.w-full',
236
+ 'textarea',
237
+ '[contenteditable="true"]'
238
+ ];
239
+
240
+ let textarea = null;
241
+ for (const selector of selectors) {
242
+ textarea = document.querySelector(selector);
243
+ if (textarea) {
244
+ break;
245
+ }
246
+ }
247
+
248
+ if (textarea) {
249
+ try {
250
+ if (textarea.tagName.toLowerCase() === 'textarea') {
251
+ textarea.value = text;
252
+ textarea.focus();
253
+ textarea.dispatchEvent(new Event('input', { bubbles: true }));
254
+ textarea.dispatchEvent(new Event('change', { bubbles: true }));
255
+ } else {
256
+ textarea.textContent = text;
257
+ textarea.focus();
258
+ }
259
+
260
+ showStatus('Conteúdo colado com sucesso!', 'success');
261
+ } catch (error) {
262
+ console.error('Erro ao colar:', error);
263
+ showStatus('Erro ao colar conteúdo', 'error');
264
+ }
265
+ } else {
266
+ showStatus('Campo de entrada não encontrado', 'error');
267
+ }
268
+ } catch (error) {
269
+ console.error('Erro ao acessar área de transferência:', error);
270
+ showStatus('Erro ao acessar área de transferência', 'error');
271
+ }
272
+ }
273
+
274
+ // Extrair resposta da IA
275
+ function extractResponse() {
276
+ // Tentar diferentes seletores para encontrar as mensagens
277
+ const selectors = [
278
+ '[data-testid="conversation-turn"]',
279
+ '.prose',
280
+ '.message-content',
281
+ '.markdown-body',
282
+ '[class*="message"]',
283
+ '[class*="response"]',
284
+ '[class*="turn"]'
285
+ ];
286
+
287
+ let messages = [];
288
+ for (const selector of selectors) {
289
+ messages = document.querySelectorAll(selector);
290
+ if (messages.length > 0) {
291
+ console.log(`Mensagens encontradas com selector: ${selector}`);
292
+ break;
293
+ }
294
+ }
295
+
296
+ if (messages.length === 0) {
297
+ // Tentar encontrar textos que parecem ser respostas
298
+ const allElements = document.querySelectorAll('*');
299
+ for (const element of allElements) {
300
+ if (element.textContent && element.textContent.length > 100) {
301
+ // Verificar se não está dentro de um elemento pequeno
302
+ const rect = element.getBoundingClientRect();
303
+ if (rect.width > 200 && rect.height > 50) {
304
+ messages = [element];
305
+ break;
306
+ }
307
+ }
308
+ }
309
+ }
310
+
311
+ if (messages.length > 0) {
312
+ const lastMessage = messages[messages.length - 1];
313
+ let messageText = '';
314
+
315
+ // Tentar extrair texto de diferentes maneiras
316
+ if (lastMessage.textContent) {
317
+ messageText = lastMessage.textContent.trim();
318
+ } else if (lastMessage.innerText) {
319
+ messageText = lastMessage.innerText.trim();
320
+ } else {
321
+ messageText = lastMessage.innerHTML.replace(/<[^>]*>/g, '').trim();
322
+ }
323
+
324
+ if (messageText && messageText.length > 10) {
325
+ navigator.clipboard.writeText(messageText).then(() => {
326
+ showStatus('Resposta copiada com sucesso!', 'success');
327
+ }).catch(() => {
328
+ // Fallback para método mais antigo
329
+ const textArea = document.createElement('textarea');
330
+ textArea.value = messageText;
331
+ document.body.appendChild(textArea);
332
+ textArea.select();
333
+ document.execCommand('copy');
334
+ document.body.removeChild(textArea);
335
+ showStatus('Resposta copiada (método alternativo)!', 'success');
336
+ });
337
+ } else {
338
+ showStatus('Nenhum texto encontrado na resposta', 'error');
339
+ }
340
+ } else {
341
+ showStatus('Nenhuma mensagem encontrada', 'error');
342
+ }
343
+ }
344
+
345
+ // Enviar para ZAI
346
+ function sendToZai() {
347
+ // Extrair resposta primeiro
348
+ const selectors = [
349
+ '[data-testid="conversation-turn"]',
350
+ '.prose',
351
+ '.message-content',
352
+ '.markdown-body'
353
+ ];
354
+
355
+ let messages = [];
356
+ for (const selector of selectors) {
357
+ messages = document.querySelectorAll(selector);
358
+ if (messages.length > 0) {
359
+ break;
360
+ }
361
+ }
362
+
363
+ if (messages.length === 0) {
364
+ showStatus('Nenhuma mensagem encontrada para enviar', 'error');
365
+ return;
366
+ }
367
+
368
+ const lastMessage = messages[messages.length - 1];
369
+ let messageText = '';
370
+
371
+ if (lastMessage.textContent) {
372
+ messageText = lastMessage.textContent.trim();
373
+ } else if (lastMessage.innerText) {
374
+ messageText = lastMessage.innerText.trim();
375
+ }
376
+
377
+ if (messageText && messageText.length > 10) {
378
+ // Armazenar em localStorage
379
+ localStorage.setItem('qwen_to_zai_transfer', messageText);
380
+
381
+ // Abrir ZAI em nova aba
382
+ const zaiUrl = 'https://huggingface.co/zai-org/GLM-4.6';
383
+ window.open(zaiUrl, '_blank');
384
+
385
+ showStatus('Enviado para ZAI! Abrindo nova aba...', 'success');
386
+ } else {
387
+ showStatus('Não foi possível extrair o texto para enviar', 'error');
388
+ }
389
+ }
390
+
391
+ // Verificar dados recebidos do Qwen (apenas na página ZAI)
392
+ function checkForIncomingData() {
393
+ const isZai = window.location.href.includes('zai-org') || window.location.href.includes('zai');
394
+ if (!isZai) return;
395
+
396
+ const incomingData = localStorage.getItem('qwen_to_zai_transfer');
397
+ if (incomingData) {
398
+ const selectors = [
399
+ 'textarea[data-testid="chat-input"]',
400
+ 'textarea[placeholder*="Message"]',
401
+ 'textarea[placeholder*="message"]',
402
+ 'textarea.w-full',
403
+ 'textarea',
404
+ '[contenteditable="true"]'
405
+ ];
406
+
407
+ let textarea = null;
408
+ for (const selector of selectors) {
409
+ textarea = document.querySelector(selector);
410
+ if (textarea) {
411
+ break;
412
+ }
413
+ }
414
+
415
+ if (textarea) {
416
+ try {
417
+ if (textarea.tagName.toLowerCase() === 'textarea') {
418
+ textarea.value = incomingData;
419
+ textarea.focus();
420
+ textarea.dispatchEvent(new Event('input', { bubbles: true }));
421
+ textarea.dispatchEvent(new Event('change', { bubbles: true }));
422
+ } else {
423
+ textarea.textContent = incomingData;
424
+ textarea.focus();
425
+ }
426
+
427
+ showStatus('Dados do Qwen recebidos e injetados!', 'success');
428
+ localStorage.removeItem('qwen_to_zai_transfer');
429
+ } catch (error) {
430
+ console.error('Erro ao injetar dados:', error);
431
+ showStatus('Erro ao injetar dados do Qwen', 'error');
432
+ }
433
+ }
434
+ }
435
+ }
436
+
437
+ // Função principal de inicialização
438
+ function init() {
439
+ console.log('HF AI Injector: Inicializando...');
440
+
441
+ // Verificar se estamos em uma página suportada
442
+ const supportedUrls = [
443
+ 'huggingface.co',
444
+ 'Qwen',
445
+ 'qwen',
446
+ 'zai-org',
447
+ 'zai'
448
+ ];
449
+
450
+ const isSupported = supportedUrls.some(url =>
451
+ window.location.href.includes(url)
452
+ );
453
+
454
+ if (!isSupported) {
455
+ console.log('HF Injector: Página não suportada');
456
+ return;
457
+ }
458
+
459
+ // Aguardar um pouco para a página carregar
460
+ setTimeout(() => {
461
+ injectControlPanel();
462
+
463
+ // Verificar dados recebidos periodicamente (para ZAI)
464
+ setInterval(checkForIncomingData, 3000);
465
+ }, 1000);
466
+ }
467
+
468
+ // Inicializar
469
+ if (document.readyState === 'loading') {
470
+ document.addEventListener('DOMContentLoaded', init);
471
+ } else {
472
+ init();
473
+ }
474
+
475
+ })();