跳到正文
DEV Community· Omer Saleem·· 10 天前AI 評分58

如何自動清理閒置的 Claude Code 工作階段

Your Claude Code sessions outlive the work. Who closes them?

AI 導讀

Omer Saleem 分享以每小時執行的 launchd 任務清理閒置 Claude Code 編輯器工作階段的方法,預設閒置門檻為 4 小時。腳本只處理超過門檻且沒有 shell 或 Claude 子進程的編輯器工作階段,不碰 launchd 服務、CLI、SDK 或記憶體工作階段。文章亦建議先用 --dry-run 核對保留或關閉原因,並以 UTC 比對時間戳。

正文

Omer Saleem

Originally published at omerbinsaleem.com by Omer Bin Saleem (Omer Saleem).

A usage report said most of my sessions had been open for more than eight hours. The fix was a small hourly job, and its first version had a timezone bug that would have closed nothing.

How to do it

  1. Read what /usage is telling you before guessing. Mine showed 94% of sessions asking for /clear and 65% open for 8 hours or more, with 10 sessions alive and 9 editor tabs between 15 and 17 hours old.
  2. Check the suspect before blaming it. I assumed Remote Control was keeping the tabs alive, but only 2 of the 5 old idle tabs had a bridge at all. The real cause was simpler: an editor tab keeps its process alive until the tab closes, and Claude Code never closes an idle session by itself.
  3. Make the reaper narrow on purpose. Mine closes only editor sessions that are idle past a threshold and have no shell or Claude child process. It never touches launchd services, CLI, SDK or memory sessions, and /resume brings any closed session back, so the worst case is a reopen.
  4. Give it a --dry-run flag that prints every session with its keep or close reason, plus an --hours flag for the threshold. Run the dry run until each reason reads right, and only then let it close anything.
  5. Compare timestamps in one timezone. The session file records the process start in UTC, while ps -o lstart prints local time. Run ps with TZ=UTC. My first version missed this and would never have closed a single session.
  6. Schedule it with launchd, once an hour with a 4 hour threshold. Log only the sessions it closed, and send errors to a separate file so the log stays readable.

Prompt to copy

Write a Python script that lists my Claude Code sessions from ~/.claude/sessions/*.json and closes only editor sessions that have been idle longer than --hours (default 4) and have no shell or claude child process. Add a --dry-run flag that prints every session with a keep or close reason. The session files record procStart in UTC, so compare against ps run with TZ=UTC. Never touch launchd services, CLI or SDK sessions. Log closed sessions to one file and errors to another. Then write a launchd plist that runs the script every hour.

I am Omer Bin Saleem, a frontend chapter lead who builds with AI every day. One practical AI hack a day at omerbinsaleem.com. LinkedIn: omer-bin-saleem · Instagram: @iomerbinsaleem.

Written with AI assistance, from my own work notes.

來源:DEV Community · dev.to