output.zig

53.5 KB · raw

1// output.zig — the only file that writes to stdout2// All ANSI codes live here. No raw escape sequences elsewhere.3const std = @import("std");4const types = @import("types.zig");5const nina_version = @import("version.zig");6const errors = @import("errors.zig");7const Io = std.Io;89// Color constants — all ANSI codes live here only10const PINK = "\x1b[38;2;255;183;197m";11const BOLD = "\x1b[1m";12const GREEN = "\x1b[32m";13const YELLOW = "\x1b[33m";14const RED = "\x1b[31m";15const CYAN = "\x1b[36m";16const DIM = "\x1b[2m";17const RESET = "\x1b[0m";1819// kaomoji constants — all kaomoji defined here, never inlined elsewhere. Rare20// and earned: each marks one genuine moment and never repeats in one output21// block. They are plain text, not ANSI, so they survive pipes and NO_COLOR.22const KAO_FACE = "(˶ᵔ ᵕ ᵔ˶)  "; // hello — her face23const KAO_COZY = "(っ˘ω˘ς)  "; // apply start24const KAO_EXCITED = "╰(*°▽°*)╯  "; // apply success after a failure this session25const KAO_GENTLE = "( ˘ᵕ˘ )  "; // back done26const KAO_CONTENT = "( ´ ∀ ` )  "; // clean freed27const KAO_HAPPY = "( ´ ▽ ` )  "; // doctor all clear / mood all good28const KAO_SLEEPY = "(˘ω˘ )  "; // try / develop exit29const KAO_READY = "( •̀ᴗ•́ )  "; // update start30const KAO_SAD = "(;ω;)  "; // network or ssh errors only — never user typos3132// Exported for TUI use (search.zig references these to avoid \x1b in that file)33pub const C_PINK = PINK;34pub const C_BOLD = BOLD;35pub const C_GREEN = GREEN;36pub const C_YELLOW = YELLOW;37pub const C_RED = RED;38pub const C_CYAN = CYAN;39pub const C_DIM = DIM;40pub const C_RESET = RESET;41pub const C_CLEAR_EOL = "\x1b[K";42pub const C_CURSOR_UP_FMT = "\x1b[{d}A";4344// Precomputed prefix strings45const HDR_C = PINK ++ ":: " ++ RESET;46const HDR_P = ":: ";47const STEP_C = "   " ++ DIM ++ "-> " ++ RESET;48const STEP_P = "   -> ";49const TEACH_C = "   " ++ DIM ++ "= " ++ RESET;50const TEACH_P = "   = ";51const ERR_C = PINK ++ ":: " ++ RED ++ "error:" ++ RESET ++ " ";52const ERR_P = ":: error: ";53const WARN_C = PINK ++ ":: " ++ YELLOW ++ "warning:" ++ RESET ++ " ";54const WARN_P = ":: warning: ";5556var _fw: Io.File.Writer = undefined;57var _w: *Io.Writer = undefined;58var color_enabled: bool = true;59var teach_enabled: bool = false;6061// --- Build panel ---6263pub const BuildPanel = struct {64    total: u32 = 0,65    completed: u32 = 0,66    total_mb: f32 = 0,67    active: [32]u8 = [_]u8{0} ** 32,68    active_len: usize = 0,69    mode: enum { fetching, building, activating } = .fetching,70    pulse_pos: u8 = 0,7172    const BAR_WIDTH = 28;7374    pub fn update(self: *BuildPanel, line: []const u8) void {75        // "these N paths will be fetched (X MiB download, Y MiB unpacked)"76        if (std.mem.indexOf(u8, line, "paths will be fetched") != null) {77            if (parseAfterWord(line, "these ")) |n_str| {78                if (std.fmt.parseInt(u32, n_str, 10) catch null) |n| self.total = n;79            }80            // "(X MiB download..."81            if (std.mem.indexOfScalar(u8, line, '(')) |pi| {82                const after = std.mem.trim(u8, line[pi + 1 ..], " \t");83                if (indexOfSpace(after)) |sp| {84                    if (std.fmt.parseFloat(f32, after[0..sp]) catch null) |mb| self.total_mb = mb;85                }86            }87            return;88        }8990        // "copying path '/nix/store/...' from '...'" (nix 2.x substituter message)91        // older nix used "fetching path '...'" — match both for compatibility92        if (std.mem.indexOf(u8, line, "copying path '") != null or93            std.mem.indexOf(u8, line, "fetching path '") != null)94        {95            self.completed +|= 1;96            self.mode = .fetching;97            self.setActiveName(line, false);98            return;99        }100101        // "building '/nix/store/...-name.drv'"102        if (std.mem.indexOf(u8, line, "building '") != null and103            std.mem.indexOf(u8, line, ".drv") != null)104        {105            self.mode = .building;106            self.setActiveName(line, true);107            return;108        }109110        // "activating the configuration..."111        if (std.mem.indexOf(u8, line, "activating the configuration") != null or112            std.mem.indexOf(u8, line, "activating configuration") != null)113        {114            self.mode = .activating;115            if (self.total > 0) self.completed = self.total;116            const msg = "activating configuration...";117            const copy_len = @min(msg.len, self.active.len);118            @memcpy(self.active[0..copy_len], msg[0..copy_len]);119            self.active_len = copy_len;120            return;121        }122    }123124    pub fn render(self: *BuildPanel) void {125        if (!color_enabled) return;126127        // Up 2 lines to the name line (blank line is below header, name is next)128        p("\x1b[2A", .{});129130        // Name line131        p("\r\x1b[K", .{});132        const name = self.active[0..self.active_len];133        switch (self.mode) {134            .fetching => p("   {s}fetching{s}  {s}{s}{s}", .{ c(DIM), c(RESET), c(CYAN), name, c(RESET) }),135            .building => p("   {s}building{s}  {s}{s}{s}", .{ c(DIM), c(RESET), c(YELLOW), name, c(RESET) }),136            .activating => p("   {s}{s}{s}", .{ c(GREEN), name, c(RESET) }),137        }138        p("\n", .{});139140        // Bar line141        p("\r\x1b[K", .{});142        if (self.total == 0) {143            self.drawPulse();144        } else {145            self.drawCountedBar();146        }147        p("\n", .{});148149        flush();150    }151152    fn drawCountedBar(self: *BuildPanel) void {153        const filled: u32 = if (self.total > 0)154            @min(BAR_WIDTH, (self.completed * BAR_WIDTH) / self.total)155        else156            0;157        const empty: u32 = BAR_WIDTH - filled;158159        const blk_color = switch (self.mode) {160            .fetching => CYAN,161            .building => YELLOW,162            .activating => GREEN,163        };164165        p("   ", .{});166        if (filled > 0) {167            p("{s}", .{c(blk_color)});168            for (0..filled) |_| p("█", .{});169            p("{s}", .{c(RESET)});170        }171        if (empty > 0) {172            p("{s}", .{c(DIM)});173            for (0..empty) |_| p("░", .{});174            p("{s}", .{c(RESET)});175        }176        p("   {s}{d} / {d} paths{s}", .{ c(DIM), self.completed, self.total, c(RESET) });177        if (self.total_mb > 0) {178            const done_mb = self.total_mb * @as(f32, @floatFromInt(self.completed)) /179                @as(f32, @floatFromInt(@max(self.total, 1)));180            p("   {d:.1} MB / {d:.1} MB", .{ done_mb, self.total_mb });181        }182    }183184    fn drawPulse(self: *BuildPanel) void {185        const PULSE_SIZE: u8 = 4;186        const blk_color = switch (self.mode) {187            .fetching => CYAN,188            .building => YELLOW,189            .activating => GREEN,190        };191        p("   ", .{});192        for (0..BAR_WIDTH) |i| {193            const pos: u8 = @intCast(i);194            const in_pulse = pos >= self.pulse_pos and pos < self.pulse_pos + PULSE_SIZE;195            if (in_pulse) {196                p("{s}█{s}", .{ c(blk_color), c(RESET) });197            } else {198                p("{s}░{s}", .{ c(DIM), c(RESET) });199            }200        }201        self.pulse_pos = (self.pulse_pos + 1) % BAR_WIDTH;202    }203204    fn setActiveName(self: *BuildPanel, line: []const u8, is_drv: bool) void {205        const store = "/nix/store/";206        const idx = std.mem.indexOf(u8, line, store) orelse return;207        const after = line[idx + store.len ..];208        if (after.len < 33) return;209        var name = after[33..]; // skip 32-char hash + dash210        if (is_drv) {211            if (std.mem.endsWith(u8, name, ".drv")) name = name[0 .. name.len - 4];212        }213        // Trim trailing quote / whitespace214        name = std.mem.trimEnd(u8, name, "' \t\r\n");215        const copy_len = @min(name.len, self.active.len);216        @memcpy(self.active[0..copy_len], name[0..copy_len]);217        self.active_len = copy_len;218    }219};220221fn parseAfterWord(line: []const u8, word: []const u8) ?[]const u8 {222    const idx = std.mem.indexOf(u8, line, word) orelse return null;223    const after = line[idx + word.len ..];224    const end = indexOfSpace(after) orelse return null;225    return after[0..end];226}227228fn indexOfSpace(s: []const u8) ?usize {229    for (s, 0..) |b, i| if (b == ' ' or b == '\t') return i;230    return null;231}232233pub fn buildPanelInit() void {234    if (!color_enabled) return;235    p("\n\n\n", .{});236    flush();237}238239pub fn buildPanelClear() void {240    if (!color_enabled) return;241    p("\n", .{});242    flush();243}244245pub fn init(writer: *Io.Writer, io: std.Io, environ: *const std.process.Environ.Map, color_config: bool) void {246    _w = writer;247    color_enabled = color_config and248        (std.Io.File.stdout().isTty(io) catch false) and249        !environ.contains("NO_COLOR");250}251252pub fn setTeach(enabled: bool) void {253    teach_enabled = enabled;254}255256pub fn flush() void {257    _w.flush() catch {};258}259260// Whether ANSI color is active (tty + config + no NO_COLOR). Callers spawning261// child processes that colorize their own output use this to gate the child.262pub fn colorEnabled() bool {263    return color_enabled;264}265266fn c(code: []const u8) []const u8 {267    return if (color_enabled) code else "";268}269270fn hdr() []const u8 {271    return if (color_enabled) HDR_C else HDR_P;272}273274fn step() []const u8 {275    return if (color_enabled) STEP_C else STEP_P;276}277278fn teach_pfx() []const u8 {279    return if (color_enabled) TEACH_C else TEACH_P;280}281282// Raw write — used by TUI283pub fn raw(bytes: []const u8) void {284    _w.writeAll(bytes) catch {};285}286287// Formatted print — used by TUI for in-place rendering288pub fn p(comptime fmt: []const u8, args: anytype) void {289    _w.print(fmt, args) catch {};290}291292pub fn cursorUp(n: usize) void {293    if (n > 0) p("\x1b[{d}A", .{n});294}295296pub fn clearLine() void {297    p("\r\x1b[K", .{});298}299300// --- Error and warning output ---301302pub fn printError(message: []const u8, detail: ?[]const u8, suggestion: ?[]const u8) void {303    p("{s}{s}\n", .{ if (color_enabled) ERR_C else ERR_P, message });304    if (detail) |d| p("   {s}{s}{s}\n", .{ c(DIM), d, c(RESET) });305    // Actionable suggestion in cyan — the next step should catch the eye.306    if (suggestion) |s| p("   {s}-> {s}{s}\n", .{ c(CYAN), s, c(RESET) });307}308309// Like printError, but for genuine system failures (network/ssh/search). The sad310// kaomoji signals "this is on the machine, not on you" — never used for typos or311// not-found errors, which go through printError.312pub fn printSystemError(message: []const u8, detail: ?[]const u8, suggestion: ?[]const u8) void {313    p("{s}{s}{s}\n", .{ KAO_SAD, if (color_enabled) ERR_C else ERR_P, message });314    if (detail) |d| p("   {s}{s}{s}\n", .{ c(DIM), d, c(RESET) });315    if (suggestion) |s| p("   {s}-> {s}{s}\n", .{ c(CYAN), s, c(RESET) });316}317318pub fn printWarning(message: []const u8) void {319    p("{s}{s}\n", .{ if (color_enabled) WARN_C else WARN_P, message });320}321322// Display a translated build error through the 3-layer pipeline format.323// is_system = true  → (;ω;) kaomoji prefix (machine's fault, not the user's)324// suggestion may contain '\n'-separated lines; the first gets "-> " and the325// rest are indented with "   " so the secondary "nix log ..." line lines up.326pub fn buildError(err: errors.TranslatedError) void {327    if (err.is_system) {328        // KAO_SAD already includes trailing spaces: "(;ω;)  "329        p("{s}{s}{s}\n\n", .{ KAO_SAD, if (color_enabled) ERR_C else ERR_P, err.title });330    } else {331        p("{s}{s}\n\n", .{ if (color_enabled) ERR_C else ERR_P, err.title });332    }333334    var body_lines = std.mem.splitScalar(u8, err.body, '\n');335    while (body_lines.next()) |line| {336        if (line.len == 0) continue;337        p("   {s}\n", .{line});338    }339340    if (err.location) |loc| {341        p("{s}   {s}{s}\n", .{ c(DIM), loc, c(RESET) });342    }343344    p("\n", .{});345346    var sug_lines = std.mem.splitScalar(u8, err.suggestion, '\n');347    var first = true;348    while (sug_lines.next()) |line| {349        if (line.len == 0) continue;350        if (first) {351            p("{s}   -> {s}{s}\n", .{ c(CYAN), line, c(RESET) });352            first = false;353        } else {354            p("{s}   {s}{s}\n", .{ c(DIM), line, c(RESET) });355        }356    }357}358359// Display post-build warnings collected from captured stderr.360// Shown after the success line in dim yellow.361pub fn buildWarnings(warnings: []const []const u8) void {362    for (warnings) |w| {363        p("{s}   \u{26a0}  {s}{s}\n", .{ c(YELLOW), w, c(RESET) });364    }365}366367pub fn aborted() void {368    p("{s}aborted\n", .{hdr()});369}370371// One-time dim note when ~/.nina.conf is migrated to the XDG config path.372pub fn configMigrated(path: []const u8) void {373    p("{s}{s}config migrated to {s}{s}\n", .{ step(), c(DIM), path, c(RESET) });374}375376pub fn printTeach(cmd: []const u8) void {377    if (teach_enabled) p("{s}{s}{s}\n", .{ teach_pfx(), cmd, c(RESET) });378}379380pub fn printSubstep(comptime fmt: []const u8, args: anytype) void {381    p("{s}", .{step()});382    p(fmt, args);383    p("\n", .{});384}385386pub fn hookFailed(name: []const u8, code: u8, hook_output: []const u8) void {387    p("{s}{s} hook exited with code {d}{s}\n\n", .{ hdr(), name, code, c(RESET) });388389    if (hook_output.len > 0) {390        var lines = std.mem.splitScalar(u8, hook_output, '\n');391        var shown: [5][]const u8 = undefined;392        var count: usize = 0;393        while (lines.next()) |line| {394            const trimmed = std.mem.trim(u8, line, " \t\r");395            if (trimmed.len == 0) continue;396            shown[count % shown.len] = trimmed;397            count += 1;398        }399400        const display_count = @min(count, shown.len);401        const start = count - display_count;402        for (0..display_count) |i| {403            const line = shown[(start + i) % shown.len];404            p("   {s}{s}{s}\n", .{ c(DIM), line, c(RESET) });405        }406        p("\n", .{});407    }408}409410pub fn hookWarning(name: []const u8, code: u8, hook_output: []const u8) void {411    _ = hook_output;412    p("{s}   warning: {s} hook exited with code {d}{s}\n", .{ c(YELLOW), name, code, c(RESET) });413}414415// --- Confirmation prompt (returns true = yes) ---416417pub fn confirm(prompt: []const u8) bool {418    p("   {s}continue? [Y/n]  ", .{prompt});419    flush();420    var buf: [64]u8 = undefined;421    var i: usize = 0;422    while (i < buf.len) {423        const n = std.posix.read(std.posix.STDIN_FILENO, buf[i .. i + 1]) catch break;424        if (n == 0) break;425        if (buf[i] == '\n') break;426        i += 1;427    }428    const input = std.mem.trim(u8, buf[0..i], " \t");429    if (input.len == 0) return true;430    return input[0] != 'n' and input[0] != 'N';431}432433// Like confirm, but defaults to NO on an empty answer — for prompts that touch434// system files, where a stray Enter should never trigger the action.435pub fn confirmDefaultNo(question: []const u8) bool {436    p("   {s} [y/N]  ", .{question});437    flush();438    var buf: [64]u8 = undefined;439    var i: usize = 0;440    while (i < buf.len) {441        const n = std.posix.read(std.posix.STDIN_FILENO, buf[i .. i + 1]) catch break;442        if (n == 0) break;443        if (buf[i] == '\n') break;444        i += 1;445    }446    const input = std.mem.trim(u8, buf[0..i], " \t");447    if (input.len == 0) return false;448    return input[0] == 'y' or input[0] == 'Y';449}450451// --- Apply / rebuild ---452453pub fn applyStart(machine: []const u8) void {454    p("{s}{s}rebuilding {s}...\n", .{ KAO_COZY, hdr(), machine });455}456457// after_failure: true only when the previous apply this session failed and this458// one succeeded — the one moment that earns the excited kaomoji. Routine459// successes show no kaomoji.460pub fn applyDone(gen: u32, elapsed_ms: u64, after_failure: bool) void {461    const face = if (after_failure) KAO_EXCITED else "";462    const secs = @as(f64, @floatFromInt(elapsed_ms)) / 1000.0;463    if (elapsed_ms >= 1000) {464        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) });465    } else {466        p("{s}{s}generation {s}{d}{s}\n", .{ face, hdr(), c(BOLD), gen, c(RESET) });467    }468}469470pub fn applyFailed(translated: []const u8) void {471    p("{s}build failed\n", .{if (color_enabled) ERR_C else ERR_P});472    if (translated.len > 0) p("   {s}{s}{s}\n", .{ c(DIM), translated, c(RESET) });473    p("   {s}-> nina doctor{s}\n", .{ c(DIM), c(RESET) });474}475476pub fn applyDry(machine: []const u8) void {477    p("{s}dry run  {s}\n", .{ hdr(), machine });478}479480pub fn applyDryDone() void {481    p("{s}no changes applied\n", .{hdr()});482}483484// --- Check ---485486pub fn checkStart(machine: []const u8) void {487    p("{s}checking {s}...\n", .{ hdr(), machine });488}489490pub fn checkOk() void {491    p("{s}{s}ok{s}\n", .{ hdr(), c(GREEN), c(RESET) });492}493494pub fn checkFailed(msg: []const u8) void {495    p("{s}config invalid\n", .{if (color_enabled) ERR_C else ERR_P});496    if (msg.len > 0) p("   {s}{s}{s}\n", .{ c(DIM), msg, c(RESET) });497}498499// --- Back / go ---500501pub fn backStart(machine: []const u8, from: u32, to: u32) void {502    p("{s}rolling back  {s}  gen {d} -> gen {d}\n", .{ hdr(), machine, from, to });503}504505pub fn goStart(machine: []const u8, current: u32, target: u32) void {506    p("{s}switching  {s}  gen {d} -> gen {d}\n", .{ hdr(), machine, current, target });507}508509pub fn generationDone(n: u32) void {510    p("{s}done  gen {s}{d}{s}\n", .{ hdr(), c(BOLD), n, c(RESET) });511}512513// `back` has nothing older to roll back to. This is a clean stop, not a build514// failure — the rollback would otherwise surface nixos-rebuild's confusing515// 'no profile version older than the current' as a fake build error.516pub fn alreadyOldest() void {517    p("{s}already at the oldest generation\n", .{if (color_enabled) ERR_C else ERR_P});518}519520// Like generationDone but for `back` specifically — a successful rollback earns521// the gentle kaomoji. `go` keeps the plain generationDone line.522pub fn backDone(n: u32) void {523    p("{s}{s}done  gen {s}{d}{s}\n", .{ KAO_GENTLE, hdr(), c(BOLD), n, c(RESET) });524}525526// --- History ---527528pub fn historyHeader(machine: []const u8) void {529    p("{s}generations  {s}\n\n", .{ hdr(), machine });530}531532pub fn historyRow(gen: types.GenerationInfo) void {533    if (gen.current) {534        p("   {s}{d}{s}   {s}   {s}   {s}current{s}\n", .{ c(BOLD), gen.number, c(RESET), gen.date, gen.time, c(BOLD), c(RESET) });535    } else {536        p("   {s}{d}   {s}   {s}{s}\n", .{ c(DIM), gen.number, gen.date, gen.time, c(RESET) });537    }538}539540// --- Clean ---541542pub fn cleanStart(machine: []const u8, keep: u32, total: u32) void {543    p("{s}cleaning  {s}  keeping {d} of {d}\n", .{ hdr(), machine, keep, total });544}545546// Fewer generations than the keep limit — there's nothing to collect. Avoids the547// nonsensical 'keeping 5 of 1'.548pub fn cleanNothing(machine: []const u8, total: u32) void {549    p("{s}cleaning  {s}\n\n", .{ hdr(), machine });550    p("   only {d} generation{s} — nothing to remove.\n", .{ total, if (total == 1) "" else "s" });551}552553pub fn cleanDone() void {554    p("{s}{s}done\n", .{ KAO_CONTENT, hdr() });555}556557// --- Status ---558559pub fn statusHeader() void {560    p("{s}status\n\n", .{hdr()});561}562563pub fn statusRow(machine: []const u8, gen: u32, time: []const u8, size: []const u8, ok: bool) void {564    if (ok) {565        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) });566    } else {567        p("   {s}{s}   {s}unreachable{s}\n", .{ c(RED), machine, "", c(RESET) });568    }569}570571// Dim Home Manager generation line, indented under the machine row. Only shown572// when standalone HM is detected; absent otherwise so the layout is unchanged.573pub fn statusHomeRow(gen: u32, detail: []const u8) void {574    if (detail.len > 0) {575        p("   {s}         hm  gen {d}   {s}{s}\n", .{ c(DIM), gen, detail, c(RESET) });576    } else {577        p("   {s}         hm  gen {d}{s}\n", .{ c(DIM), gen, c(RESET) });578    }579}580581// --- Diff ---582583pub fn diffHeader(a: u32, b: u32, machine: []const u8) void {584    p("{s}gen {d} -> gen {d}  {s}\n\n", .{ hdr(), a, b, machine });585}586587// Reached when no generation is marked current (non-standard profile layout,588// a transient readlink failure, or a non-GNU remote host) or there are too589// few generations to infer a pair — nothing safe to diff against.590pub fn diffCannotDetermine() void {591    p("{s}cannot determine current generation — nothing to diff\n", .{if (color_enabled) WARN_C else WARN_P});592}593594pub fn diffRow(entry: types.DiffEntry) void {595    switch (entry.op) {596        .add => p("   {s}+{s} {s}   {s}\n", .{ c(GREEN), c(RESET), entry.package, entry.new_version orelse "" }),597        .remove => p("   {s}-{s} {s}   {s}\n", .{ c(RED), c(RESET), entry.package, entry.old_version orelse "" }),598        .change => p("   {s}^{s} {s}   {s} -> {s}\n", .{ c(CYAN), c(RESET), entry.package, entry.old_version orelse "", entry.new_version orelse "" }),599    }600}601602// --- Doctor ---603604pub fn doctorHeader(machine: []const u8) void {605    p("{s}diagnosing  {s}\n\n", .{ hdr(), machine });606}607608pub fn doctorRow(check: types.DoctorCheck) void {609    const status_str = switch (check.status) {610        .ok => if (color_enabled) GREEN ++ "ok" ++ RESET else "ok",611        .warn => if (color_enabled) YELLOW ++ "warn" ++ RESET else "warn",612        .fail => if (color_enabled) RED ++ "fail" ++ RESET else "fail",613    };614    const note_str = check.note orelse "";615    p("   {s:<16}  {s}   {s}\n", .{ check.name, status_str, note_str });616}617618pub fn doctorSummary(warnings: u32, failures: u32) void {619    if (failures > 0) {620        p("{s}{d} problems\n", .{ hdr(), failures });621    } else if (warnings > 0) {622        p("{s}{d} warnings\n", .{ hdr(), warnings });623    } else {624        p("{s}{s}{s}all good{s}\n", .{ KAO_HAPPY, hdr(), c(GREEN), c(RESET) });625    }626}627628// --- Update ---629630pub fn updateStart(machine: []const u8) void {631    p("{s}updating channels  {s}\n\n", .{ hdr(), machine });632}633634pub fn updateChannel(name: []const u8, old: ?[]const u8, new: ?[]const u8) void {635    if (old != null and new != null and !std.mem.eql(u8, old.?, new.?)) {636        p("   {s}   {s} -> {s}\n", .{ name, old.?, new.? });637    } else {638        p("   {s}   {s}no change{s}\n", .{ name, c(DIM), c(RESET) });639    }640}641642pub fn updateDone() void {643    p("\n{s}done\n", .{hdr()});644}645646// --- Upgrade ---647648pub fn upgradeStart(machine: []const u8) void {649    p("{s}upgrading  {s}\n", .{ hdr(), machine });650}651652// --- Log ---653654pub fn logHeader(machine: []const u8) void {655    p("{s}history  {s}\n\n", .{ hdr(), machine });656}657658pub fn logRow(date: []const u8, time: []const u8, action: []const u8, detail: []const u8) void {659    p("   {s}{s}  {s}{s}   {s:<16}  {s}\n", .{ c(DIM), date, time, c(RESET), action, detail });660}661662// --- Edit ---663664pub fn editOpen(path: []const u8, editor: []const u8) void {665    p("{s}opening {s}\n", .{ hdr(), path });666    printSubstep("{s}", .{editor});667    p("\n   {s}run nina check to validate before applying{s}\n", .{ c(DIM), c(RESET) });668}669670// `nina edit hardware` is a mistake: hardware-configuration.nix is generated by671// nixos-generate-config and warns against hand-editing. Refuse and redirect.672pub fn editHardwareWarning() void {673    p("\n   {s}warning: hardware-configuration.nix is auto-generated — do not edit directly{s}\n", .{ c(YELLOW), c(RESET) });674    p("   {s}-> make hardware changes in configuration.nix instead{s}\n", .{ c(CYAN), c(RESET) });675}676677// --- Fmt ---678679pub fn fmtStart(path: []const u8) void {680    p("{s}formatting  {s}\n", .{ hdr(), path });681}682683pub fn fmtDone() void {684    p("{s}done\n", .{hdr()});685}686687pub fn fmtNeedsFormat() void {688    p("{s}needs formatting  {s}run nina fmt to fix{s}\n", .{ hdr(), c(DIM), c(RESET) });689}690691// --- Repl ---692693pub fn replStart() void {694    p("{s}nix repl  {s}nixpkgs loaded{s}  :q to exit\n", .{ hdr(), c(DIM), c(RESET) });695}696697// --- Develop ---698699pub fn developStart(pkgs: []const []const u8) void {700    p("{s}entering dev shell\n\n   ", .{hdr()});701    for (pkgs, 0..) |pkg, i| {702        if (i > 0) p("  ", .{});703        p("{s}", .{pkg});704    }705    p("\n\n   {s}-> press Ctrl+C or type 'exit' to return{s}\n\n", .{ c(DIM), c(RESET) });706}707708pub fn developDone() void {709    p("{s}{s}back\n", .{ KAO_SLEEPY, hdr() });710}711712// --- Info ---713714pub fn infoHeader(machine: []const u8) void {715    p("{s}{s}\n\n", .{ hdr(), machine });716}717718pub fn infoRow(key: []const u8, val: []const u8) void {719    p("   {s:<12}  {s}\n", .{ key, val });720}721722// --- Boot ---723724pub fn bootHeader(machine: []const u8) void {725    p("{s}boot entries  {s}\n\n", .{ hdr(), machine });726}727728pub fn bootEntry(entry: types.BootEntry, idx: usize) void {729    if (entry.current) {730        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) });731    } else {732        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) });733    }734    _ = idx;735}736737// --- Service ---738739pub fn serviceListHeader(machine: []const u8) void {740    p("{s}services  {s}\n\n", .{ hdr(), machine });741}742743pub fn serviceRow(svc: types.ServiceInfo) void {744    const state_str = switch (svc.state) {745        .active => if (color_enabled) GREEN ++ "active" ++ RESET else "active",746        .failed => if (color_enabled) RED ++ "failed" ++ RESET else "failed",747        .inactive => "inactive",748        .unknown => "unknown",749    };750    const uptime = svc.uptime orelse "";751    p("   {s:<24}  {s:<14}  {s}\n", .{ svc.name, state_str, uptime });752}753754pub fn serviceVerb(verb: []const u8, name: []const u8, machine: []const u8) void {755    p("{s}{s} {s}  {s}\n", .{ hdr(), verb, name, machine });756}757758pub fn serviceDone() void {759    p("{s}done\n", .{hdr()});760}761762pub fn serviceLogsHeader(name: []const u8, n: u32, machine: []const u8) void {763    p("{s}{s}  last {d} lines  {s}\n\n", .{ hdr(), name, n, machine });764}765766// --- Store ---767768pub fn storeInfo(info: types.StoreInfo) void {769    p("{s}store\n\n", .{hdr()});770    p("   {s:<16}  {s}\n", .{ "total", info.total_size });771    p("   {s:<16}  {d} paths\n", .{ "live", info.live_paths });772    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) });773}774775// --- Channel ---776777pub fn channelListHeader(machine: []const u8) void {778    p("{s}channels  {s}\n\n", .{ hdr(), machine });779}780781pub fn channelRow(ch: types.ChannelInfo) void {782    p("   {s:<16}  {s}\n", .{ ch.name, ch.url });783}784785// --- Flake ---786787pub fn flakeUpdateStart() void {788    p("{s}updating inputs\n\n", .{hdr()});789}790791pub fn flakeInput(input: types.FlakeInput) void {792    if (input.changed) {793        const old = if (input.old_rev) |r| r[0..@min(7, r.len)] else "?";794        const new = if (input.new_rev) |r| r[0..@min(7, r.len)] else "?";795        p("   {s:<20}  {s} -> {s}\n", .{ input.name, old, new });796    } else {797        p("   {s:<20}  {s}no change{s}\n", .{ input.name, c(DIM), c(RESET) });798    }799}800801pub fn flakeLockWritten() void {802    p("\n{s}flake.lock written\n", .{hdr()});803}804805pub fn flakeValid() void {806    p("{s}{s}valid{s}\n", .{ hdr(), c(GREEN), c(RESET) });807}808809pub fn flakeCheckStart() void {810    p("{s}checking flake\n", .{hdr()});811}812813// --- Profile ---814815pub fn profileListHeader() void {816    p("{s}profile packages\n\n", .{hdr()});817}818819pub fn profileRow(attr: []const u8, pkg_version: []const u8, description: []const u8) void {820    p("   {s:<24}  {s:<12}  {s}\n", .{ attr, pkg_version, description });821}822823// --- Install / Remove / Try ---824825// Typo help for install: the query matched nothing, so suggest the closest real826// package name (pink) and let the caller confirm.827pub fn didYouMean(query: []const u8, suggestion: []const u8) void {828    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) });829}830831pub fn installStart(pkg: []const u8, path: types.InstallPath) void {832    const path_str = switch (path) {833        .profile => "profile",834        .system => "system",835    };836    p("{s}installing {s}{s}{s}  {s}\n", .{ hdr(), c(PINK), pkg, c(RESET), path_str });837}838839pub fn installDone(pkg: []const u8) void {840    p("{s}{s}{s}{s} installed  {s}available now{s}\n", .{ hdr(), c(PINK), pkg, c(RESET), c(DIM), c(RESET) });841}842843pub fn removeStart(pkg: []const u8) void {844    p("{s}removing {s}{s}{s}\n", .{ hdr(), c(PINK), pkg, c(RESET) });845}846847// Plain-language health summary. No kaomoji, no hearts — just the facts.848pub fn mood(machine: []const u8, state: []const u8, gen: u32, age: []const u8, size: []const u8) void {849    const healthy = std.mem.eql(u8, state, "running");850    const verdict = if (healthy) "all good" else state;851    const color = if (healthy) GREEN else YELLOW;852    const face = if (healthy) KAO_HAPPY else "";853    p("{s}{s}{s}  {s}{s}{s}\n", .{ face, hdr(), machine, c(color), verdict, c(RESET) });854    if (age.len > 0 or size.len > 0) {855        p("   generation {d}, last applied {s}, {s} system closure\n", .{ gen, age, size });856    } else {857        p("   generation {d}\n", .{gen});858    }859}860861pub fn installEditorPrompt(pkg: []const u8, config_path: []const u8, line: u32, editor: []const u8) void {862    p("{s}opening {s}  add {s}{s}{s} to systemPackages\n", .{ hdr(), config_path, c(PINK), pkg, c(RESET) });863    const cmd = std.fmt.allocPrint(std.heap.page_allocator, "{s} {s} +{d}", .{ editor, config_path, line }) catch editor;864    printSubstep("{s}", .{cmd});865    p("\n   {s}save and close when done{s}\n\n", .{ c(DIM), c(RESET) });866}867868pub fn installSelectPrompt(pkg: []const u8, pkg_version: []const u8) void {869    p("{s}{s}{s}{s}  {s}\n\n", .{ hdr(), c(PINK), pkg, c(RESET), pkg_version });870    p("   [i] profile install    {s}instant  no rebuild{s}\n", .{ c(DIM), c(RESET) });871    p("   [s] system install     {s}opens editor  requires apply{s}\n", .{ c(DIM), c(RESET) });872    p("   [t] try now            {s}exits when done{s}\n\n", .{ c(DIM), c(RESET) });873    p("   > ", .{});874    flush();875}876877pub fn tryStart(pkg: []const u8) void {878    p("{s}trying {s}{s}{s}  exit when done\n", .{ hdr(), c(PINK), pkg, c(RESET) });879}880881pub fn tryExitHint() void {882    p("   {s}-> press Ctrl+C or type 'exit' to return{s}\n", .{ c(DIM), c(RESET) });883}884885pub fn tryDone() void {886    p("{s}{s}back\n", .{ KAO_SLEEPY, hdr() });887}888889// --- List ---890891pub fn listHeader(machine: []const u8) void {892    p("{s}packages  {s}\n\n", .{ hdr(), machine });893}894895pub fn listSection(title: []const u8) void {896    p("   {s}{s}{s}\n", .{ c(DIM), title, c(RESET) });897}898899// Padded name so the version column lines up into a clean two-column table.900pub fn listPkg(name: []const u8, pkg_version: []const u8) void {901    p("   {s}{s:<16}{s}  {s}{s}{s}\n", .{ c(PINK), name, c(RESET), c(DIM), pkg_version, c(RESET) });902}903904pub fn blankLine() void {905    p("\n", .{});906}907908// --- Hello ---909910pub fn hello(machines: []const types.Machine) void {911    p("{s}{s}nina\n\n", .{ KAO_FACE, hdr() });912    for (machines) |m| {913        const kind = if (m.local) "local" else "ssh";914        const detail = if (m.local) "default" else m.host orelse "";915        p("   {s}{s}{s}   {s}   {s}\n", .{ c(DIM), m.name, c(RESET), kind, detail });916    }917    p("\n", .{});918    const quick = [_][2][]const u8{919        .{ "apply", "rebuild and switch" },920        .{ "search <q>", "find packages" },921        .{ "install <pkg>", "add to profile or system" },922        .{ "status", "machine health" },923        .{ "back", "roll back one generation" },924        .{ "home apply", "apply home config" },925        .{ "home back", "roll back home config" },926        .{ "home history", "list home generations" },927        .{ "home check", "validate home config" },928        .{ "home diff", "compare home generations" },929        .{ "home packages", "list managed packages" },930    };931    for (quick) |cmd| {932        p("   {s:<16}  {s}{s}{s}\n", .{ cmd[0], c(DIM), cmd[1], c(RESET) });933    }934    p("\n", .{});935}936937// --- Help ---938939pub fn help() void {940    p("{s}nina  {s}NixOS Intuitive Navigation Assistant by Asha Software{s}\n\n", .{ hdr(), c(DIM), c(RESET) });941    const cmds = [_][2][]const u8{942        .{ "apply", "rebuild and switch" },943        .{ "back", "roll back one generation" },944        .{ "go <n>", "switch to generation n" },945        .{ "history", "list all generations" },946        .{ "clean", "remove old generations" },947        .{ "search <q>", "find packages" },948        .{ "install <pkg>", "add to profile or system" },949        .{ "remove <pkg>", "remove from profile or system" },950        .{ "try <pkg>", "test without installing" },951        .{ "list", "show installed packages" },952        .{ "edit", "open configuration.nix" },953        .{ "edit --dir", "open config directory" },954        .{ "check", "validate config" },955        .{ "diff", "changes between generations" },956        .{ "status", "machine health" },957        .{ "update", "refresh channels" },958        .{ "upgrade", "update and rebuild" },959        .{ "log", "operation history" },960        .{ "doctor", "diagnose issues" },961        .{ "mood", "plain-language health" },962        .{ "develop", "enter dev shell" },963        .{ "flake", "flake management" },964        .{ "build", "build a package" },965        .{ "run", "run without installing" },966        .{ "service", "manage services" },967        .{ "store", "nix store tools" },968        .{ "channel", "manage channels" },969        .{ "profile", "user profile packages" },970        .{ "home", "home manager commands (apply/back/history/edit/check/diff/packages)" },971        .{ "info", "system information" },972        .{ "boot", "boot entries" },973        .{ "fmt", "format configuration.nix" },974        .{ "repl", "nix repl with nixpkgs" },975        .{ "option <q>", "search nixos options" },976        .{ "pkg", "inspect packages" },977        .{ "why <pkg>", "what pulled a package in" },978        .{ "pin", "pin flake inputs" },979        .{ "hash", "compute nix hash" },980        .{ "fetch", "fetch and hash a url" },981        .{ "goodbye", "uninstall nina" },982        .{ "hello", "list machines" },983        .{ "man [topic]", "open the built-in manual pager" },984        .{ "help", "this message" },985    };986    for (cmds) |cmd| {987        p("   {s:<18}  {s}{s}{s}\n", .{ cmd[0], c(DIM), cmd[1], c(RESET) });988    }989    p("\n   {s}flags: --on <machine>  --dry  --check  --no-apply  --last <n>  --all  --json  --version{s}\n", .{ c(DIM), c(RESET) });990}991992// Render a grouped command's subcommand list, shown when the group is invoked993// with no subcommand or an explicit `help`. Rows are {invocation, description}.994pub fn subcommandHelp(group: []const u8, rows: []const [2][]const u8, footer: ?[]const u8) void {995    p("{s}{s} subcommands\n\n", .{ hdr(), group });996    for (rows) |row| {997        p("   {s:<16}  {s}{s}{s}\n", .{ row[0], c(DIM), row[1], c(RESET) });998    }999    if (footer) |f| p("\n   {s}{s}{s}\n", .{ c(DIM), f, c(RESET) });1000    p("\n   nina {s} help  {s}for this message{s}\n", .{ group, c(DIM), c(RESET) });1001}10021003pub fn version() void {1004    p("{s}nina  v{s}  zig 0.16  zero dependencies\n", .{ hdr(), nina_version.VERSION });1005}10061007// --- Search (text output before TUI) ---10081009pub fn searchResult(pkg: types.NixPackage) void {1010    p("   {s}{s}{s}   {s}{s}{s}   {s}\n", .{ c(PINK), pkg.pname, c(RESET), c(DIM), pkg.version, c(RESET), pkg.description });1011}10121013pub fn searchHeader(query: []const u8, count: usize) void {1014    p("{s}search nixpkgs {s}  {s}{d} results{s}\n\n", .{ hdr(), query, c(DIM), count, c(RESET) });1015}10161017// --- Gen commands ---10181019pub fn genCurrent(n: u32) void {1020    p("{d}\n", .{n});1021}10221023pub fn done() void {1024    p("{s}done\n", .{hdr()});1025}10261027pub fn runStart(pkg: []const u8) void {1028    p("{s}running {s}{s}{s}\n", .{ hdr(), c(PINK), pkg, c(RESET) });1029}10301031pub fn buildStart(attr: []const u8) void {1032    p("{s}building {s}\n", .{ hdr(), attr });1033}10341035pub fn buildDone() void {1036    p("{s}done\n", .{hdr()});1037}10381039// --- Self-update (nina update) ---10401041pub fn updateSelfStart() void {1042    p("{s}{s}checking for updates\n", .{ KAO_READY, hdr() });1043}10441045pub fn updateSelfCurrent(ver: []const u8) void {1046    p("{s}{s}nina {s} is up to date{s}\n", .{ hdr(), c(GREEN), ver, c(RESET) });1047}10481049pub fn updateSelfAvailable(current: []const u8, latest: []const u8) void {1050    p("{s}update available\n", .{hdr()});1051    p("{s}current  {s}{s}{s}\n", .{ step(), c(DIM), current, c(RESET) });1052    p("{s}latest   {s}{s}{s}{s}\n", .{ step(), c(BOLD), c(GREEN), latest, c(RESET) });1053}10541055fn releaseNotesHeading(line: []const u8) []const u8 {1056    var i: usize = 0;1057    while (i < line.len and line[i] == '#') : (i += 1) {}1058    return std.mem.trim(u8, line[i..], " \t");1059}10601061fn releaseNotesBullet(line: []const u8) ?[]const u8 {1062    if (line.len < 2) return null;1063    const marker = line[0];1064    if ((marker == '-' or marker == '*' or marker == '+') and line[1] == ' ') return line[2..];1065    if (std.ascii.isDigit(marker)) {1066        var i: usize = 1;1067        while (i < line.len and std.ascii.isDigit(line[i])) : (i += 1) {}1068        if (i + 1 < line.len and line[i] == '.' and line[i + 1] == ' ') return line[i + 2 ..];1069    }1070    return null;1071}10721073pub fn updateSelfReleaseNotes(notes: []const u8) void {1074    const trimmed = std.mem.trim(u8, notes, " \t\r\n");1075    if (trimmed.len == 0) return;10761077    p("{s}changelog\n", .{hdr()});1078    var lines = std.mem.splitScalar(u8, trimmed, '\n');1079    while (lines.next()) |raw_line| {1080        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;1081        const text = std.mem.trim(u8, line, " \t");1082        if (text.len == 0) {1083            p("\n", .{});1084            continue;1085        }1086        if (text[0] == '#') {1087            const title = releaseNotesHeading(text);1088            if (title.len == 0) continue;1089            p("   {s}{s}{s}{s}\n", .{ c(BOLD), c(CYAN), title, c(RESET) });1090            continue;1091        }1092        if (releaseNotesBullet(text)) |item| {1093            p("   {s}- {s}{s}\n", .{ c(CYAN), item, c(RESET) });1094            continue;1095        }1096        p("   {s}\n", .{text});1097    }1098}10991100pub fn updateSelfDownloading(ver: []const u8, platform: []const u8) void {1101    p("{s}downloading nina {s} for {s}\n", .{ step(), ver, platform });1102}11031104pub fn updateSelfVerifying() void {1105    p("{s}verifying checksum\n", .{step()});1106}11071108pub fn updateSelfInstalling(install_path: []const u8) void {1109    p("{s}installing to {s}\n", .{ step(), install_path });1110}11111112pub fn updateSelfDone(old_ver: []const u8, new_ver: []const u8) void {1113    p("{s}updated  {s} {s}→{s} {s}\n", .{ hdr(), old_ver, c(DIM), c(RESET), new_ver });1114}11151116pub fn updateSelfNoPlatform(platform: []const u8) void {1117    p("{s}no pre-built binary for {s}\n", .{ hdr(), platform });1118    p("{s}check kepr.uk/nina/releases for available platforms\n", .{step()});1119}11201121pub fn updateSelfNetworkError() void {1122    p("{s}{s}\n", .{ if (color_enabled) WARN_C else WARN_P, "could not reach kepr.uk — check your connection" });1123}11241125pub fn updateSelfChecksumFailed() void {1126    p("{s}checksum mismatch — download may be corrupt\n", .{if (color_enabled) ERR_C else ERR_P});1127    p("{s}try again or download manually from kepr.uk/nina/releases\n", .{step()});1128}11291130pub fn updateSelfNixManaged(new_ver: []const u8) void {1131    p("{s}upgrading to {s}{s}{s} via nix profile\n", .{ step(), c(BOLD), new_ver, c(RESET) });1132}11331134pub fn updateSelfNixFailed() void {1135    p("{s}nix profile upgrade failed\n", .{if (color_enabled) ERR_C else ERR_P});1136    p("{s}try manually: nix profile upgrade '.*nina.*'\n", .{step()});1137}11381139// Reached when building the new version into the store fails, before the1140// profile has been touched at all — the old nina element is still installed1141// and working.1142pub fn updateSelfNixPrefetchFailed() void {1143    p("{s}could not build the new version — check your connection and try again\n", .{if (color_enabled) ERR_C else ERR_P});1144    p("{s}your current nina install is untouched\n", .{step()});1145}11461147// Reached only after `nix profile remove` already succeeded and the1148// re-add failed despite the new version having just been built into the1149// store — nina is genuinely uninstalled at this point, not just stuck on1150// the old version, so the recovery command must reinstall from scratch1151// rather than upgrade. Expected to be rare now that the build happens1152// before the profile is touched.1153pub fn updateSelfNixReinstallFailed() void {1154    p("{s}nix profile add failed — nina was removed and is not reinstalled\n", .{if (color_enabled) ERR_C else ERR_P});1155    p("{s}reinstall manually: nix profile add --no-write-lock-file 'https://kepr.uk/nina/archive/HEAD.tar.gz#nina'\n", .{step()});1156}11571158pub fn updateSelfNixRehash() void {1159    p("{s}run {s}hash -r{s} or open a new shell to use the updated binary\n", .{ step(), c(DIM), c(RESET) });1160}11611162// Reached when nina is in the store but not a `nix profile` element — i.e. it1163// was installed by the system config (NixOS module / systemPackages) or1164// home-manager. `nina update` (the profile self-updater) can't touch those;1165// pushing them at `nix profile add` would spawn a second, drifting install.1166pub fn updateSelfSystemManaged() void {1167    p("{s}nina is managed by your system configuration, not nina update\n", .{hdr()});1168    p("{s}update it where you manage that config:\n", .{step()});1169    p("      {s}nix flake update nina && sudo nixos-rebuild switch{s}\n", .{ c(DIM), c(RESET) });1170}11711172// --- Goodbye / uninstall ---11731174pub fn goodbyeStart() void {1175    p("{s}uninstalling nina\n", .{hdr()});1176}11771178pub fn goodbyeFile(path: []const u8) void {1179    p("{s}will remove {s}\n", .{ step(), path });1180}11811182pub fn goodbyeNix() void {1183    p("{s}will remove nina from nix profile\n", .{step()});1184    p("{s}command: nix profile remove nina\n", .{step()});1185}11861187pub fn goodbyeDone() void {1188    p("{s}goodbye! see kepr.uk/nina to reinstall\n", .{hdr()});1189}11901191pub fn goodbyeFailed(msg: []const u8) void {1192    p("{s}{s}\n", .{ if (color_enabled) ERR_C else ERR_P, msg });1193}11941195// --- Setup ---11961197pub fn setupCheck() void {1198    p("{s}checking nix features\n", .{hdr()});1199}12001201pub fn setupFeatures(nix_command: bool, flakes: bool) void {1202    p("{s}nix-command  {s}{s}{s}\n", .{1203        step(),1204        if (nix_command) c(GREEN) else "",1205        if (nix_command) "enabled" else "not enabled",1206        if (nix_command) c(RESET) else "",1207    });1208    p("{s}flakes       {s}{s}{s}\n", .{1209        step(),1210        if (flakes) c(GREEN) else "",1211        if (flakes) "enabled" else "not enabled",1212        if (flakes) c(RESET) else "",1213    });1214}12151216pub fn setupAllSet() void {1217    p("{s}all set\n", .{hdr()});1218}12191220// Printed once, before the first search, when the nixpkgs registry still points1221// at a remote URL. Flush so it lands before `nix registry pin` and any results.1222pub fn pinningRegistry() void {1223    p("{s}pinning nixpkgs for fast local search...\n", .{hdr()});1224    flush();1225}12261227// --- Plain (non-tty) search rendering ---1228// Color-gated equivalents of the raw-ANSI TUI widget, for piped/scripted search.1229// Using the gated header + c() keeps ANSI out of non-tty output (NO_COLOR / pipes).12301231pub fn searchPlainHeader(mode_str: []const u8, query: []const u8, count: u64) void {1232    p("{s}search {s} {s}  {s}{d} results{s}\n", .{ hdr(), mode_str, query, c(DIM), count, c(RESET) });1233}12341235pub fn searchPlainNoResults() void {1236    p("   no results\n", .{});1237}12381239pub fn searchPlainPackage(pname: []const u8, pkg_version: []const u8, description: []const u8, unfree: bool) void {1240    if (unfree) {1241        p("   {s}   {s}{s}{s}   {s}unfree{s}   {s}\n", .{ pname, c(CYAN), pkg_version, c(RESET), c(YELLOW), c(RESET), description });1242    } else {1243        p("   {s}   {s}{s}{s}   {s}\n", .{ pname, c(CYAN), pkg_version, c(RESET), description });1244    }1245}12461247pub fn searchPlainOption(name: []const u8, type_str: []const u8) void {1248    p("   {s}   {s}{s}{s}\n", .{ name, c(DIM), type_str, c(RESET) });1249}12501251pub fn searchEmptyQuery() void {1252    p("{s}search needs a query  {s}e.g. nina search firefox{s}\n", .{ hdr(), c(DIM), c(RESET) });1253}12541255pub fn setupEnabling() void {1256    p("{s}enabling experimental features\n", .{hdr()});1257}12581259pub fn setupDone(path: []const u8) void {1260    p("{s}wrote {s}\n", .{ step(), path });1261    p("{s}done  open a new shell to pick up the change\n", .{hdr()});1262}12631264// --- NixOS setup (declarative configuration.nix) ---12651266pub fn setupNixosOffer(features_line: []const u8, conf_path: []const u8) void {1267    p("{s}on NixOS these go in your system config\n", .{hdr()});1268    p("   nina can add this line to {s}{s}{s}:\n\n", .{ c(DIM), conf_path, c(RESET) });1269    p("       {s}{s}{s}\n\n", .{ c(CYAN), features_line, c(RESET) });1270}12711272pub fn setupNixosWrote(conf_path: []const u8) void {1273    p("{s}added the line to {s}  {s}(backup: {s}.nina-bak){s}\n", .{ step(), conf_path, c(DIM), conf_path, c(RESET) });1274    p("{s}now run {s}sudo nixos-rebuild switch{s} — then nina's ready\n", .{ hdr(), c(BOLD), c(RESET) });1275}12761277pub fn setupNixosManual(features_line: []const u8, conf_path: []const u8) void {1278    p("{s}no problem — add this line inside the {s}{{ }}{s} in {s}:\n\n", .{ hdr(), c(DIM), c(RESET), conf_path });1279    p("       {s}{s}{s}\n\n", .{ c(CYAN), features_line, c(RESET) });1280    p("   then run {s}sudo nixos-rebuild switch{s} — then nina's ready\n", .{ c(BOLD), c(RESET) });1281}12821283pub fn setupNixosNeedsRebuild(conf_path: []const u8) void {1284    p("{s}already declared in {s}\n", .{ hdr(), conf_path });1285    p("   just run {s}sudo nixos-rebuild switch{s} to activate it\n", .{ c(BOLD), c(RESET) });1286}12871288pub fn pinDone(input: []const u8, commit: []const u8) void {1289    p("{s}pinned {s} -> {s}\n", .{ hdr(), input, commit });1290}12911292pub fn unpinDone(input: []const u8) void {1293    p("{s}unpinned {s}\n", .{ hdr(), input });1294}12951296pub fn hashResult(hash: []const u8) void {1297    p("{s}\n", .{hash});1298}12991300pub fn fetchResult(hash: []const u8, url: []const u8) void {1301    _ = url;1302    p("{s}\n", .{hash});1303}13041305pub fn storeRepairStart() void {1306    p("{s}repairing store\n", .{hdr()});1307}13081309pub fn storeVerifyStart() void {1310    p("{s}verifying store\n", .{hdr()});1311}13121313pub fn storeOptimiseStart(machine: []const u8) void {1314    p("{s}optimising store  {s}\n", .{ hdr(), machine });1315    printSubstep("nix store optimise", .{});1316}13171318pub fn storeOptimiseDone() void {1319    p("{s}done\n", .{hdr()});1320}13211322pub fn storeGcDone(freed: []const u8) void {1323    p("{s}freed {s}\n", .{ hdr(), freed });1324}13251326pub fn storePath(path: []const u8) void {1327    p("{s}\n", .{path});1328}13291330pub fn pkgResult(key: []const u8, val: []const u8) void {1331    p("   {s:<16}  {s}\n", .{ key, val });1332}13331334pub fn channelDone() void {1335    p("{s}done\n", .{hdr()});1336}13371338pub fn flakeShowHeader(name: []const u8) void {1339    p("{s}{s}\n\n", .{ hdr(), name });1340}13411342pub fn flakeShowEntry(kind: []const u8, name: []const u8, desc: []const u8) void {1343    p("   {s:<12}  {s:<24}  {s}\n", .{ kind, name, desc });1344}13451346// --- Home Manager ---13471348pub fn homeNotInstalled() void {1349    p("{s}home manager not detected  {s}nothing to do{s}\n", .{ hdr(), c(DIM), c(RESET) });1350}13511352// HM is a NixOS/flake module — rebuilt by nixos-rebuild, not the standalone CLI.1353pub fn homeModuleManaged() void {1354    p("{s}home manager is managed by your system config\n", .{hdr()});1355    p("   {s}-> run {s}nina apply{s}{s} to rebuild both together{s}\n", .{ c(CYAN), c(BOLD), c(RESET), c(CYAN), c(RESET) });1356}13571358pub fn homeApplyStart(machine: []const u8) void {1359    p("{s}{s}applying home config  {s}\n", .{ KAO_COZY, hdr(), machine });1360}13611362pub fn homeApplyDone(gen: u32, elapsed_ms: u64) void {1363    const secs = @as(f64, @floatFromInt(elapsed_ms)) / 1000.0;1364    // gen 0 means the post-switch generation re-read failed — the switch itself1365    // succeeded, so report success without a misleading "generation 0".1366    if (gen == 0) {1367        if (elapsed_ms >= 1000) {1368            p("{s}done  {s}[{d:.1}s]{s}\n", .{ hdr(), c(DIM), secs, c(RESET) });1369        } else {1370            p("{s}done\n", .{hdr()});1371        }1372        return;1373    }1374    if (elapsed_ms >= 1000) {1375        p("{s}generation {s}{d}{s}  {s}[{d:.1}s]{s}\n", .{ hdr(), c(BOLD), gen, c(RESET), c(DIM), secs, c(RESET) });1376    } else {1377        p("{s}generation {s}{d}{s}\n", .{ hdr(), c(BOLD), gen, c(RESET) });1378    }1379}13801381// `home` was invoked against a remote machine. Detection + flake-ref are1382// local-only, so we don't act on a remote — point the user at the local run.1383pub fn homeLocalOnly(machine: []const u8) void {1384    p("{s}home manager commands run on the local machine only\n", .{hdr()});1385    p("   {s}-> '{s}' is remote; run nina home on that machine directly{s}\n", .{ c(DIM), machine, c(RESET) });1386}13871388pub fn homeApplyDry(machine: []const u8) void {1389    p("{s}home dry run  {s}\n", .{ hdr(), machine });1390}13911392pub fn homeApplyDryDone() void {1393    p("{s}{s}ok{s}  no changes applied\n", .{ hdr(), c(GREEN), c(RESET) });1394}13951396pub fn homeBackStart(machine: []const u8, from: u32, to: u32) void {1397    p("{s}rolling back home config  {s}  gen {d} -> gen {d}\n", .{ hdr(), machine, from, to });1398}13991400pub fn homeBackDone(n: u32) void {1401    p("{s}{s}done  gen {s}{d}{s}\n", .{ KAO_GENTLE, hdr(), c(BOLD), n, c(RESET) });1402}14031404pub fn homeHistoryHeader(machine: []const u8) void {1405    p("{s}home generations  {s}\n\n", .{ hdr(), machine });1406}14071408pub fn homeHistoryRow(number: u32, date: []const u8, time: []const u8, current: bool) void {1409    if (current) {1410        p("   {s}{d}{s}   {s}   {s}   {s}current{s}\n", .{ c(BOLD), number, c(RESET), date, time, c(BOLD), c(RESET) });1411    } else {1412        p("   {s}{d}   {s}   {s}{s}\n", .{ c(DIM), number, date, time, c(RESET) });1413    }1414}14151416pub fn homeEditOpen(path: []const u8, editor: []const u8) void {1417    p("{s}opening {s}\n", .{ hdr(), path });1418    printSubstep("{s}", .{editor});1419}14201421pub fn homeCheckStart(machine: []const u8) void {1422    p("{s}checking home config  {s}\n", .{ hdr(), machine });1423}14241425pub fn homeCheckOk() void {1426    p("{s}{s}ok{s}\n", .{ hdr(), c(GREEN), c(RESET) });1427}14281429pub fn homeDiffHeader(a: u32, b: u32, machine: []const u8) void {1430    p("{s}home gen {d} -> gen {d}  {s}\n\n", .{ hdr(), a, b, machine });1431}14321433pub fn homeNothingToDiff() void {1434    p("{s}only one home generation — nothing to diff yet\n", .{hdr()});1435}14361437pub fn homePackagesHeader(machine: []const u8) void {1438    p("{s}home packages  {s}\n\n", .{ hdr(), machine });1439}14401441// A flake attribute wasn't defined — note it (dim) before trying the next, less1442// specific candidate in the home-apply fallback chain.1443pub fn homeAttrFallback(ref: []const u8) void {1444    p("   {s}{s} not defined — trying next{s}\n", .{ c(DIM), ref, c(RESET) });1445}14461447pub fn homeInitStart(switch_on_init: bool, dir: ?[]const u8) void {1448    const target = dir orelse "~/.config/home-manager";1449    if (switch_on_init) {1450        p("{s}{s}setting up home manager  {s}{s}{s}\n", .{ KAO_COZY, hdr(), c(PINK), target, c(RESET) });1451        p("   {s}-> will activate after init{s}\n", .{ c(DIM), c(RESET) });1452    } else {1453        p("{s}initialising home manager  {s}{s}{s}\n", .{ hdr(), c(PINK), target, c(RESET) });1454        p("   {s}-> edit home.nix then run {s}nina home apply{s}\n", .{ c(DIM), c(BOLD), c(RESET) });1455    }1456}14571458pub fn homeInitDone(switch_on_init: bool) void {1459    if (switch_on_init) {1460        p("{s}{s}home manager ready\n", .{ KAO_GENTLE, hdr() });1461    } else {1462        p("{s}done  edit home.nix and run {s}nina home apply{s} when ready\n", .{ hdr(), c(BOLD), c(RESET) });1463    }1464}14651466// `home init` against a config that already exists — never overwrite; point at1467// apply instead.1468pub fn homeInitExists(path: []const u8) void {1469    p("{s}home manager config already exists\n", .{if (color_enabled) WARN_C else WARN_P});1470    p("   {s}{s}{s}\n", .{ c(DIM), path, c(RESET) });1471    p("   {s}-> run {s}nina home apply{s}{s} to activate it{s}\n", .{ c(CYAN), c(BOLD), c(RESET), c(CYAN), c(RESET) });1472}14731474// --- First-run wizard ---14751476pub fn firstRunBanner() void {1477    p("{s}{s}nina \u{2014} first run\n\n", .{ KAO_FACE, hdr() });1478}14791480pub fn firstRunNoConfig() void {1481    p("   no config found. let me get set up.\n\n", .{});1482}14831484// Print a prompt line and read the user's answer. Returns the default if the1485// user presses Enter without typing anything. buf must be at least 256 bytes.1486// Returns a slice into buf (or default if empty input).1487pub fn firstRunPrompt(label: []const u8, default: []const u8, buf: []u8) []const u8 {1488    p("   {s:<14} {s}> {s}", .{ label, c(DIM), c(RESET) });1489    flush();1490    var i: usize = 0;1491    while (i < buf.len - 1) {1492        const n = std.posix.read(std.posix.STDIN_FILENO, buf[i .. i + 1]) catch break;1493        if (n == 0) break;1494        if (buf[i] == '\n') break;1495        i += 1;1496    }1497    const input = std.mem.trim(u8, buf[0..i], " \t\r");1498    if (input.len == 0) {1499        // Echo the default so the output shows what was chosen1500        p("{s}{s}{s}\n", .{ c(DIM), default, c(RESET) });1501        flush();1502        return default;1503    }1504    return input;1505}15061507pub fn firstRunScanning() void {1508    p("\n   {s}:: scanning for config...{s}\n", .{ c(DIM), c(RESET) });1509}15101511// Report what the scan found at /etc/nixos, noting flake vs channel.1512pub fn firstRunDetected(path: []const u8, is_flake: bool) void {1513    const kind = if (is_flake) "flake-based system" else "channel-based system";1514    p("   {s}-> found {s}{s}   {s}({s}){s}\n\n", .{ c(CYAN), path, c(RESET), c(DIM), kind, c(RESET) });1515}15161517pub fn firstRunNoneFound() void {1518    p("   {s}-> nothing found at /etc/nixos{s}\n\n", .{ c(DIM), c(RESET) });1519}15201521// Prompt with a pre-filled default shown in brackets. Empty input accepts the1522// default. When `detected` and a default is present, note that enter confirms.1523pub fn firstRunPromptDefault(label: []const u8, default: []const u8, detected: bool, buf: []u8) []const u8 {1524    if (default.len > 0) {1525        p("   {s:<14} {s}[{s}]{s} > ", .{ label, c(DIM), default, c(RESET) });1526        if (detected) p("{s}enter to confirm{s} ", .{ c(DIM), c(RESET) });1527    } else {1528        p("   {s:<14} {s}> {s}", .{ label, c(DIM), c(RESET) });1529    }1530    flush();1531    var i: usize = 0;1532    while (i < buf.len - 1) {1533        const n = std.posix.read(std.posix.STDIN_FILENO, buf[i .. i + 1]) catch break;1534        if (n == 0) break;1535        if (buf[i] == '\n') break;1536        i += 1;1537    }1538    const input = std.mem.trim(u8, buf[0..i], " \t\r");1539    if (input.len == 0) {1540        p("{s}{s}{s}\n", .{ c(DIM), default, c(RESET) });1541        flush();1542        return default;1543    }1544    return input;1545}15461547// Shown before channel operations on a flake-managed system, where nix-channel1548// commands generally don't apply.1549pub fn flakeChannelNote() void {1550    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) });1551}15521553pub fn firstRunWritten(path: []const u8) void {1554    p("\n   {s}written to {s}{s}\n\n", .{ c(DIM), path, c(RESET) });1555}15561557pub fn firstRunSkipped() void {1558    p("\n   {s}skipping setup in non-interactive mode{s}\n", .{ c(DIM), c(RESET) });1559}