Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 31 additions & 0 deletions native/core/src/features/updater.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ pub const PRIMER_CHEQUEO_MS: u64 = 20_000;
/// Con la ventana oculta o con batería, el chequeo automático se reintenta en 5 minutos.
pub const REINTENTO_MS: u64 = 5 * 60 * 1000;

/// Sin teclado ni mouse este rato, se considera que nadie está usando la PC.
pub const INACTIVO_MS: u64 = 15 * 60 * 1000;
/// Cada cuánto se mira si ya se puede instalar sola.
pub const MIRAR_LIBRE_MS: u64 = 60_000;
pub const SIN_DESCARGAR: &str = "Todavía no hay una actualización descargada.";
pub const BUSCA_PRIMERO: &str = "Primero buscá una actualización.";
pub const EN_DESARROLLO_CHEQUEO: &str = "En desarrollo no se buscan actualizaciones: solo en la app instalada.";
Expand Down Expand Up @@ -287,6 +291,22 @@ impl Estado {
}
}

/// Cómo está la PC cuando hay una versión descargada esperando.
#[derive(Debug, Clone, Copy)]
pub struct Momento {
pub inactivo_ms: u64,
/// Algún agente trabajando o esperando una respuesta.
pub agentes_ocupados: bool,
/// «Dejar las terminales vivas» apagado y con terminales abiertas: reiniciar las cerraría.
pub cierra_terminales: bool,
}

/// Instalar sin que nadie lo pida en ese momento: solo con permiso (el ajuste o «Cuando no la esté usando»), sin «Más tarde»
/// de hoy y sin cortar nada.
pub fn instalar_sola(permitida: bool, pospuesta_hoy: bool, m: Momento) -> bool {
permitida && !pospuesta_hoy && m.inactivo_ms >= INACTIVO_MS && !m.agentes_ocupados && !m.cierra_terminales
}

