From c6e5b0aec57394f7459377dae1d3fa45550e7bf0 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Thu, 5 Nov 2026 19:27:34 -0300 Subject: split pardes.zig by noun, Effect: what goes out moves into src/Effect.zig, the clean room's name: the Effect union (its Buf now pub, the session's fields name Effect.Buf), PtySignal, WatchMode, the two caps and the assert that a write costs the ring no room, with perform and the two helpers only it calls (writeChecked, promoteSaved); the root names the types as before and the session keeps p.perform as a declaration alias (the hosts and the tape call it); the outbox (emit, nextEffect and the parked writes) stays with the session, as the clean room's Core has emit; tests moved with perform, by name: Detach asks the host to let its terminal go, and says so when there is nothing to leave; Save on a scratch asks for a path in its inherited dir and makes it a file; Save on a terminal writes its plaintext scrollback and stays a terminal; Save on an output buffer writes its rows out and leaves the buffer alone; Save takes the path as an argument, relative to the pane's own directory; a save the host could not do leaves the pane dirty; Save elsewhere copies a file's bytes and keeps the pane on its own file; saves armed in one batch stay with their own panes; a save whose pane is gone before the drain writes nothing; Save reaches every tagline with text behind it and no other; a save path that names no file is refused before anything is rewritten; a Save the host could not do logs no save record (and their helper drainForSavePath); a pure move, no field touched, a dump and the wire as they were; gates: tui core-test 960/960, behaviour-test 238/238, gui unit-test 1518/1519 (1 skipped) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016Y9MNAtZenFv4weoMD3cge --- src/Effect.zig | 663 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 663 insertions(+) create mode 100644 src/Effect.zig (limited to 'src/Effect.zig') diff --git a/src/Effect.zig b/src/Effect.zig new file mode 100644 index 00000000..f9b0e645 --- /dev/null +++ b/src/Effect.zig @@ -0,0 +1,663 @@ +//! What goes out: the effects the core asks its host for (a child, a pty's +//! bytes, a save, a dump, a language server's question), and `perform`, +//! which hands one to the host, or to the in-process fallback a host +//! without that method has. +const std = @import("std"); +const pardes = @import("pardes.zig"); +const tape = @import("tape.zig"); +const panes = @import("panes.zig"); +const ctlfs = @import("ninep/tree.zig"); +const filesystem = @import("fs.zig"); +const host_io = @import("host_io.zig"); +const exec = @import("exec.zig"); +const lsp = @import("lsp/lsp.zig"); +const Stream = @import("Stream.zig"); +const edit = @import("edit.zig"); +const tagline = @import("tagline.zig"); +const Pardes = pardes.Pardes; +const Pane = panes.Pane; +const Host = pardes.Host; + +/// `command` is Kill's: SIGTERM to the terminal's foreground job, and never +/// to the shell itself when the shell is in the foreground. +pub const PtySignal = enum(u8) { int, term, hup, quit, kill }; + +/// IO the core wants done. Payloads are inline (fixed buffers): effects are +/// queued values with no lifetime ties back into the core. +pub const WatchMode = enum { reconcile, baseline_disk }; + +pub const effect_path_cap = 256; + +/// The bytes one `write` carries, a pty write in the hosts: as many as a +/// path's, which already size the union, so they cost the ring no room +/// (268 bytes an effect at 64 and at 256). +pub const effect_write_cap = 256; + +pub const Effect = union(enum) { + /// A child for the pane in slot `pane` -- the one whose serial is + /// `serial`: a pane closed and its slot taken before the effect is + /// performed is not the one it was for (perform). + spawn: struct { pane: u8, serial: u32, cwd: Buf(effect_path_cap) }, + write: struct { pane: u8, bytes: Buf(effect_write_cap) }, + resize_pty: struct { pane: u8, cols: u16, rows: u16 }, + /// For the pane whose serial is `serial`, as `spawn` is (perform). + signal_pty: struct { pane: u8, serial: u32, sig: PtySignal }, + /// The terminal pane in this slot is gone: the shell hangs up its pty + /// and ends the shell, rather than leave it running with nobody to read. + close_pty: struct { pane: u8 }, + open_link: Buf(256), + /// write this pane's file content to its path; the shell reads both off + /// the core (content is unbounded, effects are fixed-size values) + save_file: struct { pane: u8 }, + save_text: struct { pane: u8, serial: u32, path: Buf(effect_path_cap), promote: bool = false }, + write_dump, + set_clipboard, + read_clipboard, + /// `arg` up to 128 bytes, or for `explain` the query it explains, + /// ` `. + lsp: struct { id: u32, kind: lsp.Kind, pane: u8, offset: u32, arg: Buf(160) }, + /// Snapshot the matching request with pipeRequest(id), then run it away + /// from the UI/event loop and answer with pipe_resp. + pipe: struct { id: u32 }, + /// Start the disk search of this generation (Stream.start) on a worker + /// posting into the shell's inbox. + search: struct { gen: u32 }, + /// Carry `handover.bytes`, the dump of handover `seq`, to another + /// window, answering with `handed` (Handover.zig). + hand_over: struct { seq: u32 }, + /// Write what an Edit's `w` took (`Pipe.writes`), in order. + edit_write, + watch: struct { pane: u8, on: bool, mode: WatchMode = .reconcile }, + theme_file: struct { generation: u32, on: bool }, + /// Write the build-time theme ring below the per-user config directory. + /// The pane receives the completion/error message from the native host. + dump_themes: struct { pane: u8 }, + detach: struct { pane: u8 }, + quit, + + pub fn Buf(comptime n: usize) type { + return struct { + pub const replica = .{ .len = .{.{ "data", "len" }} }; + data: [n]u8 = undefined, + len: u16 = 0, + pub const cap = n; + pub fn slice(b: *const @This()) []const u8 { + return b.data[0..b.len]; + } + pub fn from(text: []const u8) @This() { + var b: @This() = .{}; + std.debug.assert(text.len <= n); + @memcpy(b.data[0..text.len], text); + b.len = @intCast(text.len); + return b; + } + }; + } +}; + +comptime { + // A write is never the union's largest variant, so its bytes cost the + // ring of effects no room (effect_write_cap). + std.debug.assert(@sizeOf(@FieldType(Effect, "write")) <= @sizeOf(@FieldType(Effect, "spawn"))); +} + +pub fn perform(p: *Pardes, e: Effect) void { + const taped = tape.enter(p, .{ .perform = e }); + defer tape.leave(p, taped); + // A Save performed on one twin is every twin's (File.syncTwins). + defer panes.File.syncTwins(p); + const v = p.host.vtable; + switch (e) { + // The host reads the pane (its command, its shell) as it forks, + // so the slot must still hold the pane the spawn was for. + .spawn => |s| if (if (p.panes[s.pane]) |pane| pane.serial != s.serial else true) {} else if (v.spawn) |f| f(p.host.ctx, s.pane, if (s.cwd.len == 0) (p.spawn_dirs[s.pane] orelse "") else s.cwd.slice()) else { + p.fallback.spawned[s.pane] = true; + }, + // A pane with no child is silent: nothing invents output on its + // screen, and the bytes are dropped rather than transcribed. + .write => |w| if (v.pty_write) |f| f(p.host.ctx, w.pane, w.bytes.slice()), + .resize_pty => |r| if (v.pty_resize) |f| f(p.host.ctx, r.pane, r.cols, r.rows), + // A signal for a pane that closed, its slot retaken in the same + // step, would reach another pane's child. + .signal_pty => |s| if (if (p.panes[s.pane]) |pane| pane.serial != s.serial else true) {} else if (v.pty_signal) |f| f(p.host.ctx, s.pane, s.sig), + .close_pty => |c| if (v.close_pty) |f| f(p.host.ctx, c.pane), + .open_link => |u| if (v.open_link) |f| + f(p.host.ctx, u.slice()) + else + p.fallback.setLink(u.slice()), + .save_file => |sf| { + const pane = p.panes[sf.pane] orelse return; + const f = if (pane.file) |*file| file else return; + const was = f.saved_revision; + f.saved_revision = f.revision; + // A save the host could not do (saveFailed) is its err + // record alone, not a `save`, and changes nothing: a clean + // file stays clean. + const saved_pane = writeChecked(p, sf.pane, pane.serial, f.path, f.content, was) orelse return; + const saved = if (saved_pane.file) |*file| file else return; + // Edited while it was written: what is on disk is not this. + if (saved.saved_revision != saved.revision) return; + saved.disk_gone = false; + ctlfs.events.noteLog(p, .save, saved_pane); + // On disk now, a new file too: Recent has it, open. + if (saved.output == null and Pardes.recentKeeps(saved.path)) p.recent.opened(p.recentGpa(), saved.path); + if (!saved.watch_after_save) return; + saved.watch_after_save = false; + if (filesystem.localPath(saved.path) != null) + p.emit(.{ .watch = .{ .pane = sf.pane, .on = true } }); + }, + .save_text => |st| { + const pane = p.panes[st.pane] orelse return; + if (pane.serial != st.serial) return; // a recycled slot: not ours + if (pane.file) |*f| { + // Failed, it changes nothing: not the name, not dirty. + const after = writeChecked(p, st.pane, st.serial, st.path.slice(), f.content, f.saved_revision) orelse return; + if (after.file == null) return; + if (st.promote) promoteSaved(p, st.pane, st.path.slice()) else ctlfs.events.noteLogAs(p, .save, after, st.path.slice()); + return; + } + if (!pane.isTerminal()) return; + const text = panes.terminal.screenTextAlloc(pane, p.gpa) catch return; + defer p.gpa.free(text); + if (writeChecked(p, st.pane, st.serial, st.path.slice(), text, 0)) |still| + ctlfs.events.noteLogAs(p, .save, still, st.path.slice()); + }, + .write_dump => { + const out = p.dump_out orelse return; + if (v.write_dump) |f| { + f(p.host.ctx, out); + } else { + _ = p.fallback.writeFile(host_io.Fallback.dump_path, out); + p.setLastDump(host_io.Fallback.dump_path); + } + }, + .set_clipboard => { + const text = p.registers.text(p.gpa, '+') orelse ""; + if (v.set_clipboard) |f| f(p.host.ctx, text) else p.fallback.setClipboard(text); + }, + // No desktop to ask: answer from the in-process clipboard at once, + // which is the same shape as a host answering later. + .read_clipboard => if (v.read_clipboard) |f| + f(p.host.ctx) + else + p.update(.{ .paste = p.fallback.clipboard.items }), + .lsp => |q| if (v.lsp) |f| + f(p.host.ctx, .{ .id = q.id, .kind = q.kind, .pane = q.pane, .offset = q.offset, .arg = q.arg.slice() }) + else + p.update(.{ .lsp_resp = .{ .id = q.id, .rows = "" } }), + .pipe => |q| if (v.pipe) |f| + f(p.host.ctx, q.id) + else + p.update(.{ .pipe_resp = .{ .id = q.id, .success = false, .outputs = &.{} } }), + // No workers here (a test, a board): it runs on the loop. + .search => |q| if (v.search) |f| f(p.host.ctx, q.gen) else Stream.runHere(p, q.gen), + // No windows here (a test, the tty): it stays. + .hand_over => |h| if (v.hand_over) |f| { + if (p.handover.bytes) |bytes| f(p.host.ctx, h.seq, bytes); + } else p.update(.{ .handed = .{ .seq = h.seq, .failure = "no other windows here" } }), + .edit_write => { + // Each write takes the bytes `w` took when it ran: the text + // as it was before the Edit's changes. + var writes = p.pipe.writes; + p.pipe.writes = .empty; + defer { + for (writes.items) |*w| w.deinit(p.gpa); + writes.deinit(p.gpa); + } + for (writes.items) |w| { + const was = if (p.panes[w.pane]) |pane| (if (pane.file) |f| f.saved_revision else 0) else 0; + // Failed, it changes nothing, as save_text's does not. + const pane = writeChecked(p, w.pane, w.serial, w.path, w.bytes, was) orelse continue; + const f = if (pane.file) |*file| file else continue; + if (w.promote) { + promoteSaved(p, w.pane, w.path); + } else if (w.clean != null and w.clean.? == f.revision) { + f.saved_revision = f.revision; + f.disk_gone = false; + ctlfs.events.noteLog(p, .save, pane); + } else ctlfs.events.noteLogAs(p, .save, pane, w.path); + } + }, + .watch => |w| if (v.watch_file) |f| { + // What a watch is about: a real file, or a PDF. + const path: []const u8 = if (p.panes[w.pane]) |pane| (if (pane.file) |file| (if (file.output == null) file.path else "") else pane.pdfPath() orelse "") else ""; + f(p.host.ctx, w.pane, path, w.on, w.mode); + } else { + p.fallback.watched[w.pane] = w.on; + }, + .theme_file => |t| if (v.watch_theme) |f| f(p.host.ctx, t.generation, t.on), + .dump_themes => |d| if (v.dump_themes) |f| f(p.host.ctx, d.pane), + .detach => |d| if (v.detach) |f| + f(p.host.ctx) + else + p.reportError(d.pane, "detach", error.NotAttached), + // the loop's own condition; a host tears down after its own loop + .quit => p.quit = true, + } +} + +/// Writes `bytes` to `path` for pane `id`, its directories made first: +/// the pane after it, if it is still the one `serial` names and the +/// write did not fail. A failed write changes nothing: its file goes +/// back to the saved revision `was`, dirty as it was. +pub fn writeChecked(p: *Pardes, id: u8, serial: u32, path: []const u8, bytes: []const u8, was: u32) ?*Pane { + const failures = p.fs.failures; + // A Save makes the directories its file goes in, and any above them, + // first: one rule, for the pane's own name and `Save path` alike. A + // directory it cannot make leaves the write to fail and say why. + if (filesystem.localPath(path)) |local| filesystem.makeDirs(std.fs.path.dirname(local) orelse "/"); + // The in-process filesystem reports the same way a real host does, + // so an OOM there leaves the pane dirty rather than looking saved. + if (p.host.vtable.write_file) |f| f(p.host.ctx, id, path, bytes) else if (!p.fallback.writeFile(path, bytes)) p.saveFailed(id, path, error.OutOfMemory); + const pane = p.panes[id] orelse return null; + if (pane.serial != serial) return null; + if (p.fs.failures == failures) return pane; + if (pane.file) |*f| f.saved_revision = was; + return null; +} + +/// A write of `path` the host could not do: the pane stays dirty, the +/// message row says `Save : `, and the 9P write that asked +/// for it, waiting on the save, fails with that (`fs.late_failure`). +/// A scratch written to `path` is that file from here on: named, an +/// ordinary file pane, clean, and watched (exec.saveTo). +fn promoteSaved(p: *Pardes, id: u8, path: []const u8) void { + const pane = p.panes[id] orelse return; + const f = if (pane.file) |*file| file else return; + const owned = p.gpa.dupe(u8, path) catch return; + p.gpa.free(f.path); + f.path = owned; + f.output = null; + pane.clearCwd(); + // re-derive the tag as a plain file's + if (pane.tag.own) |own| p.gpa.free(own); + pane.tag.own = null; + f.saved_revision = f.revision; + f.disk_gone = false; + ctlfs.events.noteLog(p, .save, pane); + p.recent.opened(p.recentGpa(), f.path); + if (filesystem.localPath(f.path) != null) + p.emit(.{ .watch = .{ .pane = id, .on = true } }); +} + +fn drainForSavePath(p: *Pardes, buf: []u8) ?[]const u8 { + var len: ?usize = null; + while (p.nextEffect()) |effect| { + switch (effect) { + .save_text => |st| { + const path = st.path.slice(); + @memcpy(buf[0..path.len], path); + len = path.len; + }, + else => {}, + } + p.perform(effect); + } + return if (len) |n| buf[0..n] else null; +} + +test "Detach asks the host to let its terminal go, and says so when there is nothing to leave" { + if (comptime !pardes.can_attach) return; // the word is compiled out elsewhere: see `can_attach` + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + + try std.testing.expect(p.executeBuiltinLine(0, "Detach")); + const asked = while (p.nextEffect()) |effect| switch (effect) { + .detach => |d| break d, + else => {}, + } else return error.NoDetachAsked; + try std.testing.expectEqual(@as(u8, 0), asked.pane); + + p.perform(.{ .detach = asked }); + const pane = p.panes[0].?; + try std.testing.expectEqualStrings("detach: not attached", pane.msg[0..pane.msg_len]); + try std.testing.expect(!p.quit); +} + +test "Save on a scratch asks for a path in its inherited dir and makes it a file" { + const p = try Pardes.init(std.testing.allocator, .{ .shells = 3, .cols = 100, .rows = 30 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + + const source: usize = 2; + p.setCwd(source, "/tmp/pardes-save-dir"); + try std.testing.expect(p.executeBuiltinLine(source, "New")); + const id = p.active; + const np = p.panes[id].?; + p.sync(); // the frame boundary that gives the new pane its geometry + while (p.nextEffect()) |_| {} + + // Save on a scratch arms a PATH input, prefilled with the inherited dir + try std.testing.expect(p.executeBuiltinLine(id, "Save")); + try std.testing.expect(np.prompt == .save); + try std.testing.expectEqualStrings(" Save /tmp/pardes-save-dir/", np.promptText().?); + + // typing the filename and submitting converts it into an ordinary file + edit.insertKey(p, &np.input, .{ .cp = 'n', .text = "note.txt" }); + exec.submitSave(p, id); + // The write asked for, the pane is the file once it is done. + var saved = false; + while (p.nextEffect()) |effect| { + if (effect == .save_text and @as(usize, effect.save_text.pane) == id) saved = true; + p.perform(effect); + } + try std.testing.expect(saved); + try std.testing.expect(np.file.?.output == null); + try std.testing.expectEqualStrings("/tmp/pardes-save-dir/note.txt", np.file.?.path); + try std.testing.expectEqual(np.file.?.revision, np.file.?.saved_revision); +} + +test "Save on a terminal writes its plaintext scrollback and stays a terminal" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 8 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + p.setCwd(0, "/tmp/pardes-tty-save"); + p.update(.{ .output = .{ .pane = 0, .bytes = "hello scrollback\r\n" } }); + while (p.nextEffect()) |_| {} + + try std.testing.expect(p.executeBuiltinLine(0, "Save")); + try std.testing.expect(pane.prompt == .save); + edit.insertKey(p, &pane.input, .{ .cp = 'l', .text = "log.txt" }); + exec.submitSave(p, 0); + + // the pane is untouched: still a terminal, no file behind it + try std.testing.expect(pane.isTerminal()); + try std.testing.expect(pane.file == null); + + // the host performs it, reading the scrollback off the pane as it goes + var buf: [256]u8 = undefined; + try std.testing.expectEqualStrings( + "/tmp/pardes-tty-save/log.txt", + drainForSavePath(p, &buf) orelse return error.NoSaveAsked, + ); + const written = p.fallback.get("/tmp/pardes-tty-save/log.txt") orelse return error.NothingWritten; + try std.testing.expect(std.mem.indexOf(u8, written, "hello scrollback") != null); +} + +test "Save on an output buffer writes its rows out and leaves the buffer alone" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .shells = 3, .cols = 100, .rows = 30 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + + const source: usize = 2; + p.setCwd(source, "/tmp/pardes-output-save"); + try std.testing.expect(p.executeBuiltinLine(source, "Help")); + p.sync(); // the frame boundary that gives the new pane its geometry + while (p.nextEffect()) |_| {} + + const help: panes.Output.Origin = .{ .cmd = .Help }; + const id = blk: { + for (p.panes, 0..) |slot, i| { + const pane = slot orelse continue; + const f = pane.file orelse continue; + const o = f.output orelse continue; + if (std.meta.eql(o.from, help)) break :blk i; + } + return error.MissingHelpBuffer; + }; + const out = p.panes[id].?; + const path = try gpa.dupe(u8, out.file.?.path); + defer gpa.free(path); + const rows = try gpa.dupe(u8, out.file.?.content); + defer gpa.free(rows); + + // Save leads its tagline now, and the path is REQUIRED: a bare Save asks + try std.testing.expectEqualStrings(tagline.file_pane_tail, tagline.curTail(out)); + try std.testing.expect(p.executeBuiltinLine(id, "Save")); + try std.testing.expect(out.prompt == .save); + edit.insertKey(p, &out.input, .{ .cp = 'h', .text = "help.txt" }); + exec.submitSave(p, id); + + // the buffer itself is untouched: same origin, same name, still refillable + // and still walked by n/N, because a saved copy of a list is only a copy + try std.testing.expect(out.file.?.output != null); + try std.testing.expectEqual(help, out.file.?.output.?.from); + try std.testing.expectEqualStrings(path, out.file.?.path); + + var buf: [256]u8 = undefined; + try std.testing.expectEqualStrings( + "/tmp/pardes-output-save/help.txt", + drainForSavePath(p, &buf) orelse return error.NoSaveAsked, + ); + try std.testing.expectEqualStrings( + rows, + p.fallback.get("/tmp/pardes-output-save/help.txt") orelse return error.NothingWritten, + ); +} + +test "Save takes the path as an argument, relative to the pane's own directory" { + const p = try Pardes.init(std.testing.allocator, .{ .tty_only = true, .cols = 40, .rows = 8 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = p.panes[0].?; + p.setCwd(0, "/tmp/pardes-arg-save"); + p.update(.{ .output = .{ .pane = 0, .bytes = "typed and gone\r\n" } }); + while (p.nextEffect()) |_| {} + + var buf: [256]u8 = undefined; + try std.testing.expect(p.executeBuiltinLine(0, "Save session.txt")); + try std.testing.expect(pane.prompt != .save); + try std.testing.expectEqualStrings( + "/tmp/pardes-arg-save/session.txt", + drainForSavePath(p, &buf) orelse return error.NoSaveAsked, + ); + const written = p.fallback.get("/tmp/pardes-arg-save/session.txt") orelse return error.NothingWritten; + try std.testing.expect(std.mem.indexOf(u8, written, "typed and gone") != null); + + // `.` and `..` normalize with it, so this is that same file and not a + // second one spelled differently + try std.testing.expect(p.executeBuiltinLine(0, "Save ./sub/../session.txt")); + try std.testing.expectEqualStrings( + "/tmp/pardes-arg-save/session.txt", + drainForSavePath(p, &buf) orelse return error.NoSaveAsked, + ); + + try std.testing.expect(p.executeBuiltinLine(0, "Save /tmp/pardes-elsewhere/abs.txt")); + try std.testing.expectEqualStrings( + "/tmp/pardes-elsewhere/abs.txt", + drainForSavePath(p, &buf) orelse return error.NoSaveAsked, + ); + try std.testing.expect(pane.isTerminal()); + + p.panes[0].?.clearCwd(); + try std.testing.expect(p.executeBuiltinLine(0, "Save nowhere.txt")); + try std.testing.expect(drainForSavePath(p, &buf) == null); +} + +test "a save the host could not do leaves the pane dirty" { + const gpa = std.testing.allocator; + const Refusing = struct { + fn writeFile(ctx: ?*anyopaque, pane: u8, _: []const u8, _: []const u8) void { + const core: *Pardes = @ptrCast(@alignCast(ctx.?)); + core.saveFailed(pane, "/x/y.txt", error.PermissionDenied); + } + }; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = try p.setTestFile("before\n"); + panes.File.setContent(p, &pane.file.?, try gpa.dupe(u8, "after\n")); + try std.testing.expect(pane.file.?.revision != pane.file.?.saved_revision); + + p.host = .{ .ctx = p, .vtable = &.{ .write_file = Refusing.writeFile } }; + try std.testing.expect(p.executeBuiltinLine(0, "Save")); + while (p.nextEffect()) |effect| p.perform(effect); + try std.testing.expect(pane.file.?.revision != pane.file.?.saved_revision); + + // ...and the same save against a host that CAN write does come clean, so + // the guard above is not simply "never clean". + p.host = .{}; + try std.testing.expect(p.executeBuiltinLine(0, "Save")); + while (p.nextEffect()) |effect| p.perform(effect); + try std.testing.expectEqual(pane.file.?.revision, pane.file.?.saved_revision); + try std.testing.expectEqualStrings("after\n", p.fallback.get("/test.txt").?); +} + +test "Save elsewhere copies a file's bytes and keeps the pane on its own file" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + const pane = try p.setTestFile("before\n"); + panes.File.setContent(p, &pane.file.?, try gpa.dupe(u8, "after\n")); + try std.testing.expect(pane.file.?.revision != pane.file.?.saved_revision); + + var buf: [256]u8 = undefined; + try std.testing.expect(p.executeBuiltinLine(0, "Save /tmp/pardes-copy/other.txt")); + // a copy, never a rename: the pane keeps its file, and that file is still + // unsaved, so the marker stays where it was + try std.testing.expectEqualStrings("/test.txt", pane.file.?.path); + try std.testing.expect(pane.file.?.revision != pane.file.?.saved_revision); + try std.testing.expectEqualStrings( + "/tmp/pardes-copy/other.txt", + drainForSavePath(p, &buf) orelse return error.NoSaveAsked, + ); + try std.testing.expectEqualStrings( + "after\n", + p.fallback.get("/tmp/pardes-copy/other.txt") orelse return error.NothingWritten, + ); + + // its own path, spelled out, is the in-place write — nothing is asked of + // the host but save_file, and the pane comes clean + try std.testing.expect(p.executeBuiltinLine(0, "Save /test.txt")); + try std.testing.expect(drainForSavePath(p, &buf) == null); + try std.testing.expectEqual(pane.file.?.revision, pane.file.?.saved_revision); +} + +test "saves armed in one batch stay with their own panes" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .shells = 3, .cols = 100, .rows = 30 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + + const tty_id = p.freeSlot() orelse return error.NoPaneSlots; + const shell = try p.newShell(tty_id, "/tmp/pardes-batch"); + p.setCwd(tty_id, "/tmp/pardes-batch"); + p.update(.{ .output = .{ .pane = @intCast(tty_id), .bytes = "shell text\r\n" } }); + const file = try p.setTestFile("file text\n"); + const file_id = p.paneIdOf(file) orelse return error.MissingFilePane; + try std.testing.expect(shell.isTerminal()); + try std.testing.expect(tty_id != file_id); + while (p.nextEffect()) |_| {} + + // both armed before the host drains anything — the path rides inside its + // own effect, so neither can be written with the other pane's text + try std.testing.expect(p.executeBuiltinLine(tty_id, "Save tty.txt")); + try std.testing.expect(p.executeBuiltinLine(file_id, "Save /tmp/pardes-batch/file.txt")); + while (p.nextEffect()) |effect| p.perform(effect); + const tty_bytes = p.fallback.get("/tmp/pardes-batch/tty.txt") orelse return error.NothingWritten; + try std.testing.expect(std.mem.indexOf(u8, tty_bytes, "shell text") != null); + try std.testing.expectEqualStrings( + "file text\n", + p.fallback.get("/tmp/pardes-batch/file.txt") orelse return error.NothingWritten, + ); +} + +test "a save whose pane is gone before the drain writes nothing" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .shells = 3, .cols = 100, .rows = 30 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + + const doomed = p.freeSlot() orelse return error.NoPaneSlots; + const shell = try p.newShell(doomed, "/tmp/pardes-gone"); + p.update(.{ .output = .{ .pane = @intCast(doomed), .bytes = "doomed text\r\n" } }); + while (p.nextEffect()) |_| {} + try std.testing.expect(shell.isTerminal()); + + // Save, then close the pane, then let the host drain: the bytes are read + // off the pane at drain time, so there are none to read... + try std.testing.expect(p.executeBuiltinLine(doomed, "Save /tmp/pardes-gone/log.txt")); + try std.testing.expect(p.executeBuiltinLine(doomed, "Del")); + while (p.nextEffect()) |effect| p.perform(effect); + try std.testing.expect(p.fallback.get("/tmp/pardes-gone/log.txt") == null); + + // ...and a pane that took the freed slot in the meantime is NOT the pane + // that asked, which is what the serial in the effect is for + try std.testing.expect(p.executeBuiltinLine(0, "Save /tmp/pardes-gone/recycled.txt")); + try std.testing.expect(p.executeBuiltinLine(0, "Del")); + const reused = p.freeSlot() orelse return error.NoPaneSlots; + _ = try p.newShell(reused, "/tmp/pardes-gone"); + while (p.nextEffect()) |effect| p.perform(effect); + try std.testing.expect(p.fallback.get("/tmp/pardes-gone/recycled.txt") == null); +} + +test "Save reaches every tagline with text behind it and no other" { + const gpa = std.testing.allocator; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + + const out = try p.setTestFile("build.zig:1:1 pub fn main\n"); + out.file.?.output = .{ .from = .search }; + try std.testing.expectEqualStrings(tagline.locations_pane_tail, tagline.curTail(out)); + + // A scratch is an output buffer that wears the FILE tails. + out.file.?.output = .{ .from = .{ .cmd = std.meta.stringToEnum(pardes.Builtin, "New").? } }; + try std.testing.expectEqualStrings(" Save Term Collapse Del", tagline.curTail(out)); + + // An image's bytes on disk already are what they are: nothing of the + // pane's own is unwritten, so the word is absent and inert. + const img_id = p.freeSlot().?; + const img = try panes.Image.create(p, img_id, "/tmp/pardes-tag.ppm", &.{}); + try std.testing.expectEqualStrings(" Term Collapse Del", tagline.curTail(img)); + try std.testing.expect(p.executeBuiltinLine(img_id, "Save")); + try std.testing.expect(img.prompt != .save); + var buf: [256]u8 = undefined; + try std.testing.expect(drainForSavePath(p, &buf) == null); +} + +test "a save path that names no file is refused before anything is rewritten" { + const p = try Pardes.init(std.testing.allocator, .{ .shells = 3, .cols = 100, .rows = 30 }); + defer p.deinit(); + while (p.nextEffect()) |_| {} + + const source: usize = 2; + p.setCwd(source, "/tmp/pardes-refuse"); + try std.testing.expect(p.executeBuiltinLine(source, "New")); + const id = p.active; + const scratch = p.panes[id].?; + p.sync(); + while (p.nextEffect()) |_| {} + + try std.testing.expect(p.executeBuiltinLine(id, "Save")); + try std.testing.expect(scratch.prompt == .save); + exec.submitSave(p, id); + var buf: [256]u8 = undefined; + try std.testing.expect(drainForSavePath(p, &buf) == null); + try std.testing.expect(scratch.file.?.output != null); + try std.testing.expectEqualStrings("/tmp/pardes-refuse/+New", scratch.file.?.path); + + // ...and neither is a multi-line selection chorded onto the word + try std.testing.expect(p.executeBuiltinLine(id, "Save one\ntwo")); + try std.testing.expect(drainForSavePath(p, &buf) == null); + try std.testing.expect(scratch.file.?.output != null); +} + +test "a Save the host could not do logs no save record" { + const th = @import("ninep/testing.zig"); + const p = try th.withFile(std.testing.allocator, "x\n"); + defer p.deinit(); + const Failing = struct { + core: *Pardes, + const vtable: Host.VTable = .{ .write_file = write }; + fn write(ctx: ?*anyopaque, pane: u8, path: []const u8, _: []const u8) void { + const f: *@This() = @ptrCast(@alignCast(ctx.?)); + f.core.saveFailed(pane, path, error.AccessDenied); + } + }; + var host: Failing = .{ .core = p }; + p.host = .{ .ctx = &host, .vtable = &Failing.vtable }; + _ = th.wr(p, ctlfs.Node.of(p.panes[0].?.serial, .body), "more\n"); + p.perform(.{ .save_file = .{ .pane = 0 } }); + try std.testing.expect(!th.logHas(p, "\nsave ")); + try std.testing.expect(p.panes[0].?.file.?.saved_revision != p.panes[0].?.file.?.revision); + // With the host's write done, it is logged. + p.host = .{}; + p.perform(.{ .save_file = .{ .pane = 0 } }); + try std.testing.expect(th.logHas(p, "\nsave ")); +} -- cgit v1.3