-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathclaude.rs
More file actions
2065 lines (1776 loc) · 70.5 KB
/
claude.rs
File metadata and controls
2065 lines (1776 loc) · 70.5 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
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::fs;
use std::io::{BufRead, BufReader};
use std::path::PathBuf;
use std::process::Stdio;
use std::sync::Arc;
use std::time::SystemTime;
use tauri::{AppHandle, Emitter, Manager};
use tokio::process::{Child, Command};
use tokio::sync::Mutex;
/// Global state to track current Claude process
pub struct ClaudeProcessState {
pub current_process: Arc<Mutex<Option<Child>>>,
}
impl Default for ClaudeProcessState {
fn default() -> Self {
Self {
current_process: Arc::new(Mutex::new(None)),
}
}
}
/// Represents a project in the ~/.claude/projects directory
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Project {
/// The project ID (derived from the directory name)
pub id: String,
/// The original project path (decoded from the directory name)
pub path: String,
/// List of session IDs (JSONL file names without extension)
pub sessions: Vec<String>,
/// Unix timestamp when the project directory was created
pub created_at: u64,
}
/// Represents a session with its metadata
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Session {
/// The session ID (UUID)
pub id: String,
/// The project ID this session belongs to
pub project_id: String,
/// The project path
pub project_path: String,
/// Optional todo data associated with this session
pub todo_data: Option<serde_json::Value>,
/// Unix timestamp when the session file was created
pub created_at: u64,
/// First user message content (if available)
pub first_message: Option<String>,
/// Timestamp of the first user message (if available)
pub message_timestamp: Option<String>,
}
/// Represents a message entry in the JSONL file
#[derive(Debug, Deserialize)]
struct JsonlEntry {
#[serde(rename = "type")]
#[allow(dead_code)]
entry_type: Option<String>,
message: Option<MessageContent>,
timestamp: Option<String>,
}
/// Represents the message content
#[derive(Debug, Deserialize)]
struct MessageContent {
role: Option<String>,
content: Option<String>,
}
/// Represents the settings from ~/.claude/settings.json
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClaudeSettings {
#[serde(flatten)]
pub data: serde_json::Value,
}
impl Default for ClaudeSettings {
fn default() -> Self {
Self {
data: serde_json::json!({}),
}
}
}
/// Represents the Claude Code version status
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClaudeVersionStatus {
/// Whether Claude Code is installed and working
pub is_installed: bool,
/// The version string if available
pub version: Option<String>,
/// The full output from the command
pub output: String,
}
/// Represents a CLAUDE.md file found in the project
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ClaudeMdFile {
/// Relative path from the project root
pub relative_path: String,
/// Absolute path to the file
pub absolute_path: String,
/// File size in bytes
pub size: u64,
/// Last modified timestamp
pub modified: u64,
}
/// Represents a file or directory entry
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileEntry {
/// The name of the file or directory
pub name: String,
/// The full path
pub path: String,
/// Whether this is a directory
pub is_directory: bool,
/// File size in bytes (0 for directories)
pub size: u64,
/// File extension (if applicable)
pub extension: Option<String>,
}
/// Finds the full path to the claude binary
/// This is necessary because macOS apps have a limited PATH environment
fn find_claude_binary(app_handle: &AppHandle) -> Result<String, String> {
crate::claude_binary::find_claude_binary(app_handle)
}
/// Gets the path to the ~/.claude directory
fn get_claude_dir() -> Result<PathBuf> {
dirs::home_dir()
.context("Could not find home directory")?
.join(".claude")
.canonicalize()
.context("Could not find ~/.claude directory")
}
/// Gets the actual project path by reading the cwd from the first JSONL entry
fn get_project_path_from_sessions(project_dir: &PathBuf) -> Result<String, String> {
// Try to read any JSONL file in the directory
let entries = fs::read_dir(project_dir)
.map_err(|e| format!("Failed to read project directory: {}", e))?;
for entry in entries {
if let Ok(entry) = entry {
let path = entry.path();
if path.is_file() && path.extension().and_then(|s| s.to_str()) == Some("jsonl") {
// Read the first line of the JSONL file
if let Ok(file) = fs::File::open(&path) {
let reader = BufReader::new(file);
if let Some(Ok(first_line)) = reader.lines().next() {
// Parse the JSON and extract cwd
if let Ok(json) = serde_json::from_str::<serde_json::Value>(&first_line) {
if let Some(cwd) = json.get("cwd").and_then(|v| v.as_str()) {
return Ok(cwd.to_string());
}
}
}
}
}
}
}
Err("Could not determine project path from session files".to_string())
}
/// Decodes a project directory name back to its original path
/// The directory names in ~/.claude/projects are encoded paths
/// DEPRECATED: Use get_project_path_from_sessions instead when possible
fn decode_project_path(encoded: &str) -> String {
// This is a fallback - the encoding isn't reversible when paths contain hyphens
// For example: -Users-mufeedvh-dev-jsonl-viewer could be /Users/mufeedvh/dev/jsonl-viewer
// or /Users/mufeedvh/dev/jsonl/viewer
encoded.replace('-', "/")
}
/// Extracts the first valid user message from a JSONL file
fn extract_first_user_message(jsonl_path: &PathBuf) -> (Option<String>, Option<String>) {
let file = match fs::File::open(jsonl_path) {
Ok(file) => file,
Err(_) => return (None, None),
};
let reader = BufReader::new(file);
for line in reader.lines() {
if let Ok(line) = line {
if let Ok(entry) = serde_json::from_str::<JsonlEntry>(&line) {
if let Some(message) = entry.message {
if message.role.as_deref() == Some("user") {
if let Some(content) = message.content {
// Skip if it contains the caveat message
if content.contains("Caveat: The messages below were generated by the user while running local commands") {
continue;
}
// Skip if it starts with command tags
if content.starts_with("<command-name>")
|| content.starts_with("<local-command-stdout>")
{
continue;
}
// Found a valid user message
return (Some(content), entry.timestamp);
}
}
}
}
}
}
(None, None)
}
/// Helper function to create a tokio Command with proper environment variables
/// This ensures commands like Claude can find Node.js and other dependencies
fn create_command_with_env(program: &str) -> Command {
// Convert std::process::Command to tokio::process::Command
let _std_cmd = crate::claude_binary::create_command_with_env(program);
// Create a new tokio Command from the program path
let mut tokio_cmd = Command::new(program);
// Copy over all environment variables
for (key, value) in std::env::vars() {
if key == "PATH"
|| key == "HOME"
|| key == "USER"
|| key == "SHELL"
|| key == "LANG"
|| key == "LC_ALL"
|| key.starts_with("LC_")
|| key == "NODE_PATH"
|| key == "NVM_DIR"
|| key == "NVM_BIN"
|| key == "HOMEBREW_PREFIX"
|| key == "HOMEBREW_CELLAR"
{
log::debug!("Inheriting env var: {}={}", key, value);
tokio_cmd.env(&key, &value);
}
}
// Add NVM support if the program is in an NVM directory
if program.contains("/.nvm/versions/node/") {
if let Some(node_bin_dir) = std::path::Path::new(program).parent() {
let current_path = std::env::var("PATH").unwrap_or_default();
let node_bin_str = node_bin_dir.to_string_lossy();
if !current_path.contains(&node_bin_str.as_ref()) {
let new_path = format!("{}:{}", node_bin_str, current_path);
tokio_cmd.env("PATH", new_path);
}
}
}
tokio_cmd
}
/// Lists all projects in the ~/.claude/projects directory
#[tauri::command]
pub async fn list_projects() -> Result<Vec<Project>, String> {
log::info!("Listing projects from ~/.claude/projects");
let claude_dir = get_claude_dir().map_err(|e| e.to_string())?;
let projects_dir = claude_dir.join("projects");
if !projects_dir.exists() {
log::warn!("Projects directory does not exist: {:?}", projects_dir);
return Ok(Vec::new());
}
let mut projects = Vec::new();
// Read all directories in the projects folder
let entries = fs::read_dir(&projects_dir)
.map_err(|e| format!("Failed to read projects directory: {}", e))?;
for entry in entries {
let entry = entry.map_err(|e| format!("Failed to read directory entry: {}", e))?;
let path = entry.path();
if path.is_dir() {
let dir_name = path
.file_name()
.and_then(|n| n.to_str())
.ok_or_else(|| "Invalid directory name".to_string())?;
// Get directory creation time
let metadata = fs::metadata(&path)
.map_err(|e| format!("Failed to read directory metadata: {}", e))?;
let created_at = metadata
.created()
.or_else(|_| metadata.modified())
.unwrap_or(SystemTime::UNIX_EPOCH)
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
// Get the actual project path from JSONL files
let project_path = match get_project_path_from_sessions(&path) {
Ok(path) => path,
Err(e) => {
log::warn!("Failed to get project path from sessions for {}: {}, falling back to decode", dir_name, e);
decode_project_path(dir_name)
}
};
// List all JSONL files (sessions) in this project directory
let mut sessions = Vec::new();
if let Ok(session_entries) = fs::read_dir(&path) {
for session_entry in session_entries.flatten() {
let session_path = session_entry.path();
if session_path.is_file()
&& session_path.extension().and_then(|s| s.to_str()) == Some("jsonl")
{
if let Some(session_id) = session_path.file_stem().and_then(|s| s.to_str())
{
sessions.push(session_id.to_string());
}
}
}
}
projects.push(Project {
id: dir_name.to_string(),
path: project_path,
sessions,
created_at,
});
}
}
// Sort projects by creation time (newest first)
projects.sort_by(|a, b| b.created_at.cmp(&a.created_at));
log::info!("Found {} projects", projects.len());
Ok(projects)
}
/// Gets sessions for a specific project
#[tauri::command]
pub async fn get_project_sessions(project_id: String) -> Result<Vec<Session>, String> {
log::info!("Getting sessions for project: {}", project_id);
let claude_dir = get_claude_dir().map_err(|e| e.to_string())?;
let project_dir = claude_dir.join("projects").join(&project_id);
let todos_dir = claude_dir.join("todos");
if !project_dir.exists() {
return Err(format!("Project directory not found: {}", project_id));
}
// Get the actual project path from JSONL files
let project_path = match get_project_path_from_sessions(&project_dir) {
Ok(path) => path,
Err(e) => {
log::warn!(
"Failed to get project path from sessions for {}: {}, falling back to decode",
project_id,
e
);
decode_project_path(&project_id)
}
};
let mut sessions = Vec::new();
// Read all JSONL files in the project directory
let entries = fs::read_dir(&project_dir)
.map_err(|e| format!("Failed to read project directory: {}", e))?;
for entry in entries {
let entry = entry.map_err(|e| format!("Failed to read directory entry: {}", e))?;
let path = entry.path();
if path.is_file() && path.extension().and_then(|s| s.to_str()) == Some("jsonl") {
if let Some(session_id) = path.file_stem().and_then(|s| s.to_str()) {
// Get file creation time
let metadata = fs::metadata(&path)
.map_err(|e| format!("Failed to read file metadata: {}", e))?;
let created_at = metadata
.created()
.or_else(|_| metadata.modified())
.unwrap_or(SystemTime::UNIX_EPOCH)
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
// Extract first user message and timestamp
let (first_message, message_timestamp) = extract_first_user_message(&path);
// Try to load associated todo data
let todo_path = todos_dir.join(format!("{}.json", session_id));
let todo_data = if todo_path.exists() {
fs::read_to_string(&todo_path)
.ok()
.and_then(|content| serde_json::from_str(&content).ok())
} else {
None
};
sessions.push(Session {
id: session_id.to_string(),
project_id: project_id.clone(),
project_path: project_path.clone(),
todo_data,
created_at,
first_message,
message_timestamp,
});
}
}
}
// Sort sessions by creation time (newest first)
sessions.sort_by(|a, b| b.created_at.cmp(&a.created_at));
log::info!(
"Found {} sessions for project {}",
sessions.len(),
project_id
);
Ok(sessions)
}
/// Reads the Claude settings file
#[tauri::command]
pub async fn get_claude_settings() -> Result<ClaudeSettings, String> {
log::info!("Reading Claude settings");
let claude_dir = get_claude_dir().map_err(|e| e.to_string())?;
let settings_path = claude_dir.join("settings.json");
if !settings_path.exists() {
log::warn!("Settings file not found, returning empty settings");
return Ok(ClaudeSettings {
data: serde_json::json!({}),
});
}
let content = fs::read_to_string(&settings_path)
.map_err(|e| format!("Failed to read settings file: {}", e))?;
let data: serde_json::Value = serde_json::from_str(&content)
.map_err(|e| format!("Failed to parse settings JSON: {}", e))?;
Ok(ClaudeSettings { data })
}
/// Opens a new Claude Code session by executing the claude command
#[tauri::command]
pub async fn open_new_session(app: AppHandle, path: Option<String>) -> Result<String, String> {
log::info!("Opening new Claude Code session at path: {:?}", path);
#[cfg(not(debug_assertions))]
let _claude_path = find_claude_binary(&app)?;
#[cfg(debug_assertions)]
let claude_path = find_claude_binary(&app)?;
// In production, we can't use std::process::Command directly
// The user should launch Claude Code through other means or use the execute_claude_code command
#[cfg(not(debug_assertions))]
{
log::error!("Cannot spawn processes directly in production builds");
return Err("Direct process spawning is not available in production builds. Please use Claude Code directly or use the integrated execution commands.".to_string());
}
#[cfg(debug_assertions)]
{
let mut cmd = std::process::Command::new(claude_path);
// If a path is provided, use it; otherwise use current directory
if let Some(project_path) = path {
cmd.current_dir(&project_path);
}
// Execute the command
match cmd.spawn() {
Ok(_) => {
log::info!("Successfully launched Claude Code");
Ok("Claude Code session started".to_string())
}
Err(e) => {
log::error!("Failed to launch Claude Code: {}", e);
Err(format!("Failed to launch Claude Code: {}", e))
}
}
}
}
/// Reads the CLAUDE.md system prompt file
#[tauri::command]
pub async fn get_system_prompt() -> Result<String, String> {
log::info!("Reading CLAUDE.md system prompt");
let claude_dir = get_claude_dir().map_err(|e| e.to_string())?;
let claude_md_path = claude_dir.join("CLAUDE.md");
if !claude_md_path.exists() {
log::warn!("CLAUDE.md not found");
return Ok(String::new());
}
fs::read_to_string(&claude_md_path).map_err(|e| format!("Failed to read CLAUDE.md: {}", e))
}
/// Checks if Claude Code is installed and gets its version
#[tauri::command]
pub async fn check_claude_version(app: AppHandle) -> Result<ClaudeVersionStatus, String> {
log::info!("Checking Claude Code version");
let claude_path = match find_claude_binary(&app) {
Ok(path) => path,
Err(e) => {
return Ok(ClaudeVersionStatus {
is_installed: false,
version: None,
output: e,
});
}
};
// In production builds, we can't check the version directly
#[cfg(not(debug_assertions))]
{
log::warn!("Cannot check claude version in production build");
// If we found a path (either stored or in common locations), assume it's installed
if claude_path != "claude" && PathBuf::from(&claude_path).exists() {
return Ok(ClaudeVersionStatus {
is_installed: true,
version: None,
output: "Claude binary found at: ".to_string() + &claude_path,
});
} else {
return Ok(ClaudeVersionStatus {
is_installed: false,
version: None,
output: "Cannot verify Claude installation in production build. Please ensure Claude Code is installed.".to_string(),
});
}
}
#[cfg(debug_assertions)]
{
let output = std::process::Command::new(claude_path)
.arg("--version")
.output();
match output {
Ok(output) => {
let stdout = String::from_utf8_lossy(&output.stdout).to_string();
let stderr = String::from_utf8_lossy(&output.stderr).to_string();
let full_output = if stderr.is_empty() {
stdout.clone()
} else {
format!("{}\n{}", stdout, stderr)
};
// Check if the output matches the expected format
// Expected format: "1.0.17 (Claude Code)" or similar
let is_valid = stdout.contains("(Claude Code)") || stdout.contains("Claude Code");
// Extract version number if valid
let version = if is_valid {
// Try to extract just the version number
stdout.split_whitespace().next().map(|s| s.to_string())
} else {
None
};
Ok(ClaudeVersionStatus {
is_installed: is_valid && output.status.success(),
version,
output: full_output.trim().to_string(),
})
}
Err(e) => {
log::error!("Failed to run claude command: {}", e);
Ok(ClaudeVersionStatus {
is_installed: false,
version: None,
output: format!("Command not found: {}", e),
})
}
}
}
}
/// Saves the CLAUDE.md system prompt file
#[tauri::command]
pub async fn save_system_prompt(content: String) -> Result<String, String> {
log::info!("Saving CLAUDE.md system prompt");
let claude_dir = get_claude_dir().map_err(|e| e.to_string())?;
let claude_md_path = claude_dir.join("CLAUDE.md");
fs::write(&claude_md_path, content).map_err(|e| format!("Failed to write CLAUDE.md: {}", e))?;
Ok("System prompt saved successfully".to_string())
}
/// Saves the Claude settings file
#[tauri::command]
pub async fn save_claude_settings(settings: serde_json::Value) -> Result<String, String> {
log::info!("Saving Claude settings");
let claude_dir = get_claude_dir().map_err(|e| e.to_string())?;
let settings_path = claude_dir.join("settings.json");
// Pretty print the JSON with 2-space indentation
let json_string = serde_json::to_string_pretty(&settings)
.map_err(|e| format!("Failed to serialize settings: {}", e))?;
fs::write(&settings_path, json_string)
.map_err(|e| format!("Failed to write settings file: {}", e))?;
Ok("Settings saved successfully".to_string())
}
/// Recursively finds all CLAUDE.md files in a project directory
#[tauri::command]
pub async fn find_claude_md_files(project_path: String) -> Result<Vec<ClaudeMdFile>, String> {
log::info!("Finding CLAUDE.md files in project: {}", project_path);
let path = PathBuf::from(&project_path);
if !path.exists() {
return Err(format!("Project path does not exist: {}", project_path));
}
let mut claude_files = Vec::new();
find_claude_md_recursive(&path, &path, &mut claude_files)?;
// Sort by relative path
claude_files.sort_by(|a, b| a.relative_path.cmp(&b.relative_path));
log::info!("Found {} CLAUDE.md files", claude_files.len());
Ok(claude_files)
}
/// Helper function to recursively find CLAUDE.md files
fn find_claude_md_recursive(
current_path: &PathBuf,
project_root: &PathBuf,
claude_files: &mut Vec<ClaudeMdFile>,
) -> Result<(), String> {
let entries = fs::read_dir(current_path)
.map_err(|e| format!("Failed to read directory {:?}: {}", current_path, e))?;
for entry in entries {
let entry = entry.map_err(|e| format!("Failed to read directory entry: {}", e))?;
let path = entry.path();
// Skip hidden directories and files
if let Some(name) = path.file_name().and_then(|n| n.to_str()) {
if name.starts_with('.') && name != ".claude" {
continue;
}
}
if path.is_dir() {
// Skip common directories that shouldn't be scanned
if let Some(dir_name) = path.file_name().and_then(|n| n.to_str()) {
if matches!(
dir_name,
"node_modules" | "target" | ".git" | "dist" | "build" | ".next" | "__pycache__"
) {
continue;
}
}
// Recurse into subdirectory
find_claude_md_recursive(&path, project_root, claude_files)?;
} else if path.is_file() {
// Check if it's a CLAUDE.md file (case insensitive)
if let Some(file_name) = path.file_name().and_then(|n| n.to_str()) {
if file_name.eq_ignore_ascii_case("CLAUDE.md") {
let metadata = fs::metadata(&path)
.map_err(|e| format!("Failed to read file metadata: {}", e))?;
let relative_path = path
.strip_prefix(project_root)
.map_err(|e| format!("Failed to get relative path: {}", e))?
.to_string_lossy()
.to_string();
let modified = metadata
.modified()
.unwrap_or(SystemTime::UNIX_EPOCH)
.duration_since(SystemTime::UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
claude_files.push(ClaudeMdFile {
relative_path,
absolute_path: path.to_string_lossy().to_string(),
size: metadata.len(),
modified,
});
}
}
}
}
Ok(())
}
/// Reads a specific CLAUDE.md file by its absolute path
#[tauri::command]
pub async fn read_claude_md_file(file_path: String) -> Result<String, String> {
log::info!("Reading CLAUDE.md file: {}", file_path);
let path = PathBuf::from(&file_path);
if !path.exists() {
return Err(format!("File does not exist: {}", file_path));
}
fs::read_to_string(&path).map_err(|e| format!("Failed to read file: {}", e))
}
/// Saves a specific CLAUDE.md file by its absolute path
#[tauri::command]
pub async fn save_claude_md_file(file_path: String, content: String) -> Result<String, String> {
log::info!("Saving CLAUDE.md file: {}", file_path);
let path = PathBuf::from(&file_path);
// Ensure the parent directory exists
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)
.map_err(|e| format!("Failed to create parent directory: {}", e))?;
}
fs::write(&path, content).map_err(|e| format!("Failed to write file: {}", e))?;
Ok("File saved successfully".to_string())
}
/// Loads the JSONL history for a specific session
#[tauri::command]
pub async fn load_session_history(
session_id: String,
project_id: String,
) -> Result<Vec<serde_json::Value>, String> {
log::info!(
"Loading session history for session: {} in project: {}",
session_id,
project_id
);
let claude_dir = get_claude_dir().map_err(|e| e.to_string())?;
let session_path = claude_dir
.join("projects")
.join(&project_id)
.join(format!("{}.jsonl", session_id));
if !session_path.exists() {
return Err(format!("Session file not found: {}", session_id));
}
let file =
fs::File::open(&session_path).map_err(|e| format!("Failed to open session file: {}", e))?;
let reader = BufReader::new(file);
let mut messages = Vec::new();
for line in reader.lines() {
if let Ok(line) = line {
if let Ok(json) = serde_json::from_str::<serde_json::Value>(&line) {
messages.push(json);
}
}
}
Ok(messages)
}
/// Execute a new interactive Claude Code session with streaming output
#[tauri::command]
pub async fn execute_claude_code(
app: AppHandle,
project_path: String,
prompt: String,
model: String,
) -> Result<(), String> {
log::info!(
"Starting new Claude Code session in: {} with model: {}",
project_path,
model
);
// Check if sandboxing should be used
let use_sandbox = should_use_sandbox(&app)?;
let mut cmd = if use_sandbox {
create_sandboxed_claude_command(&app, &project_path)?
} else {
let claude_path = find_claude_binary(&app)?;
create_command_with_env(&claude_path)
};
cmd.arg("-p")
.arg(&prompt)
.arg("--model")
.arg(&model)
.arg("--output-format")
.arg("stream-json")
.arg("--verbose")
.arg("--dangerously-skip-permissions")
.current_dir(&project_path)
.stdout(Stdio::piped())
.stderr(Stdio::piped());
spawn_claude_process(app, cmd, prompt, model, project_path).await
}
/// Continue an existing Claude Code conversation with streaming output
#[tauri::command]
pub async fn continue_claude_code(
app: AppHandle,
project_path: String,
prompt: String,
model: String,
) -> Result<(), String> {
log::info!(
"Continuing Claude Code conversation in: {} with model: {}",
project_path,
model
);
// Check if sandboxing should be used
let use_sandbox = should_use_sandbox(&app)?;
let mut cmd = if use_sandbox {
create_sandboxed_claude_command(&app, &project_path)?
} else {
let claude_path = find_claude_binary(&app)?;
create_command_with_env(&claude_path)
};
cmd.arg("-c") // Continue flag
.arg("-p")
.arg(&prompt)
.arg("--model")
.arg(&model)
.arg("--output-format")
.arg("stream-json")
.arg("--verbose")
.arg("--dangerously-skip-permissions")
.current_dir(&project_path)
.stdout(Stdio::piped())
.stderr(Stdio::piped());
spawn_claude_process(app, cmd, prompt, model, project_path).await
}
/// Resume an existing Claude Code session by ID with streaming output
#[tauri::command]
pub async fn resume_claude_code(
app: AppHandle,
project_path: String,
session_id: String,
prompt: String,
model: String,
) -> Result<(), String> {
log::info!(
"Resuming Claude Code session: {} in: {} with model: {}",
session_id,
project_path,
model
);
// Check if sandboxing should be used
let use_sandbox = should_use_sandbox(&app)?;
let mut cmd = if use_sandbox {
create_sandboxed_claude_command(&app, &project_path)?
} else {
let claude_path = find_claude_binary(&app)?;
create_command_with_env(&claude_path)
};
cmd.arg("--resume")
.arg(&session_id)
.arg("-p")
.arg(&prompt)
.arg("--model")
.arg(&model)
.arg("--output-format")
.arg("stream-json")
.arg("--verbose")
.arg("--dangerously-skip-permissions")
.current_dir(&project_path)
.stdout(Stdio::piped())
.stderr(Stdio::piped());
spawn_claude_process(app, cmd, prompt, model, project_path).await
}
/// Cancel the currently running Claude Code execution
#[tauri::command]
pub async fn cancel_claude_execution(
app: AppHandle,
session_id: Option<String>,
) -> Result<(), String> {
log::info!(
"Cancelling Claude Code execution for session: {:?}",
session_id
);
let killed = if let Some(sid) = &session_id {
// Try to find and kill via ProcessRegistry first
let registry = app.state::<crate::process::ProcessRegistryState>();
if let Ok(Some(process_info)) = registry.0.get_claude_session_by_id(sid) {
match registry.0.kill_process(process_info.run_id).await {
Ok(success) => success,
Err(e) => {
log::warn!("Failed to kill via registry: {}", e);
false
}
}
} else {
false
}
} else {
false
};
// If registry kill didn't work, try the legacy approach
if !killed {
let claude_state = app.state::<ClaudeProcessState>();
let mut current_process = claude_state.current_process.lock().await;
if let Some(mut child) = current_process.take() {
// Try to get the PID before killing
let pid = child.id();
log::info!("Attempting to kill Claude process with PID: {:?}", pid);
// Kill the process
match child.kill().await {
Ok(_) => {
log::info!("Successfully killed Claude process");
}
Err(e) => {
log::error!("Failed to kill Claude process: {}", e);
return Err(format!("Failed to kill Claude process: {}", e));
}
}
} else {
log::warn!("No active Claude process to cancel");
}
}
// Emit cancellation events
if let Some(sid) = session_id {
let _ = app.emit(&format!("claude-cancelled:{}", sid), true);
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
let _ = app.emit(&format!("claude-complete:{}", sid), false);
}
// Also emit generic events for backward compatibility
let _ = app.emit("claude-cancelled", true);
tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
let _ = app.emit("claude-complete", false);
Ok(())
}
/// Get all running Claude sessions
#[tauri::command]
pub async fn list_running_claude_sessions(
registry: tauri::State<'_, crate::process::ProcessRegistryState>,
) -> Result<Vec<crate::process::ProcessInfo>, String> {
registry.0.get_running_claude_sessions()
}
/// Get live output from a Claude session
#[tauri::command]
pub async fn get_claude_session_output(
registry: tauri::State<'_, crate::process::ProcessRegistryState>,
session_id: String,
) -> Result<String, String> {
// Find the process by session ID
if let Some(process_info) = registry.0.get_claude_session_by_id(&session_id)? {
registry.0.get_live_output(process_info.run_id)
} else {
Ok(String::new())
}
}
/// Helper function to check if sandboxing should be used based on settings