Skip to content
Open
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
8 changes: 2 additions & 6 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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: |
Expand Down
4 changes: 4 additions & 0 deletions Free RAM Mac.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -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 */

Expand All @@ -21,6 +22,7 @@
100000000000000000000003 /* MemoryMetrics.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MemoryMetrics.swift; sourceTree = "<group>"; };
100000000000000000000004 /* RecoveryService.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = RecoveryService.swift; sourceTree = "<group>"; };
100000000000000000000005 /* MenuBarView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = MenuBarView.swift; sourceTree = "<group>"; };
100000000000000000000006 /* LoginItem.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = LoginItem.swift; sourceTree = "<group>"; };
100000000000000000000010 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
100000000000000000000011 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
100000000000000000000012 /* Free RAM Mac.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = "Free RAM Mac.app"; sourceTree = BUILT_PRODUCTS_DIR; };
Expand Down Expand Up @@ -55,6 +57,7 @@
100000000000000000000003 /* MemoryMetrics.swift */,
100000000000000000000004 /* RecoveryService.swift */,
100000000000000000000005 /* MenuBarView.swift */,
100000000000000000000006 /* LoginItem.swift */,
100000000000000000000010 /* Assets.xcassets */,
100000000000000000000011 /* Info.plist */,
);
Expand Down Expand Up @@ -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;
};
Expand Down
26 changes: 26 additions & 0 deletions FreeRAMMac/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -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))
Expand All @@ -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 {
Expand Down
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
59 changes: 59 additions & 0 deletions FreeRAMMac/LoginItem.swift
Original file line number Diff line number Diff line change
@@ -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()
}
}
2 changes: 1 addition & 1 deletion FreeRAMMac/MenuBarView.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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.")
Expand Down
6 changes: 4 additions & 2 deletions README.es.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand Down Expand Up @@ -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

Expand All @@ -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

Expand Down
33 changes: 33 additions & 0 deletions Tests/LoginItemChecks.swift
Original file line number Diff line number Diff line change
@@ -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 }
2 changes: 2 additions & 0 deletions Tools/check.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading