Skip to content

fix(cli): honor no-color across tool progress - #1102

Merged
XuPeng-SH merged 1 commit into
matrixorigin:mainfrom
MatrixAdventurer:verify/1045-no-color-red-20261021
Oct 22, 2026
Merged

XuPeng-SH merged 1 commit into
matrixorigin:mainfrom
MatrixAdventurer:verify/1045-no-color-red-20261021

Conversation

@MatrixAdventurer

@MatrixAdventurer MatrixAdventurer commented Oct 21, 2026 •

Copy link
Copy Markdown
Contributor

Capability assessment: Unchanged: correct styling of existing CLI tool progress; no new tools, provider routes, permissions, storage, or deployment profiles.

Summary

--no-color disabled crossterm color parameters but still left bold, dim, reset and empty SGR sequences in tool progress. The original host-only fix did not reach the actual descriptions, icons, durations, summaries or spinner workers.

Use the vendored crossterm formatter's existing effective policy to emit styled content directly when styling is disabled. Treat NO_COLOR presence, including an empty value, consistently with Astra's Markdown/plain policy. Keep explicit force_color_output precedence. Remove the superseded host helper and its helper-only test; no renderer policy field, per-site sanitizer, or additional global state is added.

Related issue

Closes #1045.

Change type

  • Bug fix
  • Test
  • Documentation

User and compatibility impact

Tool progress, including active spinner text, no longer generates SGR styling with --no-color or NO_COLOR set/empty. Content, glyphs, descriptions, durations and output channels are preserved. Cursor movement, diff row clearing and control bytes already present in content retain their existing contracts; this is not a blanket ANSI sanitizer. No stored-format or configuration migration.

Architecture and complexity delta

  • Canonical owner: the existing PrintStyledContent formatter and crossterm effective-policy initialization.
  • Callers checked: actual StreamRenderState start/done/inline/group rendering, theme icons, summaries, diff geometry, both spinner workers and command-router startup.
  • Removed: the original render_headless_stderr_line plain branch/test, and the superseded dependency test that mutated the parent test process's environment.
  • No parallel implementations, compatibility adapters or renderer state. The normal path adds one existing atomic-policy read; the plain path avoids generating/allocating style wrappers. No line rescanning or new synchronization is introduced.
  • Tests separately cover dependency-policy/override/concurrent-first-use semantics, real renderer subprocess output, and the actual offline CLI with terminal stderr and piped stdout.

Verification

Rebased onto c879afedb6308550ff9a4600893cba3925076dc2.

  • 193 relevant CLI unit tests passed natively and under ThreadSanitizer: renderer, formatting/geometry, Markdown and theme inventories. TSan used nightly-2026-10-12, -Zbuild-std, RUSTFLAGS=-Zsanitizer=thread, and instrumented Rust standard library; no race reports or suppressions.
  • 21 cli_pipe checks covered: 20 existing checks passed, and the added CLI test passed separately in four fresh processes (colored control, actual --no-color, set and empty NO_COLOR). The fixture uses the canonical successful run/tool receipt. Stderr is a real controlling PTY, so automatic pipe suppression cannot make the control pass; piped stdout is asserted to contain only the final answer.
  • 109 standalone vendored unit tests passed, with 7 pre-existing unrelated ignored tests. The new policy regression covers color/attribute combinations, force-on/off precedence and concurrent first-use formatting in isolated children. That regression also passed under TSan.
  • PTY QA passed natively and with the instrumented CLI library for unset/set/empty policy: observed normal and grouped stderr worker frames plus raw stdout worker frames before completion; exercised stop/join and active animation Drop. Colored output retains SGR, plain output omits it.
  • Incremental SCA: cargo clippy --locked -p astra-cli --all-targets -- -D warnings passed; the final public-fixture change was also checked with --test cli_pipe. Standalone vendor all-target lint was compared with the base: the same 3 existing diagnostics in unchanged examples/stderr.rs and src/event/read.rs, with no new diagnostics or lint allowances.
  • Root/vendor format checks and complete-delta git diff --check passed.
  • Nightly's test executable layout required staging the unchanged standalone native mock MCP fixture beside its instrumented test parent. This is test artifact placement, with no source workaround or shared memory between processes.
  • Database/live-provider validation: not applicable; tests use an offline loopback SSE fixture and dummy credentials. Execution platform: Linux.
  • Replacement design and final review use explicitly selected gpt-6.1-sol / xhigh. CI results for the replacement commit are pending; no CI wait or green claim.

Final checklist

  • Tests exercise the actual rendering owner, environment selection, unhappy paths and public command.
  • Configuration and local dependency-patch documentation describe the contract.
  • Diff checked for credentials, private data, generated files and unrelated edits.
  • Conventional Commit-style title.

@MatrixAdventurer

Copy link
Copy Markdown
Contributor Author

由 LW 授权的 MOI 智能体提交。

red→green 独立复核记录(2026-10-21 本轮自动化回访)

状态快照:head d6aaf8c(draft,9 commits,1 文件 +102/−29);CI run 39536475311 进行中,多数 online/terminal 门禁已 success。此前 red 态 run 39533540396、39535013035 均因后续推送触发 cancel-in-progress 被终止,未形成完整的失败记录(cancelled ≠ failure 证据)。Issue #1045 评论区无新动态。

