diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index e44ab05..a48e807 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -30,12 +30,8 @@ jobs: env: GH_TOKEN: ${{ github.token }} - - name: Metric checks - run: | - mkdir -p Build/Checks - xcrun swiftc -swift-version 6 -strict-concurrency=complete -O \ - FreeRAMMac/MemoryMetrics.swift Tests/MemoryMetricsChecks.swift -o Build/Checks/MemoryMetricsChecks - Build/Checks/MemoryMetricsChecks + - name: Checks (metrics, real purge request, login item) + run: Tools/check.sh - name: Build universal Release run: | diff --git a/Free RAM Mac.xcodeproj/project.pbxproj b/Free RAM Mac.xcodeproj/project.pbxproj index 135bae9..6016b99 100644 --- a/Free RAM Mac.xcodeproj/project.pbxproj +++ b/Free RAM Mac.xcodeproj/project.pbxproj @@ -12,6 +12,7 @@ 200000000000000000000003 /* MemoryMetrics.swift in Sources */ = {isa = PBXBuildFile; fileRef = 100000000000000000000003 /* MemoryMetrics.swift */; }; 200000000000000000000004 /* RecoveryService.swift in Sources */ = {isa = PBXBuildFile; fileRef = 100000000000000000000004 /* RecoveryService.swift */; }; 200000000000000000000005 /* MenuBarView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 100000000000000000000005 /* MenuBarView.swift */; }; + 200000000000000000000006 /* LoginItem.swift in Sources */ = {isa = PBXBuildFile; fileRef = 100000000000000000000006 /* LoginItem.swift */; }; 200000000000000000000010 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 100000000000000000000010 /* Assets.xcassets */; }; /* End PBXBuildFile section */ @@ -21,6 +22,7 @@ 100000000000000000000003 /* MemoryMetrics.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MemoryMetrics.swift; sourceTree = ""; }; 100000000000000000000004 /* RecoveryService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecoveryService.swift; sourceTree = ""; }; 100000000000000000000005 /* MenuBarView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MenuBarView.swift; sourceTree = ""; }; + 100000000000000000000006 /* LoginItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LoginItem.swift; sourceTree = ""; }; 100000000000000000000010 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 100000000000000000000011 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 100000000000000000000012 /* Free RAM Mac.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "Free RAM Mac.app"; sourceTree = BUILT_PRODUCTS_DIR; }; @@ -55,6 +57,7 @@ 100000000000000000000003 /* MemoryMetrics.swift */, 100000000000000000000004 /* RecoveryService.swift */, 100000000000000000000005 /* MenuBarView.swift */, + 100000000000000000000006 /* LoginItem.swift */, 100000000000000000000010 /* Assets.xcassets */, 100000000000000000000011 /* Info.plist */, ); @@ -144,6 +147,7 @@ 200000000000000000000003 /* MemoryMetrics.swift in Sources */, 200000000000000000000004 /* RecoveryService.swift in Sources */, 200000000000000000000005 /* MenuBarView.swift in Sources */, + 200000000000000000000006 /* LoginItem.swift in Sources */, ); runOnlyForDeploymentPostprocessing = 0; }; diff --git a/FreeRAMMac/AppDelegate.swift b/FreeRAMMac/AppDelegate.swift index f1f3b61..c6653cd 100644 --- a/FreeRAMMac/AppDelegate.swift +++ b/FreeRAMMac/AppDelegate.swift @@ -21,6 +21,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate { private let idleImage = NSImage(systemSymbolName: "memorychip", accessibilityDescription: "Free RAM Mac") private let busyImage = NSImage(systemSymbolName: "memorychip.fill", accessibilityDescription: "Free RAM Mac") private let monitor = MemoryMonitor() + private let loginItem = LoginItem() func applicationDidFinishLaunching(_ notification: Notification) { NSApp.setActivationPolicy(.accessory) @@ -128,6 +129,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate { menu.addItem(menuItem("Ver detalles", action: #selector(showPopover))) menu.addItem(menuItem("Recuperar memoria purgable", action: #selector(recoverFromUserClick), enabled: !monitor.isRecovering)) menu.addItem(.separator()) + let login = loginItem.state + let loginMenuItem = menuItem(login.menuTitle, action: #selector(toggleLoginItem), + enabled: login != .unavailable) + loginMenuItem.state = login.isChecked ? .on : .off + menu.addItem(loginMenuItem) menu.addItem(menuItem("Cómo funciona…", action: #selector(showHelp))) menu.addItem(.separator()) menu.addItem(menuItem("Salir de Free RAM Mac", action: #selector(quit), enabled: !monitor.isRecovering)) @@ -143,6 +149,26 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSPopoverDelegate { return item } + @objc private func toggleLoginItem() { + let target = loginItem.state.nextEnabled + do { + if try loginItem.setEnabled(target) == .requiresApproval { + let alert = NSAlert() + alert.messageText = "Falta tu aprobación" + alert.informativeText = "macOS registró Free RAM Mac, pero debes permitirla en Ajustes del Sistema → General → Elementos de inicio." + alert.addButton(withTitle: "Abrir Ajustes") + alert.addButton(withTitle: "Más tarde") + NSApp.activate(ignoringOtherApps: true) + if alert.runModal() == .alertFirstButtonReturn { loginItem.openSystemSettings() } + } + } catch { + let alert = NSAlert(error: error) + alert.messageText = target ? "No se pudo activar el inicio de sesión" : "No se pudo desactivar el inicio de sesión" + NSApp.activate(ignoringOtherApps: true) + alert.runModal() + } + } + @objc private func showHelp() { popover?.performClose(nil) if helpWindow == nil { diff --git a/FreeRAMMac/Assets.xcassets/AppIcon.appiconset/icon_128x128@2x.png b/FreeRAMMac/Assets.xcassets/AppIcon.appiconset/icon_128x128@2x.png new file mode 100644 index 0000000..d88fde6 Binary files /dev/null and b/FreeRAMMac/Assets.xcassets/AppIcon.appiconset/icon_128x128@2x.png differ diff --git a/FreeRAMMac/Assets.xcassets/AppIcon.appiconset/icon_16x16@2x.png b/FreeRAMMac/Assets.xcassets/AppIcon.appiconset/icon_16x16@2x.png new file mode 100644 index 0000000..571da0d Binary files /dev/null and b/FreeRAMMac/Assets.xcassets/AppIcon.appiconset/icon_16x16@2x.png differ diff --git a/FreeRAMMac/Assets.xcassets/AppIcon.appiconset/icon_256x256@2x.png b/FreeRAMMac/Assets.xcassets/AppIcon.appiconset/icon_256x256@2x.png new file mode 100644 index 0000000..50e0a3d Binary files /dev/null and b/FreeRAMMac/Assets.xcassets/AppIcon.appiconset/icon_256x256@2x.png differ diff --git a/FreeRAMMac/LoginItem.swift b/FreeRAMMac/LoginItem.swift new file mode 100644 index 0000000..8bb8bb6 --- /dev/null +++ b/FreeRAMMac/LoginItem.swift @@ -0,0 +1,59 @@ +import Foundation +import ServiceManagement + +/// What the menu shows for "Abrir al iniciar sesión". Kept free of AppKit so the +/// mapping can be checked by a standalone executable (Tests/LoginItemChecks.swift). +enum LoginItemState: Equatable, Sendable { + case disabled + case enabled + /// Registered, but the user must allow it in System Settings → Login Items. + case requiresApproval + /// macOS could not find the app bundle (e.g. running from a translocated path). + case unavailable + + init(_ status: SMAppService.Status) { + switch status { + case .enabled: self = .enabled + case .requiresApproval: self = .requiresApproval + case .notRegistered: self = .disabled + case .notFound: self = .unavailable + @unknown default: self = .unavailable + } + } + + var isChecked: Bool { self == .enabled || self == .requiresApproval } + + var menuTitle: String { + switch self { + case .requiresApproval: return "Abrir al iniciar sesión (pendiente de aprobación)" + default: return "Abrir al iniciar sesión" + } + } + + /// The toggle the menu item performs from this state. + var nextEnabled: Bool { !isChecked } +} + +/// Opt-in launch at login through `SMAppService.mainApp` (macOS 13+). Nothing is +/// registered unless the user picks the menu item; there is no helper or daemon. +@MainActor +final class LoginItem { + private let service = SMAppService.mainApp + + var state: LoginItemState { LoginItemState(service.status) } + + /// Returns the resulting state; throws the ServiceManagement error as-is. + @discardableResult + func setEnabled(_ enabled: Bool) throws -> LoginItemState { + if enabled { + if service.status != .enabled { try service.register() } + } else if service.status != .notRegistered { + try service.unregister() + } + return state + } + + func openSystemSettings() { + SMAppService.openSystemSettingsLoginItems() + } +} diff --git a/FreeRAMMac/MenuBarView.swift b/FreeRAMMac/MenuBarView.swift index 72e7c67..7939a09 100644 --- a/FreeRAMMac/MenuBarView.swift +++ b/FreeRAMMac/MenuBarView.swift @@ -139,7 +139,7 @@ struct MemoryHelpView: View { ScrollView { VStack(alignment: .leading, spacing: 20) { Label("Free RAM Mac", systemImage: "memorychip.fill").font(.title2.weight(.semibold)) - explanation("Un clic desde la barra de menús", "El clic principal intenta recuperar memoria purgable en segundo plano, sin abrir ventanas ni pedir contraseña. El clic secundario permite consultar detalles. Mientras hay una solicitud activa no se inicia otra. La app no se ejecuta al iniciar sesión.") + explanation("Un clic desde la barra de menús", "El clic principal intenta recuperar memoria purgable en segundo plano, sin abrir ventanas ni pedir contraseña. El clic secundario permite consultar detalles. Mientras hay una solicitud activa no se inicia otra. La app no se ejecuta al iniciar sesión salvo que actives «Abrir al iniciar sesión» en el menú secundario.") explanation("El porcentaje de la barra", "Es la RAM en uso estimada dividida por la RAM física total, con un decimal. Se mide cada dos segundos y al comenzar y terminar la recuperación, también con el panel cerrado. Excluye la caché de archivos de la categoría en uso; no es el porcentaje de memoria que se puede liberar ni una réplica exacta de Monitor de Actividad. Puede subir, bajar o quedarse igual. Si la lectura falla, aparece —% en lugar de mostrar una cifra anterior como actual.") explanation("Qué se recupera de verdad", "Usamos mach_vm_purgable_control con VM_PURGABLE_PURGE_ALL. macOS descarta objetos volátiles que sus propias apps declararon prescindibles. El alcance es global, no solo esta app. No equivale a toda la caché de archivos; algunas apps pueden reconstruir cachés y hacer trabajo adicional después.") explanation("Tus programas siguen abiertos", "No se cierran ni pausan procesos, no se borran archivos ni se crean asignaciones grandes para forzar presión. La memoria privada normal de un modelo de IA permanece en uso. La app no vacía swap ni libera memoria cableada. No se puede garantizar ausencia de latencia al reconstruir cachés.") diff --git a/README.es.md b/README.es.md index fd0c9df..0a1da3a 100644 --- a/README.es.md +++ b/README.es.md @@ -9,9 +9,11 @@ Posicionamiento, textos localizados, guion de capturas y pendientes de App Store Abre `Build/Products/Release/Free RAM Mac.app`. Al arrancar aparece el icono con el porcentaje de RAM en uso en la barra, sin abrir paneles ni recuperar memoria automáticamente. - **Clic principal en el chip de la barra:** intenta recuperar memoria purgable silenciosamente, sin abrir panel ni informe. El porcentaje sigue mostrando mediciones del sistema, también durante la recuperación. Otro clic durante una solicitud activa no inicia otra. -- **Clic secundario o Control-clic:** abre las opciones para consultar detalles de memoria, ayuda y salir. +- **Clic secundario o Control-clic:** abre las opciones para consultar detalles de memoria, activar o desactivar el inicio de sesión, ver la ayuda y salir. -La app no se añade al inicio de sesión. Lee los contadores del kernel cada dos segundos, también con el panel cerrado, y al comenzar y terminar la recuperación. Solo hay un temporizador; no ejecuta procesos auxiliares para medir. +Por defecto la app no se añade al inicio de sesión. Si lo quieres, activa **Abrir al iniciar sesión** en el menú del clic secundario: usa `SMAppService` de Apple (sin helper ni LaunchAgent). Si macOS pide aprobación, la app te lleva a Ajustes del Sistema → General → Elementos de inicio. Vuelve a pulsarlo para desactivarlo. + +Lee los contadores del kernel cada dos segundos, también con el panel cerrado, y al comenzar y terminar la recuperación. Solo hay un temporizador; no ejecuta procesos auxiliares para medir. Las consultas opcionales de swap y presión se hacen mientras el panel de detalles está abierto; al abrirlo se actualizan de inmediato. Con el panel cerrado, la barra continúa leyendo el porcentaje cada dos segundos. diff --git a/README.md b/README.md index 1af3414..f53b79f 100644 --- a/README.md +++ b/README.md @@ -26,7 +26,8 @@ - 📊 **RAM at a glance** — estimated memory usage as a percentage in the menu bar, refreshed every two seconds with monospaced digits so it never jitters. - 🧹 **One quiet click** — a primary click asks macOS to discard *purgeable* memory in the background. No window, no report, no programs closed. - 🔍 **Details when you need them** — a secondary click (or Control‑click) opens a panel with memory pressure, estimated file cache, wired, compressed, purgeable and swap. -- 🪶 **Featherweight** — a single timer, no helper processes, no Dock icon, no login item, no password prompts, no network access. +- 🪶 **Featherweight** — a single timer, no helper processes, no Dock icon, no password prompts, no network access. +- 🚀 **Optional launch at login** — off by default. Turn on **Abrir al iniciar sesión** in the secondary‑click menu; it uses Apple's `SMAppService` (no helper, no LaunchAgent plist). If macOS asks for approval, the app takes you to System Settings → Login Items. - 🔒 **Honest by design** — no fake "freed 4 GB!" animations. Readings come straight from kernel counters, and the app is upfront when there is nothing to purge. > [!NOTE] @@ -107,7 +108,7 @@ The Release build is a universal (arm64 + x86_64) binary. Verified on macOS 27 w Tools/check.sh ``` -Validates formulas, overlaps, overflow handling, real kernel readings and an **actual** global purge request, using a self‑owned purgeable page and a small private control page (no pressure, no privileges). Results: [Notes/Validation.md](Notes/Validation.md). +Validates formulas, overlaps, overflow handling, real kernel readings and an **actual** global purge request, using a self‑owned purgeable page and a small private control page (no pressure, no privileges), plus the login‑item state mapping (nothing is registered). CI runs the same script on every pull request. Results: [Notes/Validation.md](Notes/Validation.md). ## Project layout @@ -122,7 +123,7 @@ Notes/ Architecture, metrics, recovery and validation notes - [ ] English localization - [ ] Developer ID signing and notarization -- [ ] Optional launch at login +- [x] Optional launch at login ## License diff --git a/Tests/LoginItemChecks.swift b/Tests/LoginItemChecks.swift new file mode 100644 index 0000000..34ff853 --- /dev/null +++ b/Tests/LoginItemChecks.swift @@ -0,0 +1,33 @@ +import Foundation +import ServiceManagement + +/// Checks the login-item state mapping without registering anything. +@main +struct LoginItemChecks { + @MainActor + static func main() throws { + try expect(LoginItemState(.notRegistered) == .disabled, "Not registered maps to disabled") + try expect(LoginItemState(.enabled) == .enabled, "Enabled maps to enabled") + try expect(LoginItemState(.requiresApproval) == .requiresApproval, "Requires approval is surfaced") + try expect(LoginItemState(.notFound) == .unavailable, "Missing bundle maps to unavailable") + + try expect(!LoginItemState.disabled.isChecked && LoginItemState.disabled.nextEnabled, "Disabled: unchecked, click enables") + try expect(LoginItemState.enabled.isChecked && !LoginItemState.enabled.nextEnabled, "Enabled: checked, click disables") + try expect(LoginItemState.requiresApproval.isChecked && !LoginItemState.requiresApproval.nextEnabled, + "Pending approval: checked so a click can withdraw the request") + try expect(LoginItemState.requiresApproval.menuTitle.contains("pendiente"), "Pending approval is explained in the menu") + // Reading the status of a bare executable must not register it. + _ = LoginItem().state + print("All login item checks passed. Nothing was registered.") + } + + static func expect(_ condition: Bool, _ message: String) throws { + guard condition else { + print("FAIL: \(message)") + throw CheckFailure(message: message) + } + print("PASS: \(message)") + } +} + +struct CheckFailure: Error { let message: String } diff --git a/Tools/check.sh b/Tools/check.sh index 6aa56e8..b783bc4 100755 --- a/Tools/check.sh +++ b/Tools/check.sh @@ -6,3 +6,5 @@ xcrun swiftc -swift-version 6 -strict-concurrency=complete -O FreeRAMMac/MemoryM Build/Checks/MemoryMetricsChecks xcrun swiftc -swift-version 6 -strict-concurrency=complete -O FreeRAMMac/RecoveryService.swift Tests/RecoveryChecks.swift -o Build/Checks/RecoveryChecks Build/Checks/RecoveryChecks +xcrun swiftc -swift-version 6 -strict-concurrency=complete -O FreeRAMMac/LoginItem.swift Tests/LoginItemChecks.swift -o Build/Checks/LoginItemChecks +Build/Checks/LoginItemChecks