From 0ad6da7f9bf22136694e6015c93ccaf81dc12380 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 21 Nov 2026 09:16:07 -0300 Subject: replica: a view kept for a client's rejoin is let go after its 30 s in a session nobody types in, and a join refused meanwhile is told for how long: a wake by mail alone (a join, a client's input) moves no time (tui.zig `clockNow`), so in an idle session with a client in it the core's clock stood where it last moved and Core.openView judged the kept views by it forever (test/daemon.py `kept_views`, new, in plain mode: at the four views, two raw replicas leave saying they join again, and a join 31 s later, nothing typed, was refused on pardes-merge50); Peers.join now moves the clock (`advance` with the host's `now`, on the tape) when no view is free, before the views are judged, and its refusal says "(one is kept N s more for a client joining again)" while one is kept; test/daemon.py `upgrades`, from a build that keeps views with their time (`keeps_views`: `away_ns` in its binary), waits as long as the first join's refusal says, saying so, for the two views kept for clients that never return (the raw replica and the old build's client, refused by the daemon for its build); kept_views passes; `--upgrade` between this tree's Debug and ReleaseSafe builds 3 of 3 each way (each says "the join waited 30 s"), from the installed build 3 of 3 (it keeps no time: its views load already expired); the soak (--clients 5) diverged 0, unequal 0; core-test 893/1053 (160 skipped), shell-test 1095/1098 Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/replica.zig | 13 +++++++++- test/daemon.py | 76 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+), 1 deletion(-) diff --git a/core/replica.zig b/core/replica.zig index 97da9c74..3c7a5cbc 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -2346,10 +2346,21 @@ pub const Peers = struct { ps.recording = true; ps.samples = std.c.getenv("PARDES_REPLICA_STATS") != null; } + // A join with no room lets go a view kept past its bound by the + // core's clock (Core.openView), which a wake by mail alone, as this + // join's, does not move (tui.zig `clockNow`): moved now, on the tape. + if (@popCount(core.views_open) == pardes.views.max) if (core.host.call(.now, .{})) |now| core.advance(now); const k = viewFor(core, joining.view) orelse { core.unattended = ps.count() == 0 and ps.detached; if (ps.count() == 0) ps.stop(core); - return daemon.refuseReplica(fd, "that session has as many views as it takes"); + const full = "that session has as many views as it takes"; + var left: u64 = 0; + for (0..pardes.views.max) |i| if (pardes.views.isAway(core, @intCast(i))) { + const n = (core.views[i].?.away_ns + pardes.views.away_kept_ns) -| core.clock.now_ns; + left = if (left == 0) n else @min(left, n); + }; + var why: [128]u8 = undefined; + return daemon.refuseReplica(fd, if (left == 0) full else std.fmt.bufPrint(&why, full ++ " (one is kept {d} s more for a client joining again)", .{(left + std.time.ns_per_s - 1) / std.time.ns_per_s}) catch full); }; ps.seq += 1; ps.unit(0, ps.seq); diff --git a/test/daemon.py b/test/daemon.py index 5c075520..1be89d5b 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -978,6 +978,65 @@ def attach_upgrading(binary, rounds=6, dump=True): shutil.rmtree(root, ignore_errors=True) +def kept_views(binary): + """A view kept for its client's rejoin (views.away: a bye that says it + joins again, a client cut off behind, every client at an Upgrade) is + that client's for 30 s, then a join with no room takes it, in a session + nobody types in: a `new --detach` session at its four views (a client + attached, idle; raw replicas), two of them leaving to join again and + never coming back; a join at once is refused and told for how long, one + 31 s later, nothing typed in between, is welcomed.""" + scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' + scratch.mkdir(parents=True, exist_ok=True) + root = Path(tempfile.mkdtemp(prefix='rk-', 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') + t = Term(30, 100) + rs = [] + try: + out = subprocess.run([binary, 'new', '--detach=kv'], env=env, cwd=root, capture_output=True, timeout=30, stdin=subprocess.DEVNULL) + assert out.returncode == 0, out + a = t.spawn([binary, 'attach', 'kv'], env) + wait_for('the client drawn', lambda: b'\x1b[?1049h' in t.text(), timeout=30) + sock, build = root / 'pardes-replica.sock', semantics(binary) + while True: + r = Replica(sock) + said = r.hello('kv', build) + if said[0] != 'welcome': + break + rs.append(r) + assert said[0] == 'refused' and 'as many views' in said[1] and len(rs) >= 2, (said, len(rs)) + for r in rs[:2]: + r.send(0x02, b'\x01') + r.close() + left = time.monotonic() + said = Replica(sock).hello('kv', build) + assert said[0] == 'refused' and re.search(r'as many views as it takes \(one is kept (\d+) s more for a client joining again\)', said[1]), said + print(f'kept views: {len(rs)} replicas and a client at the cap; two left to join again; a join at once refused: "{said[1]}"') + time.sleep(max(0, left + 31 - time.monotonic())) + said = Replica(sock).hello('kv', build) + assert said[0] == 'welcome', ('a view kept 31 s in an idle session, still kept', said) + assert a.poll() is None + print('kept views: a join 31 s after, nothing typed in between, took a kept view') + a.terminate() + a.wait(timeout=20) + assert subprocess.run([binary, 'kill', 'kv'], env=env, capture_output=True, timeout=30).returncode == 0 + wait_for('nothing left', lambda: not [p for p in processes(root) if alive(p)], timeout=20) + finally: + for r in rs: + r.close() + for p in processes(root): + try: + os.kill(p, signal.SIGKILL) + except OSError: + pass + t.close() + shutil.rmtree(root, ignore_errors=True) + + def pair_upgrade_views(binary): """PARDES_PAIR, two clients each in its own view (the pair's own terminal and an attach), each with its own scroll and focus: the pair's scrolled @@ -2566,6 +2625,7 @@ def main(binary, cycles): pair(binary) pair_rows(binary) attach_upgrading(binary) + kept_views(binary) pair_upgrade_views(binary) manage(binary) relink(binary) @@ -3159,6 +3219,16 @@ def upgrades(old, new): 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)) + # Two clients' views kept at the Upgrade, with the time (views.away), + # whose clients never come back (the raw replica, the old build's): + # each its client's for 30 s, and the session's views all taken. + # The first join waits as long as its refusal says. + if keeps_views(old): + said = Replica(root / 'pardes-replica.sock').hello('work', new_build) + kept = re.search(r'one is kept (\d+) s more', said[1]) if said[0] == 'refused' else None + if kept: + time.sleep(int(kept.group(1)) + .5) + print(f'upgrade: two views kept for clients that never came back; the join waited {kept.group(1)} s for one, as its refusal said') # The daemon lists the session under its new build. said = Replica(root / 'pardes-replica.sock').hello('work', new_build) assert said == ('welcome', session, 'work'), said @@ -3298,6 +3368,12 @@ def knows_size(gui_binary): return b'PARDES_JOIN_SIZE' in Path(gui_binary).read_bytes() +def keeps_views(binary): + """Whether a build keeps its clients' views at an Upgrade with the time + each was kept (View.away_ns), so that the build after holds them.""" + return b'away_ns' in Path(binary).read_bytes() + + 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).""" -- cgit v1.3 From 59ba1a8b24aab95cfec9046e042f3a34d5821e47 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 21 Nov 2026 09:35:20 -0300 Subject: test/daemon.py: an adopted shell's `echo $$` is asked once the shell answers (`adopted_pid`, the wait plain mode's own Adopt had): on a ReleaseSafe build of pardes-merge50 `--relink` failed 3 of 10 (`relink` twice, `answer_late` once), each run answered `error not run`, not another pid: the adoption sizes the shell twice (dev/Ptys.zig `take`), it draws its prompt again, and a run sent into a prompt redrawn under it reads as not run (core/ninep/pty.zig `noteMarks`, its ponytail), which a faster build reaches more often; the same wait in `relink`, `answer_late`, `upgrades`' last Adopt and plain mode's; no product change: no output in another pane, a script's run told plainly that it did not run; after: `--relink` on this line's ReleaseSafe build 10 of 10 (loads 1.3-7.0) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- test/daemon.py | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/test/daemon.py b/test/daemon.py index 1be89d5b..fc03e3cb 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -143,6 +143,16 @@ def run(client, serial, line): client.close(fid) +def adopted_pid(client, pane): + """An adopted shell's `echo $$`, once it answers: sized twice at its + adoption (dev/Ptys.zig `take`), it draws its prompt again, and a run + sent into a prompt redrawn under it reads as not run (core/ninep/pty.zig + `noteMarks`).""" + wait_for('the adopted shell answers', lambda: run(client, pane, b'true\n') == b'exit 0\n') + said = run(client, pane, b'echo $$\n') + return said.split(b'\n')[1], said + + # FreeBSD has no /proc: ps and procstat answer instead. procfs = os.path.isdir('/proc/self') @@ -1528,7 +1538,8 @@ def relink(binary): before = set(terminals(own)) own.write(f'/pane/{min(before)}/exec', b'Adopt\n') pane = wait_for('the adopted pane', lambda: set(terminals(own)) - before).pop() - assert run(own, pane, b'echo $$\n').split(b'\n')[1] == str(shell_pid).encode() + pid, said = adopted_pid(own, pane) + assert pid == str(shell_pid).encode(), (said, shell_pid) print(f'relink: a client attached to the session through the new daemon; killed outright, its shell {shell_pid} was adopted') exit_session(own, pane) stub.wait(timeout=10) @@ -1602,7 +1613,8 @@ def answer_late(binary): 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() + pid, said = adopted_pid(two, pane) + assert pid == str(shell_pid).encode(), (said, shell_pid) 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) @@ -2772,11 +2784,8 @@ def main(binary, cycles): client.write(f'/pane/{min(before)}/exec', b'Adopt\n') adopted = wait_for('the adopted pane', lambda: set(terminals(client)) - before) pane = adopted.pop() - # Sized twice (Ptys.take): a run into a prompt redrawn under it - # reads as not run (core/ninep/pty.zig). - wait_for('the adopted shell answers', lambda: run(client, pane, b'true\n') == b'exit 0\n') - said = run(client, pane, b'echo $$\n') - assert said.split(b'\n')[1] == str(shell_pid).encode(), said + pid, said = adopted_pid(client, pane) + assert pid == str(shell_pid).encode(), said print(f'daemon: shell {shell_pid} outlived kill -9 of its session and was adopted') # Attached again: a client. (After the runs: a pty/run under a # client puts it off the session's state, and it joins again; one @@ -3342,7 +3351,8 @@ def upgrades(old, new): before = set(terminals(client)) client.write(f'/pane/{min(before)}/exec', b'Adopt\n') pane = wait_for('the adopted pane', lambda: set(terminals(client)) - before).pop() - assert run(client, pane, b'echo $$\n').split(b'\n')[1] == str(shell_pid).encode() + pid, said = adopted_pid(client, pane) + assert pid == str(shell_pid).encode(), (said, shell_pid) print(f'upgrade: the upgraded daemon kept shell {shell_pid} through kill -9 of its session, and it was adopted') client.write(f'/pane/{pane}/exec', b'Exit\n') stub.wait(timeout=10) -- cgit v1.3 From 5a74a03fece68f6cd53ab2c8fccbd7deea345acb Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 21 Nov 2026 10:53:08 -0300 Subject: test/daemon.py: `--upgrade`'s rows say what they need of the old build instead of failing one run in a few: `far_exec` runs only where OLD's far client dials again when an Upgrade cuts its link with no last word (`redials_far`: PARDES_JOIN_SIZE in OLD's binary, the string of the change that brought that redial, pardes-pair-5's; the redial has no string of its own) and is skipped with a line from the installed build, whose far client took the cut for its session's end one run in five; `pair_exec_reaps` takes its mark before the Upgrade and waits for the blink (its screen left and entered again, the notes drawn after), as `far_exec` does: the mark taken after the client was seen on the new build missed a frame it had drawn by then (from the installed build 2 of 5 runs failed "drawn again" on pardes-merge50's release build and 2 of 5 on this line's, the same before the fix); after: far_exec 5 of 5 between this tree's Debug and ReleaseSafe builds, pair_exec_reaps from the installed build 6 of 6, `--upgrade` from it 3 of 3 Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- test/daemon.py | 20 +++++++++++++++++--- 1 file changed, 17 insertions(+), 3 deletions(-) diff --git a/test/daemon.py b/test/daemon.py index fc03e3cb..f4836a43 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -1186,14 +1186,17 @@ def pair_exec_reaps(old, new): wait_for('drawn', lambda: b'line 3 of the notes' in t.text(), timeout=30) install(new, binary) ino = sock.stat().st_ino + # Before the Upgrade: the exec'd client can draw before its exec is seen. + mark = len(t.text()) nine.write('/ctl', b'Upgrade\n') nine.socket.close() wait_for('the session exec\'d', lambda: sock.stat().st_ino != ino, timeout=60) wait_for('the client on the new build', lambda: exe_of(c.pid) == (str(binary), True), timeout=30) nine = reconnect(sock) assert ppid(session) == c.pid - mark = len(t.text()) - wait_for('drawn again', lambda: b'line 3 of the notes' in t.text()[mark:], timeout=30) + # The blink: its screen left and entered again, the notes drawn there. + wait_for('drawn again', lambda: (lambda x: x.rfind(b'\x1b[?1049h') > x.rfind(b'\x1b[?1049l') > mark + and b'line 3 of the notes' in x[x.rfind(b'\x1b[?1049h'):])(t.text()), timeout=30) nine.write('/ctl', b'Exit\n') nine.socket.close() assert c.wait(timeout=30) == 0, c.returncode @@ -3384,6 +3387,14 @@ def keeps_views(binary): return b'away_ns' in Path(binary).read_bytes() +def redials_far(binary): + """Whether a build's far client whose link an Upgrade cuts with no last + word dials again (core/replica.zig `cutListed`'s `far`) rather than take + it for its session's end: the change that made it gave the window its + size at its exec too (PARDES_JOIN_SIZE), the string that says so.""" + return b'PARDES_JOIN_SIZE' in Path(binary).read_bytes() + + 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).""" @@ -3609,7 +3620,10 @@ if __name__ == '__main__': upgrades(old, new) if knows_exec(old): pair_exec_reaps(old, new) - far_exec(old, new) + if redials_far(old): + far_exec(old, new) + else: + print('far exec: skipped: the old build\'s far client, cut at the Upgrade with no last word, takes it for its session\'s end (no PARDES_JOIN_SIZE)') # With a pardes-gui beside each: the clients carried too. if all(a.with_name('pardes-gui').exists() for a in (old, new)): upgrade_clients(old, new) -- cgit v1.3 From dfb051bd798f65c2217eea7f95b03dce292e30bf Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 21 Nov 2026 09:46:32 -0300 Subject: layers: `Changes [revset]` pins a revset's changes on a file's pane in this view (bare `@`, bare again off, another replaces; refusals in jj's words) and draws them: what jj says is asked in two recorded answers (Site.jj), `jj log -p --git --context=0` restricted to the file (the pins: id, author, time, the description's first line, and each one's diff, read with diff.zig's walk into hunks and the removed lines' text) and `jj file annotate` at the shown revision (which pin wrote each line), kept as flat arrays in the pane (Pane.changes: replicated, a late joiner has them in the dump, a client never runs jj) and worn by the view whose revset is File.Layers.revset; a pin's lane runs unbroken from a line it wrote to the next while every line between is a newer pin's, so lanes nest, the spine keeping its place and a nested change a level to the right on its rows only, three levels in a gutter the lanes widen (a window two cells, strips of a third of a cell with half that of air: Surface.lanes, drawn by the gui; a terminal three, a `▎` a level), coloured by the theme's accents but its green and red in hue order from the top, one within 15 degrees of the last kept skipped (doom one: magenta, blue, yellow), oldest first; a line a pin added whole (in a run it took away and wrote, past as many as it took away) is green across the line as a diff's added line; with Changes off nothing is drawn and the gutter is as it was; tests: the data through the pane (pins, lines, hunks, removed text, unpin, `@` touching nothing, a refusal), a client replaying it ends equal, the lanes and grounds of a three-deep stack in a terminal's cells and a window's strips; core-test 895/1055 (160 skipped), shell-test 1097/1100 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/Core.zig | 1 + core/File.zig | 51 +++- core/body_layer.zig | 1 + core/builtins.zig | 6 + core/config.zig | 1 + core/draw.zig | 1 + core/jj.zig | 603 ++++++++++++++++++++++++++++++++++++++++----- core/panes.zig | 8 + core/replica.zig | 1 + core/root.zig | 1 + core/surface.zig | 10 + dev/gui/gui.zig | 10 + docs/typ/builtins-gui.json | 1 + docs/typ/builtins-tui.json | 1 + docs/typ/guide.typ | 8 + 15 files changed, 633 insertions(+), 71 deletions(-) diff --git a/core/Core.zig b/core/Core.zig index d2cfadfc..385c3e74 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -876,6 +876,7 @@ pub fn deinit(p: *Pardes) void { for (&p.surface.body_layers) |*layer| gpa.free(layer.cells); for (&p.surface.tag_layers) |*layer| gpa.free(layer.cells); p.surface.placements.deinit(gpa); + p.surface.lanes.deinit(gpa); gpa.destroy(p); } diff --git a/core/File.zig b/core/File.zig index 450e4ec9..f7d6bced 100644 --- a/core/File.zig +++ b/core/File.zig @@ -372,7 +372,13 @@ pub fn gutterWidth(pane: *const Pane) u16 { var lines = if (file.line_starts.len > 0) file.line_starts.len else lineCount(file.content); var digits: u16 = 1; while (lines >= 10) : (lines /= 10) digits += 1; - return @max(config.PREFIX_W, digits + 1); + return @max(config.PREFIX_W, digits + 1) + laneCells(pane); +} + +/// The cells the changes' lanes take after the line number in this view +/// (File.Layers), none while it pins no changes. +pub fn laneCells(pane: *const Pane) u16 { + return pane.layers.lanes; } /// Convert between rendered cells and UTF-8 byte columns. Tag rows always @@ -1756,7 +1762,7 @@ fn geometryKey(pane: *const Pane, f: *const State) u64 { if (f.output) |o| pardes.walk.digest(Output.Origin, &o.from) else 0, std.hash.Wyhash.hash(0, f.path), f.tree_context, f.context.revision orelse 0, f.context.declarations.len, f.line_starts.len, t.revision orelse 0, t.list.items.len, pane.view.wrap, pane.view.layered, pane.view.body_h, pane.view.tagline_h, - pane.view.rect_h, + pane.view.rect_h, laneCells(pane), }; // One hash of them laid out as words: every reader of the map asks for // this key, a hundred times a frame. @@ -1813,7 +1819,8 @@ fn fillBody(tab: u16, dst: ?[]u8, pane: *Pane, f: *State, width: usize, record_w @memset(prefix, ' '); if (at == 0 and prefix.len > 0) { var lineno = row + 1; - var digit: usize = prefix.len - 1; + // The number, a blank, then the lanes (laneCells). + var digit: usize = prefix.len - 1 - laneCells(pane); if (row == end_slot) { prefix[digit - 1] = '~'; } else while (true) { @@ -1868,13 +1875,41 @@ fn fillBody(tab: u16, dst: ?[]u8, pane: *Pane, f: *State, width: usize, record_w /// made without the language's ink: highlightDiffPlain). /// /// Both are painted in recolorSyntax's one walk over the cells, each where -/// it says (one walk per painter cost a frame a sixth more). Ruled, not -/// built (PARDES.md "Changes on the source view"): 3. changes: a lane after -/// the line number, a line added whole green across it, a changed line's -/// words tinted, ghost rows for what the shown revision has not; 4. churn: -/// a heat lane after the number and a strip by the scroll thumb. +/// it says (one walk per painter cost a frame a sixth more). +/// +/// 3. changes (`Changes [revset]`, jj.zig): while `revset` is set, a +/// lane a pinned change after the line number (the gutter `lanes` +/// cells wider), a line one added whole green across it (jj.paint). +/// Ruled, not built (PARDES.md "Changes on the source view"): a +/// changed line's words tinted, ghost rows for what the shown +/// revision has not. +/// 4. churn, ruled, not built: a heat lane after the number and a strip +/// by the scroll thumb. pub const Layers = struct { + pub const replica = .{ .len = .{.{ "revset", "revset_len" }} }; ink: bool = true, + /// The changes this view pins (jj's revset), none while empty; what jj + /// answered for them is the pane's (`Pane.changes`). + revset: [revset_max]u8 = undefined, + revset_len: u8 = 0, + /// The cells its lanes take while it pins any, 0 while it pins none + /// (laneCells): set as it pins them, from the view's frontend: in a + /// window two, which its strips of pixels fill one and a half of + /// (Surface.Lane); in a terminal three, a glyph each. + lanes: u8 = 0, + + pub const revset_max = 64; + + pub fn pinned(l: *const Layers) []const u8 { + return l.revset[0..l.revset_len]; + } + + /// One word while it pins nothing: a digest walks every view's layers + /// of every pane (field by field it cost a step 0.1 to 0.7% more). + pub fn digest(l: *const Layers, h: *pardes.walk.Hasher) void { + h.update(&.{ @intFromBool(l.ink), l.revset_len, l.lanes }); + if (l.revset_len > 0) h.update(l.pinned()); + } }; pub const SynStyle = struct { fg: [3]u8, bold: bool }; diff --git a/core/body_layer.zig b/core/body_layer.zig index 1582136c..8d54760f 100644 --- a/core/body_layer.zig +++ b/core/body_layer.zig @@ -338,6 +338,7 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane // File layout is independent of whether its producer requests colors. if (pane.file) |*f| { drawGutter(p, s, pane, r, tx, tw, body_h, active); + if (pane.layers.revset_len > 0) @import("jj.zig").paint(p, s, pane, r, tx, tw, body_h); panes.Query.paintMark(p, s, pane, r, body_h); if (pane.colorAlgo() != .none) panes.File.recolorSyntax(p, s, pane, f, r, tx, tw, body_h); diff --git a/core/builtins.zig b/core/builtins.zig index 18b49a41..e059916a 100644 --- a/core/builtins.zig +++ b/core/builtins.zig @@ -1080,6 +1080,12 @@ pub const At = struct { pub const run = @import("jj.zig").word; }; +/// Pin the changes `revset` names (jj; bare, `@`) on a file's pane in this view: a lane each after the line number, a line one added whole green; bare again, unpinned. +pub const Changes = struct { + pub const takes_arg = true; + pub const run = @import("jj.zig").changesWord; +}; + /// Stack a diff's hunks as a diff viewer shows them, each under its place and the declarations around it, in a +Diff; on a +Diff, show the diff itself as text. `Diff ` stacks that diff's, `Diff ` git show's. /// The diff viewer's one registration: its word and traits here, all else /// its own (hunks.zig). diff --git a/core/config.zig b/core/config.zig index 361a59ed..6338c5d1 100644 --- a/core/config.zig +++ b/core/config.zig @@ -77,6 +77,7 @@ pub const leader_path = paths: { .Filter = null, .Diff = null, .At = null, + .Changes = null, .Mode = null, .Togglettymode = null, .Collapse = null, diff --git a/core/draw.zig b/core/draw.zig index b87eb56f..ed317650 100644 --- a/core/draw.zig +++ b/core/draw.zig @@ -85,6 +85,7 @@ pub fn place(p: *Pardes, s: *Surface) void { const v = p.view(); s.nregions = 0; s.nrail_ticks = 0; + s.lanes.clearRetainingCapacity(); // The facts filled in the walk the frame's places take anyway. viewFacts(p, &p.facts); s.facts = &p.facts; diff --git a/core/jj.zig b/core/jj.zig index 7784c1c1..ebd2ea27 100644 --- a/core/jj.zig +++ b/core/jj.zig @@ -16,6 +16,7 @@ const File = pardes.panes.File; const Output = pardes.panes.Output; const look = @import("look.zig"); const layout = @import("layout.zig"); +const diff = @import("diff.zig"); /// What jj answered: why not, in its own words (its first line, without /// `Error: `), or the file's bytes. The caller's, in the allocator the site @@ -195,8 +196,216 @@ pub fn looked(p: *Pardes, id: usize, dir: []const u8, text: []const u8, at: look return true; } -// ---- what `Changes` reads (PARDES.md: pinned changes as lanes), the -// data alone: flat arrays, no drawing yet ---- +// ---- `Changes [revset]` (PARDES.md: pinned changes as lanes): what jj +// answers for it, kept as flat arrays in the pane ---- + +/// What jj answered for a pane's `Changes`: the pane's replicated state (a +/// client never runs jj; one that joins late has it in the dump), drawn by +/// a view that pins the same revset (File.Layers). Two jj runs, each a +/// site of the step's tape: the changes with their diffs of the file +/// (`jj log -p --git`, the diffs read with diff.zig's walk), and who wrote +/// each line of the shown revision (`jj file annotate`). +pub const Changes = struct { + pub const replica = .{ .len = .{.{ "revset", "revset_len" }} }; + revset: [File.Layers.revset_max]u8 = undefined, + revset_len: u8 = 0, + /// The revset's changes that touch the file, oldest first. + pins: []Pin = &.{}, + /// A value a line of the shown revision. + lines: []Line = &.{}, + /// Each pin's hunks in the file, a pin's together, each in place order. + hunks: []Hunk = &.{}, + /// The lines the hunks took away, hunk after hunk, each with its `\n`. + removed: []u8 = &.{}, + + pub fn deinit(c: *Changes, gpa: std.mem.Allocator) void { + gpa.free(c.pins); + gpa.free(c.lines); + gpa.free(c.hunks); + gpa.free(c.removed); + c.* = .{}; + } + + pub fn pinned(c: *const Changes) []const u8 { + return c.revset[0..c.revset_len]; + } +}; + +/// A pinned change, as `jj log` says it. +pub const Pin = struct { + pub const replica = .{ .len = .{ .{ "author", "author_len" }, .{ "title", "title_len" } } }; + id: [8]u8, + /// Its author's time, in seconds since the epoch. + time: i64, + author: [32]u8 = undefined, + author_len: u8 = 0, + /// Its description's first line, cut to fit. + title: [96]u8 = undefined, + title_len: u8 = 0, +}; + +/// A line of the shown revision: which pin wrote it (its place in +/// `Changes.pins`) or none, and whether that pin added it whole (no line +/// it took away stood in its place) or changed one. +pub const Line = struct { + pin: PinIndex, + whole: bool = false, + /// The pins whose lanes run down it, outermost (oldest) first (`nest`). + lanes: [levels]PinIndex = @splat(.none), +}; + +/// The lanes a row shows at most: the ruled gutter fits three. +pub const levels = 3; + +pub const PinIndex = enum(u16) { + none = std.math.maxInt(u16), + _, +}; + +/// The changes a `Changes` takes at most. +pub const pins_max = 64; + +/// A run of lines a pin took away and wrote in their place, in its own +/// revisions' numbers (from 1; `old_len` 0: it only wrote, after old line +/// `old_start`). +pub const Hunk = struct { + pin: u16, + old_start: u32, + old_len: u32, + new_start: u32, + new_len: u32, + /// Its removed lines' text: `Changes.removed[removed..][0..removed_len]`. + removed: u32, + removed_len: u32, +}; + +/// The `Changes` word (builtins.zig registers it): in a file's pane (or a +/// revision's), the changes `revset` names (bare: `@`, the change against +/// its parent) pinned in this view; bare again, unpinned; another revset +/// replaces them. What jj refuses is said in its words. +pub fn changesWord(c: pardes.builtins.Ctx) void { + const p = c.p; + const pane = c.pane; + const f = if (pane.file) |*file| file else return p.reportFailure(c.id, "Changes: only a file's pane takes it"); + const arg = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); + if (arg.len == 0 and pane.layers.revset_len > 0) { + pane.layers.revset_len = 0; + pane.layers.lanes = 0; + return; + } + const revset = if (arg.len == 0) "@" else arg; + if (revset.len > File.Layers.revset_max) return p.reportFailure(c.id, "Changes: a revset that long"); + const shown: struct { path: []const u8, rev: []const u8 } = if (of(f)) |r| + .{ .path = r.path, .rev = r.rev } + else if (f.output == null and pardes.filesystem.localPath(f.path) != null) + .{ .path = f.path, .rev = "@" } + else + return p.reportFailure(c.id, "Changes: only a file's pane takes it"); + var line: pardes.Kind.Buf(512) = .{}; + var got = read(p, shown.path, shown.rev, revset, f.content) catch |err| return p.reportFailure(c.id, line.print("Changes: {s}", .{@errorName(err)})); + switch (got) { + .refused => |why| { + defer p.gpa.free(why); + return p.reportFailure(c.id, line.print("Changes: {s}", .{why[0..@min(why.len, 480)]})); + }, + .read => |*changes| { + if (changes.pins.len == 0) { + changes.deinit(p.gpa); + return p.reportFailure(c.id, line.print("Changes: no change of `{s}` touches {s}", .{ revset, std.Io.Dir.path.basename(shown.path) })); + } + @memcpy(changes.revset[0..revset.len], revset); + changes.revset_len = @intCast(revset.len); + const kept = pane.changes orelse p.gpa.create(Changes) catch { + changes.deinit(p.gpa); + return p.reportFailure(c.id, "Changes: out of memory"); + }; + if (pane.changes != null) kept.deinit(p.gpa); + kept.* = changes.*; + pane.changes = kept; + @memcpy(pane.layers.revset[0..revset.len], revset); + pane.layers.revset_len = @intCast(revset.len); + pane.layers.lanes = if (p.view().frontend.windowed) 2 else levels; + }, + } +} + +const Read = union(enum) { refused: []u8, read: Changes }; + +/// What jj says of `revset`'s changes in `path` (absolute) at `rev`, whose +/// text is `text` (what the pane shows: a line is matched to the line its +/// change added by its text). +fn read(p: *Pardes, path: []const u8, rev: []const u8, revset: []const u8, text: []const u8) error{OutOfMemory}!Read { + const gpa = p.gpa; + const arena = p.scratch.allocator(); + const set = try fileset(arena, path); + const dir = dirOf(path); + var out: Changes = .{}; + var kept = false; + defer if (!kept) out.deinit(gpa); + // The changes, oldest first, each with its diff of the file: one run. + const query = try std.fmt.allocPrint(arena, "({s}) & files({s})", .{ revset, set }); + const log_args = [_][]const u8{ "log", "--no-graph", "--reversed", "-r", query, "-T", log_template, "--git", "--context=0", "--", set }; + const logged = switch (p.tape.site(.jj, gpa, runHost, .{ gpa, dir, @as([]const []const u8, &log_args) })) { + .refused => |why| return .{ .refused = why }, + .bytes => |b| b, + }; + defer gpa.free(logged); + var pins: std.ArrayList(Pin) = .empty; + defer pins.deinit(gpa); + // Where each pin's diff starts in `logged`, and the end. + var diffs: std.ArrayList(usize) = .empty; + var it = std.mem.splitScalar(u8, logged, '\n'); + while (it.next()) |l| if (pinOf(l)) |pin| { + if (pins.items.len == pins_max) return .{ .refused = try std.fmt.allocPrint(gpa, "more than {d} changes touch it", .{pins_max}) }; + try pins.append(gpa, pin); + try diffs.append(arena, it.index orelse logged.len); + }; + try diffs.append(arena, logged.len); + out.pins = try pins.toOwnedSlice(gpa); + if (out.pins.len == 0) { + kept = true; + return .{ .read = out }; + } + // Who wrote each line. + const annotated = switch (annotate(p, path, rev)) { + .refused => |why| return .{ .refused = why }, + .bytes => |b| b, + }; + defer gpa.free(annotated); + out.lines = try provenance(gpa, annotated, out.pins); + // Each change's hunks, and which of its lines it added whole. + var hunks: std.ArrayList(Hunk) = .empty; + defer hunks.deinit(gpa); + var removed: std.ArrayList(u8) = .empty; + defer removed.deinit(gpa); + for (0..out.pins.len) |k| try hunksOf(gpa, arena, @intCast(k), logged[diffs.items[k]..diffs.items[k + 1]], text, out.lines, &hunks, &removed); + out.hunks = try hunks.toOwnedSlice(gpa); + out.removed = try removed.toOwnedSlice(gpa); + nest(out.lines, out.pins.len); + kept = true; + return .{ .read = out }; +} + +/// `jj log`'s line a change, before its diff: its id, its author's time, +/// its author, its description's first line, a tab between. +const log_template = "change_id.short(8) ++ \"\\t\" ++ author.timestamp().utc().format(\"%s\") ++ \"\\t\" ++ author.name() ++ \"\\t\" ++ description.first_line() ++ \"\\n\""; + +/// A `log_template` line, or null for a line of a diff (which starts with +/// a blank, a sign, `@`, `\\` or a word and a blank: never eight of jj's +/// id letters, k to z, and a tab). +fn pinOf(l: []const u8) ?Pin { + if (l.len < 9 or l[8] != '\t') return null; + for (l[0..8]) |c| if (c < 'k' or c > 'z') return null; + var cols = std.mem.splitScalar(u8, l[9..], '\t'); + var pin: Pin = .{ .id = l[0..8].*, .time = std.fmt.parseInt(i64, cols.next() orelse "", 10) catch 0 }; + const author = cols.next() orelse ""; + pin.author_len = @intCast(@min(author.len, pin.author.len)); + @memcpy(pin.author[0..pin.author_len], author[0..pin.author_len]); + const title = cols.rest(); + pin.title_len = @intCast(@min(title.len, pin.title.len)); + @memcpy(pin.title[0..pin.title_len], title[0..pin.title_len]); + return pin; +} /// Who last wrote each line of `path` (absolute) at `rev`: a change id /// (`change_id.short(8)`) a line, as `jj file annotate` says it. @@ -205,38 +414,204 @@ pub fn annotate(p: *Pardes, path: []const u8, rev: []const u8) Shown { return p.tape.site(.jj, p.gpa, runHost, .{ p.gpa, dirOf(path), @as([]const []const u8, &.{ "file", "annotate", "-r", rev, "-T", "commit.change_id().short(8) ++ \"\\n\"", "--", std.Io.Dir.path.basename(path) }) }); } -/// The changes `revset` names, oldest first: a change id a line, as -/// `annotate` writes them. Asked in directory `dir`, the file's. -pub fn pinned(p: *Pardes, dir: []const u8, revset: []const u8) Shown { - return p.tape.site(.jj, p.gpa, runHost, .{ p.gpa, dir, @as([]const []const u8, &.{ "log", "--no-graph", "--reversed", "-r", revset, "-T", "change_id.short(8) ++ \"\\n\"" }) }); -} - -/// A line no pinned change wrote (`provenance`). -pub const unpinned = std.math.maxInt(u16); - -/// Which pinned change wrote each line: a value a line, the change's place -/// in `changes` (`pinned`'s answer, oldest first) or `unpinned`, from -/// `annotated` (`annotate`'s answer). The caller's, in `gpa`. -pub fn provenance(gpa: std.mem.Allocator, annotated: []const u8, changes: []const u8) error{ OutOfMemory, TooManyChanges }![]u16 { - var ids: std.ArrayList([]const u8) = .empty; - defer ids.deinit(gpa); - var it = std.mem.tokenizeScalar(u8, changes, '\n'); - while (it.next()) |id| try ids.append(gpa, id); - if (ids.items.len >= unpinned) return error.TooManyChanges; - var out: std.ArrayList(u16) = .empty; +/// Which pin wrote each line: a value a line, from `annotated` +/// (`annotate`'s answer); `whole` is the hunks' to say. The caller's, in +/// `gpa`. +pub fn provenance(gpa: std.mem.Allocator, annotated: []const u8, pins: []const Pin) error{OutOfMemory}![]Line { + var out: std.ArrayList(Line) = .empty; errdefer out.deinit(gpa); var lines = std.mem.splitScalar(u8, annotated, '\n'); while (lines.next()) |id| { // The empty text after the last newline is no line. if (id.len == 0 and lines.peek() == null) break; - const at = for (ids.items, 0..) |pin, i| { - if (std.mem.eql(u8, pin, id)) break i; - } else unpinned; - try out.append(gpa, @intCast(at)); + const at: PinIndex = for (pins, 0..) |pin, i| { + if (std.mem.eql(u8, &pin.id, id)) break @enumFromInt(i); + } else .none; + try out.append(gpa, .{ .pin = at }); } return out.toOwnedSlice(gpa); } +/// Pin `k`'s hunks in `diffed` (its diff of the file, `--git --context=0`) onto +/// `hunks`, their removed lines onto `removed`; and each line of `text` +/// pin `k` wrote (`lines`) marked `whole` when the line it is, matched in +/// order by its text, was one the change added whole: in a run of lines +/// taken away and written, the first as many written as were taken away +/// are changed, the rest added whole. +fn hunksOf(gpa: std.mem.Allocator, arena: std.mem.Allocator, k: u16, diffed: []const u8, text: []const u8, lines: []Line, hunks: *std.ArrayList(Hunk), removed: *std.ArrayList(u8)) error{OutOfMemory}!void { + const Added = struct { text: []const u8, whole: bool }; + var added: std.ArrayList(Added) = .empty; + var walk: diff.Walk = .{}; + var taken: u32 = 0; + var it = std.mem.splitScalar(u8, diffed, '\n'); + while (it.next()) |raw| { + const l = walk.step(raw); + switch (l.kind) { + .hunk => { + const h = diff.parseHunk(std.mem.trimEnd(u8, raw, "\r")).?; + try hunks.append(gpa, .{ .pin = k, .old_start = @intCast(h.old_start), .old_len = @intCast(h.old_count), .new_start = @intCast(h.new_start), .new_len = @intCast(h.new_count), .removed = @intCast(removed.items.len), .removed_len = 0 }); + taken = 0; + }, + .removed => { + const body = std.mem.trimEnd(u8, raw, "\r")[1..]; + try removed.appendSlice(gpa, body); + try removed.append(gpa, '\n'); + hunks.items[hunks.items.len - 1].removed_len += @intCast(body.len + 1); + taken += 1; + }, + .added => { + try added.append(arena, .{ .text = std.mem.trimEnd(u8, raw, "\r")[1..], .whole = taken == 0 }); + taken -|= 1; + }, + else => {}, + } + } + var next: usize = 0; + var rows = std.mem.splitScalar(u8, text, '\n'); + for (lines) |*line| { + const row = rows.next() orelse break; + if (@intFromEnum(line.pin) != k) continue; + const from = next; + while (next < added.items.len and !std.mem.eql(u8, added.items[next].text, std.mem.trimEnd(u8, row, "\r"))) next += 1; + if (next == added.items.len) { + next = from; + continue; + } + line.whole = added.items[next].whole; + next += 1; + } +} + +/// Each line's lanes: the blocks of the pins that span it, oldest first. +/// A pin's block runs from a line it wrote on to each next line it wrote +/// while every line between was written by a newer pin: its lane unbroken +/// down what it wrote, through what later pins rewrote inside it. An older +/// pin's line (or one no pin wrote) ends a newer pin's block, so blocks +/// nest, the older outside, and a block keeps its level down all its rows: +/// the spine keeps its place, a nested change steps to the right on its +/// rows only. Past `levels`, the innermost are not drawn. +fn nest(lines: []Line, npins: usize) void { + for (0..npins) |k| { + var i: usize = 0; + while (i < lines.len) { + if (@intFromEnum(lines[i].pin) != k) { + i += 1; + continue; + } + var last = i; + for (lines[i + 1 ..], i + 1..) |l, j| { + const q = @intFromEnum(l.pin); + if (q == k) last = j else if (l.pin == .none or q < k) break; + } + for (lines[i .. last + 1]) |*l| for (&l.lanes) |*lane| if (lane.* == .none) { + lane.* = @enumFromInt(k); + break; + }; + i = last + 1; + } + } +} + +/// The lanes' colours, a pin's the `pin % len`th, oldest first: the +/// theme's accents but the two that mean written and taken away (its green +/// and red), in hue order from the top, each a hue `hue_apart` or more from +/// the one kept before it (doom one: magenta, blue, yellow; cyan and +/// orange go). Distinct colours, never one between two. +pub fn laneColours(th: *const pardes.Theme, buf: *[8][3]u8) []const [3]u8 { + const pal = th.palette; + const grounds = [2][3]u8{ if (pal) |c| c[1] else .{ 0xcf, 0x22, 0x2e }, if (pal) |c| c[2] else .{ 0x2e, 0xa0, 0x43 } }; + const accents: [6][3]u8 = if (pal) |c| .{ c[3], c[4], c[5], c[6], th.num, th.kw } else .{ th.kw, th.num, th.str, th.box, th.column_box orelse th.box, th.comment }; + var sorted: [6][3]u8 = undefined; + var n: usize = 0; + for (accents) |c| { + // A grey is no accent; one near written or taken away means that. + if (chroma(c) < 48 or hueApart(c, grounds[0]) < hue_apart or hueApart(c, grounds[1]) < hue_apart) continue; + sorted[n] = c; + n += 1; + } + std.sort.insertion([3]u8, sorted[0..n], {}, struct { + fn above(_: void, a: [3]u8, b: [3]u8) bool { + return hue(a) > hue(b); + } + }.above); + var kept: usize = 0; + for (sorted[0..n]) |c| { + if (kept > 0 and hueApart(c, buf[kept - 1]) < hue_apart) continue; + buf[kept] = c; + kept += 1; + } + return buf[0..kept]; +} + +/// Two hues closer than this are one colour to a lane (doom one's cyan is +/// 12 degrees from its blue, its orange 11 from its yellow). +const hue_apart = 15; + +fn chroma(c: [3]u8) u8 { + return @max(c[0], c[1], c[2]) - @min(c[0], c[1], c[2]); +} + +/// HSV's hue, in degrees. +fn hue(c: [3]u8) f32 { + const r: f32 = @floatFromInt(c[0]); + const g: f32 = @floatFromInt(c[1]); + const b: f32 = @floatFromInt(c[2]); + const hi = @max(r, g, b); + const d = hi - @min(r, g, b); + if (d == 0) return 0; + const h = if (hi == r) @mod((g - b) / d, 6) else if (hi == g) (b - r) / d + 2 else (r - g) / d + 4; + return 60 * h; +} + +fn hueApart(a: [3]u8, b: [3]u8) f32 { + const d = @abs(hue(a) - hue(b)); + return @min(d, 360 - d); +} + +/// The changes a view pins, on its body's rows (body_layer.zig, while +/// File.Layers pins any): in the gutter's lane cells after the number a +/// lane each pin whose block runs down the row, at its level, a glyph in a +/// terminal, a strip of pixels in a window (Surface.lanes); and a line a +/// pin added whole green across it, as a diff's added line. Not yet: the +/// ghost rows (what the shown revision has not: removed lines, each pin's +/// description), a changed line's words. +pub fn paint(p: *Pardes, s: *pardes.Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16) void { + const ch = pane.changes orelse return; + if (ch.lines.len == 0 or !std.mem.eql(u8, ch.pinned(), pane.layers.pinned())) return; + var buf: [8][3]u8 = undefined; + const colours = laneColours(p.theme(), &buf); + if (colours.len == 0) return; + const gutter = File.gutterWidth(pane); + const cells = File.laneCells(pane); + if (gutter >= tw or cells == 0) return; + const first = tx + gutter - cells; + const windowed = p.view().frontend.windowed; + const ground = pardes.colors.Grounds.of(p.theme()).add.row; + const body_y = p.bodyTop(pane, r); + const scroll = pane.scroll(); + var vr: u16 = pane.context_rows; + while (vr < body_h) : (vr += 1) { + const row: i32 = if (pane.wrap_n == 0) scroll + @as(i32, vr) else if (vr < pane.wrap_n) pane.wrap_line[vr] else break; + if (row < 0 or row >= ch.lines.len) continue; + const line = ch.lines[@intCast(row)]; + const y = body_y + vr; + if (line.whole and line.pin != .none) s.tint(tx + gutter, y, tw - gutter, ground, null); + for (line.lanes, 0..) |lane, level| { + if (lane == .none) break; + const rgb = colours[@intFromEnum(lane) % colours.len]; + if (windowed) { + // A body a pixel shell draws as a layer is painted on a + // temporary surface first: its lanes are not drawn yet. + if (s == &p.surface) s.lanes.append(p.gpa, .{ .x = first, .y = y, .level = @intCast(level), .rgb = rgb }) catch {}; + } else if (level < cells) { + var style = s.at(first + @as(u16, @intCast(level)), y).style; + style.fg = .{ .rgb = rgb }; + s.set(first + @as(u16, @intCast(level)), y, "\u{258e}", style); + } + } + } +} + // ---- tests ---- const testing = std.testing; @@ -268,17 +643,23 @@ const Repo = struct { const three = "const three = 3;\n"; fn init(gpa: std.mem.Allocator) !?Repo { + return with(gpa, &.{ .{ one, "one" }, .{ two, "two" } }, three); + } + + /// `a.zig` committed as each text with its message, in order; then + /// `working` in the working copy, never snapshotted. + fn with(gpa: std.mem.Allocator, commits: []const [2][]const u8, working: ?[]const u8) !?Repo { var tmp = testing.tmpDir(.{}); errdefer tmp.cleanup(); var buf: [std.Io.Dir.max_path_bytes]u8 = undefined; const dir = try gpa.dupe(u8, buf[0..try tmp.dir.realPath(testing.io, &buf)]); errdefer gpa.free(dir); if (!try run(gpa, dir, &.{ "git", "init" })) return null; - for ([_][]const u8{ one, two }, [_][]const u8{ "one", "two" }) |text, message| { - try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.zig", .data = text }); - if (!try run(gpa, dir, &.{ "commit", "-m", message })) return null; + for (commits) |c| { + try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.zig", .data = c[0] }); + if (!try run(gpa, dir, &.{ "commit", "-m", c[1] })) return null; } - try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.zig", .data = three }); + if (working) |text| try tmp.dir.writeFile(testing.io, .{ .sub_path = "a.zig", .data = text }); return .{ .tmp = tmp, .dir = dir, .file = try std.fmt.allocPrint(gpa, "{s}/a.zig", .{dir}) }; } @@ -378,45 +759,141 @@ test "a client replays the open of a file at a revision and ends equal" { try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core())); } -test "provenance: a value a line, which pinned change wrote it, from what jj answers" { +test "Changes pins a revset's changes in this view: who wrote each line, which it added whole, each one's hunks and what they took away; bare again unpins; jj's refusals are said" { const gpa = testing.allocator; var repo = try Repo.init(gpa) orelse return error.SkipZigTest; defer repo.deinit(gpa); - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 24 }); + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 }); defer p.deinit(); - // `two` wrote lines 1 and 3 of its text, `one` line 2. - const annotated = switch (annotate(p, repo.file, "@-")) { - .bytes => |b| b, - .refused => |why| { - defer gpa.free(why); - std.debug.print("annotate: {s}\n", .{why}); - return error.Refused; - }, - }; - defer gpa.free(annotated); - for ([_][]const u8{ "@--::@-", "@-" }, [_][3]u16{ .{ 1, 0, 1 }, .{ 0, unpinned, 0 } }) |revset, want| { - const changes = switch (pinned(p, repo.dir, revset)) { - .bytes => |b| b, - .refused => |why| { - gpa.free(why); - return error.Refused; - }, - }; - defer gpa.free(changes); - const lines = try provenance(gpa, annotated, changes); - defer gpa.free(lines); - try testing.expectEqualSlices(u16, &want, lines); + var line: [4200]u8 = undefined; + p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}@@-", .{repo.file}) }); + const id = p.view().active; + const pane = p.panes[id].?; + try testing.expectEqualStrings(Repo.two, pane.file.?.content); + p.update(.{ .command = "Changes @--::@-" }); + try testing.expectEqualStrings("@--::@-", pane.layers.pinned()); + const ch = pane.changes.?; + try testing.expectEqualStrings("@--::@-", ch.pinned()); + try testing.expectEqual(@as(usize, 2), ch.pins.len); + for (ch.pins, [_][]const u8{ "one", "two" }) |pin, title| { + try testing.expectEqualStrings(title, pin.title[0..pin.title_len]); + try testing.expectEqualStrings("t", pin.author[0..pin.author_len]); + try testing.expect(pin.time > 0); } - // A revset jj refuses, in its words. - switch (pinned(p, repo.dir, "nosuch")) { - .bytes => |b| { - gpa.free(b); - return error.NotRefused; - }, - .refused => |why| { - defer gpa.free(why); - try testing.expect(std.mem.indexOf(u8, why, "nosuch") != null); - }, + // `two` changed line 1 (`one`'s first) and added line 3 whole; line 2 is `one`'s, added whole. + const one: PinIndex = @enumFromInt(0); + const two: PinIndex = @enumFromInt(1); + const want = [_]Line{ + .{ .pin = two, .whole = false, .lanes = .{ two, .none, .none } }, + .{ .pin = one, .whole = true, .lanes = .{ one, .none, .none } }, + .{ .pin = two, .whole = true, .lanes = .{ two, .none, .none } }, + }; + try testing.expectEqualSlices(Line, &want, ch.lines); + const hunks = [_]Hunk{ + .{ .pin = 0, .old_start = 0, .old_len = 0, .new_start = 1, .new_len = 2, .removed = 0, .removed_len = 0 }, + .{ .pin = 1, .old_start = 1, .old_len = 1, .new_start = 1, .new_len = 1, .removed = 0, .removed_len = 15 }, + .{ .pin = 1, .old_start = 2, .old_len = 0, .new_start = 3, .new_len = 1, .removed = 15, .removed_len = 0 }, + }; + try testing.expectEqualSlices(Hunk, &hunks, ch.hunks); + try testing.expectEqualStrings("const one = 1;\n", ch.removed); + // Bare: unpinned in this view; what jj said is kept for another view. + p.update(.{ .command = "Changes" }); + try testing.expectEqual(@as(u8, 0), pane.layers.revset_len); + try testing.expectEqual(@as(usize, 2), ch.pins.len); + // Bare again: `@`, the working copy's change, which (never snapshotted) touches nothing. + p.update(.{ .command = "Changes" }); + try testing.expect(std.mem.indexOf(u8, told(p, id), "Changes: no change of `@` touches a.zig") != null); + try testing.expectEqual(@as(u8, 0), pane.layers.revset_len); + // jj's refusal, in its words. + p.update(.{ .command = "Changes nosuch" }); + try testing.expect(std.mem.indexOf(u8, told(p, id), "Changes: Revision `nosuch` doesn't exist") != null); + try testing.expectEqual(@as(u8, 0), pane.layers.revset_len); +} + +test "a client replays Changes from what the session's jj answered and ends equal" { + const gpa = testing.allocator; + var repo = try Repo.init(gpa) orelse return error.SkipZigTest; + defer repo.deinit(gpa); + const R = pardes.replica; + const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24 }, .{}, false); + defer a.deinit(); + const r = try R.Replica.init(gpa, 1, try a.unit(0, 0), false); + defer r.deinit(); + var line: [4200]u8 = undefined; + r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}@@-", .{repo.file}) })); + r.confirm(try a.local(.{ .command = "Changes @--::@-" })); + r.settle(); + try testing.expect(r.diverged == null); + const id = a.core.view().active; + try testing.expectEqual(@as(usize, 2), a.core.panes[id].?.changes.?.pins.len); + try testing.expectEqualSlices(Line, a.core.panes[id].?.changes.?.lines, r.core().panes[id].?.changes.?.lines); + try testing.expectEqualStrings("@--::@-", r.core().panes[id].?.layers.pinned()); + try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core())); +} + +test "Changes draws a lane a pinned change after the line number, nested ones a level to the right on their rows only, and a line one added whole green across it; bare again, the gutter as it was" { + const gpa = testing.allocator; + // `fn` wrote the function; `mid` rewrote its lines 3-4 as 3-6 (two + // changed, two added whole); `shift` rewrote line 4 again. + const fn_text = "fn f() void {\n a();\n b();\n c();\n g();\n h();\n i();\n}\n"; + const mid_text = "fn f() void {\n a();\n b2();\n c2();\n x();\n y();\n g();\n h();\n i();\n}\n"; + const shift_text = "fn f() void {\n a();\n b2();\n c3();\n x();\n y();\n g();\n h();\n i();\n}\n"; + var repo = try Repo.with(gpa, &.{ .{ fn_text, "fn" }, .{ mid_text, "mid" }, .{ shift_text, "shift" } }, null) orelse return error.SkipZigTest; + defer repo.deinit(gpa); + for ([_]bool{ false, true }) |windowed| { + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 60, .rows = 24, .windowed = windowed }); + defer p.deinit(); + var line: [4200]u8 = undefined; + p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) }); + const id = p.view().active; + const pane = p.panes[id].?; + const before = File.gutterWidth(pane); + p.update(.{ .command = "Changes ::@" }); + try testing.expectEqual(@as(usize, 3), pane.changes.?.pins.len); + const cells: u16 = if (windowed) 2 else levels; + try testing.expectEqual(before + cells, File.gutterWidth(pane)); + p.sync(); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const s = try p.render(arena.allocator()); + const body = s.region(.body, id).?.rect; + const first = body.x + before; + var buf: [8][3]u8 = undefined; + const colours = laneColours(p.theme(), &buf); + try testing.expect(colours.len >= 3); + const ground = pardes.colors.Grounds.of(p.theme()).add.row; + // Rows 1-10: `fn`'s spine on all; `mid` on 3-6; `shift` on 4. + const want = [_][]const u8{ "0", "0", "01", "012", "01", "01", "0", "0", "0", "0" }; + for (want, 0..) |lanes, row| { + const y = body.y + @as(u16, @intCast(row)); + if (windowed) { + var n: usize = 0; + for (s.lanes.items) |lane| if (lane.y == y) { + try testing.expectEqual(first, lane.x); + try testing.expectEqual(lanes[lane.level] - '0', lane.level); + try testing.expectEqual(colours[lane.level], lane.rgb); + n += 1; + }; + try testing.expectEqual(lanes.len, n); + } else for (0..levels) |level| { + const cell = s.at(first + @as(u16, @intCast(level)), y); + if (level < lanes.len) { + try testing.expectEqualStrings("\u{258e}", cell.grapheme()); + try testing.expectEqual(pardes.Color{ .rgb = colours[level] }, cell.style.fg); + } else if (!cell.default and !std.mem.eql(u8, cell.grapheme(), " ")) { + std.debug.print("row {d} level {d}: [{s}] {any}\n", .{ row, level, cell.grapheme(), cell.style }); + return error.TestUnexpectedResult; + } + } + // `fn`'s lines it still has (1, 2, 7-10) and `mid`'s x() and + // y() (5, 6) were added whole; b2 (3) and c3 (4) changed one. + const whole = row != 2 and row != 3; + const text_cell = s.at(body.x + File.gutterWidth(pane) + 1, y); + try testing.expectEqual(whole, std.meta.eql(text_cell.style.bg, pardes.Color{ .rgb = ground })); + } + if (!windowed) try testing.expectEqual(@as(usize, 0), s.lanes.items.len); + p.update(.{ .command = "Changes" }); + try testing.expectEqual(before, File.gutterWidth(pane)); } } diff --git a/core/panes.zig b/core/panes.zig index 5277ebba..ee03ccf2 100644 --- a/core/panes.zig +++ b/core/panes.zig @@ -320,6 +320,9 @@ pub const Pane = struct { view: SessionView = .{}, /// The painters a file's body wears in this view (File.Layers). layers: File.Layers = .{}, + /// What jj answered for the last `Changes` in any view (jj.zig): the + /// pane's, so a client that joins late has it in the dump. + changes: ?*@import("jj.zig").Changes = null, sel: [3]Sel = @splat(.{}), pointer_selections: [3]?PointerSelection = @splat(null), next_pointer_selection: u64 = 0, @@ -1279,6 +1282,11 @@ pub fn teardownPane(p: *Pardes, pane: *Pane) void { pane.input.deinit(p.gpa); pane.jump.deinit(p.gpa); pane.places.deinit(p.gpa); + if (pane.changes) |changes| { + changes.deinit(p.gpa); + p.gpa.destroy(changes); + pane.changes = null; + } if (pane.query) |q| { q.deinit(p.gpa); p.gpa.destroy(q); diff --git a/core/replica.zig b/core/replica.zig index 97da9c74..dd3f13d1 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -6583,6 +6583,7 @@ const may_wait = [_]Wait{ .{ .what = "Mini *", .on = .any, .stop = "resolve", .why = "a file opened by name, from the session's disk" }, .{ .what = "Get", .on = .any, .stop = "read_file", .why = "the file read again from the session's disk" }, .{ .what = "Save", .on = .any, .stop = "write_file", .why = "a save" }, + .{ .what = "Changes", .on = .any, .stop = "jj", .why = "what jj says of the pinned changes, the session's (P14: a word typed may take a moment once)" }, // A program run, a shell opened or closed: the session's processes. .{ .what = "Exec *", .on = .any, .stop = "kind", .why = "a program run: its name asked of the disk first" }, .{ .what = "Exec *", .on = .any, .stop = "tty_taken", .why = "a program run in a shell: whether one has it, the session's" }, diff --git a/core/root.zig b/core/root.zig index 65f61e0d..de1c44b0 100644 --- a/core/root.zig +++ b/core/root.zig @@ -55,6 +55,7 @@ pub const Facts = @import("surface.zig").Facts; pub const Region = @import("surface.zig").Region; pub const Chrome = @import("surface.zig").Chrome; pub const RailTick = @import("surface.zig").RailTick; +pub const Lane = @import("surface.zig").Lane; pub const MAX_REGIONS = @import("surface.zig").MAX_REGIONS; /// What comes in (Event.zig). pub const Mouse = @import("Event.zig").Mouse; diff --git a/core/surface.zig b/core/surface.zig index 6e05f25f..653abd82 100644 --- a/core/surface.zig +++ b/core/surface.zig @@ -147,6 +147,10 @@ pub const MAX_REGIONS = 1 + MAX_PANES * (4 + panes.Pane.Notices.max) + pardes.MA /// to a detached session draws them from the frame alone. pub const RailTick = struct { owner: u8, at: u16, current: bool }; pub const max_rail_ticks = 4096; +/// A pinned change's lane on a body row (jj.paint): a pixel shell draws +/// it as a strip in gutter cell `x`, at its `level`'s place (sample A of +/// the ruled design: each a third of a cell wide, half that of air between). +pub const Lane = struct { x: u16, y: u16, level: u8, rgb: [3]u8 }; pub const rail_tick_scale = 1024; pub const Chrome = struct { @@ -256,6 +260,12 @@ pub const Surface = struct { /// rail's track, the pane's current match's marked. rail_ticks: [max_rail_ticks]RailTick = undefined, nrail_ticks: u16 = 0, + /// The lanes of the changes pinned on the bodies, for a pixel shell + /// (in a terminal they are glyphs in the cells): the frame's own + /// surface's, gpa's, as `placements` (a list, not an array: a frame + /// makes many a temporary Surface, and a safe build fills an array's + /// `undefined` in each). + lanes: std.ArrayList(Lane) = .empty, chrome: Chrome = .{}, cells: []Cell = &.{}, /// bar: draw an insert-style thin cursor instead of the block diff --git a/dev/gui/gui.zig b/dev/gui/gui.zig index aa28a3f0..47fd14d5 100644 --- a/dev/gui/gui.zig +++ b/dev/gui/gui.zig @@ -4876,6 +4876,16 @@ fn buildDecor(g: *Gui, gpa: std.mem.Allocator, surface: *const pardes.Surface, g } else false; if (grid_bottom < win_h and tag_last) try addDecor(g, gpa, 0, grid_bottom, win_w, win_h, chrome.tag_bg, 1, win_w, win_h); try paneDecor(g, gpa, regions, surface.rail_ticks[0..surface.nrail_ticks], chrome, layout, surface.cols, surface.rows, win_w, win_h); + // The changes' lanes (jj.paint): a strip a level in the gutter's + // lane cells, each a third of a cell wide with half that of air + // before it, so three take one and a half cells (the ruled + // sample A); whole pixels, so every row's strip lines up. + for (surface.lanes.items) |lane| { + const w = @max(1, @round(layout.w / 3)); + const x0 = @round(@as(f32, @floatFromInt(lane.x)) * layout.w + w / 2 + @as(f32, @floatFromInt(lane.level)) * (w + w / 2)); + const y0 = @as(f32, @floatFromInt(lane.y)) * layout.h; + try addDecor(g, gpa, x0, y0, x0 + w, y0 + layout.h, lane.rgb, 1, win_w, win_h); + } // A single spine runs down each column, through every tag and body. for (regions) |column| { if (column.kind != .column) continue; diff --git a/docs/typ/builtins-gui.json b/docs/typ/builtins-gui.json index a00b8bdf..b019eaee 100644 --- a/docs/typ/builtins-gui.json +++ b/docs/typ/builtins-gui.json @@ -10,6 +10,7 @@ {"name": "Callstack", "leader": "SPC l b", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Show outermost callers first, with signatures and call sites (gc)."}, {"name": "CallstackDepth", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "Caller levels collected by Callstack, 1 through 64; default 8. Bare, it says the current limit."}, {"name": "Changelog", "leader": "SPC h c", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "This build's version and what changed to reach it, printed into an output buffer the same way Config prints the live settings."}, + {"name": "Changes", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Pin the changes `revset` names (jj; bare, `@`) on a file's pane in this view: a lane each after the line number, a line one added whole green; bare again, unpinned."}, {"name": "ClipPaste", "leader": "SPC p", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Paste the system clipboard after the selection."}, {"name": "ClipPasteBefore", "leader": "SPC P", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Paste the system clipboard before the selection."}, {"name": "ClipReplace", "leader": "SPC R", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Replace the selection with the system clipboard."}, diff --git a/docs/typ/builtins-tui.json b/docs/typ/builtins-tui.json index 1f0cd09d..9d613189 100644 --- a/docs/typ/builtins-tui.json +++ b/docs/typ/builtins-tui.json @@ -10,6 +10,7 @@ {"name": "Callstack", "leader": "SPC l b", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Show outermost callers first, with signatures and call sites (gc)."}, {"name": "CallstackDepth", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "Caller levels collected by Callstack, 1 through 64; default 8. Bare, it says the current limit."}, {"name": "Changelog", "leader": "SPC h c", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "This build's version and what changed to reach it, printed into an output buffer the same way Config prints the live settings."}, + {"name": "Changes", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Pin the changes `revset` names (jj; bare, `@`) on a file's pane in this view: a lane each after the line number, a line one added whole green; bare again, unpinned."}, {"name": "ClipPaste", "leader": "SPC p", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Paste the system clipboard after the selection."}, {"name": "ClipPasteBefore", "leader": "SPC P", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Paste the system clipboard before the selection."}, {"name": "ClipReplace", "leader": "SPC R", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Replace the selection with the system clipboard."}, diff --git a/docs/typ/guide.typ b/docs/typ/guide.typ index 7699ee52..db428d7f 100644 --- a/docs/typ/guide.typ +++ b/docs/typ/guide.typ @@ -295,6 +295,14 @@ the revision has not) is said in jj's words. jj reads the working copy as it last saw it (`@`): pardes never snapshots it. #word("Syntax") (#key("SPC t h")) turns a text's syntax colours off in this view, and on again. +#word("Changes") with a revset pins its changes on a file's pane (or a +revision's) in this view; bare, `@`, the change against its parent, and +bare again, off. Each change that touched the file gets a lane after the +line number, from its first line to its last, in the theme's accents in +hue order, oldest first; a change that rewrote lines inside another's +steps a lane to the right on those rows; a line one added whole is green +across the line. jj answers once, when the word is run: the lanes stay +where they were drawn through edits made since. = Call hierarchy -- cgit v1.3 From 8152cf383c8296be29e80175b57e40f8d41049bf Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 21 Nov 2026 14:17:28 -0300 Subject: layers: with `Changes` off nothing is paid (P45): the revset and jj's answers are the session's, a list by pane serial (`Pardes.changes`, `jj.answered`; `jj.forget` at the pane's end), no longer a field of every pane, and a view holds only whether it shows them (`File.Layers.lanes`, the cells their lanes take, hashed with `ink` in one update), so a second view's `Changes other` shows the new set in both and its bare `Changes` hides them in its own alone (bare with none pinned yet is `@`); measured first, per operation against gpu/tree3 (a gui ReleaseFast pardes-perf, perfops's way of counting: reorg/pardes-layers-4/perf): merge50 +0.005% a client key, round 3 +0.110%, a packed one-byte `Layers` +0.391% (a packed field cost the walks more), a plain two-byte one +0.152%, the per-pane field gone +0.118%, the gutter's three reads of the lanes taken out +0.066% with body-appends from +0.189% to -0.004%: what paid was fillBody's line number, formatted for every row of every geometry pass (no `dst`, a hundred a frame) and thrown away, whose row loop moved with any value added to it: it is now written only into a `dst` (client key +0.017%, deep-sel +0.002%, render -0.021%, body-appends -1.555%); and `jj.of` (round 1's) gave a revision's name as a slice of a by-value copy of the pane's Output, dangling once it returned (jj told "Non-UTF-8 argument" for `Changes` in a revision's pane in a window build): the pane's own now; tests: the pinned changes are the pane's, shown in a view by its own bit (a second view's revset shows in both, its bare Changes hides them there alone), the two of a terminal's cells said so (`.windowed = false`); core-test 896/1056 (160 skipped), shell-test 1098/1101 (3 skipped), gui unit-test 1695/1699 (4 skipped); the frame and perf gate against tree3 (gpu/l4-g0): 77/77 frames, 0 differ, perfab corpus2x +0.005% (noise 0.058%), perfops 121 counts within 0.1% (largest terminal on all +0.082%) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/Core.zig | 6 ++ core/File.zig | 75 +++++++++++------------- core/body_layer.zig | 2 +- core/builtins.zig | 2 +- core/jj.zig | 141 ++++++++++++++++++++++++++++++++------------- core/panes.zig | 9 +-- docs/typ/builtins-gui.json | 2 +- docs/typ/builtins-tui.json | 2 +- docs/typ/guide.typ | 5 +- 9 files changed, 150 insertions(+), 94 deletions(-) diff --git a/core/Core.zig b/core/Core.zig index 385c3e74..177a6e78 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -355,6 +355,10 @@ lsp_ask: Ask = .{}, pipe: Pipe = .{}, /// A query pane's Grep, and its Find's listing, on a worker (Stream.zig). stream: Stream = .{}, +/// What jj answered for each pane's `Changes` (jj.zig), by its serial: the +/// session's list, not a field of every pane (a digest and a rollback copy +/// walk every pane's fields at every step). +changes: std.ArrayList(@import("jj.zig").Changes) = .empty, fs: filesystem.Namespace = .{}, boot: Boot = .shell, @@ -864,6 +868,8 @@ pub fn deinit(p: *Pardes) void { for (p.spawn_dirs) |d| if (d) |dir| gpa.free(dir); p.pipe.deinit(gpa); p.stream.deinit(gpa); + for (p.changes.items) |*c| c.deinit(gpa); + p.changes.deinit(gpa); p.handover.deinit(gpa); if (p.stream.ahead.len > 0) p.tree_sitter_gpa.free(p.stream.ahead); p.locations_cache.deinit(p.tree_sitter_gpa); diff --git a/core/File.zig b/core/File.zig index f7d6bced..6e44f85e 100644 --- a/core/File.zig +++ b/core/File.zig @@ -1777,6 +1777,8 @@ fn geometryKey(pane: *const Pane, f: *const State) u64 { fn fillBody(tab: u16, dst: ?[]u8, pane: *Pane, f: *State, width: usize, record_wrap: bool) usize { if (record_wrap) pane.wrap_n = 0; const prefix_width = gutterWidth(pane); + // Where a number ends: a blank, then the lanes (laneCells), after it. + const number_end = prefix_width -| laneCells(pane) -| 1; const total = nlines(pane.gpa, f); // The slot after the text's last newline, found once: every numbered // row below asks whether it is that one. @@ -1814,24 +1816,25 @@ fn fillBody(tab: u16, dst: ?[]u8, pane: *Pane, f: *State, width: usize, record_w pane.wrap_n = @intCast(i + 1); } if (row < total) { - var lbuf: [@max(config.PREFIX_W, 32)]u8 = undefined; - const prefix = lbuf[0..prefix_width]; - @memset(prefix, ' '); - if (at == 0 and prefix.len > 0) { - var lineno = row + 1; - // The number, a blank, then the lanes (laneCells). - var digit: usize = prefix.len - 1 - laneCells(pane); - if (row == end_slot) { - prefix[digit - 1] = '~'; - } else while (true) { - digit -= 1; - prefix[digit] = '0' + @as(u8, @intCast(lineno % 10)); - lineno /= 10; - if (lineno == 0) break; + // The number only where the text is wanted: a geometry pass (no + // `dst`, a hundred a frame) counts its cells and nothing more. + if (dst) |out| { + const prefix = out[written..][0..prefix_width]; + @memset(prefix, ' '); + if (at == 0 and prefix.len > 0) { + var lineno = row + 1; + var digit: usize = number_end; + if (row == end_slot) { + prefix[digit - 1] = '~'; + } else while (true) { + digit -= 1; + prefix[digit] = '0' + @as(u8, @intCast(lineno % 10)); + lineno /= 10; + if (lineno == 0) break; + } } } - if (dst) |out| @memcpy(out[written..][0..prefix.len], prefix); - written += prefix.len; + written += prefix_width; if (dst) |out| @memcpy(out[written..][0..guide.len], guide); written += guide.len; // A table row's pads are blanks before their bytes: the row @@ -1877,38 +1880,28 @@ fn fillBody(tab: u16, dst: ?[]u8, pane: *Pane, f: *State, width: usize, record_w /// Both are painted in recolorSyntax's one walk over the cells, each where /// it says (one walk per painter cost a frame a sixth more). /// -/// 3. changes (`Changes [revset]`, jj.zig): while `revset` is set, a -/// lane a pinned change after the line number (the gutter `lanes` -/// cells wider), a line one added whole green across it (jj.paint). -/// Ruled, not built (PARDES.md "Changes on the source view"): a -/// changed line's words tinted, ghost rows for what the shown -/// revision has not. +/// 3. changes (`Changes [revset]`, jj.zig): while `lanes` is set, a +/// lane each of the pane's pinned changes after the line number (the +/// gutter `lanes` cells wider), a line one added whole green across +/// it (jj.paint). Ruled, not built (PARDES.md "Changes on the source +/// view"): a changed line's words tinted, ghost rows for what the +/// shown revision has not. /// 4. churn, ruled, not built: a heat lane after the number and a strip /// by the scroll thumb. +/// +/// Two bytes, hashed in one update: a digest takes every view's of every +/// pane at every step. pub const Layers = struct { - pub const replica = .{ .len = .{.{ "revset", "revset_len" }} }; ink: bool = true, - /// The changes this view pins (jj's revset), none while empty; what jj - /// answered for them is the pane's (`Pane.changes`). - revset: [revset_max]u8 = undefined, - revset_len: u8 = 0, - /// The cells its lanes take while it pins any, 0 while it pins none - /// (laneCells): set as it pins them, from the view's frontend: in a - /// window two, which its strips of pixels fill one and a half of - /// (Surface.Lane); in a terminal three, a glyph each. + /// Whether this view shows the pane's pinned changes (`Pardes.changes`: + /// the revset and jj's answers are the pane's), as the cells their + /// lanes take (laneCells), 0 while it does not: set from the view's + /// frontend, in a window two, which its strips of pixels fill one and + /// a half of (Surface.Lane), in a terminal three, a glyph each. lanes: u8 = 0, - pub const revset_max = 64; - - pub fn pinned(l: *const Layers) []const u8 { - return l.revset[0..l.revset_len]; - } - - /// One word while it pins nothing: a digest walks every view's layers - /// of every pane (field by field it cost a step 0.1 to 0.7% more). pub fn digest(l: *const Layers, h: *pardes.walk.Hasher) void { - h.update(&.{ @intFromBool(l.ink), l.revset_len, l.lanes }); - if (l.revset_len > 0) h.update(l.pinned()); + h.update(&.{ @intFromBool(l.ink), l.lanes }); } }; diff --git a/core/body_layer.zig b/core/body_layer.zig index 8d54760f..28b86f78 100644 --- a/core/body_layer.zig +++ b/core/body_layer.zig @@ -338,7 +338,7 @@ pub fn renderBody(p: *Pardes, s: *Surface, arena: std.mem.Allocator, pane: *Pane // File layout is independent of whether its producer requests colors. if (pane.file) |*f| { drawGutter(p, s, pane, r, tx, tw, body_h, active); - if (pane.layers.revset_len > 0) @import("jj.zig").paint(p, s, pane, r, tx, tw, body_h); + if (pane.layers.lanes > 0) @import("jj.zig").paint(p, s, pane, r, tx, tw, body_h); panes.Query.paintMark(p, s, pane, r, body_h); if (pane.colorAlgo() != .none) panes.File.recolorSyntax(p, s, pane, f, r, tx, tw, body_h); diff --git a/core/builtins.zig b/core/builtins.zig index e059916a..77fc58ed 100644 --- a/core/builtins.zig +++ b/core/builtins.zig @@ -1080,7 +1080,7 @@ pub const At = struct { pub const run = @import("jj.zig").word; }; -/// Pin the changes `revset` names (jj; bare, `@`) on a file's pane in this view: a lane each after the line number, a line one added whole green; bare again, unpinned. +/// Pin the changes `revset` names (jj) on a file's pane and show them in this view: a lane each after the line number, a line one added whole green; bare, shown here or not (none pinned yet: `@`). pub const Changes = struct { pub const takes_arg = true; pub const run = @import("jj.zig").changesWord; diff --git a/core/jj.zig b/core/jj.zig index ebd2ea27..b4d119e8 100644 --- a/core/jj.zig +++ b/core/jj.zig @@ -111,7 +111,8 @@ fn refusal(gpa: std.mem.Allocator, why: []const u8) Shown { /// A revision's pane: the file it is of (its name without `@rev`) and the /// revision. Null for any other pane. pub fn of(f: *const File.State) ?struct { path: []const u8, rev: []const u8 } { - const o = f.output orelse return null; + // The pane's own, not a copy: the revision is a slice of it. + const o = if (f.output) |*o| o else return null; if (o.from != .revision) return null; return .{ .path = f.path[0 .. f.path.len - o.arg().len - 1], .rev = o.arg() }; } @@ -199,15 +200,19 @@ pub fn looked(p: *Pardes, id: usize, dir: []const u8, text: []const u8, at: look // ---- `Changes [revset]` (PARDES.md: pinned changes as lanes): what jj // answers for it, kept as flat arrays in the pane ---- -/// What jj answered for a pane's `Changes`: the pane's replicated state (a -/// client never runs jj; one that joins late has it in the dump), drawn by -/// a view that pins the same revset (File.Layers). Two jj runs, each a +/// What jj answered for a pane's `Changes`: replicated state, the session's +/// (`Pardes.changes`, by the pane's serial: a client never runs jj; one that +/// joins late has it in the dump), its revset with it, drawn by each view that shows them (File.Layers.lanes: +/// a view holds that bit, not the revset; one set a pane, so a view's +/// `Changes other` replaces what every view shows). Two jj runs, each a /// site of the step's tape: the changes with their diffs of the file /// (`jj log -p --git`, the diffs read with diff.zig's walk), and who wrote /// each line of the shown revision (`jj file annotate`). pub const Changes = struct { pub const replica = .{ .len = .{.{ "revset", "revset_len" }} }; - revset: [File.Layers.revset_max]u8 = undefined, + /// The pane's (its serial). + serial: u32, + revset: [revset_max]u8 = undefined, revset_len: u8 = 0, /// The revset's changes that touch the file, oldest first. pins: []Pin = &.{}, @@ -223,14 +228,31 @@ pub const Changes = struct { gpa.free(c.lines); gpa.free(c.hunks); gpa.free(c.removed); - c.* = .{}; + c.* = .{ .serial = c.serial }; } pub fn pinned(c: *const Changes) []const u8 { return c.revset[0..c.revset_len]; } + + pub const revset_max = 64; }; +/// What jj answered for pane `serial`'s `Changes` (`Pardes.changes`), if anything. +pub fn answered(p: *Pardes, serial: u32) ?*Changes { + for (p.changes.items) |*c| if (c.serial == serial) return c; + return null; +} + +/// Pane `serial`'s answers let go (the pane's end). +pub fn forget(p: *Pardes, serial: u32) void { + for (p.changes.items, 0..) |*c, i| if (c.serial == serial) { + c.deinit(p.gpa); + _ = p.changes.swapRemove(i); + return; + }; +} + /// A pinned change, as `jj log` says it. pub const Pin = struct { pub const replica = .{ .len = .{ .{ "author", "author_len" }, .{ "title", "title_len" } } }; @@ -280,21 +302,27 @@ pub const Hunk = struct { }; /// The `Changes` word (builtins.zig registers it): in a file's pane (or a -/// revision's), the changes `revset` names (bare: `@`, the change against -/// its parent) pinned in this view; bare again, unpinned; another revset -/// replaces them. What jj refuses is said in its words. +/// revision's), the changes `revset` names pinned on the pane and shown in +/// this view; another revset replaces them (in every view that shows +/// them). Bare: shown in this view or not, the pane's pinned ones (none +/// yet: `@`, the change against its parent). What jj refuses is said in +/// its words. pub fn changesWord(c: pardes.builtins.Ctx) void { const p = c.p; const pane = c.pane; const f = if (pane.file) |*file| file else return p.reportFailure(c.id, "Changes: only a file's pane takes it"); const arg = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); - if (arg.len == 0 and pane.layers.revset_len > 0) { - pane.layers.revset_len = 0; + if (arg.len == 0 and pane.layers.lanes > 0) { pane.layers.lanes = 0; return; } + const cells: u8 = if (p.view().frontend.windowed) 2 else levels; + if (arg.len == 0 and answered(p, pane.serial) != null) { + pane.layers.lanes = cells; + return; + } const revset = if (arg.len == 0) "@" else arg; - if (revset.len > File.Layers.revset_max) return p.reportFailure(c.id, "Changes: a revset that long"); + if (revset.len > Changes.revset_max) return p.reportFailure(c.id, "Changes: a revset that long"); const shown: struct { path: []const u8, rev: []const u8 } = if (of(f)) |r| .{ .path = r.path, .rev = r.rev } else if (f.output == null and pardes.filesystem.localPath(f.path) != null) @@ -315,16 +343,15 @@ pub fn changesWord(c: pardes.builtins.Ctx) void { } @memcpy(changes.revset[0..revset.len], revset); changes.revset_len = @intCast(revset.len); - const kept = pane.changes orelse p.gpa.create(Changes) catch { + changes.serial = pane.serial; + if (answered(p, pane.serial)) |kept| { + kept.deinit(p.gpa); + kept.* = changes.*; + } else p.changes.append(p.gpa, changes.*) catch { changes.deinit(p.gpa); return p.reportFailure(c.id, "Changes: out of memory"); }; - if (pane.changes != null) kept.deinit(p.gpa); - kept.* = changes.*; - pane.changes = kept; - @memcpy(pane.layers.revset[0..revset.len], revset); - pane.layers.revset_len = @intCast(revset.len); - pane.layers.lanes = if (p.view().frontend.windowed) 2 else levels; + pane.layers.lanes = cells; }, } } @@ -339,7 +366,7 @@ fn read(p: *Pardes, path: []const u8, rev: []const u8, revset: []const u8, text: const arena = p.scratch.allocator(); const set = try fileset(arena, path); const dir = dirOf(path); - var out: Changes = .{}; + var out: Changes = .{ .serial = 0 }; var kept = false; defer if (!kept) out.deinit(gpa); // The changes, oldest first, each with its diff of the file: one run. @@ -568,16 +595,16 @@ fn hueApart(a: [3]u8, b: [3]u8) f32 { return @min(d, 360 - d); } -/// The changes a view pins, on its body's rows (body_layer.zig, while -/// File.Layers pins any): in the gutter's lane cells after the number a +/// The pane's pinned changes as a view shows them, on its body's rows (body_layer.zig, while +/// File.Layers.lanes is set): in the gutter's lane cells after the number a /// lane each pin whose block runs down the row, at its level, a glyph in a /// terminal, a strip of pixels in a window (Surface.lanes); and a line a /// pin added whole green across it, as a diff's added line. Not yet: the /// ghost rows (what the shown revision has not: removed lines, each pin's /// description), a changed line's words. pub fn paint(p: *Pardes, s: *pardes.Surface, pane: *Pane, r: pardes.Rect, tx: u16, tw: u16, body_h: u16) void { - const ch = pane.changes orelse return; - if (ch.lines.len == 0 or !std.mem.eql(u8, ch.pinned(), pane.layers.pinned())) return; + const ch = answered(p, pane.serial) orelse return; + if (ch.lines.len == 0) return; var buf: [8][3]u8 = undefined; const colours = laneColours(p.theme(), &buf); if (colours.len == 0) return; @@ -759,11 +786,11 @@ test "a client replays the open of a file at a revision and ends equal" { try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core())); } -test "Changes pins a revset's changes in this view: who wrote each line, which it added whole, each one's hunks and what they took away; bare again unpins; jj's refusals are said" { +test "Changes pins a revset's changes on the pane, shown in this view: who wrote each line, which it added whole, each one's hunks and what they took away; bare hides and shows them; jj's refusals are said" { const gpa = testing.allocator; var repo = try Repo.init(gpa) orelse return error.SkipZigTest; defer repo.deinit(gpa); - const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 }); + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30, .windowed = false }); defer p.deinit(); var line: [4200]u8 = undefined; p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}@@-", .{repo.file}) }); @@ -771,8 +798,8 @@ test "Changes pins a revset's changes in this view: who wrote each line, which i const pane = p.panes[id].?; try testing.expectEqualStrings(Repo.two, pane.file.?.content); p.update(.{ .command = "Changes @--::@-" }); - try testing.expectEqualStrings("@--::@-", pane.layers.pinned()); - const ch = pane.changes.?; + try testing.expectEqual(levels, pane.layers.lanes); + const ch = answered(p, pane.serial).?; try testing.expectEqualStrings("@--::@-", ch.pinned()); try testing.expectEqual(@as(usize, 2), ch.pins.len); for (ch.pins, [_][]const u8{ "one", "two" }) |pin, title| { @@ -796,18 +823,53 @@ test "Changes pins a revset's changes in this view: who wrote each line, which i }; try testing.expectEqualSlices(Hunk, &hunks, ch.hunks); try testing.expectEqualStrings("const one = 1;\n", ch.removed); - // Bare: unpinned in this view; what jj said is kept for another view. + // Bare: not shown in this view; what jj said is kept on the pane. p.update(.{ .command = "Changes" }); - try testing.expectEqual(@as(u8, 0), pane.layers.revset_len); + try testing.expectEqual(0, pane.layers.lanes); try testing.expectEqual(@as(usize, 2), ch.pins.len); - // Bare again: `@`, the working copy's change, which (never snapshotted) touches nothing. + // Bare again: the pane's, shown again (jj not asked). p.update(.{ .command = "Changes" }); - try testing.expect(std.mem.indexOf(u8, told(p, id), "Changes: no change of `@` touches a.zig") != null); - try testing.expectEqual(@as(u8, 0), pane.layers.revset_len); - // jj's refusal, in its words. + try testing.expectEqual(levels, pane.layers.lanes); + try testing.expectEqual(ch, answered(p, pane.serial).?); + // jj's refusal, in its words; what was shown stays. p.update(.{ .command = "Changes nosuch" }); try testing.expect(std.mem.indexOf(u8, told(p, id), "Changes: Revision `nosuch` doesn't exist") != null); - try testing.expectEqual(@as(u8, 0), pane.layers.revset_len); + try testing.expectEqualStrings("@--::@-", answered(p, pane.serial).?.pinned()); + // `@`, the working copy's change, which (never snapshotted) touches nothing. + p.update(.{ .command = "Changes @" }); + try testing.expect(std.mem.indexOf(u8, told(p, id), "Changes: no change of `@` touches a.zig") != null); +} + +test "the pinned changes are the pane's, shown in a view by its own bit: another view's Changes shows its set in both, and its bare Changes hides them there alone" { + const gpa = testing.allocator; + var repo = try Repo.init(gpa) orelse return error.SkipZigTest; + defer repo.deinit(gpa); + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30, .windowed = false }); + defer p.deinit(); + var line: [4200]u8 = undefined; + p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}@@-", .{repo.file}) }); + const pane = p.panes[p.view().active].?; + const before = File.gutterWidth(pane); + const other = p.openView().?; + p.update(.{ .command = "Changes @--::@-" }); + try testing.expectEqual(before + levels, File.gutterWidth(pane)); + // A view of its own: nothing shown there until it asks. + p.toView(other); + try testing.expectEqual(0, pane.layers.lanes); + try testing.expectEqual(before, File.gutterWidth(pane)); + p.update(.{ .command = "Changes @-" }); + try testing.expectEqualStrings("@-", answered(p, pane.serial).?.pinned()); + try testing.expectEqual(@as(usize, 1), answered(p, pane.serial).?.pins.len); + // The first view shows the new set, not nothing. + p.toView(.at(0)); + try testing.expectEqual(levels, pane.layers.lanes); + // Hidden in the other view alone. + p.toView(other); + p.update(.{ .command = "Changes" }); + try testing.expectEqual(0, pane.layers.lanes); + p.toView(.at(0)); + try testing.expectEqual(levels, pane.layers.lanes); + try testing.expectEqual(before + levels, File.gutterWidth(pane)); } test "a client replays Changes from what the session's jj answered and ends equal" { @@ -825,9 +887,10 @@ test "a client replays Changes from what the session's jj answered and ends equa r.settle(); try testing.expect(r.diverged == null); const id = a.core.view().active; - try testing.expectEqual(@as(usize, 2), a.core.panes[id].?.changes.?.pins.len); - try testing.expectEqualSlices(Line, a.core.panes[id].?.changes.?.lines, r.core().panes[id].?.changes.?.lines); - try testing.expectEqualStrings("@--::@-", r.core().panes[id].?.layers.pinned()); + try testing.expectEqual(@as(usize, 2), answered(a.core, a.core.panes[id].?.serial).?.pins.len); + try testing.expectEqualSlices(Line, answered(a.core, a.core.panes[id].?.serial).?.lines, answered(r.core(), r.core().panes[id].?.serial).?.lines); + try testing.expectEqualStrings("@--::@-", answered(r.core(), r.core().panes[id].?.serial).?.pinned()); + try testing.expect(r.core().panes[id].?.layers.lanes > 0); try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core())); } @@ -849,7 +912,7 @@ test "Changes draws a lane a pinned change after the line number, nested ones a const pane = p.panes[id].?; const before = File.gutterWidth(pane); p.update(.{ .command = "Changes ::@" }); - try testing.expectEqual(@as(usize, 3), pane.changes.?.pins.len); + try testing.expectEqual(@as(usize, 3), answered(p, pane.serial).?.pins.len); const cells: u16 = if (windowed) 2 else levels; try testing.expectEqual(before + cells, File.gutterWidth(pane)); p.sync(); diff --git a/core/panes.zig b/core/panes.zig index ee03ccf2..8b152132 100644 --- a/core/panes.zig +++ b/core/panes.zig @@ -320,9 +320,6 @@ pub const Pane = struct { view: SessionView = .{}, /// The painters a file's body wears in this view (File.Layers). layers: File.Layers = .{}, - /// What jj answered for the last `Changes` in any view (jj.zig): the - /// pane's, so a client that joins late has it in the dump. - changes: ?*@import("jj.zig").Changes = null, sel: [3]Sel = @splat(.{}), pointer_selections: [3]?PointerSelection = @splat(null), next_pointer_selection: u64 = 0, @@ -1282,11 +1279,7 @@ pub fn teardownPane(p: *Pardes, pane: *Pane) void { pane.input.deinit(p.gpa); pane.jump.deinit(p.gpa); pane.places.deinit(p.gpa); - if (pane.changes) |changes| { - changes.deinit(p.gpa); - p.gpa.destroy(changes); - pane.changes = null; - } + @import("jj.zig").forget(p, pane.serial); if (pane.query) |q| { q.deinit(p.gpa); p.gpa.destroy(q); diff --git a/docs/typ/builtins-gui.json b/docs/typ/builtins-gui.json index b019eaee..af6f98ae 100644 --- a/docs/typ/builtins-gui.json +++ b/docs/typ/builtins-gui.json @@ -10,7 +10,7 @@ {"name": "Callstack", "leader": "SPC l b", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Show outermost callers first, with signatures and call sites (gc)."}, {"name": "CallstackDepth", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "Caller levels collected by Callstack, 1 through 64; default 8. Bare, it says the current limit."}, {"name": "Changelog", "leader": "SPC h c", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "This build's version and what changed to reach it, printed into an output buffer the same way Config prints the live settings."}, - {"name": "Changes", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Pin the changes `revset` names (jj; bare, `@`) on a file's pane in this view: a lane each after the line number, a line one added whole green; bare again, unpinned."}, + {"name": "Changes", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Pin the changes `revset` names (jj) on a file's pane and show them in this view: a lane each after the line number, a line one added whole green; bare, shown here or not (none pinned yet: `@`)."}, {"name": "ClipPaste", "leader": "SPC p", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Paste the system clipboard after the selection."}, {"name": "ClipPasteBefore", "leader": "SPC P", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Paste the system clipboard before the selection."}, {"name": "ClipReplace", "leader": "SPC R", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Replace the selection with the system clipboard."}, diff --git a/docs/typ/builtins-tui.json b/docs/typ/builtins-tui.json index 9d613189..90dbf091 100644 --- a/docs/typ/builtins-tui.json +++ b/docs/typ/builtins-tui.json @@ -10,7 +10,7 @@ {"name": "Callstack", "leader": "SPC l b", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Show outermost callers first, with signatures and call sites (gc)."}, {"name": "CallstackDepth", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": null, "doc": "Caller levels collected by Callstack, 1 through 64; default 8. Bare, it says the current limit."}, {"name": "Changelog", "leader": "SPC h c", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "This build's version and what changed to reach it, printed into an output buffer the same way Config prints the live settings."}, - {"name": "Changes", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Pin the changes `revset` names (jj; bare, `@`) on a file's pane in this view: a lane each after the line number, a line one added whole green; bare again, unpinned."}, + {"name": "Changes", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Pin the changes `revset` names (jj) on a file's pane and show them in this view: a lane each after the line number, a line one added whole green; bare, shown here or not (none pinned yet: `@`)."}, {"name": "ClipPaste", "leader": "SPC p", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Paste the system clipboard after the selection."}, {"name": "ClipPasteBefore", "leader": "SPC P", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Paste the system clipboard before the selection."}, {"name": "ClipReplace", "leader": "SPC R", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Replace the selection with the system clipboard."}, diff --git a/docs/typ/guide.typ b/docs/typ/guide.typ index db428d7f..6216b364 100644 --- a/docs/typ/guide.typ +++ b/docs/typ/guide.typ @@ -296,8 +296,9 @@ it last saw it (`@`): pardes never snapshots it. #word("Syntax") (#key("SPC t h")) turns a text's syntax colours off in this view, and on again. #word("Changes") with a revset pins its changes on a file's pane (or a -revision's) in this view; bare, `@`, the change against its parent, and -bare again, off. Each change that touched the file gets a lane after the +revision's) and shows them in this view (one set a pane: another view's +revset replaces it there too); bare, they are hidden in this view or shown +again, and with none pinned yet it is `@`, the change against its parent. Each change that touched the file gets a lane after the line number, from its first line to its last, in the theme's accents in hue order, oldest first; a change that rewrote lines inside another's steps a lane to the right on those rows; a line one added whole is green -- cgit v1.3 From a86e213e3e8053906df5ed4a37821c41a4afd932 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 21 Nov 2026 14:44:08 -0300 Subject: layers: `Changes` does not hold the loop (P43), in Stream.zig's model: the word records what is asked (`jj.Ask`: the pane by serial, the file, the revision annotated, the revset; `Stream.changes`, one at a time, one asked meanwhile in `changes_next`) and emits the `search` effect with a generation of its own (`jj.gen_bit`); the shell's worker (`jj.start`, through Stream.start) runs jj's two commands (the log with each change's diff of the file, the annotation) and posts their raw answers as ONE input (`Event.search`, its new `jj` field naming the pane: the log in `rows`, the annotation in `styles`, a refusal with `end` failed), which the step takes (`jj.receive`): the last asked is parsed (`jj.parse`: pins, provenance, hunks, nest) and pinned, an earlier one's or a closed pane's dropped, then the one asked meanwhile goes; a replica replays that input and never runs jj; a host with no workers (a test) runs both as sites on the loop, a host whose worker cannot start hands the answer in as an input; while it runs the pane says `Changes: jj…` and what it showed stays until the answer lands; round 3's `may_wait` row for `Changes` is gone (the far-client walk: nothing stops there now); tests through the replica's surface with a worker host: the word returns before jj answers and says so, the answer lands as one input and a client replaying it ends equal; a second Changes before the first's answer pins only the second's; the pane closed before the answer: nothing pinned, nothing kept (no leak); measured (ReleaseSafe, `Changes xpxluunz..pvtvmpzx` on core/replica.zig, 16 changes, 8,328 lines, 112 hunks, jj's answers taken by hand): the step that takes the answer holds the loop 2.3-2.8 ms, where the word held it 588-603 ms (jj's two runs, 253 and 349 ms here, are the worker's now); core-test 899/1059 (160 skipped), shell-test 1101/1104 (3 skipped) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/Stream.zig | 16 ++- core/jj.zig | 366 ++++++++++++++++++++++++++++++++++++++++++++++++------- core/replica.zig | 1 - core/root.zig | 2 +- 4 files changed, 336 insertions(+), 49 deletions(-) diff --git a/core/Stream.zig b/core/Stream.zig index f65d0683..80812840 100644 --- a/core/Stream.zig +++ b/core/Stream.zig @@ -25,6 +25,7 @@ const look = @import("look.zig"); const panes = @import("panes.zig"); const syntax = @import("syntax.zig"); const Pardes = pardes.Pardes; +const jj = @import("jj.zig"); pub const Kind = enum { grep, files }; pub const Engine = enum { rg, walk }; @@ -74,6 +75,10 @@ pub const Batch = struct { /// at `revision` from byte `start`, one syntax.Syn a byte. painted: ?struct { serial: u32, revision: u32, start: usize } = null, styles: []u8 = &.{}, + /// A `Changes` answer (jj.zig) for pane `jj`, by serial: jj's log in + /// `rows` and its annotate in `styles`, or its refusal in `rows` and + /// `end` failed. + jj: ?u32 = null, pub const End = enum { done, failed }; @@ -138,7 +143,7 @@ const TextTask = struct { /// A worker joined, the turn out for it as for any blocking call (it may /// be reading through a mount of this very session): canceled, or waited /// for once it has sent its last. -fn join(future: std.Io.Future(void), io: std.Io, how: enum { cancel, wait }) void { +pub fn join(future: std.Io.Future(void), io: std.Io, how: enum { cancel, wait }) void { pardes.turn.yield(); var f = future; if (how == .cancel) f.cancel(io) else f.await(io); @@ -254,8 +259,14 @@ rows_asked_at: u8 = 0, /// Rows asked for their colours while a 9P write was served: asked again /// on the next step (Query.produceAll). rows_later: bool = false, +/// The `Changes` asked of jj and its worker, the one asked while it ran, +/// and how many were asked (jj.zig: one at a time, the last one pinned). +changes: ?jj.Task = null, +changes_next: ?*jj.Ask = null, +changes_count: u32 = 0, pub fn deinit(s: *Stream, gpa: std.mem.Allocator) void { + jj.cancel(s); s.cancelTask(); s.cancelParse(); s.cancelPaint(); @@ -584,6 +595,7 @@ pub fn start(io: std.Io, gpa: std.mem.Allocator, p: *Pardes, gen: u32, ctx: ?*an }; return; } + if (gen & jj.gen_bit != 0) return jj.start(io, gpa, p, gen, ctx, sink); // A parse's generation: its own task. if (s.parse) |*t| if (gen == s.parse_gen and t.job.gen == gen and t.future == null) { t.job.out = gpa; @@ -637,6 +649,7 @@ pub fn runHere(p: *Pardes, gen: u32, comptime in_call: bool) void { }; return; } + if (gen & jj.gen_bit != 0) return jj.runHere(p, gen, in_call); const s = &p.stream; if (gen != s.gen or s.state != .searching) return; const job = makeJob(p.gpa, s) catch |err| { @@ -687,6 +700,7 @@ const Collect = struct { pub fn receive(p: *Pardes, b: *const Batch) void { const s = &p.stream; if (b.parsed) |parsed| return receiveParse(p, b, parsed.serial, parsed.revision); + if (b.jj) |serial| return jj.receive(p, b, serial); if (b.painted != null) return receivePaint(p, b); if (b.gen != s.gen or (s.state != .searching and s.state != .capped)) { s.dropped += 1; diff --git a/core/jj.zig b/core/jj.zig index b4d119e8..5f86dbe6 100644 --- a/core/jj.zig +++ b/core/jj.zig @@ -46,7 +46,7 @@ fn dirOf(path: []const u8) []const u8 { /// The name of `path` as a fileset of that one file in its directory, /// taken literally whatever it is called. -fn fileset(arena: std.mem.Allocator, path: []const u8) ![]const u8 { +fn fileset(arena: std.mem.Allocator, path: []const u8) ![]u8 { var set: std.ArrayList(u8) = .empty; try set.appendSlice(arena, "file:\""); for (std.Io.Dir.path.basename(path)) |c| { @@ -54,7 +54,7 @@ fn fileset(arena: std.mem.Allocator, path: []const u8) ![]const u8 { try set.append(arena, c); } try set.append(arena, '"'); - return set.items; + return set.toOwnedSlice(arena); } /// jj with `args`, run in `dir`: what it printed, or its refusal. The @@ -198,16 +198,17 @@ pub fn looked(p: *Pardes, id: usize, dir: []const u8, text: []const u8, at: look } // ---- `Changes [revset]` (PARDES.md: pinned changes as lanes): what jj -// answers for it, kept as flat arrays in the pane ---- - -/// What jj answered for a pane's `Changes`: replicated state, the session's -/// (`Pardes.changes`, by the pane's serial: a client never runs jj; one that -/// joins late has it in the dump), its revset with it, drawn by each view that shows them (File.Layers.lanes: -/// a view holds that bit, not the revset; one set a pane, so a view's -/// `Changes other` replaces what every view shows). Two jj runs, each a -/// site of the step's tape: the changes with their diffs of the file -/// (`jj log -p --git`, the diffs read with diff.zig's walk), and who wrote -/// each line of the shown revision (`jj file annotate`). +// answers for it, kept as flat arrays, the session's ---- + +/// What jj answered for a pane's `Changes`: replicated state, the +/// session's (`Pardes.changes`, by the pane's serial: a client never runs +/// jj; one that joins late has it in the dump), its revset with it, drawn +/// by each view that shows them (File.Layers.lanes: a view holds that, not +/// the revset; one set a pane, so a view's `Changes other` replaces what +/// every view shows). From two jj runs off the loop (`Ask`): the changes +/// with their diffs of the file (`jj log -p --git`, the diffs read with +/// diff.zig's walk), and who wrote each line of the shown revision (`jj +/// file annotate`). pub const Changes = struct { pub const replica = .{ .len = .{.{ "revset", "revset_len" }} }; /// The pane's (its serial). @@ -329,17 +330,208 @@ pub fn changesWord(c: pardes.builtins.Ctx) void { .{ .path = f.path, .rev = "@" } else return p.reportFailure(c.id, "Changes: only a file's pane takes it"); + pane.layers.lanes = cells; + ask(p, c.id, pane.serial, shown.path, shown.rev, revset); +} + +// ---- jj off the loop (Stream.zig's model) ---- + +/// A `Changes` asked of jj: the pane (by serial), the file it shows and the +/// revision whose lines are annotated, the revset. Its two runs go on a +/// worker where the host has one (the `search` effect: Stream.start), their +/// raw answers back as one input (`Event.search`, its `jj` set) stamped +/// with its generation, which the step takes (`receive`): a replica replays +/// that input and never runs jj. With no worker (a test), on the loop, each +/// run a site of the step's tape. +pub const Ask = struct { + gpa: std.mem.Allocator, + /// What its answer is made with: the shell's, which frees a batch. + out: std.mem.Allocator, + gen: u32, + serial: u32, + path: []u8, + rev: []u8, + revset: []u8, + + fn make(gpa: std.mem.Allocator, gen: u32, serial: u32, path: []const u8, rev: []const u8, revset: []const u8) error{OutOfMemory}!*Ask { + const a = try gpa.create(Ask); + errdefer gpa.destroy(a); + const owned = try std.mem.concat(gpa, u8, &.{ path, rev, revset }); + a.* = .{ .gpa = gpa, .out = gpa, .gen = gen, .serial = serial, .path = owned[0..path.len], .rev = owned[path.len..][0..rev.len], .revset = owned[path.len + rev.len ..] }; + return a; + } + + pub fn deinit(a: *Ask) void { + a.gpa.free(a.path.ptr[0 .. a.path.len + a.rev.len + a.revset.len]); + a.gpa.destroy(a); + } +}; + +/// The `Changes` asked and its worker (`Stream.changes`), one at a time: +/// one asked while it runs waits (`Stream.changes_next`), and only the last +/// asked is pinned. +pub const Task = struct { + // The worker the host started for it, live: a replica has none. + pub const replica = .{ .authority = .{ "future", "io" } }; + ask: *Ask, + future: ?std.Io.Future(void) = null, + io: ?std.Io = null, +}; + +/// A `Changes` generation has this bit (a search's and a parse's count +/// from 0; a paint's has the top one). +pub const gen_bit: u32 = 1 << 29; + +fn liveGen(s: *const pardes.Stream) u32 { + return gen_bit | (s.changes_count & (gen_bit - 1)); +} + +/// Ask jj of `revset` for pane `serial` (said at pane `id` while it runs): +/// what the pane shows stays until the answer lands. +fn ask(p: *Pardes, id: usize, serial: u32, path: []const u8, rev: []const u8, revset: []const u8) void { + const s = &p.stream; + s.changes_count +%= 1; + const a = Ask.make(p.gpa, liveGen(s), serial, path, rev, revset) catch return p.reportFailure(id, "Changes: out of memory"); + p.setStatus(.at(id), "Changes: jj\u{2026}"); + if (s.changes != null) { + if (s.changes_next) |old| old.deinit(); + s.changes_next = a; + return; + } + go(p, a); +} + +fn go(p: *Pardes, a: *Ask) void { + p.stream.changes = .{ .ask = a }; + if (p.tape.has(p, .search)) return p.emit(.{ .search = .{ .gen = a.gen } }); + runHere(p, a.gen, false); +} + +/// The host's `search` effect for a `Changes` generation (Stream.start): +/// its runs on a worker that sends to `sink`. +pub fn start(io: std.Io, gpa: std.mem.Allocator, p: *Pardes, gen: u32, ctx: ?*anyopaque, sink: pardes.Stream.Sink) void { + const t = if (p.stream.changes) |*t| t else return; + if (t.ask.gen != gen or t.future != null) return; + t.ask.out = gpa; + // No worker to be had: here, its answer an input. + t.future = io.concurrent(work, .{ t.ask, ctx, sink }) catch return runHere(p, gen, true); + t.io = io; +} + +fn work(a: *Ask, ctx: ?*anyopaque, sink: pardes.Stream.Sink) void { + const b = answer(null, a.out, a); + if (!sink(ctx, b)) b.deinit(a.out); +} + +/// With no worker: the runs here, each a site (a replica replays them). +/// `in_call`: in the host's `search` entry, the answer handed in as an +/// input, as a worker's is. +pub fn runHere(p: *Pardes, gen: u32, comptime in_call: bool) void { + const t = p.stream.changes orelse return; + if (t.ask.gen != gen or t.future != null) return; + const b = answer(p, p.gpa, t.ask); + defer b.deinit(p.gpa); + if (in_call) p.update(.{ .search = b }) else receive(p, &b, t.ask.serial); +} + +/// jj's two answers for `a`, raw, in `gpa`: through `p`'s tape when given +/// (on the loop), else run here (a worker). +fn answer(p: ?*Pardes, gpa: std.mem.Allocator, a: *const Ask) pardes.Stream.Batch { + const failed = struct { + fn f(g: std.mem.Allocator, at: *const Ask, why: []u8) pardes.Stream.Batch { + _ = g; + return .{ .gen = at.gen, .jj = at.serial, .rows = why, .end = .failed }; + } + }.f; + const set = fileset(gpa, a.path) catch return failed(gpa, a, refusal(gpa, "out of memory").refused); + defer gpa.free(set); + // The changes, oldest first, each with its diff of the file: one run. + const query = std.fmt.allocPrint(gpa, "({s}) & files({s})", .{ a.revset, set }) catch return failed(gpa, a, refusal(gpa, "out of memory").refused); + defer gpa.free(query); + const log_args = [_][]const u8{ "log", "--no-graph", "--reversed", "-r", query, "-T", log_template, "--git", "--context=0", "--", set }; + const logged = switch (runJj(p, gpa, dirOf(a.path), &log_args)) { + .refused => |why| return failed(gpa, a, why), + .bytes => |bytes| bytes, + }; + var it = std.mem.splitScalar(u8, logged, '\n'); + const any = while (it.next()) |l| { + if (pinOf(l) != null) break true; + } else false; + if (!any) return .{ .gen = a.gen, .jj = a.serial, .rows = logged, .end = .done }; + // Who wrote each line: a path, not a fileset (annotate takes one file + // as it is named). + const annotate_args = [_][]const u8{ "file", "annotate", "-r", a.rev, "-T", "commit.change_id().short(8) ++ \"\\n\"", "--", std.Io.Dir.path.basename(a.path) }; + return switch (runJj(p, gpa, dirOf(a.path), &annotate_args)) { + .refused => |why| { + gpa.free(logged); + return failed(gpa, a, why); + }, + .bytes => |annotated| .{ .gen = a.gen, .jj = a.serial, .rows = logged, .styles = annotated, .end = .done }, + }; +} + +fn runJj(p: ?*Pardes, gpa: std.mem.Allocator, dir: []const u8, args: []const []const u8) Shown { + return if (p) |q| q.tape.site(.jj, gpa, runHost, .{ gpa, dir, args }) else runHost(gpa, dir, args); +} + +/// A `Changes` answer (`Event.search`, its `jj` set), borrowed: the last +/// asked's is parsed and pinned on its pane; an earlier one's, or a gone +/// pane's, dropped. Then the one asked meanwhile goes. +pub fn receive(p: *Pardes, b: *const pardes.Stream.Batch, serial: u32) void { + const s = &p.stream; + var revset: [Changes.revset_max]u8 = undefined; + var revset_len: usize = 0; + if (s.changes) |t| if (t.ask.gen == b.gen) { + s.changes = null; + if (t.future) |f| pardes.Stream.join(f, t.io.?, .wait); + revset_len = t.ask.revset.len; + @memcpy(revset[0..revset_len], t.ask.revset); + t.ask.deinit(); + }; + defer if (s.changes == null) if (s.changes_next) |next| { + s.changes_next = null; + go(p, next); + }; + if (b.gen != liveGen(s) or revset_len == 0) return; + const id = p.paneBySerial(serial) orelse return; + pinAnswer(p, id, b, revset[0..revset_len]); +} + +/// The session's end: the worker canceled, the asks let go. +pub fn cancel(s: *pardes.Stream) void { + if (s.changes) |t| { + s.changes = null; + if (t.future) |f| pardes.Stream.join(f, t.io.?, .cancel); + t.ask.deinit(); + } + if (s.changes_next) |a| { + s.changes_next = null; + a.deinit(); + } +} + +/// jj's answer `b` for `revset` parsed and pinned on pane `id`, or its +/// refusal said there. +fn pinAnswer(p: *Pardes, id: usize, b: *const pardes.Stream.Batch, revset: []const u8) void { + const pane = p.panes[id].?; var line: pardes.Kind.Buf(512) = .{}; - var got = read(p, shown.path, shown.rev, revset, f.content) catch |err| return p.reportFailure(c.id, line.print("Changes: {s}", .{@errorName(err)})); + const f = if (pane.file) |*file| file else return; + // Nothing pinned yet: no gutter for it. + defer if (answered(p, pane.serial) == null) { + pane.layers.lanes = 0; + }; + if (b.end == .failed) return p.reportFailure(id, line.print("Changes: {s}", .{b.rows[0..@min(b.rows.len, 480)]})); + var got = parse(p.gpa, p.scratch.allocator(), b.rows, b.styles, f.content) catch |err| return p.reportFailure(id, line.print("Changes: {s}", .{@errorName(err)})); switch (got) { .refused => |why| { defer p.gpa.free(why); - return p.reportFailure(c.id, line.print("Changes: {s}", .{why[0..@min(why.len, 480)]})); + return p.reportFailure(id, line.print("Changes: {s}", .{why[0..@min(why.len, 480)]})); }, .read => |*changes| { if (changes.pins.len == 0) { changes.deinit(p.gpa); - return p.reportFailure(c.id, line.print("Changes: no change of `{s}` touches {s}", .{ revset, std.Io.Dir.path.basename(shown.path) })); + const shown = if (of(f)) |r| r.path else f.path; + return p.reportFailure(id, line.print("Changes: no change of `{s}` touches {s}", .{ revset, std.Io.Dir.path.basename(shown) })); } @memcpy(changes.revset[0..revset.len], revset); changes.revset_len = @intCast(revset.len); @@ -349,34 +541,22 @@ pub fn changesWord(c: pardes.builtins.Ctx) void { kept.* = changes.*; } else p.changes.append(p.gpa, changes.*) catch { changes.deinit(p.gpa); - return p.reportFailure(c.id, "Changes: out of memory"); + return p.reportFailure(id, "Changes: out of memory"); }; - pane.layers.lanes = cells; + p.setStatus(.at(id), ""); }, } } const Read = union(enum) { refused: []u8, read: Changes }; -/// What jj says of `revset`'s changes in `path` (absolute) at `rev`, whose -/// text is `text` (what the pane shows: a line is matched to the line its -/// change added by its text). -fn read(p: *Pardes, path: []const u8, rev: []const u8, revset: []const u8, text: []const u8) error{OutOfMemory}!Read { - const gpa = p.gpa; - const arena = p.scratch.allocator(); - const set = try fileset(arena, path); - const dir = dirOf(path); +/// jj's answers parsed: `logged` (the pins, each with its diff of the +/// file) and `annotated` (who wrote each line of `text`, what the pane +/// shows: a line is matched to the line its change added by its text). +fn parse(gpa: std.mem.Allocator, arena: std.mem.Allocator, logged: []const u8, annotated: []const u8, text: []const u8) error{OutOfMemory}!Read { var out: Changes = .{ .serial = 0 }; var kept = false; defer if (!kept) out.deinit(gpa); - // The changes, oldest first, each with its diff of the file: one run. - const query = try std.fmt.allocPrint(arena, "({s}) & files({s})", .{ revset, set }); - const log_args = [_][]const u8{ "log", "--no-graph", "--reversed", "-r", query, "-T", log_template, "--git", "--context=0", "--", set }; - const logged = switch (p.tape.site(.jj, gpa, runHost, .{ gpa, dir, @as([]const []const u8, &log_args) })) { - .refused => |why| return .{ .refused = why }, - .bytes => |b| b, - }; - defer gpa.free(logged); var pins: std.ArrayList(Pin) = .empty; defer pins.deinit(gpa); // Where each pin's diff starts in `logged`, and the end. @@ -393,12 +573,6 @@ fn read(p: *Pardes, path: []const u8, rev: []const u8, revset: []const u8, text: kept = true; return .{ .read = out }; } - // Who wrote each line. - const annotated = switch (annotate(p, path, rev)) { - .refused => |why| return .{ .refused = why }, - .bytes => |b| b, - }; - defer gpa.free(annotated); out.lines = try provenance(gpa, annotated, out.pins); // Each change's hunks, and which of its lines it added whole. var hunks: std.ArrayList(Hunk) = .empty; @@ -434,13 +608,6 @@ fn pinOf(l: []const u8) ?Pin { return pin; } -/// Who last wrote each line of `path` (absolute) at `rev`: a change id -/// (`change_id.short(8)`) a line, as `jj file annotate` says it. -pub fn annotate(p: *Pardes, path: []const u8, rev: []const u8) Shown { - // A path, not a fileset (annotate takes one file as it is named). - return p.tape.site(.jj, p.gpa, runHost, .{ p.gpa, dirOf(path), @as([]const []const u8, &.{ "file", "annotate", "-r", rev, "-T", "commit.change_id().short(8) ++ \"\\n\"", "--", std.Io.Dir.path.basename(path) }) }); -} - /// Which pin wrote each line: a value a line, from `annotated` /// (`annotate`'s answer); `whole` is the hunks' to say. The caller's, in /// `gpa`. @@ -894,6 +1061,113 @@ test "a client replays Changes from what the session's jj answered and ends equa try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core())); } +/// A session whose `Changes` runs on a worker (Stream.start), as a shell's +/// does, its answer posted to an inbox, with a client of it. +const WorkerJj = struct { + const Inbox = @import("dev").host_io.Inbox; + const R = pardes.replica; + /// The host's: where its worker posts, and the core it starts for. + const Shell = struct { q: Inbox, core: ?*Pardes = null }; + shell: *Shell, + a: *R.Authority, + r: *R.Replica, + /// The revision `@-` of the repository's `a.zig`, open. + id: usize, + serial: u32, + + fn search(ctx: ?*anyopaque, gen: u32) void { + const shell: *Shell = @ptrCast(@alignCast(ctx.?)); + pardes.Stream.start(testing.io, testing.allocator, shell.core.?, gen, &shell.q, Inbox.pushSearch); + } + const vtable: pardes.Host.VTable = .{ .search = search }; + + fn init(repo: *const Repo) !WorkerJj { + const shell = try testing.allocator.create(Shell); + shell.* = .{ .q = .{ .gpa = testing.allocator, .lsp_allocator = testing.allocator, .io = testing.io } }; + const a = try R.Authority.init(testing.allocator, .{ .cols = 80, .rows = 24 }, .{ .vtable = &vtable, .ctx = shell }, false); + errdefer a.deinit(); + shell.core = a.core; + const r = try R.Replica.init(testing.allocator, 1, try a.unit(0, 0), false); + var line: [4200]u8 = undefined; + r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}@@-", .{repo.file}) })); + const id = a.core.view().active; + return .{ .shell = shell, .a = a, .r = r, .id = id, .serial = a.core.panes[id].?.serial }; + } + + fn deinit(w: *WorkerJj) void { + w.r.deinit(); + w.a.deinit(); + w.shell.q.deinit(); + testing.allocator.destroy(w.shell); + } + + fn word(w: *WorkerJj, text: []const u8) !void { + w.r.confirm(try w.a.local(.{ .command = text })); + w.r.settle(); + } + + /// Until no `Changes` is asked or running (five seconds at most): each + /// answer the session's input, as its loop hands it, and the client's. + fn land(w: *WorkerJj) !void { + var waited: u32 = 0; + while (w.a.core.stream.changes != null or w.a.core.stream.changes_next != null) : (waited += 1) { + if (waited == 5000) return error.Timeout; + var batch: Inbox.Batch = .{}; + w.shell.q.takeInto(&batch); + for (batch.slice()) |m| switch (m) { + .search => |b| { + defer b.deinit(testing.allocator); + w.r.confirm(try w.a.local(.{ .search = b })); + w.r.settle(); + }, + else => m.deinit(testing.allocator, testing.allocator), + }; + testing.io.sleep(.fromMilliseconds(1), .awake) catch {}; + } + try testing.expect(w.r.diverged == null); + try testing.expectEqual(pardes.tape.digestOf(w.a.core), pardes.tape.digestOf(w.r.core())); + } +}; + +test "Changes asks jj on a worker: the word says so and returns, its answer lands as one input and pins; a client replays that input and ends equal" { + var repo = try Repo.init(testing.allocator) orelse return error.SkipZigTest; + defer repo.deinit(testing.allocator); + var w = try WorkerJj.init(&repo); + defer w.deinit(); + try w.word("Changes @--::@-"); + // Asked, not answered: the word did not wait for jj. + try testing.expect(answered(w.a.core, w.serial) == null); + try testing.expect(std.mem.indexOf(u8, told(w.a.core, w.id), "Changes: jj") != null); + try w.land(); + try testing.expectEqual(@as(usize, 2), answered(w.a.core, w.serial).?.pins.len); + try testing.expectEqualSlices(Line, answered(w.a.core, w.serial).?.lines, answered(w.r.core(), w.serial).?.lines); +} + +test "a second Changes before the first's answer: only the second's pins" { + var repo = try Repo.init(testing.allocator) orelse return error.SkipZigTest; + defer repo.deinit(testing.allocator); + var w = try WorkerJj.init(&repo); + defer w.deinit(); + try w.word("Changes @--::@-"); + try w.word("Changes @-"); + try w.land(); + const ch = answered(w.a.core, w.serial).?; + try testing.expectEqualStrings("@-", ch.pinned()); + try testing.expectEqual(@as(usize, 1), ch.pins.len); +} + +test "the pane closed before its Changes answer: nothing pinned, nothing kept" { + var repo = try Repo.init(testing.allocator) orelse return error.SkipZigTest; + defer repo.deinit(testing.allocator); + var w = try WorkerJj.init(&repo); + defer w.deinit(); + try w.word("Changes @--::@-"); + try w.word("Del"); + try testing.expect(w.a.core.panes[w.id] == null or w.a.core.panes[w.id].?.serial != w.serial); + try w.land(); + try testing.expectEqual(@as(usize, 0), w.a.core.changes.items.len); +} + test "Changes draws a lane a pinned change after the line number, nested ones a level to the right on their rows only, and a line one added whole green across it; bare again, the gutter as it was" { const gpa = testing.allocator; // `fn` wrote the function; `mid` rewrote its lines 3-4 as 3-6 (two diff --git a/core/replica.zig b/core/replica.zig index dd3f13d1..97da9c74 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -6583,7 +6583,6 @@ const may_wait = [_]Wait{ .{ .what = "Mini *", .on = .any, .stop = "resolve", .why = "a file opened by name, from the session's disk" }, .{ .what = "Get", .on = .any, .stop = "read_file", .why = "the file read again from the session's disk" }, .{ .what = "Save", .on = .any, .stop = "write_file", .why = "a save" }, - .{ .what = "Changes", .on = .any, .stop = "jj", .why = "what jj says of the pinned changes, the session's (P14: a word typed may take a moment once)" }, // A program run, a shell opened or closed: the session's processes. .{ .what = "Exec *", .on = .any, .stop = "kind", .why = "a program run: its name asked of the disk first" }, .{ .what = "Exec *", .on = .any, .stop = "tty_taken", .why = "a program run in a shell: whether one has it, the session's" }, diff --git a/core/root.zig b/core/root.zig index de1c44b0..5c91afd1 100644 --- a/core/root.zig +++ b/core/root.zig @@ -629,7 +629,7 @@ const machine_lines = [_]struct { []const u8, usize, []const u8 }{ .{ "exec.zig", 3, "kindOf's stat (tape.site(.kind), its io the tape's) and Shell's check (tape.site(.shell))" }, .{ "fs.zig", 38, "the file system behind the tape's sites (open, read, write, stat, mkdir, access; their io the tape's), the process's home (read once at the start, taped), the 9P transport" }, .{ "hunks.zig", 1, "a test helper's file read" }, - .{ "jj.zig", 8, "jj run under tape.site(.jj) on an io of its own (the tape's spawns nothing) with this process's environment, the signal mask cleared as Stream's children's: the session's, a replica replays its answer" }, + .{ "jj.zig", 9, "jj run under tape.site(.jj) on an io of its own (the tape's spawns nothing) with this process's environment, the signal mask cleared as Stream's children's: the session's, a replica replays its answer; or on a worker for `Changes`, its answer an input; a test's shell inbox (dev)" }, .{ "look.zig", 6, "openLink's fork (the host's: a view's frontend opens a link) and a remote's error name" }, .{ "memory.zig", 7, "the memory regions themselves (mmap, madvise, their locks)" }, .{ "replica.zig", 75, "the client and session engines: sockets, threads, clocks, the blob cache, traces" }, -- cgit v1.3 From 2b9da7be7d9520701b24d46d8db2ec56517b45b8 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 21 Nov 2026 15:15:41 -0300 Subject: layers: the lanes tell the truth about the text in the pane: jj annotates its last snapshot (`--ignore-working-copy`), not the keys typed since, so annotate's answer now carries each line's text (`id\tcontent`, the same one run) and `jj.provenance` lines the annotated text up with the pane's by what the two agree on at either end (`File.spanOf`, the editor's differ; the one line its two ends meet inside counts when its bytes agree: an inserted line shares its indent with the line after it), a line only the pane has nobody's (no lane, no ground); and an edit after `Changes` carries the per-line values with the lines (`jj.edited`: one call in `File.edit`, the one place a text changes, an undo's too, made only while the session has pinned changes): the lines a splice takes out take their values with them, a line it puts in is nobody's, and a splice that starts in a line's leading blanks (as `o` puts a line in) leaves that line's value after what it puts in; jj is never asked again on a key; tests: a line on disk jj has not snapshotted is nobody's and the lines after it keep their changes; a line typed in a nested block (`o`) is nobody's and the rows around keep their lanes, its undo puts the values back, a deleted line takes its value, a client replaying the keys ends equal; core-test 901/1061 (160 skipped), shell-test 1103/1106 (3 skipped) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/File.zig | 2 + core/jj.zig | 206 +++++++++++++++++++++++++++++++++++++++++++++++++++++----- 2 files changed, 192 insertions(+), 16 deletions(-) diff --git a/core/File.zig b/core/File.zig index 6e44f85e..ae052344 100644 --- a/core/File.zig +++ b/core/File.zig @@ -756,6 +756,8 @@ fn edit(p: *Pardes, f: *State, off: usize, len: usize, bytes_in: []const u8, who }; }; reportEdit(p, f, off, len, bytes); + // A pinned change's per-line values ride with the lines (jj.zig). + if (p.changes.items.len > 0) @import("jj.zig").edited(p, f, off, len, bytes); if (f.mini) |*mini| mini.deinit(p.gpa); f.mini = null; if (f.line_starts.len > 0) shiftIndex(p.gpa, f, off, len, bytes); diff --git a/core/jj.zig b/core/jj.zig index 5f86dbe6..a381443c 100644 --- a/core/jj.zig +++ b/core/jj.zig @@ -460,7 +460,7 @@ fn answer(p: ?*Pardes, gpa: std.mem.Allocator, a: *const Ask) pardes.Stream.Batc if (!any) return .{ .gen = a.gen, .jj = a.serial, .rows = logged, .end = .done }; // Who wrote each line: a path, not a fileset (annotate takes one file // as it is named). - const annotate_args = [_][]const u8{ "file", "annotate", "-r", a.rev, "-T", "commit.change_id().short(8) ++ \"\\n\"", "--", std.Io.Dir.path.basename(a.path) }; + const annotate_args = [_][]const u8{ "file", "annotate", "-r", a.rev, "-T", "commit.change_id().short(8) ++ \"\\t\" ++ content", "--", std.Io.Dir.path.basename(a.path) }; return switch (runJj(p, gpa, dirOf(a.path), &annotate_args)) { .refused => |why| { gpa.free(logged); @@ -497,6 +497,50 @@ pub fn receive(p: *Pardes, b: *const pardes.Stream.Batch, serial: u32) void { pinAnswer(p, id, b, revset[0..revset_len]); } +/// A splice of `f`'s text, before its bytes go in (File.edit, the one +/// place a text changes, an undo's too): each pane showing it that has +/// pins keeps a value for each of its lines, so the values ride with the +/// lines, never asking jj again: the lines a splice takes out take their +/// values with them, and a line it puts in is nobody's. +pub fn edited(p: *Pardes, f: *const File.State, off: usize, len: usize, bytes: []const u8) void { + var i = p.changes.items.len; + while (i > 0) { + i -= 1; + const c = &p.changes.items[i]; + const id = p.paneBySerial(c.serial) orelse continue; + const shown = if (p.panes[id].?.file) |*shown| shown else continue; + if (shown.content.ptr != f.content.ptr) continue; + splice(p.gpa, c, f.content, off, len, bytes) catch { + // No room for it: its values would lie, so it goes. + c.deinit(p.gpa); + _ = p.changes.swapRemove(i); + }; + } +} + +/// `c`'s values spliced as `text`'s lines are by the splice of `len` bytes +/// at `off` for `bytes`. A splice that starts in a line's leading blanks +/// (at its start, or after its indent, as `o` puts a line in) leaves that +/// line's text after what it puts in: the lines it takes and puts come +/// before it. Else the line it starts in keeps its value, and the lines +/// taken and put come after it. +fn splice(gpa: std.mem.Allocator, c: *Changes, text: []const u8, off: usize, len: usize, bytes: []const u8) error{OutOfMemory}!void { + const taken = std.mem.count(u8, text[off..][0..len], "\n"); + const put = std.mem.count(u8, bytes, "\n"); + if (taken == 0 and put == 0) return; + const line_start = if (std.mem.lastIndexOfScalar(u8, text[0..off], '\n')) |nl| nl + 1 else 0; + const in_lead = std.mem.trimStart(u8, text[line_start..off], " \t").len == 0; + const from = std.mem.count(u8, text[0..line_start], "\n") + @intFromBool(!in_lead); + if (from > c.lines.len) return; + const take = @min(taken, c.lines.len - from); + const next = try gpa.alloc(Line, c.lines.len - take + put); + @memcpy(next[0..from], c.lines[0..from]); + @memset(next[from..][0..put], .{ .pin = .none }); + @memcpy(next[from + put ..], c.lines[from + take ..]); + gpa.free(c.lines); + c.lines = next; +} + /// The session's end: the worker canceled, the asks let go. pub fn cancel(s: *pardes.Stream) void { if (s.changes) |t| { @@ -573,7 +617,7 @@ fn parse(gpa: std.mem.Allocator, arena: std.mem.Allocator, logged: []const u8, a kept = true; return .{ .read = out }; } - out.lines = try provenance(gpa, annotated, out.pins); + out.lines = try provenance(gpa, arena, annotated, out.pins, text); // Each change's hunks, and which of its lines it added whole. var hunks: std.ArrayList(Hunk) = .empty; defer hunks.deinit(gpa); @@ -608,22 +652,67 @@ fn pinOf(l: []const u8) ?Pin { return pin; } -/// Which pin wrote each line: a value a line, from `annotated` -/// (`annotate`'s answer); `whole` is the hunks' to say. The caller's, in -/// `gpa`. -pub fn provenance(gpa: std.mem.Allocator, annotated: []const u8, pins: []const Pin) error{OutOfMemory}![]Line { - var out: std.ArrayList(Line) = .empty; - errdefer out.deinit(gpa); - var lines = std.mem.splitScalar(u8, annotated, '\n'); - while (lines.next()) |id| { +/// Which pin wrote each line of `text` (what the pane shows: `whole` is the +/// hunks' to say), a value a line, the caller's in `gpa`, from `annotated` +/// (`jj file annotate`'s answer: an id, a tab and the line, a line each, of +/// the revision it annotated, which is jj's last snapshot of a file and +/// not the keys typed since): the two texts lined up by what they agree on +/// at either end (`File.spanOf`, the editor's differ: a line inside both +/// ends keeps its owner, a line only the pane has is nobody's). +pub fn provenance(gpa: std.mem.Allocator, arena: std.mem.Allocator, annotated: []const u8, pins: []const Pin, text: []const u8) error{OutOfMemory}![]Line { + var owners: std.ArrayList(PinIndex) = .empty; + var was: std.ArrayList(u8) = .empty; + var rows = std.mem.splitScalar(u8, annotated, '\n'); + while (rows.next()) |row| { // The empty text after the last newline is no line. - if (id.len == 0 and lines.peek() == null) break; - const at: PinIndex = for (pins, 0..) |pin, i| { - if (std.mem.eql(u8, &pin.id, id)) break @enumFromInt(i); - } else .none; - try out.append(gpa, .{ .pin = at }); + if (row.len == 0 and rows.peek() == null) break; + const tab = std.mem.indexOfScalar(u8, row, '\t') orelse row.len; + try owners.append(arena, for (pins, 0..) |pin, i| { + if (std.mem.eql(u8, &pin.id, row[0..tab])) break @enumFromInt(i); + } else .none); + try was.appendSlice(arena, row[@min(tab + 1, row.len)..]); + try was.append(arena, '\n'); + } + if (!std.mem.endsWith(u8, annotated, "\n") and was.items.len > 0) was.items.len -= 1; + const out = try gpa.alloc(Line, lineCount(text)); + @memset(out, .{ .pin = .none }); + if (std.mem.eql(u8, was.items, text)) { + for (out[0..@min(out.len, owners.items.len)], owners.items[0..@min(out.len, owners.items.len)]) |*l, pin| l.pin = pin; + return out; } - return out.toOwnedSlice(gpa); + const span = File.spanOf(was.items, text); + const head = @min(std.mem.count(u8, was.items[0..span.head], "\n"), out.len, owners.items.len); + for (out[0..head], owners.items[0..head]) |*l, pin| l.pin = pin; + var tail = @min(tailLines(was.items, span.tail), out.len - head, owners.items.len - head); + // The line the two ends meet inside (an insertion before it shares its + // indent with the line above) is the same line when its bytes are. + if (head + tail < @min(out.len, owners.items.len) and std.mem.eql(u8, lineFromEnd(was.items, tail), lineFromEnd(text, tail))) tail += 1; + for (out[out.len - tail ..], owners.items[owners.items.len - tail ..]) |*l, pin| l.pin = pin; + return out; +} + +/// `text`'s line `k` from its end (0: its last). +fn lineFromEnd(text: []const u8, k: usize) []const u8 { + var end = text.len - @intFromBool(std.mem.endsWith(u8, text, "\n")); + for (0..k) |_| end = (std.mem.lastIndexOfScalar(u8, text[0..end], '\n') orelse return ""); + const from = if (std.mem.lastIndexOfScalar(u8, text[0..end], '\n')) |nl| nl + 1 else 0; + return text[from..end]; +} + +/// The lines of `text`: one after each newline but a last one, as the +/// annotation numbers them. +fn lineCount(text: []const u8) usize { + return std.mem.count(u8, text, "\n") + @intFromBool(text.len > 0 and text[text.len - 1] != '\n'); +} + +/// How many of `text`'s lines lie whole in its last `tail` bytes. +fn tailLines(text: []const u8, tail: usize) usize { + if (tail == 0) return 0; + const from = text.len - tail; + // A line starts at `from`, and after each newline in the tail but the + // text's last byte. + const starts = if (from == 0) 1 else @intFromBool(text[from - 1] == '\n'); + return starts + std.mem.count(u8, text[from .. text.len - 1], "\n"); } /// Pin `k`'s hunks in `diffed` (its diff of the file, `--git --context=0`) onto @@ -1234,6 +1323,91 @@ test "Changes draws a lane a pinned change after the line number, nested ones a } } +/// A function three changes wrote: `fn` all of it, `mid` its lines 3-6 +/// (rewriting two, adding two), `shift` line 4 again. +const Stack = struct { + const fn_text = "fn f() void {\n a();\n b();\n c();\n g();\n h();\n i();\n}\n"; + const mid_text = "fn f() void {\n a();\n b2();\n c2();\n x();\n y();\n g();\n h();\n i();\n}\n"; + const shift_text = "fn f() void {\n a();\n b2();\n c3();\n x();\n y();\n g();\n h();\n i();\n}\n"; + /// Who wrote each of shift_text's lines: fn 0, mid 1, shift 2. + const pins = [_]u16{ 0, 0, 1, 2, 1, 1, 0, 0, 0, 0 }; + + fn repo(working: ?[]const u8) !?Repo { + return Repo.with(testing.allocator, &.{ .{ fn_text, "fn" }, .{ mid_text, "mid" }, .{ shift_text, "shift" } }, working); + } +}; + +fn pinsOf(ch: *const Changes, out: []u16) []u16 { + for (ch.lines, out[0..ch.lines.len]) |l, *o| o.* = @intFromEnum(l.pin); + return out[0..ch.lines.len]; +} + +test "Changes lines jj's annotation up with the pane's text: a line jj has not seen (typed, not snapshotted) is nobody's, the lines after it keep their changes" { + // The file on disk has a line more than jj's last snapshot of it. + const working = "fn f() void {\n a();\n b2();\n c3();\n x();\n new();\n y();\n g();\n h();\n i();\n}\n"; + var repo = try Stack.repo(working) orelse return error.SkipZigTest; + defer repo.deinit(testing.allocator); + const p = try Pardes.init(testing.allocator, .{ .tty_only = true, .cols = 60, .rows = 24, .windowed = false }); + defer p.deinit(); + var line: [4200]u8 = undefined; + p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) }); + const pane = p.panes[p.view().active].?; + try testing.expectEqualStrings(working, pane.file.?.content); + p.update(.{ .command = "Changes ::@" }); + const none = @intFromEnum(PinIndex.none); + var got: [16]u16 = undefined; + try testing.expectEqualSlices(u16, &.{ 0, 0, 1, 2, 1, none, 1, 0, 0, 0, 0 }, pinsOf(answered(p, pane.serial).?, &got)); +} + +test "the lanes ride with the text: a line typed in a nested block is nobody's, its undo puts the values back, a deleted line takes its value; a client replays it equal" { + var repo = try Stack.repo(null) orelse return error.SkipZigTest; + defer repo.deinit(testing.allocator); + const R = pardes.replica; + const a = try R.Authority.init(testing.allocator, .{ .cols = 80, .rows = 24 }, .{}, false); + defer a.deinit(); + const r = try R.Replica.init(testing.allocator, 1, try a.unit(0, 0), false); + defer r.deinit(); + const Keys = struct { + fn send(au: *R.Authority, re: *R.Replica, keys: []const u8) !void { + for (keys) |k| { + const ev: pardes.Event = if (k == 27) .{ .key = .{ .cp = pardes.Key.escape } } else .{ .key = .{ .cp = k, .text = &[_]u8{k} } }; + re.confirm(try au.local(ev)); + } + re.settle(); + } + }; + var line: [4200]u8 = undefined; + r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) })); + r.confirm(try a.local(.{ .command = "Changes ::@" })); + r.settle(); + const serial = a.core.panes[a.core.view().active].?.serial; + const ch = answered(a.core, serial).?; + var got: [16]u16 = undefined; + try testing.expectEqualSlices(u16, &Stack.pins, pinsOf(ch, &got)); + const before = try testing.allocator.dupe(Line, ch.lines); + defer testing.allocator.free(before); + const none = @intFromEnum(PinIndex.none); + // A line opened below `c3();` (line 4, inside mid's block): nobody's; + // the rows around keep their lanes. + r.confirm(try a.local(.{ .command = "Look a.zig:4" })); + try Keys.send(a, r, "oz\x1b"); + try testing.expectEqualSlices(u16, &.{ 0, 0, 1, 2, none, 1, 1, 0, 0, 0, 0 }, pinsOf(answered(a.core, serial).?, &got)); + try testing.expectEqual(before[3].lanes, answered(a.core, serial).?.lines[3].lanes); + try testing.expectEqual(before[4].lanes, answered(a.core, serial).?.lines[5].lanes); + // Undone: the values as they were. + try Keys.send(a, r, "u"); + try testing.expectEqualSlices(Line, before, answered(a.core, serial).?.lines); + // `x();` (line 5, mid's) deleted: its value goes with it. + r.confirm(try a.local(.{ .command = "Look a.zig:5" })); + try Keys.send(a, r, ";xd"); + try testing.expectEqualStrings(Stack.shift_text[0..41] ++ Stack.shift_text[50..], a.core.panes[a.core.view().active].?.file.?.content); + try testing.expectEqualSlices(u16, &.{ 0, 0, 1, 2, 1, 0, 0, 0, 0 }, pinsOf(answered(a.core, serial).?, &got)); + try testing.expectEqual(before[5].lanes, answered(a.core, serial).?.lines[4].lanes); + try testing.expect(r.diverged == null); + try testing.expectEqualSlices(Line, answered(a.core, serial).?.lines, answered(r.core(), serial).?.lines); + try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core())); +} + test "a B3 click on path@rev:line in running text opens the file at that revision there" { const gpa = testing.allocator; var repo = try Repo.init(gpa) orelse return error.SkipZigTest; -- cgit v1.3 From 0635ceab26f92836de300fef4066d7e9dc2494c5 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 21 Nov 2026 06:52:28 -0300 Subject: replica.may_wait: a directory's pane walked and listed: the screen-state soak's 'client 5's input key stopped at dir_listing, which may_wait does not list' (s5-1, seed 1 at 207 ms) was a far client's own step listing a directory (Dir.zig's tape.site(.dir_listing), from a Look of a directory or Get on one), which no row listed because the walk never stood in a directory's pane; FIRST the walk: On.dir, a directory's pane made by Look / on the authority and walked as the others (every word, key, prefix and gesture): 18 inputs stopped unlisted (Enter and Tab, alone and after each prefix); then the rows, right by P14 (the session's disk): Get -> dir_listing, Enter and * Enter -> resolve, Tab and * Tab -> kind; the walk test passes (11/11 under its filter); a user's far client typing those in a directory's pane waited, as it should, but the soak called it a fault Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/replica.zig | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/core/replica.zig b/core/replica.zig index 56fc4a59..ced4329d 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -6537,7 +6537,7 @@ test "a client's n in a kind's pane is a motion: it steps to the next place a re /// `addon`: a kind whose state is its own on the session (a PDF's), which /// the walk does not stand in (its Still has no search, place or word): /// the soak's (test/replicas.zig) PDF and pictures are, judged by name. -const On = enum { any, file, kind, shell, shell_normal, addon }; +const On = enum { any, file, kind, shell, shell_normal, addon, dir }; /// What a far client may wait a round trip for (the user's line, P14: a /// side effect on the system may be slow; motions, edits and layout are @@ -6558,6 +6558,12 @@ const may_wait = [_]Wait{ .{ .what = "LookPrev", .on = .any, .stop = "resolve", .why = "a Look's walk: each word asked of the disk" }, .{ .what = "Mini *", .on = .any, .stop = "resolve", .why = "a file opened by name, from the session's disk" }, .{ .what = "Get", .on = .any, .stop = "read_file", .why = "the file read again from the session's disk" }, + .{ .what = "Get", .on = .dir, .stop = "dir_listing", .why = "a directory listed again from the session's disk" }, + // A directory's pane (Dir.zig): its entries are names on the session's disk. + .{ .what = "Enter", .on = .dir, .stop = "resolve", .why = "the entry under the cursor opened, from the session's disk" }, + .{ .what = "* Enter", .on = .dir, .stop = "resolve", .why = "the entry opened (Enter after a prefix still opens it)" }, + .{ .what = "Tab", .on = .dir, .stop = "kind", .why = "what the entry under the cursor is, asked of the session's disk" }, + .{ .what = "* Tab", .on = .dir, .stop = "kind", .why = "what the entry is (Tab after a prefix still asks)" }, .{ .what = "Save", .on = .any, .stop = "write_file", .why = "a save" }, // A program run, a shell opened or closed: the session's processes. .{ .what = "Exec *", .on = .any, .stop = "kind", .why = "a program run: its name asked of the disk first" }, @@ -6833,12 +6839,16 @@ test "a far client's every word and key, on a file's pane, a kind's and a shell' _ = try a.local(.{ .command = "Still" }); const kind = a.core.view().active; try std.testing.expect(file != kind and a.core.panes[file].?.file != null and a.core.panes[kind].?.addon != null); + // A directory's pane (Dir.zig), listed from the disk. + _ = try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}/", .{dir}) }); + const listing = a.core.view().active; + try std.testing.expect(a.core.panes[listing].?.file.?.listing != null); var seen: [may_wait.len]bool = @splat(false); var hit: [may_wait.len]bool = @splat(false); var unlisted: u32 = 0; var tried: u32 = 0; - const stands = [_]struct { On, ?usize }{ .{ .file, file }, .{ .kind, kind }, .{ .shell, shell }, .{ .shell_normal, shell } }; + const stands = [_]struct { On, ?usize }{ .{ .file, file }, .{ .kind, kind }, .{ .shell, shell }, .{ .shell_normal, shell }, .{ .dir, listing } }; for (stands) |stand| { const on, const at = stand; const id = at orelse continue; -- cgit v1.3 From 49f3522b6421a634b7271a5244b6dde43104aa3b Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 21 Nov 2026 06:52:28 -0300 Subject: soak: a client's divergence named without the trace, and four faults of the soak's own that failed or cut its runs: (1) Named: at a client's FIRST mismatch only, its digest of every field (tape.digestParts, made pub with Parts and partsDiffer) and each terminal pane's screen digest without and with its view and its Grid are kept with the unit it parted on, and the witness, replaying the kept stream in its own core, names the fields and the terminals' content and view against its own at that unit: nothing more on the session's step or the wire (the trace's per-field digests hid the divergence in 19 runs); it named the bytes soak's divergence (b5-8, b6a-7, b6b-4, b6b-8, b6b-10): pane 0's terminal, content equal, VIEW one row lower on the client (0 against 1, 1 against 2), a terminal scrolled to its history's top; (2) Soak.watch: the soak's clock is a message's time and a message due before it stepped it back: 'integer overflow' (wa-1), now -|; (3) a session loop that ended before the run (runtime/session.zig: every client gone by a close, or core.quit) returned silently and lost the seed (merge49's bytes seed 1 at 207 ms): now said, with the last eight inputs drawn and who drew them, and the run failed (error.EndedEarly); (4) the script ended its own session: a Del of the last pane (nextEvent's command 8: now only while more than 3 panes are open, Soak.spare) and, by reading, Space then q (Exit; a typist's q right after its Space becomes r, Script.space) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/tape.zig | 7 +-- test/replicas.zig | 126 +++++++++++++++++++++++++++++++++++++++++++++++++++--- 2 files changed, 124 insertions(+), 9 deletions(-) diff --git a/core/tape.zig b/core/tape.zig index 6af332a3..4872e4fc 100644 --- a/core/tape.zig +++ b/core/tape.zig @@ -945,11 +945,11 @@ const pane_fields = walk.fieldNames(pardes.Pane); const file_fields = walk.fieldNames(pardes.panes.File.State); const places_fields = walk.fieldNames(pardes.panes.Places); const view_fields = walk.fieldNames(Pardes.View); -const Parts = [pardes_fields.len + stream_fields.len + pardes.views.max * view_fields.len + pardes.MAX_PANES * (2 + pane_fields.len + file_fields.len + places_fields.len)]u64; +pub const Parts = [pardes_fields.len + stream_fields.len + pardes.views.max * view_fields.len + pardes.MAX_PANES * (2 + pane_fields.len + file_fields.len + places_fields.len)]u64; /// The session's digest as one per field of the core's, its stream's, and /// each pane's and its file's, so a divergence says where it is. -fn digestParts(p: *const Pardes, parts: *Parts) []const u64 { +pub fn digestParts(p: *const Pardes, parts: *Parts) []const u64 { var n = walk.fieldDigests(Pardes, p, parts[0..pardes_fields.len]).len; n += walk.fieldDigests(pardes.Stream, &p.stream, parts[n..][0..stream_fields.len]).len; for (&p.views) |*slot| if (slot.*) |*v| { @@ -971,7 +971,7 @@ fn digestParts(p: *const Pardes, parts: *Parts) []const u64 { } /// The fields whose digests differ, named. -fn partsDiffer(got: []const u64, want: []const u64, a: std.mem.Allocator) []const u8 { +pub fn partsDiffer(got: []const u64, want: []const u64, a: std.mem.Allocator) []const u8 { var said: std.ArrayList(u8) = .empty; if (got.len != want.len) said.print(a, "the panes there are ({d} parts, {d} recorded); ", .{ got.len, want.len }) catch {}; const n = @min(got.len, want.len); @@ -1309,6 +1309,7 @@ pub fn recordDigest(t: *Tape) void { t.record(.digest, []const u64, &d); } + /// A core made outside the tape (a replica client's, from a dump) is the /// one it replays into. pub fn adoptCore(t: *Tape, p: *Pardes) void { diff --git a/test/replicas.zig b/test/replicas.zig index e5e719b3..48eaa857 100644 --- a/test/replicas.zig +++ b/test/replicas.zig @@ -336,7 +336,7 @@ const Totals = struct { /// search (`/`, a pattern, Enter), a sweep of B1 over the PDF and its /// wheel; a yank to the system clipboard and a paste from it; now and /// then a client's Detach. -fn nextEvent(random: std.Random, buf: *[64]u8, aim: Aim, looks: []const []const u8, script: *Script, far: bool) pardes.Event { +fn nextEvent(random: std.Random, buf: *[64]u8, aim: Aim, looks: []const []const u8, script: *Script, far: bool, spare: bool) pardes.Event { const typed = "abcdefghijklmnopqrstuvwxyz0123456789 -_=+,:;()"; const normal = "hjklwbe0$xpuyoOiaAIdcv.nN%sC"; if (script.at < script.n) { @@ -346,13 +346,19 @@ fn nextEvent(random: std.Random, buf: *[64]u8, aim: Aim, looks: []const []const switch (random.uintLessThan(u8, 46)) { 0...15 => { buf[0] = typed[random.uintLessThan(usize, typed.len)]; + if (buf[0] == 'q' and script.space) buf[0] = 'r'; + script.space = buf[0] == ' '; return .{ .key = .{ .cp = buf[0], .text = buf[0..1] } }; }, 16...27 => { buf[0] = normal[random.uintLessThan(usize, normal.len)]; + script.space = false; return .{ .key = .{ .cp = buf[0], .text = buf[0..1] } }; }, - 28...31 => return .{ .key = .{ .cp = Key.escape } }, + 28...31 => { + script.space = false; + return .{ .key = .{ .cp = Key.escape } }; + }, 32 => return .{ .key = .{ .cp = Key.enter } }, 33 => return .{ .key = .{ .cp = Key.backspace } }, 34 => return .{ .key = .{ .cp = switch (random.uintLessThan(u8, 4)) { @@ -374,7 +380,9 @@ fn nextEvent(random: std.Random, buf: *[64]u8, aim: Aim, looks: []const []const 4 => "Search Panes", 5 => "Search Recent", 6, 7 => looks[random.uintLessThan(usize, looks.len)], - 8 => "Del", + // Not the session's last panes: a Del of its last ends it, and + // the run with it (`Soak.spare`). + 8 => if (spare) "Del" else "Undo", // A tab's width: every pane's layout. 9 => "Tab 2", 10 => "Tab 8", @@ -431,6 +439,9 @@ const Script = struct { evs: [3]pardes.Event = undefined, n: u8 = 0, at: u8 = 0, + /// Its last key was a space: Space then q is Exit (config.zig's + /// leader), which ends the session and the run with it. + space: bool = false, }; fn writeFile(path: [:0]const u8, lines: usize) !void { @@ -873,6 +884,62 @@ const Watchdog = struct { } }; +/// At a client's mismatch only: its digest of every field, as the mismatch +/// left its core, and the unit it parted on. The witness names the fields +/// when its own replay of the kept stream comes to that unit (`judge`): +/// nothing more on the session's step or the wire, so the run's timing is +/// the untraced one. +const Named = struct { + const Parted = struct { c: usize, origin: u16, seq: u32, parts: []u64, terms: [pardes.MAX_PANES]Term }; + /// A terminal pane's: its screen's digest without its view and with + /// it, and where its view and cursor stand. + const Term = struct { content: u64 = 0, viewed: u64 = 0, grid: pardes.Term.Grid = .{} }; + + fn terms(p: *const pardes.Pardes) [pardes.MAX_PANES]Term { + var out: [pardes.MAX_PANES]Term = @splat(.{}); + for (p.panes, &out) |slot, *t| { + const state = (slot orelse continue).terminal orelse continue; + var a = pardes.walk.Hasher.init(0); + state.digestScreen(&a, false); + var b = pardes.walk.Hasher.init(0); + state.digestScreen(&b, true); + t.* = .{ .content = a.final(), .viewed = b.final(), .grid = pardes.Term.grid(state) }; + } + return out; + } + var parted: std.ArrayListUnmanaged(Parted) = .empty; + + fn reset() void { + for (parted.items) |x| gpa.free(x.parts); + parted.clearRetainingCapacity(); + } + + /// Client `c` parted on `unit`: kept for the witness, said once. + fn say(r: Run, c: usize, rp: *replica.Replica, unit: []const u8) void { + const u = replica.parseUnit(unit) orelse return; + const mine = gpa.create(pardes.tape.Parts) catch return; + defer gpa.destroy(mine); + const got = pardes.tape.digestParts(rp.core(), mine); + parted.append(gpa, .{ .c = c, .origin = u.origin, .seq = u.seq, .parts = gpa.dupe(u64, got) catch return, .terms = terms(rp.core()) }) catch return; + std.debug.print("seed {d} rtt {d} ms: client {d} parted on unit {d}/{d} ({d} bytes; {d} applied on top, {d} pending): its fields kept for the witness\n", .{ r.seed, r.rtt_ms, c + 1, u.origin, u.seq, u.tape.len, rp.applied, rp.pending.items.len }); + } + + /// The witness at the end of unit `u`: each client that parted there, + /// its fields against the witness's (the session's stream replayed). + fn atUnit(tag: anytype, u: replica.Unit, rp: *replica.Replica, w: *std.Io.Writer) void { + for (parted.items) |x| if (x.origin == u.origin and x.seq == u.seq) { + var arena = std.heap.ArenaAllocator.init(gpa); + defer arena.deinit(); + const theirs = arena.allocator().create(pardes.tape.Parts) catch return; + const want = pardes.tape.digestParts(rp.core(), theirs); + w.print("seed {d} rtt {d} ms: client {d} names: at unit {d}/{d}, against the witness's replay: {s}\n", tag ++ .{ x.c + 1, u.origin, u.seq, pardes.tape.partsDiffer(x.parts, want, arena.allocator()) }) catch {}; + for (x.terms, terms(rp.core()), 0..) |a, b, id| if (a.viewed != b.viewed or a.content != b.content) { + w.print(" pane {d}'s terminal: content {s}, view {s}; the client's {any}; the witness's {any}\n", .{ id, if (a.content == b.content) "equal" else "DIFFERS", if (a.viewed == b.viewed) "equal" else "DIFFERS", a.grid, b.grid }) catch {}; + }; + }; + } +}; + const Witness = struct { const Sent = struct { blob: bool, bytes: []u8 }; const Dump = struct { c: usize, id: u16, view: u8, cols: u16, rows: u16, join_seq: u32, bytes: []u8, start: ?usize = null }; @@ -1050,6 +1117,7 @@ const Witness = struct { if (u.origin == 0) last0 = u.seq; rp.since_check = if (parted == null) 1 << 20 else 0; rp.confirm(m.bytes); + if (parted == null) Named.atUnit(tag, u, rp, w); if (rp.diverged) |why| { if (parted == null) { parted = i; @@ -1123,6 +1191,15 @@ const Soak = struct { l: *SessionLoop = undefined, /// What failed inside the loop (its wait returns nothing): the run's. err: ?anyerror = null, + /// `finish` ran: the session's loop ended at the run's end, not before. + finished: bool = false, + /// The session's `quit` after its last step (`sent`): an Exit's end. + quit: bool = false, + /// The last inputs the typists drew (who, as `describe` says them), + /// said with an early end. + drawn: [8]struct { who: u16 = 0, text: [48]u8 = undefined, len: u8 = 0 } = @splat(.{}), + drawn_n: usize = 0, + // ---- its host ---- /// A pty that echoes what it is written, 2 ms later, as a shell's. @@ -1354,7 +1431,22 @@ const Soak = struct { /// clients' inputs, joins and leaves taken in): what a Peer's writer /// would write, down each link; a join taken or refused; a link the /// session shut; the echoes its steps asked of the shell. + fn drew(s: *Soak, who: u16, ev: pardes.Event) void { + const d = &s.drawn[s.drawn_n % s.drawn.len]; + s.drawn_n += 1; + d.who = who; + d.len = @intCast(describe(&d.text, ev).len); + } + + /// Panes enough that the Dels in flight (a typist's each) leave one. + fn spare(s: *const Soak) bool { + var n: usize = 0; + for (s.l.core.panes) |slot| n += @intFromBool(slot != null); + return n > 3; + } + pub fn sent(s: *Soak) void { + defer s.quit = s.l.core.quit; s.sentOrFail() catch |err| { if (s.err == null) s.err = err; s.l.core.quit = true; @@ -1811,7 +1903,8 @@ const Soak = struct { switch (m.kind) { .input => { var buf: [64]u8 = undefined; - const ev = nextEvent(s.random, &buf, s.aim, s.looks, &cl.script, net.throttled == @as(?usize, c)); + const ev = nextEvent(s.random, &buf, s.aim, s.looks, &cl.script, net.throttled == @as(?usize, c), s.spare()); + s.drew(@intCast(c + 1), ev); cl.loop.input(ev); cl.left -= 1; if (cl.left > 0) try net.send(.{ .at = m.at + typistGap(s.random), .n = 0, .kind = .input, .who = m.who, .bytes = &.{} }) else { @@ -1829,7 +1922,9 @@ const Soak = struct { // what its unit cost, on this process's clock. const reloads = pardes.Term.reloads.n; const t0 = monoNs(); + const whole = rp.diverged == null; cl.loop.take(.{ .unit = try std.heap.c_allocator.dupe(u8, m.bytes) }); + if (whole and rp.diverged != null and !cl.loop.link.put_off) Named.say(s.r, c, rp, m.bytes); if (pardes.Term.reloads.n != reloads) try s.totals.join_client_ns.append(gpa, monoNs() - t0); const behind = if (net.throttled == @as(?usize, c)) &s.totals.far_behind else &s.totals.near_behind; behind.* = @max(behind.*, cl.loop.link.behind); @@ -1890,7 +1985,8 @@ const Soak = struct { s.moved_at = s.now; return; } - if (s.now - s.moved_at < stuck_us) return; + // The soak's clock is a message's time: one due before it steps it back. + if (s.now -| s.moved_at < stuck_us) return; std.debug.print("seed {d} rtt {d} ms: watchdog: nothing stepped or checked for {d} s of the soak's clock (since {d} us)\n", .{ s.r.seed, s.r.rtt_ms, stuck_us / std.time.us_per_s, s.moved_at }); s.report(); return error.Hung; @@ -1918,7 +2014,8 @@ const Soak = struct { const core = s.l.core; s.clock(); var buf: [64]u8 = undefined; - const ev = nextEvent(s.random, &buf, s.aim, s.looks, &s.own_script, false); + const ev = nextEvent(s.random, &buf, s.aim, s.looks, &s.own_script, false, s.spare()); + s.drew(0, ev); core.toView(.at(0)); core.update(ev); s.own_left -= 1; @@ -1988,6 +2085,7 @@ const Soak = struct { /// At quiescence: every client's digest the session's, its terminals /// the session's cell for cell, its files' texts byte for byte. fn finish(s: *Soak) !void { + s.finished = true; const totals = s.totals; const core = s.l.core; totals.flood_us += s.flood_end -| flood_at; @@ -2073,6 +2171,8 @@ fn run(init: std.process.Init, r: Run, dir: []const u8, totals: *Totals) !void { if (trace) std.debug.print("seed {d} rtt {d} ms\n", .{ r.seed, r.rtt_ms }); Witness.reset(); defer Witness.reset(); + Named.reset(); + defer Named.reset(); var prng = std.Random.DefaultPrng.init(r.seed *% 0x9e3779b97f4a7c15 +% r.rtt_ms); const random = prng.random(); var paths: [3][256:0]u8 = undefined; @@ -2168,6 +2268,20 @@ fn run(init: std.process.Init, r: Run, dir: []const u8, totals: *Totals) !void { // The session: THE session loop, from its start to its end. try SessionLoop.run(init, .{ .cols = 100, .rows = 30, .boot = .tty }, &soak); if (soak.err) |err| return err; + // The loop ends without the run's end too (runtime/session.zig): every + // client gone at a boundary, the last by a close; or the session ended + // (Exit, the last pane's Del). Said, and the run failed. + if (!soak.finished) { + std.debug.print("seed {d} rtt {d} ms: the session's loop ended before the run did: {s}; the clients:", .{ r.seed, r.rtt_ms, if (soak.quit) "the session ended (Exit, the last pane's Del)" else "every client gone at a boundary, the last by a close" }); + for (soak.clients, 1..) |cl, k| std.debug.print(" {d} {s}{s}{s};", .{ k, if (cl.r == null) "none" else "joined", if (cl.dialling) " dialling" else "", if (cl.shut) " shut" else "" }); + std.debug.print(" typing {d}, at {d} us; the last drawn (0 the session's own):", .{ soak.typing, soak.now }); + for (0..@min(soak.drawn_n, soak.drawn.len)) |k| { + const d = soak.drawn[(soak.drawn_n - 1 - k) % soak.drawn.len]; + std.debug.print(" {d}: {s};", .{ d.who, d.text[0..d.len] }); + } + std.debug.print("\n", .{}); + return error.EndedEarly; + } } /// What `questions`'s kitty query and `images`'s four are answered with. -- cgit v1.3 From aefdb402b577c270111e2736e175611def0833e7 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 21 Nov 2026 17:47:24 -0300 Subject: tests: a plain client watching a kitty image in a terminal under screen state joins again for ever, caught twice: core/replica.zig "a terminal's program shows a kitty image under screen state: the client's emulator never has it, and its tag says what the session's does" (an Authority and a Replica, the image fed in the session's order, a step after: the digests part in pane 0.tag, pane 0.tag_lead and pane 1.cwd, the last an inherited cwd that walks to the terminal's pane; `partsApart` names them) and test/daemon.py `kitty_image` (plain mode's list, alone `--kitty-image`: a detached session, a plain attach, the corpus scene 10's 8x8 RGB image printed in its shell, the client's joins counted over 5 s, 0 expected: on this base's Debug build 16 joins, 16 of 16 checks differ; on the installed build (6d937cd125ca) the same 16, 3.2 a second, session 20-30 ms and client 50-70 ms of CPU, 80 KB to the client's terminal); shell-test 1100/1104 with this test the one failure, core-test 898/1059 (161 skipped: it needs a shell) Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/replica.zig | 51 ++++++++++++++++++++++++++++++++++++++ test/daemon.py | 75 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 126 insertions(+) diff --git a/core/replica.zig b/core/replica.zig index 10eba502..49ae4594 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -6436,6 +6436,57 @@ test "a closed terminal with a kitty image brought back on a client: its image d try agrees(a, r); } +/// The core's fields whose digests differ between the session and a +/// client, named (tape.partsDiffer); empty when they agree. +fn partsApart(a: *Authority, r: *Replica, arena: std.mem.Allocator) ![]const u8 { + const want = try arena.create(tape.Parts); + const got = try arena.create(tape.Parts); + const w = digested: { + const was = Stepping.begin(&a.t, null); + defer was.end(); + break :digested tape.digestParts(a.core, want); + }; + const g = digested: { + const was = Stepping.begin(&r.t, &r.epoch); + defer was.end(); + break :digested tape.digestParts(r.core(), got); + }; + return if (std.mem.eql(u64, w, g)) "" else tape.partsDiffer(g, w, arena); +} + +test "a terminal's program shows a kitty image under screen state: the client's emulator never has it, and its tag says what the session's does" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const gpa = std.testing.allocator; + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, TestHost.host(), true); + defer a.deinit(); + var screens: Screens = .init(gpa); + defer screens.deinit(a.core); + const peer = try screens.addPeer(); + const r = try Replica.init(gpa, 1, try a.unit(0, 0), true); + defer r.deinit(); + const shell: u8 = for (a.core.panes, 0..) |slot, id| { + if (slot) |pane| if (pane.isTerminal()) break @intCast(id); + } else return error.NoShell; + try deliver(a, &screens, peer, r, .flush); + try std.testing.expectEqualStrings("", try partsApart(a, r, arena.allocator())); + // In the session's order: the pump's unit, then what its terminals came + // to; then a step after both, on every side. + a.output(.{ .output = .{ .pane = .at(shell), .bytes = "\x1b_Ga=T,i=7,f=24,s=2,v=2;ESIzESIzESIzESIz\x1b\\" } }); + r.confirm((try a.pending()).?); + r.settle(); + try deliver(a, &screens, peer, r, .flush); + r.confirm(try a.local(.{ .focus = true })); + r.settle(); + try std.testing.expect(pardes.Term.hasImages(a.core.panes[shell].?.terminal)); + try std.testing.expect(!pardes.Term.hasImages(r.core().panes[shell].?.terminal)); + try std.testing.expectEqualStrings("", try partsApart(a, r, arena.allocator())); + try agrees(a, r); + const prefix = try pardes.tagline.prefixIn(r.core(), arena.allocator(), r.core().panes[shell].?); + try std.testing.expect(std.mem.indexOf(u8, prefix, " petscii:") != null); +} + test "a far client's own Del of a pane whose kind's state is not plain, rolled back by another's unit: the pane comes back whole, and is closed again with the session's order" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); diff --git a/test/daemon.py b/test/daemon.py index c6ff6256..e1be141a 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -38,6 +38,8 @@ private HOME and runtime directory: python3 -B test/daemon.py --far the far clients and their blob cache alone, one under `yes` across a slow link, and a file by its hash + python3 -B test/daemon.py --kitty-image + a plain client watching a kitty image in its session's terminal python3 -B test/daemon.py --games [seconds] the games in the clients that show them, from zig build addon-test's /lib (libsnake, liblife, libliar) @@ -2608,6 +2610,76 @@ def terminals(client): return [int(row.split()[0]) for row in client.read('/index').splitlines() if row.split()[1] == b'term'] +def cpu_ticks(pid): + stat = open(f'/proc/{pid}/stat').read().rsplit(')', 1)[1].split() + return int(stat[11]) + int(stat[12]) + + +def kitty_image(binary, secs=5): + """A plain attach (screen state) watching a terminal in which a program + shows a kitty image (the corpus's scene 10's: 8x8 RGB, 10x4 cells): it + agrees with its session and does not join again (it joined again ~3.3 + times a second: the tag said ` petscii:on` on the session's side only).""" + scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' + scratch.mkdir(parents=True, exist_ok=True) + root = Path(tempfile.mkdtemp(prefix='ri-', 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') + rgb = bytes((x * 30) % 256 for x in range(8 * 8 * 3)) + (root / 'kitty.sh').write_text("printf '\\033_Ga=T,f=24,s=8,v=8,c=10,r=4;%s\\033\\\\'\nprintf '\\nKITTY\\n'\n" + % __import__('base64').b64encode(rgb).decode()) + started, terms = [], [] + try: + term = Term() + terms.append(term) + stub = term.spawn([binary, '--tty', '--9p=img'], env) + started.append(stub.pid) + wait_for('the session\'s 9P socket', (root / 'pardes-9p-img.sock').exists) + nine = Client(root / 'pardes-9p-img.sock') + session = int(dict(line.split(maxsplit=1) for line in nine.read('/status').decode().splitlines())['pid']) + started.append(session) + shell = terminals(nine)[0] + nine.write(f'/pane/{shell}/exec', b'Detach\n') + assert stub.wait(timeout=10) == 0, stub.returncode + t = Term(30, 100) + terms.append(t) + c = t.spawn([binary, 'attach', 'img'], dict(env, PARDES_REPLICA_CHECK=str(root / 'c.check'))) + started.append(c.pid) + wait_for('the client\'s first frame', lambda: b'\x1b[?1049h' in t.text(), timeout=30) + wait_for('the client agrees', lambda: agreed(root / 'c.check', 0), timeout=30) + nine.write(f'/pane/{shell}/pty/data', f'clear; sh {root}/kitty.sh\r'.encode()) + wait_for('KITTY in the session\'s body', lambda: b'KITTY' in nine.read(f'/pane/{shell}/body'), timeout=30) + wait_for('KITTY in the client\'s terminal', lambda: b'KITTY' in t.text(), timeout=30) + mark, seen = len(t.text()), len(checks(root / 'c.check')) + cpu = (cpu_ticks(session), cpu_ticks(c.pid)) + time.sleep(secs) + cpu = [(cpu_ticks(p) - was) * 1000 // os.sysconf('SC_CLK_TCK') for p, was in zip((session, c.pid), cpu)] + again = t.text()[mark:].count(b'joined again') + said = checks(root / 'c.check')[seen:] + tag = nine.read(f'/pane/{shell}/tag') + print(f'kitty image: over {secs} s the client joined again {again} times ({again / secs:.1f}/s), its checks ' + f'{len(said)} ({sum(s.startswith("differ") for s in said)} differ), CPU ms session {cpu[0]} client {cpu[1]}, ' + f'{len(t.text()) - mark} bytes to its terminal; the session\'s tag {tag[:60]!r}') + assert again == 0 and c.poll() is None, (again, said[-3:]) + assert agreed(root / 'c.check', seen), said + exit_session(nine, shell) + nine.socket.close() + wait_for('the client ended with its session', lambda: c.poll() is not None, timeout=20) + print('kitty image: a plain client watching a kitty image agreed and never joined again') + finally: + for t in terms: + t.close() + for pid in started + processes(root): + try: + os.kill(pid, signal.SIGKILL) + except OSError: + pass + shutil.rmtree(root, ignore_errors=True) + + def main(binary, cycles): scratch = Path(__file__).resolve().parent.parent.parent / '.scratch' / 'daemon' / 'dmn' scratch.mkdir(parents=True, exist_ok=True) @@ -2648,6 +2720,7 @@ def main(binary, cycles): manage(binary) relink(binary) answer_late(binary) + kitty_image(binary) shell = terminals(client)[0] shell_pid = int(run(client, shell, b'echo $$\n').split(b'\n')[1]) started.append(shell_pid) @@ -3662,6 +3735,8 @@ if __name__ == '__main__': far_find(sys.argv[2]) elif sys.argv[1:2] == ['--far-find']: far_find(sys.argv[2]) + elif sys.argv[1:2] == ['--kitty-image']: + kitty_image(sys.argv[2]) elif sys.argv[1:2] == ['--restore']: restore_client(sys.argv[2]) elif sys.argv[1:2] == ['--window-clients']: -- cgit v1.3 From f11ba0c54b500d855740c54f26208217793bcef6 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 21 Nov 2026 17:47:24 -0300 Subject: tests: a screen-state client's reads of a terminal's prompt marks are the session's in its own input's step: core/replica.zig "a command typed into a shell with prompt marks under screen state: every side notes it as the session's emulator numbers it, and Kill finds it" (pardes's bash marks, one command run, an `Exec sleep 9` typed at the prompt: `sent_command.seq` 2 on both sides, then its C mark and a Kill: every field agrees), the audit's one doubt settled by a run: the OSC 133 cycle crosses with every delta (core/term/terminal.zig `marksOf`/`takeMarks`), so exec.zig's `noteCommand` and Kill read the session's; what still parts is a step of the session's own after the same pump's output (the pump-lag class, the client replaying it over the last flush: a test of it is kept out of the tree, failing, in the report); passes on the base and with the fix Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/replica.zig | 50 ++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/core/replica.zig b/core/replica.zig index 49ae4594..1939efbc 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -6487,6 +6487,56 @@ test "a terminal's program shows a kitty image under screen state: the client's try std.testing.expect(std.mem.indexOf(u8, prefix, " petscii:") != null); } +test "a command typed into a shell with prompt marks under screen state: every side notes it as the session's emulator numbers it, and Kill finds it" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const gpa = std.testing.allocator; + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const ShellHost = struct { + fn taken(_: ?*anyopaque, _: pardes.Pane.Id) bool { + return false; + } + fn write(_: ?*anyopaque, _: pardes.Pane.Id, _: []const u8) void {} + const vtable: pardes.Host.VTable = .{ .watched = TestHost.watched, .tty_taken = taken, .pty_write = write }; + }; + const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .boot = .tty }, .{ .vtable = &ShellHost.vtable }, true); + defer a.deinit(); + var screens: Screens = .init(gpa); + defer screens.deinit(a.core); + const peer = try screens.addPeer(); + const r = try Replica.init(gpa, 1, try a.unit(0, 0), true); + defer r.deinit(); + const shell: u8 = for (a.core.panes, 0..) |slot, id| { + if (slot) |pane| if (pane.isTerminal()) break @intCast(id); + } else return error.NoShell; + // pardes's own bash marks (host_io.zig): one command run, a prompt. + const prompt = "\x1b]133;A;cl=line;aid=pardes\x07$ \x1b]133;B;aid=pardes\x07"; + a.output(.{ .output = .{ .pane = .at(shell), .bytes = prompt ++ "ls\r\n\x1b]133;C;aid=pardes\x07a b\r\n\x1b]133;D;0;aid=pardes\x07" ++ prompt } }); + r.confirm((try a.pending()).?); + r.settle(); + try deliver(a, &screens, peer, r, .flush); + a.core.view().active = shell; + r.confirm(try a.local(.{ .focus = true })); + r.settle(); + try std.testing.expectEqualStrings("", try partsApart(a, r, arena.allocator())); + // Exec'd in the shell: typed at its prompt, the command noted. + r.confirm(try a.local(.{ .command = "Exec sleep 9" })); + r.settle(); + // Its marks cross with the cells (Term.marksOf): numbered alike. + try std.testing.expectEqual(@as(u32, 2), a.core.panes[shell].?.sent_command.?.seq); + try std.testing.expectEqual(@as(u32, 2), r.core().panes[shell].?.sent_command.?.seq); + try std.testing.expectEqualStrings("", try partsApart(a, r, arena.allocator())); + // Its echo and its C mark: running. Kill is asked for it. + a.output(.{ .output = .{ .pane = .at(shell), .bytes = "sleep 9\r\n\x1b]133;C;aid=pardes\x07" } }); + r.confirm((try a.pending()).?); + r.settle(); + try deliver(a, &screens, peer, r, .flush); + r.confirm(try a.local(.{ .command = "Kill" })); + r.settle(); + try std.testing.expectEqualStrings("", try partsApart(a, r, arena.allocator())); + try agrees(a, r); +} + test "a far client's own Del of a pane whose kind's state is not plain, rolled back by another's unit: the pane comes back whole, and is closed again with the session's order" { const gpa = std.testing.allocator; const a = try Authority.init(gpa, .{ .cols = 80, .rows = 24, .file = "mise.toml" }, TestHost.host(), false); -- cgit v1.3 From 0000e169c52da6d77e9cf3538896d7202d0a313b Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 21 Nov 2026 17:47:24 -0300 Subject: a terminal showing a kitty image no longer parts a screen-state client from its session: whether the terminal holds an image is the session's fact, `Pane.term_images`, set at its output's step (core/Core.zig `.output`: taped under screen state, tape site `images`, the session's answer replayed on every client, whose emulator is fed cells and never has the image; read directly otherwise, every side fed the same bytes) and read by the tag (core/tagline.zig, for `Term.hasImages` of each side's own emulator, whose ` petscii:on|off` made the digested `tag_lead` longer on the session's side only: every quiet check differed and a plain attach joined again 3.2 times a second for as long as the image was there, the installed build too); taped and not a bit beside the cells because the step that computes the tag is the output's own unit, which a client replays before that pump's flush reaches it; wire 28 (a pane's new field in the join's dump and the digest, the tape's new site; test/daemon.py `WIRE`); daemon.py `--kitty-image` on Debug: 0 joins in 5 s, 3 of 3 (16 before); core-test 898/1060 (162 skipped), shell-test 1102/1105 (3 skipped), term-test 18/18, kitty-test 45/45 Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- abi/wire.zig | 6 +++++- core/Core.zig | 1 + core/panes.zig | 5 +++++ core/tagline.zig | 2 +- core/tape.zig | 3 +++ test/daemon.py | 2 +- 6 files changed, 16 insertions(+), 3 deletions(-) diff --git a/abi/wire.zig b/abi/wire.zig index 88a82e52..d7df7bc3 100644 --- a/abi/wire.zig +++ b/abi/wire.zig @@ -10,6 +10,10 @@ const pardes = @import("core"); const config = @import("pardes_options"); const build_info = @import("build_info"); +/// 28: whether a terminal holds a kitty image is the session's, taped +/// after its output (tape site `images`), and a pane's (Pane.term_images) +/// in its join's dump and its digest: a screen-state client's tag says +/// what the session's does; /// 27: a pair's first client makes its own core from the session's /// options and says its digest (`boot`) before its `far`: the session sends /// no dump when its own at the join has the same; @@ -46,7 +50,7 @@ const build_info = @import("build_info"); /// part B); 14: the hello names a session and /// carries the semantics hash, and a ping is answered (phase 5's /// groundwork); 13: the frames went (phase 3). -pub const version: u16 = 27; +pub const version: u16 = 28; /// The terminal's build and the window's step alike (`semantics`). const family = switch (config.platform) { diff --git a/core/Core.zig b/core/Core.zig index 177a6e78..73d0738a 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -1684,6 +1684,7 @@ fn updateInner(p: *Pardes, ev: Event) void { pane.shell_spoke = true; ctlfs.events.notePtyOutput(p, o.pane.index(), o.bytes); pane.feedOutput(p, o.bytes); + pane.term_images = if (p.tape.screen_state) p.tape.value(.images, pardes.Term.hasImages, .{pane.terminal}) else pardes.Term.hasImages(pane.terminal); ctlfs.pty.noteMarks(p, o.pane.index(), pane); exec.flushReplEnter(p, o.pane.index(), true); }, diff --git a/core/panes.zig b/core/panes.zig index 8b152132..2f561d05 100644 --- a/core/panes.zig +++ b/core/panes.zig @@ -134,6 +134,11 @@ pub const Pane = struct { /// cell), and its kitty graphics drawn as glyph art (Petscii). term_mouse: ?Term.Coordinate = null, term_petscii: bool = false, + /// Whether its terminal holds a kitty image, as the session's emulator + /// said after its program's last output (taped under screen state: a + /// client's emulator is fed the session's cells, never an image). Its + /// tag says so (tagline.zig), on every side. + term_images: bool = false, gpa: std.mem.Allocator, serial: u32 = 0, /// What the control filesystem keeps of this pane -- addr and limit, the diff --git a/core/tagline.zig b/core/tagline.zig index afee0659..26f83fba 100644 --- a/core/tagline.zig +++ b/core/tagline.zig @@ -160,7 +160,7 @@ pub fn pathPrefix(p: *const Pardes, arena: std.mem.Allocator, pane: *Pane) ![]co if (pane.terminal != null) { const chosen = pane.term_petscii; const on = chosen or !p.view().frontend.native_images; - if (chosen or panes.Term.hasImages(pane.terminal)) + if (chosen or pane.term_images) return std.fmt.allocPrint(arena, "{s} petscii:{s}", .{ (try shownDir(arena, pane)), if (on) "on" else "off" }); } return (try shownDir(arena, pane)); diff --git a/core/tape.zig b/core/tape.zig index d32f8dd8..f231831d 100644 --- a/core/tape.zig +++ b/core/tape.zig @@ -140,6 +140,9 @@ pub const Site = enum(u16) { /// A kitty image's medium as a terminal's emulator read it (a file, a /// temporary file, shared memory: Term.media), its bytes or its failure. medium, + /// Whether a terminal holds a kitty image after its program's output + /// (Pane.term_images): a screen-state replica's emulator never has one. + images, }; /// What the sites return. wire.semantics hashes their shape with the diff --git a/test/daemon.py b/test/daemon.py index e1be141a..e334b6e8 100644 --- a/test/daemon.py +++ b/test/daemon.py @@ -258,7 +258,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 = 27 + WIRE = 28 def __init__(self, path, timeout=10): self.path, self.timeout = path, timeout -- cgit v1.3 From 78aa898cf2a55c5e4e78d968b37388e0cbc6e2d2 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 21 Nov 2026 16:16:43 -0300 Subject: terminals' views: the bytes soak's divergence (a client's terminal view one row above the session's, at its history's top, 5 whole runs of 29 in round 5) fails on purpose, without a soak, in two tests: at the terminal module, a view on a wrapped line's second row, joined into the row above by a widening (ghostty's view is a pinned CELL, now mid-row at row 0) and put back at the row it reports (`viewTo(grid.view)`, as a replica's rollback puts views back, replica.zig `putViews`: at row 0 that is ghostty's `.top`) is another view after the narrowing back (expected 1, found 0: the soak's sign); at the replica's surface (an Authority and a Replica, bytes), the session's frontend widens the shell with its view there, a key of the client's is rolled back under the session's (the copy put back, `putViews`), the session narrows again: the digests part on the terminal's view (17455102819691583991 against 7777253998216201365); found by a probe ring of pane 0's view at every engine step in the soak's clients against the witness (b7b-4: put back to row 0, then the next reflow moved the witness's view and not the client's) and a fuzz of put-back against left-alone terminals under random output, reflows and scrolls (5 apart in 191 seeds); both fail on this change, the next one fixes them Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/replica.zig | 34 ++++++++++++++++++++++++++++++++++ core/term/terminal.zig | 21 +++++++++++++++++++++ 2 files changed, 55 insertions(+) diff --git a/core/replica.zig b/core/replica.zig index ced4329d..fa9a0fda 100644 --- a/core/replica.zig +++ b/core/replica.zig @@ -4692,6 +4692,40 @@ test "bytes: a session's output that moves nothing the digest covers (a colour s try sameTerminals(b.a, b.r); } +test "bytes: a terminal's view a rollback puts back is the session's through a reflow: a view on a wrapped line's second row, joined into the row above by the session's widening, is the same row after its narrowing on every side" { + if (pardes.Term.ops == null) return error.SkipZigTest; // a shell + const b = try BytesPair.init(); + defer b.deinit(); + const id = b.shell.index(); + // Lines a row and a half long, the view on the first's second row (put + // there alike on both sides: no step of either moved it). + const cols = pardes.Term.grid(b.a.core.panes[id].?.terminal).cols; + var line: [512]u8 = undefined; + const text = line[0 .. cols + cols / 2]; + @memset(text, 'x'); + b.a.output(.{ .output = .{ .pane = b.shell, .bytes = "\x1bc" } }); + for (0..40) |_| { + b.a.output(.{ .output = .{ .pane = b.shell, .bytes = text } }); + b.a.output(.{ .output = .{ .pane = b.shell, .bytes = "\r\n" } }); + } + b.r.confirm((try b.a.pending()).?); + b.r.settle(); + for ([_]*Pardes{ b.a.core, b.r.core() }) |core| pardes.Term.viewTo(core.panes[id].?.terminal.?, 1); + // The session's frontend widens: the line one row, the view at row 0, + // its cell mid-row. + b.r.confirm(try b.a.own(.{ .resize = .{ .cols = 200, .rows = 24 } })); + b.r.settle(); + try agrees(b.a, b.r); + try std.testing.expectEqual(@as(?usize, 0), pardes.Term.grid(b.a.core.panes[id].?.terminal).view); + // A key of the client's on top, the session's first: the copy put back. + try b.rollback(); + try agrees(b.a, b.r); + // The session narrows again: every side's view the same row. + b.r.confirm(try b.a.own(.{ .resize = .{ .cols = 80, .rows = 24 } })); + b.r.settle(); + try agrees(b.a, b.r); +} + test "bytes: a mouse motion a speculation told a terminal's program is told again when its input is replayed: the cell last told is the pane's, put back with it" { if (pardes.Term.ops == null) return error.SkipZigTest; // a shell const gpa = std.testing.allocator; diff --git a/core/term/terminal.zig b/core/term/terminal.zig index 1673a3d8..535ca6dc 100644 --- a/core/term/terminal.zig +++ b/core/term/terminal.zig @@ -1591,6 +1591,27 @@ pub fn images(state: *State, gpa: std.mem.Allocator, at: ImagesAt, out: *std.Arr state.images.draw(state.gpa, gpa, &state.vt, at, rows_of[0..vp_rows], out, frame, frame_cols); } +test "a view put back at the row it reports is the view it was, through a reflow: a view on a wrapped line's second row, joined into the row above by a widening and parted again by a narrowing, is the same row put back or not" { + // The bytes soak's divergence (reports/pardes-term-join-6.md): a + // client's rollback puts each terminal's view back at its row + // (core/replica.zig `putViews`), and ghostty's view is a cell, which + // a widening leaves mid-row and the next narrowing carries a row down. + const gpa = std.testing.allocator; + const left = try open(gpa, 20, 2); + defer close(left); + const put = try open(gpa, 20, 2); + defer close(put); + for ([_]*State{ left, put }) |s| { + // Lines two rows long at 20 columns, one at 40. + for (0..30) |_| ingest(s, "abcdefghijklmnopqrstuvwxyz0123\r\n"); + viewTo(s, 1); + resize(s, 40, 2, false); + } + viewTo(put, grid(put).view); + for ([_]*State{ left, put }) |s| resize(s, 20, 2, false); + try std.testing.expectEqual(grid(left), grid(put)); +} + test "the luminance table answers exactly what ghostty computes" { for (0..256) |i| { const c: u8 = @intCast(i); -- cgit v1.3 From 71a68eac9d4bce7deb19236a9cc8338b1a37caa1 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 21 Nov 2026 17:31:25 -0300 Subject: layers: with `Changes` off a client's key pays for items A and B no more: all of jj's session state is one field, `Pardes.changes: jj.Session` (jj's answers by pane serial, the `Changes` jj runs for, the one asked meanwhile, how many were asked), whose digest is nothing until a `Changes` is asked and then one update while nothing is asked of jj, where item A had three `Stream` fields (three updates in every digest of the session, and a client's key takes several digests) beside round 4's answers list (one more); `Stream` holds nothing of jj's again (its dispatch lines stay), the session's end lets the worker and the asks go in `Session.deinit`, and the batch's 8-byte `jj` field goes (a `Changes` answer is told by its generation's bit, `jj.gen_bit`, after a paint's, and the pane it is for is the ask's, which every replica holds); measured first, a variant at a time, client-key-down against tree3's pardes-perf in the gate's own layout (ReleaseFast gui, its farms and HOME; my first script's layout read about 0.05% lower): item B as it was small +0.111%, the batch's field gone and the stream's three fields one +0.104%, the session's state one field digested as nothing until asked small +0.047%, large +0.047%, medium +0.010% Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/Core.zig | 10 ++--- core/File.zig | 2 +- core/Stream.zig | 15 ++----- core/jj.zig | 125 +++++++++++++++++++++++++++++++++----------------------- 4 files changed, 83 insertions(+), 69 deletions(-) diff --git a/core/Core.zig b/core/Core.zig index 177a6e78..efa2ac3d 100644 --- a/core/Core.zig +++ b/core/Core.zig @@ -355,10 +355,11 @@ lsp_ask: Ask = .{}, pipe: Pipe = .{}, /// A query pane's Grep, and its Find's listing, on a worker (Stream.zig). stream: Stream = .{}, -/// What jj answered for each pane's `Changes` (jj.zig), by its serial: the -/// session's list, not a field of every pane (a digest and a rollback copy -/// walk every pane's fields at every step). -changes: std.ArrayList(@import("jj.zig").Changes) = .empty, +/// The panes' `Changes` (jj.zig): what was asked of jj, and what it +/// answered for each pane, by its serial: the session's, not a field of +/// every pane (a digest and a rollback copy walk every pane's fields at +/// every step), and nothing in a digest until a `Changes` is asked. +changes: @import("jj.zig").Session = .{}, fs: filesystem.Namespace = .{}, boot: Boot = .shell, @@ -868,7 +869,6 @@ pub fn deinit(p: *Pardes) void { for (p.spawn_dirs) |d| if (d) |dir| gpa.free(dir); p.pipe.deinit(gpa); p.stream.deinit(gpa); - for (p.changes.items) |*c| c.deinit(gpa); p.changes.deinit(gpa); p.handover.deinit(gpa); if (p.stream.ahead.len > 0) p.tree_sitter_gpa.free(p.stream.ahead); diff --git a/core/File.zig b/core/File.zig index ae052344..8749417f 100644 --- a/core/File.zig +++ b/core/File.zig @@ -757,7 +757,7 @@ fn edit(p: *Pardes, f: *State, off: usize, len: usize, bytes_in: []const u8, who }; reportEdit(p, f, off, len, bytes); // A pinned change's per-line values ride with the lines (jj.zig). - if (p.changes.items.len > 0) @import("jj.zig").edited(p, f, off, len, bytes); + if (p.changes.answers.items.len > 0) @import("jj.zig").edited(p, f, off, len, bytes); if (f.mini) |*mini| mini.deinit(p.gpa); f.mini = null; if (f.line_starts.len > 0) shiftIndex(p.gpa, f, off, len, bytes); diff --git a/core/Stream.zig b/core/Stream.zig index 80812840..1d061b52 100644 --- a/core/Stream.zig +++ b/core/Stream.zig @@ -74,11 +74,9 @@ pub const Batch = struct { /// A paint's answer (`paintAhead`): the colours of pane `serial`'s text /// at `revision` from byte `start`, one syntax.Syn a byte. painted: ?struct { serial: u32, revision: u32, start: usize } = null, + /// Or, with a `Changes` generation (jj.gen_bit), jj's annotate (jj's + /// log in `rows`, or its refusal and `end` failed). styles: []u8 = &.{}, - /// A `Changes` answer (jj.zig) for pane `jj`, by serial: jj's log in - /// `rows` and its annotate in `styles`, or its refusal in `rows` and - /// `end` failed. - jj: ?u32 = null, pub const End = enum { done, failed }; @@ -259,14 +257,7 @@ rows_asked_at: u8 = 0, /// Rows asked for their colours while a 9P write was served: asked again /// on the next step (Query.produceAll). rows_later: bool = false, -/// The `Changes` asked of jj and its worker, the one asked while it ran, -/// and how many were asked (jj.zig: one at a time, the last one pinned). -changes: ?jj.Task = null, -changes_next: ?*jj.Ask = null, -changes_count: u32 = 0, - pub fn deinit(s: *Stream, gpa: std.mem.Allocator) void { - jj.cancel(s); s.cancelTask(); s.cancelParse(); s.cancelPaint(); @@ -700,8 +691,8 @@ const Collect = struct { pub fn receive(p: *Pardes, b: *const Batch) void { const s = &p.stream; if (b.parsed) |parsed| return receiveParse(p, b, parsed.serial, parsed.revision); - if (b.jj) |serial| return jj.receive(p, b, serial); if (b.painted != null) return receivePaint(p, b); + if (b.gen & jj.gen_bit != 0) return jj.receive(p, b); if (b.gen != s.gen or (s.state != .searching and s.state != .capped)) { s.dropped += 1; return; diff --git a/core/jj.zig b/core/jj.zig index a381443c..0cdf94a1 100644 --- a/core/jj.zig +++ b/core/jj.zig @@ -241,15 +241,15 @@ pub const Changes = struct { /// What jj answered for pane `serial`'s `Changes` (`Pardes.changes`), if anything. pub fn answered(p: *Pardes, serial: u32) ?*Changes { - for (p.changes.items) |*c| if (c.serial == serial) return c; + for (p.changes.answers.items) |*c| if (c.serial == serial) return c; return null; } /// Pane `serial`'s answers let go (the pane's end). pub fn forget(p: *Pardes, serial: u32) void { - for (p.changes.items, 0..) |*c, i| if (c.serial == serial) { + for (p.changes.answers.items, 0..) |*c, i| if (c.serial == serial) { c.deinit(p.gpa); - _ = p.changes.swapRemove(i); + _ = p.changes.answers.swapRemove(i); return; }; } @@ -339,7 +339,7 @@ pub fn changesWord(c: pardes.builtins.Ctx) void { /// A `Changes` asked of jj: the pane (by serial), the file it shows and the /// revision whose lines are annotated, the revset. Its two runs go on a /// worker where the host has one (the `search` effect: Stream.start), their -/// raw answers back as one input (`Event.search`, its `jj` set) stamped +/// raw answers back as one input (`Event.search`) stamped /// with its generation, which the step takes (`receive`): a replica replays /// that input and never runs jj. With no worker (a test), on the loop, each /// run a site of the step's tape. @@ -367,9 +367,44 @@ pub const Ask = struct { } }; -/// The `Changes` asked and its worker (`Stream.changes`), one at a time: -/// one asked while it runs waits (`Stream.changes_next`), and only the last -/// asked is pinned. +/// The session's `Changes` (`Pardes.changes`): jj's answers, a pane's by +/// its serial; the `Changes` jj runs for, one at a time, the one asked +/// while it runs (only the last asked is pinned), and how many were asked +/// (the generation). In every digest of the session: nothing until a +/// `Changes` is asked, then one update while nothing is asked of jj. +pub const Session = struct { + answers: std.ArrayList(Changes) = .empty, + task: ?Task = null, + next: ?*Ask = null, + count: u32 = 0, + + pub fn digest(c: *const Session, h: *pardes.walk.Hasher) void { + if (c.count == 0) return; + const bits: u64 = c.count | @as(u64, @intFromBool(c.task != null)) << 32 | @as(u64, @intFromBool(c.next != null)) << 33; + h.update(std.mem.asBytes(&bits)); + pardes.walk.hash(std.ArrayList(Changes), &c.answers, h); + if (c.task) |*t| pardes.walk.hash(Task, t, h); + if (c.next) |n| pardes.walk.hash(Ask, n, h); + } + + /// The session's end: the worker canceled, the asks and the answers + /// let go. + pub fn deinit(c: *Session, gpa: std.mem.Allocator) void { + if (c.task) |t| { + c.task = null; + if (t.future) |f| pardes.Stream.join(f, t.io.?, .cancel); + t.ask.deinit(); + } + if (c.next) |a| { + c.next = null; + a.deinit(); + } + for (c.answers.items) |*a| a.deinit(gpa); + c.answers.deinit(gpa); + } +}; + +/// The `Changes` jj runs for, and its worker. pub const Task = struct { // The worker the host started for it, live: a replica has none. pub const replica = .{ .authority = .{ "future", "io" } }; @@ -382,27 +417,26 @@ pub const Task = struct { /// from 0; a paint's has the top one). pub const gen_bit: u32 = 1 << 29; -fn liveGen(s: *const pardes.Stream) u32 { - return gen_bit | (s.changes_count & (gen_bit - 1)); +fn liveGen(c: *const Session) u32 { + return gen_bit | (c.count & (gen_bit - 1)); } /// Ask jj of `revset` for pane `serial` (said at pane `id` while it runs): /// what the pane shows stays until the answer lands. fn ask(p: *Pardes, id: usize, serial: u32, path: []const u8, rev: []const u8, revset: []const u8) void { - const s = &p.stream; - s.changes_count +%= 1; - const a = Ask.make(p.gpa, liveGen(s), serial, path, rev, revset) catch return p.reportFailure(id, "Changes: out of memory"); + p.changes.count +%= 1; + const a = Ask.make(p.gpa, liveGen(&p.changes), serial, path, rev, revset) catch return p.reportFailure(id, "Changes: out of memory"); p.setStatus(.at(id), "Changes: jj\u{2026}"); - if (s.changes != null) { - if (s.changes_next) |old| old.deinit(); - s.changes_next = a; + if (p.changes.task != null) { + if (p.changes.next) |old| old.deinit(); + p.changes.next = a; return; } go(p, a); } fn go(p: *Pardes, a: *Ask) void { - p.stream.changes = .{ .ask = a }; + p.changes.task = .{ .ask = a }; if (p.tape.has(p, .search)) return p.emit(.{ .search = .{ .gen = a.gen } }); runHere(p, a.gen, false); } @@ -410,7 +444,7 @@ fn go(p: *Pardes, a: *Ask) void { /// The host's `search` effect for a `Changes` generation (Stream.start): /// its runs on a worker that sends to `sink`. pub fn start(io: std.Io, gpa: std.mem.Allocator, p: *Pardes, gen: u32, ctx: ?*anyopaque, sink: pardes.Stream.Sink) void { - const t = if (p.stream.changes) |*t| t else return; + const t = if (p.changes.task) |*t| t else return; if (t.ask.gen != gen or t.future != null) return; t.ask.out = gpa; // No worker to be had: here, its answer an input. @@ -427,11 +461,11 @@ fn work(a: *Ask, ctx: ?*anyopaque, sink: pardes.Stream.Sink) void { /// `in_call`: in the host's `search` entry, the answer handed in as an /// input, as a worker's is. pub fn runHere(p: *Pardes, gen: u32, comptime in_call: bool) void { - const t = p.stream.changes orelse return; + const t = p.changes.task orelse return; if (t.ask.gen != gen or t.future != null) return; const b = answer(p, p.gpa, t.ask); defer b.deinit(p.gpa); - if (in_call) p.update(.{ .search = b }) else receive(p, &b, t.ask.serial); + if (in_call) p.update(.{ .search = b }) else receive(p, &b); } /// jj's two answers for `a`, raw, in `gpa`: through `p`'s tape when given @@ -440,7 +474,7 @@ fn answer(p: ?*Pardes, gpa: std.mem.Allocator, a: *const Ask) pardes.Stream.Batc const failed = struct { fn f(g: std.mem.Allocator, at: *const Ask, why: []u8) pardes.Stream.Batch { _ = g; - return .{ .gen = at.gen, .jj = at.serial, .rows = why, .end = .failed }; + return .{ .gen = at.gen, .rows = why, .end = .failed }; } }.f; const set = fileset(gpa, a.path) catch return failed(gpa, a, refusal(gpa, "out of memory").refused); @@ -457,7 +491,7 @@ fn answer(p: ?*Pardes, gpa: std.mem.Allocator, a: *const Ask) pardes.Stream.Batc const any = while (it.next()) |l| { if (pinOf(l) != null) break true; } else false; - if (!any) return .{ .gen = a.gen, .jj = a.serial, .rows = logged, .end = .done }; + if (!any) return .{ .gen = a.gen, .rows = logged, .end = .done }; // Who wrote each line: a path, not a fileset (annotate takes one file // as it is named). const annotate_args = [_][]const u8{ "file", "annotate", "-r", a.rev, "-T", "commit.change_id().short(8) ++ \"\\t\" ++ content", "--", std.Io.Dir.path.basename(a.path) }; @@ -466,7 +500,7 @@ fn answer(p: ?*Pardes, gpa: std.mem.Allocator, a: *const Ask) pardes.Stream.Batc gpa.free(logged); return failed(gpa, a, why); }, - .bytes => |annotated| .{ .gen = a.gen, .jj = a.serial, .rows = logged, .styles = annotated, .end = .done }, + .bytes => |annotated| .{ .gen = a.gen, .rows = logged, .styles = annotated, .end = .done }, }; } @@ -474,25 +508,27 @@ fn runJj(p: ?*Pardes, gpa: std.mem.Allocator, dir: []const u8, args: []const []c return if (p) |q| q.tape.site(.jj, gpa, runHost, .{ gpa, dir, args }) else runHost(gpa, dir, args); } -/// A `Changes` answer (`Event.search`, its `jj` set), borrowed: the last -/// asked's is parsed and pinned on its pane; an earlier one's, or a gone -/// pane's, dropped. Then the one asked meanwhile goes. -pub fn receive(p: *Pardes, b: *const pardes.Stream.Batch, serial: u32) void { - const s = &p.stream; +/// A `Changes` answer (`Event.search` with a `Changes` generation), +/// borrowed: the last asked's is parsed and pinned on its pane (the ask +/// names it); an earlier one's, or a gone pane's, dropped. Then the one +/// asked meanwhile goes. +pub fn receive(p: *Pardes, b: *const pardes.Stream.Batch) void { var revset: [Changes.revset_max]u8 = undefined; var revset_len: usize = 0; - if (s.changes) |t| if (t.ask.gen == b.gen) { - s.changes = null; + var serial: u32 = 0; + if (p.changes.task) |t| if (t.ask.gen == b.gen) { + p.changes.task = null; if (t.future) |f| pardes.Stream.join(f, t.io.?, .wait); + serial = t.ask.serial; revset_len = t.ask.revset.len; @memcpy(revset[0..revset_len], t.ask.revset); t.ask.deinit(); }; - defer if (s.changes == null) if (s.changes_next) |next| { - s.changes_next = null; + defer if (p.changes.task == null) if (p.changes.next) |next| { + p.changes.next = null; go(p, next); }; - if (b.gen != liveGen(s) or revset_len == 0) return; + if (b.gen != liveGen(&p.changes) or revset_len == 0) return; const id = p.paneBySerial(serial) orelse return; pinAnswer(p, id, b, revset[0..revset_len]); } @@ -503,17 +539,17 @@ pub fn receive(p: *Pardes, b: *const pardes.Stream.Batch, serial: u32) void { /// lines, never asking jj again: the lines a splice takes out take their /// values with them, and a line it puts in is nobody's. pub fn edited(p: *Pardes, f: *const File.State, off: usize, len: usize, bytes: []const u8) void { - var i = p.changes.items.len; + var i = p.changes.answers.items.len; while (i > 0) { i -= 1; - const c = &p.changes.items[i]; + const c = &p.changes.answers.items[i]; const id = p.paneBySerial(c.serial) orelse continue; const shown = if (p.panes[id].?.file) |*shown| shown else continue; if (shown.content.ptr != f.content.ptr) continue; splice(p.gpa, c, f.content, off, len, bytes) catch { // No room for it: its values would lie, so it goes. c.deinit(p.gpa); - _ = p.changes.swapRemove(i); + _ = p.changes.answers.swapRemove(i); }; } } @@ -541,19 +577,6 @@ fn splice(gpa: std.mem.Allocator, c: *Changes, text: []const u8, off: usize, len c.lines = next; } -/// The session's end: the worker canceled, the asks let go. -pub fn cancel(s: *pardes.Stream) void { - if (s.changes) |t| { - s.changes = null; - if (t.future) |f| pardes.Stream.join(f, t.io.?, .cancel); - t.ask.deinit(); - } - if (s.changes_next) |a| { - s.changes_next = null; - a.deinit(); - } -} - /// jj's answer `b` for `revset` parsed and pinned on pane `id`, or its /// refusal said there. fn pinAnswer(p: *Pardes, id: usize, b: *const pardes.Stream.Batch, revset: []const u8) void { @@ -583,7 +606,7 @@ fn pinAnswer(p: *Pardes, id: usize, b: *const pardes.Stream.Batch, revset: []con if (answered(p, pane.serial)) |kept| { kept.deinit(p.gpa); kept.* = changes.*; - } else p.changes.append(p.gpa, changes.*) catch { + } else p.changes.answers.append(p.gpa, changes.*) catch { changes.deinit(p.gpa); return p.reportFailure(id, "Changes: out of memory"); }; @@ -1199,7 +1222,7 @@ const WorkerJj = struct { /// answer the session's input, as its loop hands it, and the client's. fn land(w: *WorkerJj) !void { var waited: u32 = 0; - while (w.a.core.stream.changes != null or w.a.core.stream.changes_next != null) : (waited += 1) { + while (w.a.core.changes.task != null or w.a.core.changes.next != null) : (waited += 1) { if (waited == 5000) return error.Timeout; var batch: Inbox.Batch = .{}; w.shell.q.takeInto(&batch); @@ -1254,7 +1277,7 @@ test "the pane closed before its Changes answer: nothing pinned, nothing kept" { try w.word("Del"); try testing.expect(w.a.core.panes[w.id] == null or w.a.core.panes[w.id].?.serial != w.serial); try w.land(); - try testing.expectEqual(@as(usize, 0), w.a.core.changes.items.len); + try testing.expectEqual(@as(usize, 0), w.a.core.changes.answers.items.len); } test "Changes draws a lane a pinned change after the line number, nested ones a level to the right on their rows only, and a line one added whole green across it; bare again, the gutter as it was" { -- cgit v1.3 From 32245dce9a1a09e4a95b16b0503e9ef6410dc5d2 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Sat, 21 Nov 2026 19:06:05 -0300 Subject: terminals' views: a view is its row again after every reflow (terminal.zig `reflow`, which `resize` and `resizeDeferred` share: ghostty's pinned view set to column 0), so the row a replica's rollback puts a terminal's view back at (replica.zig `keepViews`/`putViews`, the view's row index, the one record of an emulator's view outside the copy) is the view that was there: ghostty pins a view to a CELL, a widening that joins a wrapped line's second row to its first left that cell mid-row, and the next narrowing carried it a row down, where a client put back by its row (at row 0 ghostty's `.top`) stayed: the same digest (the offset) until that reflow, then the client's view a row above the session's, the bytes soak's divergence (round 5: 5 whole runs of 29, every naming a 2-row pane at its history's top, `cat`'s long lines wrapped, panes resized all through); the previous change's two tests pass (term-test 19/19, the replica test under shell-test), a fuzz of put-back against left-alone emulators under random output, reflows and scrolls went from 5 apart in 191 seeds to 0 in 3,000; core-test 885/1046 (161 skipped), shell-test 1088/1091 (3 skipped), each the base's plus the new test (loads 5-11); the bytes soak, whole, untraced, --witness, on this tree frozen (its session doing nothing extra): 21 of 21 clean (against 5 of 29 before), seed 2 at 80 ms alone 16 of 16; the screen-state soak 5 of 6 (s9b-2: seed 1 at 207 ms, 'digest 11 differs in the session', the open screen-state fault scr-1, not this one); the frame and perf gate against tree3 PASS (77/77 frames, corpus2x +0.046%, 121 counts within 0.1%, client-key-down +0.0286%); daemon.py --far and --clients x3 on Debug and ReleaseSafe, plain 5 of 5 after one timing failure on each build at load 5-7, each passing again alone; nothing in replica.zig, tape.zig or wire.zig; a user sees a scrolled-back terminal keep the row its top line starts on through a widening and a narrowing (ghostty kept the joined cell's row: within a row of it); screen-state clients never reflow their own emulator and their terminal views are not digested: not this fault there Co-Authored-By: Claude Opus Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- core/term/terminal.zig | 19 +++++++++++++++---- 1 file changed, 15 insertions(+), 4 deletions(-) diff --git a/core/term/terminal.zig b/core/term/terminal.zig index 535ca6dc..187ed144 100644 --- a/core/term/terminal.zig +++ b/core/term/terminal.zig @@ -631,19 +631,30 @@ pub fn resize(state: *State, cols: u16, rows: u16, later: bool) void { state.resize_to = .{ .cols = cols, .rows = rows }; return; } - state.changes +%= 1; - state.vt.resize(state.gpa, .{ .cols = cols, .rows = rows }) catch {}; + reflow(state, cols, rows); } /// The size `resize` left for later, made; whether there was one. pub fn resizeDeferred(state: *State) bool { const size = state.resize_to orelse return false; state.resize_to = null; - state.changes +%= 1; - state.vt.resize(state.gpa, .{ .cols = size.cols, .rows = size.rows }) catch {}; + reflow(state, size.cols, size.rows); return true; } +/// Its grid reflowed, and its view a row of its history again, as `viewTo` +/// and `grid` have it: ghostty's view follows a cell, which a widening +/// can leave mid-row (a wrapped line's second row joined to its first) and +/// the next narrowing carries a row down, where a view put back at its row +/// (a replica's rollback, core/replica.zig `putViews`) stays. +fn reflow(state: *State, cols: u16, rows: u16) void { + state.changes +%= 1; + state.vt.resize(state.gpa, .{ .cols = cols, .rows = rows }) catch {}; + inline for (.{ .primary, .alternate }) |which| if (state.vt.screens.get(which)) |screen| { + if (screen.pages.viewport == .pin) screen.pages.viewport_pin.x = 0; + }; +} + /// The emulator's size in pixels follows the core's cells: kitty graphics /// placements are sized by it, and CSI 14/16 t report it. pub fn cellPixels(state: *State, w: u32, h: u32) void { -- cgit v1.3