A self-improving RLM agent for coding workflows and long-running autonomous tasks.
Rust
fix: match TS hyperlink label rendering (#3786)
Sebastian Müller9f5fbd16b23c
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex c8666cf2d2..00a0737d55 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -344,6 +344,21 @@ jobs:- name: Bootstrap the kernel venv (ready before the kernel e2e units)if: steps.selection.outputs.units != '0'run: ./target/debug/prime-agent --prime-agent-bootstrap+ - name: Prepare pinned TS link-frame comparison binary+ if: matrix.shard == 1 && steps.selection.outputs.units != '0' && hashFiles('scripts/check_link_frames.py') != ''+ env:+ GH_TOKEN: ${{ github.token }}+ run: |+ set -euo pipefail+ reference="${RUNNER_TEMP}/link-frame-ts-reference"+ mkdir -p "${reference}/package"+ gh release download v0.9.8 --repo "${GITHUB_REPOSITORY}" \+ --pattern prime-agent-0.9.8-linux-x64.tar.gz --dir "${reference}"+ archive="${reference}/prime-agent-0.9.8-linux-x64.tar.gz"+ echo "83fb09129bf78e3e60268212cd70932166591b15188caa70c1b0efbcc76235e2 ${archive}" | sha256sum --check+ tar -xzf "${archive}" -C "${reference}/package"+ echo "PA_TS_ARCHIVE=${archive}" >> "${GITHUB_ENV}"+ echo "PA_TS_BINARY=${reference}/package/prime-agent" >> "${GITHUB_ENV}"# The real-binary lifecycle checks drive the debug binary through owned# daemons, PTYs and loopback providers only. One leg is enough.- name: Run the rust lifecycle checksdiff --git a/crates/pa-cli/tests/daemon_commands_e2e.rs b/crates/pa-cli/tests/daemon_commands_e2e.rsindex a779a9a95a..f6f7103791 100644--- a/crates/pa-cli/tests/daemon_commands_e2e.rs+++ b/crates/pa-cli/tests/daemon_commands_e2e.rs@@ -770,6 +770,34 @@ fn ts_daemon_differential_cli_output() {let work = dir.path().join("work");std::fs::create_dir_all(&sessions).expect("sessions dir");std::fs::create_dir_all(&work).expect("work dir");+ // Sends test admission, not provider completion. Give the real TS worker+ // synthetic credentials and an owned loopback listener that never replies:+ // the command must still return its receipt, and no live provider is used.+ let provider_listener =+ std::net::TcpListener::bind(("127.0.0.1", 0)).expect("fixture provider listener");+ let provider_address = provider_listener+ .local_addr()+ .expect("fixture provider address");+ std::fs::write(+ agent_dir.join("models.json"),+ json!({"providers": {"parity-cli": {+ "api": "openai-completions",+ "apiKey": "fixture-only",+ "baseUrl": format!("http://{provider_address}/v1"),+ "models": [{"id": "parity-1", "name": "CLI parity fixture",+ "reasoning": false, "input": ["text"],+ "contextWindow": 128_000, "maxTokens": 4096}]+ }}})+ .to_string(),+ )+ .expect("fixture model registry");+ std::fs::write(+ agent_dir.join("settings.json"),+ json!({"defaultProvider": "parity-cli", "defaultModel": "parity-1",+ "prewarmPythonKernel": false, "autoRefine": {"enabled": false}})+ .to_string(),+ )+ .expect("fixture model settings");// `schedule` cannot take --daemon-socket (TS parity); the daemon uses the default path.std::env::set_var("TMPDIR", dir.path());let socket = pa_daemon::socket::default_daemon_socket_path();diff --git a/crates/pa-tui/src/chat/tests.rs b/crates/pa-tui/src/chat/tests.rsindex 68f6eb3747..7847028295 100644--- a/crates/pa-tui/src/chat/tests.rs+++ b/crates/pa-tui/src/chat/tests.rs@@ -160,7 +160,7 @@ fn row_runs(row: &Line) -> Vec<(String, Style)> {#[test]fn user_block_keeps_the_link_affordance() {- crate::hyperlinks::set_hyperlinks_override(Some(true));+ crate::hyperlinks::set_hyperlinks_override(Some(false));let (bg, body, _, _, _) = user_block_styles();let link_url = bg.patch(theme().fg_style(ThemeColor::MdLinkUrl));let rows = render_user_block("see [docs](https://x.dev/a)", &theme(), " ", 60);diff --git a/crates/pa-tui/src/markdown/inline.rs b/crates/pa-tui/src/markdown/inline.rsindex aec9bc59d6..0608b40d15 100644--- a/crates/pa-tui/src/markdown/inline.rs+++ b/crates/pa-tui/src/markdown/inline.rs@@ -8,10 +8,10 @@ pub fn render_inline(text: &str, style: &MarkdownStyle) -> Line {}/// The same inline render, plus origin tracking: which spans of the returned line-/// carry a link's `(url)` bracket (`url_slots`) and which are inline-code spans-/// (`code_slots`), in ascending span order. Style-tapering callers (headings,-/// quotes) preserve those spans by origin — a span that merely renders in the same-/// style is not a slot.+/// carry a link's `(url)` bracket (`url_slots`; the bracket only renders without+/// OSC 8 support) and which are inline-code spans (`code_slots`), in ascending span+/// order. Style-tapering callers (headings, quotes) preserve those spans by origin —+/// a span that merely renders in the same style is not a slot.#[must_use]pub(crate) fn render_inline_tracked(text: &str,@@ -154,11 +154,12 @@ fn render_inline_ctx((label_spans, label_slots, label_codes),modifier | Modifier::UNDERLINED,);- // The URL rides after the wrap (the OSC 8 region covers the label- // only), in the dim `link_url` slot unless the label already is- // the URL (mailto stripped for the comparison).+ // Without OSC 8 support the URL rides after the wrap (the OSC 8+ // region covers the label only), in the dim `link_url` slot unless+ // the label already is the URL (mailto stripped for the comparison).+ // A hyperlink-capable terminal shows the clickable label alone.let comparison = url.strip_prefix("mailto:").unwrap_or(url.as_str());- if label != url && label != comparison {+ if !crate::hyperlinks::hyperlinks_enabled() && label != url && label != comparison {// The bracket renders the destination as visible text, so it// gets the same control-byte hardening as the OSC 8 target: a// smuggled escape byte can never re-enter the terminal live.@@ -382,12 +383,15 @@ fn render_inline_ctx(label.content.push_str(crate::hyperlinks::OSC8_CLOSE);}spans.push(label);- // The URL rides beside the label in the dim `link_url` slot unless the- // label already shows it (mailto-stripped comparison). The bare-url- // regex tail only excludes whitespace, so the bracket gets the same- // hardening as the OSC 8 target.+ // Without OSC 8 support the URL rides beside the label in the dim+ // `link_url` slot unless the label already shows it (mailto-stripped+ // comparison). The bare-url regex tail only excludes whitespace, so the+ // bracket gets the same hardening as the OSC 8 target.let comparison = token.href.strip_prefix("mailto:").unwrap_or(&token.href);- if token.text != token.href && token.text != comparison {+ if !crate::hyperlinks::hyperlinks_enabled()+ && token.text != token.href+ && token.text != comparison+ {let shown = crate::hyperlinks::sanitize_control_bytes(token.href.clone());url_slots.push(spans.len());spans.push(Span::styled(format!(" ({shown})"), style.link_url));diff --git a/crates/pa-tui/src/markdown/tests.rs b/crates/pa-tui/src/markdown/tests.rsindex 99992a8ac4..226e014fc9 100644--- a/crates/pa-tui/src/markdown/tests.rs+++ b/crates/pa-tui/src/markdown/tests.rs@@ -40,6 +40,7 @@ fn review_markdown_escaped_delimiters_keep_their_emphasis() {#[test]fn review_markdown_destinations_balance_before_a_title() {+ crate::hyperlinks::set_hyperlinks_override(Some(false));let style = MarkdownStyle::default();// The pinned real TS frame accepts this destination before a quoted title.let permissive = "[t](foo(bar \"title\")";@@ -67,13 +68,14 @@ fn review_markdown_destinations_balance_before_a_title() {assert_eq!(ranges[0].url, "foo(bar)");// Visible text excludes zero-width metadata under either capability.crate::hyperlinks::strip_osc8(&mut spans);- assert_eq!(- spans,- vec![- Span::styled("t", style.body.add_modifier(Modifier::UNDERLINED)),- Span::styled(" (foo(bar))", style.link_url)- ]- );+ let mut expected = vec![Span::styled(+ "t",+ style.body.add_modifier(Modifier::UNDERLINED),+ )];+ if !capability {+ expected.push(Span::styled(" (foo(bar))", style.link_url));+ }+ assert_eq!(spans, expected);}}crate::hyperlinks::set_hyperlinks_override(None);@@ -247,6 +249,7 @@ fn review_markdown_adjacent_emphasis_keeps_the_next_opener() {#[test]fn review_markdown_link_titles_skip_escaped_quotes() {+ crate::hyperlinks::set_hyperlinks_override(Some(false));let style = MarkdownStyle::default();for text in [r#"[t](url "a \"b\"")"#, r"[t](url 'a \'b\'')"] {let mut spans = render_inline(text, &style);@@ -257,6 +260,7 @@ fn review_markdown_link_titles_skip_escaped_quotes() {);assert!(spans[0].style.add_modifier.contains(Modifier::UNDERLINED));}+ crate::hyperlinks::set_hyperlinks_override(None);}#[test]@@ -535,7 +539,7 @@ fn heading_and_paragraph() {#[test]fn heading_link_wraps_keeps_the_affordance_and_counts() {- crate::hyperlinks::set_hyperlinks_override(Some(true));+ crate::hyperlinks::set_hyperlinks_override(Some(false));let style = MarkdownStyle::default();let lines = render_markdown("# [docs](https://x.dev/a)", 40, &style);assert_eq!(lines.len(), 1);@@ -551,7 +555,7 @@ fn heading_link_wraps_keeps_the_affordance_and_counts() {assert_eq!(visible, "docs (https://x.dev/a)");// A narrow heading wraps like any row: the bracket — closing `]` included —// lands on its own row instead of clipping (count==paint at every width).- let rows = render_markdown("# [docs](https://x.dev/a)", 20, &style);+ let rows = super::render_markdown("# [docs](https://x.dev/a)", 20, &style);assert_eq!(rows.len(), 2, "rows: {rows:?}");let visible: Vec<String> = rows.iter()@@ -852,6 +856,45 @@ fn inline_bold_code_link() {crate::hyperlinks::set_hyperlinks_override(None);}+#[test]+fn hyperlink_terminals_show_the_link_label_without_the_url_bracket() {+ // With OSC 8 support the clickable label stands alone on both link paths:+ // no `(url)` bracket and no bracket slot.+ crate::hyperlinks::set_hyperlinks_override(Some(true));+ let style = MarkdownStyle::default();+ for (text, label, href) in [+ ("[docs](https://x.dev/a)", "docs", "https://x.dev/a"),+ ("www.x.dev/a", "www.x.dev/a", "http://www.x.dev/a"),+ ] {+ let (spans, url_slots, _) = super::inline::render_inline_tracked(text, &style);+ assert_eq!(+ spans.iter().map(|s| s.content.as_str()).collect::<String>(),+ format!(+ "{}{label}{}",+ crate::hyperlinks::osc8_open(href),+ crate::hyperlinks::OSC8_CLOSE+ )+ );+ assert!(url_slots.is_empty(), "{text}");+ }+ crate::hyperlinks::set_hyperlinks_override(None);+}++#[test]+fn terminals_without_hyperlinks_keep_the_url_bracket() {+ crate::hyperlinks::set_hyperlinks_override(Some(false));+ let style = MarkdownStyle::default();+ for (text, href) in [+ ("[docs](https://x.dev/a)", "https://x.dev/a"),+ ("www.x.dev/a", "http://www.x.dev/a"),+ ] {+ let (spans, url_slots, _) = super::inline::render_inline_tracked(text, &style);+ assert_eq!(url_slots, vec![1], "{text}");+ assert_eq!(spans[1], Span::styled(format!(" ({href})"), style.link_url));+ }+ crate::hyperlinks::set_hyperlinks_override(None);+}+#[test]fn legacy_link_row_is_underlined_and_shows_the_url() {crate::hyperlinks::set_hyperlinks_override(Some(false));@@ -881,7 +924,7 @@ fn legacy_link_row_is_underlined_and_shows_the_url() {}#[test]-fn osc8_gated_link_row_wraps_the_label_in_a_hyperlink_and_shows_the_url() {+fn osc8_gated_link_row_wraps_the_label_in_a_hyperlink_and_hides_the_url() {crate::hyperlinks::set_hyperlinks_override(Some(true));let style = MarkdownStyle::default();let spans = render_inline("see [docs](https://x.dev/a)", &style);@@ -889,7 +932,7 @@ fn osc8_gated_link_row_wraps_the_label_in_a_hyperlink_and_shows_the_url() {assert_eq!(joined,format!(- "see {}docs{} (https://x.dev/a)",+ "see {}docs{}",crate::hyperlinks::osc8_open("https://x.dev/a"),crate::hyperlinks::OSC8_CLOSE)@@ -898,10 +941,8 @@ fn osc8_gated_link_row_wraps_the_label_in_a_hyperlink_and_shows_the_url() {spans[1].style.add_modifier.contains(Modifier::UNDERLINED),"the label underlines: {joined}");- assert_eq!(spans[2].style.fg, style.link_url.fg);- // The sequences are zero-width: the row measures like plain text plus the- // bracketed URL.- assert_eq!(str_width(&joined), str_width("see docs (https://x.dev/a)"));+ // The sequences are zero-width: the row measures like plain text.+ assert_eq!(str_width(&joined), str_width("see docs"));// Windows drive-letter targets classify as file paths; the label is// the URL, so no bracket follows it.let drive = render_inline("[c:\\src](c:\\src)", &style);@@ -934,17 +975,14 @@ fn balanced_parens_in_a_link_destination_stay_intact() {let spans = render_inline(&format!("[math]({url})"), &style);assert_eq!(spans,- vec![- Span::styled(- format!(- "{}math{}",- crate::hyperlinks::osc8_open(url),- crate::hyperlinks::OSC8_CLOSE- ),- style.body.add_modifier(Modifier::UNDERLINED),+ vec![Span::styled(+ format!(+ "{}math{}",+ crate::hyperlinks::osc8_open(url),+ crate::hyperlinks::OSC8_CLOSE),- Span::styled(format!(" ({url})"), style.link_url),- ]+ style.body.add_modifier(Modifier::UNDERLINED),+ ),]);crate::hyperlinks::set_hyperlinks_override(None);}@@ -998,7 +1036,7 @@ fn the_url_bracket_scrubs_terminal_control_bytes() {// A raw escape byte smuggled into the url must never re-enter the terminal as a// live OSC/CSI sequence: the bracket percent-encodes control bytes like the OSC 8// target.- crate::hyperlinks::set_hyperlinks_override(Some(true));+ crate::hyperlinks::set_hyperlinks_override(Some(false));let style = MarkdownStyle::default();let url = "https://x.dev/\u{1b}]52;c;base64";let spans = render_inline(&format!("[a]({url})"), &style);@@ -1018,7 +1056,7 @@ fn the_url_bracket_scrubs_terminal_control_bytes() {#[test]fn link_url_bracket_wraps_and_counts_like_text() {- crate::hyperlinks::set_hyperlinks_override(Some(true));+ crate::hyperlinks::set_hyperlinks_override(Some(false));let style = MarkdownStyle::default();let text = "see [docs](https://x.dev/a) tail";// The bracketed URL is visible text: the width accounting includes it, so the@@ -1053,10 +1091,10 @@ fn link_url_bracket_wraps_and_counts_like_text() {#[test]fn long_link_url_wraps_without_breaking_the_clickable_region() {- crate::hyperlinks::set_hyperlinks_override(Some(true));+ crate::hyperlinks::set_hyperlinks_override(Some(false));let style = MarkdownStyle::default();let url = format!("https://x.dev/{}", "a".repeat(40));- let rows = render_markdown(&format!("[docs]({url})"), 12, &style);+ let rows = super::render_markdown(&format!("[docs]({url})"), 12, &style);assert!(rows.len() >= 4, "rows: {rows:?}");for row in &rows {let joined: String = row.iter().map(|s| s.content.as_str()).collect();@@ -1172,9 +1210,10 @@ fn bare_url_autolink_forms() {}#[test]-fn www_autolink_gains_scheme_and_shows_the_url_in_both_forms() {- // A www autolink's href gains the scheme, so the target differs- // from the label and the bracket shows in BOTH capability forms.+fn www_autolink_gains_scheme_and_shows_the_url_without_hyperlinks() {+ // A www autolink's href gains the scheme, so the target differs from the+ // label: the fallback form shows the bracket, the OSC 8 form links the+ // scheme-qualified target.let style = MarkdownStyle::default();crate::hyperlinks::set_hyperlinks_override(Some(false));let spans = render_inline("www.example.com/path", &style);@@ -1195,7 +1234,7 @@ fn www_autolink_gains_scheme_and_shows_the_url_in_both_forms() {assert_eq!(joined,format!(- "{}www.example.com/path{} (http://www.example.com/path)",+ "{}www.example.com/path{}",crate::hyperlinks::osc8_open("http://www.example.com/path"),crate::hyperlinks::OSC8_CLOSE)@@ -1204,7 +1243,6 @@ fn www_autolink_gains_scheme_and_shows_the_url_in_both_forms() {spans[0].style.add_modifier.contains(Modifier::UNDERLINED),"the OSC 8 autolink label underlines");- assert_eq!(spans[1].style.fg, style.link_url.fg);crate::hyperlinks::set_hyperlinks_override(None);}diff --git a/scripts/check_link_frames.py b/scripts/check_link_frames.pynew file mode 100644index 0000000000..c4ec08e21d--- /dev/null+++ b/scripts/check_link_frames.py@@ -0,0 +1,193 @@+#!/usr/bin/env python3+"""Compare actual TS/Rust link frames and OSC 8 targets, with capability on/off.++Full-width styled cells between fixed assistant-text markers are compared.+No output geometry is normalized. Unchanged application chrome is excluded.+"""+import argparse+import copy+import fcntl+import json+import os+from pathlib import Path+import pty+import select+import re+import struct+import subprocess+import sys+import tempfile+import termios+import time++from lifecycle_lib import (DockScreen, OwnedProcesses, Supervisor, TAG, Terminal,+ actual_hello, digest, env_for, finish)++TS_ARCHIVE_SHA256 = '83fb09129bf78e3e60268212cd70932166591b15188caa70c1b0efbcc76235e2'+TS_COMMIT = '7d442aafa985f9342134fac16c2ef41f03fb45c1'+END = 'LINK_PARITY_END'+CASES = {'osc8': {'hyperlinks': True}, 'fallback': {'hyperlinks': False}}+BEGIN = 'LINK_PARITY_BEGIN'+LINKS = '[Read docs](https://example.invalid/docs) and www.example.invalid/help'+TARGETS = {'https://example.invalid/docs', 'http://www.example.invalid/help'}+++def messages():+ return [{'role': 'assistant', 'content': [{'type': 'text',+ 'text': BEGIN + '\n\n' + LINKS + '\n\n' + END}], 'stopReason': 'stop',+ 'api': 'openai-completions', 'provider': 'parity-local', 'model': 'parity-1',+ 'timestamp': 1750000000000, 'usage': {'input': 0, 'output': 0,+ 'cacheRead': 0, 'cacheWrite': 0, 'totalTokens': 0,+ 'cost': {'input': 0, 'output': 0, 'cacheRead': 0, 'cacheWrite': 0, 'total': 0}}}]+++def region(screen):+ rows = [''.join(row) for row in screen.cells]+ starts = [i for i, row in enumerate(rows) if BEGIN in row]+ ends = [i for i, row in enumerate(rows) if END in row]+ if len(starts) != 1 or len(ends) != 1 or starts[0] >= ends[0]:+ raise ValueError('complete link frame is not visible')+ result = []+ for y in range(starts[0], ends[0]):+ text = rows[y]+ cells = []+ for x, char in enumerate(text):+ style = copy.deepcopy(screen.styles[y][x])+ # Foreground on a blank cell is invisible; background and inverse+ # remain visible and are compared. No geometry is normalized.+ if char.isspace() and not any(style.get(key) for key in ('4', '7', '9')):+ style = {key: value for key, value in style.items() if key == 'bg'}+ cells.append([char, style])+ result.append(cells)+ return result+++class FrameTerminal(Terminal):+ def __init__(self, command, root, env, width):+ self.master, slave = pty.openpty()+ attrs = termios.tcgetattr(slave)+ attrs[3] &= ~(termios.ECHO | termios.ICANON)+ termios.tcsetattr(slave, termios.TCSANOW, attrs)+ fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack('HHHH', 40, width, 0, 0))+ self.process = subprocess.Popen(command, cwd=root, env=env, stdin=slave,+ stdout=slave, stderr=slave, start_new_session=True)+ os.close(slave)+ self.screen, self.raw = DockScreen(width), bytearray()+++def capture(binary, kind, case, width, root):+ root.mkdir()+ env = env_for(root)+ env[TAG] = str(root)+ env['COLORTERM'] = 'truecolor'+ if case['hyperlinks']:+ env['TERM_PROGRAM'] = 'WezTerm'+ else:+ env['TERM'] = 'screen-256color'+ settings_path = root / 'agent/settings.json'+ settings = json.loads(settings_path.read_text())+ settings['chatDetail'] = 'overview'+ settings_path.write_text(json.dumps(settings))+ if kind == 'ts':+ env['PI_PACKAGE_DIR'] = str(binary.parent)+ hello = actual_hello(binary, root, env)+ if kind == 'ts':+ assert hello.get('appVersion') == '0.9.8', hello+ assert hello.get('runtime', {}).get('buildId') == TS_COMMIT, hello+ server = Supervisor(root / 'ui.sock', hello, 'link-frames', root)+ server.messages = messages()+ scope = OwnedProcesses(binary, root, server.path)+ terminal = None+ result = {'binary_sha256': digest(binary), 'hello': hello, 'frames': {},+ 'fixture_messages': server.messages, 'initial_chat_detail': 'overview'}+ try:+ command = [str(binary), '--daemon-socket', str(server.path)]+ terminal = FrameTerminal(command, root, env, width)+ scope.register(terminal.process, command)+ terminal.send('FRAME0')+ terminal.wait('link frame painted', lambda:+ 'FRAME0' in terminal.screen.text() and BEGIN in terminal.screen.text()+ and END in terminal.screen.text() and 'Read docs' in terminal.screen.text(), server)+ result['frames']['paint'] = region(terminal.screen)+ visible = '\n'.join(''.join(cell[0] for cell in row)+ for row in result['frames']['paint'])+ assert ('(https://example.invalid/docs)' in visible) != case['hyperlinks'], visible+ assert not server.prompts, 'frame check submitted a prompt'+ assert not terminal.screen.unsupported_sgr, terminal.screen.unsupported_sgr+ assert not terminal.screen.unsupported_terminal, terminal.screen.unsupported_terminal+ result['executed'] = True+ except Exception as error:+ result['error'] = f'{type(error).__name__}: {error}'+ finally:+ try:+ if terminal:+ if terminal.process.poll() is None:+ terminal.send('\x03\x03')+ deadline = time.monotonic() + 8+ while terminal.process.poll() is None and time.monotonic() < deadline:+ terminal.pump()+ while select.select([terminal.master], [], [], 0)[0]:+ before = len(terminal.raw)+ terminal.pump()+ if len(terminal.raw) == before:+ break+ result['raw_ansi_hex'] = bytes(terminal.raw).hex()+ targets = set(re.findall(r'\x1b\]8;[^;]*;([^\x07\x1b]*)(?:\x07|\x1b\\)',+ bytes(terminal.raw).decode('utf-8', errors='replace'))) - {''}+ result['osc8_targets'] = sorted(targets)+ # Pinned TS hyperlink() always emits OSC8 metadata. Legacy+ # terminals ignore it; capability controls the visible bracket.+ result['target_check'] = TARGETS <= targets+ result['exit_code'] = terminal.process.poll()+ os.close(terminal.master)+ finally:+ try:+ server.close()+ finally:+ result['commands'] = server.commands+ result['fixture_errors'] = server.errors+ finish(scope, None, None, result)+ return result+++def frames_equal(pair):+ return bool(set(pair) == {'ts', 'rust'} and all(+ item.get('executed') and item.get('cleanup_verified') and item.get('target_check')+ and item.get('exit_code') == 0+ and not item.get('error') and not item.get('fixture_errors')+ for item in pair.values()) and pair['ts']['frames'] == pair['rust']['frames'])+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('--receipt', type=Path, required=True)+ args = parser.parse_args()+ receipt = {'verified': False, 'scope': __doc__, 'cases': {}, 'comparisons': {},+ 'not_verified': ['full wire-byte equality', 'mouse click handling', 'streaming'],+ 'source_commit': TS_COMMIT}+ try:+ assert sys.platform == 'linux', 'hosted Linux only'+ assert digest(Path(os.environ['PA_TS_ARCHIVE'])) == TS_ARCHIVE_SHA256+ receipt['ts_archive_sha256'] = TS_ARCHIVE_SHA256+ with tempfile.TemporaryDirectory(prefix='pa-link-frames-', dir='/tmp') as folder:+ for name, case in CASES.items():+ for width in (80, 120):+ key = f'{name}-{width}'+ pair = receipt['cases'][key] = {}+ for kind in ('ts', 'rust'):+ binary = Path(os.environ[f'PA_{kind.upper()}_BINARY']).resolve()+ pair[kind] = capture(binary, kind, case, width,+ Path(folder) / f'{key}-{kind}')+ receipt['comparisons'][key] = frames_equal(pair)+ receipt['verified'] = bool(receipt['comparisons'] and all(receipt['comparisons'].values()))+ except Exception as error:+ receipt['error'] = f'{type(error).__name__}: {error}'+ args.receipt.parent.mkdir(parents=True, exist_ok=True)+ args.receipt.write_text(json.dumps(receipt, ensure_ascii=False, indent=2) + '\n')+ print(json.dumps({'verified': receipt['verified'], 'comparisons': receipt['comparisons'],+ 'error': receipt.get('error')}))+ return 0 if receipt['verified'] else 1+++if __name__ == '__main__':+ sys.exit(main())diff --git a/scripts/lifecycle_lib.py b/scripts/lifecycle_lib.pyindex 1744ce8672..73dc320c6d 100644--- a/scripts/lifecycle_lib.py+++ b/scripts/lifecycle_lib.py@@ -737,6 +737,10 @@ class DockScreen:elif command == "n" and nums[0] == 6:replies.append(f"\x1b[{self.row + 1};{self.col + 1}R".encode())elif command == "c": replies.append(b"\x1b[?1;2c")+ elif command == 't' and nums == [16]:+ # Fixed fixture cell geometry: TS asks for this in+ # image-capable terminals (CSI 16 t -> CSI 6;h;w t).+ replies.append(b'\x1b[6;16;8t')elif command in 'hl' and params.startswith('?'):for mode in nums:if mode == 7:diff --git a/scripts/test_check_link_frames.py b/scripts/test_check_link_frames.pynew file mode 100644index 0000000000..a8f2eb45a5--- /dev/null+++ b/scripts/test_check_link_frames.py@@ -0,0 +1,63 @@+import copy+import unittest++from check_link_frames import BEGIN, END, frames_equal, region+from lifecycle_lib import DockScreen+++class LinkParityGuards(unittest.TestCase):+ def test_cell_size_query_is_answered_without_masking_unknown_queries(self):+ screen = DockScreen(width=80)+ self.assertEqual(screen.feed(b'\x1b[16t'), [b'\x1b[6;16;8t'])+ self.assertEqual(screen.unsupported_terminal, [])+ screen.feed(b'\x1b[17t')+ self.assertEqual(screen.unsupported_terminal, ['\x1b[17t'])++ def test_missing_targets_or_process_cleanup_cannot_pass(self):+ item = {'executed': True, 'cleanup_verified': True, 'target_check': True, 'exit_code': 0,+ 'frames': {'paint': [[['x', {'4': True}]]]}}+ pair = {'ts': copy.deepcopy(item), 'rust': copy.deepcopy(item)}+ self.assertTrue(frames_equal(pair))+ for field in ('executed', 'cleanup_verified', 'target_check'):+ changed = copy.deepcopy(pair)+ changed['rust'][field] = False+ self.assertFalse(frames_equal(changed))+ for field in ('error', 'fixture_errors'):+ changed = copy.deepcopy(pair)+ changed['rust'][field] = 'fixture failure'+ self.assertFalse(frames_equal(changed))++ def test_a_crashed_or_unexited_ui_cannot_pass(self):+ item = {'executed': True, 'cleanup_verified': True, 'target_check': True,+ 'exit_code': 0, 'frames': {'paint': [[['x', {}]]]}}+ pair = {'ts': copy.deepcopy(item), 'rust': copy.deepcopy(item)}+ self.assertTrue(frames_equal(pair))+ for code in (1, -11, None):+ changed = copy.deepcopy(pair)+ changed['rust']['exit_code'] = code+ self.assertFalse(frames_equal(changed))++ def test_text_styles_and_geometry_are_compared(self):+ item = {'executed': True, 'cleanup_verified': True, 'target_check': True, 'exit_code': 0,+ 'frames': {'paint': [[['x', {'4': True}], [' ', {}]]]}}+ pair = {'ts': copy.deepcopy(item), 'rust': copy.deepcopy(item)}+ for cells in ([['y', {'4': True}], [' ', {}]],+ [['x', {}], [' ', {}]],+ [['x', {'4': True}], [' ', {'bg': ['ansi', 41]}]],+ [[' ', {}], ['x', {'4': True}]]):+ changed = copy.deepcopy(pair)+ changed['rust']['frames']['paint'] = [cells]+ self.assertFalse(frames_equal(changed))++ def test_complete_region_keeps_trailing_colored_blanks(self):+ screen = DockScreen(width=80)+ screen.feed((BEGIN + '\r\n\x1b[41mRead docs \x1b[0m\r\n' + END).encode())+ rows = region(screen)+ self.assertEqual(len(rows[1]), 80)+ self.assertEqual(rows[1][10], [' ', {'bg': ['ansi', 41]}])+ with self.assertRaises(ValueError):+ region(DockScreen(width=80))+++if __name__ == '__main__':+ unittest.main()