Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .agents/skills/interactive-cli-pr/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__pycache__/
4 changes: 3 additions & 1 deletion .agents/skills/interactive-cli-pr/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,9 @@ If the checkout being reviewed does not contain this skill yet, use the recorder

- The recorder runs the real binary with stdout and stderr attached to the same pseudo-terminal. Both streams need to be terminals to see the interactive results table. A pipe or `Command::output()` alone captures a different layout.
- A local test server supplies synthetic metadata and payloads. This keeps runs reproducible, avoids public service traffic, and keeps real network details out of the recording. The numbers are for layout review, not a benchmark.
- The default demo runs both directions through 100 KB, 1 MB, 10 MB, 25 MB, and 100 MB with the binary's default latency and transfer counts. The recorder sets the max to 100 MB and disables adaptive stopping so all sizes appear. Use a shorter sweep only when it better shows the change, for example `--max-payload-size 100k` for one payload per direction.
- The fixture paces transfers to 250 Mbit/s down and 100 Mbit/s up by default, so larger samples approach the configured rates. Each download chunk is scheduled by elapsed time. Uploads cannot be paced from the read side, because the kernel buffers megabytes ahead of the client's writes, so the response is held for the transfer time instead. Change the rates with `--down-mbit` and `--up-mbit` if a change is easier to see at a different speed.
- The default demo runs both directions through 100 KB, 1 MB, and 10 MB with the binary's default latency and transfer counts. The recorder sets the max to 10 MB and disables adaptive stopping so all sizes appear. Pacing makes large payloads slow: 10 MB takes about 20 seconds, 25 MB about 50, and 100 MB around 150, which exceeds the CLI's 120-second deadline. The recorder warns if the estimated sweep exceeds the deadline. Use `--max-duration` to give longer runs more time. Use a shorter sweep when it better shows the change, for example `--max-payload-size 100k` for one payload per direction.
- The 100 KB row varies by more than the larger rows. A 100 KB transfer spends most of its time on connection setup, so the client's per-request cost is a large share of that row. Do not read it as a fixture problem, and do not try to steady it by slowing the small payloads down.
- Use the clean scenario for general layout changes. Add `--scenario retry` to inject a single HTTP 429 with a two-second wait, or `--scenario partial` for an HTTP 403 after two valid samples. Explain any injected error in the caption so it does not look like a failed demo. PR #313 used the full sweep with the recovered 429 to show the retry line and final diagnostic.
- The recorder applies the real cursor movements with `pyte`, then draws distinct screen states with Pillow and holds on the final frame. It captures text and layout, not terminal colors or font attributes. Use a native terminal recording if the change is about color or styling, or if it needs interactive input. Use `--columns` and `--rows` for a specific viewport and `--start-at 'visible text'` to open on a specific state.
- Open the GIF and, if generated, the final PNG before attaching. Check that viewers can see the change while it is happening, that the final output is legible, and that the recording contains no real IP addresses, secrets, or local paths. If you change defaults or how requests are made, update the fixture or its verification rather than uploading a misleading demo.
Expand Down
113 changes: 97 additions & 16 deletions .agents/skills/interactive-cli-pr/scripts/record_preview.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,10 @@
import os
import pty
import select
import socket
import struct
import subprocess
import sys
import termios
import threading
import time
Expand All @@ -33,21 +35,36 @@
}
DEFAULT_LATENCY = 25
DEFAULT_SAMPLES = 10
BLOCK = b"0" * (1024 * 1024)
DOWN_MBIT = 250.0
UP_MBIT = 100.0
# Keep the fixture inside the CLI's default 120-second run deadline.
DEFAULT_MAX_DURATION = 120
CAPTURE_GRACE_SECONDS = 5
BLOCK = b"0" * (64 * 1024)


class Fixture(ThreadingHTTPServer):
def __init__(self, scenario):
def __init__(self, scenario, down_mbit, up_mbit):
super().__init__(("127.0.0.1", 0), Handler)
self.scenario = scenario
self.down_mbit = down_mbit
self.up_mbit = up_mbit
self.downloads = Counter()
self.uploads = Counter()


