Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)

Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
  nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
andrea.difonzo
2026-11-17 12:37:52 +01:00
parent e37a0deba9
commit 7c1c6dfa8d
10306 changed files with 748026 additions and 748088 deletions

View File

@@ -0,0 +1,65 @@
//! Attach transparent page-boundary details to a freshly rebuilt activity group.
use crate::exec_cell::ExecCell;
use crate::history_cell::ComputerActivityCell;
use crate::history_cell::HistoryCell;
use crate::history_cell::ReasoningSummaryCell;
use std::sync::Arc;
#[allow(dead_code, reason = "Used by later layers of the TUI refresh stack.")]
pub(crate) fn is_hidden_activity_detail(cell: &Arc<dyn HistoryCell>) -> bool {
cell.as_any()
.downcast_ref::<ReasoningSummaryCell>()
.is_some_and(ReasoningSummaryCell::is_transcript_only)
}
/// Fold standalone reasoning using exact persisted identities from one turn.
///
/// An older page can arrive after the final reasoning page even with no newer group or live tail.
/// Rebuild only known completed calls and share their immutable details; never infer adjacency
/// from identical reasoning text or attach a detail from the next turn.
#[allow(dead_code, reason = "Used by later layers of the TUI refresh stack.")]
pub(crate) fn fold_trailing_activity_details(
older: &Arc<dyn HistoryCell>,
details: &[Arc<dyn HistoryCell>],
turns: &[akode_app_server_protocol::Turn],
) -> Option<Arc<dyn HistoryCell>> {
let (mut ids, retained) =
if let Some(group) = older.as_any().downcast_ref::<ComputerActivityCell>() {
(group.call_ids().collect::<Vec<_>>(), &group.group.details)
} else {
let group = older.as_any().downcast_ref::<ExecCell>()?;
if !group.is_exploring_cell() || group.should_flush() {
return None;
}
(
group
.iter_calls()
.map(|call| call.call_id.as_str())
.collect::<Vec<_>>(),
&group.group.details,
)
};
let count = ids.len();
for detail in details {
let detail = detail.as_any().downcast_ref::<ReasoningSummaryCell>()?;
if !detail.is_transcript_only() {
return None;
}
ids.push(detail.source_item_id()?);
}
let items = super::computer_groups::adjacent_activity_items(&ids, turns)?;
let mut retained = retained.clone();
for detail in details {
retained.push(count, Arc::clone(detail));
}
if older.as_any().is::<ComputerActivityCell>() {
let mut group = super::computer_groups::completed_group(items)?;
group.group.details = retained;
Some(Arc::new(group))
} else {
let mut group = super::exploration_groups::completed_group(items)?;
group.group.details = retained;
Some(Arc::new(group))
}
}

View File

@@ -0,0 +1,109 @@
//! Assemble computer activity across hidden reasoning and repair history-page group boundaries.
use super::tools::McpHistory;
use crate::history_cell::ComputerActivityCell;
use crate::history_cell::HistoryCell;
use crate::history_cell::McpToolCallCell;
use akode_app_server_protocol::ThreadItemPayload;
use akode_app_server_protocol::Turn;
use std::sync::Arc;
pub(super) fn append(group: &mut ComputerActivityCell, call: McpHistory) {
let cell = McpToolCallCell::new(call.id, call.invocation, /*animations_enabled*/ false);
group.complete(cell, call.duration, call.result);
}
/// Rebuild only an adjacent computer group, using its persisted IDs to verify the turn boundary.
pub(crate) fn join_computer_groups(
older: &Arc<dyn HistoryCell>,
newer: &Arc<dyn HistoryCell>,
turns: &[Turn],
) -> Option<Arc<dyn HistoryCell>> {
let older = older.as_any().downcast_ref::<ComputerActivityCell>()?;
let newer = newer.as_any().downcast_ref::<ComputerActivityCell>()?;
let mut group = completed_group(adjacent_items(older, newer, turns)?)?;
group.group.details = newer.group.details.clone();
group
.group
.details
.prepend(older.group.details.clone(), older.call_ids().count());
Some(Arc::new(group))
}
/// Restore only the older half; the caller retains the live half and its pending calls/timers.
pub(crate) fn older_computer_group(
older: &dyn HistoryCell,
newer: &ComputerActivityCell,
turns: &[Turn],
) -> Option<ComputerActivityCell> {
let older = older.as_any().downcast_ref::<ComputerActivityCell>()?;
let items = adjacent_items(older, newer, turns)?;
let older_items = items
.iter()
.filter(|entry| !matches!(&entry.payload, ThreadItemPayload::Reasoning { .. }))
.take(older.call_ids().count())
.cloned()
.collect::<Vec<_>>();
let mut group = completed_group(&older_items)?;
group.group.details = older.group.details.clone();
Some(group)
}
fn adjacent_items<'a>(
older: &ComputerActivityCell,
newer: &ComputerActivityCell,
turns: &'a [Turn],
) -> Option<&'a [akode_app_server_protocol::ThreadItem]> {
let ids = older.call_ids().chain(newer.call_ids()).collect::<Vec<_>>();
adjacent_activity_items(&ids, turns)
}
/// Validate source adjacency without mistaking invisible reasoning for an activity boundary.
pub(super) fn adjacent_activity_items<'a>(
ids: &[&str],
turns: &'a [Turn],
) -> Option<&'a [akode_app_server_protocol::ThreadItem]> {
let first = *ids.first()?;
let (turn, start) = turns.iter().find_map(|turn| {
turn.items
.iter()
.position(|item| item.id() == first)
.map(|start| (turn, start))
})?;
let mut matched = 0;
for (offset, item) in turn.item_payloads().skip(start).enumerate() {
if item.id() != ids[matched] {
if matches!(item, ThreadItemPayload::Reasoning { .. }) {
continue;
}
return None;
}
matched += 1;
if matched == ids.len() {
return Some(&turn.items[start..=start + offset]);
}
}
None
}
pub(super) fn completed_group(
items: &[akode_app_server_protocol::ThreadItem],
) -> Option<ComputerActivityCell> {
let mut group = None;
for entry in items {
let item = &entry.payload;
if matches!(item, ThreadItemPayload::Reasoning { .. }) {
continue;
}
let call = McpHistory::from_item(item.clone())?;
if !call.invocation.is_computer_activity() {
return None;
}
append(group.get_or_insert_default(), call);
}
group
}
#[cfg(test)]
#[path = "computer_groups_tests.rs"]
mod tests;

