Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

MUL-8589: fix(service): keep backslashes in formatted agent output (#9917)

Jiayuan Zhang17582d160bc8
diff --git a/server/internal/service/quick_create_failure_detail_test.go b/server/internal/service/quick_create_failure_detail_test.go
index 773fd2cb3f..25ecc1a984 100644
--- a/server/internal/service/quick_create_failure_detail_test.go
+++ b/server/internal/service/quick_create_failure_detail_test.go
@@ -48,14 +48,35 @@ func TestQuickCreateFailureDetail(t *testing.T) {
}
})
- t.Run("literal backslash-n is decoded to real newlines", func(t *testing.T) {
+ t.Run("escaped paragraph breaks are decoded to real newlines", func(t *testing.T) {
t.Parallel()
- // The daemon may deliver an Output carrying 2-char `\n` sequences; they
- // must render as real line breaks, matching the comment-fallback path.
- result := []byte(`{"output":"line one\\nline two"}`)
+ // The daemon may deliver an Output that is one escaped blob with 2-char
+ // `\n\n` paragraph breaks; they must render as real line breaks,
+ // matching the comment-fallback path.
+ result := []byte(`{"output":"Error: duplicate issue.\\n\\nSee JKY-30."}`)
got := quickCreateFailureDetail(result)
- if got != "line one\nline two" {
- t.Fatalf("expected decoded newline, got %q", got)
+ if got != "Error: duplicate issue.\n\nSee JKY-30." {
+ t.Fatalf("expected decoded newlines, got %q", got)
+ }
+ })
+
+ t.Run("single-line path is not decoded", func(t *testing.T) {
+ t.Parallel()
+ out := `Error: cannot read C:\\tools\\node_modules\\repo`
+ want := `Error: cannot read C:\tools\node_modules\repo`
+ if got := quickCreateFailureDetail([]byte(`{"output":"` + out + `"}`)); got != want {
+ t.Fatalf("expected verbatim path\n got: %q\nwant: %q", got, want)
+ }
+ })
+
+ t.Run("backslashes in multi-line output pass through", func(t *testing.T) {
+ t.Parallel()
+ // GH #8845: once the output has real line breaks, `\t` and `\r` are
+ // content (here a Windows path), not escapes to decode.
+ result := []byte(`{"output":"Error: cannot read\nC:\\tools\\repo\\task.md"}`)
+ want := "Error: cannot read\nC:\\tools\\repo\\task.md"
+ if got := quickCreateFailureDetail(result); got != want {
+ t.Fatalf("expected verbatim output\n got: %q\nwant: %q", got, want)
}
})
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 016ce3fc20..4038101202 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -4789,11 +4789,10 @@ func (s *TaskService) CompleteTaskWithTransition(ctx context.Context, taskID pgt
var payload protocol.TaskCompletedPayload
if err := json.Unmarshal(result, &payload); err == nil {
if payload.Output != "" {
- // Match the CLI's --content / --description behavior: agents that
- // emit literal `\n` 4-char sequences (Python/JSON-style) get them
- // decoded into real newlines before the comment hits the DB. See
- // util.UnescapeBackslashEscapes for the exact contract.
- body := util.UnescapeBackslashEscapes(payload.Output)
+ // An agent that emitted its whole answer as one escaped blob gets
+ // its literal `\n` decoded; formatted output is stored verbatim.
+ // See util.DecodeEscapedAgentOutput for the exact contract.
+ body := util.DecodeEscapedAgentOutput(payload.Output)
if task.TriggerCommentID.Valid && isTrivialDoneOutput(body) {
slog.Warn("suppressing trivial comment-trigger fallback output",
"task_id", util.UUIDToString(task.ID),
@@ -4885,9 +4884,9 @@ func (s *TaskService) writeChatCompletionOutcome(ctx context.Context, qtx *db.Qu
// valid JSON; an empty Output is the only case this branch cares about.
var payload protocol.TaskCompletedPayload
_ = json.Unmarshal(result, &payload)
- // Same unescape as the issue-comment path: literal `\n` from agent stdout
- // becomes a real newline so the chat panel renders paragraph breaks.
- body := util.UnescapeBackslashEscapes(payload.Output)
+ // Same decoding as the issue-comment path: an escaped blob gets its
+ // paragraph breaks back, while LaTeX and paths in formatted replies survive.
+ body := util.DecodeEscapedAgentOutput(payload.Output)
// Strip any in-band quick-actions footer from EVERY chat completion — the
// reserved syntax must never reach a stored transcript. This includes the
// agent-initiated intro turn (chat_input_task_id NULL), which previously
@@ -8111,9 +8110,9 @@ func quickCreateFailureDetail(result []byte) string {
if err := json.Unmarshal(result, &payload); err != nil {
return ""
}
- // Same unescape as the comment-fallback path: literal `\n` sequences from
- // agent stdout become real newlines before the reason reaches the user.
- body := strings.TrimSpace(util.UnescapeBackslashEscapes(payload.Output))
+ // Same decoding as the comment-fallback path: an escaped blob's literal
+ // `\n` sequences become real newlines before the reason reaches the user.
+ body := strings.TrimSpace(util.DecodeEscapedAgentOutput(payload.Output))
if body == "" {
return ""
}
diff --git a/server/internal/service/task_output_backslash_test.go b/server/internal/service/task_output_backslash_test.go
new file mode 100644
index 0000000000..71a663d0aa
--- /dev/null
+++ b/server/internal/service/task_output_backslash_test.go
@@ -0,0 +1,125 @@
+package service
+
+import (
+ "context"
+ "encoding/json"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/testutil"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+)
+
+// GH #8845 / #9014: a formatted agent reply must reach storage byte-for-byte,
+// while a reply that arrived as one escaped blob still gets its paragraph
+// breaks back (GH #1820).
+var taskOutputBackslashCases = []struct {
+ name string
+ output string
+ want string
+}{
+ {
+ name: "latex",
+ output: "Formula:\n$a \\times b$, $\\theta$, $\\text{hi}$, $A^\\top$, $n \\neq 1$, $\\rho$",
+ want: "Formula:\n$a \\times b$, $\\theta$, $\\text{hi}$, $A^\\top$, $n \\neq 1$, $\\rho$",
+ },
+ {
+ name: "windows path",
+ output: "| Path |\n| --- |\n| `C:\\tools\\repo\\node_modules` |",
+ want: "| Path |\n| --- |\n| `C:\\tools\\repo\\node_modules` |",
+ },
+ {
+ name: "quoted escapes",
+ output: "Use `\\n` for a newline\nand `\\t` for a tab",
+ want: "Use `\\n` for a newline\nand `\\t` for a tab",
+ },
+ {
+ name: "single line latex",
+ output: `$a \times b \neq 0$ and $n \neq -1$`,
+ want: `$a \times b \neq 0$ and $n \neq -1$`,
+ },
+ {
+ name: "single line path",
+ output: `Error: cannot read C:\tools\node_modules\repo`,
+ want: `Error: cannot read C:\tools\node_modules\repo`,
+ },
+ {
+ name: "escaped blob",
+ output: `First paragraph with $a \times b$.\n\nSecond paragraph.`,
+ want: "First paragraph with $a \\times b$.\n\nSecond paragraph.",
+ },
+}
+
+func TestWriteChatCompletionOutcomeBackslashes(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceID, userID, agentID, _ := seedAttributionFixture(t, pool)
+ svc := &TaskService{Queries: q, TxStarter: pool}
+
+ for _, tc := range taskOutputBackslashCases {
+ t.Run(tc.name, func(t *testing.T) {
+ var chatSessionID, taskID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO chat_session (workspace_id, agent_id, creator_id)
+ VALUES ($1, $2, $3) RETURNING id`, workspaceID, agentID, userID).Scan(&chatSessionID); err != nil {
+ t.Fatalf("seed chat session: %v", err)
+ }
+ t.Cleanup(func() {
+ pool.Exec(context.Background(), `DELETE FROM chat_message WHERE chat_session_id = $1`, chatSessionID)
+ pool.Exec(context.Background(), `DELETE FROM chat_session WHERE id = $1`, chatSessionID)
+ })
+ if err := pool.QueryRow(ctx, `SELECT gen_random_uuid()::text`).Scan(&taskID); err != nil {
+ t.Fatalf("new task id: %v", err)
+ }
+
+ result, _ := json.Marshal(protocol.TaskCompletedPayload{Output: tc.output})
+ row, err := svc.writeChatCompletionOutcome(ctx, q, db.AgentTaskQueue{
+ ID: util.MustParseUUID(taskID),
+ ChatSessionID: util.MustParseUUID(chatSessionID),
+ AgentID: util.MustParseUUID(agentID),
+ }, result)
+ if err != nil {
+ t.Fatalf("writeChatCompletionOutcome: %v", err)
+ }
+ if row == nil {
+ t.Fatal("writeChatCompletionOutcome wrote no row")
+ }
+ var got string
+ if err := pool.QueryRow(ctx, `SELECT content FROM chat_message WHERE id = $1`, row.ID).Scan(&got); err != nil {
+ t.Fatalf("read chat message: %v", err)
+ }
+ if got != tc.want {
+ t.Errorf("stored chat content = %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
+
+func TestCompleteTaskFallbackCommentBackslashes(t *testing.T) {
+ f, s, issue, agent := conditionFixture(t)
+ ctx := context.Background()
+ f.Cleanup(t, "DELETE FROM comment WHERE issue_id=$1", issue)
+
+ for _, tc := range taskOutputBackslashCases {
+ t.Run(tc.name, func(t *testing.T) {
+ output, _ := json.Marshal(protocol.TaskCompletedPayload{Output: tc.output})
+ taskID := parseTestUUID(t, f.Task(t, agent, testutil.Cols{
+ "issue_id": issue,
+ "status": "running",
+ "started_at": testutil.Raw("now()"),
+ "context": "{}",
+ "runtime_id": testutil.Raw("(SELECT runtime_id FROM agent WHERE id='" + agent + "')"),
+ }))
+ if _, err := s.Tasks.CompleteTask(ctx, taskID, output, "", "", "", false, "", ""); err != nil {
+ t.Fatalf("CompleteTask: %v", err)
+ }
+ var got string
+ f.QueryRow(t, "SELECT content FROM comment WHERE issue_id=$1 AND source_task_id=$2", issue, taskID).Scan(&got)
+ if got != tc.want {
+ t.Errorf("stored fallback comment = %q, want %q", got, tc.want)
+ }
+ })
+ }
+}
diff --git a/server/internal/util/text.go b/server/internal/util/text.go
index 82aa65cd2b..6f05b540e6 100644
--- a/server/internal/util/text.go
+++ b/server/internal/util/text.go
@@ -11,8 +11,8 @@ import (
// (\n, \r, \t, \\) that LLM agents routinely emit as 4-character literals
// because Python/JSON-style string conventions are their default. The same
// helper is used by the CLI to fix bash-double-quote bodies (where the shell
-// doesn't expand \n) and by the daemon-task completion path to fix raw agent
-// stdout that arrives with literal `\n\n` between paragraphs.
+// doesn't expand \n). Agent task output uses the narrower
+// DecodeEscapedAgentOutput instead.
//
// Only \n / \r / \t / \\ are decoded. Other escape sequences (\d, \w, \s,
// \u, \0, \", etc.) pass through verbatim so regex literals and printf
@@ -52,6 +52,52 @@ func UnescapeBackslashEscapes(s string) string {
return b.String()
}
+// DecodeEscapedAgentOutput repairs agent output that arrived as one escaped
+// blob (GH #1820): no real line break anywhere, paragraphs joined by a literal
+// `\n\n`. Only that shape is decoded, and only its `\n` sequences become
+// newlines. Everything else is returned unchanged, because a backslash in
+// agent output is usually content: a single `\n` is also how `\neq` and
+// `C:\node_modules` begin, and `\t` / `\r` begin `\times` and `\rho`
+// (GH #8845, #9014). A `\\` pair is kept as written and never starts a `\n`.
+func DecodeEscapedAgentOutput(s string) string {
+ if strings.ContainsAny(s, "\n\r") || !hasEscapedParagraphBreak(s) {
+ return s
+ }
+ var b strings.Builder
+ b.Grow(len(s))
+ for i := 0; i < len(s); i++ {
+ if s[i] == '\\' && i+1 < len(s) {
+ switch s[i+1] {
+ case 'n':
+ b.WriteByte('\n')
+ i++
+ continue
+ case '\\':
+ b.WriteString(`\\`)
+ i++
+ continue
+ }
+ }
+ b.WriteByte(s[i])
+ }
+ return b.String()
+}
+
+// hasEscapedParagraphBreak reports whether s contains a literal `\n\n` whose
+// first backslash is not itself escaped.
+func hasEscapedParagraphBreak(s string) bool {
+ for i := 0; i+1 < len(s); i++ {
+ if s[i] != '\\' {
+ continue
+ }
+ if s[i+1] == 'n' && strings.HasPrefix(s[i+2:], `\n`) {
+ return true
+ }
+ i++
+ }
+ return false
+}
+
// sanitizeJSONMaxDepth bounds SanitizeJSONForPostgres's recursion. Task tool
// input is a handful of levels deep in practice; anything past this is either
// pathological or hostile, and is dropped rather than walked so a deeply
diff --git a/server/internal/util/text_test.go b/server/internal/util/text_test.go
index 96b6619c47..5a453a0acf 100644
--- a/server/internal/util/text_test.go
+++ b/server/internal/util/text_test.go
@@ -47,3 +47,38 @@ func TestUnescapeBackslashEscapes(t *testing.T) {
})
}
}
+
+func TestDecodeEscapedAgentOutput(t *testing.T) {
+ tests := []struct {
+ name string
+ in string
+ want string
+ }{
+ {"empty", "", ""},
+ {"plain single line", "done", "done"},
+ {"escaped blob is decoded", `para1\n\npara2\n- item`, "para1\n\npara2\n- item"},
+ {"escaped blob keeps tab and carriage-return commands", `$a \times b$, $\rho$\n\nnext`, "$a \\times b$, $\\rho$\n\nnext"},
+ {"escaped blob keeps escaped backslash pairs", `a \\neq b\n\nnext`, "a \\\\neq b\n\nnext"},
+ {"escaped backslash does not start a paragraph break", `C:\\n\n`, `C:\\n\n`},
+ {"single escaped newline is not a blob", `line one\nline two`, `line one\nline two`},
+ // GH #9014: single-line LaTeX and paths that begin with `\n`.
+ {"single line neq", `$n \neq -1$`, `$n \neq -1$`},
+ {"single line times and neq", `$a \times b \neq 0$`, `$a \times b \neq 0$`},
+ {"single line node_modules path", `Error: cannot read C:\tools\node_modules\repo`, `Error: cannot read C:\tools\node_modules\repo`},
+ // GH #8845 / #9014: formatted output carries content backslashes.
+ {"latex in formatted reply", "Result:\n$a \\times b$, \\theta, \\text{x}, \\top, \\neq, \\rho", "Result:\n$a \\times b$, \\theta, \\text{x}, \\top, \\neq, \\rho"},
+ {"windows path in formatted reply", "Path:\n`D:\\Data\\secrets\\read-link.env` and `C:\\tools\\node_modules`", "Path:\n`D:\\Data\\secrets\\read-link.env` and `C:\\tools\\node_modules`"},
+ {"quoted escape in formatted reply", "Use `\\n` for a newline\nand `\\t` for a tab", "Use `\\n` for a newline\nand `\\t` for a tab"},
+ {"crlf output untouched", "line1\r\n\\temp", "line1\r\n\\temp"},
+ {"single line latex without escaped newline", `$a \times b$ and \theta`, `$a \times b$ and \theta`},
+ {"single line windows path without escaped newline", `C:\tools\repo`, `C:\tools\repo`},
+ }
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ got := DecodeEscapedAgentOutput(tt.in)
+ if got != tt.want {
+ t.Errorf("DecodeEscapedAgentOutput(%q) = %q, want %q", tt.in, got, tt.want)
+ }
+ })
+ }
+}