class Handler(BaseHTTPRequestHandler):
protocol_version = "HTTP/1.1"

def log_message(self, *_args):
pass

def setup(self):
super().setup()
# Without this, every response waits on Nagle plus delayed ACK and the
# small payloads measure about 45 ms of stall instead of the link rate.
self.connection.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)

def respond(self, size, *, status=200, headers=()):
self.send_response(status)
self.send_header("Content-Length", str(size))
Expand All @@ -61,6 +78,7 @@ def do_GET(self):
body = b"ip=127.0.0.1\ncolo=XXX\nloc=XX\n"
self.respond(len(body))
self.wfile.write(body)
self.wfile.flush()
return
url = urlsplit(self.path)
if url.path != "/__down":
Expand All @@ -73,7 +91,6 @@ def do_GET(self):
time.sleep(0.062)
self.respond(0, headers=[("Server-Timing", 'cfL4;desc="?rtt=18000"')])
return
time.sleep(0.108 + 0.008 * (attempt % 4))
if size == SIZES["100k"] and attempt == 3:
if self.server.scenario == "retry":
self.respond(0, status=429, headers=[("Retry-After", "2")])
Expand All @@ -82,11 +99,24 @@ def do_GET(self):
self.respond(0, status=403)
return
self.respond(size)
whole, rest = divmod(size, len(BLOCK))
for _ in range(whole):
self.wfile.write(BLOCK)
if rest:
self.wfile.write(BLOCK[:rest])
self.wfile.flush()
# Schedule each write before sending it, including the final chunk:
# the client stops timing as soon as it has the whole body.
start = time.monotonic()
sent = 0
while sent < size:
chunk = min(len(BLOCK), size - sent)
ahead = (sent + chunk) * 8 / (self.server.down_mbit * 1e6) - (
time.monotonic() - start
)
if ahead > 0:
time.sleep(ahead)
try:
self.wfile.write(BLOCK[:chunk])
self.wfile.flush()
except OSError:
return
sent += chunk

def do_POST(self):
if self.path != "/__up":
Expand All @@ -100,11 +130,14 @@ def do_POST(self):
if not chunk:
return
remaining -= len(chunk)
time.sleep(0.110 + 0.008 * (self.server.uploads[size] % 4))
# The client stops its upload timer when the response arrives, so the
# delay has to sit here. Reading slowly would not work: the kernel
# buffers megabytes ahead of the client's writes either way.
time.sleep(size * 8 / (self.server.up_mbit * 1e6))
self.respond(0)


def capture(command, prompt, columns, rows):
def capture(command, prompt, columns, rows, max_duration):
screen = pyte.Screen(columns, rows)
stream = pyte.ByteStream(screen)
stream.feed(prompt.encode())
Expand All @@ -129,7 +162,9 @@ def capture(command, prompt, columns, rows):
try:
frames = []
start = time.monotonic()
while time.monotonic() - start < 90:
# Allow time for the CLI to print its final output and close the PTY.
capture_timeout = max_duration + CAPTURE_GRACE_SECONDS
while time.monotonic() - start < capture_timeout:
if not select.select([master], [], [], 0.5)[0]:
continue
try:
Expand All @@ -145,7 +180,9 @@ def capture(command, prompt, columns, rows):
if not frames or frames[-1][1] != state:
frames.append((time.monotonic() - start, state))
else:
raise RuntimeError("CLI did not finish within 90 seconds")
raise RuntimeError(
f"CLI did not finish within {capture_timeout} seconds"
)
return child.wait(timeout=3), frames
finally:
if child.poll() is None:
Expand Down Expand Up @@ -267,9 +304,24 @@ def main():
parser.add_argument(
"--scenario", choices=("clean", "retry", "partial"), default="clean"
)
parser.add_argument("--max-payload-size", choices=tuple(SIZES), default="100m")
parser.add_argument("--max-payload-size", choices=tuple(SIZES), default="10m")
parser.add_argument(
"--max-duration",
type=int,
default=DEFAULT_MAX_DURATION,
help="CLI measurement deadline in seconds (default: %(default)s)",
)
parser.add_argument("--columns", type=int, default=100)
parser.add_argument("--rows", type=int, default=27)
parser.add_argument(
"--down-mbit",
type=float,
default=DOWN_MBIT,
help="Simulated download rate in Mbit/s",
)
parser.add_argument(
"--up-mbit", type=float, default=UP_MBIT, help="Simulated upload rate in Mbit/s"
)
parser.add_argument("--font", type=Path)
parser.add_argument(
"--start-at", help="Start at the first stable frame containing this text"
Expand All @@ -279,23 +331,52 @@ def main():
parser.error(f"{args.binary} not found. Build the PR checkout first.")
if not 1 <= args.columns <= 240 or not 1 <= args.rows <= 80:
parser.error("Use a viewport between 1x1 and 240x80")
if args.max_duration <= 0:
parser.error("Use a positive --max-duration")
if args.down_mbit <= 0 or args.up_mbit <= 0:
parser.error("Use positive --down-mbit and --up-mbit rates")
# Each sample also pays request setup on top of the transfer time, which
# matters for the small payloads where the paced transfer is quick.
setup = 0.02 * 2 * DEFAULT_SAMPLES
estimated = setup + sum(
DEFAULT_SAMPLES * size * 8 / 1e6 * (1 / args.down_mbit + 1 / args.up_mbit)
for size in SIZES.values()
if size <= SIZES[args.max_payload_size]
)
if estimated > args.max_duration:
print(
f"warning: {args.max_payload_size} at {args.down_mbit:g}/{args.up_mbit:g} "
f"Mbit/s is estimated to take {estimated:.0f} s, exceeding the CLI's "
f"{args.max_duration} s deadline. Lower --max-payload-size or raise "
"--max-duration.",
file=sys.stderr,
)

font = load_font(args.font)
with Fixture(args.scenario) as server:
with Fixture(args.scenario, args.down_mbit, args.up_mbit) as server:
thread = threading.Thread(target=server.serve_forever, daemon=True)
thread.start()
try:
url = f"http://127.0.0.1:{server.server_port}"
flags = [
"--max-payload-size",
args.max_payload_size,
"--max-duration",
str(args.max_duration),
"--disable-dynamic-max-payload-size",
"--server",
url,
]
prompt = f"$ cfspeedtest --max-payload-size {args.max_payload_size} \\\r\n --disable-dynamic-max-payload-size --server {url}\r\n"
prompt = (
f"$ cfspeedtest --max-payload-size {args.max_payload_size} --max-duration {args.max_duration} \\\r\n"
f" --disable-dynamic-max-payload-size --server {url}\r\n"
)
code, frames = capture(
[str(args.binary.resolve()), *flags], prompt, args.columns, args.rows
[str(args.binary.resolve()), *flags],
prompt,
args.columns,
args.rows,
args.max_duration,
)
if not frames:
raise RuntimeError("The CLI produced no output")
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,10 @@ Options:
```

Example usage:
[![asciicast](https://asciinema.org/a/Moun5mFB1sm1VFkkFljG9UGyz.svg)](https://asciinema.org/a/Moun5mFB1sm1VFkkFljG9UGyz)
![Terminal recording showing all eight transfer rows with the progress bar.](https://github.com/user-attachments/assets/8802ba8b-518f-4fa1-8ec9-6b1bf7b4f312)

Example with json-pretty output:
[![asciicast](https://asciinema.org/a/P6IUAADtaCq3bT18GbYVHmksA.svg)](https://asciinema.org/a/P6IUAADtaCq3bT18GbYVHmksA)
![Start of the JSON document printed by cfspeedtest --output-format json-pretty.](https://github.com/user-attachments/assets/5a46f069-dda0-46b3-a6b8-eef4a71e4ce2)

In human-readable mode, live progress is shown on stderr only when it is a terminal. When both stdout and stderr are terminals, each completed transfer size adds a row to the results table. Redirecting stdout keeps the end-of-run summary instead, without progress redraws. CSV and JSON modes never draw a progress bar.

Expand Down
Loading