summaryrefslogtreecommitdiff
path: root/test
diff options
context:
space:
mode:
Diffstat (limited to 'test')
-rw-r--r--test/consumer/build.zig2
-rw-r--r--test/daemon.py629
-rw-r--r--test/delay_relay.py10
-rw-r--r--test/e2e_harness.zig40
-rw-r--r--test/lspmock.zig26
-rw-r--r--test/macos_e2e.swift4
-rw-r--r--test/panes.zig4
-rw-r--r--test/perf-baseline-gui-debug.json2
-rw-r--r--test/perf-baseline-tui-debug.json2
-rw-r--r--test/perf-baseline-tui-fast.json2
-rw-r--r--test/perf.zig138
-rw-r--r--test/process/tty_editing.zig55
-rw-r--r--test/replicas.zig7
-rw-r--r--test/session.zig15
-rw-r--r--test/snapshots/collapse.golden4
-rw-r--r--test/snapshots/follow.golden2
-rw-r--r--test/snapshots/hscroll.golden2
-rw-r--r--test/snapshots/images.golden4
-rw-r--r--test/snapshots/jumps.golden2
-rw-r--r--test/snapshots/lspcomplete.golden2
-rw-r--r--test/snapshots/shrinktag.golden4
-rw-r--r--test/snapshots/ttytaken.golden2
-rw-r--r--test/snapshots/wheeldrift.golden8
-rw-r--r--test/snapshots/wrap.golden2
-rw-r--r--test/tty.zig33
25 files changed, 913 insertions, 88 deletions
diff --git a/test/consumer/build.zig b/test/consumer/build.zig
index ca63bb6e..c643bfb3 100644
--- a/test/consumer/build.zig
+++ b/test/consumer/build.zig
@@ -1,5 +1,5 @@
//! A package that depends on pardes, as a program would (build.zig's head
-//! comment has its lines): pardes's `lib-test`, which `unit-test` runs,
+//! comment has its lines): pardes's `consumer-test`, which `unit-test` runs,
//! runs `zig build test` here. `pardes-syntax` with the minimal grammars,
//! as a program that draws source text itself takes it; and
//! `pardes-editor` with no grammar of pardes's and one of its own, C's,
diff --git a/test/daemon.py b/test/daemon.py
index 11c98cd6..37487a99 100644
--- a/test/daemon.py
+++ b/test/daemon.py
@@ -30,7 +30,8 @@ private HOME and runtime directory:
python3 -B test/daemon.py --pair <pardes>
PARDES_PAIR: a terminal's session and its first client
python3 -B test/daemon.py --relink <pardes>
- the daemon killed: its sessions register again with the next
+ the daemon killed: its sessions register again with the next; and
+ one stopped: an Adopt waits for its answer to the hello
python3 -B test/daemon.py --far <pardes>
the far clients and their blob cache alone, one under `yes` across
a slow link, and a file by its hash
@@ -241,7 +242,7 @@ class Replica:
"""A replica's connection (abi/wire.zig): length-prefixed
messages, a tag byte and a little-endian u32 length. It is a near
client: its first word after the hello says so."""
- WIRE = 24
+ WIRE = 26
def __init__(self, path, timeout=10):
self.path, self.timeout = path, timeout
@@ -635,7 +636,7 @@ def pair(binary):
assert session != c.pid and ppid(session) == c.pid and os.getsid(session) == session, (session, c.pid)
wait_for('the file drawn on the terminal', lambda: b'line 3 of the notes' in t.text(), timeout=30)
listed = lambda: subprocess.run([binary, 'ps'], env=env, capture_output=True).stdout.decode()
- wait_for('the client listed', lambda: f'session pair {session} (tty, detached)' in listed()
+ wait_for('the client listed', lambda: f'session pair {session} (tty)' in listed()
and f'client {c.pid} ' in listed())
pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
os.write(t.master, b'Ofrom-the-pair\x1b')
@@ -653,12 +654,16 @@ def pair(binary):
c2 = lone.spawn([binary, '--9p=lone', str(notes)], dict(env, PARDES_DAEMON='off'))
nine2, session2 = session_of('lone')
wait_for('the lone pair drawn', lambda: b'line 3 of the notes' in lone.text(), timeout=30)
+ # An Upgrade refused, with why: its client could not find it again.
+ nine2.write('/ctl', b'Upgrade\n')
+ wait_for('the Upgrade refused', lambda: 'its client could not join it again' in screen_text(nine2), timeout=20)
+ assert alive(session2) and c2.poll() is None
nine2.socket.close()
os.kill(c2.pid, signal.SIGKILL)
c2.wait(timeout=10)
wait_for('the lone session ended with its last link', lambda: not alive(session2), timeout=20)
wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20)
- print(f'pair: with no daemon, client {c2.pid} killed outright, its session {session2} ended; nothing left behind')
+ print(f'pair: with no daemon, an Upgrade refused in words; client {c2.pid} killed outright, its session {session2} ended; nothing left behind')
finally:
for p in processes(root):
try:
@@ -672,12 +677,13 @@ def pair(binary):
def pair_rows(binary):
"""PARDES_PAIR, the shell's view (the last step's design, 1.1) and a
- session's lifetime (2.2 B), one row a step. With a daemon: a Detach in
- the pair's client says so and exits 0, the session runs on (listed); an
- attach is a client again; TERM to the client puts its terminal back and
- the session runs on; so does a KILL, and a closed terminal (HUP): each a
- loss, not a close. With none: a Detach refused (nothing could attach),
- the client on; its terminal closed, the session ends with its last link."""
+ session's lifetime (2.2 B), one row a step. `ps` says a pair's session
+ `kept` (started --detach, or a Detach typed in any client since), or
+ nothing after its kind; an Upgrade carries which. Kept: a client ended
+ by TERM, KILL or a closed terminal (HUP) leaves it running, as does a
+ Detach typed in one (said, exit 0). With no daemon: a Detach refused
+ (nothing could attach), the client on; its terminal closed, the session
+ ends with its last link."""
scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
scratch.mkdir(parents=True, exist_ok=True)
root = Path(tempfile.mkdtemp(prefix='rq-', dir=scratch))
@@ -693,6 +699,12 @@ def pair_rows(binary):
def listed():
return subprocess.run([binary, 'ps'], env=env, capture_output=True).stdout.decode()
+ def state_of(name):
+ """What `ps` says of session `name` after its pid: `(tty)`, `(tty, kept)`."""
+ for line in listed().splitlines():
+ if line.split()[:2] == ['session', name]:
+ return line[line.index('('):]
+
def drawn(t):
wait_for('drawn', lambda: b'line 3 of the notes' in t.text(), timeout=30)
@@ -713,30 +725,120 @@ def pair_rows(binary):
drawn(t)
return t, c, nine, session, pane
+ def attached(name):
+ tt = Term(30, 100)
+ terms.append(tt)
+ a = tt.spawn([binary, 'attach', name], env)
+ drawn(tt)
+ wait_for('the client listed', lambda: f'client {a.pid} ' in listed())
+ return tt, a
+
+ def ended_by(how, tt, a):
+ """Client `a` on terminal `tt` ended: TERM, KILL, or HUP (its terminal
+ closed); its exit status, once it is unlisted."""
+ if how == 'HUP':
+ tt.close()
+ terms.remove(tt)
+ else:
+ os.kill(a.pid, getattr(signal, 'SIG' + how))
+ code = a.wait(timeout=20)
+ if how == 'TERM':
+ wait_for('its terminal put back', lambda: tt.text().rfind(b'\x1b[?1049l') > tt.text().rfind(b'\x1b[?1049h'))
+ wait_for('the client unlisted', lambda: f'client {a.pid} ' not in listed())
+ return code
+
+ def upgraded(name, nine, session):
+ """An Upgrade to the same build: the session exec'd under its pid, its
+ 9P again."""
+ nine.write('/ctl', b'Upgrade\n')
+ wait_for('the session exec\'d', lambda: any(a.startswith(b'--upgraded=') for a in cmdline(session)), timeout=60)
+ nine.socket.close()
+ again = reconnect(root / f'pardes-9p-{name}.sock')
+ assert alive(session)
+ return again
+
try:
+ # Kept from birth: `new --detach`. Its clients end and it runs on.
+ out = subprocess.run([binary, 'new', '--detach=kd', str(notes)], env=env, cwd=root, capture_output=True,
+ timeout=30, stdin=subprocess.DEVNULL)
+ assert out.returncode == 0, out
+ with Client(root / 'pardes-9p-kd.sock') as kn:
+ kd = int(dict(line.split(maxsplit=1) for line in kn.read('/status').decode().splitlines())['pid'])
+ assert state_of('kd') == '(tty, kept)', listed()
+ for how in ('HUP', 'TERM'):
+ ended_by(how, *attached('kd'))
+ assert alive(kd) and state_of('kd') == '(tty, kept)', (how, listed())
+ # Started by `new` with a file: an Upgrade keeps it (its `new` is the
+ # verb still: taken for a file's name, the file was "the second" and
+ # the session ended), and it is attached to after.
+ upgraded('kd', Client(root / 'pardes-9p-kd.sock'), kd).socket.close()
+ assert alive(kd) and state_of('kd') == '(tty, kept)', listed()
+ ended_by('TERM', *attached('kd'))
+ assert alive(kd) and state_of('kd') == '(tty, kept)', listed()
+ print('pair rows: `new --detach` with a file: an Upgrade keeps it, and it is attached to after')
+ assert subprocess.run([binary, 'kill', 'kd'], env=env, capture_output=True, timeout=30).returncode == 0
+ wait_for('kd ended', lambda: not alive(kd), timeout=30)
+ print('pair rows: `new --detach` kept from birth (ps: (tty, kept)); its client ended by HUP, by TERM: it runs on')
+ # Not kept: a client's close (its terminal closed, a TERM) ends the
+ # session when it was the last; a KILL is a loss, it runs on.
+ t, c, nine, session, pane = started('nk', env)
+ assert ended_by('HUP', *attached('nk')) == 0
+ assert alive(session) and state_of('nk') == '(tty)', ('not its last client', listed())
+ os.kill(c.pid, signal.SIGKILL)
+ c.wait(timeout=10)
+ wait_for('the client unlisted', lambda: f'client {c.pid} ' not in listed())
+ assert alive(session) and state_of('nk') == '(tty)', ('a loss', listed())
+ assert ended_by('TERM', *attached('nk')) == 0
+ wait_for('the session ended at its last client\'s close', lambda: not alive(session), timeout=20)
+ assert state_of('nk') is None, listed()
+ nine.socket.close()
+ print('pair rows: not kept: a client\'s terminal closed (not the last): it runs on; its own killed -9: it runs on, '
+ 'listed; the last client TERMed (exit 0, its terminal put back): the session ended')
+ # The pair's own terminal closed after an Upgrade: its last client's
+ # close, which the Upgrade did not make kept.
+ t, c, nine, session, pane = started('nk2', env)
+ nine = upgraded('nk2', nine, session)
+ wait_for('the client joined again', lambda: b'joined again' in t.text(), timeout=30)
+ nine.socket.close()
+ t.close()
+ terms.remove(t)
+ assert c.wait(timeout=20) == 0, c.returncode
+ wait_for('the session ended with its terminal', lambda: not alive(session), timeout=20)
+ print('pair rows: not kept, upgraded: its terminal closed (exit 0): the session ended')
+ # Without the variable nothing changes: an attach client's TERM
+ # leaves the session running, and its own terminal closed detaches it.
+ own_env = {k: v for k, v in env.items() if k != 'PARDES_PAIR'}
+ t, c, nine, session, pane = started('own', own_env)
+ assert state_of('own') == '(tty, has a frontend)', listed()
+ assert ended_by('TERM', *attached('own')) == 0
+ assert alive(session) and state_of('own') == '(tty, has a frontend)', listed()
+ nine.socket.close()
+ t.close()
+ terms.remove(t)
+ c.wait(timeout=20)
+ wait_for('the own session detached', lambda: state_of('own') == '(tty, detached)')
+ assert alive(session)
+ assert subprocess.run([binary, 'kill', 'own'], env=env, capture_output=True, timeout=30).returncode == 0
+ wait_for('the own session ended', lambda: not alive(session), timeout=30)
+ print('pair rows: without the variable: an attach client TERMed, the session on; its terminal closed, it detached (ps: (tty, detached))')
+ # A pair: not kept, and not across an Upgrade either; a Detach typed
+ # in its client keeps it, across an Upgrade too.
t, c, nine, session, pane = started('rows', env)
+ assert state_of('rows') == '(tty)', listed()
+ nine = upgraded('rows', nine, session)
+ wait_for('ps after the Upgrade', lambda: state_of('rows') == '(tty)')
+ wait_for('the client joined again', lambda: b'joined again' in t.text(), timeout=30)
typed_detach(t, nine, pane)
assert c.wait(timeout=20) == 0, c.returncode
wait_for('the detach said', lambda: b"pardes: detached from 'rows', which is still running; come back with `pardes attach rows`" in t.text())
- assert alive(session) and f'session rows {session} (tty, detached)' in listed()
- print('pair rows: Detach in the client: said, exit 0; the session runs on, listed')
+ assert alive(session) and state_of('rows') == '(tty, kept)', listed()
+ nine = upgraded('rows', nine, session)
+ wait_for('ps after the Upgrade', lambda: state_of('rows') == '(tty, kept)')
+ print('pair rows: a pair (ps: (tty)), so after an Upgrade; Detach in its client: said, exit 0, it runs on, kept, so after an Upgrade')
for how in ('TERM', 'KILL', 'HUP'):
- tt = Term(30, 100)
- terms.append(tt)
- a = tt.spawn([binary, 'attach', 'rows'], env)
- drawn(tt)
- wait_for('the client listed', lambda: f'client {a.pid} ' in listed())
- if how == 'HUP':
- tt.close()
- terms.remove(tt)
- else:
- os.kill(a.pid, getattr(signal, 'SIG' + how))
- a.wait(timeout=20)
- if how == 'TERM':
- wait_for('its terminal put back', lambda: tt.text().rfind(b'\x1b[?1049l') > tt.text().rfind(b'\x1b[?1049h'))
- wait_for('the client unlisted', lambda: f'client {a.pid} ' not in listed())
- assert alive(session), how
- print(f'pair rows: a client ended by {how}: the session runs on')
+ ended_by(how, *attached('rows'))
+ assert alive(session) and state_of('rows') == '(tty, kept)', (how, listed())
+ print(f'pair rows: kept: a client ended by {how}: the session runs on')
nine.socket.close()
assert subprocess.run([binary, 'kill', 'rows'], env=env, capture_output=True, timeout=30).returncode == 0
wait_for('the session ended', lambda: not alive(session), timeout=30)
@@ -972,6 +1074,78 @@ def relink(binary):
shutil.rmtree(root, ignore_errors=True)
+def answer_late(binary):
+ """A session's Adopt asked at once, while its daemon has not answered
+ its hello (stopped 3 s, as a loaded machine can keep it), and before
+ the session's reader of the daemon has run: answered when the daemon
+ answers, never refused on a clock (daemon.zig `kept`)."""
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='ra-', dir=scratch))
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
+ TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ started = []
+ terms = []
+ wake = None
+ try:
+ term = Term()
+ terms.append(term)
+ stub = term.spawn([binary, '--tty', '--9p=one'], env)
+ started.append(stub.pid)
+ wait_for('the first session', (root / 'pardes-9p-one.sock').exists)
+ one = Client(root / 'pardes-9p-one.sock')
+ session = int(dict(line.split(maxsplit=1) for line in one.read('/status').decode().splitlines())['pid'])
+ started.append(session)
+ shell_pid = int(run(one, terminals(one)[0], b'echo $$\n').split(b'\n')[1])
+ started.append(shell_pid)
+ daemon = [p for p in processes(root) if cmdline(p)[1:2] == [b'--daemon']][0]
+ started.append(daemon)
+ wait_for('its shell listed', lambda: f'shell {shell_pid}' in subprocess.run(
+ [binary, '--ps'], env=env, capture_output=True, timeout=30).stdout.decode())
+ os.kill(session, signal.SIGKILL)
+ one.socket.close()
+ wait_for('the killed session gone', lambda: not alive(session))
+ os.kill(daemon, signal.SIGSTOP)
+ wake = threading.Timer(3, lambda: os.kill(daemon, signal.SIGCONT))
+ wake.start()
+ term = Term()
+ terms.append(term)
+ stub = term.spawn([binary, '--tty', '--9p=two'], env)
+ started.append(stub.pid)
+ wait_for('the next session', (root / 'pardes-9p-two.sock').exists)
+ two = Client(root / 'pardes-9p-two.sock', timeout=30)
+ started.append(int(dict(line.split(maxsplit=1) for line in two.read('/status').decode().splitlines())['pid']))
+ before = set(terminals(two))
+ asked = time.monotonic()
+ two.write(f'/pane/{min(before)}/exec', b'Adopt\n')
+ took = time.monotonic() - asked
+ pane = wait_for('the adopted pane', lambda: set(terminals(two)) - before).pop()
+ assert run(two, pane, b'echo $$\n').split(b'\n')[1] == str(shell_pid).encode()
+ print(f'answer late: an Adopt asked while the daemon was stopped waited {took:.1f} s for its answer, '
+ f'and shell {shell_pid} was adopted')
+ exit_session(two, pane)
+ two.socket.close()
+ wait_for('the shells hung up', lambda: not alive(shell_pid))
+ wait_for('the daemon gone once idle', lambda: not alive(daemon), timeout=5)
+ finally:
+ if wake:
+ wake.cancel()
+ for t in terms:
+ try:
+ t.close()
+ except OSError:
+ pass
+ for pid in started + processes(root):
+ try:
+ os.kill(pid, signal.SIGKILL)
+ except (ProcessLookupError, PermissionError):
+ pass
+ shutil.rmtree(root, ignore_errors=True)
+
+
class Window:
"""A pardes-gui in test mode, its window offscreen and hidden, its keys
written to its stdin (the test feed: Escape as `CSI 27 u`, which a
@@ -1419,12 +1593,13 @@ def far(binary):
f_join = joins(root / 'f.stats')[0]
assert f_join['from_disk'] > 0 and cached(cache) <= (1 << 20) + (64 << 10), (f_join, cached(cache))
far_joins(root / 'pardes-replica.sock', 'files', binary, 200)
- # Through ssh (a stand-in forwarding as `ssh -L` does): a client
- # refused and one detached each end their ssh and its socket (one
- # refused left both, 2026-10-30).
+ # Through ssh (a stand-in forwarding as `ssh -L` does, its socket
+ # bound 0.5 s before it listens: the client dials until it answers):
+ # a client refused and one detached each end their ssh and its
+ # socket (one refused left both, 2026-10-30).
fake = root / 'ssh'
fake.write_text('#!/bin/sh\nwhile [ $# -gt 0 ]; do case $1 in -L) fwd=$2; shift;; esac; shift; done\n'
- f'exec {sys.executable} -B {Path(__file__).parent / "delay_relay.py"} "${{fwd%%:*}}" "${{fwd#*:}}" --delay 0\n')
+ f'exec {sys.executable} -B {Path(__file__).parent / "delay_relay.py"} "${{fwd%%:*}}" "${{fwd#*:}}" --delay 0 --bound 500\n')
fake.chmod(0o755)
senv = dict(env, PARDES_SSH=str(fake), PARDES_REMOTE_RUNTIME=str(root), TMPDIR=str(root))
@@ -1739,6 +1914,138 @@ def games(binary, libs, secs=10):
shutil.rmtree(root, ignore_errors=True)
+def far_find(binary):
+ """A far client types a query into a Find over 40,000 names: each key
+ scores the names again a slice at a time (core/Names.zig `rescore`),
+ the client's guess of the key first. The slice is a count, the same on
+ both sides, so no guess is wrong (a slice the clock ended was the
+ client's clock's verdict, which the session's own contradicted)."""
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='rq-', dir=scratch))
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), XDG_DATA_HOME=str(root / 'data'),
+ TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1', PARDES_REPLICA_FAR='1')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ tree = root / 'tree'
+ for d in range(200):
+ (tree / f'module_{d}').mkdir(parents=True)
+ for f in range(200):
+ (tree / f'module_{d}' / f'replica_{f}.zig').touch()
+ notes = tree / 'notes.txt'
+ notes.write_text(''.join(f'line {i} of the notes\n' for i in range(300)))
+ started, terms = [], []
+ try:
+ sess = subprocess.Popen([binary, '--detach=find', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
+ started.append(sess.pid)
+ wait_for('the replica socket', (root / 'pardes-replica.sock').exists)
+ wait_for('the session\'s 9P socket', (root / 'pardes-9p-find.sock').exists)
+ nine = Client(root / 'pardes-9p-find.sock')
+ text = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
+ t = Term(30, 100)
+ terms.append(t)
+ c = t.spawn([binary, f'--attach={root / "pardes-replica.sock"}:find'],
+ dict(env, PARDES_REPLICA_CHECK=str(root / 'q.check'), PARDES_REPLICA_STATS=str(root / 'q.stats')))
+ started.append(c.pid)
+ wait_for('the client\'s first frame', lambda: b'line 3 of the notes' in t.text(), timeout=30)
+ time.sleep(.3)
+ # SPC f f: the Find, typed into, its names walked on the session's worker.
+ os.write(t.master, b' ff')
+ time.sleep(3)
+ wait_for('the client agrees once the walk is done', lambda: agreed(root / 'q.check', 0), timeout=60)
+ query = b'module_19/replica_3'
+ for ch in query:
+ os.write(t.master, bytes([ch]))
+ time.sleep(.15)
+ seen = len(checks(root / 'q.check'))
+ wait_for('the client agrees once quiet', lambda: agreed(root / 'q.check', seen), timeout=60)
+ c.send_signal(signal.SIGHUP)
+ c.wait(timeout=20)
+ line = (root / 'q.stats').read_text().split()
+ got = {line[i]: line[i + 1] for i in range(0, len(line) - 1, 2)}
+ print(f'daemon: a far client typed {len(query)} keys into a Find over 40,000 names: of its {got["inputs"]} inputs '
+ f'{got["mispredicted"]} mispredicted, {got["stopped"]} stopped, {got["fast"]} applied at once')
+ assert got['mispredicted'] == '0', got
+ exit_session(nine, text)
+ sess.wait(timeout=60)
+ nine.socket.close()
+ finally:
+ for term in terms:
+ term.close()
+ for pid in started + processes(root):
+ try:
+ os.kill(pid, signal.SIGKILL)
+ except OSError:
+ pass
+ shutil.rmtree(root, ignore_errors=True)
+
+
+def restore_client(binary):
+ """A Restore while a client is attached: the client is let go (its link
+ ends), the replacement core is the session's (its tape adopts it, its
+ options keep none), and a client attached after agrees with it, its
+ keys reaching it."""
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='rr-', dir=scratch))
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'), XDG_DATA_HOME=str(root / 'data'),
+ TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ notes = root / 'notes.txt'
+ notes.write_text(''.join(f'line {i} of the notes\n' for i in range(300)))
+ started, terms = [], []
+ try:
+ sess = subprocess.Popen([binary, '--detach=back', str(notes)], env=env, cwd=root, stdin=subprocess.DEVNULL,
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, start_new_session=True)
+ started.append(sess.pid)
+ wait_for('the replica socket', (root / 'pardes-replica.sock').exists)
+ wait_for('the session\'s 9P socket', (root / 'pardes-9p-back.sock').exists)
+ nine = Client(root / 'pardes-9p-back.sock')
+ text = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
+ def client(name):
+ t = Term(30, 100)
+ terms.append(t)
+ c = t.spawn([binary, f'--attach={root / "pardes-replica.sock"}:back'],
+ dict(env, PARDES_REPLICA_CHECK=str(root / f'{name}.check')))
+ started.append(c.pid)
+ wait_for(f'client {name}\'s first frame', lambda: b'line 3 of the notes' in t.text(), timeout=30)
+ time.sleep(.3)
+ return t, c
+ t, c = client('a')
+ nine.write(f'/pane/{text}/exec', b'Dump\n')
+ nine.write(f'/pane/{text}/exec', b'Restore\n')
+ wait_for('client a let go at the Restore', lambda: c.poll() is not None, timeout=30)
+ # The 9P link was the old core's.
+ nine.socket.close()
+ nine = reconnect(root / 'pardes-9p-back.sock')
+ text = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
+ t, c = client('r')
+ os.write(t.master, b'Oafter the restore\x1b')
+ texts = lambda: b''.join(nine.read(f'/pane/{row.split()[0].decode()}/body') for row in nine.read('/index').splitlines()
+ if row.split()[1] == b'text')
+ wait_for('the client\'s keys in the restored session', lambda: b'after the restore' in texts(), timeout=30)
+ seen = len(checks(root / 'r.check'))
+ wait_for('the client agrees once quiet', lambda: agreed(root / 'r.check', seen), timeout=60)
+ assert c.poll() is None, 'the client ended'
+ print(f'daemon: a Restore with a client attached: it was let go, and one attached after agreed ({len(checks(root / "r.check"))} checks), its keys in the restored session')
+ exit_session(nine, text)
+ sess.wait(timeout=60)
+ nine.socket.close()
+ finally:
+ for term in terms:
+ term.close()
+ for pid in started + processes(root):
+ try:
+ os.kill(pid, signal.SIGKILL)
+ except OSError:
+ pass
+ shutil.rmtree(root, ignore_errors=True)
+
+
def far_joins(sock, session, binary, n):
"""`n` far joins of one session in a row, each read whole (its blobs
asked for by none, its zstd frames unpacked) and answering a ping, then
@@ -1840,6 +2147,7 @@ def main(binary, cycles):
pair_rows(binary)
manage(binary)
relink(binary)
+ answer_late(binary)
shell = terminals(client)[0]
shell_pid = int(run(client, shell, b'echo $$\n').split(b'\n')[1])
started.append(shell_pid)
@@ -2121,6 +2429,108 @@ def gui(binary, cycles):
shutil.rmtree(root, ignore_errors=True)
+def gui_pair(gui_binary):
+ """PARDES_PAIR in a window (the last step's design, 1.2): `pardes-gui
+ FILE` is a window client and a session with no SDL, the `pardes` beside
+ it exec'd in a child (a window's session needs SDL for its wake, a
+ terminal's binary none): the session the window's child, in a session
+ of its own, listed detached with the window its client; the file in
+ the window's first frame, keys in. The window's close ends the session,
+ its last client (a CLOSE); the window killed leaves it running (a LOSS),
+ and with no daemon the session ends with its last link. Test mode:
+ hidden windows, offscreen."""
+ binary = gui_binary.replace('pardes-gui', 'pardes')
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='rgp-', dir=scratch))
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
+ SHELL='/bin/bash', PARDES_NOTIME='1', PARDES_DAEMON='on', TERM='xterm-256color', PARDES_PAIR='1')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ notes = root / 'notes.txt'
+ notes.write_text(''.join(f'line {i} of the notes\n' for i in range(30)))
+ windows = []
+
+ def listed():
+ return subprocess.run([binary, 'ps'], env=env, capture_output=True, timeout=30).stdout.decode()
+
+ def started(name, e):
+ w = Window(root, name, [gui_binary, f'--9p={name}', str(notes)], e)
+ windows.append(w)
+ sock = root / f'pardes-9p-{name}.sock'
+ wait_for(f'session {name}\'s 9P socket', sock.exists, timeout=30)
+ nine = Client(sock)
+ session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
+ assert session != w.pid and ppid(session) == w.pid and os.getsid(session) == session, (session, w.pid)
+ assert Path(cmdline(session)[0].decode()).name == 'pardes', ('the session is the pardes beside it', cmdline(session))
+ wait_for('the window\'s first frame', lambda: (root / name / 'latest.ppm').exists(), timeout=30)
+ pane = next(int(row.split()[0]) for row in nine.read('/index').splitlines() if row.split()[1] == b'text')
+ assert nine.read(f'/pane/{pane}/body').startswith(b'line 0 of the notes'), 'the file is the session\'s'
+ return w, nine, session, pane
+
+ try:
+ w, nine, session, pane = started('gp', env)
+ wait_for('the window listed its client', lambda: f'session gp {session} (tty)' in listed()
+ and f'client {w.pid} ' in listed())
+ w.keys(b'Ofrom-the-window\x1b')
+ wait_for('its keys in the session\'s text', lambda: b'from-the-window' in nine.read(f'/pane/{pane}/body'))
+ # The close button (the test feed's word for it): its last client
+ # closed, the session ends.
+ w.p.stdin.write(b'\x1b]777;close\x07')
+ w.p.stdin.flush()
+ assert w.p.wait(timeout=30) == 0, (w.p.returncode, w.said()[-400:])
+ wait_for('the session ended with its window', lambda: not alive(session), timeout=20)
+ nine.socket.close()
+ print(f'pair window: client {w.pid} (the window) and session {session} (the pardes beside it, exec\'d in its child, '
+ 'setsid, listed detached with the window); drawn, typed; the window closed ended both')
+ w, nine, session, pane = started('gl', env)
+ wait_for('the client listed', lambda: f'client {w.pid} ' in listed())
+ os.kill(w.pid, signal.SIGKILL)
+ w.p.wait(timeout=10)
+ wait_for('the client unlisted', lambda: f'client {w.pid} ' not in listed())
+ assert alive(session) and f'session gl {session} (tty)' in listed(), listed()
+ nine.socket.close()
+ assert subprocess.run([binary, 'kill', 'gl'], env=env, capture_output=True, timeout=30).returncode == 0
+ wait_for('the session ended', lambda: not alive(session), timeout=30)
+ print('pair window: the window killed: the session runs on, listed (a loss); killed by name')
+ # Kept from birth (`new --detach`): its window client's close leaves it.
+ out = subprocess.run([binary, 'new', '--detach=gk', str(notes)], env=env, cwd=root, capture_output=True,
+ timeout=30, stdin=subprocess.DEVNULL)
+ assert out.returncode == 0, out
+ with Client(root / 'pardes-9p-gk.sock') as kn:
+ gk = int(dict(line.split(maxsplit=1) for line in kn.read('/status').decode().splitlines())['pid'])
+ assert f'session gk {gk} (tty, kept)' in listed(), listed()
+ w = Window(root, 'gkw', [gui_binary, 'attach', 'gk'], env)
+ windows.append(w)
+ wait_for('the window client listed', lambda: f'client {w.pid} ' in listed(), timeout=30)
+ w.p.stdin.write(b'\x1b]777;close\x07')
+ w.p.stdin.flush()
+ assert w.p.wait(timeout=30) == 0, (w.p.returncode, w.said()[-400:])
+ wait_for('the client unlisted', lambda: f'client {w.pid} ' not in listed())
+ assert alive(gk) and f'session gk {gk} (tty, kept)' in listed(), listed()
+ assert subprocess.run([binary, 'kill', 'gk'], env=env, capture_output=True, timeout=30).returncode == 0
+ wait_for('the session ended', lambda: not alive(gk), timeout=30)
+ print('pair window: a `new --detach` session (kept): its window client closed, it runs on')
+ w, nine, session, pane = started('gn', dict(env, PARDES_DAEMON='off'))
+ nine.socket.close()
+ os.kill(w.pid, signal.SIGKILL)
+ w.p.wait(timeout=10)
+ wait_for('the lone session ended with its last link', lambda: not alive(session), timeout=20)
+ wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20)
+ print('pair window: with no daemon, the window killed, its session ended; nothing left behind')
+ finally:
+ for w in windows:
+ if w.p.poll() is None:
+ w.p.kill()
+ for p in processes(root):
+ try:
+ os.kill(p, signal.SIGKILL)
+ except OSError:
+ pass
+ shutil.rmtree(root, ignore_errors=True)
+
+
def screen_text(client):
shown = client.screen()
cells = ''.join(cell[0] for cell in shown['cells'])
@@ -2301,7 +2711,9 @@ def upgrades(old, new):
# its terminal and its stub's pipe let go once its stub is told
# (two fewer).
def level():
- gone = 2 if b'detached from' in term2.text() else 1
+ # (A client of a build that execs at an Upgrade comes back: its
+ # connection is the session's again.)
+ gone = 2 if b'detached from' in term2.text() else 0 if knows_exec(old) and stub2.poll() is None else 1
return fds_before[0] - 2 - gone + min(state_fds(session), 1) - state_before, fds_before[1]
try:
wait_for('the fds level', lambda: (fds(session), fds(daemon)) == level(), timeout=5)
@@ -2321,7 +2733,9 @@ def upgrades(old, new):
# build's own, let go (a session shows one frontend of its own now),
# its stub told.
wait_for('the second terminal redrawn or let go', lambda: b'\x1b[?1049h' in term2.text()[before[1]:] or
- (stub2.poll() is not None and (b'detached from' in term2.text() or b'upgrade this client too' in term2.text())))
+ (stub2.poll() is not None and (b'detached from' in term2.text() or b'upgrade this client too' in term2.text()
+ or b'run the same pardes at both ends' in term2.text())),
+ timeout=30)
wait_for('the word said', lambda: 'Upgrade: now pardes' in screen_text(client))
# The daemon lists the session under its new build.
said = Replica(root / 'pardes-replica.sock').hello('work', new_build)
@@ -2410,7 +2824,10 @@ def upgrades(old, new):
install(new, binary)
os.kill(session, signal.SIGKILL)
stub.wait(timeout=10)
- stub2.wait(timeout=10)
+ try:
+ stub2.wait(timeout=30)
+ except subprocess.TimeoutExpired:
+ raise AssertionError(('the second terminal\'s client on', cmdline(stub2.pid), term2.text()[-1200:]))
client.socket.close()
term.close()
term2.close()
@@ -2425,12 +2842,10 @@ def upgrades(old, new):
client = Client(sock)
again = int(dict(line.split(maxsplit=1) for line in client.read('/status').decode().splitlines())['pid'])
started.append(again)
- # Its reader of the daemon starts after its first frame: an Adopt
- # before that waits for an `ok` nobody reads, and is refused. The
- # daemon lists it once it has taken its hello, which its `ok`
- # answers: an Adopt before that waits at most 2 s for the `ok`
- # (daemon.zig `kept`), which a loaded machine can take (3 in 40 at
- # a load of 35).
+ # A build before daemon.zig's `kept` waited for the hello's answer
+ # (the new-to-old run) refused an Adopt before its reader of the
+ # daemon ran (after its first frame), or within 2 s of a slow `ok`:
+ # it is asked once the daemon lists it (answer_late tests the wait).
wait_for('the next session\'s first frame', lambda: b'\x1b[?1049h' in term.text())
wait_for('the next session listed by the daemon', lambda: f'session again {again} ' in subprocess.run(
[str(binary), '--ps'], env=env, capture_output=True, timeout=30).stdout.decode())
@@ -2457,6 +2872,124 @@ def upgrades(old, new):
shutil.rmtree(root, ignore_errors=True)
+def knows_exec(binary):
+ """Whether a build's client execs the build at its start path at an
+ Upgrade, for the view it is handed (PARDES_JOIN_VIEW)."""
+ return b'PARDES_JOIN_VIEW' in Path(binary).read_bytes()
+
+
+def upgrade_clients(old, new):
+ """Upgrade with near clients (the last step's design, 1.4): a session
+ (`new --detach`) with a terminal client and a window client attached,
+ each in its own view with a pane of its own there, onto another build installed at the path all three were
+ started from. A client of a build that execs (its start path holding
+ another file than the one it runs, the session another build than its
+ own) comes back on the build at its start path, the same process, for
+ its view: the terminal's leaves its screen and enters it again (the
+ blink), the window is a new one; in ITS view when that build joins for
+ a view it is handed (PARDES_JOIN_VIEW), else in a view of its own. One
+ of a build before it is let go and told to upgrade too. The session's
+ shell alive throughout; nothing left behind."""
+ old_gui, new_gui = old.with_name('pardes-gui'), new.with_name('pardes-gui')
+ scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn'
+ scratch.mkdir(parents=True, exist_ok=True)
+ root = Path(tempfile.mkdtemp(prefix='ruc-', dir=scratch))
+ env = {k: v for k, v in os.environ.items() if not k.startswith('PARDES_') and 'PAGER' not in k}
+ env.update(HOME=str(root), XDG_RUNTIME_DIR=str(root), XDG_CONFIG_HOME=str(root / 'config'),
+ TERM='xterm-256color', SHELL=shutil.which('bash') or '/bin/bash', PARDES_NOTIME='1')
+ (root / 'config' / 'pardes').mkdir(parents=True)
+ (root / 'config' / 'pardes' / 'init').write_text('Shell bash\nMessageLinger 0\n')
+ (root / 'bin').mkdir()
+ binary, gui_binary = root / 'bin' / 'pardes', root / 'bin' / 'pardes-gui'
+ install(old, binary)
+ install(old_gui, gui_binary)
+ terms = []
+ procs = []
+
+ def still(check, key):
+ """Its view the live one (made_live's, for either client)."""
+ seen = len(checks(check))
+ key(b'gg')
+ wait_for('the client\'s key stepped', lambda: agreed(check, seen + 1), timeout=30)
+
+ try:
+ out = subprocess.run([str(binary), 'new', '--detach=up'], env=env, cwd=root, capture_output=True, timeout=30)
+ assert out.returncode == 0, out
+ sock = root / 'pardes-9p-up.sock'
+ nine = Client(sock)
+ session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid'])
+ shell = terminals(nine)[0]
+ shell_pid = int(run(nine, shell, b'echo $$\n').split(b'\n')[1])
+ t = Term(30, 100)
+ terms.append(t)
+ tc = t.spawn([str(binary), 'attach', 'up'], dict(env, PARDES_REPLICA_CHECK=str(root / 't.check')))
+ procs.append(tc)
+ wait_for('the terminal client drawn', lambda: b'\x1b[?1049h' in t.text(), timeout=30)
+ w = Window(root, 'w', [str(gui_binary), 'attach', 'up'], dict(env, PARDES_REPLICA_CHECK=str(root / 'w.check')))
+ procs.append(w.p)
+ wait_for('the window client drawn', lambda: (root / 'w' / 'latest.ppm').exists(), timeout=30)
+ tkey = lambda b: os.write(t.master, b) # noqa: E731
+ # Each client's view live in turn, a pane of its own made there (New).
+ owners = ((w.keys, root / 'w.check'), (tkey, root / 't.check'))
+ mine = []
+ for key, check in owners:
+ still(check, key)
+ shown = view_panes(nine)
+ nine.write('/exec', b'New\n')
+ mine.append(wait_for('a pane in the client\'s view', lambda: view_panes(nine) - shown).pop())
+ for (key, check), pane, theirs in zip(owners, mine, reversed(mine)):
+ still(check, key)
+ assert pane in view_panes(nine) and theirs not in view_panes(nine), ('each its own view', pane, theirs, nine.read('/layout'))
+ install(new, binary)
+ install(new_gui, gui_binary)
+ mark = len(t.text())
+ nine.write('/ctl', b'Upgrade\n')
+ nine.socket.close()
+ wait_for('the session on the new build', lambda: exe_of(session) == (str(binary), True), timeout=30)
+ nine = reconnect(sock)
+ if not knows_exec(old):
+ # A build before the exec: let go, dialled again for 20 s, told.
+ assert tc.wait(timeout=60) == 1 and w.p.wait(timeout=60) == 1, (tc.returncode, w.p.returncode)
+ said = t.text()[mark:] + w.said().encode()
+ assert b'upgrade this client too' in said or b'run the same pardes at both ends' in said, said[-600:]
+ print('upgrade with clients: the clients of a build before it were let go, dialled again, and told to upgrade too')
+ else:
+ wait_for('the terminal client on the new build', lambda: exe_of(tc.pid) == (str(binary), True), timeout=30)
+ wait_for('the window client on the new build', lambda: exe_of(w.pid) == (str(gui_binary), True), timeout=30)
+ # The blink: its screen left, and entered again.
+ wait_for('the terminal entered again', lambda: t.text().rfind(b'\x1b[?1049h') > t.text().rfind(b'\x1b[?1049l') > mark, timeout=30)
+ assert tc.poll() is None and w.p.poll() is None
+ for (key, check), pane, theirs in zip(owners, mine, reversed(mine)):
+ still(check, key)
+ if knows_exec(new):
+ shown = view_panes(nine)
+ assert pane in shown and theirs not in shown, ('its own view again', pane, theirs, nine.read('/layout'))
+ print('upgrade with clients: a terminal client and a window client exec\'d the build at their start path, the same processes, '
+ + ('each back in its own view, its own pane in it' if knows_exec(new) else 'each in a view of its own (that build joins for no view it is handed)'))
+ assert alive(shell_pid) and ppid(shell_pid) == session
+ for p in procs:
+ if p.poll() is None:
+ p.terminate()
+ p.wait(timeout=20)
+ nine.socket.close()
+ assert subprocess.run([str(binary), 'kill', 'up'], env=env, capture_output=True, timeout=30).returncode == 0
+ wait_for('the session ended', lambda: not alive(session), timeout=30)
+ wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20)
+ print('upgrade with clients: the shell ran on throughout; nothing left behind')
+ finally:
+ for p in procs:
+ if p.poll() is None:
+ p.kill()
+ for p in processes(root):
+ try:
+ os.kill(p, signal.SIGKILL)
+ except OSError:
+ pass
+ for t in terms:
+ t.close()
+ shutil.rmtree(root, ignore_errors=True)
+
+
def gui_upgrades(old, new):
"""Upgrade in a window session (test mode: hidden windows, captured):
its window, a client window, an unsaved edit and a shell's job, onto
@@ -2551,6 +3084,11 @@ if __name__ == '__main__':
gui_upgrades(Path(sys.argv[3]).resolve(), Path(sys.argv[4]).resolve())
elif sys.argv[1:2] == ['--upgrade']:
upgrades(Path(sys.argv[2]).resolve(), Path(sys.argv[3]).resolve())
+ # With a pardes-gui beside each: the clients carried too.
+ if all(Path(a).resolve().with_name('pardes-gui').exists() for a in sys.argv[2:4]):
+ upgrade_clients(Path(sys.argv[2]).resolve(), Path(sys.argv[3]).resolve())
+ elif sys.argv[1:2] == ['--upgrade-clients']:
+ upgrade_clients(Path(sys.argv[2]).resolve(), Path(sys.argv[3]).resolve())
elif sys.argv[1:2] == ['--clients']:
clients(sys.argv[2])
elif sys.argv[1:2] == ['--manage']:
@@ -2562,19 +3100,28 @@ if __name__ == '__main__':
pair_rows(sys.argv[2])
elif sys.argv[1:2] == ['--relink']:
relink(sys.argv[2])
+ answer_late(sys.argv[2])
elif sys.argv[1:2] == ['--games']:
games(sys.argv[2], sys.argv[3], float(sys.argv[4]) if len(sys.argv) > 4 else 10)
elif sys.argv[1:2] == ['--far']:
far(sys.argv[2])
far_flood(sys.argv[2])
by_hash(sys.argv[2])
+ far_find(sys.argv[2])
+ elif sys.argv[1:2] == ['--far-find']:
+ far_find(sys.argv[2])
+ elif sys.argv[1:2] == ['--restore']:
+ restore_client(sys.argv[2])
elif sys.argv[1:2] == ['--window-clients']:
window_clients(sys.argv[2], sys.argv[3])
pdf_window(sys.argv[2], sys.argv[3])
elif sys.argv[1:2] == ['--ping']:
ping(sys.argv[2], sys.argv[3], sys.argv[4], int(sys.argv[5]) if len(sys.argv) > 5 else 50)
+ elif sys.argv[1:2] == ['--pair-gui']:
+ gui_pair(sys.argv[2])
elif '--gui' in sys.argv:
args = [a for a in sys.argv[1:] if a != '--gui']
gui(args[0], int(args[1]) if len(args) > 1 else 50)
+ gui_pair(args[0])
else:
main(sys.argv[1], int(sys.argv[2]) if len(sys.argv) > 2 else 50)
diff --git a/test/delay_relay.py b/test/delay_relay.py
index c600a3aa..b0d48e38 100644
--- a/test/delay_relay.py
+++ b/test/delay_relay.py
@@ -8,7 +8,7 @@ the ones before it have crossed at that rate, then waits out the delay. An
optional jitter adds up to that many ms more to each chunk's delay, at
random, its order kept (a chunk never overtakes the one before it).
- python3 -B test/delay_relay.py LISTEN TARGET --delay MS [--rate MB/s] [--jitter MS]
+ python3 -B test/delay_relay.py LISTEN TARGET --delay MS [--rate MB/s] [--jitter MS] [--bound MS]
python3 -B test/delay_relay.py --self-check
An address is a path (a Unix socket) or host:port (TCP). The one-way
@@ -46,7 +46,9 @@ def dial(address):
return s
-def listen(address):
+def listen(address, bound=0.0):
+ """Bound, then listening `bound` s later (an ssh -L's socket file is
+ there a moment before it answers)."""
family, addr = parse(address)
s = socket.socket(family)
if family == socket.AF_UNIX:
@@ -57,6 +59,7 @@ def listen(address):
else:
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(addr)
+ time.sleep(bound)
s.listen(64)
return s
@@ -260,8 +263,9 @@ def main():
ap.add_argument('--delay', type=float, required=True, help='one-way delay, ms')
ap.add_argument('--rate', type=float, help='a bandwidth cap, MB/s')
ap.add_argument('--jitter', type=float, default=0, help='up to this many ms more a chunk, at random')
+ ap.add_argument('--bound', type=float, default=0, help='ms between the bind and the listen')
a = ap.parse_args()
- listener = listen(a.listen)
+ listener = listen(a.listen, a.bound / 1000)
print(f'relaying {a.listen} -> {a.target}, {a.delay} ms each way'
+ (f', {a.rate} MB/s' if a.rate else '') + (f', jitter {a.jitter} ms' if a.jitter else ''), flush=True)
try:
diff --git a/test/e2e_harness.zig b/test/e2e_harness.zig
index f7d65b03..9481166e 100644
--- a/test/e2e_harness.zig
+++ b/test/e2e_harness.zig
@@ -20,6 +20,7 @@ extern "c" fn openpty(
winp: ?*const posix.winsize,
) c_int;
extern "c" fn ttyname(fd: c_int) ?[*:0]const u8;
+extern "c" fn ptsname(fd: c_int) ?[*:0]const u8;
extern "c" fn execvp(file: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int;
extern "c" fn _exit(status: c_int) noreturn;
extern "c" fn unsetenv(name: [*:0]const u8) c_int;
@@ -149,9 +150,25 @@ pub const Harness = struct {
return true;
}
+ /// The app ended as closing its terminal ends it: the master closed (its
+ /// hangup), the app given `end_ms` to end, SIGKILLed only after, and
+ /// reaped: what it ends at its own end (its shells, its language servers'
+ /// groups) does not outlive the case.
pub fn deinit(self: *Harness) void {
- posix.kill(self.pid, posix.SIG.KILL) catch {};
_ = libc.close(self.master);
+ const end_ms = 5000;
+ const until = nowMs() + end_ms;
+ var status: c_int = 0;
+ var none: [0]posix.pollfd = .{};
+ while (libc.waitpid(self.pid, &status, libc.W.NOHANG) == 0) {
+ if (nowMs() < until) {
+ _ = posix.poll(&none, 5) catch 0;
+ continue;
+ }
+ posix.kill(self.pid, posix.SIG.KILL) catch {};
+ _ = libc.waitpid(self.pid, &status, 0);
+ break;
+ }
self.stream.deinit();
self.gpa.destroy(self.raw);
self.term.deinit(self.gpa);
@@ -235,6 +252,21 @@ pub const Harness = struct {
return if (n > 0) @intCast(n) else 0;
}
+ /// Bytes typed that the app has not read yet: its end's input queue
+ /// (the master's FIONREAD counts only what the app wrote).
+ pub fn unread(self: *Harness) usize {
+ const FIONREAD: c_int = switch (@import("builtin").os.tag) {
+ .linux => posix.T.FIONREAD,
+ else => 0x4004667f,
+ };
+ const fd = libc.open(ptsname(self.master) orelse return 0, .{ .ACCMODE = .RDWR, .NOCTTY = true, .CLOEXEC = true });
+ if (fd < 0) return 0;
+ defer _ = libc.close(fd);
+ var n: c_int = 0;
+ if (posix.system.ioctl(fd, FIONREAD, @intFromPtr(&n)) != 0) return 0;
+ return if (n > 0) @intCast(n) else 0;
+ }
+
/// Resize both the pty (SIGWINCH to the app) and our terminal (grid reflows
/// to the new size). Harness terminal first so it's ready for the app's
/// re-render at the new size.
@@ -317,11 +349,13 @@ pub const Harness = struct {
};
}
- /// The visual cursor position (viewport coords): { x, y }.
- pub fn cursor(self: *Harness) struct { x: u16, y: u16 } {
+ /// The visual cursor position (viewport coords): { x, y }, and whether
+ /// the app shows it (DECTCEM).
+ pub fn cursor(self: *Harness) struct { x: u16, y: u16, shown: bool } {
return .{
.x = self.term.screens.active.cursor.x,
.y = self.term.screens.active.cursor.y,
+ .shown = self.term.modes.get(.cursor_visible),
};
}
diff --git a/test/lspmock.zig b/test/lspmock.zig
index 001c3488..8b5c73a8 100644
--- a/test/lspmock.zig
+++ b/test/lspmock.zig
@@ -15,12 +15,17 @@
//! mute handshake, then never answer another request (timeout path)
//! die exit right after the handshake (dead-server path)
//! utf16 refuse the utf-8 negotiation (column-conversion path)
+//! busy at the handshake, leave a child running in the server's
+//! group, as a build a server started does; its pid said in
+//! `lspmock-busy.pid` in the server's directory (its root)
const std = @import("std");
const libc = std.c;
extern "c" fn getenv(name: [*:0]const u8) ?[*:0]const u8;
+extern "c" fn fork() libc.pid_t;
+extern "c" fn pause() c_int;
-var mode: enum { normal, mute, die, utf16 } = .normal;
+var mode: enum { normal, mute, die, utf16, busy } = .normal;
/// stdout, written with plain libc write(2): the transport is a socketpair
/// and the frames are small, so partial writes are retried and nothing else
@@ -118,6 +123,7 @@ pub fn main(init: std.process.Init) !void {
if (std.mem.eql(u8, s, "mute")) mode = .mute;
if (std.mem.eql(u8, s, "die")) mode = .die;
if (std.mem.eql(u8, s, "utf16")) mode = .utf16;
+ if (std.mem.eql(u8, s, "busy")) mode = .busy;
}
const gpa = std.heap.page_allocator;
@@ -164,6 +170,23 @@ pub fn main(init: std.process.Init) !void {
}
}
+/// A child that runs on in this server's group, its socket closed, and
+/// says its pid.
+fn leaveChild() void {
+ const pid = fork();
+ if (pid != 0) return;
+ _ = libc.close(0);
+ _ = libc.close(1);
+ var buf: [16]u8 = undefined;
+ const said = std.fmt.bufPrint(&buf, "{d}\n", .{libc.getpid()}) catch unreachable;
+ const fd = libc.open("lspmock-busy.pid", .{ .ACCMODE = .WRONLY, .CREAT = true, .TRUNC = true }, @as(libc.mode_t, 0o600));
+ if (fd >= 0) {
+ _ = libc.write(fd, said.ptr, said.len);
+ _ = libc.close(fd);
+ }
+ while (true) _ = pause();
+}
+
fn handle(a: std.mem.Allocator, raw: []const u8) void {
const v = std.json.parseFromSliceLeaky(std.json.Value, a, raw, .{}) catch return;
const method = str(get(v, "method")) orelse "";
@@ -195,6 +218,7 @@ fn handle(a: std.mem.Allocator, raw: []const u8) void {
}
if (std.mem.eql(u8, method, "initialized")) {
if (mode == .die) std.process.exit(0);
+ if (mode == .busy) leaveChild();
// the progress trio, so the status pipeline has something to narrate
notify(a, "$/progress", "{{\"token\":\"t1\",\"value\":{{\"kind\":\"begin\",\"title\":\"mocking\"}}}}", .{});
notify(a, "$/progress", "{{\"token\":\"t1\",\"value\":{{\"kind\":\"report\",\"percentage\":50,\"message\":\"halfway\"}}}}", .{});
diff --git a/test/macos_e2e.swift b/test/macos_e2e.swift
index 38d27808..25d83957 100644
--- a/test/macos_e2e.swift
+++ b/test/macos_e2e.swift
@@ -168,7 +168,7 @@ private final class Driver: PardesViewDelegate {
message: "the view measured \(got.cols)x\(got.rows) cells, not the \(cols)x\(rows) the script asked for")
}
- var runtime = pardes_callbacks_s(
+ var callbacks = pardes_callbacks_s(
userdata: Unmanaged.passUnretained(host).toOpaque(),
wakeup: { ud in
// A pty reader thread. One flag and out — see Host.woke.
@@ -200,7 +200,7 @@ private final class Driver: PardesViewDelegate {
text.withCString { pardes_paste($0, text.utf8.count) }
})
- let rc = pardes_init(&runtime, got.cols, got.rows)
+ let rc = pardes_init(&callbacks, got.cols, got.rows)
guard rc == 0 else {
throw ScriptError(message: "pardes_init returned \(rc) at \(cols)x\(rows)")
}
diff --git a/test/panes.zig b/test/panes.zig
index 6bda3519..38eb0a71 100644
--- a/test/panes.zig
+++ b/test/panes.zig
@@ -3949,6 +3949,10 @@ const PdfAddon = struct {
}
};
const id = try opened(a, Land{ .a = a, .r = r });
+ // The effects `jobs` took last are the session's steps: a unit of
+ // its own before the client's input.
+ a.seq += 1;
+ r.confirm(try a.unit(0, a.seq));
const guessed = r.stats.mispredicted;
const stopped = r.stats.stopped;
const told = a.core.panes[id].?.addon.?.views;
diff --git a/test/perf-baseline-gui-debug.json b/test/perf-baseline-gui-debug.json
index b833000d..63c83edf 100644
--- a/test/perf-baseline-gui-debug.json
+++ b/test/perf-baseline-gui-debug.json
@@ -1 +1 @@
-{"harness":"d6c5e18a4acc4fe3","build":{"compiler":"0.17.1","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"debug","c_optimize":"fast","terminal_optimize":"safe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400}],"cells":[{"op":"open","fixture":"medium","min_us":1713,"med_us":1939,"p90_us":2099,"max_us":2119},{"op":"render","fixture":"medium","min_us":82,"med_us":83,"p90_us":86,"max_us":92},{"op":"key-down","fixture":"medium","min_us":89,"med_us":93,"p90_us":101,"max_us":106},{"op":"key-right","fixture":"medium","min_us":88,"med_us":90,"p90_us":95,"max_us":98},{"op":"page-down","fixture":"medium","min_us":88,"med_us":90,"p90_us":95,"max_us":104},{"op":"wheel","fixture":"medium","min_us":86,"med_us":88,"p90_us":93,"max_us":95},{"op":"edit-char","fixture":"medium","min_us":331,"med_us":391,"p90_us":398,"max_us":429},{"op":"edit-twin","fixture":"medium","min_us":354,"med_us":412,"p90_us":433,"max_us":455},{"op":"body-2m","fixture":"medium","min_us":1006,"med_us":1549,"p90_us":1694,"max_us":1777},{"op":"body-appends","fixture":"medium","min_us":1125,"med_us":1324,"p90_us":1392,"max_us":1416},{"op":"deep-sel","fixture":"medium","min_us":76,"med_us":78,"p90_us":83,"max_us":136},{"op":"image-frame","fixture":"medium","min_us":114,"med_us":121,"p90_us":130,"max_us":142}]}
+{"harness":"837d32e9cf0d2155","build":{"compiler":"0.17.1","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"debug","c_optimize":"fast","terminal_optimize":"safe","platform":"gui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400}],"cells":[{"op":"open","fixture":"medium","min_us":2350,"med_us":2586,"p90_us":2766,"max_us":2827},{"op":"render","fixture":"medium","min_us":88,"med_us":90,"p90_us":95,"max_us":95},{"op":"key-down","fixture":"medium","min_us":95,"med_us":97,"p90_us":100,"max_us":103},{"op":"client-key-down","fixture":"medium","min_us":158,"med_us":162,"p90_us":165,"max_us":166},{"op":"key-right","fixture":"medium","min_us":96,"med_us":97,"p90_us":100,"max_us":104},{"op":"page-down","fixture":"medium","min_us":95,"med_us":97,"p90_us":102,"max_us":105},{"op":"wheel","fixture":"medium","min_us":93,"med_us":95,"p90_us":97,"max_us":97},{"op":"edit-char","fixture":"medium","min_us":383,"med_us":472,"p90_us":526,"max_us":536},{"op":"client-edit-char","fixture":"medium","min_us":899,"med_us":960,"p90_us":1016,"max_us":1045},{"op":"client-delete-undo","fixture":"medium","min_us":4385,"med_us":4615,"p90_us":4947,"max_us":4981},{"op":"edit-twin","fixture":"medium","min_us":397,"med_us":502,"p90_us":527,"max_us":536},{"op":"body-2m","fixture":"medium","min_us":1043,"med_us":1905,"p90_us":2096,"max_us":2111},{"op":"body-appends","fixture":"medium","min_us":1262,"med_us":1507,"p90_us":1600,"max_us":1705},{"op":"deep-sel","fixture":"medium","min_us":77,"med_us":78,"p90_us":79,"max_us":80},{"op":"image-frame","fixture":"medium","min_us":52,"med_us":54,"p90_us":56,"max_us":56}]}
diff --git a/test/perf-baseline-tui-debug.json b/test/perf-baseline-tui-debug.json
index 2ed71e52..ebfcaa78 100644
--- a/test/perf-baseline-tui-debug.json
+++ b/test/perf-baseline-tui-debug.json
@@ -1 +1 @@
-{"harness":"d6c5e18a4acc4fe3","build":{"compiler":"0.17.1","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"debug","c_optimize":"fast","terminal_optimize":"safe","platform":"tui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400}],"cells":[{"op":"open","fixture":"medium","min_us":1745,"med_us":2061,"p90_us":2178,"max_us":2218},{"op":"render","fixture":"medium","min_us":81,"med_us":86,"p90_us":93,"max_us":97},{"op":"key-down","fixture":"medium","min_us":89,"med_us":96,"p90_us":110,"max_us":124},{"op":"key-right","fixture":"medium","min_us":87,"med_us":88,"p90_us":98,"max_us":109},{"op":"page-down","fixture":"medium","min_us":88,"med_us":88,"p90_us":91,"max_us":91},{"op":"wheel","fixture":"medium","min_us":85,"med_us":86,"p90_us":89,"max_us":94},{"op":"edit-char","fixture":"medium","min_us":328,"med_us":395,"p90_us":431,"max_us":433},{"op":"edit-twin","fixture":"medium","min_us":353,"med_us":405,"p90_us":439,"max_us":440},{"op":"body-2m","fixture":"medium","min_us":927,"med_us":1554,"p90_us":1651,"max_us":1974},{"op":"body-appends","fixture":"medium","min_us":1193,"med_us":1314,"p90_us":1493,"max_us":1511},{"op":"deep-sel","fixture":"medium","min_us":75,"med_us":78,"p90_us":83,"max_us":83},{"op":"image-frame","fixture":"medium","min_us":111,"med_us":119,"p90_us":132,"max_us":134}]}
+{"harness":"837d32e9cf0d2155","build":{"compiler":"0.17.1","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"debug","c_optimize":"fast","terminal_optimize":"safe","platform":"tui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400}],"cells":[{"op":"open","fixture":"medium","min_us":2043,"med_us":2295,"p90_us":2410,"max_us":2572},{"op":"render","fixture":"medium","min_us":80,"med_us":82,"p90_us":86,"max_us":86},{"op":"key-down","fixture":"medium","min_us":85,"med_us":86,"p90_us":94,"max_us":105},{"op":"client-key-down","fixture":"medium","min_us":148,"med_us":153,"p90_us":160,"max_us":175},{"op":"key-right","fixture":"medium","min_us":85,"med_us":88,"p90_us":91,"max_us":93},{"op":"page-down","fixture":"medium","min_us":86,"med_us":90,"p90_us":101,"max_us":107},{"op":"wheel","fixture":"medium","min_us":82,"med_us":86,"p90_us":89,"max_us":93},{"op":"edit-char","fixture":"medium","min_us":348,"med_us":411,"p90_us":460,"max_us":472},{"op":"client-edit-char","fixture":"medium","min_us":681,"med_us":713,"p90_us":737,"max_us":777},{"op":"client-delete-undo","fixture":"medium","min_us":3727,"med_us":4281,"p90_us":5052,"max_us":5118},{"op":"edit-twin","fixture":"medium","min_us":364,"med_us":464,"p90_us":533,"max_us":543},{"op":"body-2m","fixture":"medium","min_us":928,"med_us":1580,"p90_us":1730,"max_us":1766},{"op":"body-appends","fixture":"medium","min_us":1096,"med_us":1307,"p90_us":1416,"max_us":1532},{"op":"deep-sel","fixture":"medium","min_us":68,"med_us":70,"p90_us":72,"max_us":72},{"op":"image-frame","fixture":"medium","min_us":48,"med_us":52,"p90_us":55,"max_us":65}]}
diff --git a/test/perf-baseline-tui-fast.json b/test/perf-baseline-tui-fast.json
index 5fff67f7..b7a7e0b6 100644
--- a/test/perf-baseline-tui-fast.json
+++ b/test/perf-baseline-tui-fast.json
@@ -1 +1 @@
-{"harness":"d6c5e18a4acc4fe3","build":{"compiler":"0.17.1","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"fast","c_optimize":"fast","terminal_optimize":"fast","platform":"tui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400}],"cells":[{"op":"open","fixture":"medium","min_us":1722,"med_us":2008,"p90_us":2211,"max_us":2219},{"op":"render","fixture":"medium","min_us":74,"med_us":78,"p90_us":80,"max_us":92},{"op":"key-down","fixture":"medium","min_us":79,"med_us":81,"p90_us":83,"max_us":84},{"op":"key-right","fixture":"medium","min_us":79,"med_us":80,"p90_us":81,"max_us":83},{"op":"page-down","fixture":"medium","min_us":79,"med_us":79,"p90_us":81,"max_us":82},{"op":"wheel","fixture":"medium","min_us":76,"med_us":77,"p90_us":80,"max_us":88},{"op":"edit-char","fixture":"medium","min_us":314,"med_us":366,"p90_us":385,"max_us":404},{"op":"edit-twin","fixture":"medium","min_us":347,"med_us":405,"p90_us":469,"max_us":471},{"op":"body-2m","fixture":"medium","min_us":848,"med_us":1376,"p90_us":1575,"max_us":1692},{"op":"body-appends","fixture":"medium","min_us":931,"med_us":1171,"p90_us":1215,"max_us":1246},{"op":"deep-sel","fixture":"medium","min_us":64,"med_us":66,"p90_us":67,"max_us":70},{"op":"image-frame","fixture":"medium","min_us":43,"med_us":45,"p90_us":46,"max_us":49}]}
+{"harness":"837d32e9cf0d2155","build":{"compiler":"0.17.1","target":"x86_64-linux.5.10...7.2-gnu.2.38","cpu":"x86_64","driver_optimize":"fast","core_optimize":"fast","c_optimize":"fast","terminal_optimize":"fast","platform":"tui","grammars":"full","mupdf":true,"jpx":true,"tracy":false,"terminal_simd":true,"prebuilt_shaders":false},"cols":120,"rows":40,"reps":10,"only":"medium","fixtures":[{"name":"small","lines":1000,"cols":60,"bytes":62694},{"name":"medium","lines":50000,"cols":60,"bytes":3201944},{"name":"large","lines":300000,"cols":60,"bytes":19464444},{"name":"longline","lines":400,"cols":8000,"bytes":3200400}],"cells":[{"op":"open","fixture":"medium","min_us":1955,"med_us":2189,"p90_us":2334,"max_us":2374},{"op":"render","fixture":"medium","min_us":74,"med_us":77,"p90_us":81,"max_us":82},{"op":"key-down","fixture":"medium","min_us":78,"med_us":81,"p90_us":87,"max_us":94},{"op":"client-key-down","fixture":"medium","min_us":137,"med_us":142,"p90_us":154,"max_us":160},{"op":"key-right","fixture":"medium","min_us":79,"med_us":81,"p90_us":83,"max_us":94},{"op":"page-down","fixture":"medium","min_us":79,"med_us":83,"p90_us":84,"max_us":89},{"op":"wheel","fixture":"medium","min_us":79,"med_us":84,"p90_us":118,"max_us":135},{"op":"edit-char","fixture":"medium","min_us":331,"med_us":425,"p90_us":454,"max_us":515},{"op":"client-edit-char","fixture":"medium","min_us":700,"med_us":798,"p90_us":857,"max_us":895},{"op":"client-delete-undo","fixture":"medium","min_us":3653,"med_us":4324,"p90_us":5289,"max_us":5555},{"op":"edit-twin","fixture":"medium","min_us":361,"med_us":447,"p90_us":472,"max_us":475},{"op":"body-2m","fixture":"medium","min_us":974,"med_us":1713,"p90_us":2387,"max_us":2524},{"op":"body-appends","fixture":"medium","min_us":944,"med_us":1181,"p90_us":1286,"max_us":1376},{"op":"deep-sel","fixture":"medium","min_us":65,"med_us":67,"p90_us":68,"max_us":70},{"op":"image-frame","fixture":"medium","min_us":46,"med_us":49,"p90_us":50,"max_us":73}]}
diff --git a/test/perf.zig b/test/perf.zig
index 7920dedf..8c88ef01 100644
--- a/test/perf.zig
+++ b/test/perf.zig
@@ -391,6 +391,8 @@ const Options = struct {
creation: bool = false,
startup: bool = false,
mini: bool = false,
+ /// The scans a frame's slice bounds, a call at a time (`measureSearch`).
+ search: bool = false,
terminal_mib: ?usize = null,
/// The real binary's keystroke-to-present, `yes` stream and big open
/// (a tty pardes), or its keystrokes alone (a pardes-gui).
@@ -407,13 +409,14 @@ const Options = struct {
while (i < args.len) : (i += 1) {
const arg = args[i];
if (!std.mem.startsWith(u8, arg, "--")) return error.UnknownOption;
- const option = std.meta.stringToEnum(enum { json, creation, startup, mini, @"terminal-mib", @"self-test", reps, cols, rows, base, only, op, @"max-ratio", live, @"live-gui" }, arg[2..]) orelse
+ const option = std.meta.stringToEnum(enum { json, creation, startup, mini, search, @"terminal-mib", @"self-test", reps, cols, rows, base, only, op, @"max-ratio", live, @"live-gui" }, arg[2..]) orelse
return error.UnknownOption;
switch (option) {
.json => opts.json = true,
.creation => opts.creation = true,
.startup => opts.startup = true,
.mini => opts.mini = true,
+ .search => opts.search = true,
.@"self-test" => opts.self_test = true,
else => {
i += 1;
@@ -475,6 +478,7 @@ pub fn main(init: std.process.Init) !void {
if (opts.creation) return measureCreation(init.io, reps, opts.json);
if (opts.terminal_mib) |mib| return measureTerminalSession(init.io, mib, reps, opts.json);
if (opts.mini) return measureMini(init.io, init.gpa, reps, opts.json);
+ if (opts.search) return measureSearch(init.io);
if (opts.live) |exe| return measureLive(init.io, exe, false, reps, opts.json);
if (opts.live_gui) |exe| return measureLive(init.io, exe, true, reps, opts.json);
// The image-frame cells load the image addon by the path the build baked
@@ -1742,6 +1746,138 @@ fn measureMini(io: std.Io, fallback: std.mem.Allocator, reps: usize, json: bool)
}
}
+/// `--search`: the two scans a frame's slice bounds, each call timed and
+/// its instructions counted (user space, this thread): a find's names
+/// scored again as a query is typed into it over 200,000 paths
+/// (core/Names.zig `rescore`, Names' cap), and a search's places found a
+/// tick at a time over the large fixture, the view in its middle
+/// (core/Places.zig `settle` on a tick). The longest call of each is the
+/// slice a key or a frame can take.
+fn measureSearch(io: std.Io) !void {
+ var random: [12]u8 = undefined;
+ io.random(&random);
+ const dir = try std.fmt.allocPrint(gpa, "/tmp/pardes-perf-{x}", .{random});
+ defer gpa.free(dir);
+ try std.Io.Dir.createDirAbsolute(io, dir, .default_dir);
+ defer std.Io.Dir.cwd().deleteTree(io, dir) catch {};
+ var counter: Instructions = try .open();
+ defer counter.close();
+
+ const Names = @FieldType(pardes.panes.Query, "names");
+ var names: Names = .{};
+ defer names.deinit(gpa);
+ const dirs = [_][]const u8{ "core", "dev/gui", "dev/tui", "runtime", "test/behaviour", "addons/pdf", "zig-pkg/ghostty/src/terminal" };
+ const words = [_][]const u8{ "layout", "places", "names", "query", "stream", "surface", "replica", "tape", "kitty", "render" };
+ var row: [160]u8 = undefined;
+ for (0..200_000) |i| {
+ const path = try std.fmt.bufPrint(&row, "{s}/module_{d}/{s}_{d}.zig", .{ dirs[i % dirs.len], i / 64 % 997, words[i * 7 % words.len], i });
+ try names.add(gpa, path, 0, path.len, Names.baseOf(path), 0);
+ }
+ // Typed a key at a time, as into a find: each key's call, then the
+ // calls of the frames after it while it is busy.
+ for ([_][]const u8{ "m", "tape", "places zig", "core/module_9/replica_1", "zig-pkg/ghostty/src/terminal/module_99/kitty" }) |query| {
+ var slow: Slowest = .{};
+ names.typed(gpa, "");
+ for (1..query.len + 1) |n| {
+ var calls: usize = 0;
+ while (true) : (calls += 1) {
+ const was = counter.read();
+ const t0 = nowNs();
+ if (calls == 0) names.typed(gpa, query[0..n]) else names.rescore(gpa);
+ slow.add(nowNs() -| t0, counter.read() -| was, names.hits.items.len);
+ if (!names.busy()) break;
+ }
+ }
+ slow.report("rescore", query, names.hits.items.len);
+ }
+
+ const fx = fixtures[2];
+ const path = try std.fmt.allocPrint(gpa, "{s}/{s}.zig", .{ dir, fx.name });
+ defer gpa.free(path);
+ const text = try generate(fx);
+ try writeFile(path, text);
+ gpa.free(text);
+ for ([_][]const u8{ "e", "lorem.*amet", "helper_[0-9]+", "qqq" }) |pattern| {
+ const core = try boot();
+ defer core.deinit();
+ pardes.look.lookAt(core, 0, path);
+ pump(core);
+ const id = filePane(core) orelse return error.OpenDidNotOpenFile;
+ const pane = core.panes[id].?;
+ seek(pane, fx, 0);
+ pane.file.?.scroll = fx.lines / 2;
+ pane.body.cur_row = @intCast(fx.lines / 2);
+ _ = try frame(core);
+ const set = &pane.places;
+ set.search(core, pane, .typed, pane.serial, pattern, false, null, false);
+ var slow: Slowest = .{};
+ while (set.busy(pane) and slow.calls < 100_000) {
+ const was = counter.read();
+ const t0 = nowNs();
+ set.settle(core, pane, true);
+ slow.add(nowNs() -| t0, counter.read() -| was, 0);
+ }
+ slow.report("fill", pattern, set.hits.items.len);
+ }
+}
+
+/// The longest of a scan's calls.
+const Slowest = struct {
+ calls: usize = 0,
+ total_ns: u64 = 0,
+ ns: u64 = 0,
+ /// The instructions of the longest call (by time), and the most of any.
+ ins: u64 = 0,
+ most_ins: u64 = 0,
+ /// The same of the calls that left under 1,000 hits to sort: the scan
+ /// alone, nearly (`Names.rescore` sorts every hit at each call).
+ few_ns: u64 = 0,
+ few_ins: u64 = 0,
+
+ fn add(s: *Slowest, ns: u64, ins: u64, hits: usize) void {
+ s.calls += 1;
+ if (hits < 1000 and ns > s.few_ns) {
+ s.few_ns = ns;
+ s.few_ins = ins;
+ }
+ s.total_ns += ns;
+ if (ns > s.ns) {
+ s.ns = ns;
+ s.ins = ins;
+ }
+ s.most_ins = @max(s.most_ins, ins);
+ }
+
+ fn report(s: *const Slowest, what: []const u8, of: []const u8, hits: usize) void {
+ std.debug.print("{s} \"{s}\": {d} calls, {d} hits, {d:.2} ms in all; longest {d} us ({d} instructions); most instructions {d}; longest with under 1,000 hits {d} us ({d} instructions)\n", .{
+ what, of, s.calls, hits, @as(f64, @floatFromInt(s.total_ns)) / 1e6, s.ns / 1000, s.ins, s.most_ins, s.few_ns / 1000, s.few_ins,
+ });
+ }
+};
+
+/// This thread's instructions in user space (perf_event_open).
+const Instructions = struct {
+ fd: std.posix.fd_t,
+
+ fn open() !Instructions {
+ const linux = std.os.linux;
+ var attr: linux.perf_event_attr = .{ .type = .HARDWARE, .config = @intFromEnum(linux.PERF.COUNT.HW.INSTRUCTIONS), .flags = .{ .exclude_kernel = true, .exclude_hv = true } };
+ const rc = linux.perf_event_open(&attr, 0, -1, -1, 0);
+ if (linux.errno(rc) != .SUCCESS) return error.NoInstructionCounter;
+ return .{ .fd = @intCast(rc) };
+ }
+
+ fn read(c: Instructions) u64 {
+ var n: u64 = 0;
+ _ = std.os.linux.read(c.fd, std.mem.asBytes(&n), 8);
+ return n;
+ }
+
+ fn close(c: Instructions) void {
+ _ = std.os.linux.close(c.fd);
+ }
+};
+
fn seek(pane: *pardes.Pane, fx: Fixture, n: usize) void {
const f = &pane.file.?;
const span = @max(1, fx.lines * 8 / 10);
diff --git a/test/process/tty_editing.zig b/test/process/tty_editing.zig
index 63c75512..53e1da1e 100644
--- a/test/process/tty_editing.zig
+++ b/test/process/tty_editing.zig
@@ -27,6 +27,7 @@ pub const cases = .{
.{ "tty editing: lsp", lsp },
.{ "tty editing: lsp-client", lsp_client },
.{ "tty editing: lsp-client-edit", lsp_client_edit },
+ .{ "tty editing: lsp-hangup", lsp_hangup },
.{ "tty editing: lspcomplete", lspcomplete },
.{ "tty editing: lspcompletemoved", lspcompletemoved },
.{ "tty editing: lspdebug", lspdebug },
@@ -1511,6 +1512,60 @@ fn lsp_client(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
try t.done();
}
+// A pardes with no daemon whose terminal hangs up dies by the signal, and
+// no exit hook runs: its language servers' groups go with it all the same.
+// The mock, busy (LSPMOCK_MODE=busy), leaves a child in its group, as zls
+// in a build does, which its socket's end does not stop.
+fn lsp_hangup(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
+ var t = try Tty.init(gpa, exe, "lsp-hangup");
+ defer t.deinit();
+ _ = setenv("LSPMOCK_MODE", "busy", 1);
+ // The server's root, where it says its child's pid.
+ try t.file("Cargo.toml", "");
+ try t.file("main.rs", "fn main() {}\n");
+ try t.start(25, 100, &.{"main.rs"});
+ try t.wait(8000, "fn main()");
+ // A request starts the server (goto-definition).
+ try t.key("g");
+ try t.key("d");
+ var buf: [32]u8 = undefined;
+ const child: std.c.pid_t = for (0..1000) |_| {
+ const fd = std.c.open("lspmock-busy.pid", .{});
+ if (fd >= 0) {
+ const n = std.c.read(fd, &buf, buf.len);
+ _ = std.c.close(fd);
+ if (n > 0) if (std.fmt.parseInt(std.c.pid_t, std.mem.trim(u8, buf[0..@intCast(n)], " \n"), 10)) |pid| break pid else |_| {};
+ }
+ try t.settle(10);
+ } else return error.NoServerChild;
+ // Whatever the test's end, the child it made goes.
+ defer _ = std.c.kill(child, .KILL);
+ t.h.?.deinit(); // the terminal hangs up
+ t.h = null;
+ for (0..500) |_| {
+ if (!alive(child)) return;
+ var none: [0]std.posix.pollfd = .{};
+ _ = std.posix.poll(&none, 10) catch 0;
+ }
+ return error.ServerChildLivesOn;
+}
+
+/// Whether `pid` runs (a zombie waiting for its reaper does not).
+fn alive(pid: std.c.pid_t) bool {
+ var path: [32]u8 = undefined;
+ const p = std.fmt.bufPrintSentinel(&path, "/proc/{d}/stat", .{pid}, 0) catch return false;
+ const fd = std.c.open(p, .{});
+ if (fd < 0) return false;
+ defer _ = std.c.close(fd);
+ var stat: [256]u8 = undefined;
+ const n = std.c.read(fd, &stat, stat.len);
+ if (n <= 0) return false;
+ const close_paren = std.mem.lastIndexOfScalar(u8, stat[0..@intCast(n)], ')') orelse return false;
+ return close_paren + 2 < n and stat[close_paren + 2] != 'Z';
+}
+
+extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int;
+
// The protocol client's MUTATING answers, through the @put record path: a
// server TextEdit response becomes one atomic buffer edit with one undo step.
// = applies the mock's formatting edit (a header line) and narrates
diff --git a/test/replicas.zig b/test/replicas.zig
index e035cd81..e5e719b3 100644
--- a/test/replicas.zig
+++ b/test/replicas.zig
@@ -773,7 +773,7 @@ fn ended(cl: *Client, c: usize, net: *Net, now: u64, totals: *Totals, run_: Run,
const r = cl.r.?;
const link = &cl.loop.link;
// Its link ended by the session (a Detach), it says nothing more.
- if (!link.gone) replica.bye(link.fd, r.diverged != null or link.lagged != 0);
+ if (!link.gone) replica.bye(link.fd, .{ .again = r.diverged != null or link.lagged != 0 });
try drain(cl, c, net, now);
cl.live = 0;
if (link.lagged != 0) {
@@ -1425,7 +1425,7 @@ const Soak = struct {
// A Detach typed in a client's view, or one cut off for its lag: its
// link shut, it hears its end and nothing after; its reader's end
// said (the next boundary lets it go).
- if (s.detach_view) |k| for (s.clients) |*cl| if (cl.peer) |p| if (p.view == k and !cl.shut) {
+ if (s.detach_view) |k| for (s.clients) |*cl| if (cl.peer) |p| if (p.view.index() == k and !cl.shut) {
cl.shut = true;
};
s.detach_view = null;
@@ -1567,7 +1567,6 @@ const Soak = struct {
}
pub fn upgradeAsked(_: *Soak) void {}
- pub fn note(_: *Soak, _: anytype) void {}
pub fn restoring(_: *Soak, _: *pardes.Pardes) void {}
pub fn restored(_: *Soak, _: *SessionLoop) void {}
@@ -2484,7 +2483,7 @@ fn flushAll(sc: *replica.Screens, core: *pardes.Pardes, ps: []const u16, list: *
for (ps, 0..) |peer, c| {
list.clearRetainingCapacity();
// Terminals alone cross: the view is not read.
- try sc.flush(core, peer, 0, list);
+ try sc.flush(core, peer, list);
for (list.items) |bytes| {
tot.deltas += 1;
tot.delta_bytes += bytes.len;
diff --git a/test/session.zig b/test/session.zig
index 1cbee9df..d437ecf2 100644
--- a/test/session.zig
+++ b/test/session.zig
@@ -53,7 +53,7 @@ pub const Session = struct {
/// A session showing one file pane holding `text`, keeping what outlives
/// it in a database in memory (core/Db.zig).
pub fn initFile(gpa: std.mem.Allocator, text: []const u8) !Session {
- const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .memory });
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .memory, .tape = recording });
errdefer p.deinit();
_ = try p.setTestFile(text);
var s: Session = .{ .core = p, .arena = .init(gpa) };
@@ -75,7 +75,7 @@ pub const Session = struct {
/// A session showing one file pane, its startup file `init` (as
/// `~/.config/pardes/init` is read) applied first.
pub fn initStartup(gpa: std.mem.Allocator, init: []const u8) !Session {
- const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .memory, .startup_config = init });
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .memory, .startup_config = init, .tape = recording });
errdefer p.deinit();
_ = try p.setTestFile("x\n");
var s: Session = .{ .core = p, .arena = .init(gpa) };
@@ -85,7 +85,7 @@ pub const Session = struct {
/// A session showing its terminal pane, as `pardes` starts.
pub fn initTerm(gpa: std.mem.Allocator) !Session {
- const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .memory });
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .memory, .tape = recording });
var s: Session = .{ .core = p, .arena = .init(gpa) };
s.drain();
return s;
@@ -99,7 +99,7 @@ pub const Session = struct {
var arena: std.heap.ArenaAllocator = .init(gpa);
errdefer arena.deinit();
const config = try std.fmt.allocPrint(arena.allocator(), "DumpDir {s}\n", .{dir});
- const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .disk, .startup_config = config });
+ const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24, .state = .disk, .startup_config = config, .tape = recording });
var s: Session = .{ .core = p, .arena = arena };
s.drain();
return s;
@@ -206,12 +206,16 @@ pub const Session = struct {
s.drain();
}
+ /// The tape `recordTape` started: every session made after it records on it.
+ var recording: ?*pardes.tape.Tape = null;
+
/// Every session started from here on records what it consumes as a
/// tape in memory, as PARDES_RECORD has a real one record it
/// (core/tape.zig); `replayTape` replays it once the session is gone.
pub fn recordTape(gpa: std.mem.Allocator) !void {
const t = try gpa.create(pardes.tape.Tape);
t.* = pardes.tape.memory(gpa);
+ recording = t;
pardes.tape.on = t;
}
@@ -221,7 +225,8 @@ pub const Session = struct {
/// its end loaded to its digest and dumped to its bytes again. False
/// when a replica diverged (said on stderr). After `deinit`.
pub fn replayTape(gpa: std.mem.Allocator) bool {
- const t = pardes.tape.on orelse return true;
+ const t = recording orelse return true;
+ recording = null;
pardes.tape.on = null;
defer {
pardes.tape.release(t);
diff --git a/test/snapshots/collapse.golden b/test/snapshots/collapse.golden
index 241bc057..3f73e051 100644
--- a/test/snapshots/collapse.golden
+++ b/test/snapshots/collapse.golden
@@ -5,7 +5,7 @@
| 1 KEEP-FIRST
| 2 KEEP-SECOND
| 3 KEEP-THIRD
-== snap middle-collapsed grid=160x25 cursor=7,3
+== snap middle-collapsed grid=160x25 cursor=hidden
|3:
|4:
|5:
@@ -64,7 +64,7 @@
|3: 1 KEEP-FIRST Collapse
|4: 2 KEEP-SECOND
|5: 3 KEEP-THIRD
-== snap tab-collapsed grid=160x25 cursor=51,2
+== snap tab-collapsed grid=160x25 cursor=hidden
|3:
|4:
|5:
diff --git a/test/snapshots/follow.golden b/test/snapshots/follow.golden
index c02ea08f..69749b42 100644
--- a/test/snapshots/follow.golden
+++ b/test/snapshots/follow.golden
@@ -31,7 +31,7 @@
| 27 line 27 52 line 52 77 line 77
== snap hop grid=150x30 cursor=82,5
|3: 1 line 1 Save Term Collapse Follow Del Unfoll Save Term Collapse Follow Del Unfo
-== snap wheel grid=150x30 cursor=82,5
+== snap wheel grid=150x30 cursor=hidden
|3: 2 line 2 Save Term Collapse Follow Del Unfoll Save Term Collapse Follow Del Unfo
|4: 3 line 3 ow llow
|5: 4 line 4 29 line 29 54 line 54
diff --git a/test/snapshots/hscroll.golden b/test/snapshots/hscroll.golden
index 5f930ddf..4799b3b5 100644
--- a/test/snapshots/hscroll.golden
+++ b/test/snapshots/hscroll.golden
@@ -20,7 +20,7 @@
| Mode Filter Collapse Del
| ls
| wide.txt
-== snap wheeled grid=90x31 cursor=7,9
+== snap wheeled grid=90x31 cursor=hidden
|9: 1 ND_A_MARKER_WAY_OUT_RIGHT_padpadpadpad
== snap clamped grid=90x31 cursor=7,9
|9: 1 short1 END_A_MARKER_WAY_OUT_RIGHT_padp
diff --git a/test/snapshots/images.golden b/test/snapshots/images.golden
index 6a06f55b..04797da3 100644
--- a/test/snapshots/images.golden
+++ b/test/snapshots/images.golden
@@ -1,4 +1,4 @@
-== snap img-open grid=150x31 cursor=11,8
+== snap img-open grid=150x31 cursor=hidden
| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config History Debug Exit
| New Term Find Grep Joincol Delcol New Term Find Grep Joincol Delcol
| /tmp/pardes-snap/images/cwd Term+bash Save Mode Filter Collapse Del /tmp/pardes-snap/images/cwd Term+bash Save Mode Filter Collapse Del
@@ -63,7 +63,7 @@
|14: 0-0 d,#152019, 1-29 d,#0d1410, 30-32 p8,p4, 33-33 p4,p8, 34-34 p8,p12, 35-35 p12,p8, 36-45 p12,p12, 46-74 p12,#0d1410, 75-75 p12,#608269, 76-149 p12,#0d1410,
|15: 0-0 d,#152019, 1-29 d,#0d1410, 30-30 p4,p8, 31-31 p8,p4, 32-32 p8,p12, 33-33 p12,p8, 34-45 p12,p12, 46-74 p12,#0d1410, 75-75 p12,#608269, 76-149 p12,#0d1410,
|16: 0-0 d,#152019, 1-29 d,#0d1410, 30-30 p8,p12, 31-31 p12,p8, 32-45 p12,p12, 46-74 p12,#0d1410, 75-75 p12,#608269, 76-149 p12,#0d1410,
-== snap no-ascii grid=150x31 cursor=11,8
+== snap no-ascii grid=150x31 cursor=hidden
|6: img petscii:on palette:terminal ascii:off /tmp/pardes-snap/images/cwd/pic
|8: Ascii
|9: ██████████████🬝🬹
diff --git a/test/snapshots/jumps.golden b/test/snapshots/jumps.golden
index 6cb8a45f..34712e6e 100644
--- a/test/snapshots/jumps.golden
+++ b/test/snapshots/jumps.golden
@@ -130,7 +130,7 @@
|3: 86 line 86 Last ls
== snap last-back grid=150x31 cursor=7,17
|3: 86 line 86 ls Last
-== snap jumplist grid=150x31 cursor=7,17
+== snap jumplist grid=150x31 cursor=hidden
|3: 86 line 86 Jumplist ls
|16: /tmp/pardes-snap/jumps/cwd/+Jumps Save Term Collapse Follow LocationsConf
|17: ig Del
diff --git a/test/snapshots/lspcomplete.golden b/test/snapshots/lspcomplete.golden
index 48dac907..72b413cf 100644
--- a/test/snapshots/lspcomplete.golden
+++ b/test/snapshots/lspcomplete.golden
@@ -54,7 +54,7 @@
| 1 c.zig:7:23 verdigris Shade
| 2 c.zig:7:23 cinnabar Shade
| ~
-== snap nobrace grid=100x19 cursor=16,10
+== snap nobrace grid=100x19 cursor=hidden
| Newcol Joincol Find Grep Help Changelog Tutor Dump Themes Config History Debug Exit
| New Term Find Grep Joincol Delcol
|^*/tmp/pardes-snap/lspcomplete/cwd/d.zig Save Term Collapse Follow TreeContext Def Refs Del
diff --git a/test/snapshots/shrinktag.golden b/test/snapshots/shrinktag.golden
index bfca20e3..c8ef1a13 100644
--- a/test/snapshots/shrinktag.golden
+++ b/test/snapshots/shrinktag.golden
@@ -20,7 +20,7 @@
| de Filter Collapse Del
| ls
| w.txt
-== snap shrunk grid=100x31 cursor=4,9
+== snap shrunk grid=100x31 cursor=hidden
|4: w.txt ls
|5: w.txt
|6: /tmp/pardes-snap/shrinktag/cwd Term+bash Save Mo
@@ -31,7 +31,7 @@
|18:
|19:
|20:
-== snap move-preview grid=100x31 cursor=4,9
+== snap move-preview grid=100x31 cursor=hidden
== snap restored grid=100x31 cursor=4,9
|4: ls ls
|5: w.txt w.txt
diff --git a/test/snapshots/ttytaken.golden b/test/snapshots/ttytaken.golden
index 765dc734..ee72ccc2 100644
--- a/test/snapshots/ttytaken.golden
+++ b/test/snapshots/ttytaken.golden
@@ -38,7 +38,7 @@
|28: line 26
|29: line 27
|30: big.txt
-== snap spawned grid=210x31 cursor=109,2
+== snap spawned grid=210x31 cursor=hidden
|2: /tmp/pardes-snap/ttytaken/cwd Term+bash Save Mode Filter Collapse Del @`echo TAKEN''ONE` @`echo TAKEN''TWO`
|3: line 1 Exec
|16: :
diff --git a/test/snapshots/wheeldrift.golden b/test/snapshots/wheeldrift.golden
index 2474411c..393a57e1 100644
--- a/test/snapshots/wheeldrift.golden
+++ b/test/snapshots/wheeldrift.golden
@@ -16,7 +16,7 @@
| 11 line 11_0123456789_abcdefghij_ZEND
| 12 line 12_0123456789_abcdefghij_ZEND
| 13 line 13_0123456789_abcdefghij_ZEND
-== snap drifted grid=70x17 cursor=7,4
+== snap drifted grid=70x17 cursor=hidden
|4: 6 line 6_0123456789_abcdefghij_ZEND
|5: 7 line 7_0123456789_abcdefghij_ZEND
|6: 8 line 8_0123456789_abcdefghij_ZEND
@@ -30,8 +30,8 @@
|14: 16 line 16_0123456789_abcdefghij_ZEND
|15: 17 line 17_0123456789_abcdefghij_ZEND
|16: 18 line 18_0123456789_abcdefghij_ZEND
-== snap paying grid=70x17 cursor=7,4
-== snap moved grid=70x17 cursor=7,4
+== snap paying grid=70x17 cursor=hidden
+== snap moved grid=70x17 cursor=hidden
|4: 6 123456789_abcdefghij_ZEND
|5: 7 123456789_abcdefghij_ZEND
|6: 8 123456789_abcdefghij_ZEND
@@ -45,7 +45,7 @@
|14: 16 0123456789_abcdefghij_ZEND
|15: 17 0123456789_abcdefghij_ZEND
|16: 18 0123456789_abcdefghij_ZEND
-== snap rearmed grid=70x17 cursor=7,4
+== snap rearmed grid=70x17 cursor=hidden
|4: 5 123456789_abcdefghij_ZEND
|5: 6 123456789_abcdefghij_ZEND
|6: 7 123456789_abcdefghij_ZEND
diff --git a/test/snapshots/wrap.golden b/test/snapshots/wrap.golden
index 431664ee..ba115b3f 100644
--- a/test/snapshots/wrap.golden
+++ b/test/snapshots/wrap.golden
@@ -17,7 +17,7 @@
== snap visual-gj-again grid=48x15 cursor=10,6
== snap visual-gk grid=48x15 cursor=10,5
== snap visual-count-gj grid=48x15 cursor=10,7
-== snap off grid=48x15 cursor=10,7
+== snap off grid=48x15 cursor=hidden
|4: 1 0---------1---------2---------3---- Wrap
|5: 2 second line
|6: 3 third line
diff --git a/test/tty.zig b/test/tty.zig
index a6e37c6c..f26328ca 100644
--- a/test/tty.zig
+++ b/test/tty.zig
@@ -263,11 +263,28 @@ pub const Tty = struct {
}
/// Keys by name, space-separated: enter esc tab bs space up down left
- /// right home end pgup pgdn, a character, c-<ch> and a-<ch>. After esc,
- /// settle: vaxis reads the next byte in the same batch as alt-<ch>.
+ /// right home end pgup pgdn, a character, c-<ch> and a-<ch>. An esc is
+ /// read alone: sent once the app has read what came before it, and
+ /// read before anything after it is sent (a read that ends in ESC waits
+ /// for more, and `ESC h` is alt-h).
pub fn key(t: *Tty, names: []const u8) !void {
var it = std.mem.tokenizeScalar(u8, names, ' ');
- while (it.next()) |name| try t.live().send(keyBytes(name) orelse return error.BadKey);
+ while (it.next()) |name| {
+ const esc = std.mem.eql(u8, name, "esc");
+ if (esc) try t.allRead();
+ try t.live().send(keyBytes(name) orelse return error.BadKey);
+ if (esc) try t.allRead();
+ }
+ }
+
+ /// Pump until the app has read every byte typed (10 s at most).
+ fn allRead(t: *Tty) !void {
+ const h = t.live();
+ const until = eh.nowMs() + 10_000;
+ while (h.unread() > 0) {
+ if (eh.nowMs() > until) return error.InputNeverRead;
+ _ = try h.pumpOnce(2);
+ }
}
/// An SGR mouse press, release or drag (motion with it held) of
@@ -567,7 +584,7 @@ fn stateKey(h: *eh.Harness) ![]u8 {
styles.update("\x00");
}
}
- return std.fmt.allocPrint(h.gpa, "{d},{d},{x}\n{s}", .{ c.x, c.y, styles.final(), text });
+ return std.fmt.allocPrint(h.gpa, "{d},{d},{},{x}\n{s}", .{ c.x, c.y, c.shown, styles.final(), text });
}
/// A mouse column: either a screen column, or `@Word` / `@Word#2` - the column
@@ -797,7 +814,8 @@ fn snap9pText(arena: std.mem.Allocator, h: *eh.Harness, label: []const u8, prev:
return out.items;
}
-/// `== snap <label> grid=CxR cursor=X,Y` then either the whole screen as
+/// `== snap <label> grid=CxR cursor=X,Y` (`cursor=hidden` when the app
+/// hides it: where a hidden cursor was left is no one's) then either the whole screen as
/// `|<row text>` (first capture of a case, or after a resize) or just the
/// rows that changed as `|<n>: <row text>`. An indexed row is a patch against
/// the previous capture; an unindexed one is a frame.
@@ -810,9 +828,8 @@ fn snapText(arena: std.mem.Allocator, h: *eh.Harness, label: []const u8, prev: *
for (rows) |*r| r.* = try arena.dupe(u8, std.mem.trimEnd(u8, it.next() orelse "", " "));
var out: std.ArrayList(u8) = .empty;
- try out.appendSlice(arena, try std.fmt.allocPrint(arena, "== snap {s} grid={d}x{d} cursor={d},{d}\n", .{
- label, h.cols, h.rows, c.x, c.y,
- }));
+ try out.appendSlice(arena, try std.fmt.allocPrint(arena, "== snap {s} grid={d}x{d} cursor=", .{ label, h.cols, h.rows }));
+ try out.appendSlice(arena, if (c.shown) try std.fmt.allocPrint(arena, "{d},{d}\n", .{ c.x, c.y }) else "hidden\n");
if (prev.snap.len == rows.len and prev.snap_cols == h.cols) {
for (rows, prev.snap, 0..) |now, was, i| {
if (std.mem.eql(u8, now, was)) continue;