Skip to content

fix(cli): escape control characters at the CLI's stdout and stderr writes - #4778

Merged
thymikee merged 13 commits into
mainfrom
fix/cli-terminal-safe-output
Nov 20, 2026
Merged

thymikee merged 13 commits into
mainfrom
fix/cli-terminal-safe-output

Conversation

@thymikee

@thymikee thymikee commented Nov 19, 2026 •

Copy link
Copy Markdown
Member

Summary

Text the CLI prints can name values that a device or a remote daemon chose. Every CLI write now escapes C0 (except newline and tab), DEL and C1 as \u00NN. That form is also a JSON escape, so any JSON the CLI prints, with or without --json, still parses back to the exact values.

  • Design: values stay raw (data, --json, files, JUnit) until a display line is built.
    • The cli zone writes through src/cli/process-exit.ts, and lower zones apply escapeTerminalText from kernel/redaction themselves.
    • Only intended color and cursor codes are written raw: colored diffs, proxy startup, the doctor summary, and the replay reporter's own codes.
  • Paths covered:
    • every formatter, warning line and error, including details;
    • the replay test reporter (escaped values, checked counters, single-row live lines, command progress on its own row, written only by the built-in reporter);
    • upload progress through the CLI's progress sink;
    • the proxy takeover notice through a structured onTakeover callback;
    • --debug diagnostics;
    • agent-cdp child output (a verbatim opt-in can follow if someone needs it);
    • streamed doctor lines, via an additive optional marker on CommandProgressEvent with a ledger ack; the CLI colors the marker after escaping.
  • Warning lines: every warning folds to one Warning: line. Formatters never print response warnings: the dispatcher prints each one exactly once, on stderr for a parseable-output command such as record. Effects you can see:
    • record warnings go to stderr, not into the stdout path.
    • snapshot warnings come after the tree as Warning: lines, not as plain lines above it.
    • open warnings come after the --foreground snapshot tree, not right after Opened:. The nested snapshot warnings print once, after the tree and before the open warnings.
  • Docs: the command reference documents the \u00NN form, the layout rule, and the MCP and AI SDK text.

Split out of #4744, which stays a remote-only change. 63 files, +1553/−294 (production about +440/−240 across 37 files).

Validation

At b2b83cb50c:

  • End-to-end tests cover each surface: open, snapshot, snapshot diff, screenshot, close, get attrs, --json, errors, the replay reporter (TTY live row, malformed counters, JUnit exactness, trace lookup), upload progress, the takeover notice, doctor, debug, record, replay export, agent-cdp and --debug diagnostics.
  • Mutations: each fix has a test that fails when it is reverted.
  • Suites: src, command-output, kernel, remote, daemon-client, daemon sessions, host-kit and wire-compat (19,154 tests) and the eager-closure check pass.
  • Gates: typecheck, lint, check:layering, fallow audit --base origin/main and check:production-exports are clean.

CI validates the head.

🤖 Generated with Claude Code


Autofix with [code]smith
Open in [code]smith · Need help on this PR? Tag @codesmith-bot with what you need.

View guided diff Turn on auto-fix

@github-actions

github-actions Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Size Report

Metric Base Current Diff
Installed (including dependencies) 6.44 MB 6.45 MB +2.4 kB
Package (unpacked) 6.44 MB 6.45 MB +2.4 kB
Package (download) 1.96 MB 1.96 MB +924 B

Startup median (7 runs, lower is better):

Scenario Base Current Diff
CLI --version 22.3 ms 24.0 ms +1.7 ms
CLI --help 46.8 ms 49.5 ms +2.8 ms

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

