Skip to content

The agent that grows with you

fix(update): posix hand-off results stay valid JSON for any control character

Teknium684e7d713f40
diff --git a/scripts/desktop-update/posix.sh b/scripts/desktop-update/posix.sh
index 7211725d5f5..d6bda569a91 100755
--- a/scripts/desktop-update/posix.sh
+++ b/scripts/desktop-update/posix.sh
@@ -233,12 +233,19 @@ trap 'on_signal QUIT' QUIT
trap 'on_signal TERM' TERM
# ── shim ────────────────────────────────────────────────────────────────────
-json_escape() { # minimal JSON string escape: \ " and control whitespace
- local s=${1//\\/\\\\}
+json_escape() { # JSON string escape: \ " \n \r \t, every other control char (< 0x20) as \u00XX
+ local s=${1//\\/\\\\} o ch hex
s=${s//\"/\\\"}
s=${s//$'\n'/\\n}
s=${s//$'\r'/\\r}
s=${s//$'\t'/\\t}
+ if [[ "$s" == *[[:cntrl:]]* ]]; then # a raw control char is invalid JSON (git/ps output can carry ESC, BEL...)
+ for o in 001 002 003 004 005 006 007 010 013 014 016 017 020 021 022 023 024 025 026 027 \
+ 030 031 032 033 034 035 036 037; do
+ printf -v ch "\\$o"; printf -v hex '\\u%04x' "$((8#$o))"
+ s=${s//"$ch"/"$hex"}
+ done
+ fi
printf '%s' "$s"
}
diff --git a/tests/scripts/desktop_update/test_desktop_update_posix_handoff_protocol.py b/tests/scripts/desktop_update/test_desktop_update_posix_handoff_protocol.py
index 9963a6d4c1f..16405320fd9 100644
--- a/tests/scripts/desktop_update/test_desktop_update_posix_handoff_protocol.py
+++ b/tests/scripts/desktop_update/test_desktop_update_posix_handoff_protocol.py
@@ -14,6 +14,7 @@ One or two invariant tests per Round 5 finding:
from __future__ import annotations
+import json
import os
from pathlib import Path
import re
@@ -461,6 +462,21 @@ def test_timed_out_probe_is_killed_with_its_whole_process_tree(tmp_path, perl):
assert not Path(f"/proc/{grandchild}").exists() or Path(f"/proc/{grandchild}/stat").read_text(encoding="utf-8").split(") ")[1].startswith("Z")
[email protected]("locale", ["C", "C.UTF-8"])
+def test_json_escape_round_trips_every_control_character(locale):
+ """The result and status files are JSON built by json_escape. A message or warning carrying
+ a raw control char other than \\n \\r \\t (git/ps output: ESC colour codes, BEL...) made
+ the whole result invalid JSON, so the Desktop dropped it unread."""
+ body = POSIX.read_text(encoding="utf-8-sig")
+ found = re.search(r"^json_escape\(\) \{.*?^\}\n", body, re.S | re.M)
+ assert found
+ text = "".join(chr(c) for c in range(1, 128)) + " \u00e9 \u2713 & \\& \x1b[31mred\x1b[0m"
+ env = {**os.environ, "LC_ALL": locale}
+ out = subprocess.run([shutil.which("bash"), "-c", found.group(0) + 'json_escape "$1"', "json_escape", text],
+ env=env, capture_output=True, text=True, encoding="utf-8", timeout=30)
+ assert json.loads(f'"{out.stdout}"') == text, out.stdout
+
+
def test_line_two_is_refreshed_only_while_the_claim_is_still_ours(tmp_path, procs):
home = tmp_path / "home"; home.mkdir()
marker = home / ".hermes-update-in-progress"