diff --git a/internal/channels/telegram/richblocks.go b/internal/channels/telegram/richblocks.go index c92a95c61..38f8437c1 100644 --- a/internal/channels/telegram/richblocks.go +++ b/internal/channels/telegram/richblocks.go @@ -235,6 +235,12 @@ type markdownBlockParser struct { indented bool listItems [][]models.InputRichBlock quoteLines []string + // hardBreak records that the line just consumed ended in CommonMark's + // line-break marker, so the next line starts its own block. + hardBreak bool + // tightNext suppresses the spacer before the next block, keeping the + // lines of one hard-broken stanza visually together. + tightNext bool } // handleLine processes one line of input, dispatching to whichever @@ -283,15 +289,44 @@ func (p *markdownBlockParser) handleLine(line string) { // nothing, jamming the two lines together with no separator // whatsoever. A space is the correct soft-break rendering anyway // and survives regardless of how the client treats a literal "\n". + // + // A line that ended in a hard break is the exception: the producer + // said it is a line, so it closes its own block and the next one + // hugs it. Line-oriented reports (/status, /tasks) depend on this; + // without it every one of their lines soft-joined into one run-on + // paragraph (archie-core-8cda.6.10). p.flushList() p.flushQuote() - if p.paragraph.Len() > 0 { + switch { + case p.hardBreak: + p.flushParagraph() + p.tightNext = true + case p.paragraph.Len() > 0: p.paragraph.WriteString(" ") } - p.paragraph.WriteString(trimmed) + p.hardBreak = endsWithHardBreak(line) + p.paragraph.WriteString(trimHardBreak(trimmed)) } } +// endsWithHardBreak reports whether line carries CommonMark's line-break +// marker: two or more trailing spaces, or a trailing backslash. +func endsWithHardBreak(line string) bool { + if strings.TrimSpace(line) == "" { + return false + } + if strings.HasSuffix(strings.TrimRight(line, " \t"), "\\") { + return true + } + return strings.HasSuffix(line, " ") +} + +// trimHardBreak removes a trailing backslash marker, which unlike trailing +// spaces would otherwise survive into the rendered text. +func trimHardBreak(trimmed string) string { + return strings.TrimRight(strings.TrimSuffix(trimmed, "\\"), " ") +} + // consumeCodeLine handles one line while a code block is open, reporting // whether that block claimed it. A fenced block ends at its closing fence; an // indented block ends at the first non-indented, non-blank line, which is not @@ -338,13 +373,18 @@ func (p *markdownBlockParser) flush() { // makes that gap explicit instead of relying on client-side spacing that // doesn't exist. func (p *markdownBlockParser) appendBlock(block models.InputRichBlock) { - if len(p.blocks) > 0 && p.blocks[len(p.blocks)-1].Type != models.RichBlockTypeSectionHeading { + tight := p.tightNext + p.tightNext = false + if !tight && len(p.blocks) > 0 && p.blocks[len(p.blocks)-1].Type != models.RichBlockTypeSectionHeading { p.blocks = append(p.blocks, paragraphBlock("")) } p.blocks = append(p.blocks, block) } func (p *markdownBlockParser) flushParagraph() { + // A pending hard break belongs to the paragraph being closed. Left set, it + // would make the next block hug whatever came before a blank line. + p.hardBreak = false if p.paragraph.Len() == 0 { return } diff --git a/internal/channels/telegram/richblocks_test.go b/internal/channels/telegram/richblocks_test.go index 4023d3698..34cf13c11 100644 --- a/internal/channels/telegram/richblocks_test.go +++ b/internal/channels/telegram/richblocks_test.go @@ -382,3 +382,82 @@ func TestMarkdownToBlocksFencedCodeIsVerbatim(t *testing.T) { t.Errorf("fenced code was altered:\n got %q\nwant %q", got, body) } } + +// TestMarkdownToBlocksHardLineBreak is the regression case for a chat report +// arriving as one run-on line. /status and /tasks are line-oriented: every +// newline is a real break, not CommonMark's soft wrap. Rendered without hard +// breaks, "Runtime\nProvider: X\nModel: Y" reached Telegram as +// "Runtime Provider: X Model: Y", and a task's title, state and park reason +// were jammed into a single line each. +func TestMarkdownToBlocksHardLineBreak(t *testing.T) { + blocks := markdownToBlocks("Runtime \nProvider: DeepSeek \nModel: deepseek/flash") + + var texts []string + for _, b := range blocks { + texts = append(texts, blockText(b)) + } + want := []string{"Runtime", "Provider: DeepSeek", "Model: deepseek/flash"} + if len(texts) != len(want) { + t.Fatalf("blocks = %d (%v), want %d lines each as its own block", len(texts), texts, len(want)) + } + for i, w := range want { + if texts[i] != w { + t.Errorf("block[%d] = %q, want %q", i, texts[i], w) + } + } +} + +// TestMarkdownToBlocksHardBreakKeepsTheStanzaTight pins that hard-broken lines +// stay one visual stanza: the spacer paragraph that separates unrelated blocks +// must not be inserted between lines the producer marked as continuing. +func TestMarkdownToBlocksHardBreakKeepsTheStanzaTight(t *testing.T) { + blocks := markdownToBlocks("First line \nSecond line\n\nNew stanza") + + texts := make([]string, 0, len(blocks)) + for _, b := range blocks { + texts = append(texts, blockText(b)) + } + want := []string{"First line", "Second line", "", "New stanza"} + if len(texts) != len(want) { + t.Fatalf("blocks = %v, want %v", texts, want) + } + for i, w := range want { + if texts[i] != w { + t.Errorf("block[%d] = %q, want %q", i, texts[i], w) + } + } +} + +// TestMarkdownToBlocksSoftWrapStillJoins pins that ordinary prose is +// unaffected: a model's wrapped paragraph must not become ragged lines just +// because the reports now ask for hard breaks. +func TestMarkdownToBlocksSoftWrapStillJoins(t *testing.T) { + blocks := markdownToBlocks("A wrapped sentence\ncontinues here.") + if len(blocks) != 1 { + t.Fatalf("blocks = %d, want 1 joined paragraph", len(blocks)) + } + if got := blockText(blocks[0]); got != "A wrapped sentence continues here." { + t.Errorf("paragraph = %q, want the two lines joined with a space", got) + } +} + +// TestMarkdownToBlocksHardBreakDoesNotLeakPastABlankLine pins that a stanza's +// last line does not pull the next stanza up against it. The hard break +// belongs to the paragraph it closed, not to the document. +func TestMarkdownToBlocksHardBreakDoesNotLeakPastABlankLine(t *testing.T) { + blocks := markdownToBlocks("Line one \n\nLine two") + + texts := make([]string, 0, len(blocks)) + for _, b := range blocks { + texts = append(texts, blockText(b)) + } + want := []string{"Line one", "", "Line two"} + if len(texts) != len(want) { + t.Fatalf("blocks = %v, want %v (a spacer between the two stanzas)", texts, want) + } + for i, w := range want { + if texts[i] != w { + t.Errorf("block[%d] = %q, want %q", i, texts[i], w) + } + } +} diff --git a/internal/gateway/gateway.go b/internal/gateway/gateway.go index 25b05e570..0053d0677 100644 --- a/internal/gateway/gateway.go +++ b/internal/gateway/gateway.go @@ -624,6 +624,38 @@ func (r *Router) handleTasks(ctx context.Context) (string, error) { return formatTasks(tasks, time.Now()), nil } +// reportLineBreak ends a line of a line-oriented report. A chat report is a +// list of facts, not prose, so every one of its newlines is a real break; +// plain "\n" is CommonMark's soft wrap, which a Markdown-rendering channel +// joins into one run-on paragraph (see the Telegram renderer's +// markdownBlockParser). +const reportLineBreak = " \n" + +// parkReasonMaxRunes bounds the park reason shown per task. A reason carries +// whatever the failing stage reported, which for a lint or test gate is a +// whole tool log; unbounded, one parked task pushes every other task out of +// the reply. +const parkReasonMaxRunes = 160 + +// summarizeParkReason reduces a park reason to one readable line: the first +// non-empty line, bounded. The full reason stays on the task, which /task and +// the dashboard show in full -- this is the list view. +func summarizeParkReason(reason string) string { + line := reason + if first, _, ok := strings.Cut(reason, "\n"); ok { + line = first + } + line = strings.TrimSpace(line) + if line == "" { + line = strings.TrimSpace(reason) + } + runes := []rune(line) + if len(runes) <= parkReasonMaxRunes { + return line + } + return strings.TrimSpace(string(runes[:parkReasonMaxRunes])) + "..." +} + // formatTasks renders each task with enough identity and state to act on // it: id, title, status, workflow/stage, and age since its last // transition -- so a task that is running but stuck (old UpdatedAt) reads @@ -642,7 +674,7 @@ func formatTasks(tasks []ChatTaskSummary, now time.Time) string { if d, ok := taskStateDisplays[t.Status]; ok { icon, label = d.icon, d.label } - fmt.Fprintf(&b, "%s #%d %s\n", icon, t.ID, t.Title) + fmt.Fprintf(&b, "%s #%d %s%s", icon, t.ID, t.Title, reportLineBreak) fmt.Fprintf(&b, " %s", label) if stage := workflowStage(t.Workflow, t.Stage); stage != "" { fmt.Fprintf(&b, " ยท %s", stage) @@ -653,10 +685,10 @@ func formatTasks(tasks []ChatTaskSummary, now time.Time) string { if age := relativeAge(t.UpdatedAt, now); age != "" { fmt.Fprintf(&b, " ยท updated %s", age) } - b.WriteString("\n") if t.Status == taskstate.Parked && t.ParkReason != "" { - fmt.Fprintf(&b, " โ†ณ %s\n", t.ParkReason) + fmt.Fprintf(&b, "%s โ†ณ %s", reportLineBreak, summarizeParkReason(t.ParkReason)) } + b.WriteString("\n\n") } return strings.TrimSpace(b.String()) } @@ -796,19 +828,22 @@ func extractRuntimeInfo(models ModelManager) (provider, model string) { return formatProviderName(provider), model } +// formatRuntimeSection appends the active provider and model as two more +// report lines. They are not given a section header of their own: /status is +// four facts, and a header for the last two made a short report read like a +// document. func formatRuntimeSection(b *strings.Builder, provider, model string) { - b.WriteString("\nRuntime\n") if provider == "" && model == "" { - b.WriteString("Not configured\n") + b.WriteString("Runtime: not configured") return } if provider == "" { - provider = "Not configured" + provider = "not configured" } if model == "" { - model = "Not configured" + model = "not configured" } - fmt.Fprintf(b, "Provider: %s\nModel: %s\n", provider, model) + fmt.Fprintf(b, "Provider: %s%sModel: %s", provider, reportLineBreak, model) } // formatStatus formats daemon health into a clean, mobile-friendly summary. @@ -819,11 +854,12 @@ func formatStatus(counts map[string]int, models ModelManager) string { var b strings.Builder b.WriteString("๐Ÿ“Š Archie status\n\n") b.WriteString(formatQueueDepth(counts)) + b.WriteString(reportLineBreak) provider, model := extractRuntimeInfo(models) formatRuntimeSection(&b, provider, model) - return strings.TrimSpace(b.String()) + return b.String() } // formatQueueDepth summarizes in-flight work as one line: how many tasks @@ -836,7 +872,7 @@ func formatQueueDepth(counts map[string]int) string { parked := counts[taskstate.Parked] inFlight := running + waiting + parked if inFlight == 0 { - return "Queue: idle\n" + return "Queue: idle" } var parts []string if running > 0 { @@ -848,7 +884,7 @@ func formatQueueDepth(counts map[string]int) string { if parked > 0 { parts = append(parts, fmt.Sprintf("%d parked", parked)) } - return fmt.Sprintf("Queue: %d in flight (%s)\n", inFlight, strings.Join(parts, ", ")) + return fmt.Sprintf("Queue: %d in flight (%s)", inFlight, strings.Join(parts, ", ")) } func (r *Router) handleWhoami() (string, error) { diff --git a/internal/gateway/gateway_test.go b/internal/gateway/gateway_test.go index 36dca0549..06cce95a3 100644 --- a/internal/gateway/gateway_test.go +++ b/internal/gateway/gateway_test.go @@ -33,7 +33,7 @@ func TestRouteStatusShowsQueueDepthNotPerTaskCounts(t *testing.T) { } // queued and pr_open are not "in flight" (running/waiting/parked), so // /status reports the daemon idle -- that per-task detail is /tasks' job. - want := "๐Ÿ“Š Archie status\n\nQueue: idle\n\nRuntime\nNot configured" + want := "๐Ÿ“Š Archie status\n\nQueue: idle \nRuntime: not configured" if reply != want { t.Errorf("reply =\n%q\nwant:\n%q", reply, want) } @@ -51,7 +51,7 @@ func TestRouteStatusIncludesActiveProviderAndModel(t *testing.T) { if err != nil { t.Fatal(err) } - want := "๐Ÿ“Š Archie status\n\nQueue: 1 in flight (1 running)\n\nRuntime\nProvider: OpenAI\nModel: openai/gpt-5.6" + want := "๐Ÿ“Š Archie status\n\nQueue: 1 in flight (1 running) \nProvider: OpenAI \nModel: openai/gpt-5.6" if reply != want { t.Fatalf("reply =\n%q\nwant:\n%q", reply, want) } @@ -74,7 +74,7 @@ func TestRouteStatusEmpty(t *testing.T) { if err != nil { t.Fatalf("Route: %v", err) } - want := "๐Ÿ“Š Archie status\n\nQueue: idle\n\nRuntime\nNot configured" + want := "๐Ÿ“Š Archie status\n\nQueue: idle \nRuntime: not configured" if reply != want { t.Errorf("reply = %q, want %q", reply, want) } @@ -104,7 +104,7 @@ func TestFormatStatus(t *testing.T) { models: &fakeProviderModelManager{ activeModel: "openai/gpt-5.6-luna", }, - want: "๐Ÿ“Š Archie status\n\nQueue: 2 in flight (2 parked)\n\nRuntime\nProvider: OpenAI\nModel: openai/gpt-5.6-luna", + want: "๐Ÿ“Š Archie status\n\nQueue: 2 in flight (2 parked) \nProvider: OpenAI \nModel: openai/gpt-5.6-luna", }, { name: "in-flight states reduce to one aggregate line; queued and terminal states are excluded", @@ -123,7 +123,7 @@ func TestFormatStatus(t *testing.T) { models: &fakeProviderModelManager{ activeModel: "deepseek/deepseek-v4-pro", }, - want: "๐Ÿ“Š Archie status\n\nQueue: 6 in flight (1 running, 2 waiting on you, 3 parked)\n\nRuntime\nProvider: DeepSeek\nModel: deepseek/deepseek-v4-pro", + want: "๐Ÿ“Š Archie status\n\nQueue: 6 in flight (1 running, 2 waiting on you, 3 parked) \nProvider: DeepSeek \nModel: deepseek/deepseek-v4-pro", }, { name: "empty task counts with active model", @@ -131,7 +131,7 @@ func TestFormatStatus(t *testing.T) { models: &fakeModelManager{ activeModel: "anthropic/claude-3-5-sonnet", }, - want: "๐Ÿ“Š Archie status\n\nQueue: idle\n\nRuntime\nProvider: Anthropic\nModel: anthropic/claude-3-5-sonnet", + want: "๐Ÿ“Š Archie status\n\nQueue: idle \nProvider: Anthropic \nModel: anthropic/claude-3-5-sonnet", }, { name: "nil counts with active model", @@ -139,19 +139,19 @@ func TestFormatStatus(t *testing.T) { models: &fakeModelManager{ activeModel: "google/gemini-2.5-flash", }, - want: "๐Ÿ“Š Archie status\n\nQueue: idle\n\nRuntime\nProvider: Google\nModel: google/gemini-2.5-flash", + want: "๐Ÿ“Š Archie status\n\nQueue: idle \nProvider: Google \nModel: google/gemini-2.5-flash", }, { name: "nil model manager", counts: map[string]int{"running": 2}, models: nil, - want: "๐Ÿ“Š Archie status\n\nQueue: 2 in flight (2 running)\n\nRuntime\nNot configured", + want: "๐Ÿ“Š Archie status\n\nQueue: 2 in flight (2 running) \nRuntime: not configured", }, { name: "empty counts and nil model manager", counts: map[string]int{}, models: nil, - want: "๐Ÿ“Š Archie status\n\nQueue: idle\n\nRuntime\nNot configured", + want: "๐Ÿ“Š Archie status\n\nQueue: idle \nRuntime: not configured", }, { name: "custom display namer interface", @@ -159,7 +159,7 @@ func TestFormatStatus(t *testing.T) { models: &fakeCustomDisplayNamerManager{ activeModel: "openai/gpt-5.6", }, - want: "๐Ÿ“Š Archie status\n\nQueue: 1 in flight (1 running)\n\nRuntime\nProvider: OpenAI Custom Enterprise\nModel: openai/gpt-5.6", + want: "๐Ÿ“Š Archie status\n\nQueue: 1 in flight (1 running) \nProvider: OpenAI Custom Enterprise \nModel: openai/gpt-5.6", }, { name: "queued-only counts as idle -- queued is not in flight", @@ -167,7 +167,7 @@ func TestFormatStatus(t *testing.T) { models: &fakeProviderModelManager{ activeModel: "", }, - want: "๐Ÿ“Š Archie status\n\nQueue: idle\n\nRuntime\nNot configured", + want: "๐Ÿ“Š Archie status\n\nQueue: idle \nRuntime: not configured", }, { name: "model without slash and no provider manager", @@ -175,7 +175,7 @@ func TestFormatStatus(t *testing.T) { models: &fakeModelManager{ activeModel: "custom-local-model", }, - want: "๐Ÿ“Š Archie status\n\nQueue: 1 in flight (1 running)\n\nRuntime\nProvider: Not configured\nModel: custom-local-model", + want: "๐Ÿ“Š Archie status\n\nQueue: 1 in flight (1 running) \nProvider: not configured \nModel: custom-local-model", }, } @@ -252,14 +252,14 @@ func TestFormatTasks(t *testing.T) { tasks: []ChatTaskSummary{ {ID: 42, Title: "Fix login bug", Status: taskstate.Running, Workflow: "tdd", Stage: "implement", UpdatedAt: now.Add(-3 * time.Minute)}, }, - want: "๐Ÿ—‚ Archie tasks\n\nโ–ถ #42 Fix login bug\n Running ยท tdd/implement ยท updated 3m ago", + want: "๐Ÿ—‚ Archie tasks\n\nโ–ถ #42 Fix login bug \n Running ยท tdd/implement ยท updated 3m ago", }, { name: "parked task shows its reason", tasks: []ChatTaskSummary{ {ID: 17, Title: "Add dark mode", Status: taskstate.Parked, Workflow: "feasibility", ParkReason: "gate failed 3x", UpdatedAt: now.Add(-2 * time.Hour)}, }, - want: "๐Ÿ—‚ Archie tasks\n\nโธ #17 Add dark mode\n Parked ยท feasibility ยท updated 2h ago\n โ†ณ gate failed 3x", + want: "๐Ÿ—‚ Archie tasks\n\nโธ #17 Add dark mode \n Parked ยท feasibility ยท updated 2h ago \n โ†ณ gate failed 3x", }, { name: "attempt is shown only once a retry has happened", @@ -267,14 +267,14 @@ func TestFormatTasks(t *testing.T) { {ID: 1, Title: "First try", Status: taskstate.Running, Attempt: 1, UpdatedAt: now}, {ID: 2, Title: "Retried", Status: taskstate.Running, Attempt: 2, UpdatedAt: now}, }, - want: "๐Ÿ—‚ Archie tasks\n\nโ–ถ #1 First try\n Running ยท updated just now\nโ–ถ #2 Retried\n Running ยท attempt 2 ยท updated just now", + want: "๐Ÿ—‚ Archie tasks\n\nโ–ถ #1 First try \n Running ยท updated just now\n\nโ–ถ #2 Retried \n Running ยท attempt 2 ยท updated just now", }, { name: "an unrecognized status still renders, generically", tasks: []ChatTaskSummary{ {ID: 9, Title: "Mystery", Status: "custom_state", UpdatedAt: now}, }, - want: "๐Ÿ—‚ Archie tasks\n\nโ€ข #9 Mystery\n Custom state ยท updated just now", + want: "๐Ÿ—‚ Archie tasks\n\nโ€ข #9 Mystery \n Custom state ยท updated just now", }, { name: "actionable work leads terminal work regardless of recency", @@ -282,7 +282,7 @@ func TestFormatTasks(t *testing.T) { {ID: 3, Title: "Just merged", Status: taskstate.Merged, UpdatedAt: now}, {ID: 4, Title: "Still running", Status: taskstate.Running, UpdatedAt: now.Add(-time.Hour)}, }, - want: "๐Ÿ—‚ Archie tasks\n\nโ–ถ #4 Still running\n Running ยท updated 1h ago\nโœ… #3 Just merged\n Merged ยท updated just now", + want: "๐Ÿ—‚ Archie tasks\n\nโ–ถ #4 Still running \n Running ยท updated 1h ago\n\nโœ… #3 Just merged \n Merged ยท updated just now", }, } @@ -1125,3 +1125,36 @@ func TestLocalCommandSpecsAndCommandsAgree(t *testing.T) { } } } + +// TestSummarizeParkReasonBoundsAToolLog is the regression case for a single +// parked task swamping /tasks. A gate failure parks the task with the tool's +// whole output -- Sam's #10 carried a multi-line golangci-lint dump, warnings +// and all -- which the list view rendered verbatim, pushing every other task +// out of the reply. +func TestSummarizeParkReasonBoundsAToolLog(t *testing.T) { + reason := "stage fix: agent parked (gate_parked): [golangci-lint] golangci-lint run ./...\n" + + "level=warning msg=\"[formatter] gofumpt: extra-rules is deprecated\"\n" + + "scratchverify/main.go:38:1: calculated cyclomatic complexity for function run is 16, max is 15 (cyclop)\n" + + "1 issues:\n- cyclop: 1" + + got := summarizeParkReason(reason) + if strings.ContainsAny(got, "\n\r") { + t.Fatalf("summarizeParkReason() = %q, want a single line", got) + } + if len([]rune(got)) > parkReasonMaxRunes+3 { + t.Fatalf("summarizeParkReason() is %d runes, want at most %d plus the ellipsis", + len([]rune(got)), parkReasonMaxRunes) + } + if !strings.HasPrefix(got, "stage fix: agent parked") { + t.Fatalf("summarizeParkReason() = %q, want it to keep the leading reason", got) + } +} + +// TestSummarizeParkReasonKeepsAShortReasonIntact pins that the common case -- +// a one-line reason an operator can act on -- is passed through untouched. +func TestSummarizeParkReasonKeepsAShortReasonIntact(t *testing.T) { + const reason = "diff is 789 changed lines (cap 400) -- split the issue or approve manually" + if got := summarizeParkReason(reason); got != reason { + t.Fatalf("summarizeParkReason() = %q, want it unchanged", got) + } +}