Skip to content

fix(models): escape terminal controls in model selection reports - #176007

Merged
obviyus merged 3 commits into
openclaw:mainfrom
Alix-007:alix/fix-model-report-controls-20261018
Oct 18, 2026
Merged

obviyus merged 3 commits into
openclaw:mainfrom
Alix-007:alix/fix-model-report-controls-20261018

Conversation

@Alix-007

@Alix-007 Alix-007 commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: configured model references and aliases can clear terminal output or forge extra report lines when operators inspect model selection.

User Impact

User impact: aliases, text/image fallback lists, and model-selection status fields display control characters safely while retaining normal Unicode. JSON consumers and stored configuration keep the original values.

Why This Change Was Made

Use the existing terminal sanitizer at text output boundaries, before styling. Both fallback commands share the same owner. No routing, auth, configuration schema, defaults, dependencies, or migration changes.

Evidence

Built CLI, isolated config/state/HOME, no provider requests or production credentials:

  • Base: f45fe274c179872cf4078d14e7c1cae247b2f0b7
  • Product head: 29c737d890e2528202ab9d1dfabc20759b590f8a
  • GREEN run: 2026-10-18T02:26:11.606Z; Node 26.1.0 on Linux, OpenClaw 2026.10.4.
  • Real entry: node <checkout>/openclaw.mjs models …; all 12 child processes exited 0.
Actual CLI BASE controls: human / plain HEAD controls: human / plain
models aliases list 2 / 2 0 / 0
models fallbacks list 1 / 1 0 / 0
models image-fallbacks list 1 / 1 0 / 0
models status 14 / 1 0 / 0

BASE forged extra lines in all eight text modes. HEAD emitted visible \\n instead, with zero injected lines. The café Unicode control survived. All four --json controls retained the original alias/model strings, and the config-file SHA-256 was identical before/after the 12 commands. Readback is captured child stdout/stderr/exit status plus actual config bytes.

Focused regressions: 49 passing tests across aliases.test.ts (11), fallbacks-shared.test.ts (14), and list.status.test.ts (24). Core and canonical commands-test type checks, changed-file type-aware lint, formatting, line-cap ratchet, and independent adversarial review passed. The final focused fallback invocation was OPENCLAW_VITEST_RUNTIME=node pnpm test src/commands/models/fallbacks-shared.test.ts --maxWorkers=1 (exit 0).

Reproduce the actual CLI proof

Use clean checkouts at the two SHAs above, each installed with the pinned pnpm and built normally with pnpm build qaRuntime. Save the following two files together outside the product checkout, then run the same collector against each:

node proof-models.mjs <base-checkout> red
node proof-models.mjs <head-checkout> green

Only the helper import path below is flattened for copying. The fixture, subprocess entry, assertions, and recorder are unchanged between RED/GREEN. Each run creates an independent temporary HOME, config, state, workspace, and log, verifies the clean checkout/build stamp, and records stdout/stderr/exits plus readback in its printed receipt directory.

proof-models.mjs:

import assert from 'node:assert/strict';
import fs from 'node:fs';
import {fixture} from './proof-cli-common.mjs';

const f = fixture('models-terminal', process.argv[2], process.argv[3]);
const alias = 'café\x1b[2J\npretend';
const primary = 'openai/model\x1b[2J\nprimary';
const fallback = 'openai/fallback\x1b[2J\nnext';
const image = 'openai/image\x1b[2J\nnext';
f.config.agents.defaults.model = {primary, fallbacks: [fallback]};
f.config.agents.defaults.imageModel = {primary: 'openai/image-model', fallbacks: [image]};
f.config.agents.defaults.utilityModel = '';
f.config.agents.defaults.models = {[primary]: {alias}, [fallback]: {}, [image]: {}};
f.writeConfig();
const configHash = f.hash(fs.readFileSync(f.configPath));
const commands = [['models', 'aliases', 'list'], ['models', 'fallbacks', 'list'], ['models', 'image-fallbacks', 'list'], ['models', 'status']];
for (const command of commands) {
  for (const plain of [false, true]) {
    const result = f.run(`${command.join('-')}${plain ? '-plain' : ''}`, [...command, ...(plain ? ['--plain'] : [])]);
    assert.equal(result.code, 0, result.stderr);
    const controls = (result.stdout.match(/[\x00-\x09\x0b-\x1f\x7f-\x9f]/g) ?? []).length;
    const injectedLines = result.stdout.includes('\npretend') || result.stdout.includes('\nprimary') || result.stdout.includes('\nnext');
    if (f.phase === 'red') { assert.ok(controls > 0); assert.equal(injectedLines, true); }
    else { assert.equal(controls, 0); assert.equal(injectedLines, false); assert.ok(result.stdout.includes('\\n')); }
    if (command[1] === 'aliases') assert.ok(result.stdout.includes('café'));
    f.receipt.observations.push({command: command.join(' '), plain, controls, injectedLines});
  }
  const json = f.run(`${command.join('-')}-json-control`, [...command, '--json']);
  assert.equal(json.code, 0, json.stderr);
  const payload = JSON.parse(json.stdout);
  if (command[1] === 'aliases' || command[1] === 'status') assert.equal(payload.aliases[alias], primary);
  if (command[1] === 'fallbacks') assert.deepEqual(payload.fallbacks, [fallback]);
  if (command[1] === 'image-fallbacks') assert.deepEqual(payload.fallbacks, [image]);
}
assert.equal(f.hash(fs.readFileSync(f.configPath)), configHash);
f.receipt.observations.push({configBytesUnchanged: true, jsonRawValuesPreserved: true});
f.finish();

proof-cli-common.mjs:

import assert from 'node:assert/strict';
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import {createHash} from 'node:crypto';
import {execFileSync, spawnSync} from 'node:child_process';

export function fixture(name, checkoutArg, phase) {
  assert.ok(['red', 'green'].includes(phase));
  const checkout = path.resolve(checkoutArg);
  const root = fs.mkdtempSync(path.join(os.tmpdir(), `alix-${name}-`));
  for (const leaf of ['home', 'state', 'workspace', 'tmp']) fs.mkdirSync(path.join(root, leaf));
  const hash = bytes => createHash('sha256').update(bytes).digest('hex');
  // Read-only containers receive a host Git attestation before the bind mount.
  const head = process.env.PROOF_CHECKED_HEAD ?? execFileSync('git', ['rev-parse', 'HEAD'], {cwd: checkout, encoding: 'utf8'}).trim();
  const status = process.env.PROOF_CHECKED_STATUS ?? execFileSync('git', ['status', '--porcelain'], {cwd: checkout, encoding: 'utf8'}).trim();
  assert.match(head, /^[a-f0-9]{40}$/);
  const stamp = JSON.parse(fs.readFileSync(path.join(checkout, 'dist/.buildstamp')));
  assert.equal(status, ''); assert.equal(stamp.head, head); assert.equal(stamp.inputsClean, true);
  const configPath = path.join(root, 'openclaw.json');
  const config = {agents: {ownership: 'explicit', defaults: {systemAgent: {agentId: 'main'}}, entries: {main: {workspace: path.join(root, 'workspace')}}}, tools: {profile: 'minimal'}, plugins: {allow: [], slots: {memory: 'none'}}, logging: {level: 'warn', consoleLevel: 'warn', file: path.join(root, 'runtime.log')}};
  const receipt = {name, phase, head, time: new Date().toISOString(), root, runs: [], observations: []};
  const save = () => fs.writeFileSync(path.join(root, 'receipt.json'), JSON.stringify(receipt, null, 2));
  const writeConfig = () => fs.writeFileSync(configPath, JSON.stringify(config), {mode: 0o600});
  writeConfig();
  const env = {PATH: `${path.dirname(process.execPath)}:/usr/bin:/bin`, HOME: path.join(root, 'home'), TMPDIR: path.join(root, 'tmp'), LANG: 'C.UTF-8', TZ: 'UTC', CI: '1', OPENCLAW_CONFIG_PATH: configPath, OPENCLAW_STATE_DIR: path.join(root, 'state'), OPENCLAW_NO_RESPAWN: '1', OPENCLAW_DISABLE_BONJOUR: '1'};
  function run(label, args) {
    const result = spawnSync(process.execPath, [path.join(checkout, 'openclaw.mjs'), ...args], {cwd: path.join(root, 'workspace'), env, encoding: 'utf8', timeout: 90000, maxBuffer: 4 * 1024 * 1024});
    const row = {label, args, code: result.status, stdout: result.stdout, stderr: result.stderr};
    receipt.runs.push(row); save();
    console.log(JSON.stringify({label, code: row.code}));
    assert.equal(result.error, undefined, 'Timeout/spawn errors are not product RED');
    assert.equal(result.signal, null);
    return row;
  }
  function finish() {receipt.result = 'PASS'; save(); console.log(JSON.stringify({result: 'PASS', receipt: path.join(root, 'receipt.json')}));}
  return {root, config, configPath, writeConfig, receipt, run, finish, hash, phase};
}
Scope and validation cost

