Keep the Mac's screen awake with caffeinate only while Claude is actively working

A Claude Code mod that keeps your Mac's screen awake only while Claude is actively working. The screen can sleep again as soon as Claude finishes, or while it is waiting on you.
AskUserQuestion prompt or an MCP input prompt is waiting on you, and resumes once you answer.caffeinate, and macOS keeps the display on while any of them asks, so the screen sleeps only once no session is working.npx, no admin rights, no background server.caffeinate -t 300 renewed while the turn runs, so a session that dies leaves no stray hold for more than 5 minutes.Claude Code already runs caffeinate -i while it works, which stops the Mac from going to sleep but still lets the screen turn off. This mod adds -d to keep the display on as well.
At the prompt of a terminal session:
/plugin install cc-mod-caffeinate --marketplace williamchong/cc-mod-caffeinate
Answer y to add the marketplace, then choose a scope (user scope loads it in every session).
/usr/bin/caffeinate)| Claude is… | Screen |
|---|---|
| running a turn (thinking, calling tools) | held awake |
| showing a permission dialog, asking a question, or waiting on MCP input | released |
| done with the turn, but a background subagent, workflow or Bash job is still running | held awake |
done with the turn, with only a dev server, watcher or Monitor left in the background | released |
| done with the turn, or the session ended | released |
Background work is read from the list Claude Code hands its Stop hook when a turn ends. A finished background task wakes the session with a new turn, so the hold is checked again each time one finishes. A background Bash command counts as a server and is not held when it looks like one that runs until it is stopped: dev, serve, server, start, watch, preview, up, runserver, http.server, nodemon, --watch or tail -f. A server that slips past this list, or a job killed without waking the session, is let go after backgroundHoldMinutes.
Claude Code has no event for "a permission prompt was answered", so holding resumes at the next sign of progress: the tool finishing, a denial, or the next model request. While a tool you just approved is running, the screen is not held. Your key press to approve resets the idle timer anyway.
To check it, run this while Claude is working:
pmset -g assertions | grep caffeinate
| Option | Default | Effect |
|---|---|---|
keepAwakeLidClosed | false | Also passes -s to caffeinate, so Claude keeps working when you close the lid. AC power only: on battery, closing the lid still puts the Mac to sleep. |
showStatus | true | Shows "☕ awake" in the prompt footer while the screen is held. |
backgroundHoldMinutes | 60 | Releases the screen this many minutes after a turn ends, even if background jobs still run. It is checked as the 5-minute hold renews, so it fires up to 5 minutes late. 0 holds until they finish. |
Set it on the plugin's config screen in /plugin. When you run the mod from a checkout (--plugin-dir or CLAUDE_CODE_PLUGIN_DIRS), set it under pluginConfigs in ~/.claude/settings.json instead:
"pluginConfigs": {
"cc-mod-caffeinate": { "options": { "keepAwakeLidClosed": true } }
}
The same rules apply with the lid closed: the Mac is released while Claude waits on you and when the turn ends, so it sleeps once there is nothing left to do. Even so, avoid putting a Mac that is plugged in and working into a bag.
caffeinate -w?A one-liner keeps the screen on for as long as Claude Code is open:
caffeinate -d -w $(pgrep -n claude)
That holds for the whole session, not for the turn. A session left open overnight at an idle prompt keeps the screen on all night, which is the same as turning display sleep off.
caffeinate -d -w | This mod | |
|---|---|---|
| Screen held while Claude runs a turn | yes | yes |
| Screen can sleep when the turn ends | no | yes |
| Screen can sleep while Claude waits on you | no | yes |
| Several sessions | one command per session, run by hand | automatic |
| Shows when the screen is held | no | "☕ awake" in the prompt footer |
Two shell hooks (UserPromptSubmit to start caffeinate, Stop to kill it) get closer, but they keep holding during permission dialogs and questions, and you manage the pid files and stale holds from crashed sessions yourself.
If you quit Claude Code whenever you step away, the one-liner is enough.
pmset disablesleep.Run it from a checkout:
claude --plugin-dir /path/to/cc-mod-caffeinate
To load it in every session, set CLAUDE_CODE_PLUGIN_DIRS to the checkout's path in the env block of ~/.claude/settings.json. Saving a file reloads the mod in interactive sessions.
Check and test it:
claude plugin validate .
claude plugin test .
hooks/register.ts 215 lines1import { read } from 'claude-code'
2import type { ClassicHookInputs, EngineInterface, Register } from 'claude-code'
3
4// Each session holds its own `caffeinate` while it works. macOS keeps the
5// display awake while any process holds an assertion, so several sessions
6// combine on their own: the screen may sleep only once none is working.
7
8// A bounded lease, renewed while active, so a session that dies without
9// unloading never leaves an orphan caffeinate holding the screen for long.
10const LEASE_SECONDS = 300
11
12// Redraws the prompt footer, where a ☕ mode label shows the hold.
13const holdingState = { plugin: 'cc-mod-caffeinate', key: 'isHolding' } as const
14
15// Not `idle`: it comes after the turn ends, while background jobs may hold.
16const WAITING_NOTIFICATION = /permission|elicitation/
17
18// A background command that serves or watches runs until someone stops it,
19// so it is not work that should keep the screen on after the turn.
20const LONG_RUNNING_COMMAND =
21 /(?:^|[\s;&|:"'])(?:dev|serve|server|start|watch|preview|nodemon|runserver|http\.server|up)(?=$|[\s;&|:"'])|--watch(?:All)?\b|\btail\s+-[fF]\b/
22
23type BackgroundTask = NonNullable<ClassicHookInputs['Stop']['background_tasks']>[number]
24
25// Background work that ends on its own and wakes the session when done.
26function isBackgroundJob(task: BackgroundTask) {
27 if (task.type === 'subagent' || task.type === 'workflow') return true
28 if (task.type === 'shell') return !LONG_RUNNING_COMMAND.test(task.command ?? '')
29 return false
30}
31
32// -d keeps the display on; -i stops idle sleep; -s, opted into, also stops
33// lid-closed sleep, which macOS honours on AC power only.
34let flags: string[] = []
35let showStatus = true
36// A missed server or a job that never wakes the session is let go after this.
37let backgroundLimitMs = 0
38
39let isTurnRunning = false
40let hasBackgroundJob = false
41let backgroundSince = 0
42let isWaiting = false
43let lease: AsyncGenerator<unknown, unknown> | undefined
44// What this module last wrote to the footer. Unlike `$.state`, it starts over
45// on a reload, so a ☕ left from before the reload is not shown.
46let shownHolding: boolean | undefined
47
48function shouldHold() {
49 return (isTurnRunning || hasBackgroundJob) && !isWaiting
50}
51
52async function hold($: EngineInterface) {
53 while (shouldHold()) {
54 let child: ReturnType<EngineInterface['process']['spawn']> | undefined
55 let code: number | null = null
56 try {
57 child = $.process.spawn({
58 argv: ['/usr/bin/caffeinate', ...flags, '-t', String(LEASE_SECONDS)],
59 })
60 lease = child
61 for await (const _ of child) {
62 // caffeinate writes nothing; the loop lasts the child's life
63 }
64 code = (await child.result).code
65 } catch {
66 // could not start, or killed by a release
67 }
68 if (lease !== child) return // released, or a newer hold took over
69 // Only a lease that ran out is renewed; any other end would respawn in a spin.
70 if (code !== 0) {
71 lease = undefined
72 return
73 }
74 if (!isTurnRunning && backgroundLimitMs > 0) {
75 const now = await $.clock.now()
76 if (lease !== child) return
77 if (now - backgroundSince >= backgroundLimitMs) {
78 hasBackgroundJob = false
79 lease = undefined
80 sync($)
81 return
82 }
83 }
84 }
85}
86
87function sync($: EngineInterface) {
88 const isHolding = shouldHold()
89 if (showStatus && shownHolding !== isHolding) {
90 shownHolding = isHolding
91 // A plain set, not `update`, so rapid calls land in the order made.
92 $.state.set(holdingState, isHolding).catch(() => {
93 shownHolding = undefined
94 })
95 }
96 if (isHolding && !lease) void hold($)
97 if (!isHolding && lease) {
98 // Not awaited: a pending pull on a silent child may hold return() back.
99 void lease.return(undefined).catch(() => {})
100 lease = undefined
101 }
102}
103
104function setRunning($: EngineInterface, value: boolean) {
105 isTurnRunning = value
106 isWaiting = false
107 sync($)
108}
109
110function setWaiting($: EngineInterface, value: boolean) {
111 if (isWaiting === value) return
112 isWaiting = value
113 sync($)
114}
115
116export const register: Register = (on, options) => {
117 flags = ['-d', '-i', ...(options.keepAwakeLidClosed === true ? ['-s'] : [])]
118 showStatus = options.showStatus !== false
119 const minutes = options.backgroundHoldMinutes
120 backgroundLimitMs = (typeof minutes === 'number' && minutes >= 0 ? minutes : 60) * 60_000
121
122 on('ui.render', { component: 'SessionMode' }, async ($, e, next) => {
123 // Read first: the read is what redraws the footer when the hold changes.
124 if (!(await read($, holdingState)) || shownHolding !== true) return next(e)
125 return next({ ...e, props: { ...e.props, modes: [...e.props.modes, '☕ awake'] } })
126 })
127
128 on('turn.start', ($, e, next) => {
129 // A subagent's turn is part of main's or of a background job, held either way.
130 if (e.agentId !== undefined) {
131 setWaiting($, false)
132 return next(e)
133 }
134 // The turn holds anyway; its Stop says again what is left in the background.
135 // An interrupted turn fires no Stop, so jobs it leaves are no longer held.
136 hasBackgroundJob = false
137 setRunning($, true)
138 return next(e)
139 })
140
141 on('turn.complete', ($, e, next) => {
142 // A subagent's turn ending is not the session going idle.
143 if (e.agentId === undefined) setRunning($, false)
144 return next(e)
145 })
146
147 // A finished background task wakes the session with a new turn, whose Stop
148 // lists what is still running, so this snapshot never outlives the work.
149 on('classic.Stop', async ($, e, next) => {
150 if (e.agent_id === undefined) {
151 hasBackgroundJob = (e.background_tasks ?? []).some(isBackgroundJob)
152 sync($)
153 if (hasBackgroundJob && backgroundLimitMs > 0) backgroundSince = await $.clock.now()
154 }
155 return next(e)
156 })
157
158 on('session.end', ($, e, next) => {
159 hasBackgroundJob = false
160 setRunning($, false)
161 return next(e)
162 })
163
164 on('classic.PermissionRequest', ($, e, next) => {
165 setWaiting($, true)
166 return next(e)
167 })
168
169 on('classic.Elicitation', ($, e, next) => {
170 setWaiting($, true)
171 return next(e)
172 })
173
174 on('classic.Notification', ($, e, next) => {
175 if (WAITING_NOTIFICATION.test(e.notification_type)) setWaiting($, true)
176 return next(e)
177 })
178
179 on('tool.call', { tool: 'AskUserQuestion' }, async ($, e, next) => {
180 setWaiting($, true)
181 try {
182 return await next(e)
183 } finally {
184 setWaiting($, false)
185 }
186 })
187
188 // No event says a permission prompt was answered; these are the first
189 // signs that the turn went on after one.
190 on('classic.PostToolUse', ($, e, next) => {
191 setWaiting($, false)
192 return next(e)
193 })
194
195 on('classic.PostToolUseFailure', ($, e, next) => {
196 setWaiting($, false)
197 return next(e)
198 })
199
200 on('classic.PermissionDenied', ($, e, next) => {
201 setWaiting($, false)
202 return next(e)
203 })
204
205 on('classic.ElicitationResult', ($, e, next) => {
206 setWaiting($, false)
207 return next(e)
208 })
209
210 on('turn.step', async function* ($, e, next) {
211 setWaiting($, false)
212 return yield* next(e)
213 })
214}
215types/index.d.ts 9 lines1// Whether this session holds the screen, which the prompt footer reads.
2export type IsHolding = boolean
3
4declare module 'claude-code' {
5 interface PluginState {
6 'cc-mod-caffeinate': { isHolding: IsHolding }
7 }
8}
9