/// Canal beta: el `latest.json` del release más nuevo, aunque sea prerelease (la API de GitHub los lista del más nuevo
/// al más viejo). El estable usa el endpoint de tauri.conf.json, que es `releases/latest` y nunca da un prerelease.
pub fn latest_json_beta(releases: &Value) -> Option<String> {
Expand Down Expand Up @@ -336,6 +356,17 @@ mod tests {
Estado::nuevo("0.8.0", true, Canal::Estable)
}

#[test]
fn se_instala_sola_solo_con_permiso_y_sin_cortar_nada() {
let libre = Momento { inactivo_ms: INACTIVO_MS, agentes_ocupados: false, cierra_terminales: false };
assert!(instalar_sola(true, false, libre));
assert!(!instalar_sola(false, false, libre));
assert!(!instalar_sola(true, true, libre));
for m in [Momento { inactivo_ms: INACTIVO_MS - 1, ..libre }, Momento { agentes_ocupados: true, ..libre }, Momento { cierra_terminales: true, ..libre }] {
assert!(!instalar_sola(true, false, m), "{m:?}");
}
}

#[test]
fn amigable_traduce_los_errores_de_red() {
for m in ["getaddrinfo ENOTFOUND github.com", "connect ECONNREFUSED", "net::ERR_FAILED", "ETIMEDOUT", "error sending request for url (https://github.com/x)", "dns error: no such host"] {
Expand Down
10 changes: 7 additions & 3 deletions native/core/src/settings_model.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ pub fn por_defecto() -> Objeto {
"ui": { "reduceMotion": false, "workingAnim": true, "contrast": "normal", "intensity": "normal", "corners": "suaves", "uiFont": "inter", "listWidth": 300, "labels": true, "watermark": true, "chips": "texto", "branch": true },
"updateChannel": "estable",
"installOnQuit": false,
"autoUpdate": true,
"lightMode": false,
"shortcuts": {},
"rendimiento": { "enchufada": { "ramMB": 0, "nucleos": 0 }, "bateria": { "ramMB": 0, "nucleos": 0 }, "bateriaDistinta": false }
Expand Down Expand Up @@ -288,7 +289,7 @@ pub fn aplicar_cambio(actual: &Objeto, patch: &Value, existe_cuenta: Option<&dyn
p,
&[
"theme", "density", "uiFontSize", "accent", "terminal", "accountColors", "accountPlans", "accountCategorias", "accountCupos", "relevoCupo", "openAtLogin", "confirmClosePanes", "reopenSpaces", "keepTerminalsAlive", "confirmQuit", "sleepAfterMin", "editor",
"projectsDir", "sounds", "soundName", "noMolestar", "noMolestarNoche", "notify", "ui", "updateChannel", "installOnQuit", "lightMode", "shortcuts", "rendimiento",
"projectsDir", "sounds", "soundName", "noMolestar", "noMolestarNoche", "notify", "ui", "updateChannel", "installOnQuit", "autoUpdate", "lightMode", "shortcuts", "rendimiento",
],
"",
)?;
Expand Down Expand Up @@ -348,6 +349,9 @@ pub fn aplicar_cambio(actual: &Objeto, patch: &Value, existe_cuenta: Option<&dyn
if let Some(v) = p.get("updateChannel") {
poner(&mut next, "updateChannel", Value::String(uno_de(v, &UPDATE_CHANNELS, "El canal de actualizaciones")?));
}
if let Some(v) = p.get("autoUpdate") {
poner(&mut next, "autoUpdate", booleano(v, "«Actualizar Sloth solo»")?);
}
if let Some(v) = p.get("installOnQuit") {
poner(&mut next, "installOnQuit", booleano(v, "«Instalar al cerrar Sloth»")?);
}
Expand Down Expand Up @@ -565,7 +569,7 @@ pub fn normalizar(raw: &Value) -> Objeto {
}
};
for k in [
"theme", "density", "uiFontSize", "accent", "relevoCupo", "openAtLogin", "confirmClosePanes", "reopenSpaces", "keepTerminalsAlive", "confirmQuit", "sleepAfterMin", "editor", "projectsDir", "sounds", "soundName", "noMolestar", "noMolestarNoche", "updateChannel", "installOnQuit",
"theme", "density", "uiFontSize", "accent", "relevoCupo", "openAtLogin", "confirmClosePanes", "reopenSpaces", "keepTerminalsAlive", "confirmQuit", "sleepAfterMin", "editor", "projectsDir", "sounds", "soundName", "noMolestar", "noMolestarNoche", "updateChannel", "installOnQuit", "autoUpdate",
"lightMode",
] {
if let Some(v) = src.get(k) {
Expand Down Expand Up @@ -632,7 +636,7 @@ pub fn restaurar_seccion(actual: &Objeto, seccion: &Value) -> Result<Objeto, Str
Some("general") => copiar(&mut next, &["reopenSpaces", "keepTerminalsAlive", "confirmQuit", "sleepAfterMin", "openAtLogin", "confirmClosePanes", "editor", "projectsDir"]),
Some("notif") => copiar(&mut next, &["notify", "noMolestar", "noMolestarNoche", "sounds", "soundName"]),
Some("atajos") => copiar(&mut next, &["shortcuts"]),
Some("updates") => copiar(&mut next, &["updateChannel", "installOnQuit"]),
Some("updates") => copiar(&mut next, &["updateChannel", "installOnQuit", "autoUpdate"]),
Some("rendimiento") => copiar(&mut next, &["rendimiento"]),
_ => return Err("Sección desconocida.".into()),
}
Expand Down
2 changes: 1 addition & 1 deletion src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ ureq = { version = "2", default-features = false, features = ["tls"] }
webview2-com = "0.39"
png = "0.17"
clipboard-win = "5"
windows-sys = { version = "0.59", features = ["Win32_Foundation", "Win32_NetworkManagement_IpHelper", "Win32_NetworkManagement_Ndis", "Win32_Networking_WinSock", "Win32_System_Power", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Time", "Win32_System_Com", "Win32_System_LibraryLoader", "Win32_UI_Controls", "Win32_UI_WindowsAndMessaging"] }
windows-sys = { version = "0.59", features = ["Win32_Foundation", "Win32_NetworkManagement_IpHelper", "Win32_NetworkManagement_Ndis", "Win32_Networking_WinSock", "Win32_System_Power", "Win32_System_Registry", "Win32_System_SystemInformation", "Win32_System_Time", "Win32_System_Com", "Win32_System_LibraryLoader", "Win32_UI_Controls", "Win32_UI_Input_KeyboardAndMouse", "Win32_UI_WindowsAndMessaging"] }
tokio = { version = "1", features = ["sync", "rt", "net", "io-util", "time"] }
serde = { version = "1", features = ["derive"] }
serde_json = { version = "1", features = ["preserve_order"] }
Expand Down
1 change: 1 addition & 0 deletions src-tauri/src/canales-ui.txt
Original file line number Diff line number Diff line change
Expand Up @@ -221,6 +221,7 @@ feat:updater:install
feat:updater:later
feat:updater:queue
feat:updater:status
feat:updater:whenIdle
feat:worktrees:clean
feat:worktrees:create
feat:worktrees:openFolder
Expand Down
114 changes: 105 additions & 9 deletions src-tauri/src/handlers/updater.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@ use crate::entorno::Entorno;
use crate::router::Router;
use serde_json::Value;
use sloth_core::features::updater::{
amigable, canal_de_ajustes, cuerpo_del_release, instalar_al_cerrar, latest_json_beta, pospuesta_el, proximo_chequeo_ms, tags_de, Canal, Encontrada, Estado, Fase, Pospuesta,
BUSCA_PRIMERO, EN_DESARROLLO_CHEQUEO, EN_DESARROLLO_DESCARGA, PRIMER_CHEQUEO_MS, REINTENTO_MS, SIN_CONEXION, SIN_DESCARGAR,
amigable, canal_de_ajustes, cuerpo_del_release, instalar_al_cerrar, instalar_sola, latest_json_beta, pospuesta_el, proximo_chequeo_ms, tags_de, Canal, Encontrada, Estado, Fase, Momento, Pospuesta,
BUSCA_PRIMERO, EN_DESARROLLO_CHEQUEO, EN_DESARROLLO_DESCARGA, MIRAR_LIBRE_MS, PRIMER_CHEQUEO_MS, REINTENTO_MS, SIN_CONEXION, SIN_DESCARGAR,
};
use sloth_core::features::updater_notas::agrupar_notas;
use std::fs;
Expand Down Expand Up @@ -48,14 +48,16 @@ pub struct Actualizador {
instalar_al_salir: AtomicBool,
/// Lo que decidió `al_salir` (antes de tocar las terminales) para que `al_salir_final` lo ejecute.
instalar_al_final: AtomicBool,
/// «Cuando no la esté usando», aunque la actualización automática esté apagada.
cuando_libre: AtomicBool,
/// Cierra la app por el camino de siempre (el instalador corre al salir).
salir: Arc<dyn Fn() + Send + Sync>,
}

impl Actualizador {
pub fn nuevo(entorno: Arc<Entorno>, fuente: Arc<dyn Fuente>, habilitado: bool, salir: Arc<dyn Fn() + Send + Sync>) -> Arc<Actualizador> {
let estado = Estado::nuevo(&entorno.plataforma.version(), habilitado, Canal::Estable);
Arc::new(Actualizador { entorno, fuente, habilitado, estado: Mutex::new(estado), descarga: AtomicU64::new(0), instalar_al_salir: AtomicBool::new(false), instalar_al_final: AtomicBool::new(false), salir })
Arc::new(Actualizador { entorno, fuente, habilitado, estado: Mutex::new(estado), descarga: AtomicU64::new(0), instalar_al_salir: AtomicBool::new(false), instalar_al_final: AtomicBool::new(false), cuando_libre: AtomicBool::new(false), salir })
}

fn con_estado<T>(&self, f: impl FnOnce(&mut Estado) -> T) -> T {
Expand Down Expand Up @@ -222,6 +224,52 @@ impl Actualizador {
Ok(self.emitir())
}

fn automatica(&self) -> bool {
comun::ajuste(&self.entorno, "autoUpdate").and_then(|v| v.as_bool()).unwrap_or(true)
}

pub fn instalar_cuando_este_libre(self: &Arc<Self>) -> Result<Value, String> {
if !matches!(self.con_estado(|s| s.state), Fase::Ready | Fase::Downloading) {
self.bajar()?;
}
self.cuando_libre.store(true, Ordering::SeqCst);
Ok(self.estado())
}

/// Con la actualización automática, lo que se encontró se baja sin preguntar.
fn bajar_sola(self: &Arc<Self>) {
if self.automatica() && self.con_estado(|s| s.state == Fase::Available && s.later != Some(true)) {
if let Err(e) = self.bajar() {
sloth_core::logger_global::aviso(NOMBRE, &format!("no se pudo bajar la actualización: {e}"));
}
}
}

/// Avisa a la UI que ya se puede instalar sin molestar. La orden la da ella, que sabe si hay algo escrito sin guardar.
pub fn mirar_si_esta_libre(&self, medir: impl FnOnce() -> Momento) -> bool {
let (fase, version) = self.con_estado(|s| (s.state, s.version.clone()));
let (Fase::Ready, Some(version)) = (fase, version) else { return false };
let permitida = self.automatica() || self.cuando_libre.load(Ordering::SeqCst);
let hoy = pospuesta_el(self.pospuesta().as_ref(), &version, &comun::fecha_local(comun::ahora_ms()));
let si = permitida && instalar_sola(permitida, hoy, medir());
if si {
self.entorno.emitir(NOMBRE, "libre", &[]);
}
si
}

pub fn programar_instalacion(self: &Arc<Self>, medir: impl Fn() -> Momento + Send + 'static) {
if !self.habilitado {
return;
}
let a = Arc::downgrade(self);
std::thread::spawn(move || loop {
std::thread::sleep(Duration::from_millis(MIRAR_LIBRE_MS));
let Some(act) = a.upgrade() else { return };
act.mirar_si_esta_libre(&medir);
});
}

pub fn instalar(&self) -> Result<Value, String> {
let (fase, version) = self.con_estado(|s| (s.state, s.version.clone()));
if fase != Fase::Ready {
Expand All @@ -233,8 +281,8 @@ impl Actualizador {
Ok(Value::Bool(true))
}

/// El chequeo automático: la ventana oculta (bandeja), minimizada o la batería lo posponen 5 minutos.
pub fn programar(self: &Arc<Self>, puede_buscar: impl Fn() -> bool + Send + 'static) {
/// El chequeo automático: la batería lo pospone 5 minutos; sin actualización automática, también la ventana a la que nadie mira.
pub fn programar(self: &Arc<Self>, puede_buscar: impl Fn(bool) -> bool + Send + 'static) {
if !self.habilitado {
return;
}
Expand All @@ -243,8 +291,9 @@ impl Actualizador {
std::thread::sleep(Duration::from_millis(PRIMER_CHEQUEO_MS));
loop {
let Some(act) = a.upgrade() else { return };
let espera = if puede_buscar() {
let espera = if puede_buscar(act.automatica()) {
act.buscar(false);
act.bajar_sola();
let liviano = comun::ajuste(&act.entorno, "lightMode").and_then(|v| v.as_bool()).unwrap_or(false);
proximo_chequeo_ms(liviano)
} else {
Expand Down Expand Up @@ -309,6 +358,8 @@ pub fn registrar(router: &mut Router, actualizador: &Arc<Actualizador>) {
let a = actualizador.clone();
router.registrar("feat:updater:queue", move |_| a.encolar());
let a = actualizador.clone();
router.registrar("feat:updater:whenIdle", move |_| a.instalar_cuando_este_libre());
let a = actualizador.clone();
router.registrar("feat:updater:install", move |_| a.instalar());
}

Expand Down Expand Up @@ -397,17 +448,33 @@ fn instalada(app: &AppHandle) -> bool {
crate::recursos::raiz_de_la_app(app).1
}

/// Ante la duda (todavía sin núcleo o sin daemon que conteste) se da por ocupada.
fn momento(app: &AppHandle) -> Momento {
let Some(n) = app.try_state::<Arc<crate::nucleo::Nucleo>>() else {
return Momento { inactivo_ms: 0, agentes_ocupados: true, cierra_terminales: true };
};
let trabajando = n.agentes_json().as_object().is_some_and(|m| m.values().any(|a| matches!(a["state"].as_str(), Some("working" | "waiting"))));
let cierra = !n.ajuste_bool("keepTerminalsAlive") && n.info_daemon().ok().and_then(|i| i["sessions"].as_u64()) != Some(0);
Momento { inactivo_ms: crate::sistema::inactivo_ms(), agentes_ocupados: trabajando || !n.permisos_pendientes().is_empty(), cierra_terminales: cierra }
}

/// Arma el actualizador sobre `tauri_plugin_updater` y programa la búsqueda; sus canales los registra `canales.rs`.
pub fn armar_en_tauri(entorno: Arc<Entorno>, app: AppHandle) -> Arc<Actualizador> {
let fuente = Arc::new(FuenteTauri::nueva(app.clone(), API_GITHUB));
let app_salir = app.clone();
// Sale como el menú «Salir» de la bandeja; el instalador corre en `al_salir_final`.
let a = Actualizador::nuevo(entorno, fuente, instalada(&app), Arc::new(move || super::tray::salir_de_la_app(&app_salir)));
// Las pruebas e2e corren sobre el build instalable: ahí no se sale a buscar versiones ni se reinicia nada.
if std::env::var_os("SLOTH_E2E").is_some() {
return a;
}
let app_v = app.clone();
a.programar(move || {
let ventana_a_la_vista = app_v.get_webview_window("main").is_some_and(|w| w.is_visible().unwrap_or(false) && !w.is_minimized().unwrap_or(false));
ventana_a_la_vista && crate::sistema::con_corriente() != Some(false)
a.programar(move |automatica| {
let ventana_a_la_vista = || app_v.get_webview_window("main").is_some_and(|w| w.is_visible().unwrap_or(false) && !w.is_minimized().unwrap_or(false));
(automatica || ventana_a_la_vista()) && crate::sistema::con_corriente() != Some(false)
});
let app_m = app.clone();
a.programar_instalacion(move || momento(&app_m));
a
}

Expand Down Expand Up @@ -702,6 +769,35 @@ mod tests {
assert_eq!(p.a.bajar().unwrap()["state"], json!("ready"));
}

#[tokio::test(flavor = "multi_thread")]
async fn se_baja_sola_y_avisa_solo_cuando_se_puede_instalar_sin_molestar() {
let libre = Momento { inactivo_ms: sloth_core::features::updater::INACTIVO_MS, agentes_ocupados: false, cierra_terminales: false };
let ocupada = Momento { agentes_ocupados: true, ..libre };
let avisos = |p: &Prueba| p.t.eventos().iter().filter(|(c, _)| c == "feat:updater:libre").count();

let p = armar("upd-sola", true, json!({}));
encontrar(&p, "0.9.0", "");
p.a.buscar(false);
p.a.bajar_sola();
hasta(&p, "ready").await;
assert!(!p.a.mirar_si_esta_libre(|| ocupada));
assert!(p.a.mirar_si_esta_libre(|| libre));
assert_eq!(avisos(&p), 1);
p.a.posponer();
assert!(!p.a.mirar_si_esta_libre(|| libre));

let p = armar("upd-a-mano", true, json!({ "autoUpdate": false }));
encontrar(&p, "0.9.0", "");
p.a.buscar(false);
p.a.bajar_sola();
assert_eq!(p.a.estado()["state"], json!("available"));
p.a.bajar().unwrap();
hasta(&p, "ready").await;
assert!(!p.a.mirar_si_esta_libre(|| libre));
p.a.instalar_cuando_este_libre().unwrap();
assert!(p.a.mirar_si_esta_libre(|| libre));
}

#[tokio::test(flavor = "multi_thread")]
async fn una_descarga_cancelada_no_queda_lista_al_terminar() {
let p = armar("upd-cancelar", true, json!({}));
Expand Down
19 changes: 19 additions & 0 deletions src-tauri/src/sistema.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,25 @@ pub fn con_corriente() -> Option<bool> {
None
}

/// Cuánto hace que nadie toca el teclado ni el mouse.
#[cfg(windows)]
pub fn inactivo_ms() -> u64 {
use windows_sys::Win32::System::SystemInformation::GetTickCount;
use windows_sys::Win32::UI::Input::KeyboardAndMouse::{GetLastInputInfo, LASTINPUTINFO};
let mut u = LASTINPUTINFO { cbSize: std::mem::size_of::<LASTINPUTINFO>() as u32, dwTime: 0 };
// SAFETY: `u` es un LASTINPUTINFO válido con su tamaño puesto, como pide la API.
if unsafe { GetLastInputInfo(&mut u) } == 0 {
return 0;
}
// Los dos contadores dan la vuelta cada 49 días: la resta con vuelta sigue siendo correcta.
u64::from(unsafe { GetTickCount() }.wrapping_sub(u.dwTime))
}

#[cfg(not(windows))]
pub fn inactivo_ms() -> u64 {
0
}

/// La RAM física en MB, como `os.totalmem()` de Node.
#[cfg(windows)]
pub fn ram_total_mb() -> u64 {
Expand Down
2 changes: 2 additions & 0 deletions src/renderer/src/Modal.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { focusables, nextFocusIndex } from './focus-trap'
import { Button } from './ui/Button'
import { IconButton } from './ui/IconButton'
import { useExit } from './ui/useExit'
import { marcarSinGuardar } from './ui/sin-guardar'

export interface ModalProps {
title: ReactNode
Expand Down Expand Up @@ -53,6 +54,7 @@ export function Modal(p: ModalProps): React.JSX.Element {
escRef.current = onEscape
askingRef.current = asking
dirtyRef.current = !!dirty
useEffect(() => (dirty ? marcarSinGuardar() : undefined), [dirty])
closeRef.current = onClose
const [closing, leave] = useExit(() => closeRef.current())

Expand Down
Loading
Loading