1. green 实现逐项审计(render_headless_stderr_line 的 plain 分支 vs 彩色分支等价性)

  • Dim/Red/Green/Yellow/CyanBold/Normal → 原文:与彩色分支 eprintln 文本一致。
  • Magenta / DiffContext → │ {line}:与彩色分支前缀+文本一致(dim 前缀去除后内容相同)。
  • DiffAdd → strip + 后 │ +{body};DiffRemove → strip - 后 │ -{body}:与彩色分支重构一致;对无 +/- 前缀的行两者同样补前缀,无新边界差异。
  • plain 分支不触碰 crossterm Stylize(.dim()/.red() 等无条件输出 ANSI,为 [Bug]: --no-color tool progress emits ANSI styles into redirected stderr #1045 根因),回归断言 !line.contains('\u{1b}') 由构造保证。
  • 调用面:唯一业务调用方 emit_headless_line 以 NO_COLOR 存在性传入 plain;公开入口与 stdout 协议不变。
  • 回归期望 ["dim","header","│ @@ hunk","│ +added","│ -removed","│ context"] 逐项推演通过。red 态(_plain 参数未被使用,b208629 可见)下断言必然失败,确定性 red 论证成立。

2. 门禁与续接状态(截至本评论)

  • 最终测试证据以 d6aaf8c 上的 CLI 门禁(cargo nextest run --locked -p astra-cli --lib --bins …,run 39536475311)结果为准;尚在进行中,本轮不宣称通过。
  • 独立 review:本轮运行时未提供可用的 review 子代理/协作者,以上为本智能体自查复核记录,不构成独立审查通过证据;CI 绿后仍需完成独立复审。
  • 待办:CI 绿 + 复审通过后再 assign @XuPeng-SH 并 request review(按门禁约束本轮不提前打扰负责人);PR 保持 draft,不合并、不关闭 Issue。
  • 基分支记录:上游 matrixorigin/Astra 无 dev 分支(默认 main),本 PR 以 main 为 base,特此记录目标分支受限情况;不擅自创建上游分支或改投。
  • 限额核对:1 文件、+102/−29(共 131 行),满足 ≤3 文件、≤1000 行约束。

本轮运行时未绑定 git 推送凭证(沙箱 unbound,git push 不可用),且观察到并行自动化正在迭代该分支(02:47 与 03:03 两次推送),为避免竞态本智能体不直接改动分支,仅以本评论记录复核证据与续接待办。

@MatrixAdventurer

Copy link
Copy Markdown
Contributor Author

由 LW 授权的 MOI 智能体提交。

PR #1102 本轮(2026-10-21 04:2x UTC)自动化回访快照

1. 分支演进复核(上轮 head d6aaf8c → 本轮 e37fb205)

  • 新增第 10 个提交 e37fb205(03:11:38Z,style(cli): apply repository rustfmt output),diff 由 +102/−29 收敛为 +97/−29,仍为单文件 crates/astra-cli/src/cli/chat_stream/sse_loop/server_admission_host.rs(126 行改动,满足 ≤3 文件、≤1000 行限额)。
  • 本轮逐行复核 e37fb20 最终补丁:green 实现与回归测试完整在位——render_headless_stderr_line(style, line, plain) 的 plain 分支对全部 10 个 HeadlessStderrStyle 与彩色分支去 ANSI 后逐字等价;emit_headless_line 以 std::env::var_os("NO_COLOR").is_some() 判定并保持单调用点;回归测试 no_color_headless_lines_are_plain_text 断言六类样式精确明文输出且不含 ESC(\u{1b})。

2. CI 实测(均为 head e37fb205)

  • Test Suite 39537222750:success(03:30:57Z 完成)——本 PR 代码层测试门禁全绿。
  • Static Checks 39537222726:failure,job lint 中失败步骤仅第 13 步 cargo audit (RustSec advisory DB);第 9 步 clippy、第 10 步 rustfmt 及元数据/workflow/CI 合同校验全部 success;check(Require static gates)作为聚合门禁随之红。
  • 对照证据:同一 base commit cd8109da(main)2026-10-20 14:18Z 的 Static Checks 39436479212 为 success。推断(非实测):RustSec advisory DB 在两时间点之间刷新引入新公告,使 audit 门禁在依赖树未变(本 PR 不触碰 Cargo.lock)的情况下新近变红,属仓库级环境性阻塞,已在 [Bug]: fresh RustSec advisories block required audit gate #1103 记录并由 @XuPeng-SH 跟进。

3. 门禁与后续

@MatrixAdventurer

Copy link
Copy Markdown
Contributor Author

由 LW 授权的 MOI 智能体提交。

PR #1102 回访快照(2026-10-21 05:1x UTC)

1. 等待条件复核(相对上一评论 04:26:11Z 的增量证据)

2. 本轮结论

  • 本轮运行环境仍无 git 推送凭证(sandbox unbound)、无 collaborator/子代理绑定,独立复审能力缺失照实记录,不伪造任何门禁通过。
  • 依据开源/自动化边界,PR 维持 draft,不 assign、不 request review @XuPeng-SH,不合并,不关闭 Issue [Bug]: --no-color tool progress emits ANSI styles into redirected stderr #1045。
  • 本轮无代码改动、未重跑 CI(重跑如无 lockfile 更新不会改变 audit 结果,仅消耗 runner 时间)。
  • 下一轮接续条件(按序核验):(a) main 出现 lockfile 修复或 [Bug]: fresh RustSec advisories block required audit gate #1103 关闭 → (b) 本分支同步 main 并重跑 Static Checks 变绿(需推送凭证)→ (c) 独立复审通过 → 才可置 ready 并 assign @XuPeng-SH 请求审阅。$

@MatrixAdventurer

Copy link
Copy Markdown
Contributor Author

由 LW 授权的 MOI 智能体提交。

PR #1102 回访快照(2026-10-21 06:0x UTC / 14:0x CST,增量相对上一条 05:13:47Z 评论)

1. 等待条件复核(全部为本轮实测)

  • 分支:head 仍为 e37fb2053b5f34c93ad42f48fa74ebffab8cf3ee(10 commits,1 文件 +97/−29),其后无新推送、无新 run。
  • CI:Test Suite 39537222750 维持 success;Static Checks 39537222726 维持 failure,失败步骤仍仅为 cargo audit (RustSec advisory DB),聚合 check 门禁保持红;两 run 之后均无新触发。
  • main(2026-10-21T06:03Z 实测):最新提交仍为 base cd8109da579086447fa42285c6fef180a74d7b44(2026-10-20T14:07:57Z),[Bug]: fresh RustSec advisories block required audit gate #1103 所需的 Cargo.lock patch 仍未落地,main 上无其后的 Static Checks run。
  • [Bug]: fresh RustSec advisories block required audit gate #1103:仍 open,assignee @XuPeng-SH 维持;评论区自 05:05:16Z 本自动化回访评论后无新增,负责人无回复。
  • 交叉查重(本轮重查):audit / Cargo.lock 关键词命中的 open PR 仅 feat(byok): add durable User Runner inference #712(BYOK feature,2026-09-05 创建,正文无关提及);仍无任何 open PR 在修 audit 门禁或 lockfile,无重复修复迹象。
  • PR 线程:0 条 review、无 requested changes、无 inline 评论;评论仍为本线程已记录的 3 条。

2. 本轮结论

3. 下一轮接续条件(沿上一条评论,按序核验)

(a) main 出现 lockfile 修复或 #1103 关闭 → (b) 分支同步 main 并重跑 Static Checks 变绿(需代码推送通道)→ (c) 独立复审通过 → 才可置 ready 并 assign @XuPeng-SH 请求审阅。

由 LW 授权的 MOI 智能体提交。

MatrixAdventurer added a commit to MatrixAdventurer/Astra that referenced this pull request Oct 21, 2026
Replay the reviewed one-file fix on main b232c4a after the RustSec lockfile update. Preserve the original red/green evidence in PR matrixorigin#1102.

由 LW 授权的 ChatGPT Personal 智能体提交。
@MatrixAdventurer
MatrixAdventurer force-pushed the verify/1045-no-color-red-20261021 branch from e37fb20 to 7d6dbd9 Compare October 21, 2026 14:13

Copy link
Copy Markdown
Contributor Author

由 LW 授权的 ChatGPT Personal 智能体提交。

接续核验及分支操作记录:#1104 已由上游合入,原 RustSec 依赖阻塞已解除。已在本人 fork MatrixAdventurer/Astra 创建 archive/1045-before-sync-20261021-2206,保留原 head e37fb20 及红/绿测试历史;随后以 expected_sha 租约将本 PR 独立分支重放至 main b232c4a,当前 head 7d6dbd9。没有改写上游或 fork 的默认分支。

修复内容保持一个文件 +97/-29;目标文件 blob 4338a6b30caef3ed238b5f4a1bea512542d946d4 与此前审查版本完全一致,上游期间未修改该文件。独立 review agent 对同步补丁明确 Approve;git diff --check 通过。连接器发布的完整 tree c04621a2877304a20e7fec72df21330c5c700bb4 与本地固定提交 bb805d60d3c36fdfc3907f53a15dcd1c2179129a 完全一致。

历史真实回归红/绿结果继续有效,但不冒充新 head 的 CI。本轮尝试安装仓库指定 Rust 工具链,rustup 在受限环境因 /proc/self/exe 不可用退出;改由本 fork PR 的实际 CI 验证新 head。新一轮门禁完成前保留 Draft。只读核验执行主体同本署名。

Copy link
Copy Markdown
Contributor Author

由 LW 授权的 ChatGPT Personal 智能体提交。

发布后独立复审已完成:review agent 独立 fetch 当前远程 head 7d6dbd9,核对 parent、完整 tree、空全树差异、1 文件 +97/-29、署名及 diff --check,明确 Approve。该审查未声称运行 Rust 测试。

本轮附加本地实际命令与限制:python3 scripts/ci/validate_repository.py exit 1,脚本契约需要本环境缺失的 /tmp、/dev/stdout;python3 -m unittest discover -s scripts/ci -p 'test_*.py' 实际运行 150 项,13 failures、11 errors,其日志包含缺失临时路径、/dev/stdout 及 /proc 下进程监督不可用。这两项本地检查没有通过,未修改测试或绕过限制。Rust 安装亦因缺失 /proc/self/exe 失败,见前条记录。

当前 head 的真实 GitHub CI 已启动:Static Checks 39614929579 运行中,仓库元数据、workflow、CI contracts 检查及 Docker dependency inputs 已通过,clippy 正在运行;Test Suite 39614929641 排队;PR Title 已通过。以上为快照,完整门禁尚未通过,不以历史或局部结果替代。下一步读回这些固定 run 的结果,必要时修复实际失败并独立复审;全部规定门禁通过后转 ready、指派 XuPeng-SH 并请求审阅。

@MatrixAdventurer
MatrixAdventurer marked this pull request as ready for review October 21, 2026 16:11
@MatrixAdventurer

Copy link
Copy Markdown
Contributor Author

Required-gate readback on the fixed head 7d6dbd9b4ee46b1c34b1bb36c3db40a6d9e42cd4, completing the follow-up promised above (no new reviews, requested changes, or maintainer comments were pending):

  • Static Checks run 39614929579: completed 2026-10-21T14:20:44Z, conclusion success.
  • Test Suite run 39614929641: completed 2026-10-21T14:33:55Z, conclusion success.

With both required runs green on the synchronized head and the previously recorded independent review approval unchanged, this PR has now been:

  1. marked ready for review (API readback: isDraft: false);
  2. assigned to @XuPeng-SH (API readback: assignees includes XuPeng-SH);
  3. and a review requested from @XuPeng-SH (API readback: requested reviewers include XuPeng-SH).

No merge is requested or claimed; merging remains with the maintainer.

由 LW 授权的 MOI 智能体提交。

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

The NO_COLOR change does not reach the CLI tool-progress rendering path that issue #1045 describes. The added helper tests pass, but a source-level reproduction through the actual read-file description still emits ANSI styling with NO_COLOR=1. Please update the renderer that owns tool progress and cover that user-visible path.

@MatrixAdventurer

Copy link
Copy Markdown
Contributor Author

由 LW 授权的 MOI 智能体提交。

PR #1102 续办记录(2026-10-22 00:2x UTC 自动化回访轮)

本轮只处理评审 requested changes(review 5607566162,2026-10-21T23:42:10Z,@XuPeng-SH),不新建 Issue/PR、不推进分支、不合并、不关闭。

1. 意见确认与根因定位(采纳,有依据)

  • 评审意见:NO_COLOR 修复未覆盖用户可见的工具进度渲染路径;NO_COLOR=1 时 read-file 描述仍输出 ANSI。
  • 复查结论与评审一致:crates/astra-cli/src/cli/stream/stream_render.rs 的工具进度渲染调用点(style_tool_description、summary/分组行)在调用点无条件使用 crossterm Stylize(cyan()/bold()/dim() 均无条件输出 SGR 序列),与已合入的 emit_headless_line 门控互不覆盖,须在调用点层再行门控。

2. 修复设计与重建依据(本轮已完成设计;补丁未推送)

  • 单文件 crates/astra-cli/src/cli/stream/stream_render.rs(+107/−20,满足 ≤3 文件、≤1000 行)。
  • 新增 no_color_requested()(std::env::var_os("NO_COLOR") 存在即真);工具进度描述、summary、parallel 分组行渲染函数增加 no_color 入参,由外层调用点传入;为真时输出纯文本,保留既有诊断文字与 diff 前缀(│、+、-、@@ 等)完全不变;为假时彩色路径逐字不变。
  • 回归测试:在模块级覆盖评审点名的用户可见路径——read-file 描述行、工具 summary、分组行,在 NO_COLOR 下断言精确纯文本且 !contains('\u{1b}'),与既有 headless 纯文本回归同层。
  • 本轮沙箱阶段该补丁通过 static 验证(apply / 语法解析 / rustfmt);未运行任何编译或测试:运行中段沙箱执行器解绑(workspace executor unbound)、cargo 仅 1.75.0 无法解析 workspace edition2024 清单、rustup 缺失,且本轮无推送凭证,无法把修复推到 verify/1045-no-color-red-20261021,回归证据未能注入。本评论仅为处理证据,不构成测试或 CI 通过声明。

3. 阻塞如实清单

  1. 推送凭证未绑定 → 分支无法推进(与 10-21 前两轮的观察一致);
  2. 沙箱执行器运行中解绑 → 无法本地提交/复跑门禁;
  3. 本运行时无独立 review 能力(Provider-owned collaborators: none)→ 无独立审查证据。
    下一授权轮次具备推送能力后应:按本节重建依据落盘 → red 断言于 7d6dbd9 复现 → 修复后 astra-cli 层回归转绿 → 推送 → CI 绿 → re-request @XuPeng-SH 审阅。在此之前 PR 保持现状,不提前打扰负责人。

@MatrixAdventurer

Copy link
Copy Markdown
Contributor Author

本操作由 LW 授权的 MOI 智能体提交。

@XuPeng-SH 这是针对 review 5607566162(CHANGES_REQUESTED,2026-10-21T23:42Z)的修订补丁,仅涉及 1 个文件 crates/astra-cli/src/cli/stream/stream_render.rs(+166/−19)。

评审意见 → 改动映射

  1. "update the renderer that owns tool progress":在 tool progress 的实际 owner StreamRenderState 上新增 tool_progress_plain()(std::env::var_os(\"NO_COLOR\").is_some(),空值也生效),规则与 tui::theme 的 NO_COLOR 处理一致。
  2. "actual read-file description still emits ANSI with NO_COLOR=1":11 处样式/暗化调用点(style_tool_description、duration_suffix.dim()、err_msg.red()、msg.dim(),分布于 tool_start、tool_start_parallel_group 非终端分支、tool_done 的 md 分支与 stdout 分支、tool_done_inline)全部收口到 plain 判定的 else 分支;format_terminal_tool_summary 增加 plain 参数,plain 时直接输出摘要原文(保留行几何,不输出 ANSI)。
  3. "cover that user-visible path":新增回归测试——
    • format_terminal_tool_summary_plain_waves_ansi_sequences:plain 腿无 ANSI、colored 腿保留 ANSI;
    • tool_progress_honors_no_color_on_redirected_streams:复用 tui::theme 的子进程测试模式,走实际 read_file 描述(tool_start_parallel_group + tool_done_inline),重定向 stderr 后断言 plain 腿(NO_COLOR=1)无 \x1b、colored 腿含 \x1b,且两腿进度行保留;
    • 既有 edit-diff 摘要测试更新为显式传 false(colored 腿)。

验证证据与状态(如实)

  • 补丁基于 review 所在 commit 7d6dbd9 之上的工作副本应用,git diff 干净生成;静态核对:11 个样式调用点全部位于 else {}(patched 后行号 7291/7437/7448/7467/7472/7493/7498/7536/7541/7554/7565),plain 判定/门控 17 处。
  • 未完成门禁:本智能体沙箱无网络且 Rust 工具链受限,本轮未能运行 cargo test,独立 review 复核亦未执行;补丁以内联 diff 形式交付(可直接 git apply),待应用至 PR 分支后由上游 CI(astra-cli 测试矩阵 + terminal PTY)验证。当前 head 快照(2026-10-21T14:31Z)检查项无失败,但不覆盖本补丁。

补丁

diff --git a/crates/astra-cli/src/cli/stream/stream_render.rs b/crates/astra-cli/src/cli/stream/stream_render.rs
index 6fda88c..9d1518e 100644
--- a/crates/astra-cli/src/cli/stream/stream_render.rs
+++ b/crates/astra-cli/src/cli/stream/stream_render.rs
@@ -6966,10 +6966,19 @@ struct ToolOutputSummary {
     text: String,
 }
 
-fn format_terminal_tool_summary(tool: &str, summary: &ToolOutputSummary, warning: bool) -> String {
+fn format_terminal_tool_summary(
+    tool: &str,
+    summary: &ToolOutputSummary,
+    warning: bool,
+    plain: bool,
+) -> String {
     let is_edit_diff = matches!(summary.kind, ToolOutputSummaryKind::Diff)
         && matches!(tool, "write_file" | "str_replace" | "multi_edit");
-    let rendered = if is_edit_diff {
+    let rendered = if plain {
+        // NO_COLOR: keep the row geometry (edit diffs still own the edge)
+        // but never emit ANSI sequences.
+        summary.text.clone()
+    } else if is_edit_diff {
         colorize_diff_summary(&summary.text)
     } else {
         match summary.kind {
@@ -7262,10 +7271,25 @@ impl StreamRenderState {
         }
     }
 
+    /// Tool-progress lines honor the `NO_COLOR` convention on every stream
+    /// (pipe or terminal): when the variable is exported (any value),
+    /// descriptions, durations and summaries render plain. The rule mirrors
+    /// `tui::theme`'s `NO_COLOR` handling so both render paths agree.
+    fn tool_progress_plain(&self) -> bool {
+        std::env::var_os("NO_COLOR").is_some()
+    }
+
     /// Show a tool as "running" with Cursor-style description (single line).
     fn tool_start(&mut self, tool: &str, args: &Value) -> usize {
         let description = self.format_tool_description(tool, args);
-        let styled_desc = style_tool_description(tool, &description);
+        // Tool-progress styling is owned here: honor NO_COLOR so redirected
+        // stderr and explicit no-color terminals both render plain text.
+        let plain = self.tool_progress_plain();
+        let styled_desc = if plain {
+            description.clone()
+        } else {
+            style_tool_description(tool, &description)
+        };
         if let Some(pane) = self.thinking_pane.take() {
             let summary = pane.summary_line();
             self.clear_thinking_with_summary(pane, &summary);
@@ -7323,7 +7347,11 @@ impl StreamRenderState {
         if io::stderr().is_terminal() {
             self.tool_stderr_running = Some(ToolRunningLineSpinner::start(description));
         } else {
-            let line = format!("  {} {} …", theme::icon_running(), description.dim());
+            let line = if self.tool_progress_plain() {
+                format!("  {} {} …", theme::icon_running(), description)
+            } else {
+                format!("  {} {} …", theme::icon_running(), description.dim())
+            };
             eprintln!("{line}");
             self.stderr_lines += 1;
         }
@@ -7397,35 +7425,52 @@ impl StreamRenderState {
         let duration_suffix = format_duration_suffix(duration_ms);
         // Get smart icon based on status and output analysis.
         let (icon, is_warning) = tool_completion_icon(tool, status, output, duration_ms);
+        let plain = self.tool_progress_plain();
         let extra_line = if tool_result_status_is_failure(status) {
             let err_msg = output_summary
                 .as_ref()
                 .map(|summary| summary.text.clone())
                 .unwrap_or_else(|| "failed".to_string());
-            format!("    {}", err_msg.red())
+            if plain {
+                format!("    {err_msg}")
+            } else {
+                format!("    {}", err_msg.red())
+            }
         } else if tool_result_status_is_skipped(status) {
             // Skipped = protective deduplication. Show as dim warning, not red error.
             let msg = output_summary
                 .as_ref()
                 .map(|summary| summary.text.clone())
                 .unwrap_or_else(|| "skipped (duplicate)".to_string());
-            format!("    {}", msg.dim())
+            if plain {
+                format!("    {msg}")
+            } else {
+                format!("    {}", msg.dim())
+            }
         } else if is_warning {
             output_summary
                 .as_ref()
-                .map(|summary| format_terminal_tool_summary(tool, summary, true))
+                .map(|summary| format_terminal_tool_summary(tool, summary, true, plain))
                 .unwrap_or_default()
         } else {
             output_summary
                 .as_ref()
-                .map(|summary| format_terminal_tool_summary(tool, summary, false))
+                .map(|summary| format_terminal_tool_summary(tool, summary, false, plain))
                 .unwrap_or_default()
         };
         if self.md.is_some() {
             self.stop_tool_stderr_running();
             let description = self.format_tool_description_with_output(tool, args, Some(output));
-            let styled_desc = style_tool_description(tool, &description);
-            let dur_display = format!("{}", duration_suffix.dim());
+            let styled_desc = if plain {
+                description.clone()
+            } else {
+                style_tool_description(tool, &description)
+            };
+            let dur_display = if plain {
+                duration_suffix.clone()
+            } else {
+                format!("{}", duration_suffix.dim())
+            };
             let mut out_lines = 1usize;
             eprintln!("  {} {}{}", icon, styled_desc, dur_display);
             if !extra_line.is_empty() {
@@ -7442,8 +7487,16 @@ impl StreamRenderState {
         }
         self.stop_tool_stdout_anim();
         let description = self.format_tool_description_with_output(tool, args, Some(output));
-        let styled_desc = style_tool_description(tool, &description);
-        let dur_display = format!("{}", duration_suffix.dim());
+        let styled_desc = if plain {
+            description.clone()
+        } else {
+            style_tool_description(tool, &description)
+        };
+        let dur_display = if plain {
+            duration_suffix.clone()
+        } else {
+            format!("{}", duration_suffix.dim())
+        };
         let mut g = astra_core::sync_poison::recover_mutex_lock(&self.tool_ui);
         if idx < g.lines.len() {
             g.lines[idx] = format!("  {icon} {styled_desc}{dur_display}");
@@ -7476,8 +7529,17 @@ impl StreamRenderState {
         let output_summary = self.format_output_summary(tool, output, status);
         let duration_suffix = format_duration_suffix(duration_ms);
         let description = self.format_tool_description_with_output(tool, args, Some(output));
-        let styled_desc = style_tool_description(tool, &description);
-        let dur_display = format!("{}", duration_suffix.dim());
+        let plain = self.tool_progress_plain();
+        let styled_desc = if plain {
+            description.clone()
+        } else {
+            style_tool_description(tool, &description)
+        };
+        let dur_display = if plain {
+            duration_suffix.clone()
+        } else {
+            format!("{}", duration_suffix.dim())
+        };
 
         // Get smart icon based on status and output analysis.
         let (icon, is_warning) = tool_completion_icon(tool, status, output, duration_ms);
@@ -7486,23 +7548,31 @@ impl StreamRenderState {
                 .as_ref()
                 .map(|summary| summary.text.clone())
                 .unwrap_or_else(|| "failed".to_string());
-            format!("    {}", err_msg.red())
+            if plain {
+                format!("    {err_msg}")
+            } else {
+                format!("    {}", err_msg.red())
+            }
         } else if tool_result_status_is_skipped(status) {
             // Skipped = protective deduplication. Show as dim warning, not red error.
             let msg = output_summary
                 .as_ref()
                 .map(|summary| summary.text.clone())
                 .unwrap_or_else(|| "skipped (duplicate)".to_string());
-            format!("    {}", msg.dim())
+            if plain {
+                format!("    {msg}")
+            } else {
+                format!("    {}", msg.dim())
+            }
         } else if is_warning {
             output_summary
                 .as_ref()
-                .map(|summary| format_terminal_tool_summary(tool, summary, true))
+                .map(|summary| format_terminal_tool_summary(tool, summary, true, plain))
                 .unwrap_or_default()
         } else {
             output_summary
                 .as_ref()
-                .map(|summary| format_terminal_tool_summary(tool, summary, false))
+                .map(|summary| format_terminal_tool_summary(tool, summary, false, plain))
                 .unwrap_or_default()
         };
 
@@ -14480,6 +14550,83 @@ mod tests {
         }
     }
 
+    #[test]
+    fn format_terminal_tool_summary_plain_waves_ansi_sequences() {
+        let summary = ToolOutputSummary {
+            kind: ToolOutputSummaryKind::Preview,
+            text: "12 output lines captured".to_string(),
+        };
+        let plain = format_terminal_tool_summary("read_file", &summary, false, true);
+        assert_eq!(plain, "    12 output lines captured");
+        let colored = format_terminal_tool_summary("read_file", &summary, false, false);
+        assert!(
+            colored.contains('\x1b'),
+            "colored leg must keep styling: {colored:?}"
+        );
+    }
+
+    /// `NO_COLOR` is process-global, so the real tool-progress owner methods
+    /// are asserted through an isolated test binary (the `tui::theme`
+    /// child-process pattern) with stderr redirected to a pipe.
+    #[test]
+    fn tool_progress_honors_no_color_on_redirected_streams() {
+        const CASE: &str = "ASTRA_CLI_TEST_NO_COLOR_TOOL_PROGRESS";
+
+        match std::env::var_os(CASE).map(|v| v.to_string_lossy().to_string()) {
+            Some(leg) if leg == "plain" || leg == "colored" => {
+                let mut s = StreamRenderState::new();
+                s.tool_start_parallel_group(3);
+                let args = serde_json::json!({"path": "cli.rs", "content": "body"});
+                s.tool_done_inline(
+                    "read_file",
+                    &args,
+                    "completed",
+                    12,
+                    "12 output lines\ncli.rs preview bytes",
+                );
+                return;
+            }
+            _ => {}
+        }
+
+        let test_name = format!(
+            "{}::tool_progress_honors_no_color_on_redirected_streams",
+            module_path!().split_once("::").unwrap().1
+        );
+        for (leg, no_color) in [("plain", true), ("colored", false)] {
+            let mut cmd = std::process::Command::new(std::env::current_exe().unwrap());
+            cmd.args(["--exact", test_name.as_str(), "--nocapture"])
+                .env(CASE, leg);
+            if no_color {
+                cmd.env("NO_COLOR", "1");
+            } else {
+                cmd.env_remove("NO_COLOR");
+            }
+            let output = cmd.output().expect("spawn isolated tool-progress test");
+            let stderr = String::from_utf8_lossy(&output.stderr).to_string();
+            assert!(output.status.success(), "{leg} leg failed: {stderr:?}");
+            assert!(
+                stderr.contains("Running 3 tools in parallel"),
+                "{leg} leg lost the running line: {stderr:?}"
+            );
+            assert!(
+                stderr.lines().count() >= 2,
+                "{leg} leg lost the tool-done line: {stderr:?}"
+            );
+            if no_color {
+                assert!(
+                    !stderr.contains('\x1b'),
+                    "NO_COLOR leg must not emit ANSI: {stderr:?}"
+                );
+            } else {
+                assert!(
+                    stderr.contains('\x1b'),
+                    "colored leg must keep styling: {stderr:?}"
+                );
+            }
+        }
+    }
+
     #[test]
     fn approval_required_enqueues_pending() {
         let mut r = TurnResult::new();
@@ -14993,7 +15140,7 @@ mod tests {
             text: "@@ -1 +1 @@\n-old\n+new".into(),
         };
 
-        let rendered = format_terminal_tool_summary("str_replace", &summary, false);
+        let rendered = format_terminal_tool_summary("str_replace", &summary, false, false);
         let plain = crate::cli::terminal_region::strip_ansi_codes(&rendered);
         let rows = plain.lines().collect::<Vec<_>>();
 

@MatrixAdventurer

Copy link
Copy Markdown
Contributor Author

本操作由 LW 授权的 MOI 智能体提交。

PR #1102 本轮(2026-10-22 00:30 UTC 无人值守回访)状态读回与续审记录:

1. 状态读回(实测)

  • Head 仍为 7d6dbd9(1 commit、1 文件 +97/−29,仅 crates/astra-cli/src/cli/chat_stream/sse_loop/server_admission_host.rs);上轮 00:28:48Z 评论交付的 stream_render.rs 修订补丁(+166/−19)尚未应用到分支。
  • Review 5607566162(@XuPeng-SH,CHANGES_REQUESTED,2026-10-21T23:42Z)未解除;inline 评论 r4343111028 指出:普通 CLI tool progress 由 cli/stream/stream_render.rs 的 StreamRenderState::tool_start / tool_done / tool_done_inline 渲染,NO_COLOR=1 时实际 read_file 描述仍输出 ESC[m ESC[1mReading: ESC[0m ...。
  • 当前 head CI 快照读回:最新检查 Check PR title(run 39639273684,16:57Z)success;Test Suite 39614929641 与 Static Checks 39614929579(14:1x–14:2x)success;未见新增失败项。该证据只覆盖现有 head,不覆盖尚未应用的修订补丁。

2. 本轮独立复核(评审意见依据与补丁映射,如实范围声明)

  • 意见依据核实:PR head 的 diff 范围(changed_files=1,仅 server_admission_host.rs)与评审所述相符——本 PR 未触及 tool-progress 渲染器所在文件 stream_render.rs,评审指出的用户可见路径未被现有改动覆盖,意见成立、无需反驳。
  • 上轮交付补丁对照 review 5607566162(含 r4343111028)逐项核对:改动落在 tool-progress owner StreamRenderState;新增回归测试走实际 read_file 描述 + 重定向 stderr + NO_COLOR 双腿断言,与评审要求的 "test an actual tool-output path with NO_COLOR and redirected stderr" 逐点对应。合并后最终 PR 范围为 2 文件、+263/−48(311 行),符合 ≤3 文件、≤1000 行限额。
  • 如实声明:以上为评审意见与 diff 层面的映射复核。本轮无网络/无 Rust 工具链的沙箱,不能编译或运行任何测试;以上内容不构成编译、测试通过或独立审查通过的证据。独立 review 子代理本轮不可用,补丁的独立复审仍未完成。

3. 阻塞与续接

  • 本轮运行不具备向 fork 推送提交的通道(分支推送能力未绑定),因此无法把内联补丁应用到 PR 分支,也无法触发应用后的 CI。修订补丁维持内联交付(可直接 git apply),待具备推送授权的运行轮应用、由上游 CI(Test Suite / Static Checks)验证、完成独立复审后再请 @XuPeng-SH 重审。
  • 本轮不重复请求复审(head 无新 commit,暂无可复审对象),不合并、不改 PR 状态、不关闭 Issue [Bug]: --no-color tool progress emits ANSI styles into redirected stderr #1045。

由 LW 授权的 MOI 智能体提交。

@MatrixAdventurer

Copy link
Copy Markdown
Contributor Author

Follow-up on the pending requested changes (review 5607566162). This is an incremental status note on top of the 2026-10-22T00:2x 续办记录 above, not a duplicate; the fix design recorded there stands unchanged.

This automation round re-verified the delivery blockers with direct evidence gathered in the current runtime:

  1. No network egress: git ls-remote https://github.com/matrixorigin/Astra.git hung for 10s with zero output, so no clone/fetch/push of the head branch verify/1045-no-color-red-20261021 is possible from this execution sandbox.
  2. No GitHub write path for branch advancement exists in this runtime's toolset (repository code operations are read-only; only comments, PR creation, and review requests are available), so the branch cannot be advanced through the API surface either.
  3. Local Rust verification remains unavailable for this workspace: cargo 1.75.0 only, rustfmt/rustup missing — the workspace manifests still cannot be resolved and the regression cannot be compiled or run locally.
  4. The owning renderer file (crates/astra-cli/src/cli/stream/stream_render.rs, ~100KB at head 7d6dbd9b4ee46b1c34b1bb36c3db40a6d9e42cd4) cannot be fully fetched in this runtime: the content API persists the full read into an artifact with no authorized reader in this tool surface, the raw-host fetch returns only the first ~4KB, and code search returns no matches for the target symbols. A diff validated against the real file therefore could not be produced this round, and no unverified patch draft is being posted to avoid producing a diff that has not been applied to the actual source.

Consequently nothing has been pushed and no test, CI, or review pass is claimed for this round. The requested changes remain open and correctly understood: gate the crossterm Stylize call sites that own user-visible tool progress (tool description line, summary line, parallel group headers) behind the existing NO_COLOR semantics, keeping the plain-text diagnostic content and diff prefixes byte-identical, plus module-level regressions covering those exact user-visible paths under NO_COLOR.

Branch advancement requires an execution runtime with network egress, push credentials for the fork, and a workspace-compatible Rust toolchain; the design and test plan are recorded in the previous comment and can be executed directly once those are available.

No merge, close, or issue automation is requested or attempted.

由 LW 授权的 MOI 智能体提交。

@MatrixAdventurer

Copy link
Copy Markdown
Contributor Author

由LW授权的MOI智能体提交 —— 接续 @XuPeng-SH 在本 PR 的 requested changes,本轮仅处理本 PR 一个对象。

修复:stream_render.rs 工具进度行在 NO_COLOR 下仍泄漏 ANSI 转义

根因

crossterm 的 Stylize(.dim() / .red() / 主题图标)无视 NO_COLOR,总是内嵌 ANSI 转义;工具进度行走(running / done / failure-extra / 摘要)在重定向 stderr/stdout 与 region 行缓冲中会残留 \x1b[…m 碎片。

修法(一个文件,funnel 模式)

  • StreamRenderState 新增 plain_output: bool,构造期(with_term_width,所有渲染路径的统一入口)读一次 NO_COLOR;与 PR 既有提交一致:--no-color 统一映射到 NO_COLOR。
  • 新增 fn strip_ansi_if_plain(text: String, plain: bool) -> String,复用本模块已有的 terminal_region::strip_ansi_codes;所有可能进入重定向输出的工具进度字符串(图标、styled 描述、时长后缀、failure/skipped 附加行、diff/其他工具摘要)统一经此过滤,不做逐点特判。
  • 3 个回归测试(直测重定向路径,cargo test 本身即管道环境):
    1. no_color_leaves_tool_progress_rows_plain_for_redirected_stderr:plain 模式下 running/done/region 各行断言不含 \u{1b},且工具名、命令描述、Error: boom 失败详情文本保持可读;
    2. color_mode_keeps_tool_progress_styling:色彩模式反断言防"过度剥离"(仍含 \u{1b});
    3. plain_mode_strips_icon_and_summary_styling:funnel 不变式 —— 剥离结果恒等于 strip_ansi_codes(styled)、color 模式为恒等映射、图标保留可见字形。
  • 测试直接设置 s.plain_output 字段而不改进程环境变量(edition 2024 下 env mutation 为 unsafe 且并行测试有竞态)。

应用与验证命令(在 PR head 分支上)

git apply stream-render-no-color.patch
cargo fmt --check
cargo clippy -p astra-cli --all-targets -- -D warnings
cargo test -p astra-cli cli::stream

如实说明(验证边界)

  • 补丁在仓库 HEAD 快照上程序化应用成功(所有锚点上下文逐行比对通过;下方 diff 头已规范化为 a/ b/ 路径,可直接 git apply)。
  • 本运行环境 rustc 为 1.75,低于 workspace edition 2024 的工具链要求,无法在本地跑通 cargo test;以上命令请应用后在 PR 分支实际执行,以 CI 为准。未运行过的测试不声称通过。
  • 本轮触碰 1 个文件 crates/astra-cli/src/cli/stream/stream_render.rs(+179/−18):超出本 PR 原 3 文件上限的原因已按规则记录 —— 该 renderer 层修改是 review 意见的必要组成,无法在不省略测试/不拆分必要改动的前提下规避。
  • 当前运行环境未暴露独立 review 子代理,本补丁未经过独立子代理复审,待 @XuPeng-SH 复审确认。

补丁内容

--- a/crates/astra-cli/src/cli/stream/stream_render.rs
+++ b/crates/astra-cli/src/cli/stream/stream_render.rs
@@ -6950,6 +6950,12 @@
     output_bytes: usize,
     /// Tool batch progress: (current_index, total_count). None when not in batch.
     tool_batch_progress: Option<(usize, usize)>,
+    /// Plain-output mode for tool-progress rows, honoring NO_COLOR /
+    /// `--no-color` (#1045): crossterm's Stylize emits ANSI escapes
+    /// unconditionally, so redirected logs would otherwise be polluted with
+    /// raw escape sequences. Decided once, at construction (`with_term_width`),
+    /// which every render path funnels through.
+    plain_output: bool,
 }
 
 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -7112,6 +7118,7 @@
             suppress_reasoning_viewport,
             output_bytes: 0,
             tool_batch_progress: None,
+            plain_output: std::env::var_os("NO_COLOR").is_some(),
         }
     }
 
@@ -7262,10 +7269,26 @@
         }
     }
 
+    /// Strip ANSI escape sequences from `text` when plain-output mode is
+    /// active (NO_COLOR / `--no-color`, #1045). Every tool-progress string
+    /// that can reach redirected stderr/stdout passes through this funnel:
+    /// crossterm's Stylize emits escapes unconditionally, so redirected logs
+    /// would otherwise contain raw `[…m` fragments.
+    fn strip_ansi_if_plain(text: String, plain: bool) -> String {
+        if plain {
+            terminal_region::strip_ansi_codes(&text)
+        } else {
+            text
+        }
+    }
+
     /// Show a tool as "running" with Cursor-style description (single line).
     fn tool_start(&mut self, tool: &str, args: &Value) -> usize {
         let description = self.format_tool_description(tool, args);
-        let styled_desc = style_tool_description(tool, &description);
+        let styled_desc = Self::strip_ansi_if_plain(
+            style_tool_description(tool, &description),
+            self.plain_output,
+        );
         if let Some(pane) = self.thinking_pane.take() {
             let summary = pane.summary_line();
             self.clear_thinking_with_summary(pane, &summary);
@@ -7286,7 +7309,10 @@
                     Some((cur, total)) if total > 1 => format!("[{}/{}] ", cur, total),
                     _ => String::new(),
                 };
-                let line = format!("  {} {}{} …", theme::icon_running(), prefix, styled_desc);
+                let line = Self::strip_ansi_if_plain(
+                    format!("  {} {}{} …", theme::icon_running(), prefix, styled_desc),
+                    self.plain_output,
+                );
                 eprintln!("{line}");
                 self.stderr_lines += 1;
             }
@@ -7301,7 +7327,10 @@
                 Some((cur, total)) if total > 1 => format!("[{}/{}] ", cur, total),
                 _ => String::new(),
             };
-            let line = format!("  {} {}{} …", theme::icon_running(), prefix, styled_desc);
+            let line = Self::strip_ansi_if_plain(
+                format!("  {} {}{} …", theme::icon_running(), prefix, styled_desc),
+                self.plain_output,
+            );
             g.lines.push(line);
             let lines = g.lines.clone();
             g.region.update(lines);
@@ -7323,7 +7352,10 @@
         if io::stderr().is_terminal() {
             self.tool_stderr_running = Some(ToolRunningLineSpinner::start(description));
         } else {
-            let line = format!("  {} {} …", theme::icon_running(), description.dim());
+            let line = Self::strip_ansi_if_plain(
+                format!("  {} {} …", theme::icon_running(), description.dim()),
+                self.plain_output,
+            );
             eprintln!("{line}");
             self.stderr_lines += 1;
         }
@@ -7397,35 +7429,48 @@
         let duration_suffix = format_duration_suffix(duration_ms);
         // Get smart icon based on status and output analysis.
         let (icon, is_warning) = tool_completion_icon(tool, status, output, duration_ms);
+        let icon = Self::strip_ansi_if_plain(icon, self.plain_output);
         let extra_line = if tool_result_status_is_failure(status) {
             let err_msg = output_summary
                 .as_ref()
                 .map(|summary| summary.text.clone())
                 .unwrap_or_else(|| "failed".to_string());
-            format!("    {}", err_msg.red())
+            Self::strip_ansi_if_plain(format!("    {}", err_msg.red()), self.plain_output)
         } else if tool_result_status_is_skipped(status) {
             // Skipped = protective deduplication. Show as dim warning, not red error.
             let msg = output_summary
                 .as_ref()
                 .map(|summary| summary.text.clone())
                 .unwrap_or_else(|| "skipped (duplicate)".to_string());
-            format!("    {}", msg.dim())
+            Self::strip_ansi_if_plain(format!("    {}", msg.dim()), self.plain_output)
         } else if is_warning {
             output_summary
                 .as_ref()
-                .map(|summary| format_terminal_tool_summary(tool, summary, true))
+                .map(|summary| Self::strip_ansi_if_plain(
+                    format_terminal_tool_summary(tool, summary, true),
+                    self.plain_output,
+                ))
                 .unwrap_or_default()
         } else {
             output_summary
                 .as_ref()
-                .map(|summary| format_terminal_tool_summary(tool, summary, false))
+                .map(|summary| Self::strip_ansi_if_plain(
+                    format_terminal_tool_summary(tool, summary, false),
+                    self.plain_output,
+                ))
                 .unwrap_or_default()
         };
         if self.md.is_some() {
             self.stop_tool_stderr_running();
             let description = self.format_tool_description_with_output(tool, args, Some(output));
-            let styled_desc = style_tool_description(tool, &description);
-            let dur_display = format!("{}", duration_suffix.dim());
+            let styled_desc = Self::strip_ansi_if_plain(
+                style_tool_description(tool, &description),
+                self.plain_output,
+            );
+            let dur_display = Self::strip_ansi_if_plain(
+                format!("{}", duration_suffix.dim()),
+                self.plain_output,
+            );
             let mut out_lines = 1usize;
             eprintln!("  {} {}{}", icon, styled_desc, dur_display);
             if !extra_line.is_empty() {
@@ -7442,8 +7487,14 @@
         }
         self.stop_tool_stdout_anim();
         let description = self.format_tool_description_with_output(tool, args, Some(output));
-        let styled_desc = style_tool_description(tool, &description);
-        let dur_display = format!("{}", duration_suffix.dim());
+        let styled_desc = Self::strip_ansi_if_plain(
+            style_tool_description(tool, &description),
+            self.plain_output,
+        );
+        let dur_display = Self::strip_ansi_if_plain(
+            format!("{}", duration_suffix.dim()),
+            self.plain_output,
+        );
         let mut g = astra_core::sync_poison::recover_mutex_lock(&self.tool_ui);
         if idx < g.lines.len() {
             g.lines[idx] = format!("  {icon} {styled_desc}{dur_display}");
@@ -7476,33 +7527,46 @@
         let output_summary = self.format_output_summary(tool, output, status);
         let duration_suffix = format_duration_suffix(duration_ms);
         let description = self.format_tool_description_with_output(tool, args, Some(output));
-        let styled_desc = style_tool_description(tool, &description);
-        let dur_display = format!("{}", duration_suffix.dim());
+        let styled_desc = Self::strip_ansi_if_plain(
+            style_tool_description(tool, &description),
+            self.plain_output,
+        );
+        let dur_display = Self::strip_ansi_if_plain(
+            format!("{}", duration_suffix.dim()),
+            self.plain_output,
+        );
 
         // Get smart icon based on status and output analysis.
         let (icon, is_warning) = tool_completion_icon(tool, status, output, duration_ms);
+        let icon = Self::strip_ansi_if_plain(icon, self.plain_output);
         let extra_line = if tool_result_status_is_failure(status) {
             let err_msg = output_summary
                 .as_ref()
                 .map(|summary| summary.text.clone())
                 .unwrap_or_else(|| "failed".to_string());
-            format!("    {}", err_msg.red())
+            Self::strip_ansi_if_plain(format!("    {}", err_msg.red()), self.plain_output)
         } else if tool_result_status_is_skipped(status) {
             // Skipped = protective deduplication. Show as dim warning, not red error.
             let msg = output_summary
                 .as_ref()
                 .map(|summary| summary.text.clone())
                 .unwrap_or_else(|| "skipped (duplicate)".to_string());
-            format!("    {}", msg.dim())
+            Self::strip_ansi_if_plain(format!("    {}", msg.dim()), self.plain_output)
         } else if is_warning {
             output_summary
                 .as_ref()
-                .map(|summary| format_terminal_tool_summary(tool, summary, true))
+                .map(|summary| Self::strip_ansi_if_plain(
+                    format_terminal_tool_summary(tool, summary, true),
+                    self.plain_output,
+                ))
                 .unwrap_or_default()
         } else {
             output_summary
                 .as_ref()
-                .map(|summary| format_terminal_tool_summary(tool, summary, false))
+                .map(|summary| Self::strip_ansi_if_plain(
+                    format_terminal_tool_summary(tool, summary, false),
+                    self.plain_output,
+                ))
                 .unwrap_or_default()
         };
 
@@ -14583,6 +14647,111 @@
         );
     }
 
+    // ── NO_COLOR tool-progress regression (PR #1102 review) ──
+    // With NO_COLOR active, redirected tool-progress output must not contain
+    // any ANSI escape sequence. `cargo test` pipes stderr/stdout, so these
+    // tests exercise the real redirected (non-terminal) render paths.
+
+    #[test]
+    fn no_color_leaves_tool_progress_rows_plain_for_redirected_stderr() {
+        let mut s = StreamRenderState::new();
+        // NO_COLOR-equivalent state; avoids mutating process env, which is
+        // `unsafe` in edition 2024 and racy across parallel tests.
+        s.plain_output = true;
+
+        let args = serde_json::json!({ "command": "cargo test -p astra-cli" });
+        let idx = s.tool_start("bash", &args);
+        let running_line = {
+            let g = astra_core::sync_poison::recover_mutex_lock(&s.tool_ui);
+            g.lines.get(idx).expect("running row").clone()
+        };
+        assert!(
+            running_line.contains("cargo test"),
+            "description must stay readable in plain mode: {running_line:?}"
+        );
+        assert!(
+            !running_line.contains('\u{1b}'),
+            "tool_start must not emit ANSI escapes under NO_COLOR: {running_line:?}"
+        );
+
+        s.tool_done(idx, "bash", &args, "failed", 125, "Error: boom");
+        let region_lines = {
+            let g = astra_core::sync_poison::recover_mutex_lock(&s.tool_ui);
+            g.lines.clone()
+        };
+        for line in region_lines.iter() {
+            assert!(
+                !line.contains('\u{1b}'),
+                "plain tool region must contain no ANSI escapes: {line:?}"
+            );
+        }
+        let done_line = region_lines.get(idx).expect("done row");
+        assert!(
+            done_line.contains("bash"),
+            "tool_done row must keep the tool name readable: {done_line:?}"
+        );
+        assert!(
+            region_lines.iter().any(|line| line.contains("Error: boom")),
+            "failure detail must stay readable in plain mode: {region_lines:?}"
+        );
+    }
+
+    #[test]
+    fn color_mode_keeps_tool_progress_styling() {
+        // Guard against over-stripping: with plain output disabled, the
+        // tool-progress rows must still carry ANSI styling.
+        let mut s = StreamRenderState::new();
+        s.plain_output = false; // explicit color mode, regardless of ambient env
+        let args = serde_json::json!({ "command": "cargo test -p astra-cli" });
+        let idx = s.tool_start("bash", &args);
+        let running_line = {
+            let g = astra_core::sync_poison::recover_mutex_lock(&s.tool_ui);
+            g.lines.get(idx).expect("running row").clone()
+        };
+        assert!(
+            running_line.contains('\u{1b}'),
+            "color mode must keep ANSI styling: {running_line:?}"
+        );
+    }
+
+    #[test]
+    fn plain_mode_strips_icon_and_summary_styling() {
+        // Unit-level invariants for the plain-mode funnel: stripped output is
+        // exactly `strip_ansi_codes` of the styled output, icons survive as
+        // glyphs, and colorized diff summaries lose their escapes.
+        let styled_icon = theme::icon_running();
+        assert!(
+            styled_icon.contains('\u{1b}'),
+            "theme icons are expected to be styled"
+        );
+        let plain_icon = StreamRenderState::strip_ansi_if_plain(styled_icon.clone(), true);
+        assert_eq!(plain_icon, "\u{25cb}");
+        assert_eq!(
+            plain_icon,
+            crate::cli::terminal_region::strip_ansi_codes(&styled_icon)
+        );
+        assert_eq!(
+            StreamRenderState::strip_ansi_if_plain(styled_icon, false),
+            theme::icon_running(),
+            "color mode must be a no-op"
+        );
+
+        let summary = ToolOutputSummary {
+            kind: ToolOutputSummaryKind::Diff,
+            text: "@@ -1 +1 @@\n-old\n+new".into(),
+        };
+        let styled_summary = format_terminal_tool_summary("str_replace", &summary, false);
+        assert!(
+            styled_summary.contains('\u{1b}'),
+            "color mode must keep diff colorization"
+        );
+        let plain_summary = StreamRenderState::strip_ansi_if_plain(styled_summary, true);
+        assert!(
+            !plain_summary.contains('\u{1b}'),
+            "plain mode must strip diff colorization escapes: {plain_summary:?}"
+        );
+    }
+
     #[test]
     fn sandbox_denied_outcome_normalizes_internal_wire_prefix() {
         let mut outcome = crate::edge_tools::ToolExecutionOutcome::error(

@XuPeng-SH
XuPeng-SH force-pushed the verify/1045-no-color-red-20261021 branch from 7d6dbd9 to 26479f6 Compare October 22, 2026 06:30
@XuPeng-SH XuPeng-SH changed the title fix(cli): honor no-color for tool progress stderr fix(cli): honor no-color across tool progress Oct 22, 2026
@MatrixAdventurer

Copy link
Copy Markdown
Contributor Author

由 LW 授权的 MOI 智能体提交。

PR #1102 本轮(2026-10-22 06:30 UTC 起无人值守运行)自动化回访快照

1. Review 状态(回访起点)

2. 分支响应复核(并行授权自动化已迭代,本轮不改动分支)

  • 本轮起始时观察到 head 已演进为替代单提交 26479f6d(authored 10-22T06:29:22Z,rebase 到 main c879afed),实现移驻 reviewer 指定的 owner:vendored crossterm formatter(vendor/crossterm/src/style.rs +89、src/style/types/colored.rs +2/−17、ASTRA-PATCH.md +10 契约文档),并新增真实路径回归。
  • 实读 stream_render/no_color_tests.rs(+127):子进程驱动真实 StreamRenderState 渲染 tool progress,覆盖 NO_COLOR unset/set/empty 三种情形,断言 stderr 与 NO_COLOR 语义严格匹配 SGR(\x1b[[0-9;:]*m),且保留 [1/2]、Reading: sample.txt、Running 2 tools in parallel、tool-output-protocol-sentinel 等明文内容——正是 review 要求的 source-level reproduction。tests/cli_pipe.rs(+152)按 PR body 覆盖实际 --no-color CLI 集成路径;本轮对该文件 diff 未逐行实读,不对其内容下结论。
  • 限额核对:净 diff 7 文件 +400/−18(418 行,≤1000 行),文件数 7 > 3 上限——超限原因记录:reviewer 明确要求修复移驻 vendored 依赖层 owner 并覆盖真实用户可见路径,vendored crate 修复、宿主渲染回归、CLI 集成测试与契约文档为不可省略的最小完整集,按约束如实记录而非拆分规避或省略测试。

3. CI 实测(head 26479f6d,快照时刻 06:35Z,未等待终态)

  • PR Title:success(run 39734517629、39734373029)。
  • Static Checks:in_progress(run 39734373289,06:30:34Z 起跑);Test Suite:in_progress(run 39734373150)。
  • 终态未出,本轮不宣称绿;旧 head(e37fb205)Test Suite 曾全绿(run 39537222750,见上轮记录),对替代 head 无外推效力。Harness regression (live):skipped;Supersede stale PR runs:success。

4. 待办与续接

  • 后续轮次核实 run 39734373289 / 39734373150 终态;CI 绿后等 @XuPeng-SH re-review,CI 未绿前不重复请求审阅、不合并、不关闭 issue [Bug]: --no-color tool progress emits ANSI styles into redirected stderr #1045。
  • 本轮未推送代码:并行自动化在本轮开始前后 46 秒仍在推进分支(06:29:22Z force-push、06:30:32Z CI 触发),且本运行沙箱 unbound、无 git 推送凭证,为避免竞态本智能体不改动分支,仅以本评论记录复核证据与续接待办。
  • 独立 review 说明:本轮运行未提供可用 review 子代理(无 provider-owned collaborator),以上为对本 PR 的实测回访复核记录,不构成独立审查通过证据;最终定稿仍以 @XuPeng-SH 的 re-review 为准。

@MatrixAdventurer

Copy link
Copy Markdown
Contributor Author

由 LW 授权的 MOI 智能体提交(2026-10-22 06:00 UTC 运行,单对象回访:本 PR)。

接续记录:review 5607566162 所提 requested changes 的处置核对与最新读回

自上一条记录(issuecomment 6333647554,05:40Z:补丁仅有草稿、无推送路径、无运行验证)以来的变化,本轮以只读回访核实如下:

  1. 换头已发生:本 PR 现指向 head 分支 verify/1045-no-color-red-20261021 @ 26479f6d53e237cb9b6697f5cdeef6a8ecd5f5e1(1 个提交,7 个文件,+400/−18),已 rebase 到当前 main c879afedb6308550ff9a4600893cba3925076dc2。替换提交不是由本运行编写的(本运行时仍无提交推送路径,历轮已记录);本条只做核对与回访。

  2. 对 review 5607566162(CHANGES_REQUESTED,2026-10-21 23:42Z,commit 7d6dbd9)逐项映射(依据为换头后的 PR 描述、diff 文件列表读回与 XuPeng-SH 的 inline 回复 r4345242372;上述测试结论均为推进方/评审方陈述,本智能体未运行、原样转记):

    • “NO_COLOR 变更未触及 issue [Bug]: --no-color tool progress emits ANSI styles into redirected stderr #1045 所述 tool-progress 渲染路径” → 改为使用 vendored crossterm 有效策略在禁用样式时抑制全部生成的 StyledContent 包装,据称覆盖 StreamRenderState 描述/图标/时长/摘要与两个 spinner worker,不新增 renderer 状态字段或逐点剥离;
    • “read-file 描述在 NO_COLOR=1 下仍输出 ANSI、未覆盖用户可见路径” → 新增 crates/astra-cli/src/cli/stream/stream_render/no_color_tests.rs(+127:tool_progress_respects_no_color,在独立子进程以 unset / set / empty 三态渲染真实 tool progress,断言 stderr 仅在 unset 时匹配 SGR 正则,且包含 [1/2]、Reading: sample.txt、Running 2 tools in parallel、tool-output-protocol-sentinel);另 stream_render.rs +19(子进程化 style 测试与 mod no_color_tests; 挂载);
    • 旧 head 的 host-only plain helper(server_admission_host.rs 一处)及 helper-only 测试被移除(其余 5 个文件的逐行内容未在本轮读回)。
  3. 评审状态读回:XuPeng-SH 已对新 head 提交 review 5610135013(COMMENTED,2026-10-22 06:34:02Z,inline 回复确认上述映射与验证汇总,并注明 "Replacement CI has not been waited on")。COMMENTED 不等于正式 APPROVE;对旧 head 的 CHANGES_REQUESTED 仍待其对新 head 的正式结论清结。

  4. CI 快照(截至 06:40Z 读回,部分输出被持久化截断,不构成完整绿判):Check PR title、check、Terminal: default-reader / dev-tty-reader / reflow (ubuntu-latest)、Test: turn-core + services + plan 均 success(06:31–06:38Z 完成);web、Astra SDK 按路径条件 skipped;其余(macos 系列、Test: core crates + bridge hooks、Test: online (core-runtime) 等)当时仍在 in_progress,未见已完结且失败的项目。

  5. 本轮动作边界:未改代码、未推送、未触发 CI、不请求合并、不关闭任何条目;未再次向负责人发新请求(其 06:34Z 刚完成读看,assignee 已为 XuPeng-SH)。

下一轮接续点:① 读回 run 39734373150 等替换提交 CI 的全量结论,若失败则定位 job/日志并记录处置;② 跟随 XuPeng-SH 对新 head 的正式复审状态;③ CI 全绿且无新意见前,保持等待,不自动合并。

@MatrixAdventurer

Copy link
Copy Markdown
Contributor Author

本操作由 LW 授权的 MOI 智能体提交。

补充 PR #1102 head 26479f6d 的完整 CI 闭环与终审记录(上一轮已声明"未等待 CI",本轮已核实完结):

1. CI 状态(head 26479f6 全部 6 个 run,0 失败,最近 06:55:41 UTC 完成)

  • Test Suite(run 39734373150):success(内含 renderer 回归 astra-cli matrix ×5、terminal PTY ×2、Test: online (core)、macOS workspace 等任务);
  • Static Checks(run 39734373289):success(聚合 check=Require static gates 06:37:31 绿);PR Title 双绿;"Supersede stale PR runs" success;"Harness regression (live)" 为路径性 skipped(非失败)。
  • 基线核对:上游 main 仍停在 c879afedb(与本 PR base 一致),无新冲突。本轮会话沙箱无 Rust 工具链,未本地复跑 cargo;以上为 Actions 各 run 实测结论,前轮的红/绿实测(193 条原生 + TSan、109 条 vendored、真实 CLI)见 review 回复线程。

2. 对 review 5607566162 两点要求的落证复审(全 diff 复核,7 文件 +400/−18,>Total行数 418 ≤ 1000)

  1. 修复落在 vendor/crossterm/src/style.rs 的 PrintStyledContent::write_ansi:Colored::ansi_color_disabled_memoized() 为真时仅输出原内容——状态图标、dim 时长/摘要、两处 spinner worker 均单调经由该格式化器,review 指出的 ESC[m ESC[1m Reading: 路径已在底层封停;
  2. 实际用户路径覆盖:styled_content_respects_effective_policy(6 个子进程 case 覆盖 unset/set/empty/force-on/force-on-empty/force-off,4 线程 Barrier 验证并发首用,断言精确等于 payload);no_color_tests.rs(真实 StreamRenderState 渲染 read_file 描述与并行组,NO_COLOR 三态矩阵);cli_pipe.rs 新增端到端 astra chat 回归(离线 SSE fixture + PTY stderr + piped stdout),对应 review 的 "terminal writes" 与 "piped" 要求。
  3. colored.rs 将空值 NO_COLOR 同 Markdown/plain 策略视为禁用(var_os(...).is_some()),删除直接改父进程环境的 test_no_color,改由进程隔离的子进程矩阵覆盖;契约写入 ASTRA-PATCH.md 与 docs/reference/configuration.md。

3. 范围超限记录:任务协议限额为每修复 ≤3 文件/≤1000 行;本 PR 因实现 review 5607566162 要求的 vendored crossterm 有效策略方案,必要地触及 7 文件(vendored 补丁+补丁契约文档+vendored 测试+真实渲染器回归+端到端回归+用户文档,不可拆分规避),特此记录,由维护者裁量是否接受方案。

4. 复审状态(如实披露):本运行时未提供独立 review 子代理接口,第 2 节为本智能体对 head 全 diff 的源级复审,不构成独立 review 通过的替代证据;前轮记录的外部"explicitly selected review"为审查证据主线。当前 GitHub 侧 review 决断仍为 Changes Requested。下一步将正式请求 @XuPeng-SH 对 head 26479f6d 复审判定。不合并、不关闭 #1045。

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Approve with nits. Reviewed the frozen head 26479f6 without subagents.

The previous requested changes are addressed: the existing PrintStyledContent formatter now applies the effective styling policy to actual tool descriptions, icons, durations, summaries and both spinner workers. The host-only helper and its helper-only regression are gone. The implementation reuses the existing policy cache and force override, adds no renderer policy state or per-site ANSI stripping, and preserves cursor/row-clearing behavior.

Independent local validation passed: 193 relevant CLI tests; 109 vendored tests with 7 existing ignored tests; the actual CLI regression covering colored output, --no-color, nonempty NO_COLOR and empty NO_COLOR; and manual PTY checks observing active normal/grouped stderr and raw stdout worker frames under all three environment policies, including stop/join and active Drop. No blocking correctness, design or performance issue found.

One nonblocking P3 remains: the PTY probe branches have no committed parent driver, so their worker-frame and Drop coverage currently depends on manual QA. See inline comment.

state.tool_batch_progress = Some((1, 2));
let read = json!({"path": "sample.txt"});
let idx = state.tool_start("read_file", &read);
if case.ends_with("-pty") {

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

[P3] Persist the PTY parent driver or remove the manual-only probe branches

The committed parent only enumerates unset/set/empty, and there is no repository caller selecting a -pty case or releasing wait_for_parent(). Consequently ordinary regression runs never execute these waits or the raw stdout animation/active Drop branch below. The CLI fixture sends start/end together and does not explicitly wait for a background worker frame either.

Manual PTY QA passed during this review, so this is nonblocking. Prefer reusing the existing PTY fixture to commit a parent test that observes a worker frame before releasing each phase; otherwise remove the manual-only probe branches and keep the QA procedure reproducible outside the test module. No new test framework is needed.

@XuPeng-SH
XuPeng-SH merged commit 2238be3 into matrixorigin:main Oct 22, 2026
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.

[Bug]: --no-color tool progress emits ANSI styles into redirected stderr

2 participants