Six files: production +23/-19 lines in three existing owners; tests +65 lines. Existing-solutions preflight found the canonical terminal sanitizer; no new helper or competing model-report fix was needed. Alias confirmations/catalog warnings and fallback confirmations use the same safe egress; JSON bypasses sanitization. Status coverage is limited to model-selection fields and associated route diagnostics.

Status shard: 128.62 s for 24 tests, predominantly cold compiler/import work. Alias/fallback shard: 19.68 s, with 11 alias tests passing; the final 14-test fallback rerun took 29.54 s (40.20 s including wrapper cleanup). The native changed-test selector hit unrelated gateway/infra root-budget overruns, so the explicit canonical commands test graph was checked instead.

Not tested: provider API probes, auth inventory/profile formatting, interactive PTY colors, Windows/macOS terminals, and the full CI suite locally. No claim that every auth/probe table is terminal-safe. Fixtures remain in the printed temporary directories for inspection; remove those generated fixture directories afterward. No production state or channels were loaded, changed, or messaged.

Maintainer follow-up

  • Kept the sanitizer only on the configured-value reports (models aliases list, models fallbacks list, models image-fallbacks list, models status). models aliases add already rejects any alias outside [A-Za-z0-9_.:-], and the add commands only echo the operator's own arguments, so those hunks were dropped.

  • Real CLI in an isolated container on main d3b680c03e: a plain JSON config edit with \u001b[2J\n... in an alias and fallback refs passes validation, and all six text modes write ESC/BEL bytes and forged lines (models status: 11 ESC/BEL bytes, 8 forged lines). On a7da8addaf all six modes write 0 ESC/BEL bytes and 0 forged lines. --json output for all four commands is byte-identical between base and candidate, and the config file is unchanged.

  • The status regression fails against main's source and passes on this head (49 focused tests).

  • The models status Aliases row sanitizes the alias and target before styling them (+9 production lines), because the row-level sanitizer would strip the per-part colors. With a clean config, text and rich TTY models status output is identical to main apart from profile paths. With a control-character alias, the rich row keeps main's colors and only loses the control bytes.

Merge danger: two-way door, text rendering only; no config, state or JSON contract change. Blast radius: the text output of the four models report commands.

@clawsweeper

clawsweeper Bot commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added commands Command implementations size: S labels Oct 18, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Oct 18, 2026
@clawsweeper

clawsweeper Bot commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR sanitizes configured model values in alias, fallback, and status text reports while preserving JSON and stored configuration.

Example: An alias contains café followed by ESC[2J, a newline, and forged.

  • Before: Listing aliases can clear the terminal and print forged on another line.
  • After: The report displays café\nforged on one line, while JSON retains the original alias.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) A focused, useful repair with shipped-entry evidence, meaningful regressions, and no actionable findings; exact-head CI remains pending.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Supplied isolated Linux built-CLI results exercise aliases, both fallback commands, and status text/JSON outputs; latest-head results show zero injected controls or forged lines, unchanged JSON/config bytes, and preserved rich alias colors.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Inspecting configured model selections can clear terminal content or display forged report lines.
Reason: Safe text rendering is an existing product contract, and the repair leaves configuration, routing, JSON, and ordinary output intact.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR fixes a current terminal-rendering defect with a focused patch and supplied CLI proof; no actionable introduced defects were found.

Priority: P2
Reviewed head: a7da8addafc9408944cc35498d03f526b97238bf

Before merge

None.

Findings

None.

Agent review details

How this fits together

The models CLI loads configured aliases and model references, resolves status information, and emits human-readable, plain-text, or JSON reports.

flowchart LR
  A[Configured model values] --> B[Models command owners]
  B --> C[JSON writer]
  B --> D[Terminal sanitizer]
  D --> E[Optional styling]
  E --> F[Text output]
Loading

Technical review

Best possible solution:

Keep sanitization at the existing text-report boundaries, before styling, with JSON and persisted values preserved.

Do we have a high-confidence way to reproduce the issue?

Current-main source directly emits configured controls, and supplied built-CLI results demonstrate terminal clearing and forged lines; this read-only review ran no target code.

Is this the best way to solve the issue?

The patch repairs the existing output owners using the canonical sanitizer, preserves stdout ownership and raw JSON, and retains rich alias colors without introducing state or a competing renderer.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against d3977b073466.

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Introduced patch: The pinned introduction diff changes existing report owners and adds focused regressions, without changing configuration writers, routing, defaults, or dependencies. (a7da8addafc9)
  • Current-main defect: Current main writes configured alias and target strings directly in both text modes; the fallback owner likewise writes raw entries. (src/commands/models/aliases.ts:39, d3977b073466)
  • Existing sanitizer contract: The reused sanitizer strips ANSI sequences and control characters, renders newline/tab/carriage-return visibly, and retains ordinary Unicode. (packages/terminal-core/src/safe-text.ts:11, a7da8addafc9)
  • Rich-output preservation: The latest commit sanitizes aliases and targets before applying their individual colors; the ordinary fields sanitize before styling and JSON returns earlier. (src/commands/models/list.status-command.ts:1214, a7da8addafc9)
  • Supplied shipped-entry proof: The PR body records isolated built-CLI before/after results, preserved Unicode and raw JSON values, unchanged config bytes, and latest-head text/rich-output comparisons; collaborator obviyus contributed the scope and color-preservation repairs. (a7da8addafc9)
  • Feature history and preserved contracts: History spans the original model commands, shared fallback refactors, stdout repair, status refactors, and the former list.status.e2e.test.ts name; Peter Steinberger is the strongest recurring owner, and Alix-007 has prior merged status work. Older blob searches encountered the local lazy-fetch limitation, while relevant base blame and current source remained available. (src/commands/models/list.status-command.ts:1150, d3977b073466)

Likely related people:

  • Peter Steinberger: Raw commit fcb8c0a adds src/commands/models/list.status-command.ts:1300 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: fcb8c0a23281; files: src/commands/models/list.status-command.ts)
  • Alix-007: Raw commit ef87dfe adds src/commands/models/list.status-command.ts:200 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: ef87dfec9ed3; files: src/commands/models/list.status-command.ts)

