Skip to content

Don't write word-wrap escape sequences when stdout is not a terminal#16840

Open
markymarkburt wants to merge 1 commit into
ollama:mainfrom
markymarkburt:fix-redirect-ansi-escapes
Open

Don't write word-wrap escape sequences when stdout is not a terminal#16840
markymarkburt wants to merge 1 commit into
ollama:mainfrom
markymarkburt:fix-redirect-ansi-escapes

Conversation

@markymarkburt

Copy link
Copy Markdown

What

ollama run <model> "<prompt>" > out.txt writes terminal escape sequences into out.txt. The file ends up with cursor-control codes (\x1b[<n>D, \x1b[K) instead of clean text.

Fixes #16785

Cause

displayResponse asks for the terminal width and, when term.GetSize fails (which is what happens when stdout is a file or pipe, not a TTY), falls back to an 80-column width:

termWidth, _, _ := term.GetSize(int(os.Stdout.Fd()))
if termWidth == 0 {
    termWidth = 80
}
if wordWrap && termWidth >= 10 {
    // ... emits \x1b[..D / \x1b[K cursor-control sequences for wrapping

So even with no real terminal, the word-wrap branch was taken and its cursor-control sequences were written into the redirected output.

Fix

Word-wrapping only makes sense on a real terminal, so only take that branch when term.GetSize succeeds. When stdout is redirected, fall through to the existing plain-text branch — no escape sequences.

termWidth, _, err := term.GetSize(int(os.Stdout.Fd()))
if wordWrap && err == nil && termWidth >= 10 {

Interactive terminal behavior is unchanged (GetSize succeeds there and returns the real width).

Test

TestDisplayResponseNoEscapesWhenNotATTY redirects stdout to a pipe (not a TTY), renders content that would wrap on a terminal, and asserts the output is the plain text with no escape sequences. It fails before this change and passes after.

displayResponse fell back to an 80-column width when term.GetSize failed,
so `ollama run model "prompt" > file` still took the word-wrap path and
wrote cursor-control escape sequences into the redirected file. Only
word-wrap on a real terminal; otherwise emit plain text.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

'ollama run xx > some-file' should fail instead of writing terminal sequences into the file

1 participant