output.zig

58.6 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}395396// Strips terminal-hostile bytes from external/untrusted text before it reaches397// the terminal: full CSI sequences (ESC '[' ... final byte) — used to scrub a398// child process's ANSI color when NO_COLOR forces capture-then-print instead of399// a direct stream — plus any other byte < 0x20 except \n and \t, which would400// otherwise let hook output, a nix search description, or an unparseable log401// line smuggle escape sequences (title changes, screen garbage, spoofed lines)402// into the terminal (NINA-016).403pub fn sanitize(gpa: std.mem.Allocator, input: []const u8) ![]u8 {404    var out: std.ArrayList(u8) = .empty;405    errdefer out.deinit(gpa);406    var i: usize = 0;407    while (i < input.len) {408        const b = input[i];409        if (b == 0x1b and i + 1 < input.len and input[i + 1] == '[') {410            i += 2;411            while (i < input.len and !(input[i] >= 0x40 and input[i] <= 0x7e)) : (i += 1) {}412            if (i < input.len) i += 1; // consume the final byte413            continue;414        }415        if (b < 0x20 and b != '\n' and b != '\t') {416            i += 1;417            continue;418        }419        try out.append(gpa, b);420        i += 1;421    }422    return out.toOwnedSlice(gpa);423}424425test "sanitize strips CSI color sequences" {426    const cleaned = try sanitize(std.testing.allocator, "kepr: \x1b[31;1m13.1 KiB\x1b[0m");427    defer std.testing.allocator.free(cleaned);428    try std.testing.expectEqualStrings("kepr: 13.1 KiB", cleaned);429}430431test "sanitize strips bare control bytes but keeps newline and tab" {432    const cleaned = try sanitize(std.testing.allocator, "line one\x07\nnext\ttab\x1b]0;evil title\x07 done");433    defer std.testing.allocator.free(cleaned);434    try std.testing.expectEqualStrings("line one\nnext\ttab]0;evil title done", cleaned);435}436437// gpa sanitizes each hook output line before it reaches the terminal — hooks are438// the user's own code (weak boundary, but still not nina's own text) and their439// output could contain embedded escape sequences (NINA-016).440pub fn hookFailed(gpa: std.mem.Allocator, name: []const u8, code: u8, hook_output: []const u8) void {441    p("{s}{s} hook exited with code {d}{s}\n\n", .{ hdr(), name, code, c(RESET) });442443    if (hook_output.len > 0) {444        var lines = std.mem.splitScalar(u8, hook_output, '\n');445        var shown: [5][]const u8 = undefined;446        var count: usize = 0;447        while (lines.next()) |line| {448            const trimmed = std.mem.trim(u8, line, " \t\r");449            if (trimmed.len == 0) continue;450            shown[count % shown.len] = trimmed;451            count += 1;452        }453454        const display_count = @min(count, shown.len);455        const start = count - display_count;456        for (0..display_count) |i| {457            const line = shown[(start + i) % shown.len];458            const clean = sanitize(gpa, line) catch line;459            defer if (clean.ptr != line.ptr) gpa.free(clean);460            p("   {s}{s}{s}\n", .{ c(DIM), clean, c(RESET) });461        }462        p("\n", .{});463    }464}465466pub fn hookWarning(name: []const u8, code: u8, hook_output: []const u8) void {467    _ = hook_output;468    p("{s}   warning: {s} hook exited with code {d}{s}\n", .{ c(YELLOW), name, code, c(RESET) });469}470471// --- Confirmation prompt (returns true = yes) ---472473fn stdinIsTty() bool {474    return std.Io.File.stdin().isTty(_io) catch false;475}476477fn printConfirmAbortHint() void {478    p("   {s}refusing to assume yes on a closed/non-interactive stdin — pass --yes to confirm automatically{s}\n", .{ c(YELLOW), c(RESET) });479}480481// Pure decision for an interactive read that has already happened: `saw_eof` is482// true when the read loop hit end-of-input before a newline, `line` is whatever483// was read (possibly empty). A real EOF with nothing typed (e.g. Ctrl-D at the484// prompt) is treated the same as a closed/non-interactive stdin — silently485// proceeding on a closed input stream is exactly the footgun this prompt exists486// to prevent. Otherwise this is a plain [Y/n]-style default-yes parse.487fn decideAnswer(saw_eof: bool, line: []const u8) bool {488    if (saw_eof and line.len == 0) return false;489    const trimmed = std.mem.trim(u8, line, " \t");490    if (trimmed.len == 0) return true;491    return trimmed[0] != 'n' and trimmed[0] != 'N';492}493494// Split out from confirm() so a test can force the non-interactive branch495// deterministically instead of depending on the test runner's own stdin.496fn confirmWithTty(prompt: []const u8, is_tty: bool) bool {497    if (auto_yes) return true;498    if (!is_tty) {499        printConfirmAbortHint();500        return false;501    }502    p("   {s}continue? [Y/n]  ", .{prompt});503    flush();504    var buf: [64]u8 = undefined;505    var i: usize = 0;506    var eof = false;507    while (i < buf.len) {508        const n = std.posix.read(std.posix.STDIN_FILENO, buf[i .. i + 1]) catch {509            eof = true;510            break;511        };512        if (n == 0) {513            eof = true;514            break;515        }516        if (buf[i] == '\n') break;517        i += 1;518    }519    const line = buf[0..i];520    const answer = decideAnswer(eof, line);521    if (!answer and eof and line.len == 0) printConfirmAbortHint();522    return answer;523}524525pub fn confirm(prompt: []const u8) bool {526    return confirmWithTty(prompt, stdinIsTty());527}528529fn initForTest() void {530    const S = struct {531        var buf: [256]u8 = undefined;532        var discarding: std.Io.Writer.Discarding = .init(&buf);533        var env: std.process.Environ.Map = .init(std.testing.allocator);534    };535    init(&S.discarding.writer, std.testing.io, &S.env, false);536}537538test "confirmWithTty: non-tty stdin refuses and prints a hint instead of assuming yes (NINA-005)" {539    initForTest();540    defer setAutoYes(false);541    try std.testing.expect(!confirmWithTty("test", false));542}543544test "confirmWithTty: --yes bypasses the tty check entirely" {545    initForTest();546    setAutoYes(true);547    defer setAutoYes(false);548    try std.testing.expect(confirmWithTty("test", false));549}550551test "decideAnswer: real EOF with nothing typed refuses (NINA-005)" {552    try std.testing.expect(!decideAnswer(true, ""));553}554555test "decideAnswer: bare enter accepts the [Y/n] default" {556    try std.testing.expect(decideAnswer(false, ""));557}558559test "decideAnswer: explicit y/Y accepts" {560    try std.testing.expect(decideAnswer(false, "y"));561    try std.testing.expect(decideAnswer(false, "Y"));562}563564test "decideAnswer: explicit n/N refuses" {565    try std.testing.expect(!decideAnswer(false, "n"));566    try std.testing.expect(!decideAnswer(false, "N"));567}568569// Like confirm, but defaults to NO on an empty answer — for prompts that touch570// system files, where a stray Enter should never trigger the action.571pub fn confirmDefaultNo(question: []const u8) bool {572    p("   {s} [y/N]  ", .{question});573    flush();574    var buf: [64]u8 = undefined;575    var i: usize = 0;576    while (i < buf.len) {577        const n = std.posix.read(std.posix.STDIN_FILENO, buf[i .. i + 1]) catch break;578        if (n == 0) break;579        if (buf[i] == '\n') break;580        i += 1;581    }582    const input = std.mem.trim(u8, buf[0..i], " \t");583    if (input.len == 0) return false;584    return input[0] == 'y' or input[0] == 'Y';585}586587// --- Apply / rebuild ---588589pub fn applyStart(machine: []const u8) void {590    p("{s}{s}rebuilding {s}...\n", .{ KAO_COZY, hdr(), machine });591}592593// after_failure: true only when the previous apply this session failed and this594// one succeeded — the one moment that earns the excited kaomoji. Routine595// successes show no kaomoji.596pub fn applyDone(gen: u32, elapsed_ms: u64, after_failure: bool) void {597    const face = if (after_failure) KAO_EXCITED else "";598    const secs = @as(f64, @floatFromInt(elapsed_ms)) / 1000.0;599    if (elapsed_ms >= 1000) {600        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) });601    } else {602        p("{s}{s}generation {s}{d}{s}\n", .{ face, hdr(), c(BOLD), gen, c(RESET) });603    }604}605606pub fn applyFailed(translated: []const u8) void {607    p("{s}build failed\n", .{if (color_enabled) ERR_C else ERR_P});608    if (translated.len > 0) p("   {s}{s}{s}\n", .{ c(DIM), translated, c(RESET) });609    p("   {s}-> nina doctor{s}\n", .{ c(DIM), c(RESET) });610}611612pub fn applyDry(machine: []const u8) void {613    p("{s}dry run  {s}\n", .{ hdr(), machine });614}615616pub fn applyDryDone() void {617    p("{s}no changes applied\n", .{hdr()});618}619620// --- Check ---621622pub fn checkStart(machine: []const u8) void {623    p("{s}checking {s}...\n", .{ hdr(), machine });624}625626pub fn checkOk() void {627    p("{s}{s}ok{s}\n", .{ hdr(), c(GREEN), c(RESET) });628}629630pub fn checkFailed(msg: []const u8) void {631    p("{s}config invalid\n", .{if (color_enabled) ERR_C else ERR_P});632    if (msg.len > 0) p("   {s}{s}{s}\n", .{ c(DIM), msg, c(RESET) });633}634635// --- Back / go ---636637pub fn backStart(machine: []const u8, from: u32, to: u32) void {638    p("{s}rolling back  {s}  gen {d} -> gen {d}\n", .{ hdr(), machine, from, to });639}640641pub fn goStart(machine: []const u8, current: u32, target: u32) void {642    p("{s}switching  {s}  gen {d} -> gen {d}\n", .{ hdr(), machine, current, target });643}644645pub fn generationDone(n: u32) void {646    p("{s}done  gen {s}{d}{s}\n", .{ hdr(), c(BOLD), n, c(RESET) });647}648649// `back` has nothing older to roll back to. This is a clean stop, not a build650// failure — the rollback would otherwise surface nixos-rebuild's confusing651// 'no profile version older than the current' as a fake build error.652pub fn alreadyOldest() void {653    p("{s}already at the oldest generation\n", .{if (color_enabled) ERR_C else ERR_P});654}655656// Like generationDone but for `back` specifically — a successful rollback earns657// the gentle kaomoji. `go` keeps the plain generationDone line.658pub fn backDone(n: u32) void {659    p("{s}{s}done  gen {s}{d}{s}\n", .{ KAO_GENTLE, hdr(), c(BOLD), n, c(RESET) });660}661662// --- History ---663664pub fn historyHeader(machine: []const u8) void {665    p("{s}generations  {s}\n\n", .{ hdr(), machine });666}667668pub fn historyRow(gen: types.GenerationInfo) void {669    if (gen.current) {670        p("   {s}{d}{s}   {s}   {s}   {s}current{s}\n", .{ c(BOLD), gen.number, c(RESET), gen.date, gen.time, c(BOLD), c(RESET) });671    } else {672        p("   {s}{d}   {s}   {s}{s}\n", .{ c(DIM), gen.number, gen.date, gen.time, c(RESET) });673    }674}675676// --- Clean ---677678pub fn cleanStart(machine: []const u8, keep: u32, total: u32) void {679    p("{s}cleaning  {s}  keeping {d} of {d}\n", .{ hdr(), machine, keep, total });680}681682// Fewer generations than the keep limit — there's nothing to collect. Avoids the683// nonsensical 'keeping 5 of 1'.684pub fn cleanNothing(machine: []const u8, total: u32) void {685    p("{s}cleaning  {s}\n\n", .{ hdr(), machine });686    p("   only {d} generation{s} — nothing to remove.\n", .{ total, if (total == 1) "" else "s" });687}688689pub fn cleanDone() void {690    p("{s}{s}done\n", .{ KAO_CONTENT, hdr() });691}692693// --- Status ---694695pub fn statusHeader() void {696    p("{s}status\n\n", .{hdr()});697}698699pub fn statusRow(machine: []const u8, gen: u32, time: []const u8, size: []const u8, ok: bool) void {700    if (ok) {701        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) });702    } else {703        p("   {s}{s}   {s}unreachable{s}\n", .{ c(RED), machine, "", c(RESET) });704    }705}706707// Dim Home Manager generation line, indented under the machine row. Only shown708// when standalone HM is detected; absent otherwise so the layout is unchanged.709pub fn statusHomeRow(gen: u32, detail: []const u8) void {710    if (detail.len > 0) {711        p("   {s}         hm  gen {d}   {s}{s}\n", .{ c(DIM), gen, detail, c(RESET) });712    } else {713        p("   {s}         hm  gen {d}{s}\n", .{ c(DIM), gen, c(RESET) });714    }715}716717// --- Diff ---718719pub fn diffHeader(a: u32, b: u32, machine: []const u8) void {720    p("{s}gen {d} -> gen {d}  {s}\n\n", .{ hdr(), a, b, machine });721}722723// Reached when no generation is marked current (non-standard profile layout,724// a transient readlink failure, or a non-GNU remote host) or there are too725// few generations to infer a pair — nothing safe to diff against.726pub fn diffCannotDetermine() void {727    p("{s}cannot determine current generation — nothing to diff\n", .{if (color_enabled) WARN_C else WARN_P});728}729730pub fn diffRow(entry: types.DiffEntry) void {731    switch (entry.op) {732        .add => p("   {s}+{s} {s}   {s}\n", .{ c(GREEN), c(RESET), entry.package, entry.new_version orelse "" }),733        .remove => p("   {s}-{s} {s}   {s}\n", .{ c(RED), c(RESET), entry.package, entry.old_version orelse "" }),734        .change => p("   {s}^{s} {s}   {s} -> {s}\n", .{ c(CYAN), c(RESET), entry.package, entry.old_version orelse "", entry.new_version orelse "" }),735    }736}737738// --- Doctor ---739740pub fn doctorHeader(machine: []const u8) void {741    p("{s}diagnosing  {s}\n\n", .{ hdr(), machine });742}743744pub fn doctorRow(check: types.DoctorCheck) void {745    const status_str = switch (check.status) {746        .ok => if (color_enabled) GREEN ++ "ok" ++ RESET else "ok",747        .warn => if (color_enabled) YELLOW ++ "warn" ++ RESET else "warn",748        .fail => if (color_enabled) RED ++ "fail" ++ RESET else "fail",749    };750    const note_str = check.note orelse "";751    p("   {s:<16}  {s}   {s}\n", .{ check.name, status_str, note_str });752}753754pub fn doctorSummary(warnings: u32, failures: u32) void {755    if (failures > 0) {756        p("{s}{d} problems\n", .{ hdr(), failures });757    } else if (warnings > 0) {758        p("{s}{d} warnings\n", .{ hdr(), warnings });759    } else {760        p("{s}{s}{s}all good{s}\n", .{ KAO_HAPPY, hdr(), c(GREEN), c(RESET) });761    }762}763764// --- Update ---765766pub fn updateStart(machine: []const u8) void {767    p("{s}updating channels  {s}\n\n", .{ hdr(), machine });768}769770pub fn updateChannel(name: []const u8, old: ?[]const u8, new: ?[]const u8) void {771    if (old != null and new != null and !std.mem.eql(u8, old.?, new.?)) {772        p("   {s}   {s} -> {s}\n", .{ name, old.?, new.? });773    } else {774        p("   {s}   {s}no change{s}\n", .{ name, c(DIM), c(RESET) });775    }776}777778pub fn updateDone() void {779    p("\n{s}done\n", .{hdr()});780}781782// --- Upgrade ---783784pub fn upgradeStart(machine: []const u8) void {785    p("{s}upgrading  {s}\n", .{ hdr(), machine });786}787788// --- Log ---789790pub fn logHeader(machine: []const u8) void {791    p("{s}history  {s}\n\n", .{ hdr(), machine });792}793794pub fn logRow(date: []const u8, time: []const u8, action: []const u8, detail: []const u8) void {795    p("   {s}{s}  {s}{s}   {s:<16}  {s}\n", .{ c(DIM), date, time, c(RESET), action, detail });796}797798// --- Edit ---799800pub fn editOpen(path: []const u8, editor: []const u8) void {801    p("{s}opening {s}\n", .{ hdr(), path });802    printSubstep("{s}", .{editor});803    p("\n   {s}run nina check to validate before applying{s}\n", .{ c(DIM), c(RESET) });804}805806// `nina edit hardware` is a mistake: hardware-configuration.nix is generated by807// nixos-generate-config and warns against hand-editing. Refuse and redirect.808pub fn editHardwareWarning() void {809    p("\n   {s}warning: hardware-configuration.nix is auto-generated — do not edit directly{s}\n", .{ c(YELLOW), c(RESET) });810    p("   {s}-> make hardware changes in configuration.nix instead{s}\n", .{ c(CYAN), c(RESET) });811}812813// --- Fmt ---814815pub fn fmtStart(path: []const u8) void {816    p("{s}formatting  {s}\n", .{ hdr(), path });817}818819pub fn fmtDone() void {820    p("{s}done\n", .{hdr()});821}822823pub fn fmtNeedsFormat() void {824    p("{s}needs formatting  {s}run nina fmt to fix{s}\n", .{ hdr(), c(DIM), c(RESET) });825}826827// --- Repl ---828829pub fn replStart() void {830    p("{s}nix repl  {s}nixpkgs loaded{s}  :q to exit\n", .{ hdr(), c(DIM), c(RESET) });831}832833// --- Develop ---834835pub fn developStart(pkgs: []const []const u8) void {836    p("{s}entering dev shell\n\n   ", .{hdr()});837    for (pkgs, 0..) |pkg, i| {838        if (i > 0) p("  ", .{});839        p("{s}", .{pkg});840    }841    p("\n\n   {s}-> press Ctrl+C or type 'exit' to return{s}\n\n", .{ c(DIM), c(RESET) });842}843844pub fn developDone() void {845    p("{s}{s}back\n", .{ KAO_SLEEPY, hdr() });846}847848// --- Info ---849850pub fn infoHeader(machine: []const u8) void {851    p("{s}{s}\n\n", .{ hdr(), machine });852}853854pub fn infoRow(key: []const u8, val: []const u8) void {855    p("   {s:<12}  {s}\n", .{ key, val });856}857858// --- Boot ---859860pub fn bootHeader(machine: []const u8) void {861    p("{s}boot entries  {s}\n\n", .{ hdr(), machine });862}863864pub fn bootEntry(entry: types.BootEntry, idx: usize) void {865    if (entry.current) {866        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) });867    } else {868        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) });869    }870    _ = idx;871}872873// --- Service ---874875pub fn serviceListHeader(machine: []const u8) void {876    p("{s}services  {s}\n\n", .{ hdr(), machine });877}878879pub fn serviceRow(svc: types.ServiceInfo) void {880    const state_str = switch (svc.state) {881        .active => if (color_enabled) GREEN ++ "active" ++ RESET else "active",882        .failed => if (color_enabled) RED ++ "failed" ++ RESET else "failed",883        .inactive => "inactive",884        .unknown => "unknown",885    };886    const uptime = svc.uptime orelse "";887    p("   {s:<24}  {s:<14}  {s}\n", .{ svc.name, state_str, uptime });888}889890pub fn serviceVerb(verb: []const u8, name: []const u8, machine: []const u8) void {891    p("{s}{s} {s}  {s}\n", .{ hdr(), verb, name, machine });892}893894pub fn serviceDone() void {895    p("{s}done\n", .{hdr()});896}897898pub fn serviceLogsHeader(name: []const u8, n: u32, machine: []const u8) void {899    p("{s}{s}  last {d} lines  {s}\n\n", .{ hdr(), name, n, machine });900}901902// --- Store ---903904pub fn storeInfo(info: types.StoreInfo) void {905    p("{s}store\n\n", .{hdr()});906    p("   {s:<16}  {s}\n", .{ "total", info.total_size });907    p("   {s:<16}  {d} paths\n", .{ "live", info.live_paths });908    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) });909}910911// --- Channel ---912913pub fn channelListHeader(machine: []const u8) void {914    p("{s}channels  {s}\n\n", .{ hdr(), machine });915}916917pub fn channelRow(ch: types.ChannelInfo) void {918    p("   {s:<16}  {s}\n", .{ ch.name, ch.url });919}920921// --- Flake ---922923pub fn flakeUpdateStart() void {924    p("{s}updating inputs\n\n", .{hdr()});925}926927pub fn flakeInput(input: types.FlakeInput) void {928    if (input.changed) {929        const old = if (input.old_rev) |r| r[0..@min(7, r.len)] else "?";930        const new = if (input.new_rev) |r| r[0..@min(7, r.len)] else "?";931        p("   {s:<20}  {s} -> {s}\n", .{ input.name, old, new });932    } else {933        p("   {s:<20}  {s}no change{s}\n", .{ input.name, c(DIM), c(RESET) });934    }935}936937pub fn flakeLockWritten() void {938    p("\n{s}flake.lock written\n", .{hdr()});939}940941pub fn flakeValid() void {942    p("{s}{s}valid{s}\n", .{ hdr(), c(GREEN), c(RESET) });943}944945pub fn flakeCheckStart() void {946    p("{s}checking flake\n", .{hdr()});947}948949// --- Profile ---950951pub fn profileListHeader() void {952    p("{s}profile packages\n\n", .{hdr()});953}954955pub fn profileRow(attr: []const u8, pkg_version: []const u8, description: []const u8) void {956    p("   {s:<24}  {s:<12}  {s}\n", .{ attr, pkg_version, description });957}958959// --- Install / Remove / Try ---960961// Typo help for install: the query matched nothing, so suggest the closest real962// package name (pink) and let the caller confirm.963pub fn didYouMean(query: []const u8, suggestion: []const u8) void {964    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) });965}966967pub fn installStart(pkg: []const u8, path: types.InstallPath) void {968    const path_str = switch (path) {969        .profile => "profile",970        .system => "system",971    };972    p("{s}installing {s}{s}{s}  {s}\n", .{ hdr(), c(PINK), pkg, c(RESET), path_str });973}974975pub fn installDone(pkg: []const u8) void {976    p("{s}{s}{s}{s} installed  {s}available now{s}\n", .{ hdr(), c(PINK), pkg, c(RESET), c(DIM), c(RESET) });977}978979pub fn removeStart(pkg: []const u8) void {980    p("{s}removing {s}{s}{s}\n", .{ hdr(), c(PINK), pkg, c(RESET) });981}982983// Plain-language health summary. No kaomoji, no hearts — just the facts.984pub fn mood(machine: []const u8, state: []const u8, gen: u32, age: []const u8, size: []const u8) void {985    const healthy = std.mem.eql(u8, state, "running");986    const verdict = if (healthy) "all good" else state;987    const color = if (healthy) GREEN else YELLOW;988    const face = if (healthy) KAO_HAPPY else "";989    p("{s}{s}{s}  {s}{s}{s}\n", .{ face, hdr(), machine, c(color), verdict, c(RESET) });990    if (age.len > 0 or size.len > 0) {991        p("   generation {d}, last applied {s}, {s} system closure\n", .{ gen, age, size });992    } else {993        p("   generation {d}\n", .{gen});994    }995}996997pub fn installEditorPrompt(pkg: []const u8, config_path: []const u8, line: u32, editor: []const u8) void {998    p("{s}opening {s}  add {s}{s}{s} to systemPackages\n", .{ hdr(), config_path, c(PINK), pkg, c(RESET) });999    const cmd = std.fmt.allocPrint(std.heap.page_allocator, "{s} {s} +{d}", .{ editor, config_path, line }) catch editor;1000    printSubstep("{s}", .{cmd});1001    p("\n   {s}save and close when done{s}\n\n", .{ c(DIM), c(RESET) });1002}10031004pub fn installSelectPrompt(pkg: []const u8, pkg_version: []const u8) void {1005    p("{s}{s}{s}{s}  {s}\n\n", .{ hdr(), c(PINK), pkg, c(RESET), pkg_version });1006    p("   [i] profile install    {s}instant  no rebuild{s}\n", .{ c(DIM), c(RESET) });1007    p("   [s] system install     {s}opens editor  requires apply{s}\n", .{ c(DIM), c(RESET) });1008    p("   [t] try now            {s}exits when done{s}\n\n", .{ c(DIM), c(RESET) });1009    p("   > ", .{});1010    flush();1011}10121013pub fn tryStart(pkg: []const u8) void {1014    p("{s}trying {s}{s}{s}  exit when done\n", .{ hdr(), c(PINK), pkg, c(RESET) });1015}10161017pub fn tryExitHint() void {1018    p("   {s}-> press Ctrl+C or type 'exit' to return{s}\n", .{ c(DIM), c(RESET) });1019}10201021pub fn tryDone() void {1022    p("{s}{s}back\n", .{ KAO_SLEEPY, hdr() });1023}10241025// --- List ---10261027pub fn listHeader(machine: []const u8) void {1028    p("{s}packages  {s}\n\n", .{ hdr(), machine });1029}10301031pub fn listSection(title: []const u8) void {1032    p("   {s}{s}{s}\n", .{ c(DIM), title, c(RESET) });1033}10341035// Padded name so the version column lines up into a clean two-column table.1036pub fn listPkg(name: []const u8, pkg_version: []const u8) void {1037    p("   {s}{s:<16}{s}  {s}{s}{s}\n", .{ c(PINK), name, c(RESET), c(DIM), pkg_version, c(RESET) });1038}10391040pub fn blankLine() void {1041    p("\n", .{});1042}10431044// --- Hello ---10451046pub fn hello(machines: []const types.Machine) void {1047    p("{s}{s}nina\n\n", .{ KAO_FACE, hdr() });1048    for (machines) |m| {1049        const kind = if (m.local) "local" else "ssh";1050        const detail = if (m.local) "default" else m.host orelse "";1051        p("   {s}{s}{s}   {s}   {s}\n", .{ c(DIM), m.name, c(RESET), kind, detail });1052    }1053    p("\n", .{});1054    const quick = [_][2][]const u8{1055        .{ "apply", "rebuild and switch" },1056        .{ "search <q>", "find packages" },1057        .{ "install <pkg>", "add to profile or system" },1058        .{ "status", "machine health" },1059        .{ "back", "roll back one generation" },1060        .{ "home apply", "apply home config" },1061        .{ "home back", "roll back home config" },1062        .{ "home history", "list home generations" },1063        .{ "home check", "validate home config" },1064        .{ "home diff", "compare home generations" },1065        .{ "home packages", "list managed packages" },1066    };1067    for (quick) |cmd| {1068        p("   {s:<16}  {s}{s}{s}\n", .{ cmd[0], c(DIM), cmd[1], c(RESET) });1069    }1070    p("\n", .{});1071}10721073// --- Help ---10741075pub fn help() void {1076    p("{s}nina  {s}NixOS Intuitive Navigation Assistant by Asha Software{s}\n\n", .{ hdr(), c(DIM), c(RESET) });1077    const cmds = [_][2][]const u8{1078        .{ "apply", "rebuild and switch" },1079        .{ "back", "roll back one generation" },1080        .{ "go <n>", "switch to generation n" },1081        .{ "history", "list all generations" },1082        .{ "clean", "remove old generations" },1083        .{ "search <q>", "find packages" },1084        .{ "install <pkg>", "add to profile or system" },1085        .{ "remove <pkg>", "remove from profile or system" },1086        .{ "try <pkg>", "test without installing" },1087        .{ "list", "show installed packages" },1088        .{ "edit", "open configuration.nix" },1089        .{ "edit --dir", "open config directory" },1090        .{ "check", "validate config" },1091        .{ "diff", "changes between generations" },1092        .{ "status", "machine health" },1093        .{ "update", "refresh channels" },1094        .{ "upgrade", "update and rebuild" },1095        .{ "log", "operation history" },1096        .{ "doctor", "diagnose issues" },1097        .{ "mood", "plain-language health" },1098        .{ "develop", "enter dev shell" },1099        .{ "flake", "flake management" },1100        .{ "build", "build a package" },1101        .{ "run", "run without installing" },1102        .{ "service", "manage services" },1103        .{ "store", "nix store tools" },1104        .{ "channel", "manage channels" },1105        .{ "profile", "user profile packages" },1106        .{ "home", "home manager commands (apply/back/history/edit/check/diff/packages)" },1107        .{ "info", "system information" },1108        .{ "boot", "boot entries" },1109        .{ "fmt", "format configuration.nix" },1110        .{ "repl", "nix repl with nixpkgs" },1111        .{ "option <q>", "search nixos options" },1112        .{ "pkg", "inspect packages" },1113        .{ "why <pkg>", "what pulled a package in" },1114        .{ "unpin <input>", "release a pinned flake input (nix flake update)" },1115        .{ "hash", "compute nix hash" },1116        .{ "fetch", "fetch and hash a url" },1117        .{ "goodbye", "uninstall nina" },1118        .{ "hello", "list machines" },1119        .{ "man [topic]", "open the built-in manual pager" },1120        .{ "help", "this message" },1121    };1122    for (cmds) |cmd| {1123        p("   {s:<18}  {s}{s}{s}\n", .{ cmd[0], c(DIM), cmd[1], c(RESET) });1124    }1125    p("\n   {s}flags: --on <machine>  --dry  --check  --no-apply  --last <n>  --all  --json  --yes  --version{s}\n", .{ c(DIM), c(RESET) });1126}11271128// Render a grouped command's subcommand list, shown when the group is invoked1129// with no subcommand or an explicit `help`. Rows are {invocation, description}.1130pub fn subcommandHelp(group: []const u8, rows: []const [2][]const u8, footer: ?[]const u8) void {1131    p("{s}{s} subcommands\n\n", .{ hdr(), group });1132    for (rows) |row| {1133        p("   {s:<16}  {s}{s}{s}\n", .{ row[0], c(DIM), row[1], c(RESET) });1134    }1135    if (footer) |f| p("\n   {s}{s}{s}\n", .{ c(DIM), f, c(RESET) });1136    p("\n   nina {s} help  {s}for this message{s}\n", .{ group, c(DIM), c(RESET) });1137}11381139pub fn version() void {1140    p("{s}nina  v{s}  zig 0.16  zero dependencies\n", .{ hdr(), nina_version.VERSION });1141}11421143// --- Search (text output before TUI) ---11441145pub fn searchResult(pkg: types.NixPackage) void {1146    p("   {s}{s}{s}   {s}{s}{s}   {s}\n", .{ c(PINK), pkg.pname, c(RESET), c(DIM), pkg.version, c(RESET), pkg.description });1147}11481149pub fn searchHeader(query: []const u8, count: usize) void {1150    p("{s}search nixpkgs {s}  {s}{d} results{s}\n\n", .{ hdr(), query, c(DIM), count, c(RESET) });1151}11521153// --- Gen commands ---11541155pub fn genCurrent(n: u32) void {1156    p("{d}\n", .{n});1157}11581159pub fn done() void {1160    p("{s}done\n", .{hdr()});1161}11621163pub fn runStart(pkg: []const u8) void {1164    p("{s}running {s}{s}{s}\n", .{ hdr(), c(PINK), pkg, c(RESET) });1165}11661167pub fn buildStart(attr: []const u8) void {1168    p("{s}building {s}\n", .{ hdr(), attr });1169}11701171pub fn buildDone() void {1172    p("{s}done\n", .{hdr()});1173}11741175// --- Self-update (nina update) ---11761177pub fn updateSelfStart() void {1178    p("{s}{s}checking for updates\n", .{ KAO_READY, hdr() });1179}11801181pub fn updateSelfCurrent(ver: []const u8) void {1182    p("{s}{s}nina {s} is up to date{s}\n", .{ hdr(), c(GREEN), ver, c(RESET) });1183}11841185pub fn updateSelfAvailable(current: []const u8, latest: []const u8) void {1186    p("{s}update available\n", .{hdr()});1187    p("{s}current  {s}{s}{s}\n", .{ step(), c(DIM), current, c(RESET) });1188    p("{s}latest   {s}{s}{s}{s}\n", .{ step(), c(BOLD), c(GREEN), latest, c(RESET) });1189}11901191fn releaseNotesHeading(line: []const u8) []const u8 {1192    var i: usize = 0;1193    while (i < line.len and line[i] == '#') : (i += 1) {}1194    return std.mem.trim(u8, line[i..], " \t");1195}11961197fn releaseNotesBullet(line: []const u8) ?[]const u8 {1198    if (line.len < 2) return null;1199    const marker = line[0];1200    if ((marker == '-' or marker == '*' or marker == '+') and line[1] == ' ') return line[2..];1201    if (std.ascii.isDigit(marker)) {1202        var i: usize = 1;1203        while (i < line.len and std.ascii.isDigit(line[i])) : (i += 1) {}1204        if (i + 1 < line.len and line[i] == '.' and line[i + 1] == ' ') return line[i + 2 ..];1205    }1206    return null;1207}12081209pub fn updateSelfReleaseNotes(notes: []const u8) void {1210    const trimmed = std.mem.trim(u8, notes, " \t\r\n");1211    if (trimmed.len == 0) return;12121213    p("{s}changelog\n", .{hdr()});1214    var lines = std.mem.splitScalar(u8, trimmed, '\n');1215    while (lines.next()) |raw_line| {1216        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;1217        const text = std.mem.trim(u8, line, " \t");1218        if (text.len == 0) {1219            p("\n", .{});1220            continue;1221        }1222        if (text[0] == '#') {1223            const title = releaseNotesHeading(text);1224            if (title.len == 0) continue;1225            p("   {s}{s}{s}{s}\n", .{ c(BOLD), c(CYAN), title, c(RESET) });1226            continue;1227        }1228        if (releaseNotesBullet(text)) |item| {1229            p("   {s}- {s}{s}\n", .{ c(CYAN), item, c(RESET) });1230            continue;1231        }1232        p("   {s}\n", .{text});1233    }1234}12351236pub fn updateSelfDownloading(ver: []const u8, platform: []const u8) void {1237    p("{s}downloading nina {s} for {s}\n", .{ step(), ver, platform });1238}12391240pub fn updateSelfVerifying() void {1241    p("{s}verifying checksum\n", .{step()});1242}12431244pub fn updateSelfInstalling(install_path: []const u8) void {1245    p("{s}installing to {s}\n", .{ step(), install_path });1246}12471248pub fn updateSelfDone(old_ver: []const u8, new_ver: []const u8) void {1249    p("{s}updated  {s} {s}→{s} {s}\n", .{ hdr(), old_ver, c(DIM), c(RESET), new_ver });1250}12511252pub fn updateSelfNoPlatform(platform: []const u8) void {1253    p("{s}no pre-built binary for {s}\n", .{ hdr(), platform });1254    p("{s}check kepr.uk/nina/releases for available platforms\n", .{step()});1255}12561257pub fn updateSelfNetworkError() void {1258    p("{s}{s}\n", .{ if (color_enabled) WARN_C else WARN_P, "could not reach kepr.uk — check your connection" });1259}12601261pub fn updateSelfChecksumFailed() void {1262    p("{s}checksum mismatch — download may be corrupt\n", .{if (color_enabled) ERR_C else ERR_P});1263    p("{s}try again or download manually from kepr.uk/nina/releases\n", .{step()});1264}12651266pub fn updateSelfNixManaged(new_ver: []const u8) void {1267    p("{s}upgrading to {s}{s}{s} via nix profile\n", .{ step(), c(BOLD), new_ver, c(RESET) });1268}12691270pub fn updateSelfNixFailed() void {1271    p("{s}nix profile upgrade failed\n", .{if (color_enabled) ERR_C else ERR_P});1272    p("{s}try manually: nix profile upgrade '.*nina.*'\n", .{step()});1273}12741275// Reached when building the new version into the store fails, before the1276// profile has been touched at all — the old nina element is still installed1277// and working.1278pub fn updateSelfNixPrefetchFailed() void {1279    p("{s}could not build the new version — check your connection and try again\n", .{if (color_enabled) ERR_C else ERR_P});1280    p("{s}your current nina install is untouched\n", .{step()});1281}12821283// Reached only after `nix profile remove` already succeeded and the1284// re-add failed despite the new version having just been built into the1285// store — nina is genuinely uninstalled at this point, not just stuck on1286// the old version, so the recovery command must reinstall from scratch1287// rather than upgrade. Expected to be rare now that the build happens1288// before the profile is touched.1289pub fn updateSelfNixReinstallFailed() void {1290    p("{s}nix profile add failed — nina was removed and is not reinstalled\n", .{if (color_enabled) ERR_C else ERR_P});1291    p("{s}reinstall manually: nix profile add --no-write-lock-file 'https://kepr.uk/nina/archive/HEAD.tar.gz#nina'\n", .{step()});1292}12931294pub fn updateSelfNixRehash() void {1295    p("{s}run {s}hash -r{s} or open a new shell to use the updated binary\n", .{ step(), c(DIM), c(RESET) });1296}12971298// Reached when nina is in the store but not a `nix profile` element — i.e. it1299// was installed by the system config (NixOS module / systemPackages) or1300// home-manager. `nina update` (the profile self-updater) can't touch those;1301// pushing them at `nix profile add` would spawn a second, drifting install.1302pub fn updateSelfSystemManaged() void {1303    p("{s}nina is managed by your system configuration, not nina update\n", .{hdr()});1304    p("{s}update it where you manage that config:\n", .{step()});1305    p("      {s}nix flake update nina && sudo nixos-rebuild switch{s}\n", .{ c(DIM), c(RESET) });1306}13071308// --- Goodbye / uninstall ---13091310pub fn goodbyeStart() void {1311    p("{s}uninstalling nina\n", .{hdr()});1312}13131314pub fn goodbyeFile(path: []const u8) void {1315    p("{s}will remove {s}\n", .{ step(), path });1316}13171318pub fn goodbyeNix() void {1319    p("{s}will remove nina from nix profile\n", .{step()});1320    p("{s}command: nix profile remove nina\n", .{step()});1321}13221323pub fn goodbyeDone() void {1324    p("{s}goodbye! see kepr.uk/nina to reinstall\n", .{hdr()});1325}13261327pub fn goodbyeFailed(msg: []const u8) void {1328    p("{s}{s}\n", .{ if (color_enabled) ERR_C else ERR_P, msg });1329}13301331// --- Setup ---13321333pub fn setupCheck() void {1334    p("{s}checking nix features\n", .{hdr()});1335}13361337pub fn setupFeatures(nix_command: bool, flakes: bool) void {1338    p("{s}nix-command  {s}{s}{s}\n", .{1339        step(),1340        if (nix_command) c(GREEN) else "",1341        if (nix_command) "enabled" else "not enabled",1342        if (nix_command) c(RESET) else "",1343    });1344    p("{s}flakes       {s}{s}{s}\n", .{1345        step(),1346        if (flakes) c(GREEN) else "",1347        if (flakes) "enabled" else "not enabled",1348        if (flakes) c(RESET) else "",1349    });1350}13511352pub fn setupAllSet() void {1353    p("{s}all set\n", .{hdr()});1354}13551356// Printed once, before the first search, when the nixpkgs registry still points1357// at a remote URL. Flush so it lands before `nix registry pin` and any results.1358pub fn pinningRegistry() void {1359    p("{s}pinning nixpkgs for fast local search...\n", .{hdr()});1360    flush();1361}13621363// --- Plain (non-tty) search rendering ---1364// Color-gated equivalents of the raw-ANSI TUI widget, for piped/scripted search.1365// Using the gated header + c() keeps ANSI out of non-tty output (NO_COLOR / pipes).13661367pub fn searchPlainHeader(mode_str: []const u8, query: []const u8, count: u64) void {1368    p("{s}search {s} {s}  {s}{d} results{s}\n", .{ hdr(), mode_str, query, c(DIM), count, c(RESET) });1369}13701371pub fn searchPlainNoResults() void {1372    p("   no results\n", .{});1373}13741375pub fn searchPlainPackage(pname: []const u8, pkg_version: []const u8, description: []const u8, unfree: bool) void {1376    if (unfree) {1377        p("   {s}   {s}{s}{s}   {s}unfree{s}   {s}\n", .{ pname, c(CYAN), pkg_version, c(RESET), c(YELLOW), c(RESET), description });1378    } else {1379        p("   {s}   {s}{s}{s}   {s}\n", .{ pname, c(CYAN), pkg_version, c(RESET), description });1380    }1381}13821383pub fn searchPlainOption(name: []const u8, type_str: []const u8) void {1384    p("   {s}   {s}{s}{s}\n", .{ name, c(DIM), type_str, c(RESET) });1385}13861387pub fn searchEmptyQuery() void {1388    p("{s}search needs a query  {s}e.g. nina search firefox{s}\n", .{ hdr(), c(DIM), c(RESET) });1389}13901391pub fn setupEnabling() void {1392    p("{s}enabling experimental features\n", .{hdr()});1393}13941395pub fn setupDone(path: []const u8) void {1396    p("{s}wrote {s}\n", .{ step(), path });1397    p("{s}done  open a new shell to pick up the change\n", .{hdr()});1398}13991400// --- NixOS setup (declarative configuration.nix) ---14011402pub fn setupNixosOffer(features_line: []const u8, conf_path: []const u8) void {1403    p("{s}on NixOS these go in your system config\n", .{hdr()});1404    p("   nina can add this line to {s}{s}{s}:\n\n", .{ c(DIM), conf_path, c(RESET) });1405    p("       {s}{s}{s}\n\n", .{ c(CYAN), features_line, c(RESET) });1406}14071408pub fn setupNixosWrote(conf_path: []const u8) void {1409    p("{s}added the line to {s}  {s}(backup: {s}.nina-bak){s}\n", .{ step(), conf_path, c(DIM), conf_path, c(RESET) });1410    p("{s}now run {s}sudo nixos-rebuild switch{s} — then nina's ready\n", .{ hdr(), c(BOLD), c(RESET) });1411}14121413pub fn setupNixosManual(features_line: []const u8, conf_path: []const u8) void {1414    p("{s}no problem — add this line inside the {s}{{ }}{s} in {s}:\n\n", .{ hdr(), c(DIM), c(RESET), conf_path });1415    p("       {s}{s}{s}\n\n", .{ c(CYAN), features_line, c(RESET) });1416    p("   then run {s}sudo nixos-rebuild switch{s} — then nina's ready\n", .{ c(BOLD), c(RESET) });1417}14181419pub fn setupNixosNeedsRebuild(conf_path: []const u8) void {1420    p("{s}already declared in {s}\n", .{ hdr(), conf_path });1421    p("   just run {s}sudo nixos-rebuild switch{s} to activate it\n", .{ c(BOLD), c(RESET) });1422}14231424pub fn unpinDone(input: []const u8) void {1425    p("{s}unpinned {s}\n", .{ hdr(), input });1426}14271428pub fn hashResult(hash: []const u8) void {1429    p("{s}\n", .{hash});1430}14311432pub fn fetchResult(hash: []const u8, url: []const u8) void {1433    _ = url;1434    p("{s}\n", .{hash});1435}14361437pub fn storeRepairStart() void {1438    p("{s}repairing store\n", .{hdr()});1439}14401441pub fn storeVerifyStart() void {1442    p("{s}verifying store\n", .{hdr()});1443}14441445pub fn storeOptimiseStart(machine: []const u8) void {1446    p("{s}optimising store  {s}\n", .{ hdr(), machine });1447    printSubstep("nix store optimise", .{});1448}14491450pub fn storeOptimiseDone() void {1451    p("{s}done\n", .{hdr()});1452}14531454pub fn storeGcDone(freed: []const u8) void {1455    p("{s}freed {s}\n", .{ hdr(), freed });1456}14571458pub fn storePath(path: []const u8) void {1459    p("{s}\n", .{path});1460}14611462pub fn pkgResult(key: []const u8, val: []const u8) void {1463    p("   {s:<16}  {s}\n", .{ key, val });1464}14651466pub fn channelDone() void {1467    p("{s}done\n", .{hdr()});1468}14691470pub fn flakeShowHeader(name: []const u8) void {1471    p("{s}{s}\n\n", .{ hdr(), name });1472}14731474pub fn flakeShowEntry(kind: []const u8, name: []const u8, desc: []const u8) void {1475    p("   {s:<12}  {s:<24}  {s}\n", .{ kind, name, desc });1476}14771478// --- Home Manager ---14791480pub fn homeNotInstalled() void {1481    p("{s}home manager not detected  {s}nothing to do{s}\n", .{ hdr(), c(DIM), c(RESET) });1482}14831484// HM is a NixOS/flake module — rebuilt by nixos-rebuild, not the standalone CLI.1485pub fn homeModuleManaged() void {1486    p("{s}home manager is managed by your system config\n", .{hdr()});1487    p("   {s}-> run {s}nina apply{s}{s} to rebuild both together{s}\n", .{ c(CYAN), c(BOLD), c(RESET), c(CYAN), c(RESET) });1488}14891490pub fn homeApplyStart(machine: []const u8) void {1491    p("{s}{s}applying home config  {s}\n", .{ KAO_COZY, hdr(), machine });1492}14931494pub fn homeApplyDone(gen: u32, elapsed_ms: u64) void {1495    const secs = @as(f64, @floatFromInt(elapsed_ms)) / 1000.0;1496    // gen 0 means the post-switch generation re-read failed — the switch itself1497    // succeeded, so report success without a misleading "generation 0".1498    if (gen == 0) {1499        if (elapsed_ms >= 1000) {1500            p("{s}done  {s}[{d:.1}s]{s}\n", .{ hdr(), c(DIM), secs, c(RESET) });1501        } else {1502            p("{s}done\n", .{hdr()});1503        }1504        return;1505    }1506    if (elapsed_ms >= 1000) {1507        p("{s}generation {s}{d}{s}  {s}[{d:.1}s]{s}\n", .{ hdr(), c(BOLD), gen, c(RESET), c(DIM), secs, c(RESET) });1508    } else {1509        p("{s}generation {s}{d}{s}\n", .{ hdr(), c(BOLD), gen, c(RESET) });1510    }1511}15121513// `home` was invoked against a remote machine. Detection + flake-ref are1514// local-only, so we don't act on a remote — point the user at the local run.1515pub fn homeLocalOnly(machine: []const u8) void {1516    p("{s}home manager commands run on the local machine only\n", .{hdr()});1517    p("   {s}-> '{s}' is remote; run nina home on that machine directly{s}\n", .{ c(DIM), machine, c(RESET) });1518}15191520pub fn homeApplyDry(machine: []const u8) void {1521    p("{s}home dry run  {s}\n", .{ hdr(), machine });1522}15231524pub fn homeApplyDryDone() void {1525    p("{s}{s}ok{s}  no changes applied\n", .{ hdr(), c(GREEN), c(RESET) });1526}15271528pub fn homeBackStart(machine: []const u8, from: u32, to: u32) void {1529    p("{s}rolling back home config  {s}  gen {d} -> gen {d}\n", .{ hdr(), machine, from, to });1530}15311532pub fn homeBackDone(n: u32) void {1533    p("{s}{s}done  gen {s}{d}{s}\n", .{ KAO_GENTLE, hdr(), c(BOLD), n, c(RESET) });1534}15351536pub fn homeHistoryHeader(machine: []const u8) void {1537    p("{s}home generations  {s}\n\n", .{ hdr(), machine });1538}15391540pub fn homeHistoryRow(number: u32, date: []const u8, time: []const u8, current: bool) void {1541    if (current) {1542        p("   {s}{d}{s}   {s}   {s}   {s}current{s}\n", .{ c(BOLD), number, c(RESET), date, time, c(BOLD), c(RESET) });1543    } else {1544        p("   {s}{d}   {s}   {s}{s}\n", .{ c(DIM), number, date, time, c(RESET) });1545    }1546}15471548pub fn homeEditOpen(path: []const u8, editor: []const u8) void {1549    p("{s}opening {s}\n", .{ hdr(), path });1550    printSubstep("{s}", .{editor});1551}15521553pub fn homeCheckStart(machine: []const u8) void {1554    p("{s}checking home config  {s}\n", .{ hdr(), machine });1555}15561557pub fn homeCheckOk() void {1558    p("{s}{s}ok{s}\n", .{ hdr(), c(GREEN), c(RESET) });1559}15601561pub fn homeDiffHeader(a: u32, b: u32, machine: []const u8) void {1562    p("{s}home gen {d} -> gen {d}  {s}\n\n", .{ hdr(), a, b, machine });1563}15641565pub fn homeNothingToDiff() void {1566    p("{s}only one home generation — nothing to diff yet\n", .{hdr()});1567}15681569pub fn homePackagesHeader(machine: []const u8) void {1570    p("{s}home packages  {s}\n\n", .{ hdr(), machine });1571}15721573// A flake attribute wasn't defined — note it (dim) before trying the next, less1574// specific candidate in the home-apply fallback chain.1575pub fn homeAttrFallback(ref: []const u8) void {1576    p("   {s}{s} not defined — trying next{s}\n", .{ c(DIM), ref, c(RESET) });1577}15781579pub fn homeInitStart(switch_on_init: bool, dir: ?[]const u8) void {1580    const target = dir orelse "~/.config/home-manager";1581    if (switch_on_init) {1582        p("{s}{s}setting up home manager  {s}{s}{s}\n", .{ KAO_COZY, hdr(), c(PINK), target, c(RESET) });1583        p("   {s}-> will activate after init{s}\n", .{ c(DIM), c(RESET) });1584    } else {1585        p("{s}initialising home manager  {s}{s}{s}\n", .{ hdr(), c(PINK), target, c(RESET) });1586        p("   {s}-> edit home.nix then run {s}nina home apply{s}\n", .{ c(DIM), c(BOLD), c(RESET) });1587    }1588}15891590pub fn homeInitDone(switch_on_init: bool) void {1591    if (switch_on_init) {1592        p("{s}{s}home manager ready\n", .{ KAO_GENTLE, hdr() });1593    } else {1594        p("{s}done  edit home.nix and run {s}nina home apply{s} when ready\n", .{ hdr(), c(BOLD), c(RESET) });1595    }1596}15971598// `home init` against a config that already exists — never overwrite; point at1599// apply instead.1600pub fn homeInitExists(path: []const u8) void {1601    p("{s}home manager config already exists\n", .{if (color_enabled) WARN_C else WARN_P});1602    p("   {s}{s}{s}\n", .{ c(DIM), path, c(RESET) });1603    p("   {s}-> run {s}nina home apply{s}{s} to activate it{s}\n", .{ c(CYAN), c(BOLD), c(RESET), c(CYAN), c(RESET) });1604}16051606// --- First-run wizard ---16071608pub fn firstRunBanner() void {1609    p("{s}{s}nina \u{2014} first run\n\n", .{ KAO_FACE, hdr() });1610}16111612pub fn firstRunNoConfig() void {1613    p("   no config found. let me get set up.\n\n", .{});1614}16151616// Print a prompt line and read the user's answer. Returns the default if the1617// user presses Enter without typing anything. buf must be at least 256 bytes.1618// Returns a slice into buf (or default if empty input).1619pub fn firstRunPrompt(label: []const u8, default: []const u8, buf: []u8) []const u8 {1620    p("   {s:<14} {s}> {s}", .{ label, c(DIM), c(RESET) });1621    flush();1622    var i: usize = 0;1623    while (i < buf.len - 1) {1624        const n = std.posix.read(std.posix.STDIN_FILENO, buf[i .. i + 1]) catch break;1625        if (n == 0) break;1626        if (buf[i] == '\n') break;1627        i += 1;1628    }1629    const input = std.mem.trim(u8, buf[0..i], " \t\r");1630    if (input.len == 0) {1631        // Echo the default so the output shows what was chosen1632        p("{s}{s}{s}\n", .{ c(DIM), default, c(RESET) });1633        flush();1634        return default;1635    }1636    return input;1637}16381639pub fn firstRunScanning() void {1640    p("\n   {s}:: scanning for config...{s}\n", .{ c(DIM), c(RESET) });1641}16421643// Report what the scan found at /etc/nixos, noting flake vs channel.1644pub fn firstRunDetected(path: []const u8, is_flake: bool) void {1645    const kind = if (is_flake) "flake-based system" else "channel-based system";1646    p("   {s}-> found {s}{s}   {s}({s}){s}\n\n", .{ c(CYAN), path, c(RESET), c(DIM), kind, c(RESET) });1647}16481649pub fn firstRunNoneFound() void {1650    p("   {s}-> nothing found at /etc/nixos{s}\n\n", .{ c(DIM), c(RESET) });1651}16521653// Prompt with a pre-filled default shown in brackets. Empty input accepts the1654// default. When `detected` and a default is present, note that enter confirms.1655pub fn firstRunPromptDefault(label: []const u8, default: []const u8, detected: bool, buf: []u8) []const u8 {1656    if (default.len > 0) {1657        p("   {s:<14} {s}[{s}]{s} > ", .{ label, c(DIM), default, c(RESET) });1658        if (detected) p("{s}enter to confirm{s} ", .{ c(DIM), c(RESET) });1659    } else {1660        p("   {s:<14} {s}> {s}", .{ label, c(DIM), c(RESET) });1661    }1662    flush();1663    var i: usize = 0;1664    while (i < buf.len - 1) {1665        const n = std.posix.read(std.posix.STDIN_FILENO, buf[i .. i + 1]) catch break;1666        if (n == 0) break;1667        if (buf[i] == '\n') break;1668        i += 1;1669    }1670    const input = std.mem.trim(u8, buf[0..i], " \t\r");1671    if (input.len == 0) {1672        p("{s}{s}{s}\n", .{ c(DIM), default, c(RESET) });1673        flush();1674        return default;1675    }1676    return input;1677}16781679// Shown before channel operations on a flake-managed system, where nix-channel1680// commands generally don't apply.1681pub fn flakeChannelNote() void {1682    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) });1683}16841685pub fn firstRunWritten(path: []const u8) void {1686    p("\n   {s}written to {s}{s}\n\n", .{ c(DIM), path, c(RESET) });1687}16881689pub fn firstRunSkipped() void {1690    p("\n   {s}skipping setup in non-interactive mode{s}\n", .{ c(DIM), c(RESET) });1691}