PR surface

Source +11, Tests +65. Total +76 across 6 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 32 21 +11
Tests 3 65 0 +65
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 97 21 +76

Review metrics

Metric Value Why it matters
Production versus test LOC Production +32/-21; tests +65/-0 The small production increase applies the existing sanitizer and preserves per-part alias colors; regression coverage exercises distinct report owners and text modes.

Labels

Label changes:

  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.

Label justifications:

  • P2: Configured control characters can corrupt operator-facing reports, with a limited CLI-rendering blast radius.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

History

Review history (2 earlier review cycles)
  • reviewed 2026-10-18T02:48:28.264Z sha 29c737d :: needs maintainer review before merge. :: none
  • reviewed 2026-10-18T18:15:06.452Z sha 0afd2bb :: needs maintainer review before merge. :: none

Reviewed October 18, 2026, 2:38 PM ET / 18:38 UTC (Revision 3).

Alias names are validated on add and the add commands echo the operator's own arguments, so only the list and status reports need the sanitizer.
@obviyus

obviyus commented Oct 18, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Oct 18, 2026
Sanitize the alias and target before styling them, so the rich Aliases row keeps its base colors.
@obviyus

obviyus commented Oct 18, 2026

Copy link
Copy Markdown
Collaborator

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Oct 18, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Oct 18, 2026
@obviyus
obviyus merged commit 5fb1a75 into openclaw:main Oct 18, 2026
130 of 131 checks passed
@obviyus

obviyus commented Oct 18, 2026

Copy link
Copy Markdown
Collaborator

Landed in 5fb1a75. Thanks @Alix-007 for the fix, and for sharing it with the community.

Maintainer follow-up: dropped sanitizing on paths that only echo the operator's own validated arguments, and kept the per-part colors on the models status Aliases row by sanitizing each part. Proven end to end with the real CLI against main.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 19, 2026
…nclaw#176007)

Text output of `openclaw models aliases list`, `models fallbacks list`, `models image-fallbacks list` and `models status` no longer writes control characters from configured aliases or model refs to the terminal. An alias edited into the config with an escape sequence or newline can no longer clear the screen or forge report lines. `--json` output and the existing colors are unchanged.

Proof: real CLI in secretless Docker, output through `od -c`, with a config-file alias containing a clear-screen escape and a newline. On main a79a48b the commands print ESC bytes and forged lines; the candidate prints none. With a clean config, `models status` output matches main in plain and rich (pty, `FORCE_COLOR=1`) mode, including the per-part alias colors. Live gate passed with openai/gpt-5-mini.

Thanks @Alix-007.

Co-authored-by: Ayaan Zaidi <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

commands Command implementations P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants