SLOPSHOPPER

freeze

Freeze a Claude Code session at the next safe boundary and resume it later as if nothing happened (ctrl+x f, /freeze)

bandspinnerguardcommandtoaststatus
v0.2.0MITupdated 2026-10-12francktrouillez/claude-freeze
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · freeze
› fix the failing auth test and add an audit log call ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM › /freeze ⎿ freeze: ❄ Freezing. Running work finishes, then everything parks. /freeze or /freeze off to resume. ❄ Frozen since 08:53 · safe to disconnect · /freeze to resume ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts ⚠ freeze: ❄ Frozen since 08:53 · safe to disconnect · /freeze to resume

Draws

Spinner
❄ Frozen since 08:53 · safe to disconnect · /freeze to resume
README

<img src="assets/logo.svg" alt="Claude Freeze logo" width="112">

<h1 align="center">Claude Freeze</h1>

Stepping away in the middle of a task (a commute, a meeting, a laptop that has to sleep) leaves poor options today. Esc or Ctrl+C cancels the step in progress, and you then have to tell Claude it was only a pause. Ctrl+Z suspends the whole process wherever it happens to be, so a reply that is still streaming can fail once the network drops. Checkpoint and handoff skills carry on in a fresh session, without the live context.

/freeze keeps the session as it is. Whatever is already running finishes, then the session (subagents included) parks before its next step, and it tells you once nothing is talking to the network anymore, so you can close the lid or switch wifi. Run /freeze again and the turn continues exactly where it stopped, with nothing added to the conversation. /freeze on and /freeze off do the same explicitly, for scripts and tools that drive sessions.

The state shows on one line at a time: the spinner while a turn runs, otherwise the status line (or the band, with the optional shortcut):

✻ Freezing · 1 still running · /freeze to cancel (3m 1s)          ← finishing in-flight work
❄ Frozen since 08:12 · safe to disconnect · /freeze to resume     ← parked: animation and timer stop

What it does

  • Freezes at a safe boundary. A model reply that is streaming or a tool that is running finishes first; nothing is killed or retried.
  • Freezes everything. The main thread, subagents and background agents all park at their next model request or tool call.
  • Stops the spinner. Once parked, the animated line and its timer give way to a static ❄ Frozen since … line, so the session no longer looks busy.
  • Holds self-started turns. /loop wakeups, background-task notifications and messages you type while frozen wait until you resume; a wakeup that fires again with the same prompt is held only once.
  • Tells you when it is safe. The band and the status line say freezing… while work is still in flight and safe to disconnect once nothing is talking to the network: from then on you can close the lid, switch wifi, or go offline.
  • Pauses background tasks too (Linux). Commands started in the background, monitors and dev servers are paused once the freeze settles and continue when you resume, so nothing fails or keeps working behind your back while you are offline.
  • Names the MCP servers that dropped. If an MCP call fails on a lost connection shortly after you resume, a toast tells you which server to reconnect with /mcp.
  • Per session. Each Claude Code session freezes on its own.
  • Readable from outside. Each session's state (running, freezing or frozen) is kept in a one-word file, so a tool that drives several sessions can show it.

Install

Requires Claude Code with mods (function-hook plugins, on by default since 2.1.287; built and tested on 2.1.289) and a POSIX sh (macOS or Linux).

Option A: as a plugin (recommended)

The repo is its own marketplace:

claude plugin marketplace add francktrouillez/claude-freeze
claude plugin install freeze@claude-freeze

Then start a new session, or run /reload-plugins in a running one. /freeze works right away; the shortcut is optional (below).

Update later with:

claude plugin marketplace update claude-freeze
claude plugin update freeze@claude-freeze

Option B: from a clone (for hacking on it)

git clone https://github.com/francktrouillez/claude-freeze.git ~/Projects/claude-freeze

Then load it in every session by naming the folder in ~/.claude/settings.json:

{
  "env": {
    "CLAUDE_CODE_PLUGIN_DIRS": "~/Projects/claude-freeze"
  }
}

(or once, with claude --plugin-dir ~/Projects/claude-freeze). An interactive session watches the folder: saving a file reloads the mod.

Options

Set in /config, under the freeze plugin (the mod reloads by itself). For a clone loaded with CLAUDE_CODE_PLUGIN_DIRS, the same live in ~/.claude/settings.json under "pluginConfigs": { "freeze": { "options": { … } } }.

OptionDefaultWhat it does
pauseBackgroundonPause this session's background tasks while frozen (Linux).
shortcutoffShow the band above the prompt with the Ctrl+X F button.

Optional: the Ctrl+X F shortcut

Off by default. Turning it on adds a one-line band above the prompt that carries the button the shortcut presses. While a turn runs, the spinner already shows the state, so the band is only the button; when idle, the band takes over from the status line:

❄ ctrl+x f freeze                                                       ← not frozen
❄ ctrl+x f resume                                                       ← frozen, turn running (spinner has the rest)
❄ Frozen since 08:12 · safe to disconnect · /freeze or ctrl+x f to resume  ← frozen, idle

Turn it on with /freeze shortcut on: it adds the ctrl+x f binding to ~/.claude/keybindings.json (merged with what is there; it never takes over a key bound to something else, nor touches a file that is not valid JSON) and turns the shortcut option on. /freeze shortcut off turns the option off again.

To do it by hand instead: set the shortcut option (above) and add the binding below. Mods cannot register keyboard shortcuts of their own. The band's button borrows an engine action instead, app:cycleDiffBase (normally only live inside the diff panel), and a chord bound to that action at the prompt presses the button. Add it to ~/.claude/keybindings.json (create the file if it does not exist; merge if it does):

{
  "$schema": "https://www.schemastore.org/claude-code-keybindings.json",
  "$docs": "https://code.claude.com/docs/en/keybindings",
  "bindings": [
    {
      "context": "Chat",
      "bindings": {
        "ctrl+x f": "app:cycleDiffBase"
      }
    }
  ]
}

Why not Ctrl+F: the prompt already uses it to move the cursor forward, so the key never reaches the band. ctrl+x … is Claude Code's own prefix for extra shortcuts and is free at the prompt.

Usage

ActionHow
Freeze / resume/freeze (toggle); with the shortcut on, also Ctrl+X F or a click on the band
Freeze / resume, explicitly/freeze on / /freeze off: nothing happens when the session already is, so a script can send them safely
Turn the shortcut on / off/freeze shortcut on / /freeze shortcut off
Know it is safe to disconnectwait for safe to disconnect
Cancel a freeze that is still settling/freeze or /freeze off (/freeze on keeps it)
Abandon the parked turnEsc: the parked step is dropped, never run later

/freeze works mid-turn (it is an immediate command), including where the shortcut cannot reach: the transcript view (Ctrl+O), an open dialog, the desktop app, or a session followed from another device.

How it works

  • The gate. Hooks on turn.step (before every model request, subagents included) and tool.call (before every tool starts) check the frozen flag. When it is set, the hook waits before letting the step through, so the request is sent only after you resume, unchanged.
  • The hold. A mod hook has a 10 s budget of its own time, but time spent in a $ call does not count. A parked hook therefore waits on $.process.spawn of a tiny sh loop that exits once ~/.claude/freeze/<session-id>.thaw exists. Freezing removes that file and resuming creates it. The child is tied to the turn: Esc kills it at once, and the parked step is then refused, never run later.
  • Failing open, honestly. If the wait cannot run or exits with an error, the mod resumes the session rather than hang it, clears the frozen state (so nothing claims FROZEN while work runs) and shows a toast.
  • The in-flight counter. Each model request and tool call is counted before the gate checks the flag, and for as long as it runs. Tools that only host other loops (Agent, Task, Workflow) are not counted, since their inner steps are. freezing… turns into safe to disconnect when the count reaches zero.
  • Background tasks. Once the freeze settles (nothing in flight), the mod finds the processes whose output goes to this session's task files. Claude Code starts each background task in a session of its own, so the mod pauses that whole session (pkill -STOP -s), children included, and records it. On resume it continues exactly those (pkill -CONT -s) before the turn goes on. Anything still recorded is also continued when the mod reloads unfrozen and when the session ends. Each record names the Claude process that paused (pid and start time): if that process is gone (a crash, a kill), the next session that starts continues the tasks and drops the record, so nothing stays stopped forever.
  • Repeated wakeups. While frozen, a self-started prompt (a /loop or routine firing, a task notification) identical to one already held is dropped. Prompts you type are never touched.
  • Dropped MCP connections. For ten minutes after a resume, an MCP tool call that fails with a connection-type error (reset, timeout, not connected, 401) raises one toast per server: MCP server "x" lost its connection while frozen, run /mcp to reconnect.
  • The state file. ~/.claude/freeze/<session-id>.state holds one word and a newline: running, freezing (in-flight work still settling) or frozen (safe to disconnect). It is rewritten only when that word changes, through a temporary file renamed over it, so a reader never sees half a word. It is removed when the session ends. No file means running. A session that crashes can leave its file behind, so it only means something for a session that is still alive (leftover running files are pruned after 30 days). If the file cannot be written, a toast says so once and the freeze itself goes on.
  • One line at a time. The spinner carries the state while a turn runs; when idle, the band does (shortcut on) or else the status line.
  • The band (shortcut option only). A one-line band above the prompt carries the button the shortcut presses.

Security

  • The mod has no network access and reads nothing from your conversation.
  • It never changes a tool call or a model request. It only delays them, and drops a step you interrupt with Esc while frozen.
  • It runs a few fixed shell commands on your machine, and only signals the background tasks of the session it runs in. The session id and the state word are passed to them as arguments, never spliced into the command, and both are checked against a fixed pattern first.
  • Its files live in ~/.claude/freeze/, kept private (0700, files 0600), never in a shared /tmp. The state file says only running, freezing or frozen: nothing from the conversation.

Found a vulnerability? Please report it privately through the repository's Security tab (Report a vulnerability) rather than in a public issue.

Known limitations

  • The [-] at the right of the band (shortcut option only) is drawn by Claude Code on every band above the prompt (it collapses the band, also ctrl+x ctrl+a). A mod cannot hide it. Collapsing the band also unmounts the button, so the shortcut stops working until you expand it again; /freeze still works. Leave the option off for no band at all.
  • The band sits above the prompt. Below the prompt, a mod can only append text to the hint line (where the permission mode shows) or replace that whole line, losing Claude Code's own live indicators. The shortcut needs a button, and the band is the place for it.
  • Paused is not reconnected. Pausing stops background tasks from working and failing while you are offline, but a connection a task held open can still be reset by a network change; it sees that when it continues (many tools retry).
  • Background pausing is Linux-only (it reads /proc). On macOS the tasks keep running while frozen, and a toast says so.
  • A paused dev server does not answer until you resume. Turn pauseBackground off if you want it to keep serving while frozen.
  • MCP connections are not reconnected by the mod, which can only reach its own servers. Claude Code reconnects remote servers (sometimes asking to re-authenticate); the mod's toast tells you which one to look at.
  • Subagents are assumed to share the session id (they read the same thaw file). Verified for the main thread; for subagents it follows from the API, not a test.
  • The turn's clock still counts the frozen time. The mod hides the timer while frozen, but the elapsed time shown after you resume (and the closing … for 12m 3s line) includes the time spent frozen.
  • The prompt cache expires after about an hour. Resuming after a long freeze re-reads the whole conversation once, at full input price.

Development

claude plugin validate .   # what the module hooks and calls, and anything the engine would refuse
claude plugin test .       # tests/*.test.ts against the engine's test kit
tsc -p .                   # type-check (once the mod has loaded, which lays .claude-plugin/types/)

Files:

.claude-plugin/plugin.json       manifest
.claude-plugin/marketplace.json  makes the repo installable as a marketplace
hooks/hooks.json                 names the hooks module
hooks/register.tsx               the mod
types/index.d.ts                 the mod's state contract ($.state)
tests/freeze.test.ts             park, resume, toggle, on/off, state file, fail-open, background, MCP, spinner, band and shortcut-setup tests

Contributing

Contributions are welcome: bug reports, ideas and pull requests.

  • Issues: say what you did, what you expected and what happened, with your Claude Code version (claude --version) and OS.
  • Pull requests: keep them focused, add a test for new behaviour, and make sure claude plugin validate . and claude plugin test . pass. Mods run on an early-access API, so mention the Claude Code version you tested with.
  • Not sure about an idea? Open an issue first to talk it through.

License

MIT

Source 2 files
hooks/register.tsx 675 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { FreezeState } from '../types'
5
6// The engine keybinding action the band's Button borrows: binding a chord to
7// it in ~/.claude/keybindings.json ("Chat" context) presses the Button.
8const KEY_ACTION = 'app:cycleDiffBase'
9const KEY_LABEL = 'ctrl+x f'
10
11// Every script gets the session id as $1, never spliced in. Files live in a
12// private folder (never a shared /tmp, where another user could plant a
13// symlink or resume the session).
14const DIR = '"$HOME/.claude/freeze"'
15const FILE = `${DIR}/"$1.thaw"`
16const STOPPED = `${DIR}/"$1.stopped"`
17const STATE_FILE = `${DIR}/"$1.state"`
18const FREEZE_SH = `umask 077 && mkdir -p ${DIR} && rm -f ${FILE} && [ ! -e ${FILE} ]`
19const THAW_SH = `umask 077 && mkdir -p ${DIR} && touch ${FILE}`
20const WAIT_SH = `until [ -e ${FILE} ]; do sleep 1; done`
21
22// Background tasks are the processes whose stdout is one of this session's
23// task output files (…/<session-id>/tasks/<id>.output). Claude Code starts each
24// in a session of its own (setsid), and every child inherits it, even one in a
25// process group of its own or logging elsewhere: the session is what gets
26// paused. MCP servers share Claude's session, which is never touched, and a
27// session is only paused when its leader is itself a task process. Linux only
28// (/proc); elsewhere nothing is paused. Run once the freeze has settled, when
29// no foreground command is left.
30const PAUSE_SH = `[ -d /proc/self/fd ] || { echo unsupported; exit 0; }
31umask 077 && mkdir -p ${DIR}
32echo "# owner $PPID $(ps -o lstart= -p $PPID | tr -s ' ' '_')" > ${STOPPED}
33own=$(ps -o sid= -p $$ | tr -d ' ')
34pids=$(for fd in /proc/[0-9]*/fd/1; do
35  case "$(readlink "$fd" 2>/dev/null)" in
36    */"$1"/tasks/*) p=\${fd#/proc/}; echo "\${p%%/*}" ;;
37  esac
38done)
39leaders=" $(echo $pids) "
40for pid in $pids; do ps -o sid= -p "$pid"; done | tr -d ' ' | sort -u | while read -r sid; do
41  case "$sid" in ''|*[!0-9]*|0|1) continue ;; esac
42  [ "$sid" = "$own" ] && continue
43  case "$leaders" in *" $sid "*) ;; *) continue ;; esac
44  pkill -STOP -s "$sid" && echo "$sid" >> ${STOPPED}
45done
46grep -c '^[0-9]' ${STOPPED} || true`
47const RESUME_SH = `[ -f ${STOPPED} ] || exit 0
48while read -r sid; do
49  case "$sid" in ''|*[!0-9]*|0|1) continue ;; esac
50  pkill -CONT -s "$sid"
51done < ${STOPPED}
52rm -f ${STOPPED}`
53// A record whose owner (the Claude process that paused, by pid and start
54// time, so a reused pid does not count) is gone was left by a crash or a kill:
55// its tasks would stay stopped forever. Continue them and drop the record.
56// Thaw files older than a week are pruned. Prints how many sessions resumed.
57const RECOVER_SH = `n=0
58for f in ${DIR}/*.stopped; do
59  [ -e "$f" ] || continue
60  read -r _ _ pid start < "$f"
61  if [ -n "$pid" ] && [ "$(ps -o lstart= -p "$pid" 2>/dev/null | tr -s ' ' '_')" = "$start" ]; then
62    continue
63  fi
64  while read -r sid; do
65    case "$sid" in ''|*[!0-9]*|0|1) continue ;; esac
66    pkill -CONT -s "$sid" && n=$((n + 1))
67  done < "$f"
68  rm -f "$f"
69done
70find ${DIR} -name '*.thaw' -mtime +7 -delete 2>/dev/null
71find ${DIR} -name '*.state' -mtime +30 -exec grep -qx running {} \\; -delete 2>/dev/null
72find ${DIR} -name '.state.*' -mmin +60 -delete 2>/dev/null
73echo "$n"`
74const CLEAN_SH = `${RESUME_SH}
75rm -f ${FILE}`
76// The session's phase ($2, one of three fixed words) for tools outside the
77// session. Written to a temporary file in the private folder,
78// then renamed over the state file, so a reader never sees half a word.
79const WRITE_STATE_SH = `case "$2" in running|freezing|frozen) ;; *) exit 2 ;; esac
80umask 077 && mkdir -p ${DIR} && chmod 700 ${DIR}
81tmp=$(mktemp ${DIR}/.state.XXXXXX) || exit 1
82if printf '%s\\n' "$2" > "$tmp" && mv -f "$tmp" ${STATE_FILE}; then exit 0; fi
83rm -f "$tmp"
84exit 1`
85const REMOVE_STATE_SH = `rm -f ${STATE_FILE}`
86const SESSION_ID = /^[A-Za-z0-9_-]{1,128}$/
87
88// Tools that only host other loops: their inner steps and tool calls are
89// counted themselves, so counting the host would never let a freeze settle.
90const CONTAINER_TOOLS = new Set(['Agent', 'Task', 'Workflow'])
91
92// After a resume, an MCP call failing like this most likely hit a connection
93// that dropped while frozen (network change, expired session).
94const MCP_WATCH_MS = 10 * 60_000
95const CONNECTION_ERROR =
96  /ECONNRESET|ETIMEDOUT|ENOTFOUND|EAI_AGAIN|EPIPE|socket hang up|fetch failed|not connected|disconnected|connection (closed|lost|refused|reset)|session (expired|not found)|\b401\b|unauthori[sz]ed|re-?auth/i
97
98const IDLE: FreezeState = {
99  isFrozen: false,
100  since: null,
101  parked: 0,
102  running: 0,
103  paused: 0,
104  resumedAt: null,
105}
106const state = atom({ plugin: 'freeze', key: 'state' } as const, IDLE)
107
108// Prompts the session starts by itself (a /loop or routine firing, a task
109// notification) that arrived while frozen: an identical one is held once.
110const SELF_STARTED = new Set(['scheduled-trigger', 'task-notification'])
111let heldPrompts = new Set<string>()
112
113// Set from the options at each (re)load.
114let shouldPauseBackground = true
115let toggleHint = '/freeze'
116let hasBand = false
117// Whether the main thread's turn is running, i.e. its spinner is on screen.
118let isWorking = false
119
120const hhmm = (ms: number | null) =>
121  ms === null ? '' : new Date(ms).toTimeString().slice(0, 5)
122
123const isSettled = (s: FreezeState) => s.isFrozen && s.running === 0
124
125// What ~/.claude/freeze/<session-id>.state says: `freezing` while in-flight
126// work settles, `frozen` once it is safe to disconnect, `running` otherwise.
127type Phase = 'running' | 'freezing' | 'frozen'
128
129const phaseOf = (s: FreezeState): Phase =>
130  !s.isFrozen ? 'running' : isSettled(s) ? 'frozen' : 'freezing'
131
132// One full line at a time: the spinner while a turn runs, else the band when
133// the shortcut is on, else the status line.
134function statusText(s: FreezeState) {
135  if (!s.isFrozen || isWorking || hasBand) {
136    return undefined
137  }
138
139  return stateLine(s)
140}
141
142async function refreshStatus($: EngineInterface) {
143  $.ui.status(statusText(await read($, state)))
144}
145
146function stateLine(s: FreezeState) {
147  return isSettled(s)
148    ? frozenLine(s)
149    : `❄ Freezing · ${s.running} still running · ${toggleHint} to cancel`
150}
151
152// "❄ Frozen since 17:49 · safe to disconnect · 2 background paused · /freeze to resume"
153function frozenLine(s: FreezeState) {
154  const paused = s.paused > 0 ? ` · ${s.paused} background paused` : ''
155
156  return `❄ Frozen since ${hhmm(s.since)} · safe to disconnect${paused} · ${toggleHint} to resume`
157}
158
159function queue() {
160  let tail: Promise<unknown> = Promise.resolve()
161
162  return <T,>(work: () => Promise<T>) => {
163    const run = tail.then(work)
164    tail = run.catch(() => undefined)
165
166    return run
167  }
168}
169
170// Pausing, resuming and toggling run one at a time, so a late pause can never
171// stop processes after a resume, and quick presses cannot interleave.
172const serial = queue()
173// State file writes too, apart: a toggle waits on them, never the reverse.
174const serialStateFile = queue()
175
176// The phase last sent to the state file, written or not. Undefined after a
177// (re)load or a session end, so the next change writes it; a failed write is
178// retried when the phase changes again, not on every tool call.
179let sentPhase: Phase | undefined
180let hasWarnedStateFile = false
181// The session that ended: work still settling as it closes must not write its
182// state file again once removed.
183let endedSessionId: string | undefined
184
185// Writes the current phase, read when the write runs, so writes that queue up
186// end on the latest one. Never rejects: the file is for outside readers, and
187// must not fail a freeze, a resume or a tool call. A failure is shown once.
188function syncStateFile($: EngineInterface) {
189  return serialStateFile(async () => {
190    try {
191      const id = await $.session.id()
192      if (id === endedSessionId) {
193        return
194      }
195      endedSessionId = undefined
196      // Read again after each write, for a change that landed during it.
197      for (;;) {
198        const phase = phaseOf(await read($, state))
199        if (phase === sentPhase) {
200          return
201        }
202        sentPhase = phase
203        await shFor($, id, WRITE_STATE_SH, [phase])
204        hasWarnedStateFile = false
205      }
206    } catch (error) {
207      if (!hasWarnedStateFile) {
208        hasWarnedStateFile = true
209        $.ui.toast(`could not write the freeze state file (${reasonOf(error)})`)
210      }
211    }
212  })
213}
214
215const reasonOf = (error: unknown) => (error instanceof Error ? error.message : String(error))
216
217async function change($: EngineInterface, fn: (s: FreezeState) => FreezeState) {
218  let before = IDLE
219  // State kept from an older version of the mod may lack newer fields.
220  const next = await update($, state, s => {
221    before = { ...IDLE, ...s }
222
223    return fn(before)
224  })
225  $.ui.status(statusText(next))
226  if (phaseOf(next) !== sentPhase) {
227    await syncStateFile($)
228  }
229  if (shouldPauseBackground && !isSettled(before) && isSettled(next)) {
230    void serial(() => pauseBackground($))
231  }
232
233  return next
234}
235
236function checkSessionId(id: string) {
237  if (!SESSION_ID.test(id)) {
238    throw new Error(`unexpected session id ${JSON.stringify(id)}`)
239  }
240
241  return id
242}
243
244async function sessionId($: EngineInterface) {
245  return checkSessionId(await $.session.id())
246}
247
248// Runs a fixed script with this session's id as $1 and `args` after it.
249async function sh($: EngineInterface, script: string, args: string[] = []) {
250  return shFor($, await $.session.id(), script, args)
251}
252
253async function shFor($: EngineInterface, id: string, script: string, args: string[] = []) {
254  const { exitCode, stdout, stderr } = await $.process.run([
255    'sh',
256    '-c',
257    script,
258    'sh',
259    checkSessionId(id),
260    ...args,
261  ])
262  if (exitCode !== 0) {
263    throw new Error(stderr.trim() || `exit ${exitCode}`)
264  }
265
266  return stdout.trim()
267}
268
269async function pauseBackground($: EngineInterface) {
270  if (!isSettled(await read($, state))) {
271    return
272  }
273  try {
274    const out = await sh($, PAUSE_SH)
275    if (out === 'unsupported') {
276      $.ui.toast('pausing background tasks needs Linux (/proc); they keep running')
277
278      return
279    }
280    const paused = Number(out) || 0
281    await change($, s => ({ ...s, paused }))
282  } catch (error) {
283    $.ui.toast(`could not pause background tasks (${error instanceof Error ? error.message : String(error)})`)
284  }
285}
286
287async function freeze($: EngineInterface) {
288  // File first, then the flag: a waiter never sees "frozen" + thaw file.
289  await sh($, FREEZE_SH)
290  const since = await $.clock.now()
291  heldPrompts = new Set()
292  await change($, s => ({ ...s, isFrozen: true, since }))
293}
294
295async function thaw($: EngineInterface) {
296  // Background tasks first, then the waiters. If the thaw file cannot be
297  // written, the session stays honestly frozen.
298  await sh($, RESUME_SH)
299  await sh($, THAW_SH)
300  const resumedAt = await $.clock.now()
301  await change($, s => ({ ...s, isFrozen: false, since: null, paused: 0, resumedAt }))
302}
303
304// `/freeze shortcut on`: binds ctrl+x f in ~/.claude/keybindings.json (merged,
305// never overwriting another binding or a file that is not valid JSON) and
306// turns the option on, which reloads the mod with its band. `off` turns the
307// option off and leaves the binding (inert without the band).
308async function setShortcut($: EngineInterface, isOn: boolean) {
309  if (isOn) {
310    const problem = await bindShortcutKey($)
311    if (problem) {
312      return problem
313    }
314  }
315  const result = await $.config.set({ key: `${$.plugin.name}.shortcut`, value: isOn })
316  if ('deny' in result && result.deny) {
317    return `could not change the shortcut option (${result.deny}). Set it in /config.`
318  }
319
320  return isOn
321    ? `Shortcut on: ${KEY_LABEL} toggles freeze (bound in ~/.claude/keybindings.json).`
322    : `Shortcut off. The ${KEY_LABEL} binding stays in ~/.claude/keybindings.json, inert without the band.`
323}
324
325async function bindShortcutKey($: EngineInterface) {
326  const home = (await $.process.run(['sh', '-c', 'printf %s "$HOME"'])).stdout
327  const path = `${home}/.claude/keybindings.json`
328  const exists = (await $.process.run(['test', '-e', path])).exitCode === 0
329  let doc: { bindings?: unknown } = {}
330  if (exists) {
331    try {
332      doc = JSON.parse(await $.fs.read(path))
333    } catch {
334      return `${path} is not valid JSON, left untouched. Add the binding by hand (README).`
335    }
336  }
337  const blocks = Array.isArray(doc.bindings) ? (doc.bindings as KeyBlock[]) : []
338  const chat = blocks.find(b => b?.context === 'Chat')
339  const current = chat?.bindings?.[KEY_LABEL]
340  if (current === KEY_ACTION) {
341    return undefined
342  }
343  if (current) {
344    return `${KEY_LABEL} is already bound to ${current} in ${path}, left untouched.`
345  }
346  const nextChat: KeyBlock = {
347    context: 'Chat',
348    bindings: { ...(chat?.bindings ?? {}), [KEY_LABEL]: KEY_ACTION },
349  }
350  const nextDoc = {
351    $schema: 'https://www.schemastore.org/claude-code-keybindings.json',
352    $docs: 'https://code.claude.com/docs/en/keybindings',
353    ...doc,
354    bindings: chat ? blocks.map(b => (b === chat ? nextChat : b)) : [...blocks, nextChat],
355  }
356  await $.fs.write(path, `${JSON.stringify(nextDoc, null, 2)}\n`)
357
358  return undefined
359}
360
361type KeyBlock = { context?: string; bindings?: Record<string, string | null> }
362
363type Outcome =
364  | { kind: 'froze' | 'resumed' | 'already-frozen' | 'not-frozen' }
365  | { kind: 'failed'; action: 'freeze' | 'resume'; reason: string }
366
367// `/freeze on` and `off` are idempotent: asking for the state the session is
368// already in (settling included) changes nothing. `undefined` toggles. The
369// state is read inside the queue, so quick requests see each other's result.
370function setFrozen($: EngineInterface, shouldFreeze?: boolean) {
371  return serial(async (): Promise<Outcome> => {
372    const { isFrozen } = await read($, state)
373    const target = shouldFreeze ?? !isFrozen
374    if (target === isFrozen) {
375      return { kind: isFrozen ? 'already-frozen' : 'not-frozen' }
376    }
377    try {
378      await (target ? freeze($) : thaw($))
379
380      return { kind: target ? 'froze' : 'resumed' }
381    } catch (error) {
382      return { kind: 'failed', action: target ? 'freeze' : 'resume', reason: reasonOf(error) }
383    }
384  })
385}
386
387async function pressToggle($: EngineInterface) {
388  const outcome = await setFrozen($)
389  if (outcome.kind === 'failed') {
390    $.ui.toast(`could not ${outcome.action} (${outcome.reason})`)
391  }
392}
393
394async function outcomeText($: EngineInterface, outcome: Outcome) {
395  switch (outcome.kind) {
396    case 'froze':
397      return '❄ Freezing. Running work finishes, then everything parks. /freeze or /freeze off to resume.'
398    case 'resumed':
399      return 'Resumed.'
400    case 'not-frozen':
401      return 'Not frozen.'
402    case 'already-frozen': {
403      const s = await read($, state)
404
405      return isSettled(s)
406        ? 'Already frozen · safe to disconnect.'
407        : `Already freezing · ${s.running} still running.`
408    }
409    case 'failed':
410      return `Could not ${outcome.action} (${outcome.reason}).`
411  }
412}
413
414// Waits until resumed. The child is tied to the dispatch: Esc (`signal`)
415// kills it at once. A child that fails (cannot start, exits non-zero) is not
416// a resume: the mod fails open and clears the state, so the UI never claims
417// FROZEN while the session runs.
418async function park($: EngineInterface, signal: AbortSignal) {
419  await change($, s => ({ ...s, parked: s.parked + 1 }))
420  try {
421    const wait = $.process.spawn({ argv: ['sh', '-c', WAIT_SH, 'sh', await sessionId($)] })
422    const pieces = wait[Symbol.asyncIterator]()
423    let piece = await pieces.next()
424    while (!piece.done && !signal.aborted) {
425      piece = await pieces.next()
426    }
427    if (signal.aborted || (piece.done && piece.value?.code === 0)) {
428      return
429    }
430    throw new Error(`wait ended with ${JSON.stringify(piece.value)}`)
431  } catch (error) {
432    if (!signal.aborted) {
433      await serial(() => sh($, RESUME_SH)).catch(() => undefined)
434      await change($, s => ({ ...s, isFrozen: false, since: null, paused: 0 }))
435      $.ui.toast(`could not hold the session, resumed (${error instanceof Error ? error.message : String(error)})`)
436    }
437  } finally {
438    await change($, s => ({ ...s, parked: Math.max(0, s.parked - 1) }))
439  }
440}
441
442const running = (delta: number) => (s: FreezeState) => ({
443  ...s,
444  running: Math.max(0, s.running + delta),
445})
446
447// The gate in front of every step and tool call. It counts the work first and
448// checks the flag second, so a freeze landing in between shows "1 still
449// running" rather than "safe to disconnect". Resolves false when the dispatch
450// was abandoned (Esc) while parked: the caller must not run anything then.
451async function gate($: EngineInterface, signal: AbortSignal) {
452  await change($, running(1))
453  if (!(await read($, state)).isFrozen) {
454    return true
455  }
456
457  await change($, running(-1))
458  await park($, signal)
459  if (signal.aborted) {
460    return false
461  }
462  await change($, running(1))
463
464  return true
465}
466
467// Names the MCP server whose call failed on a dropped connection, once per
468// server, for a while after a resume.
469const warnedServers = new Set<string>()
470
471async function checkMcpCall($: EngineInterface, tool: string, outcome: unknown) {
472  const { resumedAt } = await read($, state)
473  if (resumedAt === null || (await $.clock.now()) - resumedAt > MCP_WATCH_MS) {
474    return
475  }
476  const failure =
477    outcome instanceof Error
478      ? outcome.message
479      : (outcome as { isError?: boolean }).isError
480        ? JSON.stringify(outcome)
481        : ''
482  const server = tool.split('__')[1] ?? tool
483  if (!CONNECTION_ERROR.test(failure) || warnedServers.has(server)) {
484    return
485  }
486  warnedServers.add(server)
487  $.ui.toast(`MCP server "${server}" lost its connection while frozen, run /mcp to reconnect`)
488}
489
490export const register: Register = (on, options) => {
491  const hasShortcut = options.shortcut === true
492  shouldPauseBackground = options.pauseBackground !== false
493  toggleHint = hasShortcut ? `/freeze or ${KEY_LABEL}` : '/freeze'
494  hasBand = hasShortcut
495  isWorking = false
496
497  on('turn.start', async ($, e, next) => {
498    isWorking = true
499    await refreshStatus($)
500
501    return next(e)
502  })
503
504  on('turn.complete', async ($, e, next) => {
505    if (e.agentId === undefined) {
506      isWorking = false
507      await refreshStatus($)
508    }
509
510    return next(e)
511  })
512
513  on('session.start', async ($, e, next) => {
514    await $.command.register({
515      name: 'freeze',
516      description: 'Freeze or resume this session at the next safe boundary',
517      argumentHint: '[on|off] · shortcut on|off',
518      immediate: true,
519    })
520    // Fires again on every reload: counters from a previous load are stale,
521    // and nothing may stay stopped unless the session is frozen.
522    const s = await change($, prev => ({ ...prev, parked: 0, running: 0 }))
523    if (!s.isFrozen) {
524      await serial(() => sh($, RESUME_SH)).catch(() => undefined)
525    }
526    const recovered = Number(await sh($, RECOVER_SH).catch(() => '0')) || 0
527    if (recovered > 0) {
528      $.ui.toast(`resumed ${recovered} background task(s) left paused by a session that ended`)
529    }
530
531    return next(e)
532  })
533
534  on('session.end', async ($, e, next) => {
535    // Never leave background tasks stopped behind a closed session. The ending
536    // session's id is the event's: after a /clear the process goes on under
537    // another, whose state file is written on its next change.
538    await shFor($, e.sessionId, CLEAN_SH).catch(() => undefined)
539    await serialStateFile(async () => {
540      endedSessionId = e.sessionId
541      sentPhase = undefined
542      await shFor($, e.sessionId, REMOVE_STATE_SH).catch(() => undefined)
543    })
544
545    return next(e)
546  })
547
548  on('command.run', { command: 'freeze' }, async ($, e) => {
549    const args = e.args.trim().toLowerCase().split(/\s+/).join(' ')
550    if (args === 'shortcut on' || args === 'shortcut off') {
551      return { text: await setShortcut($, args === 'shortcut on') }
552    }
553    if (args !== '' && args !== 'on' && args !== 'off') {
554      return { text: 'Usage: /freeze (toggle) · /freeze on|off · /freeze shortcut on|off' }
555    }
556    const shouldFreeze = args === '' ? undefined : args === 'on'
557
558    return { text: await outcomeText($, await setFrozen($, shouldFreeze)) }
559  })
560
561  on('prompt.submit', async ($, e, next) => {
562    if (SELF_STARTED.has(e.origin.kind) && (await read($, state)).isFrozen) {
563      const key = `${e.origin.kind}:${e.text}`
564      if (heldPrompts.has(key)) {
565        return { drop: 'the same prompt is already held until you resume' }
566      }
567      heldPrompts = new Set([...heldPrompts, key])
568    }
569
570    return next(e)
571  })
572
573  on('tool.call', async ($, e, next) => {
574    if (CONTAINER_TOOLS.has(e.tool)) {
575      // Not counted (its inner loop is gated step by step), only held.
576      if ((await read($, state)).isFrozen) {
577        await park($, next.signal)
578      }
579
580      return next.signal.aborted
581        ? { deny: 'Interrupted while the session was frozen.' }
582        : next(e)
583    }
584
585    if (!(await gate($, next.signal))) {
586      // Interrupted while parked: never run a tool of an abandoned turn.
587      return { deny: 'Interrupted while the session was frozen.' }
588    }
589    try {
590      const outcome = await next(e)
591      if (e.tool.startsWith('mcp__')) {
592        await checkMcpCall($, e.tool, outcome)
593      }
594
595      return outcome
596    } catch (error) {
597      if (e.tool.startsWith('mcp__')) {
598        await checkMcpCall($, e.tool, error)
599      }
600      throw error
601    } finally {
602      await change($, running(-1))
603    }
604  })
605
606  on('turn.step', async function* ($, e, next) {
607    if (!(await gate($, next.signal))) {
608      // Interrupted while parked: answer for the step with "no request was
609      // made", so nothing is sent for an abandoned turn (a bare return is
610      // refused by the engine, which then skips the hook).
611      return { turnId: e.turnId, index: e.index, answer: '', toolUses: [], stopReason: null, usage: null }
612    }
613    try {
614      return yield* next(e)
615    } finally {
616      await change($, running(-1))
617    }
618  })
619
620  // The line that animates while a turn runs (`Swooping… (3m 1s …)`). While
621  // work is still in flight it keeps animating, honestly, as "Freezing…"; once
622  // settled it is replaced whole, timer included, by a static frozen line.
623  on('ui.render', { component: 'Spinner' }, async ($, e, next) => {
624    const s = await read($, state)
625    if (!s.isFrozen) {
626      return next(e)
627    }
628    if (!isSettled(s)) {
629      const message = `Freezing · ${s.running} still running · ${toggleHint} to cancel`
630
631      return next({ ...e, props: { ...e.props, message, suffix: '' } })
632    }
633
634    const { Text } = $.ui.resolve(e)
635
636    return <Text color="cyan">{frozenLine(s)}</Text>
637  })
638
639  if (!hasShortcut) {
640    return
641  }
642
643  // The band exists only for the shortcut: its Button is what the borrowed
644  // keybinding action presses. Without the option, the status line suffices.
645  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
646    if (e.props.hasSurvey) {
647      return next(e)
648    }
649
650    const s = await read($, state)
651    const { Box, Button } = $.ui.resolve(e)
652    // While a turn runs, the spinner carries the state: the band is only the
653    // button. Idle, the band is the one full line.
654    const action = isSettled(s) ? 'resume' : 'cancel'
655    const label = !s.isFrozen
656      ? `❄ ${KEY_LABEL} freeze`
657      : e.props.isWorking
658        ? `❄ ${KEY_LABEL} ${action}`
659        : stateLine(s)
660
661    return (
662      <Box>
663        <Button
664          key="toggle"
665          plain
666          dimColor={!s.isFrozen}
667          action={KEY_ACTION}
668          label={label}
669          onPress={() => void pressToggle($)}
670        />
671      </Box>
672    )
673  })
674}
675
types/index.d.ts 15 lines
1export type FreezeState = {
2  isFrozen: boolean
3  since: number | null
4  parked: number
5  running: number
6  paused: number
7  resumedAt: number | null
8}
9
10declare module 'claude-code' {
11  interface PluginState {
12    freeze: { state: FreezeState }
13  }
14}
15