@tacuchi/updater 2.2.1 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/README.md +48 -2
  2. package/dist/cli.js +903 -165
  3. package/package.json +2 -2
package/dist/cli.js CHANGED
@@ -5,10 +5,10 @@ import { render } from "ink";
5
5
  import { execaSync } from "execa";
6
6
 
7
7
  // src/app.tsx
8
- import { Box as Box8, Text as Text9, useApp as useInkApp } from "ink";
8
+ import { Box as Box9, Text as Text10 } from "ink";
9
9
 
10
10
  // src/hooks/use-app-machine.tsx
11
- import { createContext, useContext, useReducer, useEffect, useRef, useCallback } from "react";
11
+ import { createContext, useContext, useReducer, useEffect, useRef, useState, useCallback } from "react";
12
12
  import { useApp } from "ink";
13
13
 
14
14
  // src/state/types.ts
@@ -29,7 +29,7 @@ function initialState(config, sudoMode2) {
29
29
  managers: {},
30
30
  order: [],
31
31
  selection: /* @__PURE__ */ new Set(),
32
- run: { queue: [], doneCount: 0, failedCount: 0, skippedCount: 0 },
32
+ run: { queue: [], doneCount: 0, failedCount: 0, skippedCount: 0, unknownCount: 0 },
33
33
  config,
34
34
  sudoMode: sudoMode2
35
35
  };
@@ -40,7 +40,9 @@ function newEntry(info) {
40
40
  group: info.group,
41
41
  requiresAdmin: info.requiresAdmin,
42
42
  version: info.version,
43
- status: "scanning",
43
+ // A manager whose probe could not answer is never scanned, so it enters
44
+ // indeterminate and stays there instead of being presented as pending work.
45
+ status: info.undetermined ? "unknown" : "scanning",
44
46
  outdated: [],
45
47
  percent: 0
46
48
  };
@@ -76,8 +78,10 @@ function appReducer(state, action) {
76
78
  outdated: action.outdated,
77
79
  status: action.outdated.length > 0 ? "outdated" : "uptodate"
78
80
  }));
81
+ // A listing that failed used to land here as `uptodate`: the single line that
82
+ // turned "I could not ask" into "nothing to update".
79
83
  case "SCAN_MANAGER_FAILED":
80
- return patch(state, action.id, (e) => ({ ...e, status: "uptodate", outdated: [] }));
84
+ return patch(state, action.id, (e) => ({ ...e, status: "unknown", outdated: [] }));
81
85
  case "SCAN_ALL_DONE":
82
86
  return { ...state, phase: "select" };
