forked from 1jehuang/jcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathimport.rs
More file actions
1504 lines (1375 loc) · 49.6 KB
/
import.rs
File metadata and controls
1504 lines (1375 loc) · 49.6 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
//! Import Claude Code sessions into jcode
//!
//! This module handles discovering, parsing, and converting Claude Code sessions
//! so they can be resumed within jcode.
use crate::message::{ContentBlock, Role};
use crate::session::{Session, SessionStatus, StoredMessage};
use anyhow::{Context, Result};
use chrono::{DateTime, Utc};
use serde::Deserialize;
use sha2::{Digest, Sha256};
use std::cmp::Reverse;
use std::collections::{BinaryHeap, HashMap, HashSet};
use std::fs::File;
use std::io::{BufRead, BufReader};
use std::path::Path;
use std::path::PathBuf;
/// Entry in the Claude Code sessions-index.json file
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionIndexEntry {
pub session_id: String,
pub full_path: String,
#[serde(default)]
pub file_mtime: Option<u64>,
#[serde(default)]
pub first_prompt: Option<String>,
#[serde(default)]
pub summary: Option<String>,
#[serde(default)]
pub message_count: Option<u32>,
#[serde(default)]
pub created: Option<String>,
#[serde(default)]
pub modified: Option<String>,
#[serde(default)]
pub git_branch: Option<String>,
#[serde(default)]
pub project_path: Option<String>,
#[serde(default)]
pub is_sidechain: Option<bool>,
}
/// Claude Code sessions-index.json format
#[derive(Debug, Deserialize)]
pub struct SessionsIndex {
pub version: u32,
pub entries: Vec<SessionIndexEntry>,
}
/// Info about a Claude Code session for listing
#[derive(Debug, Clone)]
pub struct ClaudeCodeSessionInfo {
pub session_id: String,
pub first_prompt: String,
pub summary: Option<String>,
pub message_count: u32,
pub created: Option<DateTime<Utc>>,
pub modified: Option<DateTime<Utc>>,
pub project_path: Option<String>,
pub full_path: String,
}
/// Entry in a Claude Code JSONL session file
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ClaudeCodeEntry {
#[serde(rename = "type")]
entry_type: String,
uuid: Option<String>,
parent_uuid: Option<String>,
#[serde(rename = "sessionId")]
_session_id: Option<String>,
cwd: Option<String>,
message: Option<ClaudeCodeMessage>,
timestamp: Option<String>,
#[serde(default)]
is_sidechain: bool,
}
/// Message content in Claude Code format
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
struct ClaudeCodeMessage {
role: String,
#[serde(default)]
model: Option<String>,
// Content can be a string or array
#[serde(default)]
content: ClaudeCodeContent,
}
/// Content can be either a plain string or array of blocks
#[derive(Debug, Clone, Deserialize, Default)]
#[serde(untagged)]
enum ClaudeCodeContent {
#[default]
Empty,
Text(String),
Blocks(Vec<ClaudeCodeContentBlock>),
}
/// Individual content block in Claude Code format
#[derive(Debug, Clone, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
enum ClaudeCodeContentBlock {
Text {
text: String,
},
Thinking {
thinking: String,
#[serde(default)]
#[serde(rename = "signature")]
_signature: Option<String>,
},
ToolUse {
id: String,
name: String,
input: serde_json::Value,
},
ToolResult {
tool_use_id: String,
content: String,
#[serde(default)]
is_error: Option<bool>,
},
#[serde(other)]
Unknown,
}
/// Discover all Claude Code project directories under ~/.claude/projects.
fn discover_project_dirs() -> Result<Vec<PathBuf>> {
let claude_dir = crate::storage::user_home_path(".claude/projects")
.context("Could not find Claude projects directory")?;
if !claude_dir.exists() {
return Ok(Vec::new());
}
let mut project_dirs = Vec::new();
for entry in std::fs::read_dir(&claude_dir)? {
let entry = entry?;
let path = entry.path();
if path.is_dir() {
project_dirs.push(path);
}
}
project_dirs.sort();
Ok(project_dirs)
}
/// Discover all Claude Code projects and their sessions-index.json files.
#[cfg(test)]
fn discover_projects() -> Result<Vec<PathBuf>> {
Ok(discover_project_dirs()?
.into_iter()
.map(|dir| dir.join("sessions-index.json"))
.filter(|path| path.exists())
.collect())
}
fn parse_rfc3339_string(value: Option<&str>) -> Option<DateTime<Utc>> {
value
.and_then(|ts| DateTime::parse_from_rfc3339(ts).ok())
.map(|dt| dt.with_timezone(&Utc))
}
fn clean_optional_text(value: Option<String>) -> Option<String> {
value.and_then(|text| {
let trimmed = text.trim();
if trimmed.is_empty() {
None
} else {
Some(trimmed.to_string())
}
})
}
fn resolve_claude_session_path(project_dir: &Path, entry: &SessionIndexEntry) -> Option<PathBuf> {
let indexed_path = PathBuf::from(&entry.full_path);
let fallback_path = project_dir.join(format!("{}.jsonl", entry.session_id));
if indexed_path.exists() {
Some(indexed_path)
} else if fallback_path.exists() {
Some(fallback_path)
} else {
None
}
}
fn claude_code_session_info_from_index(
path: &Path,
entry: &SessionIndexEntry,
) -> Option<ClaudeCodeSessionInfo> {
let message_count = entry.message_count.filter(|count| *count > 0)?;
let summary = clean_optional_text(entry.summary.clone());
let first_prompt =
clean_optional_text(entry.first_prompt.clone()).or_else(|| summary.clone())?;
Some(ClaudeCodeSessionInfo {
session_id: entry.session_id.clone(),
first_prompt,
summary,
message_count,
created: parse_rfc3339_string(entry.created.as_deref()),
modified: parse_rfc3339_string(entry.modified.as_deref()),
project_path: clean_optional_text(entry.project_path.clone()),
full_path: path.to_string_lossy().to_string(),
})
}
fn claude_text_from_content(content: &ClaudeCodeContent) -> Option<String> {
match content {
ClaudeCodeContent::Empty => None,
ClaudeCodeContent::Text(text) => {
let text = text.trim();
if text.is_empty() {
None
} else {
Some(text.to_string())
}
}
ClaudeCodeContent::Blocks(blocks) => {
let text = blocks
.iter()
.filter_map(|block| match block {
ClaudeCodeContentBlock::Text { text } => Some(text.trim()),
ClaudeCodeContentBlock::Thinking { thinking, .. } => Some(thinking.trim()),
ClaudeCodeContentBlock::ToolResult { content, .. } => Some(content.trim()),
_ => None,
})
.filter(|text| !text.is_empty())
.collect::<Vec<_>>()
.join("\n");
if text.is_empty() { None } else { Some(text) }
}
}
}
fn load_claude_code_entries(path: &Path) -> Result<Vec<ClaudeCodeEntry>> {
let content = std::fs::read_to_string(path)
.with_context(|| format!("Failed to read session file: {}", path.display()))?;
let mut entries = Vec::new();
for line in content.lines() {
if line.trim().is_empty() {
continue;
}
match serde_json::from_str::<ClaudeCodeEntry>(line) {
Ok(entry) => entries.push(entry),
Err(e) => {
crate::logging::debug(&format!(
"Skipping malformed Claude Code entry in {}: {}",
path.display(),
e
));
}
}
}
Ok(entries)
}
fn ordered_claude_code_message_entries(entries: &[ClaudeCodeEntry]) -> Vec<&ClaudeCodeEntry> {
let message_entries: Vec<&ClaudeCodeEntry> = entries
.iter()
.filter(|e| {
(e.entry_type == "user" || e.entry_type == "assistant")
&& e.message.is_some()
&& !e.is_sidechain
})
.collect();
let mut uuid_to_entry: HashMap<String, &ClaudeCodeEntry> = HashMap::new();
for entry in &message_entries {
if let Some(ref uuid) = entry.uuid {
uuid_to_entry.insert(uuid.clone(), entry);
}
}
let mut ordered_entries: Vec<&ClaudeCodeEntry> = Vec::new();
let mut visited: HashSet<String> = HashSet::new();
let roots: Vec<&ClaudeCodeEntry> = message_entries
.iter()
.filter(|e| {
e.parent_uuid.is_none()
|| !uuid_to_entry.contains_key(e.parent_uuid.as_deref().unwrap_or_default())
})
.copied()
.collect();
for root in roots {
let mut current = root;
loop {
if let Some(ref uuid) = current.uuid {
if visited.contains(uuid) {
break;
}
visited.insert(uuid.clone());
}
ordered_entries.push(current);
let next = message_entries.iter().find(|e| {
e.parent_uuid.as_ref() == current.uuid.as_ref()
&& e.uuid
.as_ref()
.map(|u| !visited.contains(u))
.unwrap_or(true)
});
match next {
Some(n) => current = n,
None => break,
}
}
}
for entry in message_entries {
if entry
.uuid
.as_ref()
.map(|uuid| visited.contains(uuid))
.unwrap_or(false)
{
continue;
}
ordered_entries.push(entry);
}
ordered_entries
}
fn claude_code_session_info_from_file(
path: &Path,
indexed: Option<&SessionIndexEntry>,
) -> Result<ClaudeCodeSessionInfo> {
let entries = load_claude_code_entries(path)?;
let ordered_entries = ordered_claude_code_message_entries(&entries);
let first_entry = ordered_entries.first().copied();
let last_entry = ordered_entries.last().copied();
let session_id = indexed
.map(|entry| entry.session_id.clone())
.or_else(|| {
entries
.iter()
.find_map(|entry| entry._session_id.clone())
.or_else(|| {
path.file_stem()
.and_then(|stem| stem.to_str())
.map(|s| s.to_string())
})
})
.unwrap_or_else(|| path.to_string_lossy().to_string());
let first_prompt = indexed
.and_then(|entry| clean_optional_text(entry.first_prompt.clone()))
.or_else(|| {
ordered_entries.iter().find_map(|entry| {
(entry.entry_type == "user")
.then_some(entry.message.as_ref())
.flatten()
.and_then(|message| claude_text_from_content(&message.content))
})
})
.or_else(|| indexed.and_then(|entry| clean_optional_text(entry.summary.clone())))
.unwrap_or_else(|| "No prompt".to_string());
let summary = indexed.and_then(|entry| clean_optional_text(entry.summary.clone()));
let message_count = indexed
.and_then(|entry| entry.message_count)
.filter(|count| *count > 0)
.unwrap_or(ordered_entries.len() as u32);
let created = indexed
.and_then(|entry| parse_rfc3339_string(entry.created.as_deref()))
.or_else(|| first_entry.and_then(|entry| parse_rfc3339_string(entry.timestamp.as_deref())));
let modified = indexed
.and_then(|entry| parse_rfc3339_string(entry.modified.as_deref()))
.or_else(|| last_entry.and_then(|entry| parse_rfc3339_string(entry.timestamp.as_deref())));
let project_path = indexed
.and_then(|entry| clean_optional_text(entry.project_path.clone()))
.or_else(|| first_entry.and_then(|entry| entry.cwd.clone()));
Ok(ClaudeCodeSessionInfo {
session_id,
first_prompt,
summary,
message_count,
created,
modified,
project_path,
full_path: path.to_string_lossy().to_string(),
})
}
/// List all available Claude Code sessions
pub fn list_claude_code_sessions() -> Result<Vec<ClaudeCodeSessionInfo>> {
let mut all_sessions = Vec::new();
let mut seen_session_ids = HashSet::new();
for project_dir in discover_project_dirs()? {
let index_path = project_dir.join("sessions-index.json");
if index_path.exists() {
let content = std::fs::read_to_string(&index_path)
.with_context(|| format!("Failed to read {}", index_path.display()))?;
let index: SessionsIndex = serde_json::from_str(&content)
.with_context(|| format!("Failed to parse {}", index_path.display()))?;
for entry in index.entries {
if entry.is_sidechain.unwrap_or(false) {
continue;
}
let Some(path) = resolve_claude_session_path(&project_dir, &entry) else {
continue;
};
let session =
if let Some(session) = claude_code_session_info_from_index(&path, &entry) {
session
} else {
let session = claude_code_session_info_from_file(&path, Some(&entry))?;
if session.message_count == 0
|| (session.summary.is_none() && session.first_prompt == "No prompt")
{
continue;
}
session
};
seen_session_ids.insert(session.session_id.clone());
all_sessions.push(session);
}
}
for path in collect_files_recursive(&project_dir, "jsonl") {
let Some(session_id) = path
.file_stem()
.and_then(|stem| stem.to_str())
.map(|stem| stem.to_string())
else {
continue;
};
if seen_session_ids.contains(&session_id) {
continue;
}
let session = claude_code_session_info_from_file(&path, None)?;
if session.message_count == 0
|| (session.summary.is_none() && session.first_prompt == "No prompt")
{
continue;
}
seen_session_ids.insert(session.session_id.clone());
all_sessions.push(session);
}
}
// Sort by modified date descending
all_sessions.sort_by(|a, b| {
let a_date = a.modified.or(a.created);
let b_date = b.modified.or(b.created);
b_date.cmp(&a_date)
});
Ok(all_sessions)
}
pub fn list_claude_code_sessions_lazy(scan_limit: usize) -> Result<Vec<ClaudeCodeSessionInfo>> {
let mut all_sessions = Vec::new();
let mut seen_session_ids = HashSet::new();
for project_dir in discover_project_dirs()? {
let index_path = project_dir.join("sessions-index.json");
if index_path.exists() {
let content = std::fs::read_to_string(&index_path)
.with_context(|| format!("Failed to read {}", index_path.display()))?;
let index: SessionsIndex = serde_json::from_str(&content)
.with_context(|| format!("Failed to parse {}", index_path.display()))?;
for entry in index.entries {
if entry.is_sidechain.unwrap_or(false) {
continue;
}
let Some(path) = resolve_claude_session_path(&project_dir, &entry) else {
continue;
};
if let Some(session) = claude_code_session_info_from_index(&path, &entry) {
seen_session_ids.insert(session.session_id.clone());
all_sessions.push(session);
}
}
}
for path in collect_recent_files_recursive(&project_dir, "jsonl", scan_limit) {
let Some(session_id) = path
.file_stem()
.and_then(|stem| stem.to_str())
.map(|stem| stem.to_string())
else {
continue;
};
if seen_session_ids.contains(&session_id) {
continue;
}
let modified = path
.metadata()
.and_then(|meta| meta.modified())
.ok()
.map(DateTime::<Utc>::from);
let project_path = project_dir
.file_name()
.and_then(|name| name.to_str())
.map(|name| name.replace('-', "/"));
let label = format!(
"Claude Code session {}",
&session_id[..session_id.len().min(8)]
);
all_sessions.push(ClaudeCodeSessionInfo {
session_id: session_id.clone(),
first_prompt: label.clone(),
summary: Some(label),
message_count: 0,
created: modified,
modified,
project_path,
full_path: path.to_string_lossy().to_string(),
});
seen_session_ids.insert(session_id);
}
}
all_sessions.sort_by(|a, b| {
let a_date = a.modified.or(a.created);
let b_date = b.modified.or(b.created);
b_date.cmp(&a_date)
});
all_sessions.truncate(scan_limit);
Ok(all_sessions)
}
/// List sessions filtered by project path
pub fn list_sessions_for_project(project_filter: &str) -> Result<Vec<ClaudeCodeSessionInfo>> {
let sessions = list_claude_code_sessions()?;
Ok(sessions
.into_iter()
.filter(|s| {
s.project_path
.as_ref()
.map(|p| p.contains(project_filter))
.unwrap_or(false)
})
.collect())
}
/// Find a session file by ID
fn find_session_file(session_id: &str) -> Result<PathBuf> {
let sessions = list_claude_code_sessions()?;
for session in sessions {
if session.session_id == session_id {
let path = PathBuf::from(&session.full_path);
if path.exists() {
return Ok(path);
}
}
}
anyhow::bail!("Session {} not found", session_id);
}
/// Convert Claude Code content blocks to jcode ContentBlocks
fn convert_content_blocks(content: &ClaudeCodeContent) -> Vec<ContentBlock> {
match content {
ClaudeCodeContent::Empty => vec![],
ClaudeCodeContent::Text(text) => {
if text.is_empty() {
vec![]
} else {
vec![ContentBlock::Text {
text: text.clone(),
cache_control: None,
}]
}
}
ClaudeCodeContent::Blocks(blocks) => blocks
.iter()
.filter_map(|block| match block {
ClaudeCodeContentBlock::Text { text } => Some(ContentBlock::Text {
text: text.clone(),
cache_control: None,
}),
ClaudeCodeContentBlock::Thinking { thinking, .. } => {
Some(ContentBlock::Reasoning {
text: thinking.clone(),
})
}
ClaudeCodeContentBlock::ToolUse { id, name, input } => {
Some(ContentBlock::ToolUse {
id: id.clone(),
name: name.clone(),
input: input.clone(),
})
}
ClaudeCodeContentBlock::ToolResult {
tool_use_id,
content,
is_error,
} => Some(ContentBlock::ToolResult {
tool_use_id: tool_use_id.clone(),
content: content.clone(),
is_error: *is_error,
}),
ClaudeCodeContentBlock::Unknown => None,
})
.collect(),
}
}
/// Import a Claude Code session by ID
pub fn import_session(session_id: &str) -> Result<Session> {
let session_file = find_session_file(session_id)?;
import_session_from_file(&session_file, session_id)
}
pub fn imported_claude_code_session_id(session_id: &str) -> String {
format!("imported_cc_{}", session_id)
}
pub fn imported_codex_session_id(session_id: &str) -> String {
format!("imported_codex_{}", session_id)
}
pub fn imported_opencode_session_id(session_id: &str) -> String {
format!("imported_opencode_{}", session_id)
}
pub fn imported_pi_session_id(session_path: &str) -> String {
let mut hasher = Sha256::new();
hasher.update(session_path.as_bytes());
let digest = hasher.finalize();
format!("imported_pi_{}", hex::encode(&digest[..8]))
}
pub fn imported_session_id_for_target(
target: &crate::tui::session_picker::ResumeTarget,
) -> Option<String> {
match target {
crate::tui::session_picker::ResumeTarget::JcodeSession { session_id } => {
Some(session_id.clone())
}
crate::tui::session_picker::ResumeTarget::ClaudeCodeSession { session_id, .. } => {
Some(imported_claude_code_session_id(session_id))
}
crate::tui::session_picker::ResumeTarget::CodexSession { session_id, .. } => {
Some(imported_codex_session_id(session_id))
}
crate::tui::session_picker::ResumeTarget::PiSession { session_path } => {
Some(imported_pi_session_id(session_path))
}
crate::tui::session_picker::ResumeTarget::OpenCodeSession { session_id, .. } => {
Some(imported_opencode_session_id(session_id))
}
}
}
pub fn resolve_resume_target_to_jcode(
target: &crate::tui::session_picker::ResumeTarget,
) -> Result<crate::tui::session_picker::ResumeTarget> {
use crate::tui::session_picker::ResumeTarget;
let session_id = match target {
ResumeTarget::JcodeSession { session_id } => {
return Ok(ResumeTarget::JcodeSession {
session_id: session_id.clone(),
});
}
ResumeTarget::ClaudeCodeSession {
session_id,
session_path,
} => {
import_session_from_file(Path::new(session_path), session_id)?;
imported_claude_code_session_id(session_id)
}
ResumeTarget::CodexSession {
session_id,
session_path,
} => {
import_codex_session_from_path(Path::new(session_path), Some(session_id))?;
imported_codex_session_id(session_id)
}
ResumeTarget::PiSession { session_path } => {
import_pi_session(session_path)?;
imported_pi_session_id(session_path)
}
ResumeTarget::OpenCodeSession {
session_id,
session_path,
} => {
import_opencode_session_from_path(Path::new(session_path), Some(session_id))?;
imported_opencode_session_id(session_id)
}
};
Ok(ResumeTarget::JcodeSession { session_id })
}
pub fn import_external_resume_id(resume_id: &str) -> Result<Option<String>> {
if let Ok(path) = find_codex_session_file(resume_id) {
let session = import_codex_session_from_path(&path, Some(resume_id))?;
return Ok(Some(session.id));
}
if let Ok(path) = find_session_file(resume_id) {
let session = import_session_from_file(&path, resume_id)?;
return Ok(Some(session.id));
}
if let Ok(path) = find_opencode_session_file(resume_id) {
let session = import_opencode_session_from_path(&path, Some(resume_id))?;
return Ok(Some(session.id));
}
let pi_path = Path::new(resume_id);
if pi_path.exists() {
let session = import_pi_session(resume_id)?;
return Ok(Some(session.id));
}
Ok(None)
}
/// Import a Claude Code session from a file path
pub fn import_session_from_file(path: &Path, session_id: &str) -> Result<Session> {
let content = std::fs::read_to_string(path)
.with_context(|| format!("Failed to read session file: {}", path.display()))?;
// Parse JSONL entries
let mut entries: Vec<ClaudeCodeEntry> = Vec::new();
for line in content.lines() {
if line.trim().is_empty() {
continue;
}
match serde_json::from_str::<ClaudeCodeEntry>(line) {
Ok(entry) => entries.push(entry),
Err(e) => {
// Log but skip malformed lines
crate::logging::debug(&format!("Skipping malformed entry: {}", e));
}
}
}
// Filter to actual messages (user/assistant types, not progress/snapshots)
let message_entries: Vec<&ClaudeCodeEntry> = entries
.iter()
.filter(|e| {
(e.entry_type == "user" || e.entry_type == "assistant")
&& e.message.is_some()
&& !e.is_sidechain
})
.collect();
// Build a map of uuid -> entry for ordering
let mut uuid_to_entry: HashMap<String, &ClaudeCodeEntry> = HashMap::new();
for entry in &message_entries {
if let Some(ref uuid) = entry.uuid {
uuid_to_entry.insert(uuid.clone(), entry);
}
}
// Find root entries (no parent or parent not in our message set)
// Then build the conversation in order by following parent_uuid links
let mut ordered_entries: Vec<&ClaudeCodeEntry> = Vec::new();
let mut visited: std::collections::HashSet<String> = std::collections::HashSet::new();
// Find entry with no parent (or parent is not a message entry)
let roots: Vec<&ClaudeCodeEntry> = message_entries
.iter()
.filter(|e| {
e.parent_uuid.is_none()
|| !uuid_to_entry.contains_key(e.parent_uuid.as_deref().unwrap_or_default())
})
.copied()
.collect();
// For each root, follow the chain
for root in roots {
let mut current = root;
loop {
if let Some(ref uuid) = current.uuid {
if visited.contains(uuid) {
break;
}
visited.insert(uuid.clone());
}
ordered_entries.push(current);
// Find next entry that has this one as parent
let next = message_entries.iter().find(|e| {
e.parent_uuid.as_ref() == current.uuid.as_ref()
&& e.uuid
.as_ref()
.map(|u| !visited.contains(u))
.unwrap_or(true)
});
match next {
Some(n) => current = n,
None => break,
}
}
}
// Extract metadata from entries
let first_entry = ordered_entries.first();
let working_dir = first_entry.and_then(|e| e.cwd.clone());
// Get model from first assistant message (user messages don't have model)
let model = ordered_entries
.iter()
.find(|e| e.entry_type == "assistant")
.and_then(|e| e.message.as_ref()?.model.clone());
let created_at = first_entry
.and_then(|e| e.timestamp.as_ref())
.and_then(|t| DateTime::parse_from_rfc3339(t).ok())
.map(|dt| dt.with_timezone(&Utc))
.unwrap_or_else(Utc::now);
// Get title from first user message or sessions index
let title = first_entry
.and_then(|e| {
if e.entry_type == "user" {
match &e.message.as_ref()?.content {
ClaudeCodeContent::Text(t) => Some(truncate_title(t)),
ClaudeCodeContent::Blocks(blocks) => {
for b in blocks {
if let ClaudeCodeContentBlock::Text { text } = b {
return Some(truncate_title(text));
}
}
None
}
_ => None,
}
} else {
None
}
})
.or_else(|| {
// Try to get from index
list_claude_code_sessions()
.ok()?
.into_iter()
.find(|s| s.session_id == session_id)
.and_then(|s| s.summary.or(Some(s.first_prompt)))
});
// Create jcode session
let jcode_session_id = imported_claude_code_session_id(session_id);
let mut session = Session::create_with_id(jcode_session_id, None, title);
session.provider_session_id = Some(session_id.to_string());
session.provider_key = Some("claude-code".to_string());
session.working_dir = working_dir;
session.model = model;
session.created_at = created_at;
session.status = SessionStatus::Closed;
// Convert messages
for entry in ordered_entries {
if let Some(ref msg) = entry.message {
let role = match msg.role.as_str() {
"user" => Role::User,
"assistant" => Role::Assistant,
_ => continue,
};
let content_blocks = convert_content_blocks(&msg.content);
// Skip empty messages
if content_blocks.is_empty() {
continue;
}
// Generate message ID from uuid or create new
let msg_id = entry
.uuid
.clone()
.unwrap_or_else(|| crate::id::new_id("msg"));
session.append_stored_message(StoredMessage {
id: msg_id,
role,
content: content_blocks,
display_role: None,
timestamp: None,
tool_duration_ms: None,
token_usage: None,
});
}
}
// Save the session
session.save()?;
Ok(session)
}
fn collect_files_recursive(root: &Path, extension: &str) -> Vec<PathBuf> {
fn walk(dir: &Path, extension: &str, out: &mut Vec<PathBuf>) {
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
walk(&path, extension, out);
} else if path
.extension()
.and_then(|ext| ext.to_str())
.map(|ext| ext.eq_ignore_ascii_case(extension))
.unwrap_or(false)
{
out.push(path);
}
}
}
let mut files = Vec::new();
walk(root, extension, &mut files);
files.sort();
files
}
fn collect_recent_files_recursive(root: &Path, extension: &str, limit: usize) -> Vec<PathBuf> {
fn modified_sort_key(path: &Path) -> u64 {
path.metadata()
.and_then(|meta| meta.modified())
.ok()
.and_then(|time| time.duration_since(std::time::UNIX_EPOCH).ok())
.map(|duration| duration.as_secs())
.unwrap_or(0)
}
fn walk(
dir: &Path,
extension: &str,
limit: usize,
out: &mut BinaryHeap<Reverse<(u64, PathBuf)>>,
) {
let Ok(entries) = std::fs::read_dir(dir) else {
return;
};
for entry in entries.flatten() {
let path = entry.path();
if path.is_dir() {
walk(&path, extension, limit, out);
} else if path
.extension()
.and_then(|ext| ext.to_str())
.map(|ext| ext.eq_ignore_ascii_case(extension))
.unwrap_or(false)
{
let key = (modified_sort_key(&path), path);
if out.len() < limit {
out.push(Reverse(key));
} else if out.peek().map(|smallest| key > smallest.0).unwrap_or(true) {
out.pop();
out.push(Reverse(key));
}
}
}
}
if limit == 0 {
return Vec::new();
}
let mut heap: BinaryHeap<Reverse<(u64, PathBuf)>> = BinaryHeap::new();
walk(root, extension, limit, &mut heap);
let mut files: Vec<(u64, PathBuf)> = heap.into_iter().map(|entry| entry.0).collect();
files.sort_by(|a, b| b.0.cmp(&a.0).then_with(|| b.1.cmp(&a.1)));
files.into_iter().map(|(_, path)| path).collect()
}
fn parse_rfc3339(value: Option<&serde_json::Value>) -> Option<DateTime<Utc>> {
value
.and_then(|v| v.as_str())
.and_then(|ts| DateTime::parse_from_rfc3339(ts).ok())
.map(|dt| dt.with_timezone(&Utc))
}
fn extract_text_from_json_value(value: &serde_json::Value) -> String {
fn visit(value: &serde_json::Value, out: &mut Vec<String>) {
match value {
serde_json::Value::String(text) => {
if !text.trim().is_empty() {
out.push(text.trim().to_string());