An independent correctness pass over bfda653, to fold in with the test reporter fix you are already making. The shared writer is the right boundary, and the standard response paths (default open, close, batch, snapshot bodies, screenshot summaries, CLI errors and debug details) go through it correctly. Seven paths still do not, so no label yet:

  1. JSON printed without --json can become invalid. get attrs (interaction/output.ts:25) serializes with plain JSON.stringify, so a DEL or C1 character from the device stays literal and the text writer then turns it into \xNN, which JSON.parse rejects. Plain find node output, session list, non-reload Metro results and the JSON object lines in snapshot --raw follow the same pattern. Serialize each structured payload with the terminal JSON serializer before the text writer, keeping the existing indentation (compact for snapshot --raw).
  2. The built-in replay test reporter (replay-test/reporting.ts:90) writes daemon-supplied titles, result messages, warnings and failure lines through a verbatim writer. On a TTY the live renderer also counts tabs and newlines as one column, so a multi-row title leaves stale text after a redraw. Escape untrusted fields before composing and styling, keep live progress fields on one row before measuring, and reserve raw writes for the renderer's own color and cursor codes. (This is the one you are already fixing.)
  3. Proxy startup (proxy.ts:125) always uses the raw writer; with color off, the configured token is printed verbatim. Use the ordinary writer for uncolored output.
  4. Remote upload progress (upload-progress.ts:67) prints the local artifact basename straight to stderr. Pass the CLI's terminal-safe progress sink into remote artifact preparation and keep the structured events for SDK consumers.
  5. The daemon takeover notice (daemon-client-startup.ts:263) writes the state directory and version to stderr directly on the proxy path, bypassing the escaped onReplaced callback. Route it through a callback with structured fields.
  6. doctor shows its own color codes as \x1b[... (management/output.ts:231): the summary line inserts ANSI markers and the shared writer then escapes them. The streamed path does the same when the daemon enables color (command-progress.ts:19). Send status as structured data and add color at the CLI after escaping the values.
  7. Capture warnings can still start new lines. The screenshot formatter (screenshot.ts:50) and the snapshot and snapshot-diff notice paths do not fold embedded newlines, while the new docs (commands.md:35) promise one line per warning. Fold newlines in each capture warning at its text renderer.

Not blocking:

  • stringifyTerminalJson allocates per character. On a 4.5 MB ASCII payload it takes about 129 ms against 3 ms for JSON.stringify, and about 239 ms with both passes at --level full. A fast path that returns early when the input has no DEL or C1 would remove most of that.
  • The new tests call handlers with captured streams. One test that runs the built CLI binary and asserts on its real stdout would catch a future direct write.
  • Fast help (bin.ts:34, :37) and agent-cdp child output (agent-cdp.ts:91) still write directly. The first is built-in text, and the second is a documented exception, so a short note in the docs is enough.
  • MCP framing and SDK data keep their own contracts, correctly.

@thymikee

Copy link
Copy Markdown
Member Author

One more point on bfda653, from the line-by-line review, that would simplify the fix for item 1 in the comment above.

Make the writer's escape valid inside JSON strings. Today escapeTerminalText emits \xNN, which is not a JSON escape, so every formatter that prints JSON has to remember to call stringifyTerminalJson first. get --format attrs, find, snapshot --raw, session list and Metro don't, which is item 1. A label like Pay\u009bnow prints as "Pay\x9bnow", and JSON.parse throws. If the writer emitted \u00NN for every character it escapes instead, any JSON text passing through it would still parse to the exact values. Then stringifyTerminalJson and its four call sites (generic.ts:51, screenshot.ts:34, error.ts:166, json.ts:8) could go, printJson could use the same writer as everything else, and no formatter would need to know about escaping. Proxy could drop terminalSafe too, leaving the raw path only for the two diff formatters. The cost is that text shows \u001b rather than \x1b, which is one doc sentence. Please add a test through the get attrs route with a C1 label that asserts JSON.parse returns the exact node.

The review also confirmed item 7: the screenshot default handler (screenshot.ts:45-51) and replay export warnings (replay.ts:62) skip appendWarningLinesText, so a multi-line warning prints as several unprefixed lines, although commands.md:35 promises one Warning: line each. Routing them through appendWarningLinesText, and extending the screenshot default test with a multi-line warning, would make the doc true.

Not blocking: escapeTerminalText (success-text.ts:49) builds the string one code point at a time on every write, so return the input unchanged when /[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/ does not match. The control-character predicate is also re-declared in three test files and in stringifyTerminalJson, so export one and reuse it. The process-exit.ts:33 doc block says every CLI write goes through these writers; narrow it to the cli zone, or escape the --debug stderr line from host-kit diagnostics.ts:204 as well.

@thymikee

Copy link
Copy Markdown
Member Author

Thanks. All seven are in 72f363d, folded together with the addendum (#issuecomment-7019263508). Each fix has a test that fails when it is reverted.

  1. JSON without --json: per the addendum, escapeTerminalText now writes \u00NN, which is also a JSON escape. stringifyTerminalJson and its call sites are gone. printJson, --level full, the error details block, get attrs, find, session list, Metro and snapshot --raw all print plain JSON.stringify output, and the escape keeps it parseable. A command-output table checks that each formatter's text, after the CLI escape, parses back exact.
  2. test reporter:
    • The built-in default reporter deep-escapes every string it receives (suite, step and result) before composing or styling. Its own cursor and color codes are added afterwards.
    • Step-trace lines, which come from a local trace file, are escaped too.
    • Live rows fold newlines and tabs to spaces before their width is measured.
    • A reporter hook error is escaped.
    • Custom reporters still get the stream unchanged, since context.stdout.write is their documented API.
  3. Proxy startup: with color off, values are escaped too; with color on, colorize escapes them. I kept the raw write for proxy instead of dropping terminalSafe, because dropping it would turn its colored markers into visible \u001b[....
  4. Upload progress: the CLI's progress sink is threaded through daemon-client into prepareRemoteRequestArtifacts. A TTY upload now reports command progress lines that the escaping sink renders. Without a sink (SDK use), the stderr fallback escapes the file name. The structured UploadProgressEvent API is unchanged.
  5. Takeover notice: managed client settings take an onTakeover(notice) callback with stateDir, previous and reason. ensureProxyUpstreamDaemon passes it through, and proxy renders it with the escaping writer. Without a callback, the fallback writes an escaped line.
  6. doctor colors:
    • The summary escapes its values, adds its colored markers, and returns terminalSafe, so it is written raw.
    • collapseWarningText now also escapes, so a warning the dispatcher appends to raw text stays safe.
    • The daemon no longer colors its streamed check lines. It sends the line uncolored plus an optional marker (pass, fail, warn or skip) on CommandProgressEvent. The CLI sink colors that marker after escaping, when status markers are colored for the terminal.
    • That is an additive wire change; the ledger has the new digest and an ack explaining skew in both directions. The daemon's useColor plumbing is removed.
  7. Capture warnings: the screenshot default-level warnings and the replay export warnings go through appendWarningLinesText, and readSnapshotWarnings folds newlines for the snapshot and snapshot-diff notices. Tests cover a multi-line warning on screenshot, snapshot, snapshot diff and replay export.

Optional items:

  • Fast path: escapeTerminalText scans character codes and returns the input untouched when nothing needs escaping. It only builds a new string when it finds something. I used that loop instead of a regex because oxlint refuses a control-character class.
  • Docs: the command reference now describes the \u00NN form and its JSON safety, plus the fast-help and wrapped-tool exceptions. The process-exit.ts doc is narrowed to the cli zone.
  • Built-binary test: not added. The existing binary harnesses need a built package, which the unit lane doesn't build.

Layering: escapeTerminalText moved to kernel/redaction, which every affected closure already loads, so the eager-closure check stays green with no allowlist. check:layering, fallow and check:production-exports are clean.

@thymikee

Copy link
Copy Markdown
Member Author

Addendum applied in 72f363d; details are in the reply above.

  • Escape format: the writer's escape is now \u00NN. stringifyTerminalJson and its four call sites are gone, and printJson uses the same escape as everything else.
  • get attrs test: it goes through the CLI route with a Pay\u009bnow label and asserts that JSON.parse returns the exact node.
  • Item 7: the screenshot default-level warnings and the replay export warnings go through appendWarningLinesText. The screenshot test is extended with a multi-line warning.
  • Fast path: escapeTerminalText returns its input unchanged when nothing needs escaping.
  • Shared predicate: the tests now use escapeTerminalText itself instead of re-declaring the control-character rule.
  • process-exit.ts: its doc is narrowed to the cli zone.
  • Proxy: one deviation. Proxy keeps terminalSafe (raw write), because its startup text is colored and the writer would escape those codes. Its values are escaped in both color modes, so the raw path still carries only its own color codes. That leaves the raw path in use by the two diff formatters, proxy and doctor.

@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 1 new finding on 5b55231. The verdict and the full list are in the summary comment.

Comment thread packages/remote/src/upload-progress.ts Resolved
@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

Thanks for the update. At 3141391 the one-format change works: the shared writer emits \u00NN after JSON.stringify, so get attrs, find, session list, Metro, snapshot --raw, --level full, error details and --json all parse back to exact values, and the seven earlier bypasses are routed. On size: production code is about +430/−230 across 38 files, under the 700-line threshold, so no split is needed, and the doctor marker can stay.

A second, independent correctness pass found six more gaps. Two are regressions caused by escaping too early, and three are in the replay test reporter. No label yet:

Escaping before a value is used for something other than display:

  1. JUnit artifacts change (output-common.ts:144). replayTestWarningLines now escapes, and JUnit's system-out uses it, so an XML-legal C1 character is stored as a literal \u009b, and an XML-forbidden one becomes an escape before the writer can replace it with U+FFFD. The replay docs promise both behaviors. Keep warning whitespace folding separate from terminal escaping, and escape only at terminal output.
  2. Trace lookup uses the escaped path (reporters/default.ts:100). The reporter escapes artifactsDir before replayTestFailureStepLines builds the trace path and calls readFileSync, so an artifacts root containing DEL or C1 loses its failure excerpts (and line 94 loses verbose step output). Keep raw values for filesystem lookups and escape only when rendering.

Replay reporter output still raw:
3. Verbose timing lines (trace.ts:33) build from JSON.stringify of trace positionals, and the progress reporter writes them raw.
4. Live row (progress.ts:170) folds only the title and basename. A multi-line step value or a device label with a newline or tab still breaks the redraw.

These four share one cause. The reporter escapes some values early and writes others raw. Please make the rule "values stay raw until the last moment, and every reporter line goes through the escaping writer, except the reporter's own color and cursor codes". Fold newlines and tabs in every live-row field before measuring. That fixes items 1-4 together, and future fields can't slip through.

Other direct writes:
5. --debug diagnostics (diagnostics.ts:204). With no log path, a cli_parse_failed diagnostic carrying the invalid argument goes straight to stderr through JSON.stringify, so DEL and C1 stay literal. Escape the serialized line at its stderr write, and keep the file form intact.
6. agent-cdp passthrough (agent-cdp.ts:92). The pinned agent-cdp 1.6.1 prints discovery target titles and captured console text into human stdout, and the CLI forwards both child streams raw, so page-controlled text reaches the terminal. Escape decoded child output by default, keeping Node's incremental decoder for split sequences. If verbatim passthrough is still needed, make it an explicit opt-in.

Not blocking: find, session list, Metro and snapshot --raw are covered by formatter tests, not writer-level ones, and batch summaries, response body text, snapshot node text and the help-error path have no control-character assertion through the CLI writer. One writer-level case per path would pin them.

@thymikee

Copy link
Copy Markdown
Member Author

A few more items at 3141391 from the line-by-line review, to fold into the same push:

  • Two more warning formatters skip the fold. debug (debugging/output.ts:12) and record (recording/output.ts:21, :38) render their own Warning: ${warning} without collapseWarningText, so a multi-line warning breaks the one-line promise in commands.md:35. Route them through appendWarningLinesText.
  • The takeover notice is formatted twice. writeDaemonTakeoverNotice (proxy.ts:136-144) copies formatDaemonTakeoverNotice from daemon-client-startup.ts:279-283. Export the one formatter and call it from both places.
  • Docs list for unescaped output. commands.md:35 names only help/version text and wrapped-tool output as unescaped, while --debug diagnostics also go out raw today (item 5 above). Fixing item 5 makes the list true.
  • Not blocking: diff.ts:25 escapes notices that readSnapshotWarnings already escaped (a harmless second pass; drop it); escapeReporterInput and escapeDoctorCheckText are two "copy with every string escaped" helpers that the raw-until-render rule above would replace; and the ledger acknowledgement says a released daemon's doctor lines print "escaped and uncolored", but a released daemon colored them itself when its stderr was a TTY or FORCE_COLOR was set, so those lines now show escaped color codes. Say so in the rationale.

@thymikee

Copy link
Copy Markdown
Member Author

Thanks. All six are fixed in 435a07b, together with the line-by-line items. Each fix has a test that fails when it is reverted, and I checked that the four reporter tests fail against the 3141391 reporter files.

1–4, one rule: values stay raw until a display line is built.

  • JUnit (1): replayTestWarningLines now uses a fold-only foldWarningText, so JUnit system-out stores the exact text. U+0085 is kept, and ESC becomes U+FFFD through the JUnit writer. The terminal escape lives only in collapseWarningText. Test: a warning with U+0085 and ESC lands in system-out exactly that way.
  • Trace lookup (2): escapeReporterInput is gone. Trace lookup and verbose steps read through the raw artifactsDir. Test: an artifacts root containing DEL and C1 still yields the failure step excerpt, escaped on output.
  • Timing lines and live row (3, 4): progress.ts folds and escapes each value where it is inserted: title, file, step command and value, shard device label, message, hint, session, artifacts, and the verbose timing lines. Every live-row field stays on one row before its width is measured. Tests: escaped verbose timing lines, and a live row with a multi-line step value, a tab in the command and a newline in the device label.
  • Default reporter writes: every summary line that carries values goes through one escaping write. Only the summary totals' color codes and the flaky icon are written raw.

5. --debug diagnostics: the stderr copy is escaped at its write in diagnostics.ts, and the log-file form is unchanged. Test: a cli_parse_failed argument with C1 and DEL prints escaped and the line still parses back exact.

6. agent-cdp: child stdout and stderr go through the escaping writer. Chunks arrive already decoded by the stream's UTF-8 decoder, so a sequence split across chunks stays whole. No flag or environment variable was added; the PR body says a verbatim opt-in can follow if someone needs it. Test: a target title with an SGR sequence and an OSC title sequence are both forwarded escaped.

Docs: the command reference now lists only the built-in help and version text as unescaped.

@thymikee

Copy link
Copy Markdown
Member Author

Applied in 435a07b.

  • debug and record warnings: both now go through appendWarningLinesText. For record, the folded Warning: line comes before the overlay warning, which is folded too. Tests cover a multi-line warning on debug, and on record for single and chunked recordings.
  • Takeover formatter: formatDaemonTakeoverNotice now lives in daemon-client-metadata.ts, which the daemon-client index already loads, so the closure doesn't grow. The index exports it, and both the startup fallback and proxy use it.
  • diff.ts: the second escape of notices is gone; readSnapshotWarnings already escapes them.
  • escapeReporterInput: deleted, per the rule above.
  • escapeDoctorCheckText: kept. It runs only when the doctor summary line is composed, since host-kit composes the colored marker and the label together. The data and --json keep exact values. Moving that escape into host-kit would also escape the daemon's progress text on the wire.
  • Ledger: the CommandProgressEvent ack now says that a released daemon colored its doctor lines when its stderr was a TTY or FORCE_COLOR was set. Against a new CLI, those lines print with escaped color codes, for example \u001b[32m.
  • Gates: the eager-closure check, check:layering, fallow and check:production-exports are clean. The unused collapseWarningText re-export is dropped.

@apex-sentinel-staging

This comment has been minimized.

@apex-sentinel-staging apex-sentinel-staging Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Apex Sentinel: 1 new finding on 435a07b. The verdict and the full list are in the summary comment.

Comment thread src/cli.ts Resolved
@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

At dc7384c every item from the 3141391 comments is fixed: reporter values stay raw until a display line is built, so JUnit keeps exact text and the trace lookup uses the raw path. --debug stderr lines are escaped and still parse as JSON. agent-cdp output is escaped. debug and record fold their warnings, and help and version now go through the writer. All checks are green, and the line-by-line review has no remaining findings.

A second, independent correctness pass found three more gaps that this PR introduces or exposes, so no label yet:

  1. Replay counters from the daemon are printed without a runtime check. The progress decoder passes event fields through, so a remote step event with a string stepIndex or stepTotal reaches the live row (progress.ts:172) without going through display(), and the final suite's passed and total are written raw when color is off (reporters/default.ts:127, :165-172). The daemon is untrusted and the number types are compile-time only. Validate the counters at runtime, pass every interpolated live-row field through the single-row display step, and test malformed events and suite results with color disabled.
  2. Command progress lines break the live row. A command progress event that arrives while a test-step spinner is drawn (reporting.ts:73) is written onto the spinner's row, and the next redraw clears the wrong row, leaving a stale spinner joined to the message. Have the reporter clear its live row before writing a standalone progress line, and keep the renderer's row state in sync. A test should run step, progress, then redraw in one TTY session.
  3. debug and record can now drop a warning. appendWarningLinesText (output-common.ts:98) treats any substring match in the body as "already shown", so a recording path that contains the warning text prints the path and omits the Warning: line. Before this PR these formatters always printed it. Track which warnings were actually rendered (or emit all warnings in one place), and test a warning that also appears in a path.

Not blocking:

  • The process entry's fast-path catch (bin.ts:37) writes module-load errors raw. Those carry the local install path, not untrusted input, so escaping at the entry's stdout and stderr callbacks is a nice-to-have.
  • LF and TAB are kept by design, so a multi-line app name (snapshot.ts:125) or diff line (diff.ts:34) can still look like a separate formatter line.
  • MCP text content and the AI SDK tool text now carry the terminal escapes, while structured content keeps the raw values. That is probably fine, but say so in the docs.
  • The PR body's reporter, Docs and Validation bullets describe earlier heads.

@thymikee

Copy link
Copy Markdown
Member Author

Thanks. All three are fixed in b2b83cb. Each has a test that fails when the fix is reverted (checked by mutation).

  1. Replay counters: step index and total, shard count, suite passed, total and failed, and durations are now checked at runtime. A count must be a non-negative safe integer and a duration a finite number; anything else shows as ?. A shard index that isn't a valid non-negative integer drops the shard suffix. Every live-row field, including the step counter, goes through the single-row display() step. Test: a malformed step event (string, NaN, negative) and a malformed suite with color off render ?/? and Test summary: ? passed (?), ? failed in ?, with no raw control characters.

  2. Command progress over the live row: reporters get an optional onCommandProgress hook.

    • The default reporter asks its renderer to clear the drawn live row (the new clearLiveRow() resets the renderer's row state), then writes the line escaped.
    • The next redraw starts on a fresh row.
    • The test runtime hands command lines to the reporter that takes them. Without one, it writes them escaped to stderr.

    Tests: a reporter-level TTY sequence (step, progress, redraw), where the progress line clears the spinner row and the redraw doesn't climb over it. Plus a runtime-level TTY test of the same sequence through onProgress.

  3. Dropped warnings: appendWarningLinesText, and the stderr route, now skip a warning only when it already appears as a whole line, either bare (as snapshot notices render it) or as Warning: …. A warning that only appears inside another line, such as a path, keeps its line. Test: record with outPath /tmp/Overlay skipped/recording.mp4 and warning Overlay skipped prints both.

Optional items:

  • Docs: one line in commands.md says MCP and AI SDK tool text can show these escapes in warnings and other values the shared formatters escape, while structured content keeps exact values.
  • PR body: refreshed.
  • bin.ts escape: not added. It doesn't grow the closure, but bin.ts runs on import, so a revert-sensitive test would need a spawned process. Those messages carry the local install path, not untrusted input, so I left it out of this round.

Validation: check:layering, the eager-closure check, fallow and check:production-exports are clean. The affected suites passed (19,154 tests).

@thymikee

Copy link
Copy Markdown
Member Author

At b2b83cb the three dc7384c gaps are fixed with tests that fail on the old code: malformed replay counters render as ?, every live-row field goes through display(), the reporter clears its live row before command progress, and record's path-substring case keeps its warning line. The line-by-line review is clean apart from one test note below.

A second, independent correctness pass found that the warning de-duplication is still fragile, and that the new reporter hook opens a side door. No label yet, but I think one structural change ends this:

  1. Warnings are still de-duplicated by matching text. appendWarningLinesText compares rendered body lines against warnings (output-common.ts:108-109). A warning ending in a space, tab or newline is trimmed on one side only, so default open prints it twice. And a record output path containing a newline followed by a line equal to the warning makes both the formatter and the stderr router think it was already shown, so it gets no line at all. Please stop matching text: have formatters never print warnings themselves, and let the dispatcher print every warning exactly once from the warnings channel (or have formatters return the warnings they rendered as explicit metadata). That deletes the de-duplication and both failure modes.
  2. The new onCommandProgress hook is open to custom reporters (reporting.ts:74). A custom reporter that implements it gets the raw daemon message and a raw context stream, so it can print control characters and draw over the default reporter's live row, and a hook that throws escapes the reporter error handler and rejects the test request. Since the hook exists only so the built-in reporter can clear its row, please keep it internal to the built-in path (not part of the reporter interface), write the message through the escaping writer, and contain errors.

Not blocking:

  • The redraw assertion at reporters/__tests__/default.test.ts:517 cannot fail at 200 columns, because the cursor-up only appears when the previous row wraps. Run it at a narrow width so it guards the fix.
  • The warning router splits and trims the whole body even when there are no warnings (output-common.ts:98, :137); returning early on an empty warnings list avoids that, and item 1 removes it entirely.
  • The live --debug tail (src/cli.ts:980) decodes each poll separately, so a UTF-8 character split across appends prints a replacement character. Using a StringDecoder across polls fixes it.

@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

Both fixed in 6964c8c.

Warnings: the dispatcher is the only printer. Formatters never print response warnings. appendWarningLinesText and routeResponseWarnings now append every warning once and return early when there are none. The text-matching dedupe (renderedWarningLines) is deleted. The open, debug, record and snapshot formatters no longer print warnings, and their tests now go through dispatchCliOutput. Effects you can see:

  • record is a parseable-output command, so its warning now goes to stderr. Before, the formatter wrote it into the stdout path text.
  • Snapshot warnings come after the tree as Warning: lines, not as plain notices above it.

screenshot, diff snapshot and the replay export each still print their own warnings, because they don't go through the dispatcher.

Tests for both failure cases:

  • open with a trailing-whitespace warning prints it once (management/output.test.ts).
  • record with the warning text as a whole line of the path, and inside a path segment, still prints Warning: on stderr (recording/output.test.ts).

Command progress is internal. onCommandProgress is removed from ReplayTestReporter. The built-in default reporter registers its writer in a module-private WeakMap, so a custom reporter's property of that name is never called. runReplayTestCommandProgress writes through the escape, and when the write throws it reports Command progress failed: … (escaped) instead of throwing. Tests in reporting.test.ts:

  • a custom reporter with a throwing onCommandProgress: the hook is not called and the line still prints;
  • a stderr write that throws on the progress line: the failure is reported and nothing is thrown.

Optional items:

  • The redraw test now also runs after a resize from 200 to 20 columns, with a long title. The live row is trimmed to the width, so a cursor-up only happens when the terminal shrinks after the row is drawn. That case fails if clearLiveRow stops resetting the drawn row.
  • Return early: done.
  • StringDecoder for the --debug tail: not done. The tail is a private interval in cli.ts, which is at 996 of 1,000 lines. A test that fails on revert would mean moving it into its own module, and a split character only shows as U+FFFD.

I mutated every new test: each fails when its fix is reverted. Typecheck, lint, layering, the eager-closure and wire-compat suites, fallow audit and production exports all pass locally.

@thymikee

Copy link
Copy Markdown
Member Author

At 956ff51 (6964c8c plus a one-line test fix) both structural changes are in: warnings print only from the dispatcher, once each, with the text matching deleted, and onCommandProgress is internal to the built-in reporter, escaped and contained. The trailing-whitespace and record-path cases are covered. Two gaps remain, so no label yet; both are small:

  1. open --foreground drops its snapshot warnings. The daemon nests the initial capture's response, including its warnings, under data.snapshot (session-open-foreground.ts:141). openCliOutput renders that nested snapshot directly (management/output.ts:106-110), and the dispatcher reads only the open response's top-level warnings. Now that the snapshot formatter no longer prints them, warnings such as the snapshot-quality latch or Android's empty-after-filtering never reach text or MCP output, although snapshot -i prints them for the same capture and --json still has them. b2b83cb printed them. Please route the nested snapshot's warnings through the same renderer at the composition point (for example appendWarningLinesText(snapshotOutput.text, result.snapshot)), and add an open --foreground test with distinct top-level and nested warnings that fails at 6964c8c.
  2. A throwing upload progress observer escapes the stream. On a non-CI TTY, the new upload adapter calls the caller's onProgress from inside Transform.transform (upload-progress.ts:75). If the observer throws, the exception escapes outside the stream's error channel. Contain observer errors there, either keeping the upload going or passing a normal rejection through the callback, and test an observer that throws mid-upload.

Not blocking:

  • The open warnings now print after the --foreground tree rather than before it; add that to the "effects you can see" list next to record and snapshot.
  • bin.ts:33-38 still writes the fast help, version and outer error output directly. They are static text or local install paths, as noted before.

@thymikee

Copy link
Copy Markdown
Member Author

Both gaps fixed in dd8d7b9.

  1. open --foreground: the nested snapshot is not the response, so the dispatcher never sees its warnings. openCliOutput now runs the composed snapshot text through appendWarningLinesText with the nested snapshot. Each nested warning prints once, after the tree. The top-level open warnings still come once from the dispatcher, after that. The new test in management/output.test.ts goes through dispatchCliOutput with a distinct top-level warning and a distinct nested warning, and asserts each appears exactly once and that no other warning lines appear.
  2. Throwing upload observer: createUploadProgressTransform now wraps the onProgress call in a try/catch, so a failing observer cannot fail the upload. The new test in upload-progress.test.ts pipes three 8 MiB chunks through the transform with an observer that throws on every report. All bytes arrive, and the observer was called three times.

I checked that each test fails when its fix is reverted. The PR body's warning item now lists the visible effects, including the moved open warnings. Typecheck, lint, layering, the eager-closure check, fallow audit and the affected suites pass locally.

@thymikee

Copy link
Copy Markdown
Member Author

This PR is ready at 87e371a. Since 956ff51 the two remaining gaps are fixed with tests that fail when reverted: open --foreground prints the nested snapshot warnings once, through the same renderer, and a throwing upload onProgress observer is contained inside the transform while every byte still arrives. 87e371a only updates the help-conformance sample for the new trailing Warning: line. Production code is about +440/−240, under the size threshold. All required checks pass after rerunning three unrelated failures: an unhandled ECONNRESET in the Limrun iOS runner test, a device-timing snapshot diff in the Android smoke test, and the runner actions/cache checkout fault.

Not blocking, as noted before: the process entry's fast help, version and outer error writes (bin.ts) still go out directly, and the live --debug tail decodes each poll separately.

@thymikee thymikee added the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 19, 2026
@apex-sentinel-staging

This comment has been minimized.

@thymikee

Copy link
Copy Markdown
Member Author

This now conflicts with main. Please rebase. The earlier review at 87e371a still stands for the code.

@thymikee thymikee removed the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 20, 2026
@thymikee
thymikee force-pushed the fix/cli-terminal-safe-output branch from 87e371a to c269d9d Compare November 20, 2026 08:01
@thymikee

Copy link
Copy Markdown
Member Author

Rebased onto current main. New head: c269d9d.

Conflicts: only one, in test/wire-compat/ledger.json. Main's upload-ingress change (#4721) added three entries (HttpAuthHookContext, AuxiliaryHttpAuthorizer, authorizeUpload) at the same spot where this PR adds the CommandProgressEvent marker entry. I kept all four, with main's entries first. Every other commit rebased without conflicts.

Scope: the diff against main touches the same 67 files as before the rebase, and nothing from main is reverted.

New output from main: none of it needed a fix.

  • The new ambiguous-name audit finding (feat(audit): report controls that share one accessible name #4771) is plain formatter text without terminalSafe, so the CLI's escaping writer escapes it.
  • The help changes in cli-help.ts and cli-help-workflows.ts are static text.
  • Main added no direct terminal writes and no new help samples with warnings.

Checks: build, typecheck, lint, layering, fallow audit, production exports, the eager-closure and wire-compat suites, and the affected suites (6,821 tests) pass locally. src/cli.ts is at 996 lines.

@thymikee

Copy link
Copy Markdown
Member Author

Ready again at c269d9d. The rebase onto main is clean: the changed lines match 87e371a exactly, and the one conflict in test/wire-compat/ledger.json keeps main's three new entries next to this PR's marker entry. The earlier code verdict stands.

@thymikee thymikee added the ready-for-human Valid work that needs human implementation, judgment, or maintainer merge label Nov 20, 2026
@apex-sentinel-staging

Copy link
Copy Markdown

Apex Sentinel · ✅ Approve · review of c269d9d

Since the review of 87e371a: 0 new · 0 still open · 0 no longer raised

No open findings.

2 findings below minor hidden (user_settings.min_severity).

Reviewed with this repository's own Sentinel configuration (854bba6c5a18).

💬 Talking to Sentinel

In a finding's thread, reply with:

Command What it does
@apex-sentinel-staging note <context> Adds context; Sentinel re-checks the cited code
@apex-sentinel-staging pivot <why> Says the finding is wrong; Sentinel re-checks the cited code
@apex-sentinel-staging like Marks the finding as useful
@apex-sentinel-staging dislike <why> Marks it as not useful, so it is not raised again

On this conversation, comment @apex-sentinel-staging review to run a full review once again.

thymikee and others added 13 commits November 20, 2026 11:40
…ites

Text the CLI prints can name values a device or a remote daemon chose,
such as paths and labels. Every CLI write now goes through one writer:

- text output shows C0 (except newline and tab), DEL and C1 characters
  as \xNN, so no formatter, current or future, can let a value drive the
  terminal;
- JSON output escapes DEL and C1 as \uNNNN (JSON.stringify already
  escapes C0), so it stays valid and parses back exact; the --level full
  text output and the error details block use the same serializer.

Colored diff and proxy output escapes its own values (colorize escapes
the text it wraps) and is written through a narrow raw path, as is the
output of a tool the CLI runs and passes through. Default open no longer
prints a multi-line warning twice. The command reference documents the
newline and tab layout rule.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The JSON writer and the progress sink live in the commands zone, so
they no longer import the cli zone's writer: the JSON writer's output is
already terminal-safe, and the progress sink applies the shared kernel
escape itself. This removes the commands -> cli back-edge and the zone
cycle it created.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The shared escape now writes \u00NN, which is also a JSON escape, so
  any JSON the CLI prints (get attrs, find, session list, Metro,
  snapshot --raw, --json, --level full, error details) stays valid and
  parses back exact. The separate JSON serializer is gone.
- The built-in replay test reporter escapes daemon-supplied text before
  composing it, keeps live rows on one line, and the registry escapes a
  reporter hook error.
- Proxy startup escapes its values with color off as well as on.
- Remote upload progress goes to the CLI's progress sink, which
  escapes; without a sink the file name is escaped on stderr.
- The proxy path's daemon takeover notice is a structured onTakeover
  callback the CLI renders.
- doctor keeps its own status-marker colors: the summary escapes its
  values and is written raw, and streamed check lines carry their
  status as an optional marker that the CLI colors after escaping.
- Screenshot and replay export warnings go through
  appendWarningLinesText, and snapshot notices fold newlines.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…line

The progress sink loads status-marker color asynchronously, and one
timer tick was not always enough under coverage, so the line came out
escaped but not yet colored. The test now waits until a line is colored.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A test run hands progress to the replay reporter runtime, which had no
route for command progress events, so upload progress was dropped. The
runtime now writes a command progress line to stderr, escaped, as
every other command does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…t direct writes

- The replay test reporter keeps run values raw: JUnit stores exact
  warnings (folding is separate from the terminal escape) and trace
  lookup uses the raw artifacts path. Values are folded and escaped where
  a display line is built, every value line goes through the escaping
  write, and only the reporter's own color and cursor codes are raw.
  Verbose timing lines are escaped and every live-row field stays on one
  row.
- --debug diagnostics with no log path are escaped at their stderr
  write; the file form is unchanged.
- agent-cdp child output is escaped by default.
- debug and record warnings fold through appendWarningLinesText.
- The daemon takeover notice has one formatter, shared by the startup
  fallback and proxy.
- diff notices are no longer escaped twice, and the ledger rationale
  states how a released daemon's colored doctor lines now print.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
… note

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…track shown warnings

- Replay counters and durations a daemon reports are checked at runtime
  and shown as ? when malformed; every live-row field goes through the
  single-row display step.
- A command progress line during a test run goes to the reporter that
  draws the live row: it clears the row first, and the next row starts
  on a fresh line.
- appendWarningLinesText skips a warning only when it is shown on a
  line of its own, so a warning that also appears inside a path keeps
  its Warning line.
- The command reference notes how MCP and AI SDK tool text show the
  escapes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…command progress internal

Formatters no longer print response warnings. The dispatcher prints each one
exactly once from the warnings channel, so the text-matching dedupe is gone. A
parseable command (record) now warns on stderr instead of in its stdout path.

Command progress during a test run is no longer part of the public reporter
type. Only the built-in reporter writes it, escaped, and a failure to write it
is reported without failing the run.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ng upload observer from stopping the upload

The nested snapshot of open --foreground is not the response, so the
dispatcher never prints its warnings. They now print once where the snapshot
text is composed.

An upload progress observer that throws is now contained in the progress
transform, so the upload continues.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…rivate-ax sample

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@thymikee
thymikee force-pushed the fix/cli-terminal-safe-output branch from c269d9d to c4804b5 Compare November 20, 2026 10:41
@thymikee

Copy link
Copy Markdown
Member Author

Still ready at c4804b5. The rebase onto main is clean: the changed lines match c269d9d, and the one conflict in src/cli/process-exit.ts keeps main's settleWithin import beside this PR's escapeTerminalText import. The earlier code verdict stands.

@thymikee
thymikee merged commit 74771e1 into main Nov 20, 2026
26 of 29 checks passed
@thymikee
thymikee deleted the fix/cli-terminal-safe-output branch November 20, 2026 10:49
thymikee added a commit to pcbeingused333/agent-device that referenced this pull request Nov 20, 2026
* origin/main: (70 commits)
  refactor(apple-runner): one RUNNER_ERROR_CODES row per runner error code with parity/docs gates (callstack#4774)
  fix(android): require acknowledgements for test IME typing (callstack#4722)
  feat(scroll): add scroll refresh for pull-to-refresh (callstack#4770)
  refactor(host-kit): add request Scope and use it for the wait capture deadline (callstack#4794)
  fix(android): let permission all change nothing on an app that declares no permissions (callstack#4796)
  fix(cli): replace the CLI session and generated remote config instead of rewriting them in place (callstack#4797)
  fix(host-kit): accept a group-writable script directory the user owns (callstack#4799)
  fix(cli): escape control characters at the CLI's stdout and stderr writes (callstack#4778)
  fix(audit): do not report rows under a persistent bar that scrolling reveals (callstack#4775)
  fix(daemon): refuse an unsafe state directory before first use (callstack#4783)
  refactor: settle remaining single-deadline races through settleWithin (callstack#4788)
  refactor(host-kit): settle deadline races via settleWithin with R87 race ratchet (callstack#4766)
  fix(android): authenticate and bound persistent snapshot helper sessions (callstack#4729)
  fix(daemon): bound upload ingress and finalization (callstack#4721)
  chore(gates): ratchet wire-published reason literals by value (R89) (callstack#4779)
  feat(audit): evaluate role-less clickable views on Android (callstack#4780)
  fix(mutation): keep umask-setting tests out of Stryker's thread pool (callstack#4785)
  feat(audit): report controls that share one accessible name (callstack#4771)
  fix(contracts): pair open runtime hints with their apply operation (callstack#4754)
  refactor(daemon): report startup progress over the launch channel instead of marker files (callstack#4777)
  ...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ready-for-human Valid work that needs human implementation, judgment, or maintainer merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants