-
Notifications
You must be signed in to change notification settings - Fork 154
Expand file tree
/
Copy path__init__.py
More file actions
1286 lines (1115 loc) · 51.7 KB
/
__init__.py
File metadata and controls
1286 lines (1115 loc) · 51.7 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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Convert Claude Code session JSON to a clean mobile-friendly HTML page with pagination."""
import json
import html
import os
import platform
import re
import shutil
import subprocess
import tempfile
import webbrowser
from pathlib import Path
import click
from click_default_group import DefaultGroup
import httpx
from jinja2 import Environment, PackageLoader
import markdown
import questionary
# Set up Jinja2 environment
_jinja_env = Environment(
loader=PackageLoader("claude_code_publish", "templates"),
autoescape=True,
)
# Load macros template and expose macros
_macros_template = _jinja_env.get_template("macros.html")
_macros = _macros_template.module
def get_template(name):
"""Get a Jinja2 template by name."""
return _jinja_env.get_template(name)
# Regex to match git commit output: [branch hash] message
COMMIT_PATTERN = re.compile(r"\[[\w\-/]+ ([a-f0-9]{7,})\] (.+?)(?:\n|$)")
# Regex to detect GitHub repo from git push output (e.g., github.com/owner/repo/pull/new/branch)
GITHUB_REPO_PATTERN = re.compile(
r"github\.com/([a-zA-Z0-9_-]+/[a-zA-Z0-9_-]+)/pull/new/"
)
PROMPTS_PER_PAGE = 5
LONG_TEXT_THRESHOLD = (
300 # Characters - text blocks longer than this are shown in index
)
# Module-level variable for GitHub repo (set by generate_html)
_github_repo = None
# API constants
API_BASE_URL = "https://api.anthropic.com/v1"
ANTHROPIC_VERSION = "2023-06-01"
class CredentialsError(Exception):
"""Raised when credentials cannot be obtained."""
pass
def get_access_token_from_keychain():
"""Get access token from macOS keychain.
Returns the access token or None if not found.
Raises CredentialsError with helpful message on failure.
"""
if platform.system() != "Darwin":
return None
try:
result = subprocess.run(
[
"security",
"find-generic-password",
"-a",
os.environ.get("USER", ""),
"-s",
"Claude Code-credentials",
"-w",
],
capture_output=True,
text=True,
)
if result.returncode != 0:
return None
# Parse the JSON to get the access token
creds = json.loads(result.stdout.strip())
return creds.get("claudeAiOauth", {}).get("accessToken")
except (json.JSONDecodeError, subprocess.SubprocessError):
return None
def get_org_uuid_from_config():
"""Get organization UUID from ~/.claude.json.
Returns the organization UUID or None if not found.
"""
config_path = Path.home() / ".claude.json"
if not config_path.exists():
return None
try:
with open(config_path) as f:
config = json.load(f)
return config.get("oauthAccount", {}).get("organizationUuid")
except (json.JSONDecodeError, IOError):
return None
def get_api_headers(token, org_uuid):
"""Build API request headers."""
return {
"Authorization": f"Bearer {token}",
"anthropic-version": ANTHROPIC_VERSION,
"Content-Type": "application/json",
"x-organization-uuid": org_uuid,
}
def fetch_sessions(token, org_uuid):
"""Fetch list of sessions from the API.
Returns the sessions data as a dict.
Raises httpx.HTTPError on network/API errors.
"""
headers = get_api_headers(token, org_uuid)
response = httpx.get(f"{API_BASE_URL}/sessions", headers=headers, timeout=30.0)
response.raise_for_status()
return response.json()
def fetch_session(token, org_uuid, session_id):
"""Fetch a specific session from the API.
Returns the session data as a dict.
Raises httpx.HTTPError on network/API errors.
"""
headers = get_api_headers(token, org_uuid)
response = httpx.get(
f"{API_BASE_URL}/session_ingress/session/{session_id}",
headers=headers,
timeout=60.0,
)
response.raise_for_status()
return response.json()
def detect_github_repo(loglines):
"""
Detect GitHub repo from git push output in tool results.
Looks for patterns like:
- github.com/owner/repo/pull/new/branch (from git push messages)
Returns the first detected repo (owner/name) or None.
"""
for entry in loglines:
message = entry.get("message", {})
content = message.get("content", [])
if not isinstance(content, list):
continue
for block in content:
if not isinstance(block, dict):
continue
if block.get("type") == "tool_result":
result_content = block.get("content", "")
if isinstance(result_content, str):
match = GITHUB_REPO_PATTERN.search(result_content)
if match:
return match.group(1)
return None
def format_json(obj):
try:
if isinstance(obj, str):
obj = json.loads(obj)
formatted = json.dumps(obj, indent=2, ensure_ascii=False)
return f'<pre class="json">{html.escape(formatted)}</pre>'
except (json.JSONDecodeError, TypeError):
return f"<pre>{html.escape(str(obj))}</pre>"
def render_markdown_text(text):
if not text:
return ""
return markdown.markdown(text, extensions=["fenced_code", "tables"])
def is_json_like(text):
if not text or not isinstance(text, str):
return False
text = text.strip()
return (text.startswith("{") and text.endswith("}")) or (
text.startswith("[") and text.endswith("]")
)
def render_todo_write(tool_input, tool_id):
todos = tool_input.get("todos", [])
if not todos:
return ""
return _macros.todo_list(todos, tool_id)
def render_write_tool(tool_input, tool_id):
"""Render Write tool calls with file path header and content preview."""
file_path = tool_input.get("file_path", "Unknown file")
content = tool_input.get("content", "")
return _macros.write_tool(file_path, content, tool_id)
def render_edit_tool(tool_input, tool_id):
"""Render Edit tool calls with diff-like old/new display."""
file_path = tool_input.get("file_path", "Unknown file")
old_string = tool_input.get("old_string", "")
new_string = tool_input.get("new_string", "")
replace_all = tool_input.get("replace_all", False)
return _macros.edit_tool(file_path, old_string, new_string, replace_all, tool_id)
def render_bash_tool(tool_input, tool_id):
"""Render Bash tool calls with command as plain text."""
command = tool_input.get("command", "")
description = tool_input.get("description", "")
return _macros.bash_tool(command, description, tool_id)
def render_content_block(block):
if not isinstance(block, dict):
return f"<p>{html.escape(str(block))}</p>"
block_type = block.get("type", "")
if block_type == "thinking":
content_html = render_markdown_text(block.get("thinking", ""))
return _macros.thinking(content_html)
elif block_type == "text":
content_html = render_markdown_text(block.get("text", ""))
return _macros.assistant_text(content_html)
elif block_type == "tool_use":
tool_name = block.get("name", "Unknown tool")
tool_input = block.get("input", {})
tool_id = block.get("id", "")
if tool_name == "TodoWrite":
return render_todo_write(tool_input, tool_id)
if tool_name == "Write":
return render_write_tool(tool_input, tool_id)
if tool_name == "Edit":
return render_edit_tool(tool_input, tool_id)
if tool_name == "Bash":
return render_bash_tool(tool_input, tool_id)
description = tool_input.get("description", "")
display_input = {k: v for k, v in tool_input.items() if k != "description"}
input_json = json.dumps(display_input, indent=2, ensure_ascii=False)
return _macros.tool_use(tool_name, description, input_json, tool_id)
elif block_type == "tool_result":
content = block.get("content", "")
is_error = block.get("is_error", False)
# Check for git commits and render with styled cards
if isinstance(content, str):
commits_found = list(COMMIT_PATTERN.finditer(content))
if commits_found:
# Build commit cards + remaining content
parts = []
last_end = 0
for match in commits_found:
# Add any content before this commit
before = content[last_end : match.start()].strip()
if before:
parts.append(f"<pre>{html.escape(before)}</pre>")
commit_hash = match.group(1)
commit_msg = match.group(2)
parts.append(
_macros.commit_card(commit_hash, commit_msg, _github_repo)
)
last_end = match.end()
# Add any remaining content after last commit
after = content[last_end:].strip()
if after:
parts.append(f"<pre>{html.escape(after)}</pre>")
content_html = "".join(parts)
else:
content_html = f"<pre>{html.escape(content)}</pre>"
elif isinstance(content, list) or is_json_like(content):
content_html = format_json(content)
else:
content_html = format_json(content)
return _macros.tool_result(content_html, is_error)
else:
return format_json(block)
def render_user_message_content(message_data):
content = message_data.get("content", "")
if isinstance(content, str):
if is_json_like(content):
return _macros.user_content(format_json(content))
return _macros.user_content(render_markdown_text(content))
elif isinstance(content, list):
return "".join(render_content_block(block) for block in content)
return f"<p>{html.escape(str(content))}</p>"
def render_assistant_message(message_data):
content = message_data.get("content", [])
if not isinstance(content, list):
return f"<p>{html.escape(str(content))}</p>"
return "".join(render_content_block(block) for block in content)
def make_msg_id(timestamp):
return f"msg-{timestamp.replace(':', '-').replace('.', '-')}"
def analyze_conversation(messages):
"""Analyze messages in a conversation to extract stats and long texts."""
tool_counts = {} # tool_name -> count
long_texts = []
commits = [] # list of (hash, message, timestamp)
for log_type, message_json, timestamp in messages:
if not message_json:
continue
try:
message_data = json.loads(message_json)
except json.JSONDecodeError:
continue
content = message_data.get("content", [])
if not isinstance(content, list):
continue
for block in content:
if not isinstance(block, dict):
continue
block_type = block.get("type", "")
if block_type == "tool_use":
tool_name = block.get("name", "Unknown")
tool_counts[tool_name] = tool_counts.get(tool_name, 0) + 1
elif block_type == "tool_result":
# Check for git commit output
result_content = block.get("content", "")
if isinstance(result_content, str):
for match in COMMIT_PATTERN.finditer(result_content):
commits.append((match.group(1), match.group(2), timestamp))
elif block_type == "text":
text = block.get("text", "")
if len(text) >= LONG_TEXT_THRESHOLD:
long_texts.append(text)
return {
"tool_counts": tool_counts,
"long_texts": long_texts,
"commits": commits,
}
def format_tool_stats(tool_counts):
"""Format tool counts into a concise summary string."""
if not tool_counts:
return ""
# Abbreviate common tool names
abbrev = {
"Bash": "bash",
"Read": "read",
"Write": "write",
"Edit": "edit",
"Glob": "glob",
"Grep": "grep",
"Task": "task",
"TodoWrite": "todo",
"WebFetch": "fetch",
"WebSearch": "search",
}
parts = []
for name, count in sorted(tool_counts.items(), key=lambda x: -x[1]):
short_name = abbrev.get(name, name.lower())
parts.append(f"{count} {short_name}")
return " · ".join(parts)
def is_tool_result_message(message_data):
"""Check if a message contains only tool_result blocks."""
content = message_data.get("content", [])
if not isinstance(content, list):
return False
if not content:
return False
return all(
isinstance(block, dict) and block.get("type") == "tool_result"
for block in content
)
def render_message(log_type, message_json, timestamp):
if not message_json:
return ""
try:
message_data = json.loads(message_json)
except json.JSONDecodeError:
return ""
if log_type == "user":
content_html = render_user_message_content(message_data)
# Check if this is a tool result message
if is_tool_result_message(message_data):
role_class, role_label = "tool-reply", "Tool reply"
else:
role_class, role_label = "user", "User"
elif log_type == "assistant":
content_html = render_assistant_message(message_data)
role_class, role_label = "assistant", "Assistant"
else:
return ""
if not content_html.strip():
return ""
msg_id = make_msg_id(timestamp)
return _macros.message(role_class, role_label, msg_id, timestamp, content_html)
CSS = """
:root { --bg-color: #f5f5f5; --card-bg: #ffffff; --user-bg: #e3f2fd; --user-border: #1976d2; --assistant-bg: #f5f5f5; --assistant-border: #9e9e9e; --thinking-bg: #fff8e1; --thinking-border: #ffc107; --thinking-text: #666; --tool-bg: #f3e5f5; --tool-border: #9c27b0; --tool-result-bg: #e8f5e9; --tool-error-bg: #ffebee; --text-color: #212121; --text-muted: #757575; --code-bg: #263238; --code-text: #aed581; }
* { box-sizing: border-box; }
body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; background: var(--bg-color); color: var(--text-color); margin: 0; padding: 16px; line-height: 1.6; }
.container { max-width: 800px; margin: 0 auto; }
h1 { font-size: 1.5rem; margin-bottom: 24px; padding-bottom: 8px; border-bottom: 2px solid var(--user-border); }
.message { margin-bottom: 16px; border-radius: 12px; overflow: hidden; box-shadow: 0 1px 3px rgba(0,0,0,0.1); }
.message.user { background: var(--user-bg); border-left: 4px solid var(--user-border); }
.message.assistant { background: var(--card-bg); border-left: 4px solid var(--assistant-border); }
.message.tool-reply { background: #fff8e1; border-left: 4px solid #ff9800; }
.tool-reply .role-label { color: #e65100; }
.tool-reply .tool-result { background: transparent; padding: 0; margin: 0; }
.tool-reply .tool-result .truncatable.truncated::after { background: linear-gradient(to bottom, transparent, #fff8e1); }
.message-header { display: flex; justify-content: space-between; align-items: center; padding: 8px 16px; background: rgba(0,0,0,0.03); font-size: 0.85rem; }
.role-label { font-weight: 600; text-transform: uppercase; letter-spacing: 0.5px; }
.user .role-label { color: var(--user-border); }
time { color: var(--text-muted); font-size: 0.8rem; }
.timestamp-link { color: inherit; text-decoration: none; }
.timestamp-link:hover { text-decoration: underline; }
.message:target { animation: highlight 2s ease-out; }
@keyframes highlight { 0% { background-color: rgba(25, 118, 210, 0.2); } 100% { background-color: transparent; } }
.message-content { padding: 16px; }
.message-content p { margin: 0 0 12px 0; }
.message-content p:last-child { margin-bottom: 0; }
.thinking { background: var(--thinking-bg); border: 1px solid var(--thinking-border); border-radius: 8px; padding: 12px; margin: 12px 0; font-size: 0.9rem; color: var(--thinking-text); }
.thinking-label { font-size: 0.75rem; font-weight: 600; text-transform: uppercase; color: #f57c00; margin-bottom: 8px; }
.thinking p { margin: 8px 0; }
.assistant-text { margin: 8px 0; }
.tool-use { background: var(--tool-bg); border: 1px solid var(--tool-border); border-radius: 8px; padding: 12px; margin: 12px 0; }
.tool-header { font-weight: 600; color: var(--tool-border); margin-bottom: 8px; display: flex; align-items: center; gap: 8px; }
.tool-icon { font-size: 1.1rem; }
.tool-description { font-size: 0.9rem; color: var(--text-muted); margin-bottom: 8px; font-style: italic; }
.tool-result { background: var(--tool-result-bg); border-radius: 8px; padding: 12px; margin: 12px 0; }
.tool-result.tool-error { background: var(--tool-error-bg); }
.file-tool { border-radius: 8px; padding: 12px; margin: 12px 0; }
.write-tool { background: linear-gradient(135deg, #e3f2fd 0%, #e8f5e9 100%); border: 1px solid #4caf50; }
.edit-tool { background: linear-gradient(135deg, #fff3e0 0%, #fce4ec 100%); border: 1px solid #ff9800; }
.file-tool-header { font-weight: 600; margin-bottom: 4px; display: flex; align-items: center; gap: 8px; font-size: 0.95rem; }
.write-header { color: #2e7d32; }
.edit-header { color: #e65100; }
.file-tool-icon { font-size: 1rem; }
.file-tool-path { font-family: monospace; background: rgba(0,0,0,0.08); padding: 2px 8px; border-radius: 4px; }
.file-tool-fullpath { font-family: monospace; font-size: 0.8rem; color: var(--text-muted); margin-bottom: 8px; word-break: break-all; }
.file-content { margin: 0; }
.edit-section { display: flex; margin: 4px 0; border-radius: 4px; overflow: hidden; }
.edit-label { padding: 8px 12px; font-weight: bold; font-family: monospace; display: flex; align-items: flex-start; }
.edit-old { background: #fce4ec; }
.edit-old .edit-label { color: #b71c1c; background: #f8bbd9; }
.edit-old .edit-content { color: #880e4f; }
.edit-new { background: #e8f5e9; }
.edit-new .edit-label { color: #1b5e20; background: #a5d6a7; }
.edit-new .edit-content { color: #1b5e20; }
.edit-content { margin: 0; flex: 1; background: transparent; font-size: 0.85rem; }
.edit-replace-all { font-size: 0.75rem; font-weight: normal; color: var(--text-muted); }
.write-tool .truncatable.truncated::after { background: linear-gradient(to bottom, transparent, #e6f4ea); }
.edit-tool .truncatable.truncated::after { background: linear-gradient(to bottom, transparent, #fff0e5); }
.todo-list { background: linear-gradient(135deg, #e8f5e9 0%, #f1f8e9 100%); border: 1px solid #81c784; border-radius: 8px; padding: 12px; margin: 12px 0; }
.todo-header { font-weight: 600; color: #2e7d32; margin-bottom: 10px; display: flex; align-items: center; gap: 8px; font-size: 0.95rem; }
.todo-items { list-style: none; margin: 0; padding: 0; }
.todo-item { display: flex; align-items: flex-start; gap: 10px; padding: 6px 0; border-bottom: 1px solid rgba(0,0,0,0.06); font-size: 0.9rem; }
.todo-item:last-child { border-bottom: none; }
.todo-icon { flex-shrink: 0; width: 20px; height: 20px; display: flex; align-items: center; justify-content: center; font-weight: bold; border-radius: 50%; }
.todo-completed .todo-icon { color: #2e7d32; background: rgba(46, 125, 50, 0.15); }
.todo-completed .todo-content { color: #558b2f; text-decoration: line-through; }
.todo-in-progress .todo-icon { color: #f57c00; background: rgba(245, 124, 0, 0.15); }
.todo-in-progress .todo-content { color: #e65100; font-weight: 500; }
.todo-pending .todo-icon { color: #757575; background: rgba(0,0,0,0.05); }
.todo-pending .todo-content { color: #616161; }
pre { background: var(--code-bg); color: var(--code-text); padding: 12px; border-radius: 6px; overflow-x: auto; font-size: 0.85rem; line-height: 1.5; margin: 8px 0; white-space: pre-wrap; word-wrap: break-word; }
pre.json { color: #e0e0e0; }
code { background: rgba(0,0,0,0.08); padding: 2px 6px; border-radius: 4px; font-size: 0.9em; }
pre code { background: none; padding: 0; }
.user-content { margin: 0; }
.truncatable { position: relative; }
.truncatable.truncated .truncatable-content { max-height: 200px; overflow: hidden; }
.truncatable.truncated::after { content: ''; position: absolute; bottom: 32px; left: 0; right: 0; height: 60px; background: linear-gradient(to bottom, transparent, var(--card-bg)); pointer-events: none; }
.message.user .truncatable.truncated::after { background: linear-gradient(to bottom, transparent, var(--user-bg)); }
.message.tool-reply .truncatable.truncated::after { background: linear-gradient(to bottom, transparent, #fff8e1); }
.tool-use .truncatable.truncated::after { background: linear-gradient(to bottom, transparent, var(--tool-bg)); }
.tool-result .truncatable.truncated::after { background: linear-gradient(to bottom, transparent, var(--tool-result-bg)); }
.expand-btn { display: none; width: 100%; padding: 8px 16px; margin-top: 4px; background: rgba(0,0,0,0.05); border: 1px solid rgba(0,0,0,0.1); border-radius: 6px; cursor: pointer; font-size: 0.85rem; color: var(--text-muted); }
.expand-btn:hover { background: rgba(0,0,0,0.1); }
.truncatable.truncated .expand-btn, .truncatable.expanded .expand-btn { display: block; }
.pagination { display: flex; justify-content: center; gap: 8px; margin: 24px 0; flex-wrap: wrap; }
.pagination a, .pagination span { padding: 5px 10px; border-radius: 6px; text-decoration: none; font-size: 0.85rem; }
.pagination a { background: var(--card-bg); color: var(--user-border); border: 1px solid var(--user-border); }
.pagination a:hover { background: var(--user-bg); }
.pagination .current { background: var(--user-border); color: white; }
.pagination .disabled { color: var(--text-muted); border: 1px solid #ddd; }
.pagination .index-link { background: var(--user-border); color: white; }
details.continuation { margin-bottom: 16px; }
details.continuation summary { cursor: pointer; padding: 12px 16px; background: var(--user-bg); border-left: 4px solid var(--user-border); border-radius: 12px; font-weight: 500; color: var(--text-muted); }
details.continuation summary:hover { background: rgba(25, 118, 210, 0.15); }
details.continuation[open] summary { border-radius: 12px 12px 0 0; margin-bottom: 0; }
.index-item { margin-bottom: 16px; border-radius: 12px; overflow: hidden; box-shadow: 0 1px 3px rgba(0,0,0,0.1); background: var(--user-bg); border-left: 4px solid var(--user-border); }
.index-item a { display: block; text-decoration: none; color: inherit; }
.index-item a:hover { background: rgba(25, 118, 210, 0.1); }
.index-item-header { display: flex; justify-content: space-between; align-items: center; padding: 8px 16px; background: rgba(0,0,0,0.03); font-size: 0.85rem; }
.index-item-number { font-weight: 600; color: var(--user-border); }
.index-item-content { padding: 16px; }
.index-item-stats { padding: 8px 16px 12px 32px; font-size: 0.85rem; color: var(--text-muted); border-top: 1px solid rgba(0,0,0,0.06); }
.index-item-commit { margin-top: 6px; padding: 4px 8px; background: #fff3e0; border-radius: 4px; font-size: 0.85rem; color: #e65100; }
.index-item-commit code { background: rgba(0,0,0,0.08); padding: 1px 4px; border-radius: 3px; font-size: 0.8rem; margin-right: 6px; }
.commit-card { margin: 8px 0; padding: 10px 14px; background: #fff3e0; border-left: 4px solid #ff9800; border-radius: 6px; }
.commit-card a { text-decoration: none; color: #5d4037; display: block; }
.commit-card a:hover { color: #e65100; }
.commit-card-hash { font-family: monospace; color: #e65100; font-weight: 600; margin-right: 8px; }
.index-commit { margin-bottom: 12px; padding: 10px 16px; background: #fff3e0; border-left: 4px solid #ff9800; border-radius: 8px; box-shadow: 0 1px 2px rgba(0,0,0,0.05); }
.index-commit a { display: block; text-decoration: none; color: inherit; }
.index-commit a:hover { background: rgba(255, 152, 0, 0.1); margin: -10px -16px; padding: 10px 16px; border-radius: 8px; }
.index-commit-header { display: flex; justify-content: space-between; align-items: center; font-size: 0.85rem; margin-bottom: 4px; }
.index-commit-hash { font-family: monospace; color: #e65100; font-weight: 600; }
.index-commit-msg { color: #5d4037; }
.index-item-long-text { margin-top: 8px; padding: 12px; background: var(--card-bg); border-radius: 8px; border-left: 3px solid var(--assistant-border); }
.index-item-long-text .truncatable.truncated::after { background: linear-gradient(to bottom, transparent, var(--card-bg)); }
.index-item-long-text-content { color: var(--text-color); }
@media (max-width: 600px) { body { padding: 8px; } .message, .index-item { border-radius: 8px; } .message-content, .index-item-content { padding: 12px; } pre { font-size: 0.8rem; padding: 8px; } }
"""
JS = """
document.querySelectorAll('time[data-timestamp]').forEach(function(el) {
const timestamp = el.getAttribute('data-timestamp');
const date = new Date(timestamp);
const now = new Date();
const isToday = date.toDateString() === now.toDateString();
const timeStr = date.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' });
if (isToday) { el.textContent = timeStr; }
else { el.textContent = date.toLocaleDateString(undefined, { month: 'short', day: 'numeric' }) + ' ' + timeStr; }
});
document.querySelectorAll('pre.json').forEach(function(el) {
let text = el.textContent;
text = text.replace(/"([^"]+)":/g, '<span style="color: #ce93d8">"$1"</span>:');
text = text.replace(/: "([^"]*)"/g, ': <span style="color: #81d4fa">"$1"</span>');
text = text.replace(/: (\\d+)/g, ': <span style="color: #ffcc80">$1</span>');
text = text.replace(/: (true|false|null)/g, ': <span style="color: #f48fb1">$1</span>');
el.innerHTML = text;
});
document.querySelectorAll('.truncatable').forEach(function(wrapper) {
const content = wrapper.querySelector('.truncatable-content');
const btn = wrapper.querySelector('.expand-btn');
if (content.scrollHeight > 250) {
wrapper.classList.add('truncated');
btn.addEventListener('click', function() {
if (wrapper.classList.contains('truncated')) { wrapper.classList.remove('truncated'); wrapper.classList.add('expanded'); btn.textContent = 'Show less'; }
else { wrapper.classList.remove('expanded'); wrapper.classList.add('truncated'); btn.textContent = 'Show more'; }
});
}
});
"""
# JavaScript to fix relative URLs when served via gistpreview.github.io
GIST_PREVIEW_JS = r"""
(function() {
if (window.location.hostname !== 'gistpreview.github.io') return;
// URL format: https://gistpreview.github.io/?GIST_ID/filename.html
var match = window.location.search.match(/^\?([^/]+)/);
if (!match) return;
var gistId = match[1];
document.querySelectorAll('a[href]').forEach(function(link) {
var href = link.getAttribute('href');
// Skip external links and anchors
if (href.startsWith('http') || href.startsWith('#') || href.startsWith('//')) return;
// Handle anchor in relative URL (e.g., page-001.html#msg-123)
var parts = href.split('#');
var filename = parts[0];
var anchor = parts.length > 1 ? '#' + parts[1] : '';
link.setAttribute('href', '?' + gistId + '/' + filename + anchor);
});
})();
"""
def inject_gist_preview_js(output_dir):
"""Inject gist preview JavaScript into all HTML files in the output directory."""
output_dir = Path(output_dir)
for html_file in output_dir.glob("*.html"):
content = html_file.read_text()
# Insert the gist preview JS before the closing </body> tag
if "</body>" in content:
content = content.replace(
"</body>", f"<script>{GIST_PREVIEW_JS}</script>\n</body>"
)
html_file.write_text(content)
def create_gist(output_dir, public=False):
"""Create a GitHub gist from the HTML files in output_dir.
Returns the gist ID on success, or raises click.ClickException on failure.
"""
output_dir = Path(output_dir)
html_files = list(output_dir.glob("*.html"))
if not html_files:
raise click.ClickException("No HTML files found to upload to gist.")
# Build the gh gist create command
# gh gist create file1 file2 ... --public/--private
cmd = ["gh", "gist", "create"]
cmd.extend(str(f) for f in sorted(html_files))
if public:
cmd.append("--public")
try:
result = subprocess.run(
cmd,
capture_output=True,
text=True,
check=True,
)
# Output is the gist URL, e.g., https://gist.github.com/username/GIST_ID
gist_url = result.stdout.strip()
# Extract gist ID from URL
gist_id = gist_url.rstrip("/").split("/")[-1]
return gist_id, gist_url
except subprocess.CalledProcessError as e:
error_msg = e.stderr.strip() if e.stderr else str(e)
raise click.ClickException(f"Failed to create gist: {error_msg}")
except FileNotFoundError:
raise click.ClickException(
"gh CLI not found. Install it from https://cli.github.com/ and run 'gh auth login'."
)
def generate_pagination_html(current_page, total_pages):
return _macros.pagination(current_page, total_pages)
def generate_index_pagination_html(total_pages):
"""Generate pagination for index page where Index is current (first page)."""
return _macros.index_pagination(total_pages)
def generate_html(json_path, output_dir, github_repo=None):
output_dir = Path(output_dir)
output_dir.mkdir(exist_ok=True)
# Load JSON file
with open(json_path, "r") as f:
data = json.load(f)
loglines = data.get("loglines", [])
# Auto-detect GitHub repo if not provided
if github_repo is None:
github_repo = detect_github_repo(loglines)
if github_repo:
print(f"Auto-detected GitHub repo: {github_repo}")
else:
print(
"Warning: Could not auto-detect GitHub repo. Commit links will be disabled."
)
# Set module-level variable for render functions
global _github_repo
_github_repo = github_repo
conversations = []
current_conv = None
for entry in loglines:
log_type = entry.get("type")
timestamp = entry.get("timestamp", "")
is_compact_summary = entry.get("isCompactSummary", False)
message_data = entry.get("message", {})
if not message_data:
continue
# Convert message dict to JSON string for compatibility with existing render functions
message_json = json.dumps(message_data)
is_user_prompt = False
user_text = None
if log_type == "user":
content = message_data.get("content", "")
if isinstance(content, str) and content.strip():
is_user_prompt = True
user_text = content
if is_user_prompt:
if current_conv:
conversations.append(current_conv)
current_conv = {
"user_text": user_text,
"timestamp": timestamp,
"messages": [(log_type, message_json, timestamp)],
"is_continuation": bool(is_compact_summary),
}
elif current_conv:
current_conv["messages"].append((log_type, message_json, timestamp))
if current_conv:
conversations.append(current_conv)
total_convs = len(conversations)
total_pages = (total_convs + PROMPTS_PER_PAGE - 1) // PROMPTS_PER_PAGE
for page_num in range(1, total_pages + 1):
start_idx = (page_num - 1) * PROMPTS_PER_PAGE
end_idx = min(start_idx + PROMPTS_PER_PAGE, total_convs)
page_convs = conversations[start_idx:end_idx]
messages_html = []
for conv in page_convs:
is_first = True
for log_type, message_json, timestamp in conv["messages"]:
msg_html = render_message(log_type, message_json, timestamp)
if msg_html:
# Wrap continuation summaries in collapsed details
if is_first and conv.get("is_continuation"):
msg_html = f'<details class="continuation"><summary>Session continuation summary</summary>{msg_html}</details>'
messages_html.append(msg_html)
is_first = False
pagination_html = generate_pagination_html(page_num, total_pages)
page_template = get_template("page.html")
page_content = page_template.render(
css=CSS,
js=JS,
page_num=page_num,
total_pages=total_pages,
pagination_html=pagination_html,
messages_html="".join(messages_html),
)
(output_dir / f"page-{page_num:03d}.html").write_text(page_content)
print(f"Generated page-{page_num:03d}.html")
# Calculate overall stats and collect all commits for timeline
total_tool_counts = {}
total_messages = 0
all_commits = [] # (timestamp, hash, message, page_num, conv_index)
for i, conv in enumerate(conversations):
total_messages += len(conv["messages"])
stats = analyze_conversation(conv["messages"])
for tool, count in stats["tool_counts"].items():
total_tool_counts[tool] = total_tool_counts.get(tool, 0) + count
page_num = (i // PROMPTS_PER_PAGE) + 1
for commit_hash, commit_msg, commit_ts in stats["commits"]:
all_commits.append((commit_ts, commit_hash, commit_msg, page_num, i))
total_tool_calls = sum(total_tool_counts.values())
total_commits = len(all_commits)
# Build timeline items: prompts and commits merged by timestamp
timeline_items = []
# Add prompts
prompt_num = 0
for i, conv in enumerate(conversations):
if conv.get("is_continuation"):
continue
if conv["user_text"].startswith("Stop hook feedback:"):
continue
prompt_num += 1
page_num = (i // PROMPTS_PER_PAGE) + 1
msg_id = make_msg_id(conv["timestamp"])
link = f"page-{page_num:03d}.html#{msg_id}"
rendered_content = render_markdown_text(conv["user_text"])
# Collect all messages including from subsequent continuation conversations
# This ensures long_texts from continuations appear with the original prompt
all_messages = list(conv["messages"])
for j in range(i + 1, len(conversations)):
if not conversations[j].get("is_continuation"):
break
all_messages.extend(conversations[j]["messages"])
# Analyze conversation for stats (excluding commits from inline display now)
stats = analyze_conversation(all_messages)
tool_stats_str = format_tool_stats(stats["tool_counts"])
long_texts_html = ""
for lt in stats["long_texts"]:
rendered_lt = render_markdown_text(lt)
long_texts_html += _macros.index_long_text(rendered_lt)
stats_html = _macros.index_stats(tool_stats_str, long_texts_html)
item_html = _macros.index_item(
prompt_num, link, conv["timestamp"], rendered_content, stats_html
)
timeline_items.append((conv["timestamp"], "prompt", item_html))
# Add commits as separate timeline items
for commit_ts, commit_hash, commit_msg, page_num, conv_idx in all_commits:
item_html = _macros.index_commit(
commit_hash, commit_msg, commit_ts, _github_repo
)
timeline_items.append((commit_ts, "commit", item_html))
# Sort by timestamp
timeline_items.sort(key=lambda x: x[0])
index_items = [item[2] for item in timeline_items]
index_pagination = generate_index_pagination_html(total_pages)
index_template = get_template("index.html")
index_content = index_template.render(
css=CSS,
js=JS,
pagination_html=index_pagination,
prompt_num=prompt_num,
total_messages=total_messages,
total_tool_calls=total_tool_calls,
total_commits=total_commits,
total_pages=total_pages,
index_items_html="".join(index_items),
)
index_path = output_dir / "index.html"
index_path.write_text(index_content)
print(
f"Generated {index_path.resolve()} ({total_convs} prompts, {total_pages} pages)"
)
@click.group(cls=DefaultGroup, default="session", default_if_no_args=False)
@click.version_option(None, "-v", "--version", package_name="claude-code-publish")
def cli():
"""Convert Claude Code session JSON to mobile-friendly HTML pages."""
pass
@cli.command()
@click.argument("json_file", type=click.Path(exists=True))
@click.option(
"-o",
"--output",
type=click.Path(),
help="Output directory (default: current directory, or temp dir with --gist/--open)",
)
@click.option(
"--repo",
help="GitHub repo (owner/name) for commit links. Auto-detected from git push output if not specified.",
)
@click.option(
"--gist",
is_flag=True,
help="Upload to GitHub Gist and output a gistpreview.github.io URL.",
)
@click.option(
"--json",
"include_json",
is_flag=True,
help="Include the original JSON session file in the output directory.",
)
@click.option(
"--open",
"open_browser",
is_flag=True,
help="Open the generated index.html in your default browser.",
)
def session(json_file, output, repo, gist, include_json, open_browser):
"""Convert a Claude Code session JSON file to HTML."""
# Determine output directory
if (gist or open_browser) and output is None:
# Extract session ID from JSON file for temp directory name
with open(json_file, "r") as f:
data = json.load(f)
session_id = data.get("sessionId", Path(json_file).stem)
output = Path(tempfile.gettempdir()) / session_id
elif output is None:
output = "."
output = Path(output)
generate_html(json_file, output, github_repo=repo)
# Copy JSON file to output directory if requested
if include_json:
output.mkdir(exist_ok=True)
json_source = Path(json_file)
json_dest = output / json_source.name
shutil.copy(json_file, json_dest)
json_size_kb = json_dest.stat().st_size / 1024
click.echo(f"JSON: {json_dest} ({json_size_kb:.1f} KB)")
if gist:
# Inject gist preview JS and create gist
inject_gist_preview_js(output)
click.echo("Creating GitHub gist...")
gist_id, gist_url = create_gist(output)
preview_url = f"https://gistpreview.github.io/?{gist_id}/index.html"
click.echo(f"Gist: {gist_url}")
click.echo(f"Preview: {preview_url}")
click.echo(f"Files: {output}")
if open_browser:
index_url = (output / "index.html").resolve().as_uri()
webbrowser.open(index_url)
def resolve_credentials(token, org_uuid):
"""Resolve token and org_uuid from arguments or auto-detect.
Returns (token, org_uuid) tuple.
Raises click.ClickException if credentials cannot be resolved.
"""
# Get token
if token is None:
token = get_access_token_from_keychain()
if token is None:
if platform.system() == "Darwin":
raise click.ClickException(
"Could not retrieve access token from macOS keychain. "
"Make sure you are logged into Claude Code, or provide --token."
)
else:
raise click.ClickException(
"On non-macOS platforms, you must provide --token with your access token."
)
# Get org UUID
if org_uuid is None:
org_uuid = get_org_uuid_from_config()
if org_uuid is None:
raise click.ClickException(
"Could not find organization UUID in ~/.claude.json. "
"Provide --org-uuid with your organization UUID."
)
return token, org_uuid
def format_session_for_display(session_data):
"""Format a session for display in the list or picker.
Returns a formatted string.
"""
session_id = session_data.get("id", "unknown")
title = session_data.get("title", "Untitled")
created_at = session_data.get("created_at", "")
# Truncate title if too long
if len(title) > 60:
title = title[:57] + "..."
return f"{session_id} {created_at[:19] if created_at else 'N/A':19} {title}"
@cli.command("list-web")
@click.option("--token", help="API access token (auto-detected from keychain on macOS)")
@click.option(
"--org-uuid", help="Organization UUID (auto-detected from ~/.claude.json)"
)
def list_web(token, org_uuid):
"""List available sessions from the Claude API."""
try:
token, org_uuid = resolve_credentials(token, org_uuid)
except click.ClickException:
raise
try:
sessions_data = fetch_sessions(token, org_uuid)
except httpx.HTTPStatusError as e:
raise click.ClickException(
f"API request failed: {e.response.status_code} {e.response.text}"
)
except httpx.RequestError as e:
raise click.ClickException(f"Network error: {e}")
sessions = sessions_data.get("data", [])
if not sessions:
click.echo("No sessions found.")
return
# Print header
click.echo(f"{'Session ID':<35} {'Created':<19} Name")
click.echo("-" * 80)
for session_data in sessions:
click.echo(format_session_for_display(session_data))
def generate_html_from_session_data(session_data, output_dir, github_repo=None):
"""Generate HTML from session data dict (instead of file path)."""
output_dir = Path(output_dir)
output_dir.mkdir(exist_ok=True, parents=True)
loglines = session_data.get("loglines", [])
# Auto-detect GitHub repo if not provided
if github_repo is None:
github_repo = detect_github_repo(loglines)