Skip to content

Commit 78c219d

Browse files
committed
fix ia
1 parent edc2173 commit 78c219d

2 files changed

Lines changed: 69 additions & 5 deletions

File tree

backend/src/worker.js

Lines changed: 46 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -80,12 +80,53 @@ function extractAiText(result) {
8080
}
8181

8282
function stripCodeFences(text) {
83-
// Extract content from inside a markdown code block if present
84-
const match = text.match(/```[a-zA-Z0-9]*\s*\n([\s\S]*?)\n\s*```/);
83+
const match = text.match(/```[a-zA-Z0-9]*\s*\n([\s\S]*?)\n?\s*```/);
8584
if (match) return match[1].trim();
8685
return text;
8786
}
8887

88+
function cleanAiResponse(text, originalCode) {
89+
if (!text) return originalCode;
90+
91+
// 1. Extract from markdown code fence
92+
text = stripCodeFences(text);
93+
94+
// 2. Strip common AI prefix lines (loop until stable)
95+
const prefixPatterns = [
96+
/^Linguagem:\s*\S+[ \t]*\n+/i,
97+
/^C[oó]digo(?:\s+[^\n]*)?\s*:\s*\n+/i,
98+
/^Aqui(?:\s+est[áa][^\n]*)?\s*:\s*\n+/i,
99+
/^Here(?:'s| is)[^\n]*:\s*\n+/i,
100+
/^O c[oó]digo[^\n]*:\s*\n+/i,
101+
/^Resultado[^\n]*:\s*\n+/i,
102+
/^Fixed[^\n]*:\s*\n+/i,
103+
/^Corrected[^\n]*:\s*\n+/i,
104+
/^Output[^\n]*:\s*\n+/i,
105+
];
106+
let prev;
107+
do {
108+
prev = text;
109+
for (const p of prefixPatterns) text = text.replace(p, '').trimStart();
110+
} while (text !== prev);
111+
112+
// 3. Strip trailing explanation lines
113+
const explanationStart = /^(?:Note[:\s]|Obs[:\s]|Nota[:\s]|This |Here |The |I |Este |Esta |Corrigi|Changed|Fixed|The code|O c[oó]digo)/i;
114+
const lines = text.split('\n');
115+
let cutAt = lines.length;
116+
for (let i = lines.length - 1; i >= 0; i--) {
117+
const trimmed = lines[i].trim();
118+
if (!trimmed) continue;
119+
if (explanationStart.test(trimmed)) cutAt = i;
120+
else break;
121+
}
122+
text = lines.slice(0, cutAt).join('\n').trim();
123+
124+
// 4. Strip inline backtick wrapping: `code`
125+
if (/^`[^`]+`$/.test(text)) text = text.slice(1, -1);
126+
127+
return text || originalCode;
128+
}
129+
89130
async function runDeterministicAiExecution(env, language, code, stdin = '') {
90131
const systemPrompt = `Você é um interpretador/compilador e terminal puro para a linguagem ${language}. Seu único trabalho é ler o código fornecido, executá-lo mentalmente com precisão absoluta e retornar ESTRITAMENTE o que seria impresso no stdout ou stderr de uma IDE real. Não adicione saudações, explicações, comentários ou blocos de código em markdown (\`\`\`). Se houver erro de sintaxe ou execução, retorne exatamente a mensagem de erro padrão que o compilador/interpretador daquela linguagem daria no terminal.`;
91132
const userPrompt = stdin
@@ -144,17 +185,17 @@ async function fixCodeWithAi(env, language, code) {
144185
{
145186
role: 'system',
146187
content:
147-
`Você é um revisor de código para ${language}. REGRA FUNDAMENTAL: se o conteúdo fornecido NÃO for código válido em ${language} (por exemplo, uma frase em linguagem natural ou texto em prosa), retorne-o EXATAMENTE como está, sem nenhuma alteração. Se for código, corrija APENAS indentação incorreta, erros de sintaxe óbvios e typos em nomes de variáveis/funções. Não reescreva a lógica, não resolva o problema, não complete código faltando. Retorne SOMENTE o resultado final, sem explicações, sem prefixos como "Código corrigido:", e NUNCA use blocos markdown com \`\`\`.`
188+
`You are a strict ${language} code reviewer. Rules (follow exactly):\n1. If the input is NOT valid ${language} code (e.g. a natural-language sentence, a question, a description) — return it EXACTLY as received, no changes at all.\n2. If the input IS code — fix ONLY: obvious syntax errors, wrong indentation, typos in variable/function names. Do NOT rewrite logic, do NOT add features, do NOT complete missing code.\n3. Return ONLY the final code or unchanged text. Absolutely forbidden: prefixes like "Here is:", "Fixed:", "Código:", "Linguagem:"; trailing explanations; markdown fences (\`\`\`); any commentary.`
148189
},
149190
{
150191
role: 'user',
151-
content: `Linguagem: ${language}\n\nCódigo:\n${code}`
192+
content: code
152193
}
153194
]
154195
});
155196

156197
const raw = extractAiText(result).trim();
157-
return stripCodeFences(raw);
198+
return cleanAiResponse(raw, code);
158199
}
159200

160201
export default {

frontend/index.html

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -458,6 +458,11 @@
458458
return;
459459
}
460460

461+
if (!looksLikeCode(code)) {
462+
showOutput('⚠ O conteúdo no editor não parece ser código ' + language + '.\nEscreva ou cole um código válido antes de usar o Fix Code.', 'info');
463+
return;
464+
}
465+
461466
setEditorBusyState(true, 'Fixing code with AI...');
462467

463468
try {
@@ -507,6 +512,24 @@
507512
output.appendChild(pre);
508513
}
509514

515+
function looksLikeCode(text) {
516+
const t = text.trim();
517+
if (!t) return false;
518+
// Multiple lines → almost certainly code
519+
if (t.includes('\n')) return true;
520+
// Code symbols
521+
if (/[{}();\[\]=<>]/.test(t)) return true;
522+
// Common keywords across all supported languages
523+
if (/\b(?:def|class|function|func|var|let|const|if|else|for|while|return|import|from|include|using|print|console|echo|puts|printf|cout|scanf|int|str|bool|float|void|public|private|static|new|null|true|false|nil|end|do|then|elsif|elif|pass|lambda|async|await)\b/.test(t)) return true;
524+
// Function call: word(
525+
if (/\w+\s*\(/.test(t)) return true;
526+
// Comments
527+
if (/\/\/|\/\*|#\s*\w/.test(t)) return true;
528+
// Assignment: x = something
529+
if (/\w+\s*=\s*\S/.test(t)) return true;
530+
return false;
531+
}
532+
510533
// Language boilerplates with Hello CodePulse string
511534
const boilerplates = {
512535
python: "print('Hello CodePulse!')",

0 commit comments

Comments
 (0)