Skip to content

Instantly share code, notes, and snippets.

@dui
Created August 17, 2026 12:05
Show Gist options
  • Select an option

  • Save dui/b68902f230b4ccaa703cd817463e509d to your computer and use it in GitHub Desktop.

Select an option

Save dui/b68902f230b4ccaa703cd817463e509d to your computer and use it in GitHub Desktop.
Keep a clamshell Mac awake reliably: caffeinate -is LaunchAgent + toggle script + 97-line Swift menu bar app that shows the live pmset assertion state (truth, not config)
#!/bin/bash
# awake — toggle the keep-awake LaunchAgent (fi.dui.keepawake, caffeinate -is).
# The -s (PreventSystemSleep) is what survives monitor-pull with the lid closed
# on AC (A/B isolated 2026-08-15; idle-class apps lose that pull 4/4).
# AC-only by design: on battery the Mac sleeps normally regardless.
#
# awake show status (assertion truth, not config)
# awake on load the agent, verify the assertion appears
# awake off unload the agent, verify the assertion is gone
set -u
PLIST="$HOME/Library/LaunchAgents/fi.dui.keepawake.plist"
LABEL="fi.dui.keepawake"
UID_N=$(id -u)
held() { pmset -g assertions | grep -q "PreventSystemSleep named: \"caffeinate"; }
status() {
if held; then
pid=$(launchctl print "gui/$UID_N/$LABEL" 2>/dev/null | awk '/pid =/{print $3}')
echo "AWAKE — PreventSystemSleep held (agent pid ${pid:-?}). Survives monitor-pull, lid closed, on AC."
else
echo "SLEEPY — no PreventSystemSleep assertion. Monitor-pull with lid closed will sleep the Mac."
fi
}
case "${1:-status}" in
on)
launchctl bootstrap "gui/$UID_N" "$PLIST" 2>/dev/null
sleep 1
held && status || { echo "FAILED: agent loaded but no assertion appeared — check: launchctl print gui/$UID_N/$LABEL"; exit 1; }
;;
off)
launchctl bootout "gui/$UID_N/$LABEL" 2>/dev/null
sleep 1
held && { echo "FAILED: assertion still present after unload"; exit 1; } || status
;;
status|*)
status
;;
esac
// AwakeMenubar — menu-bar truth indicator + toggle for the fi.dui.keepawake
// LaunchAgent (caffeinate -is). Shows the live assertion state, never config:
// cup (filled) = PreventSystemSleep held (survives monitor-pull, lid closed, on AC)
// zzz = not held (that pull will sleep the Mac)
// dotted circle = unknown (before the first read, or while toggling)
// Icons are SF Symbols template images, so they match the menu bar's own
// monochrome and adapt to light/dark. Left-click toggles via
// ~/.local/bin/awake on|off. Polls every 5s, reads off the main thread.
// Built locally with swiftc; no third-party code.
import AppKit
enum AwakeState { case unknown, awake, sleepy }
@discardableResult
func run(_ cmd: String, _ args: [String]) -> (Int32, String) {
let p = Process()
p.executableURL = URL(fileURLWithPath: cmd)
p.arguments = args
let pipe = Pipe()
p.standardOutput = pipe
p.standardError = Pipe()
do { try p.run() } catch { return (127, "") }
p.waitUntilExit()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
return (p.terminationStatus, String(data: data, encoding: .utf8) ?? "")
}
func readState() -> AwakeState {
let (code, out) = run("/usr/bin/pmset", ["-g", "assertions"])
guard code == 0, !out.isEmpty else { return .unknown }
return out.contains("PreventSystemSleep named: \"caffeinate") ? .awake : .sleepy
}
func symbol(_ name: String, _ desc: String) -> NSImage? {
let img = NSImage(systemSymbolName: name, accessibilityDescription: desc)
img?.isTemplate = true
return img
}
let awakePath = NSString(string: "~/.local/bin/awake").expandingTildeInPath
final class App: NSObject, NSApplicationDelegate {
var item: NSStatusItem!
var busy = false
let iconAwake = symbol("cup.and.saucer.fill", "awake")
let iconSleepy = symbol("zzz", "sleepy")
let iconUnknown = symbol("circle.dotted", "unknown")
func applicationDidFinishLaunching(_ n: Notification) {
item = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
item.button?.action = #selector(clicked)
item.button?.target = self
show(.unknown)
poll()
Timer.scheduledTimer(withTimeInterval: 5, repeats: true) { _ in self.poll() }
}
func show(_ state: AwakeState) {
switch state {
case .awake:
item.button?.image = iconAwake
item.button?.toolTip = "AWAKE — PreventSystemSleep held. Monitor-pull safe (AC, lid closed). Click to disable."
case .sleepy:
item.button?.image = iconSleepy
item.button?.toolTip = "SLEEPY — monitor-pull with lid closed will sleep the Mac. Click to enable."
case .unknown:
item.button?.image = iconUnknown
item.button?.toolTip = "Reading keep-awake state…"
}
}
func poll() {
guard !busy else { return }
DispatchQueue.global().async {
let state = readState()
DispatchQueue.main.async { if !self.busy { self.show(state) } }
}
}
@objc func clicked() {
guard !busy else { return }
busy = true
show(.unknown)
DispatchQueue.global().async {
let target = readState() == .awake ? "off" : "on"
run("/bin/bash", [awakePath, target])
let state = readState()
DispatchQueue.main.async { self.busy = false; self.show(state) }
}
}
}
let app = NSApplication.shared
app.setActivationPolicy(.accessory)
let delegate = App()
app.delegate = delegate
app.run()
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>fi.dui.keepawake</string>
<key>ProgramArguments</key>
<array>
<string>/usr/bin/caffeinate</string>
<string>-is</string>
</array>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
</dict>
</plist>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment