-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclaude_sessions.py
More file actions
executable file
·262 lines (212 loc) · 8.63 KB
/
Copy pathclaude_sessions.py
File metadata and controls
executable file
·262 lines (212 loc) · 8.63 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
#!/usr/bin/env python3
"""
Claude session navigator - lists all Claude Code sessions and opens
a new zellij pane in the selected project directory.
"""
import argparse
import json
import os
import subprocess as sp
import sys
from pathlib import Path
from typing import List, Optional
CLAUDE_PROJECTS_DIR = Path.home() / ".claude" / "projects"
CLAUDE_BUSINESS_PROJECTS_DIR = Path.home() / ".claude-business" / "projects"
def parse_session_jsonl(jsonl_path: Path) -> Optional[dict]:
"""Parse a session .jsonl file to extract session info."""
custom_title = ""
first_prompt = ""
project_path = ""
session_id = jsonl_path.stem
modified = ""
try:
with open(jsonl_path, "r") as f:
for line in f:
try:
entry = json.loads(line)
except json.JSONDecodeError:
continue
# Get custom title if present
if entry.get("type") == "custom-title":
custom_title = entry.get("customTitle", "")
# Get project path from user messages
if entry.get("type") == "user" and not project_path:
project_path = entry.get("cwd", "")
# Get first prompt from user messages
if entry.get("type") == "user" and not first_prompt:
msg = entry.get("message", {})
content = msg.get("content", [])
for item in content:
if isinstance(item, dict) and item.get("type") == "text":
first_prompt = item.get("text", "")[:60]
break
elif isinstance(item, str):
first_prompt = item[:60]
break
# Get modified time from file
modified = jsonl_path.stat().st_mtime
session_name = custom_title or first_prompt or session_id
if project_path and session_id:
return {
"sessionId": session_id,
"projectPath": project_path,
"sessionName": session_name,
"modified": modified,
}
except (IOError, OSError):
pass
return None
def get_sessions(projects_dir: Path = CLAUDE_PROJECTS_DIR) -> List[dict]:
"""Find and parse all sessions from index files and individual .jsonl files."""
sessions = []
indexed_sessions = set() # Track sessions found in index files
if not projects_dir.exists():
return sessions
for project_dir in projects_dir.iterdir():
if not project_dir.is_dir():
continue
index_file = project_dir / "sessions-index.json"
# Try to read from sessions-index.json first
if index_file.exists():
try:
with open(index_file, "r") as f:
data = json.load(f)
for entry in data.get("entries", []):
session_id = entry.get("sessionId", "")
project_path = entry.get("projectPath", "")
custom_title = entry.get("customTitle", "")
summary = entry.get("summary", "")
first_prompt = entry.get("firstPrompt", "")[:60]
modified = entry.get("modified", "")
# Use customTitle, then summary, then firstPrompt as session name
session_name = custom_title or summary or first_prompt
if project_path and session_id:
indexed_sessions.add(session_id)
sessions.append({
"sessionId": session_id,
"projectPath": project_path,
"sessionName": session_name,
"modified": modified,
})
except (json.JSONDecodeError, IOError):
pass
# Scan individual .jsonl files for sessions not in index
for jsonl_file in project_dir.glob("*.jsonl"):
session_id = jsonl_file.stem
# Skip subagent sessions and already indexed sessions
if session_id.startswith("agent-") or session_id in indexed_sessions:
continue
session = parse_session_jsonl(jsonl_file)
# Skip sessions with very short names (likely typos/tests)
if session and len(session.get("sessionName", "")) >= 3:
sessions.append(session)
# Sort by modified date (most recent first)
sessions.sort(key=lambda x: x.get("modified", 0) if isinstance(x.get("modified"), (int, float)) else 0, reverse=True)
return sessions
def gum_select(items: List[str], header: str = "Claude Sessions") -> Optional[str]:
"""Run gum filter with the given items and return the selected line."""
if not items:
print("No Claude sessions found")
return None
input_text = "\n".join(items)
proc = sp.Popen(
["gum", "filter", "--header", header],
stdin=sp.PIPE,
stdout=sp.PIPE,
text=True
)
output, _ = proc.communicate(input=input_text)
if proc.returncode != 0:
return None
return output.strip()
def resume_session(cwd: str, session_id: str, business: bool = False) -> None:
"""Change to project directory and exec into claude session.
When ``business`` is True, the spawned claude process inherits
``CLAUDE_CONFIG_DIR=$HOME/.claude-business`` so it resolves credentials,
projects, and memory from the isolated business config dir instead of
the personal one.
"""
os.chdir(cwd)
if business:
os.environ["CLAUDE_CONFIG_DIR"] = str(Path.home() / ".claude-business")
os.execvp("claude", ["claude", "--resume", session_id, "--dangerously-skip-permissions"])
def launch_sidecar(cwd: str) -> None:
"""Change to project directory and exec into sidecar."""
os.chdir(cwd)
os.execvp("sidecar", ["sidecar", "-project", cwd])
def launch_cmdr(cwd: str) -> None:
"""Change to project directory and exec into cmdr dashboard."""
import shutil
cmdr_path = shutil.which("cmdr")
if cmdr_path is None:
print(
"cmdr not found in PATH. Install with: "
"cd ~/Programs/ai/computeCommander && make install",
file=sys.stderr,
)
sys.exit(1)
os.chdir(cwd)
os.execvp("cmdr", ["cmdr", "dashboard"])
def main() -> None:
parser = argparse.ArgumentParser(description="Claude session navigator")
parser.add_argument(
"--sidecar",
action="store_true",
help="Launch sidecar TUI in the selected session's project directory",
)
parser.add_argument(
"--cmdr",
action="store_true",
help="Launch cmdr dashboard in the selected session's project directory",
)
parser.add_argument(
"--business",
action="store_true",
help=(
"List sessions from ~/.claude-business/projects and resume the "
"selected session with CLAUDE_CONFIG_DIR=$HOME/.claude-business "
"set, isolating creds/projects/memory from the personal config."
),
)
args = parser.parse_args()
projects_dir = CLAUDE_BUSINESS_PROJECTS_DIR if args.business else CLAUDE_PROJECTS_DIR
sessions = get_sessions(projects_dir)
if not sessions:
print("No Claude sessions found")
sys.exit(1)
# Build mapping of display name -> session data
# Use index to handle duplicate names
session_map = {}
display_names = []
for i, s in enumerate(sessions):
name = s["sessionName"].replace("\n", " ")
# Add index suffix if name already exists
display_name = name
if name in session_map:
display_name = f"{name} ({i})"
session_map[display_name] = s
display_names.append(display_name)
# Run gum selection
header = "Claude Sessions (BUSINESS)" if args.business else "Claude Sessions"
selected = gum_select(display_names, header=header)
if not selected:
sys.exit(0)
# Look up session data
session = session_map.get(selected)
if not session:
print(f"Session not found: {selected}")
sys.exit(1)
project_path = session["projectPath"]
session_id = session["sessionId"]
if not os.path.isdir(project_path):
print(f"Directory not found: {project_path}")
sys.exit(1)
# Launch cmdr, sidecar, or resume claude session
if args.cmdr:
launch_cmdr(project_path)
elif args.sidecar:
launch_sidecar(project_path)
else:
resume_session(project_path, session_id, business=args.business)
if __name__ == "__main__":
main()