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}", .{ c(BOLD), entry.title });867    } else {868        p("   {s}  {s}", .{ c(DIM), entry.title });869    }870    if (entry.date) |d| p("   {s}", .{d});871    p("{s}\n", .{c(RESET)});872    _ = idx;873}874875// --- Service ---876877pub fn serviceListHeader(machine: []const u8) void {878    p("{s}services  {s}\n\n", .{ hdr(), machine });879}880881pub fn serviceRow(svc: types.ServiceInfo) void {882    const state_str = switch (svc.state) {883        .active => if (color_enabled) GREEN ++ "active" ++ RESET else "active",884        .failed => if (color_enabled) RED ++ "failed" ++ RESET else "failed",885        .inactive => "inactive",886        .unknown => "unknown",887    };888    const uptime = svc.uptime orelse "";889    p("   {s:<24}  {s:<14}  {s}\n", .{ svc.name, state_str, uptime });890}891892pub fn serviceVerb(verb: []const u8, name: []const u8, machine: []const u8) void {893    p("{s}{s} {s}  {s}\n", .{ hdr(), verb, name, machine });894}895896pub fn serviceDone() void {897    p("{s}done\n", .{hdr()});898}899900pub fn serviceLogsHeader(name: []const u8, n: u32, machine: []const u8) void {901    p("{s}{s}  last {d} lines  {s}\n\n", .{ hdr(), name, n, machine });902}903904// --- Store ---905906pub fn storeInfo(info: types.StoreInfo) void {907    p("{s}store\n\n", .{hdr()});908    p("   {s:<16}  {s}\n", .{ "total", info.total_size });909    p("   {s:<16}  {d} paths\n", .{ "live", info.live_paths });910    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) });911}912913// --- Channel ---914915pub fn channelListHeader(machine: []const u8) void {916    p("{s}channels  {s}\n\n", .{ hdr(), machine });917}918919pub fn channelRow(ch: types.ChannelInfo) void {920    p("   {s:<16}  {s}\n", .{ ch.name, ch.url });921}922923// --- Flake ---924925pub fn flakeUpdateStart() void {926    p("{s}updating inputs\n\n", .{hdr()});927}928929pub fn flakeInput(input: types.FlakeInput) void {930    if (input.changed) {931        const old = if (input.old_rev) |r| r[0..@min(7, r.len)] else "?";932        const new = if (input.new_rev) |r| r[0..@min(7, r.len)] else "?";933        p("   {s:<20}  {s} -> {s}\n", .{ input.name, old, new });934    } else {935        p("   {s:<20}  {s}no change{s}\n", .{ input.name, c(DIM), c(RESET) });936    }937}938939pub fn flakeLockWritten() void {940    p("\n{s}flake.lock written\n", .{hdr()});941}942943pub fn flakeValid() void {944    p("{s}{s}valid{s}\n", .{ hdr(), c(GREEN), c(RESET) });945}946947pub fn flakeCheckStart() void {948    p("{s}checking flake\n", .{hdr()});949}950951// --- Profile ---952953pub fn profileListHeader() void {954    p("{s}profile packages\n\n", .{hdr()});955}956957pub fn profileRow(attr: []const u8, pkg_version: []const u8, description: []const u8) void {958    p("   {s:<24}  {s:<12}  {s}\n", .{ attr, pkg_version, description });959}960961// --- Install / Remove / Try ---962963// Typo help for install: the query matched nothing, so suggest the closest real964// package name (pink) and let the caller confirm.965pub fn didYouMean(query: []const u8, suggestion: []const u8) void {966    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) });967}968969pub fn installStart(pkg: []const u8, path: types.InstallPath) void {970    const path_str = switch (path) {971        .profile => "profile",972        .system => "system",973    };974    p("{s}installing {s}{s}{s}  {s}\n", .{ hdr(), c(PINK), pkg, c(RESET), path_str });975}976977pub fn installDone(pkg: []const u8) void {978    p("{s}{s}{s}{s} installed  {s}available now{s}\n", .{ hdr(), c(PINK), pkg, c(RESET), c(DIM), c(RESET) });979}980981pub fn removeStart(pkg: []const u8) void {982    p("{s}removing {s}{s}{s}\n", .{ hdr(), c(PINK), pkg, c(RESET) });983}984985// Plain-language health summary. No kaomoji, no hearts — just the facts.986pub fn mood(machine: []const u8, state: []const u8, gen: u32, age: []const u8, size: []const u8) void {987    const healthy = std.mem.eql(u8, state, "running");988    const verdict = if (healthy) "all good" else state;989    const color = if (healthy) GREEN else YELLOW;990    const face = if (healthy) KAO_HAPPY else "";991    p("{s}{s}{s}  {s}{s}{s}\n", .{ face, hdr(), machine, c(color), verdict, c(RESET) });992    if (age.len > 0 or size.len > 0) {993        p("   generation {d}, last applied {s}, {s} system closure\n", .{ gen, age, size });994    } else {995        p("   generation {d}\n", .{gen});996    }997}998999pub fn installEditorPrompt(pkg: []const u8, config_path: []const u8, line: u32, editor: []const u8) void {1000    p("{s}opening {s}  add {s}{s}{s} to systemPackages\n", .{ hdr(), config_path, c(PINK), pkg, c(RESET) });1001    const cmd = std.fmt.allocPrint(std.heap.page_allocator, "{s} {s} +{d}", .{ editor, config_path, line }) catch editor;1002    printSubstep("{s}", .{cmd});1003    p("\n   {s}save and close when done{s}\n\n", .{ c(DIM), c(RESET) });1004}10051006pub fn installSelectPrompt(pkg: []const u8, pkg_version: []const u8) void {1007    p("{s}{s}{s}{s}  {s}\n\n", .{ hdr(), c(PINK), pkg, c(RESET), pkg_version });1008    p("   [i] profile install    {s}instant  no rebuild{s}\n", .{ c(DIM), c(RESET) });1009    p("   [s] system install     {s}opens editor  requires apply{s}\n", .{ c(DIM), c(RESET) });1010    p("   [t] try now            {s}exits when done{s}\n\n", .{ c(DIM), c(RESET) });1011    p("   > ", .{});1012    flush();1013}10141015pub fn tryStart(pkg: []const u8) void {1016    p("{s}trying {s}{s}{s}  exit when done\n", .{ hdr(), c(PINK), pkg, c(RESET) });1017}10181019pub fn tryExitHint() void {1020    p("   {s}-> press Ctrl+C or type 'exit' to return{s}\n", .{ c(DIM), c(RESET) });1021}10221023pub fn tryDone() void {1024    p("{s}{s}back\n", .{ KAO_SLEEPY, hdr() });1025}10261027// --- List ---10281029pub fn listHeader(machine: []const u8) void {1030    p("{s}packages  {s}\n\n", .{ hdr(), machine });1031}10321033pub fn listSection(title: []const u8) void {1034    p("   {s}{s}{s}\n", .{ c(DIM), title, c(RESET) });1035}10361037// Padded name so the version column lines up into a clean two-column table.1038pub fn listPkg(name: []const u8, pkg_version: []const u8) void {1039    p("   {s}{s:<16}{s}  {s}{s}{s}\n", .{ c(PINK), name, c(RESET), c(DIM), pkg_version, c(RESET) });1040}10411042pub fn blankLine() void {1043    p("\n", .{});1044}10451046// --- Hello ---10471048pub fn hello(machines: []const types.Machine) void {1049    p("{s}{s}nina\n\n", .{ KAO_FACE, hdr() });1050    for (machines) |m| {1051        const kind = if (m.local) "local" else "ssh";1052        const detail = if (m.local) "default" else m.host orelse "";1053        p("   {s}{s}{s}   {s}   {s}\n", .{ c(DIM), m.name, c(RESET), kind, detail });1054    }1055    p("\n", .{});1056    const quick = [_][2][]const u8{1057        .{ "apply", "rebuild and switch" },1058        .{ "search <q>", "find packages" },1059        .{ "install <pkg>", "add to profile or system" },1060        .{ "status", "machine health" },1061        .{ "back", "roll back one generation" },1062        .{ "home apply", "apply home config" },1063        .{ "home back", "roll back home config" },1064        .{ "home history", "list home generations" },1065        .{ "home check", "validate home config" },1066        .{ "home diff", "compare home generations" },1067        .{ "home packages", "list managed packages" },1068    };1069    for (quick) |cmd| {1070        p("   {s:<16}  {s}{s}{s}\n", .{ cmd[0], c(DIM), cmd[1], c(RESET) });1071    }1072    p("\n", .{});1073}10741075// --- Help ---10761077pub fn help() void {1078    p("{s}nina  {s}NixOS Intuitive Navigation Assistant by Asha Software{s}\n\n", .{ hdr(), c(DIM), c(RESET) });1079    const cmds = [_][2][]const u8{1080        .{ "apply", "rebuild and switch" },1081        .{ "back", "roll back one generation" },1082        .{ "go <n>", "switch to generation n" },1083        .{ "history", "list all generations" },1084        .{ "clean", "remove old generations" },1085        .{ "search <q>", "find packages" },1086        .{ "install <pkg>", "add to profile or system" },1087        .{ "remove <pkg>", "remove from profile or system" },1088        .{ "try <pkg>", "test without installing" },1089        .{ "list", "show installed packages" },1090        .{ "edit", "open configuration.nix" },1091        .{ "edit --dir", "open config directory" },1092        .{ "check", "validate config" },1093        .{ "diff", "changes between generations" },1094        .{ "status", "machine health" },1095        .{ "update", "refresh channels" },1096        .{ "upgrade", "update and rebuild" },1097        .{ "log", "operation history" },1098        .{ "doctor", "diagnose issues" },1099        .{ "mood", "plain-language health" },1100        .{ "develop", "enter dev shell" },1101        .{ "flake", "flake management" },1102        .{ "build", "build a package" },1103        .{ "run", "run without installing" },1104        .{ "service", "manage services" },1105        .{ "store", "nix store tools" },1106        .{ "channel", "manage channels" },1107        .{ "profile", "user profile packages" },1108        .{ "home", "home manager commands (apply/back/history/edit/check/diff/packages)" },1109        .{ "info", "system information" },1110        .{ "boot", "boot entries" },1111        .{ "fmt", "format configuration.nix" },1112        .{ "repl", "nix repl with nixpkgs" },1113        .{ "option <q>", "search nixos options" },1114        .{ "pkg", "inspect packages" },1115        .{ "why <pkg>", "what pulled a package in" },1116        .{ "pin <input> <rev>", "pin a flake input to a commit" },1117        .{ "unpin <input>", "release a pinned flake input (nix flake update)" },1118        .{ "hash", "compute nix hash" },1119        .{ "fetch", "fetch and hash a url" },1120        .{ "goodbye", "uninstall nina" },1121        .{ "hello", "list machines" },1122        .{ "man [topic]", "open the built-in manual pager" },1123        .{ "help", "this message" },1124    };1125    for (cmds) |cmd| {1126        p("   {s:<18}  {s}{s}{s}\n", .{ cmd[0], c(DIM), cmd[1], c(RESET) });1127    }1128    p("\n   {s}flags: --on <machine>  --dry  --check  --no-apply  --last <n>  --all  --json  --yes  --version{s}\n", .{ c(DIM), c(RESET) });1129}11301131// Render a grouped command's subcommand list, shown when the group is invoked1132// with no subcommand or an explicit `help`. Rows are {invocation, description}.1133pub fn subcommandHelp(group: []const u8, rows: []const [2][]const u8, footer: ?[]const u8) void {1134    p("{s}{s} subcommands\n\n", .{ hdr(), group });1135    for (rows) |row| {1136        p("   {s:<16}  {s}{s}{s}\n", .{ row[0], c(DIM), row[1], c(RESET) });1137    }1138    if (footer) |f| p("\n   {s}{s}{s}\n", .{ c(DIM), f, c(RESET) });1139    p("\n   nina {s} help  {s}for this message{s}\n", .{ group, c(DIM), c(RESET) });1140}11411142pub fn version() void {1143    p("{s}nina  v{s}  zig 0.16  zero dependencies\n", .{ hdr(), nina_version.VERSION });1144}11451146// --- Search (text output before TUI) ---11471148pub fn searchResult(pkg: types.NixPackage) void {1149    p("   {s}{s}{s}   {s}{s}{s}   {s}\n", .{ c(PINK), pkg.pname, c(RESET), c(DIM), pkg.version, c(RESET), pkg.description });1150}11511152pub fn searchHeader(query: []const u8, count: usize) void {1153    p("{s}search nixpkgs {s}  {s}{d} results{s}\n\n", .{ hdr(), query, c(DIM), count, c(RESET) });1154}11551156// --- Gen commands ---11571158pub fn genCurrent(n: u32) void {1159    p("{d}\n", .{n});1160}11611162pub fn done() void {1163    p("{s}done\n", .{hdr()});1164}11651166pub fn runStart(pkg: []const u8) void {1167    p("{s}running {s}{s}{s}\n", .{ hdr(), c(PINK), pkg, c(RESET) });1168}11691170pub fn buildStart(attr: []const u8) void {1171    p("{s}building {s}\n", .{ hdr(), attr });1172}11731174pub fn buildDone() void {1175    p("{s}done\n", .{hdr()});1176}11771178// --- Self-update (nina update) ---11791180pub fn updateSelfStart() void {1181    p("{s}{s}checking for updates\n", .{ KAO_READY, hdr() });1182}11831184pub fn updateSelfCurrent(ver: []const u8) void {1185    p("{s}{s}nina {s} is up to date{s}\n", .{ hdr(), c(GREEN), ver, c(RESET) });1186}11871188pub fn updateSelfAvailable(current: []const u8, latest: []const u8) void {1189    p("{s}update available\n", .{hdr()});1190    p("{s}current  {s}{s}{s}\n", .{ step(), c(DIM), current, c(RESET) });1191    p("{s}latest   {s}{s}{s}{s}\n", .{ step(), c(BOLD), c(GREEN), latest, c(RESET) });1192}11931194fn releaseNotesHeading(line: []const u8) []const u8 {1195    var i: usize = 0;1196    while (i < line.len and line[i] == '#') : (i += 1) {}1197    return std.mem.trim(u8, line[i..], " \t");1198}11991200fn releaseNotesBullet(line: []const u8) ?[]const u8 {1201    if (line.len < 2) return null;1202    const marker = line[0];1203    if ((marker == '-' or marker == '*' or marker == '+') and line[1] == ' ') return line[2..];1204    if (std.ascii.isDigit(marker)) {1205        var i: usize = 1;1206        while (i < line.len and std.ascii.isDigit(line[i])) : (i += 1) {}1207        if (i + 1 < line.len and line[i] == '.' and line[i + 1] == ' ') return line[i + 2 ..];1208    }1209    return null;1210}12111212pub fn updateSelfReleaseNotes(notes: []const u8) void {1213    const trimmed = std.mem.trim(u8, notes, " \t\r\n");1214    if (trimmed.len == 0) return;12151216    p("{s}changelog\n", .{hdr()});1217    var lines = std.mem.splitScalar(u8, trimmed, '\n');1218    while (lines.next()) |raw_line| {1219        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;1220        const text = std.mem.trim(u8, line, " \t");1221        if (text.len == 0) {1222            p("\n", .{});1223            continue;1224        }1225        if (text[0] == '#') {1226            const title = releaseNotesHeading(text);1227            if (title.len == 0) continue;1228            p("   {s}{s}{s}{s}\n", .{ c(BOLD), c(CYAN), title, c(RESET) });1229            continue;1230        }1231        if (releaseNotesBullet(text)) |item| {1232            p("   {s}- {s}{s}\n", .{ c(CYAN), item, c(RESET) });1233            continue;1234        }1235        p("   {s}\n", .{text});1236    }1237}12381239pub fn updateSelfDownloading(ver: []const u8, platform: []const u8) void {1240    p("{s}downloading nina {s} for {s}\n", .{ step(), ver, platform });1241}12421243pub fn updateSelfVerifying() void {1244    p("{s}verifying checksum\n", .{step()});1245}12461247pub fn updateSelfInstalling(install_path: []const u8) void {1248    p("{s}installing to {s}\n", .{ step(), install_path });1249}12501251pub fn updateSelfDone(old_ver: []const u8, new_ver: []const u8) void {1252    p("{s}updated  {s} {s}→{s} {s}\n", .{ hdr(), old_ver, c(DIM), c(RESET), new_ver });1253}12541255pub fn updateSelfNoPlatform(platform: []const u8) void {1256    p("{s}no pre-built binary for {s}\n", .{ hdr(), platform });1257    p("{s}check kepr.uk/nina/releases for available platforms\n", .{step()});1258}12591260pub fn updateSelfNetworkError() void {1261    p("{s}{s}\n", .{ if (color_enabled) WARN_C else WARN_P, "could not reach kepr.uk — check your connection" });1262}12631264pub fn updateSelfChecksumFailed() void {1265    p("{s}checksum mismatch — download may be corrupt\n", .{if (color_enabled) ERR_C else ERR_P});1266    p("{s}try again or download manually from kepr.uk/nina/releases\n", .{step()});1267}12681269pub fn updateSelfNixManaged(new_ver: []const u8) void {1270    p("{s}upgrading to {s}{s}{s} via nix profile\n", .{ step(), c(BOLD), new_ver, c(RESET) });1271}12721273pub fn updateSelfNixFailed() void {1274    p("{s}nix profile upgrade failed\n", .{if (color_enabled) ERR_C else ERR_P});1275    p("{s}try manually: nix profile upgrade '.*nina.*'\n", .{step()});1276}12771278// Reached when building the new version into the store fails, before the1279// profile has been touched at all — the old nina element is still installed1280// and working.1281pub fn updateSelfNixPrefetchFailed() void {1282    p("{s}could not build the new version — check your connection and try again\n", .{if (color_enabled) ERR_C else ERR_P});1283    p("{s}your current nina install is untouched\n", .{step()});1284}12851286// Reached only after `nix profile remove` already succeeded and the1287// re-add failed despite the new version having just been built into the1288// store — nina is genuinely uninstalled at this point, not just stuck on1289// the old version, so the recovery command must reinstall from scratch1290// rather than upgrade. Expected to be rare now that the build happens1291// before the profile is touched.1292pub fn updateSelfNixReinstallFailed() void {1293    p("{s}nix profile add failed — nina was removed and is not reinstalled\n", .{if (color_enabled) ERR_C else ERR_P});1294    p("{s}reinstall manually: nix profile add --no-write-lock-file 'https://kepr.uk/nina/archive/HEAD.tar.gz#nina'\n", .{step()});1295}12961297pub fn updateSelfNixRehash() void {1298    p("{s}run {s}hash -r{s} or open a new shell to use the updated binary\n", .{ step(), c(DIM), c(RESET) });1299}13001301// Reached when nina is in the store but not a `nix profile` element — i.e. it1302// was installed by the system config (NixOS module / systemPackages) or1303// home-manager. `nina update` (the profile self-updater) can't touch those;1304// pushing them at `nix profile add` would spawn a second, drifting install.1305pub fn updateSelfSystemManaged() void {1306    p("{s}nina is managed by your system configuration, not nina update\n", .{hdr()});1307    p("{s}update it where you manage that config:\n", .{step()});1308    p("      {s}nix flake update nina && sudo nixos-rebuild switch{s}\n", .{ c(DIM), c(RESET) });1309}13101311// --- Goodbye / uninstall ---13121313pub fn goodbyeStart() void {1314    p("{s}uninstalling nina\n", .{hdr()});1315}13161317pub fn goodbyeFile(path: []const u8) void {1318    p("{s}will remove {s}\n", .{ step(), path });1319}13201321pub fn goodbyeNix() void {1322    p("{s}will remove nina from nix profile\n", .{step()});1323    p("{s}command: nix profile remove nina\n", .{step()});1324}13251326pub fn goodbyeDone() void {1327    p("{s}goodbye! see kepr.uk/nina to reinstall\n", .{hdr()});1328}13291330pub fn goodbyeFailed(msg: []const u8) void {1331    p("{s}{s}\n", .{ if (color_enabled) ERR_C else ERR_P, msg });1332}13331334// --- Setup ---13351336pub fn setupCheck() void {1337    p("{s}checking nix features\n", .{hdr()});1338}13391340pub fn setupFeatures(nix_command: bool, flakes: bool) void {1341    p("{s}nix-command  {s}{s}{s}\n", .{1342        step(),1343        if (nix_command) c(GREEN) else "",1344        if (nix_command) "enabled" else "not enabled",1345        if (nix_command) c(RESET) else "",1346    });1347    p("{s}flakes       {s}{s}{s}\n", .{1348        step(),1349        if (flakes) c(GREEN) else "",1350        if (flakes) "enabled" else "not enabled",1351        if (flakes) c(RESET) else "",1352    });1353}13541355pub fn setupAllSet() void {1356    p("{s}all set\n", .{hdr()});1357}13581359// Printed once, before the first search, when the nixpkgs registry still points1360// at a remote URL. Flush so it lands before `nix registry pin` and any results.1361pub fn pinningRegistry() void {1362    p("{s}pinning nixpkgs for fast local search...\n", .{hdr()});1363    flush();1364}13651366// --- Plain (non-tty) search rendering ---1367// Color-gated equivalents of the raw-ANSI TUI widget, for piped/scripted search.1368// Using the gated header + c() keeps ANSI out of non-tty output (NO_COLOR / pipes).13691370pub fn searchPlainHeader(mode_str: []const u8, query: []const u8, count: u64) void {1371    p("{s}search {s} {s}  {s}{d} results{s}\n", .{ hdr(), mode_str, query, c(DIM), count, c(RESET) });1372}13731374pub fn searchPlainNoResults() void {1375    p("   no results\n", .{});1376}13771378pub fn searchPlainPackage(pname: []const u8, pkg_version: []const u8, description: []const u8, unfree: bool) void {1379    if (unfree) {1380        p("   {s}   {s}{s}{s}   {s}unfree{s}   {s}\n", .{ pname, c(CYAN), pkg_version, c(RESET), c(YELLOW), c(RESET), description });1381    } else {1382        p("   {s}   {s}{s}{s}   {s}\n", .{ pname, c(CYAN), pkg_version, c(RESET), description });1383    }1384}13851386pub fn searchPlainOption(name: []const u8, type_str: []const u8) void {1387    p("   {s}   {s}{s}{s}\n", .{ name, c(DIM), type_str, c(RESET) });1388}13891390pub fn searchEmptyQuery() void {1391    p("{s}search needs a query  {s}e.g. nina search firefox{s}\n", .{ hdr(), c(DIM), c(RESET) });1392}13931394pub fn setupEnabling() void {1395    p("{s}enabling experimental features\n", .{hdr()});1396}13971398pub fn setupDone(path: []const u8) void {1399    p("{s}wrote {s}\n", .{ step(), path });1400    p("{s}done  open a new shell to pick up the change\n", .{hdr()});1401}14021403// --- NixOS setup (declarative configuration.nix) ---14041405pub fn setupNixosOffer(features_line: []const u8, conf_path: []const u8) void {1406    p("{s}on NixOS these go in your system config\n", .{hdr()});1407    p("   nina can add this line to {s}{s}{s}:\n\n", .{ c(DIM), conf_path, c(RESET) });1408    p("       {s}{s}{s}\n\n", .{ c(CYAN), features_line, c(RESET) });1409}14101411pub fn setupNixosWrote(conf_path: []const u8) void {1412    p("{s}added the line to {s}  {s}(backup: {s}.nina-bak){s}\n", .{ step(), conf_path, c(DIM), conf_path, c(RESET) });1413    p("{s}now run {s}sudo nixos-rebuild switch{s} — then nina's ready\n", .{ hdr(), c(BOLD), c(RESET) });1414}14151416pub fn setupNixosManual(features_line: []const u8, conf_path: []const u8) void {1417    p("{s}no problem — add this line inside the {s}{{ }}{s} in {s}:\n\n", .{ hdr(), c(DIM), c(RESET), conf_path });1418    p("       {s}{s}{s}\n\n", .{ c(CYAN), features_line, c(RESET) });1419    p("   then run {s}sudo nixos-rebuild switch{s} — then nina's ready\n", .{ c(BOLD), c(RESET) });1420}14211422pub fn setupNixosNeedsRebuild(conf_path: []const u8) void {1423    p("{s}already declared in {s}\n", .{ hdr(), conf_path });1424    p("   just run {s}sudo nixos-rebuild switch{s} to activate it\n", .{ c(BOLD), c(RESET) });1425}14261427pub fn unpinDone(input: []const u8) void {1428    p("{s}unpinned {s}\n", .{ hdr(), input });1429}14301431pub fn pinDone(input: []const u8, rev: []const u8) void {1432    p("{s}pinned {s} -> {s}\n", .{ hdr(), input, rev });1433}14341435pub fn hashResult(hash: []const u8) void {1436    p("{s}\n", .{hash});1437}14381439pub fn fetchResult(hash: []const u8, url: []const u8) void {1440    _ = url;1441    p("{s}\n", .{hash});1442}14431444pub fn storeRepairStart() void {1445    p("{s}repairing store\n", .{hdr()});1446}14471448pub fn storeVerifyStart() void {1449    p("{s}verifying store\n", .{hdr()});1450}14511452pub fn storeOptimiseStart(machine: []const u8) void {1453    p("{s}optimising store  {s}\n", .{ hdr(), machine });1454    printSubstep("nix store optimise", .{});1455}14561457pub fn storeOptimiseDone() void {1458    p("{s}done\n", .{hdr()});1459}14601461pub fn storeGcDone(freed: []const u8) void {1462    p("{s}freed {s}\n", .{ hdr(), freed });1463}14641465pub fn storePath(path: []const u8) void {1466    p("{s}\n", .{path});1467}14681469pub fn pkgResult(key: []const u8, val: []const u8) void {1470    p("   {s:<16}  {s}\n", .{ key, val });1471}14721473pub fn channelDone() void {1474    p("{s}done\n", .{hdr()});1475}14761477pub fn flakeShowHeader(name: []const u8) void {1478    p("{s}{s}\n\n", .{ hdr(), name });1479}14801481pub fn flakeShowEntry(kind: []const u8, name: []const u8, desc: []const u8) void {1482    p("   {s:<12}  {s:<24}  {s}\n", .{ kind, name, desc });1483}14841485// --- Home Manager ---14861487pub fn homeNotInstalled() void {1488    p("{s}home manager not detected  {s}nothing to do{s}\n", .{ hdr(), c(DIM), c(RESET) });1489}14901491// HM is a NixOS/flake module — rebuilt by nixos-rebuild, not the standalone CLI.1492pub fn homeModuleManaged() void {1493    p("{s}home manager is managed by your system config\n", .{hdr()});1494    p("   {s}-> run {s}nina apply{s}{s} to rebuild both together{s}\n", .{ c(CYAN), c(BOLD), c(RESET), c(CYAN), c(RESET) });1495}14961497pub fn homeApplyStart(machine: []const u8) void {1498    p("{s}{s}applying home config  {s}\n", .{ KAO_COZY, hdr(), machine });1499}15001501pub fn homeApplyDone(gen: u32, elapsed_ms: u64) void {1502    const secs = @as(f64, @floatFromInt(elapsed_ms)) / 1000.0;1503    // gen 0 means the post-switch generation re-read failed — the switch itself1504    // succeeded, so report success without a misleading "generation 0".1505    if (gen == 0) {1506        if (elapsed_ms >= 1000) {1507            p("{s}done  {s}[{d:.1}s]{s}\n", .{ hdr(), c(DIM), secs, c(RESET) });1508        } else {1509            p("{s}done\n", .{hdr()});1510        }1511        return;1512    }1513    if (elapsed_ms >= 1000) {1514        p("{s}generation {s}{d}{s}  {s}[{d:.1}s]{s}\n", .{ hdr(), c(BOLD), gen, c(RESET), c(DIM), secs, c(RESET) });1515    } else {1516        p("{s}generation {s}{d}{s}\n", .{ hdr(), c(BOLD), gen, c(RESET) });1517    }1518}15191520// `home` was invoked against a remote machine. Detection + flake-ref are1521// local-only, so we don't act on a remote — point the user at the local run.1522pub fn homeLocalOnly(machine: []const u8) void {1523    p("{s}home manager commands run on the local machine only\n", .{hdr()});1524    p("   {s}-> '{s}' is remote; run nina home on that machine directly{s}\n", .{ c(DIM), machine, c(RESET) });1525}15261527pub fn homeApplyDry(machine: []const u8) void {1528    p("{s}home dry run  {s}\n", .{ hdr(), machine });1529}15301531pub fn homeApplyDryDone() void {1532    p("{s}{s}ok{s}  no changes applied\n", .{ hdr(), c(GREEN), c(RESET) });1533}15341535pub fn homeBackStart(machine: []const u8, from: u32, to: u32) void {1536    p("{s}rolling back home config  {s}  gen {d} -> gen {d}\n", .{ hdr(), machine, from, to });1537}15381539pub fn homeBackDone(n: u32) void {1540    p("{s}{s}done  gen {s}{d}{s}\n", .{ KAO_GENTLE, hdr(), c(BOLD), n, c(RESET) });1541}15421543pub fn homeHistoryHeader(machine: []const u8) void {1544    p("{s}home generations  {s}\n\n", .{ hdr(), machine });1545}15461547pub fn homeHistoryRow(number: u32, date: []const u8, time: []const u8, current: bool) void {1548    if (current) {1549        p("   {s}{d}{s}   {s}   {s}   {s}current{s}\n", .{ c(BOLD), number, c(RESET), date, time, c(BOLD), c(RESET) });1550    } else {1551        p("   {s}{d}   {s}   {s}{s}\n", .{ c(DIM), number, date, time, c(RESET) });1552    }1553}15541555pub fn homeEditOpen(path: []const u8, editor: []const u8) void {1556    p("{s}opening {s}\n", .{ hdr(), path });1557    printSubstep("{s}", .{editor});1558}15591560pub fn homeCheckStart(machine: []const u8) void {1561    p("{s}checking home config  {s}\n", .{ hdr(), machine });1562}15631564pub fn homeCheckOk() void {1565    p("{s}{s}ok{s}\n", .{ hdr(), c(GREEN), c(RESET) });1566}15671568pub fn homeDiffHeader(a: u32, b: u32, machine: []const u8) void {1569    p("{s}home gen {d} -> gen {d}  {s}\n\n", .{ hdr(), a, b, machine });1570}15711572pub fn homeNothingToDiff() void {1573    p("{s}only one home generation — nothing to diff yet\n", .{hdr()});1574}15751576pub fn homePackagesHeader(machine: []const u8) void {1577    p("{s}home packages  {s}\n\n", .{ hdr(), machine });1578}15791580// A flake attribute wasn't defined — note it (dim) before trying the next, less1581// specific candidate in the home-apply fallback chain.1582pub fn homeAttrFallback(ref: []const u8) void {1583    p("   {s}{s} not defined — trying next{s}\n", .{ c(DIM), ref, c(RESET) });1584}15851586pub fn homeInitStart(switch_on_init: bool, dir: ?[]const u8) void {1587    const target = dir orelse "~/.config/home-manager";1588    if (switch_on_init) {1589        p("{s}{s}setting up home manager  {s}{s}{s}\n", .{ KAO_COZY, hdr(), c(PINK), target, c(RESET) });1590        p("   {s}-> will activate after init{s}\n", .{ c(DIM), c(RESET) });1591    } else {1592        p("{s}initialising home manager  {s}{s}{s}\n", .{ hdr(), c(PINK), target, c(RESET) });1593        p("   {s}-> edit home.nix then run {s}nina home apply{s}\n", .{ c(DIM), c(BOLD), c(RESET) });1594    }1595}15961597pub fn homeInitDone(switch_on_init: bool) void {1598    if (switch_on_init) {1599        p("{s}{s}home manager ready\n", .{ KAO_GENTLE, hdr() });1600    } else {1601        p("{s}done  edit home.nix and run {s}nina home apply{s} when ready\n", .{ hdr(), c(BOLD), c(RESET) });1602    }1603}16041605// `home init` against a config that already exists — never overwrite; point at1606// apply instead.1607pub fn homeInitExists(path: []const u8) void {1608    p("{s}home manager config already exists\n", .{if (color_enabled) WARN_C else WARN_P});1609    p("   {s}{s}{s}\n", .{ c(DIM), path, c(RESET) });1610    p("   {s}-> run {s}nina home apply{s}{s} to activate it{s}\n", .{ c(CYAN), c(BOLD), c(RESET), c(CYAN), c(RESET) });1611}16121613// --- First-run wizard ---16141615pub fn firstRunBanner() void {1616    p("{s}{s}nina \u{2014} first run\n\n", .{ KAO_FACE, hdr() });1617}16181619pub fn firstRunNoConfig() void {1620    p("   no config found. let me get set up.\n\n", .{});1621}16221623// Print a prompt line and read the user's answer. Returns the default if the1624// user presses Enter without typing anything. buf must be at least 256 bytes.1625// Returns a slice into buf (or default if empty input).1626pub fn firstRunPrompt(label: []const u8, default: []const u8, buf: []u8) []const u8 {1627    p("   {s:<14} {s}> {s}", .{ label, c(DIM), c(RESET) });1628    flush();1629    var i: usize = 0;1630    while (i < buf.len - 1) {1631        const n = std.posix.read(std.posix.STDIN_FILENO, buf[i .. i + 1]) catch break;1632        if (n == 0) break;1633        if (buf[i] == '\n') break;1634        i += 1;1635    }1636    const input = std.mem.trim(u8, buf[0..i], " \t\r");1637    if (input.len == 0) {1638        // Echo the default so the output shows what was chosen1639        p("{s}{s}{s}\n", .{ c(DIM), default, c(RESET) });1640        flush();1641        return default;1642    }1643    return input;1644}16451646pub fn firstRunScanning() void {1647    p("\n   {s}:: scanning for config...{s}\n", .{ c(DIM), c(RESET) });1648}16491650// Report what the scan found at /etc/nixos, noting flake vs channel.1651pub fn firstRunDetected(path: []const u8, is_flake: bool) void {1652    const kind = if (is_flake) "flake-based system" else "channel-based system";1653    p("   {s}-> found {s}{s}   {s}({s}){s}\n\n", .{ c(CYAN), path, c(RESET), c(DIM), kind, c(RESET) });1654}16551656pub fn firstRunNoneFound() void {1657    p("   {s}-> nothing found at /etc/nixos{s}\n\n", .{ c(DIM), c(RESET) });1658}16591660// Prompt with a pre-filled default shown in brackets. Empty input accepts the1661// default. When `detected` and a default is present, note that enter confirms.1662pub fn firstRunPromptDefault(label: []const u8, default: []const u8, detected: bool, buf: []u8) []const u8 {1663    if (default.len > 0) {1664        p("   {s:<14} {s}[{s}]{s} > ", .{ label, c(DIM), default, c(RESET) });1665        if (detected) p("{s}enter to confirm{s} ", .{ c(DIM), c(RESET) });1666    } else {1667        p("   {s:<14} {s}> {s}", .{ label, c(DIM), c(RESET) });1668    }1669    flush();1670    var i: usize = 0;1671    while (i < buf.len - 1) {1672        const n = std.posix.read(std.posix.STDIN_FILENO, buf[i .. i + 1]) catch break;1673        if (n == 0) break;1674        if (buf[i] == '\n') break;1675        i += 1;1676    }1677    const input = std.mem.trim(u8, buf[0..i], " \t\r");1678    if (input.len == 0) {1679        p("{s}{s}{s}\n", .{ c(DIM), default, c(RESET) });1680        flush();1681        return default;1682    }1683    return input;1684}16851686// Shown before channel operations on a flake-managed system, where nix-channel1687// commands generally don't apply.1688pub fn flakeChannelNote() void {1689    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) });1690}16911692pub fn firstRunWritten(path: []const u8) void {1693    p("\n   {s}written to {s}{s}\n\n", .{ c(DIM), path, c(RESET) });1694}16951696pub fn firstRunSkipped() void {1697    p("\n   {s}skipping setup in non-interactive mode{s}\n", .{ c(DIM), c(RESET) });1698}