83
87
  case "TOGGLE_ITEM": {
@@ -94,7 +98,22 @@ function appReducer(state, action) {
94
98
  return state.selection.size > 0 ? { ...state, phase: "confirm" } : state;
95
99
  case "GOTO_SELECT":
96
100
  return { ...state, phase: "select" };
101
+ // Same shape as the settings overlay: a screen SWAP grows no region, which
102
+ // is what keeps a long package list from having to be capped by hand.
103
+ //
104
+ // Abrir lo que YA está abierto no vuelve a guardar el origen. Si lo
105
+ // guardara, `prevPhase` pasaría a valer `'detail'` y el cierre devolvería a
106
+ // la misma pantalla: el detalle quedaría SIN SALIDA para siempre, y no hace
107
+ // falta nada raro para caer ahí —dos `d` seguidas alcanzan, y la repetición
108
+ // del teclado las produce sola—. Así se colgó CI, 74 pulsaciones seguidas
109
+ // sin mover un pixel.
110
+ case "OPEN_DETAIL":
111
+ if (state.phase === "detail") return state;
112
+ return { ...state, prevPhase: state.phase, phase: "detail" };
113
+ case "CLOSE_DETAIL":
114
+ return { ...state, phase: state.prevPhase };
97
115
  case "OPEN_SETTINGS":
116
+ if (state.phase === "settings") return state;
98
117
  return { ...state, prevPhase: state.phase, phase: "settings" };
99
118
  case "CLOSE_SETTINGS":
100
119
  return { ...state, phase: state.prevPhase };
@@ -113,13 +132,20 @@ function appReducer(state, action) {
113
132
  ...state,
114
133
  phase: "updating",
115
134
  managers,
116
- run: { queue: action.queue, doneCount: 0, failedCount: 0, skippedCount: 0 }
135
+ run: { queue: action.queue, doneCount: 0, failedCount: 0, skippedCount: 0, unknownCount: 0 }
117
136
  };
118
137
  }
119
138
  case "MGR_QUEUED":
120
139
  return patch(state, action.id, (e) => ({ ...e, status: "queued" }));
140
+ // `at` comes in the action, not from Date.now(): the reducer stays pure, and
141
+ // it used to store 0 — which is why no row could show how long it had been
142
+ // running.
121
143
  case "MGR_RUNNING":
122
- return patch(state, action.id, (e) => ({ ...e, status: "running", startedAt: e.startedAt ?? 0 }));
144
+ return patch(state, action.id, (e) => ({
145
+ ...e,
146
+ status: "running",
147
+ startedAt: e.startedAt !== void 0 && e.startedAt > 0 ? e.startedAt : action.at
148
+ }));
123
149
  case "MGR_PROGRESS":
124
150
  return patch(state, action.id, (e) => ({
125
151
  ...e,
@@ -141,6 +167,13 @@ function appReducer(state, action) {
141
167
  ...patch(state, action.id, (e) => ({ ...e, status: "skipped", manualCommand: action.manualCommand })),
142
168
  run: { ...state.run, skippedCount: state.run.skippedCount + 1 }
143
169
  };
170
+ // Its own counter on purpose: an upgrade whose result could not be verified
171
+ // is neither done nor failed, and folding it into either is the lie.
172
+ case "MGR_UNKNOWN":
173
+ return {
174
+ ...patch(state, action.id, (e) => ({ ...e, status: "unknown", percent: 100, result: action.result })),
175
+ run: { ...state.run, unknownCount: state.run.unknownCount + 1 }
176
+ };
144
177
  case "RUN_DONE":
145
178
  return { ...state, phase: "summary" };
146
179
  case "SET_LANGUAGE":
@@ -229,7 +262,12 @@ import treeKill from "tree-kill";
229
262
  function killTree(pid, signal = "SIGTERM") {
230
263
  if (!pid) return;
231
264
  try {
232
- treeKill(pid, signal, () => {
265
+ treeKill(pid, signal, (err) => {
266
+ if (!err) return;
267
+ try {
268
+ process.kill(pid, signal);
269
+ } catch {
270
+ }
233
271
  });
234
272
  } catch {
235
273
  }
@@ -260,7 +298,6 @@ function execaOptions(opts, all) {
260
298
  reject: false,
261
299
  cwd: opts.cwd,
262
300
  env: opts.env,
263
- cancelSignal: opts.signal,
264
301
  all,
265
302
  // Capture raw bytes; we sniff-decode (UTF-8 / UTF-16LE / OEM) ourselves.
266
303
  encoding: "buffer"
@@ -316,6 +353,10 @@ async function* runStream(cmd, args2, opts, percentParser) {
316
353
  }
317
354
 
318
355
  // src/lib/executor.ts
356
+ function isSpawnFailure(r) {
357
+ if (r.code === "ENOENT") return true;
358
+ return typeof r.originalMessage === "string" && r.originalMessage.includes("ENOENT");
359
+ }
319
360
  async function execCommand(cmd, args2, timeout = 5e3, sudo = false) {
320
361
  const [finalCmd, finalArgs] = withSudo(cmd, args2, sudo);
321
362
  try {
@@ -328,14 +369,18 @@ async function execCommand(cmd, args2, timeout = 5e3, sudo = false) {
328
369
  return {
329
370
  stdout: decodeSmart(result.stdout),
330
371
  stderr: decodeSmart(result.stderr),
331
- exitCode: result.exitCode ?? (result.failed ? 127 : 0)
372
+ exitCode: result.exitCode ?? (result.failed ? 127 : 0),
373
+ timedOut: result.timedOut === true,
374
+ spawnFailed: isSpawnFailure(result)
332
375
  };
333
376
  } catch (err) {
334
377
  if (err instanceof ExecaError) {
335
378
  return {
336
379
  stdout: decodeSmart(err.stdout),
337
380
  stderr: decodeSmart(err.stderr) || String(err.message),
338
- exitCode: err.exitCode ?? 1
381
+ exitCode: err.exitCode ?? 1,
382
+ timedOut: err.timedOut === true,
383
+ spawnFailed: isSpawnFailure(err)
339
384
  };
340
385
  }
341
386
  throw err;
@@ -375,8 +420,30 @@ function reconcile(requested, before, after, commands, successExitCodes) {
375
420
  const beforeByName = new Map(before.map((p) => [p.name, p]));
376
421
  const targetNames = requested ?? before.map((p) => p.name);
377
422
  const targets = [...new Set(targetNames)];
378
- const stillOutdated = new Set(after.stillOutdated.map((p) => p.name));
379
423
  const cmdKind = dominantFailureKind(commands, successExitCodes);
424
+ if (after === null) {
425
+ return {
426
+ success: false,
427
+ upgraded: 0,
428
+ failed: 0,
429
+ errors: ["no se pudo verificar el resultado: el listado posterior fall\xF3"],
430
+ status: "unknown",
431
+ skipped: 0,
432
+ reason: cmdKind ?? void 0,
433
+ reboot: rebootFrom(commands),
434
+ packages: targets.map((name) => {
435
+ const b = beforeByName.get(name);
436
+ return {
437
+ name,
438
+ outcome: "unknown",
439
+ fromVersion: b?.currentVersion,
440
+ toVersion: b?.newVersion
441
+ };
442
+ }),
443
+ commands
444
+ };
445
+ }
446
+ const stillOutdated = new Set(after.stillOutdated.map((p) => p.name));
380
447
  const packages = targets.map((name) => {
381
448
  const b = beforeByName.get(name);
382
449
  if (stillOutdated.has(name)) {
@@ -426,14 +493,13 @@ function reconcile(requested, before, after, commands, successExitCodes) {
426
493
  }
427
494
 
428
495
  // src/lib/logger.ts
429
- import fs2 from "fs";
430
- import path2 from "path";
496
+ import fs3 from "fs";
497
+ import path3 from "path";
431
498
 
432
499
  // src/lib/config.ts
433
500
  import fs from "fs";
434
501
  import path from "path";
435
502
  import os from "os";
436
- import envPaths from "env-paths";
437
503
  var DEFAULTS = {
438
504
  enabledManagers: {},
439
505
  verbosity: "info",
@@ -441,7 +507,9 @@ var DEFAULTS = {
441
507
  concurrency: 4,
442
508
  timeoutsMs: {},
443
509
  logTailBytes: 16384,
444
- managers: {}
510
+ managers: {},
511
+ logRetentionRuns: 30,
512
+ selfCheck: true
445
513
  };
446
514
  var MIN_CONCURRENCY = 1;
447
515
  var MAX_CONCURRENCY = 8;
@@ -457,17 +525,29 @@ function normalizeConfig(parsed) {
457
525
  timeoutsMs: { ...DEFAULTS.timeoutsMs, ...parsed.timeoutsMs },
458
526
  managers: { ...DEFAULTS.managers, ...parsed.managers },
459
527
  concurrency: clampConcurrency(parsed.concurrency),
460
- logTailBytes: typeof parsed.logTailBytes === "number" && parsed.logTailBytes > 0 ? Math.round(parsed.logTailBytes) : DEFAULTS.logTailBytes
528
+ logTailBytes: typeof parsed.logTailBytes === "number" && parsed.logTailBytes > 0 ? Math.round(parsed.logTailBytes) : DEFAULTS.logTailBytes,
529
+ logRetentionRuns: typeof parsed.logRetentionRuns === "number" && parsed.logRetentionRuns >= 1 ? Math.round(parsed.logRetentionRuns) : DEFAULTS.logRetentionRuns,
530
+ selfCheck: typeof parsed.selfCheck === "boolean" ? parsed.selfCheck : DEFAULTS.selfCheck
461
531
  };
462
532
  }
463
533
  var APP = "tacuchi-updater";
464
- function getConfigDir() {
465
- if (process.platform === "win32") return envPaths(APP, { suffix: "" }).config;
534
+ function windowsPaths() {
535
+ const home = os.homedir();
536
+ const roaming = process.env["APPDATA"] || path.join(home, "AppData", "Roaming");
537
+ const local = process.env["LOCALAPPDATA"] || path.join(home, "AppData", "Local");
538
+ return { config: path.join(roaming, APP, "Config"), log: path.join(local, APP, "Log") };
539
+ }
540
+ function getConfigDir(platform = process.platform) {
541
+ const override = process.env["TACUCHI_UPDATER_CONFIG_DIR"];
542
+ if (override) return override;
543
+ if (platform === "win32") return windowsPaths().config;
466
544
  return path.join(os.homedir(), ".tacuchi-updater");
467
545
  }
468
- function getLogDir() {
469
- if (process.platform === "win32") return envPaths(APP, { suffix: "" }).log;
470
- return path.join(getConfigDir(), "logs");
546
+ function getLogDir(platform = process.platform) {
547
+ const override = process.env["TACUCHI_UPDATER_LOG_DIR"];
548
+ if (override) return override;
549
+ if (platform === "win32") return windowsPaths().log;
550
+ return path.join(getConfigDir(platform), "logs");
471
551
  }
472
552
  function getConfigPath() {
473
553
  return path.join(getConfigDir(), "config.json");
@@ -489,7 +569,14 @@ function loadConfig() {
489
569
  migrateLegacyConfig();
490
570
  const configPath = getConfigPath();
491
571
  try {
492
- if (!fs.existsSync(configPath)) return { ...DEFAULTS };
572
+ if (!fs.existsSync(configPath)) {
573
+ const defaults = { ...DEFAULTS };
574
+ try {
575
+ saveConfig(defaults);
576
+ } catch {
577
+ }
578
+ return defaults;
579
+ }
493
580
  const raw = fs.readFileSync(configPath, "utf-8");
494
581
  const parsed = JSON.parse(raw);
495
582
  return normalizeConfig(parsed);
@@ -528,30 +615,80 @@ function isManagerEnabled(config, managerId) {
528
615
  return true;
529
616
  }
530
617
 
618
+ // src/lib/log-retention.ts
619
+ import fs2 from "fs";
620
+ import path2 from "path";
621
+ var defaultRetentionDeps = {
622
+ listFiles: (dir) => fs2.existsSync(dir) ? fs2.readdirSync(dir).filter((f) => f.endsWith(".log")) : [],
623
+ mtimeMs: (file) => fs2.statSync(file).mtimeMs,
624
+ remove: (file) => fs2.unlinkSync(file)
625
+ };
626
+ function isPermissionDenied(err) {
627
+ const code = err?.code;
628
+ return code === "EACCES" || code === "EPERM";
629
+ }
630
+ function pruneLogs(dir, keep, deps = defaultRetentionDeps) {
631
+ const limit = Math.max(1, Math.floor(keep));
632
+ const report = { kept: 0, removed: 0, unremovable: [] };
633
+ let files;
634
+ try {
635
+ files = deps.listFiles(dir);
636
+ } catch {
637
+ return report;
638
+ }
639
+ const dated = files.map((f) => {
640
+ const full = path2.join(dir, f);
641
+ try {
642
+ return { full, mtime: deps.mtimeMs(full) };
643
+ } catch {
644
+ return null;
645
+ }
646
+ }).filter((x) => x !== null).sort((a, b) => b.mtime - a.mtime);
647
+ report.kept = Math.min(dated.length, limit);
648
+ for (const entry of dated.slice(limit)) {
649
+ try {
650
+ deps.remove(entry.full);
651
+ report.removed += 1;
652
+ } catch (err) {
653
+ if (isPermissionDenied(err)) {
654
+ report.unremovable.push({ file: entry.full, reason: "sin permiso" });
655
+ }
656
+ }
657
+ }
658
+ return report;
659
+ }
660
+ function unremovableReport(files, platform) {
661
+ if (files.length === 0) return null;
662
+ if (platform === "win32") {
663
+ return { reason: "bloqueado(s) por otro proceso", command: null };
664
+ }
665
+ return {
666
+ reason: "de otro due\xF1o",
667
+ command: `sudo rm -f ${files.map((f) => `'${f}'`).join(" ")}`
668
+ };
669
+ }
670
+
531
671
  // src/lib/logger.ts
532
672
  var logFilePath = null;
533
- var logStream = null;
673
+ var logFd = null;
534
674
  var inMemoryLog = [];
535
675
  var entryCounter = 0;
536
- function createStream(dir, filename) {
537
- if (!fs2.existsSync(dir)) fs2.mkdirSync(dir, { recursive: true });
538
- const filePath = path2.join(dir, filename);
539
- const stream = fs2.createWriteStream(filePath, { flags: "a", encoding: "utf-8" });
540
- return { stream, filePath };
676
+ function openLog(dir, filename) {
677
+ if (!fs3.existsSync(dir)) fs3.mkdirSync(dir, { recursive: true });
678
+ const filePath = path3.join(dir, filename);
679
+ return { fd: fs3.openSync(filePath, "a"), filePath };
541
680
  }
542
- function initLogger() {
681
+ function initLogger(retentionRuns) {
543
682
  const now = /* @__PURE__ */ new Date();
544
683
  const stamp = now.toISOString().replace(/[T:]/g, "_").split(".")[0]?.replace(/-/g, "");
545
684
  const filename = `system_updater_${stamp}.log`;
685
+ closeLogger();
546
686
  try {
547
- const { stream, filePath } = createStream(getLogDir(), filename);
548
- logStream = stream;
687
+ const { fd, filePath } = openLog(getLogDir(), filename);
688
+ logFd = fd;
549
689
  logFilePath = filePath;
550
- logStream.on("error", () => {
551
- logStream = null;
552
- });
553
690
  } catch {
554
- logStream = null;
691
+ logFd = null;
555
692
  logFilePath = null;
556
693
  }
557
694
  writeRaw("INFO", "Logger iniciado \u2014 @tacuchi/updater");
@@ -561,14 +698,39 @@ function initLogger() {
561
698
  `PID: ${process.pid} | UID: ${process.getuid?.() ?? "N/A"} | SUDO_USER: ${process.env["SUDO_USER"] ?? "N/A"}`
562
699
  );
563
700
  writeRaw("INFO", `Platform: ${process.platform} | Node: ${process.version}`);
701
+ if (retentionRuns !== void 0) pruneDeposit(retentionRuns);
564
702
  return logFilePath ?? "";
565
703
  }
704
+ function pruneDeposit(retentionRuns) {
705
+ const report = pruneLogs(getLogDir(), retentionRuns);
706
+ writeRaw(
707
+ "INFO",
708
+ `Retenci\xF3n: conservadas=${report.kept} retiradas=${report.removed} sin retirar=${report.unremovable.length} (l\xEDmite=${retentionRuns} corridas)`
709
+ );
710
+ const unremovable = unremovableReport(
711
+ report.unremovable.map((u) => u.file),
712
+ process.platform
713
+ );
714
+ if (unremovable !== null) {
715
+ const how = unremovable.command === null ? "" : ` Para retirarlos: ${unremovable.command}`;
716
+ writeRaw("WARN", `Retenci\xF3n: ${report.unremovable.length} archivo(s) ${unremovable.reason}.${how}`);
717
+ }
718
+ }
566
719
  function writeRaw(level, message) {
720
+ if (logFd === null) return;
567
721
  const now = /* @__PURE__ */ new Date();
568
722
  const timestamp = now.toISOString().replace("T", " ").split(".")[0];
569
723
  const line = `${timestamp} [${level.padEnd(5)}] SystemUpdater - ${message}
570
724
  `;
571
- logStream?.write(line);
725
+ try {
726
+ const bytes = new TextEncoder().encode(line);
727
+ let written = 0;
728
+ while (written < bytes.length) {
729
+ written += fs3.writeSync(logFd, bytes.subarray(written));
730
+ }
731
+ } catch {
732
+ logFd = null;
733
+ }
572
734
  }
573
735
  function addToMemory(level, message) {
574
736
  const id = String(++entryCounter);
@@ -576,6 +738,14 @@ function addToMemory(level, message) {
576
738
  inMemoryLog.push({ id, timestamp, level, message });
577
739
  if (inMemoryLog.length > 200) inMemoryLog.shift();
578
740
  }
741
+ function log(message) {
742
+ writeRaw("INFO", message);
743
+ addToMemory("info", message);
744
+ }
745
+ function debug(message) {
746
+ writeRaw("DEBUG", message);
747
+ addToMemory("debug", message);
748
+ }
579
749
  function warn(message) {
580
750
  writeRaw("WARN", message);
581
751
  addToMemory("warn", message);
@@ -593,6 +763,43 @@ function logCommand(rec) {
593
763
  }
594
764
  addToMemory("debug", `$ ${rec.cmd} (${status})`);
595
765
  }
766
+ function exitOf(code) {
767
+ return code === null ? "exit=n/d" : `exit=${code}`;
768
+ }
769
+ function waitOf(timeoutMs) {
770
+ return timeoutMs === void 0 ? "" : ` timeout=${timeoutMs}ms`;
771
+ }
772
+ function timeoutMark(timedOut) {
773
+ return timedOut === true ? " (expir\xF3)" : "";
774
+ }
775
+ function formatDetectLine(r) {
776
+ const verdict = r.available ? `disponible${r.version ? ` version=${r.version}` : ""}` : r.undetermined ? `indeterminado${timeoutMark(r.timedOut)}` : "ausente";
777
+ const via = r.viaEscapeHatch ? " via=escape-hatch" : "";
778
+ return `${r.managerId}: detect cmd="${r.cmd}"${via}${waitOf(r.timeoutMs)} ${exitOf(r.exitCode)} (${r.durationMs}ms) \u2192 ${verdict}`;
779
+ }
780
+ function formatScanLine(r) {
781
+ const verdict = r.ok ? `pendientes=${r.count}` : `indeterminado${timeoutMark(r.timedOut)}`;
782
+ return `${r.managerId}: scan cmd="${r.cmd}"${waitOf(r.timeoutMs)} ${exitOf(r.exitCode)} (${r.durationMs}ms) \u2192 ${verdict}`;
783
+ }
784
+ function logDetect(r) {
785
+ const line = formatDetectLine(r);
786
+ writeRaw("DEBUG", line);
787
+ addToMemory("debug", line);
788
+ }
789
+ function logScan(r) {
790
+ const line = formatScanLine(r);
791
+ writeRaw(r.ok ? "DEBUG" : "WARN", line);
792
+ addToMemory(r.ok ? "debug" : "warn", line);
793
+ }
794
+ function formatSelectionLines(s) {
795
+ const lines = [`Selecci\xF3n: ofrecidos=${s.offered} elegidos=${s.chosen}`];
796
+ for (const m of s.managers) lines.push(` ${m.id}: ofrecidos=${m.offered} elegidos=${m.chosen}`);
797
+ return lines;
798
+ }
799
+ function logSelection(s) {
800
+ for (const line of formatSelectionLines(s)) writeRaw("INFO", line);
801
+ addToMemory("info", `Selecci\xF3n: ${s.chosen} de ${s.offered}`);
802
+ }
596
803
  function formatResultLines(r) {
597
804
  const id = r.managerId ?? "?";
598
805
  const reason = r.reason ? ` reason=${r.reason}` : "";
@@ -603,16 +810,19 @@ function formatResultLines(r) {
603
810
  }
604
811
  for (const p of r.packages ?? []) {
605
812
  const ver = p.fromVersion || p.toVersion ? ` ${p.fromVersion ?? "?"}->${p.toVersion ?? "?"}` : "";
606
- lines.push(` ${id}: ${p.name}${ver} [${p.outcome}]`);
813
+ const why = p.failureKind ? ` (${p.failureKind})` : "";
814
+ lines.push(` ${id}: ${p.name}${ver} [${p.outcome}]${why}`);
607
815
  }
608
816
  return lines;
609
817
  }
610
818
  function logResult(r) {
611
819
  const id = r.managerId ?? "?";
612
820
  const ok = r.status === "success" || r.status === "noop";
613
- const level = ok ? "INFO" : r.status === "partial" ? "WARN" : "ERROR";
821
+ const level = ok ? "INFO" : r.status === "partial" || r.status === "unknown" ? "WARN" : "ERROR";
614
822
  for (const line of formatResultLines(r)) writeRaw(level, line);
615
- for (const e of r.errors) writeRaw(level, ` ${id}: ${e}`);
823
+ if ((r.packages ?? []).length === 0) {
824
+ for (const e of r.errors) writeRaw(level, ` ${id}: ${e}`);
825
+ }
616
826
  const memLevel = ok ? "info" : r.status === "partial" ? "warn" : "error";
617
827
  addToMemory(memLevel, `${id}: ${r.status} (${r.upgraded} ok, ${r.failed} fail)`);
618
828
  }
@@ -622,22 +832,69 @@ function formatRunSummary(s) {
622
832
  const dur = m.durationMs !== void 0 ? ` ${m.durationMs}ms` : "";
623
833
  lines.push(` ${m.id}: ${m.status} (${m.upgraded} ok, ${m.failed} fail)${dur}`);
624
834
  }
625
- lines.push(`Total: ${s.upgraded} upgraded \xB7 ${s.failed} failed \xB7 ${s.skipped} skipped`);
835
+ lines.push(
836
+ `Total: ${s.upgraded} upgraded \xB7 ${s.failed} failed \xB7 ${s.skipped} skipped \xB7 ${s.unknown} unknown`
837
+ );
626
838
  return lines;
627
839
  }
628
- function logRunSummary(s) {
629
- for (const line of formatRunSummary(s)) writeRaw("INFO", line);
630
- addToMemory("info", `Resumen: ${s.upgraded} ok \xB7 ${s.failed} fail \xB7 ${s.skipped} skip`);
631
- }
632
840
  function getLogFilePath() {
633
841
  return logFilePath;
634
842
  }
843
+ function closeLogger() {
844
+ if (logFd === null) return;
845
+ try {
846
+ fs3.fsyncSync(logFd);
847
+ } catch {
848
+ }
849
+ try {
850
+ fs3.closeSync(logFd);
851
+ } catch {
852
+ }
853
+ logFd = null;
854
+ }
855
+ function formatRunClosure(mode, summary, detail) {
856
+ const lines = summary ? formatRunSummary(summary) : [];
857
+ lines.push(`Cierre del run: modo=${mode}${detail ? ` (${detail})` : ""}`);
858
+ return lines;
859
+ }
860
+ function logRunClosure(mode, summary, detail) {
861
+ for (const line of formatRunClosure(mode, summary, detail)) writeRaw("INFO", line);
862
+ addToMemory("info", `Cierre del run: ${mode}`);
863
+ }
864
+
865
+ // src/managers/listing.ts
866
+ var ListingUnavailableError = class extends Error {
867
+ constructor(managerId, detail) {
868
+ super(`${managerId}: no se pudo determinar la lista de pendientes (${detail})`);
869
+ this.managerId = managerId;
870
+ this.detail = detail;
871
+ this.name = "ListingUnavailableError";
872
+ }
873
+ };
874
+ function requireListing(managerId, res, okExitCodes = [0]) {
875
+ if (okExitCodes.includes(res.exitCode)) return;
876
+ throw new ListingUnavailableError(
877
+ managerId,
878
+ res.timedOut ? "expir\xF3 la espera" : `exit=${res.exitCode}`
879
+ );
880
+ }
635
881
 
636
882
  // src/managers/engine.ts
637
883
  var defaultDeps = { execCommand, runStream };
638
884
  var DETECT_TIMEOUT = 5e3;
639
885
  var LIST_TIMEOUT = 3e4;
640
886
  var UPGRADE_TIMEOUT = 6e5;
887
+ function undeterminedResult(managerId, detail) {
888
+ return {
889
+ success: false,
890
+ upgraded: 0,
891
+ failed: 0,
892
+ errors: [detail],
893
+ skipped: 0,
894
+ status: "unknown",
895
+ managerId
896
+ };
897
+ }
641
898
  function skippedResult(managerId, manualCommand) {
642
899
  return {
643
900
  success: false,
@@ -668,25 +925,83 @@ function fromDescriptor(d, cfg, deps = defaultDeps) {
668
925
  group: d.group,
669
926
  defaultTimeoutMs: d.defaultTimeoutMs,
670
927
  async detect() {
928
+ const spec = d.detectCmd;
929
+ const timeoutMs = spec.timeout ?? DETECT_TIMEOUT;
930
+ const startedAt = Date.now();
671
931
  if (d.escapeHatch?.detect) {
672
932
  const r = await d.escapeHatch.detect(ctx(false));
933
+ logDetect({
934
+ managerId: d.id,
935
+ cmd: `${spec.cmd} ${spec.args.join(" ")}`,
936
+ viaEscapeHatch: true,
937
+ timeoutMs,
938
+ durationMs: Date.now() - startedAt,
939
+ exitCode: null,
940
+ available: r.available,
941
+ version: r.version
942
+ });
673
943
  return { available: r.available, version: r.version };
674
944
  }
675
- const spec = d.detectCmd;
676
- const res = await deps.execCommand(spec.cmd, spec.args, spec.timeout ?? DETECT_TIMEOUT, sudoFor(spec, ctx(false)));
945
+ const res = await deps.execCommand(spec.cmd, spec.args, timeoutMs, sudoFor(spec, ctx(false)));
677
946
  const ok = res.exitCode === 0 || (d.detectOkExitCodes?.includes(res.exitCode) ?? false);
678
- if (!ok) return { available: false };
679
- return { available: true, version: d.parseVersion?.(res.stdout, res.stderr) };
947
+ const detection = ok ? { available: true, version: d.parseVersion?.(res.stdout, res.stderr) } : res.spawnFailed ? { available: false } : { available: false, undetermined: true };
948
+ logDetect({
949
+ managerId: d.id,
950
+ cmd: `${spec.cmd} ${spec.args.join(" ")}`,
951
+ timeoutMs,
952
+ durationMs: Date.now() - startedAt,
953
+ exitCode: res.exitCode,
954
+ available: detection.available,
955
+ undetermined: detection.undetermined === true,
956
+ timedOut: res.timedOut,
957
+ version: detection.version
958
+ });
959
+ return detection;
680
960
  },
681
961
  async listOutdated() {
682
962
  const c = ctx(false);
683
- if (d.escapeHatch?.listOutdated) return d.escapeHatch.listOutdated(c);
684
- if (!d.listOutdatedCmd || !d.parseOutdated) return [];
963
+ const startedAt = Date.now();
964
+ if (d.escapeHatch?.listOutdated) {
965
+ const list2 = await d.escapeHatch.listOutdated(c);
966
+ logScan({
967
+ managerId: d.id,
968
+ cmd: "(escape hatch)",
969
+ timeoutMs: LIST_TIMEOUT,
970
+ durationMs: Date.now() - startedAt,
971
+ exitCode: null,
972
+ count: list2.length,
973
+ ok: true
974
+ });
975
+ return list2;
976
+ }
977
+ if (!d.listOutdatedCmd || !d.parseOutdated) {
978
+ logScan({
979
+ managerId: d.id,
980
+ cmd: "(sin comando de listado)",
981
+ durationMs: Date.now() - startedAt,
982
+ exitCode: null,
983
+ count: 0,
984
+ ok: true
985
+ });
986
+ return [];
987
+ }
685
988
  const spec = d.listOutdatedCmd(c);
686
- const res = await deps.execCommand(spec.cmd, spec.args, spec.timeout ?? LIST_TIMEOUT, sudoFor(spec, c));
989
+ const timeoutMs = spec.timeout ?? LIST_TIMEOUT;
990
+ const res = await deps.execCommand(spec.cmd, spec.args, timeoutMs, sudoFor(spec, c));
687
991
  const ok = res.exitCode === 0 || (d.listOkExitCodes?.includes(res.exitCode) ?? false);
688
- if (!ok) return [];
689
- return d.parseOutdated(res.stdout, res.stderr, c);
992
+ const list = ok ? d.parseOutdated(res.stdout, res.stderr, c) : [];
993
+ logScan({
994
+ managerId: d.id,
995
+ cmd: `${spec.cmd} ${spec.args.join(" ")}`,
996
+ timeoutMs,
997
+ durationMs: Date.now() - startedAt,
998
+ exitCode: res.exitCode,
999
+ count: list.length,
1000
+ ok,
1001
+ timedOut: res.timedOut
1002
+ });
1003
+ requireListing(d.id, res, [0, ...d.listOkExitCodes ?? []]);
1004
+ return list;
690
1005
  },
691
1006
  async *upgrade(packages, sudoMode2, signal) {
692
1007
  const c = ctx(sudoMode2 ?? false, signal);
@@ -705,7 +1020,17 @@ function fromDescriptor(d, cfg, deps = defaultDeps) {
705
1020
  return { ...r, startedAt, finishedAt: Date.now() };
706
1021
  }
707
1022
  yield { type: "phase", phase: "upgrading", message: `Actualizando ${d.id}...` };
708
- const before = await this.listOutdated();
1023
+ let before = [];
1024
+ try {
1025
+ before = await this.listOutdated();
1026
+ } catch (err) {
1027
+ if (!(err instanceof ListingUnavailableError)) throw err;
1028
+ if (!packages || packages.length === 0) {
1029
+ const r = { ...undeterminedResult(d.id, err.message), startedAt, finishedAt: Date.now() };
1030
+ logResult(r);
1031
+ return r;
1032
+ }
1033
+ }
709
1034
  const target = packages ?? before.map((p) => p.name);
710
1035
  const commands = [];
711
1036
  const pp = d.percentParser ? (line) => d.percentParser(line, c) : void 0;
@@ -739,7 +1064,13 @@ function fromDescriptor(d, cfg, deps = defaultDeps) {
739
1064
  yield* runOne(d.upgradeCmd(target.length ? target : void 0, c));
740
1065
  for (const spec of d.postUpgradeCmds?.(c) ?? []) yield* runOne(spec);
741
1066
  yield { type: "phase", phase: "verifying", message: "Verificando resultado..." };
742
- const after = await verifySnapshot(d, c, deps, this);
1067
+ let after;
1068
+ try {
1069
+ after = await verifySnapshot(d, c, deps, this);
1070
+ } catch (err) {
1071
+ if (!(err instanceof ListingUnavailableError)) throw err;
1072
+ after = null;
1073
+ }
743
1074
  const result = {
744
1075
  managerId: d.id,
745
1076
  startedAt,
@@ -862,7 +1193,7 @@ async function pep668Flags() {
862
1193
  async function listOutdated() {
863
1194
  const { cmd, baseArgs } = await resolvedInvocation();
864
1195
  const res = await execCommand(cmd, [...baseArgs, "list", "--outdated", "--format=json"], 3e4);
865
- if (res.exitCode !== 0) return [];
1196
+ requireListing("pip", res);
866
1197
  return parsePipOutdated(res.stdout);
867
1198
  }
868
1199
  var pip = {
@@ -1000,7 +1331,7 @@ async function userGems() {
1000
1331
  }
1001
1332
  async function listOutdated2() {
1002
1333
  const res = await execCommand("gem", ["outdated"], 3e4);
1003
- if (res.exitCode !== 0) return [];
1334
+ requireListing("gem", res);
1004
1335
  return parseGemOutdated(res.stdout, await userGems());
1005
1336
  }
1006
1337
  function updateArgs(packages, useSudo) {
@@ -1103,6 +1434,7 @@ async function listWinget() {
1103
1434
  ["list", "--upgrade-available", "--include-unknown", "--accept-source-agreements"],
1104
1435
  6e4
1105
1436
  );
1437
+ requireListing("winget", res);
1106
1438
  return parseWingetOutdated(res.stdout);
1107
1439
  }
1108
1440
  var winget = {
@@ -1700,7 +2032,7 @@ function firstVersionToken(cell) {
1700
2032
  }
1701
2033
  async function listOutdated6() {
1702
2034
  const res = await execCommand("pnpm", ["outdated", "--global"], 3e4);
1703
- if (res.exitCode !== 0 && res.exitCode !== 1) return [];
2035
+ requireListing("pnpm", res, [0, 1]);
1704
2036
  return parsePnpmOutdated(res.stdout);
1705
2037
  }
1706
2038
  var pnpm = {
@@ -1982,7 +2314,7 @@ function highestInstalled(versions) {
1982
2314
  async function plugins() {
1983
2315
  return once("asdf:plugins", async () => {
1984
2316
  const res = await execCommand("asdf", ["plugin", "list"], 1e4);
1985
- if (res.exitCode !== 0) return [];
2317
+ requireListing("asdf", res);
1986
2318
  return parsePlugins(res.stdout);
1987
2319
  });
1988
2320
  }
@@ -2163,7 +2495,7 @@ function parsePipxList(stdout) {
2163
2495
  }
2164
2496
  async function snapshot() {
2165
2497
  const res = await execCommand("pipx", ["list", "--json"], 3e4);
2166
- if (res.exitCode !== 0) return {};
2498
+ requireListing("pipx", res);
2167
2499
  return parsePipxList(res.stdout);
2168
2500
  }
2169
2501
  async function listOutdated9() {
@@ -2260,7 +2592,7 @@ async function detectManagers(config) {
2260
2592
  managers.map(async (m) => ({ manager: m, detection: await m.detect() }))
2261
2593
  );
2262
2594
  return results.filter(
2263
- (r) => r.status === "fulfilled" && r.value.detection.available
2595
+ (r) => r.status === "fulfilled" && (r.value.detection.available || r.value.detection.undetermined === true)
2264
2596
  ).map((r) => r.value);
2265
2597
  }
2266
2598
 
@@ -2513,6 +2845,7 @@ var es = {
2513
2845
  confirm: "Confirmar",
2514
2846
  updating: "Actualizando",
2515
2847
  summary: "Resumen",
2848
+ detail: "Detalle por paquete",
2516
2849
  settings: "Ajustes"
2517
2850
  },
2518
2851
  // Etiquetas de estado por-gestor (ManagerStatus)
@@ -2525,7 +2858,8 @@ var es = {
2525
2858
  running: "ACTUALIZANDO",
2526
2859
  done: "OK",
2527
2860
  failed: "ERROR",
2528
- skipped: "MANUAL"
2861
+ skipped: "MANUAL",
2862
+ unknown: "INDETERMINADO"
2529
2863
  },
2530
2864
  // Cadenas de la interfaz del flujo
2531
2865
  ui: {
@@ -2547,7 +2881,13 @@ var es = {
2547
2881
  passwordNote: 'Si aparece "Password:" abajo, es un gestor (p.ej. un cask de brew): escr\xEDbela y Enter.',
2548
2882
  summaryHint: "R re-escanear \xB7 Q salir",
2549
2883
  elapsed: "transcurrido",
2550
- cancel: "Cancelando..."
2884
+ cancel: "Cancelando...",
2885
+ undetermined: "no se pudo determinar",
2886
+ undeterminedCount: "no se pudieron determinar",
2887
+ undeterminedTotal: "indeterminados",
2888
+ detailHint: "D detalle \xB7 R re-escanear \xB7 Q salir",
2889
+ detailBack: "\u2191\u2193 recorrer \xB7 D volver al resumen \xB7 Q salir",
2890
+ noChanges: "Ninguna corrida cambi\xF3 paquetes."
2551
2891
  }
2552
2892
  };
2553
2893
 
@@ -2714,6 +3054,7 @@ var en = {
2714
3054
  confirm: "Confirm",
2715
3055
  updating: "Updating",
2716
3056
  summary: "Summary",
3057
+ detail: "Per-package detail",
2717
3058
  settings: "Settings"
2718
3059
  },
2719
3060
  status: {
@@ -2725,7 +3066,8 @@ var en = {
2725
3066
  running: "UPDATING",
2726
3067
  done: "OK",
2727
3068
  failed: "ERROR",
2728
- skipped: "MANUAL"
3069
+ skipped: "MANUAL",
3070
+ unknown: "UNDETERMINED"
2729
3071
  },
2730
3072
  ui: {
2731
3073
  detecting: "Detecting package managers...",
@@ -2746,7 +3088,13 @@ var en = {
2746
3088
  passwordNote: 'If a "Password:" prompt appears below, it is a manager (e.g. a brew cask): type it and Enter.',
2747
3089
  summaryHint: "R rescan \xB7 Q quit",
2748
3090
  elapsed: "elapsed",
2749
- cancel: "Cancelling..."
3091
+ cancel: "Cancelling...",
3092
+ undetermined: "could not be determined",
3093
+ undeterminedCount: "could not be determined",
3094
+ undeterminedTotal: "undetermined",
3095
+ detailHint: "D detail \xB7 R rescan \xB7 Q quit",
3096
+ detailBack: "\u2191\u2193 scroll \xB7 D back to summary \xB7 Q quit",
3097
+ noChanges: "No run changed any package."
2750
3098
  }
2751
3099
  };
2752
3100
 
@@ -2774,11 +3122,11 @@ function managerName(id) {
2774
3122
  }
2775
3123
 
2776
3124
  // src/hooks/use-app-machine.tsx
2777
- import { writeFileSync, mkdirSync } from "fs";
3125
+ import { writeFileSync as writeFileSync2, mkdirSync as mkdirSync2 } from "fs";
2778
3126
  import { dirname } from "path";
2779
3127
 
2780
3128
  // src/lib/elevation.ts
2781
- import path3 from "path";
3129
+ import path4 from "path";
2782
3130
  import { execa as execa3 } from "execa";
2783
3131
  import isAdmin from "is-admin";
2784
3132
  async function isElevated() {
@@ -2793,7 +3141,7 @@ async function isElevated() {
2793
3141
  }
2794
3142
  function elevatedSummaryPath() {
2795
3143
  const base = process.env["LOCALAPPDATA"] ?? process.env["TEMP"] ?? process.cwd();
2796
- return path3.join(base, "tacuchi-updater", "last-run-summary.json");
3144
+ return path4.join(base, "tacuchi-updater", "last-run-summary.json");
2797
3145
  }
2798
3146
  var psQuote = (s) => `'${s.replace(/'/g, "''")}'`;
2799
3147
  async function relaunchElevated(extraArgs = []) {
@@ -2828,6 +3176,131 @@ function fireProcessCancel() {
2828
3176
  }
2829
3177
  }
2830
3178
 
3179
+ // src/lib/run-closure.ts
3180
+ var provider = null;
3181
+ var settled = false;
3182
+ function registerRunSummary(fn) {
3183
+ provider = fn;
3184
+ return () => {
3185
+ if (provider === fn) provider = null;
3186
+ };
3187
+ }
3188
+ function settleRun(mode, detail) {
3189
+ if (settled) return false;
3190
+ settled = true;
3191
+ let summary = null;
3192
+ try {
3193
+ summary = provider?.() ?? null;
3194
+ } catch {
3195
+ summary = null;
3196
+ }
3197
+ logRunClosure(mode, summary, detail);
3198
+ closeLogger();
3199
+ return true;
3200
+ }
3201
+
3202
+ // src/lib/self-update.ts
3203
+ import { readFileSync, writeFileSync, mkdirSync, existsSync } from "fs";
3204
+ import path5 from "path";
3205
+ var DAY_MS = 24 * 60 * 60 * 1e3;
3206
+ var PACKAGE2 = "@tacuchi/updater";
3207
+ function isNewer(current, candidate) {
3208
+ const parse = (v) => (v.split("-")[0] ?? "").split(".").map((n) => Number.parseInt(n, 10) || 0);
3209
+ const a = parse(current);
3210
+ const b = parse(candidate);
3211
+ for (let i = 0; i < 3; i += 1) {
3212
+ const left = a[i] ?? 0;
3213
+ const right = b[i] ?? 0;
3214
+ if (right > left) return true;
3215
+ if (right < left) return false;
3216
+ }
3217
+ return false;
3218
+ }
3219
+ function selfCheckStatePath() {
3220
+ return path5.join(getConfigDir(), "self-check.json");
3221
+ }
3222
+ function readStateFromDisk() {
3223
+ try {
3224
+ const raw = readFileSync(selfCheckStatePath(), "utf-8");
3225
+ const parsed = JSON.parse(raw);
3226
+ if (typeof parsed.lastCheckedAt !== "number") return null;
3227
+ return { lastCheckedAt: parsed.lastCheckedAt, latest: parsed.latest };
3228
+ } catch {
3229
+ return null;
3230
+ }
3231
+ }
3232
+ function writeStateToDisk(state) {
3233
+ try {
3234
+ const dir = getConfigDir();
3235
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
3236
+ writeFileSync(selfCheckStatePath(), JSON.stringify(state, null, 2), "utf-8");
3237
+ } catch {
3238
+ }
3239
+ }
3240
+ async function fetchLatestFromRegistry() {
3241
+ const res = await fetch(`https://registry.npmjs.org/${PACKAGE2}/latest`, {
3242
+ signal: AbortSignal.timeout(4e3)
3243
+ });
3244
+ if (!res.ok) throw new Error(`registro respondi\xF3 ${res.status}`);
3245
+ const body = await res.json();
3246
+ if (!body.version) throw new Error("el registro no devolvi\xF3 version");
3247
+ return body.version;
3248
+ }
3249
+ var defaultSelfCheckDeps = {
3250
+ now: () => Date.now(),
3251
+ fetchLatest: fetchLatestFromRegistry,
3252
+ readState: readStateFromDisk,
3253
+ writeState: writeStateToDisk
3254
+ };
3255
+ async function checkForNewerSelf(current, enabled, deps = defaultSelfCheckDeps) {
3256
+ if (!enabled) return { newer: null, queried: false };
3257
+ const state = deps.readState();
3258
+ const fresh = state !== null && deps.now() - state.lastCheckedAt < DAY_MS;
3259
+ if (fresh) {
3260
+ const cached2 = state.latest;
3261
+ const newer = cached2 && isNewer(current, cached2) ? cached2 : null;
3262
+ return newer ? { newer, queried: false, howTo: howToUpgrade(newer) } : { newer: null, queried: false };
3263
+ }
3264
+ try {
3265
+ const latest = await deps.fetchLatest();
3266
+ deps.writeState({ lastCheckedAt: deps.now(), latest });
3267
+ if (!isNewer(current, latest)) {
3268
+ debug(`Auto-chequeo: ${current} est\xE1 al d\xEDa (latest=${latest})`);
3269
+ return { newer: null, queried: true };
3270
+ }
3271
+ log(`Auto-chequeo: hay una versi\xF3n m\xE1s nueva del updater (${current} \u2192 ${latest})`);
3272
+ return { newer: latest, queried: true, howTo: howToUpgrade(latest) };
3273
+ } catch (err) {
3274
+ warn(`Auto-chequeo: no se pudo consultar la versi\xF3n m\xE1s nueva (${String(err)})`);
3275
+ return { newer: null, queried: true };
3276
+ }
3277
+ }
3278
+ function howToUpgrade(version) {
3279
+ return `npm i -g ${PACKAGE2}@${version}`;
3280
+ }
3281
+
3282
+ // src/lib/version.ts
3283
+ import { readFileSync as readFileSync2 } from "fs";
3284
+ import { fileURLToPath } from "url";
3285
+ import path6 from "path";
3286
+ var cached = null;
3287
+ function getVersion() {
3288
+ if (cached !== null) return cached;
3289
+ const here = path6.dirname(fileURLToPath(import.meta.url));
3290
+ for (const rel of ["../package.json", "../../package.json"]) {
3291
+ try {
3292
+ const pkg = JSON.parse(readFileSync2(path6.join(here, rel), "utf-8"));
3293
+ if (pkg.version) {
3294
+ cached = pkg.version;
3295
+ return cached;
3296
+ }
3297
+ } catch {
3298
+ }
3299
+ }
3300
+ cached = "0.0.0";
3301
+ return cached;
3302
+ }
3303
+
2831
3304
  // src/hooks/use-app-machine.tsx
2832
3305
  import { jsx } from "react/jsx-runtime";
2833
3306
  function toManagerResult(r, logRef) {
@@ -2858,6 +3331,7 @@ function summarizeRun(state) {
2858
3331
  let upgraded = 0;
2859
3332
  let failed = 0;
2860
3333
  let skipped = 0;
3334
+ let unknown = 0;
2861
3335
  const managers = [];
2862
3336
  for (const id of state.run.queue) {
2863
3337
  const e = state.managers[id];
@@ -2867,6 +3341,11 @@ function summarizeRun(state) {
2867
3341
  managers.push({ id, status: "skipped", upgraded: 0, failed: 0 });
2868
3342
  continue;
2869
3343
  }
3344
+ if (e.status === "unknown") {
3345
+ unknown++;
3346
+ managers.push({ id, status: "unknown", upgraded: 0, failed: 0 });
3347
+ continue;
3348
+ }
2870
3349
  const r = e.result;
2871
3350
  const u = r?.upgraded ?? 0;
2872
3351
  const f = r?.failed ?? 0;
@@ -2875,7 +3354,7 @@ function summarizeRun(state) {
2875
3354
  const durationMs = r?.startedAt !== void 0 && r?.finishedAt !== void 0 ? r.finishedAt - r.startedAt : void 0;
2876
3355
  managers.push({ id, status: e.status, upgraded: u, failed: f, durationMs, packages: r?.packages });
2877
3356
  }
2878
- return { upgraded, failed, skipped, managers };
3357
+ return { upgraded, failed, skipped, unknown, managers };
2879
3358
  }
2880
3359
  var MachineContext = createContext(null);
2881
3360
  function useMachine() {
@@ -2892,6 +3371,7 @@ function useAppMachine(sudoMode2, nonInteractive2 = false) {
2892
3371
  );
2893
3372
  const detectedRef = useRef([]);
2894
3373
  const abortRef = useRef(null);
3374
+ const runLogRef = useRef(null);
2895
3375
  const boot = useCallback(async () => {
2896
3376
  const config = configRef.current;
2897
3377
  dispatch({ type: "BOOT_DONE" });
@@ -2904,11 +3384,13 @@ function useAppMachine(sudoMode2, nonInteractive2 = false) {
2904
3384
  id: d.manager.id,
2905
3385
  group: d.manager.group ?? "language",
2906
3386
  requiresAdmin: d.manager.requiresAdmin,
2907
- version: d.detection.version
3387
+ version: d.detection.version,
3388
+ undetermined: d.detection.undetermined === true
2908
3389
  }))
2909
3390
  });
2910
3391
  await Promise.allSettled(
2911
3392
  detected.map(async (dm) => {
3393
+ if (dm.detection.undetermined) return;
2912
3394
  if (!isManagerEnabled(config, dm.manager.id)) {
2913
3395
  dispatch({ type: "SCAN_MANAGER_DONE", id: dm.manager.id, outdated: [] });
2914
3396
  return;
@@ -2918,7 +3400,9 @@ function useAppMachine(sudoMode2, nonInteractive2 = false) {
2918
3400
  const outdated = await dm.manager.listOutdated();
2919
3401
  dispatch({ type: "SCAN_MANAGER_DONE", id: dm.manager.id, outdated });
2920
3402
  } catch (err) {
2921
- error(`Error escaneando ${dm.manager.id}: ${String(err)}`);
3403
+ if (!(err instanceof ListingUnavailableError)) {
3404
+ error(`Error escaneando ${dm.manager.id}: ${String(err)}`);
3405
+ }
2922
3406
  dispatch({ type: "SCAN_MANAGER_FAILED", id: dm.manager.id });
2923
3407
  }
2924
3408
  })
@@ -2926,14 +3410,28 @@ function useAppMachine(sudoMode2, nonInteractive2 = false) {
2926
3410
  dispatch({ type: "SCAN_ALL_DONE" });
2927
3411
  } catch (err) {
2928
3412
  dispatch({ type: "DETECT_FAILED", error: String(err) });
3413
+ settleRun("fallida", `detecci\xF3n: ${String(err)}`);
2929
3414
  }
2930
3415
  }, []);
2931
3416
  useEffect(() => {
2932
- initLogger();
3417
+ initLogger(configRef.current.logRetentionRuns);
2933
3418
  setLanguage(configRef.current.language);
2934
3419
  void boot();
2935
3420
  }, [boot]);
3421
+ const [selfUpdate, setSelfUpdate] = useState(null);
3422
+ useEffect(() => {
3423
+ let alive = true;
3424
+ void checkForNewerSelf(getVersion(), configRef.current.selfCheck).then((outcome) => {
3425
+ if (alive && outcome.newer && outcome.howTo) {
3426
+ setSelfUpdate({ version: outcome.newer, howTo: outcome.howTo });
3427
+ }
3428
+ });
3429
+ return () => {
3430
+ alive = false;
3431
+ };
3432
+ }, []);
2936
3433
  useEffect(() => onProcessCancel(() => abortRef.current?.abort()), []);
3434
+ useEffect(() => registerRunSummary(() => runLogRef.current), []);
2937
3435
  const startRun = useCallback(() => {
2938
3436
  const config = configRef.current;
2939
3437
  const packagesByManager = /* @__PURE__ */ new Map();
@@ -2945,10 +3443,52 @@ function useAppMachine(sudoMode2, nonInteractive2 = false) {
2945
3443
  }
2946
3444
  const tasks = detectedRef.current.filter((dm) => packagesByManager.has(dm.manager.id)).map((dm) => ({ manager: dm.manager, op: "upgrade", packages: packagesByManager.get(dm.manager.id) }));
2947
3445
  if (tasks.length === 0) return;
2948
- dispatch({ type: "RUN_START", queue: tasks.map((t3) => t3.manager.id) });
3446
+ const queue = tasks.map((t3) => t3.manager.id);
3447
+ logSelection({
3448
+ offered: state.order.reduce((n, id) => n + (state.managers[id]?.outdated.length ?? 0), 0),
3449
+ chosen: state.selection.size,
3450
+ managers: state.order.filter((id) => (state.managers[id]?.outdated.length ?? 0) > 0).map((id) => ({
3451
+ id,
3452
+ offered: state.managers[id]?.outdated.length ?? 0,
3453
+ chosen: packagesByManager.get(id)?.length ?? 0
3454
+ }))
3455
+ });
3456
+ dispatch({ type: "RUN_START", queue });
2949
3457
  const ac = new AbortController();
2950
3458
  abortRef.current = ac;
2951
3459
  const logRef = getLogFilePath() ?? void 0;
3460
+ const settledResults = /* @__PURE__ */ new Map();
3461
+ const skippedIds = /* @__PURE__ */ new Set();
3462
+ const rebuildRunLog = () => {
3463
+ let upgraded = 0;
3464
+ let failed = 0;
3465
+ let skipped = 0;
3466
+ let unknownTotal = 0;
3467
+ const managers = queue.map((id) => {
3468
+ if (skippedIds.has(id)) {
3469
+ skipped++;
3470
+ return { id, status: "noop", upgraded: 0, failed: 0 };
3471
+ }
3472
+ const r = settledResults.get(id);
3473
+ if (!r) {
3474
+ unknownTotal++;
3475
+ return { id, status: "unknown", upgraded: 0, failed: 0 };
3476
+ }
3477
+ if (r.status === "unknown") unknownTotal++;
3478
+ upgraded += r.upgraded;
3479
+ failed += r.failed;
3480
+ const durationMs = r.startedAt !== void 0 && r.finishedAt !== void 0 ? r.finishedAt - r.startedAt : void 0;
3481
+ return {
3482
+ id,
3483
+ status: r.status ?? (r.success ? "success" : "failed"),
3484
+ upgraded: r.upgraded,
3485
+ failed: r.failed,
3486
+ durationMs
3487
+ };
3488
+ });
3489
+ runLogRef.current = { upgraded, failed, skipped, unknown: unknownTotal, managers };
3490
+ };
3491
+ rebuildRunLog();
2952
3492
  let pending = [];
2953
3493
  let scheduled = false;
2954
3494
  const flush = () => {
@@ -2973,12 +3513,17 @@ function useAppMachine(sudoMode2, nonInteractive2 = false) {
2973
3513
  if (e.event?.percent !== void 0) {
2974
3514
  enqueue({ type: "MGR_PROGRESS", id, percent: e.event.percent });
2975
3515
  } else if (!e.event) {
2976
- enqueue({ type: "MGR_RUNNING", id });
3516
+ enqueue({ type: "MGR_RUNNING", id, at: Date.now() });
2977
3517
  }
2978
3518
  } else if (e.phase === "done" && e.result) {
2979
3519
  const r = e.result;
3520
+ settledResults.set(id, r);
3521
+ if (r.status === "noop" && r.manualCommand) skippedIds.add(id);
3522
+ rebuildRunLog();
2980
3523
  if (r.status === "noop" && r.manualCommand) {
2981
3524
  enqueue({ type: "MGR_SKIPPED", id, manualCommand: r.manualCommand });
3525
+ } else if (r.status === "unknown") {
3526
+ enqueue({ type: "MGR_UNKNOWN", id, result: toManagerResult(r, logRef) });
2982
3527
  } else if (r.success || r.status === "success" || r.status === "partial") {
2983
3528
  enqueue({ type: "MGR_DONE", id, result: toManagerResult(r, logRef) });
2984
3529
  } else {
@@ -2986,16 +3531,23 @@ function useAppMachine(sudoMode2, nonInteractive2 = false) {
2986
3531
  }
2987
3532
  }
2988
3533
  };
3534
+ let engineError = null;
2989
3535
  void runEngine(tasks, {
2990
3536
  concurrency: config.concurrency,
2991
3537
  signal: ac.signal,
2992
3538
  sudoMode: sudoMode2,
2993
3539
  timeoutsMs: config.timeoutsMs,
2994
3540
  onEvent
3541
+ }).catch((err) => {
3542
+ engineError = err;
3543
+ error(`El motor termin\xF3 con error: ${String(err)}`);
2995
3544
  }).finally(() => {
2996
3545
  flush();
2997
3546
  dispatch({ type: "RUN_DONE" });
2998
3547
  abortRef.current = null;
3548
+ if (ac.signal.aborted) settleRun("cancelada", "corrida abortada en vuelo");
3549
+ else if (engineError !== null) settleRun("fallida", `motor: ${String(engineError)}`);
3550
+ else settleRun("completa");
2999
3551
  });
3000
3552
  }, [state.selection, sudoMode2]);
3001
3553
  const cancelRun = useCallback(() => {
@@ -3013,6 +3565,7 @@ function useAppMachine(sudoMode2, nonInteractive2 = false) {
3013
3565
  if (exitedRef.current) return;
3014
3566
  exitedRef.current = true;
3015
3567
  process.exitCode = code;
3568
+ settleRun("completa");
3016
3569
  exit();
3017
3570
  if (!process.env["VITEST"]) {
3018
3571
  const t3 = setTimeout(() => process.exit(code), 100);
@@ -3047,20 +3600,17 @@ function useAppMachine(sudoMode2, nonInteractive2 = false) {
3047
3600
  if (state.phase !== "summary" || process.platform !== "win32") return;
3048
3601
  try {
3049
3602
  const p = elevatedSummaryPath();
3050
- mkdirSync(dirname(p), { recursive: true });
3051
- writeFileSync(p, JSON.stringify({ ...summarizeRun(state), at: Date.now() }, null, 2), "utf-8");
3603
+ mkdirSync2(dirname(p), { recursive: true });
3604
+ writeFileSync2(p, JSON.stringify({ ...summarizeRun(state), at: Date.now() }, null, 2), "utf-8");
3052
3605
  } catch {
3053
3606
  }
3054
3607
  }, [state.phase]);
3055
- useEffect(() => {
3056
- if (state.phase !== "summary") return;
3057
- logRunSummary(summarizeRun(state));
3058
- }, [state.phase]);
3059
3608
  const relaunch = useCallback(() => {
3060
3609
  void (async () => {
3061
3610
  const ok = await relaunchElevated();
3062
3611
  if (ok) {
3063
3612
  process.exitCode = 0;
3613
+ settleRun("cedida", "consola elevada");
3064
3614
  exit();
3065
3615
  if (!process.env["VITEST"]) {
3066
3616
  const t3 = setTimeout(() => process.exit(0), 100);
@@ -3069,6 +3619,17 @@ function useAppMachine(sudoMode2, nonInteractive2 = false) {
3069
3619
  }
3070
3620
  })();
3071
3621
  }, [exit]);
3622
+ const quitApp = useCallback(() => {
3623
+ const inFlight = abortRef.current !== null;
3624
+ abortRef.current?.abort();
3625
+ settleRun("cancelada", inFlight ? "tecla de salida con corrida en vuelo" : "tecla de salida");
3626
+ const code = inFlight ? 130 : 0;
3627
+ process.exitCode = code;
3628
+ exit();
3629
+ if (!process.env["VITEST"]) {
3630
+ setTimeout(() => process.exit(code), 200);
3631
+ }
3632
+ }, [exit]);
3072
3633
  const persist = useCallback((next) => {
3073
3634
  dispatch(next);
3074
3635
  }, []);
@@ -3097,10 +3658,14 @@ function useAppMachine(sudoMode2, nonInteractive2 = false) {
3097
3658
  cancelRun,
3098
3659
  relaunch,
3099
3660
  rescan,
3661
+ openDetail: useCallback(() => persist({ type: "OPEN_DETAIL" }), [persist]),
3662
+ closeDetail: useCallback(() => persist({ type: "CLOSE_DETAIL" }), [persist]),
3100
3663
  openSettings: useCallback(() => persist({ type: "OPEN_SETTINGS" }), [persist]),
3101
3664
  closeSettings: useCallback(() => persist({ type: "CLOSE_SETTINGS" }), [persist]),
3102
3665
  setLang,
3103
- toggleEnabled
3666
+ toggleEnabled,
3667
+ quitApp,
3668
+ selfUpdate
3104
3669
  };
3105
3670
  }
3106
3671
  function MachineProvider({ value, children }) {
@@ -3111,7 +3676,7 @@ function MachineProvider({ value, children }) {
3111
3676
  import { useInput, useStdin } from "ink";
3112
3677
  function useSafeInput(handler, options) {
3113
3678
  const { isRawModeSupported } = useStdin();
3114
- const active = (options?.isActive ?? true) && isRawModeSupported;
3679
+ const active = (options?.isActive ?? true) && isRawModeSupported === true;
3115
3680
  useInput(handler, { ...options, isActive: active });
3116
3681
  }
3117
3682
 
@@ -3153,6 +3718,8 @@ var colors = {
3153
3718
  // Texto
3154
3719
  onSurface: "#e5e2e1",
3155
3720
  onSurfaceVariant: "#a09d9c",
3721
+ // Ámbar — reservado al estado «no se pudo determinar»
3722
+ unknown: "#f0b429",
3156
3723
  // Bordes
3157
3724
  outlineVariant: "#484556",
3158
3725
  outline: "#6f6d70"
@@ -3166,6 +3733,10 @@ var semantic = {
3166
3733
  // rojo
3167
3734
  warning: colors.secondary,
3168
3735
  // rosa (admin / skipped / atención)
3736
+ // Ámbar — «no se pudo determinar». NO puede reusar `muted`, que hoy significa
3737
+ // «al día»: eso es exactamente confundir «no lo sé» con «está bien»
3738
+ // (DES-001@r1). Se distingue a la vez del rosa de advertencia y del gris.
3739
+ unknown: colors.unknown,
3169
3740
  text: colors.onSurface,
3170
3741
  muted: colors.onSurfaceVariant
3171
3742
  };
@@ -3187,6 +3758,7 @@ var UNICODE = {
3187
3758
  done: "\u2713",
3188
3759
  failed: "\u2717",
3189
3760
  skipped: "\u2298",
3761
+ unknown: "?",
3190
3762
  cursor: "\u276F",
3191
3763
  checkOn: "[\u2713]",
3192
3764
  checkOff: "[ ]",
@@ -3209,6 +3781,7 @@ var ASCII_GLYPHS = {
3209
3781
  done: "+",
3210
3782
  failed: "x",
3211
3783
  skipped: "-",
3784
+ unknown: "?",
3212
3785
  cursor: ">",
3213
3786
  checkOn: "[x]",
3214
3787
  checkOff: "[ ]",
@@ -3246,6 +3819,13 @@ function StepHeader({ phase }) {
3246
3819
  t("flow", "summary")
3247
3820
  ] }) });
3248
3821
  }
3822
+ if (phase === "detail") {
3823
+ return /* @__PURE__ */ jsx2(Box, { marginBottom: 1, children: /* @__PURE__ */ jsxs(Text, { color: semantic.action, bold: true, children: [
3824
+ g.stepOn,
3825
+ " ",
3826
+ t("flow", "detail")
3827
+ ] }) });
3828
+ }
3249
3829
  if (phase === "settings") {
3250
3830
  return /* @__PURE__ */ jsx2(Box, { marginBottom: 1, children: /* @__PURE__ */ jsxs(Text, { color: semantic.action, bold: true, children: [
3251
3831
  g.stepOn,
@@ -3273,7 +3853,7 @@ function StepHeader({ phase }) {
3273
3853
  }
3274
3854
 
3275
3855
  // src/components/status-glyph.tsx
3276
- import { useEffect as useEffect2, useState } from "react";
3856
+ import { useEffect as useEffect2, useState as useState2 } from "react";
3277
3857
  import { Text as Text2 } from "ink";
3278
3858
  import { jsx as jsx3 } from "react/jsx-runtime";
3279
3859
  var SPECS = {
@@ -3285,7 +3865,12 @@ var SPECS = {
3285
3865
  running: { glyph: g.running, color: semantic.action },
3286
3866
  done: { glyph: g.done, color: semantic.success },
3287
3867
  failed: { glyph: g.failed, color: semantic.error },
3288
- skipped: { glyph: g.skipped, color: semantic.warning }
3868
+ skipped: { glyph: g.skipped, color: semantic.warning },
3869
+ // Amber and a one-cell `?`: it cannot reuse `muted`, which is the colour of
3870
+ // "up to date" — the confusion this state exists to remove (DES-001@r1). The
3871
+ // spec lands here with the domain state because this table is exhaustive over
3872
+ // ManagerStatus, so the state cannot exist without it.
3873
+ unknown: { glyph: g.unknown, color: semantic.unknown }
3289
3874
  };
3290
3875
  function statusColor(status) {
3291
3876
  return SPECS[status].color;
@@ -3295,7 +3880,7 @@ function StatusGlyph({ status }) {
3295
3880
  return /* @__PURE__ */ jsx3(Text2, { color: spec.color, children: spec.glyph });
3296
3881
  }
3297
3882
  function RunningGlyph() {
3298
- const [i, setI] = useState(0);
3883
+ const [i, setI] = useState2(0);
3299
3884
  useEffect2(() => {
3300
3885
  if (NO_ANIM) return;
3301
3886
  const t3 = setInterval(() => setI((n) => (n + 1) % spinnerFrames.length), 90);
@@ -3312,7 +3897,7 @@ function DetectScreen() {
3312
3897
  const scanning = state.phase === "scanning";
3313
3898
  const done = state.order.filter((id) => {
3314
3899
  const s = state.managers[id]?.status;
3315
- return s === "outdated" || s === "uptodate";
3900
+ return s === "outdated" || s === "uptodate" || s === "unknown";
3316
3901
  }).length;
3317
3902
  return /* @__PURE__ */ jsxs2(Box2, { flexDirection: "column", children: [
3318
3903
  /* @__PURE__ */ jsx4(StepHeader, { phase: state.phase }),
@@ -3337,14 +3922,14 @@ function DetectScreen() {
3337
3922
  e.outdated.length,
3338
3923
  " ",
3339
3924
  g.outdated
3340
- ] }) : e.status === "uptodate" ? /* @__PURE__ */ jsx4(Text3, { color: colors.outline, children: "-" }) : /* @__PURE__ */ jsx4(Text3, { color: semantic.muted, children: g.ellipsis })
3925
+ ] }) : e.status === "uptodate" ? /* @__PURE__ */ jsx4(Text3, { color: colors.outline, children: "-" }) : e.status === "unknown" ? /* @__PURE__ */ jsx4(Text3, { color: semantic.unknown, children: t("ui", "undetermined") }) : /* @__PURE__ */ jsx4(Text3, { color: semantic.muted, children: g.ellipsis })
3341
3926
  ] }, id);
3342
3927
  })
3343
3928
  ] });
3344
3929
  }
3345
3930
 
3346
3931
  // src/screens/select.tsx
3347
- import { useState as useState2 } from "react";
3932
+ import { useState as useState3 } from "react";
3348
3933
  import { Box as Box3, Text as Text4 } from "ink";
3349
3934
  import { jsx as jsx5, jsxs as jsxs3 } from "react/jsx-runtime";
3350
3935
  function clip(s, n) {
@@ -3352,13 +3937,14 @@ function clip(s, n) {
3352
3937
  }
3353
3938
  function SelectScreen() {
3354
3939
  const { state, toggleItem, selectAll, selectNone, goConfirm, openSettings } = useMachine();
3355
- const [cursor, setCursor] = useState2(0);
3940
+ const [cursor, setCursor] = useState3(0);
3356
3941
  const rows = [];
3357
3942
  for (const id of state.order) {
3358
3943
  const m = state.managers[id];
3359
3944
  if (m && m.status === "outdated") for (const pkg of m.outdated) rows.push({ managerId: id, pkg });
3360
3945
  }
3361
3946
  const clamped = Math.min(cursor, Math.max(0, rows.length - 1));
3947
+ const undetermined = state.order.filter((id) => state.managers[id]?.status === "unknown");
3362
3948
  useSafeInput((input, key) => {
3363
3949
  if (key.downArrow || input === "j") setCursor((c) => Math.min(rows.length - 1, c + 1));
3364
3950
  else if (key.upArrow || input === "k") setCursor((c) => Math.max(0, c - 1));
@@ -3377,6 +3963,16 @@ function SelectScreen() {
3377
3963
  "\u2713 ",
3378
3964
  t("ui", "noUpdates")
3379
3965
  ] }),
3966
+ undetermined.length > 0 && /* @__PURE__ */ jsxs3(Text4, { color: semantic.unknown, children: [
3967
+ g.unknown,
3968
+ " ",
3969
+ undetermined.length,
3970
+ " ",
3971
+ t("ui", "undeterminedCount"),
3972
+ ":",
3973
+ " ",
3974
+ undetermined.map((id) => managerName(id)).join(", ")
3975
+ ] }),
3380
3976
  /* @__PURE__ */ jsx5(Box3, { marginTop: 1, children: /* @__PURE__ */ jsxs3(Text4, { color: semantic.muted, children: [
3381
3977
  "R ",
3382
3978
  t("flow", "detecting"),
@@ -3403,6 +3999,16 @@ function SelectScreen() {
3403
3999
  t("ui", "selected")
3404
4000
  ] })
3405
4001
  ] }),
4002
+ undetermined.length > 0 && /* @__PURE__ */ jsx5(Box3, { marginBottom: 1, children: /* @__PURE__ */ jsxs3(Text4, { color: semantic.unknown, children: [
4003
+ g.unknown,
4004
+ " ",
4005
+ undetermined.length,
4006
+ " ",
4007
+ t("ui", "undeterminedCount"),
4008
+ ":",
4009
+ " ",
4010
+ undetermined.map((id) => managerName(id)).join(", ")
4011
+ ] }) }),
3406
4012
  start > 0 && /* @__PURE__ */ jsxs3(Text4, { color: colors.outline, children: [
3407
4013
  g.scrollUp,
3408
4014
  " ",
@@ -3479,21 +4085,40 @@ function ConfirmScreen() {
3479
4085
  }
3480
4086
 
3481
4087
  // src/screens/update.tsx
4088
+ import { useEffect as useEffect3, useState as useState4 } from "react";
3482
4089
  import { Box as Box5, Text as Text6 } from "ink";
3483
- import { jsx as jsx7, jsxs as jsxs5 } from "react/jsx-runtime";
4090
+ import { Fragment, jsx as jsx7, jsxs as jsxs5 } from "react/jsx-runtime";
3484
4091
  function clip2(s, n) {
3485
4092
  return s.length > n ? s.slice(0, Math.max(0, n - g.ellipsis.length)) + g.ellipsis : s;
3486
4093
  }
4094
+ function formatElapsed(ms) {
4095
+ const total = Math.max(0, Math.floor(ms / 1e3));
4096
+ const s = total % 60;
4097
+ const m = Math.floor(total / 60) % 60;
4098
+ const h = Math.floor(total / 3600);
4099
+ if (h > 0) return `${h}h${String(m).padStart(2, "0")}m`;
4100
+ if (m > 0) return `${m}m${String(s).padStart(2, "0")}s`;
4101
+ return `${s}s`;
4102
+ }
4103
+ function Elapsed({ startedAt }) {
4104
+ const [now, setNow] = useState4(() => Date.now());
4105
+ useEffect3(() => {
4106
+ const timer = setInterval(() => setNow(Date.now()), 1e3);
4107
+ return () => clearInterval(timer);
4108
+ }, []);
4109
+ return /* @__PURE__ */ jsx7(Fragment, { children: formatElapsed(now - startedAt) });
4110
+ }
3487
4111
  function Row({ e, width }) {
3488
4112
  let detail = "";
3489
- if (e.status === "running") detail = e.percent > 0 ? `${e.percent}%` : "";
4113
+ if (e.status === "running") detail = "";
3490
4114
  else if (e.status === "skipped") detail = e.manualCommand ?? "manual";
3491
4115
  else if (e.status === "failed") detail = e.result?.failures[0]?.message ?? "";
4116
+ else if (e.status === "unknown") detail = e.result?.failures[0]?.message ?? t("ui", "undetermined");
3492
4117
  return /* @__PURE__ */ jsxs5(Box5, { children: [
3493
4118
  /* @__PURE__ */ jsx7(Box5, { width: 2, children: e.status === "running" ? /* @__PURE__ */ jsx7(RunningGlyph, {}) : /* @__PURE__ */ jsx7(StatusGlyph, { status: e.status }) }),
3494
4119
  /* @__PURE__ */ jsx7(Box5, { width: 16, children: /* @__PURE__ */ jsx7(Text6, { color: semantic.text, bold: e.status === "running", children: clip2(managerName(e.id), 15) }) }),
3495
4120
  /* @__PURE__ */ jsx7(Box5, { width: 13, children: /* @__PURE__ */ jsx7(Text6, { color: statusColor(e.status), children: t("status", e.status) }) }),
3496
- /* @__PURE__ */ jsx7(Text6, { color: semantic.muted, children: clip2(detail, Math.max(0, width - 33)) })
4121
+ /* @__PURE__ */ jsx7(Text6, { color: semantic.muted, children: e.status === "running" ? e.percent > 0 ? `${e.percent}%` : e.startedAt !== void 0 && e.startedAt > 0 ? /* @__PURE__ */ jsx7(Elapsed, { startedAt: e.startedAt }) : "" : clip2(detail, Math.max(0, width - 33)) })
3497
4122
  ] });
3498
4123
  }
3499
4124
  function UpdateScreen() {
@@ -3502,7 +4127,7 @@ function UpdateScreen() {
3502
4127
  if (key.escape) cancelRun();
3503
4128
  });
3504
4129
  const total = state.run.queue.length;
3505
- const finished = state.run.doneCount + state.run.failedCount + state.run.skippedCount;
4130
+ const finished = state.run.doneCount + state.run.failedCount + state.run.skippedCount + state.run.unknownCount;
3506
4131
  const width = Math.min((process.stdout.columns ?? 90) - 4, 92);
3507
4132
  return /* @__PURE__ */ jsxs5(Box5, { flexDirection: "column", children: [
3508
4133
  /* @__PURE__ */ jsx7(StepHeader, { phase: state.phase }),
@@ -3546,10 +4171,13 @@ function UpdateScreen() {
3546
4171
  import { Box as Box6, Text as Text7 } from "ink";
3547
4172
  import { jsx as jsx8, jsxs as jsxs6 } from "react/jsx-runtime";
3548
4173
  function versionDelta(m) {
3549
- const ups = (m.packages ?? []).filter((p2) => p2.outcome === "upgraded" && p2.toVersion);
3550
- if (ups.length !== 1) return "";
3551
- const p = ups[0];
3552
- return p.fromVersion ? `${p.name} ${p.fromVersion} ${g.arrow} ${p.toVersion}` : `${p.name} ${g.arrow} ${p.toVersion}`;
4174
+ const ups = (m.packages ?? []).filter((p) => p.outcome === "upgraded" && p.toVersion);
4175
+ if (ups.length === 0) return "";
4176
+ if (ups.length === 1) {
4177
+ const p = ups[0];
4178
+ return p.fromVersion ? `${p.name} ${p.fromVersion} ${g.arrow} ${p.toVersion}` : `${p.name} ${g.arrow} ${p.toVersion}`;
4179
+ }
4180
+ return `${ups.length} ${t("ui", "upgraded")}`;
3553
4181
  }
3554
4182
  function ManagerRow({ m }) {
3555
4183
  const dur = m.durationMs !== void 0 ? `${(m.durationMs / 1e3).toFixed(1)}s` : "";
@@ -3574,16 +4202,19 @@ function ManagerRow({ m }) {
3574
4202
  ] });
3575
4203
  }
3576
4204
  function SummaryScreen() {
3577
- const { state, rescan } = useMachine();
4205
+ const { state, rescan, openDetail } = useMachine();
3578
4206
  useSafeInput((input) => {
3579
4207
  if (input === "r" || input === "R") rescan();
4208
+ else if (input === "d" || input === "D") openDetail();
3580
4209
  });
3581
4210
  const summary = summarizeRun(state);
3582
- const { upgraded, failed, skipped } = summary;
4211
+ const { upgraded, failed, skipped, unknown } = summary;
3583
4212
  const hasErrors = failed > 0;
4213
+ const hasPackages = summary.managers.some((m) => (m.packages ?? []).length > 0);
3584
4214
  const failures = [];
3585
4215
  const manuals = [];
3586
4216
  const reboots = [];
4217
+ const undetermined = [];
3587
4218
  for (const id of state.run.queue) {
3588
4219
  const e = state.managers[id];
3589
4220
  if (!e) continue;
@@ -3591,6 +4222,10 @@ function SummaryScreen() {
3591
4222
  if (e.manualCommand) manuals.push({ manager: id, command: e.manualCommand });
3592
4223
  continue;
3593
4224
  }
4225
+ if (e.status === "unknown") {
4226
+ undetermined.push(id);
4227
+ continue;
4228
+ }
3594
4229
  const r = e.result;
3595
4230
  if (r) {
3596
4231
  for (const f of r.failures) failures.push({ manager: id, package: f.package, message: f.message, kind: f.kind });
@@ -3600,6 +4235,25 @@ function SummaryScreen() {
3600
4235
  return /* @__PURE__ */ jsxs6(Box6, { flexDirection: "column", children: [
3601
4236
  /* @__PURE__ */ jsx8(StepHeader, { phase: state.phase }),
3602
4237
  /* @__PURE__ */ jsx8(Box6, { marginBottom: 1, children: /* @__PURE__ */ jsx8(Text7, { color: hasErrors ? semantic.error : semantic.success, bold: true, children: hasErrors ? `${g.failed} ${t("ui", "withErrors")}` : `${g.done} ${t("ui", "allDone")}` }) }),
4238
+ undetermined.length > 0 && /* @__PURE__ */ jsx8(Box6, { flexDirection: "column", marginBottom: 1, children: /* @__PURE__ */ jsxs6(Text7, { color: semantic.unknown, children: [
4239
+ g.unknown,
4240
+ " ",
4241
+ undetermined.length,
4242
+ " ",
4243
+ t("ui", "undeterminedCount"),
4244
+ ":",
4245
+ " ",
4246
+ undetermined.map((id) => managerName(id)).join(", ")
4247
+ ] }) }),
4248
+ manuals.length > 0 && /* @__PURE__ */ jsxs6(Box6, { flexDirection: "column", marginBottom: 1, children: [
4249
+ /* @__PURE__ */ jsx8(Text7, { color: semantic.warning, children: t("ui", "manualNeeded") }),
4250
+ manuals.map((m, i) => /* @__PURE__ */ jsxs6(Text7, { color: semantic.muted, children: [
4251
+ " ",
4252
+ managerName(m.manager),
4253
+ ": ",
4254
+ /* @__PURE__ */ jsx8(Text7, { color: semantic.text, children: m.command })
4255
+ ] }, i))
4256
+ ] }),
3603
4257
  /* @__PURE__ */ jsxs6(Box6, { marginBottom: 1, children: [
3604
4258
  /* @__PURE__ */ jsxs6(Text7, { color: semantic.success, children: [
3605
4259
  upgraded,
@@ -3617,6 +4271,12 @@ function SummaryScreen() {
3617
4271
  skipped,
3618
4272
  " ",
3619
4273
  t("ui", "skipped")
4274
+ ] }),
4275
+ /* @__PURE__ */ jsx8(Text7, { color: semantic.muted, children: " \xB7 " }),
4276
+ /* @__PURE__ */ jsxs6(Text7, { color: unknown > 0 ? semantic.unknown : semantic.muted, children: [
4277
+ unknown,
4278
+ " ",
4279
+ t("ui", "undeterminedTotal")
3620
4280
  ] })
3621
4281
  ] }),
3622
4282
  summary.managers.length > 0 && /* @__PURE__ */ jsx8(Box6, { flexDirection: "column", marginBottom: 1, children: summary.managers.map((m) => /* @__PURE__ */ jsx8(ManagerRow, { m }, m.id)) }),
@@ -3639,15 +4299,6 @@ function SummaryScreen() {
3639
4299
  " Un TIMEOUT suele indicar un paquete que pide interacci\xF3n (ej. un cask que requiere cerrar la app o sudo). Actual\xEDzalo manualmente en una terminal."
3640
4300
  ] })
3641
4301
  ] }),
3642
- manuals.length > 0 && /* @__PURE__ */ jsxs6(Box6, { flexDirection: "column", marginBottom: 1, children: [
3643
- /* @__PURE__ */ jsx8(Text7, { color: semantic.warning, children: t("ui", "manualNeeded") }),
3644
- manuals.map((m, i) => /* @__PURE__ */ jsxs6(Text7, { color: semantic.muted, children: [
3645
- " ",
3646
- managerName(m.manager),
3647
- ": ",
3648
- /* @__PURE__ */ jsx8(Text7, { color: semantic.text, children: m.command })
3649
- ] }, i))
3650
- ] }),
3651
4302
  reboots.length > 0 && /* @__PURE__ */ jsx8(Box6, { marginBottom: 1, children: /* @__PURE__ */ jsxs6(Text7, { color: semantic.warning, children: [
3652
4303
  g.reboot,
3653
4304
  " Reinicio pendiente: ",
@@ -3658,18 +4309,18 @@ function SummaryScreen() {
3658
4309
  " ",
3659
4310
  getLogFilePath() ?? "~/.tacuchi-updater/logs/"
3660
4311
  ] }),
3661
- /* @__PURE__ */ jsx8(Box6, { marginTop: 1, children: /* @__PURE__ */ jsx8(Text7, { color: semantic.muted, children: t("ui", "summaryHint") }) })
4312
+ /* @__PURE__ */ jsx8(Box6, { marginTop: 1, children: /* @__PURE__ */ jsx8(Text7, { color: semantic.muted, children: hasPackages ? t("ui", "detailHint") : t("ui", "summaryHint") }) })
3662
4313
  ] });
3663
4314
  }
3664
4315
 
3665
4316
  // src/screens/settings-screen.tsx
3666
- import { useState as useState3 } from "react";
4317
+ import { useState as useState5 } from "react";
3667
4318
  import { Box as Box7, Text as Text8 } from "ink";
3668
4319
  import { jsx as jsx9, jsxs as jsxs7 } from "react/jsx-runtime";
3669
4320
  function SettingsScreen() {
3670
4321
  const { state, toggleEnabled, setLang, closeSettings } = useMachine();
3671
4322
  const ids = state.order;
3672
- const [cursor, setCursor] = useState3(0);
4323
+ const [cursor, setCursor] = useState5(0);
3673
4324
  const clamped = Math.min(cursor, Math.max(0, ids.length - 1));
3674
4325
  useSafeInput((input, key) => {
3675
4326
  if (key.escape) closeSettings();
@@ -3705,40 +4356,99 @@ function SettingsScreen() {
3705
4356
  ] });
3706
4357
  }
3707
4358
 
3708
- // src/lib/version.ts
3709
- import { readFileSync } from "fs";
3710
- import { fileURLToPath } from "url";
3711
- import path4 from "path";
3712
- var cached = null;
3713
- function getVersion() {
3714
- if (cached !== null) return cached;
3715
- const here = path4.dirname(fileURLToPath(import.meta.url));
3716
- for (const rel of ["../package.json", "../../package.json"]) {
3717
- try {
3718
- const pkg = JSON.parse(readFileSync(path4.join(here, rel), "utf-8"));
3719
- if (pkg.version) {
3720
- cached = pkg.version;
3721
- return cached;
3722
- }
3723
- } catch {
4359
+ // src/screens/detail.tsx
4360
+ import { useState as useState6 } from "react";
4361
+ import { Box as Box8, Text as Text9 } from "ink";
4362
+ import { jsx as jsx10, jsxs as jsxs8 } from "react/jsx-runtime";
4363
+ function glyphStatus(outcome) {
4364
+ switch (outcome) {
4365
+ case "upgraded":
4366
+ return "done";
4367
+ case "failed":
4368
+ return "failed";
4369
+ case "unknown":
4370
+ return "unknown";
4371
+ case "skipped":
4372
+ return "skipped";
4373
+ default:
4374
+ return "uptodate";
4375
+ }
4376
+ }
4377
+ function delta(from, to) {
4378
+ if (!from && !to) return "";
4379
+ if (!from) return `${g.arrow} ${to}`;
4380
+ if (!to) return from;
4381
+ return `${from} ${g.arrow} ${to}`;
4382
+ }
4383
+ function DetailScreen() {
4384
+ const { state, closeDetail } = useMachine();
4385
+ const [offset, setOffset] = useState6(0);
4386
+ const summary = summarizeRun(state);
4387
+ const rows = [];
4388
+ for (const m of summary.managers) {
4389
+ const packages = m.packages ?? [];
4390
+ if (packages.length === 0) continue;
4391
+ rows.push({ kind: "manager", managerId: m.id });
4392
+ for (const p of packages) {
4393
+ rows.push({
4394
+ kind: "package",
4395
+ managerId: m.id,
4396
+ name: p.name,
4397
+ outcome: p.outcome,
4398
+ right: delta(p.fromVersion, p.toVersion)
4399
+ });
3724
4400
  }
3725
4401
  }
3726
- cached = "0.0.0";
3727
- return cached;
4402
+ const width = Math.min((process.stdout.columns ?? 90) - 4, 92);
4403
+ const view = Math.max(6, (process.stdout.rows ?? 24) - 11);
4404
+ const maxOffset = Math.max(0, rows.length - view);
4405
+ const start = Math.min(offset, maxOffset);
4406
+ const visible = rows.slice(start, start + view);
4407
+ const nameWidth = Math.max(12, Math.min(32, width - 26));
4408
+ useSafeInput((input, key) => {
4409
+ if (input === "d" || input === "D") closeDetail();
4410
+ else if (key.downArrow || input === "j") setOffset((o) => Math.min(maxOffset, o + 1));
4411
+ else if (key.upArrow || input === "k") setOffset((o) => Math.max(0, o - 1));
4412
+ });
4413
+ return /* @__PURE__ */ jsxs8(Box8, { flexDirection: "column", children: [
4414
+ /* @__PURE__ */ jsx10(StepHeader, { phase: state.phase }),
4415
+ /* @__PURE__ */ jsx10(Text9, { color: colors.outline, children: start > 0 ? `${g.scrollUp} ${start}` : " " }),
4416
+ rows.length === 0 ? /* @__PURE__ */ jsx10(Text9, { color: semantic.muted, children: t("ui", "noChanges") }) : visible.map(
4417
+ (r, i) => r.kind === "manager" ? /* @__PURE__ */ jsx10(Text9, { color: semantic.muted, bold: true, children: managerName(r.managerId) }, `m:${r.managerId}:${i}`) : /* @__PURE__ */ jsxs8(Box8, { children: [
4418
+ /* @__PURE__ */ jsx10(Box8, { width: 2, children: /* @__PURE__ */ jsx10(StatusGlyph, { status: glyphStatus(r.outcome ?? "unchanged") }) }),
4419
+ /* @__PURE__ */ jsx10(Box8, { width: nameWidth, children: /* @__PURE__ */ jsx10(Text9, { color: semantic.text, wrap: "truncate-end", children: r.name }) }),
4420
+ /* @__PURE__ */ jsx10(Box8, { flexGrow: 1, justifyContent: "flex-end", children: /* @__PURE__ */ jsx10(Text9, { color: semantic.muted, wrap: "truncate-end", children: r.right }) })
4421
+ ] }, `p:${r.managerId}:${r.name}:${i}`)
4422
+ ),
4423
+ /* @__PURE__ */ jsx10(Text9, { color: colors.outline, children: start + visible.length < rows.length ? `${g.scrollDown} ${rows.length - start - visible.length}` : " " }),
4424
+ /* @__PURE__ */ jsx10(Box8, { marginTop: 1, children: /* @__PURE__ */ jsx10(Text9, { color: semantic.muted, children: t("ui", "detailBack") }) })
4425
+ ] });
3728
4426
  }
3729
4427
 
3730
4428
  // src/app.tsx
3731
- import { jsx as jsx10, jsxs as jsxs8 } from "react/jsx-runtime";
4429
+ import { jsx as jsx11, jsxs as jsxs9 } from "react/jsx-runtime";
3732
4430
  function Header({ sudoMode: sudoMode2 }) {
3733
- return /* @__PURE__ */ jsxs8(Box8, { justifyContent: "space-between", marginBottom: 1, children: [
3734
- /* @__PURE__ */ jsxs8(Box8, { children: [
3735
- /* @__PURE__ */ jsx10(Text9, { color: semantic.action, bold: true, children: "@tacuchi/updater" }),
3736
- /* @__PURE__ */ jsxs8(Text9, { color: colors.outline, children: [
4431
+ const { selfUpdate } = useMachine();
4432
+ return /* @__PURE__ */ jsxs9(Box9, { justifyContent: "space-between", marginBottom: 1, children: [
4433
+ /* @__PURE__ */ jsxs9(Box9, { children: [
4434
+ /* @__PURE__ */ jsx11(Text10, { color: semantic.action, bold: true, children: "@tacuchi/updater" }),
4435
+ /* @__PURE__ */ jsxs9(Text10, { color: colors.outline, children: [
3737
4436
  " v",
3738
4437
  getVersion()
3739
- ] })
4438
+ ] }),
4439
+ selfUpdate ? (
4440
+ // `warning`, NOT `unknown`: el ámbar está reservado a «no se pudo
4441
+ // determinar» (DES-001@r1) y reusarlo acá lo vuelve a significar dos cosas.
4442
+ /* @__PURE__ */ jsxs9(Text10, { color: semantic.warning, children: [
4443
+ " ",
4444
+ "\u2192 v",
4445
+ selfUpdate.version,
4446
+ " \xB7 ",
4447
+ selfUpdate.howTo
4448
+ ] })
4449
+ ) : null
3740
4450
  ] }),
3741
- /* @__PURE__ */ jsx10(Text9, { color: sudoMode2 ? semantic.warning : colors.outline, children: sudoMode2 ? "SUDO" : `${process.platform}` })
4451
+ /* @__PURE__ */ jsx11(Text10, { color: sudoMode2 ? semantic.warning : colors.outline, children: sudoMode2 ? "SUDO" : `${process.platform}` })
3742
4452
  ] });
3743
4453
  }
3744
4454
  function PhaseRouter() {
@@ -3747,32 +4457,31 @@ function PhaseRouter() {
3747
4457
  case "boot":
3748
4458
  case "detecting":
3749
4459
  case "scanning":
3750
- return /* @__PURE__ */ jsx10(DetectScreen, {});
4460
+ return /* @__PURE__ */ jsx11(DetectScreen, {});
3751
4461
  case "select":
3752
- return /* @__PURE__ */ jsx10(SelectScreen, {});
4462
+ return /* @__PURE__ */ jsx11(SelectScreen, {});
3753
4463
  case "confirm":
3754
- return /* @__PURE__ */ jsx10(ConfirmScreen, {});
4464
+ return /* @__PURE__ */ jsx11(ConfirmScreen, {});
3755
4465
  case "updating":
3756
- return /* @__PURE__ */ jsx10(UpdateScreen, {});
4466
+ return /* @__PURE__ */ jsx11(UpdateScreen, {});
3757
4467
  case "summary":
3758
- return /* @__PURE__ */ jsx10(SummaryScreen, {});
4468
+ return /* @__PURE__ */ jsx11(SummaryScreen, {});
4469
+ case "detail":
4470
+ return /* @__PURE__ */ jsx11(DetailScreen, {});
3759
4471
  case "settings":
3760
- return /* @__PURE__ */ jsx10(SettingsScreen, {});
4472
+ return /* @__PURE__ */ jsx11(SettingsScreen, {});
3761
4473
  default:
3762
4474
  return null;
3763
4475
  }
3764
4476
  }
3765
4477
  function Shell({ sudoMode: sudoMode2 }) {
3766
- const { exit } = useInkApp();
4478
+ const { quitApp } = useMachine();
3767
4479
  useSafeInput((input) => {
3768
- if (input === "q" || input === "Q") {
3769
- exit();
3770
- process.exit(0);
3771
- }
4480
+ if (input === "q" || input === "Q") quitApp();
3772
4481
  });
3773
- return /* @__PURE__ */ jsxs8(Box8, { flexDirection: "column", paddingX: 1, width: Math.min(process.stdout.columns ?? 100, 100), children: [
3774
- /* @__PURE__ */ jsx10(Header, { sudoMode: sudoMode2 }),
3775
- /* @__PURE__ */ jsx10(PhaseRouter, {})
4482
+ return /* @__PURE__ */ jsxs9(Box9, { flexDirection: "column", paddingX: 1, width: Math.min(process.stdout.columns ?? 100, 100), children: [
4483
+ /* @__PURE__ */ jsx11(Header, { sudoMode: sudoMode2 }),
4484
+ /* @__PURE__ */ jsx11(PhaseRouter, {})
3776
4485
  ] });
3777
4486
  }
3778
4487
  function App({
@@ -3780,11 +4489,37 @@ function App({
3780
4489
  nonInteractive: nonInteractive2 = false
3781
4490
  }) {
3782
4491
  const machine = useAppMachine(sudoMode2, nonInteractive2);
3783
- return /* @__PURE__ */ jsx10(MachineProvider, { value: machine, children: /* @__PURE__ */ jsx10(Shell, { sudoMode: sudoMode2 }) });
4492
+ return /* @__PURE__ */ jsx11(MachineProvider, { value: machine, children: /* @__PURE__ */ jsx11(Shell, { sudoMode: sudoMode2 }) });
4493
+ }
4494
+
4495
+ // src/lib/signals.ts
4496
+ var COMMON = [
4497
+ { signal: "SIGINT", code: 130, mode: "cancelada" },
4498
+ { signal: "SIGTERM", code: 143, mode: "interrumpida" },
4499
+ // The console window closing. On Windows Node raises it too, with a grace
4500
+ // period the OS controls — which is why the closing block is written
4501
+ // SYNCHRONOUSLY inside the handler and not after any timer.
4502
+ { signal: "SIGHUP", code: 129, mode: "interrumpida" }
4503
+ ];
4504
+ var WINDOWS_ONLY = [{ signal: "SIGBREAK", code: 130, mode: "cancelada" }];
4505
+ function signalRoutes(platform) {
4506
+ return platform === "win32" ? [...COMMON, ...WINDOWS_ONLY] : COMMON;
4507
+ }
4508
+ var SIGNAL_GRACE_MS = 200;
4509
+ function answerSignal(route, effects) {
4510
+ effects.settle(route.mode, `se\xF1al ${route.signal}`);
4511
+ effects.cancel();
4512
+ effects.schedule(() => {
4513
+ try {
4514
+ effects.unmount();
4515
+ } catch {
4516
+ }
4517
+ effects.exit(route.code);
4518
+ }, SIGNAL_GRACE_MS);
3784
4519
  }
3785
4520
 
3786
4521
  // src/cli.tsx
3787
- import { jsx as jsx11 } from "react/jsx-runtime";
4522
+ import { jsx as jsx12 } from "react/jsx-runtime";
3788
4523
  var args = process.argv.slice(2);
3789
4524
  var sudoRequested = args.includes("--sudo") || args.includes("-s");
3790
4525
  var isRoot = process.getuid?.() === 0;
@@ -3837,15 +4572,18 @@ if (process.platform === "win32" && sudoRequested && !elevated) {
3837
4572
  }
3838
4573
  var sudoMode = process.platform === "win32" ? elevated : isRoot || sudoRequested;
3839
4574
  var nonInteractive = !process.stdin.isTTY || args.includes("--yes") || args.includes("-y") || args.includes("--all");
3840
- var { unmount } = render(/* @__PURE__ */ jsx11(App, { sudoMode, nonInteractive }));
3841
- var onSignal = (code, name) => () => {
3842
- warn(`Interrumpido por se\xF1al (${name}) \u2014 run incompleto, sin resumen`);
3843
- fireProcessCancel();
3844
- setTimeout(() => {
3845
- unmount();
3846
- process.exit(code);
3847
- }, 200);
3848
- };
3849
- process.on("SIGINT", onSignal(130, "SIGINT"));
3850
- process.on("SIGTERM", onSignal(143, "SIGTERM"));
3851
- process.on("SIGBREAK", onSignal(130, "SIGBREAK"));
4575
+ var { unmount } = render(/* @__PURE__ */ jsx12(App, { sudoMode, nonInteractive }));
4576
+ for (const route of signalRoutes(process.platform)) {
4577
+ process.on(
4578
+ route.signal,
4579
+ () => answerSignal(route, {
4580
+ settle: (mode, detail) => settleRun(mode, detail),
4581
+ cancel: fireProcessCancel,
4582
+ unmount,
4583
+ exit: (exitCode) => process.exit(exitCode),
4584
+ schedule: (fn, ms) => {
4585
+ setTimeout(fn, ms);
4586
+ }
4587
+ })
4588
+ );
4589
+ }