Repository navigation
Expand file tree
/
Copy pathlich
More file actions
executable file
·1534 lines (1447 loc) · 69.2 KB
/
Copy pathlich
File metadata and controls
executable file
·1534 lines (1447 loc) · 69.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/bin/bash
# lich — keep a MacBook awake with the lid closed, but ONLY while it is
# plugged in AND you are logged in. Unplug it, log out, or lay it to rest,
# and it sleeps like any mortal machine.
#
# The lore is the spec: the power cord is the phylactery. While it feeds the
# machine, the lich stays risen — lid open or closed. Sever the phylactery
# (unplug), or let the soul depart (log out), and the body returns to rest.
#
# How it works, in one paragraph:
# `lich install` loads a per-user LaunchAgent that runs `lich watch`.
# Every 5 seconds the watcher reads the risen/at-rest flag in
# ~/.lich/desired-state and the power source, and flips the hidden
# `pmset disablesleep` setting: 1 when risen AND (on AC power OR roaming)
# (lid-close no longer sleeps), 0 otherwise. `lich on|off` just writes the
# flag — so anything that can write a file (the menu bar app, the Control
# Center toggle, an ssh session) can control it. Because the watcher is a
# per-user LaunchAgent it only exists while you're logged in — at logout
# launchd sends SIGTERM and the cleanup trap re-enables normal sleep.
#
# Roaming (~/.lich/roam) is the deliberate exception to "no cord, no lich":
# staying risen on battery for one trip, for a timer, or always — always
# under a battery floor (~/.lich/config) that outranks every mode and every
# caller. The same tick that reconciles power expires timers, spends
# one-shots and enforces the floor, so a roam ends within ~5 seconds of the
# condition that ends it.
#
# Read this before you grant sudo (then read the rest — it's one short file):
# * The passwordless sudoers rule installed here permits exactly two command
# lines and nothing else: `pmset -a disablesleep 0` and
# `pmset -a disablesleep 1`. That is the entire standing privilege.
# * Nothing runs as root. The watcher is a per-user LaunchAgent running as
# you; it borrows root only for that one setting. `install`/`uninstall`
# use ordinary *prompted* sudo to place and remove their own files —
# that's the one password prompt.
# * Every `sudo -n` below means "never prompt", deliberately: a background
# watcher must fail loudly, not hang on a prompt nobody can see.
#
# Inspired by: tmad4000/nosleep (scoped sudoers, cleanup traps),
# Moarram/wake (minimal pmset wrapping), hizzt/mac-sleep-tool
# (power-event-driven LaunchAgent — plus fixing its missing logout reset).
set -euo pipefail
# Everything lich touches, in one place. `lich uninstall` removes all of it
# except the log, which it leaves for you to read.
LABEL="com.lichbook.watcher"
CLI_LINK="/usr/local/bin/lich" # only created if lich isn't already on PATH
PLIST="$HOME/Library/LaunchAgents/$LABEL.plist"
# Per-user filename, so a second user's install can never clobber the first
# user's rule (each install/uninstall touches only its own file). Dots are
# stripped because #includedir silently ignores filenames containing them.
LICH_USER="${USER:-$(id -un)}" # USER can be unset in sanitized envs
SUDOERS="/etc/sudoers.d/lichbook-${LICH_USER//./_}"
SUDOERS_LEGACY="/etc/sudoers.d/lichbook" # pre-v0.3.2 shared filename
LOG_FILE="$HOME/Library/Logs/lich.log"
STATE_DIR="$HOME/.lich" # sandboxed Control Center widget writes here
FLAG="$STATE_DIR/desired-state" # contents: "on" (risen) or "off" (at rest)
ROAM="$STATE_DIR/roam" # "<standing>[ <trip>]": off|always|timer,
# then optionally once | until <epoch>
CONFIG="$STATE_DIR/config" # key=value lines: floor, roam_mins
DEADLINE_LEGACY="$STATE_DIR/session-deadline" # pre-v0.4.3 timer signpost;
# the watcher deletes it at startup
FLOOR_LATCH="$STATE_DIR/floor-reached" # exists from the floor until a charge
# past floor+margin: roaming stays ended
MENUBAR_ICON="$STATE_DIR/menubar-icon" # the menu bar app's own verdict on
# whether its icon is on screen
PMSET="/usr/bin/pmset" # absolute: the sudoers rule matches this
# exact string, so every caller must too
POLL_INTERVAL=5 # seconds between checks; the worst-case delay for a flag
# flip or plug/unplug to take effect
# Roaming defaults, used whenever ~/.lich/config is missing or says nothing
# about a key. The floor is the one number that overrules the user: below it
# roaming ends, always-mode included. A machine that runs itself flat in a bag
# is a worse tool than one that sleeps, so there is no override flag.
DEFAULT_FLOOR=20 # percent
DEFAULT_ROAM_MINS=30 # minutes, for `lich roam timer`
FLOOR_RESUME_MARGIN=5 # points above the floor a charge must reach before
# a floor-ended roam can resume (hysteresis)
# How long the Mac may stay awake after lich hands sleep back to macOS before
# the watcher goes looking for who is holding it up. Well past any sane
# display-sleep + idle-sleep timer, so a firing is meaningful, not jitter.
AWAKE_WARN_MINS=15
# Watcher memory — meaningful only inside the `watch` loop, where the process
# lives for the whole session. Deliberately not persisted: a watcher restart
# forgetting these is acceptable (worst case, an armed one-shot survives one
# extra plug-in, or a suspension is logged twice — every failure
# leans toward awake, never toward data loss).
ROAM_GRANTED_ON_BATTERY=0 # a "once" trip actually held the Mac awake off AC
FLOOR_SUSPEND_LOGGED=0 # standing-mode floor suspension: log once, not 12/min
BATTERY_UNREADABLE_LOGGED=0 # ditto for an unparsable battery reading
BATTERY_PCT=100 # last reading; set by read_battery, never read raw
TIMER_ENDED_LOGGED=0 # standing timer handed sleep back: log once per
# idle stretch (input re-arms it, and this)
AWAKE_TICKS=0 # consecutive battery ticks with disablesleep=0;
# ticks freeze while the Mac sleeps, so this
# approximates awake time that macOS owns
AWAKE_WARN_LOGGED=0 # overdue-sleep warning: once per battery session
# Every log line goes to $LOG_FILE directly, no matter who called — watcher,
# CLI, menu bar app (which discards CLI output), Control-Center-triggered
# ticks. That makes the log a complete, timestamped history of every state
# transition, usable as evidence when marking docs/STATE-TABLE.md rows Tested.
# Terminal echo only when interactive; under launchd stdout is already the
# log file and echoing would double every line.
log() {
local line
line="$(printf '%s %s' "$(date '+%Y-%m-%d %H:%M:%S')" "$*")"
{ mkdir -p "$(dirname "$LOG_FILE")" && printf '%s\n' "$line" >> "$LOG_FILE"; } 2>/dev/null || true
[[ -t 1 ]] && printf '%s\n' "$line"
return 0
}
# Same, but the interactive echo goes to stderr — stdout stays clean for the
# machine-readable commands (`roam status`, `config`).
log_warn() {
local line
line="$(printf '%s %s' "$(date '+%Y-%m-%d %H:%M:%S')" "$*")"
{ mkdir -p "$(dirname "$LOG_FILE")" && printf '%s\n' "$line" >> "$LOG_FILE"; } 2>/dev/null || true
[[ -t 2 ]] && printf '%s\n' "$line" >&2
return 0
}
die() { echo "lich: $*" >&2; exit 1; }
# Color, only when stdout is a terminal — pipes, logs and scripts get plain
# text. C_ACT (bold yellow) marks THE COMMAND THE USER MUST RUN NEXT; that is
# its whole job, so use it sparingly or it stops meaning anything.
if [[ -t 1 ]]; then
C_ACT=$'\033[1;33m' C_OK=$'\033[32m' C_BAD=$'\033[31m' C_OFF=$'\033[0m'
else
C_ACT="" C_OK="" C_BAD="" C_OFF=""
fi
# ---------- state probes ----------------------------------------------------
# All read-only. Nothing in this section needs privileges.
# Line 1 of `pmset -g ps` names the live source: "'AC Power'" / "'Battery Power'".
on_ac() { "$PMSET" -g ps | head -1 | grep -q "AC Power"; }
power_source() { on_ac && echo "AC (phylactery intact)" || echo "battery"; }
# What you asked for. A missing or unreadable flag reads as at rest, so the
# safe answer is always the default one.
risen() { [[ "$(cat "$FLAG" 2>/dev/null)" == "on" ]]; }
# The first percentage `pmset -g batt` prints — the internal battery's charge —
# left in $BATTERY_PCT. Anything we can't parse (a desktop Mac, an unexpected
# format) reads as 100: fail toward staying awake, exactly like every other
# probe here, and say so in the log the first time.
#
# It sets a variable instead of printing one because a `$(...)` caller runs it
# in a subshell, where the "log this once" latch would be thrown away with the
# subshell and the watcher would repeat the warning twelve times a minute.
read_battery() {
local p
p="$("$PMSET" -g batt 2>/dev/null | grep -o '[0-9][0-9]*%' | head -1 | tr -d '%' || true)"
if [[ "$p" =~ ^[0-9]+$ ]]; then
BATTERY_PCT="$p"
else
BATTERY_PCT=100
if [[ "$BATTERY_UNREADABLE_LOGGED" == 0 ]]; then
log_warn "WARNING: cannot read battery percentage from 'pmset -g batt' — assuming 100%"
BATTERY_UNREADABLE_LOGGED=1
fi
fi
}
# ~/.lich/config, one key=value per line. Deliberately dumb: no arrays (bash
# 3.2 has none), last assignment wins, surrounding whitespace trimmed, and
# anything that isn't a plain integer — junk value, unknown key, missing file —
# falls back to the default rather than failing.
config_get() {
local key="$1" def="$2" v=""
if [[ -f "$CONFIG" ]]; then
v="$(awk -F= -v k="$key" '
NF < 2 { next }
{ name = $1; val = $2
gsub(/^[ \t]+|[ \t]+$/, "", name)
gsub(/^[ \t]+|[ \t]+$/, "", val)
if (name == k) out = val }
END { print out }' "$CONFIG" 2>/dev/null || true)"
fi
[[ "$v" =~ ^[0-9]+$ ]] || v="$def"
echo "$v"
}
# Rewrite one key, leaving every other line (including keys we don't know)
# alone. Temp file in the same directory so the replace is an atomic rename —
# the watcher reads this file every tick and must never see half of it.
config_set() {
local key="$1" val="$2" tmp
mkdir -p "$STATE_DIR"
tmp="$STATE_DIR/.config.$$"
: > "$tmp"
if [[ -f "$CONFIG" ]]; then
grep -v "^[[:space:]]*${key}[[:space:]]*=" "$CONFIG" >> "$tmp" || true
fi
printf '%s=%s\n' "$key" "$val" >> "$tmp"
mv "$tmp" "$CONFIG"
}
# ---------- roaming --------------------------------------------------------
# Roaming is staying risen without the phylactery: awake on battery, because
# you said so. Two layers, deliberately:
#
# STANDING mode — the owner's preference, which persists until the owner
# changes it: `off` (unplugged means sleep), `always` (unplugged never
# means sleep), or `timer` (unplugged, it stays awake until nobody has
# touched it for roam_mins, then sleeps; any input re-arms it).
#
# TRIP — a temporary overlay: `once` (until the cord returns) or
# `until <epoch>` (a bounded window, e.g. `lich roam 45`). A trip rides on
# top of the standing mode and, when spent or expired, evaporates —
# revealing the standing mode again, NOT wiping it to off. Predictability
# is the point: using the machine "just this once" never costs you the
# default you configured.
#
# File grammar (~/.lich/roam, one line): "<standing>[ <trip>]", e.g. "timer",
# "off once", "timer until 1785768543". Legacy single-value files from
# v0.2.x ("once", "until N") read as a trip atop standing off.
# Parse the roam file into ROAM_STANDING and ROAM_TRIP. Missing/unrecognized
# reads as off with no trip — the state a Mac that never heard of roaming
# should be in.
roam_read() {
local raw
raw="$(head -1 "$ROAM" 2>/dev/null || true)"
raw="${raw#"${raw%%[![:space:]]*}"}" # trim leading whitespace
raw="${raw%"${raw##*[![:space:]]}"}" # trim trailing whitespace
ROAM_STANDING=off ROAM_TRIP=""
case "$raw" in
"") ;;
once) ROAM_TRIP="once" ;;
'until '*) ROAM_TRIP="$raw" ;;
off|always|timer) ROAM_STANDING="$raw" ;;
'off once'|'always once'|'timer once')
ROAM_STANDING="${raw%% *}" ROAM_TRIP="once" ;;
'off until '*|'always until '*|'timer until '*)
ROAM_STANDING="${raw%% *}" ROAM_TRIP="${raw#* }" ;;
*) ;;
esac
}
# Write-then-rename, so a tick that reads this file in the same instant sees
# the old value or the new one and never an empty file — an empty read means
# "off", which on battery with the lid shut would sleep the Mac mid-roam.
# $1 = standing, $2 = trip ("" for none).
roam_write() {
local line="$1" tmp
[[ -n "${2:-}" ]] && line="$1 $2"
mkdir -p "$STATE_DIR"
tmp="$STATE_DIR/.roam.$$"
printf '%s\n' "$line" > "$tmp"
mv "$tmp" "$ROAM"
}
# The charge at which a floor-ended roam may resume: floor + margin, but no
# higher than 80% — Optimized Battery Charging can hold a Mac there for days,
# and a latch waiting for 81% would never clear — and always above the floor.
floor_resume_pct() {
local f r
f="$(config_get floor "$DEFAULT_FLOOR")"
r=$(( f + FLOOR_RESUME_MARGIN ))
[[ "$r" -gt 80 ]] && r=80
[[ "$r" -le "$f" ]] && r=$(( f + 1 ))
echo "$r"
}
# Seconds since the last keyboard, mouse, or trackpad input (IOHIDSystem's
# HIDIdleTime, in ns) — the clock the standing timer runs on. Empty when
# unreadable. awk reads to EOF on purpose: quitting early would SIGPIPE ioreg,
# and under pipefail that reads as failure (see console_locked).
idle_seconds() {
ioreg -c IOHIDSystem -d 4 2>/dev/null \
| awk '/HIDIdleTime/ && !f {printf "%d\n", $NF / 1000000000; f = 1}'
}
# The machine-readable state, EXACTLY two tokens on one line:
# "<standing> <trip>" where standing ∈ off|always|timer and trip ∈
# "-" (none) | "once" | "until:<epoch>".
# The menu bar app parses this — no decoration, no extra lines. Pure — no
# writes, no log lines — an elapsed trip reports as "-"; clearing it is the
# watcher's job, and only the watcher's, so the log gets exactly one line.
roam_state() {
local trip="-" epoch
roam_read
case "$ROAM_TRIP" in
once) trip="once" ;;
'until '*)
epoch="${ROAM_TRIP#until }"
if [[ "$epoch" =~ ^[0-9]+$ ]] && [[ "$(date +%s)" -lt "$epoch" ]]; then
trip="until:$epoch"
fi
;;
esac
echo "$ROAM_STANDING $trip"
}
# Roaming in English, for `lich status`.
roam_human() {
local state standing trip epoch left mins standing_desc
state="$(roam_state)"
standing="${state%% *}"
trip="${state#* }"
mins="$(config_get roam_mins "$DEFAULT_ROAM_MINS")"
case "$standing" in
always) standing_desc="always — stays risen unplugged" ;;
timer) standing_desc="timer — stays risen unplugged until ${mins} min idle" ;;
*) standing_desc="off — unplugged means sleep" ;;
esac
case "$trip" in
once)
echo "once (this trip, until you plug back in) — then: $standing_desc" ;;
until:*)
epoch="${trip#until:}"
left=$(( ( epoch - $(date +%s) + 59 ) / 60 ))
[[ "$left" -lt 1 ]] && left=1
echo "$left min left (this trip) — then: $standing_desc" ;;
*)
echo "$standing_desc" ;;
esac
}
# The watcher's question, asked only on battery (on AC the answer doesn't
# matter — the phylactery already keeps the lich up). Unlike everything above
# this one is allowed to write: trip expiry, floor breach and their log lines
# are state changes the watcher owns. Standing modes are NEVER written here —
# only the owner (roam off / roam always / roam timer) changes those.
roam_active() {
local floor epoch mins idle
roam_read
[[ "$ROAM_STANDING" == off && -z "$ROAM_TRIP" ]] && return 1
# The floor outranks everything. A trip that hits it is spent — cleared, so
# nothing silently resumes at 19%. A standing mode is only suspended: it is
# the owner's preference, and it must survive to the next charge.
#
# And it LATCHES until the battery has charged FLOOR_RESUME_MARGIN points
# past the floor. Without that, a reading wobbling 20% → 21%, or a few
# minutes on the charger (field log, 2026-10-20), re-armed roaming only for
# the floor to end it again minutes later. A file, not watcher memory, so
# the CLI and the menu bar give the same answer as the watcher.
floor="$(config_get floor "$DEFAULT_FLOOR")"
read_battery
if [[ "$BATTERY_PCT" -le "$floor" || -f "$FLOOR_LATCH" ]]; then
[[ -f "$FLOOR_LATCH" ]] || { mkdir -p "$STATE_DIR" && : > "$FLOOR_LATCH"; } 2>/dev/null || true
if [[ -n "$ROAM_TRIP" ]]; then
roam_write "$ROAM_STANDING" ""
log "battery floor ${floor}% — trip roam canceled"
fi
if [[ "$ROAM_STANDING" != off && "$FLOOR_SUSPEND_LOGGED" == 0 ]]; then
log "battery floor ${floor}% — standing roam ($ROAM_STANDING) suspended until charged to $(floor_resume_pct)%"
FLOOR_SUSPEND_LOGGED=1
fi
return 1
fi
# Trip overlay first — it exists to outlast/override the standing answer.
case "$ROAM_TRIP" in
once)
# Remember that the grant did real work, so the return of the
# phylactery can spend it. In-memory on purpose (see the top of file).
ROAM_GRANTED_ON_BATTERY=1
return 0
;;
'until '*)
epoch="${ROAM_TRIP#until }"
if [[ "$epoch" =~ ^[0-9]+$ ]] && [[ "$(date +%s)" -lt "$epoch" ]]; then
return 0
fi
roam_write "$ROAM_STANDING" ""
log "trip roam expired — back to standing setting: $ROAM_STANDING"
;;
esac
# Then the standing mode.
case "$ROAM_STANDING" in
always) return 0 ;;
timer)
# Awake until nobody has touched the Mac for roam_mins — measured from
# the last keyboard/trackpad input, not from the unplug. So a Mac in
# active use never runs out of grace under you, walking away (or
# closing the lid) starts the countdown, and any input re-arms it.
# Stateless on purpose: the watcher, a CLI call, a menu click and a
# restarted watcher all compute the same answer from the same clock.
mins="$(config_get roam_mins "$DEFAULT_ROAM_MINS")"
idle="$(idle_seconds)"
if [[ "$idle" =~ ^[0-9]+$ && "$idle" -lt $(( mins * 60 )) ]]; then
TIMER_ENDED_LOGGED=0
return 0
fi
if [[ "$TIMER_ENDED_LOGGED" == 0 ]]; then
if [[ "$idle" =~ ^[0-9]+$ ]]; then
log "standing timer: idle ${mins} min on battery — sleep handed back to macOS (any input re-arms it)"
else
log "standing timer: idle time unreadable — sleep handed back to macOS"
fi
TIMER_ENDED_LOGGED=1
fi
return 1
;;
*) return 1 ;;
esac
}
# What the tick has to do about roaming when the cord is back: spend a
# one-shot trip that actually did work, and reset the per-battery-session
# memory (floor-suspension notice, timer window). Only called with AC present.
roam_on_ac() {
roam_read
if [[ "$ROAM_GRANTED_ON_BATTERY" == 1 && "$ROAM_TRIP" == "once" ]]; then
roam_write "$ROAM_STANDING" ""
log "phylactery restored — one-shot roam spent (standing setting kept: $ROAM_STANDING)"
fi
ROAM_GRANTED_ON_BATTERY=0
FLOOR_SUSPEND_LOGGED=0
if [[ -f "$FLOOR_LATCH" ]]; then
read_battery
if [[ "$BATTERY_PCT" -ge "$(floor_resume_pct)" ]]; then
rm -f "$FLOOR_LATCH" 2>/dev/null || true
log "charged to ${BATTERY_PCT}% — battery floor cleared, roaming can resume"
fi
fi
TIMER_ENDED_LOGGED=0
}
# ---------- more state probes ----------------------------------------------
# What the kernel actually has set — not necessarily what we last asked for
# (a reboot, a crash, another tool). Ground truth for reconcile.
sleep_disabled() {
local v
v="$("$PMSET" -g | awk '/SleepDisabled/ {print $2}')"
echo "${v:-0}"
}
watcher_running() { launchctl print "gui/$UID/$LABEL" >/dev/null 2>&1; }
lid_closed() {
ioreg -r -k AppleClamshellState -d 1 2>/dev/null \
| awk '/"AppleClamshellState" = Yes/ {f = 1} END {exit !f}'
}
# Both probes read their whole input (awk, not grep -q): IOConsoleLocked sits
# on line 2 of ~110 KB of plutil output, so `grep -q` quits early, plutil dies
# of SIGPIPE, and under pipefail the probe reported "not locked" every single
# time — 252 false "lock did NOT take" warnings before anyone noticed.
console_locked() {
ioreg -n Root -d1 -a 2>/dev/null | plutil -p - 2>/dev/null \
| awk '/"IOConsoleLocked" => true/ {f = 1} END {exit !f}'
}
# Who ELSE is keeping the Mac awake. disablesleep is lich's lever; power
# assertions are everyone else's — a playing video, a Zoom call, a stray
# caffeinate — and with the lid open they block idle sleep just as thoroughly.
# One line per assertion: '<process> — <type> "<name>" (held <h:mm:ss>)'.
# Two deliberate omissions: powerd's "prevent sleep while display is on" is a
# consequence of the display being on, not a cause, and would pad every
# snapshot; UserIsActive is a 2-minute input tickle that would name the user
# for touching the trackpad.
sleep_blockers() {
# Each line carries its pid through the pipe so the loop can name the
# parent — "started by claude" is the difference between a mystery
# caffeinate and a known one. Parent = launchd means "launched normally"
# (Dock, Finder, login) and is omitted as noise; a vanished parent (or a
# vanished blocker — these race) is omitted the same way.
local pid rest ppid parent held stuck
"$PMSET" -g assertions 2>/dev/null | sed -nE \
's/^[[:space:]]*pid ([0-9]+)\(([^)]*)\): \[[^]]*\] ([0-9:]+) (NoDisplaySleepAssertion|PreventUserIdleDisplaySleep|PreventUserIdleSystemSleep|PreventSystemSleep|NoIdleSleepAssertion) named: "([^"]*)".*/\1|\2 — \4 "\5" (held \3)/p' \
| grep -v 'Powerd - Prevent sleep while display is on' \
| while IFS='|' read -r pid rest; do
ppid="$(ps -o ppid= -p "$pid" 2>/dev/null | tr -d ' ' || true)"
parent=""
[[ "$ppid" =~ ^[0-9]+$ && "$ppid" -gt 1 ]] \
&& parent="$(ps -o comm= -p "$ppid" 2>/dev/null | sed 's|.*/||' || true)"
# Held for half a day or more = almost certainly stuck, not working:
# the field log caught a Finder "force_move" assertion held for 12
# days, quietly keeping the Mac from idle-sleeping on battery. Say
# what clears it, because nothing about lich can.
held="${rest##*(held }"; held="${held%%:*}"
stuck=""
[[ "$held" =~ ^[0-9]+$ && "$held" -ge 12 ]] \
&& stuck=" — held ${held}h, probably stuck: quit or relaunch it to release"
case "$parent" in
""|launchd) printf '%s\n' "$rest$stuck" ;;
*) printf '%s\n' "$rest — started by $parent$stuck" ;;
esac
done || true
}
# Write each live blocker to the log under a prefix. Returns 0 if anything was
# logged, 1 if the coast is clear — the caller owns latching and severity.
log_blockers() {
local prefix="$1" any=1 line
while IFS= read -r line; do
[[ -n "$line" ]] || continue
log "$prefix $line"
any=0
done < <(sleep_blockers)
return "$any"
}
# Locking = starting the screensaver, which arms the system's own
# "require password after screensaver/display off" setting. No accessibility
# or automation permission needed, and it works with the lid already shut.
lock_console() { open -a ScreenSaverEngine 2>/dev/null || true; }
# ---------- watcher (runs under launchd; not meant to be called by hand) ----
# The entire policy: disablesleep is 1 only when you have raised the lich AND
# (the phylactery is intact OR you asked to roam without it). Idempotent —
# compares desired against live and calls sudo only on a difference, so the
# 5-second loop stays silent until something actually changes.
#
# Order matters. roam_active is asked only on battery, both because on AC the
# answer is irrelevant and because asking it is what expires timers and
# enforces the floor — work that belongs to a tick that is actually running on
# battery. The AC branch does the mirror-image bookkeeping: spending a
# one-shot the moment the cord comes back.
reconcile() {
local want=0 roam=off ac=0
if on_ac; then
ac=1
roam_on_ac
if risen; then want=1; fi
elif risen && roam_active; then
want=1
fi
[[ "$(sleep_disabled)" == "$want" ]] && return 0
roam="$(roam_state | tr ' ' '/')" # e.g. off/-, timer/once — one log token
if sudo -n "$PMSET" -a disablesleep "$want" 2>/dev/null; then
log "risen=$(risen && echo yes || echo no) power=$(power_source) roam=$roam -> disablesleep=$want"
# Handing sleep back is a promise macOS may not keep: any app assertion
# live at this moment blocks the idle sleep we just re-enabled. Name them
# now, so a Mac found awake hours later has its culprit on record.
if [[ "$want" == 0 && "$ac" == 0 ]]; then
log_blockers " blocker at handoff:" || true
fi
else
# Refused, and -n means we never hung on a prompt to find out. Don't spin
# silently: die and let the log say why.
log "ERROR: 'sudo pmset' refused — sudoers rule missing? Run: lich install"
return 78 # EX_CONFIG; the watcher exits on it, interactive callers don't
fi
}
cleanup() {
# Runs on ANY exit — normal, error, Ctrl-C, and the SIGTERM launchd sends at
# logout. This trap is the entire "only while logged in" guarantee: no
# session, no watcher, no disablesleep. Best-effort, because an exit path
# must never fail; a SIGKILL or panic skips it and the next reconcile fixes
# it at your next login.
if sudo -n "$PMSET" -a disablesleep 0 2>/dev/null; then
log "watcher down — normal sleep restored"
else
log "ERROR: watcher down but 'sudo pmset' was refused — sleep may still be disabled (fix: sudo pmset -a disablesleep 0)"
fi
}
cmd_watch() {
# A trapped signal in bash runs its handler and then RESUMES the script, so
# `trap cleanup TERM` alone restored sleep at logout and then let the loop
# re-arm disablesleep=1 on its next tick. TERM/INT therefore just exit;
# the EXIT trap does the cleanup, exactly once.
trap cleanup EXIT
trap 'exit 143' TERM
trap 'exit 130' INT
rm -f "$DEADLINE_LEGACY" 2>/dev/null || true
log "watcher up (pid $$)"
# Plain polling, on purpose — not an oversight. `pmset -g pslog` looks like
# the elegant answer but does not stream reliably under launchd (it exits
# right after its header), and an event stream that dies quietly takes
# disablesleep down with it. Two cheap pmset reads per tick cannot desync.
# Closing the lid normally locks a Mac by putting it to sleep. When lich is
# the reason it stays awake, macOS never fires that lock — measured, not
# assumed: IOConsoleLocked stays false. So the watcher restores the
# guarantee itself: on the tick where the lid goes shut while we hold the
# machine awake, lock the console. Once per closure, not continuously — so
# a deliberate unlock over Screen Sharing with the lid down isn't fought.
# The lock is *requested*, then *verified* on the following tick — because
# locking rides on the user's "require password after screen saver/display
# off" setting, which lich cannot see and Tahoe has known regressions in.
# One verdict per closure, logged honestly; no retry loop, so a deliberate
# unlock over Screen Sharing with the lid down is never fought.
LID_WAS_CLOSED=0
LOCK_PENDING=0
local sd saver screenlock power last_power=""
while :; do
reconcile || exit $? # broken sudoers = die loudly; launchd retries
sd="$(sleep_disabled)"
# Every plug and unplug, on the record — otherwise a replug that leaves
# disablesleep unchanged (risen, roaming → AC) leaves no trace at all.
on_ac && power=AC || power=battery
if [[ -n "$last_power" && "$power" != "$last_power" ]]; then
log "power: $last_power -> $power"
fi
last_power="$power"
# Overdue-sleep watchdog. Once lich lets go on battery, macOS should sleep
# the Mac within its own idle timers — minutes. If we are still ticking
# AWAKE_WARN_MINS later, something is holding it awake, and the whole
# point of this log is to name that something while it is still there.
# (Ticks freeze during sleep, so the counter only accumulates real awake
# time; an active user counts too, and gets named honestly — once.)
if on_ac; then
AWAKE_TICKS=0; AWAKE_WARN_LOGGED=0
elif [[ "$sd" == "0" ]]; then
AWAKE_TICKS=$(( AWAKE_TICKS + 1 ))
if [[ "$AWAKE_WARN_LOGGED" == 0 && "$AWAKE_TICKS" -ge $(( AWAKE_WARN_MINS * 60 / POLL_INTERVAL )) ]]; then
AWAKE_WARN_LOGGED=1
log_warn "WARNING: still awake ${AWAKE_WARN_MINS} min after sleep was handed back to macOS — naming who holds it:"
log_blockers " blocker:" \
|| log " no app assertions found — not an app holding it; check 'pmset -g log' for the story"
fi
else
AWAKE_TICKS=0
fi
if [[ "$sd" == "1" ]] && lid_closed; then
if [[ "$LID_WAS_CLOSED" == 0 ]]; then
if console_locked; then
LOCK_PENDING=0
else
lock_console
log "lid closed while risen — lock requested"
LOCK_PENDING=1
fi
LID_WAS_CLOSED=1
elif [[ "$LOCK_PENDING" == 1 ]]; then
if console_locked; then
log "lock confirmed"
else
# Name the two moving parts before blaming the user's settings: is
# the screensaver we asked for even running, and what does the
# require-password delay actually say? Together they split "lock
# never armed" from "armed but the OS hasn't flipped IOConsoleLocked".
saver="not running"; pgrep -xq ScreenSaverEngine 2>/dev/null && saver="running"
screenlock="$(sysadminctl -screenLock status 2>&1 | sed -E 's/.*sysadminctl\[[^]]*\] //' || true)"
log_warn "WARNING: lock did NOT take — an opened lid lands on your desktop. (ScreenSaverEngine: ${saver}; ${screenlock:-screenLock status unreadable}; IOConsoleLocked still false)"
fi
LOCK_PENDING=0
fi
else
LID_WAS_CLOSED=0
LOCK_PENDING=0
fi
# Backgrounded + wait: bash defers a trap until the foreground command
# finishes, but `wait` is interrupted at once — so logout gets an
# immediate cleanup instead of one up to POLL_INTERVAL later.
sleep "$POLL_INTERVAL" &
wait $! || true
done
}
# ---------- user commands ---------------------------------------------------
# on/off only write the flag; the watcher is what makes it true. Hence the menu
# bar app, the Control Center toggle and an ssh one-liner are all equally valid
# front ends — they write the same file.
# Writing the flag and applying it now, without the announcement — `lich on`
# and every `lich roam` form need exactly this, and they say different things
# about it afterwards.
raise() {
mkdir -p "$STATE_DIR"
echo on > "$FLAG"
# Apply now instead of waiting up to POLL_INTERVAL for the tick. Tolerate
# failure (not installed yet): the flag is set, and the callers' warning
# says what to do about it.
reconcile || true
}
# Worth saying loudly: with no watcher, nothing will undo any of this on
# unplug, on a timer, or at the battery floor.
# Arming on battery after the floor has already ended this unplug's roaming:
# the setting is saved, but it won't keep the Mac awake until the next
# plug-in. Say so, rather than print 💀 and let lid-close surprise someone.
warn_floor_latched() {
if [[ -f "$FLOOR_LATCH" ]]; then
echo " (but the battery floor already ended roaming — this takes effect once charged to $(floor_resume_pct)%)"
fi
return 0
}
warn_no_watcher() {
watcher_running || echo "warning: watcher not running — run: ${C_ACT}lich install${C_OFF}" >&2
}
cmd_on() {
raise
log "cmd: on"
echo "💀 lich risen — lid-close keeps this Mac awake while on AC power"
warn_no_watcher
}
cmd_off() {
mkdir -p "$STATE_DIR"
echo off > "$FLAG"
# Also restore sleep directly, so `lich off` is instant and works even with
# no watcher. Best-effort: the flag is what matters.
sudo -n "$PMSET" -a disablesleep 0 2>/dev/null || true
log "cmd: off"
echo "⚰️ lich at rest — normal sleep behavior restored"
}
# ---------- roaming commands ------------------------------------------------
# Every arming form also raises the lich: "keep me awake off the cord" is one
# intention, and making it two commands only invites the half-armed state
# where roam is set and the flag isn't. `off` and `status` never touch the
# risen flag — laying the lich to rest stays a separate, deliberate decision.
cmd_roam() {
local arg="${1:-once}" mins floor epoch
case "$arg" in
# Read-only forms first, so nothing below can be reached by accident.
status)
# EXACTLY one bare line: the menu bar app parses this. No decoration,
# no second line, no emoji — and no writes (see roam_state).
roam_state
return 0
;;
off)
# The one command that clears the STANDING preference (and any trip).
roam_write off ""
log "cmd: roam off"
echo "roam off — unplugging lays the lich to rest again"
return 0
;;
esac
floor="$(config_get floor "$DEFAULT_FLOOR")"
case "$arg" in
""|once)
# A trip atop the standing mode — spending it never costs the default.
roam_read
roam_write "$ROAM_STANDING" "once"
raise
log "cmd: roam once (standing kept: $ROAM_STANDING)"
echo "💀 roaming once — risen without the phylactery until you plug back in (floor ${floor}%)"
[[ "$ROAM_STANDING" != off ]] && echo " (your standing setting — $ROAM_STANDING — is kept and returns after this trip)"
;;
always)
# Standing preference: replaces any previous standing mode; a pending
# trip is subsumed (always outranks it anyway).
roam_write always ""
raise
log "cmd: roam always (standing)"
echo "💀 roaming always — unplugging no longer rests the lich (floor ${floor}% still does)"
;;
timer)
# Standing preference: unplugged, stay awake until roam_mins without
# input; the setting persists until `lich roam off`.
mins="$(config_get roam_mins "$DEFAULT_ROAM_MINS")"
roam_write timer ""
raise
log "cmd: roam timer (standing, ${mins}m idle)"
echo "💀 roaming on a timer — unplugged, stays awake until ${mins} min without use, then sleeps (floor ${floor}%; setting persists)"
;;
*)
# `lich roam 45` / `45m`: a bounded trip — this window only, standing kept.
if [[ "$arg" =~ ^([0-9]+)m?$ ]]; then
mins="${BASH_REMATCH[1]}"
[[ "$mins" -ge 1 ]] || die "roam: minutes must be 1 or more"
epoch=$(( $(date +%s) + mins * 60 ))
roam_read
roam_write "$ROAM_STANDING" "until $epoch"
raise
log "cmd: roam ${mins}m trip (until $epoch, standing kept: $ROAM_STANDING)"
echo "💀 roaming for ${mins} min — risen without the phylactery until $(date -r "$epoch" '+%H:%M') (floor ${floor}%)"
[[ "$ROAM_STANDING" != off ]] && echo " (your standing setting — $ROAM_STANDING — is kept and returns after this trip)"
else
die "unknown roam mode: $arg (try: lich roam, roam always, roam timer, roam <minutes>, roam off, roam status)"
fi
;;
esac
warn_floor_latched
warn_no_watcher
}
# For an agent handing the machine back. It spends a trip it may have been
# given; it does not spend the owner's standing preference, and it never lays
# the lich to rest — `lich off` is a human decision about a human's Mac.
cmd_done() {
roam_read
if [[ -n "$ROAM_TRIP" ]]; then
roam_write "$ROAM_STANDING" ""
log "cmd: done (trip cleared, standing kept: $ROAM_STANDING)"
if [[ "$ROAM_STANDING" == off ]]; then
echo "trip cleared — this Mac may sleep again once unplugged (still risen; 'lich off' to rest)"
else
echo "trip cleared — back to the owner's standing setting: $ROAM_STANDING"
fi
elif [[ "$ROAM_STANDING" != off ]]; then
echo "no trip to clear — '$ROAM_STANDING' is the owner's standing setting, not yours to spend (lich roam off, if you're the owner)"
else
echo "roam already off — nothing to clear"
fi
}
# ---------- config ----------------------------------------------------------
cmd_config() {
local key="${1:-}" val="${2:-}"
case "$key" in
"")
# The *effective* config, defaults included — the menu bar app reads
# roam_mins from here to label its timer item, so it must always answer.
echo "floor=$(config_get floor "$DEFAULT_FLOOR")"
echo "roam_mins=$(config_get roam_mins "$DEFAULT_ROAM_MINS")"
echo "no_app=$(config_get no_app 0)"
;;
floor)
[[ "$val" =~ ^[0-9]+$ ]] || die "config floor: need a whole number of percent (5-95)"
# 5 is low enough to be reckless but not bricking; 95 keeps the setting
# from being a way to disable roaming by accident.
[[ "$val" -ge 5 && "$val" -le 95 ]] || die "config floor: must be between 5 and 95"
config_set floor "$val"
echo "floor=$val"
;;
roam_mins)
[[ "$val" =~ ^[0-9]+$ ]] || die "config roam_mins: need a whole number of minutes (1-1440)"
[[ "$val" -ge 1 && "$val" -le 1440 ]] || die "config roam_mins: must be between 1 and 1440"
config_set roam_mins "$val"
echo "roam_mins=$val"
;;
no_app)
# CLI-only preference: 1 = install/upgrade never touch the menu bar
# app. Persisted like any standing setting, so an upgrade can't
# resurrect an interface the owner explicitly declined.
[[ "$val" == 0 || "$val" == 1 ]] || die "config no_app: 0 (install the menu bar app) or 1 (CLI only)"
config_set no_app "$val"
echo "no_app=$val"
if [[ "$val" == 1 && -d /Applications/Lich.app ]]; then
remove_menubar_app
echo "menu bar app removed (lich config no_app 0 && lich install brings it back)"
fi
;;
*)
die "unknown config key: $key (known: floor, roam_mins, no_app)"
;;
esac
}
cmd_status() {
local quiet="${1:-}"
# --quiet: no output, exit 0 when risen. The menu bar app polls this rather
# than parsing the human block below.
if [[ "$quiet" == "--quiet" || "$quiet" == "-q" ]]; then
risen; exit $?
fi
if risen; then
echo "lich: 💀 risen"
else
echo "lich: ⚰️ at rest"
fi
echo "power: $(power_source)"
# Separate line from "lich:" because the two legitimately disagree: risen on
# battery means this setting is off, and that is correct.
# Read ONCE and reuse for the on-battery note at the bottom: two reads could
# straddle a watcher tick and print the exact contradiction ("normal — lid-
# close sleeps" over "note: roaming") that note is there to make impossible.
local sleep_dis; sleep_dis="$(sleep_disabled)"
if [[ "$sleep_dis" == "1" ]]; then
if on_ac; then
echo "sleep: disabled — lid-close keeps the Mac awake"
else
# On battery the guarantee has an end — say which one, so a glance
# answers "will this thing sleep on its own if I walk away?". A ticking
# clock doubles as confirmation the timer checkbox is doing its job.
local sstate standing strip dl now_s idle when=""
sstate="$(roam_state)"; standing="${sstate%% *}"; strip="${sstate#* }"
dl=""
now_s="$(date +%s)"
case "$strip" in
until:*) dl="${strip#until:}" ;;
esac
if [[ -z "$dl" && "$strip" == "-" && "$standing" == "timer" ]]; then
# Idle-based: the deadline moves every time someone touches the Mac.
# Run from a terminal it reads the full window (you just typed);
# over ssh with the lid shut it is a real countdown.
idle="$(idle_seconds)"
if [[ "$idle" =~ ^[0-9]+$ ]]; then
dl=$(( now_s - idle + $(config_get roam_mins "$DEFAULT_ROAM_MINS") * 60 ))
when=" if left untouched"
fi
fi
if [[ -n "$dl" && "$dl" -gt "$now_s" ]]; then
echo "sleep: disabled — hands back to macOS at $(date -r "$dl" '+%H:%M')${when} ($(( (dl - now_s + 59) / 60 )) min left)"
elif [[ -n "$when" ]]; then
echo "sleep: disabled — handing back to macOS within ~5 seconds (idle past the timer)"
else
echo "sleep: disabled — until plugged back in (or battery floor)"
fi
fi
else
echo "sleep: normal — lid-close sleeps"
fi
# The other half of the sleep story: app power assertions block idle sleep
# with the lid open no matter what disablesleep says. Shown only when live,
# so a clean status stays five lines.
local blockers
blockers="$(sleep_blockers)"
if [[ -n "$blockers" ]]; then
echo "held awake by:"
printf '%s\n' "$blockers" | sed 's/^/ /'
fi
# Roaming and the battery are two lines, not one, for the same reason as
# above: they legitimately disagree. "roam: always" with the battery under
# the floor is a suspended preference, not a contradiction.
local floor; floor="$(config_get floor "$DEFAULT_FLOOR")"
read_battery
echo "roam: $(roam_human)"
echo "battery: ${BATTERY_PCT}% (floor ${floor}%)"
watcher_running && echo "watcher: running" || echo "watcher: NOT running (run: lich install)"
if ! risen; then
echo
echo "raise it: ${C_ACT}lich on${C_OFF} (stays awake with the lid closed while plugged in)"
elif ! on_ac; then
echo
# The note follows the LIVE setting, never the roam mode alone: a standing
# timer still reads "timer" long after its window closed, and this branch
# used to answer "roaming" there while lid-close would have slept the Mac
# on the spot. Whatever "sleep:" printed above, this agrees with it.
# Ordering after that: the floor outranks every mode (see roam_active), so
# a suspended mode is named as suspended rather than as expired.
local rnow rstanding; rnow="$(roam_state)"; rstanding="${rnow%% *}"
if [[ "$sleep_dis" == "1" && "${rnow#* }" != "-" ]]; then
echo "note: roaming — risen without the phylactery; 'lich done' when the work is finished"
elif [[ "$sleep_dis" == "1" ]]; then
echo "note: roaming — risen without the phylactery (standing setting: $rstanding)"
elif [[ "$rstanding" != "off" && ( "$BATTERY_PCT" -le "$floor" || -f "$FLOOR_LATCH" ) ]]; then
echo "note: the battery floor ended roaming — it resumes once charged to $(floor_resume_pct)%"
elif [[ "$rstanding" == "timer" ]]; then
# Typing `lich status` is itself input, so an ended timer is usually
# re-arming as you read this — say so, rather than claim it's over.
local rmins ridle; rmins="$(config_get roam_mins "$DEFAULT_ROAM_MINS")"; ridle="$(idle_seconds)"
if [[ "$ridle" =~ ^[0-9]+$ && "$ridle" -lt $(( rmins * 60 )) ]]; then
echo "note: timer re-arming — you're active again, so it stays awake within ~5 seconds"
else
echo "note: idle ${rmins}+ min — the timer handed sleep back; lid-close will sleep this Mac now"
echo " (any input re-arms it, or: ${C_ACT}lich roam always${C_OFF})"
fi
else
echo "note: on battery — the lich rests until the phylactery (AC power) returns"
echo " (or roam: lich roam — stay risen unplugged, down to the floor)"
fi
fi
}
# Copy a built Lich.app into /Applications and (re)launch it. The app must
# live at a stable path: it registers itself as a login item, and a pointer
# into a versioned Cellar directory dies on the next upgrade. Sources, in
# order: the brew prefix (the formula builds the app at install time, on this
# machine, so its ad-hoc signature is trusted here) or a clone's menubar/
# build. Quiet; returns 0 synced, 1 nothing to sync, 2 copy failed.
sync_menubar_app() {
local self="$1" src=""
if [[ -d "${self%/bin/lich}/Lich.app" ]]; then
src="${self%/bin/lich}/Lich.app"
elif [[ -d "$(dirname "$self")/menubar/Lich.app" ]]; then
src="$(dirname "$self")/menubar/Lich.app"
else
return 1
fi
pkill -f lich-menubar 2>/dev/null
rm -rf /Applications/Lich.app 2>/dev/null
cp -R "$src" /Applications/Lich.app 2>/dev/null || return 2
rm -f "$MENUBAR_ICON" 2>/dev/null # so menubar_verify reads a fresh verdict
open /Applications/Lich.app 2>/dev/null
return 0
}
# Take the menu bar app back out: login item first (an entry pointing at a
# deleted bundle lingers in System Settings), then the process, then the
# bundle. Only builds that know --unregister-login-item get asked — an older binary would
# treat the flag as a normal launch and never exit.
remove_menubar_app() {
local bin=/Applications/Lich.app/Contents/MacOS/lich-menubar
[[ -d /Applications/Lich.app ]] || return 0
if LC_ALL=C grep -aq -- '--unregister-login-item' "$bin" 2>/dev/null; then
"$bin" --unregister-login-item 2>/dev/null || true
fi
pkill -x lich-menubar 2>/dev/null || true
rm -rf /Applications/Lich.app 2>/dev/null || true
}
# Did the 💀 actually appear? "The app launched" is not the same thing: on
# plenty of Macs it runs fine with its icon hidden (macOS 26's per-app menu
# bar switch, a full menu bar behind the notch, a menu bar manager). The app
# checks for itself a few seconds after launch and writes its verdict to
# $MENUBAR_ICON; this waits for that. Prints one word: visible | hidden |
# unknown (screen locked/asleep, or the app is older than the check) |
# not-running.
menubar_verify() {
local i=0
while [[ "$i" -lt 50 ]]; do
[[ -s "$MENUBAR_ICON" ]] && break
sleep 0.2; i=$((i + 1))
done