|
| 1 | +// Package clauderegistry reads Claude Code's on-disk live-session registry |
| 2 | +// at $CLAUDE_CONFIG_DIR/sessions/<pid>.json — one file per top-level |
| 3 | +// claude process, written at startup and mutated in place as state |
| 4 | +// changes. CCX uses it to detect which sessions are alive and which are |
| 5 | +// actively producing a turn. |
| 6 | +// |
| 7 | +// Only the fields ccx actually consumes are decoded below. The full |
| 8 | +// schema, lifecycle, and quirks (status values, name vs custom-title, |
| 9 | +// PID reuse, WSL leak) are documented in |
| 10 | +// docs/claude-code/live-session-registry.md. |
| 11 | +// |
| 12 | +// Diagnostic logging: set CCX_DEBUG=1 to surface registry errors to |
| 13 | +// /tmp/ccx-debug.log (falls back to stderr if that path isn't writable). |
| 14 | +// Without it, errors are swallowed silently so a transient registry |
| 15 | +// glitch never crashes ccx — the trade-off is that users have no way to |
| 16 | +// see why "live" suddenly went empty. |
| 17 | +package clauderegistry |
| 18 | + |
| 19 | +import ( |
| 20 | + "encoding/json" |
| 21 | + "errors" |
| 22 | + "io" |
| 23 | + "io/fs" |
| 24 | + "log" |
| 25 | + "os" |
| 26 | + "path/filepath" |
| 27 | + "strings" |
| 28 | + "syscall" |
| 29 | + "time" |
| 30 | +) |
| 31 | + |
| 32 | +// Field values we actually branch on. |
| 33 | +const ( |
| 34 | + statusBusy = "busy" // actively processing a turn |
| 35 | + kindInteractive = "interactive" // normal user session |
| 36 | +) |
| 37 | + |
| 38 | +// debugLog is wired in init below. Silent (io.Discard) unless CCX_DEBUG |
| 39 | +// is set, matching the convention in internal/tui/conversation.go. |
| 40 | +var debugLog *log.Logger |
| 41 | + |
| 42 | +func init() { |
| 43 | + if os.Getenv("CCX_DEBUG") == "" { |
| 44 | + debugLog = log.New(io.Discard, "", 0) |
| 45 | + return |
| 46 | + } |
| 47 | + f, err := os.OpenFile("/tmp/ccx-debug.log", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0o644) |
| 48 | + if err != nil { |
| 49 | + debugLog = log.New(os.Stderr, "clauderegistry: ", log.Ltime|log.Lmicroseconds) |
| 50 | + return |
| 51 | + } |
| 52 | + debugLog = log.New(f, "clauderegistry: ", log.Ltime|log.Lmicroseconds) |
| 53 | +} |
| 54 | + |
| 55 | +// LiveSession is the subset of a registry entry that ccx consumes. The |
| 56 | +// on-disk file has many more fields — see the docs. |
| 57 | +// |
| 58 | +// Status, in particular, may be absent on a file captured between |
| 59 | +// registration and the first REPL state update. Empty Status is treated |
| 60 | +// as "not responding". |
| 61 | +type LiveSession struct { |
| 62 | + PID int `json:"pid"` |
| 63 | + SessionID string `json:"sessionId"` |
| 64 | + CWD string `json:"cwd"` |
| 65 | + Status string `json:"status,omitempty"` |
| 66 | + Kind string `json:"kind,omitempty"` |
| 67 | +} |
| 68 | + |
| 69 | +// IsBusy reports whether the model is actively generating right now — |
| 70 | +// upstream Claude's StatusBusy. This is the "responding" signal CCX |
| 71 | +// surfaces via session.Session.IsResponding. |
| 72 | +// |
| 73 | +// StatusShell (REPL idle, background Bash still running) and |
| 74 | +// StatusWaiting (blocked on user input) deliberately don't count: a |
| 75 | +// session that left a long-running tool in the background would |
| 76 | +// otherwise show a permanent responding badge. |
| 77 | +func (s LiveSession) IsBusy() bool { |
| 78 | + return s.Status == statusBusy |
| 79 | +} |
| 80 | + |
| 81 | +// Dir returns the registry directory honoring $CLAUDE_CONFIG_DIR, falling |
| 82 | +// back to ~/.claude/sessions. |
| 83 | +func Dir() string { |
| 84 | + if d := os.Getenv("CLAUDE_CONFIG_DIR"); d != "" { |
| 85 | + return filepath.Join(d, "sessions") |
| 86 | + } |
| 87 | + home, err := os.UserHomeDir() |
| 88 | + if err != nil { |
| 89 | + return "" |
| 90 | + } |
| 91 | + return filepath.Join(home, ".claude", "sessions") |
| 92 | +} |
| 93 | + |
| 94 | +// Read returns every live interactive session known to Claude Code. |
| 95 | +// Ghost entries (process gone) are filtered out. A missing directory |
| 96 | +// returns (nil, nil) — older Claude Code versions don't write this |
| 97 | +// directory and we treat that as "registry unavailable". |
| 98 | +func Read() ([]LiveSession, error) { |
| 99 | + dir := Dir() |
| 100 | + if dir == "" { |
| 101 | + return nil, nil |
| 102 | + } |
| 103 | + entries, err := os.ReadDir(dir) |
| 104 | + if err != nil { |
| 105 | + if errors.Is(err, fs.ErrNotExist) { |
| 106 | + return nil, nil |
| 107 | + } |
| 108 | + debugLog.Printf("ReadDir(%s): %v", dir, err) |
| 109 | + return nil, err |
| 110 | + } |
| 111 | + out := make([]LiveSession, 0, len(entries)) |
| 112 | + for _, e := range entries { |
| 113 | + if e.IsDir() || !strings.HasSuffix(e.Name(), ".json") { |
| 114 | + continue |
| 115 | + } |
| 116 | + s, ok := readOne(filepath.Join(dir, e.Name())) |
| 117 | + if !ok { |
| 118 | + continue |
| 119 | + } |
| 120 | + // Kind defaults to "interactive" when unset. Skip bg/daemon |
| 121 | + // variants — those aren't user sessions. |
| 122 | + if s.Kind != "" && s.Kind != kindInteractive { |
| 123 | + continue |
| 124 | + } |
| 125 | + if !processAlive(s.PID) { |
| 126 | + continue |
| 127 | + } |
| 128 | + out = append(out, s) |
| 129 | + } |
| 130 | + return out, nil |
| 131 | +} |
| 132 | + |
| 133 | +// readOne parses a single registry file. Claude Code writes these files |
| 134 | +// without an atomic rename, so a concurrent read can land mid-write and |
| 135 | +// see truncated JSON. Retry a few times — the write window is microseconds. |
| 136 | +// |
| 137 | +// A file that fails every retry is skipped, not propagated as an error: |
| 138 | +// a single broken entry shouldn't blank out the whole live list. The |
| 139 | +// failure is logged when CCX_DEBUG is on. |
| 140 | +func readOne(path string) (LiveSession, bool) { |
| 141 | + var lastErr error |
| 142 | + for range 3 { |
| 143 | + data, err := os.ReadFile(path) |
| 144 | + if err != nil { |
| 145 | + if errors.Is(err, fs.ErrNotExist) { |
| 146 | + return LiveSession{}, false |
| 147 | + } |
| 148 | + lastErr = err |
| 149 | + time.Sleep(5 * time.Millisecond) |
| 150 | + continue |
| 151 | + } |
| 152 | + var s LiveSession |
| 153 | + if err := json.Unmarshal(data, &s); err == nil && s.SessionID != "" { |
| 154 | + return s, true |
| 155 | + } else if err != nil { |
| 156 | + lastErr = err |
| 157 | + } |
| 158 | + time.Sleep(5 * time.Millisecond) |
| 159 | + } |
| 160 | + if lastErr != nil { |
| 161 | + debugLog.Printf("readOne(%s) gave up after 3 retries: %v", path, lastErr) |
| 162 | + } |
| 163 | + return LiveSession{}, false |
| 164 | +} |
| 165 | + |
| 166 | +// processAlive returns true iff a process with this PID exists. kill(pid, 0) |
| 167 | +// sends no signal but performs the existence + permission check. |
| 168 | +func processAlive(pid int) bool { |
| 169 | + if pid <= 0 { |
| 170 | + return false |
| 171 | + } |
| 172 | + return syscall.Kill(pid, 0) == nil |
| 173 | +} |
| 174 | + |
| 175 | +// Cwds returns absolute project paths of every live registry entry, |
| 176 | +// deduplicated and preserving the registry's enumeration order. Used by |
| 177 | +// callers that only need "which project paths have a claude running" |
| 178 | +// and don't care about pane attribution. |
| 179 | +func Cwds() []string { |
| 180 | + live, err := Read() |
| 181 | + if err != nil || len(live) == 0 { |
| 182 | + return nil |
| 183 | + } |
| 184 | + seen := make(map[string]bool, len(live)) |
| 185 | + paths := make([]string, 0, len(live)) |
| 186 | + for _, l := range live { |
| 187 | + abs, _ := filepath.Abs(l.CWD) |
| 188 | + if abs == "" { |
| 189 | + abs = l.CWD |
| 190 | + } |
| 191 | + if abs == "" || seen[abs] { |
| 192 | + continue |
| 193 | + } |
| 194 | + seen[abs] = true |
| 195 | + paths = append(paths, abs) |
| 196 | + } |
| 197 | + return paths |
| 198 | +} |
| 199 | + |
| 200 | +// CwdSet is the set form of Cwds. |
| 201 | +func CwdSet() map[string]bool { |
| 202 | + paths := Cwds() |
| 203 | + out := make(map[string]bool, len(paths)) |
| 204 | + for _, p := range paths { |
| 205 | + out[p] = true |
| 206 | + } |
| 207 | + return out |
| 208 | +} |
0 commit comments