@tacuchi/updater 2.2.1 → 3.0.1

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 +959 -203
  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
  }
@@ -255,22 +293,35 @@ function tail(s, bytes) {
255
293
  return s.length > bytes ? s.slice(-bytes) : s;
256
294
  }
257
295
  function execaOptions(opts, all) {
296
+ if (!Number.isFinite(opts.timeoutMs) || opts.timeoutMs < 0) {
297
+ throw new TypeError("timeoutMs must be a finite, non-negative number");
298
+ }
258
299
  return {
259
- timeout: opts.timeoutMs,
260
300
  reject: false,
261
301
  cwd: opts.cwd,
262
302
  env: opts.env,
263
- cancelSignal: opts.signal,
264
303
  all,
265
304
  // Capture raw bytes; we sniff-decode (UTF-8 / UTF-16LE / OEM) ourselves.
266
305
  encoding: "buffer"
267
306
  };
268
307
  }
269
- function attachTreeKill(signal, child) {
270
- if (!signal) return;
308
+ function attachTreeKill(opts, child) {
309
+ const { signal } = opts;
310
+ const lifetime = {
311
+ timedOut: false,
312
+ dispose() {
313
+ clearTimeout(timer);
314
+ signal?.removeEventListener("abort", onAbort);
315
+ }
316
+ };
271
317
  const onAbort = () => killTree(child.pid);
272
- if (signal.aborted) onAbort();
273
- else signal.addEventListener("abort", onAbort, { once: true });
318
+ const timer = opts.timeoutMs === 0 ? void 0 : setTimeout(() => {
319
+ lifetime.timedOut = true;
320
+ killTree(child.pid, "SIGKILL");
321
+ }, opts.timeoutMs);
322
+ if (signal?.aborted) onAbort();
323
+ else signal?.addEventListener("abort", onAbort, { once: true });
324
+ return lifetime;
274
325
  }
275
326
  var WARN_RE = /error|fail|denied|errno|cannot|unable/i;
276
327
  async function* runStream(cmd, args2, opts, percentParser) {
@@ -278,44 +329,52 @@ async function* runStream(cmd, args2, opts, percentParser) {
278
329
  const tailBytes = opts.tailBytes ?? DEFAULT_TAIL_BYTES;
279
330
  const started = Date.now();
280
331
  const child = execa(finalCmd, finalArgs, { ...execaOptions(opts, true), stdout: "pipe", stderr: "pipe" });
281
- attachTreeKill(opts.signal, child);
282
- if (child.all) {
283
- const decoder = new StreamDecoder();
284
- let lineBuf = "";
285
- const emit = function* (raw) {
286
- const line = raw.replace(/\r$/, "");
287
- if (!line) return;
288
- const percent = percentParser?.(line);
289
- if (percent !== void 0) {
290
- yield { type: "progress", message: line, percent };
291
- } else {
292
- yield { type: "log", message: line, severity: WARN_RE.test(line) ? "warn" : "info" };
293
- }
294
- };
295
- for await (const chunk of child.all) {
296
- lineBuf += decoder.write(chunk);
297
- let nl;
298
- while ((nl = lineBuf.indexOf("\n")) >= 0) {
299
- const raw = lineBuf.slice(0, nl);
300
- lineBuf = lineBuf.slice(nl + 1);
301
- yield* emit(raw);
332
+ const lifetime = attachTreeKill(opts, child);
333
+ try {
334
+ if (child.all) {
335
+ const decoder = new StreamDecoder();
336
+ let lineBuf = "";
337
+ const emit = function* (raw) {
338
+ const line = raw.replace(/\r$/, "");
339
+ if (!line) return;
340
+ const percent = percentParser?.(line);
341
+ if (percent !== void 0) {
342
+ yield { type: "progress", message: line, percent };
343
+ } else {
344
+ yield { type: "log", message: line, severity: WARN_RE.test(line) ? "warn" : "info" };
345
+ }
346
+ };
347
+ for await (const chunk of child.all) {
348
+ lineBuf += decoder.write(chunk);
349
+ let nl;
350
+ while ((nl = lineBuf.indexOf("\n")) >= 0) {
351
+ const raw = lineBuf.slice(0, nl);
352
+ lineBuf = lineBuf.slice(nl + 1);
353
+ yield* emit(raw);
354
+ }
302
355
  }
356
+ lineBuf += decoder.end();
357
+ if (lineBuf) yield* emit(lineBuf);
303
358
  }
304
- lineBuf += decoder.end();
305
- if (lineBuf) yield* emit(lineBuf);
359
+ const result = await child;
360
+ return {
361
+ cmd: [finalCmd, ...finalArgs].join(" "),
362
+ exitCode: result.exitCode ?? null,
363
+ durationMs: Date.now() - started,
364
+ timedOut: lifetime.timedOut,
365
+ stdoutTail: tail(decodeSmart(result.stdout), tailBytes),
366
+ stderrTail: tail(decodeSmart(result.stderr), tailBytes)
367
+ };
368
+ } finally {
369
+ lifetime.dispose();
306
370
  }
307
- const result = await child;
308
- return {
309
- cmd: [finalCmd, ...finalArgs].join(" "),
310
- exitCode: result.exitCode ?? null,
311
- durationMs: Date.now() - started,
312
- timedOut: result.timedOut ?? false,
313
- stdoutTail: tail(decodeSmart(result.stdout), tailBytes),
314
- stderrTail: tail(decodeSmart(result.stderr), tailBytes)
315
- };
316
371
  }
317
372
 
318
373
  // src/lib/executor.ts
374
+ function isSpawnFailure(r) {
375
+ if (r.code === "ENOENT") return true;
376
+ return typeof r.originalMessage === "string" && r.originalMessage.includes("ENOENT");
377
+ }
319
378
  async function execCommand(cmd, args2, timeout = 5e3, sudo = false) {
320
379
  const [finalCmd, finalArgs] = withSudo(cmd, args2, sudo);
321
380
  try {
@@ -328,14 +387,18 @@ async function execCommand(cmd, args2, timeout = 5e3, sudo = false) {
328
387
  return {
329
388
  stdout: decodeSmart(result.stdout),
330
389
  stderr: decodeSmart(result.stderr),
331
- exitCode: result.exitCode ?? (result.failed ? 127 : 0)
390
+ exitCode: result.exitCode ?? (result.failed ? 127 : 0),
391
+ timedOut: result.timedOut === true,
392
+ spawnFailed: isSpawnFailure(result)
332
393
  };
333
394
  } catch (err) {
334
395
  if (err instanceof ExecaError) {
335
396
  return {
336
397
  stdout: decodeSmart(err.stdout),
337
398
  stderr: decodeSmart(err.stderr) || String(err.message),
338
- exitCode: err.exitCode ?? 1
399
+ exitCode: err.exitCode ?? 1,
400
+ timedOut: err.timedOut === true,
401
+ spawnFailed: isSpawnFailure(err)
339
402
  };
340
403
  }
341
404
  throw err;
@@ -375,8 +438,30 @@ function reconcile(requested, before, after, commands, successExitCodes) {
375
438
  const beforeByName = new Map(before.map((p) => [p.name, p]));
376
439
  const targetNames = requested ?? before.map((p) => p.name);
377
440
  const targets = [...new Set(targetNames)];
378
- const stillOutdated = new Set(after.stillOutdated.map((p) => p.name));
379
441
  const cmdKind = dominantFailureKind(commands, successExitCodes);
442
+ if (after === null) {
443
+ return {
444
+ success: false,
445
+ upgraded: 0,
446
+ failed: 0,
447
+ errors: ["no se pudo verificar el resultado: el listado posterior fall\xF3"],
448
+ status: "unknown",
449
+ skipped: 0,
450
+ reason: cmdKind ?? void 0,
451
+ reboot: rebootFrom(commands),
452
+ packages: targets.map((name) => {
453
+ const b = beforeByName.get(name);
454
+ return {
455
+ name,
456
+ outcome: "unknown",
457
+ fromVersion: b?.currentVersion,
458
+ toVersion: b?.newVersion
459
+ };
460
+ }),
461
+ commands
462
+ };
463
+ }
464
+ const stillOutdated = new Set(after.stillOutdated.map((p) => p.name));
380
465
  const packages = targets.map((name) => {
381
466
  const b = beforeByName.get(name);
382
467
  if (stillOutdated.has(name)) {
@@ -426,14 +511,13 @@ function reconcile(requested, before, after, commands, successExitCodes) {
426
511
  }
427
512
 
428
513
  // src/lib/logger.ts
429
- import fs2 from "fs";
430
- import path2 from "path";
514
+ import fs3 from "fs";
515
+ import path3 from "path";
431
516
 
432
517
  // src/lib/config.ts
433
518
  import fs from "fs";
434
519
  import path from "path";
435
520
  import os from "os";
436
- import envPaths from "env-paths";
437
521
  var DEFAULTS = {
438
522
  enabledManagers: {},
439
523
  verbosity: "info",
@@ -441,7 +525,9 @@ var DEFAULTS = {
441
525
  concurrency: 4,
442
526
  timeoutsMs: {},
443
527
  logTailBytes: 16384,
444
- managers: {}
528
+ managers: {},
529
+ logRetentionRuns: 30,
530
+ selfCheck: true
445
531
  };
446
532
  var MIN_CONCURRENCY = 1;
447
533
  var MAX_CONCURRENCY = 8;
@@ -457,17 +543,29 @@ function normalizeConfig(parsed) {
457
543
  timeoutsMs: { ...DEFAULTS.timeoutsMs, ...parsed.timeoutsMs },
458
544
  managers: { ...DEFAULTS.managers, ...parsed.managers },
459
545
  concurrency: clampConcurrency(parsed.concurrency),
460
- logTailBytes: typeof parsed.logTailBytes === "number" && parsed.logTailBytes > 0 ? Math.round(parsed.logTailBytes) : DEFAULTS.logTailBytes
546
+ logTailBytes: typeof parsed.logTailBytes === "number" && parsed.logTailBytes > 0 ? Math.round(parsed.logTailBytes) : DEFAULTS.logTailBytes,
547
+ logRetentionRuns: typeof parsed.logRetentionRuns === "number" && parsed.logRetentionRuns >= 1 ? Math.round(parsed.logRetentionRuns) : DEFAULTS.logRetentionRuns,
548
+ selfCheck: typeof parsed.selfCheck === "boolean" ? parsed.selfCheck : DEFAULTS.selfCheck
461
549
  };
462
550
  }
463
551
  var APP = "tacuchi-updater";
464
- function getConfigDir() {
465
- if (process.platform === "win32") return envPaths(APP, { suffix: "" }).config;
552
+ function windowsPaths() {
553
+ const home = os.homedir();
554
+ const roaming = process.env["APPDATA"] || path.join(home, "AppData", "Roaming");
555
+ const local = process.env["LOCALAPPDATA"] || path.join(home, "AppData", "Local");
556
+ return { config: path.join(roaming, APP, "Config"), log: path.join(local, APP, "Log") };
557
+ }
558
+ function getConfigDir(platform = process.platform) {
559
+ const override = process.env["TACUCHI_UPDATER_CONFIG_DIR"];
560
+ if (override) return override;
561
+ if (platform === "win32") return windowsPaths().config;
466
562
  return path.join(os.homedir(), ".tacuchi-updater");
467
563
  }
468
- function getLogDir() {
469
- if (process.platform === "win32") return envPaths(APP, { suffix: "" }).log;
470
- return path.join(getConfigDir(), "logs");
564
+ function getLogDir(platform = process.platform) {
565
+ const override = process.env["TACUCHI_UPDATER_LOG_DIR"];
566
+ if (override) return override;
567
+ if (platform === "win32") return windowsPaths().log;
568
+ return path.join(getConfigDir(platform), "logs");
471
569
  }
472
570
  function getConfigPath() {
473
571
  return path.join(getConfigDir(), "config.json");
@@ -489,7 +587,14 @@ function loadConfig() {
489
587
  migrateLegacyConfig();
490
588
  const configPath = getConfigPath();
491
589
  try {
492
- if (!fs.existsSync(configPath)) return { ...DEFAULTS };
590
+ if (!fs.existsSync(configPath)) {
591
+ const defaults = { ...DEFAULTS };
592
+ try {
593
+ saveConfig(defaults);
594
+ } catch {
595
+ }
596
+ return defaults;
597
+ }
493
598
  const raw = fs.readFileSync(configPath, "utf-8");
494
599
  const parsed = JSON.parse(raw);
495
600
  return normalizeConfig(parsed);
@@ -528,30 +633,80 @@ function isManagerEnabled(config, managerId) {
528
633
  return true;
529
634
  }
530
635
 
636
+ // src/lib/log-retention.ts
637
+ import fs2 from "fs";
638
+ import path2 from "path";
639
+ var defaultRetentionDeps = {
640
+ listFiles: (dir) => fs2.existsSync(dir) ? fs2.readdirSync(dir).filter((f) => f.endsWith(".log")) : [],
641
+ mtimeMs: (file) => fs2.statSync(file).mtimeMs,
642
+ remove: (file) => fs2.unlinkSync(file)
643
+ };
644
+ function isPermissionDenied(err) {
645
+ const code = err?.code;
646
+ return code === "EACCES" || code === "EPERM";
647
+ }
648
+ function pruneLogs(dir, keep, deps = defaultRetentionDeps) {
649
+ const limit = Math.max(1, Math.floor(keep));
650
+ const report = { kept: 0, removed: 0, unremovable: [] };
651
+ let files;
652
+ try {
653
+ files = deps.listFiles(dir);
654
+ } catch {
655
+ return report;
656
+ }
657
+ const dated = files.map((f) => {
658
+ const full = path2.join(dir, f);
659
+ try {
660
+ return { full, mtime: deps.mtimeMs(full) };
661
+ } catch {
662
+ return null;
663
+ }
664
+ }).filter((x) => x !== null).sort((a, b) => b.mtime - a.mtime);
665
+ report.kept = Math.min(dated.length, limit);
666
+ for (const entry of dated.slice(limit)) {
667
+ try {
668
+ deps.remove(entry.full);
669
+ report.removed += 1;
670
+ } catch (err) {
671
+ if (isPermissionDenied(err)) {
672
+ report.unremovable.push({ file: entry.full, reason: "sin permiso" });
673
+ }
674
+ }
675
+ }
676
+ return report;
677
+ }
678
+ function unremovableReport(files, platform) {
679
+ if (files.length === 0) return null;
680
+ if (platform === "win32") {
681
+ return { reason: "bloqueado(s) por otro proceso", command: null };
682
+ }
683
+ return {
684
+ reason: "de otro due\xF1o",
685
+ command: `sudo rm -f ${files.map((f) => `'${f}'`).join(" ")}`
686
+ };
687
+ }
688
+
531
689
  // src/lib/logger.ts
532
690
  var logFilePath = null;
533
- var logStream = null;
691
+ var logFd = null;
534
692
  var inMemoryLog = [];
535
693
  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 };
694
+ function openLog(dir, filename) {
695
+ if (!fs3.existsSync(dir)) fs3.mkdirSync(dir, { recursive: true });
696
+ const filePath = path3.join(dir, filename);
697
+ return { fd: fs3.openSync(filePath, "a"), filePath };
541
698
  }
542
- function initLogger() {
699
+ function initLogger(retentionRuns) {
543
700
  const now = /* @__PURE__ */ new Date();
544
701
  const stamp = now.toISOString().replace(/[T:]/g, "_").split(".")[0]?.replace(/-/g, "");
545
702
  const filename = `system_updater_${stamp}.log`;
703
+ closeLogger();
546
704
  try {
547
- const { stream, filePath } = createStream(getLogDir(), filename);
548
- logStream = stream;
705
+ const { fd, filePath } = openLog(getLogDir(), filename);
706
+ logFd = fd;
549
707
  logFilePath = filePath;
550
- logStream.on("error", () => {
551
- logStream = null;
552
- });
553
708
  } catch {
554
- logStream = null;
709
+ logFd = null;
555
710
  logFilePath = null;
556
711
  }
557
712
  writeRaw("INFO", "Logger iniciado \u2014 @tacuchi/updater");
@@ -561,14 +716,39 @@ function initLogger() {
561
716
  `PID: ${process.pid} | UID: ${process.getuid?.() ?? "N/A"} | SUDO_USER: ${process.env["SUDO_USER"] ?? "N/A"}`
562
717
  );
563
718
  writeRaw("INFO", `Platform: ${process.platform} | Node: ${process.version}`);
719
+ if (retentionRuns !== void 0) pruneDeposit(retentionRuns);
564
720
  return logFilePath ?? "";
565
721
  }
722
+ function pruneDeposit(retentionRuns) {
723
+ const report = pruneLogs(getLogDir(), retentionRuns);
724
+ writeRaw(
725
+ "INFO",
726
+ `Retenci\xF3n: conservadas=${report.kept} retiradas=${report.removed} sin retirar=${report.unremovable.length} (l\xEDmite=${retentionRuns} corridas)`
727
+ );
728
+ const unremovable = unremovableReport(
729
+ report.unremovable.map((u) => u.file),
730
+ process.platform
731
+ );
732
+ if (unremovable !== null) {
733
+ const how = unremovable.command === null ? "" : ` Para retirarlos: ${unremovable.command}`;
734
+ writeRaw("WARN", `Retenci\xF3n: ${report.unremovable.length} archivo(s) ${unremovable.reason}.${how}`);
735
+ }
736
+ }
566
737
  function writeRaw(level, message) {
738
+ if (logFd === null) return;
567
739
  const now = /* @__PURE__ */ new Date();
568
740
  const timestamp = now.toISOString().replace("T", " ").split(".")[0];
569
741
  const line = `${timestamp} [${level.padEnd(5)}] SystemUpdater - ${message}
570
742
  `;
571
- logStream?.write(line);
743
+ try {
744
+ const bytes = new TextEncoder().encode(line);
745
+ let written = 0;
746
+ while (written < bytes.length) {
747
+ written += fs3.writeSync(logFd, bytes.subarray(written));
748
+ }
749
+ } catch {
750
+ logFd = null;
751
+ }
572
752
  }
573
753
  function addToMemory(level, message) {
574
754
  const id = String(++entryCounter);
@@ -576,6 +756,14 @@ function addToMemory(level, message) {
576
756
  inMemoryLog.push({ id, timestamp, level, message });
577
757
  if (inMemoryLog.length > 200) inMemoryLog.shift();
578
758
  }
759
+ function log(message) {
760
+ writeRaw("INFO", message);
761
+ addToMemory("info", message);
762
+ }
763
+ function debug(message) {
764
+ writeRaw("DEBUG", message);
765
+ addToMemory("debug", message);
766
+ }
579
767
  function warn(message) {
580
768
  writeRaw("WARN", message);
581
769
  addToMemory("warn", message);
@@ -593,6 +781,43 @@ function logCommand(rec) {
593
781
  }
594
782
  addToMemory("debug", `$ ${rec.cmd} (${status})`);
595
783
  }
784
+ function exitOf(code) {
785
+ return code === null ? "exit=n/d" : `exit=${code}`;
786
+ }
787
+ function waitOf(timeoutMs) {
788
+ return timeoutMs === void 0 ? "" : ` timeout=${timeoutMs}ms`;
789
+ }
790
+ function timeoutMark(timedOut) {
791
+ return timedOut === true ? " (expir\xF3)" : "";
792
+ }
793
+ function formatDetectLine(r) {
794
+ const verdict = r.available ? `disponible${r.version ? ` version=${r.version}` : ""}` : r.undetermined ? `indeterminado${timeoutMark(r.timedOut)}` : "ausente";
795
+ const via = r.viaEscapeHatch ? " via=escape-hatch" : "";
796
+ return `${r.managerId}: detect cmd="${r.cmd}"${via}${waitOf(r.timeoutMs)} ${exitOf(r.exitCode)} (${r.durationMs}ms) \u2192 ${verdict}`;
797
+ }
798
+ function formatScanLine(r) {
799
+ const verdict = r.ok ? `pendientes=${r.count}` : `indeterminado${timeoutMark(r.timedOut)}`;
800
+ return `${r.managerId}: scan cmd="${r.cmd}"${waitOf(r.timeoutMs)} ${exitOf(r.exitCode)} (${r.durationMs}ms) \u2192 ${verdict}`;
801
+ }
802
+ function logDetect(r) {
803
+ const line = formatDetectLine(r);
804
+ writeRaw("DEBUG", line);
805
+ addToMemory("debug", line);
806
+ }
807
+ function logScan(r) {
808
+ const line = formatScanLine(r);
809
+ writeRaw(r.ok ? "DEBUG" : "WARN", line);
810
+ addToMemory(r.ok ? "debug" : "warn", line);
811
+ }
812
+ function formatSelectionLines(s) {
813
+ const lines = [`Selecci\xF3n: ofrecidos=${s.offered} elegidos=${s.chosen}`];
814
+ for (const m of s.managers) lines.push(` ${m.id}: ofrecidos=${m.offered} elegidos=${m.chosen}`);
815
+ return lines;
816
+ }
817
+ function logSelection(s) {
818
+ for (const line of formatSelectionLines(s)) writeRaw("INFO", line);
819
+ addToMemory("info", `Selecci\xF3n: ${s.chosen} de ${s.offered}`);
820
+ }
596
821
  function formatResultLines(r) {
597
822
  const id = r.managerId ?? "?";
598
823
  const reason = r.reason ? ` reason=${r.reason}` : "";
@@ -603,16 +828,19 @@ function formatResultLines(r) {
603
828
  }
604
829
  for (const p of r.packages ?? []) {
605
830
  const ver = p.fromVersion || p.toVersion ? ` ${p.fromVersion ?? "?"}->${p.toVersion ?? "?"}` : "";
606
- lines.push(` ${id}: ${p.name}${ver} [${p.outcome}]`);
831
+ const why = p.failureKind ? ` (${p.failureKind})` : "";
832
+ lines.push(` ${id}: ${p.name}${ver} [${p.outcome}]${why}`);
607
833
  }
608
834
  return lines;
609
835
  }
610
836
  function logResult(r) {
611
837
  const id = r.managerId ?? "?";
612
838
  const ok = r.status === "success" || r.status === "noop";
613
- const level = ok ? "INFO" : r.status === "partial" ? "WARN" : "ERROR";
839
+ const level = ok ? "INFO" : r.status === "partial" || r.status === "unknown" ? "WARN" : "ERROR";
614
840
  for (const line of formatResultLines(r)) writeRaw(level, line);
615
- for (const e of r.errors) writeRaw(level, ` ${id}: ${e}`);
841
+ if ((r.packages ?? []).length === 0) {
842
+ for (const e of r.errors) writeRaw(level, ` ${id}: ${e}`);
843
+ }
616
844
  const memLevel = ok ? "info" : r.status === "partial" ? "warn" : "error";
617
845
  addToMemory(memLevel, `${id}: ${r.status} (${r.upgraded} ok, ${r.failed} fail)`);
618
846
  }
@@ -622,22 +850,69 @@ function formatRunSummary(s) {
622
850
  const dur = m.durationMs !== void 0 ? ` ${m.durationMs}ms` : "";
623
851
  lines.push(` ${m.id}: ${m.status} (${m.upgraded} ok, ${m.failed} fail)${dur}`);
624
852
  }
625
- lines.push(`Total: ${s.upgraded} upgraded \xB7 ${s.failed} failed \xB7 ${s.skipped} skipped`);
853
+ lines.push(
854
+ `Total: ${s.upgraded} upgraded \xB7 ${s.failed} failed \xB7 ${s.skipped} skipped \xB7 ${s.unknown} unknown`
855
+ );
626
856
  return lines;
627
857
  }
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
858
  function getLogFilePath() {
633
859
  return logFilePath;
634
860
  }
861
+ function closeLogger() {
862
+ if (logFd === null) return;
863
+ try {
864
+ fs3.fsyncSync(logFd);
865
+ } catch {
866
+ }
867
+ try {
868
+ fs3.closeSync(logFd);
869
+ } catch {
870
+ }
871
+ logFd = null;
872
+ }
873
+ function formatRunClosure(mode, summary, detail) {
874
+ const lines = summary ? formatRunSummary(summary) : [];
875
+ lines.push(`Cierre del run: modo=${mode}${detail ? ` (${detail})` : ""}`);
876
+ return lines;
877
+ }
878
+ function logRunClosure(mode, summary, detail) {
879
+ for (const line of formatRunClosure(mode, summary, detail)) writeRaw("INFO", line);
880
+ addToMemory("info", `Cierre del run: ${mode}`);
881
+ }
882
+
883
+ // src/managers/listing.ts
884
+ var ListingUnavailableError = class extends Error {
885
+ constructor(managerId, detail) {
886
+ super(`${managerId}: no se pudo determinar la lista de pendientes (${detail})`);
887
+ this.managerId = managerId;
888
+ this.detail = detail;
889
+ this.name = "ListingUnavailableError";
890
+ }
891
+ };
892
+ function requireListing(managerId, res, okExitCodes = [0]) {
893
+ if (okExitCodes.includes(res.exitCode)) return;
894
+ throw new ListingUnavailableError(
895
+ managerId,
896
+ res.timedOut ? "expir\xF3 la espera" : `exit=${res.exitCode}`
897
+ );
898
+ }
635
899
 
636
900
  // src/managers/engine.ts
637
901
  var defaultDeps = { execCommand, runStream };
638
902
  var DETECT_TIMEOUT = 5e3;
639
903
  var LIST_TIMEOUT = 3e4;
640
904
  var UPGRADE_TIMEOUT = 6e5;
905
+ function undeterminedResult(managerId, detail) {
906
+ return {
907
+ success: false,
908
+ upgraded: 0,
909
+ failed: 0,
910
+ errors: [detail],
911
+ skipped: 0,
912
+ status: "unknown",
913
+ managerId
914
+ };
915
+ }
641
916
  function skippedResult(managerId, manualCommand) {
642
917
  return {
643
918
  success: false,
@@ -668,25 +943,83 @@ function fromDescriptor(d, cfg, deps = defaultDeps) {
668
943
  group: d.group,
669
944
  defaultTimeoutMs: d.defaultTimeoutMs,
670
945
  async detect() {
946
+ const spec = d.detectCmd;
947
+ const timeoutMs = spec.timeout ?? DETECT_TIMEOUT;
948
+ const startedAt = Date.now();
671
949
  if (d.escapeHatch?.detect) {
672
950
  const r = await d.escapeHatch.detect(ctx(false));
951
+ logDetect({
952
+ managerId: d.id,
953
+ cmd: `${spec.cmd} ${spec.args.join(" ")}`,
954
+ viaEscapeHatch: true,
955
+ timeoutMs,
956
+ durationMs: Date.now() - startedAt,
957
+ exitCode: null,
958
+ available: r.available,
959
+ version: r.version
960
+ });
673
961
  return { available: r.available, version: r.version };
674
962
  }
675
- const spec = d.detectCmd;
676
- const res = await deps.execCommand(spec.cmd, spec.args, spec.timeout ?? DETECT_TIMEOUT, sudoFor(spec, ctx(false)));
963
+ const res = await deps.execCommand(spec.cmd, spec.args, timeoutMs, sudoFor(spec, ctx(false)));
677
964
  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) };
965
+ const detection = ok ? { available: true, version: d.parseVersion?.(res.stdout, res.stderr) } : res.spawnFailed ? { available: false } : { available: false, undetermined: true };
966
+ logDetect({
967
+ managerId: d.id,
968
+ cmd: `${spec.cmd} ${spec.args.join(" ")}`,
969
+ timeoutMs,
970
+ durationMs: Date.now() - startedAt,
971
+ exitCode: res.exitCode,
972
+ available: detection.available,
973
+ undetermined: detection.undetermined === true,
974
+ timedOut: res.timedOut,
975
+ version: detection.version
976
+ });
977
+ return detection;
680
978
  },
681
979
  async listOutdated() {
682
980
  const c = ctx(false);
683
- if (d.escapeHatch?.listOutdated) return d.escapeHatch.listOutdated(c);
684
- if (!d.listOutdatedCmd || !d.parseOutdated) return [];
981
+ const startedAt = Date.now();
982
+ if (d.escapeHatch?.listOutdated) {
983
+ const list2 = await d.escapeHatch.listOutdated(c);
984
+ logScan({
985
+ managerId: d.id,
986
+ cmd: "(escape hatch)",
987
+ timeoutMs: LIST_TIMEOUT,
988
+ durationMs: Date.now() - startedAt,
989
+ exitCode: null,
990
+ count: list2.length,
991
+ ok: true
992
+ });
993
+ return list2;
994
+ }
995
+ if (!d.listOutdatedCmd || !d.parseOutdated) {
996
+ logScan({
997
+ managerId: d.id,
998
+ cmd: "(sin comando de listado)",
999
+ durationMs: Date.now() - startedAt,
1000
+ exitCode: null,
1001
+ count: 0,
1002
+ ok: true
1003
+ });
1004
+ return [];
1005
+ }
685
1006
  const spec = d.listOutdatedCmd(c);
686
- const res = await deps.execCommand(spec.cmd, spec.args, spec.timeout ?? LIST_TIMEOUT, sudoFor(spec, c));
1007
+ const timeoutMs = spec.timeout ?? LIST_TIMEOUT;
1008
+ const res = await deps.execCommand(spec.cmd, spec.args, timeoutMs, sudoFor(spec, c));
687
1009
  const ok = res.exitCode === 0 || (d.listOkExitCodes?.includes(res.exitCode) ?? false);
688
- if (!ok) return [];
689
- return d.parseOutdated(res.stdout, res.stderr, c);
1010
+ const list = ok ? d.parseOutdated(res.stdout, res.stderr, c) : [];
1011
+ logScan({
1012
+ managerId: d.id,
1013
+ cmd: `${spec.cmd} ${spec.args.join(" ")}`,
1014
+ timeoutMs,
1015
+ durationMs: Date.now() - startedAt,
1016
+ exitCode: res.exitCode,
1017
+ count: list.length,
1018
+ ok,
1019
+ timedOut: res.timedOut
1020
+ });
1021
+ requireListing(d.id, res, [0, ...d.listOkExitCodes ?? []]);
1022
+ return list;
690
1023
  },
691
1024
  async *upgrade(packages, sudoMode2, signal) {
692
1025
  const c = ctx(sudoMode2 ?? false, signal);
@@ -705,7 +1038,17 @@ function fromDescriptor(d, cfg, deps = defaultDeps) {
705
1038
  return { ...r, startedAt, finishedAt: Date.now() };
706
1039
  }
707
1040
  yield { type: "phase", phase: "upgrading", message: `Actualizando ${d.id}...` };
708
- const before = await this.listOutdated();
1041
+ let before = [];
1042
+ try {
1043
+ before = await this.listOutdated();
1044
+ } catch (err) {
1045
+ if (!(err instanceof ListingUnavailableError)) throw err;
1046
+ if (!packages || packages.length === 0) {
1047
+ const r = { ...undeterminedResult(d.id, err.message), startedAt, finishedAt: Date.now() };
1048
+ logResult(r);
1049
+ return r;
1050
+ }
1051
+ }
709
1052
  const target = packages ?? before.map((p) => p.name);
710
1053
  const commands = [];
711
1054
  const pp = d.percentParser ? (line) => d.percentParser(line, c) : void 0;
@@ -739,7 +1082,13 @@ function fromDescriptor(d, cfg, deps = defaultDeps) {
739
1082
  yield* runOne(d.upgradeCmd(target.length ? target : void 0, c));
740
1083
  for (const spec of d.postUpgradeCmds?.(c) ?? []) yield* runOne(spec);
741
1084
  yield { type: "phase", phase: "verifying", message: "Verificando resultado..." };
742
- const after = await verifySnapshot(d, c, deps, this);
1085
+ let after;
1086
+ try {
1087
+ after = await verifySnapshot(d, c, deps, this);
1088
+ } catch (err) {
1089
+ if (!(err instanceof ListingUnavailableError)) throw err;
1090
+ after = null;
1091
+ }
743
1092
  const result = {
744
1093
  managerId: d.id,
745
1094
  startedAt,
@@ -862,7 +1211,7 @@ async function pep668Flags() {
862
1211
  async function listOutdated() {
863
1212
  const { cmd, baseArgs } = await resolvedInvocation();
864
1213
  const res = await execCommand(cmd, [...baseArgs, "list", "--outdated", "--format=json"], 3e4);
865
- if (res.exitCode !== 0) return [];
1214
+ requireListing("pip", res);
866
1215
  return parsePipOutdated(res.stdout);
867
1216
  }
868
1217
  var pip = {
@@ -1000,7 +1349,7 @@ async function userGems() {
1000
1349
  }
1001
1350
  async function listOutdated2() {
1002
1351
  const res = await execCommand("gem", ["outdated"], 3e4);
1003
- if (res.exitCode !== 0) return [];
1352
+ requireListing("gem", res);
1004
1353
  return parseGemOutdated(res.stdout, await userGems());
1005
1354
  }
1006
1355
  function updateArgs(packages, useSudo) {
@@ -1103,6 +1452,7 @@ async function listWinget() {
1103
1452
  ["list", "--upgrade-available", "--include-unknown", "--accept-source-agreements"],
1104
1453
  6e4
1105
1454
  );
1455
+ requireListing("winget", res);
1106
1456
  return parseWingetOutdated(res.stdout);
1107
1457
  }
1108
1458
  var winget = {
@@ -1332,7 +1682,7 @@ async function currentVersion() {
1332
1682
  async function latestStable(platform) {
1333
1683
  return once(`flutter:latest:${platformKey(platform)}`, async () => {
1334
1684
  try {
1335
- const resp = await fetch(releasesUrl(platform));
1685
+ const resp = await fetch(releasesUrl(platform), { signal: AbortSignal.timeout(1e4) });
1336
1686
  if (!resp.ok) return void 0;
1337
1687
  return findLatestStable(await resp.text());
1338
1688
  } catch {
@@ -1700,7 +2050,7 @@ function firstVersionToken(cell) {
1700
2050
  }
1701
2051
  async function listOutdated6() {
1702
2052
  const res = await execCommand("pnpm", ["outdated", "--global"], 3e4);
1703
- if (res.exitCode !== 0 && res.exitCode !== 1) return [];
2053
+ requireListing("pnpm", res, [0, 1]);
1704
2054
  return parsePnpmOutdated(res.stdout);
1705
2055
  }
1706
2056
  var pnpm = {
@@ -1982,7 +2332,7 @@ function highestInstalled(versions) {
1982
2332
  async function plugins() {
1983
2333
  return once("asdf:plugins", async () => {
1984
2334
  const res = await execCommand("asdf", ["plugin", "list"], 1e4);
1985
- if (res.exitCode !== 0) return [];
2335
+ requireListing("asdf", res);
1986
2336
  return parsePlugins(res.stdout);
1987
2337
  });
1988
2338
  }
@@ -2163,7 +2513,7 @@ function parsePipxList(stdout) {
2163
2513
  }
2164
2514
  async function snapshot() {
2165
2515
  const res = await execCommand("pipx", ["list", "--json"], 3e4);
2166
- if (res.exitCode !== 0) return {};
2516
+ requireListing("pipx", res);
2167
2517
  return parsePipxList(res.stdout);
2168
2518
  }
2169
2519
  async function listOutdated9() {
@@ -2260,7 +2610,7 @@ async function detectManagers(config) {
2260
2610
  managers.map(async (m) => ({ manager: m, detection: await m.detect() }))
2261
2611
  );
2262
2612
  return results.filter(
2263
- (r) => r.status === "fulfilled" && r.value.detection.available
2613
+ (r) => r.status === "fulfilled" && (r.value.detection.available || r.value.detection.undetermined === true)
2264
2614
  ).map((r) => r.value);
2265
2615
  }
2266
2616
 
@@ -2513,6 +2863,7 @@ var es = {
2513
2863
  confirm: "Confirmar",
2514
2864
  updating: "Actualizando",
2515
2865
  summary: "Resumen",
2866
+ detail: "Detalle por paquete",
2516
2867
  settings: "Ajustes"
2517
2868
  },
2518
2869
  // Etiquetas de estado por-gestor (ManagerStatus)
@@ -2525,7 +2876,8 @@ var es = {
2525
2876
  running: "ACTUALIZANDO",
2526
2877
  done: "OK",
2527
2878
  failed: "ERROR",
2528
- skipped: "MANUAL"
2879
+ skipped: "MANUAL",
2880
+ unknown: "INDETERMINADO"
2529
2881
  },
2530
2882
  // Cadenas de la interfaz del flujo
2531
2883
  ui: {
@@ -2547,7 +2899,13 @@ var es = {
2547
2899
  passwordNote: 'Si aparece "Password:" abajo, es un gestor (p.ej. un cask de brew): escr\xEDbela y Enter.',
2548
2900
  summaryHint: "R re-escanear \xB7 Q salir",
2549
2901
  elapsed: "transcurrido",
2550
- cancel: "Cancelando..."
2902
+ cancel: "Cancelando...",
2903
+ undetermined: "no se pudo determinar",
2904
+ undeterminedCount: "no se pudieron determinar",
2905
+ undeterminedTotal: "indeterminados",
2906
+ detailHint: "D detalle \xB7 R re-escanear \xB7 Q salir",
2907
+ detailBack: "\u2191\u2193 recorrer \xB7 D volver al resumen \xB7 Q salir",
2908
+ noChanges: "Ninguna corrida cambi\xF3 paquetes."
2551
2909
  }
2552
2910
  };
2553
2911
 
@@ -2714,6 +3072,7 @@ var en = {
2714
3072
  confirm: "Confirm",
2715
3073
  updating: "Updating",
2716
3074
  summary: "Summary",
3075
+ detail: "Per-package detail",
2717
3076
  settings: "Settings"
2718
3077
  },
2719
3078
  status: {
@@ -2725,7 +3084,8 @@ var en = {
2725
3084
  running: "UPDATING",
2726
3085
  done: "OK",
2727
3086
  failed: "ERROR",
2728
- skipped: "MANUAL"
3087
+ skipped: "MANUAL",
3088
+ unknown: "UNDETERMINED"
2729
3089
  },
2730
3090
  ui: {
2731
3091
  detecting: "Detecting package managers...",
@@ -2746,7 +3106,13 @@ var en = {
2746
3106
  passwordNote: 'If a "Password:" prompt appears below, it is a manager (e.g. a brew cask): type it and Enter.',
2747
3107
  summaryHint: "R rescan \xB7 Q quit",
2748
3108
  elapsed: "elapsed",
2749
- cancel: "Cancelling..."
3109
+ cancel: "Cancelling...",
3110
+ undetermined: "could not be determined",
3111
+ undeterminedCount: "could not be determined",
3112
+ undeterminedTotal: "undetermined",
3113
+ detailHint: "D detail \xB7 R rescan \xB7 Q quit",
3114
+ detailBack: "\u2191\u2193 scroll \xB7 D back to summary \xB7 Q quit",
3115
+ noChanges: "No run changed any package."
2750
3116
  }
2751
3117
  };
2752
3118
 
@@ -2774,11 +3140,11 @@ function managerName(id) {
2774
3140
  }
2775
3141
 
2776
3142
  // src/hooks/use-app-machine.tsx
2777
- import { writeFileSync, mkdirSync } from "fs";
3143
+ import { writeFileSync as writeFileSync2, mkdirSync as mkdirSync2 } from "fs";
2778
3144
  import { dirname } from "path";
2779
3145
 
2780
3146
  // src/lib/elevation.ts
2781
- import path3 from "path";
3147
+ import path4 from "path";
2782
3148
  import { execa as execa3 } from "execa";
2783
3149
  import isAdmin from "is-admin";
2784
3150
  async function isElevated() {
@@ -2793,7 +3159,7 @@ async function isElevated() {
2793
3159
  }
2794
3160
  function elevatedSummaryPath() {
2795
3161
  const base = process.env["LOCALAPPDATA"] ?? process.env["TEMP"] ?? process.cwd();
2796
- return path3.join(base, "tacuchi-updater", "last-run-summary.json");
3162
+ return path4.join(base, "tacuchi-updater", "last-run-summary.json");
2797
3163
  }
2798
3164
  var psQuote = (s) => `'${s.replace(/'/g, "''")}'`;
2799
3165
  async function relaunchElevated(extraArgs = []) {
@@ -2828,6 +3194,131 @@ function fireProcessCancel() {
2828
3194
  }
2829
3195
  }
2830
3196
 
3197
+ // src/lib/run-closure.ts
3198
+ var provider = null;
3199
+ var settled = false;
3200
+ function registerRunSummary(fn) {
3201
+ provider = fn;
3202
+ return () => {
3203
+ if (provider === fn) provider = null;
3204
+ };
3205
+ }
3206
+ function settleRun(mode, detail) {
3207
+ if (settled) return false;
3208
+ settled = true;
3209
+ let summary = null;
3210
+ try {
3211
+ summary = provider?.() ?? null;
3212
+ } catch {
3213
+ summary = null;
3214
+ }
3215
+ logRunClosure(mode, summary, detail);
3216
+ closeLogger();
3217
+ return true;
3218
+ }
3219
+
3220
+ // src/lib/self-update.ts
3221
+ import { readFileSync, writeFileSync, mkdirSync, existsSync } from "fs";
3222
+ import path5 from "path";
3223
+ var DAY_MS = 24 * 60 * 60 * 1e3;
3224
+ var PACKAGE2 = "@tacuchi/updater";
3225
+ function isNewer(current, candidate) {
3226
+ const parse = (v) => (v.split("-")[0] ?? "").split(".").map((n) => Number.parseInt(n, 10) || 0);
3227
+ const a = parse(current);
3228
+ const b = parse(candidate);
3229
+ for (let i = 0; i < 3; i += 1) {
3230
+ const left = a[i] ?? 0;
3231
+ const right = b[i] ?? 0;
3232
+ if (right > left) return true;
3233
+ if (right < left) return false;
3234
+ }
3235
+ return false;
3236
+ }
3237
+ function selfCheckStatePath() {
3238
+ return path5.join(getConfigDir(), "self-check.json");
3239
+ }
3240
+ function readStateFromDisk() {
3241
+ try {
3242
+ const raw = readFileSync(selfCheckStatePath(), "utf-8");
3243
+ const parsed = JSON.parse(raw);
3244
+ if (typeof parsed.lastCheckedAt !== "number") return null;
3245
+ return { lastCheckedAt: parsed.lastCheckedAt, latest: parsed.latest };
3246
+ } catch {
3247
+ return null;
3248
+ }
3249
+ }
3250
+ function writeStateToDisk(state) {
3251
+ try {
3252
+ const dir = getConfigDir();
3253
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true });
3254
+ writeFileSync(selfCheckStatePath(), JSON.stringify(state, null, 2), "utf-8");
3255
+ } catch {
3256
+ }
3257
+ }
3258
+ async function fetchLatestFromRegistry() {
3259
+ const res = await fetch(`https://registry.npmjs.org/${PACKAGE2}/latest`, {
3260
+ signal: AbortSignal.timeout(4e3)
3261
+ });
3262
+ if (!res.ok) throw new Error(`registro respondi\xF3 ${res.status}`);
3263
+ const body = await res.json();
3264
+ if (!body.version) throw new Error("el registro no devolvi\xF3 version");
3265
+ return body.version;
3266
+ }
3267
+ var defaultSelfCheckDeps = {
3268
+ now: () => Date.now(),
3269
+ fetchLatest: fetchLatestFromRegistry,
3270
+ readState: readStateFromDisk,
3271
+ writeState: writeStateToDisk
3272
+ };
3273
+ async function checkForNewerSelf(current, enabled, deps = defaultSelfCheckDeps) {
3274
+ if (!enabled) return { newer: null, queried: false };
3275
+ const state = deps.readState();
3276
+ const fresh = state !== null && deps.now() - state.lastCheckedAt < DAY_MS;
3277
+ if (fresh) {
3278
+ const cached2 = state.latest;
3279
+ const newer = cached2 && isNewer(current, cached2) ? cached2 : null;
3280
+ return newer ? { newer, queried: false, howTo: howToUpgrade(newer) } : { newer: null, queried: false };
3281
+ }
3282
+ try {
3283
+ const latest = await deps.fetchLatest();
3284
+ deps.writeState({ lastCheckedAt: deps.now(), latest });
3285
+ if (!isNewer(current, latest)) {
3286
+ debug(`Auto-chequeo: ${current} est\xE1 al d\xEDa (latest=${latest})`);
3287
+ return { newer: null, queried: true };
3288
+ }
3289
+ log(`Auto-chequeo: hay una versi\xF3n m\xE1s nueva del updater (${current} \u2192 ${latest})`);
3290
+ return { newer: latest, queried: true, howTo: howToUpgrade(latest) };
3291
+ } catch (err) {
3292
+ warn(`Auto-chequeo: no se pudo consultar la versi\xF3n m\xE1s nueva (${String(err)})`);
3293
+ return { newer: null, queried: true };
3294
+ }
3295
+ }
3296
+ function howToUpgrade(version) {
3297
+ return `npm i -g ${PACKAGE2}@${version}`;
3298
+ }
3299
+
3300
+ // src/lib/version.ts
3301
+ import { readFileSync as readFileSync2 } from "fs";
3302
+ import { fileURLToPath } from "url";
3303
+ import path6 from "path";
3304
+ var cached = null;
3305
+ function getVersion() {
3306
+ if (cached !== null) return cached;
3307
+ const here = path6.dirname(fileURLToPath(import.meta.url));
3308
+ for (const rel of ["../package.json", "../../package.json"]) {
3309
+ try {
3310
+ const pkg = JSON.parse(readFileSync2(path6.join(here, rel), "utf-8"));
3311
+ if (pkg.version) {
3312
+ cached = pkg.version;
3313
+ return cached;
3314
+ }
3315
+ } catch {
3316
+ }
3317
+ }
3318
+ cached = "0.0.0";
3319
+ return cached;
3320
+ }
3321
+
2831
3322
  // src/hooks/use-app-machine.tsx
2832
3323
  import { jsx } from "react/jsx-runtime";
2833
3324
  function toManagerResult(r, logRef) {
@@ -2858,6 +3349,7 @@ function summarizeRun(state) {
2858
3349
  let upgraded = 0;
2859
3350
  let failed = 0;
2860
3351
  let skipped = 0;
3352
+ let unknown = 0;
2861
3353
  const managers = [];
2862
3354
  for (const id of state.run.queue) {
2863
3355
  const e = state.managers[id];
@@ -2867,6 +3359,11 @@ function summarizeRun(state) {
2867
3359
  managers.push({ id, status: "skipped", upgraded: 0, failed: 0 });
2868
3360
  continue;
2869
3361
  }
3362
+ if (e.status === "unknown") {
3363
+ unknown++;
3364
+ managers.push({ id, status: "unknown", upgraded: 0, failed: 0 });
3365
+ continue;
3366
+ }
2870
3367
  const r = e.result;
2871
3368
  const u = r?.upgraded ?? 0;
2872
3369
  const f = r?.failed ?? 0;
@@ -2875,7 +3372,7 @@ function summarizeRun(state) {
2875
3372
  const durationMs = r?.startedAt !== void 0 && r?.finishedAt !== void 0 ? r.finishedAt - r.startedAt : void 0;
2876
3373
  managers.push({ id, status: e.status, upgraded: u, failed: f, durationMs, packages: r?.packages });
2877
3374
  }
2878
- return { upgraded, failed, skipped, managers };
3375
+ return { upgraded, failed, skipped, unknown, managers };
2879
3376
  }
2880
3377
  var MachineContext = createContext(null);
2881
3378
  function useMachine() {
@@ -2892,6 +3389,7 @@ function useAppMachine(sudoMode2, nonInteractive2 = false) {
2892
3389
  );
2893
3390
  const detectedRef = useRef([]);
2894
3391
  const abortRef = useRef(null);
3392
+ const runLogRef = useRef(null);
2895
3393
  const boot = useCallback(async () => {
2896
3394
  const config = configRef.current;
2897
3395
  dispatch({ type: "BOOT_DONE" });
@@ -2904,11 +3402,13 @@ function useAppMachine(sudoMode2, nonInteractive2 = false) {
2904
3402
  id: d.manager.id,
2905
3403
  group: d.manager.group ?? "language",
2906
3404
  requiresAdmin: d.manager.requiresAdmin,
2907
- version: d.detection.version
3405
+ version: d.detection.version,
3406
+ undetermined: d.detection.undetermined === true
2908
3407
  }))
2909
3408
  });
2910
3409
  await Promise.allSettled(
2911
3410
  detected.map(async (dm) => {
3411
+ if (dm.detection.undetermined) return;
2912
3412
  if (!isManagerEnabled(config, dm.manager.id)) {
2913
3413
  dispatch({ type: "SCAN_MANAGER_DONE", id: dm.manager.id, outdated: [] });
2914
3414
  return;
@@ -2918,7 +3418,9 @@ function useAppMachine(sudoMode2, nonInteractive2 = false) {
2918
3418
  const outdated = await dm.manager.listOutdated();
2919
3419
  dispatch({ type: "SCAN_MANAGER_DONE", id: dm.manager.id, outdated });
2920
3420
  } catch (err) {
2921
- error(`Error escaneando ${dm.manager.id}: ${String(err)}`);
3421
+ if (!(err instanceof ListingUnavailableError)) {
3422
+ error(`Error escaneando ${dm.manager.id}: ${String(err)}`);
3423
+ }
2922
3424
  dispatch({ type: "SCAN_MANAGER_FAILED", id: dm.manager.id });
2923
3425
  }
2924
3426
  })
@@ -2926,14 +3428,28 @@ function useAppMachine(sudoMode2, nonInteractive2 = false) {
2926
3428
  dispatch({ type: "SCAN_ALL_DONE" });
2927
3429
  } catch (err) {
2928
3430
  dispatch({ type: "DETECT_FAILED", error: String(err) });
3431
+ settleRun("fallida", `detecci\xF3n: ${String(err)}`);
2929
3432
  }
2930
3433
  }, []);
2931
3434
  useEffect(() => {
2932
- initLogger();
3435
+ initLogger(configRef.current.logRetentionRuns);
2933
3436
  setLanguage(configRef.current.language);
2934
3437
  void boot();
2935
3438
  }, [boot]);
3439
+ const [selfUpdate, setSelfUpdate] = useState(null);
3440
+ useEffect(() => {
3441
+ let alive = true;
3442
+ void checkForNewerSelf(getVersion(), configRef.current.selfCheck).then((outcome) => {
3443
+ if (alive && outcome.newer && outcome.howTo) {
3444
+ setSelfUpdate({ version: outcome.newer, howTo: outcome.howTo });
3445
+ }
3446
+ });
3447
+ return () => {
3448
+ alive = false;
3449
+ };
3450
+ }, []);
2936
3451
  useEffect(() => onProcessCancel(() => abortRef.current?.abort()), []);
3452
+ useEffect(() => registerRunSummary(() => runLogRef.current), []);
2937
3453
  const startRun = useCallback(() => {
2938
3454
  const config = configRef.current;
2939
3455
  const packagesByManager = /* @__PURE__ */ new Map();
@@ -2945,10 +3461,52 @@ function useAppMachine(sudoMode2, nonInteractive2 = false) {
2945
3461
  }
2946
3462
  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
3463
  if (tasks.length === 0) return;
2948
- dispatch({ type: "RUN_START", queue: tasks.map((t3) => t3.manager.id) });
3464
+ const queue = tasks.map((t3) => t3.manager.id);
3465
+ logSelection({
3466
+ offered: state.order.reduce((n, id) => n + (state.managers[id]?.outdated.length ?? 0), 0),
3467
+ chosen: state.selection.size,
3468
+ managers: state.order.filter((id) => (state.managers[id]?.outdated.length ?? 0) > 0).map((id) => ({
3469
+ id,
3470
+ offered: state.managers[id]?.outdated.length ?? 0,
3471
+ chosen: packagesByManager.get(id)?.length ?? 0
3472
+ }))
3473
+ });
3474
+ dispatch({ type: "RUN_START", queue });
2949
3475
  const ac = new AbortController();
2950
3476
  abortRef.current = ac;
2951
3477
  const logRef = getLogFilePath() ?? void 0;
3478
+ const settledResults = /* @__PURE__ */ new Map();
3479
+ const skippedIds = /* @__PURE__ */ new Set();
3480
+ const rebuildRunLog = () => {
3481
+ let upgraded = 0;
3482
+ let failed = 0;
3483
+ let skipped = 0;
3484
+ let unknownTotal = 0;
3485
+ const managers = queue.map((id) => {
3486
+ if (skippedIds.has(id)) {
3487
+ skipped++;
3488
+ return { id, status: "noop", upgraded: 0, failed: 0 };
3489
+ }
3490
+ const r = settledResults.get(id);
3491
+ if (!r) {
3492
+ unknownTotal++;
3493
+ return { id, status: "unknown", upgraded: 0, failed: 0 };
3494
+ }
3495
+ if (r.status === "unknown") unknownTotal++;
3496
+ upgraded += r.upgraded;
3497
+ failed += r.failed;
3498
+ const durationMs = r.startedAt !== void 0 && r.finishedAt !== void 0 ? r.finishedAt - r.startedAt : void 0;
3499
+ return {
3500
+ id,
3501
+ status: r.status ?? (r.success ? "success" : "failed"),
3502
+ upgraded: r.upgraded,
3503
+ failed: r.failed,
3504
+ durationMs
3505
+ };
3506
+ });
3507
+ runLogRef.current = { upgraded, failed, skipped, unknown: unknownTotal, managers };
3508
+ };
3509
+ rebuildRunLog();
2952
3510
  let pending = [];
2953
3511
  let scheduled = false;
2954
3512
  const flush = () => {
@@ -2973,12 +3531,17 @@ function useAppMachine(sudoMode2, nonInteractive2 = false) {
2973
3531
  if (e.event?.percent !== void 0) {
2974
3532
  enqueue({ type: "MGR_PROGRESS", id, percent: e.event.percent });
2975
3533
  } else if (!e.event) {
2976
- enqueue({ type: "MGR_RUNNING", id });
3534
+ enqueue({ type: "MGR_RUNNING", id, at: Date.now() });
2977
3535
  }
2978
3536
  } else if (e.phase === "done" && e.result) {
2979
3537
  const r = e.result;
3538
+ settledResults.set(id, r);
3539
+ if (r.status === "noop" && r.manualCommand) skippedIds.add(id);
3540
+ rebuildRunLog();
2980
3541
  if (r.status === "noop" && r.manualCommand) {
2981
3542
  enqueue({ type: "MGR_SKIPPED", id, manualCommand: r.manualCommand });
3543
+ } else if (r.status === "unknown") {
3544
+ enqueue({ type: "MGR_UNKNOWN", id, result: toManagerResult(r, logRef) });
2982
3545
  } else if (r.success || r.status === "success" || r.status === "partial") {
2983
3546
  enqueue({ type: "MGR_DONE", id, result: toManagerResult(r, logRef) });
2984
3547
  } else {
@@ -2986,16 +3549,23 @@ function useAppMachine(sudoMode2, nonInteractive2 = false) {
2986
3549
  }
2987
3550
  }
2988
3551
  };
3552
+ let engineError = null;
2989
3553
  void runEngine(tasks, {
2990
3554
  concurrency: config.concurrency,
2991
3555
  signal: ac.signal,
2992
3556
  sudoMode: sudoMode2,
2993
3557
  timeoutsMs: config.timeoutsMs,
2994
3558
  onEvent
3559
+ }).catch((err) => {
3560
+ engineError = err;
3561
+ error(`El motor termin\xF3 con error: ${String(err)}`);
2995
3562
  }).finally(() => {
2996
3563
  flush();
2997
3564
  dispatch({ type: "RUN_DONE" });
2998
3565
  abortRef.current = null;
3566
+ if (ac.signal.aborted) settleRun("cancelada", "corrida abortada en vuelo");
3567
+ else if (engineError !== null) settleRun("fallida", `motor: ${String(engineError)}`);
3568
+ else settleRun("completa");
2999
3569
  });
3000
3570
  }, [state.selection, sudoMode2]);
3001
3571
  const cancelRun = useCallback(() => {
@@ -3013,6 +3583,7 @@ function useAppMachine(sudoMode2, nonInteractive2 = false) {
3013
3583
  if (exitedRef.current) return;
3014
3584
  exitedRef.current = true;
3015
3585
  process.exitCode = code;
3586
+ settleRun("completa");
3016
3587
  exit();
3017
3588
  if (!process.env["VITEST"]) {
3018
3589
  const t3 = setTimeout(() => process.exit(code), 100);
@@ -3047,20 +3618,17 @@ function useAppMachine(sudoMode2, nonInteractive2 = false) {
3047
3618
  if (state.phase !== "summary" || process.platform !== "win32") return;
3048
3619
  try {
3049
3620
  const p = elevatedSummaryPath();
3050
- mkdirSync(dirname(p), { recursive: true });
3051
- writeFileSync(p, JSON.stringify({ ...summarizeRun(state), at: Date.now() }, null, 2), "utf-8");
3621
+ mkdirSync2(dirname(p), { recursive: true });
3622
+ writeFileSync2(p, JSON.stringify({ ...summarizeRun(state), at: Date.now() }, null, 2), "utf-8");
3052
3623
  } catch {
3053
3624
  }
3054
3625
  }, [state.phase]);
3055
- useEffect(() => {
3056
- if (state.phase !== "summary") return;
3057
- logRunSummary(summarizeRun(state));
3058
- }, [state.phase]);
3059
3626
  const relaunch = useCallback(() => {
3060
3627
  void (async () => {
3061
3628
  const ok = await relaunchElevated();
3062
3629
  if (ok) {
3063
3630
  process.exitCode = 0;
3631
+ settleRun("cedida", "consola elevada");
3064
3632
  exit();
3065
3633
  if (!process.env["VITEST"]) {
3066
3634
  const t3 = setTimeout(() => process.exit(0), 100);
@@ -3069,6 +3637,17 @@ function useAppMachine(sudoMode2, nonInteractive2 = false) {
3069
3637
  }
3070
3638
  })();
3071
3639
  }, [exit]);
3640
+ const quitApp = useCallback(() => {
3641
+ const inFlight = abortRef.current !== null;
3642
+ abortRef.current?.abort();
3643
+ settleRun("cancelada", inFlight ? "tecla de salida con corrida en vuelo" : "tecla de salida");
3644
+ const code = inFlight ? 130 : 0;
3645
+ process.exitCode = code;
3646
+ exit();
3647
+ if (!process.env["VITEST"]) {
3648
+ setTimeout(() => process.exit(code), 200);
3649
+ }
3650
+ }, [exit]);
3072
3651
  const persist = useCallback((next) => {
3073
3652
  dispatch(next);
3074
3653
  }, []);
@@ -3097,10 +3676,14 @@ function useAppMachine(sudoMode2, nonInteractive2 = false) {
3097
3676
  cancelRun,
3098
3677
  relaunch,
3099
3678
  rescan,
3679
+ openDetail: useCallback(() => persist({ type: "OPEN_DETAIL" }), [persist]),
3680
+ closeDetail: useCallback(() => persist({ type: "CLOSE_DETAIL" }), [persist]),
3100
3681
  openSettings: useCallback(() => persist({ type: "OPEN_SETTINGS" }), [persist]),
3101
3682
  closeSettings: useCallback(() => persist({ type: "CLOSE_SETTINGS" }), [persist]),
3102
3683
  setLang,
3103
- toggleEnabled
3684
+ toggleEnabled,
3685
+ quitApp,
3686
+ selfUpdate
3104
3687
  };
3105
3688
  }
3106
3689
  function MachineProvider({ value, children }) {
@@ -3111,7 +3694,7 @@ function MachineProvider({ value, children }) {
3111
3694
  import { useInput, useStdin } from "ink";
3112
3695
  function useSafeInput(handler, options) {
3113
3696
  const { isRawModeSupported } = useStdin();
3114
- const active = (options?.isActive ?? true) && isRawModeSupported;
3697
+ const active = (options?.isActive ?? true) && isRawModeSupported === true;
3115
3698
  useInput(handler, { ...options, isActive: active });
3116
3699
  }
3117
3700
 
@@ -3153,6 +3736,8 @@ var colors = {
3153
3736
  // Texto
3154
3737
  onSurface: "#e5e2e1",
3155
3738
  onSurfaceVariant: "#a09d9c",
3739
+ // Ámbar — reservado al estado «no se pudo determinar»
3740
+ unknown: "#f0b429",
3156
3741
  // Bordes
3157
3742
  outlineVariant: "#484556",
3158
3743
  outline: "#6f6d70"
@@ -3166,6 +3751,10 @@ var semantic = {
3166
3751
  // rojo
3167
3752
  warning: colors.secondary,
3168
3753
  // rosa (admin / skipped / atención)
3754
+ // Ámbar — «no se pudo determinar». NO puede reusar `muted`, que hoy significa
3755
+ // «al día»: eso es exactamente confundir «no lo sé» con «está bien»
3756
+ // (DES-001@r1). Se distingue a la vez del rosa de advertencia y del gris.
3757
+ unknown: colors.unknown,
3169
3758
  text: colors.onSurface,
3170
3759
  muted: colors.onSurfaceVariant
3171
3760
  };
@@ -3187,6 +3776,7 @@ var UNICODE = {
3187
3776
  done: "\u2713",
3188
3777
  failed: "\u2717",
3189
3778
  skipped: "\u2298",
3779
+ unknown: "?",
3190
3780
  cursor: "\u276F",
3191
3781
  checkOn: "[\u2713]",
3192
3782
  checkOff: "[ ]",
@@ -3209,6 +3799,7 @@ var ASCII_GLYPHS = {
3209
3799
  done: "+",
3210
3800
  failed: "x",
3211
3801
  skipped: "-",
3802
+ unknown: "?",
3212
3803
  cursor: ">",
3213
3804
  checkOn: "[x]",
3214
3805
  checkOff: "[ ]",
@@ -3246,6 +3837,13 @@ function StepHeader({ phase }) {
3246
3837
  t("flow", "summary")
3247
3838
  ] }) });
3248
3839
  }
3840
+ if (phase === "detail") {
3841
+ return /* @__PURE__ */ jsx2(Box, { marginBottom: 1, children: /* @__PURE__ */ jsxs(Text, { color: semantic.action, bold: true, children: [
3842
+ g.stepOn,
3843
+ " ",
3844
+ t("flow", "detail")
3845
+ ] }) });
3846
+ }
3249
3847
  if (phase === "settings") {
3250
3848
  return /* @__PURE__ */ jsx2(Box, { marginBottom: 1, children: /* @__PURE__ */ jsxs(Text, { color: semantic.action, bold: true, children: [
3251
3849
  g.stepOn,
@@ -3273,7 +3871,7 @@ function StepHeader({ phase }) {
3273
3871
  }
3274
3872
 
3275
3873
  // src/components/status-glyph.tsx
3276
- import { useEffect as useEffect2, useState } from "react";
3874
+ import { useEffect as useEffect2, useState as useState2 } from "react";
3277
3875
  import { Text as Text2 } from "ink";
3278
3876
  import { jsx as jsx3 } from "react/jsx-runtime";
3279
3877
  var SPECS = {
@@ -3285,7 +3883,12 @@ var SPECS = {
3285
3883
  running: { glyph: g.running, color: semantic.action },
3286
3884
  done: { glyph: g.done, color: semantic.success },
3287
3885
  failed: { glyph: g.failed, color: semantic.error },
3288
- skipped: { glyph: g.skipped, color: semantic.warning }
3886
+ skipped: { glyph: g.skipped, color: semantic.warning },
3887
+ // Amber and a one-cell `?`: it cannot reuse `muted`, which is the colour of
3888
+ // "up to date" — the confusion this state exists to remove (DES-001@r1). The
3889
+ // spec lands here with the domain state because this table is exhaustive over
3890
+ // ManagerStatus, so the state cannot exist without it.
3891
+ unknown: { glyph: g.unknown, color: semantic.unknown }
3289
3892
  };
3290
3893
  function statusColor(status) {
3291
3894
  return SPECS[status].color;
@@ -3295,7 +3898,7 @@ function StatusGlyph({ status }) {
3295
3898
  return /* @__PURE__ */ jsx3(Text2, { color: spec.color, children: spec.glyph });
3296
3899
  }
3297
3900
  function RunningGlyph() {
3298
- const [i, setI] = useState(0);
3901
+ const [i, setI] = useState2(0);
3299
3902
  useEffect2(() => {
3300
3903
  if (NO_ANIM) return;
3301
3904
  const t3 = setInterval(() => setI((n) => (n + 1) % spinnerFrames.length), 90);
@@ -3312,7 +3915,7 @@ function DetectScreen() {
3312
3915
  const scanning = state.phase === "scanning";
3313
3916
  const done = state.order.filter((id) => {
3314
3917
  const s = state.managers[id]?.status;
3315
- return s === "outdated" || s === "uptodate";
3918
+ return s === "outdated" || s === "uptodate" || s === "unknown";
3316
3919
  }).length;
3317
3920
  return /* @__PURE__ */ jsxs2(Box2, { flexDirection: "column", children: [
3318
3921
  /* @__PURE__ */ jsx4(StepHeader, { phase: state.phase }),
@@ -3337,14 +3940,14 @@ function DetectScreen() {
3337
3940
  e.outdated.length,
3338
3941
  " ",
3339
3942
  g.outdated
3340
- ] }) : e.status === "uptodate" ? /* @__PURE__ */ jsx4(Text3, { color: colors.outline, children: "-" }) : /* @__PURE__ */ jsx4(Text3, { color: semantic.muted, children: g.ellipsis })
3943
+ ] }) : 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
3944
  ] }, id);
3342
3945
  })
3343
3946
  ] });
3344
3947
  }
3345
3948
 
3346
3949
  // src/screens/select.tsx
3347
- import { useState as useState2 } from "react";
3950
+ import { useState as useState3 } from "react";
3348
3951
  import { Box as Box3, Text as Text4 } from "ink";
3349
3952
  import { jsx as jsx5, jsxs as jsxs3 } from "react/jsx-runtime";
3350
3953
  function clip(s, n) {
@@ -3352,13 +3955,14 @@ function clip(s, n) {
3352
3955
  }
3353
3956
  function SelectScreen() {
3354
3957
  const { state, toggleItem, selectAll, selectNone, goConfirm, openSettings } = useMachine();
3355
- const [cursor, setCursor] = useState2(0);
3958
+ const [cursor, setCursor] = useState3(0);
3356
3959
  const rows = [];
3357
3960
  for (const id of state.order) {
3358
3961
  const m = state.managers[id];
3359
3962
  if (m && m.status === "outdated") for (const pkg of m.outdated) rows.push({ managerId: id, pkg });
3360
3963
  }
3361
3964
  const clamped = Math.min(cursor, Math.max(0, rows.length - 1));
3965
+ const undetermined = state.order.filter((id) => state.managers[id]?.status === "unknown");
3362
3966
  useSafeInput((input, key) => {
3363
3967
  if (key.downArrow || input === "j") setCursor((c) => Math.min(rows.length - 1, c + 1));
3364
3968
  else if (key.upArrow || input === "k") setCursor((c) => Math.max(0, c - 1));
@@ -3377,6 +3981,16 @@ function SelectScreen() {
3377
3981
  "\u2713 ",
3378
3982
  t("ui", "noUpdates")
3379
3983
  ] }),
3984
+ undetermined.length > 0 && /* @__PURE__ */ jsxs3(Text4, { color: semantic.unknown, children: [
3985
+ g.unknown,
3986
+ " ",
3987
+ undetermined.length,
3988
+ " ",
3989
+ t("ui", "undeterminedCount"),
3990
+ ":",
3991
+ " ",
3992
+ undetermined.map((id) => managerName(id)).join(", ")
3993
+ ] }),
3380
3994
  /* @__PURE__ */ jsx5(Box3, { marginTop: 1, children: /* @__PURE__ */ jsxs3(Text4, { color: semantic.muted, children: [
3381
3995
  "R ",
3382
3996
  t("flow", "detecting"),
@@ -3403,6 +4017,16 @@ function SelectScreen() {
3403
4017
  t("ui", "selected")
3404
4018
  ] })
3405
4019
  ] }),
4020
+ undetermined.length > 0 && /* @__PURE__ */ jsx5(Box3, { marginBottom: 1, children: /* @__PURE__ */ jsxs3(Text4, { color: semantic.unknown, children: [
4021
+ g.unknown,
4022
+ " ",
4023
+ undetermined.length,
4024
+ " ",
4025
+ t("ui", "undeterminedCount"),
4026
+ ":",
4027
+ " ",
4028
+ undetermined.map((id) => managerName(id)).join(", ")
4029
+ ] }) }),
3406
4030
  start > 0 && /* @__PURE__ */ jsxs3(Text4, { color: colors.outline, children: [
3407
4031
  g.scrollUp,
3408
4032
  " ",
@@ -3479,21 +4103,40 @@ function ConfirmScreen() {
3479
4103
  }
3480
4104
 
3481
4105
  // src/screens/update.tsx
4106
+ import { useEffect as useEffect3, useState as useState4 } from "react";
3482
4107
  import { Box as Box5, Text as Text6 } from "ink";
3483
- import { jsx as jsx7, jsxs as jsxs5 } from "react/jsx-runtime";
4108
+ import { Fragment, jsx as jsx7, jsxs as jsxs5 } from "react/jsx-runtime";
3484
4109
  function clip2(s, n) {
3485
4110
  return s.length > n ? s.slice(0, Math.max(0, n - g.ellipsis.length)) + g.ellipsis : s;
3486
4111
  }
4112
+ function formatElapsed(ms) {
4113
+ const total = Math.max(0, Math.floor(ms / 1e3));
4114
+ const s = total % 60;
4115
+ const m = Math.floor(total / 60) % 60;
4116
+ const h = Math.floor(total / 3600);
4117
+ if (h > 0) return `${h}h${String(m).padStart(2, "0")}m`;
4118
+ if (m > 0) return `${m}m${String(s).padStart(2, "0")}s`;
4119
+ return `${s}s`;
4120
+ }
4121
+ function Elapsed({ startedAt }) {
4122
+ const [now, setNow] = useState4(() => Date.now());
4123
+ useEffect3(() => {
4124
+ const timer = setInterval(() => setNow(Date.now()), 1e3);
4125
+ return () => clearInterval(timer);
4126
+ }, []);
4127
+ return /* @__PURE__ */ jsx7(Fragment, { children: formatElapsed(now - startedAt) });
4128
+ }
3487
4129
  function Row({ e, width }) {
3488
4130
  let detail = "";
3489
- if (e.status === "running") detail = e.percent > 0 ? `${e.percent}%` : "";
4131
+ if (e.status === "running") detail = "";
3490
4132
  else if (e.status === "skipped") detail = e.manualCommand ?? "manual";
3491
4133
  else if (e.status === "failed") detail = e.result?.failures[0]?.message ?? "";
4134
+ else if (e.status === "unknown") detail = e.result?.failures[0]?.message ?? t("ui", "undetermined");
3492
4135
  return /* @__PURE__ */ jsxs5(Box5, { children: [
3493
4136
  /* @__PURE__ */ jsx7(Box5, { width: 2, children: e.status === "running" ? /* @__PURE__ */ jsx7(RunningGlyph, {}) : /* @__PURE__ */ jsx7(StatusGlyph, { status: e.status }) }),
3494
4137
  /* @__PURE__ */ jsx7(Box5, { width: 16, children: /* @__PURE__ */ jsx7(Text6, { color: semantic.text, bold: e.status === "running", children: clip2(managerName(e.id), 15) }) }),
3495
4138
  /* @__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)) })
4139
+ /* @__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
4140
  ] });
3498
4141
  }
3499
4142
  function UpdateScreen() {
@@ -3502,7 +4145,7 @@ function UpdateScreen() {
3502
4145
  if (key.escape) cancelRun();
3503
4146
  });
3504
4147
  const total = state.run.queue.length;
3505
- const finished = state.run.doneCount + state.run.failedCount + state.run.skippedCount;
4148
+ const finished = state.run.doneCount + state.run.failedCount + state.run.skippedCount + state.run.unknownCount;
3506
4149
  const width = Math.min((process.stdout.columns ?? 90) - 4, 92);
3507
4150
  return /* @__PURE__ */ jsxs5(Box5, { flexDirection: "column", children: [
3508
4151
  /* @__PURE__ */ jsx7(StepHeader, { phase: state.phase }),
@@ -3546,10 +4189,13 @@ function UpdateScreen() {
3546
4189
  import { Box as Box6, Text as Text7 } from "ink";
3547
4190
  import { jsx as jsx8, jsxs as jsxs6 } from "react/jsx-runtime";
3548
4191
  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}`;
4192
+ const ups = (m.packages ?? []).filter((p) => p.outcome === "upgraded" && p.toVersion);
4193
+ if (ups.length === 0) return "";
4194
+ if (ups.length === 1) {
4195
+ const p = ups[0];
4196
+ return p.fromVersion ? `${p.name} ${p.fromVersion} ${g.arrow} ${p.toVersion}` : `${p.name} ${g.arrow} ${p.toVersion}`;
4197
+ }
4198
+ return `${ups.length} ${t("ui", "upgraded")}`;
3553
4199
  }
3554
4200
  function ManagerRow({ m }) {
3555
4201
  const dur = m.durationMs !== void 0 ? `${(m.durationMs / 1e3).toFixed(1)}s` : "";
@@ -3574,16 +4220,19 @@ function ManagerRow({ m }) {
3574
4220
  ] });
3575
4221
  }
3576
4222
  function SummaryScreen() {
3577
- const { state, rescan } = useMachine();
4223
+ const { state, rescan, openDetail } = useMachine();
3578
4224
  useSafeInput((input) => {
3579
4225
  if (input === "r" || input === "R") rescan();
4226
+ else if (input === "d" || input === "D") openDetail();
3580
4227
  });
3581
4228
  const summary = summarizeRun(state);
3582
- const { upgraded, failed, skipped } = summary;
4229
+ const { upgraded, failed, skipped, unknown } = summary;
3583
4230
  const hasErrors = failed > 0;
4231
+ const hasPackages = summary.managers.some((m) => (m.packages ?? []).length > 0);
3584
4232
  const failures = [];
3585
4233
  const manuals = [];
3586
4234
  const reboots = [];
4235
+ const undetermined = [];
3587
4236
  for (const id of state.run.queue) {
3588
4237
  const e = state.managers[id];
3589
4238
  if (!e) continue;
@@ -3591,6 +4240,10 @@ function SummaryScreen() {
3591
4240
  if (e.manualCommand) manuals.push({ manager: id, command: e.manualCommand });
3592
4241
  continue;
3593
4242
  }
4243
+ if (e.status === "unknown") {
4244
+ undetermined.push(id);
4245
+ continue;
4246
+ }
3594
4247
  const r = e.result;
3595
4248
  if (r) {
3596
4249
  for (const f of r.failures) failures.push({ manager: id, package: f.package, message: f.message, kind: f.kind });
@@ -3600,6 +4253,25 @@ function SummaryScreen() {
3600
4253
  return /* @__PURE__ */ jsxs6(Box6, { flexDirection: "column", children: [
3601
4254
  /* @__PURE__ */ jsx8(StepHeader, { phase: state.phase }),
3602
4255
  /* @__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")}` }) }),
4256
+ undetermined.length > 0 && /* @__PURE__ */ jsx8(Box6, { flexDirection: "column", marginBottom: 1, children: /* @__PURE__ */ jsxs6(Text7, { color: semantic.unknown, children: [
4257
+ g.unknown,
4258
+ " ",
4259
+ undetermined.length,
4260
+ " ",
4261
+ t("ui", "undeterminedCount"),
4262
+ ":",
4263
+ " ",
4264
+ undetermined.map((id) => managerName(id)).join(", ")
4265
+ ] }) }),
4266
+ manuals.length > 0 && /* @__PURE__ */ jsxs6(Box6, { flexDirection: "column", marginBottom: 1, children: [
4267
+ /* @__PURE__ */ jsx8(Text7, { color: semantic.warning, children: t("ui", "manualNeeded") }),
4268
+ manuals.map((m, i) => /* @__PURE__ */ jsxs6(Text7, { color: semantic.muted, children: [
4269
+ " ",
4270
+ managerName(m.manager),
4271
+ ": ",
4272
+ /* @__PURE__ */ jsx8(Text7, { color: semantic.text, children: m.command })
4273
+ ] }, i))
4274
+ ] }),
3603
4275
  /* @__PURE__ */ jsxs6(Box6, { marginBottom: 1, children: [
3604
4276
  /* @__PURE__ */ jsxs6(Text7, { color: semantic.success, children: [
3605
4277
  upgraded,
@@ -3617,6 +4289,12 @@ function SummaryScreen() {
3617
4289
  skipped,
3618
4290
  " ",
3619
4291
  t("ui", "skipped")
4292
+ ] }),
4293
+ /* @__PURE__ */ jsx8(Text7, { color: semantic.muted, children: " \xB7 " }),
4294
+ /* @__PURE__ */ jsxs6(Text7, { color: unknown > 0 ? semantic.unknown : semantic.muted, children: [
4295
+ unknown,
4296
+ " ",
4297
+ t("ui", "undeterminedTotal")
3620
4298
  ] })
3621
4299
  ] }),
3622
4300
  summary.managers.length > 0 && /* @__PURE__ */ jsx8(Box6, { flexDirection: "column", marginBottom: 1, children: summary.managers.map((m) => /* @__PURE__ */ jsx8(ManagerRow, { m }, m.id)) }),
@@ -3639,15 +4317,6 @@ function SummaryScreen() {
3639
4317
  " 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
4318
  ] })
3641
4319
  ] }),
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
4320
  reboots.length > 0 && /* @__PURE__ */ jsx8(Box6, { marginBottom: 1, children: /* @__PURE__ */ jsxs6(Text7, { color: semantic.warning, children: [
3652
4321
  g.reboot,
3653
4322
  " Reinicio pendiente: ",
@@ -3658,18 +4327,18 @@ function SummaryScreen() {
3658
4327
  " ",
3659
4328
  getLogFilePath() ?? "~/.tacuchi-updater/logs/"
3660
4329
  ] }),
3661
- /* @__PURE__ */ jsx8(Box6, { marginTop: 1, children: /* @__PURE__ */ jsx8(Text7, { color: semantic.muted, children: t("ui", "summaryHint") }) })
4330
+ /* @__PURE__ */ jsx8(Box6, { marginTop: 1, children: /* @__PURE__ */ jsx8(Text7, { color: semantic.muted, children: hasPackages ? t("ui", "detailHint") : t("ui", "summaryHint") }) })
3662
4331
  ] });
3663
4332
  }
3664
4333
 
3665
4334
  // src/screens/settings-screen.tsx
3666
- import { useState as useState3 } from "react";
4335
+ import { useState as useState5 } from "react";
3667
4336
  import { Box as Box7, Text as Text8 } from "ink";
3668
4337
  import { jsx as jsx9, jsxs as jsxs7 } from "react/jsx-runtime";
3669
4338
  function SettingsScreen() {
3670
4339
  const { state, toggleEnabled, setLang, closeSettings } = useMachine();
3671
4340
  const ids = state.order;
3672
- const [cursor, setCursor] = useState3(0);
4341
+ const [cursor, setCursor] = useState5(0);
3673
4342
  const clamped = Math.min(cursor, Math.max(0, ids.length - 1));
3674
4343
  useSafeInput((input, key) => {
3675
4344
  if (key.escape) closeSettings();
@@ -3705,40 +4374,99 @@ function SettingsScreen() {
3705
4374
  ] });
3706
4375
  }
3707
4376
 
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 {
4377
+ // src/screens/detail.tsx
4378
+ import { useState as useState6 } from "react";
4379
+ import { Box as Box8, Text as Text9 } from "ink";
4380
+ import { jsx as jsx10, jsxs as jsxs8 } from "react/jsx-runtime";
4381
+ function glyphStatus(outcome) {
4382
+ switch (outcome) {
4383
+ case "upgraded":
4384
+ return "done";
4385
+ case "failed":
4386
+ return "failed";
4387
+ case "unknown":
4388
+ return "unknown";
4389
+ case "skipped":
4390
+ return "skipped";
4391
+ default:
4392
+ return "uptodate";
4393
+ }
4394
+ }
4395
+ function delta(from, to) {
4396
+ if (!from && !to) return "";
4397
+ if (!from) return `${g.arrow} ${to}`;
4398
+ if (!to) return from;
4399
+ return `${from} ${g.arrow} ${to}`;
4400
+ }
4401
+ function DetailScreen() {
4402
+ const { state, closeDetail } = useMachine();
4403
+ const [offset, setOffset] = useState6(0);
4404
+ const summary = summarizeRun(state);
4405
+ const rows = [];
4406
+ for (const m of summary.managers) {
4407
+ const packages = m.packages ?? [];
4408
+ if (packages.length === 0) continue;
4409
+ rows.push({ kind: "manager", managerId: m.id });
4410
+ for (const p of packages) {
4411
+ rows.push({
4412
+ kind: "package",
4413
+ managerId: m.id,
4414
+ name: p.name,
4415
+ outcome: p.outcome,
4416
+ right: delta(p.fromVersion, p.toVersion)
4417
+ });
3724
4418
  }
3725
4419
  }
3726
- cached = "0.0.0";
3727
- return cached;
4420
+ const width = Math.min((process.stdout.columns ?? 90) - 4, 92);
4421
+ const view = Math.max(6, (process.stdout.rows ?? 24) - 11);
4422
+ const maxOffset = Math.max(0, rows.length - view);
4423
+ const start = Math.min(offset, maxOffset);
4424
+ const visible = rows.slice(start, start + view);
4425
+ const nameWidth = Math.max(12, Math.min(32, width - 26));
4426
+ useSafeInput((input, key) => {
4427
+ if (input === "d" || input === "D") closeDetail();
4428
+ else if (key.downArrow || input === "j") setOffset((o) => Math.min(maxOffset, o + 1));
4429
+ else if (key.upArrow || input === "k") setOffset((o) => Math.max(0, o - 1));
4430
+ });
4431
+ return /* @__PURE__ */ jsxs8(Box8, { flexDirection: "column", children: [
4432
+ /* @__PURE__ */ jsx10(StepHeader, { phase: state.phase }),
4433
+ /* @__PURE__ */ jsx10(Text9, { color: colors.outline, children: start > 0 ? `${g.scrollUp} ${start}` : " " }),
4434
+ rows.length === 0 ? /* @__PURE__ */ jsx10(Text9, { color: semantic.muted, children: t("ui", "noChanges") }) : visible.map(
4435
+ (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: [
4436
+ /* @__PURE__ */ jsx10(Box8, { width: 2, children: /* @__PURE__ */ jsx10(StatusGlyph, { status: glyphStatus(r.outcome ?? "unchanged") }) }),
4437
+ /* @__PURE__ */ jsx10(Box8, { width: nameWidth, children: /* @__PURE__ */ jsx10(Text9, { color: semantic.text, wrap: "truncate-end", children: r.name }) }),
4438
+ /* @__PURE__ */ jsx10(Box8, { flexGrow: 1, justifyContent: "flex-end", children: /* @__PURE__ */ jsx10(Text9, { color: semantic.muted, wrap: "truncate-end", children: r.right }) })
4439
+ ] }, `p:${r.managerId}:${r.name}:${i}`)
4440
+ ),
4441
+ /* @__PURE__ */ jsx10(Text9, { color: colors.outline, children: start + visible.length < rows.length ? `${g.scrollDown} ${rows.length - start - visible.length}` : " " }),
4442
+ /* @__PURE__ */ jsx10(Box8, { marginTop: 1, children: /* @__PURE__ */ jsx10(Text9, { color: semantic.muted, children: t("ui", "detailBack") }) })
4443
+ ] });
3728
4444
  }
3729
4445
 
3730
4446
  // src/app.tsx
3731
- import { jsx as jsx10, jsxs as jsxs8 } from "react/jsx-runtime";
4447
+ import { jsx as jsx11, jsxs as jsxs9 } from "react/jsx-runtime";
3732
4448
  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: [
4449
+ const { selfUpdate } = useMachine();
4450
+ return /* @__PURE__ */ jsxs9(Box9, { justifyContent: "space-between", marginBottom: 1, children: [
4451
+ /* @__PURE__ */ jsxs9(Box9, { children: [
4452
+ /* @__PURE__ */ jsx11(Text10, { color: semantic.action, bold: true, children: "@tacuchi/updater" }),
4453
+ /* @__PURE__ */ jsxs9(Text10, { color: colors.outline, children: [
3737
4454
  " v",
3738
4455
  getVersion()
3739
- ] })
4456
+ ] }),
4457
+ selfUpdate ? (
4458
+ // `warning`, NOT `unknown`: el ámbar está reservado a «no se pudo
4459
+ // determinar» (DES-001@r1) y reusarlo acá lo vuelve a significar dos cosas.
4460
+ /* @__PURE__ */ jsxs9(Text10, { color: semantic.warning, children: [
4461
+ " ",
4462
+ "\u2192 v",
4463
+ selfUpdate.version,
4464
+ " \xB7 ",
4465
+ selfUpdate.howTo
4466
+ ] })
4467
+ ) : null
3740
4468
  ] }),
3741
- /* @__PURE__ */ jsx10(Text9, { color: sudoMode2 ? semantic.warning : colors.outline, children: sudoMode2 ? "SUDO" : `${process.platform}` })
4469
+ /* @__PURE__ */ jsx11(Text10, { color: sudoMode2 ? semantic.warning : colors.outline, children: sudoMode2 ? "SUDO" : `${process.platform}` })
3742
4470
  ] });
3743
4471
  }
3744
4472
  function PhaseRouter() {
@@ -3747,32 +4475,31 @@ function PhaseRouter() {
3747
4475
  case "boot":
3748
4476
  case "detecting":
3749
4477
  case "scanning":
3750
- return /* @__PURE__ */ jsx10(DetectScreen, {});
4478
+ return /* @__PURE__ */ jsx11(DetectScreen, {});
3751
4479
  case "select":
3752
- return /* @__PURE__ */ jsx10(SelectScreen, {});
4480
+ return /* @__PURE__ */ jsx11(SelectScreen, {});
3753
4481
  case "confirm":
3754
- return /* @__PURE__ */ jsx10(ConfirmScreen, {});
4482
+ return /* @__PURE__ */ jsx11(ConfirmScreen, {});
3755
4483
  case "updating":
3756
- return /* @__PURE__ */ jsx10(UpdateScreen, {});
4484
+ return /* @__PURE__ */ jsx11(UpdateScreen, {});
3757
4485
  case "summary":
3758
- return /* @__PURE__ */ jsx10(SummaryScreen, {});
4486
+ return /* @__PURE__ */ jsx11(SummaryScreen, {});
4487
+ case "detail":
4488
+ return /* @__PURE__ */ jsx11(DetailScreen, {});
3759
4489
  case "settings":
3760
- return /* @__PURE__ */ jsx10(SettingsScreen, {});
4490
+ return /* @__PURE__ */ jsx11(SettingsScreen, {});
3761
4491
  default:
3762
4492
  return null;
3763
4493
  }
3764
4494
  }
3765
4495
  function Shell({ sudoMode: sudoMode2 }) {
3766
- const { exit } = useInkApp();
4496
+ const { quitApp } = useMachine();
3767
4497
  useSafeInput((input) => {
3768
- if (input === "q" || input === "Q") {
3769
- exit();
3770
- process.exit(0);
3771
- }
4498
+ if (input === "q" || input === "Q") quitApp();
3772
4499
  });
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, {})
4500
+ return /* @__PURE__ */ jsxs9(Box9, { flexDirection: "column", paddingX: 1, width: Math.min(process.stdout.columns ?? 100, 100), children: [
4501
+ /* @__PURE__ */ jsx11(Header, { sudoMode: sudoMode2 }),
4502
+ /* @__PURE__ */ jsx11(PhaseRouter, {})
3776
4503
  ] });
3777
4504
  }
3778
4505
  function App({
@@ -3780,11 +4507,37 @@ function App({
3780
4507
  nonInteractive: nonInteractive2 = false
3781
4508
  }) {
3782
4509
  const machine = useAppMachine(sudoMode2, nonInteractive2);
3783
- return /* @__PURE__ */ jsx10(MachineProvider, { value: machine, children: /* @__PURE__ */ jsx10(Shell, { sudoMode: sudoMode2 }) });
4510
+ return /* @__PURE__ */ jsx11(MachineProvider, { value: machine, children: /* @__PURE__ */ jsx11(Shell, { sudoMode: sudoMode2 }) });
4511
+ }
4512
+
4513
+ // src/lib/signals.ts
4514
+ var COMMON = [
4515
+ { signal: "SIGINT", code: 130, mode: "cancelada" },
4516
+ { signal: "SIGTERM", code: 143, mode: "interrumpida" },
4517
+ // The console window closing. On Windows Node raises it too, with a grace
4518
+ // period the OS controls — which is why the closing block is written
4519
+ // SYNCHRONOUSLY inside the handler and not after any timer.
4520
+ { signal: "SIGHUP", code: 129, mode: "interrumpida" }
4521
+ ];
4522
+ var WINDOWS_ONLY = [{ signal: "SIGBREAK", code: 130, mode: "cancelada" }];
4523
+ function signalRoutes(platform) {
4524
+ return platform === "win32" ? [...COMMON, ...WINDOWS_ONLY] : COMMON;
4525
+ }
4526
+ var SIGNAL_GRACE_MS = 200;
4527
+ function answerSignal(route, effects) {
4528
+ effects.settle(route.mode, `se\xF1al ${route.signal}`);
4529
+ effects.cancel();
4530
+ effects.schedule(() => {
4531
+ try {
4532
+ effects.unmount();
4533
+ } catch {
4534
+ }
4535
+ effects.exit(route.code);
4536
+ }, SIGNAL_GRACE_MS);
3784
4537
  }
3785
4538
 
3786
4539
  // src/cli.tsx
3787
- import { jsx as jsx11 } from "react/jsx-runtime";
4540
+ import { jsx as jsx12 } from "react/jsx-runtime";
3788
4541
  var args = process.argv.slice(2);
3789
4542
  var sudoRequested = args.includes("--sudo") || args.includes("-s");
3790
4543
  var isRoot = process.getuid?.() === 0;
@@ -3837,15 +4590,18 @@ if (process.platform === "win32" && sudoRequested && !elevated) {
3837
4590
  }
3838
4591
  var sudoMode = process.platform === "win32" ? elevated : isRoot || sudoRequested;
3839
4592
  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"));
4593
+ var { unmount } = render(/* @__PURE__ */ jsx12(App, { sudoMode, nonInteractive }));
4594
+ for (const route of signalRoutes(process.platform)) {
4595
+ process.on(
4596
+ route.signal,
4597
+ () => answerSignal(route, {
4598
+ settle: (mode, detail) => settleRun(mode, detail),
4599
+ cancel: fireProcessCancel,
4600
+ unmount,
4601
+ exit: (exitCode) => process.exit(exitCode),
4602
+ schedule: (fn, ms) => {
4603
+ setTimeout(fn, ms);
4604
+ }
4605
+ })
4606
+ );
4607
+ }