View File

@@ -0,0 +1,176 @@
//! Page boundaries must not change the compact or expanded rendering of computer activity.
use super::*;
use crate::thread_transcript::RawReasoningVisibility;
use crate::thread_transcript::TranscriptCells;
use crate::thread_transcript::thread_items_to_transcript_cells;
use akode_app_server_protocol::ThreadItem;
use akode_app_server_protocol::ThreadItemPayload;
use akode_app_server_protocol::TurnItemsView;
use akode_app_server_protocol::TurnStatus;
use akode_utils_absolute_path::AbsolutePathBuf;
use pretty_assertions::assert_eq;
fn computer(id: &str) -> ThreadItemPayload {
serde_json::from_value(serde_json::json!({
"type": "mcpToolCall", "id": id, "server": "cua_repl", "tool": "js",
"status": "completed", "arguments": {"title": format!("Inspect {id}"), "code": "await cua.getState()"},
"appContext": null, "pluginId": null, "readOnlyHint": null,
"result": {"content": [{"type": "text", "text": format!("Result {id}")}], "structuredContent": null},
"error": null, "durationMs": 10
})).unwrap()
}
fn turn(id: &str, items: Vec<ThreadItemPayload>) -> Turn {
Turn {
id: id.to_string(),
root_turn_id: None,
items: items.into_iter().map(ThreadItem::untimed).collect(),
items_view: TurnItemsView::Full,
status: TurnStatus::Completed,
error: None,
started_at: None,
completed_at: None,
duration_ms: None,
}
}
fn project(items: &[impl std::borrow::Borrow<ThreadItemPayload>]) -> TranscriptCells {
thread_items_to_transcript_cells(
/*thread_id*/ None,
&AbsolutePathBuf::current_dir().unwrap(),
items.iter().map(|entry| entry.borrow().clone()),
RawReasoningVisibility::Hidden,
/*config*/ None,
)
}
#[test]
fn every_page_split_retains_the_same_rich_computer_group() {
let turns = vec![turn(
"turn",
vec![
computer("first"),
ThreadItemPayload::Reasoning {
id: "reasoning-first".to_owned(),
summary: vec!["Inspect the second screen".to_owned()],
content: Vec::new(),
},
computer("second"),
computer("third"),
ThreadItemPayload::Reasoning {
id: "reasoning-second".to_owned(),
summary: vec!["Confirm the final screen".to_owned()],
content: Vec::new(),
},
computer("last"),
],
)];
let items = &turns[0].items;
let expected = project(items);
for split in 1..items.len() {
let older = project(&items[..split]);
let newer = project(&items[split..]);
let detail_count = newer
.iter()
.take_while(|cell| {
crate::thread_transcript::activity_pages::is_hidden_activity_detail(cell)
})
.count();
let older_group = if detail_count > 0 {
crate::thread_transcript::activity_pages::fold_trailing_activity_details(
&older[0],
&newer[..detail_count],
&turns,
)
.unwrap()
} else {
Arc::clone(&older[0])
};
let joined = join_computer_groups(&older_group, &newer[detail_count], &turns).unwrap();
assert_eq!(
joined.display_hyperlink_lines(/*width*/ 30),
expected[0].display_hyperlink_lines(/*width*/ 30)
);
assert_eq!(
joined.transcript_hyperlink_lines(/*width*/ 30),
expected[0].transcript_hyperlink_lines(/*width*/ 30)
);
assert_eq!(joined.raw_lines(), expected[0].raw_lines());
}
}
#[test]
fn successive_single_item_pages_reunite_without_duplicating_calls() {
let turns = vec![turn(
"turn",
(0..6).map(|i| computer(&i.to_string())).collect(),
)];
let items = &turns[0].items;
let mut joined = project(&items[5..]).remove(/*index*/ 0);
for item in items[..5].iter().rev() {
let older = project(std::slice::from_ref(item));
joined = join_computer_groups(&older[0], &joined, &turns).unwrap();
}
let expected = project(items);
assert_eq!(
joined.transcript_lines(/*width*/ 80),
expected[0].transcript_lines(/*width*/ 80)
);
}
#[test]
fn joins_respect_actual_turns_and_intervening_items() {
let first = computer("first");
let last = computer("last");
let older = project(std::slice::from_ref(&first));
let newer = project(std::slice::from_ref(&last));
let turns = vec![
turn("first-turn", vec![first.clone()]),
turn("last-turn", vec![last.clone()]),
];
assert!(join_computer_groups(&older[0], &newer[0], &turns).is_none());
let grouped = project(&[
first.clone(),
ThreadItemPayload::Sleep(akode_app_server_protocol::SleepItem {
id: "sleep".into(),
duration_ms: 10,
}),
last.clone(),
]);
let adjacent = project(&[first.clone(), last.clone()]);
assert_eq!(grouped.len(), 1);
assert_eq!(
grouped[0].transcript_lines(/*width*/ 80),
adjacent[0].transcript_lines(/*width*/ 80)
);
let mut turns = vec![turn(
"turn",
vec![
first,
ThreadItemPayload::Reasoning {
id: "reasoning".to_string(),
summary: Vec::new(),
content: Vec::new(),
},
last,
],
)];
let joined = join_computer_groups(&older[0], &newer[0], &turns)
.expect("hidden reasoning retains the adjacent computer group");
let expected = project(&turns[0].items);
assert_eq!(
joined.transcript_lines(/*width*/ 80),
expected[0].transcript_lines(/*width*/ 80),
);
turns[0].items[1] = ThreadItem::untimed(ThreadItemPayload::AgentMessage {
moderation: None,
id: "message".to_string(),
text: "Visible boundary".to_string(),
phase: None,
memory_citation: None,
delivery: None,
questions: None,
});
assert!(join_computer_groups(&older[0], &newer[0], &turns).is_none());
}

View File

@@ -0,0 +1,79 @@
//! Apply live exploration compatibility to replay and repair groups split by history pages.
use super::tools::CommandHistory;
use crate::exec_cell::ExecCell;
use crate::history_cell::HistoryCell;
use akode_app_server_protocol::ThreadItemPayload;
use akode_app_server_protocol::Turn;
use std::sync::Arc;
pub(crate) fn join_exploration_groups(
older: &Arc<dyn HistoryCell>,
newer: &Arc<dyn HistoryCell>,
turns: &[Turn],
) -> Option<Arc<dyn HistoryCell>> {
let older = older.as_any().downcast_ref::<ExecCell>()?;
let newer = newer.as_any().downcast_ref::<ExecCell>()?;
let items = adjacent_items(older, newer, turns)?;
let mut group = completed_group(items)?;
group.group.details = newer.group.details.clone();
group
.group
.details
.prepend(older.group.details.clone(), older.group.calls.len());
Some(Arc::new(group))
}
pub(crate) fn older_exploration_group(
older: &dyn HistoryCell,
newer: &ExecCell,
turns: &[Turn],
) -> Option<ExecCell> {
let older = older.as_any().downcast_ref::<ExecCell>()?;
let items = adjacent_items(older, newer, turns)?;
let older_items = items
.iter()
.filter(|entry| !matches!(&entry.payload, ThreadItemPayload::Reasoning { .. }))
.take(older.group.calls.len())
.cloned()
.collect::<Vec<_>>();
let mut group = completed_group(&older_items)?;
group.group.details = older.group.details.clone();
Some(group)
}
fn adjacent_items<'a>(
older: &ExecCell,
newer: &ExecCell,
turns: &'a [Turn],
) -> Option<&'a [akode_app_server_protocol::ThreadItem]> {
if !older.is_exploring_cell() || older.should_flush() || !newer.is_exploring_cell() {
return None;
}
let ids = older
.iter_calls()
.chain(newer.iter_calls())
.map(|call| call.call_id.as_str())
.collect::<Vec<_>>();
super::computer_groups::adjacent_activity_items(&ids, turns)
}
pub(super) fn completed_group(items: &[akode_app_server_protocol::ThreadItem]) -> Option<ExecCell> {
let mut group: Option<ExecCell> = None;
for entry in items {
let item = &entry.payload;
if matches!(item, ThreadItemPayload::Reasoning { .. }) {
continue;
}
let call = CommandHistory::from_item(item.clone())?.into_cell();
if !call.is_exploring_cell() {
return None;
}
if let Some(group) = &mut group {
group.append_completed(call).ok()?;
} else {
group = Some(call);
}
}
group
}

View File

@@ -0,0 +1,150 @@
//! Restore historical tool and notice cells without changing live application state.
//!
//! Formatting stays in the same history cells used by live events. Only completed
//! patches render as applied changes; other statuses retain their actual outcome.
use super::TranscriptCells;
use crate::app_server_approval_conversions::file_update_changes_to_display;
use crate::history_cell;
use crate::history_cell::PlainHistoryCell;
use crate::multi_agents;
use akode_app_server_protocol::PatchApplyStatus;
use akode_app_server_protocol::ThreadItemPayload;
use akode_app_server_protocol::WebSearchAction;
use akode_utils_absolute_path::AbsolutePathBuf;
use ratatui::style::Stylize as _;
use std::sync::Arc;
pub(super) fn cells(item: ThreadItemPayload, cwd: &AbsolutePathBuf) -> TranscriptCells {
let mut cells: TranscriptCells = Vec::new();
match item {
ThreadItemPayload::FileChange {
id,
changes,
status,
} => match status {
PatchApplyStatus::Completed if !changes.is_empty() => {
cells.push(Arc::new(
history_cell::new_patch_event(
file_update_changes_to_display(changes),
cwd.as_path(),
)
.with_activity_id(id),
));
}
PatchApplyStatus::Completed => {}
PatchApplyStatus::Failed => {
cells.push(Arc::new(history_cell::new_patch_apply_failure(
String::new(),
)));
}
PatchApplyStatus::InProgress | PatchApplyStatus::Declined => {
let message = if status == PatchApplyStatus::Declined {
"Patch application declined"
} else {
"Patch application in progress"
};
cells.push(Arc::new(history_cell::new_info_event(
message.to_string(),
/*hint*/ None,
)));
}
},
ThreadItemPayload::WebSearch(item) => {
cells.push(Arc::new(history_cell::new_web_search_call(
item.id,
item.query,
item.action.unwrap_or(WebSearchAction::Other),
)))
}
ThreadItemPayload::ImageView { id, path } => {
cells.push(Arc::new(history_cell::new_view_image_tool_call(id, path)))
}
ThreadItemPayload::ImageGeneration(item)
if !matches!(item.status.as_str(), "completed" | "failed") =>
{
let status = if item.status.is_empty() {
"status unavailable"
} else {
&item.status
};
cells.push(Arc::new(history_cell::new_info_event(
format!("Image generation · {status}"),
/*hint*/ None,
)));
}
ThreadItemPayload::ImageGeneration(item) => {
cells.push(Arc::new(history_cell::new_image_generation_call(
item.id,
&item.status,
item.revised_prompt,
item.saved_path,
)));
}
item @ ThreadItemPayload::CollabAgentToolCall { .. } => {
if let Some(cell) = multi_agents::tool_call_history_cell(
&item,
/*cached_spawn_request*/ None,
|_| multi_agents::AgentMetadata::default(),
) {
cells.push(Arc::new(cell));
}
}
item @ ThreadItemPayload::SubAgentActivity { .. } => {
if let Some(cell) = multi_agents::sub_agent_activity_history_cell(&item) {
cells.push(Arc::new(cell));
}
}
ThreadItemPayload::EnteredReviewMode { review, .. } => {
cells.push(Arc::new(history_cell::new_review_status_line(format!(
">> Code review started: {review} <<"
))));
}
ThreadItemPayload::ExitedReviewMode { review, .. } => {
cells.push(Arc::new(history_cell::new_review_status_line(format!(
"<< Code review finished: {review} >>"
))));
}
ThreadItemPayload::ContextCompaction { .. } => {
cells.push(Arc::new(history_cell::new_info_event(
"Context compacted".to_string(),
/*hint*/ None,
)));
}
// These items do not have richer history-cell presentations yet.
ThreadItemPayload::HookPrompt { fragments, .. } => {
if !fragments.is_empty() {
cells.push(Arc::new(PlainHistoryCell::new(
fragments
.into_iter()
.map(|fragment| {
vec![
"hook prompt: ".dim(),
fragment.text.trim().to_string().into(),
]
.into()
})
.collect(),
)));
}
}
item @ ThreadItemPayload::DynamicToolCall { .. } => {
if let Some(cell) = history_cell::DynamicToolCallCell::from_item(item) {
cells.push(Arc::new(cell));
}
}
ThreadItemPayload::UserMessage { .. }
| ThreadItemPayload::AgentMessage { .. }
| ThreadItemPayload::FunctionCallOutput { .. }
| ThreadItemPayload::Plan { .. }
| ThreadItemPayload::Reasoning { .. }
| ThreadItemPayload::CommandExecution { .. }
| ThreadItemPayload::McpToolCall { .. }
| ThreadItemPayload::Sleep(_) => {}
}
cells
}
#[cfg(test)]
#[path = "other_items_tests.rs"]
mod tests;

View File

@@ -0,0 +1,196 @@
//! Persisted tool projections retain rich detail, styles, and truthful outcomes.
use super::cells;
use crate::diff_model::FileChange;
use crate::history_cell;
use crate::history_cell::HistoryCell;
use crate::test_support::PathBufExt;
use crate::test_support::test_path_buf;
use akode_app_server_protocol::FileUpdateChange;
use akode_app_server_protocol::GeneratedImageRef;
use akode_app_server_protocol::ImageGenerationItem;
use akode_app_server_protocol::PatchApplyStatus;
use akode_app_server_protocol::PatchChangeKind;
use akode_app_server_protocol::SubAgentActivityKind;
use akode_app_server_protocol::ThreadItemPayload;
use akode_app_server_protocol::WebSearchAction;
use akode_app_server_protocol::WebSearchItem;
use akode_utils_path_uri::LegacyAppPathString;
use pretty_assertions::assert_eq;
use std::collections::HashMap;
use std::path::PathBuf;
#[test]
fn completed_patch_restores_rich_diff_and_styles() {
let cwd = test_path_buf("/workspace").abs();
let mut changes = vec![
FileUpdateChange {
path: "new.rs".to_string(),
kind: PatchChangeKind::Add,
diff: "fn greet() {\n println!(\"hello\");\n}\n".to_string(),
},
FileUpdateChange {
path: "old.txt".to_string(),
kind: PatchChangeKind::Delete,
diff: "outdated\n".to_string(),
},
FileUpdateChange {
path: "src/before.rs".to_string(),
kind: PatchChangeKind::Update {
move_path: Some(PathBuf::from("src/after.rs")),
},
diff: "@@ -1 +1 @@\n-let before = 1;\n+let after = 2;\n".to_string(),
},
];
let expected = history_cell::new_patch_event(
HashMap::from([
(
PathBuf::from("new.rs"),
FileChange::Add {
content: changes[0].diff.clone(),
},
),
(
PathBuf::from("old.txt"),
FileChange::Delete {
content: changes[1].diff.clone(),
},
),
(
PathBuf::from("src/before.rs"),
FileChange::Update {
unified_diff: changes[2].diff.clone(),
move_path: Some(PathBuf::from("src/after.rs")),
},
),
]),
cwd.as_path(),
);
changes[2].diff.push_str("\n\nMoved to: src/after.rs");
let actual = cells(
ThreadItemPayload::FileChange {
id: "patch-1".to_string(),
changes,
status: PatchApplyStatus::Completed,
},
&cwd,
);
assert_eq!(actual.len(), 1);
assert_eq!(
actual[0].transcript_hyperlink_lines(/*width*/ 80),
expected.transcript_hyperlink_lines(/*width*/ 80),
);
}
#[test]
fn unfinished_and_rejected_patches_keep_their_outcome() {
let cwd = test_path_buf("/workspace").abs();
let rendered = [
PatchApplyStatus::InProgress,
PatchApplyStatus::Declined,
PatchApplyStatus::Failed,
]
.into_iter()
.flat_map(|status| {
cells(
ThreadItemPayload::FileChange {
id: "patch-1".to_string(),
changes: vec![FileUpdateChange {
path: "main.rs".to_string(),
kind: PatchChangeKind::Add,
diff: "fn main() {}\n".to_string(),
}],
status,
},
&cwd,
)
})
.flat_map(|cell| cell.display_lines(/*width*/ 80))
.map(|line| line.to_string())
.collect::<Vec<_>>()
.join("\n");
insta::assert_snapshot!(rendered, @"
• Patch application in progress
• Patch application declined
✘ Failed to apply patch
");
}
#[test]
fn tool_and_notice_projection_uses_normal_transcript_presentation() {
let cwd = test_path_buf("/workspace").abs();
let image = ImageGenerationItem {
id: "image-1".to_string(),
status: "completed".to_string(),
revised_prompt: Some("A diagram of the history pages".to_string()),
image: GeneratedImageRef::Inline {
result: String::new(),
},
transparent_background: None,
failure: None,
saved_path: None,
input_images: Vec::new(),
imagegen_request_id: None,
generation_id: None,
};
let items = vec![
ThreadItemPayload::EnteredReviewMode {
id: "review-start".to_string(),
review: "current changes".to_string(),
},
ThreadItemPayload::WebSearch(WebSearchItem {
id: "search-1".to_string(),
query: "fallback query".to_string(),
action: Some(WebSearchAction::FindInPage {
url: Some("https://example.com".to_string()),
pattern: Some("pagination".to_string()),
}),
results: None,
}),
ThreadItemPayload::ImageView {
id: "view-1".to_string(),
path: LegacyAppPathString::from_string("diagram.png".to_string()),
},
ThreadItemPayload::ImageGeneration(image.clone()),
ThreadItemPayload::ImageGeneration(ImageGenerationItem {
status: "in_progress".into(),
..image
}),
ThreadItemPayload::SubAgentActivity {
model: None,
reasoning_effort: None,
id: "agent-1".to_string(),
kind: SubAgentActivityKind::Completed,
agent_thread_id: "01912345-1234-7123-8123-123456789abc".to_string(),
agent_path: "/root/reviewer".to_string(),
},
ThreadItemPayload::ExitedReviewMode {
id: "review-end".to_string(),
review: "No findings".to_string(),
},
ThreadItemPayload::ContextCompaction {
id: "compact-1".to_string(),
},
];
let rendered = items
.into_iter()
.flat_map(|item| cells(item, &cwd))
.flat_map(|cell| cell.display_lines(/*width*/ 80))
.map(|line| line.to_string())
.collect::<Vec<_>>()
.join("\n");
insta::assert_snapshot!(rendered, @"
>> Code review started: current changes <<
• Searched for 'pagination' in https://example.com
• Viewed image diagram.png
• Generated Image:
└ A diagram of the history pages
• Image generation · in_progress
• Completed `/root/reviewer`
<< Code review finished: No findings >>
• Context compacted
");
}

View File

@@ -0,0 +1,9 @@
---
source: tui/src/thread_transcript/tools_tests.rs
expression: "snapshots.join(\"\\n\")"
---
agent tool: SpawnAgent · In progress at last update
agent tool: SendInput · Failed
agent tool: CloseAgent · Interrupted
agent tool: ResumeAgent · Failed
agent tool: Wait · Interrupted

View File

@@ -0,0 +1,34 @@
---
source: tui/src/thread_transcript/tools_tests.rs
expression: rendered
---
Command: compact
• Ran cargo check
└ output line 1
output line 2
output line 3
+9 lines (⌃t to view transcript)
Command: detailed
$ cargo check
output line 1
output line 2
output line 3
output line 4
output line 5
output line 6
output line 7
output line 8
output line 9
output line 10
output line 11
output line 12
✓ • 0ms
MCP: compact
• Called example.js({"title":"Inspect page mcp","code":"await cua.getState()"})
└ Full result for mcp
MCP: detailed
• Called example.js({"title":"Inspect page mcp","code":"await cua.getState()"})
└ Full result for mcp

View File

@@ -0,0 +1,52 @@
---
source: tui/src/thread_transcript/tools_tests.rs
expression: "snapshots.join(\"\\n\\n\")"
---
declined
$ cargo check
Declined
first line
indented output
last line
opaque command
$ C:\Program Files\Git\bin\bash.exe -lc "echo hi"
Completed · exit 0
first line
indented output
last line
UNC command
$ \\server\share\tool.exe -arg
Completed · exit 0
first line
indented output
last line
completed interaction
$ cargo check
Terminal interaction · Completed · exit 0
first line
indented output
last line
failed interaction
$ cargo check
Terminal interaction · Failed · exit 7
first line
indented output
last line
failed interaction without exit code
$ cargo check
Terminal interaction · Failed
first line
indented output
last line
pending interaction
$ cargo check
Terminal interaction · In progress at last update
first line
indented output
last line

View File

@@ -0,0 +1,21 @@
---
source: tui/src/thread_transcript/tools_tests.rs
assertion_line: 135
expression: rendered
---
$ cargo check
In progress at last update
output line 1
output line 2
output line 3
output line 4
output line 5
output line 6
output line 7
output line 8
output line 9
output line 10
output line 11
output line 12
mcp tool: example/js · In progress at last update
mcp tool: example/js · Completed · result unavailable

View File

@@ -0,0 +1,248 @@
//! Share tool history conversion between live handlers and persisted transcript pages.
//!
//! These values contain presentation data only. Creating historical cells never starts a task,
//! changes composer state, or leaves an animation running; pending items retain their last known
//! status. Callers own chronological grouping.
use std::time::Duration;
use crate::exec_cell::CommandOutput;
use crate::exec_cell::ExecCell;
use crate::exec_cell::new_active_exec_command;
use crate::history_cell::McpInvocation;
use crate::history_cell::McpToolCallCell;
use crate::history_cell::PlainHistoryCell;
use crate::history_cell::new_active_mcp_tool_call;
use akode_app_server_protocol::CollabAgentTool;
use akode_app_server_protocol::CollabAgentToolCallStatus;
use akode_app_server_protocol::CommandExecutionSource;
use akode_app_server_protocol::CommandExecutionStatus;
use akode_app_server_protocol::McpToolCallStatus;
use akode_app_server_protocol::ThreadItemPayload;
use akode_protocol::mcp::CallToolResult;
use akode_protocol::parse_command::ParsedCommand;
use ratatui::style::Stylize as _;
use ratatui::text::Line;
/// Preserve status and output when replay cannot reconstruct a rich completed tool cell.
/// Declined commands never ran, and historical terminal interactions do not carry stdin details.
/// Pending items retain their last known state without starting a running clock.
pub(crate) fn historical_tool_fallback(item: &ThreadItemPayload) -> Option<PlainHistoryCell> {
let lines = match item {
ThreadItemPayload::CommandExecution {
command,
source,
status,
aggregated_output,
exit_code,
..
} if matches!(
status,
CommandExecutionStatus::InProgress | CommandExecutionStatus::Declined
) || *source == CommandExecutionSource::UnifiedExecInteraction
|| replay_command_args(command).is_none() =>
{
let status_label = match status {
CommandExecutionStatus::InProgress => "In progress at last update",
CommandExecutionStatus::Completed => "Completed",
CommandExecutionStatus::Failed => "Failed",
CommandExecutionStatus::Declined => "Declined",
};
let mut status_line = if *source == CommandExecutionSource::UnifiedExecInteraction {
format!("Terminal interaction · {status_label}")
} else {
status_label.to_string()
};
if matches!(
status,
CommandExecutionStatus::Completed | CommandExecutionStatus::Failed
) && let Some(code) = exit_code
{
status_line.push_str(&format!(" · exit {code}"));
}
let mut lines: Vec<Line<'static>> = vec![
vec!["$ ".dim(), command.clone().into()].into(),
status_line.dim().into(),
];
if let Some(output) = aggregated_output {
lines.extend(
output
.lines()
.map(|line| vec![" ".dim(), line.trim_end().to_string().dim()].into()),
);
}
lines
}
ThreadItemPayload::McpToolCall {
server,
tool,
status,
result,
error,
..
} if *status == McpToolCallStatus::InProgress || (result.is_none() && error.is_none()) => {
let status = match status {
McpToolCallStatus::InProgress => "In progress at last update",
McpToolCallStatus::Completed => "Completed · result unavailable",
McpToolCallStatus::Failed => "Failed · result unavailable",
};
vec![format!("mcp tool: {server}/{tool} · {status}").dim().into()]
}
ThreadItemPayload::CollabAgentToolCall {
tool:
tool @ (CollabAgentTool::SpawnAgent
| CollabAgentTool::SendInput
| CollabAgentTool::CloseAgent
| CollabAgentTool::ResumeAgent
| CollabAgentTool::Wait),
status,
..
} if *status != CollabAgentToolCallStatus::Completed => {
let status = match status {
CollabAgentToolCallStatus::InProgress => "In progress at last update",
CollabAgentToolCallStatus::Failed => "Failed",
CollabAgentToolCallStatus::Interrupted => "Interrupted",
CollabAgentToolCallStatus::Completed => "Completed",
};
vec![format!("agent tool: {tool:?} · {status}").dim().into()]
}
_ => return None,
};
Some(PlainHistoryCell::new(lines))
}
// The protocol joins argv with shlex. Keep noncanonical legacy commands verbatim.
fn replay_command_args(command: &str) -> Option<Vec<String>> {
let args = shlex::split(command)?;
(shlex::try_join(args.iter().map(String::as_str)).as_deref() == Ok(command)).then_some(args)
}
pub(crate) struct CommandHistory {
pub(crate) id: String,
pub(crate) command: Vec<String>,
pub(crate) parsed: Vec<ParsedCommand>,
pub(crate) source: CommandExecutionSource,
pub(crate) aggregated_output: String,
pub(crate) exit_code: i32,
pub(crate) duration: Duration,
}
impl CommandHistory {
pub(crate) fn from_item(item: ThreadItemPayload) -> Option<Self> {
let ThreadItemPayload::CommandExecution {
id,
command,
source,
status,
command_actions,
aggregated_output,
exit_code,
duration_ms,
..
} = item
else {
return None;
};
// Thread snapshots omit stdin, so `None` would falsely classify these as waits.
if source == CommandExecutionSource::UnifiedExecInteraction {
return None;
}
let exit_code = match status {
CommandExecutionStatus::InProgress | CommandExecutionStatus::Declined => return None,
CommandExecutionStatus::Completed => exit_code.unwrap_or_default(),
CommandExecutionStatus::Failed => {
exit_code.filter(|code| *code != 0).unwrap_or(/*default*/ 1)
}
};
Some(Self {
id,
command: replay_command_args(&command)?,
parsed: command_actions
.into_iter()
.map(akode_app_server_protocol::CommandAction::into_core)
.collect(),
source,
aggregated_output: aggregated_output.unwrap_or_default(),
exit_code,
duration: Duration::from_millis(duration_ms.unwrap_or_default().max(/*other*/ 0) as u64),
})
}
pub(crate) fn into_cell(self) -> ExecCell {
let output = CommandOutput::new(self.exit_code, self.aggregated_output);
let mut cell = new_active_exec_command(
self.id.clone(),
self.command,
self.parsed,
self.source,
/*interaction_input*/ None,
/*animations_enabled*/ false,
);
let completed = cell.complete_call(&self.id, output, self.duration);
debug_assert!(completed, "new exec cell should contain {}", self.id);
cell
}
}
pub(crate) struct McpHistory {
pub(crate) id: String,
pub(crate) invocation: McpInvocation,
pub(crate) duration: Duration,
pub(crate) result: Result<CallToolResult, String>,
}
impl McpHistory {
pub(crate) fn from_item(item: ThreadItemPayload) -> Option<Self> {
let ThreadItemPayload::McpToolCall {
id,
server,
tool,
status,
arguments,
result,
error,
duration_ms,
..
} = item
else {
return None;
};
if status == McpToolCallStatus::InProgress {
return None;
}
let result = match (result, error) {
(_, Some(error)) => Err(error.message),
(Some(result), None) => {
let result = *result;
Ok(CallToolResult {
content: result.content,
structured_content: result.structured_content,
is_error: Some(status == McpToolCallStatus::Failed),
meta: None,
})
}
(None, None) => Err("MCP tool call completed without a result".to_string()),
};
Some(Self {
id,
invocation: McpInvocation {
server,
tool,
arguments: Some(arguments),
},
duration: Duration::from_millis(duration_ms.unwrap_or_default().max(/*other*/ 0) as u64),
result,
})
}
pub(crate) fn into_cell(self) -> McpToolCallCell {
let mut cell =
new_active_mcp_tool_call(self.id, self.invocation, /*animations_enabled*/ false);
cell.complete(self.duration, self.result);
cell
}
}
#[cfg(test)]
#[path = "tools_tests.rs"]
mod tests;

View File

@@ -0,0 +1,339 @@
use super::*;
use crate::test_support::PathBufExt;
use crate::test_support::test_path_buf;
use crate::thread_transcript::RawReasoningVisibility;
use crate::thread_transcript::thread_items_to_transcript_cells;
use akode_app_server_protocol::CommandAction;
use akode_app_server_protocol::McpToolCallResult;
use akode_utils_path_uri::LegacyAppPathString;
use pretty_assertions::assert_eq;
use serde_json::json;
fn command_item(status: CommandExecutionStatus) -> ThreadItemPayload {
ThreadItemPayload::CommandExecution {
id: "command".to_string(),
plugin_id: None,
script_path: None,
model_context: None,
sandbox_type: None,
command: "cargo check".to_string(),
cwd: LegacyAppPathString::from_string("/tmp/project"),
process_id: None,
source: CommandExecutionSource::Agent,
status,
command_actions: vec![CommandAction::Unknown {
command: "cargo check".to_string(),
}],
aggregated_output: Some(
(1..=12)
.map(|line| format!("output line {line}"))
.collect::<Vec<_>>()
.join("\n"),
),
exit_code: Some(0),
duration_ms: Some(-5),
}
}
fn mcp_item(server: &str, id: &str) -> ThreadItemPayload {
ThreadItemPayload::McpToolCall {
id: id.to_string(),
server: server.to_string(),
tool: "js".to_string(),
status: McpToolCallStatus::Completed,
arguments: json!({"title": format!("Inspect page {id}"), "code": "await cua.getState()"}),
app_context: None,
mcp_app_resource_uri: None,
plugin_id: None,
read_only_hint: None,
mcp_app_ui: None,
result: Some(Box::new(McpToolCallResult {
content: vec![json!({"type": "text", "text": format!("Full result for {id}")})],
structured_content: None,
meta: None,
})),
error: None,
duration_ms: Some(5),
}
}
#[test]
fn completed_tools_keep_compact_and_detailed_presentations() {
let cwd = test_path_buf("/workspace").abs();
let items = [
command_item(CommandExecutionStatus::Completed),
mcp_item("example", "mcp"),
];
let cells = thread_items_to_transcript_cells(
/*thread_id*/ None,
&cwd,
items,
RawReasoningVisibility::Hidden,
/*config*/ None,
);
assert_eq!(cells.len(), 2);
let rendered = ["Command", "MCP"]
.into_iter()
.zip(cells)
.map(|(label, cell)| {
assert_eq!(cell.transcript_animation_tick(), None);
let display = cell
.display_lines(/*width*/ 80)
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join("\n");
let transcript = cell
.transcript_lines(/*width*/ 80)
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join("\n");
format!("{label}: compact\n{display}\n\n{label}: detailed\n{transcript}")
})
.collect::<Vec<_>>()
.join("\n\n");
insta::assert_snapshot!("completed_tool_presentations", rendered);
}
#[test]
fn failed_commands_keep_failure_when_exit_code_is_missing_or_zero() {
for exit in [None, Some(0)] {
let mut item = command_item(CommandExecutionStatus::Failed);
if let ThreadItemPayload::CommandExecution { exit_code, .. } = &mut item {
*exit_code = exit;
}
let command = CommandHistory::from_item(item).unwrap();
assert_eq!((command.exit_code, command.duration), (1, Duration::ZERO));
}
}
#[test]
fn incomplete_tool_payloads_preserve_last_known_status_and_output() {
let command = command_item(CommandExecutionStatus::InProgress);
let mut mcp = mcp_item("example", "pending");
if let ThreadItemPayload::McpToolCall { status, result, .. } = &mut mcp {
*status = McpToolCallStatus::InProgress;
*result = None;
}
let mut missing_result = mcp_item("example", "completed");
if let ThreadItemPayload::McpToolCall { result, .. } = &mut missing_result {
*result = None;
}
let cwd = test_path_buf("/workspace").abs();
let rendered = thread_items_to_transcript_cells(
/*thread_id*/ None,
&cwd,
[command, mcp, missing_result],
RawReasoningVisibility::Hidden,
/*config*/ None,
)
.into_iter()
.flat_map(|cell| cell.display_lines(/*width*/ 80))
.map(|line| line.to_string())
.collect::<Vec<_>>()
.join("\n");
insta::assert_snapshot!("pending_tool_presentations", rendered);
}
#[test]
fn historical_command_fallbacks_preserve_status_output_and_group_boundaries() {
let cwd = test_path_buf("/workspace").abs();
let exploration = |call_id: &str| {
let mut item = command_item(CommandExecutionStatus::Completed);
if let ThreadItemPayload::CommandExecution {
id,
command,
command_actions,
..
} = &mut item
{
*id = call_id.to_owned();
*command = "cat README.md".to_owned();
*command_actions = vec![CommandAction::Read {
command: command.clone(),
name: "README.md".to_owned(),
path: LegacyAppPathString::from_string("/workspace/README.md"),
}];
}
item
};
let mut snapshots = Vec::new();
for (source, status, recorded_exit, label) in [
(
CommandExecutionSource::Agent,
CommandExecutionStatus::Declined,
None,
"declined",
),
(
CommandExecutionSource::Agent,
CommandExecutionStatus::Completed,
Some(0),
"opaque command",
),
(
CommandExecutionSource::Agent,
CommandExecutionStatus::Completed,
Some(0),
"UNC command",
),
(
CommandExecutionSource::UnifiedExecInteraction,
CommandExecutionStatus::Completed,
Some(0),
"completed interaction",
),
(
CommandExecutionSource::UnifiedExecInteraction,
CommandExecutionStatus::Failed,
Some(7),
"failed interaction",
),
(
CommandExecutionSource::UnifiedExecInteraction,
CommandExecutionStatus::Failed,
None,
"failed interaction without exit code",
),
(
CommandExecutionSource::UnifiedExecInteraction,
CommandExecutionStatus::InProgress,
None,
"pending interaction",
),
] {
let mut item = command_item(status);
if let ThreadItemPayload::CommandExecution {
source: item_source,
command,
aggregated_output,
exit_code,
..
} = &mut item
{
*item_source = source;
if label == "opaque command" {
*command = r#"C:\Program Files\Git\bin\bash.exe -lc "echo hi""#.to_owned();
} else if label == "UNC command" {
*command = r"\\server\share\tool.exe -arg".to_owned();
}
*aggregated_output = Some("first line\n indented output\nlast line".to_owned());
*exit_code = recorded_exit;
}
let cells = thread_items_to_transcript_cells(
/*thread_id*/ None,
&cwd,
[exploration("before"), item, exploration("after")],
RawReasoningVisibility::Hidden,
/*config*/ None,
);
assert_eq!(cells.len(), 3);
for cell in [&cells[0], &cells[2]] {
assert!(
cell.as_any()
.downcast_ref::<ExecCell>()
.unwrap()
.is_exploring_cell()
);
}
let [compact, detailed, raw] = [
cells[1].display_lines(/*width*/ 80),
cells[1].transcript_lines(/*width*/ 80),
cells[1].raw_lines(),
]
.map(|lines| {
lines
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join("\n")
});
assert_eq!((&detailed, &raw), (&compact, &compact));
snapshots.push(format!("{label}\n{compact}"));
}
insta::assert_snapshot!(snapshots.join("\n\n"));
}
#[test]
fn agent_tool_fallbacks_preserve_status_without_duplicating_v2_activity() {
let cwd = test_path_buf("/workspace").abs();
let mut snapshots = Vec::new();
for (tool, status) in [
(
CollabAgentTool::SpawnAgent,
CollabAgentToolCallStatus::InProgress,
),
(
CollabAgentTool::SendInput,
CollabAgentToolCallStatus::Failed,
),
(
CollabAgentTool::CloseAgent,
CollabAgentToolCallStatus::Interrupted,
),
(
CollabAgentTool::ResumeAgent,
CollabAgentToolCallStatus::Failed,
),
(
CollabAgentTool::Wait,
CollabAgentToolCallStatus::Interrupted,
),
(
CollabAgentTool::SendMessage,
CollabAgentToolCallStatus::InProgress,
),
(
CollabAgentTool::FollowupTask,
CollabAgentToolCallStatus::InProgress,
),
(
CollabAgentTool::InterruptAgent,
CollabAgentToolCallStatus::InProgress,
),
(
CollabAgentTool::ListAgents,
CollabAgentToolCallStatus::InProgress,
),
] {
let visible = matches!(
tool,
CollabAgentTool::SpawnAgent
| CollabAgentTool::SendInput
| CollabAgentTool::CloseAgent
| CollabAgentTool::ResumeAgent
| CollabAgentTool::Wait
);
let item = ThreadItemPayload::CollabAgentToolCall {
id: "pending-agent-call".to_string(),
tool,
status,
sender_thread_id: "00000000-0000-0000-0000-000000000001".to_string(),
receiver_thread_ids: vec!["00000000-0000-0000-0000-000000000002".to_string()],
prompt: Some("Inspect the parser".to_string()),
model: None,
reasoning_effort: None,
agents_states: Default::default(),
};
let cells = thread_items_to_transcript_cells(
/*thread_id*/ None,
&cwd,
[item],
RawReasoningVisibility::Hidden,
/*config*/ None,
);
assert_eq!(cells.len(), usize::from(visible));
for cell in cells {
assert_eq!(cell.transcript_animation_tick(), None);
let text = cell
.transcript_lines(/*width*/ 80)
.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join("\n");
snapshots.push(text);
}
}
insta::assert_snapshot!(snapshots.join("\n"));
}