From b2b454c563a5a094788b56d505fb212c1ac754ba Mon Sep 17 00:00:00 2001 From: Anders Holck Date: Wed, 27 May 2026 10:55:47 +0200 Subject: [PATCH] Fix AI edit mode: strip code fences, stronger prompt --- internal/api/ai.go | 21 +++++++++++++++++---- 1 file changed, 17 insertions(+), 4 deletions(-) diff --git a/internal/api/ai.go b/internal/api/ai.go index 2383769..2f11ffe 100644 --- a/internal/api/ai.go +++ b/internal/api/ai.go @@ -157,10 +157,11 @@ func (s *Server) handleAIChat(w http.ResponseWriter, r *http.Request) { var userMsg string if req.Mode == "edit" { - systemPrompt = `You are a document editor. The user will give you a markdown document and an instruction. -Apply the instruction to the document and return ONLY the complete updated document. -Do not add explanations, comments, or markdown code fences around the output. -Preserve the document's existing style and formatting.` + systemPrompt = "You are a document editor. The user will give you a markdown document and an instruction. " + + "Apply the instruction to the document and return ONLY the complete updated document. " + + "Do not add explanations, comments, or wrap the output in code fences. " + + "Do not prefix with any markers. Preserve the document's existing style and formatting. " + + "Return the raw markdown content only." userMsg = "Document:\n\n" + req.Content + "\n\nInstruction: " + req.Message } else { systemPrompt = `You are a helpful writing assistant. The user has a markdown document open and is asking a question about it. @@ -175,6 +176,18 @@ Answer concisely in markdown. Reference the document content when relevant.` } if req.Mode == "edit" { + // Strip markdown code fences if AI wrapped the output + response = strings.TrimSpace(response) + if strings.HasPrefix(response, "```") { + lines := strings.Split(response, "\n") + if len(lines) > 2 { + lines = lines[1:] // remove opening fence + if strings.TrimSpace(lines[len(lines)-1]) == "```" { + lines = lines[:len(lines)-1] // remove closing fence + } + response = strings.Join(lines, "\n") + } + } writeJSON(w, 200, map[string]string{"content": response}) } else { writeJSON(w, 200, map[string]string{"result": response})