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
//! Agent task spawning for Iris Studio
//!
//! Contains all async task spawning functions for Iris agent operations.
use crate::types::GeneratedMessage;
use super::{ChatUpdateType, IrisTaskResult, StudioApp};
use crate::studio::events::{BlameInfo, SemanticBlameResult, TaskType};
impl StudioApp {
// ═══════════════════════════════════════════════════════════════════════════════
// Generic Structured Task Spawner
// ═══════════════════════════════════════════════════════════════════════════════
/// Spawn a structured (non-streaming) agent task.
///
/// Handles the common pattern shared by review, PR, changelog, and release notes:
/// agent availability check → status messages → `tokio::spawn` → result channel.
fn spawn_structured_task<F, Fut>(
&self,
task_type: TaskType,
agent_task: &super::super::events::AgentTask,
task_fn: F,
) where
F: FnOnce(std::sync::Arc<crate::agents::IrisAgentService>) -> Fut + Send + 'static,
Fut: std::future::Future<Output = IrisTaskResult> + Send,
{
let Some(agent) = self.agent_service.clone() else {
let tx = self.iris_result_tx.clone();
let _ = tx.send(IrisTaskResult::Error {
task_type,
error: "Agent service not available".to_string(),
});
return;
};
self.spawn_status_messages(agent_task);
let tx = self.iris_result_tx.clone();
tokio::spawn(async move {
let result = task_fn(agent).await;
let _ = tx.send(result);
});
}
// ═══════════════════════════════════════════════════════════════════════════════
// Chat Query
// ═══════════════════════════════════════════════════════════════════════════════
/// Spawn a task for chat query - uses Iris agent with chat capability
pub(super) fn spawn_chat_query(
&self,
message: String,
context: crate::studio::events::ChatContext,
) {
use super::super::events::AgentTask;
use crate::agents::StructuredResponse;
use crate::agents::status::IRIS_STATUS;
use crate::agents::tools::{ContentUpdate, create_content_update_channel};
use crate::studio::state::{ChatMessage, ChatRole};
use tokio_util::sync::CancellationToken;
let Some(agent) = self.agent_service.clone() else {
let tx = self.iris_result_tx.clone();
let _ = tx.send(IrisTaskResult::ChatResponse(
"Agent service not available".to_string(),
));
return;
};
// Spawn dynamic status messages
let task = AgentTask::Chat {
message: message.clone(),
context: context.clone(),
};
self.spawn_status_messages(&task);
// Create bounded content update channel for tool-based updates
let (content_tx, mut content_rx) = create_content_update_channel();
// Capture context before spawning async task
let tx = self.iris_result_tx.clone();
let tx_status = self.iris_result_tx.clone();
let tx_updates = self.iris_result_tx.clone();
let mode = context.mode;
// Extract conversation history (convert VecDeque → Vec)
let chat_history: Vec<ChatMessage> =
self.state.chat_state.messages.iter().cloned().collect();
// Use context content if provided, otherwise extract from state
let current_content = context
.current_content
.or_else(|| self.get_current_content_for_chat());
// Cancellation token to signal when the main task is done
let cancel_token = CancellationToken::new();
let cancel_status = cancel_token.clone();
let cancel_updates = cancel_token.clone();
// Spawn a status polling task (polls global state, so still uses interval)
tokio::spawn(async move {
use crate::agents::status::IrisPhase;
let mut last_tool: Option<String> = None;
let mut interval = tokio::time::interval(tokio::time::Duration::from_millis(100));
loop {
tokio::select! {
() = cancel_status.cancelled() => break,
_ = interval.tick() => {
let status = IRIS_STATUS.get_current();
// Check if we're in a tool execution phase
if let IrisPhase::ToolExecution {
ref tool_name,
ref reason,
} = status.phase
{
// Only send if it's a new tool
if last_tool.as_ref() != Some(tool_name) {
let _ = tx_status.send(IrisTaskResult::ToolStatus {
tool_name: tool_name.clone(),
message: reason.clone(),
});
last_tool = Some(tool_name.clone());
}
}
}
}
}
});
// Spawn a task to listen for content updates from tools (uses select! for zero latency)
tokio::spawn(async move {
loop {
tokio::select! {
() = cancel_updates.cancelled() => break,
update = content_rx.recv() => {
let Some(update) = update else { break };
let chat_update = match update {
ContentUpdate::Commit {
emoji,
title,
message,
} => {
tracing::info!("Content update tool: commit - {}", title);
ChatUpdateType::CommitMessage(GeneratedMessage {
emoji,
title,
message,
completion_message: None,
})
}
ContentUpdate::PR { content } => {
tracing::info!("Content update tool: PR");
ChatUpdateType::PRDescription(content)
}
ContentUpdate::Review { content } => {
tracing::info!("Content update tool: review");
ChatUpdateType::Review(content)
}
};
let _ = tx_updates.send(IrisTaskResult::ChatUpdate(chat_update));
}
}
}
});
tokio::spawn(async move {
// Build comprehensive context (universal chat across all modes)
let mode_context = format!(
"Current Mode: {:?}\nYou are Iris, a helpful git assistant. You have access to all generated content across modes and can help with commit messages, PR descriptions, code reviews, changelogs, and release notes.",
mode
);
// Build conversation history string
let history_str = if chat_history.is_empty() {
String::new()
} else {
let mut hist = String::from("\n## Conversation History\n");
for msg in &chat_history {
match msg.role {
ChatRole::User => hist.push_str(&format!("User: {}\n", msg.content)),
ChatRole::Iris => hist.push_str(&format!("Iris: {}\n", msg.content)),
}
}
hist
};
// Build current content section
let content_section = if let Some(content) = ¤t_content {
format!("\n## Current Content\n```\n{}\n```\n", content)
} else {
String::new()
};
// Tool-based update instructions
let update_instructions = r"
## Response Guidelines
- Be concise - don't repeat content the user already sees
- When updating content, briefly explain what you changed
## Content Update Tools
You have tools to update content. When the user asks you to modify, change, update, or rewrite content:
1. **update_commit** - Update the commit message (emoji, title, message)
2. **update_pr** - Update the PR description (content)
3. **update_review** - Update the code review (content)
Simply call the appropriate tool with the new content. Do NOT echo back the full content in your response - the tool will update it directly.";
let prompt = format!(
"{}{}{}{}\n\n## Current Request\nUser: {}",
mode_context, content_section, history_str, update_instructions, message
);
// Execute with streaming and content update tools
let streaming_tx = tx.clone();
let on_chunk = move |chunk: &str, aggregated: &str| {
let _ = streaming_tx.send(IrisTaskResult::StreamingChunk {
task_type: TaskType::Chat,
chunk: chunk.to_string(),
aggregated: aggregated.to_string(),
});
};
match agent
.execute_chat_streaming(&prompt, content_tx, on_chunk)
.await
{
Ok(response) => {
// Signal streaming complete
let _ = tx.send(IrisTaskResult::StreamingComplete {
task_type: TaskType::Chat,
});
let text = match response {
StructuredResponse::PlainText(text) => text,
other => other.to_string(),
};
tracing::debug!("Chat response received, length: {}", text.len());
let _ = tx.send(IrisTaskResult::ChatResponse(text));
}
Err(e) => {
let _ = tx.send(IrisTaskResult::ChatResponse(format!(
"I encountered an error: {}",
e
)));
}
}
// Signal that we're done so the helper tasks stop
cancel_token.cancel();
});
}
/// Get ALL generated content for chat context (universal across modes)
pub(super) fn get_current_content_for_chat(&self) -> Option<String> {
let mut sections = Vec::new();
// Commit message
let commit = &self.state.modes.commit;
if let Some(msg) = commit.messages.get(commit.current_index) {
let formatted = crate::types::format_commit_message(msg);
if !formatted.trim().is_empty() {
sections.push(format!("## Commit Message\n{}", formatted));
}
}
// Code review
let review = &self.state.modes.review.review_content;
if !review.is_empty() {
let preview = if review.len() > 500 {
format!("{}...", &review[..500])
} else {
review.clone()
};
sections.push(format!("## Code Review\n{}", preview));
}
// PR description
let pr = &self.state.modes.pr.pr_content;
if !pr.is_empty() {
let preview = if pr.len() > 500 {
format!("{}...", &pr[..500])
} else {
pr.clone()
};
sections.push(format!("## PR Description\n{}", preview));
}
// Changelog
let cl = &self.state.modes.changelog.changelog_content;
if !cl.is_empty() {
let preview = if cl.len() > 500 {
format!("{}...", &cl[..500])
} else {
cl.clone()
};
sections.push(format!("## Changelog\n{}", preview));
}
// Release notes
let rn = &self.state.modes.release_notes.release_notes_content;
if !rn.is_empty() {
let preview = if rn.len() > 500 {
format!("{}...", &rn[..500])
} else {
rn.clone()
};
sections.push(format!("## Release Notes\n{}", preview));
}
if sections.is_empty() {
None
} else {
Some(sections.join("\n\n"))
}
}
// ═══════════════════════════════════════════════════════════════════════════════
// Review Generation
// ═══════════════════════════════════════════════════════════════════════════════
/// Spawn a task for code review generation
pub(super) fn spawn_review_generation(&self, from_ref: String, to_ref: String) {
use super::super::events::AgentTask;
use crate::agents::{StructuredResponse, TaskContext};
let task = AgentTask::Review {
from_ref: from_ref.clone(),
to_ref: to_ref.clone(),
};
self.spawn_structured_task(TaskType::Review, &task, move |agent| async move {
let context = match TaskContext::for_review(None, Some(from_ref), Some(to_ref), false) {
Ok(ctx) => ctx,
Err(e) => {
return IrisTaskResult::Error {
task_type: TaskType::Review,
error: format!("Context error: {e}"),
};
}
};
match agent.execute_task("review", context).await {
Ok(response) => {
let text = match response {
StructuredResponse::MarkdownReview(r) => r.content,
StructuredResponse::PlainText(t) => t,
other => other.to_string(),
};
IrisTaskResult::ReviewContent(text)
}
Err(e) => IrisTaskResult::Error {
task_type: TaskType::Review,
error: format!("Review error: {e}"),
},
}
});
}
// ═══════════════════════════════════════════════════════════════════════════════
// PR Generation
// ═══════════════════════════════════════════════════════════════════════════════
/// Spawn a task for PR description generation
pub(super) fn spawn_pr_generation(&self, base_branch: String, to_ref: &str) {
use super::super::events::AgentTask;
use crate::agents::{StructuredResponse, TaskContext};
let to_ref = to_ref.to_string();
let task = AgentTask::PR {
base_branch: base_branch.clone(),
to_ref: to_ref.clone(),
};
self.spawn_structured_task(TaskType::PR, &task, move |agent| async move {
let context = TaskContext::for_pr(Some(base_branch), Some(to_ref));
match agent.execute_task("pr", context).await {
Ok(response) => {
let text = match response {
StructuredResponse::PullRequest(pr) => pr.content,
StructuredResponse::PlainText(t) => t,
other => other.to_string(),
};
IrisTaskResult::PRContent(text)
}
Err(e) => IrisTaskResult::Error {
task_type: TaskType::PR,
error: format!("PR error: {e}"),
},
}
});
}
// ═══════════════════════════════════════════════════════════════════════════════
// Changelog Generation
// ═══════════════════════════════════════════════════════════════════════════════
/// Spawn a task for changelog generation
pub(super) fn spawn_changelog_generation(&self, from_ref: String, to_ref: String) {
use super::super::events::AgentTask;
use crate::agents::{StructuredResponse, TaskContext};
let task = AgentTask::Changelog {
from_ref: from_ref.clone(),
to_ref: to_ref.clone(),
};
self.spawn_structured_task(TaskType::Changelog, &task, move |agent| async move {
let context = TaskContext::for_changelog(from_ref, Some(to_ref), None, None);
match agent.execute_task("changelog", context).await {
Ok(response) => {
let text = match response {
StructuredResponse::Changelog(cl) => cl.content,
StructuredResponse::PlainText(t) => t,
other => other.to_string(),
};
IrisTaskResult::ChangelogContent(text)
}
Err(e) => IrisTaskResult::Error {
task_type: TaskType::Changelog,
error: format!("Changelog error: {e}"),
},
}
});
}
// ═══════════════════════════════════════════════════════════════════════════════
// Release Notes Generation
// ═══════════════════════════════════════════════════════════════════════════════
/// Spawn a task for release notes generation
pub(super) fn spawn_release_notes_generation(&self, from_ref: String, to_ref: String) {
use super::super::events::AgentTask;
use crate::agents::{StructuredResponse, TaskContext};
let task = AgentTask::ReleaseNotes {
from_ref: from_ref.clone(),
to_ref: to_ref.clone(),
};
self.spawn_structured_task(TaskType::ReleaseNotes, &task, move |agent| async move {
let context = TaskContext::for_changelog(from_ref, Some(to_ref), None, None);
match agent.execute_task("release_notes", context).await {
Ok(response) => {
let text = match response {
StructuredResponse::ReleaseNotes(rn) => rn.content,
StructuredResponse::PlainText(t) => t,
other => other.to_string(),
};
IrisTaskResult::ReleaseNotesContent(text)
}
Err(e) => IrisTaskResult::Error {
task_type: TaskType::ReleaseNotes,
error: format!("Release notes error: {e}"),
},
}
});
}
// ═══════════════════════════════════════════════════════════════════════════════
// Commit Generation
// ═══════════════════════════════════════════════════════════════════════════════
/// Spawn a task to generate a commit message
pub(super) fn spawn_commit_generation(
&self,
instructions: Option<String>,
preset: String,
use_gitmoji: bool,
amend: bool,
) {
use super::super::events::AgentTask;
use crate::agents::{StructuredResponse, TaskContext};
let Some(agent) = self.agent_service.clone() else {
let tx = self.iris_result_tx.clone();
let _ = tx.send(IrisTaskResult::Error {
task_type: TaskType::Commit,
error: "Agent service not available".to_string(),
});
return;
};
// Spawn dynamic status messages
let task = AgentTask::Commit {
instructions: instructions.clone(),
preset: preset.clone(),
use_gitmoji,
amend,
};
self.spawn_status_messages(&task);
// Get original message for amend mode
let original_message = if amend {
self.state
.repo
.as_ref()
.and_then(|r| r.get_head_commit_message().ok())
.unwrap_or_default()
} else {
String::new()
};
let tx = self.iris_result_tx.clone();
tokio::spawn(async move {
// Use amend context if amending, otherwise standard commit context
let context = if amend {
TaskContext::for_amend(original_message)
} else {
TaskContext::for_gen()
};
// Execute commit capability with style overrides
let preset_opt = if preset == "default" {
None
} else {
Some(preset.as_str())
};
match agent
.execute_task_with_style(
"commit",
context,
preset_opt,
Some(use_gitmoji),
instructions.as_deref(),
)
.await
{
Ok(response) => {
// Extract message from response
match response {
StructuredResponse::CommitMessage(msg) => {
let _ = tx.send(IrisTaskResult::CommitMessages(vec![msg]));
}
_ => {
let _ = tx.send(IrisTaskResult::Error {
task_type: TaskType::Commit,
error: "Unexpected response type from agent".to_string(),
});
}
}
}
Err(e) => {
let _ = tx.send(IrisTaskResult::Error {
task_type: TaskType::Commit,
error: format!("Agent error: {}", e),
});
}
}
});
}
// ═══════════════════════════════════════════════════════════════════════════════
// Semantic Blame
// ═══════════════════════════════════════════════════════════════════════════════
/// Gather blame information from git and spawn the semantic blame agent.
/// All blocking I/O (file read, git blame) runs in a background task to avoid
/// blocking the UI event loop.
pub(super) fn gather_blame_and_spawn(
&self,
file: &std::path::Path,
start_line: usize,
end_line: usize,
) {
use crate::agents::StructuredResponse;
let Some(repo) = &self.state.repo else {
let tx = self.iris_result_tx.clone();
let _ = tx.send(IrisTaskResult::Error {
task_type: TaskType::SemanticBlame,
error: "Repository not available".to_string(),
});
return;
};
let Some(agent) = self.agent_service.clone() else {
let tx = self.iris_result_tx.clone();
let _ = tx.send(IrisTaskResult::Error {
task_type: TaskType::SemanticBlame,
error: "Agent service not available".to_string(),
});
return;
};
// Clone values needed in the async task
let tx = self.iris_result_tx.clone();
let file = file.to_path_buf();
let repo_path = repo.repo_path().clone();
tokio::spawn(async move {
// Run blocking I/O in spawn_blocking to avoid blocking the tokio runtime
let blame_result = tokio::task::spawn_blocking(move || {
use std::fs;
use std::process::Command;
// Read file content
let content = fs::read_to_string(&file)?;
let lines: Vec<&str> = content.lines().collect();
if start_line == 0 || start_line > lines.len() {
return Err(anyhow::anyhow!("Invalid line range"));
}
let end = end_line.min(lines.len());
let code_content = lines[(start_line - 1)..end].join("\n");
// Run git blame
let output = Command::new("git")
.args([
"-C",
&repo_path.to_string_lossy(),
"blame",
"-L",
&format!("{},{}", start_line, end_line),
"--porcelain",
&file.to_string_lossy(),
])
.output()?;
if !output.status.success() {
let err = String::from_utf8_lossy(&output.stderr);
return Err(anyhow::anyhow!("Git blame failed: {}", err));
}
let blame_output = String::from_utf8_lossy(&output.stdout);
let (commit_hash, author, commit_date, commit_message) =
parse_blame_porcelain(&blame_output);
Ok(BlameInfo {
file,
start_line,
end_line,
commit_hash,
author,
commit_date,
commit_message,
code_content,
})
})
.await;
// Handle spawn_blocking result
let blame_info = match blame_result {
Ok(Ok(info)) => info,
Ok(Err(e)) => {
let _ = tx.send(IrisTaskResult::Error {
task_type: TaskType::SemanticBlame,
error: e.to_string(),
});
return;
}
Err(e) => {
let _ = tx.send(IrisTaskResult::Error {
task_type: TaskType::SemanticBlame,
error: format!("Task panicked: {}", e),
});
return;
}
};
// Build context for agent
let context_text = format!(
"File: {}\nLines: {}-{}\nCommit: {} by {} on {}\nMessage: {}\n\nCode:\n{}",
blame_info.file.display(),
blame_info.start_line,
blame_info.end_line,
blame_info.commit_hash,
blame_info.author,
blame_info.commit_date,
blame_info.commit_message,
blame_info.code_content
);
// Execute semantic_blame capability
match agent
.execute_task_with_prompt("semantic_blame", &context_text)
.await
{
Ok(response) => match response {
StructuredResponse::SemanticBlame(explanation) => {
let result = SemanticBlameResult {
file: blame_info.file,
start_line: blame_info.start_line,
end_line: blame_info.end_line,
commit_hash: blame_info.commit_hash,
author: blame_info.author,
commit_date: blame_info.commit_date,
commit_message: blame_info.commit_message,
explanation,
};
let _ = tx.send(IrisTaskResult::SemanticBlame(result));
}
_ => {
let _ = tx.send(IrisTaskResult::Error {
task_type: TaskType::SemanticBlame,
error: "Unexpected response type from agent".to_string(),
});
}
},
Err(e) => {
let _ = tx.send(IrisTaskResult::Error {
task_type: TaskType::SemanticBlame,
error: format!("Semantic blame error: {}", e),
});
}
}
});
}
/// Spawn the semantic blame agent to explain why the code exists.
/// Used when blame info is already collected (e.g., from `AgentTask::SemanticBlame`).
pub(super) fn spawn_semantic_blame(&self, blame_info: BlameInfo) {
use super::super::events::AgentTask;
use crate::agents::StructuredResponse;
let Some(agent) = self.agent_service.clone() else {
let tx = self.iris_result_tx.clone();
let _ = tx.send(IrisTaskResult::Error {
task_type: TaskType::SemanticBlame,
error: "Agent service not available".to_string(),
});
return;
};
// Spawn dynamic status messages
let task = AgentTask::SemanticBlame {
blame_info: blame_info.clone(),
};
self.spawn_status_messages(&task);
let tx = self.iris_result_tx.clone();
tokio::spawn(async move {
// Build context with blame info
let context_text = format!(
"File: {}\nLines: {}-{}\nCommit: {} by {} on {}\nMessage: {}\n\nCode:\n{}",
blame_info.file.display(),
blame_info.start_line,
blame_info.end_line,
blame_info.commit_hash,
blame_info.author,
blame_info.commit_date,
blame_info.commit_message,
blame_info.code_content
);
// Execute semantic_blame capability
match agent
.execute_task_with_prompt("semantic_blame", &context_text)
.await
{
Ok(response) => match response {
StructuredResponse::SemanticBlame(explanation) => {
let result = SemanticBlameResult {
file: blame_info.file,
start_line: blame_info.start_line,
end_line: blame_info.end_line,
commit_hash: blame_info.commit_hash,
author: blame_info.author,
commit_date: blame_info.commit_date,
commit_message: blame_info.commit_message,
explanation,
};
let _ = tx.send(IrisTaskResult::SemanticBlame(result));
}
_ => {
let _ = tx.send(IrisTaskResult::Error {
task_type: TaskType::SemanticBlame,
error: "Unexpected response type from agent".to_string(),
});
}
},
Err(e) => {
let _ = tx.send(IrisTaskResult::Error {
task_type: TaskType::SemanticBlame,
error: format!("Semantic blame error: {}", e),
});
}
}
});
}
}
// ═══════════════════════════════════════════════════════════════════════════════
// Helper Functions
// ═══════════════════════════════════════════════════════════════════════════════
/// Parse git blame porcelain output to extract commit info
fn parse_blame_porcelain(output: &str) -> (String, String, String, String) {
let mut commit_hash = String::new();
let mut author = String::new();
let mut commit_time = String::new();
let mut summary = String::new();
for line in output.lines() {
if commit_hash.is_empty()
&& line.len() >= 40
&& line.chars().take(40).all(|c| c.is_ascii_hexdigit())
{
commit_hash = line.split_whitespace().next().unwrap_or("").to_string();
} else if let Some(rest) = line.strip_prefix("author ") {
author = rest.to_string();
} else if let Some(rest) = line.strip_prefix("author-time ") {
if let Ok(timestamp) = rest.parse::<i64>() {
commit_time = chrono::DateTime::from_timestamp(timestamp, 0).map_or_else(
|| "Unknown date".to_string(),
|dt| dt.format("%Y-%m-%d %H:%M").to_string(),
);
}
} else if let Some(rest) = line.strip_prefix("summary ") {
summary = rest.to_string();
}
}
if commit_hash.is_empty() {
commit_hash = "Unknown".to_string();
}
if author.is_empty() {
author = "Unknown".to_string();
}
if commit_time.is_empty() {
commit_time = "Unknown date".to_string();
}
(commit_hash, author, commit_time, summary)
}