Skip to content

ANSI codes possible in JSON when stdout detection fails #1956

Description

@Widthdom

Summary

ConsoleUi.ColorizeKind (src/CodeIndex/Cli/ConsoleUi.cs:818-841) emits ANSI escape codes conditionally on ShouldUseInteractiveConsole(). That helper's check is !Console.IsOutputRedirected && !Console.Out.Encoding.Equals(Encoding.Unicode). The UTF-16 check defends against test StringWriter capture, but in some container/test environments Console.Out ends up wrapped in a custom encoder that passes both gates, allowing ANSI codes to leak into --json output. Any JSON parser then chokes on "\x1b[36mclass\x1b[0m" strings.

Where

  • src/CodeIndex/Cli/ConsoleUi.cs:843-851 (ShouldUseInteractiveConsole heuristic)
  • src/CodeIndex/Cli/ConsoleUi.cs:818-841 (ColorizeKind output)
  • src/CodeIndex/Cli/QueryCommandRunner.cs:837 (one of many call sites)

Suggested approach

  1. Thread options.Json into ColorizeKind so JSON-mode callers always receive unstyled text.
  2. Alternatively, set a thread-local ColorMode in ProgramRunner after argument parsing and consult it before any styled output.
  3. In --json paths, never invoke ColorizeKind at all (skip styling entirely).
  4. Add a unit test that calls ColorizeKind under JSON mode and asserts no \x1b byte appears.
  5. Add an end-to-end test piping --json output through JsonDocument.Parse to catch regressions.
  6. Document the JSON-mode invariant in DEVELOPER_GUIDE.md.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions