output.zig

56.5 KB · raw

1// output.zig — the only file that writes to stdout2// All ANSI codes live here. No raw escape sequences elsewhere.3const std = @import("std");4const types = @import("types.zig");5const nina_version = @import("version.zig");6const errors = @import("errors.zig");7const Io = std.Io;89// Color constants — all ANSI codes live here only10const PINK = "\x1b[38;2;255;183;197m";11const BOLD = "\x1b[1m";12const GREEN = "\x1b[32m";13const YELLOW = "\x1b[33m";14const RED = "\x1b[31m";15const CYAN = "\x1b[36m";16const DIM = "\x1b[2m";17const RESET = "\x1b[0m";1819// kaomoji constants — all kaomoji defined here, never inlined elsewhere. Rare20// and earned: each marks one genuine moment and never repeats in one output21// block. They are plain text, not ANSI, so they survive pipes and NO_COLOR.22const KAO_FACE = "(˶ᵔ ᵕ ᵔ˶)  "; // hello — her face23const KAO_COZY = "(っ˘ω˘ς)  "; // apply start24const KAO_EXCITED = "╰(*°▽°*)╯  "; // apply success after a failure this session25const KAO_GENTLE = "( ˘ᵕ˘ )  "; // back done26const KAO_CONTENT = "( ´ ∀ ` )  "; // clean freed27const KAO_HAPPY = "( ´ ▽ ` )  "; // doctor all clear / mood all good28const KAO_SLEEPY = "(˘ω˘ )  "; // try / develop exit29const KAO_READY = "( •̀ᴗ•́ )  "; // update start30const KAO_SAD = "(;ω;)  "; // network or ssh errors only — never user typos3132// Exported for TUI use (search.zig references these to avoid \x1b in that file)33pub const C_PINK = PINK;34pub const C_BOLD = BOLD;35pub const C_GREEN = GREEN;36pub const C_YELLOW = YELLOW;37pub const C_RED = RED;38pub const C_CYAN = CYAN;39pub const C_DIM = DIM;40pub const C_RESET = RESET;41pub const C_CLEAR_EOL = "\x1b[K";42pub const C_CURSOR_UP_FMT = "\x1b[{d}A";4344// Precomputed prefix strings45const HDR_C = PINK ++ ":: " ++ RESET;46const HDR_P = ":: ";47const STEP_C = "   " ++ DIM ++ "-> " ++ RESET;48const STEP_P = "   -> ";49const TEACH_C = "   " ++ DIM ++ "= " ++ RESET;50const TEACH_P = "   = ";51const ERR_C = PINK ++ ":: " ++ RED ++ "error:" ++ RESET ++ " ";52const ERR_P = ":: error: ";53const WARN_C = PINK ++ ":: " ++ YELLOW ++ "warning:" ++ RESET ++ " ";54const WARN_P = ":: warning: ";5556var _fw: Io.File.Writer = undefined;57var _w: *Io.Writer = undefined;58var _io: Io = undefined;59var color_enabled: bool = true;60var teach_enabled: bool = false;61var auto_yes: bool = false;6263// --- Build panel ---6465pub const BuildPanel = struct {66    total: u32 = 0,67    completed: u32 = 0,68    total_mb: f32 = 0,69    active: [32]u8 = [_]u8{0} ** 32,70    active_len: usize = 0,71    mode: enum { fetching, building, activating } = .fetching,72    pulse_pos: u8 = 0,7374    const BAR_WIDTH = 28;7576    pub fn update(self: *BuildPanel, line: []const u8) void {77        // "these N paths will be fetched (X MiB download, Y MiB unpacked)"78        if (std.mem.indexOf(u8, line, "paths will be fetched") != null) {79            if (parseAfterWord(line, "these ")) |n_str| {80                if (std.fmt.parseInt(u32, n_str, 10) catch null) |n| self.total = n;81            }82            // "(X MiB download..."83            if (std.mem.indexOfScalar(u8, line, '(')) |pi| {84                const after = std.mem.trim(u8, line[pi + 1 ..], " \t");85                if (indexOfSpace(after)) |sp| {86                    if (std.fmt.parseFloat(f32, after[0..sp]) catch null) |mb| self.total_mb = mb;87                }88            }89            return;90        }9192        // "copying path '/nix/store/...' from '...'" (nix 2.x substituter message)93        // older nix used "fetching path '...'" — match both for compatibility94        if (std.mem.indexOf(u8, line, "copying path '") != null or95            std.mem.indexOf(u8, line, "fetching path '") != null)96        {97            self.completed +|= 1;98            self.mode = .fetching;99            self.setActiveName(line, false);100            return;101        }102103        // "building '/nix/store/...-name.drv'"104        if (std.mem.indexOf(u8, line, "building '") != null and105            std.mem.indexOf(u8, line, ".drv") != null)106        {107            self.mode = .building;108            self.setActiveName(line, true);109            return;110        }111112        // "activating the configuration..."113        if (std.mem.indexOf(u8, line, "activating the configuration") != null or114            std.mem.indexOf(u8, line, "activating configuration") != null)115        {116            self.mode = .activating;117            if (self.total > 0) self.completed = self.total;118            const msg = "activating configuration...";119            const copy_len = @min(msg.len, self.active.len);120            @memcpy(self.active[0..copy_len], msg[0..copy_len]);121            self.active_len = copy_len;122            return;123        }124    }125126    pub fn render(self: *BuildPanel) void {127        if (!color_enabled) return;128129        // Up 2 lines to the name line (blank line is below header, name is next)130        p("\x1b[2A", .{});131132        // Name line133        p("\r\x1b[K", .{});134        const name = self.active[0..self.active_len];135        switch (self.mode) {136            .fetching => p("   {s}fetching{s}  {s}{s}{s}", .{ c(DIM), c(RESET), c(CYAN), name, c(RESET) }),137            .building => p("   {s}building{s}  {s}{s}{s}", .{ c(DIM), c(RESET), c(YELLOW), name, c(RESET) }),138            .activating => p("   {s}{s}{s}", .{ c(GREEN), name, c(RESET) }),139        }140        p("\n", .{});141142        // Bar line143        p("\r\x1b[K", .{});144        if (self.total == 0) {145            self.drawPulse();146        } else {147            self.drawCountedBar();148        }149        p("\n", .{});150151        flush();152    }153154    fn drawCountedBar(self: *BuildPanel) void {155        const filled: u32 = if (self.total > 0)156            @min(BAR_WIDTH, (self.completed * BAR_WIDTH) / self.total)157        else158            0;159        const empty: u32 = BAR_WIDTH - filled;160161        const blk_color = switch (self.mode) {162            .fetching => CYAN,163            .building => YELLOW,164            .activating => GREEN,165        };166167        p("   ", .{});168        if (filled > 0) {169            p("{s}", .{c(blk_color)});170            for (0..filled) |_| p("█", .{});171            p("{s}", .{c(RESET)});172        }173        if (empty > 0) {174            p("{s}", .{c(DIM)});175            for (0..empty) |_| p("░", .{});176            p("{s}", .{c(RESET)});177        }178        p("   {s}{d} / {d} paths{s}", .{ c(DIM), self.completed, self.total, c(RESET) });179        if (self.total_mb > 0) {180            const done_mb = self.total_mb * @as(f32, @floatFromInt(self.completed)) /181                @as(f32, @floatFromInt(@max(self.total, 1)));182            p("   {d:.1} MB / {d:.1} MB", .{ done_mb, self.total_mb });183        }184    }185186    fn drawPulse(self: *BuildPanel) void {187        const PULSE_SIZE: u8 = 4;188        const blk_color = switch (self.mode) {189            .fetching => CYAN,190            .building => YELLOW,191            .activating => GREEN,192        };193        p("   ", .{});194        for (0..BAR_WIDTH) |i| {195            const pos: u8 = @intCast(i);196            const in_pulse = pos >= self.pulse_pos and pos < self.pulse_pos + PULSE_SIZE;197            if (in_pulse) {198                p("{s}█{s}", .{ c(blk_color), c(RESET) });199            } else {200                p("{s}░{s}", .{ c(DIM), c(RESET) });201            }202        }203        self.pulse_pos = (self.pulse_pos + 1) % BAR_WIDTH;204    }205206    fn setActiveName(self: *BuildPanel, line: []const u8, is_drv: bool) void {207        const store = "/nix/store/";208        const idx = std.mem.indexOf(u8, line, store) orelse return;209        const after = line[idx + store.len ..];210        if (after.len < 33) return;211        var name = after[33..]; // skip 32-char hash + dash212        if (is_drv) {213            if (std.mem.endsWith(u8, name, ".drv")) name = name[0 .. name.len - 4];214        }215        // Trim trailing quote / whitespace216        name = std.mem.trimEnd(u8, name, "' \t\r\n");217        const copy_len = @min(name.len, self.active.len);218        @memcpy(self.active[0..copy_len], name[0..copy_len]);219        self.active_len = copy_len;220    }221};222223fn parseAfterWord(line: []const u8, word: []const u8) ?[]const u8 {224    const idx = std.mem.indexOf(u8, line, word) orelse return null;225    const after = line[idx + word.len ..];226    const end = indexOfSpace(after) orelse return null;227    return after[0..end];228}229230fn indexOfSpace(s: []const u8) ?usize {231    for (s, 0..) |b, i| if (b == ' ' or b == '\t') return i;232    return null;233}234235pub fn buildPanelInit() void {236    if (!color_enabled) return;237    p("\n\n\n", .{});238    flush();239}240241pub fn buildPanelClear() void {242    if (!color_enabled) return;243    p("\n", .{});244    flush();245}246247pub fn init(writer: *Io.Writer, io: std.Io, environ: *const std.process.Environ.Map, color_config: bool) void {248    _w = writer;249    _io = io;250    color_enabled = color_config and251        (std.Io.File.stdout().isTty(io) catch false) and252        !environ.contains("NO_COLOR");253}254255pub fn setTeach(enabled: bool) void {256    teach_enabled = enabled;257}258259// Set by --yes: bypass confirm() entirely for scripted/automated invocations260// that want the old prompts skipped on purpose, instead of by accident via a261// closed stdin. Does not affect confirmDefaultNo, which stays opt-in-only.262pub fn setAutoYes(enabled: bool) void {263    auto_yes = enabled;264}265266pub fn flush() void {267    _w.flush() catch {};268}269270// Whether ANSI color is active (tty + config + no NO_COLOR). Callers spawning271// child processes that colorize their own output use this to gate the child.272pub fn colorEnabled() bool {273    return color_enabled;274}275276fn c(code: []const u8) []const u8 {277    return if (color_enabled) code else "";278}279280fn hdr() []const u8 {281    return if (color_enabled) HDR_C else HDR_P;282}283284fn step() []const u8 {285    return if (color_enabled) STEP_C else STEP_P;286}287288fn teach_pfx() []const u8 {289    return if (color_enabled) TEACH_C else TEACH_P;290}291292// Raw write — used by TUI293pub fn raw(bytes: []const u8) void {294    _w.writeAll(bytes) catch {};295}296297// Formatted print — used by TUI for in-place rendering298pub fn p(comptime fmt: []const u8, args: anytype) void {299    _w.print(fmt, args) catch {};300}301302pub fn cursorUp(n: usize) void {303    if (n > 0) p("\x1b[{d}A", .{n});304}305306pub fn clearLine() void {307    p("\r\x1b[K", .{});308}309310// --- Error and warning output ---311312pub fn printError(message: []const u8, detail: ?[]const u8, suggestion: ?[]const u8) void {313    p("{s}{s}\n", .{ if (color_enabled) ERR_C else ERR_P, message });314    if (detail) |d| p("   {s}{s}{s}\n", .{ c(DIM), d, c(RESET) });315    // Actionable suggestion in cyan — the next step should catch the eye.316    if (suggestion) |s| p("   {s}-> {s}{s}\n", .{ c(CYAN), s, c(RESET) });317}318319// Like printError, but for genuine system failures (network/ssh/search). The sad320// kaomoji signals "this is on the machine, not on you" — never used for typos or321// not-found errors, which go through printError.322pub fn printSystemError(message: []const u8, detail: ?[]const u8, suggestion: ?[]const u8) void {323    p("{s}{s}{s}\n", .{ KAO_SAD, if (color_enabled) ERR_C else ERR_P, message });324    if (detail) |d| p("   {s}{s}{s}\n", .{ c(DIM), d, c(RESET) });325    if (suggestion) |s| p("   {s}-> {s}{s}\n", .{ c(CYAN), s, c(RESET) });326}327328pub fn printWarning(message: []const u8) void {329    p("{s}{s}\n", .{ if (color_enabled) WARN_C else WARN_P, message });330}331332// Display a translated build error through the 3-layer pipeline format.333// is_system = true  → (;ω;) kaomoji prefix (machine's fault, not the user's)334// suggestion may contain '\n'-separated lines; the first gets "-> " and the335// rest are indented with "   " so the secondary "nix log ..." line lines up.336pub fn buildError(err: errors.TranslatedError) void {337    if (err.is_system) {338        // KAO_SAD already includes trailing spaces: "(;ω;)  "339        p("{s}{s}{s}\n\n", .{ KAO_SAD, if (color_enabled) ERR_C else ERR_P, err.title });340    } else {341        p("{s}{s}\n\n", .{ if (color_enabled) ERR_C else ERR_P, err.title });342    }343344    var body_lines = std.mem.splitScalar(u8, err.body, '\n');345    while (body_lines.next()) |line| {346        if (line.len == 0) continue;347        p("   {s}\n", .{line});348    }349350    if (err.location) |loc| {351        p("{s}   {s}{s}\n", .{ c(DIM), loc, c(RESET) });352    }353354    p("\n", .{});355356    var sug_lines = std.mem.splitScalar(u8, err.suggestion, '\n');357    var first = true;358    while (sug_lines.next()) |line| {359        if (line.len == 0) continue;360        if (first) {361            p("{s}   -> {s}{s}\n", .{ c(CYAN), line, c(RESET) });362            first = false;363        } else {364            p("{s}   {s}{s}\n", .{ c(DIM), line, c(RESET) });365        }366    }367}368369// Display post-build warnings collected from captured stderr.370// Shown after the success line in dim yellow.371pub fn buildWarnings(warnings: []const []const u8) void {372    for (warnings) |w| {373        p("{s}   \u{26a0}  {s}{s}\n", .{ c(YELLOW), w, c(RESET) });374    }375}376377pub fn aborted() void {378    p("{s}aborted\n", .{hdr()});379}380381// One-time dim note when ~/.nina.conf is migrated to the XDG config path.382pub fn configMigrated(path: []const u8) void {383    p("{s}{s}config migrated to {s}{s}\n", .{ step(), c(DIM), path, c(RESET) });384}385386pub fn printTeach(cmd: []const u8) void {387    if (teach_enabled) p("{s}{s}{s}\n", .{ teach_pfx(), cmd, c(RESET) });388}389390pub fn printSubstep(comptime fmt: []const u8, args: anytype) void {391    p("{s}", .{step()});392    p(fmt, args);393    p("\n", .{});394}395396pub fn hookFailed(name: []const u8, code: u8, hook_output: []const u8) void {397    p("{s}{s} hook exited with code {d}{s}\n\n", .{ hdr(), name, code, c(RESET) });398399    if (hook_output.len > 0) {400        var lines = std.mem.splitScalar(u8, hook_output, '\n');401        var shown: [5][]const u8 = undefined;402        var count: usize = 0;403        while (lines.next()) |line| {404            const trimmed = std.mem.trim(u8, line, " \t\r");405            if (trimmed.len == 0) continue;406            shown[count % shown.len] = trimmed;407            count += 1;408        }409410        const display_count = @min(count, shown.len);411        const start = count - display_count;412        for (0..display_count) |i| {413            const line = shown[(start + i) % shown.len];414            p("   {s}{s}{s}\n", .{ c(DIM), line, c(RESET) });415        }416        p("\n", .{});417    }418}419420pub fn hookWarning(name: []const u8, code: u8, hook_output: []const u8) void {421    _ = hook_output;422    p("{s}   warning: {s} hook exited with code {d}{s}\n", .{ c(YELLOW), name, code, c(RESET) });423}424425// --- Confirmation prompt (returns true = yes) ---426427fn stdinIsTty() bool {428    return std.Io.File.stdin().isTty(_io) catch false;429}430431fn printConfirmAbortHint() void {432    p("   {s}refusing to assume yes on a closed/non-interactive stdin — pass --yes to confirm automatically{s}\n", .{ c(YELLOW), c(RESET) });433}434435// Pure decision for an interactive read that has already happened: `saw_eof` is436// true when the read loop hit end-of-input before a newline, `line` is whatever437// was read (possibly empty). A real EOF with nothing typed (e.g. Ctrl-D at the438// prompt) is treated the same as a closed/non-interactive stdin — silently439// proceeding on a closed input stream is exactly the footgun this prompt exists440// to prevent. Otherwise this is a plain [Y/n]-style default-yes parse.441fn decideAnswer(saw_eof: bool, line: []const u8) bool {442    if (saw_eof and line.len == 0) return false;443    const trimmed = std.mem.trim(u8, line, " \t");444    if (trimmed.len == 0) return true;445    return trimmed[0] != 'n' and trimmed[0] != 'N';446}447448// Split out from confirm() so a test can force the non-interactive branch449// deterministically instead of depending on the test runner's own stdin.450fn confirmWithTty(prompt: []const u8, is_tty: bool) bool {451    if (auto_yes) return true;452    if (!is_tty) {453        printConfirmAbortHint();454        return false;455    }456    p("   {s}continue? [Y/n]  ", .{prompt});457    flush();458    var buf: [64]u8 = undefined;459    var i: usize = 0;460    var eof = false;461    while (i < buf.len) {462        const n = std.posix.read(std.posix.STDIN_FILENO, buf[i .. i + 1]) catch {463            eof = true;464            break;465        };466        if (n == 0) {467            eof = true;468            break;469        }470        if (buf[i] == '\n') break;471        i += 1;472    }473    const line = buf[0..i];474    const answer = decideAnswer(eof, line);475    if (!answer and eof and line.len == 0) printConfirmAbortHint();476    return answer;477}478479pub fn confirm(prompt: []const u8) bool {480    return confirmWithTty(prompt, stdinIsTty());481}482483fn initForTest() void {484    const S = struct {485        var buf: [256]u8 = undefined;486        var discarding: std.Io.Writer.Discarding = .init(&buf);487        var env: std.process.Environ.Map = .init(std.testing.allocator);488    };489    init(&S.discarding.writer, std.testing.io, &S.env, false);490}491492test "confirmWithTty: non-tty stdin refuses and prints a hint instead of assuming yes (NINA-005)" {493    initForTest();494    defer setAutoYes(false);495    try std.testing.expect(!confirmWithTty("test", false));496}497498test "confirmWithTty: --yes bypasses the tty check entirely" {499    initForTest();500    setAutoYes(true);501    defer setAutoYes(false);502    try std.testing.expect(confirmWithTty("test", false));503}504505test "decideAnswer: real EOF with nothing typed refuses (NINA-005)" {506    try std.testing.expect(!decideAnswer(true, ""));507}508509test "decideAnswer: bare enter accepts the [Y/n] default" {510    try std.testing.expect(decideAnswer(false, ""));511}512513test "decideAnswer: explicit y/Y accepts" {514    try std.testing.expect(decideAnswer(false, "y"));515    try std.testing.expect(decideAnswer(false, "Y"));516}517518test "decideAnswer: explicit n/N refuses" {519    try std.testing.expect(!decideAnswer(false, "n"));520    try std.testing.expect(!decideAnswer(false, "N"));521}522523// Like confirm, but defaults to NO on an empty answer — for prompts that touch524// system files, where a stray Enter should never trigger the action.525pub fn confirmDefaultNo(question: []const u8) bool {526    p("   {s} [y/N]  ", .{question});527    flush();528    var buf: [64]u8 = undefined;529    var i: usize = 0;530    while (i < buf.len) {531        const n = std.posix.read(std.posix.STDIN_FILENO, buf[i .. i + 1]) catch break;532        if (n == 0) break;533        if (buf[i] == '\n') break;534        i += 1;535    }536    const input = std.mem.trim(u8, buf[0..i], " \t");537    if (input.len == 0) return false;538    return input[0] == 'y' or input[0] == 'Y';539}540541// --- Apply / rebuild ---542543pub fn applyStart(machine: []const u8) void {544    p("{s}{s}rebuilding {s}...\n", .{ KAO_COZY, hdr(), machine });545}546547// after_failure: true only when the previous apply this session failed and this548// one succeeded — the one moment that earns the excited kaomoji. Routine549// successes show no kaomoji.550pub fn applyDone(gen: u32, elapsed_ms: u64, after_failure: bool) void {551    const face = if (after_failure) KAO_EXCITED else "";552    const secs = @as(f64, @floatFromInt(elapsed_ms)) / 1000.0;553    if (elapsed_ms >= 1000) {554        p("{s}{s}generation {s}{d}{s}  {s}[{d:.1}s]{s}\n", .{ face, hdr(), c(BOLD), gen, c(RESET), c(DIM), secs, c(RESET) });555    } else {556        p("{s}{s}generation {s}{d}{s}\n", .{ face, hdr(), c(BOLD), gen, c(RESET) });557    }558}559560pub fn applyFailed(translated: []const u8) void {561    p("{s}build failed\n", .{if (color_enabled) ERR_C else ERR_P});562    if (translated.len > 0) p("   {s}{s}{s}\n", .{ c(DIM), translated, c(RESET) });563    p("   {s}-> nina doctor{s}\n", .{ c(DIM), c(RESET) });564}565566pub fn applyDry(machine: []const u8) void {567    p("{s}dry run  {s}\n", .{ hdr(), machine });568}569570pub fn applyDryDone() void {571    p("{s}no changes applied\n", .{hdr()});572}573574// --- Check ---575576pub fn checkStart(machine: []const u8) void {577    p("{s}checking {s}...\n", .{ hdr(), machine });578}579580pub fn checkOk() void {581    p("{s}{s}ok{s}\n", .{ hdr(), c(GREEN), c(RESET) });582}583584pub fn checkFailed(msg: []const u8) void {585    p("{s}config invalid\n", .{if (color_enabled) ERR_C else ERR_P});586    if (msg.len > 0) p("   {s}{s}{s}\n", .{ c(DIM), msg, c(RESET) });587}588589// --- Back / go ---590591pub fn backStart(machine: []const u8, from: u32, to: u32) void {592    p("{s}rolling back  {s}  gen {d} -> gen {d}\n", .{ hdr(), machine, from, to });593}594595pub fn goStart(machine: []const u8, current: u32, target: u32) void {596    p("{s}switching  {s}  gen {d} -> gen {d}\n", .{ hdr(), machine, current, target });597}598599pub fn generationDone(n: u32) void {600    p("{s}done  gen {s}{d}{s}\n", .{ hdr(), c(BOLD), n, c(RESET) });601}602603// `back` has nothing older to roll back to. This is a clean stop, not a build604// failure — the rollback would otherwise surface nixos-rebuild's confusing605// 'no profile version older than the current' as a fake build error.606pub fn alreadyOldest() void {607    p("{s}already at the oldest generation\n", .{if (color_enabled) ERR_C else ERR_P});608}609610// Like generationDone but for `back` specifically — a successful rollback earns611// the gentle kaomoji. `go` keeps the plain generationDone line.612pub fn backDone(n: u32) void {613    p("{s}{s}done  gen {s}{d}{s}\n", .{ KAO_GENTLE, hdr(), c(BOLD), n, c(RESET) });614}615616// --- History ---617618pub fn historyHeader(machine: []const u8) void {619    p("{s}generations  {s}\n\n", .{ hdr(), machine });620}621622pub fn historyRow(gen: types.GenerationInfo) void {623    if (gen.current) {624        p("   {s}{d}{s}   {s}   {s}   {s}current{s}\n", .{ c(BOLD), gen.number, c(RESET), gen.date, gen.time, c(BOLD), c(RESET) });625    } else {626        p("   {s}{d}   {s}   {s}{s}\n", .{ c(DIM), gen.number, gen.date, gen.time, c(RESET) });627    }628}629630// --- Clean ---631632pub fn cleanStart(machine: []const u8, keep: u32, total: u32) void {633    p("{s}cleaning  {s}  keeping {d} of {d}\n", .{ hdr(), machine, keep, total });634}635636// Fewer generations than the keep limit — there's nothing to collect. Avoids the637// nonsensical 'keeping 5 of 1'.638pub fn cleanNothing(machine: []const u8, total: u32) void {639    p("{s}cleaning  {s}\n\n", .{ hdr(), machine });640    p("   only {d} generation{s} — nothing to remove.\n", .{ total, if (total == 1) "" else "s" });641}642643pub fn cleanDone() void {644    p("{s}{s}done\n", .{ KAO_CONTENT, hdr() });645}646647// --- Status ---648649pub fn statusHeader() void {650    p("{s}status\n\n", .{hdr()});651}652653pub fn statusRow(machine: []const u8, gen: u32, time: []const u8, size: []const u8, ok: bool) void {654    if (ok) {655        p("   {s}{s}{s}   gen {s}{d}{s}   {s}{s}   {s}{s}\n", .{ c(DIM), machine, c(RESET), c(BOLD), gen, c(RESET), c(DIM), time, size, c(RESET) });656    } else {657        p("   {s}{s}   {s}unreachable{s}\n", .{ c(RED), machine, "", c(RESET) });658    }659}660661// Dim Home Manager generation line, indented under the machine row. Only shown662// when standalone HM is detected; absent otherwise so the layout is unchanged.663pub fn statusHomeRow(gen: u32, detail: []const u8) void {664    if (detail.len > 0) {665        p("   {s}         hm  gen {d}   {s}{s}\n", .{ c(DIM), gen, detail, c(RESET) });666    } else {667        p("   {s}         hm  gen {d}{s}\n", .{ c(DIM), gen, c(RESET) });668    }669}670671// --- Diff ---672673pub fn diffHeader(a: u32, b: u32, machine: []const u8) void {674    p("{s}gen {d} -> gen {d}  {s}\n\n", .{ hdr(), a, b, machine });675}676677// Reached when no generation is marked current (non-standard profile layout,678// a transient readlink failure, or a non-GNU remote host) or there are too679// few generations to infer a pair — nothing safe to diff against.680pub fn diffCannotDetermine() void {681    p("{s}cannot determine current generation — nothing to diff\n", .{if (color_enabled) WARN_C else WARN_P});682}683684pub fn diffRow(entry: types.DiffEntry) void {685    switch (entry.op) {686        .add => p("   {s}+{s} {s}   {s}\n", .{ c(GREEN), c(RESET), entry.package, entry.new_version orelse "" }),687        .remove => p("   {s}-{s} {s}   {s}\n", .{ c(RED), c(RESET), entry.package, entry.old_version orelse "" }),688        .change => p("   {s}^{s} {s}   {s} -> {s}\n", .{ c(CYAN), c(RESET), entry.package, entry.old_version orelse "", entry.new_version orelse "" }),689    }690}691692// --- Doctor ---693694pub fn doctorHeader(machine: []const u8) void {695    p("{s}diagnosing  {s}\n\n", .{ hdr(), machine });696}697698pub fn doctorRow(check: types.DoctorCheck) void {699    const status_str = switch (check.status) {700        .ok => if (color_enabled) GREEN ++ "ok" ++ RESET else "ok",701        .warn => if (color_enabled) YELLOW ++ "warn" ++ RESET else "warn",702        .fail => if (color_enabled) RED ++ "fail" ++ RESET else "fail",703    };704    const note_str = check.note orelse "";705    p("   {s:<16}  {s}   {s}\n", .{ check.name, status_str, note_str });706}707708pub fn doctorSummary(warnings: u32, failures: u32) void {709    if (failures > 0) {710        p("{s}{d} problems\n", .{ hdr(), failures });711    } else if (warnings > 0) {712        p("{s}{d} warnings\n", .{ hdr(), warnings });713    } else {714        p("{s}{s}{s}all good{s}\n", .{ KAO_HAPPY, hdr(), c(GREEN), c(RESET) });715    }716}717718// --- Update ---719720pub fn updateStart(machine: []const u8) void {721    p("{s}updating channels  {s}\n\n", .{ hdr(), machine });722}723724pub fn updateChannel(name: []const u8, old: ?[]const u8, new: ?[]const u8) void {725    if (old != null and new != null and !std.mem.eql(u8, old.?, new.?)) {726        p("   {s}   {s} -> {s}\n", .{ name, old.?, new.? });727    } else {728        p("   {s}   {s}no change{s}\n", .{ name, c(DIM), c(RESET) });729    }730}731732pub fn updateDone() void {733    p("\n{s}done\n", .{hdr()});734}735736// --- Upgrade ---737738pub fn upgradeStart(machine: []const u8) void {739    p("{s}upgrading  {s}\n", .{ hdr(), machine });740}741742// --- Log ---743744pub fn logHeader(machine: []const u8) void {745    p("{s}history  {s}\n\n", .{ hdr(), machine });746}747748pub fn logRow(date: []const u8, time: []const u8, action: []const u8, detail: []const u8) void {749    p("   {s}{s}  {s}{s}   {s:<16}  {s}\n", .{ c(DIM), date, time, c(RESET), action, detail });750}751752// --- Edit ---753754pub fn editOpen(path: []const u8, editor: []const u8) void {755    p("{s}opening {s}\n", .{ hdr(), path });756    printSubstep("{s}", .{editor});757    p("\n   {s}run nina check to validate before applying{s}\n", .{ c(DIM), c(RESET) });758}759760// `nina edit hardware` is a mistake: hardware-configuration.nix is generated by761// nixos-generate-config and warns against hand-editing. Refuse and redirect.762pub fn editHardwareWarning() void {763    p("\n   {s}warning: hardware-configuration.nix is auto-generated — do not edit directly{s}\n", .{ c(YELLOW), c(RESET) });764    p("   {s}-> make hardware changes in configuration.nix instead{s}\n", .{ c(CYAN), c(RESET) });765}766767// --- Fmt ---768769pub fn fmtStart(path: []const u8) void {770    p("{s}formatting  {s}\n", .{ hdr(), path });771}772773pub fn fmtDone() void {774    p("{s}done\n", .{hdr()});775}776777pub fn fmtNeedsFormat() void {778    p("{s}needs formatting  {s}run nina fmt to fix{s}\n", .{ hdr(), c(DIM), c(RESET) });779}780781// --- Repl ---782783pub fn replStart() void {784    p("{s}nix repl  {s}nixpkgs loaded{s}  :q to exit\n", .{ hdr(), c(DIM), c(RESET) });785}786787// --- Develop ---788789pub fn developStart(pkgs: []const []const u8) void {790    p("{s}entering dev shell\n\n   ", .{hdr()});791    for (pkgs, 0..) |pkg, i| {792        if (i > 0) p("  ", .{});793        p("{s}", .{pkg});794    }795    p("\n\n   {s}-> press Ctrl+C or type 'exit' to return{s}\n\n", .{ c(DIM), c(RESET) });796}797798pub fn developDone() void {799    p("{s}{s}back\n", .{ KAO_SLEEPY, hdr() });800}801802// --- Info ---803804pub fn infoHeader(machine: []const u8) void {805    p("{s}{s}\n\n", .{ hdr(), machine });806}807808pub fn infoRow(key: []const u8, val: []const u8) void {809    p("   {s:<12}  {s}\n", .{ key, val });810}811812// --- Boot ---813814pub fn bootHeader(machine: []const u8) void {815    p("{s}boot entries  {s}\n\n", .{ hdr(), machine });816}817818pub fn bootEntry(entry: types.BootEntry, idx: usize) void {819    if (entry.current) {820        p("   {s}> {s}{s}{s}\n", .{ c(BOLD), entry.title, if (entry.date) |d| std.fmt.allocPrint(std.heap.page_allocator, "   {s}", .{d}) catch "   " else "", c(RESET) });821    } else {822        p("   {s}  {s}{s}{s}\n", .{ c(DIM), entry.title, if (entry.date) |d| std.fmt.allocPrint(std.heap.page_allocator, "   {s}", .{d}) catch "   " else "", c(RESET) });823    }824    _ = idx;825}826827// --- Service ---828829pub fn serviceListHeader(machine: []const u8) void {830    p("{s}services  {s}\n\n", .{ hdr(), machine });831}832833pub fn serviceRow(svc: types.ServiceInfo) void {834    const state_str = switch (svc.state) {835        .active => if (color_enabled) GREEN ++ "active" ++ RESET else "active",836        .failed => if (color_enabled) RED ++ "failed" ++ RESET else "failed",837        .inactive => "inactive",838        .unknown => "unknown",839    };840    const uptime = svc.uptime orelse "";841    p("   {s:<24}  {s:<14}  {s}\n", .{ svc.name, state_str, uptime });842}843844pub fn serviceVerb(verb: []const u8, name: []const u8, machine: []const u8) void {845    p("{s}{s} {s}  {s}\n", .{ hdr(), verb, name, machine });846}847848pub fn serviceDone() void {849    p("{s}done\n", .{hdr()});850}851852pub fn serviceLogsHeader(name: []const u8, n: u32, machine: []const u8) void {853    p("{s}{s}  last {d} lines  {s}\n\n", .{ hdr(), name, n, machine });854}855856// --- Store ---857858pub fn storeInfo(info: types.StoreInfo) void {859    p("{s}store\n\n", .{hdr()});860    p("   {s:<16}  {s}\n", .{ "total", info.total_size });861    p("   {s:<16}  {d} paths\n", .{ "live", info.live_paths });862    p("   {s:<16}  {s}{d} paths{s}   {s}run nina clean{s}\n", .{ "reclaimable", c(DIM), info.reclaimable_paths, c(RESET), c(CYAN), c(RESET) });863}864865// --- Channel ---866867pub fn channelListHeader(machine: []const u8) void {868    p("{s}channels  {s}\n\n", .{ hdr(), machine });869}870871pub fn channelRow(ch: types.ChannelInfo) void {872    p("   {s:<16}  {s}\n", .{ ch.name, ch.url });873}874875// --- Flake ---876877pub fn flakeUpdateStart() void {878    p("{s}updating inputs\n\n", .{hdr()});879}880881pub fn flakeInput(input: types.FlakeInput) void {882    if (input.changed) {883        const old = if (input.old_rev) |r| r[0..@min(7, r.len)] else "?";884        const new = if (input.new_rev) |r| r[0..@min(7, r.len)] else "?";885        p("   {s:<20}  {s} -> {s}\n", .{ input.name, old, new });886    } else {887        p("   {s:<20}  {s}no change{s}\n", .{ input.name, c(DIM), c(RESET) });888    }889}890891pub fn flakeLockWritten() void {892    p("\n{s}flake.lock written\n", .{hdr()});893}894895pub fn flakeValid() void {896    p("{s}{s}valid{s}\n", .{ hdr(), c(GREEN), c(RESET) });897}898899pub fn flakeCheckStart() void {900    p("{s}checking flake\n", .{hdr()});901}902903// --- Profile ---904905pub fn profileListHeader() void {906    p("{s}profile packages\n\n", .{hdr()});907}908909pub fn profileRow(attr: []const u8, pkg_version: []const u8, description: []const u8) void {910    p("   {s:<24}  {s:<12}  {s}\n", .{ attr, pkg_version, description });911}912913// --- Install / Remove / Try ---914915// Typo help for install: the query matched nothing, so suggest the closest real916// package name (pink) and let the caller confirm.917pub fn didYouMean(query: []const u8, suggestion: []const u8) void {918    p("{s}{s}'{s}' not found{s}  —  did you mean {s}{s}{s}?\n", .{ hdr(), c(DIM), query, c(RESET), c(PINK), suggestion, c(RESET) });919}920921pub fn installStart(pkg: []const u8, path: types.InstallPath) void {922    const path_str = switch (path) {923        .profile => "profile",924        .system => "system",925    };926    p("{s}installing {s}{s}{s}  {s}\n", .{ hdr(), c(PINK), pkg, c(RESET), path_str });927}928929pub fn installDone(pkg: []const u8) void {930    p("{s}{s}{s}{s} installed  {s}available now{s}\n", .{ hdr(), c(PINK), pkg, c(RESET), c(DIM), c(RESET) });931}932933pub fn removeStart(pkg: []const u8) void {934    p("{s}removing {s}{s}{s}\n", .{ hdr(), c(PINK), pkg, c(RESET) });935}936937// Plain-language health summary. No kaomoji, no hearts — just the facts.938pub fn mood(machine: []const u8, state: []const u8, gen: u32, age: []const u8, size: []const u8) void {939    const healthy = std.mem.eql(u8, state, "running");940    const verdict = if (healthy) "all good" else state;941    const color = if (healthy) GREEN else YELLOW;942    const face = if (healthy) KAO_HAPPY else "";943    p("{s}{s}{s}  {s}{s}{s}\n", .{ face, hdr(), machine, c(color), verdict, c(RESET) });944    if (age.len > 0 or size.len > 0) {945        p("   generation {d}, last applied {s}, {s} system closure\n", .{ gen, age, size });946    } else {947        p("   generation {d}\n", .{gen});948    }949}950951pub fn installEditorPrompt(pkg: []const u8, config_path: []const u8, line: u32, editor: []const u8) void {952    p("{s}opening {s}  add {s}{s}{s} to systemPackages\n", .{ hdr(), config_path, c(PINK), pkg, c(RESET) });953    const cmd = std.fmt.allocPrint(std.heap.page_allocator, "{s} {s} +{d}", .{ editor, config_path, line }) catch editor;954    printSubstep("{s}", .{cmd});955    p("\n   {s}save and close when done{s}\n\n", .{ c(DIM), c(RESET) });956}957958pub fn installSelectPrompt(pkg: []const u8, pkg_version: []const u8) void {959    p("{s}{s}{s}{s}  {s}\n\n", .{ hdr(), c(PINK), pkg, c(RESET), pkg_version });960    p("   [i] profile install    {s}instant  no rebuild{s}\n", .{ c(DIM), c(RESET) });961    p("   [s] system install     {s}opens editor  requires apply{s}\n", .{ c(DIM), c(RESET) });962    p("   [t] try now            {s}exits when done{s}\n\n", .{ c(DIM), c(RESET) });963    p("   > ", .{});964    flush();965}966967pub fn tryStart(pkg: []const u8) void {968    p("{s}trying {s}{s}{s}  exit when done\n", .{ hdr(), c(PINK), pkg, c(RESET) });969}970971pub fn tryExitHint() void {972    p("   {s}-> press Ctrl+C or type 'exit' to return{s}\n", .{ c(DIM), c(RESET) });973}974975pub fn tryDone() void {976    p("{s}{s}back\n", .{ KAO_SLEEPY, hdr() });977}978979// --- List ---980981pub fn listHeader(machine: []const u8) void {982    p("{s}packages  {s}\n\n", .{ hdr(), machine });983}984985pub fn listSection(title: []const u8) void {986    p("   {s}{s}{s}\n", .{ c(DIM), title, c(RESET) });987}988989// Padded name so the version column lines up into a clean two-column table.990pub fn listPkg(name: []const u8, pkg_version: []const u8) void {991    p("   {s}{s:<16}{s}  {s}{s}{s}\n", .{ c(PINK), name, c(RESET), c(DIM), pkg_version, c(RESET) });992}993994pub fn blankLine() void {995    p("\n", .{});996}997998// --- Hello ---9991000pub fn hello(machines: []const types.Machine) void {1001    p("{s}{s}nina\n\n", .{ KAO_FACE, hdr() });1002    for (machines) |m| {1003        const kind = if (m.local) "local" else "ssh";1004        const detail = if (m.local) "default" else m.host orelse "";1005        p("   {s}{s}{s}   {s}   {s}\n", .{ c(DIM), m.name, c(RESET), kind, detail });1006    }1007    p("\n", .{});1008    const quick = [_][2][]const u8{1009        .{ "apply", "rebuild and switch" },1010        .{ "search <q>", "find packages" },1011        .{ "install <pkg>", "add to profile or system" },1012        .{ "status", "machine health" },1013        .{ "back", "roll back one generation" },1014        .{ "home apply", "apply home config" },1015        .{ "home back", "roll back home config" },1016        .{ "home history", "list home generations" },1017        .{ "home check", "validate home config" },1018        .{ "home diff", "compare home generations" },1019        .{ "home packages", "list managed packages" },1020    };1021    for (quick) |cmd| {1022        p("   {s:<16}  {s}{s}{s}\n", .{ cmd[0], c(DIM), cmd[1], c(RESET) });1023    }1024    p("\n", .{});1025}10261027// --- Help ---10281029pub fn help() void {1030    p("{s}nina  {s}NixOS Intuitive Navigation Assistant by Asha Software{s}\n\n", .{ hdr(), c(DIM), c(RESET) });1031    const cmds = [_][2][]const u8{1032        .{ "apply", "rebuild and switch" },1033        .{ "back", "roll back one generation" },1034        .{ "go <n>", "switch to generation n" },1035        .{ "history", "list all generations" },1036        .{ "clean", "remove old generations" },1037        .{ "search <q>", "find packages" },1038        .{ "install <pkg>", "add to profile or system" },1039        .{ "remove <pkg>", "remove from profile or system" },1040        .{ "try <pkg>", "test without installing" },1041        .{ "list", "show installed packages" },1042        .{ "edit", "open configuration.nix" },1043        .{ "edit --dir", "open config directory" },1044        .{ "check", "validate config" },1045        .{ "diff", "changes between generations" },1046        .{ "status", "machine health" },1047        .{ "update", "refresh channels" },1048        .{ "upgrade", "update and rebuild" },1049        .{ "log", "operation history" },1050        .{ "doctor", "diagnose issues" },1051        .{ "mood", "plain-language health" },1052        .{ "develop", "enter dev shell" },1053        .{ "flake", "flake management" },1054        .{ "build", "build a package" },1055        .{ "run", "run without installing" },1056        .{ "service", "manage services" },1057        .{ "store", "nix store tools" },1058        .{ "channel", "manage channels" },1059        .{ "profile", "user profile packages" },1060        .{ "home", "home manager commands (apply/back/history/edit/check/diff/packages)" },1061        .{ "info", "system information" },1062        .{ "boot", "boot entries" },1063        .{ "fmt", "format configuration.nix" },1064        .{ "repl", "nix repl with nixpkgs" },1065        .{ "option <q>", "search nixos options" },1066        .{ "pkg", "inspect packages" },1067        .{ "why <pkg>", "what pulled a package in" },1068        .{ "unpin <input>", "release a pinned flake input (nix flake update)" },1069        .{ "hash", "compute nix hash" },1070        .{ "fetch", "fetch and hash a url" },1071        .{ "goodbye", "uninstall nina" },1072        .{ "hello", "list machines" },1073        .{ "man [topic]", "open the built-in manual pager" },1074        .{ "help", "this message" },1075    };1076    for (cmds) |cmd| {1077        p("   {s:<18}  {s}{s}{s}\n", .{ cmd[0], c(DIM), cmd[1], c(RESET) });1078    }1079    p("\n   {s}flags: --on <machine>  --dry  --check  --no-apply  --last <n>  --all  --json  --yes  --version{s}\n", .{ c(DIM), c(RESET) });1080}10811082// Render a grouped command's subcommand list, shown when the group is invoked1083// with no subcommand or an explicit `help`. Rows are {invocation, description}.1084pub fn subcommandHelp(group: []const u8, rows: []const [2][]const u8, footer: ?[]const u8) void {1085    p("{s}{s} subcommands\n\n", .{ hdr(), group });1086    for (rows) |row| {1087        p("   {s:<16}  {s}{s}{s}\n", .{ row[0], c(DIM), row[1], c(RESET) });1088    }1089    if (footer) |f| p("\n   {s}{s}{s}\n", .{ c(DIM), f, c(RESET) });1090    p("\n   nina {s} help  {s}for this message{s}\n", .{ group, c(DIM), c(RESET) });1091}10921093pub fn version() void {1094    p("{s}nina  v{s}  zig 0.16  zero dependencies\n", .{ hdr(), nina_version.VERSION });1095}10961097// --- Search (text output before TUI) ---10981099pub fn searchResult(pkg: types.NixPackage) void {1100    p("   {s}{s}{s}   {s}{s}{s}   {s}\n", .{ c(PINK), pkg.pname, c(RESET), c(DIM), pkg.version, c(RESET), pkg.description });1101}11021103pub fn searchHeader(query: []const u8, count: usize) void {1104    p("{s}search nixpkgs {s}  {s}{d} results{s}\n\n", .{ hdr(), query, c(DIM), count, c(RESET) });1105}11061107// --- Gen commands ---11081109pub fn genCurrent(n: u32) void {1110    p("{d}\n", .{n});1111}11121113pub fn done() void {1114    p("{s}done\n", .{hdr()});1115}11161117pub fn runStart(pkg: []const u8) void {1118    p("{s}running {s}{s}{s}\n", .{ hdr(), c(PINK), pkg, c(RESET) });1119}11201121pub fn buildStart(attr: []const u8) void {1122    p("{s}building {s}\n", .{ hdr(), attr });1123}11241125pub fn buildDone() void {1126    p("{s}done\n", .{hdr()});1127}11281129// --- Self-update (nina update) ---11301131pub fn updateSelfStart() void {1132    p("{s}{s}checking for updates\n", .{ KAO_READY, hdr() });1133}11341135pub fn updateSelfCurrent(ver: []const u8) void {1136    p("{s}{s}nina {s} is up to date{s}\n", .{ hdr(), c(GREEN), ver, c(RESET) });1137}11381139pub fn updateSelfAvailable(current: []const u8, latest: []const u8) void {1140    p("{s}update available\n", .{hdr()});1141    p("{s}current  {s}{s}{s}\n", .{ step(), c(DIM), current, c(RESET) });1142    p("{s}latest   {s}{s}{s}{s}\n", .{ step(), c(BOLD), c(GREEN), latest, c(RESET) });1143}11441145fn releaseNotesHeading(line: []const u8) []const u8 {1146    var i: usize = 0;1147    while (i < line.len and line[i] == '#') : (i += 1) {}1148    return std.mem.trim(u8, line[i..], " \t");1149}11501151fn releaseNotesBullet(line: []const u8) ?[]const u8 {1152    if (line.len < 2) return null;1153    const marker = line[0];1154    if ((marker == '-' or marker == '*' or marker == '+') and line[1] == ' ') return line[2..];1155    if (std.ascii.isDigit(marker)) {1156        var i: usize = 1;1157        while (i < line.len and std.ascii.isDigit(line[i])) : (i += 1) {}1158        if (i + 1 < line.len and line[i] == '.' and line[i + 1] == ' ') return line[i + 2 ..];1159    }1160    return null;1161}11621163pub fn updateSelfReleaseNotes(notes: []const u8) void {1164    const trimmed = std.mem.trim(u8, notes, " \t\r\n");1165    if (trimmed.len == 0) return;11661167    p("{s}changelog\n", .{hdr()});1168    var lines = std.mem.splitScalar(u8, trimmed, '\n');1169    while (lines.next()) |raw_line| {1170        const line = if (raw_line.len > 0 and raw_line[raw_line.len - 1] == '\r') raw_line[0 .. raw_line.len - 1] else raw_line;1171        const text = std.mem.trim(u8, line, " \t");1172        if (text.len == 0) {1173            p("\n", .{});1174            continue;1175        }1176        if (text[0] == '#') {1177            const title = releaseNotesHeading(text);1178            if (title.len == 0) continue;1179            p("   {s}{s}{s}{s}\n", .{ c(BOLD), c(CYAN), title, c(RESET) });1180            continue;1181        }1182        if (releaseNotesBullet(text)) |item| {1183            p("   {s}- {s}{s}\n", .{ c(CYAN), item, c(RESET) });1184            continue;1185        }1186        p("   {s}\n", .{text});1187    }1188}11891190pub fn updateSelfDownloading(ver: []const u8, platform: []const u8) void {1191    p("{s}downloading nina {s} for {s}\n", .{ step(), ver, platform });1192}11931194pub fn updateSelfVerifying() void {1195    p("{s}verifying checksum\n", .{step()});1196}11971198pub fn updateSelfInstalling(install_path: []const u8) void {1199    p("{s}installing to {s}\n", .{ step(), install_path });1200}12011202pub fn updateSelfDone(old_ver: []const u8, new_ver: []const u8) void {1203    p("{s}updated  {s} {s}→{s} {s}\n", .{ hdr(), old_ver, c(DIM), c(RESET), new_ver });1204}12051206pub fn updateSelfNoPlatform(platform: []const u8) void {1207    p("{s}no pre-built binary for {s}\n", .{ hdr(), platform });1208    p("{s}check kepr.uk/nina/releases for available platforms\n", .{step()});1209}12101211pub fn updateSelfNetworkError() void {1212    p("{s}{s}\n", .{ if (color_enabled) WARN_C else WARN_P, "could not reach kepr.uk — check your connection" });1213}12141215pub fn updateSelfChecksumFailed() void {1216    p("{s}checksum mismatch — download may be corrupt\n", .{if (color_enabled) ERR_C else ERR_P});1217    p("{s}try again or download manually from kepr.uk/nina/releases\n", .{step()});1218}12191220pub fn updateSelfNixManaged(new_ver: []const u8) void {1221    p("{s}upgrading to {s}{s}{s} via nix profile\n", .{ step(), c(BOLD), new_ver, c(RESET) });1222}12231224pub fn updateSelfNixFailed() void {1225    p("{s}nix profile upgrade failed\n", .{if (color_enabled) ERR_C else ERR_P});1226    p("{s}try manually: nix profile upgrade '.*nina.*'\n", .{step()});1227}12281229// Reached when building the new version into the store fails, before the1230// profile has been touched at all — the old nina element is still installed1231// and working.1232pub fn updateSelfNixPrefetchFailed() void {1233    p("{s}could not build the new version — check your connection and try again\n", .{if (color_enabled) ERR_C else ERR_P});1234    p("{s}your current nina install is untouched\n", .{step()});1235}12361237// Reached only after `nix profile remove` already succeeded and the1238// re-add failed despite the new version having just been built into the1239// store — nina is genuinely uninstalled at this point, not just stuck on1240// the old version, so the recovery command must reinstall from scratch1241// rather than upgrade. Expected to be rare now that the build happens1242// before the profile is touched.1243pub fn updateSelfNixReinstallFailed() void {1244    p("{s}nix profile add failed — nina was removed and is not reinstalled\n", .{if (color_enabled) ERR_C else ERR_P});1245    p("{s}reinstall manually: nix profile add --no-write-lock-file 'https://kepr.uk/nina/archive/HEAD.tar.gz#nina'\n", .{step()});1246}12471248pub fn updateSelfNixRehash() void {1249    p("{s}run {s}hash -r{s} or open a new shell to use the updated binary\n", .{ step(), c(DIM), c(RESET) });1250}12511252// Reached when nina is in the store but not a `nix profile` element — i.e. it1253// was installed by the system config (NixOS module / systemPackages) or1254// home-manager. `nina update` (the profile self-updater) can't touch those;1255// pushing them at `nix profile add` would spawn a second, drifting install.1256pub fn updateSelfSystemManaged() void {1257    p("{s}nina is managed by your system configuration, not nina update\n", .{hdr()});1258    p("{s}update it where you manage that config:\n", .{step()});1259    p("      {s}nix flake update nina && sudo nixos-rebuild switch{s}\n", .{ c(DIM), c(RESET) });1260}12611262// --- Goodbye / uninstall ---12631264pub fn goodbyeStart() void {1265    p("{s}uninstalling nina\n", .{hdr()});1266}12671268pub fn goodbyeFile(path: []const u8) void {1269    p("{s}will remove {s}\n", .{ step(), path });1270}12711272pub fn goodbyeNix() void {1273    p("{s}will remove nina from nix profile\n", .{step()});1274    p("{s}command: nix profile remove nina\n", .{step()});1275}12761277pub fn goodbyeDone() void {1278    p("{s}goodbye! see kepr.uk/nina to reinstall\n", .{hdr()});1279}12801281pub fn goodbyeFailed(msg: []const u8) void {1282    p("{s}{s}\n", .{ if (color_enabled) ERR_C else ERR_P, msg });1283}12841285// --- Setup ---12861287pub fn setupCheck() void {1288    p("{s}checking nix features\n", .{hdr()});1289}12901291pub fn setupFeatures(nix_command: bool, flakes: bool) void {1292    p("{s}nix-command  {s}{s}{s}\n", .{1293        step(),1294        if (nix_command) c(GREEN) else "",1295        if (nix_command) "enabled" else "not enabled",1296        if (nix_command) c(RESET) else "",1297    });1298    p("{s}flakes       {s}{s}{s}\n", .{1299        step(),1300        if (flakes) c(GREEN) else "",1301        if (flakes) "enabled" else "not enabled",1302        if (flakes) c(RESET) else "",1303    });1304}13051306pub fn setupAllSet() void {1307    p("{s}all set\n", .{hdr()});1308}13091310// Printed once, before the first search, when the nixpkgs registry still points1311// at a remote URL. Flush so it lands before `nix registry pin` and any results.1312pub fn pinningRegistry() void {1313    p("{s}pinning nixpkgs for fast local search...\n", .{hdr()});1314    flush();1315}13161317// --- Plain (non-tty) search rendering ---1318// Color-gated equivalents of the raw-ANSI TUI widget, for piped/scripted search.1319// Using the gated header + c() keeps ANSI out of non-tty output (NO_COLOR / pipes).13201321pub fn searchPlainHeader(mode_str: []const u8, query: []const u8, count: u64) void {1322    p("{s}search {s} {s}  {s}{d} results{s}\n", .{ hdr(), mode_str, query, c(DIM), count, c(RESET) });1323}13241325pub fn searchPlainNoResults() void {1326    p("   no results\n", .{});1327}13281329pub fn searchPlainPackage(pname: []const u8, pkg_version: []const u8, description: []const u8, unfree: bool) void {1330    if (unfree) {1331        p("   {s}   {s}{s}{s}   {s}unfree{s}   {s}\n", .{ pname, c(CYAN), pkg_version, c(RESET), c(YELLOW), c(RESET), description });1332    } else {1333        p("   {s}   {s}{s}{s}   {s}\n", .{ pname, c(CYAN), pkg_version, c(RESET), description });1334    }1335}13361337pub fn searchPlainOption(name: []const u8, type_str: []const u8) void {1338    p("   {s}   {s}{s}{s}\n", .{ name, c(DIM), type_str, c(RESET) });1339}13401341pub fn searchEmptyQuery() void {1342    p("{s}search needs a query  {s}e.g. nina search firefox{s}\n", .{ hdr(), c(DIM), c(RESET) });1343}13441345pub fn setupEnabling() void {1346    p("{s}enabling experimental features\n", .{hdr()});1347}13481349pub fn setupDone(path: []const u8) void {1350    p("{s}wrote {s}\n", .{ step(), path });1351    p("{s}done  open a new shell to pick up the change\n", .{hdr()});1352}13531354// --- NixOS setup (declarative configuration.nix) ---13551356pub fn setupNixosOffer(features_line: []const u8, conf_path: []const u8) void {1357    p("{s}on NixOS these go in your system config\n", .{hdr()});1358    p("   nina can add this line to {s}{s}{s}:\n\n", .{ c(DIM), conf_path, c(RESET) });1359    p("       {s}{s}{s}\n\n", .{ c(CYAN), features_line, c(RESET) });1360}13611362pub fn setupNixosWrote(conf_path: []const u8) void {1363    p("{s}added the line to {s}  {s}(backup: {s}.nina-bak){s}\n", .{ step(), conf_path, c(DIM), conf_path, c(RESET) });1364    p("{s}now run {s}sudo nixos-rebuild switch{s} — then nina's ready\n", .{ hdr(), c(BOLD), c(RESET) });1365}13661367pub fn setupNixosManual(features_line: []const u8, conf_path: []const u8) void {1368    p("{s}no problem — add this line inside the {s}{{ }}{s} in {s}:\n\n", .{ hdr(), c(DIM), c(RESET), conf_path });1369    p("       {s}{s}{s}\n\n", .{ c(CYAN), features_line, c(RESET) });1370    p("   then run {s}sudo nixos-rebuild switch{s} — then nina's ready\n", .{ c(BOLD), c(RESET) });1371}13721373pub fn setupNixosNeedsRebuild(conf_path: []const u8) void {1374    p("{s}already declared in {s}\n", .{ hdr(), conf_path });1375    p("   just run {s}sudo nixos-rebuild switch{s} to activate it\n", .{ c(BOLD), c(RESET) });1376}13771378pub fn unpinDone(input: []const u8) void {1379    p("{s}unpinned {s}\n", .{ hdr(), input });1380}13811382pub fn hashResult(hash: []const u8) void {1383    p("{s}\n", .{hash});1384}13851386pub fn fetchResult(hash: []const u8, url: []const u8) void {1387    _ = url;1388    p("{s}\n", .{hash});1389}13901391pub fn storeRepairStart() void {1392    p("{s}repairing store\n", .{hdr()});1393}13941395pub fn storeVerifyStart() void {1396    p("{s}verifying store\n", .{hdr()});1397}13981399pub fn storeOptimiseStart(machine: []const u8) void {1400    p("{s}optimising store  {s}\n", .{ hdr(), machine });1401    printSubstep("nix store optimise", .{});1402}14031404pub fn storeOptimiseDone() void {1405    p("{s}done\n", .{hdr()});1406}14071408pub fn storeGcDone(freed: []const u8) void {1409    p("{s}freed {s}\n", .{ hdr(), freed });1410}14111412pub fn storePath(path: []const u8) void {1413    p("{s}\n", .{path});1414}14151416pub fn pkgResult(key: []const u8, val: []const u8) void {1417    p("   {s:<16}  {s}\n", .{ key, val });1418}14191420pub fn channelDone() void {1421    p("{s}done\n", .{hdr()});1422}14231424pub fn flakeShowHeader(name: []const u8) void {1425    p("{s}{s}\n\n", .{ hdr(), name });1426}14271428pub fn flakeShowEntry(kind: []const u8, name: []const u8, desc: []const u8) void {1429    p("   {s:<12}  {s:<24}  {s}\n", .{ kind, name, desc });1430}14311432// --- Home Manager ---14331434pub fn homeNotInstalled() void {1435    p("{s}home manager not detected  {s}nothing to do{s}\n", .{ hdr(), c(DIM), c(RESET) });1436}14371438// HM is a NixOS/flake module — rebuilt by nixos-rebuild, not the standalone CLI.1439pub fn homeModuleManaged() void {1440    p("{s}home manager is managed by your system config\n", .{hdr()});1441    p("   {s}-> run {s}nina apply{s}{s} to rebuild both together{s}\n", .{ c(CYAN), c(BOLD), c(RESET), c(CYAN), c(RESET) });1442}14431444pub fn homeApplyStart(machine: []const u8) void {1445    p("{s}{s}applying home config  {s}\n", .{ KAO_COZY, hdr(), machine });1446}14471448pub fn homeApplyDone(gen: u32, elapsed_ms: u64) void {1449    const secs = @as(f64, @floatFromInt(elapsed_ms)) / 1000.0;1450    // gen 0 means the post-switch generation re-read failed — the switch itself1451    // succeeded, so report success without a misleading "generation 0".1452    if (gen == 0) {1453        if (elapsed_ms >= 1000) {1454            p("{s}done  {s}[{d:.1}s]{s}\n", .{ hdr(), c(DIM), secs, c(RESET) });1455        } else {1456            p("{s}done\n", .{hdr()});1457        }1458        return;1459    }1460    if (elapsed_ms >= 1000) {1461        p("{s}generation {s}{d}{s}  {s}[{d:.1}s]{s}\n", .{ hdr(), c(BOLD), gen, c(RESET), c(DIM), secs, c(RESET) });1462    } else {1463        p("{s}generation {s}{d}{s}\n", .{ hdr(), c(BOLD), gen, c(RESET) });1464    }1465}14661467// `home` was invoked against a remote machine. Detection + flake-ref are1468// local-only, so we don't act on a remote — point the user at the local run.1469pub fn homeLocalOnly(machine: []const u8) void {1470    p("{s}home manager commands run on the local machine only\n", .{hdr()});1471    p("   {s}-> '{s}' is remote; run nina home on that machine directly{s}\n", .{ c(DIM), machine, c(RESET) });1472}14731474pub fn homeApplyDry(machine: []const u8) void {1475    p("{s}home dry run  {s}\n", .{ hdr(), machine });1476}14771478pub fn homeApplyDryDone() void {1479    p("{s}{s}ok{s}  no changes applied\n", .{ hdr(), c(GREEN), c(RESET) });1480}14811482pub fn homeBackStart(machine: []const u8, from: u32, to: u32) void {1483    p("{s}rolling back home config  {s}  gen {d} -> gen {d}\n", .{ hdr(), machine, from, to });1484}14851486pub fn homeBackDone(n: u32) void {1487    p("{s}{s}done  gen {s}{d}{s}\n", .{ KAO_GENTLE, hdr(), c(BOLD), n, c(RESET) });1488}14891490pub fn homeHistoryHeader(machine: []const u8) void {1491    p("{s}home generations  {s}\n\n", .{ hdr(), machine });1492}14931494pub fn homeHistoryRow(number: u32, date: []const u8, time: []const u8, current: bool) void {1495    if (current) {1496        p("   {s}{d}{s}   {s}   {s}   {s}current{s}\n", .{ c(BOLD), number, c(RESET), date, time, c(BOLD), c(RESET) });1497    } else {1498        p("   {s}{d}   {s}   {s}{s}\n", .{ c(DIM), number, date, time, c(RESET) });1499    }1500}15011502pub fn homeEditOpen(path: []const u8, editor: []const u8) void {1503    p("{s}opening {s}\n", .{ hdr(), path });1504    printSubstep("{s}", .{editor});1505}15061507pub fn homeCheckStart(machine: []const u8) void {1508    p("{s}checking home config  {s}\n", .{ hdr(), machine });1509}15101511pub fn homeCheckOk() void {1512    p("{s}{s}ok{s}\n", .{ hdr(), c(GREEN), c(RESET) });1513}15141515pub fn homeDiffHeader(a: u32, b: u32, machine: []const u8) void {1516    p("{s}home gen {d} -> gen {d}  {s}\n\n", .{ hdr(), a, b, machine });1517}15181519pub fn homeNothingToDiff() void {1520    p("{s}only one home generation — nothing to diff yet\n", .{hdr()});1521}15221523pub fn homePackagesHeader(machine: []const u8) void {1524    p("{s}home packages  {s}\n\n", .{ hdr(), machine });1525}15261527// A flake attribute wasn't defined — note it (dim) before trying the next, less1528// specific candidate in the home-apply fallback chain.1529pub fn homeAttrFallback(ref: []const u8) void {1530    p("   {s}{s} not defined — trying next{s}\n", .{ c(DIM), ref, c(RESET) });1531}15321533pub fn homeInitStart(switch_on_init: bool, dir: ?[]const u8) void {1534    const target = dir orelse "~/.config/home-manager";1535    if (switch_on_init) {1536        p("{s}{s}setting up home manager  {s}{s}{s}\n", .{ KAO_COZY, hdr(), c(PINK), target, c(RESET) });1537        p("   {s}-> will activate after init{s}\n", .{ c(DIM), c(RESET) });1538    } else {1539        p("{s}initialising home manager  {s}{s}{s}\n", .{ hdr(), c(PINK), target, c(RESET) });1540        p("   {s}-> edit home.nix then run {s}nina home apply{s}\n", .{ c(DIM), c(BOLD), c(RESET) });1541    }1542}15431544pub fn homeInitDone(switch_on_init: bool) void {1545    if (switch_on_init) {1546        p("{s}{s}home manager ready\n", .{ KAO_GENTLE, hdr() });1547    } else {1548        p("{s}done  edit home.nix and run {s}nina home apply{s} when ready\n", .{ hdr(), c(BOLD), c(RESET) });1549    }1550}15511552// `home init` against a config that already exists — never overwrite; point at1553// apply instead.1554pub fn homeInitExists(path: []const u8) void {1555    p("{s}home manager config already exists\n", .{if (color_enabled) WARN_C else WARN_P});1556    p("   {s}{s}{s}\n", .{ c(DIM), path, c(RESET) });1557    p("   {s}-> run {s}nina home apply{s}{s} to activate it{s}\n", .{ c(CYAN), c(BOLD), c(RESET), c(CYAN), c(RESET) });1558}15591560// --- First-run wizard ---15611562pub fn firstRunBanner() void {1563    p("{s}{s}nina \u{2014} first run\n\n", .{ KAO_FACE, hdr() });1564}15651566pub fn firstRunNoConfig() void {1567    p("   no config found. let me get set up.\n\n", .{});1568}15691570// Print a prompt line and read the user's answer. Returns the default if the1571// user presses Enter without typing anything. buf must be at least 256 bytes.1572// Returns a slice into buf (or default if empty input).1573pub fn firstRunPrompt(label: []const u8, default: []const u8, buf: []u8) []const u8 {1574    p("   {s:<14} {s}> {s}", .{ label, c(DIM), c(RESET) });1575    flush();1576    var i: usize = 0;1577    while (i < buf.len - 1) {1578        const n = std.posix.read(std.posix.STDIN_FILENO, buf[i .. i + 1]) catch break;1579        if (n == 0) break;1580        if (buf[i] == '\n') break;1581        i += 1;1582    }1583    const input = std.mem.trim(u8, buf[0..i], " \t\r");1584    if (input.len == 0) {1585        // Echo the default so the output shows what was chosen1586        p("{s}{s}{s}\n", .{ c(DIM), default, c(RESET) });1587        flush();1588        return default;1589    }1590    return input;1591}15921593pub fn firstRunScanning() void {1594    p("\n   {s}:: scanning for config...{s}\n", .{ c(DIM), c(RESET) });1595}15961597// Report what the scan found at /etc/nixos, noting flake vs channel.1598pub fn firstRunDetected(path: []const u8, is_flake: bool) void {1599    const kind = if (is_flake) "flake-based system" else "channel-based system";1600    p("   {s}-> found {s}{s}   {s}({s}){s}\n\n", .{ c(CYAN), path, c(RESET), c(DIM), kind, c(RESET) });1601}16021603pub fn firstRunNoneFound() void {1604    p("   {s}-> nothing found at /etc/nixos{s}\n\n", .{ c(DIM), c(RESET) });1605}16061607// Prompt with a pre-filled default shown in brackets. Empty input accepts the1608// default. When `detected` and a default is present, note that enter confirms.1609pub fn firstRunPromptDefault(label: []const u8, default: []const u8, detected: bool, buf: []u8) []const u8 {1610    if (default.len > 0) {1611        p("   {s:<14} {s}[{s}]{s} > ", .{ label, c(DIM), default, c(RESET) });1612        if (detected) p("{s}enter to confirm{s} ", .{ c(DIM), c(RESET) });1613    } else {1614        p("   {s:<14} {s}> {s}", .{ label, c(DIM), c(RESET) });1615    }1616    flush();1617    var i: usize = 0;1618    while (i < buf.len - 1) {1619        const n = std.posix.read(std.posix.STDIN_FILENO, buf[i .. i + 1]) catch break;1620        if (n == 0) break;1621        if (buf[i] == '\n') break;1622        i += 1;1623    }1624    const input = std.mem.trim(u8, buf[0..i], " \t\r");1625    if (input.len == 0) {1626        p("{s}{s}{s}\n", .{ c(DIM), default, c(RESET) });1627        flush();1628        return default;1629    }1630    return input;1631}16321633// Shown before channel operations on a flake-managed system, where nix-channel1634// commands generally don't apply.1635pub fn flakeChannelNote() void {1636    p("{s}{s}note: flake-based system — use {s}nina flake update{s}{s} to update inputs{s}\n", .{ hdr(), c(DIM), c(CYAN), c(RESET), c(DIM), c(RESET) });1637}16381639pub fn firstRunWritten(path: []const u8) void {1640    p("\n   {s}written to {s}{s}\n\n", .{ c(DIM), path, c(RESET) });1641}16421643pub fn firstRunSkipped() void {1644    p("\n   {s}skipping setup in non-interactive mode{s}\n", .{ c(DIM), c(RESET) });1645}