aKode fase 5: rinomina interna (crate akode-*, akode-rs/, akode-cli/, binario akode, AKODE_*, ~/.akode, snapshot)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
76
akode-rs/tui/src/activation_key_guard.rs
Normal file
76
akode-rs/tui/src/activation_key_guard.rs
Normal file
@@ -0,0 +1,76 @@
|
||||
//! Keep a held activation key from triggering another action.
|
||||
//!
|
||||
//! Terminals with enhanced keyboard reporting distinguish a held `Repeat` from a fresh `Press`.
|
||||
//! A view transition on a press-only terminal can use a bounded window to block ambiguous presses.
|
||||
|
||||
use crate::key_hint::KeyBinding;
|
||||
use crossterm::event::KeyEventKind;
|
||||
use std::time::Duration;
|
||||
use std::time::Instant;
|
||||
|
||||
const INITIAL_GUARD: Duration = Duration::from_secs(/*secs*/ 1);
|
||||
const LEGACY_REPEAT_GUARD: Duration = Duration::from_secs(/*secs*/ 1);
|
||||
|
||||
pub(crate) enum ActivationKeySuppression {
|
||||
ViewTransition,
|
||||
ReportedRepeats,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct ActivationKeyGuard {
|
||||
key: KeyBinding,
|
||||
block_until: Instant,
|
||||
legacy_repeat_fallback: bool,
|
||||
active: bool,
|
||||
}
|
||||
|
||||
impl ActivationKeyGuard {
|
||||
pub(crate) fn new_at(key: KeyBinding, now: Instant, reported_repeats_only: bool) -> Self {
|
||||
Self {
|
||||
key,
|
||||
block_until: now.checked_add(INITIAL_GUARD).unwrap_or(now),
|
||||
legacy_repeat_fallback: !reported_repeats_only,
|
||||
active: true,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn consume(&mut self, key: KeyBinding, kind: KeyEventKind) -> bool {
|
||||
self.consume_at(key, kind, Instant::now())
|
||||
}
|
||||
|
||||
fn consume_at(&mut self, key: KeyBinding, kind: KeyEventKind, now: Instant) -> bool {
|
||||
if !self.active {
|
||||
return false;
|
||||
}
|
||||
|
||||
if self.key.is_same_physical_key(key) {
|
||||
if kind == KeyEventKind::Release {
|
||||
self.active = false;
|
||||
return true;
|
||||
}
|
||||
// Without the legacy fallback, only a reported Repeat is treated as held.
|
||||
if !self.legacy_repeat_fallback && kind == KeyEventKind::Press {
|
||||
self.active = false;
|
||||
return false;
|
||||
}
|
||||
if kind == KeyEventKind::Repeat || now <= self.block_until {
|
||||
let repeat_until = now.checked_add(LEGACY_REPEAT_GUARD).unwrap_or(now);
|
||||
self.block_until = self.block_until.max(repeat_until);
|
||||
return true;
|
||||
}
|
||||
self.active = false;
|
||||
} else if matches!(kind, KeyEventKind::Press | KeyEventKind::Repeat) {
|
||||
self.active = false;
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
pub(crate) fn is_active(self) -> bool {
|
||||
self.active
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "activation_key_guard_tests.rs"]
|
||||
mod tests;
|
||||
39
akode-rs/tui/src/activation_key_guard_tests.rs
Normal file
39
akode-rs/tui/src/activation_key_guard_tests.rs
Normal file
@@ -0,0 +1,39 @@
|
||||
use super::*;
|
||||
use crate::key_hint;
|
||||
use crossterm::event::KeyCode;
|
||||
|
||||
#[test]
|
||||
fn suppresses_activation_until_release_and_bounds_legacy_presses() {
|
||||
let start = Instant::now();
|
||||
let key = key_hint::plain(KeyCode::Enter);
|
||||
let mut guard = ActivationKeyGuard::new_at(key, start, /*reported_repeats_only*/ true);
|
||||
|
||||
assert!(guard.consume_at(key, KeyEventKind::Repeat, start));
|
||||
assert!(guard.consume_at(key, KeyEventKind::Release, start));
|
||||
assert!(!guard.consume_at(key, KeyEventKind::Press, start));
|
||||
|
||||
let mut guard = ActivationKeyGuard::new_at(key, start, /*reported_repeats_only*/ false);
|
||||
for elapsed in [900, 1_300] {
|
||||
assert!(guard.consume_at(
|
||||
key,
|
||||
KeyEventKind::Press,
|
||||
start + Duration::from_millis(/*millis*/ elapsed),
|
||||
));
|
||||
}
|
||||
assert!(!guard.consume_at(
|
||||
key,
|
||||
KeyEventKind::Press,
|
||||
start + Duration::from_millis(/*millis*/ 2_301),
|
||||
));
|
||||
assert!(!guard.is_active());
|
||||
|
||||
let mut guard = ActivationKeyGuard::new_at(
|
||||
key_hint::plain(KeyCode::BackTab),
|
||||
start,
|
||||
/*reported_repeats_only*/ true,
|
||||
);
|
||||
let tab = key_hint::plain(KeyCode::Tab);
|
||||
assert!(guard.consume_at(tab, KeyEventKind::Repeat, start));
|
||||
assert!(guard.consume_at(tab, KeyEventKind::Release, start));
|
||||
assert!(!guard.is_active());
|
||||
}
|
||||
149
akode-rs/tui/src/additional_dirs.rs
Normal file
149
akode-rs/tui/src/additional_dirs.rs
Normal file
@@ -0,0 +1,149 @@
|
||||
use akode_protocol::models::PermissionProfile;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Returns a warning describing why `--add-dir` entries will be ignored for the
|
||||
/// resolved permission profile. The caller is responsible for presenting the
|
||||
/// warning to the user (for example, printing to stderr).
|
||||
pub fn add_dir_warning_message(
|
||||
additional_dirs: &[PathBuf],
|
||||
permission_profile: &PermissionProfile,
|
||||
cwd: &std::path::Path,
|
||||
) -> Option<String> {
|
||||
if additional_dirs.is_empty() {
|
||||
return None;
|
||||
}
|
||||
|
||||
if matches!(
|
||||
permission_profile,
|
||||
PermissionProfile::Disabled | PermissionProfile::External { .. }
|
||||
) {
|
||||
return None;
|
||||
}
|
||||
|
||||
let file_system_policy = permission_profile.file_system_sandbox_policy();
|
||||
if file_system_policy.has_full_disk_write_access() {
|
||||
return None;
|
||||
}
|
||||
|
||||
if file_system_policy.can_write_local_path_with_cwd(cwd, cwd) {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(format_warning(additional_dirs))
|
||||
}
|
||||
|
||||
fn format_warning(additional_dirs: &[PathBuf]) -> String {
|
||||
let joined_paths = additional_dirs
|
||||
.iter()
|
||||
.map(|path| path.to_string_lossy())
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
format!(
|
||||
"Ignoring --add-dir ({joined_paths}) because the effective permissions do not allow additional writable roots. Switch to workspace-write or danger-full-access to allow them."
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::add_dir_warning_message;
|
||||
use akode_protocol::models::ManagedFileSystemPermissions;
|
||||
use akode_protocol::models::PermissionProfile;
|
||||
use akode_protocol::permissions::FileSystemAccessMode;
|
||||
use akode_protocol::permissions::FileSystemPath;
|
||||
use akode_protocol::permissions::FileSystemSandboxEntry;
|
||||
use akode_protocol::permissions::FileSystemSpecialPath;
|
||||
use akode_protocol::permissions::NetworkSandboxPolicy;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[test]
|
||||
fn returns_none_for_workspace_write() {
|
||||
let profile = PermissionProfile::workspace_write();
|
||||
let dirs = vec![PathBuf::from("/tmp/example")];
|
||||
assert_eq!(
|
||||
add_dir_warning_message(&dirs, &profile, Path::new("/tmp/project")),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn returns_none_for_danger_full_access() {
|
||||
let profile = PermissionProfile::Disabled;
|
||||
let dirs = vec![PathBuf::from("/tmp/example")];
|
||||
assert_eq!(
|
||||
add_dir_warning_message(&dirs, &profile, Path::new("/tmp/project")),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn returns_none_for_external_sandbox() {
|
||||
let profile: PermissionProfile = PermissionProfile::External {
|
||||
network: NetworkSandboxPolicy::Enabled,
|
||||
};
|
||||
let dirs = vec![PathBuf::from("/tmp/example")];
|
||||
assert_eq!(
|
||||
add_dir_warning_message(&dirs, &profile, Path::new("/tmp/project")),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warns_for_read_only() {
|
||||
let profile = PermissionProfile::read_only();
|
||||
let dirs = vec![PathBuf::from("relative"), PathBuf::from("/abs")];
|
||||
let message = add_dir_warning_message(&dirs, &profile, Path::new("/tmp/project"))
|
||||
.expect("expected warning for read-only sandbox");
|
||||
assert_eq!(
|
||||
message,
|
||||
"Ignoring --add-dir (relative, /abs) because the effective permissions do not allow additional writable roots. Switch to workspace-write or danger-full-access to allow them."
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warns_when_profile_can_write_elsewhere_but_not_cwd() {
|
||||
let profile: PermissionProfile = PermissionProfile::Managed {
|
||||
network: NetworkSandboxPolicy::Restricted,
|
||||
file_system: ManagedFileSystemPermissions::Restricted {
|
||||
entries: vec![
|
||||
FileSystemSandboxEntry {
|
||||
path: FileSystemPath::Special {
|
||||
value: FileSystemSpecialPath::Root,
|
||||
},
|
||||
access: FileSystemAccessMode::Read,
|
||||
missing_path_behavior: None,
|
||||
},
|
||||
FileSystemSandboxEntry {
|
||||
path: FileSystemPath::Path {
|
||||
path: akode_utils_absolute_path::AbsolutePathBuf::try_from(
|
||||
"/tmp/writable",
|
||||
)
|
||||
.expect("absolute path")
|
||||
.into(),
|
||||
},
|
||||
access: FileSystemAccessMode::Write,
|
||||
missing_path_behavior: None,
|
||||
},
|
||||
],
|
||||
glob_scan_max_depth: None,
|
||||
},
|
||||
};
|
||||
let dirs = vec![PathBuf::from("/tmp/extra")];
|
||||
|
||||
assert_eq!(
|
||||
add_dir_warning_message(&dirs, &profile, Path::new("/tmp/project")),
|
||||
Some("Ignoring --add-dir (/tmp/extra) because the effective permissions do not allow additional writable roots. Switch to workspace-write or danger-full-access to allow them.".to_string())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn returns_none_when_no_additional_dirs() {
|
||||
let profile = PermissionProfile::read_only();
|
||||
let dirs: Vec<PathBuf> = Vec::new();
|
||||
assert_eq!(
|
||||
add_dir_warning_message(&dirs, &profile, Path::new("/tmp/project")),
|
||||
None
|
||||
);
|
||||
}
|
||||
}
|
||||
1445
akode-rs/tui/src/app.rs
Normal file
1445
akode-rs/tui/src/app.rs
Normal file
File diff suppressed because it is too large
Load Diff
90
akode-rs/tui/src/app/activity_groups.rs
Normal file
90
akode-rs/tui/src/app/activity_groups.rs
Normal file
@@ -0,0 +1,90 @@
|
||||
//! Repair activity groups split by transport pages without rewriting terminal scrollback.
|
||||
//!
|
||||
//! Only persisted member adjacency within one turn permits joins. Overlay callbacks retain the
|
||||
//! displayed source revision before canonical cells are replaced or absorbed into the live tail.
|
||||
|
||||
use super::*;
|
||||
use crate::thread_transcript::join_computer_groups;
|
||||
use crate::thread_transcript::join_exploration_groups;
|
||||
|
||||
impl App {
|
||||
pub(super) fn join_older_activity_group(&mut self, boundary: usize, turns: &[Turn]) {
|
||||
let Some(start) = self.transcript_cells[..boundary]
|
||||
.iter()
|
||||
.rposition(|cell| !crate::thread_transcript::is_hidden_activity_detail(cell))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let mut newer_index = self.transcript_cells[boundary..]
|
||||
.iter()
|
||||
.position(|cell| !crate::thread_transcript::is_hidden_activity_detail(cell))
|
||||
.map_or(self.transcript_cells.len(), |offset| boundary + offset);
|
||||
// A reasoning-only page belongs to the preceding group even when an answer or turn
|
||||
// separator follows it. Verify identities before touching either side of that boundary.
|
||||
if start + 1 < newer_index {
|
||||
let Some(older) = crate::thread_transcript::fold_trailing_activity_details(
|
||||
&self.transcript_cells[start],
|
||||
&self.transcript_cells[start + 1..newer_index],
|
||||
turns,
|
||||
) else {
|
||||
return;
|
||||
};
|
||||
let range = start..newer_index;
|
||||
self.native_history
|
||||
.consolidate(&self.transcript_cells[range.clone()], &older);
|
||||
self.transcript_view
|
||||
.replace_group(&self.transcript_cells, range.clone(), &older);
|
||||
if let Some(Overlay::Transcript(overlay)) = self.overlay.as_mut() {
|
||||
overlay.regroup_cells(range.clone(), Arc::clone(&older));
|
||||
}
|
||||
self.transcript_cells.splice(range, [older]);
|
||||
newer_index = start + 1;
|
||||
}
|
||||
if newer_index == self.transcript_cells.len() {
|
||||
let Some((previous_revision, hydrated_revision)) = self
|
||||
.chat_widget
|
||||
.prepend_active_computer_history(self.transcript_cells[start].as_ref(), turns)
|
||||
.or_else(|| {
|
||||
self.chat_widget.prepend_active_exploration_history(
|
||||
self.transcript_cells[start].as_ref(),
|
||||
turns,
|
||||
)
|
||||
})
|
||||
else {
|
||||
return;
|
||||
};
|
||||
self.transcript_view.absorb_tail_into_live(
|
||||
&self.transcript_cells,
|
||||
previous_revision,
|
||||
hydrated_revision,
|
||||
);
|
||||
if let Some(Overlay::Transcript(overlay)) = self.overlay.as_mut() {
|
||||
overlay.absorb_tail_into_live(previous_revision, hydrated_revision);
|
||||
}
|
||||
self.transcript_cells.pop();
|
||||
self.native_history.retain(&self.transcript_cells);
|
||||
return;
|
||||
}
|
||||
let Some(newer) = self.transcript_cells.get(newer_index) else {
|
||||
return;
|
||||
};
|
||||
let Some(group) = join_computer_groups(&self.transcript_cells[start], newer, turns)
|
||||
.or_else(|| join_exploration_groups(&self.transcript_cells[start], newer, turns))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let range = start..newer_index + 1;
|
||||
self.native_history
|
||||
.consolidate(&self.transcript_cells[range.clone()], &group);
|
||||
self.transcript_view
|
||||
.replace_group(&self.transcript_cells, range.clone(), &group);
|
||||
if let Some(Overlay::Transcript(overlay)) = self.overlay.as_mut() {
|
||||
overlay.regroup_cells(range.clone(), Arc::clone(&group));
|
||||
}
|
||||
self.transcript_cells.splice(range, [group]);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "activity_groups_tests.rs"]
|
||||
mod tests;
|
||||
285
akode-rs/tui/src/app/activity_groups_tests.rs
Normal file
285
akode-rs/tui/src/app/activity_groups_tests.rs
Normal file
@@ -0,0 +1,285 @@
|
||||
//! Page transport cannot change activity chronology, rich details, or pending live completion.
|
||||
|
||||
use super::*;
|
||||
use crate::app::test_support::make_test_app;
|
||||
use crate::thread_transcript::RawReasoningVisibility;
|
||||
use crate::thread_transcript::thread_items_to_transcript_cells;
|
||||
use akode_app_server_protocol::ThreadItem;
|
||||
use akode_app_server_protocol::TurnItemsView;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
enum ActivityKind {
|
||||
Computer,
|
||||
Exploration,
|
||||
}
|
||||
|
||||
fn call(id: &str, kind: ActivityKind, status: &str) -> ThreadItemPayload {
|
||||
let value = match kind {
|
||||
ActivityKind::Computer => serde_json::json!({
|
||||
"type": "mcpToolCall", "id": id, "server": "cua_repl", "tool": "js",
|
||||
"status": status, "arguments": {"title": format!("Inspect {id}")},
|
||||
"result": {"content": [{"type": "text", "text": format!("Result {id}")}]},
|
||||
"durationMs": 10
|
||||
}),
|
||||
ActivityKind::Exploration => serde_json::json!({
|
||||
"type": "commandExecution", "id": id, "command": format!("cat {id}.rs"),
|
||||
"cwd": crate::test_support::test_path_buf("/workspace"), "source": "agent",
|
||||
"status": status, "commandActions": [{"type": "read", "command": format!("cat {id}.rs"), "name": format!("{id}.rs"), "path": format!("{id}.rs")}],
|
||||
"aggregatedOutput": format!("Result {id}"), "exitCode": 0, "durationMs": 10
|
||||
}),
|
||||
};
|
||||
serde_json::from_value(value).expect("activity fixture")
|
||||
}
|
||||
|
||||
fn reasoning(id: &str) -> ThreadItemPayload {
|
||||
ThreadItemPayload::Reasoning {
|
||||
id: id.to_owned(),
|
||||
summary: vec![format!(
|
||||
"**Considering {id}**\n\nRetained reasoning for {id}."
|
||||
)],
|
||||
content: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn turn(items: Vec<ThreadItemPayload>) -> Turn {
|
||||
Turn {
|
||||
id: "turn".to_owned(),
|
||||
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(
|
||||
app: &App,
|
||||
items: &[impl std::borrow::Borrow<ThreadItemPayload>],
|
||||
) -> Vec<Arc<dyn HistoryCell>> {
|
||||
thread_items_to_transcript_cells(
|
||||
/*thread_id*/ None,
|
||||
&app.config.cwd,
|
||||
items.iter().map(|entry| entry.borrow().clone()),
|
||||
RawReasoningVisibility::Hidden,
|
||||
Some(&app.config),
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn older_page_hydration_keeps_pending_computer_and_exploration_completion() {
|
||||
for kind in [ActivityKind::Computer, ActivityKind::Exploration] {
|
||||
let mut app = make_test_app().await;
|
||||
match kind {
|
||||
ActivityKind::Computer => {
|
||||
app.chat_widget.handle_mcp_tool_call_completed_now(call(
|
||||
"newer",
|
||||
kind,
|
||||
"completed",
|
||||
));
|
||||
app.chat_widget.handle_mcp_tool_call_started_now(call(
|
||||
"pending",
|
||||
kind,
|
||||
"inProgress",
|
||||
));
|
||||
}
|
||||
ActivityKind::Exploration => {
|
||||
app.chat_widget.handle_command_execution_completed_now(call(
|
||||
"newer",
|
||||
kind,
|
||||
"completed",
|
||||
));
|
||||
app.chat_widget.handle_command_execution_started_now(call(
|
||||
"pending",
|
||||
kind,
|
||||
"inProgress",
|
||||
));
|
||||
}
|
||||
}
|
||||
let mut current = turn(vec![
|
||||
call("older", kind, "completed"),
|
||||
reasoning("boundary"),
|
||||
call("newer", kind, "completed"),
|
||||
call("pending", kind, "inProgress"),
|
||||
]);
|
||||
current.status = TurnStatus::InProgress;
|
||||
// Separate projections model reasoning arriving on its own intervening page.
|
||||
app.transcript_cells = project(&app, ¤t.items[..1]);
|
||||
app.transcript_cells
|
||||
.extend(project(&app, ¤t.items[1..2]));
|
||||
app.join_older_activity_group(/*boundary*/ 1, std::slice::from_ref(¤t));
|
||||
assert!(app.transcript_cells.is_empty());
|
||||
if matches!(kind, ActivityKind::Computer) {
|
||||
assert!(
|
||||
crate::chatwidget::tests::helpers::render_bottom_popup(
|
||||
&app.chat_widget,
|
||||
/*width*/ 80
|
||||
)
|
||||
.contains("Using computer · 3 actions")
|
||||
);
|
||||
}
|
||||
match kind {
|
||||
ActivityKind::Computer => app.chat_widget.handle_mcp_tool_call_completed_now(call(
|
||||
"pending",
|
||||
kind,
|
||||
"completed",
|
||||
)),
|
||||
ActivityKind::Exploration => app
|
||||
.chat_widget
|
||||
.handle_command_execution_completed_now(call("pending", kind, "completed")),
|
||||
}
|
||||
current.items[3] = ThreadItem::untimed(call("pending", kind, "completed"));
|
||||
let expected = project(&app, ¤t.items);
|
||||
assert_eq!(
|
||||
app.chat_widget
|
||||
.active_cell_transcript_lines(/*width*/ 80)
|
||||
.unwrap(),
|
||||
expected[0].transcript_lines(/*width*/ 80),
|
||||
"{kind:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn trailing_reasoning_identity_rejects_identical_text_from_another_turn() {
|
||||
for kind in [ActivityKind::Computer, ActivityKind::Exploration] {
|
||||
let mut app = make_test_app().await;
|
||||
let mut same_turn = reasoning("same-turn-detail");
|
||||
let mut next_turn = reasoning("next-turn-detail");
|
||||
for item in [&mut same_turn, &mut next_turn] {
|
||||
if let ThreadItemPayload::Reasoning { summary, .. } = item {
|
||||
*summary = vec!["Exactly the same reasoning text".to_owned()];
|
||||
}
|
||||
}
|
||||
let first = turn(vec![call("call", kind, "completed"), same_turn.clone()]);
|
||||
let mut second = turn(vec![next_turn.clone()]);
|
||||
second.id = "next-turn".to_owned();
|
||||
let turns = vec![first, second];
|
||||
for detail in [same_turn, next_turn] {
|
||||
let older = project(&app, &turns[0].items[..1]).remove(/*index*/ 0);
|
||||
let trailing = project(&app, std::slice::from_ref(&detail)).remove(/*index*/ 0);
|
||||
app.transcript_cells = vec![Arc::clone(&older), Arc::clone(&trailing)];
|
||||
app.join_older_activity_group(/*boundary*/ 1, &turns);
|
||||
if detail.id() == "same-turn-detail" {
|
||||
let expected = project(&app, &turns[0].items);
|
||||
assert_eq!(app.transcript_cells.len(), 1);
|
||||
assert_eq!(app.transcript_cells[0].raw_lines(), expected[0].raw_lines());
|
||||
} else {
|
||||
assert_eq!(app.transcript_cells.len(), 2);
|
||||
assert!(Arc::ptr_eq(&app.transcript_cells[0], &older));
|
||||
assert!(Arc::ptr_eq(&app.transcript_cells[1], &trailing));
|
||||
}
|
||||
}
|
||||
// Live reasoning without persisted identity cannot prove an older-page relationship.
|
||||
let unidentified: Arc<dyn HistoryCell> = Arc::new(history_cell::ReasoningSummaryCell::new(
|
||||
String::new(),
|
||||
"Exactly the same reasoning text".to_owned(),
|
||||
app.config.cwd.as_path(),
|
||||
/*transcript_only*/ true,
|
||||
));
|
||||
app.transcript_cells = project(&app, &turns[0].items[..1]);
|
||||
app.transcript_cells.push(Arc::clone(&unidentified));
|
||||
app.join_older_activity_group(/*boundary*/ 1, &turns);
|
||||
assert_eq!(app.transcript_cells.len(), 2);
|
||||
assert!(Arc::ptr_eq(&app.transcript_cells[1], &unidentified));
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn every_page_split_folds_reasoning_before_answer_and_completion_boundaries() {
|
||||
for kind in [ActivityKind::Computer, ActivityKind::Exploration] {
|
||||
for answer in [None, Some("The answer")] {
|
||||
let mut app = make_test_app().await;
|
||||
let mut items = vec![call("call", kind, "completed"), reasoning("detail")];
|
||||
if let Some(text) = answer {
|
||||
items.push(ThreadItemPayload::AgentMessage {
|
||||
moderation: None,
|
||||
id: "answer".to_owned(),
|
||||
text: text.to_owned(),
|
||||
phase: None,
|
||||
memory_citation: None,
|
||||
delivery: None,
|
||||
questions: None,
|
||||
});
|
||||
}
|
||||
let current = turn(items);
|
||||
let separator: Arc<dyn HistoryCell> =
|
||||
Arc::new(history_cell::FinalMessageSeparator::new(
|
||||
/*elapsed_seconds*/ Some(65),
|
||||
/*runtime_metrics*/ None,
|
||||
));
|
||||
let mut expected = project(&app, ¤t.items);
|
||||
expected.push(Arc::clone(&separator));
|
||||
for split in 1..current.items.len() {
|
||||
let older = project(&app, ¤t.items[..split]);
|
||||
let mut newer = project(&app, ¤t.items[split..]);
|
||||
newer.push(Arc::clone(&separator));
|
||||
let boundary = older.len();
|
||||
app.transcript_cells = older.into_iter().chain(newer).collect();
|
||||
app.join_older_activity_group(boundary, std::slice::from_ref(¤t));
|
||||
for width in [24, 80] {
|
||||
let rendered = |cells: &[Arc<dyn HistoryCell>]| {
|
||||
cells
|
||||
.iter()
|
||||
.map(|cell| {
|
||||
(
|
||||
cell.display_hyperlink_lines(width),
|
||||
cell.transcript_hyperlink_lines(width),
|
||||
cell.raw_lines(),
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(
|
||||
rendered(&app.transcript_cells),
|
||||
rendered(&expected),
|
||||
"{kind:?}, answer {answer:?}, split {split}"
|
||||
);
|
||||
}
|
||||
assert!(Arc::ptr_eq(
|
||||
app.transcript_cells.last().unwrap(),
|
||||
&separator
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_exploration_retains_following_reasoning_at_every_page_split() {
|
||||
let mut app = make_test_app().await;
|
||||
let mut failed = call("failed", ActivityKind::Exploration, "failed");
|
||||
if let ThreadItemPayload::CommandExecution { exit_code, .. } = &mut failed {
|
||||
*exit_code = Some(1);
|
||||
}
|
||||
let current = turn(vec![
|
||||
call("first", ActivityKind::Exploration, "completed"),
|
||||
failed,
|
||||
reasoning("after-failure"),
|
||||
]);
|
||||
let expected = project(&app, ¤t.items);
|
||||
assert_eq!(expected.len(), 1);
|
||||
for split in 1..current.items.len() {
|
||||
let older = project(&app, ¤t.items[..split]);
|
||||
let boundary = older.len();
|
||||
app.transcript_cells = older
|
||||
.into_iter()
|
||||
.chain(project(&app, ¤t.items[split..]))
|
||||
.collect();
|
||||
app.join_older_activity_group(boundary, std::slice::from_ref(¤t));
|
||||
let rendered = |cells: &[Arc<dyn HistoryCell>]| {
|
||||
cells
|
||||
.iter()
|
||||
.map(|cell| cell.transcript_hyperlink_lines(/*width*/ 80))
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(
|
||||
rendered(&app.transcript_cells),
|
||||
rendered(&expected),
|
||||
"split {split}"
|
||||
);
|
||||
}
|
||||
}
|
||||
191
akode-rs/tui/src/app/agent_center/hints.rs
Normal file
191
akode-rs/tui/src/app/agent_center/hints.rs
Normal file
@@ -0,0 +1,191 @@
|
||||
//! A compact footer advertises primary actions; help lists the configured task shortcuts.
|
||||
|
||||
use super::*;
|
||||
use crate::key_hint;
|
||||
use crate::shortcut_help::Group;
|
||||
use crate::shortcut_help::Shortcut;
|
||||
use crate::style::footer_hint_label_style;
|
||||
|
||||
pub(super) fn hint_line(items: &[(String, String)]) -> Line<'static> {
|
||||
let mut line = Line::default();
|
||||
for (key, label) in items.iter().filter(|(key, _)| !key.is_empty()) {
|
||||
if !line.spans.is_empty() {
|
||||
line.spans.push(" ".dim());
|
||||
}
|
||||
line.spans.extend(key_hint::key_label_spans(key));
|
||||
line.spans.push(Span::styled(
|
||||
format!(" {label}"),
|
||||
footer_hint_label_style().not_bold(),
|
||||
));
|
||||
}
|
||||
line
|
||||
}
|
||||
|
||||
impl AgentsOverviewView {
|
||||
fn center_list_hint(&self, action: ListAction) -> Option<ShortcutHint> {
|
||||
self.keymap.primary_hint(action).filter(|hint| {
|
||||
!matches!(hint, ShortcutHint::Single(binding) if [
|
||||
&self.agents_keymap.resume,
|
||||
&self.agents_keymap.search,
|
||||
&self.agents_keymap.new_task,
|
||||
&self.agents_keymap.new_worktree,
|
||||
&self.agents_keymap.fork,
|
||||
&self.agents_keymap.rename,
|
||||
&self.agents_keymap.stop,
|
||||
&self.agents_keymap.archive,
|
||||
&self.agents_keymap.delete,
|
||||
&self.agents_keymap.hide,
|
||||
&self.agents_keymap.toggle_pin,
|
||||
&self.agents_keymap.toggle_grouping,
|
||||
].into_iter().any(|bindings| bindings.contains(binding)))
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn center_filter_hint(&self) -> String {
|
||||
[key_hint::plain(KeyCode::Tab), key_hint::shift(KeyCode::Tab)]
|
||||
.into_iter()
|
||||
.filter(|hint| {
|
||||
let (code, modifiers) = hint.parts();
|
||||
!self
|
||||
.center_shortcut_keys
|
||||
.is_pressed(KeyEvent::new(code, modifiers))
|
||||
})
|
||||
.map(|hint| hint.display_label())
|
||||
.collect::<Vec<_>>()
|
||||
.join("/")
|
||||
}
|
||||
|
||||
pub(super) fn center_help_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
let mut navigate = Group {
|
||||
title: "Navigate",
|
||||
entries: Vec::new(),
|
||||
};
|
||||
for (action, label) in [
|
||||
(ListAction::MoveUp, "Up"),
|
||||
(ListAction::MoveDown, "Down"),
|
||||
(ListAction::Accept, "Open"),
|
||||
(ListAction::PageUp, "Page up"),
|
||||
(ListAction::PageDown, "Page down"),
|
||||
] {
|
||||
navigate.push(self.center_list_hint(action), label);
|
||||
}
|
||||
navigate
|
||||
.entries
|
||||
.push(Shortcut::new(key_hint::ctrl(KeyCode::Char('c')), "Quit"));
|
||||
let mut tasks = Group {
|
||||
title: "Tasks",
|
||||
entries: Vec::new(),
|
||||
};
|
||||
for (action, bindings, label) in [
|
||||
("new_task", &self.agents_keymap.new_task, "New"),
|
||||
(
|
||||
"new_worktree",
|
||||
&self.agents_keymap.new_worktree,
|
||||
"New worktree",
|
||||
),
|
||||
("resume", &self.agents_keymap.resume, "Resume"),
|
||||
("fork", &self.agents_keymap.fork, "Fork"),
|
||||
("rename", &self.agents_keymap.rename, "Rename"),
|
||||
("stop", &self.agents_keymap.stop, "Stop"),
|
||||
("archive", &self.agents_keymap.archive, "Archive"),
|
||||
("hide", &self.agents_keymap.hide, "Hide"),
|
||||
("delete", &self.agents_keymap.delete, "Delete"),
|
||||
("toggle_pin", &self.agents_keymap.toggle_pin, "Pin/unpin"),
|
||||
] {
|
||||
if (action != "new_worktree" || self.worktrees_enabled)
|
||||
&& (action != "toggle_pin" || self.can_toggle_selected_pin())
|
||||
{
|
||||
tasks.push(self.agents_keymap.primary_hint(action, bindings), label);
|
||||
}
|
||||
}
|
||||
let mut view = Group {
|
||||
title: "View",
|
||||
entries: Vec::new(),
|
||||
};
|
||||
let filter = self.center_filter_hint();
|
||||
if !filter.is_empty() {
|
||||
view.entries.push(Shortcut {
|
||||
key: filter,
|
||||
action: "Filter",
|
||||
});
|
||||
}
|
||||
for (action, bindings, label) in [
|
||||
("search", &self.agents_keymap.search, "Search"),
|
||||
(
|
||||
"toggle_grouping",
|
||||
&self.agents_keymap.toggle_grouping,
|
||||
"Group",
|
||||
),
|
||||
] {
|
||||
view.push(self.agents_keymap.primary_hint(action, bindings), label);
|
||||
}
|
||||
let mut lines = vec!["Task shortcuts".bold().into(), Line::default()];
|
||||
lines.extend(crate::shortcut_help::group_lines(
|
||||
[navigate, tasks, view],
|
||||
width,
|
||||
));
|
||||
crate::wrapping::word_wrap_lines(lines, usize::from(width.max(/*other*/ 1)))
|
||||
}
|
||||
|
||||
pub(super) fn center_footer_hints(&self) -> Vec<(String, String)> {
|
||||
let state = self.state();
|
||||
if let Some(items) = &state.key_chord_hint {
|
||||
return items.clone();
|
||||
}
|
||||
let mut hints = Vec::new();
|
||||
if !state.help
|
||||
&& !state.editing_metadata()
|
||||
&& ![KeyModifiers::NONE, KeyModifiers::SHIFT]
|
||||
.into_iter()
|
||||
.any(|modifiers| {
|
||||
self.center_shortcut_keys
|
||||
.is_pressed(KeyEvent::new(KeyCode::Char('?'), modifiers))
|
||||
})
|
||||
{
|
||||
hints.push(("?".into(), "help".into()));
|
||||
}
|
||||
let cancel = if state.help {
|
||||
self.keymap.primary_hint(ListAction::Cancel)
|
||||
} else if state.editing_metadata() || self.can_return_to_chat {
|
||||
self.center_list_hint(ListAction::Cancel)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(hint) = cancel {
|
||||
hints.push((hint.display_label(), "back".into()));
|
||||
}
|
||||
if state.help {
|
||||
return hints;
|
||||
}
|
||||
if !state.editing_metadata() {
|
||||
let navigation = [ListAction::MoveUp, ListAction::MoveDown]
|
||||
.into_iter()
|
||||
.filter_map(|action| self.center_list_hint(action))
|
||||
.map(ShortcutHint::display_label)
|
||||
.collect::<Vec<_>>()
|
||||
.join("/");
|
||||
if !navigation.is_empty() {
|
||||
hints.push((navigation, "move".into()));
|
||||
}
|
||||
}
|
||||
if let Some(hint) = self.center_list_hint(ListAction::Accept) {
|
||||
hints.push((
|
||||
hint.display_label(),
|
||||
if state.rename_target.is_some() {
|
||||
"rename"
|
||||
} else {
|
||||
"open"
|
||||
}
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
if !state.editing_metadata()
|
||||
&& let Some(hint) = self
|
||||
.agents_keymap
|
||||
.primary_hint("new_task", &self.agents_keymap.new_task)
|
||||
{
|
||||
hints.push((hint.display_label(), "new".into()));
|
||||
}
|
||||
hints
|
||||
}
|
||||
}
|
||||
110
akode-rs/tui/src/app/agent_center/input.rs
Normal file
110
akode-rs/tui/src/app/agent_center/input.rs
Normal file
@@ -0,0 +1,110 @@
|
||||
//! Shared rename editing and task shortcuts respect configured editor and list bindings.
|
||||
|
||||
use super::*;
|
||||
use crossterm::event::KeyEventKind;
|
||||
|
||||
impl AgentsOverviewView {
|
||||
pub(in crate::app::agents_overview_view) fn rename_key(&mut self, key: KeyEvent) -> bool {
|
||||
let mut state = self.state();
|
||||
if state.rename_target.is_none() {
|
||||
return false;
|
||||
}
|
||||
let input = &mut state.input;
|
||||
let editing = input.should_handle_vim_insert_escape(key) || input.is_vim_operator_pending();
|
||||
if !editing {
|
||||
match self.keymap.action_for(key) {
|
||||
Some(ListAction::Cancel) => {
|
||||
drop(state);
|
||||
self.on_ctrl_c();
|
||||
return true;
|
||||
}
|
||||
Some(ListAction::Accept) if !is_plain_text_key_event(key) => {
|
||||
let online = state.connection_notice.is_none() && !state.creating_worktree;
|
||||
drop(state);
|
||||
if online {
|
||||
self.activate();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let editor_binding = crate::keymap::keymap_action_ids()
|
||||
.filter(|action| action.context == input.keymap_context())
|
||||
.any(|action| {
|
||||
crate::keymap::bindings_for_action(
|
||||
&self.editor_keymap,
|
||||
action.context.config_name(),
|
||||
action.action,
|
||||
)
|
||||
.is_some_and(|bindings| bindings.is_pressed(key))
|
||||
});
|
||||
if editing
|
||||
|| is_plain_text_key_event(key)
|
||||
|| editor_binding
|
||||
|| !self.center_shortcut_keys.is_pressed(key)
|
||||
{
|
||||
input.input(key);
|
||||
return !crate::keymap::is_dispatch_token_event(key);
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
pub(in crate::app::agents_overview_view) fn command_center_key(
|
||||
&mut self,
|
||||
key: KeyEvent,
|
||||
) -> bool {
|
||||
if self.state().editing_metadata() {
|
||||
if self.keymap.action_for(key) == Some(ListAction::Cancel) {
|
||||
self.on_ctrl_c();
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
let mut state = self.state();
|
||||
if state.help && self.keymap.action_for(key) == Some(ListAction::Cancel) {
|
||||
state.help = false;
|
||||
return true;
|
||||
}
|
||||
if state.help {
|
||||
if key.code == KeyCode::Char('?')
|
||||
&& key.kind == KeyEventKind::Press
|
||||
&& !key
|
||||
.modifiers
|
||||
.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)
|
||||
{
|
||||
state.help = false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
if self.center_shortcut_keys.is_pressed(key) {
|
||||
return false;
|
||||
}
|
||||
if key.code == KeyCode::Char('?')
|
||||
&& key.kind == KeyEventKind::Press
|
||||
&& !key
|
||||
.modifiers
|
||||
.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)
|
||||
{
|
||||
state.help = !state.help;
|
||||
return true;
|
||||
}
|
||||
if key.code == KeyCode::Tab
|
||||
&& !key
|
||||
.modifiers
|
||||
.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT)
|
||||
{
|
||||
let step = if key.modifiers.contains(KeyModifiers::SHIFT) {
|
||||
TASK_FILTERS.len() - 1
|
||||
} else {
|
||||
1
|
||||
};
|
||||
state.status_filter = (state.status_filter + step) % TASK_FILTERS.len();
|
||||
state.scroll = 0;
|
||||
drop(state);
|
||||
self.reconcile_command_center_selection();
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
}
|
||||
36
akode-rs/tui/src/app/agent_center/mod.rs
Normal file
36
akode-rs/tui/src/app/agent_center/mod.rs
Normal file
@@ -0,0 +1,36 @@
|
||||
//! Status filters and viewport state survive refreshes of the shared task projection.
|
||||
|
||||
mod hints;
|
||||
mod input;
|
||||
mod navigation;
|
||||
mod render;
|
||||
mod rows;
|
||||
|
||||
use super::*;
|
||||
|
||||
// Counts and filtering use the same status groups.
|
||||
pub(super) const TASK_FILTERS: &[(&str, Option<AgentsOverviewGroup>)] = &[
|
||||
("All", None),
|
||||
("Needs you", Some(AgentsOverviewGroup::NeedsYou)),
|
||||
("Working", Some(AgentsOverviewGroup::Working)),
|
||||
("Ready", Some(AgentsOverviewGroup::Ready)),
|
||||
("Inactive", Some(AgentsOverviewGroup::Finished)),
|
||||
];
|
||||
|
||||
impl AgentsOverviewView {
|
||||
pub(in crate::app::agents_overview_view) fn selectable_indices(&self) -> Vec<usize> {
|
||||
let mut indices = self.visible_indices();
|
||||
if self.state().more_available() {
|
||||
indices.push(usize::MAX);
|
||||
}
|
||||
indices
|
||||
}
|
||||
|
||||
pub(in crate::app::agents_overview_view) fn reconcile_command_center_selection(&mut self) {
|
||||
let visible = self.selectable_indices();
|
||||
if !visible.contains(&self.selected) {
|
||||
self.selected = visible.first().copied().unwrap_or(usize::MAX);
|
||||
self.state().show_more_selected = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
92
akode-rs/tui/src/app/agent_center/navigation.rs
Normal file
92
akode-rs/tui/src/app/agent_center/navigation.rs
Normal file
@@ -0,0 +1,92 @@
|
||||
//! Page navigation shares the rendered row layout, including group headings.
|
||||
//! Command-center paging moves the viewport and selection together without wrapping at either end.
|
||||
|
||||
use super::*;
|
||||
|
||||
pub(super) enum CenterRow {
|
||||
Group(usize),
|
||||
Task(usize),
|
||||
Gap,
|
||||
ShowMore,
|
||||
}
|
||||
|
||||
impl AgentsOverviewView {
|
||||
pub(super) fn center_rows(
|
||||
&self,
|
||||
indices: &[usize],
|
||||
grouping: AgentsOverviewGrouping,
|
||||
) -> Vec<CenterRow> {
|
||||
let mut entries = Vec::new();
|
||||
let mut previous = None;
|
||||
for index in indices.iter().copied() {
|
||||
if index == usize::MAX {
|
||||
entries.push(CenterRow::Gap);
|
||||
entries.push(CenterRow::ShowMore);
|
||||
continue;
|
||||
}
|
||||
if previous.is_none_or(|previous| !self.same_group(grouping, previous, index)) {
|
||||
if previous.is_some() {
|
||||
entries.push(CenterRow::Gap);
|
||||
}
|
||||
entries.push(CenterRow::Group(index));
|
||||
}
|
||||
entries.push(CenterRow::Task(index));
|
||||
previous = Some(index);
|
||||
}
|
||||
entries
|
||||
}
|
||||
|
||||
pub(in crate::app::agents_overview_view) fn page_selection(&mut self, action: ListAction) {
|
||||
let indices = self.selectable_indices();
|
||||
let mut state = self.state();
|
||||
if state.rename_target.is_some() || indices.is_empty() {
|
||||
return;
|
||||
}
|
||||
let forward = action == ListAction::PageDown;
|
||||
let entries = self.center_rows(&indices, state.grouping);
|
||||
let tasks = entries
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(position, row)| {
|
||||
if let CenterRow::Task(index) = row {
|
||||
Some((position, *index))
|
||||
} else if matches!(row, CenterRow::ShowMore) {
|
||||
Some((position, usize::MAX))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let current = tasks
|
||||
.iter()
|
||||
.find(|(_, index)| *index == self.selected)
|
||||
.map(|(position, _)| *position)
|
||||
.unwrap_or(tasks[0].0);
|
||||
let height = state.page_height.max(/*other*/ 1);
|
||||
let target = if forward {
|
||||
current.saturating_add(height)
|
||||
} else {
|
||||
current.saturating_sub(height)
|
||||
};
|
||||
let selected = if forward {
|
||||
tasks
|
||||
.partition_point(|(position, _)| *position < target)
|
||||
.min(tasks.len() - 1)
|
||||
} else {
|
||||
tasks
|
||||
.partition_point(|(position, _)| *position <= target)
|
||||
.saturating_sub(1)
|
||||
};
|
||||
let selected = tasks[selected].1;
|
||||
let scroll = state.scroll;
|
||||
state.scroll = (if forward {
|
||||
scroll.saturating_add(height)
|
||||
} else {
|
||||
scroll.saturating_sub(height)
|
||||
})
|
||||
.min(entries.len().saturating_sub(height));
|
||||
drop(state);
|
||||
self.selected = selected;
|
||||
self.state().show_more_selected = selected == usize::MAX;
|
||||
}
|
||||
}
|
||||
273
akode-rs/tui/src/app/agent_center/render.rs
Normal file
273
akode-rs/tui/src/app/agent_center/render.rs
Normal file
@@ -0,0 +1,273 @@
|
||||
//! Status tabs, task rows, the rename editor and details share a wide/narrow layout.
|
||||
|
||||
use super::hints::hint_line;
|
||||
use super::*;
|
||||
use crate::bottom_pane::render_filled_tab_bar;
|
||||
use crate::line_truncation::truncate_line_with_ellipsis_if_overflow;
|
||||
use crossterm::cursor::SetCursorStyle;
|
||||
use ratatui::widgets::WidgetRef;
|
||||
use unicode_segmentation::UnicodeSegmentation;
|
||||
|
||||
pub(super) fn row(area: Rect, offset: u16, height: u16) -> Rect {
|
||||
let offset = offset.min(area.height);
|
||||
Rect::new(
|
||||
area.x,
|
||||
area.y + offset,
|
||||
area.width,
|
||||
height.min(area.height - offset),
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn line(text: impl Into<Line<'static>>, area: Rect, buf: &mut Buffer) {
|
||||
if !area.is_empty() {
|
||||
truncate_line_with_ellipsis_if_overflow(text.into(), usize::from(area.width))
|
||||
.render(row(area, /*offset*/ 0, /*height*/ 1), buf);
|
||||
}
|
||||
}
|
||||
|
||||
fn visible_suffix(input: &str, available: usize) -> &str {
|
||||
let mut start = input.len();
|
||||
let mut visible_width = 0;
|
||||
for (offset, grapheme) in input.grapheme_indices(/*is_extended*/ true).rev() {
|
||||
let width = grapheme.width();
|
||||
if visible_width + width > available {
|
||||
break;
|
||||
}
|
||||
visible_width += width;
|
||||
start = offset;
|
||||
}
|
||||
&input[start..]
|
||||
}
|
||||
|
||||
struct CenterLayout {
|
||||
header: Rect,
|
||||
list: Rect,
|
||||
gap: Rect,
|
||||
details: Rect,
|
||||
search: Rect,
|
||||
footer: Rect,
|
||||
}
|
||||
|
||||
impl AgentsOverviewView {
|
||||
fn center_layout(&self, area: Rect) -> CenterLayout {
|
||||
let state = self.state();
|
||||
let footer_height = u16::from(area.height >= 2);
|
||||
let header_height = if area.height >= 6 { 3 } else { 0 };
|
||||
let footer = row(area, area.height - footer_height, footer_height);
|
||||
let header = row(area, /*offset*/ 0, header_height);
|
||||
let body = row(area, header_height, footer.y - header.bottom())
|
||||
.inner(Margin::new(/*horizontal*/ 2, /*vertical*/ 0));
|
||||
let [list, gap, details] = if body.width >= 90 {
|
||||
Layout::horizontal([
|
||||
Constraint::Min(46),
|
||||
Constraint::Length(3),
|
||||
Constraint::Length(38),
|
||||
])
|
||||
.areas(body)
|
||||
} else {
|
||||
[body, Rect::default(), Rect::default()]
|
||||
};
|
||||
let search = row(list, /*offset*/ 0, u16::from(state.editing_metadata()));
|
||||
let list = row(
|
||||
list,
|
||||
search.height,
|
||||
list.height.saturating_sub(search.height),
|
||||
);
|
||||
CenterLayout {
|
||||
header,
|
||||
list,
|
||||
gap,
|
||||
details,
|
||||
search,
|
||||
footer,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Renderable for AgentsOverviewView {
|
||||
fn desired_height(&self, _width: u16) -> u16 {
|
||||
24
|
||||
}
|
||||
|
||||
fn cursor_style(&self, _area: Rect) -> SetCursorStyle {
|
||||
let state = self.state();
|
||||
if state.rename_target.is_some() && state.input.uses_vim_insert_cursor() {
|
||||
SetCursorStyle::SteadyBar
|
||||
} else {
|
||||
SetCursorStyle::DefaultUserShape
|
||||
}
|
||||
}
|
||||
|
||||
fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> {
|
||||
let layout = self.center_layout(area);
|
||||
let state = self.state();
|
||||
if state.editing_metadata() && !layout.search.is_empty() {
|
||||
if state.rename_target.is_some() {
|
||||
let mut area = layout.search;
|
||||
let prefix_width = 9.min(area.width);
|
||||
area.x += prefix_width;
|
||||
area.width -= prefix_width;
|
||||
return state.input.cursor_pos(area);
|
||||
}
|
||||
let input = &state.search;
|
||||
let prefix = "Search › ";
|
||||
let available = usize::from(layout.search.width).saturating_sub(prefix.width() + 1);
|
||||
return Some((
|
||||
layout.search.x
|
||||
+ (prefix.width() + visible_suffix(input, available).width())
|
||||
.min(usize::from(layout.search.width.saturating_sub(/*rhs*/ 1)))
|
||||
as u16,
|
||||
layout.search.y,
|
||||
));
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn render(&self, area: Rect, buf: &mut Buffer) {
|
||||
Clear.render(area, buf);
|
||||
let layout = self.center_layout(area);
|
||||
let inset =
|
||||
|area: Rect| area.inner(Margin::new(/*horizontal*/ 2, /*vertical*/ 0));
|
||||
let footer_hints = self.center_footer_hints();
|
||||
let state = self.state();
|
||||
let filter_keys = if state.editing_metadata() {
|
||||
String::new()
|
||||
} else {
|
||||
self.center_filter_hint()
|
||||
};
|
||||
let grouping = match state.grouping {
|
||||
AgentsOverviewGrouping::Project => "Project",
|
||||
AgentsOverviewGrouping::Directory => "Directory",
|
||||
AgentsOverviewGrouping::Status => "Status",
|
||||
AgentsOverviewGrouping::Model => "Model",
|
||||
};
|
||||
let group_key = self
|
||||
.agents_keymap
|
||||
.primary_hint("toggle_grouping", &self.agents_keymap.toggle_grouping)
|
||||
.map(ShortcutHint::display_label)
|
||||
.unwrap_or_default();
|
||||
line(
|
||||
vec![
|
||||
"Agent command center".bold(),
|
||||
format!(" Group: {grouping} {group_key}").dim(),
|
||||
],
|
||||
inset(layout.header),
|
||||
buf,
|
||||
);
|
||||
let history = state.history.as_ref();
|
||||
let labels = TASK_FILTERS
|
||||
.iter()
|
||||
.map(|(label, group)| {
|
||||
let count = self
|
||||
.rows
|
||||
.iter()
|
||||
.filter(|row| state.includes_row(row))
|
||||
.filter(|row| group.is_none_or(|group| group == row.group))
|
||||
.count();
|
||||
format!("{label} {count}")
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let mut tabs = inset(row(layout.header, /*offset*/ 1, /*height*/ 1));
|
||||
let filter_hint = hint_line(&[(filter_keys, "filter".into())]);
|
||||
if tabs.width >= 80 && filter_hint.width() > 0 {
|
||||
let hint_width = filter_hint.width() as u16;
|
||||
filter_hint.render(
|
||||
Rect::new(tabs.right() - hint_width, tabs.y, hint_width, tabs.height),
|
||||
buf,
|
||||
);
|
||||
tabs.width = tabs.width.saturating_sub(hint_width + 2);
|
||||
}
|
||||
render_filled_tab_bar(
|
||||
&labels.iter().map(String::as_str).collect::<Vec<_>>(),
|
||||
state.status_filter,
|
||||
tabs,
|
||||
buf,
|
||||
);
|
||||
line(
|
||||
"─"
|
||||
.repeat(usize::from(area.width.saturating_sub(/*rhs*/ 4)))
|
||||
.dim(),
|
||||
inset(row(layout.header, /*offset*/ 2, /*height*/ 1)),
|
||||
buf,
|
||||
);
|
||||
if state.editing_metadata() {
|
||||
buf.set_style(layout.search, crate::bottom_pane::active_tab_style());
|
||||
if state.rename_target.is_some() {
|
||||
line("Rename › ".cyan().bold(), layout.search, buf);
|
||||
let mut area = layout.search;
|
||||
let prefix_width = 9.min(area.width);
|
||||
area.x += prefix_width;
|
||||
area.width -= prefix_width;
|
||||
WidgetRef::render_ref(&&state.input, area, buf);
|
||||
} else {
|
||||
let label = "Search › ";
|
||||
let available = usize::from(layout.search.width).saturating_sub(label.width() + 1);
|
||||
line(
|
||||
vec![
|
||||
label.cyan().bold(),
|
||||
visible_suffix(&state.search, available).to_owned().into(),
|
||||
],
|
||||
layout.search,
|
||||
buf,
|
||||
);
|
||||
}
|
||||
}
|
||||
let notice = state
|
||||
.connection_notice
|
||||
.map(str::to_owned)
|
||||
.or_else(|| {
|
||||
state
|
||||
.creating_worktree
|
||||
.then(|| "Creating worktree…".to_owned())
|
||||
})
|
||||
.or_else(|| {
|
||||
state.removal.map(|action| match action {
|
||||
AgentsOverviewAction::Archive => {
|
||||
"Archiving task… You can still browse.".to_owned()
|
||||
}
|
||||
AgentsOverviewAction::Delete => {
|
||||
"Deleting task… You can still browse.".to_owned()
|
||||
}
|
||||
})
|
||||
})
|
||||
.or_else(|| {
|
||||
let failed = state.refresh_failed || history.is_some_and(|s| s.failed);
|
||||
(failed && !state.loading).then(|| "Error loading tasks".to_owned())
|
||||
})
|
||||
.or_else(|| state.server_version_notice.clone());
|
||||
if let Some(notice) = notice.filter(|_| !state.help && state.key_chord_hint.is_none()) {
|
||||
line(notice.dim(), inset(layout.footer), buf);
|
||||
} else {
|
||||
line(hint_line(&footer_hints), inset(layout.footer), buf);
|
||||
}
|
||||
let help = state.help;
|
||||
drop(state);
|
||||
if help {
|
||||
let body = row(
|
||||
area,
|
||||
layout.header.height,
|
||||
layout.footer.y - layout.header.bottom(),
|
||||
);
|
||||
Clear.render(inset(body), buf);
|
||||
let body = inset(body);
|
||||
let mut lines = self.center_help_lines(body.width);
|
||||
if lines.len() > usize::from(body.height) {
|
||||
lines.truncate(usize::from(body.height.saturating_sub(/*rhs*/ 1)));
|
||||
lines.push("… resize to see all".dim().into());
|
||||
}
|
||||
Paragraph::new(lines).render(body, buf);
|
||||
return;
|
||||
}
|
||||
for y in layout.gap.y..layout.gap.bottom() {
|
||||
if layout.gap.width > 1 {
|
||||
buf[(layout.gap.x + 1, y)]
|
||||
.set_symbol("│")
|
||||
.set_style(Style::default().dim());
|
||||
}
|
||||
}
|
||||
self.render_center_rows(layout.list, buf);
|
||||
if !layout.details.is_empty() {
|
||||
self.render_details(layout.details, buf);
|
||||
}
|
||||
}
|
||||
}
|
||||
296
akode-rs/tui/src/app/agent_center/rows.rs
Normal file
296
akode-rs/tui/src/app/agent_center/rows.rs
Normal file
@@ -0,0 +1,296 @@
|
||||
//! Grouped live tasks with shared identity colors and stable title, status and age columns.
|
||||
//! Full titles use the flexible column; metadata drops at narrow widths.
|
||||
//! The final cell stays blank inside the full-width selection highlight.
|
||||
|
||||
use super::navigation::CenterRow;
|
||||
use super::render::line;
|
||||
use super::render::row;
|
||||
use super::*;
|
||||
use crate::bottom_pane::selection_style;
|
||||
use crate::resume_picker::format_relative_time;
|
||||
use crate::status::format_directory_display;
|
||||
|
||||
fn columns(area: Rect) -> (Rect, Rect, Rect) {
|
||||
let metadata = if area.width >= 56 { 24 } else { 0 };
|
||||
let gutter = area.width.min(/*other*/ 4);
|
||||
let title = Rect::new(
|
||||
area.x + gutter,
|
||||
area.y,
|
||||
area.width - gutter - metadata,
|
||||
area.height,
|
||||
);
|
||||
let updated = Rect::new(
|
||||
area.right() - metadata.min(/*other*/ 9),
|
||||
area.y,
|
||||
metadata.min(/*other*/ 9),
|
||||
area.height,
|
||||
);
|
||||
let status = Rect::new(
|
||||
title.right() + metadata.min(/*other*/ 2),
|
||||
area.y,
|
||||
if metadata == 24 { 11 } else { 0 },
|
||||
area.height,
|
||||
);
|
||||
(title, status, updated)
|
||||
}
|
||||
|
||||
impl AgentsOverviewView {
|
||||
pub(super) fn render_center_rows(&self, area: Rect, buf: &mut Buffer) {
|
||||
let row_width = area.width;
|
||||
let area = Rect {
|
||||
width: row_width.saturating_sub(/*rhs*/ 1),
|
||||
..area
|
||||
};
|
||||
if area.is_empty() {
|
||||
return;
|
||||
}
|
||||
let indices = self.selectable_indices();
|
||||
let mut state = self.state();
|
||||
if indices.is_empty() {
|
||||
line(
|
||||
if state.connection_notice.is_some() {
|
||||
"Reconnecting…"
|
||||
} else if state.history.is_some() {
|
||||
"No matching tasks"
|
||||
} else if state.loading && self.rows.is_empty() {
|
||||
"Loading tasks…"
|
||||
} else if state.refresh_failed {
|
||||
"Could not load tasks"
|
||||
} else if self.rows.is_empty() {
|
||||
"No tasks yet"
|
||||
} else {
|
||||
"No matching tasks"
|
||||
}
|
||||
.dim(),
|
||||
area,
|
||||
buf,
|
||||
);
|
||||
return;
|
||||
}
|
||||
let entries = self.center_rows(&indices, state.grouping);
|
||||
let selected = entries
|
||||
.iter()
|
||||
.position(|row| match row {
|
||||
CenterRow::Task(index) => *index == self.selected,
|
||||
CenterRow::ShowMore => self.selected == usize::MAX,
|
||||
_ => false,
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let padding = u16::from(area.height >= 3);
|
||||
let viewport = row(area, padding, area.height - padding * 2);
|
||||
if padding > 0 {
|
||||
let (title, status, updated) = columns(row(area, /*offset*/ 0, /*height*/ 1));
|
||||
line("Tasks".dim(), title, buf);
|
||||
line("Status".dim(), status, buf);
|
||||
Line::from("Updated".dim())
|
||||
.right_aligned()
|
||||
.render(updated, buf);
|
||||
}
|
||||
let reference = chrono::Utc::now();
|
||||
let height = usize::from(viewport.height);
|
||||
state.page_height = height;
|
||||
let mut start = state.scroll.min(entries.len().saturating_sub(height));
|
||||
if selected < start {
|
||||
start = if height > 1
|
||||
&& selected > 0
|
||||
&& matches!(entries[selected - 1], CenterRow::Group(_))
|
||||
{
|
||||
selected - 1
|
||||
} else {
|
||||
selected
|
||||
};
|
||||
}
|
||||
if selected >= start + height {
|
||||
start = selected.saturating_add(/*rhs*/ 1).saturating_sub(height);
|
||||
}
|
||||
state.scroll = start;
|
||||
for (offset, entry) in entries.iter().skip(start).take(height).enumerate() {
|
||||
let index = match entry {
|
||||
CenterRow::Group(index) | CenterRow::Task(index) => *index,
|
||||
CenterRow::Gap => continue,
|
||||
CenterRow::ShowMore => {
|
||||
let rect = row(viewport, offset as u16, /*height*/ 1);
|
||||
let selected = self.selected == usize::MAX;
|
||||
let style = if selected {
|
||||
selection_style()
|
||||
} else {
|
||||
Style::default()
|
||||
};
|
||||
buf.set_style(
|
||||
Rect {
|
||||
width: row_width,
|
||||
..rect
|
||||
},
|
||||
style,
|
||||
);
|
||||
let label = if let Some(search) = &state.history {
|
||||
if search.loading {
|
||||
"Searching history…"
|
||||
} else if search.failed {
|
||||
"Show more (retry)"
|
||||
} else {
|
||||
"Show more matches"
|
||||
}
|
||||
} else if state.loading {
|
||||
"Loading more…"
|
||||
} else if state.refresh_failed {
|
||||
"Show more (retry)"
|
||||
} else {
|
||||
"Show more"
|
||||
};
|
||||
let marker = if selected { "›" } else { " " };
|
||||
line(
|
||||
Line::from(format!("{marker} {label}")).style(style),
|
||||
rect,
|
||||
buf,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let task = &self.rows[index];
|
||||
let rect = row(viewport, offset as u16, /*height*/ 1);
|
||||
if matches!(entry, CenterRow::Group(_)) {
|
||||
let group = match state.grouping {
|
||||
AgentsOverviewGrouping::Status => task.group.label().to_owned(),
|
||||
_ if self.is_pinned(index) => "Pinned".to_owned(),
|
||||
AgentsOverviewGrouping::Project => format_directory_display(
|
||||
&self.project_groups[index].heading,
|
||||
/*max_width*/ None,
|
||||
),
|
||||
AgentsOverviewGrouping::Directory => format_directory_display(
|
||||
self.rows[index].thread.cwd.as_path(),
|
||||
/*max_width*/ None,
|
||||
),
|
||||
AgentsOverviewGrouping::Model => model_name(&task.thread).to_owned(),
|
||||
};
|
||||
let count = indices
|
||||
.iter()
|
||||
.filter(|&&candidate| {
|
||||
candidate != usize::MAX && self.same_group(state.grouping, candidate, index)
|
||||
})
|
||||
.count();
|
||||
let total = (0..self.rows.len())
|
||||
.filter(|&i| state.includes_row(&self.rows[i]))
|
||||
.filter(|&candidate| self.same_group(state.grouping, candidate, index))
|
||||
.count();
|
||||
let count = if count == total {
|
||||
count.to_string()
|
||||
} else {
|
||||
format!("{count} of {total}")
|
||||
};
|
||||
let group = if matches!(
|
||||
state.grouping,
|
||||
AgentsOverviewGrouping::Project | AgentsOverviewGrouping::Directory
|
||||
) && !self.is_pinned(index)
|
||||
{
|
||||
crate::text_formatting::center_truncate_path(
|
||||
&group,
|
||||
usize::from(rect.width)
|
||||
.saturating_sub(count.width() + 2)
|
||||
.min(/*other*/ 64),
|
||||
)
|
||||
} else {
|
||||
group
|
||||
};
|
||||
line(format!("{group} {count}").dim(), rect, buf);
|
||||
continue;
|
||||
}
|
||||
let style = if index == self.selected {
|
||||
selection_style()
|
||||
} else {
|
||||
Style::default()
|
||||
};
|
||||
buf.set_style(
|
||||
Rect {
|
||||
width: row_width,
|
||||
..rect
|
||||
},
|
||||
style,
|
||||
);
|
||||
let (status, mut dot) = Self::status(task);
|
||||
let idle = matches!(
|
||||
task.group,
|
||||
AgentsOverviewGroup::Ready | AgentsOverviewGroup::Finished
|
||||
);
|
||||
if task.unread || idle {
|
||||
dot = crate::style::task_marker(task.unread, style);
|
||||
} else if index == self.selected {
|
||||
dot.style = style;
|
||||
}
|
||||
line(
|
||||
Line::from(if index == self.selected { "›" } else { " " }).style(style),
|
||||
rect,
|
||||
buf,
|
||||
);
|
||||
line(
|
||||
Line::from(dot),
|
||||
Rect::new(
|
||||
rect.x + rect.width.min(/*other*/ 2),
|
||||
rect.y,
|
||||
rect.width.saturating_sub(/*rhs*/ 2).min(/*other*/ 1),
|
||||
/*height*/ 1,
|
||||
),
|
||||
buf,
|
||||
);
|
||||
let (mut title, status_area, updated) = columns(rect);
|
||||
if task.has_voice && title.width >= 8 {
|
||||
let badge = Rect::new(
|
||||
title.right() - 8,
|
||||
title.y,
|
||||
/*width*/ 8,
|
||||
/*height*/ 1,
|
||||
);
|
||||
title.width -= 8;
|
||||
line(Line::from(" voice").style(style), badge, buf);
|
||||
}
|
||||
let title_style = if index == self.selected {
|
||||
style
|
||||
} else {
|
||||
self.title_style(task.thread_id)
|
||||
};
|
||||
let task_title = display_title(&task.thread);
|
||||
// On narrow rows the result dot shares the only slot for the working or alert icon.
|
||||
let task_title = if task.unread && !idle && status_area.is_empty() {
|
||||
format!("{status}: {task_title}")
|
||||
} else {
|
||||
task_title.to_owned()
|
||||
};
|
||||
let task_title =
|
||||
if state.grouping == AgentsOverviewGrouping::Status && self.is_pinned(index) {
|
||||
format!("📌 {task_title}")
|
||||
} else {
|
||||
task_title
|
||||
};
|
||||
line(Line::from(task_title).style(title_style), title, buf);
|
||||
line(Line::from(status).style(style), status_area, buf);
|
||||
if !updated.is_empty() {
|
||||
let age = format_relative_time(
|
||||
reference,
|
||||
chrono::DateTime::from_timestamp(task.thread.updated_at, /*nsecs*/ 0),
|
||||
);
|
||||
Line::from(age)
|
||||
.style(if index == self.selected {
|
||||
style
|
||||
} else {
|
||||
style.dim()
|
||||
})
|
||||
.right_aligned()
|
||||
.render(updated, buf);
|
||||
}
|
||||
}
|
||||
if padding > 0 && start > 0 {
|
||||
line("↑".dim(), row(area, /*offset*/ 0, /*height*/ 1), buf);
|
||||
}
|
||||
if padding > 0 && start + height < entries.len() {
|
||||
line(
|
||||
"↓".dim(),
|
||||
row(
|
||||
area,
|
||||
area.height.saturating_sub(/*rhs*/ 1),
|
||||
/*height*/ 1,
|
||||
),
|
||||
buf,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
912
akode-rs/tui/src/app/agent_center_tests.rs
Normal file
912
akode-rs/tui/src/app/agent_center_tests.rs
Normal file
@@ -0,0 +1,912 @@
|
||||
//! Dashboard rows, paging, metadata clipping and status-filter regressions.
|
||||
|
||||
use super::*;
|
||||
use assert_matches::assert_matches;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
pub(super) fn screen(view: &AgentsOverviewView, width: u16, height: u16) -> String {
|
||||
let area = Rect::new(/*x*/ 0, /*y*/ 0, width, height);
|
||||
let mut buf = ratatui::buffer::Buffer::empty(area);
|
||||
view.render(area, &mut buf);
|
||||
crate::chatwidget::tests::helpers::normalize_agent_center_snapshot(
|
||||
buf.content
|
||||
.chunks(usize::from(width))
|
||||
.map(|row| {
|
||||
row.iter()
|
||||
.map(ratatui::buffer::Cell::symbol)
|
||||
.collect::<String>()
|
||||
.trim_end()
|
||||
.to_owned()
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n"),
|
||||
)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn live_center_keeps_status_order_across_progress_refreshes() {
|
||||
let mut app = make_test_app_with_chat().await;
|
||||
app.agents_overview.view_state.lock().unwrap().grouping = AgentsOverviewGrouping::Status;
|
||||
let ids = [1, 2, 3, 4, 5].map(ThreadId::from_u128);
|
||||
let mut threads = [
|
||||
(
|
||||
"Alpha",
|
||||
ThreadStatus::Active {
|
||||
active_flags: vec![],
|
||||
},
|
||||
10,
|
||||
),
|
||||
(
|
||||
"Bravo",
|
||||
ThreadStatus::Active {
|
||||
active_flags: vec![],
|
||||
},
|
||||
20,
|
||||
),
|
||||
(
|
||||
"Charlie",
|
||||
ThreadStatus::Active {
|
||||
active_flags: vec![],
|
||||
},
|
||||
20,
|
||||
),
|
||||
("Ready task", ThreadStatus::Idle, 40),
|
||||
("Needs input", ThreadStatus::SystemError, 0),
|
||||
]
|
||||
.into_iter()
|
||||
.zip(ids)
|
||||
.map(|((name, status, updated_at), id)| {
|
||||
let mut thread = overview_thread(id, /*parent_thread_id*/ None, name, status);
|
||||
// Future timestamps render as "now", keeping the visual fixture clock-independent.
|
||||
thread.updated_at = 4_000_000_000 + updated_at;
|
||||
thread
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
threads.reverse();
|
||||
let view = app.agents_overview_view(threads.clone(), Some(ids[0]));
|
||||
let expected = vec![ids[4], ids[1], ids[2], ids[0], ids[3]];
|
||||
assert_eq!(view.thread_ids(), expected);
|
||||
let before = screen(&view, /*width*/ 100, /*height*/ 18);
|
||||
app.agents_overview.visible_thread_ids = view.thread_ids();
|
||||
app.chat_widget.show_bottom_pane_view(Box::new(view));
|
||||
|
||||
for (step, id) in [ids[0], ids[2], ids[1], ids[0]].into_iter().enumerate() {
|
||||
let thread = threads
|
||||
.iter_mut()
|
||||
.find(|thread| thread.id == id.to_string())
|
||||
.unwrap();
|
||||
thread.updated_at = 4_000_000_100 + step as i64;
|
||||
thread.preview = format!("Progress update {step}");
|
||||
threads.rotate_left(/*mid*/ 1);
|
||||
app.agents_overview.threads = threads
|
||||
.iter()
|
||||
.cloned()
|
||||
.map(|thread| (ThreadId::from_string(&thread.id).unwrap(), Some(thread)))
|
||||
.collect();
|
||||
app.repaint_agents_overview();
|
||||
assert_eq!(app.agents_overview.visible_thread_ids[1], id);
|
||||
let selected = app
|
||||
.chat_widget
|
||||
.selected_index_for_present_view(AGENTS_OVERVIEW_VIEW_ID)
|
||||
.unwrap();
|
||||
assert_eq!(app.agents_overview.visible_thread_ids[selected], ids[0]);
|
||||
}
|
||||
app.agents_overview.pinned_thread_ids = Some(vec![ids[3], ids[2]]);
|
||||
for parent in [ids[0], ids[3]] {
|
||||
threads.push(overview_thread(
|
||||
ThreadId::new(),
|
||||
Some(parent),
|
||||
"Failed subagent",
|
||||
ThreadStatus::SystemError,
|
||||
));
|
||||
}
|
||||
let view = app.agents_overview_view(threads, Some(ids[0]));
|
||||
assert!(
|
||||
view.rows[view.selected_index().unwrap()]
|
||||
.details
|
||||
.lines
|
||||
.is_empty()
|
||||
);
|
||||
let after = screen(&view, /*width*/ 100, /*height*/ 18);
|
||||
insta::assert_snapshot!(format!(
|
||||
"Initial display:\n{before}\n\nAfter subagents fail under Alpha and Ready task:\n{after}"
|
||||
));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_background_worker_only_needs_attention_for_a_pending_request() {
|
||||
let app = make_test_app().await;
|
||||
let worker_id = ThreadId::new();
|
||||
let mut worker = overview_thread(
|
||||
worker_id,
|
||||
/*parent_thread_id*/ None,
|
||||
"Background review",
|
||||
ThreadStatus::SystemError,
|
||||
);
|
||||
worker.source = SessionSource::SubAgent(SubAgentSource::Review);
|
||||
let view = app.agents_overview_view(vec![worker.clone()], Some(worker_id));
|
||||
assert_eq!(view.rows[0].group, AgentsOverviewGroup::Finished);
|
||||
assert!(view.rows[0].details.lines.is_empty());
|
||||
|
||||
let child = overview_thread(
|
||||
ThreadId::new(),
|
||||
Some(worker_id),
|
||||
"Check dependencies",
|
||||
ThreadStatus::Active {
|
||||
active_flags: vec![ThreadActiveFlag::WaitingOnApproval],
|
||||
},
|
||||
);
|
||||
let view = app.agents_overview_view(vec![worker, child], Some(worker_id));
|
||||
assert_eq!(view.rows[0].group, AgentsOverviewGroup::NeedsYou);
|
||||
let rendered = screen(&view, /*width*/ 100, /*height*/ 32);
|
||||
assert!(rendered.contains("● Needs input"));
|
||||
assert!(rendered.contains("Waiting for approval."));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn live_center_sorts_arrivals_and_status_transitions_by_update_time() {
|
||||
let app = make_test_app().await;
|
||||
let [alpha, bravo, charlie, delta, child] = [1, 2, 3, 4, 5].map(ThreadId::from_u128);
|
||||
let working = ThreadStatus::Active {
|
||||
active_flags: vec![],
|
||||
};
|
||||
let mut threads = vec![
|
||||
overview_thread(
|
||||
alpha,
|
||||
/*parent_thread_id*/ None,
|
||||
"Alpha",
|
||||
working.clone(),
|
||||
),
|
||||
overview_thread(
|
||||
bravo,
|
||||
/*parent_thread_id*/ None,
|
||||
"Bravo",
|
||||
working.clone(),
|
||||
),
|
||||
overview_thread(
|
||||
charlie,
|
||||
/*parent_thread_id*/ None,
|
||||
"Charlie",
|
||||
ThreadStatus::Idle,
|
||||
),
|
||||
];
|
||||
assert_eq!(
|
||||
app.agents_overview_view(threads.clone(), Some(bravo))
|
||||
.thread_ids(),
|
||||
vec![alpha, bravo, charlie]
|
||||
);
|
||||
let mut arrival = overview_thread(delta, /*parent_thread_id*/ None, "Delta", working);
|
||||
arrival.updated_at += 100;
|
||||
threads.push(arrival);
|
||||
let mut child = overview_thread(
|
||||
child,
|
||||
/*parent_thread_id*/ None,
|
||||
"Child",
|
||||
ThreadStatus::SystemError,
|
||||
);
|
||||
child.parent_thread_id = Some(bravo.to_string());
|
||||
threads.push(child);
|
||||
assert_eq!(
|
||||
app.agents_overview_view(threads.clone(), Some(bravo))
|
||||
.thread_ids(),
|
||||
vec![delta, alpha, bravo, charlie]
|
||||
);
|
||||
threads[1].status = ThreadStatus::Idle;
|
||||
let view = app.agents_overview_view(threads.clone(), Some(bravo));
|
||||
assert_eq!(view.thread_ids(), vec![delta, alpha, bravo, charlie]);
|
||||
let selected = &view.rows[view.selected_index().unwrap()];
|
||||
assert_eq!(selected.group, AgentsOverviewGroup::Ready);
|
||||
assert!(selected.details.lines.is_empty());
|
||||
// A request from a descendant can still bring its idle parent to the top.
|
||||
threads.last_mut().unwrap().status = ThreadStatus::Active {
|
||||
active_flags: vec![ThreadActiveFlag::WaitingOnApproval],
|
||||
};
|
||||
assert_eq!(
|
||||
app.agents_overview_view(threads.clone(), Some(bravo))
|
||||
.thread_ids(),
|
||||
vec![bravo, delta, alpha, charlie]
|
||||
);
|
||||
threads.pop();
|
||||
let view = app.agents_overview_view(threads.clone(), Some(bravo));
|
||||
assert_eq!(view.thread_ids(), vec![delta, alpha, bravo, charlie]);
|
||||
assert_eq!(view.rows[view.selected_index().unwrap()].thread_id, bravo);
|
||||
// Rediscovery restores the task to its position by update time.
|
||||
let removed = threads.remove(/*index*/ 0);
|
||||
assert_eq!(
|
||||
app.agents_overview_view(threads.clone(), Some(bravo))
|
||||
.thread_ids(),
|
||||
vec![delta, bravo, charlie]
|
||||
);
|
||||
threads.push(removed);
|
||||
assert_eq!(
|
||||
app.agents_overview_view(threads, Some(bravo)).thread_ids(),
|
||||
vec![delta, alpha, bravo, charlie]
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn live_center_status_order_tracks_updates_while_filtered_and_pinned() {
|
||||
let mut app = make_test_app().await;
|
||||
app.agents_overview.view_state.lock().unwrap().grouping = AgentsOverviewGrouping::Status;
|
||||
let ids = [1, 2, 3].map(ThreadId::from_u128);
|
||||
let mut threads = ["Alpha", "Bravo", "Charlie"]
|
||||
.into_iter()
|
||||
.zip(ids)
|
||||
.map(|(name, id)| {
|
||||
overview_thread(
|
||||
id,
|
||||
/*parent_thread_id*/ None,
|
||||
name,
|
||||
ThreadStatus::Active {
|
||||
active_flags: vec![],
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let rendered_titles = |view: &AgentsOverviewView| {
|
||||
screen(view, /*width*/ 100, /*height*/ 18)
|
||||
.lines()
|
||||
.filter_map(|line| {
|
||||
let (_, task_column) = line.split('│').next()?.split_once("● ")?;
|
||||
let task_column = task_column.trim_start_matches('📌').trim_start();
|
||||
["Alpha", "Bravo", "Charlie"]
|
||||
.into_iter()
|
||||
.find(|title| task_column.starts_with(title))
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let mut view = app.agents_overview_view(threads.clone(), Some(ids[1]));
|
||||
// Hidden rows also pick up timestamp changes when the filter is cleared.
|
||||
view.handle_key_event(KeyCode::Char('/').into());
|
||||
view.handle_paste("Bravo".into());
|
||||
threads[2].updated_at += 100;
|
||||
view = app.agents_overview_view(threads.clone(), Some(ids[1]));
|
||||
assert_eq!(rendered_titles(&view), vec!["Bravo"]);
|
||||
view.handle_key_event(KeyCode::Esc.into());
|
||||
assert_eq!(rendered_titles(&view), vec!["Charlie", "Alpha", "Bravo"]);
|
||||
// Update another working task while the empty Needs input tab is selected.
|
||||
view.handle_key_event(KeyCode::Tab.into());
|
||||
assert!(rendered_titles(&view).is_empty());
|
||||
threads[1].updated_at += 200;
|
||||
view = app.agents_overview_view(threads.clone(), /*selected_thread_id*/ None);
|
||||
view.handle_key_event(KeyCode::Tab.into());
|
||||
assert_eq!(rendered_titles(&view), vec!["Bravo", "Charlie", "Alpha"]);
|
||||
view.handle_key_event(KeyEvent::new(KeyCode::BackTab, KeyModifiers::SHIFT));
|
||||
view.handle_key_event(KeyEvent::new(KeyCode::BackTab, KeyModifiers::SHIFT));
|
||||
app.agents_overview.pinned_thread_ids = Some(vec![ids[0], ids[2]]);
|
||||
view = app.agents_overview_view(threads.clone(), Some(ids[1]));
|
||||
assert_eq!(rendered_titles(&view), vec!["Alpha", "Charlie", "Bravo"]);
|
||||
app.agents_overview.pinned_thread_ids = Some(vec![]);
|
||||
view = app.agents_overview_view(threads, Some(ids[1]));
|
||||
assert_eq!(rendered_titles(&view), vec!["Bravo", "Charlie", "Alpha"]);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn live_center_columns() {
|
||||
let mut app = make_test_app().await;
|
||||
let current = ThreadId::from_u128(/*value*/ 42);
|
||||
app.primary_thread_id = Some(current);
|
||||
let now = chrono::Utc::now().timestamp();
|
||||
let fixtures = [
|
||||
("Current task", ThreadStatus::Idle, -3600),
|
||||
(
|
||||
"A longer task title that uses the available column",
|
||||
ThreadStatus::Idle,
|
||||
330,
|
||||
),
|
||||
(
|
||||
"Needs an answer",
|
||||
ThreadStatus::Active {
|
||||
active_flags: vec![ThreadActiveFlag::WaitingOnUserInput],
|
||||
},
|
||||
7230,
|
||||
),
|
||||
("Unloaded task", ThreadStatus::NotLoaded, 172830),
|
||||
(
|
||||
"Working task",
|
||||
ThreadStatus::Active {
|
||||
active_flags: Vec::new(),
|
||||
},
|
||||
86430,
|
||||
),
|
||||
("Failed task", ThreadStatus::SystemError, 3630),
|
||||
];
|
||||
let mut threads = fixtures
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, (title, status, age))| {
|
||||
let mut thread = overview_thread(
|
||||
ThreadId::from_u128(index as u128 + 42),
|
||||
/*parent_thread_id*/ None,
|
||||
title,
|
||||
status.clone(),
|
||||
);
|
||||
thread.updated_at = now - age;
|
||||
thread
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let child = ThreadId::from_u128(/*value*/ 48);
|
||||
threads.push(overview_thread(
|
||||
child,
|
||||
Some(ThreadId::from_u128(/*value*/ 43)),
|
||||
"Child",
|
||||
ThreadStatus::Idle,
|
||||
));
|
||||
crate::chatwidget::activate_voice_for_thread(&mut app.chat_widget, child);
|
||||
app.agents_overview.pinned_thread_ids = Some(vec![current, ThreadId::from_u128(/*value*/ 44)]);
|
||||
app.agents_overview
|
||||
.unread
|
||||
.insert(ThreadId::from_u128(/*value*/ 47));
|
||||
let mut view = app.agents_overview_view(threads, Some(current));
|
||||
assert!(screen(&view, /*width*/ 50, /*height*/ 24).contains("● Error: Failed task"));
|
||||
insta::assert_snapshot!(screen(&view, /*width*/ 160, /*height*/ 22));
|
||||
view.pinned_thread_ranks = None;
|
||||
let mut selected_status_styles = Vec::new();
|
||||
for _ in 0..fixtures.len() {
|
||||
let area = Rect::new(
|
||||
/*x*/ 0, /*y*/ 0, /*width*/ 160, /*height*/ 22,
|
||||
);
|
||||
let mut buf = ratatui::buffer::Buffer::empty(area);
|
||||
view.render(area, &mut buf);
|
||||
let selected_row = buf
|
||||
.content
|
||||
.chunks(usize::from(area.width))
|
||||
.find(|row| row.iter().any(|cell| cell.symbol() == "›"))
|
||||
.unwrap();
|
||||
let marker = selected_row
|
||||
.iter()
|
||||
.position(|cell| cell.symbol() == "›")
|
||||
.unwrap();
|
||||
selected_status_styles.push(format!(
|
||||
"{} | {:?}",
|
||||
selected_row[marker + 2].symbol(),
|
||||
selected_row[marker + 2].style()
|
||||
));
|
||||
view.handle_key_event(KeyCode::Down.into());
|
||||
}
|
||||
insta::assert_snapshot!(
|
||||
"live_center_selected_status_styles",
|
||||
selected_status_styles.join("\n")
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn live_center_pages_visible_rows_without_wrapping() {
|
||||
for (count, offline) in [(5, false), (30, true)] {
|
||||
let app = make_test_app().await;
|
||||
let first = ThreadId::from_u128(/*value*/ 100);
|
||||
let threads = (0..count)
|
||||
.map(|index| {
|
||||
let mut thread = overview_thread(
|
||||
ThreadId::from_u128(100 + index),
|
||||
/*parent_thread_id*/ None,
|
||||
&format!("Paging task {index:02}"),
|
||||
ThreadStatus::Idle,
|
||||
);
|
||||
thread.updated_at -= index as i64;
|
||||
if index >= 10 {
|
||||
thread.cwd = test_path_buf("/tmp/second-project").abs();
|
||||
}
|
||||
thread
|
||||
})
|
||||
.collect();
|
||||
let mut view = app.agents_overview_view(threads, Some(first));
|
||||
if offline {
|
||||
app.agents_overview
|
||||
.view_state
|
||||
.lock()
|
||||
.unwrap()
|
||||
.connection_notice = Some("Reconnecting…");
|
||||
view.handle_key_event(KeyCode::Char('/').into());
|
||||
view.handle_paste("Paging".into());
|
||||
}
|
||||
screen(&view, /*width*/ 110, /*height*/ 18);
|
||||
view.handle_key_event(KeyCode::PageDown.into());
|
||||
// Eleven visible rows: skip the next heading/gap, or clamp a short list.
|
||||
assert_eq!(
|
||||
view.rows[view.selected_index().unwrap()].thread_id,
|
||||
ThreadId::from_u128(100 + (count - 1).min(10)),
|
||||
);
|
||||
let page_down = view.selected_index().unwrap();
|
||||
view.handle_key_event(KeyCode::PageUp.into());
|
||||
assert!(view.selected_index().unwrap() < page_down);
|
||||
view.handle_key_event(KeyCode::PageUp.into());
|
||||
assert_eq!(view.rows[view.selected_index().unwrap()].thread_id, first);
|
||||
// Repeated pages eventually reach the last filtered task and stay there.
|
||||
for _ in 0..count {
|
||||
view.handle_key_event(KeyEvent::new(KeyCode::Char('f'), KeyModifiers::CONTROL));
|
||||
screen(&view, /*width*/ 110, /*height*/ 18);
|
||||
}
|
||||
let last = view.rows[view.selected_index().unwrap()].thread_id;
|
||||
view.handle_key_event(KeyCode::PageDown.into());
|
||||
assert_eq!(
|
||||
(last, view.rows[view.selected_index().unwrap()].thread_id),
|
||||
(ThreadId::from_u128(100 + count - 1), last)
|
||||
);
|
||||
view.handle_key_event(KeyCode::Down.into());
|
||||
assert!(
|
||||
screen(&view, /*width*/ 110, /*height*/ 18)
|
||||
.lines()
|
||||
.any(|line| line.trim_start().starts_with("/tmp/project"))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn live_center_metadata_clips_at_grapheme_boundaries() {
|
||||
let app = make_test_app().await;
|
||||
let mut view = app.agents_overview_view(
|
||||
vec![overview_thread(
|
||||
ThreadId::new(),
|
||||
/*parent_thread_id*/ None,
|
||||
"Retained task",
|
||||
ThreadStatus::Idle,
|
||||
)],
|
||||
/*selected_thread_id*/ None,
|
||||
);
|
||||
let input = format!("{}日本語 e\u{301} 👩\u{200d}💻", "界".repeat(/*n*/ 100_000));
|
||||
for (key, label) in [('r', "Rename › "), ('/', "Search › ")] {
|
||||
view.handle_key_event(KeyCode::Char(key).into());
|
||||
view.handle_paste(input.clone());
|
||||
let rendered = screen(&view, /*width*/ 40, /*height*/ 18);
|
||||
let prompt = rendered.lines().find(|line| line.contains(label)).unwrap();
|
||||
assert!(prompt.contains("e\u{301}"));
|
||||
assert!(prompt.ends_with("👩\u{200d}💻"));
|
||||
assert_eq!(
|
||||
view.cursor_pos(Rect::new(
|
||||
/*x*/ 0, /*y*/ 0, /*width*/ 40, /*height*/ 18
|
||||
)),
|
||||
Some((36, 3))
|
||||
);
|
||||
if key == 'r' {
|
||||
let cursor = view
|
||||
.cursor_pos(Rect::new(
|
||||
/*x*/ 0, /*y*/ 0, /*width*/ 24, /*height*/ 18,
|
||||
))
|
||||
.unwrap();
|
||||
assert!(cursor.0 < 24);
|
||||
insta::assert_snapshot!("live_center_narrow_rename", rendered);
|
||||
}
|
||||
view.handle_key_event(KeyCode::Esc.into());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn live_center_rename_retains_target_when_status_leaves_filter() -> Result<()> {
|
||||
let mut app = make_test_app().await;
|
||||
app.chat_widget.toggle_vim_mode_and_notify();
|
||||
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
|
||||
app.app_event_tx = AppEventSender::new(tx);
|
||||
let id = ThreadId::new();
|
||||
let other = ThreadId::new();
|
||||
let mut threads = vec![
|
||||
overview_thread(
|
||||
id,
|
||||
/*parent_thread_id*/ None,
|
||||
"Tar\nget",
|
||||
ThreadStatus::Idle,
|
||||
),
|
||||
overview_thread(
|
||||
other,
|
||||
/*parent_thread_id*/ None,
|
||||
"Other",
|
||||
ThreadStatus::Idle,
|
||||
),
|
||||
];
|
||||
for key in [KeyCode::Esc, KeyCode::Enter] {
|
||||
threads[0].status = ThreadStatus::Idle;
|
||||
let mut view = app.agents_overview_view(threads.clone(), Some(id));
|
||||
// Reuse the Ready tab after the first iteration.
|
||||
if key == KeyCode::Esc {
|
||||
for _ in 0..3 {
|
||||
view.handle_key_event(KeyCode::Tab.into());
|
||||
}
|
||||
}
|
||||
view.handle_key_event(KeyCode::Char('r').into());
|
||||
assert_eq!(
|
||||
view.cursor_style(Rect::default()),
|
||||
crossterm::cursor::SetCursorStyle::SteadyBar
|
||||
);
|
||||
threads[0].status = ThreadStatus::SystemError;
|
||||
view = app.agents_overview_view(threads.clone(), Some(id));
|
||||
if key == KeyCode::Enter {
|
||||
for edit in [
|
||||
KeyCode::Esc,
|
||||
KeyCode::Char('0'),
|
||||
KeyCode::Char('c'),
|
||||
KeyCode::Char('w'),
|
||||
] {
|
||||
view.handle_key_event(edit.into());
|
||||
}
|
||||
view.handle_paste("Target".into());
|
||||
}
|
||||
view.handle_key_event(KeyCode::Char('!').into());
|
||||
view.handle_key_event(key.into());
|
||||
if key == KeyCode::Esc {
|
||||
assert_eq!(
|
||||
view.cursor_style(Rect::default()),
|
||||
crossterm::cursor::SetCursorStyle::DefaultUserShape
|
||||
);
|
||||
view.handle_key_event(KeyCode::Esc.into());
|
||||
}
|
||||
assert_eq!(view.rows[view.selected_index().unwrap()].thread_id, other);
|
||||
if key == KeyCode::Enter {
|
||||
let rename = rx.try_recv().unwrap();
|
||||
assert!(
|
||||
matches!(&rename, AppEvent::RenameAgentsOverviewThread { thread_id, name } if *thread_id == id && name == "Target!")
|
||||
);
|
||||
app.agents_overview.threads = threads
|
||||
.iter()
|
||||
.map(|thread| {
|
||||
(
|
||||
ThreadId::from_string(&thread.id).unwrap(),
|
||||
Some(thread.clone()),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
app.agents_overview.visible_thread_ids = view.thread_ids();
|
||||
app.chat_widget.show_bottom_pane_view(Box::new(view));
|
||||
let mut server = crate::start_embedded_app_server_for_picker(&app.config).await?;
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
// Synthetic IDs have no rollout: the server rejects the rename.
|
||||
Box::pin(app.handle_event(&mut tui, &mut server, rename)).await?;
|
||||
let mut retry = app.agents_overview_view(threads.clone(), Some(other));
|
||||
assert_eq!(retry.rows[retry.selected_index().unwrap()].thread_id, id);
|
||||
retry.handle_key_event(KeyCode::Enter.into());
|
||||
assert!(std::iter::from_fn(|| rx.try_recv().ok()).any(|event| matches!(event, AppEvent::RenameAgentsOverviewThread { thread_id, name } if thread_id == id && name == "Target!")));
|
||||
server.shutdown().await?;
|
||||
} else {
|
||||
assert!(rx.try_recv().is_err());
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn escape_returns_to_a_chat_that_is_still_starting() {
|
||||
let mut app = make_test_app().await;
|
||||
app.pending_startup_thread_start = true;
|
||||
let mut view = app.agents_overview_view(Vec::new(), /*selected_thread_id*/ None);
|
||||
view.handle_key_event(KeyCode::Esc.into());
|
||||
assert!(view.is_complete());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn live_center_navigation_and_complete_hints() {
|
||||
let app = make_test_app_with_chat().await;
|
||||
let ready = ThreadId::from_u128(/*value*/ 42);
|
||||
let needs_you = ThreadId::from_u128(/*value*/ 43);
|
||||
let unloaded = ThreadId::from_u128(/*value*/ 44);
|
||||
let mut view = app.agents_overview_view(
|
||||
vec![
|
||||
overview_thread(
|
||||
ready,
|
||||
/*parent_thread_id*/ None,
|
||||
"Ready task",
|
||||
ThreadStatus::Idle,
|
||||
),
|
||||
overview_thread(
|
||||
needs_you,
|
||||
/*parent_thread_id*/ None,
|
||||
"Needs input",
|
||||
ThreadStatus::SystemError,
|
||||
),
|
||||
overview_thread(
|
||||
unloaded,
|
||||
/*parent_thread_id*/ None,
|
||||
"Unloaded task",
|
||||
ThreadStatus::NotLoaded,
|
||||
),
|
||||
],
|
||||
Some(ready),
|
||||
);
|
||||
let selected = |view: &AgentsOverviewView| view.rows[view.selected_index().unwrap()].thread_id;
|
||||
view.handle_key_event(KeyCode::Tab.into());
|
||||
assert_eq!(selected(&view), needs_you);
|
||||
view.handle_key_event(KeyEvent::new(KeyCode::BackTab, KeyModifiers::SHIFT));
|
||||
view.handle_key_event(KeyEvent::new(KeyCode::Tab, KeyModifiers::SHIFT));
|
||||
assert_eq!(selected(&view), unloaded);
|
||||
insta::assert_snapshot!(
|
||||
"live_center_status_filter",
|
||||
screen(&view, /*width*/ 40, /*height*/ 12)
|
||||
);
|
||||
view.handle_key_event(KeyCode::Tab.into());
|
||||
|
||||
let repeat_help =
|
||||
KeyEvent::new_with_kind(KeyCode::Char('?'), KeyModifiers::NONE, KeyEventKind::Repeat);
|
||||
view.handle_key_event(KeyCode::Char('?').into());
|
||||
view.handle_key_event(repeat_help);
|
||||
for (name, width, height) in [
|
||||
("live_center_help_three_columns", 100, 24),
|
||||
("live_center_help_two_columns", 60, 24),
|
||||
("live_center_help_one_column", 40, 32),
|
||||
("live_center_navigation_and_complete_hints", 40, 24),
|
||||
] {
|
||||
insta::assert_snapshot!(name, screen(&view, width, height));
|
||||
}
|
||||
view.handle_key_event(KeyCode::Esc.into());
|
||||
view.handle_key_event(repeat_help);
|
||||
assert!(screen(&view, /*width*/ 40, /*height*/ 24).contains("Tasks"));
|
||||
assert!(!view.is_complete());
|
||||
view.handle_key_event(KeyCode::Esc.into());
|
||||
assert!(view.is_complete());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn live_center_fixed_shortcuts_yield_to_configured_actions() {
|
||||
let mut app = make_test_app().await;
|
||||
let config: TuiKeymap = toml::from_str("[list]\ncancel = 'q'").unwrap();
|
||||
app.keymap = RuntimeKeymap::from_config(&config).unwrap();
|
||||
for editor_key in ['/', 'r'] {
|
||||
let mut view = app.agents_overview_view(
|
||||
vec![overview_thread(
|
||||
ThreadId::from_u128(/*value*/ 42),
|
||||
/*parent_thread_id*/ None,
|
||||
"Task",
|
||||
ThreadStatus::Idle,
|
||||
)],
|
||||
/*selected_thread_id*/ None,
|
||||
);
|
||||
view.handle_key_event(KeyCode::Char(editor_key).into());
|
||||
assert!(
|
||||
app.agents_overview
|
||||
.view_state
|
||||
.lock()
|
||||
.unwrap()
|
||||
.editing_metadata()
|
||||
);
|
||||
view.handle_key_event(KeyCode::Char('q').into());
|
||||
assert!(
|
||||
!app.agents_overview
|
||||
.view_state
|
||||
.lock()
|
||||
.unwrap()
|
||||
.editing_metadata()
|
||||
);
|
||||
assert!(!view.is_complete());
|
||||
}
|
||||
for (binding, key) in [
|
||||
("tab", KeyEvent::from(KeyCode::Tab)),
|
||||
("?", KeyEvent::from(KeyCode::Char('?'))),
|
||||
(
|
||||
"shift-?",
|
||||
KeyEvent::new(KeyCode::Char('?'), KeyModifiers::SHIFT),
|
||||
),
|
||||
("f9", KeyEvent::from(KeyCode::F(9))),
|
||||
("enter", KeyEvent::from(KeyCode::Enter)),
|
||||
] {
|
||||
let mut app = make_test_app().await;
|
||||
let config: TuiKeymap = toml::from_str(&format!(
|
||||
"[list]\ncancel = 'f9'\n[agents]\nresume = '{binding}'"
|
||||
))
|
||||
.unwrap();
|
||||
app.keymap = RuntimeKeymap::from_config(&config).unwrap();
|
||||
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
|
||||
app.app_event_tx = AppEventSender::new(tx);
|
||||
let mut view = app.agents_overview_view(Vec::new(), /*selected_thread_id*/ None);
|
||||
view.handle_key_event(KeyCode::Esc.into());
|
||||
assert!(!view.is_complete());
|
||||
if key.code == KeyCode::Char('?') {
|
||||
assert!(!screen(&view, /*width*/ 100, /*height*/ 24).contains("? help"));
|
||||
}
|
||||
if key.code == KeyCode::Enter {
|
||||
assert!(!screen(&view, /*width*/ 100, /*height*/ 24).contains("enter open"));
|
||||
view.handle_key_event(KeyCode::Char('?').into());
|
||||
assert!(!screen(&view, /*width*/ 100, /*height*/ 24).contains("enter open"));
|
||||
app.agents_overview
|
||||
.view_state
|
||||
.lock()
|
||||
.unwrap()
|
||||
.server_version_notice = Some("Version notice".into());
|
||||
assert!(screen(&view, /*width*/ 100, /*height*/ 24).contains("f9 back"));
|
||||
view.handle_key_event(KeyCode::Esc.into());
|
||||
assert!(screen(&view, /*width*/ 100, /*height*/ 24).contains("Task shortcuts"));
|
||||
view.handle_key_event(KeyCode::F(9).into());
|
||||
assert!(!screen(&view, /*width*/ 100, /*height*/ 24).contains("Task shortcuts"));
|
||||
app.agents_overview
|
||||
.view_state
|
||||
.lock()
|
||||
.unwrap()
|
||||
.server_version_notice = None;
|
||||
view.handle_key_event(KeyCode::Char('/').into());
|
||||
assert!(!screen(&view, /*width*/ 100, /*height*/ 24).contains("enter open"));
|
||||
}
|
||||
view.handle_key_event(key);
|
||||
assert!(!view.is_complete());
|
||||
assert!(
|
||||
matches!(rx.try_recv(), Ok(AppEvent::OpenResumePicker)),
|
||||
"{binding}"
|
||||
);
|
||||
assert!(rx.try_recv().is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn live_center_hints_follow_configured_bindings() {
|
||||
let mut app = make_test_app_with_chat().await;
|
||||
let config: TuiKeymap = toml::from_str(
|
||||
r#"
|
||||
[list]
|
||||
move_up = 'k'
|
||||
move_down = 'j'
|
||||
page_up = []
|
||||
[agents]
|
||||
archive = []
|
||||
rename = 'z r'
|
||||
toggle_pin = 'z p'
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
app.keymap = RuntimeKeymap::from_config(&config).unwrap();
|
||||
app.agents_overview.pinned_thread_ids = Some(Vec::new());
|
||||
let view = app.agents_overview_view(Vec::new(), /*selected_thread_id*/ None);
|
||||
insta::assert_snapshot!(
|
||||
"live_center_custom_footer",
|
||||
screen(&view, /*width*/ 100, /*height*/ 12)
|
||||
);
|
||||
let thread_id = ThreadId::from_u128(/*value*/ 42);
|
||||
let mut view = app.agents_overview_view(
|
||||
vec![overview_thread(
|
||||
thread_id,
|
||||
/*parent_thread_id*/ None,
|
||||
"Task",
|
||||
ThreadStatus::Idle,
|
||||
)],
|
||||
Some(thread_id),
|
||||
);
|
||||
view.handle_key_event(KeyCode::Char('?').into());
|
||||
insta::assert_snapshot!(
|
||||
"live_center_custom_help",
|
||||
screen(&view, /*width*/ 100, /*height*/ 24)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn live_center_search_row_appears_only_while_editing() {
|
||||
let app = make_test_app().await;
|
||||
let mut view = app.agents_overview_view(
|
||||
vec![overview_thread(
|
||||
ThreadId::from_u128(/*value*/ 42),
|
||||
/*parent_thread_id*/ None,
|
||||
"Task to find",
|
||||
ThreadStatus::Idle,
|
||||
)],
|
||||
/*selected_thread_id*/ None,
|
||||
);
|
||||
let area = Rect::new(
|
||||
/*x*/ 0, /*y*/ 0, /*width*/ 88, /*height*/ 16,
|
||||
);
|
||||
let mut buf = ratatui::buffer::Buffer::empty(area);
|
||||
view.render(area, &mut buf);
|
||||
let header = &buf.content[3 * 88..4 * 88];
|
||||
let text = header
|
||||
.iter()
|
||||
.map(ratatui::buffer::Cell::symbol)
|
||||
.collect::<String>();
|
||||
let styles =
|
||||
["Tasks", "Status", "Updated"].map(|label| header[text.find(label).unwrap()].style());
|
||||
assert_eq!(styles, [styles[0]; 3]);
|
||||
let idle = screen(&view, area.width, area.height);
|
||||
for key in [KeyCode::Char('/'), KeyCode::F(3)] {
|
||||
view.handle_key_event(key.into());
|
||||
view.handle_paste("find".into());
|
||||
insta::assert_snapshot!(
|
||||
"live_center_search_active",
|
||||
screen(&view, area.width, area.height)
|
||||
);
|
||||
view.handle_key_event(KeyCode::Esc.into());
|
||||
assert_eq!(screen(&view, area.width, area.height), idle);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn backspace_edits_search_and_rename_without_deleting_tasks() {
|
||||
let mut app = make_test_app().await;
|
||||
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
|
||||
app.app_event_tx = AppEventSender::new(tx);
|
||||
let mut view = app.agents_overview_view(
|
||||
vec![overview_thread(
|
||||
ThreadId::new(),
|
||||
/*parent_thread_id*/ None,
|
||||
"Task",
|
||||
ThreadStatus::Idle,
|
||||
)],
|
||||
/*selected_thread_id*/ None,
|
||||
);
|
||||
for key in ['/', 'r'] {
|
||||
view.handle_key_event(KeyCode::Char(key).into());
|
||||
let initial = screen(&view, /*width*/ 88, /*height*/ 16);
|
||||
view.handle_paste("!".into());
|
||||
view.handle_key_event(KeyCode::Backspace.into());
|
||||
assert_eq!(screen(&view, /*width*/ 88, /*height*/ 16), initial);
|
||||
if key == '/' {
|
||||
assert_matches!(rx.try_recv(), Ok(AppEvent::SearchAgentsOverview(..)));
|
||||
}
|
||||
assert!(rx.try_recv().is_err());
|
||||
view.handle_key_event(KeyCode::Esc.into());
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn overview_clears_voice_badge_after_async_close() -> Result<()> {
|
||||
let (mut app, mut events, _) = crate::app::tests::make_test_app_with_channels().await;
|
||||
let owner = ThreadId::new();
|
||||
crate::chatwidget::activate_voice_for_thread(&mut app.chat_widget, owner);
|
||||
app.chat_widget.park_voice();
|
||||
let (visible, _, _, _) = crate::chatwidget::tests::make_chatwidget_manual_with_sender().await;
|
||||
app.background_voice = Some(Box::new(std::mem::replace(&mut app.chat_widget, visible)));
|
||||
app.primary_thread_id = Some(owner);
|
||||
let thread = overview_thread(
|
||||
owner,
|
||||
/*parent_thread_id*/ None,
|
||||
"Voice owner",
|
||||
ThreadStatus::Idle,
|
||||
);
|
||||
app.agents_overview
|
||||
.threads
|
||||
.insert(owner, Some(thread.clone()));
|
||||
let view = app.agents_overview_view(vec![thread], Some(owner));
|
||||
app.agents_overview.visible_thread_ids = view.thread_ids();
|
||||
app.chat_widget.show_bottom_pane_view(Box::new(view));
|
||||
assert!(render_bottom_popup(&app.chat_widget, /*width*/ 100).contains(" voice"));
|
||||
let mut server = crate::start_embedded_app_server_for_picker(&app.config).await?;
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
app.deliver_background_voice_notification(
|
||||
owner,
|
||||
&ServerNotification::ThreadRealtimeClosed(
|
||||
akode_app_server_protocol::ThreadRealtimeClosedNotification {
|
||||
thread_id: owner.to_string(),
|
||||
reason: Some("requested".into()),
|
||||
},
|
||||
),
|
||||
);
|
||||
while let Ok(event) = events.try_recv() {
|
||||
Box::pin(app.handle_event(&mut tui, &mut server, event)).await?;
|
||||
}
|
||||
assert!(!render_bottom_popup(&app.chat_widget, /*width*/ 100).contains(" voice"));
|
||||
server.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn live_center_show_more_navigation_search_and_loading() {
|
||||
let mut app = make_test_app_with_chat().await;
|
||||
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
|
||||
app.app_event_tx = AppEventSender::new(tx);
|
||||
app.agents_overview.view_state.lock().unwrap().has_more = true;
|
||||
let thread = overview_thread(
|
||||
ThreadId::new(),
|
||||
/*parent_thread_id*/ None,
|
||||
"Recent task",
|
||||
ThreadStatus::NotLoaded,
|
||||
);
|
||||
let mut view = app.agents_overview_view(vec![thread], /*selected_thread_id*/ None);
|
||||
view.handle_key_event(KeyCode::Down.into());
|
||||
insta::assert_snapshot!(
|
||||
"live_center_show_more",
|
||||
screen(&view, /*width*/ 80, /*height*/ 12)
|
||||
);
|
||||
view.handle_key_event(KeyCode::Enter.into());
|
||||
view.handle_key_event(KeyCode::Enter.into());
|
||||
assert_matches!(rx.try_recv(), Ok(AppEvent::ShowMoreAgentsOverview));
|
||||
assert!(rx.try_recv().is_err());
|
||||
assert!(screen(&view, /*width*/ 80, /*height*/ 12).contains("Loading more"));
|
||||
{
|
||||
let mut state = app.agents_overview.view_state.lock().unwrap();
|
||||
state.loading = false;
|
||||
state.refresh_failed = true;
|
||||
}
|
||||
view.handle_key_event(KeyCode::Char('/').into());
|
||||
view.handle_paste("Older task".into());
|
||||
let id = assert_matches!(rx.try_recv(), Ok(AppEvent::SearchAgentsOverview(id, _)) => id);
|
||||
insta::assert_snapshot!(screen(&view, /*width*/ 80, /*height*/ 12).lines().nth(6).unwrap(), @" › Searching history…");
|
||||
app.apply_agents_overview_search_page(id, Vec::new(), Default::default(), /*ok*/ false);
|
||||
insta::assert_snapshot!(
|
||||
"live_center_show_more_search_retry",
|
||||
screen(&view, /*width*/ 80, /*height*/ 12)
|
||||
);
|
||||
view.handle_key_event(KeyCode::Enter.into());
|
||||
let id = assert_matches!(rx.try_recv(), Ok(AppEvent::SearchAgentsOverview(id, _)) => id);
|
||||
app.apply_agents_overview_search_page(id, Vec::new(), Default::default(), /*ok*/ true);
|
||||
insta::assert_snapshot!(screen(&view, /*width*/ 80, /*height*/ 12).lines().nth(6).unwrap(), @" › Show more matches");
|
||||
}
|
||||
126
akode-rs/tui/src/app/agent_message_consolidation.rs
Normal file
126
akode-rs/tui/src/app/agent_message_consolidation.rs
Normal file
@@ -0,0 +1,126 @@
|
||||
//! Transcript consolidation for finalized streaming agent messages.
|
||||
//!
|
||||
//! During streaming, the chat widget emits transient `AgentMessageCell`s so it
|
||||
//! can animate stable lines into scrollback while keeping the active mutable
|
||||
//! tail in the bottom pane. Once the answer finishes, the app replaces that
|
||||
//! trailing run with a single source-backed `AgentMarkdownCell`. This makes the
|
||||
//! transcript the canonical owner of the raw markdown source used for future
|
||||
//! resize re-renders. The retained view preserves its displayed revision before that
|
||||
//! replacement, then repaints without replaying terminal scrollback.
|
||||
|
||||
use std::ops::Range;
|
||||
use std::sync::Arc;
|
||||
|
||||
use color_eyre::eyre::Result;
|
||||
|
||||
use super::App;
|
||||
use super::resize_reflow::trailing_run_start;
|
||||
use crate::app_event::ConsolidationScrollbackReflow;
|
||||
use crate::history_cell;
|
||||
use crate::history_cell::HistoryCell;
|
||||
use crate::pager_overlay::Overlay;
|
||||
use crate::tui;
|
||||
|
||||
impl App {
|
||||
pub(super) fn handle_consolidate_agent_message(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
source: history_cell::AgentMarkdownCell,
|
||||
scrollback_reflow: ConsolidationScrollbackReflow,
|
||||
deferred_history_cell: Option<Box<dyn HistoryCell>>,
|
||||
) -> Result<()> {
|
||||
// Some finalize paths must preserve a last provisional stream cell long
|
||||
// enough for queue ordering, then fold it into the canonical
|
||||
// source-backed cell during consolidation.
|
||||
if let Some(cell) = deferred_history_cell {
|
||||
let cell: Arc<dyn HistoryCell> = cell.into();
|
||||
if let Some(Overlay::Transcript(t)) = &mut self.overlay {
|
||||
t.insert_cell(cell.clone());
|
||||
}
|
||||
if !tui.is_owned_screen() {
|
||||
self.native_history.defer(&cell);
|
||||
}
|
||||
self.transcript_cells.push(cell);
|
||||
}
|
||||
|
||||
// Walk backward to find the contiguous run of streaming AgentMessageCells that
|
||||
// belong to the just-finalized stream.
|
||||
let end = self.transcript_cells.len();
|
||||
tracing::debug!(
|
||||
"ConsolidateAgentMessage: transcript_cells.len()={end}, source_len={}",
|
||||
source.copy_source().map_or(/*default*/ 0, str::len)
|
||||
);
|
||||
let start = trailing_run_start::<history_cell::AgentMessageCell>(&self.transcript_cells);
|
||||
self.replace_agent_message(tui, start..end, source, scrollback_reflow)
|
||||
}
|
||||
|
||||
pub(super) fn replace_agent_message(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
range: Range<usize>,
|
||||
source: history_cell::AgentMarkdownCell,
|
||||
scrollback_reflow: ConsolidationScrollbackReflow,
|
||||
) -> Result<()> {
|
||||
let Range { start, end } = range;
|
||||
if start < end {
|
||||
tracing::debug!(
|
||||
"ConsolidateAgentMessage: replacing cells [{start}..{end}] with AgentMarkdownCell"
|
||||
);
|
||||
let consolidated: Arc<dyn HistoryCell> = Arc::new(source);
|
||||
self.native_history
|
||||
.consolidate(&self.transcript_cells[start..end], &consolidated);
|
||||
if tui.is_owned_screen() {
|
||||
self.transcript_view.replace_group(
|
||||
&self.transcript_cells,
|
||||
start..end,
|
||||
&consolidated,
|
||||
);
|
||||
} else {
|
||||
self.transcript_view.replace_range(
|
||||
&self.transcript_cells,
|
||||
start..end,
|
||||
&consolidated,
|
||||
);
|
||||
}
|
||||
self.transcript_cells
|
||||
.splice(start..end, std::iter::once(consolidated.clone()));
|
||||
|
||||
if let Some(Overlay::Transcript(t)) = &mut self.overlay {
|
||||
t.regroup_cells(start..end, consolidated.clone());
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
|
||||
self.finish_agent_message_consolidation(tui, scrollback_reflow)?;
|
||||
} else {
|
||||
tracing::debug!(
|
||||
"ConsolidateAgentMessage: no cells to consolidate(start={start}, end={end})",
|
||||
);
|
||||
self.maybe_finish_stream_reflow(tui)?;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn finish_agent_message_consolidation(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
scrollback_reflow: ConsolidationScrollbackReflow,
|
||||
) -> Result<()> {
|
||||
if tui.is_owned_screen() {
|
||||
self.transcript_reflow.clear_pending_reflow();
|
||||
self.transcript_reflow.clear_stream_flags();
|
||||
tui.frame_requester().schedule_frame();
|
||||
return Ok(());
|
||||
}
|
||||
match scrollback_reflow {
|
||||
ConsolidationScrollbackReflow::IfResizeReflowRan => {
|
||||
self.maybe_finish_stream_reflow(tui)?;
|
||||
}
|
||||
ConsolidationScrollbackReflow::Required => {
|
||||
self.finish_required_stream_reflow(tui)?;
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
620
akode-rs/tui/src/app/agent_navigation.rs
Normal file
620
akode-rs/tui/src/app/agent_navigation.rs
Normal file
@@ -0,0 +1,620 @@
|
||||
//! Multi-agent picker navigation and labeling state for the TUI app.
|
||||
//!
|
||||
//! This module exists to keep the pure parts of multi-agent navigation out of [`crate::app::App`].
|
||||
//! It owns the stable spawn-order cache used by the `/subagents` picker, keyboard next/previous
|
||||
//! navigation, and the contextual footer label for the thread currently being watched.
|
||||
//!
|
||||
//! Responsibilities here are intentionally narrow:
|
||||
//! - remember picker entries and their first-seen order
|
||||
//! - remember which V2 child threads are owned by their parent agent
|
||||
//! - answer traversal questions like "what is the next thread?"
|
||||
//! - derive user-facing picker/footer text from cached thread metadata
|
||||
//!
|
||||
//! Responsibilities that stay in `App`:
|
||||
//! - discovering threads from the backend
|
||||
//! - deciding which thread is currently displayed
|
||||
//! - mutating UI state such as switching threads or updating the footer widget
|
||||
//!
|
||||
//! The key invariant is that traversal follows first-seen spawn order rather than thread-id sort
|
||||
//! order. Once a thread id is observed it keeps its place in the cycle even if the entry is later
|
||||
//! updated or marked closed.
|
||||
|
||||
use crate::multi_agents::AgentPickerThreadEntry;
|
||||
use crate::multi_agents::SubAgentActivityDisplay;
|
||||
use crate::multi_agents::format_agent_picker_item_name;
|
||||
use crate::multi_agents::next_agent_shortcut;
|
||||
use crate::multi_agents::previous_agent_shortcut;
|
||||
use akode_protocol::ThreadId;
|
||||
use ratatui::text::Span;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Small state container for multi-agent picker ordering and labeling.
|
||||
///
|
||||
/// `App` owns thread lifecycle and UI side effects. This type keeps the pure rules for stable
|
||||
/// spawn-order traversal, picker copy, and active-agent labels together and separately testable.
|
||||
///
|
||||
/// The core invariant is that `order` records first-seen thread ids exactly once, while `threads`
|
||||
/// stores the latest metadata for those ids. Mutation is intentionally funneled through `upsert`,
|
||||
/// `mark_closed`, and `clear` so those two collections do not drift semantically even if they are
|
||||
/// temporarily out of sync during teardown races.
|
||||
#[derive(Debug, Default)]
|
||||
pub(crate) struct AgentNavigationState {
|
||||
/// Latest picker metadata for each tracked thread id.
|
||||
threads: HashMap<ThreadId, AgentPickerThreadEntry>,
|
||||
/// First-seen order for keyboard cycling. The picker groups waiting threads first.
|
||||
order: Vec<ThreadId>,
|
||||
/// Threads with observed terminal liveness that must not be revived by delayed activity.
|
||||
stopped_threads: HashSet<ThreadId>,
|
||||
/// Spawned child threads whose instructions are owned by their parent agent.
|
||||
parent_owned_threads: HashSet<ThreadId>,
|
||||
picker_excluded_threads: HashSet<ThreadId>,
|
||||
/// Inactive threads with an approval outstanding in their event store.
|
||||
pub(super) pending_approvals: HashSet<ThreadId>,
|
||||
/// Thread IDs in the currently rendered picker, so a refresh can restore its cursor by ID.
|
||||
pub(super) picker_row_ids: Vec<ThreadId>,
|
||||
/// Coalesces root refreshes while rejecting replies from a previous session.
|
||||
pub(super) picker_refresh: Option<AgentPickerRefreshState>,
|
||||
}
|
||||
|
||||
/// Direction of keyboard traversal through the first-seen order.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(crate) enum AgentNavigationDirection {
|
||||
/// Move toward the entry that was seen earlier in spawn order, wrapping at the front.
|
||||
Previous,
|
||||
/// Move toward the entry that was seen later in spawn order, wrapping at the end.
|
||||
Next,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) enum AgentPickerThreadVisibility {
|
||||
Visible,
|
||||
Hidden,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct AgentPickerRefreshState {
|
||||
root: ThreadId,
|
||||
request_id: Uuid,
|
||||
pub(super) visibility_changed_threads: HashSet<ThreadId>,
|
||||
pub(super) follow_up_requested: bool,
|
||||
}
|
||||
|
||||
impl AgentNavigationState {
|
||||
pub(crate) fn begin_picker_refresh(&mut self, thread_id: ThreadId) -> Option<Uuid> {
|
||||
if self
|
||||
.picker_refresh
|
||||
.as_ref()
|
||||
.is_some_and(|refresh| refresh.root == thread_id)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let request_id = Uuid::new_v4();
|
||||
self.picker_refresh = Some(AgentPickerRefreshState {
|
||||
root: thread_id,
|
||||
request_id,
|
||||
visibility_changed_threads: HashSet::new(),
|
||||
follow_up_requested: false,
|
||||
});
|
||||
Some(request_id)
|
||||
}
|
||||
|
||||
pub(crate) fn queue_picker_refresh(&mut self, thread_id: ThreadId) -> bool {
|
||||
let Some(refresh) = self.picker_refresh.as_mut() else {
|
||||
return false;
|
||||
};
|
||||
if refresh.root != thread_id {
|
||||
return false;
|
||||
}
|
||||
refresh.follow_up_requested = true;
|
||||
true
|
||||
}
|
||||
|
||||
pub(crate) fn finish_picker_refresh(
|
||||
&mut self,
|
||||
thread_id: ThreadId,
|
||||
request_id: Uuid,
|
||||
) -> Option<AgentPickerRefreshState> {
|
||||
if !self
|
||||
.picker_refresh
|
||||
.as_ref()
|
||||
.is_some_and(|refresh| refresh.root == thread_id && refresh.request_id == request_id)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
self.picker_refresh.take()
|
||||
}
|
||||
|
||||
/// Returns the cached picker entry for a specific thread id.
|
||||
///
|
||||
/// Callers use this when they already know which thread they care about and need the last
|
||||
/// metadata captured for picker or footer rendering. If a caller assumes every tracked thread
|
||||
/// must be present here, shutdown races can turn that assumption into a panic elsewhere, so
|
||||
/// this stays optional.
|
||||
pub(crate) fn get(&self, thread_id: &ThreadId) -> Option<&AgentPickerThreadEntry> {
|
||||
self.threads.get(thread_id)
|
||||
}
|
||||
|
||||
pub(crate) fn is_parent_owned(&self, thread_id: ThreadId) -> bool {
|
||||
self.parent_owned_threads.contains(&thread_id)
|
||||
}
|
||||
|
||||
/// Marks a spawned child thread as view-only for direct user instructions.
|
||||
pub(crate) fn mark_parent_owned(&mut self, thread_id: ThreadId) {
|
||||
self.parent_owned_threads.insert(thread_id);
|
||||
}
|
||||
|
||||
/// Returns whether the picker currently has any visible threads.
|
||||
///
|
||||
/// This is the cheapest way for `App` to decide whether opening the picker should show "No
|
||||
/// agents available yet." rather than constructing picker rows from an empty state.
|
||||
pub(crate) fn is_empty(&self) -> bool {
|
||||
self.threads
|
||||
.keys()
|
||||
.all(|thread_id| self.picker_excluded_threads.contains(thread_id))
|
||||
}
|
||||
|
||||
/// Inserts or updates a picker entry while preserving first-seen traversal order.
|
||||
///
|
||||
/// The key invariant of this module is enforced here: a thread id is appended to `order` only
|
||||
/// the first time it is seen. Later updates may change nickname, role, or closed state, but
|
||||
/// they must not move the thread in the cycle or keyboard navigation would feel unstable.
|
||||
pub(crate) fn upsert(
|
||||
&mut self,
|
||||
thread_id: ThreadId,
|
||||
agent_nickname: Option<String>,
|
||||
agent_role: Option<String>,
|
||||
is_closed: bool,
|
||||
) {
|
||||
if !self.threads.contains_key(&thread_id) {
|
||||
self.order.push(thread_id);
|
||||
}
|
||||
let (previous_agent_path, previous_is_running) = self
|
||||
.threads
|
||||
.get(&thread_id)
|
||||
.map(|entry| (entry.agent_path.clone(), entry.is_running))
|
||||
.unwrap_or((None, false));
|
||||
self.threads.insert(
|
||||
thread_id,
|
||||
AgentPickerThreadEntry {
|
||||
agent_nickname,
|
||||
agent_role,
|
||||
agent_path: previous_agent_path,
|
||||
is_running: previous_is_running && !is_closed,
|
||||
is_closed,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
pub(crate) fn record_sub_agent_activity(&mut self, activity: SubAgentActivityDisplay) {
|
||||
if !self.threads.contains_key(&activity.thread_id) {
|
||||
self.order.push(activity.thread_id);
|
||||
}
|
||||
let entry =
|
||||
self.threads
|
||||
.entry(activity.thread_id)
|
||||
.or_insert_with(|| AgentPickerThreadEntry {
|
||||
agent_nickname: None,
|
||||
agent_role: None,
|
||||
agent_path: None,
|
||||
is_running: false,
|
||||
is_closed: false,
|
||||
});
|
||||
entry.agent_path = Some(activity.agent_path);
|
||||
if activity.is_running_hint
|
||||
&& !entry.is_closed
|
||||
&& !self.stopped_threads.contains(&activity.thread_id)
|
||||
{
|
||||
entry.is_running = true;
|
||||
} else {
|
||||
entry.is_running = false;
|
||||
self.stopped_threads.insert(activity.thread_id);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn mark_running(&mut self, thread_id: ThreadId) {
|
||||
if self
|
||||
.threads
|
||||
.get(&thread_id)
|
||||
.is_some_and(|entry| entry.is_closed)
|
||||
{
|
||||
return;
|
||||
}
|
||||
self.stopped_threads.remove(&thread_id);
|
||||
self.set_running(thread_id, /*is_running*/ true);
|
||||
}
|
||||
|
||||
pub(crate) fn mark_stopped(&mut self, thread_id: ThreadId) {
|
||||
self.stopped_threads.insert(thread_id);
|
||||
self.set_running(thread_id, /*is_running*/ false);
|
||||
}
|
||||
|
||||
pub(crate) fn set_running(&mut self, thread_id: ThreadId, is_running: bool) {
|
||||
if let Some(entry) = self.threads.get_mut(&thread_id) {
|
||||
entry.is_running = is_running;
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn set_agent_path(&mut self, thread_id: ThreadId, agent_path: Option<String>) {
|
||||
if let Some(agent_path) = agent_path
|
||||
&& let Some(entry) = self.threads.get_mut(&thread_id)
|
||||
{
|
||||
entry.agent_path = Some(agent_path);
|
||||
}
|
||||
}
|
||||
|
||||
/// Marks a thread as closed without removing it from the traversal cache.
|
||||
///
|
||||
/// Closed threads stay in the picker and in spawn order so users can still review them and so
|
||||
/// next/previous navigation does not reshuffle around disappearing entries. If a caller "cleans
|
||||
/// this up" by deleting the entry instead, wraparound navigation will silently change shape
|
||||
/// mid-session.
|
||||
pub(crate) fn mark_closed(&mut self, thread_id: ThreadId) {
|
||||
if let Some(entry) = self.threads.get_mut(&thread_id) {
|
||||
entry.is_closed = true;
|
||||
entry.is_running = false;
|
||||
} else {
|
||||
self.upsert(
|
||||
thread_id, /*agent_nickname*/ None, /*agent_role*/ None,
|
||||
/*is_closed*/ true,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Drops all cached picker state.
|
||||
///
|
||||
/// This is used when `App` tears down thread event state and needs the picker cache to return
|
||||
/// to a pristine single-session state.
|
||||
pub(crate) fn clear(&mut self) {
|
||||
self.threads.clear();
|
||||
self.order.clear();
|
||||
self.stopped_threads.clear();
|
||||
self.parent_owned_threads.clear();
|
||||
self.picker_excluded_threads.clear();
|
||||
self.pending_approvals.clear();
|
||||
self.picker_row_ids.clear();
|
||||
self.picker_refresh = None;
|
||||
}
|
||||
|
||||
/// Removes a tracked thread entirely from picker metadata and traversal order.
|
||||
///
|
||||
/// This is reserved for entries that were only discovered opportunistically and never became
|
||||
/// replayable local threads. Keeping those around after the backend confirms they are gone
|
||||
/// would leave ghost rows in `/subagents`.
|
||||
pub(crate) fn remove(&mut self, thread_id: ThreadId) {
|
||||
self.threads.remove(&thread_id);
|
||||
self.order.retain(|candidate| *candidate != thread_id);
|
||||
self.stopped_threads.remove(&thread_id);
|
||||
self.parent_owned_threads.remove(&thread_id);
|
||||
self.picker_excluded_threads.remove(&thread_id);
|
||||
}
|
||||
|
||||
/// Returns whether there is at least one tracked thread other than the primary one.
|
||||
///
|
||||
/// `App` uses this to decide whether the picker should be available even when the collaboration
|
||||
/// feature flag is currently disabled, because already-existing sub-agent threads should remain
|
||||
/// inspectable.
|
||||
pub(crate) fn has_non_primary_thread(&self, primary_thread_id: Option<ThreadId>) -> bool {
|
||||
self.threads.keys().any(|thread_id| {
|
||||
Some(*thread_id) != primary_thread_id
|
||||
&& !self.picker_excluded_threads.contains(thread_id)
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns live picker rows in the same order users cycle through them.
|
||||
///
|
||||
/// The `order` vector is intentionally historical and may briefly contain thread ids that no
|
||||
/// longer have cached metadata, so this filters through the map instead of assuming both
|
||||
/// collections are perfectly synchronized.
|
||||
pub(crate) fn ordered_threads(&self) -> Vec<(ThreadId, &AgentPickerThreadEntry)> {
|
||||
self.order
|
||||
.iter()
|
||||
.filter_map(|thread_id| self.threads.get(thread_id).map(|entry| (*thread_id, entry)))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(crate) fn visible_threads(&self) -> Vec<(ThreadId, &AgentPickerThreadEntry)> {
|
||||
self.ordered_threads()
|
||||
.into_iter()
|
||||
.filter(|(thread_id, _)| !self.picker_excluded_threads.contains(thread_id))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn pending_approval_threads(&self) -> impl Iterator<Item = ThreadId> + '_ {
|
||||
self.order.iter().copied().filter(|id| {
|
||||
self.pending_approvals.contains(id) && !self.picker_excluded_threads.contains(id)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn set_picker_thread_visibility(
|
||||
&mut self,
|
||||
thread_id: ThreadId,
|
||||
visibility: AgentPickerThreadVisibility,
|
||||
) {
|
||||
let track_hidden = self.threads.contains_key(&thread_id) || self.picker_refresh.is_some();
|
||||
match visibility {
|
||||
AgentPickerThreadVisibility::Visible => self.picker_excluded_threads.remove(&thread_id),
|
||||
AgentPickerThreadVisibility::Hidden => {
|
||||
track_hidden && self.picker_excluded_threads.insert(thread_id)
|
||||
}
|
||||
};
|
||||
if let Some(refresh) = self.picker_refresh.as_mut() {
|
||||
refresh.visibility_changed_threads.insert(thread_id);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn prune_untracked_picker_exclusions(&mut self) {
|
||||
self.picker_excluded_threads
|
||||
.retain(|thread_id| self.threads.contains_key(thread_id));
|
||||
}
|
||||
|
||||
pub(crate) fn ordered_path_backed_subagent_threads(
|
||||
&self,
|
||||
primary_thread_id: Option<ThreadId>,
|
||||
) -> Vec<(ThreadId, &AgentPickerThreadEntry)> {
|
||||
self.visible_threads()
|
||||
.into_iter()
|
||||
.filter(|(thread_id, entry)| {
|
||||
Some(*thread_id) != primary_thread_id
|
||||
&& entry
|
||||
.agent_path
|
||||
.as_deref()
|
||||
.is_some_and(|agent_path| !agent_path.trim().is_empty())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Returns tracked thread ids in first-seen order.
|
||||
pub(crate) fn tracked_thread_ids(&self) -> Vec<ThreadId> {
|
||||
self.ordered_threads()
|
||||
.into_iter()
|
||||
.map(|(thread_id, _)| thread_id)
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Returns the adjacent thread id for keyboard navigation in stable spawn order.
|
||||
///
|
||||
/// The caller must pass the thread whose transcript is actually being shown to the user, not
|
||||
/// just whichever thread bookkeeping most recently marked active. If the wrong current thread
|
||||
/// is supplied, next/previous navigation will jump in a way that feels nondeterministic even
|
||||
/// though the cache itself is correct.
|
||||
pub(crate) fn adjacent_thread_id(
|
||||
&self,
|
||||
current_displayed_thread_id: Option<ThreadId>,
|
||||
direction: AgentNavigationDirection,
|
||||
) -> Option<ThreadId> {
|
||||
let current_thread_id = current_displayed_thread_id?;
|
||||
let current_idx = self
|
||||
.order
|
||||
.iter()
|
||||
.position(|thread_id| *thread_id == current_thread_id)?;
|
||||
(1..self.order.len()).find_map(|offset| {
|
||||
let idx = match direction {
|
||||
AgentNavigationDirection::Next => (current_idx + offset) % self.order.len(),
|
||||
AgentNavigationDirection::Previous => {
|
||||
(current_idx + self.order.len() - offset) % self.order.len()
|
||||
}
|
||||
};
|
||||
let thread_id = self.order[idx];
|
||||
(self.threads.contains_key(&thread_id)
|
||||
&& !self.picker_excluded_threads.contains(&thread_id))
|
||||
.then_some(thread_id)
|
||||
})
|
||||
}
|
||||
|
||||
/// Derives the contextual footer label for the currently displayed thread.
|
||||
///
|
||||
/// This intentionally returns `None` until there is more than one tracked thread so
|
||||
/// single-thread sessions do not waste footer space restating the obvious. When metadata for
|
||||
/// the displayed thread is missing, the label falls back to the same generic naming rules used
|
||||
/// by the picker.
|
||||
pub(crate) fn active_agent_label(
|
||||
&self,
|
||||
current_displayed_thread_id: Option<ThreadId>,
|
||||
primary_thread_id: Option<ThreadId>,
|
||||
) -> Option<String> {
|
||||
if self.threads.len() <= 1 {
|
||||
return None;
|
||||
}
|
||||
|
||||
let thread_id = current_displayed_thread_id?;
|
||||
let is_primary = primary_thread_id == Some(thread_id);
|
||||
Some(
|
||||
self.threads
|
||||
.get(&thread_id)
|
||||
.map(|entry| {
|
||||
if !is_primary
|
||||
&& let Some(agent_path) = entry
|
||||
.agent_path
|
||||
.as_deref()
|
||||
.filter(|agent_path| !agent_path.trim().is_empty())
|
||||
{
|
||||
return format!("`{agent_path}`");
|
||||
}
|
||||
format_agent_picker_item_name(
|
||||
entry.agent_nickname.as_deref(),
|
||||
entry.agent_role.as_deref(),
|
||||
is_primary,
|
||||
)
|
||||
})
|
||||
.unwrap_or_else(|| {
|
||||
format_agent_picker_item_name(
|
||||
/*agent_nickname*/ None, /*agent_role*/ None, is_primary,
|
||||
)
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/// Builds the `/subagents` picker subtitle from the same canonical bindings used by key handling.
|
||||
///
|
||||
/// Keeping this text derived from the actual shortcut helpers prevents the picker copy from
|
||||
/// drifting if the bindings ever change on one platform.
|
||||
pub(crate) fn picker_subtitle() -> String {
|
||||
let previous: Span<'static> = previous_agent_shortcut().into();
|
||||
let next: Span<'static> = next_agent_shortcut().into();
|
||||
format!(
|
||||
"Select an agent to watch. {} previous, {} next.",
|
||||
previous.content, next.content
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
/// Returns only the ordered thread ids for focused tests of traversal invariants.
|
||||
///
|
||||
/// This helper exists so tests can assert on ordering without embedding the full picker entry
|
||||
/// payload in every expectation.
|
||||
pub(crate) fn ordered_thread_ids(&self) -> Vec<ThreadId> {
|
||||
self.ordered_threads()
|
||||
.into_iter()
|
||||
.map(|(thread_id, _)| thread_id)
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn populated_state() -> (AgentNavigationState, ThreadId, ThreadId, ThreadId) {
|
||||
let mut state = AgentNavigationState::default();
|
||||
let main_thread_id =
|
||||
ThreadId::from_string("00000000-0000-0000-0000-000000000101").expect("valid thread");
|
||||
let first_agent_id =
|
||||
ThreadId::from_string("00000000-0000-0000-0000-000000000102").expect("valid thread");
|
||||
let second_agent_id =
|
||||
ThreadId::from_string("00000000-0000-0000-0000-000000000103").expect("valid thread");
|
||||
|
||||
state.upsert(
|
||||
main_thread_id,
|
||||
/*agent_nickname*/ None,
|
||||
/*agent_role*/ None,
|
||||
/*is_closed*/ false,
|
||||
);
|
||||
state.upsert(
|
||||
first_agent_id,
|
||||
Some("Robie".to_string()),
|
||||
Some("explorer".to_string()),
|
||||
/*is_closed*/ false,
|
||||
);
|
||||
state.upsert(
|
||||
second_agent_id,
|
||||
Some("Bob".to_string()),
|
||||
Some("worker".to_string()),
|
||||
/*is_closed*/ false,
|
||||
);
|
||||
|
||||
(state, main_thread_id, first_agent_id, second_agent_id)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn upsert_preserves_first_seen_order() {
|
||||
let (mut state, main_thread_id, first_agent_id, second_agent_id) = populated_state();
|
||||
|
||||
state.upsert(
|
||||
first_agent_id,
|
||||
Some("Robie".to_string()),
|
||||
Some("worker".to_string()),
|
||||
/*is_closed*/ true,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
state.ordered_thread_ids(),
|
||||
vec![main_thread_id, first_agent_id, second_agent_id]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parent_owned_state_is_removed_with_thread_metadata() {
|
||||
let (mut state, _main_thread_id, first_agent_id, second_agent_id) = populated_state();
|
||||
|
||||
state.mark_parent_owned(first_agent_id);
|
||||
assert!(state.is_parent_owned(first_agent_id));
|
||||
state.remove(first_agent_id);
|
||||
assert!(!state.is_parent_owned(first_agent_id));
|
||||
|
||||
state.mark_parent_owned(second_agent_id);
|
||||
state.clear();
|
||||
assert!(!state.is_parent_owned(second_agent_id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picker_refresh_rejects_responses_from_before_clear() {
|
||||
let mut state = AgentNavigationState::default();
|
||||
let thread_id = ThreadId::new();
|
||||
let stale_request = state
|
||||
.begin_picker_refresh(thread_id)
|
||||
.expect("first picker refresh");
|
||||
|
||||
assert_eq!(state.begin_picker_refresh(thread_id), None);
|
||||
state.clear();
|
||||
let current_request = state
|
||||
.begin_picker_refresh(thread_id)
|
||||
.expect("refresh after session reset");
|
||||
|
||||
assert!(
|
||||
state
|
||||
.finish_picker_refresh(thread_id, stale_request)
|
||||
.is_none()
|
||||
);
|
||||
assert!(
|
||||
state
|
||||
.finish_picker_refresh(thread_id, current_request)
|
||||
.is_some()
|
||||
);
|
||||
state.set_picker_thread_visibility(ThreadId::new(), AgentPickerThreadVisibility::Hidden);
|
||||
assert!(state.picker_excluded_threads.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn adjacent_thread_id_wraps_in_spawn_order() {
|
||||
let (state, main_thread_id, first_agent_id, second_agent_id) = populated_state();
|
||||
|
||||
assert_eq!(
|
||||
state.adjacent_thread_id(Some(second_agent_id), AgentNavigationDirection::Next),
|
||||
Some(main_thread_id)
|
||||
);
|
||||
assert_eq!(
|
||||
state.adjacent_thread_id(Some(second_agent_id), AgentNavigationDirection::Previous),
|
||||
Some(first_agent_id)
|
||||
);
|
||||
assert_eq!(
|
||||
state.adjacent_thread_id(Some(main_thread_id), AgentNavigationDirection::Previous),
|
||||
Some(second_agent_id)
|
||||
);
|
||||
|
||||
let mut state = state;
|
||||
state.set_agent_path(first_agent_id, Some("/root/first".to_string()));
|
||||
state.set_picker_thread_visibility(first_agent_id, AgentPickerThreadVisibility::Hidden);
|
||||
assert!(
|
||||
state
|
||||
.ordered_path_backed_subagent_threads(Some(main_thread_id))
|
||||
.is_empty()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn picker_subtitle_mentions_shortcuts() {
|
||||
let previous: Span<'static> = previous_agent_shortcut().into();
|
||||
let next: Span<'static> = next_agent_shortcut().into();
|
||||
let subtitle = AgentNavigationState::picker_subtitle();
|
||||
|
||||
assert!(subtitle.contains(previous.content.as_ref()));
|
||||
assert!(subtitle.contains(next.content.as_ref()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn active_agent_label_tracks_current_thread() {
|
||||
let (state, main_thread_id, first_agent_id, _) = populated_state();
|
||||
|
||||
assert_eq!(
|
||||
state.active_agent_label(Some(first_agent_id), Some(main_thread_id)),
|
||||
Some("Robie [explorer]".to_string())
|
||||
);
|
||||
assert_eq!(
|
||||
state.active_agent_label(Some(main_thread_id), Some(main_thread_id)),
|
||||
Some("Main [default]".to_string())
|
||||
);
|
||||
}
|
||||
}
|
||||
270
akode-rs/tui/src/app/agent_picker.rs
Normal file
270
akode-rs/tui/src/app/agent_picker.rs
Normal file
@@ -0,0 +1,270 @@
|
||||
//! Root-scoped background refresh for the agent picker.
|
||||
|
||||
use super::agent_navigation::AgentPickerThreadVisibility;
|
||||
use super::app_server_event_targets::ServerNotificationThreadTarget;
|
||||
use super::app_server_event_targets::server_notification_thread_target;
|
||||
use super::*;
|
||||
use crate::app_event::AgentPickerThreadRefresh;
|
||||
use akode_app_server_protocol::RequestId;
|
||||
use akode_app_server_protocol::SortDirection;
|
||||
use akode_app_server_protocol::ThreadListParams;
|
||||
use akode_app_server_protocol::ThreadListResponse;
|
||||
use akode_app_server_protocol::ThreadSourceKind;
|
||||
use akode_app_server_protocol::ThreadStatus;
|
||||
use std::collections::HashSet;
|
||||
|
||||
pub(super) const AGENT_PICKER_VIEW_ID: &str = "agent-picker";
|
||||
const AGENT_PICKER_PAGE_SIZE: u32 = 100;
|
||||
const AGENT_PICKER_MAX_THREADS: usize = 1_000;
|
||||
|
||||
impl App {
|
||||
pub(super) fn refresh_agent_picker_threads(
|
||||
&mut self,
|
||||
app_server: &AppServerSession,
|
||||
root: ThreadId,
|
||||
) {
|
||||
let Some(request_id) = self.agent_navigation.begin_picker_refresh(root) else {
|
||||
return;
|
||||
};
|
||||
let request_handle = app_server.request_handle();
|
||||
let app_event_tx = self.app_event_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
let result = async {
|
||||
let mut refresh = AgentPickerThreadRefresh::default();
|
||||
for archived in [false, true] {
|
||||
let mut cursor = None;
|
||||
let mut seen_cursors = HashSet::new();
|
||||
let mut listed = 0;
|
||||
while listed < AGENT_PICKER_MAX_THREADS && seen_cursors.insert(cursor.clone()) {
|
||||
let page = match request_handle
|
||||
.request_typed::<ThreadListResponse>(ClientRequest::ThreadList {
|
||||
request_id: RequestId::String(Uuid::new_v4().to_string()),
|
||||
params: ThreadListParams {
|
||||
current_account_only: false,
|
||||
excluded_thread_ids: None,
|
||||
attached_to_thread_id: None,
|
||||
originators: None,
|
||||
cursor,
|
||||
limit: Some(AGENT_PICKER_PAGE_SIZE),
|
||||
sort_key: None,
|
||||
sort_direction: Some(SortDirection::Desc),
|
||||
model_providers: Some(vec![]),
|
||||
source_kinds: Some(vec![ThreadSourceKind::SubAgentThreadSpawn]),
|
||||
archived: Some(archived),
|
||||
section_id: None,
|
||||
project_id: None,
|
||||
cwd: None,
|
||||
use_state_db_only: true,
|
||||
search_term: None,
|
||||
parent_thread_id: None,
|
||||
ancestor_thread_id: Some(root.to_string()),
|
||||
},
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(page) => page,
|
||||
Err(err) if !archived && listed == 0 => return Err(err.to_string()),
|
||||
Err(err) => {
|
||||
tracing::warn!(%err, archived, "incomplete agent picker refresh");
|
||||
break;
|
||||
}
|
||||
};
|
||||
let page_threads: Vec<_> = page
|
||||
.data
|
||||
.into_iter()
|
||||
.take(AGENT_PICKER_MAX_THREADS - listed)
|
||||
.collect();
|
||||
listed += page_threads.len();
|
||||
if archived {
|
||||
refresh.archived_thread_ids.extend(
|
||||
page_threads
|
||||
.into_iter()
|
||||
.filter_map(|thread| ThreadId::from_string(&thread.id).ok()),
|
||||
);
|
||||
} else {
|
||||
refresh.threads.extend(page_threads);
|
||||
}
|
||||
let Some(next_cursor) = page.next_cursor else {
|
||||
break;
|
||||
};
|
||||
cursor = Some(next_cursor);
|
||||
}
|
||||
}
|
||||
refresh.threads.reverse();
|
||||
Ok(refresh)
|
||||
}
|
||||
.await;
|
||||
|
||||
app_event_tx.send(AppEvent::AgentPickerThreadsLoaded {
|
||||
primary_thread_id: root,
|
||||
request_id,
|
||||
result,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn apply_agent_picker_thread_refresh(
|
||||
&mut self,
|
||||
app_server: &AppServerSession,
|
||||
root: ThreadId,
|
||||
request_id: Uuid,
|
||||
result: Result<AgentPickerThreadRefresh, String>,
|
||||
) {
|
||||
let Some(completion) = self
|
||||
.agent_navigation
|
||||
.finish_picker_refresh(root, request_id)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if self.primary_thread_id != Some(root) {
|
||||
return;
|
||||
}
|
||||
let refresh = match result {
|
||||
Ok(refresh) => refresh,
|
||||
Err(err) => {
|
||||
tracing::warn!(%err, "failed to refresh agent picker descendants");
|
||||
self.agent_navigation.prune_untracked_picker_exclusions();
|
||||
if completion.follow_up_requested {
|
||||
self.refresh_agent_picker_threads(app_server, root);
|
||||
}
|
||||
return;
|
||||
}
|
||||
};
|
||||
for thread in refresh.threads {
|
||||
let Ok(thread_id) = ThreadId::from_string(&thread.id) else {
|
||||
continue;
|
||||
};
|
||||
if !completion.visibility_changed_threads.contains(&thread_id) {
|
||||
self.update_agent_picker_thread_visibility(
|
||||
thread_id,
|
||||
AgentPickerThreadVisibility::Visible,
|
||||
);
|
||||
}
|
||||
let live = self
|
||||
.thread_event_channels
|
||||
.get(&thread_id)
|
||||
.is_some_and(|channel| channel.attachment() == ThreadEventAttachment::Live);
|
||||
let previous = self.agent_navigation.get(&thread_id);
|
||||
let is_running = matches!(thread.status, ThreadStatus::Active { .. });
|
||||
let update_liveness = previous.is_none() || !is_running;
|
||||
let is_closed = !live && matches!(thread.status, ThreadStatus::NotLoaded);
|
||||
if !is_closed && previous.is_some_and(|entry| entry.is_closed) {
|
||||
continue;
|
||||
}
|
||||
let agent_path = crate::app_server_session::source_agent_path(&thread.source);
|
||||
let agent_nickname = thread
|
||||
.agent_nickname
|
||||
.or_else(|| previous.and_then(|entry| entry.agent_nickname.clone()));
|
||||
let agent_role = thread
|
||||
.agent_role
|
||||
.or_else(|| previous.and_then(|entry| entry.agent_role.clone()));
|
||||
if thread.can_accept_direct_input == Some(false) {
|
||||
self.agent_navigation.mark_parent_owned(thread_id);
|
||||
}
|
||||
self.upsert_agent_picker_thread(thread_id, agent_nickname, agent_role, is_closed);
|
||||
self.agent_navigation.set_agent_path(thread_id, agent_path);
|
||||
if !live && update_liveness {
|
||||
self.agent_navigation.set_running(thread_id, is_running);
|
||||
}
|
||||
}
|
||||
for thread_id in refresh.archived_thread_ids {
|
||||
if !completion.visibility_changed_threads.contains(&thread_id) {
|
||||
self.update_agent_picker_thread_visibility(
|
||||
thread_id,
|
||||
AgentPickerThreadVisibility::Hidden,
|
||||
);
|
||||
}
|
||||
}
|
||||
self.agent_navigation.prune_untracked_picker_exclusions();
|
||||
|
||||
self.refresh_agent_picker();
|
||||
if completion.follow_up_requested {
|
||||
self.refresh_agent_picker_threads(app_server, root);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn set_agent_picker_thread_visibility(
|
||||
&mut self,
|
||||
thread_id: ThreadId,
|
||||
visibility: AgentPickerThreadVisibility,
|
||||
) {
|
||||
self.update_agent_picker_thread_visibility(thread_id, visibility);
|
||||
self.refresh_agent_picker();
|
||||
}
|
||||
|
||||
fn update_agent_picker_thread_visibility(
|
||||
&mut self,
|
||||
thread_id: ThreadId,
|
||||
visibility: AgentPickerThreadVisibility,
|
||||
) {
|
||||
if matches!(visibility, AgentPickerThreadVisibility::Hidden) {
|
||||
self.agent_navigation.mark_stopped(thread_id);
|
||||
if let Some(channel) = self.thread_event_channels.get_mut(&thread_id) {
|
||||
channel.mark_replay_only();
|
||||
}
|
||||
}
|
||||
self.agent_navigation
|
||||
.set_picker_thread_visibility(thread_id, visibility);
|
||||
}
|
||||
|
||||
pub(super) fn handle_agent_picker_visibility_notification(
|
||||
&mut self,
|
||||
app_server: &AppServerSession,
|
||||
notification: &ServerNotification,
|
||||
) {
|
||||
let visibility = match notification {
|
||||
ServerNotification::ThreadArchived(_) => AgentPickerThreadVisibility::Hidden,
|
||||
ServerNotification::ThreadUnarchived(_) => AgentPickerThreadVisibility::Visible,
|
||||
_ => return,
|
||||
};
|
||||
let ServerNotificationThreadTarget::Thread(thread_id) =
|
||||
server_notification_thread_target(notification)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if matches!(notification, ServerNotification::ThreadArchived(_))
|
||||
&& (self.side_threads.contains_key(&thread_id)
|
||||
|| self
|
||||
.sidebars
|
||||
.values()
|
||||
.any(|pane| pane.chat_tabs().choice_index(thread_id).is_some()))
|
||||
{
|
||||
self.app_event_tx.send(AppEvent::SideChatArchived {
|
||||
backend_id: app_server.backend_id(),
|
||||
target: thread_id,
|
||||
});
|
||||
}
|
||||
let refresh_uncached_thread = matches!(visibility, AgentPickerThreadVisibility::Visible)
|
||||
&& self.agent_navigation.get(&thread_id).is_none();
|
||||
self.set_agent_picker_thread_visibility(thread_id, visibility);
|
||||
if refresh_uncached_thread
|
||||
&& let Some(primary_thread_id) = self.primary_thread_id
|
||||
&& !self
|
||||
.agent_navigation
|
||||
.queue_picker_refresh(primary_thread_id)
|
||||
{
|
||||
self.refresh_agent_picker_threads(app_server, primary_thread_id);
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep the approval notice and any open picker in sync with the same navigation state.
|
||||
pub(super) fn refresh_agent_picker(&mut self) -> bool {
|
||||
self.sync_active_agent_label();
|
||||
let pending = self
|
||||
.agent_navigation
|
||||
.pending_approval_threads()
|
||||
.map(|id| self.thread_label(id))
|
||||
.collect();
|
||||
self.chat_widget.set_pending_thread_approvals(pending);
|
||||
if !self.chat_widget.has_active_modal() {
|
||||
return false;
|
||||
}
|
||||
let selected = self
|
||||
.chat_widget
|
||||
.selected_index_for_present_view(AGENT_PICKER_VIEW_ID)
|
||||
.and_then(|index| self.agent_navigation.picker_row_ids.get(index).copied());
|
||||
let params = self.agent_picker_selection_view_params(selected);
|
||||
self.chat_widget
|
||||
.replace_selection_view_if_present(AGENT_PICKER_VIEW_ID, params)
|
||||
}
|
||||
}
|
||||
229
akode-rs/tui/src/app/agent_status_feed.rs
Normal file
229
akode-rs/tui/src/app/agent_status_feed.rs
Normal file
@@ -0,0 +1,229 @@
|
||||
//! Bounded, best-effort previews for the v2 `/subagents` status output.
|
||||
|
||||
use super::ThreadBufferedEvent;
|
||||
use super::ThreadEventStore;
|
||||
use crate::history_cell::HistoryCell;
|
||||
use crate::history_cell::plain_lines;
|
||||
use crate::style::accent_color;
|
||||
use crate::text_formatting::truncate_text;
|
||||
use akode_app_server_protocol::CollabAgentTool;
|
||||
use akode_app_server_protocol::ServerNotification;
|
||||
use akode_app_server_protocol::SubAgentActivityKind;
|
||||
use akode_app_server_protocol::ThreadItemPayload;
|
||||
use ratatui::style::Stylize;
|
||||
use ratatui::text::Line;
|
||||
use std::collections::HashSet;
|
||||
|
||||
const AGENT_STATUS_PREVIEW_LINES: usize = 3;
|
||||
const AGENT_STATUS_PREVIEW_ITEMS: usize = 6;
|
||||
const AGENT_STATUS_PREVIEW_GRAPHEMES: usize = 240;
|
||||
const AGENT_STATUS_PREVIEW_INDENT: u16 = 4;
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct AgentStatusHistoryCell {
|
||||
entries: Vec<AgentStatusThreadPreview>,
|
||||
}
|
||||
|
||||
impl AgentStatusHistoryCell {
|
||||
pub(super) fn new(entries: Vec<AgentStatusThreadPreview>) -> Self {
|
||||
Self { entries }
|
||||
}
|
||||
}
|
||||
|
||||
impl HistoryCell for AgentStatusHistoryCell {
|
||||
fn display_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
let mut lines: Vec<Line<'static>> = vec![
|
||||
"/subagents".magenta().into(),
|
||||
"Sub-agents running".bold().into(),
|
||||
"".into(),
|
||||
];
|
||||
|
||||
if self.entries.is_empty() {
|
||||
lines.push(" • No sub-agents running.".italic().into());
|
||||
return lines;
|
||||
}
|
||||
|
||||
for entry in &self.entries {
|
||||
lines.push(entry.title_line());
|
||||
let preview_width = width.saturating_sub(AGENT_STATUS_PREVIEW_INDENT).max(1);
|
||||
let preview_lines = entry.preview_lines(preview_width);
|
||||
if preview_lines.is_empty() {
|
||||
lines.push(vec![" ".into(), "No recent activity yet.".dim().italic()].into());
|
||||
} else {
|
||||
lines.extend(preview_lines.into_iter().map(indent_preview_line));
|
||||
}
|
||||
lines.push("".into());
|
||||
}
|
||||
let _ = lines.pop();
|
||||
lines
|
||||
}
|
||||
|
||||
fn raw_lines(&self) -> Vec<Line<'static>> {
|
||||
plain_lines(self.display_lines(u16::MAX))
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct AgentStatusThreadPreview {
|
||||
agent_path: String,
|
||||
activity: Vec<String>,
|
||||
}
|
||||
|
||||
impl AgentStatusThreadPreview {
|
||||
pub(super) fn from_store(agent_path: String, store: &ThreadEventStore) -> Self {
|
||||
Self::from_events(agent_path, store.buffer.iter().rev())
|
||||
}
|
||||
|
||||
pub(super) fn empty(agent_path: String) -> Self {
|
||||
Self::from_events(agent_path, std::iter::empty())
|
||||
}
|
||||
|
||||
fn from_events<'a>(
|
||||
agent_path: String,
|
||||
events: impl Iterator<Item = &'a ThreadBufferedEvent>,
|
||||
) -> Self {
|
||||
let mut seen_item_ids = HashSet::new();
|
||||
let mut activity = Vec::new();
|
||||
for event in events {
|
||||
let item = match event {
|
||||
ThreadBufferedEvent::Notification(notification) => match notification.as_ref() {
|
||||
ServerNotification::ItemCompleted(event) => &event.item,
|
||||
ServerNotification::ItemStarted(event) => &event.item,
|
||||
_ => continue,
|
||||
},
|
||||
ThreadBufferedEvent::Request(_)
|
||||
| ThreadBufferedEvent::HistoryEntryResponse(_)
|
||||
| ThreadBufferedEvent::FeedbackSubmission(_) => continue,
|
||||
};
|
||||
if !seen_item_ids.insert(item.id().to_string()) {
|
||||
continue;
|
||||
}
|
||||
if let Some(summary) = activity_summary(&item.payload) {
|
||||
activity.push(summary);
|
||||
if activity.len() == AGENT_STATUS_PREVIEW_ITEMS {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
activity.reverse();
|
||||
Self {
|
||||
agent_path,
|
||||
activity,
|
||||
}
|
||||
}
|
||||
|
||||
fn title_line(&self) -> Line<'static> {
|
||||
vec![
|
||||
" • ".dim(),
|
||||
format!("`{}`", self.agent_path).fg(accent_color()),
|
||||
]
|
||||
.into()
|
||||
}
|
||||
|
||||
fn preview_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
let mut lines = self
|
||||
.activity
|
||||
.iter()
|
||||
.flat_map(|activity| textwrap::wrap(activity, width as usize))
|
||||
.filter(|line| !line.trim().is_empty())
|
||||
.map(|line| line.into_owned().dim().into())
|
||||
.collect::<Vec<_>>();
|
||||
if lines.len() > AGENT_STATUS_PREVIEW_LINES {
|
||||
lines.drain(..lines.len() - AGENT_STATUS_PREVIEW_LINES);
|
||||
}
|
||||
lines
|
||||
}
|
||||
}
|
||||
|
||||
fn activity_summary(item: &ThreadItemPayload) -> Option<String> {
|
||||
let summary = match item {
|
||||
ThreadItemPayload::AgentMessage { text, .. } | ThreadItemPayload::Plan { text, .. } => text,
|
||||
ThreadItemPayload::Reasoning { summary, .. } => summary.last()?,
|
||||
ThreadItemPayload::CommandExecution { command, .. } => {
|
||||
let command = truncate_text(
|
||||
command,
|
||||
AGENT_STATUS_PREVIEW_GRAPHEMES.saturating_sub("$ ".len()),
|
||||
);
|
||||
return bounded_summary(&format!("$ {command}"));
|
||||
}
|
||||
ThreadItemPayload::FileChange { changes, .. } => {
|
||||
return bounded_summary(&format!("Updated {} file(s)", changes.len()));
|
||||
}
|
||||
ThreadItemPayload::McpToolCall { server, tool, .. } => {
|
||||
return bounded_summary(&format!("MCP {server}/{tool}"));
|
||||
}
|
||||
ThreadItemPayload::DynamicToolCall {
|
||||
namespace, tool, ..
|
||||
} => {
|
||||
let tool = namespace
|
||||
.as_ref()
|
||||
.map(|namespace| format!("{namespace}/{tool}"))
|
||||
.unwrap_or_else(|| tool.clone());
|
||||
return bounded_summary(&format!("Tool {tool}"));
|
||||
}
|
||||
ThreadItemPayload::CollabAgentToolCall { tool, .. } => {
|
||||
let action = match tool {
|
||||
CollabAgentTool::SendMessage
|
||||
| CollabAgentTool::FollowupTask
|
||||
| CollabAgentTool::InterruptAgent
|
||||
| CollabAgentTool::ListAgents => return None,
|
||||
CollabAgentTool::SpawnAgent => "Spawned an agent",
|
||||
CollabAgentTool::SendInput => "Sent input to an agent",
|
||||
CollabAgentTool::ResumeAgent => "Resumed an agent",
|
||||
CollabAgentTool::Wait => "Waited for an agent",
|
||||
CollabAgentTool::CloseAgent => "Closed an agent",
|
||||
};
|
||||
return Some(action.to_string());
|
||||
}
|
||||
ThreadItemPayload::SubAgentActivity {
|
||||
kind, agent_path, ..
|
||||
} => {
|
||||
let action = match kind {
|
||||
SubAgentActivityKind::Started => "Started",
|
||||
SubAgentActivityKind::Interacted => "Contacted",
|
||||
SubAgentActivityKind::Interrupted => "Interrupted",
|
||||
SubAgentActivityKind::Completed => "Completed",
|
||||
};
|
||||
return bounded_summary(&format!("{action} {agent_path}"));
|
||||
}
|
||||
ThreadItemPayload::WebSearch(item) => {
|
||||
return bounded_summary(&format!("Web search: {}", item.query));
|
||||
}
|
||||
ThreadItemPayload::ImageView { path, .. } => {
|
||||
let path = path.render_for_ui();
|
||||
return bounded_summary(&format!("Viewed {path}"));
|
||||
}
|
||||
ThreadItemPayload::ImageGeneration(_) => return Some("Generated an image".to_string()),
|
||||
ThreadItemPayload::EnteredReviewMode { .. } => {
|
||||
return Some("Entered review mode".to_string());
|
||||
}
|
||||
ThreadItemPayload::ExitedReviewMode { .. } => {
|
||||
return Some("Exited review mode".to_string());
|
||||
}
|
||||
ThreadItemPayload::ContextCompaction { .. } => {
|
||||
return Some("Compacted context".to_string());
|
||||
}
|
||||
ThreadItemPayload::UserMessage { .. }
|
||||
| ThreadItemPayload::HookPrompt { .. }
|
||||
| ThreadItemPayload::FunctionCallOutput { .. }
|
||||
| ThreadItemPayload::Sleep(_) => {
|
||||
return None;
|
||||
}
|
||||
};
|
||||
bounded_summary(summary)
|
||||
}
|
||||
|
||||
fn bounded_summary(summary: &str) -> Option<String> {
|
||||
let summary = truncate_text(summary, AGENT_STATUS_PREVIEW_GRAPHEMES);
|
||||
let summary = summary.split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
(!summary.is_empty()).then_some(summary)
|
||||
}
|
||||
|
||||
fn indent_preview_line(mut line: Line<'static>) -> Line<'static> {
|
||||
line.spans.insert(0, " ".into());
|
||||
line
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "agent_status_feed_tests.rs"]
|
||||
mod tests;
|
||||
122
akode-rs/tui/src/app/agent_status_feed_tests.rs
Normal file
122
akode-rs/tui/src/app/agent_status_feed_tests.rs
Normal file
@@ -0,0 +1,122 @@
|
||||
use super::*;
|
||||
use akode_app_server_protocol::CommandExecutionSource;
|
||||
use akode_app_server_protocol::CommandExecutionStatus;
|
||||
use akode_app_server_protocol::ItemCompletedNotification;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
|
||||
#[test]
|
||||
fn agent_status_uses_bounded_buffered_activity() {
|
||||
let mut store = ThreadEventStore::new(/*capacity*/ 8);
|
||||
store.push_notification(ServerNotification::ItemCompleted(
|
||||
ItemCompletedNotification::new(
|
||||
"thread-child".to_string(),
|
||||
"turn-1".to_string(),
|
||||
ThreadItemPayload::CommandExecution {
|
||||
model_context: None,
|
||||
sandbox_type: None,
|
||||
id: "command-1".to_string(),
|
||||
command: "cargo test -p akode-tui".to_string(),
|
||||
cwd: AbsolutePathBuf::try_from("/workspace")
|
||||
.expect("absolute path")
|
||||
.into(),
|
||||
process_id: None,
|
||||
plugin_id: None,
|
||||
script_path: None,
|
||||
source: CommandExecutionSource::Agent,
|
||||
status: CommandExecutionStatus::Completed,
|
||||
command_actions: Vec::new(),
|
||||
aggregated_output: Some("unbounded output\n".repeat(10_000)),
|
||||
exit_code: Some(0),
|
||||
duration_ms: Some(42),
|
||||
},
|
||||
/*started_at_ms*/ None,
|
||||
/*completed_at_ms*/ 1,
|
||||
),
|
||||
));
|
||||
store.push_notification(ServerNotification::ItemCompleted(
|
||||
ItemCompletedNotification::new(
|
||||
"thread-child".to_string(),
|
||||
"turn-1".to_string(),
|
||||
ThreadItemPayload::AgentMessage {
|
||||
moderation: None,
|
||||
id: "message-1".to_string(),
|
||||
text: "Finished checking the focused TUI tests.".to_string(),
|
||||
phase: None,
|
||||
memory_citation: None,
|
||||
delivery: None,
|
||||
questions: None,
|
||||
},
|
||||
/*started_at_ms*/ None,
|
||||
/*completed_at_ms*/ 2,
|
||||
),
|
||||
));
|
||||
|
||||
let preview = AgentStatusThreadPreview::from_store("/root/reviewer".to_string(), &store);
|
||||
let cell = AgentStatusHistoryCell::new(vec![preview]);
|
||||
let rendered = cell
|
||||
.display_lines(/*width*/ 80)
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
|
||||
insta::assert_snapshot!(rendered, @r###"
|
||||
/subagents
|
||||
Sub-agents running
|
||||
|
||||
• `/root/reviewer`
|
||||
$ cargo test -p akode-tui
|
||||
Finished checking the focused TUI tests.
|
||||
"###);
|
||||
assert!(!rendered.contains("unbounded output"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_status_uses_reasoning_summaries_only() {
|
||||
let mut store = ThreadEventStore::new(/*capacity*/ 8);
|
||||
store.push_notification(ServerNotification::ItemCompleted(
|
||||
ItemCompletedNotification::new(
|
||||
"thread-child".to_string(),
|
||||
"turn-1".to_string(),
|
||||
ThreadItemPayload::Reasoning {
|
||||
id: "reasoning-with-summary".to_string(),
|
||||
summary: vec!["safe summary".to_string()],
|
||||
content: vec!["hidden raw reasoning".to_string()],
|
||||
},
|
||||
/*started_at_ms*/ None,
|
||||
/*completed_at_ms*/ 1,
|
||||
),
|
||||
));
|
||||
store.push_notification(ServerNotification::ItemCompleted(
|
||||
ItemCompletedNotification::new(
|
||||
"thread-child".to_string(),
|
||||
"turn-1".to_string(),
|
||||
ThreadItemPayload::Reasoning {
|
||||
id: "reasoning-without-summary".to_string(),
|
||||
summary: Vec::new(),
|
||||
content: vec!["raw-only reasoning".to_string()],
|
||||
},
|
||||
/*started_at_ms*/ None,
|
||||
/*completed_at_ms*/ 2,
|
||||
),
|
||||
));
|
||||
|
||||
let preview = AgentStatusThreadPreview::from_store("/root/reviewer".to_string(), &store);
|
||||
let cell = AgentStatusHistoryCell::new(vec![preview]);
|
||||
let rendered = cell
|
||||
.display_lines(/*width*/ 80)
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
|
||||
insta::assert_snapshot!(rendered, @r###"
|
||||
/subagents
|
||||
Sub-agents running
|
||||
|
||||
• `/root/reviewer`
|
||||
safe summary
|
||||
"###);
|
||||
assert!(!rendered.contains("hidden raw reasoning"));
|
||||
assert!(!rendered.contains("raw-only reasoning"));
|
||||
}
|
||||
1240
akode-rs/tui/src/app/agents_overview.rs
Normal file
1240
akode-rs/tui/src/app/agents_overview.rs
Normal file
File diff suppressed because it is too large
Load Diff
119
akode-rs/tui/src/app/agents_overview_action_progress_tests.rs
Normal file
119
akode-rs/tui/src/app/agents_overview_action_progress_tests.rs
Normal file
@@ -0,0 +1,119 @@
|
||||
//! The dashboard remains browsable while lifecycle requests hold the server lock.
|
||||
|
||||
use super::*;
|
||||
use crate::chatwidget::tests::helpers::normalize_agent_center_snapshot;
|
||||
use crate::test_support::PathBufExt;
|
||||
use crate::test_support::test_path_buf;
|
||||
use crossterm::event::KeyCode;
|
||||
use futures::stream;
|
||||
use pretty_assertions::assert_eq;
|
||||
use ratatui::Terminal;
|
||||
use ratatui::backend::TestBackend;
|
||||
use std::collections::VecDeque;
|
||||
use std::task::Poll;
|
||||
use std::time::Duration;
|
||||
|
||||
#[tokio::test]
|
||||
async fn modal_consumes_input_and_finishes_after_input_closes() -> color_eyre::Result<()> {
|
||||
for (action, snapshot) in [
|
||||
(AgentsOverviewAction::Archive, "archive_progress"),
|
||||
(AgentsOverviewAction::Delete, "delete_progress"),
|
||||
] {
|
||||
let (mut app, mut rx, _) = crate::app::tests::make_test_app_with_channels().await;
|
||||
let mut server = crate::start_embedded_app_server_for_picker(&app.config).await?;
|
||||
for index in 1..=3 {
|
||||
let id = ThreadId::from_string(
|
||||
&app_test_support::create_fake_rollout(
|
||||
&app.config.codex_home,
|
||||
&format!("2025-01-0{index}T12-00-00"),
|
||||
&format!("2025-01-0{index}T12:00:00Z"),
|
||||
&format!("Task {index}"),
|
||||
Some(&app.config.model_provider_id),
|
||||
/*git_info*/ None,
|
||||
)
|
||||
.expect("materialize task"),
|
||||
)?;
|
||||
let mut thread = server.thread_read(id, /*include_turns*/ false).await?;
|
||||
thread.cwd = test_path_buf("/tmp/project").abs();
|
||||
app.agents_overview.threads.insert(id, Some(thread));
|
||||
}
|
||||
let threads = app
|
||||
.agents_overview
|
||||
.threads
|
||||
.values()
|
||||
.flatten()
|
||||
.cloned()
|
||||
.collect();
|
||||
let view = app.agents_overview_view(threads, /*selected_thread_id*/ None);
|
||||
app.agents_overview.visible_thread_ids = view.thread_ids();
|
||||
app.chat_widget.show_bottom_pane_view(Box::new(view));
|
||||
let removed = app.agents_overview.visible_thread_ids[0];
|
||||
app.prepare_agents_overview_removal(&HashSet::from([removed]));
|
||||
app.agents_overview.hidden_threads.insert(removed);
|
||||
app.agents_overview.view_state.lock().unwrap().removal = Some(action);
|
||||
app.repaint_agents_overview();
|
||||
assert!(!app.agents_overview.visible_thread_ids.contains(&removed));
|
||||
while rx.try_recv().is_ok() {}
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
tui.pause_events();
|
||||
let (finished_input, wait_for_input) = tokio::sync::oneshot::channel();
|
||||
let mut finished_input = Some(finished_input);
|
||||
let mut events = VecDeque::from([
|
||||
tui::TuiEvent::Key(KeyCode::End.into()),
|
||||
// Leaving and server mutations wait without accumulating actions.
|
||||
tui::TuiEvent::Key(KeyCode::Esc.into()),
|
||||
tui::TuiEvent::Key(KeyCode::Enter.into()),
|
||||
tui::TuiEvent::Key(KeyCode::Char('n').into()),
|
||||
tui::TuiEvent::Draw,
|
||||
tui::TuiEvent::Resize(ratatui::layout::Size::new(66, 20)),
|
||||
tui::TuiEvent::FocusGained,
|
||||
]);
|
||||
let events = stream::poll_fn(move |_| {
|
||||
if let Some(event) = events.pop_front() {
|
||||
Poll::Ready(Some(event))
|
||||
} else {
|
||||
if let Some(finished_input) = finished_input.take() {
|
||||
let _ = finished_input.send(());
|
||||
}
|
||||
Poll::Ready(None)
|
||||
}
|
||||
});
|
||||
let result = tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
run_lifecycle_modal(
|
||||
&mut tui,
|
||||
&mut app,
|
||||
async {
|
||||
wait_for_input.await.expect("all modal input was consumed");
|
||||
"operation finished"
|
||||
},
|
||||
events,
|
||||
),
|
||||
)
|
||||
.await??;
|
||||
assert_eq!(result, "operation finished");
|
||||
assert_eq!(
|
||||
tui.terminal.last_known_screen_size,
|
||||
ratatui::layout::Size::new(66, 20)
|
||||
);
|
||||
let selected = app
|
||||
.chat_widget
|
||||
.selected_index_for_active_view(AGENTS_OVERVIEW_VIEW_ID)
|
||||
.expect("dashboard stays open");
|
||||
assert_eq!(selected, app.agents_overview.visible_thread_ids.len() - 1);
|
||||
assert!(
|
||||
!std::iter::from_fn(|| rx.try_recv().ok()).any(|event| matches!(
|
||||
event,
|
||||
AppEvent::SelectAgentsOverviewThread { .. }
|
||||
| AppEvent::NewAgentsOverviewSession { .. }
|
||||
))
|
||||
);
|
||||
let mut terminal = Terminal::new(TestBackend::new(80, 24))?;
|
||||
terminal.draw(|frame| app.chat_widget.render(frame.area(), frame.buffer_mut()))?;
|
||||
let text = normalize_agent_center_snapshot(terminal.backend().to_string());
|
||||
let age = regex_lite::Regex::new(r" +[0-9]+d ago").unwrap();
|
||||
insta::assert_snapshot!(snapshot, age.replace_all(&text, " [age]"));
|
||||
server.shutdown().await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
452
akode-rs/tui/src/app/agents_overview_actions.rs
Normal file
452
akode-rs/tui/src/app/agents_overview_actions.rs
Normal file
@@ -0,0 +1,452 @@
|
||||
//! Server RPCs own lifecycle outcomes; successful actions invalidate dashboard group caches.
|
||||
//! Keep the dashboard browsable during RPCs while deferring task notifications.
|
||||
//! Removing the current root leaves an unattached dashboard, even when it is empty.
|
||||
|
||||
use super::App;
|
||||
use super::agents_overview::AGENTS_OVERVIEW_VIEW_ID;
|
||||
use crate::app_event::AgentsOverviewAction;
|
||||
use crate::app_event::AppEvent;
|
||||
use crate::app_server_session::AppServerSession;
|
||||
use crate::bottom_pane::SelectionItem;
|
||||
use crate::bottom_pane::SelectionViewParams;
|
||||
use crate::chatwidget::ChatWidget;
|
||||
use crate::render::renderable::Renderable;
|
||||
use crate::tui;
|
||||
use crate::wrapping::word_wrap_lines;
|
||||
use akode_app_server_protocol::ClientRequest;
|
||||
use akode_app_server_protocol::RequestId;
|
||||
use akode_app_server_protocol::SessionSource;
|
||||
use akode_app_server_protocol::ThreadLoadedListParams;
|
||||
use akode_app_server_protocol::ThreadSectionMoveParams;
|
||||
use akode_app_server_protocol::ThreadSectionMoveResponse;
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_protocol::protocol::SubAgentSource;
|
||||
use akode_state::PINNED_THREAD_SECTION_ID;
|
||||
use ratatui::buffer::Buffer;
|
||||
use ratatui::layout::Rect;
|
||||
use ratatui::style::Stylize;
|
||||
use ratatui::text::Line;
|
||||
use ratatui::widgets::Paragraph;
|
||||
use std::collections::HashSet;
|
||||
use std::future::Future;
|
||||
use tokio_stream::Stream;
|
||||
use tokio_stream::StreamExt;
|
||||
use uuid::Uuid;
|
||||
|
||||
struct LifecycleHeader(Vec<Line<'static>>);
|
||||
|
||||
impl Renderable for LifecycleHeader {
|
||||
fn render(&self, area: Rect, buf: &mut Buffer) {
|
||||
Renderable::render(
|
||||
&Paragraph::new(word_wrap_lines(&self.0, usize::from(area.width))),
|
||||
area,
|
||||
buf,
|
||||
);
|
||||
}
|
||||
|
||||
fn desired_height(&self, width: u16) -> u16 {
|
||||
word_wrap_lines(&self.0, usize::from(width)).len() as u16
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep browsing responsive without queuing actions against a locked server.
|
||||
async fn run_lifecycle_modal<T>(
|
||||
tui: &mut tui::Tui,
|
||||
app: &mut App,
|
||||
operation: impl Future<Output = T>,
|
||||
events: impl Stream<Item = tui::TuiEvent> + Unpin,
|
||||
) -> color_eyre::Result<T> {
|
||||
app.render_chat_widget_frame(tui, tui.terminal.last_known_screen_size)?;
|
||||
let mut events = events.fuse();
|
||||
tokio::pin!(operation);
|
||||
let result = loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = &mut operation => break result,
|
||||
Some(event) = events.next() => {
|
||||
let screen_size = tui.screen_size_for_event(&event)?;
|
||||
if matches!(&event, tui::TuiEvent::Paste(_) | tui::TuiEvent::FocusLost) {
|
||||
app.cancel_pending_key_chord();
|
||||
}
|
||||
let dashboard_active = app.chat_widget
|
||||
.selected_index_for_active_view(AGENTS_OVERVIEW_VIEW_ID)
|
||||
.is_some();
|
||||
match event {
|
||||
tui::TuiEvent::Key(key) if dashboard_active => {
|
||||
if let Some(key) = app.route_key_chord_event(tui, key) {
|
||||
app.chat_widget.handle_key_event_with_activation_key(key, app.routed_key_activation);
|
||||
}
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
tui::TuiEvent::Paste(text) if dashboard_active => {
|
||||
app.chat_widget.handle_paste(text);
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
tui::TuiEvent::Key(_) | tui::TuiEvent::Paste(_) | tui::TuiEvent::FocusLost | tui::TuiEvent::Mouse(_) => {}
|
||||
tui::TuiEvent::Draw | tui::TuiEvent::Resize(_) | tui::TuiEvent::Resume | tui::TuiEvent::FocusGained => {
|
||||
app.expire_pending_key_chord(tui);
|
||||
app.render_chat_widget_frame(tui, screen_size)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
tui.frame_requester().schedule_frame();
|
||||
Ok(result)
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub(super) fn toggle_agents_overview_pin(
|
||||
&mut self,
|
||||
app_server: &AppServerSession,
|
||||
thread_id: ThreadId,
|
||||
pinned: bool,
|
||||
) {
|
||||
if self.agents_overview.pending_pin_change.is_some() {
|
||||
return;
|
||||
}
|
||||
let request_id = Uuid::new_v4();
|
||||
self.agents_overview.pending_pin_change = Some(request_id);
|
||||
let request_handle = app_server.request_handle();
|
||||
let app_event_tx = self.app_event_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
let result = request_handle
|
||||
.request_typed::<ThreadSectionMoveResponse>(ClientRequest::ThreadSectionMove {
|
||||
request_id: RequestId::String(Uuid::new_v4().to_string()),
|
||||
params: ThreadSectionMoveParams {
|
||||
thread_id: thread_id.to_string(),
|
||||
section_id: pinned.then(|| PINNED_THREAD_SECTION_ID.to_string()),
|
||||
before_thread_id: None,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.map(|_| ())
|
||||
.map_err(|error| error.to_string());
|
||||
app_event_tx.send(AppEvent::AgentsOverviewPinToggled {
|
||||
request_id,
|
||||
thread_id,
|
||||
pinned,
|
||||
result,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn complete_agents_overview_pin(
|
||||
&mut self,
|
||||
app_server: &AppServerSession,
|
||||
request_id: Uuid,
|
||||
thread_id: ThreadId,
|
||||
pinned: bool,
|
||||
result: Result<(), String>,
|
||||
) {
|
||||
if self.agents_overview.pending_pin_change != Some(request_id) {
|
||||
return;
|
||||
}
|
||||
self.agents_overview.pending_pin_change = None;
|
||||
match result {
|
||||
Ok(()) => {
|
||||
if let Some(pinned_thread_ids) = self.agents_overview.pinned_thread_ids.as_mut() {
|
||||
if pinned {
|
||||
if !pinned_thread_ids.contains(&thread_id) {
|
||||
pinned_thread_ids.push(thread_id);
|
||||
}
|
||||
} else {
|
||||
pinned_thread_ids.retain(|id| *id != thread_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(error) => {
|
||||
self.add_agents_overview_error(format!(
|
||||
"Failed to {} task: {error}",
|
||||
if pinned { "pin" } else { "unpin" }
|
||||
));
|
||||
}
|
||||
}
|
||||
let restore_show_more = self.agents_overview.refresh_show_more;
|
||||
if let Some(refresh) = self.agents_overview.refresh_task.take() {
|
||||
refresh.abort();
|
||||
}
|
||||
self.agents_overview.request_id = None;
|
||||
self.agents_overview.refresh_show_more = false;
|
||||
self.agents_overview.refresh_notifications.clear();
|
||||
let refresh_thread_ids =
|
||||
std::mem::take(&mut self.agents_overview.active_refresh_thread_ids);
|
||||
self.agents_overview
|
||||
.refresh_thread_ids
|
||||
.extend(refresh_thread_ids);
|
||||
self.agents_overview.refresh_pending = false;
|
||||
self.agents_overview.show_more_requested |= restore_show_more;
|
||||
self.refresh_agents_overview_threads(app_server);
|
||||
self.repaint_agents_overview();
|
||||
}
|
||||
|
||||
pub(super) fn confirm_agents_overview_action(
|
||||
&mut self,
|
||||
thread_id: ThreadId,
|
||||
action: AgentsOverviewAction,
|
||||
) {
|
||||
let Some(thread) = self
|
||||
.agents_overview
|
||||
.threads
|
||||
.get(&thread_id)
|
||||
.and_then(Option::as_ref)
|
||||
.or_else(|| self.agents_overview.search_matches.get(&thread_id))
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let name = thread.name.as_deref().unwrap_or(&thread.preview);
|
||||
let name = name
|
||||
.trim()
|
||||
.lines()
|
||||
.next()
|
||||
.filter(|name| !name.is_empty())
|
||||
.unwrap_or("Untitled task");
|
||||
let (title, description, label) = match action {
|
||||
AgentsOverviewAction::Archive => (
|
||||
format!("Archive “{name}”?"),
|
||||
"This stops any running work in this task and its child agents, then archives them. Their history can be restored from the resume picker.",
|
||||
"Archive task and child agents",
|
||||
),
|
||||
AgentsOverviewAction::Delete => (
|
||||
format!("Permanently delete “{name}”?"),
|
||||
"Tasks with saved side chats stay intact. Otherwise, deleting this task stops its running work and permanently deletes its history and its child agents’ history.",
|
||||
"Permanently delete task and child agents",
|
||||
),
|
||||
};
|
||||
self.chat_widget.show_selection_view(SelectionViewParams {
|
||||
header: Box::new(LifecycleHeader(vec![
|
||||
title.bold().into(),
|
||||
description.dim().into(),
|
||||
])),
|
||||
items: vec![
|
||||
SelectionItem {
|
||||
name: "Cancel".to_string(),
|
||||
dismiss_on_select: true,
|
||||
..Default::default()
|
||||
},
|
||||
SelectionItem {
|
||||
name: label.to_string(),
|
||||
actions: vec![Box::new(move |tx| {
|
||||
tx.send(AppEvent::RunAgentsOverviewAction { thread_id, action })
|
||||
})],
|
||||
dismiss_on_select: true,
|
||||
require_explicit_confirmation: action == AgentsOverviewAction::Delete,
|
||||
..Default::default()
|
||||
},
|
||||
],
|
||||
..SelectionViewParams::confirmation()
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn known_thread_subtree(&self, thread_id: ThreadId) -> HashSet<ThreadId> {
|
||||
let mut removed = HashSet::from([thread_id]);
|
||||
loop {
|
||||
let previous_len = removed.len();
|
||||
for (id, thread) in &self.agents_overview.threads {
|
||||
let Some(thread) = thread else { continue };
|
||||
let parent = thread
|
||||
.parent_thread_id
|
||||
.as_deref()
|
||||
.and_then(|id| ThreadId::from_string(id).ok())
|
||||
.or(match &thread.source {
|
||||
SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
|
||||
parent_thread_id,
|
||||
..
|
||||
}) => Some(*parent_thread_id),
|
||||
_ => None,
|
||||
});
|
||||
if thread.session_id == thread_id.to_string()
|
||||
|| parent.is_some_and(|parent| removed.contains(&parent))
|
||||
{
|
||||
removed.insert(*id);
|
||||
}
|
||||
}
|
||||
if removed.len() == previous_len {
|
||||
break;
|
||||
}
|
||||
}
|
||||
removed
|
||||
}
|
||||
|
||||
pub(super) async fn run_agents_overview_action(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
app_server: &mut AppServerSession,
|
||||
thread_id: ThreadId,
|
||||
action: AgentsOverviewAction,
|
||||
) -> color_eyre::Result<()> {
|
||||
if self.windows_sandbox_blocks_thread_switch() {
|
||||
return Ok(());
|
||||
}
|
||||
// The overview may lack intermediate ancestors, or even the primary's metadata.
|
||||
let mut removes_primary = self.primary_thread_id == Some(thread_id);
|
||||
let mut attempted = false;
|
||||
let primary_thread_id = self.primary_thread_id;
|
||||
let events = tui.event_stream();
|
||||
self.prepare_agents_overview_removal(&HashSet::from([thread_id]));
|
||||
let hidden = self.agents_overview.hidden_threads.insert(thread_id);
|
||||
{
|
||||
let mut state = self
|
||||
.agents_overview
|
||||
.view_state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
state.removal = Some(action);
|
||||
// Confirmation may have been opened from the rename editor.
|
||||
state.rename_target = None;
|
||||
}
|
||||
self.repaint_agents_overview();
|
||||
let voice_result = self
|
||||
.stop_voice_for_removed_thread(app_server, thread_id)
|
||||
.await;
|
||||
let operation = async {
|
||||
let result = async {
|
||||
voice_result?;
|
||||
if let Some(primary) = primary_thread_id
|
||||
&& primary != thread_id
|
||||
{
|
||||
removes_primary = app_server
|
||||
.thread_read(primary, /*include_turns*/ false)
|
||||
.await?
|
||||
.session_id
|
||||
== thread_id.to_string();
|
||||
}
|
||||
attempted = true;
|
||||
match action {
|
||||
AgentsOverviewAction::Archive => app_server.thread_archive(thread_id).await,
|
||||
AgentsOverviewAction::Delete => app_server.thread_delete(thread_id).await,
|
||||
}
|
||||
}
|
||||
.await;
|
||||
let mut detach_primary = removes_primary && attempted;
|
||||
if detach_primary
|
||||
&& result.is_err()
|
||||
&& let Some(primary) = primary_thread_id
|
||||
{
|
||||
// A rejected operation may have left the attachment alive. Ask the server directly.
|
||||
let mut cursor = None;
|
||||
while let Ok(page) = app_server
|
||||
.thread_loaded_list(ThreadLoadedListParams {
|
||||
cursor,
|
||||
limit: None,
|
||||
})
|
||||
.await
|
||||
{
|
||||
if page.data.contains(&primary.to_string()) {
|
||||
detach_primary = false;
|
||||
break;
|
||||
}
|
||||
let Some(next) = page.next_cursor else { break };
|
||||
cursor = Some(next);
|
||||
}
|
||||
}
|
||||
(result, detach_primary)
|
||||
};
|
||||
let outcome = run_lifecycle_modal(tui, self, operation, events).await;
|
||||
if hidden {
|
||||
self.agents_overview.hidden_threads.remove(&thread_id);
|
||||
}
|
||||
self.agents_overview
|
||||
.view_state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.removal = None;
|
||||
let (result, detach_primary) = outcome?;
|
||||
if attempted {
|
||||
// A read started before the RPC can contain stale task and approval state.
|
||||
if let Some(refresh) = self.agents_overview.refresh_task.take() {
|
||||
refresh.abort();
|
||||
}
|
||||
self.agents_overview.request_id = None;
|
||||
self.agents_overview.refresh_show_more = false;
|
||||
self.agents_overview.active_refresh_thread_ids.clear();
|
||||
self.agents_overview
|
||||
.view_state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.loading = false;
|
||||
self.agents_overview.refresh_pending = false;
|
||||
self.agents_overview.refresh_notifications.clear();
|
||||
}
|
||||
if result.is_ok() {
|
||||
// Invalidate cached details for the displayed group, without inferring child outcomes.
|
||||
let mut removed = self.known_thread_subtree(thread_id);
|
||||
if let Some(primary) = self.primary_thread_id
|
||||
&& removes_primary
|
||||
{
|
||||
removed.insert(primary);
|
||||
}
|
||||
self.prepare_agents_overview_removal(&removed);
|
||||
for removed_id in removed {
|
||||
self.remove_agents_overview_thread(removed_id);
|
||||
self.agents_overview.activity.remove(&removed_id);
|
||||
self.agents_overview.last_messages.remove(&removed_id);
|
||||
self.agents_overview.usage.remove(&removed_id);
|
||||
self.agents_overview.refresh_thread_ids.remove(&removed_id);
|
||||
self.agents_overview.input_states.remove(&removed_id);
|
||||
self.agents_overview.dispatched_requests.remove(&removed_id);
|
||||
}
|
||||
}
|
||||
if detach_primary {
|
||||
self.agents_overview.selection_after_removal =
|
||||
self.agents_overview.selection_after_removal.or_else(|| {
|
||||
self.chat_widget
|
||||
.selected_index_for_present_view(AGENTS_OVERVIEW_VIEW_ID)
|
||||
.and_then(|index| {
|
||||
self.agents_overview.visible_thread_ids.get(index).copied()
|
||||
})
|
||||
});
|
||||
self.reset_for_thread_switch(tui)?;
|
||||
self.pending_thread_switch_resets += 1;
|
||||
self.app_event_tx
|
||||
.send(AppEvent::ResetTranscriptForThreadSwitch);
|
||||
self.detach_current_thread_for_navigation(app_server, /*destination*/ None)
|
||||
.await;
|
||||
self.reset_thread_event_state().await;
|
||||
let init = self.chatwidget_init_for_forked_or_resumed_thread(
|
||||
tui,
|
||||
self.config.clone(),
|
||||
/*initial_user_message*/ None,
|
||||
);
|
||||
self.replace_chat_widget(ChatWidget::new_with_app_event(init));
|
||||
self.open_agents_overview(app_server);
|
||||
} else {
|
||||
self.repaint_agents_overview();
|
||||
if attempted {
|
||||
self.refresh_agents_overview_threads(app_server);
|
||||
}
|
||||
}
|
||||
if let Err(error) = result {
|
||||
let verb = match action {
|
||||
AgentsOverviewAction::Archive => "archive",
|
||||
AgentsOverviewAction::Delete => "delete",
|
||||
};
|
||||
let mut header = vec![
|
||||
format!("Could not {verb} task").red().bold().into(),
|
||||
format!("{error:#}").red().into(),
|
||||
];
|
||||
if attempted {
|
||||
header.push(
|
||||
"Work may have stopped. Resume the task to continue, or retry the action."
|
||||
.dim()
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
self.chat_widget.show_selection_view(SelectionViewParams {
|
||||
header: Box::new(LifecycleHeader(header)),
|
||||
items: vec![SelectionItem {
|
||||
name: "Back to agents".to_string(),
|
||||
dismiss_on_select: true,
|
||||
..Default::default()
|
||||
}],
|
||||
..SelectionViewParams::picker()
|
||||
});
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "agents_overview_action_progress_tests.rs"]
|
||||
mod progress_tests;
|
||||
1144
akode-rs/tui/src/app/agents_overview_actions_tests.rs
Normal file
1144
akode-rs/tui/src/app/agents_overview_actions_tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
293
akode-rs/tui/src/app/agents_overview_details.rs
Normal file
293
akode-rs/tui/src/app/agents_overview_details.rs
Normal file
@@ -0,0 +1,293 @@
|
||||
//! Bounded overview previews from existing reads and already-delivered events.
|
||||
//! Observing activity never attaches to a thread or fetches additional history.
|
||||
//! Message previews retain Markdown until the details panel's width is known.
|
||||
|
||||
use super::App;
|
||||
use super::ThreadBufferedEvent;
|
||||
use super::ThreadEventAttachment;
|
||||
use super::agents_overview_view::AgentsOverviewGroup;
|
||||
use akode_app_server_protocol::ItemCompletedNotification;
|
||||
use akode_app_server_protocol::McpServerElicitationRequest;
|
||||
use akode_app_server_protocol::ServerNotification;
|
||||
use akode_app_server_protocol::ServerRequest;
|
||||
use akode_app_server_protocol::Thread;
|
||||
use akode_app_server_protocol::ThreadActiveFlag;
|
||||
use akode_app_server_protocol::ThreadItemPayload;
|
||||
use akode_app_server_protocol::ThreadStatus;
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use ratatui::style::Stylize;
|
||||
use ratatui::text::Line;
|
||||
use std::collections::HashMap;
|
||||
|
||||
const PREVIEW_CHARS: usize = 512;
|
||||
|
||||
pub(super) fn preview_agent_message(text: &str) -> String {
|
||||
preview_markdown(&crate::markdown::normalize_markdown_for_rendering(text))
|
||||
}
|
||||
|
||||
pub(super) fn preview_markdown(text: &str) -> String {
|
||||
text.chars()
|
||||
.filter(|ch| !ch.is_control() || matches!(ch, '\n' | '\t'))
|
||||
.take(PREVIEW_CHARS)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub(super) struct AgentsOverviewDetails {
|
||||
pub(super) latest_prompt: Option<String>,
|
||||
pub(super) lines: Vec<Line<'static>>,
|
||||
pub(super) usage_lines: Vec<Line<'static>>,
|
||||
pub(super) last_message: Option<(String, AbsolutePathBuf)>,
|
||||
}
|
||||
|
||||
pub(super) fn preview_text(text: &str) -> String {
|
||||
text.chars()
|
||||
.map(|ch| if ch.is_whitespace() { ' ' } else { ch })
|
||||
.filter(|ch| !ch.is_control())
|
||||
.take(PREVIEW_CHARS)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct AgentsOverviewActivity {
|
||||
pub(super) latest_prompt: Option<String>,
|
||||
reasoning: Option<ReasoningPreview>,
|
||||
last_message: Option<String>,
|
||||
}
|
||||
|
||||
struct ReasoningPreview {
|
||||
turn_id: String,
|
||||
item_id: String,
|
||||
summary_index: i64,
|
||||
buffer: String,
|
||||
header: Option<String>,
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub(super) fn track_agents_overview_activity(
|
||||
&mut self,
|
||||
thread_id: ThreadId,
|
||||
notification: &ServerNotification,
|
||||
) {
|
||||
if !self.agents_overview.threads.contains_key(&thread_id) {
|
||||
return;
|
||||
}
|
||||
let activity = self.agents_overview.activity.entry(thread_id).or_default();
|
||||
let changed = match notification {
|
||||
ServerNotification::ReasoningSummaryTextDelta(delta) => {
|
||||
let had_header = activity
|
||||
.reasoning
|
||||
.as_ref()
|
||||
.is_some_and(|reasoning| reasoning.header.is_some());
|
||||
if activity.reasoning.as_ref().is_none_or(|reasoning| {
|
||||
reasoning.turn_id != delta.turn_id
|
||||
|| reasoning.item_id != delta.item_id
|
||||
|| reasoning.summary_index != delta.summary_index
|
||||
}) {
|
||||
activity.reasoning = Some(ReasoningPreview {
|
||||
turn_id: delta.turn_id.clone(),
|
||||
item_id: delta.item_id.clone(),
|
||||
summary_index: delta.summary_index,
|
||||
buffer: String::new(),
|
||||
header: None,
|
||||
});
|
||||
}
|
||||
let Some(reasoning) = activity.reasoning.as_mut() else {
|
||||
return;
|
||||
};
|
||||
if reasoning.header.is_some() {
|
||||
return;
|
||||
}
|
||||
let remaining = PREVIEW_CHARS.saturating_sub(reasoning.buffer.chars().count());
|
||||
reasoning.buffer.extend(delta.delta.chars().take(remaining));
|
||||
reasoning.header = crate::chatwidget::extract_first_bold(&reasoning.buffer)
|
||||
.map(|header| preview_text(&header));
|
||||
had_header || reasoning.header.is_some()
|
||||
}
|
||||
ServerNotification::ItemCompleted(ItemCompletedNotification {
|
||||
item:
|
||||
akode_app_server_protocol::ThreadItem {
|
||||
payload: ThreadItemPayload::AgentMessage { text, .. },
|
||||
..
|
||||
},
|
||||
..
|
||||
}) => {
|
||||
activity.last_message = Some(preview_agent_message(text));
|
||||
activity.reasoning = None;
|
||||
true
|
||||
}
|
||||
ServerNotification::TurnStarted(_)
|
||||
| ServerNotification::TurnCompleted(_)
|
||||
| ServerNotification::ReasoningSummaryPartAdded(_)
|
||||
| ServerNotification::ItemStarted(_) => activity.reasoning.take().is_some(),
|
||||
ServerNotification::ThreadStatusChanged(status)
|
||||
if !matches!(status.status, ThreadStatus::Active { .. }) =>
|
||||
{
|
||||
activity.reasoning.take().is_some()
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
if changed {
|
||||
self.repaint_agents_overview();
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn agents_overview_details(
|
||||
&self,
|
||||
root: &Thread,
|
||||
children: &HashMap<String, Vec<&Thread>>,
|
||||
) -> AgentsOverviewDetails {
|
||||
let mut lines = Vec::new();
|
||||
// Urgency comes first; on ties, prefer available current detail over history.
|
||||
let priority = |thread: &Thread| {
|
||||
let group = AgentsOverviewGroup::for_thread(thread);
|
||||
let has_detail = ThreadId::from_string(&thread.id).is_ok_and(|id| match group {
|
||||
AgentsOverviewGroup::NeedsYou => self.agents_overview_request_preview(id).is_some(),
|
||||
AgentsOverviewGroup::Working => {
|
||||
self.thread_event_channels
|
||||
.get(&id)
|
||||
.is_none_or(|channel| channel.attachment() == ThreadEventAttachment::Live)
|
||||
&& self
|
||||
.agents_overview
|
||||
.activity
|
||||
.get(&id)
|
||||
.and_then(|activity| activity.reasoning.as_ref())
|
||||
.is_some_and(|reasoning| reasoning.header.is_some())
|
||||
}
|
||||
AgentsOverviewGroup::Ready | AgentsOverviewGroup::Finished => false,
|
||||
});
|
||||
(group, !has_detail)
|
||||
};
|
||||
let mut source = root;
|
||||
let mut pending = vec![root];
|
||||
while let Some(thread) = pending.pop() {
|
||||
if priority(thread) < priority(source) {
|
||||
source = thread;
|
||||
}
|
||||
pending.extend(children.get(&thread.id).into_iter().flatten().copied());
|
||||
pending.sort_by(|left, right| right.id.cmp(&left.id));
|
||||
}
|
||||
let Ok(thread_id) = ThreadId::from_string(&source.id) else {
|
||||
return AgentsOverviewDetails::default();
|
||||
};
|
||||
let channel = self.thread_event_channels.get(&thread_id);
|
||||
let is_child = source.id != root.id;
|
||||
if is_child {
|
||||
let name = source
|
||||
.agent_nickname
|
||||
.as_deref()
|
||||
.or(source.name.as_deref())
|
||||
.unwrap_or(&source.id);
|
||||
lines.push(Line::default());
|
||||
lines.push(vec!["Agent: ".dim(), preview_text(name).into()].into());
|
||||
}
|
||||
if AgentsOverviewGroup::for_thread(source) == AgentsOverviewGroup::NeedsYou {
|
||||
if !is_child {
|
||||
lines.extend([Line::default(), "Needs attention".red().into()]);
|
||||
}
|
||||
if let Some(request) = self.agents_overview_request_preview(thread_id) {
|
||||
lines.push(request.into());
|
||||
}
|
||||
lines.push("Open task to review.".dim().into());
|
||||
match &source.status {
|
||||
ThreadStatus::Active { active_flags } => {
|
||||
if active_flags.contains(&ThreadActiveFlag::WaitingOnApproval) {
|
||||
lines.push("Waiting for approval.".into());
|
||||
}
|
||||
if active_flags.contains(&ThreadActiveFlag::WaitingOnUserInput) {
|
||||
lines.push("Waiting for your response.".into());
|
||||
}
|
||||
}
|
||||
ThreadStatus::SystemError => lines.push("Task encountered an error.".into()),
|
||||
ThreadStatus::NotLoaded | ThreadStatus::Idle => {}
|
||||
}
|
||||
}
|
||||
let activity = self.agents_overview.activity.get(&thread_id).filter(|_| {
|
||||
channel.is_none_or(|channel| channel.attachment() == ThreadEventAttachment::Live)
|
||||
});
|
||||
if matches!(source.status, ThreadStatus::Active { .. })
|
||||
&& let Some(header) = activity
|
||||
.and_then(|activity| activity.reasoning.as_ref())
|
||||
.and_then(|reasoning| reasoning.header.as_ref())
|
||||
{
|
||||
if !is_child {
|
||||
lines.push(Line::default());
|
||||
}
|
||||
lines.extend(["Latest activity".dim().into(), header.clone().into()]);
|
||||
}
|
||||
let last_message = activity
|
||||
.and_then(|activity| activity.last_message.as_ref())
|
||||
.or_else(|| self.agents_overview.last_messages.get(&thread_id))
|
||||
.filter(|message| !message.trim().is_empty())
|
||||
.map(|message| (message.clone(), source.cwd.clone()));
|
||||
let root_id = ThreadId::from_string(&root.id).ok();
|
||||
AgentsOverviewDetails {
|
||||
latest_prompt: root_id.and_then(|id| {
|
||||
self.agents_overview
|
||||
.activity
|
||||
.get(&id)?
|
||||
.latest_prompt
|
||||
.clone()
|
||||
}),
|
||||
lines,
|
||||
usage_lines: root_id
|
||||
.and_then(|id| self.agents_overview.usage.get(&id))
|
||||
.map(super::agents_overview_usage::usage_lines)
|
||||
.unwrap_or_default(),
|
||||
last_message,
|
||||
}
|
||||
}
|
||||
|
||||
fn agents_overview_request_preview(&self, thread_id: ThreadId) -> Option<String> {
|
||||
self.agents_overview
|
||||
.dispatched_requests
|
||||
.get(&thread_id)
|
||||
.and_then(|requests| {
|
||||
requests
|
||||
.iter()
|
||||
.find_map(|request| request_preview(&request.request))
|
||||
})
|
||||
.or_else(|| {
|
||||
let channel = self
|
||||
.thread_event_channels
|
||||
.get(&thread_id)
|
||||
.filter(|channel| channel.attachment() == ThreadEventAttachment::Live)?;
|
||||
let store = channel.store.try_lock().ok()?;
|
||||
store.buffer.iter().find_map(|event| {
|
||||
if let ThreadBufferedEvent::Request(request) = event
|
||||
&& store
|
||||
.pending_interactive_replay
|
||||
.should_replay_snapshot_request(request)
|
||||
{
|
||||
request_preview(request)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn request_preview(request: &ServerRequest) -> Option<String> {
|
||||
let text = match request {
|
||||
ServerRequest::CommandExecutionRequestApproval { params, .. } => {
|
||||
params.reason.as_deref().or(params.command.as_deref())
|
||||
}
|
||||
ServerRequest::FileChangeRequestApproval { params, .. } => params.reason.as_deref(),
|
||||
ServerRequest::PermissionsRequestApproval { params, .. } => params.reason.as_deref(),
|
||||
ServerRequest::McpServerElicitationRequest { params, .. } => match ¶ms.request {
|
||||
McpServerElicitationRequest::Form { message, .. }
|
||||
| McpServerElicitationRequest::OpenAiForm { message, .. }
|
||||
| McpServerElicitationRequest::OpenAiElicitationForm { message, .. }
|
||||
| McpServerElicitationRequest::Url { message, .. } => Some(message.as_str()),
|
||||
McpServerElicitationRequest::UserVerification { .. } => None,
|
||||
},
|
||||
ServerRequest::ToolRequestUserInput { params, .. } => params
|
||||
.questions
|
||||
.first()
|
||||
.map(|question| question.question.as_str()),
|
||||
_ => None,
|
||||
}?;
|
||||
Some(preview_text(text))
|
||||
}
|
||||
349
akode-rs/tui/src/app/agents_overview_discovery.rs
Normal file
349
akode-rs/tui/src/app/agents_overview_discovery.rs
Normal file
@@ -0,0 +1,349 @@
|
||||
//! Demand-driven history discovery. Each source retains its cursor and unshown rows.
|
||||
//! Each new query scans the active backend from the start with its own paging cursor.
|
||||
|
||||
use super::App;
|
||||
use crate::app_event::AppEvent;
|
||||
use akode_app_server_client::AppServerRequestHandle;
|
||||
use akode_app_server_client::TypedRequestError;
|
||||
use akode_app_server_protocol::ClientRequest;
|
||||
use akode_app_server_protocol::RequestId;
|
||||
use akode_app_server_protocol::SessionSource;
|
||||
use akode_app_server_protocol::Thread;
|
||||
use akode_app_server_protocol::ThreadListParams;
|
||||
use akode_app_server_protocol::ThreadListResponse;
|
||||
use akode_app_server_protocol::ThreadSortKey;
|
||||
use akode_app_server_protocol::ThreadSourceKind;
|
||||
use akode_protocol::protocol::SubAgentSource;
|
||||
use akode_state::PINNED_THREAD_SECTION_ID;
|
||||
use std::collections::VecDeque;
|
||||
use std::sync::PoisonError;
|
||||
use tokio_util::task::AbortOnDropHandle;
|
||||
use uuid::Uuid;
|
||||
|
||||
const PAGE_SIZE: u32 = 10;
|
||||
|
||||
// Pair each row with its batched receipt before buffering or merging source pages.
|
||||
fn listed_threads(page: ThreadListResponse) -> impl Iterator<Item = (Thread, bool)> {
|
||||
page.data.into_iter().map(move |thread| {
|
||||
let unread = page
|
||||
.read_states
|
||||
.as_ref()
|
||||
.and_then(|states| states.get(&thread.id))
|
||||
.is_some_and(|state| state.first_unread.is_some());
|
||||
(thread, unread)
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn list_pinned_threads(
|
||||
handle: &AppServerRequestHandle,
|
||||
) -> Result<Option<Vec<(Thread, bool)>>, String> {
|
||||
let mut threads = Vec::new();
|
||||
for source_kinds in [
|
||||
Vec::new(),
|
||||
vec![ThreadSourceKind::Exec, ThreadSourceKind::AppServer],
|
||||
] {
|
||||
let mut cursor = None;
|
||||
loop {
|
||||
let result = handle
|
||||
.request_typed::<ThreadListResponse>(ClientRequest::ThreadList {
|
||||
request_id: RequestId::String(Uuid::new_v4().to_string()),
|
||||
params: ThreadListParams {
|
||||
current_account_only: true,
|
||||
excluded_thread_ids: None,
|
||||
originators: None,
|
||||
cursor: cursor.clone(),
|
||||
limit: Some(100),
|
||||
attached_to_thread_id: None,
|
||||
sort_key: Some(ThreadSortKey::SectionPosition),
|
||||
sort_direction: None,
|
||||
model_providers: Some(Vec::new()),
|
||||
source_kinds: Some(source_kinds.clone()),
|
||||
archived: Some(false),
|
||||
section_id: Some(Some(PINNED_THREAD_SECTION_ID.to_string())),
|
||||
project_id: None,
|
||||
parent_thread_id: None,
|
||||
ancestor_thread_id: None,
|
||||
cwd: None,
|
||||
use_state_db_only: true,
|
||||
search_term: None,
|
||||
},
|
||||
})
|
||||
.await;
|
||||
match result {
|
||||
Ok(page) => {
|
||||
let next_cursor = page.next_cursor.clone();
|
||||
threads.extend(listed_threads(page).filter(|(thread, _)| {
|
||||
is_overview_thread(thread) && supports_shared_pinning(&thread.source)
|
||||
}));
|
||||
let Some(next_cursor) = next_cursor else {
|
||||
break;
|
||||
};
|
||||
cursor = Some(next_cursor);
|
||||
}
|
||||
Err(TypedRequestError::Server { source, .. })
|
||||
if matches!(source.code, -32602..=-32600) =>
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
Err(error) => return Err(error.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Some(threads))
|
||||
}
|
||||
|
||||
fn is_overview_thread(thread: &Thread) -> bool {
|
||||
!thread.ephemeral
|
||||
&& thread.parent_thread_id.is_none()
|
||||
&& !matches!(
|
||||
thread.source,
|
||||
SessionSource::SubAgent(SubAgentSource::ThreadSpawn { .. })
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn supports_shared_pinning(source: &SessionSource) -> bool {
|
||||
matches!(
|
||||
source,
|
||||
SessionSource::Cli | SessionSource::VsCode | SessionSource::Exec | SessionSource::AppServer
|
||||
) || matches!(source, SessionSource::Custom(source) if matches!(source.as_str(), "atlas" | "chatgpt"))
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
struct SourcePage {
|
||||
cursor: Option<String>,
|
||||
rows: VecDeque<(Thread, bool)>,
|
||||
exhausted: bool,
|
||||
sort_key: ThreadSortKey,
|
||||
page_size: u32,
|
||||
}
|
||||
|
||||
impl Default for SourcePage {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
cursor: None,
|
||||
rows: VecDeque::new(),
|
||||
exhausted: false,
|
||||
sort_key: ThreadSortKey::RecencyAt,
|
||||
page_size: PAGE_SIZE,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(crate) struct AgentsOverviewDiscovery {
|
||||
sources: [SourcePage; 2],
|
||||
}
|
||||
|
||||
impl AgentsOverviewDiscovery {
|
||||
pub(super) fn has_more(&self) -> bool {
|
||||
self.sources
|
||||
.iter()
|
||||
.any(|source| !source.exhausted || !source.rows.is_empty())
|
||||
}
|
||||
|
||||
pub(super) async fn next_batch(
|
||||
&mut self,
|
||||
handle: &AppServerRequestHandle,
|
||||
limit: usize,
|
||||
) -> (Vec<(Thread, bool)>, bool) {
|
||||
let [interactive, other] = &mut self.sources;
|
||||
let (left, right) = tokio::join!(
|
||||
interactive.fill(handle, Vec::new()),
|
||||
other.fill(
|
||||
handle,
|
||||
vec![ThreadSourceKind::Exec, ThreadSourceKind::AppServer]
|
||||
),
|
||||
);
|
||||
let mut rows = Vec::new();
|
||||
for _ in 0..limit {
|
||||
let next = self
|
||||
.sources
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, source)| {
|
||||
source.rows.front().map(|(thread, _)| (index, thread))
|
||||
})
|
||||
.max_by(|(_, left), (_, right)| {
|
||||
left.recency_at
|
||||
.unwrap_or(left.updated_at)
|
||||
.cmp(&right.recency_at.unwrap_or(right.updated_at))
|
||||
.then_with(|| left.id.cmp(&right.id))
|
||||
})
|
||||
.map(|(index, _)| index);
|
||||
let Some(index) = next else { break };
|
||||
if let Some(row) = self.sources[index].rows.pop_front() {
|
||||
rows.push(row);
|
||||
}
|
||||
}
|
||||
(rows, left && right)
|
||||
}
|
||||
}
|
||||
|
||||
impl SourcePage {
|
||||
async fn fill(
|
||||
&mut self,
|
||||
handle: &AppServerRequestHandle,
|
||||
source_kinds: Vec<ThreadSourceKind>,
|
||||
) -> bool {
|
||||
if self.exhausted || self.rows.len() >= PAGE_SIZE as usize {
|
||||
return true;
|
||||
}
|
||||
loop {
|
||||
let result = handle
|
||||
.request_typed::<ThreadListResponse>(ClientRequest::ThreadList {
|
||||
request_id: RequestId::String(Uuid::new_v4().to_string()),
|
||||
params: ThreadListParams {
|
||||
current_account_only: true,
|
||||
excluded_thread_ids: None,
|
||||
attached_to_thread_id: None,
|
||||
originators: None,
|
||||
cursor: self.cursor.clone(),
|
||||
limit: Some(self.page_size),
|
||||
sort_key: Some(self.sort_key),
|
||||
sort_direction: None,
|
||||
model_providers: Some(Vec::new()),
|
||||
source_kinds: Some(source_kinds.clone()),
|
||||
archived: Some(false),
|
||||
section_id: None,
|
||||
project_id: None,
|
||||
parent_thread_id: None,
|
||||
ancestor_thread_id: None,
|
||||
cwd: None,
|
||||
use_state_db_only: true,
|
||||
search_term: None,
|
||||
},
|
||||
})
|
||||
.await;
|
||||
match result {
|
||||
Err(TypedRequestError::Server { source, .. })
|
||||
if self.sort_key == ThreadSortKey::RecencyAt
|
||||
&& matches!(source.code, -32600 | -32602)
|
||||
&& source.message.contains("recency_at") =>
|
||||
{
|
||||
self.sort_key = ThreadSortKey::UpdatedAt;
|
||||
self.cursor = None;
|
||||
}
|
||||
Ok(page) => {
|
||||
if page.next_cursor.is_some() && page.next_cursor == self.cursor {
|
||||
return false;
|
||||
}
|
||||
self.exhausted = page.next_cursor.is_none();
|
||||
self.cursor = page.next_cursor.clone();
|
||||
self.rows.extend(
|
||||
listed_threads(page).filter(|(thread, _)| is_overview_thread(thread)),
|
||||
);
|
||||
return true;
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "failed to list more agent threads");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct HistorySearch {
|
||||
pub(super) id: Uuid,
|
||||
pub(super) cursor: AgentsOverviewDiscovery,
|
||||
/// Requested number of matches visible under the active status filter.
|
||||
pub(super) target: usize,
|
||||
pub(super) loading: bool,
|
||||
pub(super) failed: bool,
|
||||
pub(super) task: Option<AbortOnDropHandle<()>>,
|
||||
}
|
||||
|
||||
pub(super) fn matches_query(thread: &Thread, query: &str) -> bool {
|
||||
let name = thread.name.as_deref().unwrap_or_default();
|
||||
let cwd = thread.cwd.display();
|
||||
format!("{name} {} {cwd}", thread.preview)
|
||||
.to_lowercase()
|
||||
.contains(query)
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub(super) fn search_agents_overview(
|
||||
&mut self,
|
||||
handle: AppServerRequestHandle,
|
||||
id: Uuid,
|
||||
limit: usize,
|
||||
) {
|
||||
let shared = &self.agents_overview.view_state;
|
||||
let mut state = shared.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let query = state.search.to_lowercase();
|
||||
let Some(search) = state.history.as_mut().filter(|search| search.id == id) else {
|
||||
return;
|
||||
};
|
||||
let first = self.agents_overview.search_id != id;
|
||||
let mut cursor = std::mem::take(&mut search.cursor);
|
||||
if first {
|
||||
self.agents_overview.search_matches.clear();
|
||||
self.agents_overview.search_id = id;
|
||||
}
|
||||
for source in &mut cursor.sources {
|
||||
source.page_size = 100;
|
||||
}
|
||||
if matches!(handle, AppServerRequestHandle::Cloud(_)) {
|
||||
cursor.sources[1].exhausted = true;
|
||||
}
|
||||
let tx = self.app_event_tx.clone();
|
||||
search.task = Some(AbortOnDropHandle::new(tokio::spawn(async move {
|
||||
if first {
|
||||
tokio::time::sleep(std::time::Duration::from_millis(180)).await;
|
||||
}
|
||||
loop {
|
||||
let (mut rows, ok) = cursor.next_batch(&handle, limit).await;
|
||||
rows.retain(|(thread, _)| matches_query(thread, &query));
|
||||
if rows.is_empty() && ok && cursor.has_more() {
|
||||
continue;
|
||||
}
|
||||
tx.send(AppEvent::AgentsOverviewSearchPage {
|
||||
id,
|
||||
rows,
|
||||
cursor,
|
||||
ok,
|
||||
});
|
||||
return;
|
||||
}
|
||||
})));
|
||||
}
|
||||
|
||||
pub(super) fn apply_agents_overview_search_page(
|
||||
&mut self,
|
||||
id: Uuid,
|
||||
rows: Vec<(Thread, bool)>,
|
||||
cursor: AgentsOverviewDiscovery,
|
||||
ok: bool,
|
||||
) {
|
||||
let overview = &mut self.agents_overview;
|
||||
let mut state = overview
|
||||
.view_state
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner);
|
||||
let Some(search) = state.history.as_mut().filter(|s| s.id == id) else {
|
||||
return;
|
||||
};
|
||||
for (thread, unread) in rows {
|
||||
if let Ok(id) = akode_protocol::ThreadId::from_string(&thread.id)
|
||||
&& !overview.threads.get(&id).is_some_and(Option::is_some)
|
||||
&& !overview.removed_threads.contains(&id)
|
||||
&& !overview.hidden_threads.contains(&id)
|
||||
&& let std::collections::hash_map::Entry::Vacant(entry) =
|
||||
overview.search_matches.entry(id)
|
||||
{
|
||||
entry.insert(thread);
|
||||
if unread {
|
||||
overview.unread.insert(id);
|
||||
} else {
|
||||
overview.unread.remove(&id);
|
||||
}
|
||||
}
|
||||
}
|
||||
search.cursor = cursor;
|
||||
search.loading = false;
|
||||
search.failed = !ok;
|
||||
drop(state);
|
||||
self.repaint_agents_overview();
|
||||
}
|
||||
}
|
||||
325
akode-rs/tui/src/app/agents_overview_discovery_tests.rs
Normal file
325
akode-rs/tui/src/app/agents_overview_discovery_tests.rs
Normal file
@@ -0,0 +1,325 @@
|
||||
//! Demand-driven discovery, cursor retry, and visible Show more behavior.
|
||||
|
||||
use super::*;
|
||||
use crate::app_event::AgentsOverviewAction;
|
||||
use crate::app_server_session::ThreadParamsMode;
|
||||
use akode_app_server_protocol::JSONRPCMessage;
|
||||
use futures::SinkExt;
|
||||
use futures::StreamExt;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicBool;
|
||||
use std::sync::atomic::Ordering;
|
||||
use tokio::net::TcpListener;
|
||||
use tokio_tungstenite::tungstenite::Message;
|
||||
|
||||
#[tokio::test]
|
||||
async fn overview_show_more_refills_archived_rows_and_retries_without_losing_rows() -> Result<()> {
|
||||
check_discovery(/*mixed_sources*/ false).await?;
|
||||
check_discovery(/*mixed_sources*/ true).await
|
||||
}
|
||||
|
||||
async fn check_discovery(mixed_sources: bool) -> Result<()> {
|
||||
let mut app = make_test_app().await;
|
||||
let rows: Vec<_> = (0..24)
|
||||
.map(|index| {
|
||||
let mut thread = overview_thread(
|
||||
ThreadId::new(),
|
||||
/*parent_thread_id*/ None,
|
||||
&format!("Task {index}"),
|
||||
ThreadStatus::NotLoaded,
|
||||
);
|
||||
if mixed_sources && (index == 0 || index >= 21) {
|
||||
thread.source = SessionSource::Exec;
|
||||
}
|
||||
if index == 23 {
|
||||
thread.name = None;
|
||||
}
|
||||
thread.updated_at += 24 - index;
|
||||
thread.recency_at = Some(thread.updated_at);
|
||||
thread
|
||||
})
|
||||
.collect();
|
||||
let ids: Vec<_> = rows
|
||||
.iter()
|
||||
.map(|row| ThreadId::from_string(&row.id).unwrap())
|
||||
.collect();
|
||||
let mut expected: HashMap<_, _> = rows
|
||||
.iter()
|
||||
.map(|thread| {
|
||||
(
|
||||
ThreadId::from_string(&thread.id).unwrap(),
|
||||
Some(thread.clone()),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let reopened_pin = overview_thread(
|
||||
ThreadId::new(),
|
||||
/*parent_thread_id*/ None,
|
||||
"Pinned after reopen",
|
||||
ThreadStatus::NotLoaded,
|
||||
);
|
||||
let reopened_pin_id = ThreadId::from_string(&reopened_pin.id).unwrap();
|
||||
let show_reopened_pin = Arc::new(AtomicBool::new(false));
|
||||
let expected_first_twenty: HashSet<_> = rows[1..21]
|
||||
.iter()
|
||||
.map(|row| ThreadId::from_string(&row.id).unwrap())
|
||||
.collect();
|
||||
let listener = TcpListener::bind("127.0.0.1:0").await?;
|
||||
let endpoint = crate::resolve_remote_addr(&format!("ws://{}", listener.local_addr()?))?;
|
||||
let server_show_reopened_pin = Arc::clone(&show_reopened_pin);
|
||||
let server = tokio::spawn(async move {
|
||||
let (stream, _) = listener.accept().await?;
|
||||
let mut socket = tokio_tungstenite::accept_async(stream).await?;
|
||||
let mut cursors = Vec::new();
|
||||
while let Some(Ok(Message::Text(text))) = socket.next().await {
|
||||
let JSONRPCMessage::Request(request) = serde_json::from_str(&text)? else {
|
||||
continue;
|
||||
};
|
||||
let params = request.params.unwrap_or_default();
|
||||
let result = match request.method.as_str() {
|
||||
"initialize" => json!({"userAgent": "overview-test/1.0"}),
|
||||
"thread/loaded/list" => json!({"data": [], "nextCursor": null}),
|
||||
"thread/list" => {
|
||||
if params["sortKey"] == "section_position" {
|
||||
assert_eq!(params["sectionId"], akode_state::PINNED_THREAD_SECTION_ID);
|
||||
let interactive = params["sourceKinds"] == json!([]);
|
||||
let cursor = params["cursor"].as_str();
|
||||
let reopened = server_show_reopened_pin.load(Ordering::SeqCst);
|
||||
let data = if reopened && interactive && cursor.is_none() {
|
||||
vec![reopened_pin.clone()]
|
||||
} else if interactive && cursor == Some("pinned-page-2") {
|
||||
vec![rows[1].clone()]
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
socket
|
||||
.send(Message::Text(
|
||||
json!({
|
||||
"id": request.id,
|
||||
"result": {
|
||||
"data": data,
|
||||
"nextCursor": (!reopened && interactive && cursor.is_none())
|
||||
.then_some("pinned-page-2"),
|
||||
}
|
||||
})
|
||||
.to_string()
|
||||
.into(),
|
||||
))
|
||||
.await?;
|
||||
continue;
|
||||
}
|
||||
assert_eq!(params["sortKey"], "recency_at");
|
||||
let limit = params["limit"].as_u64().unwrap() as usize;
|
||||
assert!(params["searchTerm"].is_null());
|
||||
{
|
||||
let interactive = params["sourceKinds"] == json!([]);
|
||||
let mut source_rows: Vec<_> = rows
|
||||
.iter()
|
||||
.filter(|row| matches!(row.source, SessionSource::Exec) != interactive)
|
||||
.collect();
|
||||
if interactive && server_show_reopened_pin.load(Ordering::SeqCst) {
|
||||
source_rows.insert(0, &reopened_pin);
|
||||
}
|
||||
let cursor = params["cursor"].as_str().unwrap_or("0").parse::<usize>()?;
|
||||
if interactive && limit == 10 {
|
||||
cursors.push(cursor);
|
||||
}
|
||||
if limit == 10 && !mixed_sources && interactive && cursors == [0, 10] {
|
||||
socket.send(Message::Text(json!({"id": request.id, "error": {"code": -32603, "message": "transient"}}).to_string().into())).await?;
|
||||
continue;
|
||||
}
|
||||
let end = (cursor + limit).min(source_rows.len());
|
||||
json!({"data": source_rows[cursor..end], "nextCursor": (end < source_rows.len()).then(|| end.to_string())})
|
||||
}
|
||||
}
|
||||
"thread/read" => {
|
||||
let thread = rows
|
||||
.iter()
|
||||
.find(|thread| thread.id == params["threadId"])
|
||||
.unwrap();
|
||||
json!({"thread": thread, "readState": {"revision": "read", "firstUnread": null}})
|
||||
}
|
||||
"thread/turns/list" if params["threadId"] == rows[23].id => json!({"data": [{
|
||||
"id":"latest", "status":"completed", "items":[{"type":"userMessage","id":"prompt",
|
||||
"content":[{"type":"text","text":"A later prompt","textElements":[]}]}]
|
||||
}], "nextCursor":null}),
|
||||
"thread/turns/list" => json!({"data": [], "nextCursor": null}),
|
||||
"thread/archive" | "thread/delete" => {
|
||||
socket.send(Message::Text(json!({"id": request.id, "error":{"code":-32603,"message":"try again"}}).to_string().into())).await?;
|
||||
continue;
|
||||
}
|
||||
method => panic!("unexpected request: {method}"),
|
||||
};
|
||||
socket
|
||||
.send(Message::Text(
|
||||
json!({"id": request.id, "result": result})
|
||||
.to_string()
|
||||
.into(),
|
||||
))
|
||||
.await?;
|
||||
}
|
||||
Ok::<_, color_eyre::Report>(cursors)
|
||||
});
|
||||
let mut session = AppServerSession::new(
|
||||
crate::backend_id::BackendId::new(),
|
||||
crate::connect_remote_app_server(endpoint).await?,
|
||||
ThreadParamsMode::Remote,
|
||||
);
|
||||
let view = app.agents_overview_view(Vec::new(), /*selected_thread_id*/ None);
|
||||
app.chat_widget.show_bottom_pane_view(Box::new(view));
|
||||
let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
|
||||
app.app_event_tx = AppEventSender::new(tx);
|
||||
app.refresh_agents_overview_threads(&session);
|
||||
finish_overview_refresh(&mut app, &session, &mut rx).await;
|
||||
assert_eq!(app.agents_overview.threads.len(), 10);
|
||||
assert_eq!(app.agents_overview.pinned_thread_ids, Some(vec![ids[1]]));
|
||||
assert!(app.agents_overview.discovery.has_more());
|
||||
let browse = app.agents_overview.threads.clone();
|
||||
let browse_rows = || browse.values().flatten().cloned().collect();
|
||||
let mut view = app.agents_overview_view(browse_rows(), Some(ids[4]));
|
||||
view.handle_key_event(KeyCode::Char('/').into());
|
||||
view.handle_paste("TASK 23".into());
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
tui.pause_events();
|
||||
finish_history_search(&mut app, &mut tui, &mut session, &mut rx).await?;
|
||||
assert_eq!(app.agents_overview.search_matches.len(), 1);
|
||||
view = app.agents_overview_view(browse_rows(), /*selected_thread_id*/ None);
|
||||
assert_eq!(view.thread_ids()[view.selected_index().unwrap()], ids[23]);
|
||||
let action = if mixed_sources {
|
||||
AgentsOverviewAction::Archive
|
||||
} else {
|
||||
AgentsOverviewAction::Delete
|
||||
};
|
||||
Box::pin(app.run_agents_overview_action(&mut tui, &mut session, ids[23], action)).await?;
|
||||
finish_overview_refresh(&mut app, &session, &mut rx).await;
|
||||
app.chat_widget.handle_key_event(KeyCode::Enter.into());
|
||||
assert!(render_bottom_popup(&app.chat_widget, /*width*/ 100).contains("Task 23"));
|
||||
view.handle_key_event(KeyCode::Esc.into());
|
||||
assert_eq!(view.thread_ids()[view.selected_index().unwrap()], ids[4]);
|
||||
assert_eq!(app.agents_overview.threads, browse);
|
||||
view.handle_key_event(KeyCode::Char('/').into());
|
||||
view.handle_paste("TASK 22".into());
|
||||
assert!(super::command_center::screen(&view, /*width*/ 100, /*height*/ 16).contains("All 10 "));
|
||||
finish_history_search(&mut app, &mut tui, &mut session, &mut rx).await?;
|
||||
view = app.agents_overview_view(browse_rows(), /*selected_thread_id*/ None);
|
||||
let rendered = super::command_center::screen(&view, /*width*/ 100, /*height*/ 16);
|
||||
assert!(rendered.contains("All 11 "));
|
||||
assert!(rendered.contains("1 of 10"), "{rendered}"); // The pinned task has its own group.
|
||||
view.handle_key_event(KeyCode::Esc.into());
|
||||
|
||||
app.track_agents_overview_notification(&ServerNotification::ThreadArchived(
|
||||
ThreadArchivedNotification {
|
||||
thread_id: ids[0].to_string(),
|
||||
},
|
||||
));
|
||||
app.remove_agents_overview_thread(ids[0]); // Duplicate local completion must not refill twice.
|
||||
expected.remove(&ids[0]);
|
||||
app.refresh_agents_overview_threads(&session);
|
||||
finish_overview_refresh(&mut app, &session, &mut rx).await;
|
||||
if !mixed_sources {
|
||||
assert_eq!(app.agents_overview.threads.len(), 9);
|
||||
assert!(
|
||||
app.agents_overview
|
||||
.view_state
|
||||
.lock()
|
||||
.unwrap()
|
||||
.refresh_failed
|
||||
);
|
||||
app.show_more_agents_overview(&session);
|
||||
finish_overview_refresh(&mut app, &session, &mut rx).await;
|
||||
}
|
||||
assert_eq!(app.agents_overview.threads.len(), 10);
|
||||
assert!(app.agents_overview.threads.contains_key(&ids[10]));
|
||||
app.show_more_agents_overview(&session);
|
||||
finish_overview_refresh(&mut app, &session, &mut rx).await;
|
||||
assert_eq!(
|
||||
app.agents_overview
|
||||
.threads
|
||||
.keys()
|
||||
.copied()
|
||||
.collect::<HashSet<_>>(),
|
||||
expected_first_twenty
|
||||
);
|
||||
// Another client read this older, unloaded task while the center was closed.
|
||||
app.agents_overview.unread.insert(ids[19]);
|
||||
app.remove_agents_overview_thread(ids[1]);
|
||||
expected.remove(&ids[1]);
|
||||
app.refresh_agents_overview_threads(&session);
|
||||
finish_overview_refresh(&mut app, &session, &mut rx).await;
|
||||
assert!(!app.agents_overview.unread.contains(&ids[19]));
|
||||
assert_eq!(app.agents_overview.threads.len(), 20);
|
||||
assert!(app.agents_overview.threads.contains_key(&ids[21]));
|
||||
for &id in &ids[2..22] {
|
||||
app.remove_agents_overview_thread(id);
|
||||
expected.remove(&id);
|
||||
}
|
||||
assert!(app.agents_overview.threads.is_empty());
|
||||
app.refresh_agents_overview_threads(&session);
|
||||
finish_overview_refresh(&mut app, &session, &mut rx).await;
|
||||
assert_eq!(app.agents_overview.threads, expected);
|
||||
assert!(!app.agents_overview.discovery.has_more());
|
||||
let old = app.agents_overview.threads[&ids[23]].as_ref().unwrap();
|
||||
assert_eq!(old.preview, "Task 23");
|
||||
assert_eq!(
|
||||
app.agents_overview_details(old, &HashMap::new())
|
||||
.latest_prompt
|
||||
.as_deref(),
|
||||
Some("A later prompt")
|
||||
);
|
||||
// Another CLI inserts a matching session ahead of the exhausted browse cursor.
|
||||
show_reopened_pin.store(true, Ordering::SeqCst);
|
||||
view.handle_key_event(KeyCode::Char('/').into());
|
||||
view.handle_paste("Pinned after reopen".into());
|
||||
finish_history_search(&mut app, &mut tui, &mut session, &mut rx).await?;
|
||||
assert!(
|
||||
app.agents_overview
|
||||
.search_matches
|
||||
.contains_key(&reopened_pin_id)
|
||||
);
|
||||
view.handle_key_event(KeyCode::Esc.into());
|
||||
app.agents_overview.threads.clear();
|
||||
app.agents_overview.pinned_thread_ids = Some(Vec::new());
|
||||
app.agents_overview.refill_count = 0;
|
||||
app.refresh_agents_overview_threads(&session);
|
||||
finish_overview_refresh(&mut app, &session, &mut rx).await;
|
||||
assert_eq!(
|
||||
app.agents_overview.pinned_thread_ids,
|
||||
Some(vec![reopened_pin_id])
|
||||
);
|
||||
assert!(app.agents_overview.threads.contains_key(&reopened_pin_id));
|
||||
session.shutdown().await?;
|
||||
assert_eq!(
|
||||
server.await??,
|
||||
if mixed_sources {
|
||||
vec![0, 10]
|
||||
} else {
|
||||
vec![0, 10, 10, 20]
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn finish_history_search(
|
||||
app: &mut App,
|
||||
tui: &mut crate::tui::Tui,
|
||||
session: &mut AppServerSession,
|
||||
rx: &mut tokio::sync::mpsc::UnboundedReceiver<AppEvent>,
|
||||
) -> Result<()> {
|
||||
while app
|
||||
.agents_overview
|
||||
.view_state
|
||||
.lock()
|
||||
.unwrap()
|
||||
.history
|
||||
.as_ref()
|
||||
.is_some_and(|s| s.loading)
|
||||
{
|
||||
let event = tokio::time::timeout(Duration::from_secs(10), rx.recv())
|
||||
.await?
|
||||
.expect("search event");
|
||||
app.handle_event(tui, session, event).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
57
akode-rs/tui/src/app/agents_overview_errors.rs
Normal file
57
akode-rs/tui/src/app/agents_overview_errors.rs
Normal file
@@ -0,0 +1,57 @@
|
||||
//! Reports command-center action failures above the retained dashboard.
|
||||
|
||||
use super::*;
|
||||
use crate::wrapping::word_wrap_lines;
|
||||
use ratatui::buffer::Buffer;
|
||||
|
||||
struct AgentsOverviewErrorHeader(Vec<Line<'static>>);
|
||||
|
||||
impl Renderable for AgentsOverviewErrorHeader {
|
||||
fn render(&self, area: Rect, buf: &mut Buffer) {
|
||||
Renderable::render(
|
||||
&Paragraph::new(word_wrap_lines(&self.0, usize::from(area.width))),
|
||||
area,
|
||||
buf,
|
||||
);
|
||||
}
|
||||
|
||||
fn desired_height(&self, width: u16) -> u16 {
|
||||
word_wrap_lines(&self.0, usize::from(width)).len() as u16
|
||||
}
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub(in crate::app) fn add_agents_overview_error(&mut self, message: String) {
|
||||
self.show_agents_overview_error(/*title*/ None, message);
|
||||
}
|
||||
|
||||
pub(in crate::app) fn show_agents_overview_error(
|
||||
&mut self,
|
||||
title: Option<&'static str>,
|
||||
message: String,
|
||||
) {
|
||||
if self
|
||||
.chat_widget
|
||||
.selected_index_for_present_view(AGENTS_OVERVIEW_VIEW_ID)
|
||||
.is_some()
|
||||
{
|
||||
let items = vec![SelectionItem {
|
||||
name: "Return to command center".to_string(),
|
||||
dismiss_on_select: true,
|
||||
..Default::default()
|
||||
}];
|
||||
self.chat_widget.show_selection_view(SelectionViewParams {
|
||||
header: Box::new(AgentsOverviewErrorHeader(vec![
|
||||
Line::from(title.unwrap_or("Unable to complete action").bold()),
|
||||
Line::from(message.clone().dim()),
|
||||
])),
|
||||
items,
|
||||
..SelectionViewParams::picker()
|
||||
});
|
||||
}
|
||||
self.chat_widget.add_error_message(match title {
|
||||
Some(title) => format!("{title}: {message}"),
|
||||
None => message,
|
||||
});
|
||||
}
|
||||
}
|
||||
163
akode-rs/tui/src/app/agents_overview_grouping.rs
Normal file
163
akode-rs/tui/src/app/agents_overview_grouping.rs
Normal file
@@ -0,0 +1,163 @@
|
||||
//! Command Center grouping, including restoration and client-local preference persistence.
|
||||
//! Directory is view-local so selecting it never writes a value that older clients reject.
|
||||
|
||||
use super::super::App;
|
||||
use super::super::agents_overview::AgentsOverviewState;
|
||||
use super::super::agents_overview_discovery::matches_query;
|
||||
use super::AgentsOverviewView;
|
||||
use crate::legacy_core::config::edit::ConfigEdit;
|
||||
use crate::legacy_core::config::edit::ConfigEditsBuilder;
|
||||
use akode_app_server_protocol::Thread;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
|
||||
pub(in crate::app) enum AgentsOverviewGrouping {
|
||||
#[default]
|
||||
Project,
|
||||
Directory,
|
||||
Status,
|
||||
Model,
|
||||
}
|
||||
|
||||
impl From<akode_config::types::AgentsOverviewGrouping> for AgentsOverviewGrouping {
|
||||
fn from(grouping: akode_config::types::AgentsOverviewGrouping) -> Self {
|
||||
match grouping {
|
||||
akode_config::types::AgentsOverviewGrouping::Project => Self::Project,
|
||||
akode_config::types::AgentsOverviewGrouping::Status => Self::Status,
|
||||
akode_config::types::AgentsOverviewGrouping::Model => Self::Model,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AgentsOverviewGrouping {
|
||||
pub(super) fn persisted(self) -> Option<akode_config::types::AgentsOverviewGrouping> {
|
||||
match self {
|
||||
Self::Project => Some(akode_config::types::AgentsOverviewGrouping::Project),
|
||||
Self::Directory => None,
|
||||
Self::Status => Some(akode_config::types::AgentsOverviewGrouping::Status),
|
||||
Self::Model => Some(akode_config::types::AgentsOverviewGrouping::Model),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn model_name(thread: &Thread) -> &str {
|
||||
thread
|
||||
.model
|
||||
.as_deref()
|
||||
.filter(|model| !model.is_empty())
|
||||
.unwrap_or("Unknown")
|
||||
}
|
||||
|
||||
impl AgentsOverviewView {
|
||||
pub(super) fn is_pinned(&self, index: usize) -> bool {
|
||||
self.pinned_thread_ranks
|
||||
.as_ref()
|
||||
.is_some_and(|ranks| ranks.contains_key(&self.rows[index].thread_id))
|
||||
}
|
||||
|
||||
pub(in crate::app) fn visible_indices(&self) -> Vec<usize> {
|
||||
let state = self.state();
|
||||
let search = state.search.to_lowercase();
|
||||
let (_, status_group) = super::command_center::TASK_FILTERS[state.status_filter];
|
||||
let (mut pinned, mut visible): (Vec<_>, Vec<_>) = self
|
||||
.rows
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(index, row)| {
|
||||
(state.rename_target == Some(row.thread_id)
|
||||
|| (state.includes_row(row)
|
||||
&& (search.is_empty() || matches_query(&row.thread, &search))
|
||||
&& status_group.is_none_or(|group| group == row.group)))
|
||||
.then_some(index)
|
||||
})
|
||||
.partition(|index| self.is_pinned(*index));
|
||||
if let Some(ranks) = &self.pinned_thread_ranks {
|
||||
pinned.sort_by_key(|index| ranks.get(&self.rows[*index].thread_id).copied());
|
||||
}
|
||||
match state.grouping {
|
||||
AgentsOverviewGrouping::Project => visible.sort_by_key(|index| {
|
||||
(
|
||||
&self.project_groups[*index].key,
|
||||
std::cmp::Reverse(self.rows[*index].thread.updated_at),
|
||||
)
|
||||
}),
|
||||
AgentsOverviewGrouping::Directory => visible.sort_by_key(|index| {
|
||||
(
|
||||
&self.directory_group_keys[*index],
|
||||
std::cmp::Reverse(self.rows[*index].thread.updated_at),
|
||||
)
|
||||
}),
|
||||
AgentsOverviewGrouping::Status => {
|
||||
pinned.extend(visible);
|
||||
// Stable grouping preserves pin order, then the supplied newest-first order.
|
||||
pinned.sort_by_key(|index| self.rows[*index].group);
|
||||
return pinned;
|
||||
}
|
||||
AgentsOverviewGrouping::Model => visible.sort_by_key(|index| {
|
||||
(
|
||||
model_name(&self.rows[*index].thread),
|
||||
std::cmp::Reverse(self.rows[*index].thread.updated_at),
|
||||
)
|
||||
}),
|
||||
}
|
||||
pinned.extend(visible);
|
||||
pinned
|
||||
}
|
||||
|
||||
pub(super) fn same_group(
|
||||
&self,
|
||||
grouping: AgentsOverviewGrouping,
|
||||
left: usize,
|
||||
right: usize,
|
||||
) -> bool {
|
||||
match grouping {
|
||||
AgentsOverviewGrouping::Status => self.rows[left].group == self.rows[right].group,
|
||||
_ if self.is_pinned(left) || self.is_pinned(right) => {
|
||||
self.is_pinned(left) && self.is_pinned(right)
|
||||
}
|
||||
AgentsOverviewGrouping::Project => {
|
||||
self.project_groups[left].key == self.project_groups[right].key
|
||||
}
|
||||
AgentsOverviewGrouping::Directory => {
|
||||
self.directory_group_keys[left] == self.directory_group_keys[right]
|
||||
}
|
||||
AgentsOverviewGrouping::Model => {
|
||||
model_name(&self.rows[left].thread) == model_name(&self.rows[right].thread)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AgentsOverviewState {
|
||||
pub(in super::super) fn new(grouping: akode_config::types::AgentsOverviewGrouping) -> Self {
|
||||
let state = Self::default();
|
||||
state
|
||||
.view_state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.grouping = grouping.into();
|
||||
state
|
||||
}
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub(in super::super) async fn persist_agents_overview_grouping(
|
||||
&mut self,
|
||||
grouping: akode_config::types::AgentsOverviewGrouping,
|
||||
) {
|
||||
self.local_settings.tui.agents_overview_grouping = grouping;
|
||||
let edit = ConfigEdit::SetPath {
|
||||
segments: vec!["tui".to_string(), "agents_overview_grouping".to_string()],
|
||||
value: grouping.as_str().into(),
|
||||
};
|
||||
if let Err(err) =
|
||||
ConfigEditsBuilder::for_config_path(self.local_settings.user_config_path.as_path())
|
||||
.with_edits([edit])
|
||||
.apply()
|
||||
.await
|
||||
{
|
||||
self.add_agents_overview_error(format!(
|
||||
"Failed to save Command Center grouping: {err}"
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
19
akode-rs/tui/src/app/agents_overview_loading.rs
Normal file
19
akode-rs/tui/src/app/agents_overview_loading.rs
Normal file
@@ -0,0 +1,19 @@
|
||||
//! Transient feedback while command-center selection waits for a session to load.
|
||||
//! Draw directly because the app event handler cannot process scheduled frames while awaiting.
|
||||
|
||||
use crate::tui::Tui;
|
||||
use ratatui::style::Stylize;
|
||||
use ratatui::text::Line;
|
||||
use ratatui::widgets::Paragraph;
|
||||
|
||||
pub(super) fn draw(tui: &mut Tui) -> std::io::Result<()> {
|
||||
tui.draw(u16::MAX, |frame| {
|
||||
let lines = textwrap::wrap("Loading task…", usize::from(frame.area().width.max(1)))
|
||||
.into_iter()
|
||||
.map(|line| Line::from(line.into_owned().bold()))
|
||||
.collect::<Vec<_>>();
|
||||
frame.render_widget_ref(&Paragraph::new(lines), frame.area());
|
||||
})?;
|
||||
tui.frame_requester().schedule_frame();
|
||||
Ok(())
|
||||
}
|
||||
328
akode-rs/tui/src/app/agents_overview_new.rs
Normal file
328
akode-rs/tui/src/app/agents_overview_new.rs
Normal file
@@ -0,0 +1,328 @@
|
||||
//! Creates empty sessions from the command center without interrupting other agents.
|
||||
//! Worktrees start at the repository default branch and bind only the new session.
|
||||
|
||||
use super::*;
|
||||
use crate::app_server_session::is_server_shutting_down_error;
|
||||
use crate::startup_draft::StartupDraftInitialScreen;
|
||||
use crate::startup_draft::StartupDraftPump;
|
||||
use crate::startup_draft::StartupDraftSessionAction;
|
||||
|
||||
/// Owns a freshly created checkout until the UI accepts its completion event.
|
||||
/// Dropping a cancelled worker or undelivered event removes only a clean checkout.
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct PendingWorktree {
|
||||
pub(in crate::app) manager: akode_worktree::WorktreeManager,
|
||||
pub(in crate::app) checkout: Option<akode_worktree::ManagedWorktree>,
|
||||
}
|
||||
|
||||
impl Drop for PendingWorktree {
|
||||
fn drop(&mut self) {
|
||||
if let Some(checkout) = &self.checkout {
|
||||
let result = dunce::canonicalize(&checkout.root)
|
||||
.map_err(anyhow::Error::from)
|
||||
.and_then(|root| self.manager.remove(&checkout.source_cwd, &root));
|
||||
if let Err(error) = result {
|
||||
tracing::error!(path = %checkout.root.display(), %error, "Could not remove unclaimed worktree");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl App {
|
||||
fn agents_overview_retained_worktree_error(
|
||||
&mut self,
|
||||
checkout: &akode_worktree::ManagedWorktree,
|
||||
title: Option<&'static str>,
|
||||
reason: impl std::fmt::Display,
|
||||
) {
|
||||
self.show_agents_overview_error(title, format!("{reason} A checkout was retained at {}; remove it with `git worktree remove <checkout-path>` from the source repository if it is no longer needed.", checkout.root.display()));
|
||||
}
|
||||
|
||||
pub(in crate::app) async fn new_agents_overview_session(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
app_server: &mut AppServerSession,
|
||||
cwd: Option<AbsolutePathBuf>,
|
||||
) -> Result<AppRunControl> {
|
||||
if self.reconnect.offline || self.windows_sandbox_blocks_thread_switch() {
|
||||
return Ok(AppRunControl::Continue);
|
||||
}
|
||||
let previous_thread = self.current_displayed_thread_id();
|
||||
let mut draft = self
|
||||
.agents_overview
|
||||
.new_session_draft
|
||||
.take()
|
||||
.unwrap_or_else(|| {
|
||||
Box::new(StartupDraftPump::new(
|
||||
tui,
|
||||
StartupDraftInitialScreen::Composer,
|
||||
StartupDraftSessionAction::NewFromCommandCenter,
|
||||
))
|
||||
});
|
||||
let mut display_config = self.chat_widget.config_ref().clone();
|
||||
if let Some(cwd) = cwd.as_ref() {
|
||||
display_config.cwd = cwd.clone();
|
||||
}
|
||||
draft.apply_settings(
|
||||
&crate::local_settings::LocalSettings::from(&display_config),
|
||||
display_config.cwd.as_path(),
|
||||
);
|
||||
draft.show(tui)?;
|
||||
// Keep the large session-start future off the TUI's stack in dev builds.
|
||||
let result = Box::pin(self.start_agents_overview_session(
|
||||
tui,
|
||||
app_server,
|
||||
cwd,
|
||||
/*managed_worktree*/ None,
|
||||
Some(&mut draft),
|
||||
))
|
||||
.await;
|
||||
if self.current_displayed_thread_id() != previous_thread {
|
||||
draft.flush_pending_paste_newline(tui).await?;
|
||||
self.chat_widget
|
||||
.empty_state_animation
|
||||
.borrow_mut()
|
||||
.continue_from(&mut draft.blossom.borrow_mut());
|
||||
self.chat_widget.restore_startup_draft(draft.take_draft());
|
||||
} else {
|
||||
// Retain edits if setup fails so retrying `n` does not lose the draft.
|
||||
draft.flush_pending_events(tui).await?;
|
||||
self.agents_overview.new_session_draft = Some(draft);
|
||||
}
|
||||
tui.frame_requester().schedule_frame();
|
||||
result
|
||||
}
|
||||
|
||||
pub(in crate::app) async fn start_agents_overview_session(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
app_server: &mut AppServerSession,
|
||||
cwd: Option<AbsolutePathBuf>,
|
||||
managed_worktree: Option<(
|
||||
akode_worktree::WorktreeManager,
|
||||
akode_worktree::ManagedWorktree,
|
||||
)>,
|
||||
mut startup_draft: Option<&mut StartupDraftPump>,
|
||||
) -> Result<AppRunControl> {
|
||||
if self.reconnect.offline || self.windows_sandbox_blocks_thread_switch() {
|
||||
if let Some((_, checkout)) = &managed_worktree {
|
||||
self.agents_overview_retained_worktree_error(
|
||||
checkout,
|
||||
/*title*/ None,
|
||||
"Could not start the session.",
|
||||
);
|
||||
}
|
||||
return Ok(AppRunControl::Continue);
|
||||
}
|
||||
// Keep folder consent and config loading off the session-start stack frame.
|
||||
let Some((config, remote_cwd)) = Box::pin(self.agents_overview_session_config(
|
||||
tui,
|
||||
app_server,
|
||||
cwd,
|
||||
startup_draft.as_deref_mut(),
|
||||
))
|
||||
.await
|
||||
else {
|
||||
if let Some((_, checkout)) = &managed_worktree {
|
||||
self.agents_overview_retained_worktree_error(
|
||||
checkout,
|
||||
/*title*/ None,
|
||||
"Could not load the new session settings.",
|
||||
);
|
||||
}
|
||||
return Ok(AppRunControl::Continue);
|
||||
};
|
||||
let selected_profile = self.chat_widget.thread_id().and_then(|thread_id| {
|
||||
if let Some(selection) = self
|
||||
.agents_overview
|
||||
.requested_permission_profiles
|
||||
.get(&thread_id)
|
||||
{
|
||||
return Some(selection.clone());
|
||||
}
|
||||
let source = self.chat_widget.config_ref();
|
||||
let active = source.permissions.active_permission_profile()?;
|
||||
(self
|
||||
.agents_overview
|
||||
.selected_permission_profiles
|
||||
.get(&thread_id)
|
||||
== Some(&active.id))
|
||||
.then(|| PermissionProfileSelection {
|
||||
profile_id: active.id.clone(),
|
||||
approval_policy: Some(source.permissions.approval_policy.value().into()),
|
||||
approvals_reviewer: Some(source.approvals_reviewer),
|
||||
display_label: active.id,
|
||||
})
|
||||
});
|
||||
let local_settings = self.local_settings.reloaded(&config);
|
||||
if let Some(draft) = startup_draft.as_deref_mut() {
|
||||
draft.apply_settings(&local_settings, config.cwd.as_path());
|
||||
}
|
||||
let result = StartupDraftPump::run_with_optional_draft(
|
||||
startup_draft.as_deref_mut(),
|
||||
tui,
|
||||
Box::pin(app_server.start_thread_with_session_start_source(
|
||||
&local_settings,
|
||||
&config,
|
||||
/*session_start_source*/ None,
|
||||
remote_cwd.as_deref(),
|
||||
selected_profile.as_ref(),
|
||||
self.backend_preference_context.local_cwd.as_deref(),
|
||||
)),
|
||||
)
|
||||
.await;
|
||||
let started = match result {
|
||||
Ok(started) => started,
|
||||
Err(error) => {
|
||||
let (title, message) = if matches!(
|
||||
error.downcast_ref::<TypedRequestError>(),
|
||||
Some(TypedRequestError::Server { source, .. })
|
||||
if is_server_shutting_down_error(source)
|
||||
) {
|
||||
let mut message = String::from(
|
||||
"New sessions are paused while active turns finish or are canceled. The default shutdown wait is up to one minute.",
|
||||
);
|
||||
if !matches!(self.app_server_target, AppServerTarget::Embedded) {
|
||||
message.push_str(
|
||||
" If the server restarts, aKode will reconnect automatically.",
|
||||
);
|
||||
}
|
||||
(Some("aKode's background server is shutting down"), message)
|
||||
} else {
|
||||
(None, format!("Failed to start session: {error}"))
|
||||
};
|
||||
if let Some((_, checkout)) = &managed_worktree {
|
||||
self.agents_overview_retained_worktree_error(checkout, title, message);
|
||||
} else {
|
||||
self.show_agents_overview_error(title, message);
|
||||
}
|
||||
return Ok(AppRunControl::Continue);
|
||||
}
|
||||
};
|
||||
let thread_id = started.session.thread_id;
|
||||
if let Some(selected) = selected_profile {
|
||||
self.agents_overview
|
||||
.selected_permission_profiles
|
||||
.insert(thread_id, selected.profile_id);
|
||||
}
|
||||
if let Some((manager, checkout)) = &managed_worktree {
|
||||
let result =
|
||||
if crate::session_resume::cwds_differ(started.session.cwd.as_path(), &checkout.cwd)
|
||||
{
|
||||
Err(anyhow::anyhow!(
|
||||
"The server did not apply the worktree directory."
|
||||
))
|
||||
} else {
|
||||
manager.bind_thread(&checkout.root, &thread_id.to_string())
|
||||
};
|
||||
if let Err(error) = result {
|
||||
let _ = app_server.thread_unsubscribe(thread_id).await;
|
||||
self.agents_overview_retained_worktree_error(checkout, /*title*/ None, error);
|
||||
return Ok(AppRunControl::Continue);
|
||||
}
|
||||
}
|
||||
self.agents_overview
|
||||
.blank_sessions
|
||||
.insert(thread_id, started.clone());
|
||||
// Use the dashboard's existing attachment path, which preserves running agents
|
||||
// and unsent input in the previous session. Do not send an initial turn.
|
||||
let control = Box::pin(self.attach_agents_overview_thread(
|
||||
tui,
|
||||
app_server,
|
||||
thread_id,
|
||||
Some((config, started)),
|
||||
startup_draft,
|
||||
))
|
||||
.await?;
|
||||
if self.current_displayed_thread_id() != Some(thread_id) {
|
||||
self.agents_overview.blank_sessions.remove(&thread_id);
|
||||
let _ = app_server.thread_unsubscribe(thread_id).await;
|
||||
if let Some((_, checkout)) = &managed_worktree {
|
||||
self.agents_overview_retained_worktree_error(
|
||||
checkout,
|
||||
/*title*/ None,
|
||||
"Could not open the new session.",
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(control)
|
||||
}
|
||||
|
||||
pub(in crate::app) async fn new_agents_overview_worktree(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
app_server: &mut AppServerSession,
|
||||
cwd: Option<AbsolutePathBuf>,
|
||||
) {
|
||||
if self.reconnect.offline
|
||||
|| self.pending_managed_worktree_creation
|
||||
|| self.windows_sandbox_blocks_thread_switch()
|
||||
{
|
||||
return;
|
||||
}
|
||||
if crate::uses_remote_workspace_or_environment(
|
||||
&self.app_server_target,
|
||||
self.environment_manager.as_ref(),
|
||||
) {
|
||||
self.add_agents_overview_error(
|
||||
"Managed worktrees require local worktree support.".to_string(),
|
||||
);
|
||||
return;
|
||||
}
|
||||
let Some((config, _)) = self
|
||||
.agents_overview_session_config(tui, app_server, cwd, /*startup_draft*/ None)
|
||||
.await
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let setup = async {
|
||||
anyhow::ensure!(
|
||||
!config.active_project.is_untrusted(),
|
||||
"The source project is not trusted."
|
||||
);
|
||||
let host = crate::legacy_core::config::load_config_toml_with_layer_stack(
|
||||
&self.config.codex_home,
|
||||
/*cwd*/ None,
|
||||
Vec::new(),
|
||||
akode_config::ConfigLoadOptions::default(),
|
||||
)
|
||||
.await?;
|
||||
let settings = akode_worktree::WorktreeSettings::for_cli(
|
||||
&self.config.codex_home,
|
||||
host.config_toml.desktop.as_ref(),
|
||||
)?;
|
||||
anyhow::Ok(akode_worktree::WorktreeManager::new(settings))
|
||||
}
|
||||
.await;
|
||||
let manager = match setup {
|
||||
Ok(value) => value,
|
||||
Err(error) => return self.add_agents_overview_error(error.to_string()),
|
||||
};
|
||||
self.pending_managed_worktree_creation = true;
|
||||
self.agents_overview
|
||||
.view_state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.creating_worktree = true;
|
||||
let sender = self.app_event_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
akode_worktree::default_worktree_base(config.cwd.as_path())
|
||||
.and_then(|base| {
|
||||
manager.create(&akode_worktree::CreateWorktree {
|
||||
source_cwd: config.cwd.to_path_buf(),
|
||||
base: Some(base),
|
||||
})
|
||||
})
|
||||
.map(|checkout| PendingWorktree {
|
||||
manager,
|
||||
checkout: Some(checkout),
|
||||
})
|
||||
.map_err(|error| error.to_string())
|
||||
})
|
||||
.await
|
||||
.unwrap_or_else(|error| Err(format!("Worktree creation task failed: {error}")));
|
||||
sender.send(AppEvent::AgentsOverviewWorktreeCreated(result));
|
||||
});
|
||||
}
|
||||
}
|
||||
32
akode-rs/tui/src/app/agents_overview_selection.rs
Normal file
32
akode-rs/tui/src/app/agents_overview_selection.rs
Normal file
@@ -0,0 +1,32 @@
|
||||
//! Preserves Command Center selection across local and server-driven removals.
|
||||
//! Choose against the displayed order before mutation; pending successors survive
|
||||
//! batched removals and duplicate completion notifications until the next repaint.
|
||||
|
||||
use super::AGENTS_OVERVIEW_VIEW_ID;
|
||||
use super::App;
|
||||
use akode_protocol::ThreadId;
|
||||
use std::collections::HashSet;
|
||||
|
||||
impl App {
|
||||
pub(in crate::app) fn prepare_agents_overview_removal(&mut self, removed: &HashSet<ThreadId>) {
|
||||
let selected = self.agents_overview.selection_after_removal.or_else(|| {
|
||||
let index = self
|
||||
.chat_widget
|
||||
.selected_index_for_present_view(AGENTS_OVERVIEW_VIEW_ID)?;
|
||||
self.agents_overview.visible_thread_ids.get(index).copied()
|
||||
});
|
||||
let Some(selected) = selected.filter(|id| removed.contains(id)) else {
|
||||
return;
|
||||
};
|
||||
let threads = self
|
||||
.agents_overview
|
||||
.threads
|
||||
.values()
|
||||
.flatten()
|
||||
.cloned()
|
||||
.collect();
|
||||
self.agents_overview.selection_after_removal = self
|
||||
.agents_overview_view(threads, Some(selected))
|
||||
.selection_after_removal(removed);
|
||||
}
|
||||
}
|
||||
3191
akode-rs/tui/src/app/agents_overview_tests.rs
Normal file
3191
akode-rs/tui/src/app/agents_overview_tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
511
akode-rs/tui/src/app/agents_overview_threads.rs
Normal file
511
akode-rs/tui/src/app/agents_overview_threads.rs
Normal file
@@ -0,0 +1,511 @@
|
||||
//! Retains overview membership for this TUI, independently of server subscriptions.
|
||||
//! A bounded recent seed runs at startup, after reconnect, and after event lag.
|
||||
//! Discovery merges into retained membership without evicting rows.
|
||||
|
||||
use super::App;
|
||||
use super::agents_overview::AGENTS_OVERVIEW_VIEW_ID;
|
||||
use super::agents_overview_details::preview_agent_message;
|
||||
use super::agents_overview_discovery::list_pinned_threads;
|
||||
use super::app_server_event_targets::ServerNotificationThreadTarget;
|
||||
use super::app_server_event_targets::server_notification_thread_target;
|
||||
use crate::app_event::AgentsOverviewThreadRefresh;
|
||||
use crate::app_event::AppEvent;
|
||||
use crate::app_server_session::AppServerSession;
|
||||
use crate::chatwidget::ChatWidget;
|
||||
use akode_app_server_protocol::ClientRequest;
|
||||
use akode_app_server_protocol::RequestId;
|
||||
use akode_app_server_protocol::ServerNotification;
|
||||
use akode_app_server_protocol::SessionSource;
|
||||
use akode_app_server_protocol::Thread;
|
||||
use akode_app_server_protocol::ThreadItemPayload;
|
||||
use akode_app_server_protocol::ThreadLoadedListParams;
|
||||
use akode_app_server_protocol::ThreadLoadedListResponse;
|
||||
use akode_app_server_protocol::ThreadReadParams;
|
||||
use akode_app_server_protocol::ThreadReadResponse;
|
||||
use akode_app_server_protocol::ThreadStatus;
|
||||
use akode_app_server_protocol::ThreadTurnsListParams;
|
||||
use akode_app_server_protocol::ThreadTurnsListResponse;
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_protocol::protocol::SubAgentSource;
|
||||
use futures::StreamExt;
|
||||
use std::collections::HashMap;
|
||||
use uuid::Uuid;
|
||||
|
||||
const RECENT_DETAIL_LIMIT: usize = 10;
|
||||
|
||||
// Listing supplies membership and row metadata without replaying every historical rollout.
|
||||
// Keep transcript previews fresh for recent and loaded tasks, plus notification-targeted reads.
|
||||
fn detail_thread_ids<'a>(threads: impl Iterator<Item = &'a Thread>) -> Vec<ThreadId> {
|
||||
let mut threads: Vec<_> = threads.collect();
|
||||
threads.sort_by(|left, right| {
|
||||
right
|
||||
.recency_at
|
||||
.unwrap_or(right.updated_at)
|
||||
.cmp(&left.recency_at.unwrap_or(left.updated_at))
|
||||
.then_with(|| right.id.cmp(&left.id))
|
||||
});
|
||||
threads
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.filter(|(index, thread)| {
|
||||
*index < RECENT_DETAIL_LIMIT || thread.status != ThreadStatus::NotLoaded
|
||||
})
|
||||
.filter_map(|(_, thread)| ThreadId::from_string(&thread.id).ok())
|
||||
.collect()
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub(super) fn remove_agents_overview_thread(&mut self, thread_id: ThreadId) {
|
||||
self.prepare_agents_overview_removal(&std::collections::HashSet::from([thread_id]));
|
||||
self.agents_overview.search_matches.remove(&thread_id);
|
||||
self.agents_overview.removed_threads.insert(thread_id);
|
||||
self.agents_overview.unread.remove(&thread_id);
|
||||
if let Some(Some(thread)) = self.agents_overview.threads.remove(&thread_id)
|
||||
&& !thread.ephemeral
|
||||
&& thread.parent_thread_id.is_none()
|
||||
&& !matches!(
|
||||
thread.source,
|
||||
SessionSource::SubAgent(SubAgentSource::ThreadSpawn { .. })
|
||||
)
|
||||
&& !self.agents_overview.hidden_threads.contains(&thread_id)
|
||||
{
|
||||
self.agents_overview.refill_count += 1;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn show_more_agents_overview(&mut self, app_server: &AppServerSession) {
|
||||
if !self.agents_overview.discovery.has_more() {
|
||||
return;
|
||||
}
|
||||
self.agents_overview.show_more_requested |= self.agents_overview.refill_count == 0;
|
||||
self.start_agents_overview_refresh(app_server);
|
||||
}
|
||||
|
||||
pub(super) fn track_agents_overview_notification(&mut self, notification: &ServerNotification) {
|
||||
let ServerNotificationThreadTarget::Thread(thread_id) =
|
||||
server_notification_thread_target(notification)
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if matches!(
|
||||
notification,
|
||||
ServerNotification::TurnStarted(_)
|
||||
| ServerNotification::ThreadClosed(_)
|
||||
| ServerNotification::ThreadArchived(_)
|
||||
| ServerNotification::ThreadDeleted(_)
|
||||
) {
|
||||
self.agents_overview.blank_sessions.remove(&thread_id);
|
||||
}
|
||||
self.track_agents_overview_activity(thread_id, notification);
|
||||
let thread = self
|
||||
.agents_overview
|
||||
.threads
|
||||
.get_mut(&thread_id)
|
||||
.and_then(Option::as_mut)
|
||||
.or_else(|| self.agents_overview.search_matches.get_mut(&thread_id));
|
||||
match notification {
|
||||
ServerNotification::ThreadReadStateChanged(change) => {
|
||||
if change.read_state.first_unread.is_some() {
|
||||
self.agents_overview.unread.insert(thread_id);
|
||||
} else {
|
||||
self.agents_overview.unread.remove(&thread_id);
|
||||
}
|
||||
self.repaint_agents_overview();
|
||||
}
|
||||
ServerNotification::ThreadTokenUsageUpdated(usage) => {
|
||||
if self.agents_overview.threads.contains_key(&thread_id) {
|
||||
self.agents_overview
|
||||
.usage
|
||||
.entry(thread_id)
|
||||
.or_default()
|
||||
.tokens = Some(usage.token_usage.total.clone());
|
||||
self.repaint_agents_overview();
|
||||
}
|
||||
}
|
||||
ServerNotification::ThreadStarted(started) => {
|
||||
if started.thread.ephemeral {
|
||||
return;
|
||||
}
|
||||
self.agents_overview.removed_threads.remove(&thread_id);
|
||||
let mut thread = started.thread.clone();
|
||||
thread.turns.clear();
|
||||
self.agents_overview.search_matches.remove(&thread_id);
|
||||
self.agents_overview.threads.insert(thread_id, Some(thread));
|
||||
}
|
||||
ServerNotification::ThreadArchived(_) | ServerNotification::ThreadDeleted(_) => {
|
||||
self.agents_overview
|
||||
.requested_permission_profiles
|
||||
.remove(&thread_id);
|
||||
self.agents_overview
|
||||
.selected_permission_profiles
|
||||
.remove(&thread_id);
|
||||
self.agents_overview.activity.remove(&thread_id);
|
||||
self.agents_overview.last_messages.remove(&thread_id);
|
||||
self.agents_overview.usage.remove(&thread_id);
|
||||
self.remove_agents_overview_thread(thread_id);
|
||||
self.agents_overview.refresh_thread_ids.remove(&thread_id);
|
||||
}
|
||||
ServerNotification::ThreadUnarchived(_) => {
|
||||
self.agents_overview.removed_threads.remove(&thread_id);
|
||||
}
|
||||
ServerNotification::ThreadClosed(_) => {
|
||||
self.agents_overview
|
||||
.requested_permission_profiles
|
||||
.remove(&thread_id);
|
||||
self.agents_overview.activity.remove(&thread_id);
|
||||
if let Some(usage) = self.agents_overview.usage.get_mut(&thread_id) {
|
||||
usage.tokens = None;
|
||||
}
|
||||
if let Some(thread) = thread {
|
||||
thread.status = ThreadStatus::NotLoaded;
|
||||
}
|
||||
}
|
||||
ServerNotification::ThreadReverted(_) => {
|
||||
self.agents_overview.activity.remove(&thread_id);
|
||||
self.agents_overview.last_messages.remove(&thread_id);
|
||||
if let Some(usage) = self.agents_overview.usage.get_mut(&thread_id) {
|
||||
usage.tokens = None;
|
||||
}
|
||||
self.repaint_agents_overview();
|
||||
}
|
||||
ServerNotification::ThreadStatusChanged(status) => {
|
||||
if let Some(thread) = thread {
|
||||
thread.status = status.status.clone();
|
||||
}
|
||||
}
|
||||
ServerNotification::ThreadNameUpdated(name) => {
|
||||
if let Some(thread) = thread {
|
||||
thread.name.clone_from(&name.thread_name);
|
||||
}
|
||||
}
|
||||
ServerNotification::ThreadSettingsUpdated(settings) => {
|
||||
if !self.pending_server_profiles.contains_key(&thread_id)
|
||||
&& !self
|
||||
.agents_overview
|
||||
.requested_permission_profiles
|
||||
.contains_key(&thread_id)
|
||||
&& self
|
||||
.agents_overview
|
||||
.selected_permission_profiles
|
||||
.get(&thread_id)
|
||||
!= settings
|
||||
.thread_settings
|
||||
.active_permission_profile
|
||||
.as_ref()
|
||||
.map(|profile| &profile.id)
|
||||
{
|
||||
self.agents_overview
|
||||
.selected_permission_profiles
|
||||
.remove(&thread_id);
|
||||
}
|
||||
if let Some(thread) = thread {
|
||||
thread.cwd.clone_from(&settings.thread_settings.cwd);
|
||||
thread.model = Some(settings.thread_settings.model.clone());
|
||||
thread
|
||||
.model_provider
|
||||
.clone_from(&settings.thread_settings.model_provider);
|
||||
}
|
||||
}
|
||||
_ => return,
|
||||
}
|
||||
if !matches!(
|
||||
notification,
|
||||
ServerNotification::ThreadReverted(_)
|
||||
| ServerNotification::ThreadTokenUsageUpdated(_)
|
||||
| ServerNotification::ThreadReadStateChanged(_)
|
||||
) && self.agents_overview.threads.contains_key(&thread_id)
|
||||
{
|
||||
self.agents_overview.refresh_thread_ids.insert(thread_id);
|
||||
}
|
||||
if self.agents_overview.request_id.is_some() {
|
||||
// Replay the latest notification of each kind after the read, in arrival order.
|
||||
// This also protects sessions whose metadata has not arrived in the initial seed.
|
||||
let pending = self
|
||||
.agents_overview
|
||||
.refresh_notifications
|
||||
.entry(thread_id)
|
||||
.or_default();
|
||||
pending.retain(|previous| {
|
||||
std::mem::discriminant(previous) != std::mem::discriminant(notification)
|
||||
});
|
||||
pending.push(notification.clone());
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn refresh_agents_overview_threads(&mut self, app_server: &AppServerSession) {
|
||||
self.agents_overview.pin_refresh_requested = true;
|
||||
self.agents_overview.refresh_thread_ids.extend(
|
||||
self.agents_overview
|
||||
.threads
|
||||
.iter()
|
||||
.filter_map(|(id, thread)| thread.is_none().then_some(*id)),
|
||||
);
|
||||
self.agents_overview
|
||||
.refresh_thread_ids
|
||||
.extend(detail_thread_ids(
|
||||
self.agents_overview.threads.values().flatten(),
|
||||
));
|
||||
self.start_agents_overview_refresh(app_server);
|
||||
}
|
||||
|
||||
pub(super) fn refresh_changed_agents_overview_threads(
|
||||
&mut self,
|
||||
app_server: &AppServerSession,
|
||||
) {
|
||||
if self
|
||||
.chat_widget
|
||||
.selected_index_for_present_view(AGENTS_OVERVIEW_VIEW_ID)
|
||||
.is_none()
|
||||
|| (!self.agents_overview.initialized && self.agents_overview.request_id.is_none())
|
||||
{
|
||||
return;
|
||||
}
|
||||
self.start_agents_overview_refresh(app_server);
|
||||
}
|
||||
|
||||
fn start_agents_overview_refresh(&mut self, app_server: &AppServerSession) {
|
||||
let visible = self
|
||||
.chat_widget
|
||||
.selected_index_for_present_view(AGENTS_OVERVIEW_VIEW_ID)
|
||||
.is_some();
|
||||
if !visible && self.agents_overview.initialized {
|
||||
return;
|
||||
}
|
||||
if self.agents_overview.request_id.is_some() {
|
||||
self.agents_overview.refresh_pending = true;
|
||||
return;
|
||||
}
|
||||
if self.agents_overview.initialized
|
||||
&& self.agents_overview.refresh_thread_ids.is_empty()
|
||||
&& !self.agents_overview.show_more_requested
|
||||
&& !(self.agents_overview.refill_count > 0 && self.agents_overview.discovery.has_more())
|
||||
&& !self.agents_overview.pin_refresh_requested
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let mut unread_rows = Vec::new();
|
||||
if std::mem::take(&mut self.agents_overview.pin_refresh_requested) {
|
||||
unread_rows.extend(
|
||||
self.agents_overview
|
||||
.visible_thread_ids
|
||||
.iter()
|
||||
.copied()
|
||||
.filter(|id| self.agents_overview.unread.contains(id)),
|
||||
);
|
||||
}
|
||||
let request_id = Uuid::new_v4();
|
||||
self.agents_overview.request_id = Some(request_id);
|
||||
let initialized = self.agents_overview.initialized;
|
||||
let refill = self.agents_overview.refill_count;
|
||||
let show_more =
|
||||
refill == 0 && std::mem::take(&mut self.agents_overview.show_more_requested);
|
||||
self.agents_overview.refresh_show_more = show_more;
|
||||
let discover =
|
||||
!initialized || show_more || (refill > 0 && self.agents_overview.discovery.has_more());
|
||||
let limit = if initialized && refill > 0 {
|
||||
refill.min(10)
|
||||
} else {
|
||||
10
|
||||
};
|
||||
let mut discovery = discover.then(|| {
|
||||
if initialized {
|
||||
self.agents_overview.discovery.clone()
|
||||
} else {
|
||||
self.agents_overview.removed_threads.clear();
|
||||
Default::default()
|
||||
}
|
||||
});
|
||||
let mut thread_ids = std::mem::take(&mut self.agents_overview.refresh_thread_ids);
|
||||
self.agents_overview.active_refresh_thread_ids = thread_ids.clone();
|
||||
let request_handle = app_server.request_handle();
|
||||
let app_event_tx = self.app_event_tx.clone();
|
||||
self.agents_overview
|
||||
.view_state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.loading = discover;
|
||||
let refresh_task = tokio::spawn(async move {
|
||||
let result = async {
|
||||
let mut threads = HashMap::new();
|
||||
let mut last_messages = HashMap::new();
|
||||
let mut recent_seed_complete = true;
|
||||
let pinned_thread_ids = match list_pinned_threads(&request_handle).await {
|
||||
Ok(Some(pinned_threads)) => {
|
||||
let mut ids = Vec::with_capacity(pinned_threads.len());
|
||||
for (thread, is_unread) in pinned_threads {
|
||||
if let Ok(thread_id) = ThreadId::from_string(&thread.id) {
|
||||
ids.push(thread_id);
|
||||
threads.insert(thread_id, Some((thread, is_unread, None)));
|
||||
}
|
||||
}
|
||||
Some(Some(ids))
|
||||
}
|
||||
Ok(None) => Some(None),
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "failed to list pinned agent threads");
|
||||
None
|
||||
}
|
||||
};
|
||||
if let Some(discovery) = &mut discovery {
|
||||
let loaded = async {
|
||||
if initialized {
|
||||
return Ok(ThreadLoadedListResponse {
|
||||
data: Vec::new(),
|
||||
next_cursor: None,
|
||||
});
|
||||
}
|
||||
request_handle
|
||||
.request_typed::<ThreadLoadedListResponse>(
|
||||
ClientRequest::ThreadLoadedList {
|
||||
request_id: RequestId::String(Uuid::new_v4().to_string()),
|
||||
params: ThreadLoadedListParams {
|
||||
cursor: None,
|
||||
limit: None,
|
||||
},
|
||||
},
|
||||
)
|
||||
.await
|
||||
};
|
||||
let (loaded, (recent, complete)) =
|
||||
tokio::join!(loaded, discovery.next_batch(&request_handle, limit));
|
||||
let loaded = loaded.map_err(|error| error.to_string())?;
|
||||
recent_seed_complete = complete;
|
||||
thread_ids.extend(
|
||||
loaded
|
||||
.data
|
||||
.into_iter()
|
||||
.filter_map(|id| ThreadId::from_string(&id).ok()),
|
||||
);
|
||||
thread_ids.extend(detail_thread_ids(recent.iter().map(|(thread, _)| thread)));
|
||||
for (thread, is_unread) in recent {
|
||||
if let Ok(thread_id) = ThreadId::from_string(&thread.id) {
|
||||
threads.insert(thread_id, Some((thread, is_unread, None)));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Recheck dots on older rows without fetching their transcript previews.
|
||||
unread_rows.retain(|id| !threads.contains_key(id) && !thread_ids.contains(id));
|
||||
let cleared_unread = futures::stream::iter(unread_rows)
|
||||
.map(async |id| {
|
||||
let response: ThreadReadResponse = request_handle
|
||||
.request_typed(ClientRequest::ThreadRead {
|
||||
request_id: RequestId::String(Uuid::new_v4().to_string()),
|
||||
params: ThreadReadParams {
|
||||
thread_id: id.to_string(),
|
||||
include_turns: false,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.ok()?;
|
||||
response.read_state?.first_unread.is_none().then_some(id)
|
||||
})
|
||||
.buffer_unordered(16)
|
||||
.filter_map(std::future::ready)
|
||||
.collect()
|
||||
.await;
|
||||
let mut reads = tokio::task::JoinSet::new();
|
||||
for thread_id in thread_ids {
|
||||
threads.entry(thread_id).or_default();
|
||||
let request_handle = request_handle.clone();
|
||||
reads.spawn(async move {
|
||||
match request_handle
|
||||
.request_typed::<ThreadReadResponse>(ClientRequest::ThreadRead {
|
||||
request_id: RequestId::String(Uuid::new_v4().to_string()),
|
||||
params: ThreadReadParams {
|
||||
thread_id: thread_id.to_string(),
|
||||
include_turns: false,
|
||||
},
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(response) => {
|
||||
let mut latest_prompt = None;
|
||||
let mut last_message = None;
|
||||
if let Ok(turns) = request_handle
|
||||
.request_typed::<ThreadTurnsListResponse>(
|
||||
ClientRequest::ThreadTurnsList {
|
||||
request_id: RequestId::String(
|
||||
Uuid::new_v4().to_string(),
|
||||
),
|
||||
params: ThreadTurnsListParams {
|
||||
thread_id: thread_id.to_string(),
|
||||
cursor: None,
|
||||
limit: Some(1),
|
||||
sort_direction: None,
|
||||
items_view: None,
|
||||
},
|
||||
},
|
||||
)
|
||||
.await
|
||||
&& let Some(turn) = turns.data.first()
|
||||
{
|
||||
if let Some(ThreadItemPayload::UserMessage {
|
||||
content, ..
|
||||
}) = turn.item_payloads().next()
|
||||
{
|
||||
latest_prompt =
|
||||
Some(super::agents_overview_details::preview_markdown(
|
||||
&ChatWidget::user_message_display_from_inputs(
|
||||
content,
|
||||
)
|
||||
.message,
|
||||
));
|
||||
}
|
||||
last_message =
|
||||
turn.item_payloads().rev().find_map(|item| match item {
|
||||
ThreadItemPayload::AgentMessage { text, .. } => {
|
||||
Some(preview_agent_message(text))
|
||||
}
|
||||
_ => None,
|
||||
});
|
||||
}
|
||||
let unread = response
|
||||
.read_state
|
||||
.is_some_and(|state| state.first_unread.is_some());
|
||||
Some((
|
||||
thread_id,
|
||||
(response.thread, unread, latest_prompt),
|
||||
last_message,
|
||||
))
|
||||
}
|
||||
Err(error) => {
|
||||
tracing::warn!(%thread_id, %error, "failed to read agent thread");
|
||||
None
|
||||
}
|
||||
}
|
||||
});
|
||||
if reads.len() >= 16
|
||||
&& let Some(Ok(Some((thread_id, thread, last_message)))) =
|
||||
reads.join_next().await
|
||||
{
|
||||
threads.insert(thread_id, Some(thread));
|
||||
if let Some(message) = last_message {
|
||||
last_messages.insert(thread_id, message);
|
||||
}
|
||||
}
|
||||
}
|
||||
while let Some(result) = reads.join_next().await {
|
||||
if let Ok(Some((thread_id, thread, last_message))) = result {
|
||||
threads.insert(thread_id, Some(thread));
|
||||
if let Some(message) = last_message {
|
||||
last_messages.insert(thread_id, message);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(AgentsOverviewThreadRefresh {
|
||||
cleared_unread,
|
||||
threads,
|
||||
last_messages,
|
||||
recent_seed_complete,
|
||||
discovery,
|
||||
pinned_thread_ids,
|
||||
})
|
||||
}
|
||||
.await;
|
||||
app_event_tx.send(AppEvent::AgentsOverviewThreadsLoaded { request_id, result });
|
||||
});
|
||||
self.agents_overview.refresh_task = Some(refresh_task.abort_handle());
|
||||
}
|
||||
}
|
||||
22
akode-rs/tui/src/app/agents_overview_usage.rs
Normal file
22
akode-rs/tui/src/app/agents_overview_usage.rs
Normal file
@@ -0,0 +1,22 @@
|
||||
//! Local token usage shown for the selected task in the agents dashboard.
|
||||
|
||||
use crate::status::format_tokens_compact;
|
||||
use akode_app_server_protocol::TokenUsageBreakdown;
|
||||
use ratatui::style::Stylize;
|
||||
use ratatui::text::Line;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct AgentsOverviewUsage {
|
||||
pub(super) tokens: Option<TokenUsageBreakdown>,
|
||||
}
|
||||
|
||||
pub(super) fn usage_lines(usage: &AgentsOverviewUsage) -> Vec<Line<'static>> {
|
||||
let Some(tokens) = usage.tokens.as_ref() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let tokens = [
|
||||
format!("{} in", format_tokens_compact(tokens.input_tokens)),
|
||||
format!("{} out", format_tokens_compact(tokens.output_tokens)),
|
||||
];
|
||||
vec![vec!["Tokens: ".dim(), tokens.join(" · ").into()].into()]
|
||||
}
|
||||
896
akode-rs/tui/src/app/agents_overview_view.rs
Normal file
896
akode-rs/tui/src/app/agents_overview_view.rs
Normal file
@@ -0,0 +1,896 @@
|
||||
//! Dashboard for inspecting and managing the TUI's retained daemon tasks.
|
||||
//! Search, rename, status filters and selection survive metadata refreshes.
|
||||
//! The caller supplies rows in status, descending update time, and thread ID order.
|
||||
|
||||
#[path = "agent_center/mod.rs"]
|
||||
pub(super) mod command_center;
|
||||
|
||||
#[path = "agents_overview_grouping.rs"]
|
||||
mod grouping;
|
||||
|
||||
pub(super) use grouping::AgentsOverviewGrouping;
|
||||
use grouping::model_name;
|
||||
|
||||
use super::agents_overview::AGENTS_OVERVIEW_VIEW_ID;
|
||||
use super::agents_overview_details::AgentsOverviewDetails;
|
||||
use super::agents_overview_discovery::HistorySearch;
|
||||
use super::agents_overview_discovery::supports_shared_pinning;
|
||||
use crate::app_event::AgentsOverviewAction;
|
||||
use crate::app_event::AppEvent;
|
||||
use crate::app_event_sender::AppEventSender;
|
||||
use crate::bottom_pane::BottomPaneView;
|
||||
use crate::bottom_pane::CancellationEvent;
|
||||
use crate::bottom_pane::TextArea;
|
||||
use crate::bottom_pane::ViewCompletion;
|
||||
use crate::key_hint::KeyBindingListExt;
|
||||
use crate::key_hint::ShortcutHint;
|
||||
use crate::key_hint::is_plain_text_key_event;
|
||||
use crate::keymap::AgentsKeymap;
|
||||
use crate::keymap::KeymapContext;
|
||||
use crate::keymap::KeymapContextSet;
|
||||
use crate::keymap::ListAction;
|
||||
use crate::keymap::ListKeymap;
|
||||
use crate::keymap::RuntimeKeymap;
|
||||
use crate::render::renderable::Renderable;
|
||||
use crate::terminal_hyperlinks::HyperlinkLine;
|
||||
use crate::terminal_hyperlinks::mark_buffer_hyperlinks;
|
||||
use crate::terminal_hyperlinks::plain_hyperlink_lines;
|
||||
use crate::terminal_hyperlinks::remap_wrapped_line;
|
||||
use crate::terminal_hyperlinks::visible_lines;
|
||||
use akode_app_server_protocol::SessionSource;
|
||||
use akode_app_server_protocol::Thread;
|
||||
use akode_app_server_protocol::ThreadActiveFlag;
|
||||
use akode_app_server_protocol::ThreadStatus;
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_protocol::openai_models::ReasoningEffort;
|
||||
use crossterm::event::KeyCode;
|
||||
use crossterm::event::KeyEvent;
|
||||
use crossterm::event::KeyModifiers;
|
||||
use ratatui::buffer::Buffer;
|
||||
use ratatui::layout::Constraint;
|
||||
use ratatui::layout::Layout;
|
||||
use ratatui::layout::Margin;
|
||||
use ratatui::layout::Rect;
|
||||
use ratatui::style::Style;
|
||||
use ratatui::style::Stylize;
|
||||
use ratatui::text::Line;
|
||||
use ratatui::text::Span;
|
||||
use ratatui::widgets::Clear;
|
||||
use ratatui::widgets::Paragraph;
|
||||
use ratatui::widgets::Widget;
|
||||
use std::collections::HashMap;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::MutexGuard;
|
||||
use std::sync::PoisonError;
|
||||
use unicode_width::UnicodeWidthStr;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
|
||||
pub(super) enum AgentsOverviewGroup {
|
||||
NeedsYou,
|
||||
Working,
|
||||
Ready,
|
||||
Finished,
|
||||
}
|
||||
|
||||
impl AgentsOverviewGroup {
|
||||
pub(super) fn for_thread(thread: &Thread) -> Self {
|
||||
match &thread.status {
|
||||
ThreadStatus::Active { active_flags }
|
||||
if active_flags.contains(&ThreadActiveFlag::WaitingOnApproval)
|
||||
|| active_flags.contains(&ThreadActiveFlag::WaitingOnUserInput) =>
|
||||
{
|
||||
Self::NeedsYou
|
||||
}
|
||||
ThreadStatus::Active { .. } => Self::Working,
|
||||
ThreadStatus::Idle => Self::Ready,
|
||||
// A subagent failure ends its work without asking the user to act.
|
||||
ThreadStatus::SystemError if !is_subagent(thread) => Self::NeedsYou,
|
||||
ThreadStatus::SystemError | ThreadStatus::NotLoaded => Self::Finished,
|
||||
}
|
||||
}
|
||||
|
||||
fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::NeedsYou => "Needs input",
|
||||
Self::Working => "Working",
|
||||
Self::Ready => "Ready",
|
||||
Self::Finished => "Inactive",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_subagent(thread: &Thread) -> bool {
|
||||
thread.parent_thread_id.is_some() || matches!(thread.source, SessionSource::SubAgent(_))
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(super) struct AgentsOverviewRow {
|
||||
pub(super) search_id: Option<uuid::Uuid>,
|
||||
pub(super) details: AgentsOverviewDetails,
|
||||
pub(super) thread: Thread,
|
||||
pub(super) thread_id: ThreadId,
|
||||
pub(super) group: AgentsOverviewGroup,
|
||||
pub(super) is_current: bool,
|
||||
pub(super) unread: bool,
|
||||
pub(super) has_voice: bool,
|
||||
}
|
||||
|
||||
fn display_title(thread: &Thread) -> &str {
|
||||
let title = thread.name.as_deref().unwrap_or(&thread.preview);
|
||||
title.trim().lines().next().unwrap_or("Untitled task")
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Eq, PartialEq)]
|
||||
struct AgentsOverviewProjectGroup {
|
||||
key: (PathBuf, PathBuf),
|
||||
heading: PathBuf,
|
||||
}
|
||||
|
||||
impl AgentsOverviewProjectGroup {
|
||||
fn for_thread(thread: &Thread, worktrees_enabled: bool) -> Self {
|
||||
if worktrees_enabled
|
||||
&& let Some(identity) = akode_git_utils::repository_identity(thread.cwd.as_path())
|
||||
{
|
||||
Self {
|
||||
key: (
|
||||
identity.common_dir.into_path_buf(),
|
||||
identity.relative_cwd.clone(),
|
||||
),
|
||||
heading: identity.primary_root.as_path().join(identity.relative_cwd),
|
||||
}
|
||||
} else {
|
||||
Self {
|
||||
key: (thread.cwd.to_path_buf(), PathBuf::new()),
|
||||
heading: thread.cwd.to_path_buf(),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn directory_group_key(cwd: &Path, worktrees_enabled: bool) -> PathBuf {
|
||||
worktrees_enabled
|
||||
.then(|| dunce::canonicalize(cwd).ok())
|
||||
.flatten()
|
||||
.unwrap_or_else(|| cwd.to_path_buf())
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct AgentsOverviewViewState {
|
||||
scroll: usize,
|
||||
page_height: usize,
|
||||
status_filter: usize,
|
||||
help: bool,
|
||||
pub(super) input: TextArea,
|
||||
pub(super) vim_enabled: bool,
|
||||
pub(super) key_chord_hint: Option<Vec<(String, String)>>,
|
||||
pub(super) creating_worktree: bool,
|
||||
pub(super) refresh_failed: bool,
|
||||
pub(super) loading: bool,
|
||||
pub(super) has_more: bool,
|
||||
show_more_selected: bool,
|
||||
pub(super) connection_notice: Option<&'static str>,
|
||||
/// Browse only while the server holds its lifecycle lock.
|
||||
pub(super) removal: Option<AgentsOverviewAction>,
|
||||
pub(super) server_version_notice: Option<String>,
|
||||
pub(super) search: String,
|
||||
pub(super) history: Option<HistorySearch>,
|
||||
browse_selection: Option<ThreadId>,
|
||||
searching: bool,
|
||||
pub(super) grouping: AgentsOverviewGrouping,
|
||||
pub(super) rename_target: Option<ThreadId>,
|
||||
// The picker can finish this retained view when it selects the already active session.
|
||||
pub(super) completion: Option<ViewCompletion>,
|
||||
}
|
||||
|
||||
impl AgentsOverviewViewState {
|
||||
pub(super) fn set_rename_input(&mut self, text: &str, keymap: &RuntimeKeymap) {
|
||||
let mut input = TextArea::new_single_line();
|
||||
input.set_keymap_bindings(keymap);
|
||||
input.set_vim_enabled(self.vim_enabled);
|
||||
input.set_text_clearing_elements(text);
|
||||
input.set_cursor(input.text().len());
|
||||
input.enter_vim_insert_mode();
|
||||
self.input = input;
|
||||
}
|
||||
|
||||
pub(super) fn restart_history_search(&mut self) {
|
||||
self.history =
|
||||
(!self.search.is_empty() && self.connection_notice.is_none()).then(|| HistorySearch {
|
||||
id: uuid::Uuid::new_v4(),
|
||||
target: self.history.as_ref().map_or(10, |search| search.target),
|
||||
..Default::default()
|
||||
});
|
||||
}
|
||||
|
||||
fn includes_row(&self, row: &AgentsOverviewRow) -> bool {
|
||||
row.search_id.is_none()
|
||||
|| row.search_id == self.history.as_ref().map(|search| search.id)
|
||||
|| self.rename_target == Some(row.thread_id)
|
||||
}
|
||||
|
||||
fn more_available(&self) -> bool {
|
||||
self.history
|
||||
.as_ref()
|
||||
.map_or(self.has_more && !self.searching, |search| {
|
||||
search.cursor.has_more()
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn editing_metadata(&self) -> bool {
|
||||
self.searching || self.rename_target.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct AgentsOverviewView {
|
||||
use_theme_colors: bool,
|
||||
pub(super) rows: Vec<AgentsOverviewRow>,
|
||||
project_groups: Vec<AgentsOverviewProjectGroup>,
|
||||
directory_group_keys: Vec<PathBuf>,
|
||||
pub(super) pinned_thread_ranks: Option<HashMap<ThreadId, usize>>,
|
||||
pub(super) pin_action_pending: bool,
|
||||
pub(super) can_return_to_chat: bool,
|
||||
selected: usize,
|
||||
state: Arc<Mutex<AgentsOverviewViewState>>,
|
||||
app_event_tx: AppEventSender,
|
||||
keymap: ListKeymap,
|
||||
agents_keymap: AgentsKeymap,
|
||||
center_shortcut_keys: Vec<crate::key_hint::KeyBinding>,
|
||||
worktrees_enabled: bool,
|
||||
editor_keymap: RuntimeKeymap,
|
||||
}
|
||||
|
||||
impl AgentsOverviewView {
|
||||
pub(super) fn new(
|
||||
rows: Vec<AgentsOverviewRow>,
|
||||
selected_thread_id: Option<ThreadId>,
|
||||
worktrees_enabled: bool,
|
||||
use_theme_colors: bool,
|
||||
app_event_tx: AppEventSender,
|
||||
keymap: RuntimeKeymap,
|
||||
state: Arc<Mutex<AgentsOverviewViewState>>,
|
||||
) -> Self {
|
||||
let selected = state
|
||||
.lock()
|
||||
.unwrap_or_else(PoisonError::into_inner)
|
||||
.rename_target
|
||||
.and_then(|thread_id| rows.iter().position(|row| row.thread_id == thread_id))
|
||||
.or_else(|| {
|
||||
selected_thread_id.and_then(|id| rows.iter().position(|row| row.thread_id == id))
|
||||
})
|
||||
.or_else(|| rows.iter().position(|row| row.is_current))
|
||||
.unwrap_or(0);
|
||||
let project_groups = rows
|
||||
.iter()
|
||||
.map(|row| AgentsOverviewProjectGroup::for_thread(&row.thread, worktrees_enabled))
|
||||
.collect();
|
||||
let directory_group_keys = rows
|
||||
.iter()
|
||||
.map(|row| directory_group_key(row.thread.cwd.as_path(), worktrees_enabled))
|
||||
.collect();
|
||||
let center_shortcut_keys = crate::keymap::keymap_action_ids()
|
||||
.filter(|action| matches!(action.context, KeymapContext::List | KeymapContext::Agents))
|
||||
.flat_map(|action| {
|
||||
crate::keymap::bindings_for_action(
|
||||
&keymap,
|
||||
action.context.config_name(),
|
||||
action.action,
|
||||
)
|
||||
.unwrap_or_default()
|
||||
.iter()
|
||||
.copied()
|
||||
})
|
||||
.chain(keymap.chords.bindings.iter().filter_map(|binding| {
|
||||
matches!(
|
||||
binding.action.context,
|
||||
KeymapContext::List | KeymapContext::Agents
|
||||
)
|
||||
.then_some(binding.chord.prefix)
|
||||
}))
|
||||
.collect();
|
||||
{
|
||||
let mut state = state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let vim_enabled = state.vim_enabled;
|
||||
if state.rename_target.is_some() {
|
||||
state.input.set_keymap_bindings(&keymap);
|
||||
if state.input.is_vim_enabled() != vim_enabled {
|
||||
state.input.set_vim_enabled(vim_enabled);
|
||||
state.input.enter_vim_insert_mode();
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut view = Self {
|
||||
editor_keymap: keymap.clone(),
|
||||
use_theme_colors,
|
||||
rows,
|
||||
project_groups,
|
||||
directory_group_keys,
|
||||
pinned_thread_ranks: None,
|
||||
pin_action_pending: false,
|
||||
can_return_to_chat: false,
|
||||
selected,
|
||||
state,
|
||||
app_event_tx,
|
||||
keymap: keymap.list,
|
||||
agents_keymap: keymap.agents,
|
||||
center_shortcut_keys,
|
||||
worktrees_enabled,
|
||||
};
|
||||
if selected_thread_id.is_none() && view.state().show_more_selected {
|
||||
view.selected = usize::MAX;
|
||||
}
|
||||
view.state().completion = None;
|
||||
view.reconcile_command_center_selection();
|
||||
view
|
||||
}
|
||||
|
||||
pub(super) fn thread_ids(&self) -> Vec<ThreadId> {
|
||||
self.rows.iter().map(|row| row.thread_id).collect()
|
||||
}
|
||||
|
||||
pub(super) fn selection_after_removal(
|
||||
&self,
|
||||
removed: &std::collections::HashSet<ThreadId>,
|
||||
) -> Option<ThreadId> {
|
||||
let visible = self.visible_indices();
|
||||
let position = visible.iter().position(|index| *index == self.selected)?;
|
||||
visible[position..]
|
||||
.iter()
|
||||
.chain(visible[..position].iter().rev())
|
||||
.map(|index| self.rows[*index].thread_id)
|
||||
.find(|id| !removed.contains(id))
|
||||
}
|
||||
|
||||
fn title_style(&self, thread_id: ThreadId) -> Style {
|
||||
if self.use_theme_colors {
|
||||
Style::default().fg(crate::thread_color::thread_color(thread_id))
|
||||
} else {
|
||||
Style::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn state(&self) -> MutexGuard<'_, AgentsOverviewViewState> {
|
||||
self.state.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
fn selected_row(&self) -> Option<&AgentsOverviewRow> {
|
||||
self.rows
|
||||
.get(self.selected)
|
||||
.filter(|_| self.visible_indices().contains(&self.selected))
|
||||
}
|
||||
|
||||
fn can_toggle_selected_pin(&self) -> bool {
|
||||
!self.pin_action_pending
|
||||
&& self.pinned_thread_ranks.is_some()
|
||||
&& self
|
||||
.selected_row()
|
||||
.is_some_and(|row| supports_shared_pinning(&row.thread.source))
|
||||
}
|
||||
|
||||
fn move_selection(&mut self, forward: bool) {
|
||||
if self.state().rename_target.is_some() {
|
||||
return;
|
||||
}
|
||||
let visible = self.selectable_indices();
|
||||
if visible.is_empty() {
|
||||
return;
|
||||
}
|
||||
let current = visible
|
||||
.iter()
|
||||
.position(|index| *index == self.selected)
|
||||
.unwrap_or(0);
|
||||
self.selected = if forward {
|
||||
visible[(current + 1) % visible.len()]
|
||||
} else {
|
||||
visible[current.checked_sub(1).unwrap_or(visible.len() - 1)]
|
||||
};
|
||||
self.state().show_more_selected = self.selected == usize::MAX;
|
||||
}
|
||||
|
||||
pub(super) fn load_search_matches(&self, additional: usize) {
|
||||
if self.state().history.is_none() {
|
||||
return;
|
||||
}
|
||||
let visible = self.visible_indices().len();
|
||||
let mut state = self.state();
|
||||
if state.more_available()
|
||||
&& let Some(search) = &mut state.history
|
||||
&& !search.loading
|
||||
{
|
||||
if additional > 0 {
|
||||
search.target = visible + additional;
|
||||
search.failed = false;
|
||||
}
|
||||
if search.failed || visible >= search.target {
|
||||
return;
|
||||
}
|
||||
search.loading = true;
|
||||
self.app_event_tx.send(AppEvent::SearchAgentsOverview(
|
||||
search.id,
|
||||
search.target - visible,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
fn activate(&mut self) {
|
||||
if self.selected == usize::MAX && self.state().searching {
|
||||
self.load_search_matches(/*additional*/ 10);
|
||||
return;
|
||||
}
|
||||
if self.selected == usize::MAX && self.state().has_more {
|
||||
if !self.state().loading {
|
||||
self.state().loading = true;
|
||||
self.app_event_tx.send(AppEvent::ShowMoreAgentsOverview);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let input = self.state().input.text().to_owned();
|
||||
if self.state().rename_target.is_some() && !input.trim().is_empty() {
|
||||
if let Some(row) = self.selected_row() {
|
||||
self.app_event_tx
|
||||
.send(AppEvent::RenameAgentsOverviewThread {
|
||||
thread_id: row.thread_id,
|
||||
name: input.trim().to_string(),
|
||||
});
|
||||
}
|
||||
self.state().rename_target = None;
|
||||
self.state().input.set_text_clearing_elements("");
|
||||
self.reconcile_command_center_selection();
|
||||
} else if let Some(row) = self
|
||||
.selected_row()
|
||||
.filter(|_| self.state().rename_target.is_none())
|
||||
{
|
||||
self.app_event_tx
|
||||
.send(AppEvent::SelectAgentsOverviewThread {
|
||||
thread_id: row.thread_id,
|
||||
});
|
||||
if self.state().searching {
|
||||
let mut state = self.state();
|
||||
state.history = None;
|
||||
state.search.clear();
|
||||
state.searching = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn edit_input(&mut self, edit: impl FnOnce(&mut String)) -> bool {
|
||||
let mut state = self.state.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
let searching = state.searching;
|
||||
if searching {
|
||||
edit(&mut state.search);
|
||||
state.restart_history_search();
|
||||
}
|
||||
drop(state);
|
||||
if searching {
|
||||
self.load_search_matches(/*additional*/ 10);
|
||||
self.state().show_more_selected = false;
|
||||
self.selected = self
|
||||
.selectable_indices()
|
||||
.first()
|
||||
.copied()
|
||||
.unwrap_or(usize::MAX);
|
||||
}
|
||||
true
|
||||
}
|
||||
|
||||
fn status(row: &AgentsOverviewRow) -> (&'static str, Span<'static>) {
|
||||
match row.group {
|
||||
AgentsOverviewGroup::NeedsYou
|
||||
if row.thread.status == ThreadStatus::SystemError && !is_subagent(&row.thread) =>
|
||||
{
|
||||
("Error", "!".red())
|
||||
}
|
||||
AgentsOverviewGroup::NeedsYou => ("Needs input", "●".red()),
|
||||
AgentsOverviewGroup::Working => ("Working", "●".green()),
|
||||
AgentsOverviewGroup::Ready => ("Ready", "○".cyan()),
|
||||
AgentsOverviewGroup::Finished => ("Inactive", "○".dim()),
|
||||
}
|
||||
}
|
||||
|
||||
fn render_details(&self, area: Rect, buf: &mut Buffer) {
|
||||
let Some(row) = self.selected_row() else {
|
||||
return;
|
||||
};
|
||||
let (status, dot) = Self::status(row);
|
||||
let width = usize::from(area.width);
|
||||
let model = crate::line_truncation::truncate_line_with_ellipsis_if_overflow(
|
||||
Line::from(vec![
|
||||
"Model: ".dim(),
|
||||
model_name(&row.thread).to_string().into(),
|
||||
]),
|
||||
width,
|
||||
);
|
||||
let reasoning = crate::line_truncation::truncate_line_with_ellipsis_if_overflow(
|
||||
Line::from(vec![
|
||||
"Reasoning: ".dim(),
|
||||
row.thread
|
||||
.reasoning_effort
|
||||
.as_ref()
|
||||
.map_or("Unknown", ReasoningEffort::as_str)
|
||||
.to_string()
|
||||
.into(),
|
||||
]),
|
||||
width,
|
||||
);
|
||||
let mut lines = vec![
|
||||
Line::from("Task details".bold()),
|
||||
Line::default(),
|
||||
crate::line_truncation::truncate_line_with_ellipsis_if_overflow(
|
||||
Line::from(Span::styled(
|
||||
display_title(&row.thread).to_owned(),
|
||||
self.title_style(row.thread_id).bold(),
|
||||
)),
|
||||
width,
|
||||
),
|
||||
Line::from(vec![dot, " ".into(), status.into()]),
|
||||
Line::default(),
|
||||
model,
|
||||
reasoning,
|
||||
Line::default(),
|
||||
Line::from("Project".dim()),
|
||||
Line::from(row.thread.cwd.display().to_string()),
|
||||
];
|
||||
lines.extend(row.details.usage_lines.clone());
|
||||
if let Some(branch) = row
|
||||
.thread
|
||||
.git_info
|
||||
.as_ref()
|
||||
.and_then(|git| git.branch.as_ref())
|
||||
{
|
||||
lines.push(Line::default());
|
||||
lines.push("Branch".dim().into());
|
||||
lines.push(branch.clone().into());
|
||||
}
|
||||
// Keep destinations attached to their text through wrapping and clipping.
|
||||
let wrap = |lines: Vec<HyperlinkLine>| {
|
||||
lines
|
||||
.into_iter()
|
||||
.flat_map(|line| {
|
||||
let wrapped = crate::wrapping::word_wrap_lines([line.line.clone()], width);
|
||||
remap_wrapped_line(&line, wrapped)
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
let preview = super::agents_overview_details::preview_markdown(
|
||||
row.details
|
||||
.latest_prompt
|
||||
.as_deref()
|
||||
.unwrap_or(&row.thread.preview),
|
||||
);
|
||||
let prompt_start = crate::wrapping::word_wrap_lines(lines.clone(), width).len();
|
||||
lines.extend([Line::default(), Line::from("Prompt".dim())]);
|
||||
let prompt = crate::markdown_render::render_markdown_lines_with_width_and_cwd(
|
||||
match preview.as_str() {
|
||||
"" => "No prompt available.",
|
||||
preview => preview,
|
||||
},
|
||||
Some(width),
|
||||
Some(row.thread.cwd.as_path()),
|
||||
);
|
||||
let mut prompt = wrap(prompt);
|
||||
if prompt.len() > 2 {
|
||||
prompt.truncate(2);
|
||||
prompt[1] = HyperlinkLine::new("…".dim().into());
|
||||
}
|
||||
let details_start = prompt_start;
|
||||
let mut lines = wrap(plain_hyperlink_lines(lines));
|
||||
lines.extend(prompt);
|
||||
if self.state().connection_notice.is_none() {
|
||||
let mut details = plain_hyperlink_lines(row.details.lines.clone());
|
||||
if let Some((message, cwd)) = &row.details.last_message {
|
||||
details.extend(plain_hyperlink_lines(vec![
|
||||
Line::default(),
|
||||
"Last message".dim().into(),
|
||||
]));
|
||||
details.extend(
|
||||
crate::markdown_render::render_markdown_lines_with_width_and_cwd(
|
||||
&crate::markdown::normalize_markdown_for_rendering(message),
|
||||
Some(width),
|
||||
Some(cwd.as_path()),
|
||||
),
|
||||
);
|
||||
}
|
||||
let mut details = wrap(details);
|
||||
if !row.details.usage_lines.is_empty()
|
||||
&& details.len() > usize::from(area.height).saturating_sub(lines.len())
|
||||
{
|
||||
// Activity and usage take precedence over repeating the original prompt.
|
||||
lines.truncate(prompt_start);
|
||||
}
|
||||
let available = usize::from(area.height).saturating_sub(lines.len());
|
||||
if details.len() > available {
|
||||
details.truncate(available);
|
||||
if let Some(last) = details.last_mut() {
|
||||
*last = HyperlinkLine::new("…".dim().into());
|
||||
}
|
||||
}
|
||||
lines.splice(details_start..details_start, details);
|
||||
}
|
||||
Paragraph::new(visible_lines(lines.clone())).render(area, buf);
|
||||
mark_buffer_hyperlinks(buf, area, &lines, /*scroll_rows*/ 0);
|
||||
}
|
||||
}
|
||||
|
||||
impl BottomPaneView for AgentsOverviewView {
|
||||
fn view_id(&self) -> Option<&'static str> {
|
||||
Some(AGENTS_OVERVIEW_VIEW_ID)
|
||||
}
|
||||
|
||||
fn selected_index(&self) -> Option<usize> {
|
||||
Some(self.selected)
|
||||
}
|
||||
|
||||
fn keymap_contexts(&self) -> KeymapContextSet {
|
||||
let state = self.state();
|
||||
if state.rename_target.is_some() {
|
||||
let contexts = KeymapContextSet::new(state.input.keymap_context());
|
||||
if state.input.is_vim_operator_pending() {
|
||||
contexts
|
||||
} else {
|
||||
contexts
|
||||
.with(KeymapContext::List)
|
||||
.with(KeymapContext::Agents)
|
||||
}
|
||||
} else {
|
||||
KeymapContextSet::new(KeymapContext::List).with(KeymapContext::Agents)
|
||||
}
|
||||
}
|
||||
|
||||
fn completion(&self) -> Option<ViewCompletion> {
|
||||
self.state().completion
|
||||
}
|
||||
|
||||
fn is_complete(&self) -> bool {
|
||||
self.completion().is_some()
|
||||
}
|
||||
|
||||
fn prefer_esc_to_handle_key_event(&self) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn on_ctrl_c(&mut self) -> CancellationEvent {
|
||||
let mut state = self.state();
|
||||
if state.editing_metadata() {
|
||||
let restore = state.searching.then_some(state.browse_selection);
|
||||
state.history = None;
|
||||
state.searching = false;
|
||||
state.rename_target = None;
|
||||
state.search.clear();
|
||||
state.input.set_text_clearing_elements("");
|
||||
drop(state);
|
||||
if let Some(selected) = restore {
|
||||
self.selected = selected
|
||||
.and_then(|id| self.rows.iter().position(|row| row.thread_id == id))
|
||||
.unwrap_or(usize::MAX);
|
||||
self.state().show_more_selected = self.selected == usize::MAX;
|
||||
}
|
||||
self.reconcile_command_center_selection();
|
||||
return CancellationEvent::Handled;
|
||||
}
|
||||
if state.removal.is_some() {
|
||||
return CancellationEvent::Handled;
|
||||
}
|
||||
CancellationEvent::NotHandled
|
||||
}
|
||||
|
||||
fn handle_paste(&mut self, pasted: String) -> bool {
|
||||
if self.state().rename_target.is_some() {
|
||||
self.state()
|
||||
.input
|
||||
.insert_str(&crate::history_cell::sanitize_user_text(pasted.into()));
|
||||
return true;
|
||||
}
|
||||
if self.state().editing_metadata() {
|
||||
return self.edit_input(|input| {
|
||||
input.push_str(&crate::history_cell::sanitize_user_text(pasted.into()))
|
||||
});
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn handle_key_event(&mut self, mut key: KeyEvent) {
|
||||
// Terminals encode Shift-Tab as either BackTab or Tab with the shift modifier.
|
||||
if key.code == KeyCode::BackTab {
|
||||
key.code = KeyCode::Tab;
|
||||
key.modifiers.insert(KeyModifiers::SHIFT);
|
||||
}
|
||||
if key.kind == crossterm::event::KeyEventKind::Release {
|
||||
return;
|
||||
}
|
||||
if self.rename_key(key) || self.command_center_key(key) {
|
||||
return;
|
||||
}
|
||||
if key.code == KeyCode::Backspace
|
||||
&& self.state().editing_metadata()
|
||||
&& key.modifiers.is_empty()
|
||||
&& self.keymap.action_for(key).is_none()
|
||||
{
|
||||
self.edit_input(|input| {
|
||||
input.pop();
|
||||
});
|
||||
return;
|
||||
}
|
||||
if is_plain_text_key_event(key)
|
||||
&& let KeyCode::Char(character) = key.code
|
||||
&& self.state().editing_metadata()
|
||||
{
|
||||
self.edit_input(|input| input.push(character));
|
||||
return;
|
||||
}
|
||||
|
||||
if self.agents_keymap.search.is_pressed(key) {
|
||||
let mut state = self.state();
|
||||
if state.rename_target.is_none() {
|
||||
if state.searching {
|
||||
drop(state);
|
||||
self.on_ctrl_c();
|
||||
} else {
|
||||
state.browse_selection = self.rows.get(self.selected).map(|row| row.thread_id);
|
||||
state.searching = true;
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (self.state().connection_notice.is_some()
|
||||
|| self.state().creating_worktree
|
||||
|| self.state().removal.is_some())
|
||||
&& self.keymap.action_for(key) != Some(ListAction::Cancel)
|
||||
{
|
||||
match self.keymap.action_for(key) {
|
||||
Some(ListAction::MoveUp) => self.move_selection(/*forward*/ false),
|
||||
Some(ListAction::MoveDown) => self.move_selection(/*forward*/ true),
|
||||
Some(action @ (ListAction::PageUp | ListAction::PageDown)) => {
|
||||
self.page_selection(action)
|
||||
}
|
||||
Some(ListAction::JumpTop) => {
|
||||
self.selected = self.visible_indices().first().copied().unwrap_or(0);
|
||||
}
|
||||
Some(ListAction::JumpBottom) => {
|
||||
self.selected = self.visible_indices().last().copied().unwrap_or(0);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if self.agents_keymap.resume.is_pressed(key) {
|
||||
self.app_event_tx.send(AppEvent::OpenResumePicker);
|
||||
return;
|
||||
}
|
||||
if self.agents_keymap.toggle_grouping.is_pressed(key) {
|
||||
let mut state = self.state();
|
||||
state.grouping = match state.grouping {
|
||||
AgentsOverviewGrouping::Project => AgentsOverviewGrouping::Directory,
|
||||
AgentsOverviewGrouping::Directory => AgentsOverviewGrouping::Status,
|
||||
AgentsOverviewGrouping::Status => AgentsOverviewGrouping::Model,
|
||||
AgentsOverviewGrouping::Model => AgentsOverviewGrouping::Project,
|
||||
};
|
||||
if let Some(grouping) = state.grouping.persisted() {
|
||||
self.app_event_tx
|
||||
.send(AppEvent::PersistAgentsOverviewGrouping(grouping));
|
||||
}
|
||||
return;
|
||||
}
|
||||
if self.agents_keymap.toggle_pin.is_pressed(key) {
|
||||
if self.can_toggle_selected_pin()
|
||||
&& let (Some(ranks), Some(row)) = (&self.pinned_thread_ranks, self.selected_row())
|
||||
{
|
||||
let thread_id = row.thread_id;
|
||||
let pinned = !ranks.contains_key(&thread_id);
|
||||
self.pin_action_pending = true;
|
||||
self.app_event_tx
|
||||
.send(AppEvent::ToggleAgentsOverviewPin { thread_id, pinned });
|
||||
}
|
||||
return;
|
||||
}
|
||||
if self.agents_keymap.new_task.is_pressed(key) {
|
||||
self.app_event_tx.send(AppEvent::NewAgentsOverviewSession {
|
||||
cwd: self.selected_row().map(|row| row.thread.cwd.clone()),
|
||||
});
|
||||
return;
|
||||
}
|
||||
if self.agents_keymap.new_worktree.is_pressed(key) {
|
||||
if self.worktrees_enabled {
|
||||
self.app_event_tx.send(AppEvent::NewAgentsOverviewWorktree {
|
||||
cwd: self.selected_row().map(|row| row.thread.cwd.clone()),
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
if self.agents_keymap.fork.is_pressed(key) {
|
||||
if let Some(row) = self.selected_row() {
|
||||
self.app_event_tx.send(AppEvent::ForkAgentsOverviewThread {
|
||||
thread_id: row.thread_id,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
if self.agents_keymap.rename.is_pressed(key) {
|
||||
if let Some(row) = self.selected_row() {
|
||||
let mut state = self.state();
|
||||
if state.rename_target.is_none() {
|
||||
state.set_rename_input(
|
||||
row.thread.name.as_deref().unwrap_or_default(),
|
||||
&self.editor_keymap,
|
||||
);
|
||||
state.history = None;
|
||||
state.search.clear();
|
||||
state.searching = false;
|
||||
state.rename_target = Some(row.thread_id);
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
for (bindings, action) in [
|
||||
(&self.agents_keymap.archive, AgentsOverviewAction::Archive),
|
||||
(&self.agents_keymap.delete, AgentsOverviewAction::Delete),
|
||||
] {
|
||||
if bindings.is_pressed(key) {
|
||||
if let Some(row) = self.selected_row() {
|
||||
self.app_event_tx
|
||||
.send(AppEvent::ConfirmAgentsOverviewAction {
|
||||
thread_id: row.thread_id,
|
||||
action,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
if self.agents_keymap.hide.is_pressed(key) {
|
||||
if let Some(row) = self.selected_row() {
|
||||
let thread_id = row.thread_id;
|
||||
self.app_event_tx
|
||||
.send(AppEvent::HideAgentsOverviewThread { thread_id });
|
||||
}
|
||||
return;
|
||||
}
|
||||
if self.agents_keymap.stop.is_pressed(key) {
|
||||
if let Some(row) = self.selected_row()
|
||||
&& matches!(row.thread.status, ThreadStatus::Active { .. })
|
||||
{
|
||||
self.app_event_tx.send(AppEvent::StopAgentsOverviewThread {
|
||||
thread_id: row.thread_id,
|
||||
});
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if let Some(action) = self.keymap.action_for(key) {
|
||||
if self.state().rename_target.is_some()
|
||||
&& matches!(action, ListAction::JumpTop | ListAction::JumpBottom)
|
||||
{
|
||||
return;
|
||||
}
|
||||
match action {
|
||||
ListAction::MoveUp => self.move_selection(/*forward*/ false),
|
||||
ListAction::MoveDown => self.move_selection(/*forward*/ true),
|
||||
ListAction::JumpTop => {
|
||||
self.selected = self.visible_indices().first().copied().unwrap_or(0);
|
||||
}
|
||||
ListAction::JumpBottom => {
|
||||
self.selected = self.visible_indices().last().copied().unwrap_or(0);
|
||||
}
|
||||
ListAction::Accept => self.activate(),
|
||||
ListAction::Cancel => {
|
||||
if self.can_return_to_chat
|
||||
&& matches!(self.on_ctrl_c(), CancellationEvent::NotHandled)
|
||||
{
|
||||
self.state().completion = Some(ViewCompletion::Cancelled);
|
||||
}
|
||||
}
|
||||
ListAction::PageUp | ListAction::PageDown => {
|
||||
self.page_selection(action);
|
||||
}
|
||||
ListAction::MoveRight if !self.state().editing_metadata() => self.activate(),
|
||||
ListAction::MoveLeft | ListAction::MoveRight => {}
|
||||
}
|
||||
} else if key.code == KeyCode::Backspace {
|
||||
self.edit_input(|input| {
|
||||
input.pop();
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
137
akode-rs/tui/src/app/akode_setup.rs
Normal file
137
akode-rs/tui/src/app/akode_setup.rs
Normal file
@@ -0,0 +1,137 @@
|
||||
//! aKode settings flows inside a session: interface palette (`/theme`), the guided setup
|
||||
//! (`/setup`) and switching between configured providers from `/model`.
|
||||
|
||||
use super::App;
|
||||
use crate::app_event::AppEvent;
|
||||
use crate::app_server_session::AppServerSession;
|
||||
use crate::legacy_core::config::edit::ConfigEditsBuilder;
|
||||
use crate::tui;
|
||||
use crate::ui_theme;
|
||||
use crate::ui_theme::UiPalette;
|
||||
|
||||
impl App {
|
||||
pub(super) async fn apply_ui_theme_selection(&mut self, tui: &mut tui::Tui, palette: String) {
|
||||
let Some(selected) = UiPalette::from_config_value(&palette) else {
|
||||
return;
|
||||
};
|
||||
let edit = crate::legacy_core::config::edit::ui_theme_edit(selected.config_value());
|
||||
let result =
|
||||
ConfigEditsBuilder::for_config_path(self.local_settings.user_config_path.as_path())
|
||||
.with_edits([edit])
|
||||
.apply()
|
||||
.await;
|
||||
match result {
|
||||
Ok(()) => {
|
||||
ui_theme::set_active_palette(Some(selected));
|
||||
self.local_settings.tui.ui_theme = Some(selected.config_value().to_string());
|
||||
self.refresh_status_line();
|
||||
}
|
||||
Err(err) => {
|
||||
ui_theme::apply_configured_palette(self.local_settings.tui.ui_theme.as_deref());
|
||||
tracing::error!(error = %err, "failed to persist interface palette");
|
||||
self.app_event_tx.send(AppEvent::FollowTranscript);
|
||||
self.chat_widget
|
||||
.report_config_save_error(format!("Failed to save theme: {err}"));
|
||||
}
|
||||
}
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
|
||||
/// `/setup`: run the guided setup, then start a new chat with the provider it added.
|
||||
pub(super) async fn run_setup(&mut self, tui: &mut tui::Tui, app_server: &AppServerSession) {
|
||||
let config = self.chat_widget.config_ref().clone();
|
||||
let outcome = crate::onboarding::onboarding_screen::run_setup_in_app(
|
||||
tui,
|
||||
app_server.request_handle(),
|
||||
&config,
|
||||
)
|
||||
.await;
|
||||
match outcome {
|
||||
Ok(Some(setup)) => {
|
||||
ui_theme::set_active_palette(Some(setup.palette));
|
||||
self.local_settings.tui.ui_theme = Some(setup.palette.config_value().to_string());
|
||||
self.chat_widget.add_info_message(
|
||||
format!(
|
||||
"Added provider `{}` with model `{}`; starting a new chat with it.",
|
||||
setup.provider_id, setup.model
|
||||
),
|
||||
Some("Use /model to switch between configured providers.".to_string()),
|
||||
);
|
||||
self.app_event_tx.send(AppEvent::NewSession { name: None });
|
||||
}
|
||||
Ok(None) => {
|
||||
// Cancelled: the palette preview was already restored by the setup.
|
||||
self.chat_widget
|
||||
.add_info_message("Setup cancelled.".to_string(), /*hint*/ None);
|
||||
}
|
||||
Err(err) => {
|
||||
self.chat_widget
|
||||
.add_error_message(format!("Setup failed: {err}"));
|
||||
}
|
||||
}
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
|
||||
/// Fetch another provider's model list directly from its server (`GET {base_url}/models`).
|
||||
pub(super) fn open_provider_models(&mut self, provider_id: String) {
|
||||
let config = self.chat_widget.config_ref();
|
||||
let Some(provider) = config.model_providers.get(&provider_id).cloned() else {
|
||||
self.chat_widget
|
||||
.add_error_message(format!("Model provider `{provider_id}` is not configured."));
|
||||
return;
|
||||
};
|
||||
let Some(base_url) = provider.base_url.clone() else {
|
||||
self.chat_widget
|
||||
.add_error_message(format!("Model provider `{provider_id}` has no base_url."));
|
||||
return;
|
||||
};
|
||||
let tx = self.app_event_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
let api_key = match provider.api_key() {
|
||||
Ok(key) => key,
|
||||
Err(err) => {
|
||||
tx.send(AppEvent::ProviderModelsLoaded {
|
||||
provider_id,
|
||||
result: Err(err.to_string()),
|
||||
});
|
||||
return;
|
||||
}
|
||||
};
|
||||
let result =
|
||||
crate::onboarding::setup_wizard::fetch_provider_models(base_url, api_key).await;
|
||||
tx.send(AppEvent::ProviderModelsLoaded {
|
||||
provider_id,
|
||||
result,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// Make `provider_id`/`model` the default for new chats and start one.
|
||||
pub(super) async fn switch_provider(
|
||||
&mut self,
|
||||
app_server: &mut AppServerSession,
|
||||
provider_id: String,
|
||||
model: String,
|
||||
) {
|
||||
let edits = vec![
|
||||
crate::config_update::replace_config_value(
|
||||
"model_provider",
|
||||
serde_json::json!(provider_id),
|
||||
),
|
||||
crate::config_update::replace_config_value("model", serde_json::json!(model)),
|
||||
];
|
||||
match crate::config_update::write_config_batch(app_server.request_handle(), edits).await {
|
||||
Ok(_) => {
|
||||
self.chat_widget.add_info_message(
|
||||
format!("Switched to `{provider_id}` · `{model}`; starting a new chat."),
|
||||
/*hint*/ None,
|
||||
);
|
||||
self.app_event_tx.send(AppEvent::NewSession { name: None });
|
||||
}
|
||||
Err(err) => self.chat_widget.add_error_message(format!(
|
||||
"Could not switch provider: {}",
|
||||
crate::config_update::format_config_error(&err)
|
||||
)),
|
||||
}
|
||||
}
|
||||
}
|
||||
384
akode-rs/tui/src/app/app_server_event_targets.rs
Normal file
384
akode-rs/tui/src/app/app_server_event_targets.rs
Normal file
@@ -0,0 +1,384 @@
|
||||
//! Thread targeting helpers for app-server requests and notifications.
|
||||
|
||||
use akode_app_server_protocol::ServerNotification;
|
||||
use akode_app_server_protocol::ServerRequest;
|
||||
use akode_protocol::ThreadId;
|
||||
|
||||
pub(super) fn server_request_thread_id(request: &ServerRequest) -> Option<ThreadId> {
|
||||
match request {
|
||||
ServerRequest::CommandExecutionRequestApproval { params, .. } => {
|
||||
ThreadId::from_string(¶ms.thread_id).ok()
|
||||
}
|
||||
ServerRequest::FileChangeRequestApproval { params, .. } => {
|
||||
ThreadId::from_string(¶ms.thread_id).ok()
|
||||
}
|
||||
ServerRequest::ToolRequestUserInput { params, .. } => {
|
||||
ThreadId::from_string(¶ms.thread_id).ok()
|
||||
}
|
||||
ServerRequest::McpServerElicitationRequest { params, .. } => {
|
||||
ThreadId::from_string(¶ms.thread_id).ok()
|
||||
}
|
||||
ServerRequest::PermissionsRequestApproval { params, .. } => {
|
||||
ThreadId::from_string(¶ms.thread_id).ok()
|
||||
}
|
||||
ServerRequest::DynamicToolCall { params, .. } => {
|
||||
ThreadId::from_string(¶ms.thread_id).ok()
|
||||
}
|
||||
ServerRequest::CurrentTimeRead { params, .. } => {
|
||||
ThreadId::from_string(¶ms.thread_id).ok()
|
||||
}
|
||||
ServerRequest::ApplyPatchApproval { .. } | ServerRequest::ExecCommandApproval { .. } => {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(super) enum ServerNotificationThreadTarget {
|
||||
Thread(ThreadId),
|
||||
InvalidThreadId(String),
|
||||
AppScoped,
|
||||
Global,
|
||||
}
|
||||
|
||||
pub(super) fn server_notification_thread_target(
|
||||
notification: &ServerNotification,
|
||||
) -> ServerNotificationThreadTarget {
|
||||
let thread_id = match notification {
|
||||
ServerNotification::Error(notification) => Some(notification.thread_id.as_str()),
|
||||
ServerNotification::ThreadStarted(notification) => Some(notification.thread.id.as_str()),
|
||||
ServerNotification::ThreadStatusChanged(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::ThreadReverted(notification) => Some(notification.thread_id.as_str()),
|
||||
ServerNotification::ThreadArchived(notification) => Some(notification.thread_id.as_str()),
|
||||
ServerNotification::ThreadDeleted(notification) => Some(notification.thread_id.as_str()),
|
||||
ServerNotification::ThreadUnarchived(notification) => Some(notification.thread_id.as_str()),
|
||||
ServerNotification::ThreadClosed(notification) => Some(notification.thread_id.as_str()),
|
||||
ServerNotification::ThreadNameUpdated(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::ThreadAttachmentUpdated(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::ThreadProjectUpdated(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::ThreadTokenUsageUpdated(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::ThreadGoalUpdated(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::ThreadPredictionUpdated(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::ThreadGoalCleared(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::ThreadQueueChanged(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::ThreadSettingsUpdated(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::TurnStarted(notification) => Some(notification.thread_id.as_str()),
|
||||
ServerNotification::HookStarted(notification) => Some(notification.thread_id.as_str()),
|
||||
ServerNotification::TurnCompleted(notification) => Some(notification.thread_id.as_str()),
|
||||
ServerNotification::HookCompleted(notification) => Some(notification.thread_id.as_str()),
|
||||
ServerNotification::TurnDiffUpdated(notification) => Some(notification.thread_id.as_str()),
|
||||
ServerNotification::TurnPlanUpdated(notification) => Some(notification.thread_id.as_str()),
|
||||
ServerNotification::ItemStarted(notification) => Some(notification.thread_id.as_str()),
|
||||
ServerNotification::ItemGuardianApprovalReviewStarted(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::ItemGuardianApprovalReviewCompleted(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::StrictReviewRequired(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::ItemCompleted(notification) => Some(notification.thread_id.as_str()),
|
||||
ServerNotification::RawResponseItemCompleted(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::RawResponseCompleted(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::AgentMessageDelta(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::PlanDelta(notification) => Some(notification.thread_id.as_str()),
|
||||
ServerNotification::CommandExecutionOutputDelta(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::TerminalInteraction(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::FileChangeOutputDelta(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::FileChangePatchUpdated(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::ServerRequestResolved(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::McpToolCallProgress(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::ReasoningSummaryTextDelta(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::ReasoningSummaryPartAdded(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::ReasoningTextDelta(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::ContextCompacted(notification) => Some(notification.thread_id.as_str()),
|
||||
ServerNotification::ModelSafetyBufferingUpdated(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::TurnModerationMetadata(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::ThreadRealtimeStarted(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::ThreadRealtimeItemAdded(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::ThreadRealtimeItemStarted(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::ThreadRealtimeItemTranscriptDelta(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::ThreadRealtimeItemCompleted(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::ThreadRealtimeTranscriptDelta(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::ThreadRealtimeTranscriptDone(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::ThreadRealtimeOutputAudioDelta(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::ThreadRealtimeSdp(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::ThreadRealtimeError(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::ThreadRealtimeClosed(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::AuthRecoveryStarted(notification)
|
||||
| ServerNotification::AuthRecoveryCompleted(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::ThreadReadStateChanged(notification) => {
|
||||
Some(notification.thread_id.as_str())
|
||||
}
|
||||
ServerNotification::Warning(notification) => notification.thread_id.as_deref(),
|
||||
ServerNotification::GuardianWarning(notification) => Some(notification.thread_id.as_str()),
|
||||
ServerNotification::McpServerOauthLoginCompleted(notification) => {
|
||||
match notification.thread_id.as_deref() {
|
||||
Some(thread_id) => Some(thread_id),
|
||||
None => return ServerNotificationThreadTarget::AppScoped,
|
||||
}
|
||||
}
|
||||
ServerNotification::McpServerStatusUpdated(notification) => {
|
||||
match notification.thread_id.as_deref() {
|
||||
Some(thread_id) => Some(thread_id),
|
||||
None => return ServerNotificationThreadTarget::AppScoped,
|
||||
}
|
||||
}
|
||||
ServerNotification::ProjectChanged(_)
|
||||
| ServerNotification::SkillsChanged(_)
|
||||
| ServerNotification::AccountUpdated(_)
|
||||
| ServerNotification::ThreadSectionChanged(_)
|
||||
| ServerNotification::GatewayOAuthChanged(_)
|
||||
| ServerNotification::AccountRateLimitsUpdated(_)
|
||||
| ServerNotification::EnvironmentConnected(_)
|
||||
| ServerNotification::EnvironmentDisconnected(_)
|
||||
| ServerNotification::RemoteControlStatusChanged(_)
|
||||
| ServerNotification::ExternalAgentConfigImportProgress(_)
|
||||
| ServerNotification::ExternalAgentConfigImportCompleted(_)
|
||||
| ServerNotification::DeprecationNotice(_)
|
||||
| ServerNotification::ConfigWarning(_)
|
||||
| ServerNotification::FuzzyFileSearchSessionUpdated(_)
|
||||
| ServerNotification::FuzzyFileSearchSessionCompleted(_)
|
||||
| ServerNotification::CommandExecOutputDelta(_)
|
||||
| ServerNotification::ProcessOutputDelta(_)
|
||||
| ServerNotification::ProcessExited(_)
|
||||
| ServerNotification::FsChanged(_)
|
||||
| ServerNotification::WindowsWorldWritableWarning(_)
|
||||
| ServerNotification::WindowsSandboxSetupCompleted(_)
|
||||
| ServerNotification::AccountLoginCompleted(_) => None,
|
||||
};
|
||||
|
||||
match thread_id {
|
||||
Some(thread_id) => match ThreadId::from_string(thread_id) {
|
||||
Ok(thread_id) => ServerNotificationThreadTarget::Thread(thread_id),
|
||||
Err(_) => ServerNotificationThreadTarget::InvalidThreadId(thread_id.to_string()),
|
||||
},
|
||||
None => ServerNotificationThreadTarget::Global,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::ServerNotificationThreadTarget;
|
||||
use super::server_notification_thread_target;
|
||||
use crate::test_support::PathBufExt;
|
||||
use crate::test_support::test_path_buf;
|
||||
use akode_app_server_protocol::GuardianWarningNotification;
|
||||
use akode_app_server_protocol::McpServerStartupState;
|
||||
use akode_app_server_protocol::McpServerStatusUpdatedNotification;
|
||||
use akode_app_server_protocol::ServerNotification;
|
||||
use akode_app_server_protocol::ThreadAttachmentOperation;
|
||||
use akode_app_server_protocol::ThreadAttachmentUpdatedNotification;
|
||||
use akode_app_server_protocol::ThreadSettings;
|
||||
use akode_app_server_protocol::ThreadSettingsUpdatedNotification;
|
||||
use akode_app_server_protocol::WarningNotification;
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_protocol::config_types::CollaborationMode;
|
||||
use akode_protocol::config_types::ModeKind;
|
||||
use akode_protocol::config_types::Settings;
|
||||
use akode_protocol::openai_models::ReasoningEffort;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn test_thread_settings() -> ThreadSettings {
|
||||
ThreadSettings {
|
||||
disabled_plugin_ids: Vec::new(),
|
||||
cwd: test_path_buf("/tmp/thread-settings").abs(),
|
||||
approval_policy: akode_app_server_protocol::AskForApproval::Never,
|
||||
approvals_reviewer: akode_app_server_protocol::ApprovalsReviewer::User,
|
||||
sandbox_policy: akode_app_server_protocol::SandboxPolicy::ReadOnly {
|
||||
network_access: false,
|
||||
},
|
||||
active_permission_profile: None,
|
||||
model: "gpt-5.4".to_string(),
|
||||
model_provider: "openai".to_string(),
|
||||
service_tier: None,
|
||||
effort: Some(ReasoningEffort::High),
|
||||
summary: None,
|
||||
collaboration_mode: CollaborationMode {
|
||||
mode: ModeKind::Default,
|
||||
settings: Settings {
|
||||
model: "gpt-5.4".to_string(),
|
||||
reasoning_effort: Some(ReasoningEffort::High),
|
||||
developer_instructions: None,
|
||||
},
|
||||
},
|
||||
multi_agent_mode: Default::default(),
|
||||
personality: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warning_notifications_without_threads_are_global() {
|
||||
let notification = ServerNotification::Warning(WarningNotification {
|
||||
thread_id: None,
|
||||
message: "warning".to_string(),
|
||||
});
|
||||
|
||||
let target = server_notification_thread_target(¬ification);
|
||||
|
||||
assert_eq!(target, ServerNotificationThreadTarget::Global);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn warning_notifications_route_to_threads_when_thread_id_is_present() {
|
||||
let thread_id = ThreadId::new();
|
||||
let notification = ServerNotification::Warning(WarningNotification {
|
||||
thread_id: Some(thread_id.to_string()),
|
||||
message: "warning".to_string(),
|
||||
});
|
||||
|
||||
let target = server_notification_thread_target(¬ification);
|
||||
|
||||
assert_eq!(target, ServerNotificationThreadTarget::Thread(thread_id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn guardian_warning_notifications_route_to_threads() {
|
||||
let thread_id = ThreadId::new();
|
||||
let notification = ServerNotification::GuardianWarning(GuardianWarningNotification {
|
||||
thread_id: thread_id.to_string(),
|
||||
message: "warning".to_string(),
|
||||
});
|
||||
|
||||
let target = server_notification_thread_target(¬ification);
|
||||
|
||||
assert_eq!(target, ServerNotificationThreadTarget::Thread(thread_id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_startup_notifications_route_to_threads() {
|
||||
let thread_id = ThreadId::new();
|
||||
let notification =
|
||||
ServerNotification::McpServerStatusUpdated(McpServerStatusUpdatedNotification {
|
||||
thread_id: Some(thread_id.to_string()),
|
||||
name: "sentry".to_string(),
|
||||
status: McpServerStartupState::Failed,
|
||||
error: Some("sentry is not logged in".to_string()),
|
||||
failure_reason: None,
|
||||
});
|
||||
|
||||
let target = server_notification_thread_target(¬ification);
|
||||
|
||||
assert_eq!(target, ServerNotificationThreadTarget::Thread(thread_id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mcp_startup_notifications_without_threads_are_app_scoped() {
|
||||
let notification =
|
||||
ServerNotification::McpServerStatusUpdated(McpServerStatusUpdatedNotification {
|
||||
thread_id: None,
|
||||
name: "sentry".to_string(),
|
||||
status: McpServerStartupState::Failed,
|
||||
error: Some("sentry is not logged in".to_string()),
|
||||
failure_reason: None,
|
||||
});
|
||||
|
||||
let target = server_notification_thread_target(¬ification);
|
||||
|
||||
assert_eq!(target, ServerNotificationThreadTarget::AppScoped);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_settings_updated_notifications_route_to_threads() {
|
||||
let thread_id = ThreadId::new();
|
||||
let notification =
|
||||
ServerNotification::ThreadSettingsUpdated(ThreadSettingsUpdatedNotification {
|
||||
thread_id: thread_id.to_string(),
|
||||
thread_settings: test_thread_settings(),
|
||||
});
|
||||
|
||||
let target = server_notification_thread_target(¬ification);
|
||||
|
||||
assert_eq!(target, ServerNotificationThreadTarget::Thread(thread_id));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_attachment_updated_notifications_route_to_threads() {
|
||||
let thread_id = ThreadId::new();
|
||||
let notification =
|
||||
ServerNotification::ThreadAttachmentUpdated(ThreadAttachmentUpdatedNotification {
|
||||
thread_id: thread_id.to_string(),
|
||||
attachment_type: "pull_request".to_string(),
|
||||
identity_key: r#"["github.com","openai","codex",123]"#.to_string(),
|
||||
attachment_id: "attachment-1".to_string(),
|
||||
operation: ThreadAttachmentOperation::Deleted,
|
||||
});
|
||||
|
||||
let target = server_notification_thread_target(¬ification);
|
||||
|
||||
assert_eq!(target, ServerNotificationThreadTarget::Thread(thread_id));
|
||||
}
|
||||
}
|
||||
800
akode-rs/tui/src/app/app_server_events.rs
Normal file
800
akode-rs/tui/src/app/app_server_events.rs
Normal file
@@ -0,0 +1,800 @@
|
||||
//! App-server event stream handling for the TUI app.
|
||||
//! Hidden structured threads reject requests instead of entering interactive routing.
|
||||
|
||||
use super::App;
|
||||
use super::ThreadBufferedEvent;
|
||||
use super::app_server_event_targets::ServerNotificationThreadTarget;
|
||||
use super::app_server_event_targets::server_notification_thread_target;
|
||||
use super::app_server_event_targets::server_request_thread_id;
|
||||
use super::app_server_requests::BufferedServerRequest;
|
||||
use crate::app_command::AppCommand;
|
||||
use crate::app_event::AppEvent;
|
||||
#[cfg(any(target_os = "windows", test))]
|
||||
use crate::app_event::WindowsSandboxEnableMode;
|
||||
use crate::app_server_session::AppServerSession;
|
||||
use crate::app_server_session::status_account_display_from_auth_mode;
|
||||
use akode_app_server_client::AppServerEvent;
|
||||
use akode_app_server_client::TypedRequestError;
|
||||
use akode_app_server_protocol::ClientRequest;
|
||||
use akode_app_server_protocol::JSONRPCErrorError;
|
||||
use akode_app_server_protocol::RequestId;
|
||||
use akode_app_server_protocol::ServerNotification;
|
||||
use akode_app_server_protocol::ServerRequest;
|
||||
use akode_app_server_protocol::SessionSource;
|
||||
use akode_app_server_protocol::ThreadItemPayload;
|
||||
use akode_app_server_protocol::ThreadReadParams;
|
||||
use akode_app_server_protocol::ThreadReadResponse;
|
||||
use akode_app_server_protocol::ThreadSource;
|
||||
use akode_app_server_protocol::ThreadStatus;
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_protocol::protocol::SubAgentSource;
|
||||
use akode_protocol::request_permissions::RequestPermissionProfile as CoreRequestPermissionProfile;
|
||||
use std::time::Duration;
|
||||
|
||||
impl App {
|
||||
async fn reject_unsupported_app_server_request(
|
||||
&mut self,
|
||||
unsupported: super::app_server_requests::UnsupportedAppServerRequest,
|
||||
request: &BufferedServerRequest,
|
||||
) {
|
||||
tracing::warn!(
|
||||
request_id = ?unsupported.request_id,
|
||||
message = unsupported.message,
|
||||
"rejecting unsupported app-server request"
|
||||
);
|
||||
self.chat_widget
|
||||
.add_error_message(unsupported.message.clone());
|
||||
let result = request
|
||||
.reply
|
||||
.clone()
|
||||
.reject(JSONRPCErrorError {
|
||||
code: -32000,
|
||||
message: unsupported.message,
|
||||
data: None,
|
||||
})
|
||||
.await
|
||||
.map_err(|err| format!("failed to reject app-server request: {err}"));
|
||||
if let Err(err) = result {
|
||||
tracing::warn!("{err}");
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn refresh_mcp_startup_expected_servers_from_config(&mut self) {
|
||||
let configured_servers = self.config.mcp_servers.get();
|
||||
let is_subagent = self
|
||||
.current_displayed_thread_id()
|
||||
.zip(self.primary_thread_id)
|
||||
.is_some_and(|(thread_id, primary_thread_id)| {
|
||||
self.agent_navigation.is_parent_owned(thread_id)
|
||||
|| (thread_id != primary_thread_id
|
||||
&& !self.side_threads.contains_key(&thread_id))
|
||||
});
|
||||
if is_subagent || !matches!(self.app_server_target, crate::AppServerTarget::Embedded) {
|
||||
// Shared app servers only send startup updates after subscription and may
|
||||
// have different configured servers. Subagents can start deferred servers
|
||||
// individually. In both cases, wait only for the startups we observe.
|
||||
self.chat_widget.track_reported_mcp_startup_servers();
|
||||
return;
|
||||
}
|
||||
|
||||
let enabled_servers = configured_servers
|
||||
.iter()
|
||||
.filter(|(_, server)| server.enabled);
|
||||
// Plugins can contribute lazy servers outside the explicit configuration.
|
||||
if self
|
||||
.config
|
||||
.features
|
||||
.enabled(akode_features::Feature::McpLazyStdioStartup)
|
||||
{
|
||||
self.chat_widget.set_initial_mcp_startup_expected_servers(
|
||||
enabled_servers
|
||||
.filter(|(_, server)| !server.can_defer_stdio_startup())
|
||||
.map(|(name, _)| name.clone()),
|
||||
);
|
||||
} else {
|
||||
self.chat_widget
|
||||
.set_mcp_startup_expected_servers(enabled_servers.map(|(name, _)| name.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn handle_app_server_event(
|
||||
&mut self,
|
||||
app_server_client: &AppServerSession,
|
||||
event: AppServerEvent,
|
||||
) {
|
||||
match event {
|
||||
AppServerEvent::Lagged { skipped } => {
|
||||
tracing::warn!(
|
||||
skipped,
|
||||
"app-server event consumer lagged; dropping ignored events"
|
||||
);
|
||||
self.refresh_mcp_startup_expected_servers_from_config();
|
||||
self.chat_widget.finish_mcp_startup_after_lag();
|
||||
if let Some(task) = self.agents_overview.refresh_task.take() {
|
||||
task.abort();
|
||||
}
|
||||
self.agents_overview.request_id = None;
|
||||
self.agents_overview.refresh_show_more = false;
|
||||
self.agents_overview.active_refresh_thread_ids.clear();
|
||||
self.agents_overview.refresh_pending = false;
|
||||
self.agents_overview.initialized = false;
|
||||
self.agents_overview.refresh_notifications.clear();
|
||||
self.agents_overview.activity.clear();
|
||||
self.agents_overview.last_messages.clear();
|
||||
self.agents_overview.usage.clear();
|
||||
self.repaint_agents_overview();
|
||||
self.refresh_agents_overview_threads(app_server_client);
|
||||
if let Some(primary_thread_id) = self.primary_thread_id
|
||||
&& !self
|
||||
.agent_navigation
|
||||
.queue_picker_refresh(primary_thread_id)
|
||||
{
|
||||
self.refresh_agent_picker_threads(app_server_client, primary_thread_id);
|
||||
}
|
||||
}
|
||||
AppServerEvent::ServerNotification(notification) => {
|
||||
let request_resolved = matches!(
|
||||
notification.as_ref(),
|
||||
ServerNotification::ServerRequestResolved(_)
|
||||
);
|
||||
self.handle_server_notification_event(app_server_client, *notification)
|
||||
.await;
|
||||
if request_resolved {
|
||||
self.repaint_agents_overview();
|
||||
}
|
||||
}
|
||||
AppServerEvent::ServerRequest(request) => {
|
||||
let request =
|
||||
BufferedServerRequest::new(*request, &app_server_client.request_handle());
|
||||
self.handle_server_request_event(app_server_client, request)
|
||||
.await;
|
||||
self.repaint_agents_overview();
|
||||
}
|
||||
AppServerEvent::ThreadStreamDisconnected(error) => {
|
||||
self.handle_server_notification_event(
|
||||
app_server_client,
|
||||
ServerNotification::Error(*error),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
AppServerEvent::Disconnected { message } => {
|
||||
// The request result distinguishes a refused start from a lost reply.
|
||||
if self.pending_startup_thread_start
|
||||
&& !matches!(self.app_server_target, crate::AppServerTarget::Embedded)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if self.begin_reconnect() {
|
||||
return;
|
||||
}
|
||||
tracing::warn!("app-server event stream disconnected: {message}");
|
||||
self.chat_widget.add_error_message(message.clone());
|
||||
self.app_event_tx.send(AppEvent::FatalExitRequest(message));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn handle_server_notification_event(
|
||||
&mut self,
|
||||
app_server_client: &AppServerSession,
|
||||
mut notification: ServerNotification,
|
||||
) {
|
||||
if let ServerNotification::TurnModerationMetadata(metadata) = &mut notification
|
||||
&& (!super::safety_recourse::supports_server(app_server_client)
|
||||
|| self
|
||||
.primary_thread_id
|
||||
.is_none_or(|id| id.to_string() != metadata.thread_id))
|
||||
&& let Some(metadata) = metadata.metadata.as_object_mut()
|
||||
{
|
||||
metadata.remove("safety_block");
|
||||
metadata.remove("safety_recourse");
|
||||
}
|
||||
// A picker can leave an old runtime's close notification queued while the same thread
|
||||
// is resumed. Thread IDs survive reloads, so confirm that the displayed thread is still
|
||||
// unloaded before routing a close that would exit the TUI or switch away from it.
|
||||
if let ServerNotification::ThreadClosed(closed) = ¬ification
|
||||
&& let Ok(thread_id) = ThreadId::from_string(&closed.thread_id)
|
||||
&& self.current_displayed_thread_id() == Some(thread_id)
|
||||
{
|
||||
let deadline = tokio::time::Instant::now() + Duration::from_secs(/*secs*/ 5);
|
||||
for attempt in 0..2 {
|
||||
let result = tokio::time::timeout_at(
|
||||
deadline,
|
||||
app_server_client
|
||||
.request_handle()
|
||||
.request_typed::<ThreadReadResponse>(ClientRequest::ThreadRead {
|
||||
request_id: RequestId::String(format!(
|
||||
"thread-closed-{thread_id}-{attempt}"
|
||||
)),
|
||||
params: ThreadReadParams {
|
||||
thread_id: closed.thread_id.clone(),
|
||||
include_turns: false,
|
||||
},
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
match result {
|
||||
Ok(Ok(response))
|
||||
if !matches!(response.thread.status, ThreadStatus::NotLoaded) =>
|
||||
{
|
||||
return;
|
||||
}
|
||||
Ok(Ok(_)) => break,
|
||||
// Unpersisted closed threads can no longer be read. Preserve that close
|
||||
// and compatibility with servers that do not support this request.
|
||||
Ok(Err(TypedRequestError::Server { source, .. }))
|
||||
if matches!(source.code, -32602..=-32600) =>
|
||||
{
|
||||
break;
|
||||
}
|
||||
Ok(Err(TypedRequestError::Server { source, .. }))
|
||||
if source.code == -32603 && attempt == 0 =>
|
||||
{
|
||||
continue;
|
||||
}
|
||||
Ok(Err(_)) | Err(_) => {
|
||||
// A failed read does not confirm closure. Remote connections recover
|
||||
// through the normal reconnect path, rather than exiting the TUI.
|
||||
tracing::warn!("could not confirm displayed thread closure");
|
||||
if self.begin_reconnect() {
|
||||
return;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if let ServerNotification::ThreadStatusChanged(status) = ¬ification {
|
||||
let _ = self.dynamic_tool_status_updates.send(status.clone());
|
||||
}
|
||||
|
||||
if let ServerNotification::ThreadStarted(started) = ¬ification
|
||||
&& started.thread.ephemeral
|
||||
&& matches!(
|
||||
started.thread.thread_source.as_ref(),
|
||||
Some(ThreadSource::Feature(feature)) if matches!(feature.as_str(), "system" | "thread_title")
|
||||
)
|
||||
{
|
||||
return;
|
||||
}
|
||||
// Hidden helper threads must not enter visible thread routing or overview refreshes.
|
||||
if let ServerNotificationThreadTarget::Thread(thread_id) =
|
||||
server_notification_thread_target(¬ification)
|
||||
&& let Some(sender) = self.temporary_structured_requests.get(&thread_id)
|
||||
{
|
||||
if matches!(
|
||||
¬ification,
|
||||
ServerNotification::ItemCompleted(_) | ServerNotification::TurnCompleted(_)
|
||||
) && sender.send(notification).is_err()
|
||||
{
|
||||
self.temporary_structured_requests.remove(&thread_id);
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
self.handle_agent_picker_visibility_notification(app_server_client, ¬ification);
|
||||
|
||||
if let ServerNotification::ThreadStarted(started) = ¬ification
|
||||
&& let SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
|
||||
parent_thread_id, ..
|
||||
}) = &started.thread.source
|
||||
&& self
|
||||
.agents_overview
|
||||
.dispatched_requests
|
||||
.contains_key(parent_thread_id)
|
||||
&& let Ok(thread_id) = akode_protocol::ThreadId::from_string(&started.thread.id)
|
||||
{
|
||||
self.agents_overview
|
||||
.dispatched_requests
|
||||
.entry(thread_id)
|
||||
.or_default();
|
||||
}
|
||||
self.track_agents_overview_notification(¬ification);
|
||||
// Retained blank sessions stay subscribed after their event channels are cleared.
|
||||
if let ServerNotification::ThreadSettingsUpdated(settings) = ¬ification
|
||||
&& let Ok(thread_id) = ThreadId::from_string(&settings.thread_id)
|
||||
&& self.agents_overview.blank_sessions.contains_key(&thread_id)
|
||||
&& !self.thread_event_channels.contains_key(&thread_id)
|
||||
{
|
||||
self.apply_thread_settings_to_cached_session(thread_id, &settings.thread_settings)
|
||||
.await;
|
||||
if let Some(input) = self.agents_overview.input_states.get_mut(&thread_id) {
|
||||
input.pending_thread_settings = Some(settings.clone());
|
||||
}
|
||||
}
|
||||
if matches!(
|
||||
¬ification,
|
||||
ServerNotification::ThreadStarted(_)
|
||||
| ServerNotification::ThreadStatusChanged(_)
|
||||
| ServerNotification::ThreadSettingsUpdated(_)
|
||||
| ServerNotification::ThreadNameUpdated(_)
|
||||
| ServerNotification::ThreadArchived(_)
|
||||
| ServerNotification::ThreadDeleted(_)
|
||||
| ServerNotification::ThreadClosed(_)
|
||||
) {
|
||||
self.repaint_agents_overview();
|
||||
self.refresh_changed_agents_overview_threads(app_server_client);
|
||||
}
|
||||
match ¬ification {
|
||||
ServerNotification::ServerRequestResolved(notification) => {
|
||||
if let Some((_, task)) = self.dynamic_tool_tasks.remove(¬ification.request_id) {
|
||||
task.abort();
|
||||
}
|
||||
let notification_thread_id =
|
||||
akode_protocol::ThreadId::from_string(¬ification.thread_id).ok();
|
||||
self.pending_primary_events.retain(|event| {
|
||||
!matches!(event, ThreadBufferedEvent::Request(request)
|
||||
if request.id() == ¬ification.request_id
|
||||
&& server_request_thread_id(request) == notification_thread_id)
|
||||
});
|
||||
if let Some(thread_id) = notification_thread_id
|
||||
&& let Some(requests) =
|
||||
self.agents_overview.dispatched_requests.get_mut(&thread_id)
|
||||
{
|
||||
requests.retain(|request| request.request.id() != ¬ification.request_id);
|
||||
}
|
||||
if let Some(resolved) = self
|
||||
.pending_app_server_requests
|
||||
.resolve_notification(¬ification.thread_id, ¬ification.request_id)
|
||||
&& self.chat_widget.thread_id().map(|id| id.to_string())
|
||||
== Some(resolved.thread_id)
|
||||
{
|
||||
self.chat_widget
|
||||
.dismiss_app_server_request(&resolved.request);
|
||||
if self.startup_pending_protected_request {
|
||||
self.startup_pending_protected_request =
|
||||
self.chat_widget.has_active_modal()
|
||||
|| self.chat_widget.has_pending_protected_request();
|
||||
}
|
||||
}
|
||||
}
|
||||
ServerNotification::McpServerStatusUpdated(_) => {
|
||||
self.refresh_mcp_startup_expected_servers_from_config();
|
||||
}
|
||||
ServerNotification::McpServerOauthLoginCompleted(notification) => {
|
||||
// The start response identifies the new attempt. Hold completions until then
|
||||
// so a replacement's cancellation cannot appear as a fresh login failure.
|
||||
if let Some(pending) = self.pending_mcp_login_start.as_mut()
|
||||
&& pending.name == notification.name
|
||||
{
|
||||
pending.completions.push(notification.clone());
|
||||
return;
|
||||
}
|
||||
if notification.login_id.is_some() {
|
||||
if notification.login_id.as_ref()
|
||||
!= self.active_mcp_login_ids.get(¬ification.name)
|
||||
{
|
||||
return;
|
||||
}
|
||||
self.active_mcp_login_ids.remove(¬ification.name);
|
||||
}
|
||||
}
|
||||
|
||||
ServerNotification::AccountRateLimitsUpdated(notification) => {
|
||||
self.chat_widget
|
||||
.on_rate_limit_snapshot(Some(notification.rate_limits.clone()));
|
||||
return;
|
||||
}
|
||||
ServerNotification::AccountUpdated(notification) => {
|
||||
self.repaint_agents_overview();
|
||||
let account_display = status_account_display_from_auth_mode(notification.auth_mode);
|
||||
self.chat_widget.update_account_state(account_display);
|
||||
return;
|
||||
}
|
||||
ServerNotification::ExternalAgentConfigImportCompleted(notification) => {
|
||||
let should_report_completion = app_server_client
|
||||
.consume_external_agent_config_import_completion(¬ification.import_id);
|
||||
if !app_server_client.uses_remote_workspace()
|
||||
&& let Err(err) = self.refresh_in_memory_config_from_disk().await
|
||||
{
|
||||
tracing::warn!(
|
||||
error = %err,
|
||||
"failed to refresh config after external agent config import"
|
||||
);
|
||||
}
|
||||
let cwd = self.chat_widget.config_ref().cwd.to_path_buf();
|
||||
self.chat_widget.refresh_plugin_mentions();
|
||||
self.chat_widget.submit_op(AppCommand::reload_user_config());
|
||||
self.fetch_plugins_list(app_server_client, cwd);
|
||||
if should_report_completion {
|
||||
self.chat_widget.add_plain_history_lines(
|
||||
crate::external_agent_config_migration::flow::external_agent_config_migration_finished_lines(notification),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
match server_notification_thread_target(¬ification) {
|
||||
ServerNotificationThreadTarget::Thread(thread_id) => {
|
||||
if self.current_displayed_thread_id() != Some(thread_id)
|
||||
&& let ServerNotification::ItemCompleted(item) = ¬ification
|
||||
&& let ThreadItemPayload::UserMessage {
|
||||
client_id: Some(client_id),
|
||||
..
|
||||
} = &item.item.payload
|
||||
{
|
||||
// Acknowledge by ID before routing can discard the receipt. ID-less receipts
|
||||
// cannot safely distinguish identical pending submissions.
|
||||
let mut store = match self.thread_event_channels.get(&thread_id) {
|
||||
Some(channel) => Some(channel.store.lock().await),
|
||||
None => None,
|
||||
};
|
||||
for input in store
|
||||
.as_mut()
|
||||
.and_then(|store| store.input_state.as_mut())
|
||||
.into_iter()
|
||||
.chain(self.agents_overview.input_states.get_mut(&thread_id))
|
||||
{
|
||||
if input
|
||||
.pending_steers
|
||||
.front()
|
||||
.is_some_and(|pending| pending.client_id == *client_id)
|
||||
{
|
||||
input.pending_steers.pop_front();
|
||||
}
|
||||
}
|
||||
}
|
||||
let background_voice = self.background_voice.as_ref().is_some_and(|owner| {
|
||||
owner.thread_id() == Some(thread_id) && owner.realtime_conversation_is_running()
|
||||
});
|
||||
if self.primary_thread_id.is_none()
|
||||
&& !self.pending_startup_thread_start
|
||||
&& !background_voice
|
||||
{
|
||||
return;
|
||||
}
|
||||
let untracked_thread =
|
||||
self.primary_thread_id.is_some() && !self.owns_thread_for_routing(thread_id);
|
||||
if untracked_thread
|
||||
&& !self
|
||||
.owns_untracked_notification(app_server_client, thread_id, ¬ification)
|
||||
.await
|
||||
{
|
||||
return;
|
||||
}
|
||||
let result = if self.primary_thread_id.is_none() && !background_voice {
|
||||
self.enqueue_primary_thread_notification(notification).await
|
||||
} else {
|
||||
self.enqueue_thread_notification(thread_id, notification)
|
||||
.await
|
||||
};
|
||||
|
||||
if let Err(err) = result {
|
||||
tracing::warn!("failed to enqueue app-server notification: {err}");
|
||||
}
|
||||
return;
|
||||
}
|
||||
ServerNotificationThreadTarget::InvalidThreadId(thread_id) => {
|
||||
tracing::warn!(
|
||||
thread_id,
|
||||
"ignoring app-server notification with invalid thread_id"
|
||||
);
|
||||
return;
|
||||
}
|
||||
ServerNotificationThreadTarget::AppScoped => {
|
||||
tracing::debug!(
|
||||
"ignoring app-scoped MCP startup notification without a TUI app-level target"
|
||||
);
|
||||
return;
|
||||
}
|
||||
ServerNotificationThreadTarget::Global => {}
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "windows", test))]
|
||||
if let ServerNotification::WindowsSandboxSetupCompleted(result) = notification {
|
||||
let Some((mode, preset, profile_selection)) =
|
||||
self.windows_sandbox.pending_setup.clone()
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let expected_mode = match mode {
|
||||
WindowsSandboxEnableMode::Elevated => {
|
||||
akode_app_server_protocol::WindowsSandboxSetupMode::Elevated
|
||||
}
|
||||
WindowsSandboxEnableMode::Legacy => {
|
||||
akode_app_server_protocol::WindowsSandboxSetupMode::Unelevated
|
||||
}
|
||||
};
|
||||
if result.mode != expected_mode {
|
||||
return;
|
||||
}
|
||||
if result.success {
|
||||
self.app_event_tx
|
||||
.send(AppEvent::EnableWindowsSandboxForAgentMode {
|
||||
preset,
|
||||
mode,
|
||||
profile_selection,
|
||||
});
|
||||
} else if mode == WindowsSandboxEnableMode::Elevated {
|
||||
self.app_event_tx
|
||||
.send(AppEvent::OpenWindowsSandboxFallbackPrompt {
|
||||
preset,
|
||||
profile_selection,
|
||||
});
|
||||
} else {
|
||||
self.windows_sandbox.pending_setup = None;
|
||||
self.chat_widget.clear_windows_sandbox_setup_status();
|
||||
self.windows_sandbox.setup_started_at = None;
|
||||
if self
|
||||
.chat_widget
|
||||
.recover_inline_permission_profile_selection()
|
||||
{
|
||||
self.app_event_tx.send(AppEvent::SettingsSelectionClosed);
|
||||
} else {
|
||||
self.chat_widget
|
||||
.retain_input_after_failed_permission_selection();
|
||||
}
|
||||
self.chat_widget.add_error_message(format!(
|
||||
"Windows sandbox setup failed: {}",
|
||||
result.error.unwrap_or_else(|| "unknown error".to_string())
|
||||
));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
self.chat_widget
|
||||
.handle_server_notification(notification, /*replay_kind*/ None);
|
||||
}
|
||||
|
||||
pub(in crate::app) async fn handle_server_request_event(
|
||||
&mut self,
|
||||
app_server_client: &AppServerSession,
|
||||
buffered_request: BufferedServerRequest,
|
||||
) {
|
||||
let request = &buffered_request.request;
|
||||
let thread_id = server_request_thread_id(request);
|
||||
if thread_id
|
||||
.is_some_and(|thread_id| self.temporary_structured_requests.contains_key(&thread_id))
|
||||
{
|
||||
self.reject_unsupported_app_server_request(
|
||||
super::app_server_requests::UnsupportedAppServerRequest {
|
||||
request_id: request.id().clone(),
|
||||
message:
|
||||
"temporary structured threads cannot request tools or user interaction"
|
||||
.to_string(),
|
||||
},
|
||||
&buffered_request,
|
||||
)
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
if let ServerRequest::DynamicToolCall { request_id, params } = &request {
|
||||
let tui_tool = params.namespace.as_deref() == Some(crate::dynamic_tools::NAMESPACE);
|
||||
// Another client may own this request on a shared server.
|
||||
if self.dynamic_tool_tasks.contains_key(request_id)
|
||||
|| (!tui_tool && !app_server_client.uses_embedded_app_server())
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let requires_mcp = crate::dynamic_tools::DELEGATION_TOOLS
|
||||
.contains(¶ms.tool.as_str())
|
||||
|| matches!(
|
||||
app_server_client.thread_tool_transport(),
|
||||
crate::dynamic_tools_mcp::ThreadToolTransport::Mcp(_)
|
||||
);
|
||||
if !tui_tool
|
||||
|| requires_mcp
|
||||
|| akode_protocol::ThreadId::from_string(¶ms.thread_id)
|
||||
.is_ok_and(|thread_id| self.abandoned_side_threads.contains(&thread_id))
|
||||
{
|
||||
let response = crate::dynamic_tools::failure_response(if requires_mcp {
|
||||
"TUI task tools require the approval-gated MCP server"
|
||||
} else {
|
||||
"TUI dynamic tools require an active task in the TUI namespace"
|
||||
});
|
||||
self.app_event_tx.send(AppEvent::DynamicToolCallCompleted {
|
||||
request_id: request_id.clone(),
|
||||
response,
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
let request_handle = app_server_client.request_handle();
|
||||
let app_event_tx = self.app_event_tx.clone();
|
||||
let status_updates = self.dynamic_tool_status_updates.subscribe();
|
||||
let request_id = request_id.clone();
|
||||
let task_request_id = request_id.clone();
|
||||
let source_thread_id = params.thread_id.clone();
|
||||
let inherits_task_tools = params.tool == "fork_thread"
|
||||
&& params
|
||||
.arguments
|
||||
.get("threadId")
|
||||
.and_then(serde_json::Value::as_str)
|
||||
.and_then(|thread_id| ThreadId::from_string(thread_id).ok())
|
||||
.is_none_or(|thread_id| app_server_client.task_tools_available(thread_id));
|
||||
let params = params.clone();
|
||||
let mut thread_start_params =
|
||||
crate::app_server_session::thread_start_params_from_config(
|
||||
&self.config,
|
||||
app_server_client.thread_params_mode(),
|
||||
app_server_client.remote_cwd_override(),
|
||||
/*session_start_source*/ None,
|
||||
);
|
||||
app_server_client
|
||||
.thread_tool_transport()
|
||||
.configure(&mut thread_start_params);
|
||||
let task = tokio::spawn(async move {
|
||||
let response = crate::dynamic_tools::execute(
|
||||
request_handle,
|
||||
params,
|
||||
thread_start_params,
|
||||
status_updates,
|
||||
Some(&app_event_tx),
|
||||
)
|
||||
.await;
|
||||
if inherits_task_tools
|
||||
&& response.success
|
||||
&& let [
|
||||
akode_app_server_protocol::DynamicToolCallOutputContentItem::InputText {
|
||||
text,
|
||||
},
|
||||
] = response.content_items.as_slice()
|
||||
&& let Ok(result) = serde_json::from_str::<serde_json::Value>(text)
|
||||
&& let Some(thread_id) =
|
||||
result.get("threadId").and_then(serde_json::Value::as_str)
|
||||
&& let Ok(thread_id) = ThreadId::from_string(thread_id)
|
||||
{
|
||||
app_event_tx.send(AppEvent::TaskToolsAvailable { thread_id });
|
||||
}
|
||||
app_event_tx.send(AppEvent::DynamicToolCallCompleted {
|
||||
request_id,
|
||||
response,
|
||||
});
|
||||
});
|
||||
self.dynamic_tool_tasks
|
||||
.insert(task_request_id, (source_thread_id, task));
|
||||
return;
|
||||
}
|
||||
|
||||
let background_voice = self.background_voice.as_ref().is_some_and(|owner| {
|
||||
owner.realtime_conversation_is_running()
|
||||
&& owner.thread_id().is_some()
|
||||
&& owner.thread_id() == thread_id
|
||||
});
|
||||
if thread_id.is_some_and(|thread_id| self.abandoned_side_threads.contains(&thread_id)) {
|
||||
self.reject_unsupported_app_server_request(
|
||||
super::app_server_requests::UnsupportedAppServerRequest {
|
||||
request_id: request.id().clone(),
|
||||
message: "side conversation was closed".to_string(),
|
||||
},
|
||||
&buffered_request,
|
||||
)
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
if thread_id.is_some()
|
||||
&& self.primary_thread_id.is_none()
|
||||
&& !background_voice
|
||||
&& self.pending_startup_thread_start
|
||||
{
|
||||
if let Some(unsupported) = self
|
||||
.pending_app_server_requests
|
||||
.note_buffered_request(&buffered_request)
|
||||
{
|
||||
self.reject_unsupported_app_server_request(unsupported, &buffered_request)
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
self.pending_primary_events
|
||||
.push_back(ThreadBufferedEvent::Request(Box::new(
|
||||
buffered_request.request,
|
||||
)));
|
||||
return;
|
||||
}
|
||||
let unsupported_request = matches!(
|
||||
&request,
|
||||
ServerRequest::DynamicToolCall { .. }
|
||||
| ServerRequest::CurrentTimeRead { .. }
|
||||
| ServerRequest::ApplyPatchApproval { .. }
|
||||
| ServerRequest::ExecCommandApproval { .. }
|
||||
);
|
||||
if let ServerRequest::PermissionsRequestApproval { request_id, params } = &request
|
||||
&& let Err(err) = CoreRequestPermissionProfile::try_from(params.permissions.clone())
|
||||
{
|
||||
self.reject_unsupported_app_server_request(
|
||||
super::app_server_requests::UnsupportedAppServerRequest {
|
||||
request_id: request_id.clone(),
|
||||
message: format!("failed to localize requested filesystem paths: {err}"),
|
||||
},
|
||||
&buffered_request,
|
||||
)
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
if self
|
||||
.pending_app_server_requests
|
||||
.contains_server_request(request)
|
||||
{
|
||||
return;
|
||||
}
|
||||
if let Some(thread_id) = thread_id
|
||||
&& self.primary_thread_id != Some(thread_id)
|
||||
&& self.active_thread_id != Some(thread_id)
|
||||
&& !unsupported_request
|
||||
&& !background_voice
|
||||
&& let Some(requests) = self.agents_overview.dispatched_requests.get_mut(&thread_id)
|
||||
{
|
||||
requests.push(buffered_request);
|
||||
return;
|
||||
}
|
||||
if thread_id.is_some()
|
||||
&& self.primary_thread_id.is_none()
|
||||
&& !background_voice
|
||||
&& !self.pending_startup_thread_start
|
||||
&& !unsupported_request
|
||||
{
|
||||
return;
|
||||
}
|
||||
if let Some(thread_id) = thread_id
|
||||
&& self.primary_thread_id.is_some()
|
||||
&& self.primary_thread_id != Some(thread_id)
|
||||
&& !self.thread_event_channels.contains_key(&thread_id)
|
||||
&& self.agent_navigation.get(&thread_id).is_none()
|
||||
&& !self.side_threads.contains_key(&thread_id)
|
||||
&& !unsupported_request
|
||||
{
|
||||
let thread = app_server_client
|
||||
.request_handle()
|
||||
.request_typed::<ThreadReadResponse>(ClientRequest::ThreadRead {
|
||||
request_id: RequestId::String(format!("subagent-approval-{thread_id}")),
|
||||
params: ThreadReadParams {
|
||||
thread_id: thread_id.to_string(),
|
||||
include_turns: false,
|
||||
},
|
||||
})
|
||||
.await;
|
||||
let Ok(ThreadReadResponse { thread, .. }) = thread else {
|
||||
return;
|
||||
};
|
||||
let SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
|
||||
parent_thread_id, ..
|
||||
}) = thread.source
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if !self.owns_thread_for_routing(parent_thread_id) {
|
||||
if self
|
||||
.agents_overview
|
||||
.dispatched_requests
|
||||
.contains_key(&parent_thread_id)
|
||||
{
|
||||
self.agents_overview
|
||||
.dispatched_requests
|
||||
.entry(thread_id)
|
||||
.or_default()
|
||||
.push(buffered_request);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
let unsupported = self
|
||||
.pending_app_server_requests
|
||||
.note_buffered_request(&buffered_request);
|
||||
if let Some(unsupported) = unsupported {
|
||||
self.reject_unsupported_app_server_request(unsupported, &buffered_request)
|
||||
.await;
|
||||
return;
|
||||
}
|
||||
|
||||
let Some(thread_id) = thread_id else {
|
||||
tracing::warn!("ignoring threadless app-server request");
|
||||
return;
|
||||
};
|
||||
|
||||
let result = if self.primary_thread_id.is_none() && !background_voice {
|
||||
self.enqueue_primary_thread_request(buffered_request.request)
|
||||
.await
|
||||
} else {
|
||||
self.enqueue_thread_request(thread_id, buffered_request.request)
|
||||
.await
|
||||
};
|
||||
if let Err(err) = result {
|
||||
tracing::warn!("failed to enqueue app-server request: {err}");
|
||||
}
|
||||
}
|
||||
}
|
||||
1185
akode-rs/tui/src/app/app_server_requests.rs
Normal file
1185
akode-rs/tui/src/app/app_server_requests.rs
Normal file
File diff suppressed because it is too large
Load Diff
83
akode-rs/tui/src/app/app_server_thread_ownership.rs
Normal file
83
akode-rs/tui/src/app/app_server_thread_ownership.rs
Normal file
@@ -0,0 +1,83 @@
|
||||
//! Ownership checks for routing app-server events to a TUI root.
|
||||
|
||||
use super::App;
|
||||
use crate::app_server_session::AppServerSession;
|
||||
use akode_app_server_client::TypedRequestError;
|
||||
use akode_app_server_protocol::ClientRequest;
|
||||
use akode_app_server_protocol::RequestId;
|
||||
use akode_app_server_protocol::ServerNotification;
|
||||
use akode_app_server_protocol::SessionSource;
|
||||
use akode_app_server_protocol::ThreadReadParams;
|
||||
use akode_app_server_protocol::ThreadReadResponse;
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_protocol::protocol::SubAgentSource;
|
||||
use std::time::Duration;
|
||||
|
||||
async fn read_mcp_subagent_parent_thread_id(
|
||||
app_server_client: &AppServerSession,
|
||||
thread_id: ThreadId,
|
||||
) -> Option<ThreadId> {
|
||||
let response = tokio::time::timeout(Duration::from_secs(/*secs*/ 1), async {
|
||||
let mut retry_delay = Duration::from_millis(50);
|
||||
loop {
|
||||
match app_server_client
|
||||
.request_handle()
|
||||
.request_typed::<ThreadReadResponse>(ClientRequest::ThreadRead {
|
||||
request_id: RequestId::String(uuid::Uuid::new_v4().to_string()),
|
||||
params: ThreadReadParams {
|
||||
thread_id: thread_id.to_string(),
|
||||
include_turns: false,
|
||||
},
|
||||
})
|
||||
.await
|
||||
{
|
||||
Ok(response) => return Some(response),
|
||||
Err(TypedRequestError::Server { source, .. })
|
||||
if source.message.starts_with("thread not found:")
|
||||
|| source.message.starts_with("thread not loaded:") =>
|
||||
{
|
||||
tokio::time::sleep(retry_delay).await;
|
||||
retry_delay = retry_delay.saturating_mul(2).min(Duration::from_secs(1));
|
||||
}
|
||||
Err(_) => return None,
|
||||
}
|
||||
}
|
||||
})
|
||||
.await
|
||||
.ok()??;
|
||||
subagent_parent(&response.thread.source)
|
||||
}
|
||||
|
||||
fn subagent_parent(source: &SessionSource) -> Option<ThreadId> {
|
||||
match source {
|
||||
SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
|
||||
parent_thread_id, ..
|
||||
}) => Some(*parent_thread_id),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub(super) fn owns_thread_for_routing(&self, thread_id: ThreadId) -> bool {
|
||||
self.primary_thread_id == Some(thread_id)
|
||||
|| self.thread_event_channels.contains_key(&thread_id)
|
||||
|| self.side_threads.contains_key(&thread_id)
|
||||
|| self.agent_navigation.get(&thread_id).is_some()
|
||||
}
|
||||
|
||||
pub(super) async fn owns_untracked_notification(
|
||||
&self,
|
||||
app_server_client: &AppServerSession,
|
||||
thread_id: ThreadId,
|
||||
notification: &ServerNotification,
|
||||
) -> bool {
|
||||
let parent_thread_id = match notification {
|
||||
ServerNotification::ThreadStarted(started) => subagent_parent(&started.thread.source),
|
||||
ServerNotification::McpServerStatusUpdated(_) => {
|
||||
read_mcp_subagent_parent_thread_id(app_server_client, thread_id).await
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
parent_thread_id.is_some_and(|thread_id| self.owns_thread_for_routing(thread_id))
|
||||
}
|
||||
}
|
||||
45
akode-rs/tui/src/app/backend_events.rs
Normal file
45
akode-rs/tui/src/app/backend_events.rs
Normal file
@@ -0,0 +1,45 @@
|
||||
//! Checks incoming event ownership before consulting native-thread caches or UI state.
|
||||
//! Connection-wide lifecycle and account events may only update the displayed conversation's UI.
|
||||
|
||||
use super::App;
|
||||
use super::app_server_event_targets::ServerNotificationThreadTarget;
|
||||
use super::app_server_event_targets::server_notification_thread_target;
|
||||
use crate::app_server_session::AppServerSession;
|
||||
use crate::app_server_session::AppServerSessionEvent;
|
||||
use crate::backend_id::BackendId;
|
||||
use akode_app_server_client::AppServerEvent;
|
||||
|
||||
impl App {
|
||||
pub(super) async fn handle_polled_backend_event(
|
||||
&mut self,
|
||||
app_server: &AppServerSession,
|
||||
displayed_owner: BackendId,
|
||||
event: AppServerSessionEvent,
|
||||
) {
|
||||
if displayed_owner != event.backend_id {
|
||||
// A parked voice session still needs its own notifications.
|
||||
if event.backend_id == app_server.backend_id()
|
||||
&& let AppServerEvent::ServerNotification(notification) = &event.event
|
||||
&& let ServerNotificationThreadTarget::Thread(thread_id) =
|
||||
server_notification_thread_target(notification)
|
||||
&& self.voice_owner_thread_id() == Some(thread_id)
|
||||
{
|
||||
self.deliver_background_voice_notification(thread_id, notification);
|
||||
}
|
||||
return;
|
||||
}
|
||||
self.handle_backend_event(app_server, event).await;
|
||||
}
|
||||
|
||||
pub(super) async fn handle_backend_event(
|
||||
&mut self,
|
||||
app_server: &AppServerSession,
|
||||
event: AppServerSessionEvent,
|
||||
) {
|
||||
if event.backend_id != app_server.backend_id() {
|
||||
tracing::warn!("ignoring server event from a different backend");
|
||||
return;
|
||||
}
|
||||
self.handle_app_server_event(app_server, event.event).await;
|
||||
}
|
||||
}
|
||||
489
akode-rs/tui/src/app/backend_selection.rs
Normal file
489
akode-rs/tui/src/app/backend_selection.rs
Normal file
@@ -0,0 +1,489 @@
|
||||
//! Prepare conversations through their owning backend before replacing the UI.
|
||||
|
||||
use super::backend_sessions::BackendSessions;
|
||||
use super::backend_sessions::SessionSlot;
|
||||
use super::cloud_switch_wait::ClipboardHandoff;
|
||||
use super::cloud_switch_wait::finish_failed_cloud_switch;
|
||||
use super::cloud_switch_wait::wait_for_cloud_switch;
|
||||
use super::resume_preparation::ResumeSource;
|
||||
use super::session_lifecycle::PreparedFreshSession;
|
||||
use super::session_lifecycle::ThreadAttachPresentation;
|
||||
use super::*;
|
||||
use akode_app_server_protocol::ThreadItemPayload;
|
||||
use futures::TryFutureExt;
|
||||
|
||||
pub(super) enum NewBackendSession {
|
||||
Fresh { name: Option<String> },
|
||||
CarryDraft,
|
||||
}
|
||||
|
||||
/// Host inputs for the new-thread preference. A cloud thread's cwd and credentials
|
||||
/// belong to the executor and must never determine where this preference is saved.
|
||||
pub(crate) struct BackendPreferenceContext {
|
||||
pub(crate) local_cwd: Option<PathBuf>,
|
||||
project_root_markers: Vec<String>,
|
||||
}
|
||||
|
||||
impl BackendPreferenceContext {
|
||||
pub(crate) fn new(config: &Config, local_cwd: Option<PathBuf>) -> Self {
|
||||
let project_root_markers = config
|
||||
.config_layer_stack
|
||||
.layers_high_to_low()
|
||||
.filter(|layer| !matches!(layer.name, akode_config::ConfigLayerSource::Project { .. }))
|
||||
.find_map(|layer| {
|
||||
akode_config::project_root_markers_from_config(&layer.config)
|
||||
.ok()
|
||||
.flatten()
|
||||
})
|
||||
.unwrap_or_else(akode_config::default_project_root_markers);
|
||||
Self {
|
||||
local_cwd,
|
||||
project_root_markers,
|
||||
}
|
||||
}
|
||||
|
||||
async fn scope(&self) -> Option<(String, String)> {
|
||||
let cwd = AbsolutePathBuf::from_absolute_path(self.local_cwd.as_deref()?).ok()?;
|
||||
let project = akode_config::loader::find_project_root(
|
||||
akode_exec_server::LOCAL_FS.as_ref(),
|
||||
&cwd,
|
||||
&self.project_root_markers,
|
||||
)
|
||||
.await
|
||||
.ok()?;
|
||||
// Credentials carry no account identity; a local profile is already private
|
||||
// to its AKODE_HOME.
|
||||
let user = "local".to_string();
|
||||
Some((
|
||||
akode_config::loader::project_trust_key(project.as_path()),
|
||||
user,
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub(super) fn remember_attached_host_project(&mut self, app_server: &AppServerSession) {
|
||||
if !app_server.uses_remote_workspace()
|
||||
&& !crate::uses_remote_workspace_or_environment(
|
||||
&self.app_server_target,
|
||||
&self.environment_manager,
|
||||
)
|
||||
{
|
||||
self.backend_preference_context.local_cwd =
|
||||
Some(self.chat_widget.config_ref().cwd.to_path_buf());
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn new_thread_host_preference(&self) -> Option<&str> {
|
||||
let defaults = &self.local_settings.tui.default_hosts;
|
||||
if defaults.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let (project, user) = self.backend_preference_context.scope().await?;
|
||||
defaults.get(&project)?.get(&user).map(String::as_str)
|
||||
}
|
||||
|
||||
pub(super) async fn other_new_session_backend(
|
||||
&self,
|
||||
backends: &BackendSessions,
|
||||
) -> Option<crate::backend_id::BackendId> {
|
||||
backends
|
||||
.preferred_listening_backend(self.new_thread_host_preference().await)
|
||||
.filter(|owner| *owner != backends.displayed_owner())
|
||||
}
|
||||
|
||||
pub(super) fn can_cycle_conversation_backend(&self) -> bool {
|
||||
self.voice_owner_thread_id().is_none()
|
||||
&& self.chat_widget.can_choose_new_backend()
|
||||
&& self
|
||||
.current_displayed_thread_id()
|
||||
.and_then(|id| self.thread_event_channels.get(&id))
|
||||
.and_then(|channel| channel.store.try_lock().ok())
|
||||
.is_some_and(|store| store.session.is_some() && store.latest_turn_id.is_none())
|
||||
}
|
||||
|
||||
pub(super) async fn start_new_session_on_other_backend(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
backends: &mut BackendSessions,
|
||||
owner: crate::backend_id::BackendId,
|
||||
session: NewBackendSession,
|
||||
) -> Result<(), String> {
|
||||
let slot = backends
|
||||
.listening_slot(owner)
|
||||
.ok_or("That connection is unavailable. Choose another and try again.")?;
|
||||
if self.windows_sandbox_blocks_thread_switch()
|
||||
|| self.reject_pending_permission_root_switch()
|
||||
{
|
||||
return Ok(());
|
||||
}
|
||||
if self.voice_owner_thread_id().is_some() {
|
||||
return Err("End the voice call before switching.".into());
|
||||
}
|
||||
let displayed_thread = self.current_displayed_thread_id();
|
||||
let outgoing_slot = backends.displayed;
|
||||
if let Some(thread_id) = displayed_thread
|
||||
&& self.active_turn_id_for_thread(thread_id).await.is_some()
|
||||
{
|
||||
return Err("Wait for the current turn to finish before switching.".into());
|
||||
}
|
||||
let mut settings = backends
|
||||
.settings
|
||||
.get(&owner)
|
||||
.cloned()
|
||||
.ok_or("Connection settings are unavailable.")?;
|
||||
if settings.target == AppServerTarget::Cloud && self.chat_widget.thread_id().is_some() {
|
||||
self.remember_attached_host_project(backends.session_at(outgoing_slot));
|
||||
}
|
||||
let preference = if matches!(session, NewBackendSession::CarryDraft)
|
||||
&& let Some(key) = backends.preference_key(slot)
|
||||
{
|
||||
self.backend_preference_context
|
||||
.scope()
|
||||
.await
|
||||
.map(|(project, user)| (project, user, key.to_owned()))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let user_config_path = self.local_settings.user_config_path.clone();
|
||||
let responsive_cloud_switch = settings.target == AppServerTarget::Cloud
|
||||
&& matches!(session, NewBackendSession::CarryDraft);
|
||||
let (name, mut draft) = match session {
|
||||
NewBackendSession::Fresh { name } => (name, None),
|
||||
NewBackendSession::CarryDraft => (
|
||||
self.chat_widget.thread_name(),
|
||||
(!responsive_cloud_switch).then(|| self.chat_widget.composer_draft_snapshot()),
|
||||
),
|
||||
};
|
||||
let destination = backends.session_at_mut(slot);
|
||||
let clipboard_after_bootstrap = if destination.remote_cwd_override().is_some() {
|
||||
// An explicit remote directory can open the trust prompt after bootstrap.
|
||||
ClipboardHandoff::SettleBeforeNextView
|
||||
} else {
|
||||
ClipboardHandoff::ContinueEditing
|
||||
};
|
||||
let bootstrap = destination
|
||||
.bootstrap_for_new_thread(&settings.config)
|
||||
.map_err(|error| format!("Failed to prepare the new conversation: {error}"));
|
||||
let bootstrap = if responsive_cloud_switch {
|
||||
let events = tui.event_stream();
|
||||
wait_for_cloud_switch(self, tui, bootstrap, events, clipboard_after_bootstrap).await
|
||||
} else {
|
||||
bootstrap.await
|
||||
}?;
|
||||
let destination_cwd = settings.config.cwd.to_path_buf();
|
||||
if let Err(control) = self
|
||||
.confirm_directory_trust_for_target(
|
||||
tui,
|
||||
destination,
|
||||
&settings.target,
|
||||
&settings.local_settings,
|
||||
&mut settings.config,
|
||||
&destination_cwd,
|
||||
crate::onboarding::DirectoryTrustOptions {
|
||||
cancel: displayed_thread
|
||||
.map(|_| crate::onboarding::TrustCancelAction::CurrentTask),
|
||||
..Default::default()
|
||||
},
|
||||
/*startup_draft*/ None,
|
||||
)
|
||||
.await
|
||||
{
|
||||
if responsive_cloud_switch {
|
||||
let events = tui.event_stream();
|
||||
finish_failed_cloud_switch(self, tui, events).await;
|
||||
}
|
||||
if matches!(control, AppRunControl::Exit(_)) {
|
||||
self.app_event_tx.send(AppEvent::Exit(ExitMode::Immediate));
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
let (config, local_settings) = self
|
||||
.load_new_session_config_from(
|
||||
destination,
|
||||
&settings,
|
||||
destination_cwd,
|
||||
responsive_cloud_switch.then_some(&mut *tui),
|
||||
)
|
||||
.await
|
||||
.map_err(|error| format!("Failed to read new session defaults: {error}"))?;
|
||||
let host_project_cwd = self.backend_preference_context.local_cwd.clone();
|
||||
let start = destination
|
||||
.start_thread_with_session_start_source(
|
||||
&local_settings,
|
||||
&config,
|
||||
/*session_start_source*/ None,
|
||||
/*remote_cwd_override*/ None,
|
||||
/*selected_profile*/ None,
|
||||
host_project_cwd.as_deref(),
|
||||
)
|
||||
.map_err(|error| format!("Failed to start the new conversation: {error}"));
|
||||
let started = if responsive_cloud_switch {
|
||||
let events = tui.event_stream();
|
||||
wait_for_cloud_switch(
|
||||
self,
|
||||
tui,
|
||||
start,
|
||||
events,
|
||||
ClipboardHandoff::SettleBeforeNextView,
|
||||
)
|
||||
.await
|
||||
} else {
|
||||
start.await
|
||||
}?;
|
||||
if responsive_cloud_switch {
|
||||
draft = Some(self.chat_widget.composer_draft_snapshot());
|
||||
}
|
||||
// Clear before switching so a terminal error leaves the outgoing conversation usable.
|
||||
if let Err(error) = tui.clear_for_thread_switch() {
|
||||
if responsive_cloud_switch {
|
||||
let events = tui.event_stream();
|
||||
finish_failed_cloud_switch(self, tui, events).await;
|
||||
}
|
||||
return Err(format!("Failed to open the new conversation: {error}"));
|
||||
}
|
||||
let destination_thread = started.session.thread_id;
|
||||
self.switch_backend_context(
|
||||
backends,
|
||||
slot,
|
||||
started.session.thread_id,
|
||||
settings.target,
|
||||
config.cwd.to_path_buf(),
|
||||
bootstrap,
|
||||
)
|
||||
.await;
|
||||
let destination = backends.session_at_mut(slot);
|
||||
self.adopt_fresh_session(
|
||||
tui,
|
||||
destination,
|
||||
PreparedFreshSession {
|
||||
started,
|
||||
config,
|
||||
local_settings,
|
||||
},
|
||||
ThreadAttachPresentation::FreshAfterClear,
|
||||
/*initial_user_message*/ None,
|
||||
name,
|
||||
)
|
||||
.await;
|
||||
backends.displayed = slot;
|
||||
if !backends.session_at_mut(slot).uses_remote_workspace()
|
||||
&& self.current_displayed_thread_id() == Some(destination_thread)
|
||||
{
|
||||
let cwd = self.config.cwd.to_path_buf();
|
||||
self.review_folder_hooks_after_attach(backends.session_at_mut(slot), cwd)
|
||||
.await;
|
||||
}
|
||||
tui.set_notification_settings(
|
||||
self.local_settings.tui.notification_settings.method,
|
||||
self.local_settings.tui.notification_settings.condition,
|
||||
);
|
||||
if let Some(draft) = draft {
|
||||
if responsive_cloud_switch {
|
||||
self.chat_widget.restore_cloud_switch_draft(draft);
|
||||
} else {
|
||||
self.chat_widget.restore_startup_draft(draft);
|
||||
}
|
||||
if let Some(thread_id) = displayed_thread
|
||||
&& self.current_displayed_thread_id() == Some(destination_thread)
|
||||
&& self
|
||||
.agents_overview
|
||||
.blank_sessions
|
||||
.remove(&thread_id)
|
||||
.is_some()
|
||||
{
|
||||
self.agents_overview.input_states.remove(&thread_id);
|
||||
self.remove_agents_overview_thread(thread_id);
|
||||
if let Err(error) = backends
|
||||
.session_at_mut(outgoing_slot)
|
||||
.thread_unsubscribe(thread_id)
|
||||
.await
|
||||
{
|
||||
tracing::warn!(%error, "failed to unsubscribe replaced blank thread {thread_id}");
|
||||
}
|
||||
self.discard_thread_local_state(thread_id).await;
|
||||
}
|
||||
}
|
||||
if self.current_displayed_thread_id() == Some(destination_thread)
|
||||
&& let Some((project, user, key)) = preference
|
||||
{
|
||||
let result = ConfigEditsBuilder::for_config_path(user_config_path.as_path())
|
||||
.with_edits([crate::legacy_core::config::edit::ConfigEdit::SetPath {
|
||||
segments: vec![
|
||||
"tui".into(),
|
||||
"default_hosts".into(),
|
||||
project.clone(),
|
||||
user.clone(),
|
||||
],
|
||||
value: toml_edit::value(key.clone()),
|
||||
}])
|
||||
.apply()
|
||||
.await;
|
||||
match result {
|
||||
Ok(()) => {
|
||||
for settings in std::iter::once(&mut self.local_settings).chain(
|
||||
backends
|
||||
.settings
|
||||
.values_mut()
|
||||
.map(|settings| &mut settings.local_settings),
|
||||
) {
|
||||
settings
|
||||
.tui
|
||||
.default_hosts
|
||||
.entry(project.clone())
|
||||
.or_default()
|
||||
.insert(user.clone(), key.clone());
|
||||
}
|
||||
}
|
||||
Err(error) => self.chat_widget.add_error_message(format!(
|
||||
"Switched, but could not save the default for this project: {error}"
|
||||
)),
|
||||
}
|
||||
}
|
||||
tui.frame_requester().schedule_frame();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// Both create and resume call this after the destination thread is ready.
|
||||
async fn switch_backend_context(
|
||||
&mut self,
|
||||
backends: &mut BackendSessions,
|
||||
destination_slot: SessionSlot,
|
||||
thread_id: ThreadId,
|
||||
target: AppServerTarget,
|
||||
cwd: PathBuf,
|
||||
bootstrap: AppServerBootstrap,
|
||||
) {
|
||||
let outgoing = backends.displayed_owner();
|
||||
self.capture_session_inputs().await;
|
||||
for channel in self.thread_event_channels.values_mut() {
|
||||
channel.backend_id.get_or_insert(outgoing);
|
||||
}
|
||||
backends.settings.insert(outgoing, self.backend_settings());
|
||||
self.detach_current_thread_for_navigation(
|
||||
backends.session_at_mut(backends.displayed),
|
||||
Some(thread_id),
|
||||
)
|
||||
.await;
|
||||
let destination = backends.session_at_mut(destination_slot);
|
||||
self.store_active_thread_receiver().await;
|
||||
self.clear_active_thread().await;
|
||||
self.agents_overview.search_matches.clear();
|
||||
self.app_event_tx = AppEventSender::new(self.app_event_tx.app_event_tx.clone());
|
||||
self.app_server_target = target;
|
||||
self.reconnect = Default::default();
|
||||
if let Ok(mut state) = self.agents_overview.view_state.lock() {
|
||||
state.connection_notice = None;
|
||||
state.restart_history_search();
|
||||
}
|
||||
self.file_search.on_user_query(String::new());
|
||||
self.bind_backend_workspace(destination, cwd);
|
||||
self.model_catalog = Arc::new(
|
||||
ModelCatalog::new(bootstrap.available_models)
|
||||
.for_backend(destination.backend_id(), &mut self.provider_writes)
|
||||
.with_collaboration_modes(bootstrap.collaboration_modes),
|
||||
);
|
||||
self.chat_widget.requires_openai_auth = bootstrap.requires_openai_auth;
|
||||
self.chat_widget
|
||||
.update_account_state(bootstrap.status_account_display);
|
||||
}
|
||||
|
||||
pub(super) fn resume_backend_session<'a>(
|
||||
&'a mut self,
|
||||
tui: &'a mut tui::Tui,
|
||||
backends: &'a mut BackendSessions,
|
||||
target: SessionTarget,
|
||||
) -> futures::future::LocalBoxFuture<'a, Result<AppRunControl>> {
|
||||
Box::pin(async move {
|
||||
let displayed_session = backends.displayed;
|
||||
let owner = target.backend_id;
|
||||
let outgoing = backends.displayed_owner();
|
||||
if owner == outgoing {
|
||||
return self
|
||||
.apply_resume_picker_selection(
|
||||
tui,
|
||||
backends.session_at_mut(displayed_session),
|
||||
SessionSelection::Resume(target),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
if self.windows_sandbox_blocks_thread_switch()
|
||||
|| self.reject_pending_permission_root_switch()
|
||||
{
|
||||
return Ok(AppRunControl::Continue);
|
||||
}
|
||||
if let Some(thread_id) = self.current_displayed_thread_id()
|
||||
&& self.active_turn_id_for_thread(thread_id).await.is_some()
|
||||
{
|
||||
self.add_session_picker_error(
|
||||
"Wait for the current turn to finish before switching.".into(),
|
||||
);
|
||||
return Ok(AppRunControl::Continue);
|
||||
}
|
||||
let Some(settings) = backends.settings.get(&owner).cloned() else {
|
||||
self.add_session_picker_error(
|
||||
"Connection settings are unavailable. Open the session picker again.".into(),
|
||||
);
|
||||
return Ok(AppRunControl::Continue);
|
||||
};
|
||||
let Some(destination_slot) = backends.listening_slot(owner) else {
|
||||
self.add_session_picker_error(
|
||||
"The connection for this conversation is unavailable. Open the session picker again.".into(),
|
||||
);
|
||||
return Ok(AppRunControl::Continue);
|
||||
};
|
||||
let destination = backends.session_at_mut(destination_slot);
|
||||
let bootstrap = match destination.bootstrap(&settings.config).await {
|
||||
Ok(bootstrap) => bootstrap,
|
||||
Err(error) => {
|
||||
let message = format!("Failed to prepare the conversation: {error}");
|
||||
self.add_session_picker_error(message);
|
||||
return Ok(AppRunControl::Continue);
|
||||
}
|
||||
};
|
||||
let prepared = match self
|
||||
.prepare_target_session(tui, destination, &target, ResumeSource::Backend(&settings))
|
||||
.await
|
||||
{
|
||||
Ok(prepared) => prepared,
|
||||
Err(control) => return Ok(control),
|
||||
};
|
||||
self.switch_backend_context(
|
||||
backends,
|
||||
destination_slot,
|
||||
target.thread_id,
|
||||
settings.target,
|
||||
prepared.config.cwd.to_path_buf(),
|
||||
bootstrap,
|
||||
)
|
||||
.await;
|
||||
let destination = backends.session_at_mut(destination_slot);
|
||||
let thread_id = target.thread_id;
|
||||
if let Some(input) = self.agents_overview.input_states.get_mut(&thread_id) {
|
||||
input.provider_error = None;
|
||||
for item in prepared.thread.turns.iter().flat_map(Turn::item_payloads) {
|
||||
if let ThreadItemPayload::UserMessage {
|
||||
client_id: Some(id),
|
||||
..
|
||||
} = item
|
||||
{
|
||||
input.pending_steers.retain(|steer| steer.client_id != *id);
|
||||
}
|
||||
}
|
||||
}
|
||||
let control = self
|
||||
.activate_prepared_session(tui, destination, prepared)
|
||||
.await?;
|
||||
backends.displayed = destination_slot;
|
||||
if let Some(mut input) = self.agents_overview.input_states.remove(&thread_id) {
|
||||
let blank = self.agents_overview.blank_sessions.contains_key(&thread_id);
|
||||
let settings = blank
|
||||
.then(|| input.pending_thread_settings.take())
|
||||
.flatten();
|
||||
self.restore_session_draft(thread_id, input, settings).await;
|
||||
}
|
||||
tui.frame_requester().schedule_frame();
|
||||
Ok(control)
|
||||
})
|
||||
}
|
||||
}
|
||||
310
akode-rs/tui/src/app/backend_sessions.rs
Normal file
310
akode-rs/tui/src/app/backend_sessions.rs
Normal file
@@ -0,0 +1,310 @@
|
||||
//! Owns backend sessions independently of the displayed conversation's UI state.
|
||||
//! Polling is fair and cancellation-safe; closing one stream never closes another.
|
||||
|
||||
use super::resume_preparation::BackendSettings;
|
||||
use crate::AppServerTarget;
|
||||
use crate::app_server_session::AppServerSession;
|
||||
use crate::app_server_session::AppServerSessionEvent;
|
||||
use crate::backend_id::BackendId;
|
||||
#[cfg(test)]
|
||||
use crate::legacy_core::config::Config;
|
||||
#[cfg(test)]
|
||||
use crate::local_settings::LocalSettings;
|
||||
use akode_app_server_client::AppServerEvent;
|
||||
use akode_app_server_protocol::ServerNotification;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::VecDeque;
|
||||
use std::future::Future;
|
||||
use std::task::Poll;
|
||||
|
||||
type BackendSettingsById = HashMap<BackendId, BackendSettings>;
|
||||
|
||||
/// The initial conventional session and any additional sessions registered at launch.
|
||||
pub(crate) struct InitialBackendSessions {
|
||||
initial: AppServerSession,
|
||||
others: Vec<AppServerSession>,
|
||||
settings: BackendSettingsById,
|
||||
}
|
||||
|
||||
impl InitialBackendSessions {
|
||||
pub(crate) fn singleton(initial: AppServerSession) -> Self {
|
||||
Self {
|
||||
initial,
|
||||
others: Vec::new(),
|
||||
settings: HashMap::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn register(
|
||||
&mut self,
|
||||
connection: AppServerSession,
|
||||
target: AppServerTarget,
|
||||
config: Config,
|
||||
local_settings: LocalSettings,
|
||||
) {
|
||||
self.settings.insert(
|
||||
connection.backend_id(),
|
||||
BackendSettings {
|
||||
target,
|
||||
config,
|
||||
local_settings,
|
||||
},
|
||||
);
|
||||
self.others.push(connection);
|
||||
}
|
||||
|
||||
pub(super) fn into_parts(
|
||||
self,
|
||||
) -> (AppServerSession, Vec<AppServerSession>, BackendSettingsById) {
|
||||
(self.initial, self.others, self.settings)
|
||||
}
|
||||
}
|
||||
|
||||
struct SessionEntry {
|
||||
// Stable, nonsecret name supplied by the registrar for this logical app-server.
|
||||
preference_key: Option<String>,
|
||||
session: AppServerSession,
|
||||
listening: bool,
|
||||
pending_events: VecDeque<AppServerSessionEvent>,
|
||||
side_startup: Vec<AppServerSessionEvent>,
|
||||
}
|
||||
|
||||
/// A session's stable position in an append-only backend collection.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct SessionSlot(usize);
|
||||
|
||||
pub(super) struct BackendSessions {
|
||||
entries: Vec<SessionEntry>,
|
||||
pub(super) displayed: SessionSlot,
|
||||
pub(super) settings: HashMap<BackendId, BackendSettings>,
|
||||
next_source: usize,
|
||||
}
|
||||
|
||||
impl BackendSessions {
|
||||
pub(super) fn from_initial(initial: AppServerSession, others: Vec<AppServerSession>) -> Self {
|
||||
let mut sessions = Self::new(initial);
|
||||
for session in others {
|
||||
sessions.insert(session);
|
||||
}
|
||||
sessions
|
||||
}
|
||||
|
||||
pub(super) fn new(session: AppServerSession) -> Self {
|
||||
let mut sessions = Self {
|
||||
entries: Vec::new(),
|
||||
displayed: SessionSlot(0),
|
||||
settings: HashMap::new(),
|
||||
next_source: 0,
|
||||
};
|
||||
sessions.insert(session);
|
||||
sessions
|
||||
}
|
||||
|
||||
pub(super) fn insert(&mut self, session: AppServerSession) {
|
||||
assert!(self.session(session.backend_id()).is_none());
|
||||
self.entries.push(SessionEntry {
|
||||
preference_key: None,
|
||||
session,
|
||||
listening: true,
|
||||
pending_events: VecDeque::new(),
|
||||
side_startup: Vec::new(),
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn session(&self, owner: BackendId) -> Option<&AppServerSession> {
|
||||
self.slot(owner).map(|slot| self.session_at(slot))
|
||||
}
|
||||
|
||||
pub(super) fn slot(&self, owner: BackendId) -> Option<SessionSlot> {
|
||||
self.entries
|
||||
.iter()
|
||||
.position(|entry| entry.session.backend_id() == owner)
|
||||
.map(SessionSlot)
|
||||
}
|
||||
|
||||
pub(super) fn session_at(&self, slot: SessionSlot) -> &AppServerSession {
|
||||
&self.entries[slot.0].session
|
||||
}
|
||||
|
||||
pub(super) fn displayed_owner(&self) -> BackendId {
|
||||
self.session_at(self.displayed).backend_id()
|
||||
}
|
||||
|
||||
pub(super) fn picker_views(&self) -> Vec<AppServerSession> {
|
||||
let displayed_owner = self.displayed_owner();
|
||||
self.entries
|
||||
.iter()
|
||||
.filter(|entry| entry.listening || entry.session.backend_id() == displayed_owner)
|
||||
.map(|entry| entry.session.request_view())
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn displayed_name(&self, target: &AppServerTarget) -> Option<String> {
|
||||
let slot = self.displayed.0;
|
||||
self.entries[slot].listening.then(|| match (target, slot) {
|
||||
(AppServerTarget::Cloud, _) => "Cloud".to_string(),
|
||||
(_, 0) => "Local".to_string(),
|
||||
(_, index) => format!("Connection {}", index + 1),
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn set_preference_key(&mut self, owner: BackendId, key: &str) {
|
||||
#[expect(
|
||||
clippy::expect_used,
|
||||
reason = "preference keys are assigned only after the backend is registered"
|
||||
)]
|
||||
let slot = self.slot(owner).expect("registered app-server");
|
||||
assert!(
|
||||
!key.is_empty()
|
||||
&& key
|
||||
.bytes()
|
||||
.all(|c| c.is_ascii_alphanumeric() || b"._-".contains(&c))
|
||||
);
|
||||
assert!(
|
||||
self.entries
|
||||
.iter()
|
||||
.all(|entry| entry.preference_key.as_deref() != Some(key))
|
||||
);
|
||||
assert!(self.preference_key(slot).is_none());
|
||||
self.entries[slot.0].preference_key = Some(key.to_owned());
|
||||
}
|
||||
|
||||
pub(super) fn preference_key(&self, slot: SessionSlot) -> Option<&str> {
|
||||
self.entries[slot.0].preference_key.as_deref()
|
||||
}
|
||||
|
||||
pub(super) fn preferred_listening_backend(
|
||||
&self,
|
||||
preference: Option<&str>,
|
||||
) -> Option<BackendId> {
|
||||
let mut listening = self.entries.iter().filter(|entry| entry.listening);
|
||||
let preferred = preference.and_then(|key| {
|
||||
listening
|
||||
.clone()
|
||||
.find(|entry| entry.preference_key.as_deref() == Some(key))
|
||||
});
|
||||
preferred
|
||||
.or_else(|| listening.next())
|
||||
.map(|entry| entry.session.backend_id())
|
||||
}
|
||||
|
||||
/// Cycle through listening connections in registration order, excluding the current one.
|
||||
pub(super) fn next_listening_backend(&self, current: BackendId) -> Option<BackendId> {
|
||||
let index = self.slot(current)?.0;
|
||||
self.entries[index + 1..]
|
||||
.iter()
|
||||
.chain(&self.entries[..index])
|
||||
.find(|entry| entry.listening)
|
||||
.map(|entry| entry.session.backend_id())
|
||||
}
|
||||
|
||||
pub(super) fn session_at_mut(&mut self, slot: SessionSlot) -> &mut AppServerSession {
|
||||
&mut self.entries[slot.0].session
|
||||
}
|
||||
|
||||
pub(super) fn listening_slot(&self, owner: BackendId) -> Option<SessionSlot> {
|
||||
self.slot(owner)
|
||||
.filter(|slot| self.entries[slot.0].listening)
|
||||
}
|
||||
|
||||
pub(super) fn is_listening(&self, owner: BackendId) -> bool {
|
||||
self.listening_slot(owner).is_some()
|
||||
}
|
||||
|
||||
pub(super) fn replay_ready_side_startup(&mut self, app: &super::App) {
|
||||
let owner = self.displayed_owner();
|
||||
let entry = &mut self.entries[self.displayed.0];
|
||||
entry
|
||||
.pending_events
|
||||
.extend(entry.side_startup.extract_if(.., |event| {
|
||||
!app.defer_side_startup_notification(event, owner)
|
||||
}));
|
||||
}
|
||||
|
||||
pub(super) fn defer_side_startup(&mut self, event: AppServerSessionEvent) {
|
||||
if let Some(slot) = self.slot(event.backend_id) {
|
||||
self.entries[slot.0].side_startup.push(event);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn resume_events(&mut self, owner: BackendId) {
|
||||
if let Some(entry) = self
|
||||
.entries
|
||||
.iter_mut()
|
||||
.find(|entry| entry.session.backend_id() == owner)
|
||||
{
|
||||
entry.listening = true;
|
||||
entry.pending_events.clear();
|
||||
entry.side_startup.clear();
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn next_event(
|
||||
&mut self,
|
||||
paused_backend: Option<BackendId>,
|
||||
) -> (BackendId, Option<AppServerSessionEvent>) {
|
||||
let request_owner = self.displayed_owner();
|
||||
std::future::poll_fn(|cx| {
|
||||
for offset in 0..self.entries.len() {
|
||||
let index = (self.next_source + offset) % self.entries.len();
|
||||
let entry = &mut self.entries[index];
|
||||
let owner = entry.session.backend_id();
|
||||
if !entry.listening || paused_backend == Some(owner) {
|
||||
continue;
|
||||
}
|
||||
let event = if owner == request_owner
|
||||
&& let Some(event) = entry.pending_events.pop_front()
|
||||
{
|
||||
Some(event)
|
||||
} else {
|
||||
// Both transports have cancellation-safe event queues.
|
||||
let Poll::Ready(event) = std::pin::pin!(entry.session.next_event()).poll(cx)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
event
|
||||
};
|
||||
let event = match event {
|
||||
Some(event)
|
||||
if owner != request_owner
|
||||
&& matches!(&event.event, AppServerEvent::ServerRequest(_)) =>
|
||||
{
|
||||
entry.pending_events.push_back(event);
|
||||
cx.waker().wake_by_ref();
|
||||
continue;
|
||||
}
|
||||
event => event,
|
||||
};
|
||||
if let Some(AppServerSessionEvent { event: AppServerEvent::ServerNotification(notification), .. }) = &event
|
||||
&& let ServerNotification::ServerRequestResolved(resolved) = notification.as_ref()
|
||||
{
|
||||
entry.pending_events.retain(|pending| !matches!(
|
||||
&pending.event, AppServerEvent::ServerRequest(request) if request.id() == &resolved.request_id
|
||||
));
|
||||
}
|
||||
if event
|
||||
.as_ref()
|
||||
.is_none_or(|event| matches!(event.event, AppServerEvent::Disconnected { .. }))
|
||||
{
|
||||
entry.pending_events.clear();
|
||||
}
|
||||
entry.listening = event.is_some();
|
||||
self.next_source = (index + 1) % self.entries.len();
|
||||
return Poll::Ready((owner, event));
|
||||
}
|
||||
Poll::Pending
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub(super) async fn shutdown(self) -> std::io::Result<()> {
|
||||
let mut first_error = None;
|
||||
for entry in self.entries {
|
||||
if let Err(error) = entry.session.shutdown().await {
|
||||
first_error.get_or_insert(error);
|
||||
}
|
||||
}
|
||||
first_error.map_or(Ok(()), Err)
|
||||
}
|
||||
}
|
||||
1117
akode-rs/tui/src/app/background_requests.rs
Normal file
1117
akode-rs/tui/src/app/background_requests.rs
Normal file
File diff suppressed because it is too large
Load Diff
116
akode-rs/tui/src/app/clipboard.rs
Normal file
116
akode-rs/tui/src/app/clipboard.rs
Normal file
@@ -0,0 +1,116 @@
|
||||
//! Dispatch clipboard key actions in order and apply completions to their selection owner.
|
||||
|
||||
use super::*;
|
||||
use crate::chatwidget::KeyEventAction;
|
||||
use crate::clipboard_copy::CopyFormat;
|
||||
use crate::clipboard_copy::worker::PasteSource;
|
||||
use crate::clipboard_paste::PasteImageError;
|
||||
|
||||
impl App {
|
||||
pub(super) fn handle_clipboard_key_action(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
action: KeyEventAction,
|
||||
) {
|
||||
match action {
|
||||
KeyEventAction::None => {}
|
||||
KeyEventAction::CopyLastResponse(text) => {
|
||||
let result = tui
|
||||
.clipboard
|
||||
.copy(text, CopyFormat::Markdown, tui.frame_requester());
|
||||
self.chat_widget.show_copy_result("last message", result);
|
||||
}
|
||||
KeyEventAction::PasteImage {
|
||||
text_fallback,
|
||||
context,
|
||||
} => {
|
||||
if text_fallback.is_some()
|
||||
&& self
|
||||
.right_click_paste_target(tui, PasteSource::Clipboard, text_fallback)
|
||||
.is_none()
|
||||
{
|
||||
return;
|
||||
}
|
||||
// Finish paste before the next key, but never wait on the copy worker's lock.
|
||||
if tui.clipboard.is_busy() || self.pending_right_click_paste.is_some() {
|
||||
self.chat_widget
|
||||
.add_info_message("Clipboard busy; try again".into(), /*hint*/ None);
|
||||
} else {
|
||||
match self.chat_widget.paste_image(context, text_fallback) {
|
||||
Ok(()) => {}
|
||||
Err(PasteImageError::NoImage(_)) if text_fallback.is_some() => {
|
||||
self.start_clipboard_text_paste(
|
||||
tui,
|
||||
PasteSource::Clipboard,
|
||||
text_fallback,
|
||||
);
|
||||
}
|
||||
Err(err) => {
|
||||
tracing::warn!("failed to paste image: {err}");
|
||||
self.chat_widget
|
||||
.add_error_message(format!("Failed to paste image: {err}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn finish_clipboard(&mut self, tui: &mut tui::Tui, event: &TuiEvent) {
|
||||
let current = tui.is_owned_screen() && self.overlay.is_none();
|
||||
if let Some(completion) = tui.clipboard.poll() {
|
||||
if let Some(characters) = self.chat_widget.finish_clipboard(completion, current) {
|
||||
self.transcript_view
|
||||
.show_copy_feedback(&completion.1, characters);
|
||||
}
|
||||
{
|
||||
let mut selection = self.chat_widget.rendered_selection.borrow_mut();
|
||||
let crate::rendered_selection::RenderedSelection { view, cells, .. } =
|
||||
&mut *selection;
|
||||
view.finish_copy(cells, completion, current);
|
||||
}
|
||||
let passive = self
|
||||
.conversation_frame
|
||||
.side_pane()
|
||||
.map(|panes| panes.passive_thread);
|
||||
for (id, companion) in &mut self.side_companions {
|
||||
let visible = current && passive == Some(*id);
|
||||
if companion
|
||||
.view
|
||||
.finish_copy(&companion.cells, completion, visible)
|
||||
== Some(true)
|
||||
{
|
||||
companion.view.jump_to_latest();
|
||||
}
|
||||
}
|
||||
let follow =
|
||||
self.transcript_view
|
||||
.finish_copy(&self.transcript_cells, completion, current);
|
||||
let pending_exit_key = if current {
|
||||
self.backtrack
|
||||
.finish_pending_select_exit_key(completion.0, /*select_mode_closed*/ true)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if follow == Some(true) {
|
||||
if self.backtrack.overlay_preview_active {
|
||||
self.close_transcript_overlay(tui);
|
||||
}
|
||||
self.transcript_view.jump_to_latest();
|
||||
self.backtrack.select_exit_key = pending_exit_key;
|
||||
}
|
||||
}
|
||||
if !current || matches!(event, TuiEvent::FocusLost | TuiEvent::Resume) {
|
||||
self.transcript_view.cancel_primary();
|
||||
for companion in self.side_companions.values_mut() {
|
||||
companion.view.cancel_primary();
|
||||
}
|
||||
self.chat_widget.cancel_composer_primary();
|
||||
self.chat_widget
|
||||
.rendered_selection
|
||||
.borrow_mut()
|
||||
.view
|
||||
.cancel_primary();
|
||||
}
|
||||
}
|
||||
}
|
||||
210
akode-rs/tui/src/app/cloud_switch_wait.rs
Normal file
210
akode-rs/tui/src/app/cloud_switch_wait.rs
Normal file
@@ -0,0 +1,210 @@
|
||||
//! Keeps the composer editable while a Cloud backend switch owns navigation.
|
||||
//!
|
||||
//! Handles editing and redraws. The original handoff owns
|
||||
//! session preparation and adoption, so no competing navigation can install a Cloud stream.
|
||||
|
||||
use super::App;
|
||||
use crate::bottom_pane::RestrictedInputMode;
|
||||
use crate::chatwidget::ClipboardPasteContext;
|
||||
use crate::tui;
|
||||
use crossterm::event::KeyCode;
|
||||
use crossterm::event::KeyEvent;
|
||||
use crossterm::event::KeyModifiers;
|
||||
use ratatui::layout::Size;
|
||||
use std::future::Future;
|
||||
use tokio_stream::Stream;
|
||||
use tokio_stream::StreamExt;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) enum ClipboardHandoff {
|
||||
ContinueEditing,
|
||||
SettleBeforeNextView,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum CloudSwitchProgress {
|
||||
Connecting(ClipboardHandoff),
|
||||
Failed,
|
||||
}
|
||||
|
||||
/// Process editor and repaint events while a Cloud switch owns navigation.
|
||||
fn handle_cloud_switch_event(
|
||||
app: &mut App,
|
||||
tui: &mut tui::Tui,
|
||||
event: tui::TuiEvent,
|
||||
progress: CloudSwitchProgress,
|
||||
) {
|
||||
let screen_size = match tui.screen_size_for_event(&event) {
|
||||
Ok(size) => size,
|
||||
Err(error) => {
|
||||
tracing::warn!(%error, "failed to inspect terminal size during cloud switch");
|
||||
return;
|
||||
}
|
||||
};
|
||||
// Clipboard text is delivered on Draw after ordinary input invalidation and target checks.
|
||||
app.invalidate_right_click_paste(&event);
|
||||
// Polling retains copy feedback for the ordinary event loop.
|
||||
tui.clipboard.poll();
|
||||
let event = app.finish_right_click_paste(tui, event);
|
||||
if app.pending_right_click_paste.is_some() {
|
||||
if matches!(event, tui::TuiEvent::Draw) {
|
||||
// A PRIMARY read may be waiting for an earlier copy or publication.
|
||||
tui.clipboard.advance(tui.frame_requester());
|
||||
} else if matches!(event, tui::TuiEvent::Resize(_)) {
|
||||
// A size change can consume the worker's completion frame.
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
}
|
||||
match event {
|
||||
tui::TuiEvent::Key(mut key) => {
|
||||
let escape = if app.should_recover_vim_insert_escape(tui, key)
|
||||
&& !(tui.is_owned_screen()
|
||||
&& crate::transcript_view::JumpTarget::from_key(key).is_some())
|
||||
{
|
||||
key.modifiers.remove(KeyModifiers::ALT);
|
||||
Some(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
for key in escape.into_iter().chain([key]) {
|
||||
if let Some(key) = app.route_key_chord_event(tui, key) {
|
||||
let action = app
|
||||
.chat_widget
|
||||
.handle_restricted_key(key, RestrictedInputMode::DraftHandoff);
|
||||
app.handle_clipboard_key_action(tui, action);
|
||||
}
|
||||
}
|
||||
show_cloud_switch_hint(app, progress);
|
||||
}
|
||||
tui::TuiEvent::Paste(text) => {
|
||||
app.cancel_pending_key_chord();
|
||||
app.chat_widget
|
||||
.handle_paste(text.replace("\r\n", "\n").replace('\r', "\n"));
|
||||
show_cloud_switch_hint(app, progress);
|
||||
}
|
||||
tui::TuiEvent::Draw
|
||||
| tui::TuiEvent::Resize(_)
|
||||
| tui::TuiEvent::Resume
|
||||
| tui::TuiEvent::FocusGained => {
|
||||
if app
|
||||
.chat_widget
|
||||
.handle_handoff_paste_tick(tui.frame_requester())
|
||||
{
|
||||
tui.defer_screen_size(screen_size);
|
||||
return;
|
||||
}
|
||||
app.chat_widget.pre_draw_tick();
|
||||
draw_cloud_switch(app, tui, screen_size);
|
||||
}
|
||||
tui::TuiEvent::FocusLost => {
|
||||
app.cancel_pending_key_chord();
|
||||
show_cloud_switch_hint(app, progress);
|
||||
}
|
||||
tui::TuiEvent::Mouse(mouse) => {
|
||||
app.start_right_click_paste(tui, mouse, ClipboardPasteContext::DraftHandoff);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn show_cloud_switch_hint(app: &mut App, progress: CloudSwitchProgress) {
|
||||
let (label, action) = match progress {
|
||||
CloudSwitchProgress::Connecting(_) => ("Connecting to Cloud…", "submit when ready"),
|
||||
CloudSwitchProgress::Failed => ("Cloud conversation did not open", "draft kept"),
|
||||
};
|
||||
app.chat_widget
|
||||
.set_footer_hint_override(Some(vec![(label.into(), action.into())]));
|
||||
}
|
||||
|
||||
fn draw_cloud_switch(app: &mut App, tui: &mut tui::Tui, screen_size: Size) {
|
||||
if let Err(error) = app.render_chat_widget_frame(tui, screen_size) {
|
||||
tracing::warn!(%error, "failed to render during cloud switch");
|
||||
}
|
||||
}
|
||||
|
||||
/// Keep input restricted through the failure frame and any input that arrived during its paint.
|
||||
pub(super) async fn finish_failed_cloud_switch(
|
||||
app: &mut App,
|
||||
tui: &mut tui::Tui,
|
||||
mut events: impl Stream<Item = tui::TuiEvent> + Unpin,
|
||||
) {
|
||||
let progress = CloudSwitchProgress::Failed;
|
||||
show_cloud_switch_hint(app, progress);
|
||||
draw_cloud_switch(app, tui, tui.terminal.last_known_screen_size);
|
||||
drain_cloud_switch_events(app, tui, &mut events, progress).await;
|
||||
}
|
||||
|
||||
async fn drain_cloud_switch_events(
|
||||
app: &mut App,
|
||||
tui: &mut tui::Tui,
|
||||
events: &mut (impl Stream<Item = tui::TuiEvent> + Unpin),
|
||||
progress: CloudSwitchProgress,
|
||||
) {
|
||||
// The current draft owns paste keys and any clipboard text until adoption.
|
||||
let settle_clipboard = matches!(
|
||||
progress,
|
||||
CloudSwitchProgress::Connecting(ClipboardHandoff::SettleBeforeNextView)
|
||||
);
|
||||
if settle_clipboard && app.pending_right_click_paste.is_some() {
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
loop {
|
||||
let clipboard_deadline = if settle_clipboard {
|
||||
app.pending_right_click_paste
|
||||
.as_ref()
|
||||
.and_then(|pending| tui.clipboard.text_read_deadline(&pending.request))
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let deadline = app
|
||||
.chat_widget
|
||||
.composer_paste_deadline()
|
||||
.max(clipboard_deadline)
|
||||
.map(tokio::time::Instant::from_std)
|
||||
.unwrap_or_else(tokio::time::Instant::now);
|
||||
let Ok(Some(event)) = tokio::time::timeout_at(deadline, events.next()).await else {
|
||||
if clipboard_deadline.is_some() {
|
||||
// The terminal stream can end or the deadline can beat its scheduled Draw.
|
||||
handle_cloud_switch_event(app, tui, tui::TuiEvent::Draw, progress);
|
||||
app.pending_right_click_paste = None;
|
||||
}
|
||||
break;
|
||||
};
|
||||
handle_cloud_switch_event(app, tui, event, progress);
|
||||
}
|
||||
app.cancel_pending_key_chord();
|
||||
app.chat_widget.set_footer_hint_override(/*items*/ None);
|
||||
}
|
||||
|
||||
/// Keep the draft editable while Cloud prepares its destination. Other app actions wait
|
||||
/// until the handoff completes, so a second navigation cannot replace the pending stream.
|
||||
pub(crate) async fn wait_for_cloud_switch<T, E>(
|
||||
app: &mut App,
|
||||
tui: &mut tui::Tui,
|
||||
operation: impl Future<Output = Result<T, E>>,
|
||||
events: impl Stream<Item = tui::TuiEvent> + Unpin,
|
||||
clipboard_handoff: ClipboardHandoff,
|
||||
) -> Result<T, E> {
|
||||
let progress = CloudSwitchProgress::Connecting(clipboard_handoff);
|
||||
app.cancel_pending_key_chord();
|
||||
show_cloud_switch_hint(app, progress);
|
||||
draw_cloud_switch(app, tui, tui.terminal.last_known_screen_size);
|
||||
if app.pending_right_click_paste.is_some() {
|
||||
// A completion frame can arrive between Cloud preparation phases.
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
let mut events = events.fuse();
|
||||
tokio::pin!(operation);
|
||||
let result = loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
result = &mut operation => break result,
|
||||
Some(event) = events.next() => handle_cloud_switch_event(app, tui, event, progress),
|
||||
}
|
||||
};
|
||||
if result.is_err() {
|
||||
finish_failed_cloud_switch(app, tui, events).await;
|
||||
} else {
|
||||
drain_cloud_switch_events(app, tui, &mut events, progress).await;
|
||||
}
|
||||
result
|
||||
}
|
||||
26
akode-rs/tui/src/app/composer_hints.rs
Normal file
26
akode-rs/tui/src/app/composer_hints.rs
Normal file
@@ -0,0 +1,26 @@
|
||||
//! Usage warnings appear above the fullscreen composer when no interaction takes priority.
|
||||
|
||||
use super::*;
|
||||
use crate::terminal_hyperlinks::HyperlinkLine;
|
||||
|
||||
impl App {
|
||||
pub(super) fn composer_hint(&self, width: u16) -> Option<HyperlinkLine> {
|
||||
if !self.chat_widget.no_modal_or_popup_active()
|
||||
|| !self.transcript_view.is_following()
|
||||
|| self.transcript_view.has_active_interaction()
|
||||
|| self.backtrack.primed
|
||||
|| self.backtrack.overlay_preview_active
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let width = width.checked_sub(/*rhs*/ 2)?;
|
||||
if width == 0 {
|
||||
return None;
|
||||
}
|
||||
self.chat_widget.usage_notice(width).map(HyperlinkLine::new)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "composer_hints_tests.rs"]
|
||||
mod tests;
|
||||
235
akode-rs/tui/src/app/composer_hints_tests.rs
Normal file
235
akode-rs/tui/src/app/composer_hints_tests.rs
Normal file
@@ -0,0 +1,235 @@
|
||||
//! Usage warnings preserve composer geometry and yield to active interactions.
|
||||
|
||||
use super::*;
|
||||
use akode_app_server_protocol::RateLimitSnapshot;
|
||||
use akode_app_server_protocol::ServerNotification;
|
||||
use akode_app_server_protocol::Turn;
|
||||
use akode_app_server_protocol::TurnItemsView;
|
||||
use akode_app_server_protocol::TurnStartedNotification;
|
||||
use akode_app_server_protocol::TurnStatus;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn quota(used_percent: i32) -> RateLimitSnapshot {
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"primary": {"usedPercent": used_percent, "windowDurationMins": 300},
|
||||
}))
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn usage_notice_preserves_composer_geometry_on_recovery() -> Result<()> {
|
||||
let mut snapshots = Vec::new();
|
||||
for (width, height, running, queued, used_percent) in [
|
||||
(80, 10, false, false, 92),
|
||||
(80, 12, true, false, 98),
|
||||
(32, 10, true, false, 101),
|
||||
(18, 10, true, false, 95),
|
||||
(80, 18, true, true, 98),
|
||||
(80, 11, true, true, 98),
|
||||
(80, 6, true, false, 98),
|
||||
] {
|
||||
let (mut app, mut events, _ops) = crate::app::tests::make_test_app_with_channels().await;
|
||||
app.local_settings.tui.show_tooltips = !running;
|
||||
app.local_settings.tui.animations = false;
|
||||
app.transcript_cells
|
||||
.push(Arc::new(crate::history_cell::PlainHistoryCell::new(
|
||||
if running {
|
||||
(0..20)
|
||||
.map(|row| format!("Conversation row {row}").into())
|
||||
.collect()
|
||||
} else {
|
||||
vec!["Conversation".into()]
|
||||
},
|
||||
)));
|
||||
if running {
|
||||
app.chat_widget.handle_server_notification(
|
||||
ServerNotification::TurnStarted(TurnStartedNotification {
|
||||
thread_id: ThreadId::new().to_string(),
|
||||
turn: Turn {
|
||||
id: "turn".into(),
|
||||
root_turn_id: None,
|
||||
items_view: TurnItemsView::Full,
|
||||
items: Vec::new(),
|
||||
status: TurnStatus::InProgress,
|
||||
error: None,
|
||||
started_at: None,
|
||||
completed_at: None,
|
||||
duration_ms: None,
|
||||
},
|
||||
}),
|
||||
/*replay_kind*/ None,
|
||||
);
|
||||
assert!(app.chat_widget.is_user_turn_pending_or_running());
|
||||
if queued {
|
||||
app.keymap.chat.edit_queued_message = vec![crate::key_hint::shift(KeyCode::Left)];
|
||||
app.chat_widget
|
||||
.apply_keymap_update(Default::default(), &app.keymap);
|
||||
app.chat_widget
|
||||
.apply_external_edit("queued follow-up".into());
|
||||
app.chat_widget
|
||||
.handle_key_event(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE));
|
||||
assert_eq!(
|
||||
app.chat_widget.queued_user_message_texts(),
|
||||
vec!["queued follow-up"],
|
||||
);
|
||||
}
|
||||
app.chat_widget.apply_external_edit(if queued {
|
||||
"draft stays\nsecond line".into()
|
||||
} else {
|
||||
"draft stays".into()
|
||||
});
|
||||
}
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
tui.set_owned_screen(/*owned*/ true)?;
|
||||
let size = Size::new(width, height);
|
||||
tui.terminal.resize(size)?;
|
||||
let before = app.render_owned_transcript(&mut tui, size)?;
|
||||
let cursor = tui.terminal.last_known_cursor_pos;
|
||||
let hint = app.composer_hint(width);
|
||||
app.chat_widget
|
||||
.on_rate_limit_snapshot(Some(quota(used_percent)));
|
||||
while let Ok(event) = events.try_recv() {
|
||||
if let AppEvent::InsertHistoryCell(cell) = event {
|
||||
app.insert_history_cell(&mut tui, cell);
|
||||
}
|
||||
}
|
||||
app.render_owned_transcript(&mut tui, size)?;
|
||||
assert_eq!(tui.terminal.last_known_cursor_pos, cursor);
|
||||
let buffer = crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal);
|
||||
let screen = buffer
|
||||
.content()
|
||||
.chunks(usize::from(buffer.area.width))
|
||||
.map(|row| {
|
||||
row.iter()
|
||||
.map(ratatui::buffer::Cell::symbol)
|
||||
.collect::<String>()
|
||||
.trim_end()
|
||||
.to_owned()
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
snapshots.push(format!(
|
||||
"{width} columns, {height} rows, running={running}, queued={queued}\n{screen}"
|
||||
));
|
||||
app.chat_widget
|
||||
.on_rate_limit_snapshot(Some(quota(/*used_percent*/ 10)));
|
||||
assert_eq!(app.composer_hint(width), hint);
|
||||
assert_eq!(app.render_owned_transcript(&mut tui, size)?, before);
|
||||
assert_eq!(tui.terminal.last_known_cursor_pos, cursor);
|
||||
tui.set_owned_screen(/*owned*/ false)?;
|
||||
}
|
||||
insta::assert_snapshot!(
|
||||
"composer_usage_notice",
|
||||
crate::chatwidget::tests::helpers::normalize_snapshot_paths(snapshots.join("\n\n")),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn usage_notice_yields_to_interactions_and_blocking_banners() {
|
||||
let mut app = crate::app::test_support::make_test_app().await;
|
||||
app.local_settings.tui.show_tooltips = true;
|
||||
let hint = app.composer_hint(/*width*/ 80);
|
||||
app.chat_widget
|
||||
.on_rate_limit_snapshot(Some(quota(/*used_percent*/ 92)));
|
||||
let notice = app.composer_hint(/*width*/ 80);
|
||||
assert!(notice.is_some());
|
||||
assert_ne!(notice, hint);
|
||||
let notice_line = notice.as_ref().map(|notice| notice.line.clone());
|
||||
app.transcript_view.begin_search();
|
||||
assert_eq!(app.composer_hint(/*width*/ 80), None);
|
||||
app.transcript_view = Default::default();
|
||||
assert_eq!(app.composer_hint(/*width*/ 80), notice);
|
||||
app.chat_widget.open_warnings(&app.transcript_cells);
|
||||
assert_eq!(app.composer_hint(/*width*/ 80), None);
|
||||
app.chat_widget.handle_key_event(KeyCode::Esc.into());
|
||||
assert_eq!(app.composer_hint(/*width*/ 80), notice);
|
||||
|
||||
for (spend_control, reached_type) in [
|
||||
(Some(true), None),
|
||||
(
|
||||
None,
|
||||
Some(akode_app_server_protocol::RateLimitReachedType::RateLimitReached),
|
||||
),
|
||||
] {
|
||||
let mut update = quota(/*used_percent*/ 92);
|
||||
update.spend_control_reached = spend_control;
|
||||
update.rate_limit_reached_type = reached_type;
|
||||
app.chat_widget.on_rate_limit_snapshot(Some(update));
|
||||
assert_eq!(app.chat_widget.usage_notice(/*width*/ 80), None);
|
||||
}
|
||||
app.chat_widget.on_rate_limit_snapshot(/*snapshot*/ None);
|
||||
app.chat_widget
|
||||
.on_rate_limit_snapshot(Some(quota(/*used_percent*/ 92)));
|
||||
assert_eq!(app.chat_widget.usage_notice(/*width*/ 78), notice_line);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn escape_closes_shortcut_help_before_transcript_backtracking() -> Result<()> {
|
||||
let mut app = crate::app::test_support::make_test_app().await;
|
||||
let mut server = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?;
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
tui.set_owned_screen(/*owned*/ true)?;
|
||||
app.transcript_cells = vec![Arc::new(crate::history_cell::PlainHistoryCell::new(
|
||||
(0..60)
|
||||
.map(|row| format!("response row {row}").into())
|
||||
.collect(),
|
||||
))];
|
||||
app.render_owned_transcript(&mut tui, Size::new(/*width*/ 80, /*height*/ 24))?;
|
||||
app.transcript_view
|
||||
.scroll(&app.transcript_cells, /*rows*/ -20);
|
||||
let area = Rect::new(
|
||||
/*x*/ 0, /*y*/ 0, /*width*/ 80, /*height*/ 8,
|
||||
);
|
||||
let mut before = ratatui::buffer::Buffer::empty(area);
|
||||
app.transcript_view
|
||||
.render(area, &mut before, &app.transcript_cells);
|
||||
let escape = KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE);
|
||||
let toggle = KeyEvent::new(KeyCode::Char('?'), KeyModifiers::NONE);
|
||||
assert!(app.should_handle_backtrack_esc(escape));
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(toggle))
|
||||
.await?;
|
||||
assert!(app.chat_widget.shortcut_overlay_visible());
|
||||
assert!(!app.should_handle_backtrack_esc(escape));
|
||||
assert!(!app.should_reject_side_backtrack_esc(escape));
|
||||
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(escape))
|
||||
.await?;
|
||||
assert!(!app.chat_widget.shortcut_overlay_visible());
|
||||
assert!(!app.backtrack.primed);
|
||||
assert!(!app.transcript_view.is_following());
|
||||
assert!(app.should_handle_backtrack_esc(escape));
|
||||
let mut after = ratatui::buffer::Buffer::empty(area);
|
||||
app.transcript_view
|
||||
.render(area, &mut after, &app.transcript_cells);
|
||||
assert_eq!(after, before);
|
||||
|
||||
// Search and selection replace the help footer and keep their own first Escape.
|
||||
for search in [true, false] {
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(toggle))
|
||||
.await?;
|
||||
if search {
|
||||
app.transcript_view.begin_search();
|
||||
} else {
|
||||
tui.screen_size_for_event(&TuiEvent::Resize(Size::new(
|
||||
/*width*/ 80, /*height*/ 40,
|
||||
)))?;
|
||||
app.handle_owned_transcript_event(
|
||||
&mut tui,
|
||||
&mut server,
|
||||
&TuiEvent::Key(KeyEvent::new(KeyCode::Char(' '), KeyModifiers::CONTROL)),
|
||||
)?;
|
||||
}
|
||||
assert!(app.transcript_view.has_active_interaction());
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(escape))
|
||||
.await?;
|
||||
assert!(!app.transcript_view.has_active_interaction());
|
||||
assert!(app.chat_widget.shortcut_overlay_visible());
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(escape))
|
||||
.await?;
|
||||
assert!(!app.chat_widget.shortcut_overlay_visible());
|
||||
}
|
||||
server.shutdown().await?;
|
||||
tui.set_owned_screen(/*owned*/ false)?;
|
||||
Ok(())
|
||||
}
|
||||
186
akode-rs/tui/src/app/config_panel.rs
Normal file
186
akode-rs/tui/src/app/config_panel.rs
Normal file
@@ -0,0 +1,186 @@
|
||||
//! Persists config-panel preferences, applies live-safe values, and handles notification previews.
|
||||
|
||||
use super::*;
|
||||
use crate::config_panel::ConfigPreference;
|
||||
use crate::config_panel::ConfigToggle;
|
||||
use crate::config_update::format_config_error;
|
||||
use crate::legacy_core::config::load_config_toml_with_layer_stack;
|
||||
use crate::local_settings::LocalSettings;
|
||||
|
||||
impl App {
|
||||
pub(super) async fn save_config_preference(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
preference: ConfigPreference,
|
||||
) {
|
||||
let result =
|
||||
ConfigEditsBuilder::for_config_path(self.local_settings.user_config_path.as_path())
|
||||
.with_edits([preference.edit()])
|
||||
.apply()
|
||||
.await;
|
||||
if let Err(error) = result {
|
||||
self.chat_widget
|
||||
.refresh_config_panel(/*notice*/ Some(format!(
|
||||
"Could not save: {}",
|
||||
format_config_error(&error)
|
||||
)));
|
||||
return;
|
||||
}
|
||||
|
||||
// TUI preferences are local, so remote sessions reload them from the launch directory.
|
||||
let config_cwd = if crate::uses_remote_workspace_or_environment(
|
||||
&self.app_server_target,
|
||||
&self.environment_manager,
|
||||
) {
|
||||
self.launch_cwd.clone()
|
||||
} else {
|
||||
self.chat_widget.config_ref().cwd.to_path_buf()
|
||||
};
|
||||
let resolved = match async {
|
||||
let cwd = AbsolutePathBuf::relative_to_current_dir(&config_cwd)?;
|
||||
let bootstrap = load_config_toml_with_layer_stack(
|
||||
self.local_settings.codex_home.as_path(),
|
||||
Some(&cwd),
|
||||
self.cli_kv_overrides.clone(),
|
||||
akode_config::ConfigLoadOptions {
|
||||
loader_overrides: self.loader_overrides.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
LocalSettings::from_bootstrap(&bootstrap, self.local_settings.codex_home.clone())
|
||||
.map_err(std::io::Error::other)
|
||||
}
|
||||
.await
|
||||
.wrap_err_with(|| format!("Failed to rebuild config for cwd {}", config_cwd.display()))
|
||||
{
|
||||
Ok(settings) => settings,
|
||||
Err(error) => {
|
||||
self.chat_widget
|
||||
.refresh_config_panel(
|
||||
/*notice*/ Some(format!("Saved, but could not reload: {error}")),
|
||||
);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
preference.adopt(&mut self.local_settings.tui, &resolved.tui);
|
||||
self.chat_widget
|
||||
.apply_config_preference(preference, &resolved.tui);
|
||||
if matches!(
|
||||
preference,
|
||||
ConfigPreference::Toggle {
|
||||
setting: ConfigToggle::Notifications,
|
||||
..
|
||||
}
|
||||
) && !ConfigToggle::Notifications.enabled(&resolved.tui)
|
||||
{
|
||||
self.chat_widget.pending_notification = None;
|
||||
self.config_notification_test_pending = None;
|
||||
}
|
||||
self.local_settings.custom_notification_filters = resolved.custom_notification_filters;
|
||||
self.chat_widget.local_settings.custom_notification_filters =
|
||||
resolved.custom_notification_filters;
|
||||
preference.adopt(&mut self.chat_widget.config_panel_tui, &resolved.tui);
|
||||
if matches!(
|
||||
preference,
|
||||
ConfigPreference::Toggle {
|
||||
setting: ConfigToggle::StatusLineColors,
|
||||
..
|
||||
}
|
||||
) {
|
||||
self.refresh_status_line();
|
||||
}
|
||||
if matches!(preference, ConfigPreference::NotificationCondition(_)) {
|
||||
tui.set_notification_condition(self.local_settings.tui.notification_settings.condition);
|
||||
}
|
||||
let effective = match preference {
|
||||
ConfigPreference::Toggle { setting, enabled } => {
|
||||
setting.enabled(&resolved.tui) == enabled
|
||||
}
|
||||
ConfigPreference::CopyOnSelect(mode) => resolved.tui.copy_on_select == mode,
|
||||
ConfigPreference::NotificationCondition(condition) => {
|
||||
resolved.tui.notification_settings.condition == condition
|
||||
}
|
||||
ConfigPreference::RightClickPaste(mode) => resolved.tui.right_click_paste == mode,
|
||||
ConfigPreference::SessionPickerLayout(mode) => {
|
||||
resolved.tui.session_picker_view.unwrap_or_default() == mode
|
||||
}
|
||||
ConfigPreference::ResumeDirectory(mode) => resolved.tui.resume_cwd == mode,
|
||||
};
|
||||
let notice = if !effective {
|
||||
Some("Saved · overridden by config or system setting")
|
||||
} else if matches!(
|
||||
preference,
|
||||
ConfigPreference::Toggle {
|
||||
setting: ConfigToggle::StartInVimMode,
|
||||
..
|
||||
}
|
||||
) {
|
||||
Some("Saved · applies to new composers")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let notice = notice.map(str::to_string);
|
||||
if effective {
|
||||
self.chat_widget
|
||||
.refresh_config_panel_after_effective_save(notice, preference);
|
||||
} else {
|
||||
self.chat_widget.refresh_config_panel(notice);
|
||||
}
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub(super) fn schedule_config_notification_test(&mut self) {
|
||||
if self.config_notification_test_pending.is_some() {
|
||||
self.chat_widget.refresh_config_panel(/*notice*/ Some(
|
||||
"Test already scheduled · switch apps".into(),
|
||||
));
|
||||
return;
|
||||
}
|
||||
self.config_notification_test_generation = self
|
||||
.config_notification_test_generation
|
||||
.wrapping_add(/*rhs*/ 1);
|
||||
let generation = self.config_notification_test_generation;
|
||||
self.config_notification_test_pending = Some(generation);
|
||||
self.chat_widget.refresh_config_panel(
|
||||
/*notice*/ Some("Test scheduled in 5s · switch apps".into()),
|
||||
);
|
||||
let tx = self.app_event_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(std::time::Duration::from_secs(/*secs*/ 5)).await;
|
||||
tx.send(AppEvent::SendConfigTestNotification { generation });
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn send_config_notification_test(&mut self, tui: &mut tui::Tui, generation: u64) {
|
||||
if self.config_notification_test_pending != Some(generation) {
|
||||
return;
|
||||
}
|
||||
self.config_notification_test_pending = None;
|
||||
let notice = if !tui.notify_test("aKode notification test") {
|
||||
"Could not send test · check terminal connection"
|
||||
} else if akode_terminal_detection::terminal_info().name
|
||||
== akode_terminal_detection::TerminalName::Ghostty
|
||||
&& tui.is_terminal_focused()
|
||||
{
|
||||
"Test sent · Ghostty hides banners while focused"
|
||||
} else {
|
||||
"Test sent · check terminal/system settings"
|
||||
};
|
||||
if !self
|
||||
.chat_widget
|
||||
.refresh_config_panel(/*notice*/ Some(notice.into()))
|
||||
{
|
||||
self.chat_widget
|
||||
.add_info_message(notice.into(), /*hint*/ None);
|
||||
}
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "config_panel_tests.rs"]
|
||||
mod tests;
|
||||
369
akode-rs/tui/src/app/config_panel_tests.rs
Normal file
369
akode-rs/tui/src/app/config_panel_tests.rs
Normal file
@@ -0,0 +1,369 @@
|
||||
//! Config-panel persistence and delayed notification-preview behavior.
|
||||
|
||||
use super::*;
|
||||
use crate::AppServerTarget;
|
||||
use crate::app::test_support::make_test_app;
|
||||
use crate::app_event::AppEvent;
|
||||
use crate::chatwidget::tests::make_chatwidget_manual_with_sender;
|
||||
use crate::chatwidget::tests::render_bottom_popup;
|
||||
use crate::config_panel::ConfigEditor;
|
||||
use crate::config_panel::ConfigEditorHandoff;
|
||||
use crate::local_settings::LocalSettings;
|
||||
use akode_protocol::config_types::TrustLevel;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tokio::sync::mpsc::UnboundedReceiver;
|
||||
|
||||
fn open_effects_editor(app: &mut App) {
|
||||
let handoff = ConfigEditorHandoff::new(
|
||||
ConfigEditor::Effects,
|
||||
crate::key_hint::plain(KeyCode::Enter),
|
||||
);
|
||||
handoff.mark_activation_inactive();
|
||||
app.chat_widget.open_config_editor(
|
||||
handoff,
|
||||
crate::config_panel::ResumeCurrentAvailability::Available,
|
||||
);
|
||||
}
|
||||
|
||||
fn next_config_preference(rx: &mut UnboundedReceiver<AppEvent>) -> Result<ConfigPreference> {
|
||||
let AppEvent::SaveConfigPreference(preference) = rx.try_recv()? else {
|
||||
panic!("expected config preference save");
|
||||
};
|
||||
Ok(preference)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn config_toggle_save_uses_host_config_and_applies_live_while_offline() -> Result<()> {
|
||||
let root = tempfile::tempdir()?;
|
||||
let home = root.path().join("home");
|
||||
let local_cwd = root.path().join("local");
|
||||
let session_cwd = root.path().join("session");
|
||||
std::fs::create_dir_all(&home)?;
|
||||
for (cwd, auto_recap) in [(&local_cwd, false), (&session_cwd, true)] {
|
||||
std::fs::create_dir_all(cwd.join(".akode"))?;
|
||||
std::fs::write(
|
||||
cwd.join(".akode/config.toml"),
|
||||
format!("[tui]\nauto_recap = {auto_recap}\n"),
|
||||
)?;
|
||||
}
|
||||
let local_cwd = AbsolutePathBuf::from_absolute_path(std::fs::canonicalize(local_cwd)?)?;
|
||||
let session_cwd = AbsolutePathBuf::from_absolute_path(std::fs::canonicalize(session_cwd)?)?;
|
||||
ConfigEditsBuilder::new(&home)
|
||||
.set_project_trust_level(local_cwd.to_path_buf(), TrustLevel::Trusted)
|
||||
.set_project_trust_level(session_cwd.to_path_buf(), TrustLevel::Trusted)
|
||||
.apply()
|
||||
.await
|
||||
.map_err(|error| color_eyre::eyre::eyre!(error.to_string()))?;
|
||||
let loader_overrides = LoaderOverrides::without_managed_config_for_tests();
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(home)
|
||||
.harness_overrides(ConfigOverrides {
|
||||
cwd: Some(local_cwd.to_path_buf()),
|
||||
..Default::default()
|
||||
})
|
||||
.loader_overrides(loader_overrides.clone())
|
||||
.build()
|
||||
.await?;
|
||||
assert!(!config.tui_auto_recap);
|
||||
|
||||
let mut app = Box::pin(make_test_app()).await;
|
||||
app.config = config.clone();
|
||||
app.local_settings = LocalSettings::from(&config);
|
||||
app.launch_cwd = local_cwd.to_path_buf();
|
||||
app.config.cwd = session_cwd.clone();
|
||||
app.loader_overrides = loader_overrides;
|
||||
app.app_server_target = AppServerTarget::Remote {
|
||||
endpoint: crate::RemoteAppServerEndpoint::WebSocket {
|
||||
websocket_url: "ws://127.0.0.1:8765".to_string(),
|
||||
auth_token: None,
|
||||
},
|
||||
};
|
||||
app.reconnect.offline = true;
|
||||
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
let mut app_server = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?;
|
||||
let mut session_config = config;
|
||||
session_config.cwd = session_cwd.clone();
|
||||
let init = app.chatwidget_init_for_forked_or_resumed_thread(
|
||||
&mut tui,
|
||||
session_config,
|
||||
/*initial_user_message*/ None,
|
||||
);
|
||||
app.chat_widget = ChatWidget::new_with_app_event(init);
|
||||
app.local_settings.tui.auto_recap = true;
|
||||
app.chat_widget.local_settings.tui.auto_recap = true;
|
||||
// Resolving execution settings would fail, but local preferences remain editable.
|
||||
app.cli_kv_overrides = vec![("model_provider".into(), "missing-provider".into())];
|
||||
|
||||
Box::pin(app.handle_event(
|
||||
&mut tui,
|
||||
&mut app_server,
|
||||
AppEvent::SaveConfigPreference(ConfigPreference::Toggle {
|
||||
setting: ConfigToggle::AutomaticRecaps,
|
||||
enabled: false,
|
||||
}),
|
||||
))
|
||||
.await?;
|
||||
|
||||
app.chat_widget.handle_key_event(KeyCode::Char('a').into());
|
||||
assert!(app.chat_widget.is_in_paste_burst());
|
||||
Box::pin(app.handle_event(
|
||||
&mut tui,
|
||||
&mut app_server,
|
||||
AppEvent::SaveConfigPreference(ConfigPreference::Toggle {
|
||||
setting: ConfigToggle::PasteDetection,
|
||||
enabled: false,
|
||||
}),
|
||||
))
|
||||
.await?;
|
||||
|
||||
assert_eq!(
|
||||
(
|
||||
app.local_settings.tui.auto_recap,
|
||||
app.chat_widget.local_settings.tui.auto_recap,
|
||||
app.chat_widget.config_panel_tui.auto_recap,
|
||||
app.local_settings.tui.disable_paste_burst,
|
||||
app.chat_widget.local_settings.tui.disable_paste_burst,
|
||||
),
|
||||
(false, false, false, Some(true), Some(true)),
|
||||
);
|
||||
assert!(!app.chat_widget.is_in_paste_burst());
|
||||
app.chat_widget.handle_key_event(KeyCode::Char('b').into());
|
||||
assert!(!app.chat_widget.is_in_paste_burst());
|
||||
let saved: toml::Value = toml::from_str(&std::fs::read_to_string(
|
||||
&app.local_settings.user_config_path,
|
||||
)?)?;
|
||||
assert_eq!(saved["tui"]["auto_recap"].as_bool(), Some(false));
|
||||
assert_eq!(saved["tui"]["disable_paste_burst"].as_bool(), Some(true));
|
||||
assert_eq!(app.launch_cwd, local_cwd.to_path_buf());
|
||||
assert_eq!(
|
||||
(&app.config.cwd, &app.chat_widget.config_ref().cwd),
|
||||
(&session_cwd, &session_cwd),
|
||||
);
|
||||
|
||||
app_server.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn effects_editor_refresh_preserves_pending_toggles() -> Result<()> {
|
||||
let (mut app, mut rx, _ops) = crate::app::tests::make_test_app_with_channels().await;
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
app.local_settings.tui.animations = false;
|
||||
app.chat_widget.local_settings.tui.animations = false;
|
||||
app.chat_widget.config_panel_tui.animations = false;
|
||||
open_effects_editor(&mut app);
|
||||
|
||||
app.chat_widget.handle_key_event(KeyCode::Enter.into());
|
||||
app.chat_widget.handle_key_event(KeyCode::Enter.into());
|
||||
let first_preference = next_config_preference(&mut rx)?;
|
||||
app.save_config_preference(&mut tui, first_preference).await;
|
||||
|
||||
insta::assert_snapshot!(
|
||||
"effects_picker_after_animation_save",
|
||||
render_bottom_popup(&app.chat_widget, /*width*/ 80)
|
||||
);
|
||||
|
||||
app.chat_widget.handle_key_event(KeyCode::Enter.into());
|
||||
let second_preference = next_config_preference(&mut rx)?;
|
||||
app.save_config_preference(&mut tui, second_preference)
|
||||
.await;
|
||||
let third_preference = next_config_preference(&mut rx)?;
|
||||
assert_eq!(
|
||||
third_preference,
|
||||
ConfigPreference::Toggle {
|
||||
setting: ConfigToggle::Animations,
|
||||
enabled: true,
|
||||
}
|
||||
);
|
||||
app.save_config_preference(&mut tui, third_preference).await;
|
||||
assert!(app.chat_widget.config_panel_tui.animations);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn effects_editor_preserves_pending_stars_while_disabled() -> Result<()> {
|
||||
let (mut app, mut rx, _ops) = crate::app::tests::make_test_app_with_channels().await;
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
app.local_settings.tui.animations = true;
|
||||
app.local_settings.tui.effects.starfield = true;
|
||||
app.chat_widget.local_settings.tui.animations = true;
|
||||
app.chat_widget.local_settings.tui.effects.starfield = true;
|
||||
app.chat_widget.config_panel_tui.animations = true;
|
||||
app.chat_widget.config_panel_tui.effects.starfield = true;
|
||||
open_effects_editor(&mut app);
|
||||
|
||||
for shortcut in ['1', '2', '2'] {
|
||||
app.chat_widget
|
||||
.handle_key_event(KeyCode::Char(shortcut).into());
|
||||
}
|
||||
let animations_off = next_config_preference(&mut rx)?;
|
||||
assert_eq!(
|
||||
animations_off,
|
||||
ConfigPreference::Toggle {
|
||||
setting: ConfigToggle::Animations,
|
||||
enabled: false,
|
||||
}
|
||||
);
|
||||
app.save_config_preference(&mut tui, animations_off).await;
|
||||
|
||||
app.chat_widget.handle_key_event(KeyCode::Char('1').into());
|
||||
for _ in 0..3 {
|
||||
let preference = next_config_preference(&mut rx)?;
|
||||
app.save_config_preference(&mut tui, preference).await;
|
||||
}
|
||||
|
||||
assert_eq!(
|
||||
(
|
||||
app.chat_widget.config_panel_tui.animations,
|
||||
app.chat_widget.config_panel_tui.effects.starfield,
|
||||
),
|
||||
(true, true),
|
||||
);
|
||||
app.chat_widget.handle_key_event(KeyCode::Char('2').into());
|
||||
assert_eq!(
|
||||
next_config_preference(&mut rx)?,
|
||||
ConfigPreference::Toggle {
|
||||
setting: ConfigToggle::ComposerStars,
|
||||
enabled: false,
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn effects_editor_reset_clears_pending_toggle_state() -> Result<()> {
|
||||
let (mut app, mut rx, _ops) = crate::app::tests::make_test_app_with_channels().await;
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
app.local_settings.tui.animations = true;
|
||||
app.local_settings.tui.effects.starfield = true;
|
||||
app.chat_widget.local_settings.tui.animations = true;
|
||||
app.chat_widget.local_settings.tui.effects.starfield = true;
|
||||
app.chat_widget.config_panel_tui.animations = true;
|
||||
app.chat_widget.config_panel_tui.effects.starfield = true;
|
||||
open_effects_editor(&mut app);
|
||||
|
||||
app.chat_widget.handle_key_event(KeyCode::Char('1').into());
|
||||
app.chat_widget.handle_key_event(KeyCode::Char('2').into());
|
||||
let _animations_off = next_config_preference(&mut rx)?;
|
||||
let stars_off = next_config_preference(&mut rx)?;
|
||||
|
||||
app.chat_widget.refresh_config_panel(/*notice*/ None);
|
||||
app.save_config_preference(&mut tui, stars_off).await;
|
||||
|
||||
assert!(!app.chat_widget.config_panel_tui.effects.starfield);
|
||||
app.chat_widget.handle_key_event(KeyCode::Char('2').into());
|
||||
assert_eq!(
|
||||
next_config_preference(&mut rx)?,
|
||||
ConfigPreference::Toggle {
|
||||
setting: ConfigToggle::ComposerStars,
|
||||
enabled: true,
|
||||
}
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn notification_test_delay_rejects_cancelled_and_rescheduled_timers() -> Result<()> {
|
||||
let (mut app, mut rx, _ops) = crate::app::tests::make_test_app_with_channels().await;
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
let notification_generation = |event| match event {
|
||||
AppEvent::SendConfigTestNotification { generation } => generation,
|
||||
_ => panic!("expected notification preview timer"),
|
||||
};
|
||||
tui.set_notification_settings(
|
||||
akode_config::types::NotificationMethod::Bel,
|
||||
akode_config::types::NotificationCondition::Unfocused,
|
||||
);
|
||||
app.chat_widget.open_config_panel();
|
||||
app.chat_widget.handle_key_event(KeyCode::Right.into());
|
||||
app.chat_widget.handle_key_event(KeyCode::Char('/').into());
|
||||
app.chat_widget.handle_paste("test notification".into());
|
||||
app.chat_widget.handle_key_event(KeyCode::Enter.into());
|
||||
assert!(matches!(
|
||||
rx.try_recv().expect("test notification action"),
|
||||
AppEvent::TestConfigNotification
|
||||
));
|
||||
app.schedule_config_notification_test();
|
||||
app.schedule_config_notification_test();
|
||||
tokio::task::yield_now().await;
|
||||
app.chat_widget
|
||||
.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
|
||||
app.chat_widget
|
||||
.handle_key_event(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE));
|
||||
assert!(rx.try_recv().is_err());
|
||||
|
||||
tokio::time::advance(std::time::Duration::from_secs(/*secs*/ 4)).await;
|
||||
assert!(rx.try_recv().is_err());
|
||||
tokio::time::advance(std::time::Duration::from_secs(/*secs*/ 1)).await;
|
||||
tokio::task::yield_now().await;
|
||||
let generation = notification_generation(rx.try_recv().expect("scheduled preview"));
|
||||
assert!(rx.try_recv().is_err());
|
||||
|
||||
app.send_config_notification_test(&mut tui, generation);
|
||||
let AppEvent::InsertHistoryCell(cell) = rx.try_recv()? else {
|
||||
panic!("expected notification result in history");
|
||||
};
|
||||
assert!(
|
||||
cell.display_lines(/*width*/ 120)
|
||||
.iter()
|
||||
.any(|line| line.to_string().starts_with("• Test sent · "))
|
||||
);
|
||||
|
||||
app.schedule_config_notification_test();
|
||||
let cancelled_generation = app
|
||||
.config_notification_test_pending
|
||||
.expect("pending preview");
|
||||
tokio::task::yield_now().await;
|
||||
let (replacement, _, mut replacement_events, _) = make_chatwidget_manual_with_sender().await;
|
||||
app.replace_chat_widget(replacement);
|
||||
assert!(app.config_notification_test_pending.is_none());
|
||||
app.schedule_config_notification_test();
|
||||
let rescheduled_generation = app
|
||||
.config_notification_test_pending
|
||||
.expect("rescheduled preview");
|
||||
assert_ne!(cancelled_generation, rescheduled_generation);
|
||||
tokio::task::yield_now().await;
|
||||
tokio::time::advance(std::time::Duration::from_secs(/*secs*/ 5)).await;
|
||||
tokio::task::yield_now().await;
|
||||
let mut timer_generations = Vec::new();
|
||||
for _ in 0..2 {
|
||||
timer_generations.push(notification_generation(
|
||||
rx.try_recv().expect("preview timer"),
|
||||
));
|
||||
}
|
||||
timer_generations.sort_unstable();
|
||||
assert_eq!(
|
||||
timer_generations,
|
||||
vec![cancelled_generation, rescheduled_generation]
|
||||
);
|
||||
|
||||
app.send_config_notification_test(&mut tui, cancelled_generation);
|
||||
assert_eq!(
|
||||
app.config_notification_test_pending,
|
||||
Some(rescheduled_generation)
|
||||
);
|
||||
assert!(rx.try_recv().is_err());
|
||||
assert!(replacement_events.try_recv().is_err());
|
||||
app.send_config_notification_test(&mut tui, rescheduled_generation);
|
||||
assert!(matches!(
|
||||
replacement_events.try_recv(),
|
||||
Ok(AppEvent::InsertHistoryCell(_))
|
||||
));
|
||||
|
||||
app.schedule_config_notification_test();
|
||||
app.save_config_preference(
|
||||
&mut tui,
|
||||
ConfigPreference::Toggle {
|
||||
setting: ConfigToggle::Notifications,
|
||||
enabled: false,
|
||||
},
|
||||
)
|
||||
.await;
|
||||
tokio::time::advance(std::time::Duration::from_secs(/*secs*/ 5)).await;
|
||||
tokio::task::yield_now().await;
|
||||
let generation = notification_generation(rx.try_recv().expect("cancelled preview timer"));
|
||||
app.send_config_notification_test(&mut tui, generation);
|
||||
assert!(rx.try_recv().is_err());
|
||||
Ok(())
|
||||
}
|
||||
2197
akode-rs/tui/src/app/config_persistence.rs
Normal file
2197
akode-rs/tui/src/app/config_persistence.rs
Normal file
File diff suppressed because it is too large
Load Diff
209
akode-rs/tui/src/app/daemon_menu.rs
Normal file
209
akode-rs/tui/src/app/daemon_menu.rs
Normal file
@@ -0,0 +1,209 @@
|
||||
//! Local daemon maintenance confirms restarts and updates before acting.
|
||||
//! Restarts use normal TUI reconnection; updates run after restoring the terminal.
|
||||
|
||||
use super::*;
|
||||
use crate::bottom_pane::SelectionItem;
|
||||
use crate::bottom_pane::SelectionViewParams;
|
||||
use crate::update_action::DaemonUpdateSource;
|
||||
use crate::wrapping::word_wrap_lines;
|
||||
use ratatui::buffer::Buffer;
|
||||
use ratatui::widgets::Paragraph;
|
||||
|
||||
struct DaemonMenuHeader(Vec<Line<'static>>);
|
||||
|
||||
impl Renderable for DaemonMenuHeader {
|
||||
fn render(&self, area: Rect, buf: &mut Buffer) {
|
||||
Renderable::render(
|
||||
&Paragraph::new(word_wrap_lines(&self.0, usize::from(area.width))),
|
||||
area,
|
||||
buf,
|
||||
);
|
||||
}
|
||||
|
||||
fn desired_height(&self, width: u16) -> u16 {
|
||||
word_wrap_lines(&self.0, usize::from(width)).len() as u16
|
||||
}
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub(super) async fn verify_managed_daemon(&mut self) {
|
||||
// A discovered socket alone does not prove it belongs to a managed daemon.
|
||||
// Probe only when the user opens a view that offers restart, never during startup.
|
||||
if !self.reconnect.offline
|
||||
&& let Some(connection) = &mut self.chat_widget.remote_connection
|
||||
&& connection.is_local_daemon
|
||||
&& !connection.is_managed_daemon
|
||||
{
|
||||
connection.is_managed_daemon =
|
||||
akode_app_server_daemon::run(akode_app_server_daemon::LifecycleCommand::Version)
|
||||
.await
|
||||
.is_ok_and(|output| output.backend.is_some());
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn open_daemon_menu(&mut self) {
|
||||
let status = self
|
||||
.chat_widget
|
||||
.remote_connection
|
||||
.as_ref()
|
||||
.filter(|_| matches!(self.app_server_target, AppServerTarget::LocalDaemon { .. }))
|
||||
.map(|connection| format!("Running daemon: {}", connection.version))
|
||||
.unwrap_or_else(|| "Not connected to the local background server.".to_string());
|
||||
let mut header = vec![Line::from("Daemon".bold()), Line::from(status.dim())];
|
||||
let unavailable = if matches!(
|
||||
self.app_server_target,
|
||||
AppServerTarget::Remote { .. } | AppServerTarget::Cloud
|
||||
) {
|
||||
Some(
|
||||
"Manage this server on its host. Local daemon updates are unavailable for remote connections.",
|
||||
)
|
||||
} else if self.daemon_cli_executable.is_none() {
|
||||
Some("Run the aKode CLI to manage the daemon from this menu.")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(guidance) = unavailable {
|
||||
header.push(Line::from(guidance.dim()));
|
||||
}
|
||||
let has_package = self.daemon_cli_executable.as_ref().is_some_and(|path| {
|
||||
akode_install_context::InstallContext::from_exe(
|
||||
cfg!(target_os = "macos"),
|
||||
Some(path.as_path()),
|
||||
/*method_override*/ None,
|
||||
)
|
||||
.package_layout
|
||||
.is_some()
|
||||
});
|
||||
let mut items: Vec<SelectionItem> = [
|
||||
(
|
||||
DaemonUpdateSource::PublicStable,
|
||||
"Install latest public stable",
|
||||
),
|
||||
(DaemonUpdateSource::ThisCli, "Use this CLI build"),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(source, name)| SelectionItem {
|
||||
name: name.to_string(),
|
||||
is_disabled: unavailable.is_some(),
|
||||
disabled_reason: (unavailable.is_none()
|
||||
&& source == DaemonUpdateSource::ThisCli
|
||||
&& !has_package)
|
||||
.then(|| "This CLI has no local package to copy".to_string()),
|
||||
actions: vec![Box::new(move |tx| {
|
||||
tx.send(AppEvent::ConfirmDaemonUpdate(source));
|
||||
})],
|
||||
dismiss_on_select: true,
|
||||
..Default::default()
|
||||
})
|
||||
.collect();
|
||||
items.push(SelectionItem {
|
||||
name: "Restart background server".to_string(),
|
||||
is_disabled: !self
|
||||
.chat_widget
|
||||
.remote_connection
|
||||
.as_ref()
|
||||
.is_some_and(|connection| connection.is_managed_daemon)
|
||||
|| self.reconnect.offline
|
||||
|| self.daemon_restart.is_some(),
|
||||
disabled_reason: self
|
||||
.chat_widget
|
||||
.remote_connection
|
||||
.as_ref()
|
||||
.filter(|connection| connection.is_local_daemon && !connection.is_managed_daemon)
|
||||
.map(|_| {
|
||||
"aKode hasn't verified it manages this server. Restart it where it was started."
|
||||
.to_string()
|
||||
}),
|
||||
actions: vec![Box::new(|tx| tx.send(AppEvent::ConfirmDaemonRestart))],
|
||||
dismiss_on_select: true,
|
||||
..Default::default()
|
||||
});
|
||||
self.chat_widget.show_selection_view(SelectionViewParams {
|
||||
header: Box::new(DaemonMenuHeader(header)),
|
||||
items,
|
||||
..SelectionViewParams::picker()
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn confirm_daemon_restart(&mut self) {
|
||||
if !self
|
||||
.chat_widget
|
||||
.remote_connection
|
||||
.as_ref()
|
||||
.is_some_and(|connection| connection.is_managed_daemon)
|
||||
|| self.daemon_restart.is_some()
|
||||
{
|
||||
return;
|
||||
}
|
||||
self.chat_widget.show_selection_view(SelectionViewParams {
|
||||
header: Box::new(DaemonMenuHeader(vec![
|
||||
Line::from("Restart background server?".bold()),
|
||||
Line::from("Active or queued work in other chats may be interrupted."),
|
||||
Line::from("aKode will reconnect automatically."),
|
||||
])),
|
||||
items: vec![
|
||||
SelectionItem {
|
||||
name: "Cancel".to_string(),
|
||||
dismiss_on_select: true,
|
||||
..Default::default()
|
||||
},
|
||||
SelectionItem {
|
||||
name: "Restart".to_string(),
|
||||
actions: vec![Box::new(|tx| tx.send(AppEvent::RunDaemonRestart))],
|
||||
require_explicit_confirmation: true,
|
||||
dismiss_on_select: true,
|
||||
..Default::default()
|
||||
},
|
||||
],
|
||||
..SelectionViewParams::confirmation()
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn confirm_daemon_update(&mut self, source: DaemonUpdateSource) {
|
||||
let Some(executable) = &self.daemon_cli_executable else {
|
||||
return;
|
||||
};
|
||||
if matches!(
|
||||
self.app_server_target,
|
||||
AppServerTarget::Remote { .. } | AppServerTarget::Cloud
|
||||
) {
|
||||
return;
|
||||
}
|
||||
let mut explanation = match source {
|
||||
DaemonUpdateSource::PublicStable => "Install the latest public stable release. Restore production updates; keep your automatic-update setting.".to_string(),
|
||||
DaemonUpdateSource::ThisCli => {
|
||||
let version = akode_install_context::InstallContext::current()
|
||||
.package_manifest()
|
||||
.map_or_else(|| AKODE_CLI_VERSION.to_string(), |manifest| manifest.version.to_string());
|
||||
format!("Use this CLI package v{version} from {}. Copy the complete package and pin it against automatic updates.", executable.display())
|
||||
}
|
||||
};
|
||||
explanation.push_str("\nThis may restart the daemon and interrupt active or queued work.\nCodex exits to update in this terminal. Relaunch it afterward.");
|
||||
let mut header = vec![Line::from("Update daemon and exit aKode?".bold())];
|
||||
header.extend(explanation.lines().map(|line| Line::from(line.to_owned())));
|
||||
self.chat_widget.show_selection_view(SelectionViewParams {
|
||||
header: Box::new(DaemonMenuHeader(header)),
|
||||
items: vec![
|
||||
SelectionItem {
|
||||
name: "Cancel".to_string(),
|
||||
dismiss_on_select: true,
|
||||
..Default::default()
|
||||
},
|
||||
SelectionItem {
|
||||
name: "Update and exit".to_string(),
|
||||
actions: vec![Box::new(move |tx| {
|
||||
tx.send(AppEvent::RunDaemonUpdate(source))
|
||||
})],
|
||||
require_explicit_confirmation: true,
|
||||
dismiss_on_select: true,
|
||||
..Default::default()
|
||||
},
|
||||
],
|
||||
..SelectionViewParams::confirmation()
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "daemon_menu_tests.rs"]
|
||||
mod tests;
|
||||
323
akode-rs/tui/src/app/daemon_menu_tests.rs
Normal file
323
akode-rs/tui/src/app/daemon_menu_tests.rs
Normal file
@@ -0,0 +1,323 @@
|
||||
use super::*;
|
||||
use crate::app::test_support::make_test_app;
|
||||
use crate::chatwidget::tests::helpers::render_bottom_popup;
|
||||
use crate::chatwidget::tests::make_chatwidget_manual_with_sender;
|
||||
use crate::status::remote_connection::RemoteConnectionStatus;
|
||||
use crossterm::event::KeyCode;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn daemon_version_notice_preserves_manual_update_guidance() {
|
||||
let mut app = make_test_app().await;
|
||||
app.app_server_target = AppServerTarget::LocalDaemon {
|
||||
allow_embedded_fallback: true,
|
||||
endpoint: crate::RemoteAppServerEndpoint::UnixSocket {
|
||||
socket_path: AbsolutePathBuf::relative_to_current_dir("akode.sock").unwrap(),
|
||||
},
|
||||
};
|
||||
let view = app.agents_overview_view(Vec::new(), /*selected_thread_id*/ None);
|
||||
app.chat_widget.show_bottom_pane_view(Box::new(view));
|
||||
let mut notices = Vec::new();
|
||||
for (client, server, comparison) in [
|
||||
("0.155.0-alpha.23", "0.155.0-alpha.22", "older than"),
|
||||
("0.155.0-alpha.23", "0.156.0", "different from"),
|
||||
("0.0.0", "0.156.0", "different from"),
|
||||
] {
|
||||
app.local_settings.tui.show_server_version_notice = true;
|
||||
assert_eq!(
|
||||
app.initialize_server_version_notice(client, Some(server)),
|
||||
Some(format!(
|
||||
"A background aKode service is running v{server}, {comparison} your aKode CLI v{client}."
|
||||
))
|
||||
);
|
||||
let overview = render_bottom_popup(&app.chat_widget, /*width*/ 100);
|
||||
notices.push(
|
||||
overview
|
||||
.lines()
|
||||
.find(|line| line.contains("Service v"))
|
||||
.unwrap()
|
||||
.trim()
|
||||
.to_string(),
|
||||
);
|
||||
assert_eq!(app.pending_update_action, None);
|
||||
|
||||
app.local_settings.tui.show_server_version_notice = false;
|
||||
assert_eq!(
|
||||
app.initialize_server_version_notice(client, Some(server)),
|
||||
None
|
||||
);
|
||||
assert_eq!(
|
||||
app.agents_overview
|
||||
.view_state
|
||||
.lock()
|
||||
.unwrap()
|
||||
.server_version_notice,
|
||||
None
|
||||
);
|
||||
}
|
||||
insta::assert_snapshot!(notices.join("\n"), @"
|
||||
Service v0.155.0-alpha.22 < aKode CLI v0.155.0-alpha.23 · /daemon
|
||||
Service v0.156.0 ≠ aKode CLI v0.155.0-alpha.23 · /daemon
|
||||
Service v0.156.0 ≠ aKode CLI v0.0.0 · /daemon
|
||||
");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn daemon_menu_is_read_only_and_confirmation_can_cancel_or_handoff() {
|
||||
let mut app = make_test_app().await;
|
||||
let (chat, _, mut rx, _) = make_chatwidget_manual_with_sender().await;
|
||||
app.chat_widget = chat;
|
||||
let package = tempfile::tempdir().unwrap();
|
||||
std::fs::create_dir(package.path().join("bin")).unwrap();
|
||||
std::fs::write(package.path().join("bin/akode"), "CLI").unwrap();
|
||||
std::fs::write(package.path().join("akode-package.json"), "{}").unwrap();
|
||||
app.daemon_cli_executable =
|
||||
Some(AbsolutePathBuf::from_absolute_path(package.path().join("bin/akode")).unwrap());
|
||||
app.app_server_target = AppServerTarget::LocalDaemon {
|
||||
allow_embedded_fallback: true,
|
||||
endpoint: crate::RemoteAppServerEndpoint::UnixSocket {
|
||||
socket_path: AbsolutePathBuf::relative_to_current_dir("akode.sock").unwrap(),
|
||||
},
|
||||
};
|
||||
app.chat_widget.remote_connection = Some(RemoteConnectionStatus {
|
||||
address: "local".into(),
|
||||
version: "v0.153.0".into(),
|
||||
is_local_daemon: true,
|
||||
is_managed_daemon: true,
|
||||
});
|
||||
app.initialize_server_version_notice("0.154.0", Some("0.153.0"));
|
||||
let view = app.agents_overview_view(Vec::new(), /*selected_thread_id*/ None);
|
||||
app.chat_widget.show_bottom_pane_view(Box::new(view));
|
||||
let overview = render_bottom_popup(&app.chat_widget, /*width*/ 80);
|
||||
insta::assert_snapshot!(overview.lines().find(|line| line.contains("Service v")).unwrap().trim(), @"Service v0.153.0 < aKode CLI v0.154.0 · /daemon");
|
||||
let executable = app.daemon_cli_executable.clone();
|
||||
for (width, source, snapshot) in [
|
||||
(
|
||||
80,
|
||||
DaemonUpdateSource::PublicStable,
|
||||
"daemon_stable_confirmation",
|
||||
),
|
||||
(100, DaemonUpdateSource::ThisCli, "daemon_cli_confirmation"),
|
||||
] {
|
||||
app.daemon_cli_executable = executable.clone();
|
||||
app.open_daemon_menu();
|
||||
if source == DaemonUpdateSource::PublicStable {
|
||||
insta::assert_snapshot!(
|
||||
"daemon_menu",
|
||||
render_bottom_popup(&app.chat_widget, /*width*/ 80)
|
||||
);
|
||||
} else {
|
||||
app.chat_widget.handle_key_event(KeyCode::Down.into());
|
||||
}
|
||||
assert!(rx.try_recv().is_err());
|
||||
app.chat_widget.handle_key_event(KeyCode::Enter.into());
|
||||
assert!(
|
||||
matches!(rx.try_recv().unwrap(), AppEvent::ConfirmDaemonUpdate(selected) if selected == source)
|
||||
);
|
||||
app.daemon_cli_executable = Some(
|
||||
AbsolutePathBuf::from_absolute_path(if cfg!(windows) {
|
||||
r"C:\cli-build\bin\codex"
|
||||
} else {
|
||||
"/x/cli-build/bin/akode"
|
||||
})
|
||||
.unwrap(),
|
||||
);
|
||||
app.confirm_daemon_update(source);
|
||||
insta::assert_snapshot!(
|
||||
snapshot,
|
||||
render_bottom_popup(&app.chat_widget, width)
|
||||
.replace(r"C:\cli-build\bin\codex", "/x/cli-build/bin/akode")
|
||||
);
|
||||
// The default choice cancels without emitting an update or exiting.
|
||||
app.chat_widget.handle_key_event(KeyCode::Enter.into());
|
||||
assert!(rx.try_recv().is_err());
|
||||
assert_eq!(app.pending_update_action, None);
|
||||
app.confirm_daemon_update(source);
|
||||
app.chat_widget.handle_key_event(KeyCode::Down.into());
|
||||
app.chat_widget.handle_key_event(KeyCode::Enter.into());
|
||||
assert!(
|
||||
matches!(rx.try_recv().unwrap(), AppEvent::RunDaemonUpdate(selected) if selected == source)
|
||||
);
|
||||
}
|
||||
|
||||
app.daemon_cli_executable = executable.clone();
|
||||
app.open_daemon_menu();
|
||||
let mut terminal = crate::custom_terminal::Terminal::with_options(
|
||||
crate::test_backend::VT100Backend::new(/*width*/ 120, /*height*/ 30),
|
||||
)
|
||||
.unwrap();
|
||||
let area = Rect::new(0, 0, 120, 30);
|
||||
terminal.set_viewport_area(area);
|
||||
crate::terminal_palette::with_test_default_colors(
|
||||
crate::terminal_probe::DefaultColors {
|
||||
fg: (229, 229, 229),
|
||||
bg: (30, 40, 56),
|
||||
},
|
||||
|| {
|
||||
terminal
|
||||
.draw(|frame| app.chat_widget.render(area, frame.buffer_mut()))
|
||||
.unwrap()
|
||||
},
|
||||
);
|
||||
app.chat_widget.handle_key_event(KeyCode::Down.into());
|
||||
app.chat_widget.handle_key_event(KeyCode::Down.into());
|
||||
app.chat_widget.handle_key_event(KeyCode::Enter.into());
|
||||
assert!(matches!(
|
||||
rx.try_recv().unwrap(),
|
||||
AppEvent::ConfirmDaemonRestart
|
||||
));
|
||||
app.confirm_daemon_restart();
|
||||
insta::assert_snapshot!(
|
||||
"daemon_restart_confirmation",
|
||||
render_bottom_popup(&app.chat_widget, /*width*/ 80)
|
||||
);
|
||||
crate::terminal_palette::with_test_default_colors(
|
||||
crate::terminal_probe::DefaultColors {
|
||||
fg: (229, 229, 229),
|
||||
bg: (30, 40, 56),
|
||||
},
|
||||
|| {
|
||||
// Simulate a terminal that erased the menu's blank tails with its default
|
||||
// background rather than the cached panel color.
|
||||
use std::io::Write;
|
||||
for y in 0..area.height {
|
||||
write!(terminal.backend_mut(), "\x1b[{};25H\x1b[0m\x1b[K", y + 1).unwrap();
|
||||
}
|
||||
terminal
|
||||
.draw(|frame| app.chat_widget.render(area, frame.buffer_mut()))
|
||||
.unwrap();
|
||||
let expected = crate::custom_terminal::test_support::last_rendered_buffer(&terminal);
|
||||
let screen = terminal.backend().vt100().screen();
|
||||
for y in 0..area.height {
|
||||
for x in 24..96 {
|
||||
let expected_bg = match expected[(x, y)].bg {
|
||||
ratatui::style::Color::Rgb(r, g, b) => vt100::Color::Rgb(r, g, b),
|
||||
ratatui::style::Color::Reset => vt100::Color::Default,
|
||||
_ => continue,
|
||||
};
|
||||
assert_eq!(
|
||||
screen.cell(y, x).unwrap().bgcolor(),
|
||||
expected_bg,
|
||||
"at {x}, {y}: {:?}",
|
||||
expected[(x, y)]
|
||||
);
|
||||
}
|
||||
}
|
||||
},
|
||||
);
|
||||
// Cancel is the default; a confirmed restart stays in the TUI.
|
||||
app.chat_widget.handle_key_event(KeyCode::Enter.into());
|
||||
assert!(rx.try_recv().is_err());
|
||||
app.confirm_daemon_restart();
|
||||
app.chat_widget.handle_key_event(KeyCode::Down.into());
|
||||
app.chat_widget.handle_key_event(KeyCode::Enter.into());
|
||||
assert!(matches!(rx.try_recv().unwrap(), AppEvent::RunDaemonRestart));
|
||||
|
||||
// A local socket alone does not mean Codex can restart its owner.
|
||||
app.chat_widget
|
||||
.remote_connection
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.is_managed_daemon = false;
|
||||
app.open_daemon_menu();
|
||||
insta::assert_snapshot!(
|
||||
"daemon_unmanaged",
|
||||
render_bottom_popup(&app.chat_widget, /*width*/ 80)
|
||||
);
|
||||
app.chat_widget.handle_key_event(KeyCode::Down.into());
|
||||
app.chat_widget.handle_key_event(KeyCode::Down.into());
|
||||
app.chat_widget.handle_key_event(KeyCode::Enter.into());
|
||||
assert!(matches!(
|
||||
rx.try_recv().unwrap(),
|
||||
AppEvent::ConfirmDaemonUpdate(_)
|
||||
));
|
||||
app.confirm_daemon_restart();
|
||||
assert!(rx.try_recv().is_err());
|
||||
|
||||
// Maintenance remains available when startup selects the embedded server.
|
||||
app.app_server_target = AppServerTarget::Embedded;
|
||||
app.chat_widget.remote_connection = None;
|
||||
app.daemon_cli_executable = executable;
|
||||
for source in [
|
||||
DaemonUpdateSource::PublicStable,
|
||||
DaemonUpdateSource::ThisCli,
|
||||
] {
|
||||
app.open_daemon_menu();
|
||||
if source == DaemonUpdateSource::PublicStable {
|
||||
insta::assert_snapshot!(
|
||||
"daemon_disconnected",
|
||||
render_bottom_popup(&app.chat_widget, /*width*/ 80)
|
||||
);
|
||||
} else {
|
||||
app.chat_widget.handle_key_event(KeyCode::Down.into());
|
||||
}
|
||||
assert!(rx.try_recv().is_err());
|
||||
app.chat_widget.handle_key_event(KeyCode::Enter.into());
|
||||
assert!(
|
||||
matches!(rx.try_recv().unwrap(), AppEvent::ConfirmDaemonUpdate(selected) if selected == source)
|
||||
);
|
||||
app.confirm_daemon_update(source);
|
||||
app.chat_widget.handle_key_event(KeyCode::Enter.into());
|
||||
assert!(rx.try_recv().is_err());
|
||||
assert_eq!(app.pending_update_action, None);
|
||||
app.confirm_daemon_update(source);
|
||||
app.chat_widget.handle_key_event(KeyCode::Down.into());
|
||||
app.chat_widget.handle_key_event(KeyCode::Enter.into());
|
||||
assert!(
|
||||
matches!(rx.try_recv().unwrap(), AppEvent::RunDaemonUpdate(selected) if selected == source)
|
||||
);
|
||||
}
|
||||
|
||||
std::fs::remove_file(package.path().join("akode-package.json")).unwrap();
|
||||
// The full CLI can have any filename; capability comes from its entry point.
|
||||
app.daemon_cli_executable =
|
||||
Some(AbsolutePathBuf::from_absolute_path(package.path().join("bin/akode-tui")).unwrap());
|
||||
app.open_daemon_menu();
|
||||
insta::assert_snapshot!(
|
||||
"daemon_unpackaged_cli",
|
||||
render_bottom_popup(&app.chat_widget, /*width*/ 80)
|
||||
);
|
||||
app.chat_widget.handle_key_event(KeyCode::Enter.into());
|
||||
assert!(matches!(
|
||||
rx.try_recv().unwrap(),
|
||||
AppEvent::ConfirmDaemonUpdate(DaemonUpdateSource::PublicStable)
|
||||
));
|
||||
|
||||
app.daemon_cli_executable = None;
|
||||
app.open_daemon_menu();
|
||||
insta::assert_snapshot!(
|
||||
"daemon_no_cli_handoff",
|
||||
render_bottom_popup(&app.chat_widget, /*width*/ 80)
|
||||
);
|
||||
app.chat_widget.handle_key_event(KeyCode::Enter.into());
|
||||
assert!(rx.try_recv().is_err());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unavailable_daemon_menu_offers_guidance_without_update_actions() {
|
||||
let mut app = make_test_app().await;
|
||||
app.daemon_cli_executable =
|
||||
Some(AbsolutePathBuf::from_absolute_path(std::env::current_exe().unwrap()).unwrap());
|
||||
let (chat, _, mut rx, _) = make_chatwidget_manual_with_sender().await;
|
||||
app.chat_widget = chat;
|
||||
app.app_server_target = AppServerTarget::Remote {
|
||||
endpoint: crate::RemoteAppServerEndpoint::WebSocket {
|
||||
websocket_url: "ws://example.test:1234".into(),
|
||||
auth_token: None,
|
||||
},
|
||||
};
|
||||
app.chat_widget.remote_connection = Some(RemoteConnectionStatus {
|
||||
address: "ws://example.test:1234".into(),
|
||||
version: "v0.153.0".into(),
|
||||
is_local_daemon: false,
|
||||
is_managed_daemon: false,
|
||||
});
|
||||
app.open_daemon_menu();
|
||||
insta::assert_snapshot!(
|
||||
"daemon_remote_guidance",
|
||||
render_bottom_popup(&app.chat_widget, /*width*/ 80)
|
||||
);
|
||||
app.chat_widget.handle_key_event(KeyCode::Enter.into());
|
||||
assert!(rx.try_recv().is_err());
|
||||
assert_eq!(app.pending_update_action, None);
|
||||
}
|
||||
322
akode-rs/tui/src/app/empty_state_animation_tests.rs
Normal file
322
akode-rs/tui/src/app/empty_state_animation_tests.rs
Normal file
@@ -0,0 +1,322 @@
|
||||
//! Empty-state decoration integration uses the actual owned-screen draw path.
|
||||
//! Startup content opts in; other history dismisses the logo independently of viewport space.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use ratatui::buffer::Buffer;
|
||||
|
||||
fn has_splash(tui: &tui::Tui) -> bool {
|
||||
text(crate::custom_terminal::test_support::last_rendered_buffer(
|
||||
&tui.terminal,
|
||||
))
|
||||
.contains(crate::branding::WELCOME_LINE)
|
||||
}
|
||||
|
||||
fn text(buffer: &Buffer) -> String {
|
||||
let project = crate::test_support::test_path_display("/tmp/project");
|
||||
let normalized_project = format!("{:<width$}", "/tmp/project", width = project.len());
|
||||
buffer
|
||||
.content
|
||||
.chunks(usize::from(buffer.area.width))
|
||||
.map(|row| {
|
||||
row.iter()
|
||||
.map(ratatui::buffer::Cell::symbol)
|
||||
.collect::<String>()
|
||||
.replace(&project, &normalized_project)
|
||||
.trim_end()
|
||||
.to_string()
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
fn draw(app: &mut App, tui: &mut tui::Tui, size: Size) -> Result<Rect> {
|
||||
tui.screen_size_for_event(&TuiEvent::Resize(size))?;
|
||||
app.render_owned_transcript(tui, size)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn fresh_logo_returns_only_to_the_ordinary_composer() -> Result<()> {
|
||||
let mut app = crate::app::test_support::make_test_app().await;
|
||||
app.local_settings.tui.animations = true;
|
||||
let size = Size::new(/*width*/ 120, /*height*/ 44);
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
tui.set_owned_screen(/*owned*/ true)?;
|
||||
app.queue_clear_ui_header(&mut tui);
|
||||
app.chat_widget
|
||||
.empty_state_animation
|
||||
.borrow_mut()
|
||||
.start_fresh();
|
||||
draw(&mut app, &mut tui, size)?;
|
||||
let cursor = tui.terminal.last_known_cursor_pos;
|
||||
assert!(has_splash(&tui));
|
||||
|
||||
app.open_transcript_overlay(&mut tui);
|
||||
draw(&mut app, &mut tui, size)?;
|
||||
assert!(!has_splash(&tui));
|
||||
assert_eq!(tui.terminal.last_known_cursor_pos, cursor);
|
||||
app.close_transcript_overlay(&mut tui);
|
||||
draw(&mut app, &mut tui, size)?;
|
||||
assert!(has_splash(&tui));
|
||||
|
||||
app.transcript_view.begin_search();
|
||||
draw(&mut app, &mut tui, size)?;
|
||||
assert!(!has_splash(&tui));
|
||||
app.transcript_view.handle_key(
|
||||
KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE),
|
||||
&app.transcript_cells,
|
||||
);
|
||||
draw(&mut app, &mut tui, size)?;
|
||||
assert!(has_splash(&tui));
|
||||
|
||||
for enabled in [true, false] {
|
||||
app.apply_raw_output_mode(&mut tui, enabled, /*notify*/ false);
|
||||
draw(&mut app, &mut tui, size)?;
|
||||
assert_eq!(has_splash(&tui), !enabled);
|
||||
}
|
||||
app.chat_widget.apply_external_edit(String::new());
|
||||
for (key, visible) in [(KeyCode::Char('?'), false), (KeyCode::Right, true)] {
|
||||
app.chat_widget
|
||||
.handle_key_event(KeyEvent::new(key, KeyModifiers::NONE));
|
||||
draw(&mut app, &mut tui, size)?;
|
||||
assert_eq!(has_splash(&tui), visible);
|
||||
}
|
||||
tui.set_owned_screen(/*owned*/ false)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn non_startup_history_dismisses_logo_until_a_new_thread() -> Result<()> {
|
||||
let mut app = crate::app::test_support::make_test_app().await;
|
||||
app.local_settings.tui.animations = true;
|
||||
// Leave room for the full release-note card above the centered logo.
|
||||
let size = Size::new(/*width*/ 120, /*height*/ 64);
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
tui.set_owned_screen(/*owned*/ true)?;
|
||||
app.chat_widget
|
||||
.empty_state_animation
|
||||
.borrow_mut()
|
||||
.start_fresh();
|
||||
app.queue_clear_ui_header(&mut tui);
|
||||
app.insert_history_cell(
|
||||
&mut tui,
|
||||
Box::new(history_cell::StartupWarningsCell::new(vec![
|
||||
"Startup notice".into(),
|
||||
])),
|
||||
);
|
||||
app.insert_history_cell(
|
||||
&mut tui,
|
||||
Box::new(history_cell::new_deprecation_notice(
|
||||
"Deprecated setting".into(),
|
||||
/*details*/ None,
|
||||
)),
|
||||
);
|
||||
app.insert_history_cell(
|
||||
&mut tui,
|
||||
Box::new(history_cell::new_server_version_warning(
|
||||
crate::status::remote_connection::ServerVersionNotice {
|
||||
message: "Server version differs from the client".into(),
|
||||
offer_update: false,
|
||||
},
|
||||
)),
|
||||
);
|
||||
app.insert_history_cell(
|
||||
&mut tui,
|
||||
Box::new(history_cell::UpdateAvailableHistoryCell::new(
|
||||
"99.0.0".into(),
|
||||
/*update_action*/ None,
|
||||
)),
|
||||
);
|
||||
app.insert_history_cell(
|
||||
&mut tui,
|
||||
Box::new(history_cell::SessionNoticeCell(
|
||||
history_cell::PlainHistoryCell::new(vec!["Rate limit reset notice".into()]),
|
||||
)),
|
||||
);
|
||||
draw(&mut app, &mut tui, size)?;
|
||||
assert!(has_splash(&tui));
|
||||
|
||||
// Even invisible non-startup content ends eligibility before a frame or clear can erase it.
|
||||
app.insert_history_cell(
|
||||
&mut tui,
|
||||
Box::new(history_cell::PlainHistoryCell::new(Vec::new())),
|
||||
);
|
||||
app.reset_transcript_state_after_clear();
|
||||
app.queue_clear_ui_header(&mut tui);
|
||||
draw(&mut app, &mut tui, size)?;
|
||||
assert!(!has_splash(&tui));
|
||||
app.chat_widget
|
||||
.empty_state_animation
|
||||
.borrow_mut()
|
||||
.start_fresh();
|
||||
draw(&mut app, &mut tui, size)?;
|
||||
assert!(has_splash(&tui));
|
||||
tui.set_owned_screen(/*owned*/ false)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn empty_state_animation_preserves_header_cursor_and_footer() -> Result<()> {
|
||||
let mut app = crate::app::test_support::make_test_app().await;
|
||||
app.local_settings.tui.animations = true;
|
||||
let size = Size::new(/*width*/ 120, /*height*/ 44);
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
tui.set_owned_screen(/*owned*/ true)?;
|
||||
app.queue_clear_ui_header(&mut tui);
|
||||
app.transcript_cells
|
||||
.push(Arc::new(history_cell::StartupWarningsCell::mcp(
|
||||
vec!["Example MCP is unavailable".to_string()],
|
||||
["example".to_string()],
|
||||
/*failure_reason*/ None,
|
||||
)));
|
||||
let before_bottom = draw(&mut app, &mut tui, size)?;
|
||||
let history_len = app.transcript_cells.len();
|
||||
let before = crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal).clone();
|
||||
let cursor = tui.terminal.last_known_cursor_pos;
|
||||
assert!(!has_splash(&tui));
|
||||
app.chat_widget
|
||||
.empty_state_animation
|
||||
.borrow_mut()
|
||||
.start_fresh();
|
||||
assert_eq!(draw(&mut app, &mut tui, size)?, before_bottom);
|
||||
let after = crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal);
|
||||
assert!(has_splash(&tui));
|
||||
assert_eq!(tui.terminal.last_known_cursor_pos, cursor);
|
||||
assert_eq!(
|
||||
&after.content[after.index_of(/*x*/ 0, before_bottom.y)..],
|
||||
&before.content[before.index_of(/*x*/ 0, before_bottom.y)..]
|
||||
);
|
||||
insta::assert_snapshot!(
|
||||
"fresh_thread_header",
|
||||
format!(
|
||||
"enabled:\n{}\n---\ndisabled:\n{}",
|
||||
text(after),
|
||||
text(&before)
|
||||
)
|
||||
);
|
||||
let short = Size::new(/*width*/ 120, /*height*/ 12);
|
||||
draw(&mut app, &mut tui, short)?;
|
||||
assert!(!has_splash(&tui));
|
||||
draw(&mut app, &mut tui, size)?;
|
||||
assert!(has_splash(&tui));
|
||||
|
||||
app.chat_widget.apply_external_edit("/m".to_string());
|
||||
draw(&mut app, &mut tui, size)?;
|
||||
assert!(!has_splash(&tui));
|
||||
app.chat_widget.apply_external_edit(String::new());
|
||||
draw(&mut app, &mut tui, size)?;
|
||||
assert!(has_splash(&tui));
|
||||
assert_eq!(app.transcript_cells.len(), history_len);
|
||||
app.local_settings.tui.animations = false;
|
||||
draw(&mut app, &mut tui, size)?;
|
||||
let disabled = crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal);
|
||||
assert_eq!(disabled, &before);
|
||||
app.local_settings.tui.animations = true;
|
||||
app.local_settings.tui.effects.welcome = false;
|
||||
draw(&mut app, &mut tui, size)?;
|
||||
assert_eq!(
|
||||
crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal),
|
||||
&before
|
||||
);
|
||||
app.local_settings.tui.effects.welcome = true;
|
||||
app.local_settings.tui.effects.shimmer = false;
|
||||
draw(&mut app, &mut tui, size)?;
|
||||
assert!(has_splash(&tui));
|
||||
tui.set_owned_screen(/*owned*/ false)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn submitting_a_draft_dismisses_logo_even_after_clear() -> Result<()> {
|
||||
let (mut app, _events, _ops) = crate::app::tests::make_test_app_with_channels().await;
|
||||
app.local_settings.tui.animations = true;
|
||||
let size = Size::new(/*width*/ 120, /*height*/ 44);
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
tui.set_owned_screen(/*owned*/ true)?;
|
||||
app.queue_clear_ui_header(&mut tui);
|
||||
app.chat_widget
|
||||
.empty_state_animation
|
||||
.borrow_mut()
|
||||
.start_fresh();
|
||||
draw(&mut app, &mut tui, size)?;
|
||||
assert!(has_splash(&tui));
|
||||
app.chat_widget
|
||||
.apply_external_edit("first prompt".to_string());
|
||||
draw(&mut app, &mut tui, size)?;
|
||||
let drafting = crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal);
|
||||
assert!(!has_splash(&tui));
|
||||
assert!(text(drafting).contains("first prompt"));
|
||||
app.chat_widget.apply_external_edit(String::new());
|
||||
draw(&mut app, &mut tui, size)?;
|
||||
assert!(has_splash(&tui));
|
||||
app.chat_widget
|
||||
.apply_external_edit("first prompt".to_string());
|
||||
app.chat_widget
|
||||
.handle_key_event(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE));
|
||||
draw(&mut app, &mut tui, size)?;
|
||||
assert!(!has_splash(&tui));
|
||||
let short = Size::new(/*width*/ 120, /*height*/ 8);
|
||||
draw(&mut app, &mut tui, short)?;
|
||||
draw(&mut app, &mut tui, size)?;
|
||||
assert!(!has_splash(&tui));
|
||||
app.reset_transcript_state_after_clear();
|
||||
draw(&mut app, &mut tui, size)?;
|
||||
assert!(!has_splash(&tui));
|
||||
tui.set_owned_screen(/*owned*/ false)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn empty_state_animation_survives_plain_transcript_clicks() -> Result<()> {
|
||||
use crossterm::event::MouseButton;
|
||||
use crossterm::event::MouseEvent;
|
||||
use crossterm::event::MouseEventKind;
|
||||
|
||||
let mut app = crate::app::test_support::make_test_app().await;
|
||||
app.local_settings.tui.animations = true;
|
||||
let size = Size::new(/*width*/ 120, /*height*/ 44);
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
tui.set_owned_screen(/*owned*/ true)?;
|
||||
app.queue_clear_ui_header(&mut tui);
|
||||
app.chat_widget
|
||||
.empty_state_animation
|
||||
.borrow_mut()
|
||||
.start_fresh();
|
||||
draw(&mut app, &mut tui, size)?;
|
||||
let cursor = tui.terminal.last_known_cursor_pos;
|
||||
for (kind, column, visible) in [
|
||||
(MouseEventKind::Down(MouseButton::Left), 4, true),
|
||||
(MouseEventKind::Up(MouseButton::Left), 4, true),
|
||||
(MouseEventKind::Down(MouseButton::Left), 7, true),
|
||||
(MouseEventKind::Drag(MouseButton::Left), 18, false),
|
||||
(MouseEventKind::Up(MouseButton::Left), 18, false),
|
||||
] {
|
||||
app.transcript_view.handle_mouse(
|
||||
MouseEvent {
|
||||
kind,
|
||||
column,
|
||||
row: 1,
|
||||
modifiers: KeyModifiers::NONE,
|
||||
},
|
||||
&app.transcript_cells,
|
||||
);
|
||||
draw(&mut app, &mut tui, size)?;
|
||||
assert_eq!(has_splash(&tui), visible);
|
||||
if visible {
|
||||
assert_eq!(tui.terminal.last_known_cursor_pos, cursor);
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
app.transcript_view
|
||||
.selected_text(&app.transcript_cells)
|
||||
.is_some()
|
||||
);
|
||||
app.transcript_view.end_selection(&app.transcript_cells);
|
||||
draw(&mut app, &mut tui, size)?;
|
||||
assert!(!has_splash(&tui));
|
||||
app.transcript_view.jump_to_latest();
|
||||
draw(&mut app, &mut tui, size)?;
|
||||
assert!(has_splash(&tui));
|
||||
tui.set_owned_screen(/*owned*/ false)?;
|
||||
Ok(())
|
||||
}
|
||||
49
akode-rs/tui/src/app/empty_state_policy.rs
Normal file
49
akode-rs/tui/src/app/empty_state_policy.rs
Normal file
@@ -0,0 +1,49 @@
|
||||
//! Allow fresh-thread decoration only on the ordinary compact conversation surface.
|
||||
//! View changes hide it temporarily; non-startup content dismisses it until a new thread.
|
||||
|
||||
use super::*;
|
||||
use crate::empty_state_animation::ComposerState;
|
||||
use crate::empty_state_animation::is_startup_cell;
|
||||
use crate::history_cell::HistoryRenderMode;
|
||||
|
||||
impl App {
|
||||
pub(super) fn first_screen_composer(&self) -> Option<ComposerState> {
|
||||
if !self
|
||||
.transcript_cells
|
||||
.iter()
|
||||
.all(|cell| is_startup_cell(cell.as_ref()))
|
||||
{
|
||||
self.chat_widget
|
||||
.empty_state_animation
|
||||
.borrow_mut()
|
||||
.dismiss();
|
||||
}
|
||||
// Evaluate live content even while a different view temporarily owns the screen.
|
||||
let composer = self.chat_widget.empty_state_composer();
|
||||
let view = &self.transcript_view;
|
||||
match self.chat_widget.history_render_mode() {
|
||||
HistoryRenderMode::Raw => None,
|
||||
HistoryRenderMode::Rich => match (
|
||||
self.overlay.as_ref(),
|
||||
view.is_detailed(),
|
||||
view.is_search_editing(),
|
||||
view.is_activity_focused(),
|
||||
view.has_selection_range(),
|
||||
) {
|
||||
// A refocus click without selected text remains an ordinary conversation.
|
||||
(None, false, false, false, false)
|
||||
if (view.is_following() || view.has_pending_latest_selection())
|
||||
&& self.local_settings.tui.effects.welcome
|
||||
&& self
|
||||
.chat_widget
|
||||
.empty_state_animation
|
||||
.borrow()
|
||||
.is_eligible() =>
|
||||
{
|
||||
composer
|
||||
}
|
||||
_ => None,
|
||||
},
|
||||
}
|
||||
}
|
||||
}
|
||||
3899
akode-rs/tui/src/app/event_dispatch.rs
Normal file
3899
akode-rs/tui/src/app/event_dispatch.rs
Normal file
File diff suppressed because it is too large
Load Diff
148
akode-rs/tui/src/app/exit_summary.rs
Normal file
148
akode-rs/tui/src/app/exit_summary.rs
Normal file
@@ -0,0 +1,148 @@
|
||||
//! Exit output distinguishes a disconnected client from a stopped embedded server.
|
||||
//! Persisted sessions offer a direct UUID command and an optional named picker hint.
|
||||
|
||||
use super::*;
|
||||
use crate::RemoteAppServerEndpoint;
|
||||
use crate::exec_command::escape_command;
|
||||
use crate::status::remote_connection::sanitized_websocket_url;
|
||||
|
||||
/// A persisted thread that can be resumed after the TUI exits.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ResumableThread {
|
||||
pub thread_id: ThreadId,
|
||||
pub thread_name: Option<String>,
|
||||
}
|
||||
|
||||
/// Reconnection and stop guidance for a task owned by a persistent app server.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct DisconnectInfo {
|
||||
/// CLI arguments identifying the server, without credential values.
|
||||
pub command: Vec<String>,
|
||||
pub stop_hint: String,
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub(super) fn exit_info(&self, exit_reason: ExitReason) -> AppExitInfo {
|
||||
let thread_id = self.chat_widget.thread_id().or(self.primary_thread_id);
|
||||
let disconnect_info = thread_id.and_then(|_| {
|
||||
let command = match &self.app_server_target {
|
||||
AppServerTarget::Embedded | AppServerTarget::Cloud => return None,
|
||||
AppServerTarget::LocalDaemon { .. } => vec!["codex".to_string()],
|
||||
AppServerTarget::Remote { endpoint } => {
|
||||
let address = match endpoint {
|
||||
RemoteAppServerEndpoint::WebSocket { websocket_url, .. } => {
|
||||
sanitized_websocket_url(websocket_url)
|
||||
.and_then(|url| {
|
||||
let host = url.host()?;
|
||||
let port = url.port_or_known_default()?;
|
||||
// The CLI requires an explicit port, including 80/443.
|
||||
Some(format!("{}://{host}:{port}{}", url.scheme(), url.path()))
|
||||
})
|
||||
.unwrap_or_else(|| "<server-address>".to_string())
|
||||
}
|
||||
RemoteAppServerEndpoint::UnixSocket { socket_path } => {
|
||||
format!("unix://{}", socket_path.display())
|
||||
}
|
||||
};
|
||||
vec!["codex".to_string(), "--remote".to_string(), address]
|
||||
}
|
||||
};
|
||||
let stop_hint = self
|
||||
.keymap
|
||||
.agents
|
||||
.primary_hint("stop", &self.keymap.agents.stop)
|
||||
.map_or_else(
|
||||
|| "use the configured stop shortcut".to_string(),
|
||||
|key| format!("press {}", key.display_label()),
|
||||
);
|
||||
Some(DisconnectInfo { command, stop_hint })
|
||||
});
|
||||
AppExitInfo {
|
||||
token_usage: self.token_usage(),
|
||||
thread_id,
|
||||
resume_hint: resumable_thread(
|
||||
thread_id,
|
||||
self.chat_widget.thread_name(),
|
||||
self.chat_widget.rollout_path().as_deref(),
|
||||
),
|
||||
disconnect_info,
|
||||
update_action: self.pending_update_action,
|
||||
exit_reason,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl AppExitInfo {
|
||||
/// Format the terminal summary for both the CLI and standalone TUI binaries.
|
||||
pub fn format_exit_messages(self, color_enabled: bool) -> Vec<String> {
|
||||
let color_command = |command: String| {
|
||||
if color_enabled {
|
||||
format!("\u{1b}[36m{command}\u{1b}[39m")
|
||||
} else {
|
||||
command
|
||||
}
|
||||
};
|
||||
let mut lines = Vec::new();
|
||||
if let Some(disconnect) = self.disconnect_info
|
||||
&& let Some(thread_id) = self.thread_id
|
||||
{
|
||||
let turn_interrupted = matches!(self.exit_reason, ExitReason::TurnInterrupted);
|
||||
let message = match self.exit_reason {
|
||||
ExitReason::UserRequested => {
|
||||
"Disconnected from this task. Any running work continues."
|
||||
}
|
||||
ExitReason::Fatal(_) => "Disconnected from this task. Work may still be running.",
|
||||
ExitReason::TurnInterrupted => {
|
||||
"Disconnected from this task. The current turn was stopped."
|
||||
}
|
||||
};
|
||||
lines.push(message.to_string());
|
||||
let mut resume_command = disconnect.command.clone();
|
||||
resume_command.extend(["resume".to_string(), thread_id.to_string()]);
|
||||
lines.push("To reconnect, run:".to_string());
|
||||
lines.push(format!(
|
||||
" {}",
|
||||
color_command(escape_command(&resume_command)),
|
||||
));
|
||||
if !turn_interrupted {
|
||||
let mut agents_command = disconnect.command;
|
||||
agents_command.push("agents".to_string());
|
||||
lines.push(format!(
|
||||
"Stop the current turn: run {}, select this task, and {}.",
|
||||
color_command(escape_command(&agents_command)),
|
||||
disconnect.stop_hint,
|
||||
));
|
||||
}
|
||||
if !self.token_usage.is_zero() {
|
||||
let usage = self.token_usage.to_string();
|
||||
lines.push(if turn_interrupted {
|
||||
usage
|
||||
} else {
|
||||
usage.replacen("Token usage:", "Token usage so far:", /*count*/ 1)
|
||||
});
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
if !self.token_usage.is_zero() {
|
||||
lines.push(self.token_usage.to_string());
|
||||
}
|
||||
if let Some(thread) = self.resume_hint {
|
||||
lines.push("To continue this session, run:".to_string());
|
||||
lines.push(format!(
|
||||
" {}",
|
||||
color_command(format!("akode resume {}", thread.thread_id)),
|
||||
));
|
||||
if let Some(thread_name) = thread.thread_name.filter(|name| !name.is_empty()) {
|
||||
lines.push(format!(
|
||||
"Or run {} and select {}.",
|
||||
color_command("akode resume".to_string()),
|
||||
color_command(thread_name),
|
||||
));
|
||||
}
|
||||
} else if let Some(thread_id) = self.thread_id {
|
||||
lines.push(format!("Session ID: {thread_id}"));
|
||||
}
|
||||
lines
|
||||
}
|
||||
}
|
||||
119
akode-rs/tui/src/app/experimental_features.rs
Normal file
119
akode-rs/tui/src/app/experimental_features.rs
Normal file
@@ -0,0 +1,119 @@
|
||||
//! Server-backed feature persistence. Configured readback never replaces task state,
|
||||
//! and an accepted save finishes even if its popup closes or the user navigates.
|
||||
|
||||
use super::config_persistence::overridden_write_message;
|
||||
use super::*;
|
||||
use crate::experimental_features::FeatureWriteResult;
|
||||
use tokio::sync::oneshot;
|
||||
|
||||
impl App {
|
||||
pub(super) async fn enable_feature_for_new_threads(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
app_server: &AppServerSession,
|
||||
feature: Feature,
|
||||
) {
|
||||
let label = match feature {
|
||||
Feature::Collab => "Subagents",
|
||||
Feature::MemoryTool => "Memories",
|
||||
_ => return,
|
||||
};
|
||||
let mut edits = vec![crate::config_update::build_feature_enabled_edit(
|
||||
feature.key(),
|
||||
/*enabled*/ true,
|
||||
)];
|
||||
if feature == Feature::MemoryTool {
|
||||
// Older app servers still use the legacy key for this feature.
|
||||
edits.push(crate::config_update::build_feature_enabled_edit(
|
||||
"memory_tool",
|
||||
/*enabled*/ true,
|
||||
));
|
||||
}
|
||||
let notice: Box<dyn HistoryCell> = match crate::config_update::write_config_batch(
|
||||
app_server.request_handle(),
|
||||
edits,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(response) if response.status == WriteStatus::Ok => {
|
||||
Box::new(history_cell::new_warning_event(format!(
|
||||
"{label} setting saved on the server for new threads. This thread is unchanged. Project or task settings may override it."
|
||||
)))
|
||||
}
|
||||
Ok(response) => {
|
||||
self.transcript_view.jump_to_latest();
|
||||
Box::new(history_cell::new_error_event(format!(
|
||||
"{label} setting was saved but is overridden: {}",
|
||||
overridden_write_message(&response)
|
||||
)))
|
||||
}
|
||||
Err(err) => {
|
||||
self.transcript_view.jump_to_latest();
|
||||
Box::new(history_cell::new_error_event(format!(
|
||||
"Failed to save {label} setting: {}",
|
||||
crate::config_update::format_config_error(&err)
|
||||
)))
|
||||
}
|
||||
};
|
||||
self.insert_history_cell(tui, notice);
|
||||
}
|
||||
|
||||
pub(super) fn fetch_experimental_features(
|
||||
&self,
|
||||
app_server: &AppServerSession,
|
||||
thread_id: ThreadId,
|
||||
mut response_tx: oneshot::Sender<
|
||||
Result<Vec<akode_app_server_protocol::ExperimentalFeature>, String>,
|
||||
>,
|
||||
) {
|
||||
let lock = self.feature_write_lock.clone();
|
||||
let handle = app_server.request_handle();
|
||||
tokio::spawn(async move {
|
||||
// A reopened popup must discover values after the outstanding save.
|
||||
tokio::select! {
|
||||
_ = response_tx.closed() => {},
|
||||
_guard = lock.lock() => crate::experimental_features::fetch(
|
||||
handle, Some(thread_id), "tui-experimental-features", response_tx,
|
||||
),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn save_experimental_features(
|
||||
&mut self,
|
||||
app_server: &AppServerSession,
|
||||
thread_id: ThreadId,
|
||||
updates: Vec<(String, bool)>,
|
||||
response_tx: oneshot::Sender<Result<FeatureWriteResult, String>>,
|
||||
) {
|
||||
let Ok(guard) = self.feature_write_lock.clone().try_lock_owned() else {
|
||||
let error =
|
||||
"An experimental feature save is still in progress. Retry after it finishes.";
|
||||
self.chat_widget.add_warning_message(error.to_string());
|
||||
let _ = response_tx.send(Err(error.to_string()));
|
||||
return;
|
||||
};
|
||||
let request_handle = app_server.request_handle();
|
||||
let tx = self.app_event_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
let result =
|
||||
crate::experimental_features::write(request_handle, thread_id, updates).await;
|
||||
drop(guard);
|
||||
// Report unresolved outcomes even if the popup closes before its next draw.
|
||||
let warning = match &result {
|
||||
Ok(result) => result.warning.as_ref(),
|
||||
Err(error) => Some(error),
|
||||
};
|
||||
if let Some(warning) = warning {
|
||||
tx.send(AppEvent::InsertHistoryCell(Box::new(
|
||||
history_cell::new_warning_event(warning.clone()),
|
||||
)));
|
||||
}
|
||||
let _ = response_tx.send(result);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "experimental_features_tests.rs"]
|
||||
mod tests;
|
||||
143
akode-rs/tui/src/app/experimental_features_tests.rs
Normal file
143
akode-rs/tui/src/app/experimental_features_tests.rs
Normal file
@@ -0,0 +1,143 @@
|
||||
use super::*;
|
||||
use crate::app::tests::make_test_app_with_channels;
|
||||
use akode_app_server_client::AppServerClient;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn experimental_features_use_selected_server_profile_and_preserve_task_settings() -> Result<()>
|
||||
{
|
||||
let home = tempfile::tempdir()?;
|
||||
let selected = AbsolutePathBuf::from_absolute_path(home.path().join("work.config.toml"))?;
|
||||
let managed = home.path().join("managed.toml");
|
||||
std::fs::write(home.path().join("config.toml"), "# unselected\n")?;
|
||||
std::fs::write(&selected, "[features]\nnetwork_proxy = true\n")?;
|
||||
// The provider lives in the managed layer so both user files stay as written.
|
||||
std::fs::write(
|
||||
&managed,
|
||||
crate::test_support::with_test_model_provider(home.path(), ""),
|
||||
)?;
|
||||
let loader = LoaderOverrides {
|
||||
user_config_path: Some(selected.clone()),
|
||||
user_config_profile: Some("work".parse()?),
|
||||
managed_config_path: Some(managed.clone()),
|
||||
ignore_project_config: true,
|
||||
..LoaderOverrides::without_managed_config_for_tests()
|
||||
};
|
||||
let config = ConfigBuilder::default()
|
||||
.codex_home(home.path().to_path_buf())
|
||||
.loader_overrides(loader.clone())
|
||||
.build()
|
||||
.await?;
|
||||
let client = Box::pin(crate::start_embedded_app_server(
|
||||
Default::default(),
|
||||
config.clone(),
|
||||
Vec::new(),
|
||||
loader,
|
||||
/*strict_config*/ false,
|
||||
akode_feedback::CodexFeedback::new(),
|
||||
/*log_db*/ None,
|
||||
/*state_db*/ None,
|
||||
Arc::new(EnvironmentManager::default_for_tests()),
|
||||
Default::default(),
|
||||
))
|
||||
.await?;
|
||||
let mut server = AppServerSession::new(
|
||||
crate::backend_id::BackendId::new(),
|
||||
AppServerClient::InProcess(client),
|
||||
crate::app_server_session::ThreadParamsMode::Remote,
|
||||
);
|
||||
let thread = server.start_thread(&config).await?.session.thread_id;
|
||||
let (mut app, mut events, _ops) = make_test_app_with_channels().await;
|
||||
let before = (app.config.clone(), app.chat_widget.config_ref().clone());
|
||||
let updates = vec![
|
||||
("network_proxy".to_string(), false),
|
||||
("multi_agent".to_string(), false),
|
||||
("memories".to_string(), true),
|
||||
];
|
||||
let (response_tx, response_rx) = oneshot::channel();
|
||||
app.save_experimental_features(&server, thread, updates.clone(), response_tx);
|
||||
let (retry_tx, retry_rx) = oneshot::channel();
|
||||
app.save_experimental_features(&server, thread, updates.clone(), retry_tx);
|
||||
assert!(retry_rx.await?.unwrap_err().contains("still in progress"));
|
||||
assert!(matches!(events.try_recv()?, AppEvent::InsertHistoryCell(_)));
|
||||
let (catalog_tx, catalog_rx) = oneshot::channel();
|
||||
app.fetch_experimental_features(&server, thread, catalog_tx);
|
||||
// Navigation while the write is pending must not change the new task's settings.
|
||||
app.active_thread_id = Some(ThreadId::new());
|
||||
let result = tokio::time::timeout(std::time::Duration::from_secs(/*secs*/ 15), response_rx)
|
||||
.await??
|
||||
.map_err(|error| color_eyre::eyre::eyre!(error))?;
|
||||
assert_eq!(result.warning, None);
|
||||
assert_eq!(
|
||||
catalog_rx
|
||||
.await?
|
||||
.map_err(|error| color_eyre::eyre::eyre!(error))?,
|
||||
result.features
|
||||
);
|
||||
let saved: toml::Value = toml::from_str(&std::fs::read_to_string(&selected)?)?;
|
||||
assert_eq!(
|
||||
serde_json::to_value(saved)?,
|
||||
serde_json::json!({"features": {"multi_agent": false, "memories": true}})
|
||||
);
|
||||
assert_eq!(
|
||||
(app.config.clone(), app.chat_widget.config_ref().clone()),
|
||||
before
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(home.path().join("config.toml"))?,
|
||||
"# unselected\n"
|
||||
);
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
let notice_text = |app: &App| {
|
||||
app.transcript_cells
|
||||
.last()
|
||||
.unwrap()
|
||||
.transcript_lines(/*width*/ 120)
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
};
|
||||
app.enable_feature_for_new_threads(&mut tui, &server, Feature::Collab)
|
||||
.await;
|
||||
insta::assert_snapshot!("subagents_enable_notice", notice_text(&app));
|
||||
std::fs::write(
|
||||
&selected,
|
||||
format!(
|
||||
"{}memory_tool = false\n",
|
||||
std::fs::read_to_string(&selected)?
|
||||
),
|
||||
)?;
|
||||
app.enable_feature_for_new_threads(&mut tui, &server, Feature::MemoryTool)
|
||||
.await;
|
||||
insta::assert_snapshot!("memories_enable_notice", notice_text(&app));
|
||||
let saved: toml::Value = toml::from_str(&std::fs::read_to_string(&selected)?)?;
|
||||
assert_eq!(saved["features"]["multi_agent"].as_bool(), Some(true));
|
||||
assert_eq!(saved["features"]["memories"].as_bool(), Some(true));
|
||||
assert_eq!(saved["features"]["memory_tool"].as_bool(), Some(true));
|
||||
assert_eq!(
|
||||
(app.config.clone(), app.chat_widget.config_ref().clone()),
|
||||
before
|
||||
);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(home.path().join("config.toml"))?,
|
||||
"# unselected\n"
|
||||
);
|
||||
std::fs::write(&managed, "[features]\nmulti_agent = false\n")?;
|
||||
app.enable_feature_for_new_threads(&mut tui, &server, Feature::Collab)
|
||||
.await;
|
||||
insta::assert_snapshot!(
|
||||
"subagents_enable_overridden",
|
||||
notice_text(&app).replace(managed.display().to_string().as_str(), "<managed config>")
|
||||
);
|
||||
// A failed save still reports to history after its popup has closed.
|
||||
let (tx, rx) = oneshot::channel();
|
||||
drop(rx);
|
||||
app.save_experimental_features(&server, thread, vec![("missing_feature".into(), true)], tx);
|
||||
assert!(matches!(
|
||||
events.recv().await,
|
||||
Some(AppEvent::InsertHistoryCell(_))
|
||||
));
|
||||
server.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
94
akode-rs/tui/src/app/feedback_save.rs
Normal file
94
akode-rs/tui/src/app/feedback_save.rs
Normal file
@@ -0,0 +1,94 @@
|
||||
//! Save a feedback report as a local ZIP archive on the app-server host.
|
||||
//! Feedback is never uploaded. Log consent gates staging of the TUI client logs;
|
||||
//! cleanup runs after staging or save failures too.
|
||||
|
||||
use crate::app_server_session::fs::AppServerFileSystem;
|
||||
use akode_app_server_client::AppServerPath;
|
||||
use akode_app_server_client::AppServerRequestHandle;
|
||||
use akode_app_server_protocol::ClientRequest;
|
||||
use akode_app_server_protocol::FeedbackReportParams;
|
||||
use akode_app_server_protocol::FeedbackSaveParams;
|
||||
use akode_app_server_protocol::FeedbackSaveResponse;
|
||||
use akode_app_server_protocol::RequestId;
|
||||
use akode_feedback::CodexFeedback;
|
||||
use akode_utils_path_uri::LegacyAppPathString;
|
||||
use color_eyre::eyre::Result;
|
||||
use color_eyre::eyre::WrapErr;
|
||||
use color_eyre::eyre::eyre;
|
||||
use std::path::PathBuf;
|
||||
use uuid::Uuid;
|
||||
|
||||
// Base64 adds only a third to this size, keeping fs/writeFile below the 16 MiB frame limit.
|
||||
const MAX_CLIENT_LOG_SIZE: usize = 1024 * 1024;
|
||||
|
||||
pub(super) async fn save_feedback_locally(
|
||||
request_handle: AppServerRequestHandle,
|
||||
codex_home: Option<AppServerPath>,
|
||||
mut params: FeedbackReportParams,
|
||||
feedback: CodexFeedback,
|
||||
) -> Result<FeedbackSaveResponse> {
|
||||
let fs = AppServerFileSystem { request_handle };
|
||||
let codex_home = codex_home
|
||||
.ok_or_else(|| eyre!("App server did not report $AKODE_HOME; cannot save feedback"))?;
|
||||
let staging_dir = params.include_logs.then(|| {
|
||||
codex_home
|
||||
.join("tmp")
|
||||
.join(format!("tui-feedback-{}", Uuid::new_v4()))
|
||||
});
|
||||
if let Some(directory) = staging_dir.as_ref() {
|
||||
let staged = async {
|
||||
// These RPCs use the app-server's local filesystem, where feedback/save
|
||||
// reads extraLogFiles, independently of the thread's executor environment.
|
||||
fs.fs_create_directory_all_path(directory).await?;
|
||||
let path = directory.join("client-logs.txt");
|
||||
let mut logs = feedback
|
||||
.snapshot(/*session_id*/ None)
|
||||
.log_attachment(/*logs_override*/ None)
|
||||
.buffer;
|
||||
logs.drain(..logs.len().saturating_sub(MAX_CLIENT_LOG_SIZE));
|
||||
fs.fs_write_file_path(&path, logs).await?;
|
||||
Ok::<_, color_eyre::Report>(path)
|
||||
}
|
||||
.await;
|
||||
match staged {
|
||||
Ok(path) => params
|
||||
.extra_log_files
|
||||
.get_or_insert_with(Vec::new)
|
||||
.push(PathBuf::from(path.as_str())),
|
||||
Err(err) => {
|
||||
tracing::warn!("failed to stage TUI feedback logs: {err}");
|
||||
params.reason.get_or_insert_with(String::new).push_str(
|
||||
"\n\nTUI client logs were omitted because they could not be staged on the app-server.",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
let result = async {
|
||||
let feedback_dir = codex_home.join("feedback");
|
||||
fs.fs_create_directory_all_path(&feedback_dir).await?;
|
||||
let save_path = feedback_dir.join(format!(
|
||||
"feedback-{}-{}.zip",
|
||||
chrono::Local::now().format("%Y%m%d-%H%M%S"),
|
||||
Uuid::new_v4().simple()
|
||||
));
|
||||
let request_id = RequestId::String(format!("feedback-save-{}", Uuid::new_v4()));
|
||||
fs.request_handle
|
||||
.request_typed(ClientRequest::FeedbackSave {
|
||||
request_id,
|
||||
params: FeedbackSaveParams {
|
||||
feedback: params,
|
||||
save_path: LegacyAppPathString::from_string(save_path.as_str()),
|
||||
},
|
||||
})
|
||||
.await
|
||||
.wrap_err("feedback/save failed in TUI")
|
||||
}
|
||||
.await;
|
||||
|
||||
if let Some(directory) = staging_dir
|
||||
&& let Err(err) = fs.fs_remove_path(&directory).await
|
||||
{
|
||||
tracing::warn!("failed to remove staged feedback logs: {err}");
|
||||
}
|
||||
result
|
||||
}
|
||||
72
akode-rs/tui/src/app/file_change_approvals.rs
Normal file
72
akode-rs/tui/src/app/file_change_approvals.rs
Normal file
@@ -0,0 +1,72 @@
|
||||
//! Recover file-change details for live and replayed approval requests.
|
||||
//!
|
||||
//! The approval RPC identifies an item but does not repeat its diff. Recover the
|
||||
//! matching item before constructing the approval so its full-screen pager owns
|
||||
//! the same changes that were already displayed in the transcript.
|
||||
|
||||
use super::*;
|
||||
|
||||
impl App {
|
||||
pub(super) async fn thread_file_change_changes(
|
||||
&self,
|
||||
thread_id: ThreadId,
|
||||
turn_id: &str,
|
||||
item_id: &str,
|
||||
) -> Option<Vec<akode_app_server_protocol::FileUpdateChange>> {
|
||||
let channel = self.thread_event_channels.get(&thread_id)?;
|
||||
let store = channel.store.lock().await;
|
||||
store.file_change_changes(turn_id, item_id)
|
||||
}
|
||||
|
||||
pub(super) async fn handle_thread_event_now_recovering_file_changes(
|
||||
&mut self,
|
||||
event: ThreadBufferedEvent,
|
||||
) {
|
||||
let changes = match (&event, self.active_thread_id) {
|
||||
(ThreadBufferedEvent::Request(request), Some(thread_id)) => match request.as_ref() {
|
||||
ServerRequest::FileChangeRequestApproval { params, .. } => {
|
||||
self.thread_file_change_changes(thread_id, ¶ms.turn_id, ¶ms.item_id)
|
||||
.await
|
||||
}
|
||||
_ => None,
|
||||
},
|
||||
_ => None,
|
||||
};
|
||||
match (changes, event) {
|
||||
(Some(changes), ThreadBufferedEvent::Request(request)) => {
|
||||
if self
|
||||
.pending_app_server_requests
|
||||
.contains_server_request(request.as_ref())
|
||||
{
|
||||
self.handle_file_change_request(*request, changes);
|
||||
}
|
||||
}
|
||||
(_, event) => self.handle_thread_event_now(event),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn handle_file_change_request(
|
||||
&mut self,
|
||||
request: ServerRequest,
|
||||
changes: Vec<akode_app_server_protocol::FileUpdateChange>,
|
||||
) {
|
||||
let ServerRequest::FileChangeRequestApproval { params, .. } = request else {
|
||||
return;
|
||||
};
|
||||
self.chat_widget.on_apply_patch_approval_request(
|
||||
params.item_id.clone(),
|
||||
crate::approval_events::ApplyPatchApprovalRequestEvent {
|
||||
call_id: params.item_id,
|
||||
turn_id: params.turn_id,
|
||||
changes: crate::app_server_approval_conversions::file_update_changes_to_display(
|
||||
changes,
|
||||
),
|
||||
reason: params.reason,
|
||||
grant_root: params.grant_root,
|
||||
},
|
||||
);
|
||||
if self.startup_protected_input_boundary && !self.chat_widget.has_active_modal() {
|
||||
self.startup_pending_protected_request = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
84
akode-rs/tui/src/app/footer_selection.rs
Normal file
84
akode-rs/tui/src/app/footer_selection.rs
Normal file
@@ -0,0 +1,84 @@
|
||||
//! Route registered read-only selections before copy, interrupt, clicks, and paste shortcuts.
|
||||
//! A stationary click is replayed to the existing widget handler after selection releases it.
|
||||
|
||||
use super::*;
|
||||
use crate::clipboard_copy::CopyFormat;
|
||||
use crate::keymap::ListAction;
|
||||
use crate::rendered_selection::RegionAction;
|
||||
use crate::rendered_selection::RenderedSelection;
|
||||
use crate::transcript_view::ViewAction;
|
||||
|
||||
impl App {
|
||||
pub(super) fn handle_rendered_selection_event(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
event: &TuiEvent,
|
||||
) -> Result<bool> {
|
||||
let warning_active = self.chat_widget.keymap_contexts().is_warnings();
|
||||
if !tui.is_owned_screen()
|
||||
|| self.overlay.is_some()
|
||||
|| (!warning_active
|
||||
&& (!self.chat_widget.no_modal_or_popup_active()
|
||||
|| self.chat_widget.is_external_writer_view()))
|
||||
{
|
||||
*self.chat_widget.rendered_selection.borrow_mut() = RenderedSelection::default();
|
||||
return Ok(false);
|
||||
}
|
||||
let refresh = matches!(event, TuiEvent::Mouse(mouse)
|
||||
if self.chat_widget.rendered_selection.borrow().needs_refresh(*mouse));
|
||||
if refresh {
|
||||
self.refresh_owned_transcript(tui)?;
|
||||
}
|
||||
let action = {
|
||||
let mut selection = self.chat_widget.rendered_selection.borrow_mut();
|
||||
if warning_active
|
||||
&& let TuiEvent::Key(key) = event
|
||||
&& matches!(
|
||||
self.keymap.list.action_for(*key),
|
||||
Some(ListAction::PageUp | ListAction::PageDown)
|
||||
)
|
||||
{
|
||||
selection.clear();
|
||||
return Ok(false);
|
||||
}
|
||||
selection.view.copy_on_select = self
|
||||
.local_settings
|
||||
.copy_on_select(&akode_terminal_detection::terminal_info());
|
||||
selection.view.copy_on_select_clear_selection =
|
||||
self.local_settings.tui.copy_on_select_clear_selection;
|
||||
selection.view.primary_selection = self.right_click_paste_environment.primary;
|
||||
selection.handle_event(event, tui.terminal.previous_buffer())
|
||||
};
|
||||
let Some(action) = action else {
|
||||
return Ok(false);
|
||||
};
|
||||
if warning_active {
|
||||
self.chat_widget.record_warning_activity();
|
||||
}
|
||||
self.cancel_pending_key_chord();
|
||||
match action {
|
||||
RegionAction::Click(mouse) => {
|
||||
self.chat_widget
|
||||
.handle_warning_event(&TuiEvent::Mouse(mouse), &self.transcript_cells);
|
||||
}
|
||||
RegionAction::Selection(action) => {
|
||||
self.transcript_view.end_selection(&self.transcript_cells);
|
||||
self.transcript_view.cancel_search();
|
||||
self.transcript_view.clear_activity_focus();
|
||||
self.chat_widget.clear_composer_selection();
|
||||
let copied = {
|
||||
let mut selection = self.chat_widget.rendered_selection.borrow_mut();
|
||||
let RenderedSelection { view, cells, .. } = &mut *selection;
|
||||
view.copy_action(tui, cells, &action, CopyFormat::PlainText)
|
||||
};
|
||||
if let Some((characters, result)) = copied {
|
||||
self.transcript_view.show_copy_feedback(&result, characters);
|
||||
} else if let ViewAction::OpenLink(url) = action {
|
||||
self.open_url_in_browser(url);
|
||||
}
|
||||
}
|
||||
}
|
||||
tui.frame_requester().schedule_frame();
|
||||
Ok(true)
|
||||
}
|
||||
}
|
||||
35
akode-rs/tui/src/app/history_completion.rs
Normal file
35
akode-rs/tui/src/app/history_completion.rs
Normal file
@@ -0,0 +1,35 @@
|
||||
//! Separate older history at every turn boundary; only successful turns gain completion metadata.
|
||||
//! A page splitting a turn only adds completion metadata when it contains that turn's last item.
|
||||
|
||||
use akode_app_server_protocol::ThreadItemPayload;
|
||||
use akode_app_server_protocol::Turn;
|
||||
use akode_app_server_protocol::TurnStatus;
|
||||
use std::collections::HashMap;
|
||||
|
||||
pub(super) fn group_completed_turn_items(
|
||||
items: Vec<ThreadItemPayload>,
|
||||
turns: &[Turn],
|
||||
) -> Vec<(Vec<ThreadItemPayload>, Option<&Turn>)> {
|
||||
let boundaries: HashMap<_, _> = turns
|
||||
.iter()
|
||||
.filter_map(|turn| turn.items.last().map(|item| (item.id(), turn)))
|
||||
.collect();
|
||||
let mut groups = Vec::new();
|
||||
let mut pending = Vec::new();
|
||||
for item in items {
|
||||
let boundary = boundaries.get(item.id()).copied();
|
||||
pending.push(item);
|
||||
if let Some(turn) = boundary {
|
||||
let completed_turn = (turn.status == TurnStatus::Completed).then_some(turn);
|
||||
groups.push((std::mem::take(&mut pending), completed_turn));
|
||||
}
|
||||
}
|
||||
if !pending.is_empty() {
|
||||
groups.push((pending, None));
|
||||
}
|
||||
groups
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "history_completion_tests.rs"]
|
||||
mod tests;
|
||||
90
akode-rs/tui/src/app/history_completion_tests.rs
Normal file
90
akode-rs/tui/src/app/history_completion_tests.rs
Normal file
@@ -0,0 +1,90 @@
|
||||
//! Pagination boundaries preserve grouped item rendering and attach completion metadata once.
|
||||
|
||||
use super::*;
|
||||
use akode_app_server_protocol::ThreadItem;
|
||||
use akode_app_server_protocol::TurnItemsView;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn payloads(items: &[akode_app_server_protocol::ThreadItem]) -> Vec<ThreadItemPayload> {
|
||||
items.iter().map(|entry| entry.payload.clone()).collect()
|
||||
}
|
||||
|
||||
fn turn(id: &str, status: TurnStatus, item_ids: &[&str]) -> Turn {
|
||||
Turn {
|
||||
id: id.to_string(),
|
||||
root_turn_id: None,
|
||||
items: item_ids
|
||||
.iter()
|
||||
.map(|id| ThreadItemPayload::UserMessage {
|
||||
id: id.to_string(),
|
||||
client_id: None,
|
||||
content: Vec::new(),
|
||||
})
|
||||
.map(ThreadItem::untimed)
|
||||
.collect(),
|
||||
items_view: TurnItemsView::Summary,
|
||||
status,
|
||||
error: None,
|
||||
started_at: None,
|
||||
completed_at: Some(1_700_000_000),
|
||||
duration_ms: Some(125_000),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn split_turn_only_completes_on_the_page_with_its_last_item() {
|
||||
let turns = vec![turn(
|
||||
"turn",
|
||||
TurnStatus::Completed,
|
||||
&["first", "second", "last"],
|
||||
)];
|
||||
assert_eq!(
|
||||
group_completed_turn_items(payloads(&turns[0].items[1..]), &turns),
|
||||
vec![(payloads(&turns[0].items[1..]), Some(&turns[0]))],
|
||||
);
|
||||
assert_eq!(
|
||||
group_completed_turn_items(payloads(&turns[0].items[..1]), &turns),
|
||||
vec![(payloads(&turns[0].items[..1]), None)],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiple_turns_keep_item_groups_and_completion_order() {
|
||||
let turns = vec![
|
||||
turn("first", TurnStatus::Completed, &["a", "b"]),
|
||||
turn("second", TurnStatus::Completed, &["c", "d"]),
|
||||
];
|
||||
let items = turns
|
||||
.iter()
|
||||
.flat_map(Turn::item_payloads)
|
||||
.cloned()
|
||||
.collect();
|
||||
assert_eq!(
|
||||
group_completed_turn_items(items, &turns),
|
||||
vec![
|
||||
(payloads(&turns[0].items), Some(&turns[0])),
|
||||
(payloads(&turns[1].items), Some(&turns[1])),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsuccessful_and_running_turns_separate_groups_without_completion_metadata() {
|
||||
let turns = vec![
|
||||
turn("failed", TurnStatus::Failed, &["a"]),
|
||||
turn("interrupted", TurnStatus::Interrupted, &["b"]),
|
||||
turn("running", TurnStatus::InProgress, &["c"]),
|
||||
];
|
||||
let items = turns
|
||||
.iter()
|
||||
.flat_map(Turn::item_payloads)
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
group_completed_turn_items(items, &turns),
|
||||
turns
|
||||
.iter()
|
||||
.map(|turn| (payloads(&turn.items), None))
|
||||
.collect::<Vec<_>>(),
|
||||
);
|
||||
}
|
||||
485
akode-rs/tui/src/app/history_pagination.rs
Normal file
485
akode-rs/tui/src/app/history_pagination.rs
Normal file
@@ -0,0 +1,485 @@
|
||||
//! Load bounded history pages into the transcript before updating its owned or inline viewport.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::ops::Range;
|
||||
|
||||
use super::*;
|
||||
use crate::app_server_session::HISTORY_ITEM_PAGE_LIMIT;
|
||||
use crate::app_server_session::thread_items_page_params;
|
||||
use crate::history_cell::UserHistoryCell;
|
||||
use crate::history_cell::is_session_history_prefix_cell;
|
||||
use crate::pager_overlay::TranscriptHistoryState;
|
||||
use crate::thread_transcript::RawReasoningVisibility;
|
||||
use crate::thread_transcript::thread_items_to_transcript_cells;
|
||||
use akode_app_server_protocol::ClientRequest;
|
||||
use akode_app_server_protocol::ThreadItemsListResponse;
|
||||
|
||||
#[path = "history_completion.rs"]
|
||||
mod completion;
|
||||
|
||||
impl App {
|
||||
/// Start one bounded page request shared by scrollback refill and the transcript overlay.
|
||||
pub(crate) fn request_older_history_page(
|
||||
&self,
|
||||
app_server: &mut AppServerSession,
|
||||
thread_id: ThreadId,
|
||||
) -> bool {
|
||||
let Some(cursor) = app_server.begin_older_history_page(thread_id) else {
|
||||
return false;
|
||||
};
|
||||
tracing::debug!(
|
||||
%thread_id,
|
||||
%cursor,
|
||||
overlay = self.overlay.is_some(),
|
||||
"loading older transcript history page"
|
||||
);
|
||||
let request_id = app_server.next_request_id();
|
||||
let request_handle = app_server.request_handle();
|
||||
let app_event_tx = self.app_event_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
let result = request_handle
|
||||
.request_typed::<ThreadItemsListResponse>(ClientRequest::ThreadItemsList {
|
||||
request_id,
|
||||
params: thread_items_page_params(
|
||||
thread_id,
|
||||
/*turn_id*/ None,
|
||||
Some(cursor.clone()),
|
||||
HISTORY_ITEM_PAGE_LIMIT,
|
||||
),
|
||||
})
|
||||
.await
|
||||
.map_err(|err| err.to_string());
|
||||
app_event_tx.send(AppEvent::OlderThreadHistoryLoaded {
|
||||
thread_id,
|
||||
cursor,
|
||||
result,
|
||||
});
|
||||
});
|
||||
true
|
||||
}
|
||||
|
||||
pub(super) async fn handle_older_history_page(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
app_server: &mut AppServerSession,
|
||||
thread_id: ThreadId,
|
||||
cursor: &str,
|
||||
result: Result<ThreadItemsListResponse, String>,
|
||||
) -> Result<()> {
|
||||
if !app_server.is_older_history_page_pending(thread_id, cursor) {
|
||||
return Ok(());
|
||||
}
|
||||
// The widget can already belong to the destination while the transcript still replays.
|
||||
let parked = self.chat_widget.thread_id() != Some(thread_id);
|
||||
if self.awaiting_side_replay(tui)
|
||||
|| (parked && !self.side_companions.contains_key(&thread_id))
|
||||
|| (!parked && tui.is_owned_screen() && !self.scrollback_has_older_history)
|
||||
{
|
||||
app_server.cancel_older_history_page(thread_id, cursor);
|
||||
return Ok(());
|
||||
}
|
||||
let page = result.map_err(|err| color_eyre::eyre::eyre!(err))?;
|
||||
let Some(store) = self
|
||||
.thread_event_channels
|
||||
.get(&thread_id)
|
||||
.map(|channel| Arc::clone(&channel.store))
|
||||
else {
|
||||
app_server.cancel_older_history_page(thread_id, cursor);
|
||||
return Ok(());
|
||||
};
|
||||
let (cwd, mut turns) = {
|
||||
let store = store.lock().await;
|
||||
(
|
||||
store
|
||||
.session
|
||||
.as_ref()
|
||||
.map_or_else(|| self.config.cwd.clone(), |session| session.cwd.clone()),
|
||||
store.turns.clone(),
|
||||
)
|
||||
};
|
||||
let items = app_server
|
||||
.apply_older_history_page(thread_id, cursor, page, &mut turns)
|
||||
.await?;
|
||||
let hidden_item_ids = hidden_review_item_ids(&turns);
|
||||
let visibility = if self.config.show_raw_agent_reasoning {
|
||||
RawReasoningVisibility::Visible
|
||||
} else {
|
||||
RawReasoningVisibility::Hidden
|
||||
};
|
||||
let width = tui.terminal.last_known_screen_size.width;
|
||||
self.remove_hidden_review_cells(tui, &turns, &hidden_item_ids, thread_id, &cwd, visibility);
|
||||
let cells = self.project_older_history_cells(
|
||||
items,
|
||||
&turns,
|
||||
&hidden_item_ids,
|
||||
thread_id,
|
||||
&cwd,
|
||||
visibility,
|
||||
);
|
||||
if let Some(pane) = self.side_companions.get_mut(&thread_id).filter(|_| parked) {
|
||||
let index = history_prefix_len(&pane.cells);
|
||||
let inserted = index..index + cells.len();
|
||||
pane.splice_older_cells(index..index, cells);
|
||||
pane.view.history_loaded(&pane.cells, inserted);
|
||||
pane.view.history = if app_server.has_older_history(thread_id) {
|
||||
TranscriptHistoryState::Partial
|
||||
} else {
|
||||
TranscriptHistoryState::Complete
|
||||
};
|
||||
merge_older_turns(&mut store.lock().await.turns, turns);
|
||||
tui.frame_requester().schedule_frame();
|
||||
return Ok(());
|
||||
}
|
||||
let inserted = self.prepend_older_transcript_cells(cells);
|
||||
self.transcript_view
|
||||
.history_loaded(&self.transcript_cells, inserted.clone());
|
||||
if !inserted.is_empty() {
|
||||
self.join_older_activity_group(inserted.end, &turns);
|
||||
}
|
||||
merge_older_turns(&mut store.lock().await.turns, turns);
|
||||
self.scrollback_has_older_history = app_server.has_older_history(thread_id);
|
||||
if self.backtrack.overlay_preview_active
|
||||
&& self.backtrack.nth_user_message == usize::MAX
|
||||
&& !self.scrollback_has_older_history
|
||||
{
|
||||
self.cancel_transcript_browsing(tui);
|
||||
self.chat_widget.add_info_message(
|
||||
"No previous message to edit.".to_string(),
|
||||
/*hint*/ None,
|
||||
);
|
||||
}
|
||||
|
||||
if tui.is_owned_screen() {
|
||||
self.finish_owned_history_page(tui, app_server, thread_id);
|
||||
return Ok(());
|
||||
}
|
||||
self.finish_inline_history_page(tui, app_server, thread_id, width);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Remove prompts revealed as internal review input by an older page's review marker.
|
||||
fn remove_hidden_review_cells(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
turns: &[Turn],
|
||||
hidden_item_ids: &HashSet<&str>,
|
||||
thread_id: ThreadId,
|
||||
cwd: &AbsolutePathBuf,
|
||||
visibility: RawReasoningVisibility,
|
||||
) {
|
||||
if hidden_item_ids.is_empty() {
|
||||
return;
|
||||
}
|
||||
let user_items = turns
|
||||
.iter()
|
||||
.flat_map(Turn::item_payloads)
|
||||
.filter(|item| matches!(item, ThreadItemPayload::UserMessage { .. }))
|
||||
.map(|item| (item.id().to_string(), item.clone()))
|
||||
.collect::<Vec<_>>();
|
||||
let projected_user_cells = thread_items_to_transcript_cells(
|
||||
Some(thread_id),
|
||||
cwd,
|
||||
user_items.iter().map(|(_, item)| item.clone()),
|
||||
visibility,
|
||||
Some(&self.config),
|
||||
);
|
||||
let persisted_user_cells = user_items
|
||||
.into_iter()
|
||||
.zip(projected_user_cells)
|
||||
.map(|((item_id, _), cell)| (item_id, cell))
|
||||
.collect();
|
||||
if self.chat_widget.thread_id() != Some(thread_id)
|
||||
&& let Some(pane) = self.side_companions.get_mut(&thread_id)
|
||||
{
|
||||
for index in
|
||||
hidden_transcript_indices(&pane.cells, persisted_user_cells, hidden_item_ids)
|
||||
{
|
||||
pane.splice_older_cells(index..index + 1, Vec::new());
|
||||
pane.view.restart_search();
|
||||
}
|
||||
return;
|
||||
}
|
||||
let indices = hidden_transcript_indices(
|
||||
&self.transcript_cells,
|
||||
persisted_user_cells,
|
||||
hidden_item_ids,
|
||||
);
|
||||
if indices.is_empty() {
|
||||
return;
|
||||
}
|
||||
if self.backtrack.overlay_preview_active {
|
||||
let selected_index = crate::app_backtrack::nth_user_position(
|
||||
&self.transcript_cells,
|
||||
self.backtrack.nth_user_message,
|
||||
);
|
||||
if selected_index.is_some_and(|selected| indices.contains(&selected)) {
|
||||
self.cancel_transcript_browsing(tui);
|
||||
} else {
|
||||
let removed_visible_users = indices
|
||||
.iter()
|
||||
.filter(|&&index| {
|
||||
selected_index.is_some_and(|selected| index < selected)
|
||||
&& crate::app_backtrack::user_count(std::slice::from_ref(
|
||||
&self.transcript_cells[index],
|
||||
)) != 0
|
||||
})
|
||||
.count();
|
||||
self.backtrack.nth_user_message = self
|
||||
.backtrack
|
||||
.nth_user_message
|
||||
.saturating_sub(removed_visible_users);
|
||||
}
|
||||
}
|
||||
for index in indices {
|
||||
self.transcript_cells.remove(index);
|
||||
}
|
||||
self.native_history.retain(&self.transcript_cells);
|
||||
self.transcript_view.restart_search();
|
||||
self.transcript_view
|
||||
.history_loaded(&self.transcript_cells, 0..0);
|
||||
if let Some(Overlay::Transcript(overlay)) = self.overlay.as_mut() {
|
||||
overlay.replace_cells(self.transcript_cells.clone());
|
||||
}
|
||||
}
|
||||
|
||||
/// Project successful turn completion metadata after the corresponding page's final item.
|
||||
fn project_older_history_cells(
|
||||
&mut self,
|
||||
items: Vec<ThreadItemPayload>,
|
||||
turns: &[Turn],
|
||||
hidden_item_ids: &HashSet<&str>,
|
||||
thread_id: ThreadId,
|
||||
cwd: &AbsolutePathBuf,
|
||||
visibility: RawReasoningVisibility,
|
||||
) -> Vec<Arc<dyn HistoryCell>> {
|
||||
let mut cells = Vec::new();
|
||||
for (items, completed_turn) in completion::group_completed_turn_items(items, turns) {
|
||||
// Internal prompts stay invisible, but still separate adjacent tool groups.
|
||||
for visible in items.split(|item| hidden_item_ids.contains(item.id())) {
|
||||
cells.extend(thread_items_to_transcript_cells(
|
||||
Some(thread_id),
|
||||
cwd,
|
||||
visible.iter().cloned(),
|
||||
visibility,
|
||||
Some(&self.config),
|
||||
));
|
||||
}
|
||||
if let Some(turn) = completed_turn
|
||||
&& let Some(completion) = if let Some(pane) =
|
||||
self.side_companions.get_mut(&thread_id)
|
||||
&& self.chat_widget.thread_id() != Some(thread_id)
|
||||
{
|
||||
history_cell::FinalMessageSeparator::from_turn_once(
|
||||
turn,
|
||||
&mut pane.display.rendered_completion_turn_ids,
|
||||
/*fallback_elapsed*/ None,
|
||||
/*fallback_completed_at*/ None,
|
||||
)
|
||||
} else {
|
||||
self.chat_widget
|
||||
.completion_cell(turn, Some(ReplayKind::ResumeInitialMessages))
|
||||
}
|
||||
{
|
||||
cells.push(Arc::new(completion));
|
||||
}
|
||||
}
|
||||
for cell in cells.iter_mut().filter_map(Arc::get_mut) {
|
||||
self.link_viewed_image(cell);
|
||||
}
|
||||
cells
|
||||
}
|
||||
|
||||
/// Insert each page once, keeping session headers and any backtrack selection in place.
|
||||
fn prepend_older_transcript_cells(&mut self, cells: Vec<Arc<dyn HistoryCell>>) -> Range<usize> {
|
||||
if self.backtrack.overlay_preview_active {
|
||||
let added_prompts = crate::app_backtrack::user_count(&cells);
|
||||
self.backtrack.nth_user_message = if self.backtrack.nth_user_message == usize::MAX {
|
||||
added_prompts.checked_sub(1).unwrap_or(usize::MAX)
|
||||
} else {
|
||||
self.backtrack
|
||||
.nth_user_message
|
||||
.saturating_add(added_prompts)
|
||||
};
|
||||
}
|
||||
let index = if let Some(Overlay::Transcript(overlay)) = self.overlay.as_mut() {
|
||||
overlay.prepend(cells.clone())
|
||||
} else {
|
||||
history_prefix_len(&self.transcript_cells)
|
||||
};
|
||||
let inserted = index..index + cells.len();
|
||||
self.transcript_cells.splice(index..index, cells);
|
||||
inserted
|
||||
}
|
||||
|
||||
/// Continue explicit history traversal without rewriting native scrollback.
|
||||
fn finish_owned_history_page(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
app_server: &mut AppServerSession,
|
||||
thread_id: ThreadId,
|
||||
) {
|
||||
let previous = self.transcript_view.history;
|
||||
self.transcript_view.history = if self.scrollback_has_older_history {
|
||||
TranscriptHistoryState::Partial
|
||||
} else {
|
||||
TranscriptHistoryState::Complete
|
||||
};
|
||||
let continue_to_start = previous == TranscriptHistoryState::LoadingBeginning;
|
||||
if continue_to_start && !self.scrollback_has_older_history {
|
||||
if self.transcript_view.is_select_mode() {
|
||||
self.transcript_view
|
||||
.complete_select_beginning(&self.transcript_cells);
|
||||
} else {
|
||||
self.transcript_view
|
||||
.jump_to_beginning(&self.transcript_cells);
|
||||
}
|
||||
}
|
||||
if self.scrollback_has_older_history
|
||||
&& (continue_to_start
|
||||
|| self.browsing_needs_history()
|
||||
|| self.transcript_view.needs_history(&self.transcript_cells))
|
||||
&& self.request_older_history_page(app_server, thread_id)
|
||||
{
|
||||
self.transcript_view.history = if continue_to_start {
|
||||
TranscriptHistoryState::LoadingBeginning
|
||||
} else {
|
||||
TranscriptHistoryState::LoadingOlder
|
||||
};
|
||||
}
|
||||
if self.backtrack.overlay_preview_active {
|
||||
self.apply_backtrack_selection_internal(self.backtrack.nth_user_message);
|
||||
}
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
|
||||
/// Preserve the legacy overlay and inline scrollback refill behavior.
|
||||
fn finish_inline_history_page(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
app_server: &mut AppServerSession,
|
||||
thread_id: ThreadId,
|
||||
width: u16,
|
||||
) {
|
||||
let mut continue_to_start = false;
|
||||
if let Some(Overlay::Transcript(overlay)) = self.overlay.as_mut() {
|
||||
let previous_state = overlay.set_history_state(if self.scrollback_has_older_history {
|
||||
TranscriptHistoryState::Partial
|
||||
} else {
|
||||
TranscriptHistoryState::Complete
|
||||
});
|
||||
continue_to_start = previous_state == TranscriptHistoryState::LoadingBeginning
|
||||
&& self.scrollback_has_older_history;
|
||||
} else {
|
||||
let wrap_width = self.chat_widget.history_wrap_width(width);
|
||||
let rendered_rows = self
|
||||
.render_transcript_lines_for_reflow(wrap_width)
|
||||
.lines
|
||||
.len();
|
||||
self.schedule_immediate_resize_reflow(tui);
|
||||
if self.scrollback_history_needs_top_up(rendered_rows)
|
||||
&& self.request_older_history_page(app_server, thread_id)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
if continue_to_start
|
||||
&& self.request_older_history_page(app_server, thread_id)
|
||||
&& let Some(Overlay::Transcript(overlay)) = self.overlay.as_mut()
|
||||
{
|
||||
overlay.set_history_state(TranscriptHistoryState::LoadingBeginning);
|
||||
}
|
||||
if self.backtrack.overlay_preview_active {
|
||||
self.apply_backtrack_selection_internal(self.backtrack.nth_user_message);
|
||||
}
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
}
|
||||
|
||||
/// Classify internal review prompts across page boundaries before rendering any older items.
|
||||
fn hidden_review_item_ids(turns: &[Turn]) -> HashSet<&str> {
|
||||
let mut hidden = HashSet::new();
|
||||
let mut review_mode = false;
|
||||
for (index, turn) in turns.iter().enumerate() {
|
||||
let hidden_nested_review_turn = index
|
||||
.checked_sub(/*rhs*/ 1)
|
||||
.and_then(|previous| turns.get(previous))
|
||||
.is_some_and(|previous| {
|
||||
crate::app_backtrack::is_hidden_nested_review_turn(previous, turn)
|
||||
});
|
||||
for item in &turn.items {
|
||||
match &item.payload {
|
||||
ThreadItemPayload::EnteredReviewMode { .. } => review_mode = true,
|
||||
ThreadItemPayload::ExitedReviewMode { .. } => review_mode = false,
|
||||
ThreadItemPayload::UserMessage { .. }
|
||||
if review_mode || hidden_nested_review_turn =>
|
||||
{
|
||||
hidden.insert(item.id());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
hidden
|
||||
}
|
||||
|
||||
fn history_prefix_len(cells: &[Arc<dyn HistoryCell>]) -> usize {
|
||||
cells
|
||||
.iter()
|
||||
.rposition(|cell| is_session_history_prefix_cell(cell.as_ref()))
|
||||
.map_or(/*default*/ 0, |index| index + 1)
|
||||
}
|
||||
|
||||
/// Match repeated user messages from newest to oldest so identical visible prompts stay distinct.
|
||||
fn hidden_transcript_indices(
|
||||
cells: &[Arc<dyn HistoryCell>],
|
||||
mut persisted_user_cells: Vec<(String, Arc<dyn HistoryCell>)>,
|
||||
hidden_item_ids: &HashSet<&str>,
|
||||
) -> Vec<usize> {
|
||||
let mut indices = Vec::new();
|
||||
for (index, cell) in cells.iter().enumerate().rev() {
|
||||
let Some(user_cell) = cell.as_any().downcast_ref::<UserHistoryCell>() else {
|
||||
continue;
|
||||
};
|
||||
let Some(position) = persisted_user_cells.iter().rposition(|(_, projected)| {
|
||||
projected
|
||||
.as_any()
|
||||
.downcast_ref::<UserHistoryCell>()
|
||||
.is_some_and(|projected| {
|
||||
projected.message == user_cell.message
|
||||
&& projected.text_elements == user_cell.text_elements
|
||||
&& projected.local_image_paths == user_cell.local_image_paths
|
||||
&& projected.remote_image_urls == user_cell.remote_image_urls
|
||||
})
|
||||
}) else {
|
||||
continue;
|
||||
};
|
||||
if hidden_item_ids.contains(persisted_user_cells[position].0.as_str()) {
|
||||
indices.push(index);
|
||||
}
|
||||
persisted_user_cells.truncate(position);
|
||||
}
|
||||
indices
|
||||
}
|
||||
|
||||
/// Preserve events received while the request was in flight and deduplicate overlapping pages.
|
||||
fn merge_older_turns(current_turns: &mut Vec<Turn>, mut older_turns: Vec<Turn>) {
|
||||
older_turns.retain_mut(|turn| {
|
||||
let Some(current) = current_turns
|
||||
.iter_mut()
|
||||
.find(|current| current.id == turn.id)
|
||||
else {
|
||||
return true;
|
||||
};
|
||||
let items = std::mem::take(&mut turn.items)
|
||||
.into_iter()
|
||||
.filter(|item| !current.items.iter().any(|known| known.id() == item.id()))
|
||||
.collect::<Vec<_>>();
|
||||
current.items.splice(0..0, items);
|
||||
false
|
||||
});
|
||||
current_turns.splice(0..0, older_turns);
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "history_pagination_tests.rs"]
|
||||
mod tests;
|
||||
309
akode-rs/tui/src/app/history_pagination_tests.rs
Normal file
309
akode-rs/tui/src/app/history_pagination_tests.rs
Normal file
@@ -0,0 +1,309 @@
|
||||
//! Older pages must preserve newer events and identify repeated hidden prompts precisely.
|
||||
|
||||
use super::*;
|
||||
use crate::app::test_support::make_test_app;
|
||||
use crate::history_cell::ComputerActivityCell;
|
||||
use crate::history_cell::FinalMessageSeparator;
|
||||
use crate::history_cell::ForkedThreadHistoryCell;
|
||||
use akode_app_server_protocol::ThreadItem;
|
||||
use akode_app_server_protocol::TurnItemsView;
|
||||
use akode_app_server_protocol::UserInput;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn turn(id: &str, status: TurnStatus, item_ids: &[&str]) -> Turn {
|
||||
Turn {
|
||||
id: id.to_string(),
|
||||
root_turn_id: None,
|
||||
items: item_ids
|
||||
.iter()
|
||||
.map(|id| ThreadItemPayload::UserMessage {
|
||||
id: id.to_string(),
|
||||
client_id: None,
|
||||
content: Vec::new(),
|
||||
})
|
||||
.map(ThreadItem::untimed)
|
||||
.collect(),
|
||||
items_view: TurnItemsView::Full,
|
||||
status,
|
||||
error: None,
|
||||
started_at: None,
|
||||
completed_at: None,
|
||||
duration_ms: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn overlapping_history_keeps_live_turn_state_and_newer_items() {
|
||||
let mut current = vec![turn("shared", TurnStatus::InProgress, &["overlap", "live"])];
|
||||
let older = vec![
|
||||
turn("old", TurnStatus::Completed, &["first"]),
|
||||
turn("shared", TurnStatus::Completed, &["before", "overlap"]),
|
||||
];
|
||||
merge_older_turns(&mut current, older);
|
||||
assert_eq!(
|
||||
current,
|
||||
vec![
|
||||
turn("old", TurnStatus::Completed, &["first"]),
|
||||
turn(
|
||||
"shared",
|
||||
TurnStatus::InProgress,
|
||||
&["before", "overlap", "live"]
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
fn user_cell(message: &str) -> Arc<dyn HistoryCell> {
|
||||
Arc::new(UserHistoryCell {
|
||||
presentation: Default::default(),
|
||||
message: message.to_string(),
|
||||
text_elements: Vec::new(),
|
||||
local_image_paths: Vec::new(),
|
||||
remote_image_urls: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn fork_lineage_stays_before_repeated_older_history_pages() {
|
||||
let mut app = make_test_app().await;
|
||||
app.transcript_cells = vec![
|
||||
Arc::new(ForkedThreadHistoryCell(
|
||||
crate::history_cell::PlainHistoryCell::new(vec!["Thread forked from parent".into()]),
|
||||
)),
|
||||
Arc::new(crate::history_cell::PlainHistoryCell::new(vec![
|
||||
"recent history".into(),
|
||||
])),
|
||||
];
|
||||
|
||||
app.prepend_older_transcript_cells(vec![Arc::new(crate::history_cell::PlainHistoryCell::new(
|
||||
vec!["older history".into()],
|
||||
))]);
|
||||
app.prepend_older_transcript_cells(vec![Arc::new(crate::history_cell::PlainHistoryCell::new(
|
||||
vec!["oldest history".into()],
|
||||
))]);
|
||||
|
||||
let rendered = app
|
||||
.transcript_cells
|
||||
.iter()
|
||||
.flat_map(|cell| cell.display_lines(/*width*/ 80))
|
||||
.map(|line| {
|
||||
line.spans
|
||||
.into_iter()
|
||||
.map(|span| span.content.into_owned())
|
||||
.collect::<String>()
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
insta::assert_snapshot!(rendered, @r###"
|
||||
Thread forked from parent
|
||||
oldest history
|
||||
older history
|
||||
recent history
|
||||
"###);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_prompt_matching_removes_only_the_hidden_occurrence() {
|
||||
let cells = vec![user_cell("repeat"), user_cell("other"), user_cell("repeat")];
|
||||
let persisted = vec![
|
||||
("unloaded".to_string(), user_cell("repeat")),
|
||||
("hidden".to_string(), user_cell("repeat")),
|
||||
("middle".to_string(), user_cell("other")),
|
||||
("visible".to_string(), user_cell("repeat")),
|
||||
];
|
||||
assert_eq!(
|
||||
hidden_transcript_indices(&cells, persisted, &HashSet::from(["hidden", "unloaded"])),
|
||||
vec![0],
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn hidden_last_item_keeps_turn_groups_and_completion_boundaries() {
|
||||
let computer = |id: &str| {
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"type": "mcpToolCall", "id": id, "server": "cua_repl", "tool": "js",
|
||||
"status": "completed", "arguments": {"title": format!("Inspect {id}")},
|
||||
"appContext": null, "pluginId": null, "readOnlyHint": null,
|
||||
"result": {"content": [], "structuredContent": null},
|
||||
"error": null, "durationMs": 10
|
||||
}))
|
||||
.expect("valid completed computer call")
|
||||
};
|
||||
for status in [
|
||||
TurnStatus::Completed,
|
||||
TurnStatus::Failed,
|
||||
TurnStatus::Interrupted,
|
||||
] {
|
||||
let mut app = make_test_app().await;
|
||||
let cwd = app.config.cwd.clone();
|
||||
let thread_id = ThreadId::new();
|
||||
let expected_completions = usize::from(status == TurnStatus::Completed);
|
||||
let mut first = turn("first", status, &[]);
|
||||
first.items = vec![
|
||||
ThreadItem::untimed(ThreadItemPayload::EnteredReviewMode {
|
||||
id: "enter-review".to_string(),
|
||||
review: "current changes".to_string(),
|
||||
}),
|
||||
computer("older-call"),
|
||||
ThreadItem::untimed(ThreadItemPayload::UserMessage {
|
||||
id: "hidden".to_string(),
|
||||
client_id: None,
|
||||
content: vec![UserInput::Text {
|
||||
text: "internal review prompt".to_string(),
|
||||
text_elements: Vec::new(),
|
||||
}],
|
||||
}),
|
||||
];
|
||||
first.completed_at = Some(1_700_000_000);
|
||||
first.duration_ms = Some(125_000);
|
||||
let mut second = turn("second", TurnStatus::InProgress, &[]);
|
||||
second.items = vec![computer("newer-call")];
|
||||
let turns = vec![first, second];
|
||||
let hidden = hidden_review_item_ids(&turns);
|
||||
assert_eq!(hidden, HashSet::from(["hidden"]));
|
||||
let items = turns
|
||||
.iter()
|
||||
.flat_map(Turn::item_payloads)
|
||||
.cloned()
|
||||
.collect::<Vec<_>>();
|
||||
|
||||
let cells = app.project_older_history_cells(
|
||||
items.clone(),
|
||||
&turns,
|
||||
&hidden,
|
||||
thread_id,
|
||||
&cwd,
|
||||
RawReasoningVisibility::Hidden,
|
||||
);
|
||||
let groups = cells
|
||||
.iter()
|
||||
.filter_map(|cell| cell.as_any().downcast_ref::<ComputerActivityCell>())
|
||||
.map(|cell| cell.call_ids().map(str::to_string).collect::<Vec<_>>())
|
||||
.collect::<Vec<_>>();
|
||||
let completions = cells
|
||||
.iter()
|
||||
.filter(|cell| cell.as_any().is::<FinalMessageSeparator>())
|
||||
.count();
|
||||
let visible_users = cells
|
||||
.iter()
|
||||
.filter(|cell| cell.as_any().is::<UserHistoryCell>())
|
||||
.count();
|
||||
assert_eq!(
|
||||
(groups, completions, visible_users),
|
||||
(
|
||||
vec![
|
||||
vec!["older-call".to_string()],
|
||||
vec!["newer-call".to_string()]
|
||||
],
|
||||
expected_completions,
|
||||
0,
|
||||
),
|
||||
);
|
||||
|
||||
let repeated = app.project_older_history_cells(
|
||||
items,
|
||||
&turns,
|
||||
&hidden,
|
||||
thread_id,
|
||||
&cwd,
|
||||
RawReasoningVisibility::Hidden,
|
||||
);
|
||||
assert_eq!(
|
||||
repeated
|
||||
.iter()
|
||||
.filter(|cell| cell.as_any().is::<FinalMessageSeparator>())
|
||||
.count(),
|
||||
0,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn browsing_waits_for_a_prompt_outside_the_initial_history_window() -> Result<()> {
|
||||
let mut app = make_test_app().await;
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
tui.set_owned_screen(/*owned*/ true)?;
|
||||
app.scrollback_has_older_history = true;
|
||||
app.transcript_cells = vec![
|
||||
user_cell(""),
|
||||
Arc::new(crate::history_cell::PlainHistoryCell::new(vec![
|
||||
"recent answer".into(),
|
||||
])),
|
||||
];
|
||||
app.handle_backtrack_esc_key(&mut tui);
|
||||
app.handle_backtrack_esc_key(&mut tui);
|
||||
assert!(app.backtrack.overlay_preview_active && app.browsing_needs_history());
|
||||
app.prepend_older_transcript_cells(vec![
|
||||
user_cell(""),
|
||||
Arc::new(crate::history_cell::PlainHistoryCell::new(vec![
|
||||
"earlier answer".into(),
|
||||
])),
|
||||
]);
|
||||
assert!(app.browsing_needs_history());
|
||||
app.prepend_older_transcript_cells(vec![
|
||||
user_cell(""),
|
||||
user_cell("older prompt"),
|
||||
user_cell("latest prompt"),
|
||||
]);
|
||||
app.apply_backtrack_selection_internal(app.backtrack.nth_user_message);
|
||||
assert_eq!(
|
||||
(
|
||||
app.backtrack.nth_user_message,
|
||||
crate::app_backtrack::nth_user_position(
|
||||
&app.transcript_cells,
|
||||
app.backtrack.nth_user_message
|
||||
)
|
||||
),
|
||||
(1, Some(2))
|
||||
);
|
||||
assert!(!app.browsing_needs_history());
|
||||
app.apply_backtrack_selection_internal(/*nth_user_message*/ 0);
|
||||
let mut review_turn = turn(
|
||||
"review",
|
||||
TurnStatus::Completed,
|
||||
&["older prompt", "latest prompt"],
|
||||
);
|
||||
for item in &mut review_turn.items {
|
||||
if let ThreadItemPayload::UserMessage { id, content, .. } = &mut item.payload {
|
||||
*content = vec![UserInput::Text {
|
||||
text: id.clone(),
|
||||
text_elements: Vec::new(),
|
||||
}];
|
||||
}
|
||||
}
|
||||
review_turn.items.insert(
|
||||
/*index*/ 0,
|
||||
ThreadItem::untimed(ThreadItemPayload::EnteredReviewMode {
|
||||
id: "enter".to_string(),
|
||||
review: "review".to_string(),
|
||||
}),
|
||||
);
|
||||
review_turn.items.insert(
|
||||
/*index*/ 2,
|
||||
ThreadItem::untimed(ThreadItemPayload::ExitedReviewMode {
|
||||
id: "exit".to_string(),
|
||||
review: "review".to_string(),
|
||||
}),
|
||||
);
|
||||
let turns = [review_turn];
|
||||
app.remove_hidden_review_cells(
|
||||
&mut tui,
|
||||
&turns,
|
||||
&hidden_review_item_ids(&turns),
|
||||
ThreadId::new(),
|
||||
&app.config.cwd.clone(),
|
||||
RawReasoningVisibility::Hidden,
|
||||
);
|
||||
assert!(!app.backtrack.overlay_preview_active);
|
||||
assert_eq!(
|
||||
app.transcript_cells
|
||||
.iter()
|
||||
.filter_map(|cell| cell.as_any().downcast_ref::<UserHistoryCell>())
|
||||
.filter(|cell| !cell.message.is_empty())
|
||||
.map(|cell| cell.message.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
vec!["latest prompt"]
|
||||
);
|
||||
tui.set_owned_screen(/*owned*/ false)?;
|
||||
Ok(())
|
||||
}
|
||||
365
akode-rs/tui/src/app/history_ui.rs
Normal file
365
akode-rs/tui/src/app/history_ui.rs
Normal file
@@ -0,0 +1,365 @@
|
||||
//! Terminal history, desktop handoff, and clear-screen UI helpers for the TUI app.
|
||||
//!
|
||||
//! This module owns rendering the fresh session header, clearing inline or alternate-screen UI
|
||||
//! state, and resetting transcript-related app state after `/clear` or Ctrl-L. Owned-screen sessions
|
||||
//! keep committed cells as the render source and never enqueue terminal-scrollback rows here.
|
||||
|
||||
use super::*;
|
||||
use crate::terminal_hyperlinks::HyperlinkLine;
|
||||
|
||||
const DESKTOP_THREAD_OPENED_MESSAGE: &str = "Opened this session in the Desktop app.";
|
||||
|
||||
/// Lines of the most recently committed history cell, kept so reflow and restore can be verified.
|
||||
pub(super) struct RenderedHistoryTail {
|
||||
#[cfg_attr(not(test), allow(dead_code))]
|
||||
pub(super) lines: Vec<HyperlinkLine>,
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub(super) fn link_viewed_image(&self, cell: &mut dyn HistoryCell) {
|
||||
if let Some(image) = cell
|
||||
.as_any_mut()
|
||||
.downcast_mut::<history_cell::ViewImageHistoryCell>()
|
||||
&& !self.app_server_target.uses_remote_workspace()
|
||||
&& crate::projectless::has_only_local_environments(&self.environment_manager)
|
||||
&& !crate::clipboard_copy::is_ssh_session()
|
||||
{
|
||||
image.link_local_image();
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn insert_history_cell(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
mut cell: Box<dyn HistoryCell>,
|
||||
) {
|
||||
self.link_viewed_image(cell.as_mut());
|
||||
// Global deprecations can be delivered again by hidden threads. Scope deduplication to
|
||||
// retained history so clearing or rebuilding a transcript can show the notice again.
|
||||
if let Some(notice) = cell
|
||||
.as_any()
|
||||
.downcast_ref::<history_cell::DeprecationNoticeCell>()
|
||||
&& self.transcript_cells.iter().any(|existing| {
|
||||
existing
|
||||
.as_any()
|
||||
.downcast_ref::<history_cell::DeprecationNoticeCell>()
|
||||
== Some(notice)
|
||||
})
|
||||
{
|
||||
return;
|
||||
}
|
||||
if !crate::empty_state_animation::is_startup_cell(cell.as_ref()) {
|
||||
self.chat_widget
|
||||
.empty_state_animation
|
||||
.borrow_mut()
|
||||
.dismiss();
|
||||
}
|
||||
if let Some(warnings) = cell
|
||||
.as_any()
|
||||
.downcast_ref::<history_cell::StartupWarningsCell>()
|
||||
{
|
||||
self.merge_startup_warnings(tui, warnings);
|
||||
return;
|
||||
}
|
||||
let is_session_header = cell.as_any().is::<history_cell::SessionInfoCell>();
|
||||
let cell: Arc<dyn HistoryCell> = cell.into();
|
||||
if let Some(Overlay::Transcript(t)) = &mut self.overlay {
|
||||
t.insert_cell(cell.clone());
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
self.transcript_cells.push(cell.clone());
|
||||
let deferred = tui.is_owned_screen() || self.native_history.insert(&cell);
|
||||
self.render_inserted_history_cell(tui, &cell, deferred);
|
||||
// A committed cell can unblock a settled /usage card that was waiting
|
||||
// behind a transient active cell or a provisional stream tail.
|
||||
if is_session_header {
|
||||
self.merge_startup_warnings(tui, &history_cell::StartupWarningsCell::default());
|
||||
}
|
||||
}
|
||||
|
||||
/// Track mutable status cards before choosing retained or terminal-owned rendering.
|
||||
pub(super) fn render_inserted_history_cell(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
cell: &Arc<dyn HistoryCell>,
|
||||
deferred: bool,
|
||||
) {
|
||||
let width = self
|
||||
.chat_widget
|
||||
.history_wrap_width(tui.terminal.last_known_screen_size.width);
|
||||
// Owned replay must not eagerly format every historical entry. Composite status cards are
|
||||
// the only committed cells whose mutable usage data needs insertion-time bookkeeping.
|
||||
let lines = if !deferred || cell.as_any().is::<history_cell::CompositeHistoryCell>() {
|
||||
cell.display_hyperlink_lines_for_mode(width, self.chat_widget.history_render_mode())
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
// Invisible diagnostics still update the badge without replacing the rendered tail.
|
||||
if deferred || lines.is_empty() {
|
||||
tui.frame_requester().schedule_frame();
|
||||
return;
|
||||
}
|
||||
if self.initial_history_replay_buffer.as_ref().is_some() {
|
||||
self.insert_history_cell_lines_with_initial_replay_buffer(tui, cell.as_ref(), width);
|
||||
self.last_rendered_history_tail = None;
|
||||
} else {
|
||||
self.insert_history_cell_lines(tui, cell.as_ref(), width);
|
||||
self.last_rendered_history_tail = if self.overlay.is_none() {
|
||||
Some(RenderedHistoryTail { lines })
|
||||
} else {
|
||||
None
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn open_url_in_browser(&mut self, url: String) {
|
||||
if let Err(err) = webbrowser::open(&url) {
|
||||
self.chat_widget
|
||||
.add_error_message(format!("Failed to open browser for {url}: {err}"));
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn open_desktop_thread(&mut self, thread_id: ThreadId) {
|
||||
let url = format!("codex://threads/{thread_id}");
|
||||
if let Err(err) = open_desktop_thread_url(&url) {
|
||||
self.chat_widget
|
||||
.add_error_message(desktop_thread_open_error_message(&err));
|
||||
return;
|
||||
}
|
||||
|
||||
self.chat_widget.add_info_message(
|
||||
DESKTOP_THREAD_OPENED_MESSAGE.to_string(),
|
||||
/*hint*/ None,
|
||||
);
|
||||
}
|
||||
|
||||
pub(super) fn clear_ui_header_lines_with_version(
|
||||
&self,
|
||||
width: u16,
|
||||
version: &'static str,
|
||||
) -> Vec<Line<'static>> {
|
||||
self.clear_ui_header_cell(version)
|
||||
.display_lines_for_mode(width, self.chat_widget.history_render_mode())
|
||||
}
|
||||
|
||||
/// Share the source-backed header between retained drawing and legacy terminal insertion.
|
||||
fn clear_ui_header_cell(
|
||||
&self,
|
||||
version: &'static str,
|
||||
) -> history_cell::SessionHeaderHistoryCell {
|
||||
history_cell::SessionHeaderHistoryCell::new(
|
||||
self.chat_widget.model_display_name().to_string(),
|
||||
self.chat_widget.current_reasoning_effort(),
|
||||
self.config.cwd.to_path_buf(),
|
||||
version,
|
||||
)
|
||||
.with_yolo_mode(history_cell::is_yolo_mode(&self.config))
|
||||
.with_provider_name(Some(self.config.model_provider.name.clone()))
|
||||
}
|
||||
|
||||
pub(super) fn clear_ui_header_lines(&self, width: u16) -> Vec<Line<'static>> {
|
||||
self.clear_ui_header_lines_with_version(width, AKODE_CLI_VERSION)
|
||||
}
|
||||
|
||||
pub(super) fn start_cleared_display(&mut self, tui: &mut tui::Tui) {
|
||||
self.reset_terminal_display_state();
|
||||
self.transcript_cells
|
||||
.retain(|cell| !cell.as_any().is::<history_cell::ClearScreenHeader>());
|
||||
let header = history_cell::ClearScreenHeader(self.clear_ui_header_cell(AKODE_CLI_VERSION));
|
||||
self.insert_history_cell(tui, Box::new(header));
|
||||
}
|
||||
|
||||
pub(super) fn queue_clear_ui_header(&mut self, tui: &mut tui::Tui) {
|
||||
if tui.is_owned_screen() {
|
||||
if !self.transcript_cells.iter().any(|cell| {
|
||||
cell.as_any().is::<history_cell::SessionInfoCell>()
|
||||
|| cell.as_any().is::<history_cell::SessionHeaderHistoryCell>()
|
||||
}) {
|
||||
let header: Arc<dyn HistoryCell> =
|
||||
Arc::new(self.clear_ui_header_cell(AKODE_CLI_VERSION));
|
||||
self.transcript_cells.insert(/*index*/ 0, header);
|
||||
}
|
||||
tui.frame_requester().schedule_frame();
|
||||
return;
|
||||
}
|
||||
let width = self
|
||||
.chat_widget
|
||||
.history_wrap_width(tui.terminal.last_known_screen_size.width);
|
||||
let header_lines = self.clear_ui_header_lines(width);
|
||||
if !header_lines.is_empty() {
|
||||
tui.insert_history_lines_with_wrap_policy(
|
||||
header_lines,
|
||||
self.history_line_wrap_policy(),
|
||||
);
|
||||
self.has_emitted_history_lines = true;
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn clear_terminal_ui(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
redraw_header: bool,
|
||||
) -> Result<()> {
|
||||
let is_alt_screen_active = tui.is_alt_screen_active();
|
||||
|
||||
// Drop queued history insertions so stale transcript lines cannot be flushed after /clear.
|
||||
tui.clear_pending_history_lines();
|
||||
|
||||
if tui.is_owned_screen() || is_alt_screen_active {
|
||||
tui.terminal.clear_visible_screen()?;
|
||||
} else {
|
||||
// Some terminals (Terminal.app, Warp) do not reliably drop scrollback when purge and
|
||||
// clear are emitted as separate backend commands. Prefer a single ANSI sequence.
|
||||
tui.terminal.clear_scrollback_and_visible_screen_ansi()?;
|
||||
}
|
||||
|
||||
let mut area = tui.terminal.viewport_area;
|
||||
if area.y > 0 {
|
||||
// After a full clear, anchor the inline viewport at the top and redraw a fresh header
|
||||
// box. `insert_history_lines()` will shift the viewport down by the rendered height.
|
||||
area.y = 0;
|
||||
tui.terminal.set_viewport_area(area);
|
||||
}
|
||||
self.has_emitted_history_lines = false;
|
||||
|
||||
if redraw_header {
|
||||
self.queue_clear_ui_header(tui);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn reset_app_ui_state_after_clear(&mut self) {
|
||||
self.reset_transcript_state_after_clear();
|
||||
}
|
||||
|
||||
pub(super) fn reset_transcript_state_after_clear(&mut self) {
|
||||
self.transcript_cells.clear();
|
||||
self.reset_terminal_display_state();
|
||||
}
|
||||
|
||||
fn reset_terminal_display_state(&mut self) {
|
||||
self.overlay = None;
|
||||
self.turn_tips.dismiss();
|
||||
self.chat_widget.warning_display_state.dismissed.clear();
|
||||
self.chat_widget.warning_display_state.transcript = Arc::default();
|
||||
self.chat_widget.warning_display_state.synced_cells = None;
|
||||
self.native_history = Default::default();
|
||||
self.cancel_pending_key_chord();
|
||||
self.transcript_view = Default::default();
|
||||
*self.chat_widget.rendered_selection.borrow_mut() = Default::default();
|
||||
self.last_rendered_history_tail = None;
|
||||
self.deferred_history_lines.clear();
|
||||
self.has_emitted_history_lines = false;
|
||||
self.transcript_reflow.clear();
|
||||
self.initial_history_replay_buffer = None;
|
||||
self.scrollback_has_older_history = false;
|
||||
self.backtrack = BacktrackState::default();
|
||||
self.backtrack_render_pending = false;
|
||||
self.skill_load_warnings.clear();
|
||||
}
|
||||
}
|
||||
|
||||
fn desktop_thread_open_error_message(err: &str) -> String {
|
||||
format!(
|
||||
"Failed to open this session in the Desktop app: {err}. Install or launch the Desktop app and try again."
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
fn open_desktop_thread_url(url: &str) -> Result<(), String> {
|
||||
let status = std::process::Command::new("open")
|
||||
.arg(url)
|
||||
.status()
|
||||
.map_err(|err| format!("failed to invoke `open`: {err}"))?;
|
||||
|
||||
if status.success() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(format!("`open {url}` exited with {status}"))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn open_desktop_thread_url(url: &str) -> Result<(), String> {
|
||||
let script = windows_desktop_app_launch_script(url);
|
||||
let output = std::process::Command::new("powershell.exe")
|
||||
.arg("-NoProfile")
|
||||
.arg("-Command")
|
||||
.arg(&script)
|
||||
.output()
|
||||
.map_err(|err| format!("failed to launch the Desktop app through PowerShell: {err}"))?;
|
||||
|
||||
if output.status.success() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
|
||||
if stderr.is_empty() {
|
||||
Err(format!(
|
||||
"failed to launch the Desktop app through PowerShell with {}",
|
||||
output.status
|
||||
))
|
||||
} else {
|
||||
Err(stderr)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn windows_desktop_app_launch_script(url: &str) -> String {
|
||||
let url = powershell_single_quoted_string(url);
|
||||
format!(
|
||||
r#"
|
||||
$ErrorActionPreference = 'Stop'
|
||||
$url = {url}
|
||||
|
||||
$package = Get-AppxPackage -Name OpenAI.Codex -ErrorAction SilentlyContinue
|
||||
if ($null -eq $package) {{
|
||||
Write-Error 'Desktop app package is not installed'
|
||||
exit 1
|
||||
}}
|
||||
|
||||
$manifest = Get-AppxPackageManifest -Package $package.PackageFullName
|
||||
$application = $manifest.Package.Applications.Application |
|
||||
Where-Object {{
|
||||
@($_.Extensions.Extension) | Where-Object {{
|
||||
$_.Category -eq 'windows.protocol' -and $_.Protocol.Name -eq 'codex'
|
||||
}}
|
||||
}} |
|
||||
Select-Object -First 1
|
||||
if ($null -eq $application -or [string]::IsNullOrWhiteSpace($application.Executable)) {{
|
||||
Write-Error 'Desktop app package does not declare a codex protocol executable'
|
||||
exit 1
|
||||
}}
|
||||
|
||||
# Launch the package-declared protocol executable rather than an internal Electron shim.
|
||||
# Windows can deny direct starts of internal executables under WindowsApps.
|
||||
$exe = Join-Path $package.InstallLocation $application.Executable
|
||||
$appDir = Split-Path -Parent $exe
|
||||
$app = Join-Path $appDir 'resources\app.asar'
|
||||
if (-not (Test-Path $exe)) {{
|
||||
Write-Error "Desktop app executable not found at $exe"
|
||||
exit 1
|
||||
}}
|
||||
if (-not (Test-Path $app)) {{
|
||||
Write-Error "Desktop app bundle not found at $app"
|
||||
exit 1
|
||||
}}
|
||||
|
||||
Start-Process -FilePath $exe -WorkingDirectory $appDir -ArgumentList @('resources\app.asar', $url)
|
||||
"#
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
fn powershell_single_quoted_string(value: &str) -> String {
|
||||
format!("'{}'", value.replace('\'', "''"))
|
||||
}
|
||||
|
||||
#[cfg(not(any(target_os = "macos", target_os = "windows")))]
|
||||
fn open_desktop_thread_url(_url: &str) -> Result<(), String> {
|
||||
Err("The Desktop app is only available on macOS and Windows".to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "history_ui_tests.rs"]
|
||||
mod tests;
|
||||
101
akode-rs/tui/src/app/history_ui_tests.rs
Normal file
101
akode-rs/tui/src/app/history_ui_tests.rs
Normal file
@@ -0,0 +1,101 @@
|
||||
//! Desktop handoff output and clear-screen history reset behavior.
|
||||
|
||||
use super::*;
|
||||
use crate::app::tests::make_test_app_with_channels;
|
||||
use crate::history_cell;
|
||||
use crate::history_cell::HistoryCell;
|
||||
use crate::history_cell::PlainHistoryCell;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn desktop_thread_opened_history_snapshot() {
|
||||
let cell = history_cell::new_info_event(
|
||||
DESKTOP_THREAD_OPENED_MESSAGE.to_string(),
|
||||
/*hint*/ None,
|
||||
);
|
||||
|
||||
insta::assert_snapshot!("desktop_thread_opened_history", render_cell(&cell));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn desktop_thread_open_error_history_snapshot() {
|
||||
let cell = history_cell::new_error_event(desktop_thread_open_error_message("launch failed"));
|
||||
|
||||
insta::assert_snapshot!("desktop_thread_open_error_history", render_cell(&cell));
|
||||
}
|
||||
|
||||
fn render_cell(cell: &impl HistoryCell) -> String {
|
||||
let lines = cell.display_lines(/*width*/ 80);
|
||||
lines
|
||||
.iter()
|
||||
.map(ToString::to_string)
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn viewed_image_links_follow_workspace_locality() -> Result<()> {
|
||||
let dir = tempfile::tempdir()?;
|
||||
let path = dir.path().join("frame.png");
|
||||
image::RgbaImage::new(1, 1).save(&path)?;
|
||||
let endpoint = crate::resolve_remote_addr("ws://127.0.0.1:4500")?;
|
||||
let (mut app, _, _) = make_test_app_with_channels().await;
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
let local_links = !crate::clipboard_copy::is_ssh_session();
|
||||
for (target, linked) in [
|
||||
(AppServerTarget::Embedded, local_links),
|
||||
(
|
||||
AppServerTarget::LocalDaemon {
|
||||
endpoint: endpoint.clone(),
|
||||
allow_embedded_fallback: false,
|
||||
},
|
||||
local_links,
|
||||
),
|
||||
(AppServerTarget::Remote { endpoint }, false),
|
||||
] {
|
||||
app.app_server_target = target;
|
||||
let cell = history_cell::new_view_image_tool_call(
|
||||
"view".into(),
|
||||
akode_utils_path_uri::LegacyAppPathString::from_path(&path),
|
||||
);
|
||||
app.insert_history_cell(&mut tui, Box::new(cell));
|
||||
let rows = app
|
||||
.transcript_cells
|
||||
.last()
|
||||
.unwrap()
|
||||
.compact_hyperlink_lines(/*width*/ 80);
|
||||
assert_eq!(!rows[0].hyperlinks.is_empty(), linked);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn owned_clear_resets_navigation_and_retains_one_fresh_header() -> Result<()> {
|
||||
let (mut app, _rx, _op_rx) = make_test_app_with_channels().await;
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
tui.set_owned_screen(/*owned*/ true)?;
|
||||
app.insert_history_cell(
|
||||
&mut tui,
|
||||
Box::new(PlainHistoryCell::new(vec!["old".into()])),
|
||||
);
|
||||
app.transcript_view
|
||||
.jump_to_entry(&app.transcript_cells, /*index*/ 0);
|
||||
app.reset_transcript_state_after_clear();
|
||||
app.queue_clear_ui_header(&mut tui);
|
||||
app.queue_clear_ui_header(&mut tui);
|
||||
|
||||
assert_eq!(app.transcript_cells.len(), 1);
|
||||
assert_eq!(
|
||||
app.transcript_cells[0].display_lines(/*width*/ 80),
|
||||
app.clear_ui_header_lines(/*width*/ 80),
|
||||
);
|
||||
app.chat_widget.set_raw_output_mode(/*enabled*/ true);
|
||||
assert_eq!(
|
||||
app.transcript_cells[0].raw_lines(),
|
||||
app.clear_ui_header_lines(/*width*/ 80),
|
||||
);
|
||||
assert!(app.transcript_view.is_following());
|
||||
assert!(tui.pending_history_lines_for_test().is_empty());
|
||||
tui.set_owned_screen(/*owned*/ false)?;
|
||||
Ok(())
|
||||
}
|
||||
919
akode-rs/tui/src/app/input.rs
Normal file
919
akode-rs/tui/src/app/input.rs
Normal file
@@ -0,0 +1,919 @@
|
||||
//! Keyboard input, external editor, and status-line dispatch for the TUI app.
|
||||
//!
|
||||
//! This module owns global key bindings that sit above ChatWidget, including transcript overlay
|
||||
//! entry, Ctrl-L clear, external editor launch, agent navigation shortcuts, and legacy Vim
|
||||
//! Escape recovery for the active composer or command-center rename editor.
|
||||
|
||||
use super::*;
|
||||
use crate::app_backtrack::SIDE_EDIT_PREVIOUS_UNAVAILABLE_MESSAGE;
|
||||
use crate::keymap::KeymapContextSet;
|
||||
use crate::keymap::bindings_for_action;
|
||||
use crate::keymap::keymap_action_ids;
|
||||
|
||||
mod select_mode;
|
||||
|
||||
impl App {
|
||||
pub(super) fn should_recover_vim_insert_escape(
|
||||
&self,
|
||||
tui: &tui::Tui,
|
||||
key_event: KeyEvent,
|
||||
) -> bool {
|
||||
let active_contexts = self.key_chord_contexts(tui);
|
||||
if self.focused_sidebar_chooser(tui) {
|
||||
return false;
|
||||
}
|
||||
let rename_active = self
|
||||
.chat_widget
|
||||
.selected_index_for_active_view(AGENTS_OVERVIEW_VIEW_ID)
|
||||
.is_some();
|
||||
let escape = KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE);
|
||||
let insert_escape = if rename_active {
|
||||
let state = self
|
||||
.agents_overview
|
||||
.view_state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
state.rename_target.is_some() && state.input.should_handle_vim_insert_escape(escape)
|
||||
} else {
|
||||
self.chat_widget.no_modal_or_popup_active()
|
||||
&& self.chat_widget.should_handle_vim_insert_escape(escape)
|
||||
};
|
||||
// Legacy terminals encode Alt+character and Escape+character identically. Active
|
||||
// bindings and either stroke of a chord win; inactive bindings do not consume input.
|
||||
cfg!(unix)
|
||||
&& !self.enhanced_keys_supported
|
||||
&& self.overlay.is_none()
|
||||
&& !self.transcript_view.is_search_editing()
|
||||
&& insert_escape
|
||||
&& matches!(key_event.code, KeyCode::Char(_))
|
||||
&& matches!(key_event.kind, KeyEventKind::Press | KeyEventKind::Repeat)
|
||||
&& (key_event.modifiers == KeyModifiers::ALT
|
||||
|| key_event.modifiers == (KeyModifiers::ALT | KeyModifiers::SHIFT))
|
||||
// ChatWidget's fixed image-paste shortcut is not in the configurable keymap.
|
||||
&& !(!rename_active
|
||||
&& key_event.kind == KeyEventKind::Press
|
||||
&& matches!(key_event.code, KeyCode::Char('v' | 'V')))
|
||||
// Empty-draft agent navigation also has fixed legacy-terminal fallbacks.
|
||||
&& !(!rename_active
|
||||
&& self.chat_widget.composer_text_with_pending().is_empty()
|
||||
&& (previous_agent_shortcut_matches(key_event, /*allow_word_motion_fallback*/ true)
|
||||
|| next_agent_shortcut_matches(key_event, /*allow_word_motion_fallback*/ true)))
|
||||
&& !keymap_action_ids()
|
||||
.filter(|action| active_contexts.contains_action(*action))
|
||||
.any(|action| {
|
||||
bindings_for_action(&self.keymap, action.context.config_name(), action.action)
|
||||
.is_some_and(|bindings| bindings.is_pressed(key_event))
|
||||
})
|
||||
&& !matches!(
|
||||
self.key_chord_matcher.clone().advance(
|
||||
key_event,
|
||||
&self.keymap.chords,
|
||||
active_contexts),
|
||||
crate::keymap::KeyChordMatch::Pending(_)
|
||||
| crate::keymap::KeyChordMatch::Completed(_)
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn route_key_chord_event(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
key_event: KeyEvent,
|
||||
) -> Option<KeyEvent> {
|
||||
self.routed_key_activation = None;
|
||||
if self.chat_widget.take_key_chord_reset() {
|
||||
self.cancel_pending_key_chord();
|
||||
}
|
||||
if self
|
||||
.chat_widget
|
||||
.consume_view_transition_key_event(key_event)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
// Pending config handoffs must see the physical key before a chord or global shortcut
|
||||
// consumes it.
|
||||
self.chat_widget
|
||||
.observe_config_editor_transition_key_event(key_event);
|
||||
self.transcript_view.set_keymap_bindings(&self.keymap);
|
||||
if let Some(Overlay::Transcript(overlay)) = &mut self.overlay {
|
||||
overlay.set_keymap_bindings(&self.keymap);
|
||||
}
|
||||
if self.overlay.is_none() && self.chat_widget.handle_quick_dial_menu(key_event) {
|
||||
return None;
|
||||
}
|
||||
let contexts = self.key_chord_contexts(tui);
|
||||
let select_mode_chord = self.select_mode_owns_chord(tui, key_event);
|
||||
if (matches!(&self.overlay, Some(Overlay::Transcript(overlay)) if overlay.owns_interaction_key(key_event))
|
||||
|| (tui.is_owned_screen()
|
||||
&& self.overlay.is_none()
|
||||
&& !self.focused_sidebar_chooser(tui)
|
||||
&& self.chat_widget.no_modal_or_popup_active()
|
||||
&& self.transcript_view.owns_interaction_key(key_event)
|
||||
&& (self.transcript_view.has_active_interaction()
|
||||
|| self.backtrack.overlay_preview_active
|
||||
|| crate::transcript_view::JumpTarget::from_key(key_event).is_none())))
|
||||
&& !select_mode_chord
|
||||
{
|
||||
let close = tui.is_owned_screen()
|
||||
&& self.overlay.is_none()
|
||||
&& self.transcript_view.is_detailed()
|
||||
&& !self.transcript_view.has_active_interaction()
|
||||
&& !self.backtrack.overlay_preview_active;
|
||||
let allowed = |action: crate::keymap::KeymapActionId| {
|
||||
(close
|
||||
&& action.context == crate::keymap::KeymapContext::Pager
|
||||
&& action.action == "close_transcript")
|
||||
|| (action.is_side_pane() && contexts.contains_action(action))
|
||||
};
|
||||
let chord = match self.key_chord_matcher.clone().advance(
|
||||
key_event,
|
||||
&self.keymap.chords,
|
||||
contexts,
|
||||
) {
|
||||
crate::keymap::KeyChordMatch::Completed(event) => {
|
||||
self.keymap.chords.bindings.iter().any(|binding| {
|
||||
allowed(binding.action)
|
||||
&& crate::keymap::dispatch_event(binding.action) == Some(event)
|
||||
})
|
||||
}
|
||||
crate::keymap::KeyChordMatch::Pending(prefix) => self
|
||||
.keymap
|
||||
.chords
|
||||
.bindings
|
||||
.iter()
|
||||
.any(|binding| binding.chord.prefix == prefix && allowed(binding.action)),
|
||||
crate::keymap::KeyChordMatch::PassThrough
|
||||
| crate::keymap::KeyChordMatch::Cancelled
|
||||
| crate::keymap::KeyChordMatch::Ignored => false,
|
||||
};
|
||||
if !chord {
|
||||
self.cancel_pending_key_chord();
|
||||
return Some(key_event);
|
||||
}
|
||||
}
|
||||
let was_pending = self.key_chord_matcher.is_pending();
|
||||
if !was_pending
|
||||
&& contexts.is_warnings()
|
||||
&& (crate::key_hint::plain(KeyCode::Char('k')).is_press(key_event)
|
||||
|| (!crate::key_hint::is_plain_text_key_event(key_event)
|
||||
&& self
|
||||
.keymap
|
||||
.list
|
||||
.action_for(key_event)
|
||||
.is_some_and(|action| action != crate::keymap::ListAction::Accept)))
|
||||
{
|
||||
return Some(key_event);
|
||||
}
|
||||
if !was_pending
|
||||
&& contexts.contains(crate::keymap::KeymapContext::Agents)
|
||||
&& {
|
||||
let state = self
|
||||
.agents_overview
|
||||
.view_state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
state.editing_metadata() && state.rename_target.is_none()
|
||||
}
|
||||
&& crate::key_hint::is_plain_text_key_event(key_event)
|
||||
{
|
||||
return Some(key_event);
|
||||
}
|
||||
match self
|
||||
.key_chord_matcher
|
||||
.advance(key_event, &self.keymap.chords, contexts)
|
||||
{
|
||||
crate::keymap::KeyChordMatch::PassThrough => {
|
||||
if was_pending && !self.key_chord_matcher.is_pending() {
|
||||
self.set_key_chord_hint_override(/*items*/ None);
|
||||
}
|
||||
Some(key_event)
|
||||
}
|
||||
crate::keymap::KeyChordMatch::Pending(_) => {
|
||||
if self.backtrack.primed && !self.backtrack.overlay_preview_active {
|
||||
self.reset_backtrack_state();
|
||||
}
|
||||
if self.key_chord_matcher.workspace_leader().is_some() {
|
||||
tui.frame_requester()
|
||||
.schedule_frame_in(super::workspace_hud::REVEAL_DELAY);
|
||||
return None;
|
||||
}
|
||||
self.set_key_chord_hint_override(self.key_chord_matcher.pending_hint_items(
|
||||
&self.keymap.chords,
|
||||
tui.terminal.last_known_screen_size.width,
|
||||
));
|
||||
tui.frame_requester()
|
||||
.schedule_frame_in(crate::keymap::KEY_CHORD_TIMEOUT);
|
||||
None
|
||||
}
|
||||
crate::keymap::KeyChordMatch::Completed(dispatch_event) => {
|
||||
self.set_key_chord_hint_override(/*items*/ None);
|
||||
// A view transition needs the physical completion key to suppress held input.
|
||||
self.routed_key_activation = Some(KeyBinding::from_event(key_event));
|
||||
Some(dispatch_event)
|
||||
}
|
||||
crate::keymap::KeyChordMatch::Cancelled => {
|
||||
self.set_key_chord_hint_override(/*items*/ None);
|
||||
None
|
||||
}
|
||||
crate::keymap::KeyChordMatch::Ignored => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn expire_pending_key_chord(&mut self, tui: &tui::Tui) {
|
||||
if self.chat_widget.take_key_chord_reset() {
|
||||
self.cancel_pending_key_chord();
|
||||
}
|
||||
let contexts = self.key_chord_contexts(tui);
|
||||
if self.key_chord_matcher.expire(contexts) {
|
||||
self.set_key_chord_hint_override(/*items*/ None);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn cancel_pending_key_chord(&mut self) {
|
||||
self.chat_widget.cancel_quick_dial_menu();
|
||||
if self.key_chord_matcher.cancel() {
|
||||
self.set_key_chord_hint_override(/*items*/ None);
|
||||
}
|
||||
}
|
||||
|
||||
fn set_key_chord_hint_override(&mut self, items: Option<Vec<(String, String)>>) {
|
||||
if let Some(Overlay::Transcript(overlay)) = &mut self.overlay {
|
||||
overlay.key_chord_hint = items.clone();
|
||||
}
|
||||
self.agents_overview
|
||||
.view_state
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.key_chord_hint = items.clone();
|
||||
self.chat_widget.set_footer_hint_override(items);
|
||||
}
|
||||
|
||||
fn focused_sidebar_chooser(&self, tui: &tui::Tui) -> bool {
|
||||
self.conversation_focus_available(tui)
|
||||
&& self.chooser_focus() == Some(super::sidebar::PaneFocus::Sidebar)
|
||||
&& self.sidebar_chooser_available()
|
||||
}
|
||||
|
||||
fn key_chord_contexts(&self, tui: &tui::Tui) -> crate::keymap::KeymapContextSet {
|
||||
let contexts = self.active_keymap_contexts();
|
||||
if !self.conversation_focus_available(tui) {
|
||||
return contexts;
|
||||
}
|
||||
if self.focused_sidebar_chooser(tui) {
|
||||
let contexts = KeymapContextSet::focused_sidebar_chooser();
|
||||
return if self.can_nudge_side_width(tui) {
|
||||
contexts.with_sidebar_resize().with_focused_side_pane()
|
||||
} else {
|
||||
contexts
|
||||
};
|
||||
}
|
||||
let mut contexts = contexts.with_pane_directions();
|
||||
if self.sidebar_has_focus() && self.sidebar_chooser_available() {
|
||||
contexts = contexts.with_focused_sidebar();
|
||||
}
|
||||
if self.open_pane_focus().is_some() {
|
||||
contexts = contexts.with_open_pane();
|
||||
}
|
||||
if self.can_resize_sidebar(tui) {
|
||||
contexts = contexts.with_sidebar_resize();
|
||||
}
|
||||
if self.can_nudge_side_width(tui) {
|
||||
contexts = contexts.with_focused_side_pane();
|
||||
}
|
||||
if self.main_composer_shortcut_available() {
|
||||
contexts = contexts.with_main_composer_focus();
|
||||
}
|
||||
if self.switchable_side_child().is_some() {
|
||||
contexts.with_side_pane()
|
||||
} else if self.sidebar_chooser_available() {
|
||||
contexts.with_sidebar_chooser()
|
||||
} else {
|
||||
contexts
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn active_keymap_contexts(&self) -> crate::keymap::KeymapContextSet {
|
||||
use crate::keymap::KeymapContext;
|
||||
use crate::keymap::KeymapContextSet;
|
||||
|
||||
if let Some(overlay) = &self.overlay {
|
||||
let context = if matches!(overlay, Overlay::Transcript(view) if view.is_search_editing())
|
||||
{
|
||||
KeymapContext::Editor
|
||||
} else {
|
||||
KeymapContext::Pager
|
||||
};
|
||||
let contexts =
|
||||
if matches!(overlay, Overlay::Transcript(_)) && context == KeymapContext::Pager {
|
||||
KeymapContextSet::transcript()
|
||||
} else {
|
||||
KeymapContextSet::new(context)
|
||||
}
|
||||
.with_voice_toggle(&self.keymap);
|
||||
return if self.backtrack.overlay_preview_active && context == KeymapContext::Pager {
|
||||
KeymapContextSet::browsing().with_voice_toggle(&self.keymap)
|
||||
} else {
|
||||
contexts
|
||||
};
|
||||
}
|
||||
if self.transcript_view.is_search_editing() && self.chat_widget.no_modal_or_popup_active() {
|
||||
return KeymapContextSet::new(KeymapContext::Editor).with_voice_toggle(&self.keymap);
|
||||
}
|
||||
if self.transcript_view.is_select_mode() && self.chat_widget.no_modal_or_popup_active() {
|
||||
return KeymapContextSet::transcript().with_voice_toggle(&self.keymap);
|
||||
}
|
||||
if self.transcript_view.is_activity_focused() && self.chat_widget.no_modal_or_popup_active()
|
||||
{
|
||||
return KeymapContextSet::activity().with_voice_toggle(&self.keymap);
|
||||
}
|
||||
if self.backtrack.overlay_preview_active && self.chat_widget.no_modal_or_popup_active() {
|
||||
return KeymapContextSet::browsing().with_voice_toggle(&self.keymap);
|
||||
}
|
||||
let voice_available = self.chat_widget.realtime_microphone_shortcut_available()
|
||||
|| self.voice_owner_thread_id().is_some();
|
||||
let contexts = self.chat_widget.keymap_contexts();
|
||||
let contexts = if self.chat_widget.no_modal_or_popup_active() {
|
||||
let contexts = contexts
|
||||
.with(KeymapContext::Global)
|
||||
.with(KeymapContext::Chat);
|
||||
let contexts = if self.transcript_view.is_detailed() {
|
||||
contexts.with_transcript_close()
|
||||
} else {
|
||||
contexts
|
||||
};
|
||||
if voice_available {
|
||||
contexts.with(KeymapContext::Voice)
|
||||
} else {
|
||||
contexts
|
||||
}
|
||||
} else {
|
||||
contexts
|
||||
};
|
||||
contexts.with_voice_toggle(&self.keymap)
|
||||
}
|
||||
|
||||
pub(super) async fn launch_external_editor(&mut self, tui: &mut tui::Tui) {
|
||||
let editor_cmd = match external_editor::resolve_editor_command() {
|
||||
Ok(cmd) => cmd,
|
||||
Err(external_editor::EditorError::MissingEditor) => {
|
||||
self.chat_widget
|
||||
.add_to_history(history_cell::new_error_event(
|
||||
"Cannot open external editor: set $VISUAL or $EDITOR before starting aKode."
|
||||
.to_string(),
|
||||
));
|
||||
self.reset_external_editor_state(tui);
|
||||
return;
|
||||
}
|
||||
Err(err) => {
|
||||
self.chat_widget
|
||||
.add_to_history(history_cell::new_error_event(format!(
|
||||
"Failed to open editor: {err}",
|
||||
)));
|
||||
self.reset_external_editor_state(tui);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let seed = self.chat_widget.composer_text_with_pending();
|
||||
let config = self.chat_widget.config_ref();
|
||||
let file_system_policy = config.permissions.file_system_sandbox_policy();
|
||||
let editor_result = tui
|
||||
.with_restored(tui::TerminalHandoff::KeepScreen, || async {
|
||||
external_editor::run_editor(
|
||||
&seed,
|
||||
&editor_cmd,
|
||||
config.codex_home.as_path(),
|
||||
&file_system_policy,
|
||||
config.cwd.as_path(),
|
||||
)
|
||||
.await
|
||||
})
|
||||
.await;
|
||||
self.reset_external_editor_state(tui);
|
||||
|
||||
match editor_result {
|
||||
Ok(new_text) => {
|
||||
// Trim trailing whitespace
|
||||
let cleaned = new_text.trim_end().to_string();
|
||||
self.chat_widget.apply_external_edit(cleaned);
|
||||
}
|
||||
Err(err) => {
|
||||
self.chat_widget
|
||||
.add_to_history(history_cell::new_error_event(format!(
|
||||
"Failed to open editor: {err}",
|
||||
)));
|
||||
}
|
||||
}
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
|
||||
pub(super) fn request_external_editor_launch(&mut self, tui: &mut tui::Tui) {
|
||||
self.chat_widget
|
||||
.set_external_editor_state(ExternalEditorState::Requested);
|
||||
self.chat_widget.set_footer_hint_override(Some(vec![(
|
||||
EXTERNAL_EDITOR_HINT.to_string(),
|
||||
String::new(),
|
||||
)]));
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
|
||||
pub(super) fn reset_external_editor_state(&mut self, tui: &mut tui::Tui) {
|
||||
self.chat_widget
|
||||
.set_external_editor_state(ExternalEditorState::Closed);
|
||||
self.chat_widget.set_footer_hint_override(/*items*/ None);
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
|
||||
pub(super) fn apply_raw_output_mode(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
enabled: bool,
|
||||
notify: bool,
|
||||
) {
|
||||
if notify {
|
||||
self.chat_widget.set_raw_output_mode_and_notify(enabled);
|
||||
} else {
|
||||
self.chat_widget.set_raw_output_mode(enabled);
|
||||
}
|
||||
if tui.is_owned_screen() {
|
||||
self.transcript_view.set_presentation(
|
||||
self.transcript_view.is_detailed(),
|
||||
self.chat_widget.history_render_mode(),
|
||||
);
|
||||
tui.frame_requester().schedule_frame();
|
||||
return;
|
||||
}
|
||||
if self.overlay.is_some() {
|
||||
self.schedule_immediate_resize_reflow(tui);
|
||||
return;
|
||||
}
|
||||
let terminal_width = tui.terminal.last_known_screen_size.into();
|
||||
if let Err(err) = self.reflow_transcript_now(tui, terminal_width) {
|
||||
tracing::warn!(error = %err, "failed to reflow transcript after raw output mode toggle");
|
||||
self.chat_widget
|
||||
.add_error_message(format!("Failed to redraw transcript: {err}"));
|
||||
}
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
|
||||
pub(super) async fn handle_key_event(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
app_server: &mut AppServerSession,
|
||||
key_event: KeyEvent,
|
||||
) {
|
||||
let activation_key = self.routed_key_activation.take();
|
||||
if self.chat_widget.fork_in_progress {
|
||||
return;
|
||||
}
|
||||
if self.chat_widget.has_provider_error()
|
||||
&& self.overlay.is_none()
|
||||
&& self.chat_widget.no_modal_or_popup_active()
|
||||
&& key_event.kind == KeyEventKind::Press
|
||||
&& key_event.modifiers == KeyModifiers::NONE
|
||||
{
|
||||
match key_event.code {
|
||||
KeyCode::Char('c') if self.chat_widget.rollout_path().is_some() => {
|
||||
if let Some(thread_id) = self.chat_widget.thread_id() {
|
||||
self.app_event_tx
|
||||
.send(AppEvent::ContinueProviderChat { thread_id });
|
||||
}
|
||||
return;
|
||||
}
|
||||
KeyCode::Char('n') => {
|
||||
self.app_event_tx.send(AppEvent::NewSession { name: None });
|
||||
return;
|
||||
}
|
||||
KeyCode::Esc => {
|
||||
self.app_event_tx.send(AppEvent::OpenResumePicker);
|
||||
return;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if self.chat_widget.is_external_writer_view()
|
||||
&& self.overlay.is_none()
|
||||
&& self.chat_widget.no_modal_or_popup_active()
|
||||
&& key_event.kind == KeyEventKind::Press
|
||||
{
|
||||
let modifiers = key_event.modifiers;
|
||||
if key_event.code == KeyCode::Esc && modifiers == KeyModifiers::NONE {
|
||||
self.open_agents_overview(app_server);
|
||||
return;
|
||||
}
|
||||
let quit = match key_event.code {
|
||||
KeyCode::Char('q' | 'Q') => {
|
||||
modifiers == KeyModifiers::NONE || modifiers == KeyModifiers::SHIFT
|
||||
}
|
||||
KeyCode::Char('c' | 'C') => {
|
||||
modifiers == KeyModifiers::CONTROL
|
||||
|| modifiers == (KeyModifiers::CONTROL | KeyModifiers::SHIFT)
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
if quit {
|
||||
self.app_event_tx.send(AppEvent::Exit(ExitMode::Immediate));
|
||||
return;
|
||||
}
|
||||
if matches!(key_event.code, KeyCode::Char('f' | 'F'))
|
||||
&& (modifiers == KeyModifiers::NONE || modifiers == KeyModifiers::SHIFT)
|
||||
{
|
||||
self.chat_widget.fork_in_progress = true;
|
||||
self.app_event_tx
|
||||
.send(AppEvent::ForkCurrentSession { name: None });
|
||||
return;
|
||||
}
|
||||
if matches!(key_event.code, KeyCode::Char('r' | 'R'))
|
||||
&& (modifiers == KeyModifiers::NONE || modifiers == KeyModifiers::SHIFT)
|
||||
&& let Some(thread_id) = self.current_displayed_thread_id()
|
||||
{
|
||||
let target = SessionTarget {
|
||||
backend_id: app_server.backend_id(),
|
||||
path: self
|
||||
.primary_session_configured
|
||||
.as_ref()
|
||||
.and_then(|session| session.rollout_path.clone()),
|
||||
thread_id,
|
||||
cwd: None,
|
||||
history_mode: None,
|
||||
};
|
||||
if let Ok(AppRunControl::Exit(_)) =
|
||||
self.resume_target_session(tui, app_server, target).await
|
||||
{
|
||||
self.app_event_tx.send(AppEvent::Exit(ExitMode::Immediate));
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
// Some terminals, especially on macOS, encode Option+Left/Right as Option+b/f unless
|
||||
// enhanced keyboard reporting is available. We only treat those word-motion fallbacks as
|
||||
// agent-switch shortcuts when the composer is empty so we never steal the expected
|
||||
// editing behavior for moving across words inside a draft.
|
||||
let allow_agent_word_motion_fallback = !self.enhanced_keys_supported
|
||||
&& self.chat_widget.composer_text_with_pending().is_empty();
|
||||
if self.overlay.is_none()
|
||||
&& self.chat_widget.no_modal_or_popup_active()
|
||||
// Alt+Left/Right are also natural word-motion keys in the composer. Keep agent
|
||||
// fast-switch available only once the draft is empty so editing behavior wins whenever
|
||||
// there is text on screen.
|
||||
&& self.chat_widget.composer_text_with_pending().is_empty()
|
||||
&& previous_agent_shortcut_matches(key_event, allow_agent_word_motion_fallback)
|
||||
{
|
||||
if let Some(thread_id) = self
|
||||
.adjacent_thread_id_with_backfill(app_server, AgentNavigationDirection::Previous)
|
||||
.await
|
||||
{
|
||||
let _ = self.select_agent_thread(tui, app_server, thread_id).await;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if self.overlay.is_none()
|
||||
&& self.chat_widget.no_modal_or_popup_active()
|
||||
// Mirror the previous-agent rule above: empty drafts may use these keys for thread
|
||||
// switching, but non-empty drafts keep them for expected word-wise cursor motion.
|
||||
&& self.chat_widget.composer_text_with_pending().is_empty()
|
||||
&& next_agent_shortcut_matches(key_event, allow_agent_word_motion_fallback)
|
||||
{
|
||||
if let Some(thread_id) = self
|
||||
.adjacent_thread_id_with_backfill(app_server, AgentNavigationDirection::Next)
|
||||
.await
|
||||
{
|
||||
let _ = self.select_agent_thread(tui, app_server, thread_id).await;
|
||||
}
|
||||
return;
|
||||
}
|
||||
if matches!(self.app_server_target, AppServerTarget::LocalDaemon { .. })
|
||||
&& self.overlay.is_none()
|
||||
&& self.chat_widget.no_modal_or_popup_active()
|
||||
&& self.chat_widget.composer_is_empty()
|
||||
&& self.active_side_parent_thread_id().is_none()
|
||||
&& matches!(
|
||||
key_event,
|
||||
KeyEvent {
|
||||
code: KeyCode::Char(c),
|
||||
modifiers,
|
||||
kind: KeyEventKind::Press,
|
||||
..
|
||||
} if modifiers.contains(KeyModifiers::CONTROL) && c.eq_ignore_ascii_case(&'c')
|
||||
)
|
||||
{
|
||||
let mut running_thread_id = if self.chat_widget.is_agent_turn_running() {
|
||||
self.chat_widget.thread_id()
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let mut running_side_thread_id =
|
||||
running_thread_id.filter(|thread_id| self.side_threads.contains_key(thread_id));
|
||||
if running_side_thread_id.is_none() {
|
||||
running_side_thread_id = self.running_side_thread_id().await;
|
||||
}
|
||||
if running_thread_id.is_none() {
|
||||
running_thread_id = running_side_thread_id;
|
||||
}
|
||||
|
||||
if let Some(thread_id) = running_thread_id {
|
||||
let allow_background = running_side_thread_id.is_none()
|
||||
&& !self.chat_widget.has_queued_follow_up_messages();
|
||||
self.chat_widget.show_selection_view(SelectionViewParams {
|
||||
title: Some("Task is still running".to_string()),
|
||||
subtitle: Some("Choose what happens to the current task.".to_string()),
|
||||
footer_hint: Some(standard_popup_hint_line()),
|
||||
items: [
|
||||
(
|
||||
"Cancel task",
|
||||
"Stop the current task and stay in aKode",
|
||||
RunningTaskExitAction::CancelTask,
|
||||
),
|
||||
(
|
||||
"Run in background",
|
||||
"Exit aKode and leave the task running",
|
||||
RunningTaskExitAction::RunInBackground,
|
||||
),
|
||||
(
|
||||
"Exit",
|
||||
"Stop the current task and exit aKode",
|
||||
RunningTaskExitAction::Exit,
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.filter(|(_, _, action)| {
|
||||
allow_background || *action != RunningTaskExitAction::RunInBackground
|
||||
})
|
||||
.map(|(name, description, action)| SelectionItem {
|
||||
name: name.to_string(),
|
||||
description: Some(description.to_string()),
|
||||
actions: vec![Box::new(move |tx| {
|
||||
tx.send(AppEvent::RunningTaskExit { action, thread_id });
|
||||
})],
|
||||
dismiss_on_select: true,
|
||||
..Default::default()
|
||||
})
|
||||
.collect(),
|
||||
..SelectionViewParams::picker()
|
||||
});
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if side_return_shortcut_matches(key_event)
|
||||
&& self
|
||||
.maybe_return_from_side(tui, app_server, key_event)
|
||||
.await
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let app_keymap_shortcuts_available = self.app_keymap_shortcuts_available();
|
||||
if app_keymap_shortcuts_available
|
||||
&& self
|
||||
.handle_shared_app_keymap_action(tui, app_server, key_event)
|
||||
.await
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
let find_transcript = self.keymap.app.find_transcript.is_pressed(key_event);
|
||||
let select_transcript = self.keymap.app.select_transcript.is_pressed(key_event);
|
||||
if app_keymap_shortcuts_available
|
||||
&& (self.keymap.app.open_transcript.is_pressed(key_event)
|
||||
|| find_transcript
|
||||
|| select_transcript)
|
||||
{
|
||||
self.scrollback_has_older_history = self
|
||||
.chat_widget
|
||||
.thread_id()
|
||||
.is_some_and(|thread_id| app_server.has_older_history(thread_id));
|
||||
self.open_transcript_overlay(tui);
|
||||
if find_transcript && let Some(Overlay::Transcript(overlay)) = &mut self.overlay {
|
||||
overlay.set_keymap_bindings(&self.keymap);
|
||||
overlay.begin_search();
|
||||
}
|
||||
if select_transcript && let Some(Overlay::Transcript(overlay)) = &mut self.overlay {
|
||||
overlay.set_keymap_bindings(&self.keymap);
|
||||
overlay.begin_select_mode();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if self.chat_widget.is_external_writer_view()
|
||||
&& self.overlay.is_none()
|
||||
&& self.chat_widget.no_modal_or_popup_active()
|
||||
{
|
||||
if key_event.kind == KeyEventKind::Press
|
||||
&& key_event.code == KeyCode::Left
|
||||
&& key_event.modifiers == KeyModifiers::NONE
|
||||
&& self.chat_widget.agents_navigation_key_available()
|
||||
{
|
||||
self.open_agents_overview(app_server);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if self.should_handle_unavailable_thread_key(key_event) {
|
||||
self.chat_widget
|
||||
.handle_restricted_key(key_event, RestrictedInputMode::UnavailableThread);
|
||||
return;
|
||||
}
|
||||
|
||||
if matches!(key_event.code, KeyCode::Esc)
|
||||
&& matches!(key_event.kind, KeyEventKind::Press | KeyEventKind::Repeat)
|
||||
{
|
||||
// Esc primes/advances backtracking only in normal (not working) mode
|
||||
// with the composer focused and empty. In any other state, forward
|
||||
// Esc so the active UI (e.g. status indicator, modals, popups)
|
||||
// handles it.
|
||||
if self.should_handle_backtrack_esc(key_event) {
|
||||
self.chat_widget.prepare_composer_sparkle_key(key_event);
|
||||
if key_event.kind == KeyEventKind::Press {
|
||||
self.handle_backtrack_esc_key(tui);
|
||||
}
|
||||
} else if self.should_reject_side_backtrack_esc(key_event) {
|
||||
self.reject_side_backtrack_esc();
|
||||
} else {
|
||||
let action = self
|
||||
.chat_widget
|
||||
.handle_key_event_with_activation_key(key_event, activation_key);
|
||||
self.handle_clipboard_key_action(tui, action);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
match key_event {
|
||||
// Enter confirms backtrack when primed + count > 0. Otherwise pass to widget.
|
||||
KeyEvent {
|
||||
code: KeyCode::Enter,
|
||||
kind: KeyEventKind::Press,
|
||||
..
|
||||
} if self.backtrack.primed
|
||||
&& self.backtrack.nth_user_message != usize::MAX
|
||||
&& self.chat_widget.composer_is_empty() =>
|
||||
{
|
||||
if let Some(selection) = self.confirm_backtrack_from_main() {
|
||||
self.apply_backtrack_selection(selection);
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
}
|
||||
KeyEvent {
|
||||
kind: KeyEventKind::Press | KeyEventKind::Repeat,
|
||||
..
|
||||
} => {
|
||||
// Any non-Esc key press should cancel a primed backtrack.
|
||||
// This avoids stale "Esc-primed" state after the user starts typing
|
||||
// (even if they later backspace to empty).
|
||||
if key_event.code != KeyCode::Esc && self.backtrack.primed {
|
||||
if self.backtrack.overlay_preview_active {
|
||||
self.cancel_transcript_browsing(tui);
|
||||
} else {
|
||||
self.reset_backtrack_state();
|
||||
}
|
||||
}
|
||||
let action = self
|
||||
.chat_widget
|
||||
.handle_key_event_with_activation_key(key_event, activation_key);
|
||||
self.handle_clipboard_key_action(tui, action);
|
||||
}
|
||||
_ => {
|
||||
self.chat_widget
|
||||
.handle_key_event_with_activation_key(key_event, activation_key);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
pub(crate) async fn handle_shared_app_keymap_action(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
app_server: &mut AppServerSession,
|
||||
key_event: KeyEvent,
|
||||
) -> bool {
|
||||
if self.keymap.app.open_warnings.is_pressed(key_event) {
|
||||
self.verify_managed_daemon().await;
|
||||
self.chat_widget.open_warnings(&self.transcript_cells);
|
||||
return true;
|
||||
}
|
||||
let side_toggle_bindings = &self.keymap.app.toggle_side_conversation;
|
||||
if side_toggle_bindings.is_pressed(key_event)
|
||||
|| side_toggle_bindings.contains(&crate::key_hint::ctrl(KeyCode::Char('/')))
|
||||
&& crate::key_hint::ctrl(KeyCode::Char('7')).is_press(key_event)
|
||||
{
|
||||
if let Err(err) = self.toggle_side_conversation(tui, app_server).await {
|
||||
self.chat_widget
|
||||
.add_error_message(format!("Failed to switch side conversation: {err}"));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if self.keymap.app.toggle_vim_mode.is_pressed(key_event) {
|
||||
self.chat_widget.toggle_vim_mode_and_notify();
|
||||
return true;
|
||||
}
|
||||
|
||||
if self.keymap.app.toggle_fast_mode.is_pressed(key_event)
|
||||
&& self.chat_widget.can_toggle_fast_mode_from_keybinding()
|
||||
{
|
||||
self.chat_widget.toggle_fast_mode_from_ui();
|
||||
return true;
|
||||
}
|
||||
|
||||
if self.keymap.app.toggle_raw_output.is_pressed(key_event) {
|
||||
let enabled = !self.chat_widget.raw_output_mode();
|
||||
self.apply_raw_output_mode(tui, enabled, /*notify*/ false);
|
||||
return true;
|
||||
}
|
||||
|
||||
if self.keymap.app.open_agents.is_pressed(key_event) {
|
||||
self.open_agents_overview(app_server);
|
||||
return true;
|
||||
}
|
||||
|
||||
if self.keymap.app.open_external_editor.is_pressed(key_event) {
|
||||
if self.overlay.is_none()
|
||||
&& self.chat_widget.can_launch_external_editor()
|
||||
&& self.chat_widget.external_editor_state() == ExternalEditorState::Closed
|
||||
{
|
||||
self.request_external_editor_launch(tui);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
if self.keymap.app.clear_terminal.is_pressed(key_event) {
|
||||
// Leave cached history intact and let the unavailable-thread input path handle this key.
|
||||
if self.should_handle_unavailable_thread_key(key_event) {
|
||||
return false;
|
||||
}
|
||||
if !self.chat_widget.can_run_ctrl_l_clear_now() {
|
||||
return true;
|
||||
}
|
||||
if let Err(err) = self.clear_terminal_ui(tui, /*redraw_header*/ false) {
|
||||
tracing::warn!(error = %err, "failed to clear terminal UI");
|
||||
self.chat_widget
|
||||
.add_error_message(format!("Failed to clear terminal UI: {err}"));
|
||||
} else {
|
||||
self.start_cleared_display(tui);
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
false
|
||||
}
|
||||
|
||||
fn should_handle_unavailable_thread_key(&self, key_event: KeyEvent) -> bool {
|
||||
!self.chat_widget.has_active_view()
|
||||
&& self
|
||||
.current_displayed_thread_id()
|
||||
.is_some_and(|id| self.thread_unavailable(id))
|
||||
&& !(key_event.modifiers.contains(KeyModifiers::CONTROL)
|
||||
&& matches!(key_event.code, KeyCode::Char('c' | 'd')))
|
||||
}
|
||||
|
||||
pub(crate) fn should_handle_backtrack_esc(&self, key_event: KeyEvent) -> bool {
|
||||
!self.chat_widget.is_external_writer_view()
|
||||
&& !self.chat_widget.has_provider_error()
|
||||
&& !self.chat_widget.side_conversation_active()
|
||||
&& !self.chat_widget.shortcut_overlay_visible()
|
||||
&& self.chat_widget.is_normal_backtrack_mode()
|
||||
&& self.chat_widget.composer_is_empty()
|
||||
&& !self.chat_widget.should_handle_vim_insert_escape(key_event)
|
||||
}
|
||||
|
||||
pub(super) fn should_reject_side_backtrack_esc(&self, key_event: KeyEvent) -> bool {
|
||||
self.chat_widget.side_conversation_active()
|
||||
&& !self.chat_widget.shortcut_overlay_visible()
|
||||
&& self.chat_widget.is_normal_backtrack_mode()
|
||||
&& self.chat_widget.composer_is_empty()
|
||||
&& !self.chat_widget.should_handle_vim_insert_escape(key_event)
|
||||
}
|
||||
|
||||
pub(super) fn reject_side_backtrack_esc(&mut self) {
|
||||
self.reset_backtrack_state();
|
||||
self.chat_widget
|
||||
.add_error_message(SIDE_EDIT_PREVIOUS_UNAVAILABLE_MESSAGE.to_string());
|
||||
}
|
||||
|
||||
fn app_keymap_shortcuts_available(&self) -> bool {
|
||||
self.overlay.is_none() && self.chat_widget.no_modal_or_popup_active()
|
||||
}
|
||||
|
||||
pub(super) fn refresh_status_line(&mut self) {
|
||||
self.chat_widget.refresh_status_line();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "input_ownership_tests.rs"]
|
||||
mod ownership_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::super::test_support::make_test_app;
|
||||
|
||||
#[tokio::test]
|
||||
async fn app_keymap_shortcuts_are_disabled_while_keymap_view_is_active() {
|
||||
let mut app = make_test_app().await;
|
||||
assert!(app.app_keymap_shortcuts_available());
|
||||
|
||||
let keymap = app.keymap.clone();
|
||||
app.chat_widget.open_keymap_debug(&keymap);
|
||||
|
||||
assert!(!app.app_keymap_shortcuts_available());
|
||||
}
|
||||
}
|
||||
146
akode-rs/tui/src/app/input/select_mode.rs
Normal file
146
akode-rs/tui/src/app/input/select_mode.rs
Normal file
@@ -0,0 +1,146 @@
|
||||
//! Transcript selection chord routing kept outside the central application input path.
|
||||
|
||||
use super::super::*;
|
||||
|
||||
impl App {
|
||||
pub(crate) fn transcript_select_exit_key(event: &TuiEvent) -> Option<KeyBinding> {
|
||||
let TuiEvent::Key(key) = event else {
|
||||
return None;
|
||||
};
|
||||
let (code, modifiers) = crate::key_hint::normalize_key_parts(key.code, key.modifiers);
|
||||
(key.kind == KeyEventKind::Press
|
||||
&& modifiers == KeyModifiers::NONE
|
||||
&& matches!(code, KeyCode::Esc | KeyCode::Enter | KeyCode::Char('q')))
|
||||
.then(|| KeyBinding::from_event(*key))
|
||||
}
|
||||
|
||||
pub(super) fn select_mode_owns_chord(&self, tui: &tui::Tui, key_event: KeyEvent) -> bool {
|
||||
let select_mode = matches!(
|
||||
&self.overlay,
|
||||
Some(Overlay::Transcript(overlay)) if overlay.is_select_mode()
|
||||
) || (tui.is_owned_screen()
|
||||
&& self.overlay.is_none()
|
||||
&& self.transcript_view.is_select_mode());
|
||||
if !select_mode {
|
||||
return false;
|
||||
}
|
||||
let contexts = self.key_chord_contexts(tui);
|
||||
let search_editing = matches!(
|
||||
&self.overlay,
|
||||
Some(Overlay::Transcript(overlay)) if overlay.is_search_editing()
|
||||
) || (self.overlay.is_none()
|
||||
&& self.transcript_view.is_search_editing());
|
||||
let (code, modifiers) =
|
||||
crate::key_hint::normalize_key_parts(key_event.code, key_event.modifiers);
|
||||
let fixed_search_control = search_editing
|
||||
&& (code == KeyCode::Esc
|
||||
|| (modifiers == KeyModifiers::NONE
|
||||
&& matches!(code, KeyCode::Enter | KeyCode::PageUp | KeyCode::PageDown))
|
||||
|| (modifiers == KeyModifiers::CONTROL
|
||||
&& matches!(code, KeyCode::Char('c' | 'n' | 'p'))));
|
||||
let fixed_select_control = !search_editing
|
||||
&& key_event.kind != KeyEventKind::Release
|
||||
&& (crate::text_selection::is_copy_key(key_event)
|
||||
|| matches!(
|
||||
(code, modifiers),
|
||||
(
|
||||
KeyCode::Enter | KeyCode::Esc | KeyCode::Char('q' | '/' | 'o' | 'y'),
|
||||
KeyModifiers::NONE
|
||||
) | (
|
||||
KeyCode::Char(' '),
|
||||
KeyModifiers::NONE | KeyModifiers::CONTROL
|
||||
) | (
|
||||
KeyCode::Char('v' | 'n' | 'g' | '$'),
|
||||
KeyModifiers::NONE | KeyModifiers::SHIFT
|
||||
) | (
|
||||
KeyCode::Left | KeyCode::Right | KeyCode::Up | KeyCode::Down,
|
||||
KeyModifiers::NONE | KeyModifiers::SHIFT
|
||||
) | (
|
||||
KeyCode::Char('h' | 'l' | 'k' | 'j' | 'w' | 'b' | 'e' | '0'),
|
||||
KeyModifiers::NONE
|
||||
) | (
|
||||
KeyCode::Home | KeyCode::End,
|
||||
KeyModifiers::NONE | KeyModifiers::CONTROL
|
||||
) | (KeyCode::PageUp | KeyCode::PageDown, KeyModifiers::NONE)
|
||||
| (KeyCode::Char('b' | 'f' | 'u' | 'd'), KeyModifiers::CONTROL)
|
||||
));
|
||||
let pager_motion = !search_editing
|
||||
&& [
|
||||
&self.keymap.pager.scroll_up,
|
||||
&self.keymap.pager.scroll_down,
|
||||
&self.keymap.pager.page_up,
|
||||
&self.keymap.pager.page_down,
|
||||
&self.keymap.pager.half_page_up,
|
||||
&self.keymap.pager.half_page_down,
|
||||
&self.keymap.pager.jump_top,
|
||||
&self.keymap.pager.jump_bottom,
|
||||
]
|
||||
.into_iter()
|
||||
.any(|bindings| bindings.is_pressed(key_event));
|
||||
let active_action = |action: crate::keymap::KeymapActionId| {
|
||||
contexts.contains_action(action)
|
||||
&& if search_editing {
|
||||
action.context == crate::keymap::KeymapContext::Editor
|
||||
|| matches!(
|
||||
(action.context, action.action),
|
||||
(crate::keymap::KeymapContext::Chat, "toggle_voice")
|
||||
)
|
||||
} else {
|
||||
matches!(
|
||||
(action.context, action.action),
|
||||
(crate::keymap::KeymapContext::Global, "find_transcript")
|
||||
| (crate::keymap::KeymapContext::Chat, "toggle_voice")
|
||||
| (
|
||||
crate::keymap::KeymapContext::Pager,
|
||||
"find"
|
||||
| "scroll_up"
|
||||
| "scroll_down"
|
||||
| "page_up"
|
||||
| "page_down"
|
||||
| "half_page_up"
|
||||
| "half_page_down"
|
||||
| "jump_top"
|
||||
| "jump_bottom"
|
||||
)
|
||||
) || (self.overlay.is_some()
|
||||
&& action.context == crate::keymap::KeymapContext::Pager
|
||||
&& matches!(action.action, "close" | "close_transcript"))
|
||||
}
|
||||
};
|
||||
let completed_action = |dispatch| {
|
||||
self.keymap.chords.bindings.iter().any(|binding| {
|
||||
active_action(binding.action)
|
||||
&& crate::keymap::dispatch_event(binding.action) == Some(dispatch)
|
||||
})
|
||||
};
|
||||
if fixed_search_control || fixed_select_control || pager_motion {
|
||||
false
|
||||
} else if self.key_chord_matcher.is_pending() {
|
||||
match self
|
||||
.key_chord_matcher
|
||||
.clone()
|
||||
.advance(key_event, &self.keymap.chords, contexts)
|
||||
{
|
||||
crate::keymap::KeyChordMatch::Completed(dispatch) => completed_action(dispatch),
|
||||
crate::keymap::KeyChordMatch::Pending(prefix) => {
|
||||
let (code, modifiers) = prefix.parts();
|
||||
self.keymap.chords.bindings.iter().any(|binding| {
|
||||
active_action(binding.action)
|
||||
&& crate::keymap::chord_stroke_matches(
|
||||
binding.chord.prefix,
|
||||
KeyEvent::new(code, modifiers),
|
||||
)
|
||||
})
|
||||
}
|
||||
crate::keymap::KeyChordMatch::Ignored => true,
|
||||
crate::keymap::KeyChordMatch::PassThrough
|
||||
| crate::keymap::KeyChordMatch::Cancelled => false,
|
||||
}
|
||||
} else {
|
||||
self.keymap.chords.bindings.iter().any(|binding| {
|
||||
active_action(binding.action)
|
||||
&& crate::keymap::chord_stroke_matches(binding.chord.prefix, key_event)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
83
akode-rs/tui/src/app/input_ownership_tests.rs
Normal file
83
akode-rs/tui/src/app/input_ownership_tests.rs
Normal file
@@ -0,0 +1,83 @@
|
||||
//! Find and transcript selection retain control keys ahead of configurable chord prefixes.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn selection_copy_cancels_a_pending_find_editor_chord() -> Result<()> {
|
||||
let mut app = crate::app::test_support::make_test_app().await;
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
tui.set_owned_screen(/*owned*/ true)?;
|
||||
app.keymap = RuntimeKeymap::from_config(&serde_json::from_value(serde_json::json!({
|
||||
"editor": {"move_line_start": ["ctrl-p h", "ctrl-x h"], "move_up": []}
|
||||
}))?)
|
||||
.expect("valid editor keymap");
|
||||
app.transcript_cells = vec![Arc::new(history_cell::PlainHistoryCell::new(vec![
|
||||
"needle text".into(),
|
||||
]))];
|
||||
app.transcript_view.begin_search();
|
||||
app.transcript_view.paste_search("needle");
|
||||
for key in [
|
||||
KeyEvent::new(KeyCode::Char('p'), KeyModifiers::CONTROL),
|
||||
KeyCode::Enter.into(),
|
||||
KeyCode::Esc.into(),
|
||||
] {
|
||||
assert_eq!(app.route_key_chord_event(&mut tui, key), Some(key));
|
||||
assert!(!app.key_chord_matcher.is_pending());
|
||||
}
|
||||
app.render_owned_transcript(&mut tui, Size::new(/*width*/ 80, /*height*/ 24))?;
|
||||
assert_eq!(
|
||||
app.route_key_chord_event(
|
||||
&mut tui,
|
||||
KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL)
|
||||
),
|
||||
None
|
||||
);
|
||||
assert!(app.key_chord_matcher.is_pending());
|
||||
app.transcript_view.handle_key(
|
||||
KeyEvent::new(KeyCode::Char(' '), KeyModifiers::CONTROL),
|
||||
&app.transcript_cells,
|
||||
);
|
||||
for _ in "needle text".chars() {
|
||||
app.transcript_view
|
||||
.handle_key(KeyCode::Right.into(), &app.transcript_cells);
|
||||
}
|
||||
let copy = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL);
|
||||
assert_eq!(app.route_key_chord_event(&mut tui, copy), Some(copy));
|
||||
assert!(!app.key_chord_matcher.is_pending());
|
||||
assert_eq!(
|
||||
app.transcript_view
|
||||
.selected_text(&app.transcript_cells)
|
||||
.as_deref(),
|
||||
Some("needle text")
|
||||
);
|
||||
tui.set_owned_screen(/*owned*/ false)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn keypress_inspector_distinguishes_ctrl_alt_c_from_ctrl_c() -> Result<()> {
|
||||
let mut app = crate::app::test_support::make_test_app().await;
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
for (modifier, expected, cancel) in [
|
||||
(KeyModifiers::ALT, "ctrl-alt-c", 'c'),
|
||||
(KeyModifiers::SHIFT, "ctrl-shift-c", 'C'),
|
||||
] {
|
||||
app.chat_widget.open_keymap_debug(&app.keymap);
|
||||
let inspect = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL | modifier);
|
||||
let inspect = app
|
||||
.route_key_chord_event(&mut tui, inspect)
|
||||
.expect("physical inspector key");
|
||||
app.chat_widget.handle_key_event(inspect);
|
||||
let screen =
|
||||
crate::chatwidget::tests::render_bottom_popup(&app.chat_widget, /*width*/ 80);
|
||||
assert!(
|
||||
screen.contains(&format!("Config key: {expected}")),
|
||||
"{screen}"
|
||||
);
|
||||
app.chat_widget
|
||||
.handle_key_event(KeyEvent::new(KeyCode::Char(cancel), KeyModifiers::CONTROL));
|
||||
assert!(!app.chat_widget.has_active_view());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
164
akode-rs/tui/src/app/link_hover.rs
Normal file
164
akode-rs/tui/src/app/link_hover.rs
Normal file
@@ -0,0 +1,164 @@
|
||||
//! Match hover feedback to transcript links and the pane divider. Keep passive link drags with their original view.
|
||||
//! Recheck after painting so scrolling and live output cannot leave a hand over stale content.
|
||||
|
||||
use akode_protocol::ThreadId;
|
||||
use crossterm::event::KeyModifiers;
|
||||
use crossterm::event::MouseButton::Left;
|
||||
use crossterm::event::MouseEvent;
|
||||
use crossterm::event::MouseEventKind::Drag;
|
||||
use crossterm::event::MouseEventKind::Moved;
|
||||
use crossterm::event::MouseEventKind::ScrollDown;
|
||||
use crossterm::event::MouseEventKind::ScrollUp;
|
||||
use crossterm::event::MouseEventKind::Up;
|
||||
|
||||
use super::App;
|
||||
use crate::transcript_view::ViewAction;
|
||||
use crate::tui::PointerShape;
|
||||
use crate::tui::Tui;
|
||||
use crate::tui::TuiEvent;
|
||||
|
||||
impl App {
|
||||
pub(super) fn transcript_link_at(&self, mouse: MouseEvent) -> Option<String> {
|
||||
if !mouse.modifiers.is_empty()
|
||||
&& !mouse
|
||||
.modifiers
|
||||
.intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER)
|
||||
{
|
||||
return None;
|
||||
}
|
||||
let view = if let Some(panes) = self.conversation_frame.side_pane()
|
||||
&& panes.passive.contains((mouse.column, mouse.row).into())
|
||||
{
|
||||
let passive = &self.side_companions.get(&panes.passive_thread)?.view;
|
||||
if passive.is_select_mode() {
|
||||
return None;
|
||||
}
|
||||
passive
|
||||
} else {
|
||||
&self.transcript_view
|
||||
};
|
||||
view.link_at(mouse.column, mouse.row)
|
||||
}
|
||||
|
||||
pub(super) fn handle_passive_transcript_event(
|
||||
&mut self,
|
||||
tui: &mut Tui,
|
||||
id: ThreadId,
|
||||
event: &TuiEvent,
|
||||
) -> bool {
|
||||
let Some(companion) = self.side_companions.get_mut(&id) else {
|
||||
return false;
|
||||
};
|
||||
let view = &mut companion.view;
|
||||
view.mouse_scroll_speed = self.transcript_view.mouse_scroll_speed;
|
||||
view.copy_on_select = self.transcript_view.copy_on_select;
|
||||
view.copy_on_select_clear_selection = self.transcript_view.copy_on_select_clear_selection;
|
||||
view.primary_selection = self.transcript_view.primary_selection;
|
||||
let action = match event {
|
||||
TuiEvent::Mouse(mouse) => view.handle_mouse(*mouse, &companion.cells),
|
||||
TuiEvent::Key(key) if crate::text_selection::is_copy_key(*key) => view
|
||||
.handle_selection_key(*key, &companion.cells)
|
||||
.filter(|action| matches!(action, ViewAction::Copy(_))),
|
||||
_ => None,
|
||||
};
|
||||
let Some(action) = action else {
|
||||
return false;
|
||||
};
|
||||
if let Some((count, result)) = view.copy_action(
|
||||
tui,
|
||||
&companion.cells,
|
||||
&action,
|
||||
crate::clipboard_copy::CopyFormat::Markdown,
|
||||
) {
|
||||
self.transcript_view.show_copy_feedback(&result, count);
|
||||
} else if let ViewAction::OpenLink(url) = action {
|
||||
self.open_url_in_browser(url);
|
||||
}
|
||||
tui.frame_requester().schedule_frame();
|
||||
true
|
||||
}
|
||||
|
||||
pub(super) fn continue_passive_link_drag(
|
||||
&mut self,
|
||||
tui: &mut Tui,
|
||||
event: &TuiEvent,
|
||||
) -> color_eyre::eyre::Result<bool> {
|
||||
let Some((id, area)) = self.passive_link_drag else {
|
||||
return Ok(false);
|
||||
};
|
||||
if self.conversation_focus_available(tui) {
|
||||
match event {
|
||||
TuiEvent::Draw => {
|
||||
if let Some(companion) = self.side_companions.get_mut(&id)
|
||||
&& companion.view.tick_selection(&companion.cells)
|
||||
{
|
||||
tui.frame_requester()
|
||||
.schedule_frame_in(crate::tui::TARGET_FRAME_INTERVAL);
|
||||
}
|
||||
return Ok(false);
|
||||
}
|
||||
TuiEvent::Mouse(mouse) if mouse.kind == Moved => return Ok(false),
|
||||
TuiEvent::Mouse(mouse)
|
||||
if matches!(mouse.kind, Drag(Left) | Up(Left) | ScrollUp | ScrollDown) =>
|
||||
{
|
||||
self.refresh_owned_transcript(tui)?;
|
||||
if self
|
||||
.conversation_frame
|
||||
.side_pane()
|
||||
.is_some_and(|panes| panes.passive_thread == id && panes.passive == area)
|
||||
{
|
||||
self.handle_passive_transcript_event(tui, id, event);
|
||||
if mouse.kind == Up(Left) {
|
||||
self.passive_link_drag = None;
|
||||
}
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
self.passive_link_drag = None;
|
||||
if let Some(companion) = self.side_companions.get_mut(&id) {
|
||||
companion.view.end_drag();
|
||||
} else if self.current_displayed_thread_id() == Some(id) {
|
||||
self.transcript_view.end_drag();
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
pub(super) fn refresh_link_hover(&self, tui: &mut Tui) -> std::io::Result<()> {
|
||||
let shape = if tui
|
||||
.link_hover
|
||||
.mouse
|
||||
.is_some_and(|mouse| self.conversation_frame.hud_contains(mouse))
|
||||
|| !tui.is_owned_screen()
|
||||
|| self.overlay.is_some()
|
||||
{
|
||||
PointerShape::Default
|
||||
} else if self.conversation_focus_available(tui)
|
||||
&& (self.divider_drag.is_some()
|
||||
|| tui.link_hover.mouse.is_some_and(|mouse| {
|
||||
self.conversation_frame
|
||||
.divider_area()
|
||||
.is_some_and(|area| area.contains((mouse.column, mouse.row).into()))
|
||||
&& self.divider_is_settled(tui, tui.terminal.last_known_screen_size.into())
|
||||
}))
|
||||
{
|
||||
PointerShape::Resize
|
||||
} else if self.chat_widget.no_modal_or_popup_active()
|
||||
&& tui
|
||||
.link_hover
|
||||
.mouse
|
||||
.is_some_and(|mouse| self.transcript_link_at(mouse).is_some())
|
||||
{
|
||||
PointerShape::Link
|
||||
} else {
|
||||
PointerShape::Default
|
||||
};
|
||||
if (shape == PointerShape::Resize) != (tui.link_hover.shape == PointerShape::Resize) {
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
tui.link_hover.shape = shape;
|
||||
tui.set_pointer_shape(shape)
|
||||
}
|
||||
}
|
||||
262
akode-rs/tui/src/app/loaded_threads.rs
Normal file
262
akode-rs/tui/src/app/loaded_threads.rs
Normal file
@@ -0,0 +1,262 @@
|
||||
//! Discovers subagent threads that belong to a primary thread by walking spawn-tree edges.
|
||||
//!
|
||||
//! When the TUI resumes or switches to an existing thread, it needs to populate
|
||||
//! `AgentNavigationState` and `ChatWidget` metadata for every subagent that was spawned during
|
||||
//! that thread's lifetime. The app server exposes a flat list of currently loaded threads via
|
||||
//! `thread/loaded/list`, but the TUI must figure out which of those are descendants of the
|
||||
//! primary thread.
|
||||
//!
|
||||
//! This module provides the pure, synchronous tree-walk that turns that flat list into the filtered
|
||||
//! set of descendants. It intentionally has no async, no I/O, and no side effects so it can be
|
||||
//! unit-tested in isolation.
|
||||
//!
|
||||
//! The walk starts from `primary_thread_id` and repeatedly follows
|
||||
//! `SessionSource::SubAgent(ThreadSpawn { parent_thread_id, .. })` edges until no new children are
|
||||
//! found. The primary thread itself is never included in the output.
|
||||
|
||||
use crate::app_server_session::thread_blocks_direct_input;
|
||||
use akode_app_server_protocol::SessionSource;
|
||||
use akode_app_server_protocol::Thread;
|
||||
use akode_app_server_protocol::ThreadStatus;
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_protocol::protocol::SubAgentSource;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
|
||||
/// A subagent thread discovered by the spawn-tree walk, carrying just enough metadata for the
|
||||
/// TUI to register it in the navigation cache and rendering metadata map.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(crate) struct LoadedSubagentThread {
|
||||
pub(crate) thread_id: ThreadId,
|
||||
pub(crate) agent_nickname: Option<String>,
|
||||
pub(crate) agent_role: Option<String>,
|
||||
pub(crate) agent_path: Option<String>,
|
||||
pub(crate) blocks_direct_input: bool,
|
||||
pub(crate) is_running: bool,
|
||||
pub(crate) is_closed: bool,
|
||||
}
|
||||
|
||||
/// Walks the spawn tree rooted at `primary_thread_id` and returns every descendant subagent.
|
||||
///
|
||||
/// The walk is breadth-first over `SessionSource::SubAgent(ThreadSpawn { parent_thread_id })` edges.
|
||||
/// Threads whose `source` is not a `ThreadSpawn`, or whose `parent_thread_id` does not chain back
|
||||
/// to `primary_thread_id`, are excluded. The primary thread itself is never included.
|
||||
///
|
||||
/// Results are sorted by stringified thread id for deterministic output in tests and in the
|
||||
/// navigation cache. Callers should not rely on this ordering for anything semantic; it exists
|
||||
/// purely to make snapshot assertions stable.
|
||||
///
|
||||
/// If two threads claim the same parent, both are included. Cycles in the parent chain are not
|
||||
/// possible because `ThreadId`s are server-assigned UUIDs and the server enforces acyclicity, but
|
||||
/// the `included` set guards against re-visiting regardless.
|
||||
pub(crate) fn find_loaded_subagent_threads_for_primary(
|
||||
threads: Vec<Thread>,
|
||||
primary_thread_id: ThreadId,
|
||||
) -> Vec<LoadedSubagentThread> {
|
||||
let mut threads_by_id = HashMap::new();
|
||||
for thread in threads {
|
||||
let Ok(thread_id) = ThreadId::from_string(&thread.id) else {
|
||||
continue;
|
||||
};
|
||||
threads_by_id.insert(thread_id, thread);
|
||||
}
|
||||
|
||||
let mut included = HashSet::new();
|
||||
let mut pending = vec![primary_thread_id];
|
||||
while let Some(parent_thread_id) = pending.pop() {
|
||||
for (thread_id, thread) in &threads_by_id {
|
||||
if included.contains(thread_id) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let Some(source_parent_thread_id) = thread_spawn_parent_thread_id(&thread.source)
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
|
||||
if source_parent_thread_id != parent_thread_id {
|
||||
continue;
|
||||
}
|
||||
|
||||
included.insert(*thread_id);
|
||||
pending.push(*thread_id);
|
||||
}
|
||||
}
|
||||
|
||||
let mut loaded_threads: Vec<LoadedSubagentThread> = included
|
||||
.into_iter()
|
||||
.filter_map(|thread_id| {
|
||||
threads_by_id
|
||||
.remove(&thread_id)
|
||||
.map(|thread| LoadedSubagentThread {
|
||||
blocks_direct_input: thread_blocks_direct_input(&thread),
|
||||
is_running: matches!(&thread.status, ThreadStatus::Active { .. }),
|
||||
is_closed: matches!(&thread.status, ThreadStatus::NotLoaded),
|
||||
thread_id,
|
||||
agent_nickname: thread.agent_nickname,
|
||||
agent_role: thread.agent_role,
|
||||
agent_path: thread_spawn_agent_path(&thread.source),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
loaded_threads.sort_by_key(|thread| thread.thread_id.to_string());
|
||||
loaded_threads
|
||||
}
|
||||
|
||||
fn thread_spawn_agent_path(source: &SessionSource) -> Option<String> {
|
||||
match source {
|
||||
SessionSource::SubAgent(SubAgentSource::ThreadSpawn { agent_path, .. }) => {
|
||||
agent_path.clone().map(String::from)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn thread_spawn_parent_thread_id(source: &SessionSource) -> Option<ThreadId> {
|
||||
match source {
|
||||
SessionSource::SubAgent(SubAgentSource::ThreadSpawn {
|
||||
parent_thread_id, ..
|
||||
}) => Some(*parent_thread_id),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::LoadedSubagentThread;
|
||||
use super::find_loaded_subagent_threads_for_primary;
|
||||
use akode_app_server_protocol::SessionSource;
|
||||
use akode_app_server_protocol::Thread;
|
||||
use akode_app_server_protocol::ThreadStatus;
|
||||
use akode_protocol::ThreadId;
|
||||
use akode_utils_absolute_path::test_support::PathBufExt;
|
||||
use akode_utils_absolute_path::test_support::test_path_buf;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn test_thread(thread_id: ThreadId, source: SessionSource) -> Thread {
|
||||
Thread {
|
||||
originator: None,
|
||||
environments: None,
|
||||
id: thread_id.to_string(),
|
||||
extra: None,
|
||||
session_id: thread_id.to_string(),
|
||||
forked_from_id: None,
|
||||
parent_thread_id: None,
|
||||
preview: String::new(),
|
||||
ephemeral: false,
|
||||
section: None,
|
||||
section_entered_at: None,
|
||||
project_id: None,
|
||||
history_mode: Default::default(),
|
||||
model_provider: "openai".to_string(),
|
||||
model: None,
|
||||
reasoning_effort: None,
|
||||
created_at: 0,
|
||||
updated_at: 0,
|
||||
recency_at: Some(0),
|
||||
status: ThreadStatus::Idle,
|
||||
path: None,
|
||||
cwd: test_path_buf("/tmp").abs(),
|
||||
cli_version: "0.0.0".to_string(),
|
||||
source,
|
||||
can_accept_direct_input: None,
|
||||
thread_source: None,
|
||||
agent_nickname: None,
|
||||
agent_role: None,
|
||||
git_info: None,
|
||||
name: None,
|
||||
turns: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn thread_spawn_source(
|
||||
parent_thread_id: ThreadId,
|
||||
depth: i32,
|
||||
agent_nickname: &str,
|
||||
agent_role: &str,
|
||||
) -> SessionSource {
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"subAgent": {
|
||||
"thread_spawn": {
|
||||
"parent_thread_id": parent_thread_id.to_string(),
|
||||
"depth": depth,
|
||||
"agent_nickname": agent_nickname,
|
||||
"agent_role": agent_role,
|
||||
}
|
||||
}
|
||||
}))
|
||||
.expect("valid subagent source")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn finds_loaded_subagent_tree_for_primary_thread() {
|
||||
let primary_thread_id =
|
||||
ThreadId::from_string("00000000-0000-0000-0000-000000000001").expect("valid thread");
|
||||
let child_thread_id =
|
||||
ThreadId::from_string("00000000-0000-0000-0000-000000000002").expect("valid thread");
|
||||
let grandchild_thread_id =
|
||||
ThreadId::from_string("00000000-0000-0000-0000-000000000003").expect("valid thread");
|
||||
let unrelated_parent_id =
|
||||
ThreadId::from_string("00000000-0000-0000-0000-000000000004").expect("valid thread");
|
||||
let unrelated_child_id =
|
||||
ThreadId::from_string("00000000-0000-0000-0000-000000000005").expect("valid thread");
|
||||
|
||||
let mut child = test_thread(
|
||||
child_thread_id,
|
||||
thread_spawn_source(primary_thread_id, /*depth*/ 1, "Scout", "explorer"),
|
||||
);
|
||||
child.agent_nickname = Some("Scout".to_string());
|
||||
child.agent_role = Some("explorer".to_string());
|
||||
child.can_accept_direct_input = Some(true);
|
||||
child.status = ThreadStatus::Active {
|
||||
active_flags: Vec::new(),
|
||||
};
|
||||
|
||||
let mut grandchild = test_thread(
|
||||
grandchild_thread_id,
|
||||
thread_spawn_source(child_thread_id, /*depth*/ 2, "Atlas", "worker"),
|
||||
);
|
||||
grandchild.agent_nickname = Some("Atlas".to_string());
|
||||
grandchild.agent_role = Some("worker".to_string());
|
||||
grandchild.can_accept_direct_input = Some(false);
|
||||
grandchild.status = ThreadStatus::NotLoaded;
|
||||
let unrelated_child = test_thread(
|
||||
unrelated_child_id,
|
||||
thread_spawn_source(unrelated_parent_id, /*depth*/ 1, "Other", "researcher"),
|
||||
);
|
||||
|
||||
let loaded = find_loaded_subagent_threads_for_primary(
|
||||
vec![
|
||||
test_thread(primary_thread_id, SessionSource::Cli),
|
||||
child,
|
||||
grandchild,
|
||||
unrelated_child,
|
||||
],
|
||||
primary_thread_id,
|
||||
);
|
||||
|
||||
assert_eq!(
|
||||
loaded,
|
||||
vec![
|
||||
LoadedSubagentThread {
|
||||
blocks_direct_input: false,
|
||||
thread_id: child_thread_id,
|
||||
agent_nickname: Some("Scout".to_string()),
|
||||
agent_role: Some("explorer".to_string()),
|
||||
agent_path: None,
|
||||
is_running: true,
|
||||
is_closed: false,
|
||||
},
|
||||
LoadedSubagentThread {
|
||||
blocks_direct_input: true,
|
||||
thread_id: grandchild_thread_id,
|
||||
agent_nickname: Some("Atlas".to_string()),
|
||||
agent_role: Some("worker".to_string()),
|
||||
agent_path: None,
|
||||
is_running: false,
|
||||
is_closed: true,
|
||||
},
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
295
akode-rs/tui/src/app/managed_worktree_creation.rs
Normal file
295
akode-rs/tui/src/app/managed_worktree_creation.rs
Normal file
@@ -0,0 +1,295 @@
|
||||
//! Managed checkout creation and handoff from blocking Git work to the TUI event loop.
|
||||
//!
|
||||
//! Source-only blockers are checked before allocation. The completion event rechecks the
|
||||
//! original session and reports a recovery path for every retained checkout.
|
||||
|
||||
use super::*;
|
||||
use crate::app_event::ManagedWorktreeCreated;
|
||||
use crate::app_event::ManagedWorktreeTransition;
|
||||
use crate::history_cell::McpInventoryLoadingCell as LoadingCell;
|
||||
use akode_app_server_protocol::ThreadBackgroundTerminalsListParams;
|
||||
use akode_app_server_protocol::ThreadBackgroundTerminalsListResponse as ListResponse;
|
||||
|
||||
pub(super) fn background_terminals_blocker(
|
||||
result: Result<ListResponse, TypedRequestError>,
|
||||
target: &AppServerTarget,
|
||||
) -> Option<&'static str> {
|
||||
match result {
|
||||
Ok(response) if response.data.is_empty() => None,
|
||||
Err(TypedRequestError::Server { source, .. })
|
||||
if matches!(target, AppServerTarget::LocalDaemon { .. })
|
||||
&& (source.code == -32601
|
||||
|| source.code == -32600
|
||||
&& source.message.contains("thread/backgroundTerminals/list")
|
||||
&& (source.message.contains("unknown variant")
|
||||
|| source.message.contains("unknown method"))) =>
|
||||
{
|
||||
Some(
|
||||
"The local aKode service cannot check background terminals. Run `akode app-server daemon update`, then restart aKode.",
|
||||
)
|
||||
}
|
||||
_ => Some("Active background terminals block /cd."),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn check_background_terminals(
|
||||
app_server: &mut AppServerSession,
|
||||
target: &AppServerTarget,
|
||||
thread_ids: impl IntoIterator<Item = ThreadId>,
|
||||
) -> Option<&'static str> {
|
||||
for thread_id in thread_ids {
|
||||
let request = ClientRequest::ThreadBackgroundTerminalsList {
|
||||
request_id: app_server.next_request_id(),
|
||||
params: ThreadBackgroundTerminalsListParams {
|
||||
thread_id: thread_id.to_string(),
|
||||
cursor: None,
|
||||
limit: Some(1),
|
||||
},
|
||||
};
|
||||
let result = app_server
|
||||
.request_handle()
|
||||
.request_typed::<ListResponse>(request)
|
||||
.await;
|
||||
if let Some(message) = background_terminals_blocker(result, target) {
|
||||
return Some(message);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub(super) async fn start_managed_worktree(
|
||||
&mut self,
|
||||
app_server: &mut AppServerSession,
|
||||
mode: crate::app_event::ManagedWorktreeMode,
|
||||
name: Option<String>,
|
||||
) {
|
||||
if self.config.active_project.is_untrusted() {
|
||||
self.chat_widget.add_error_message(
|
||||
"Cannot create a worktree from an explicitly untrusted source.".to_string(),
|
||||
);
|
||||
} else if crate::uses_remote_workspace_or_environment(
|
||||
&self.app_server_target,
|
||||
self.environment_manager.as_ref(),
|
||||
) {
|
||||
self.chat_widget.add_error_message(
|
||||
"Managed worktrees are only supported for local sessions.".to_string(),
|
||||
);
|
||||
} else if self
|
||||
.primary_thread_id
|
||||
.is_none_or(|thread_id| !self.chat_widget.can_change_working_directory(thread_id))
|
||||
{
|
||||
self.chat_widget.add_error_message(
|
||||
"Creating a worktree requires an idle primary session without queued input."
|
||||
.to_string(),
|
||||
);
|
||||
} else if self.pending_managed_worktree_creation {
|
||||
self.chat_widget
|
||||
.add_error_message("A worktree is already being created.".to_string());
|
||||
} else {
|
||||
// These source-only checks must precede allocation. The transition repeats them
|
||||
// after the background task, since the session can change while Git is running.
|
||||
if self
|
||||
.transcript_cells
|
||||
.iter()
|
||||
.any(|cell| cell.as_any().is::<LoadingCell>())
|
||||
{
|
||||
return self.working_directory_error("MCP inventory is still loading.");
|
||||
}
|
||||
let Some(thread_id) = self.primary_thread_id else {
|
||||
return self.working_directory_error(
|
||||
"Creating a worktree requires an idle primary session without queued input.",
|
||||
);
|
||||
};
|
||||
let agents = self.agent_navigation.ordered_threads();
|
||||
let closed_agents: HashSet<_> = agents
|
||||
.iter()
|
||||
.filter_map(|(id, agent)| agent.is_closed.then_some(*id))
|
||||
.collect();
|
||||
let active = self.thread_event_channels.iter().any(|(id, channel)| {
|
||||
*id != thread_id
|
||||
&& !closed_agents.contains(id)
|
||||
&& !channel
|
||||
.store
|
||||
.try_lock()
|
||||
.is_ok_and(|store| store.active_turn_id().is_none())
|
||||
});
|
||||
if active
|
||||
|| agents
|
||||
.iter()
|
||||
.any(|(id, agent)| *id != thread_id && agent.is_running)
|
||||
{
|
||||
return self.working_directory_error("Cannot change: another agent is running.");
|
||||
}
|
||||
let rollout = self.chat_widget.rollout_path();
|
||||
let has_rollout = rollout.as_deref().is_some_and(rollout_path_is_resumable);
|
||||
if mode == crate::app_event::ManagedWorktreeMode::Fork
|
||||
&& !has_rollout
|
||||
&& (!self.chat_widget.token_usage().is_zero()
|
||||
|| self
|
||||
.thread_event_channels
|
||||
.get(&thread_id)
|
||||
.is_some_and(|channel| {
|
||||
channel.store.try_lock().map_or(/*default*/ true, |store| {
|
||||
!store.turns.is_empty() || store.buffer.iter().any(|event| {
|
||||
matches!(event, ThreadBufferedEvent::Notification(notification)
|
||||
if matches!(notification.as_ref(),
|
||||
ServerNotification::TurnStarted(_)
|
||||
| ServerNotification::TurnCompleted(_)))
|
||||
})
|
||||
})
|
||||
}))
|
||||
{
|
||||
return self.working_directory_error("Conversation history is not saved.");
|
||||
}
|
||||
let mut ids: HashSet<_> = self
|
||||
.thread_event_channels
|
||||
.keys()
|
||||
.copied()
|
||||
.filter(|id| !closed_agents.contains(id))
|
||||
.collect();
|
||||
ids.extend(
|
||||
agents
|
||||
.iter()
|
||||
.filter_map(|(id, agent)| (!agent.is_closed).then_some(*id)),
|
||||
);
|
||||
if let Some(message) =
|
||||
check_background_terminals(app_server, &self.app_server_target, ids).await
|
||||
{
|
||||
return self.working_directory_error(message);
|
||||
}
|
||||
let setup = async {
|
||||
let source = self
|
||||
.rebuild_config_for_cwd(self.config.cwd.to_path_buf())
|
||||
.await
|
||||
.map_err(|error| anyhow::anyhow!(error.to_string()))?;
|
||||
anyhow::ensure!(
|
||||
!source.active_project.is_untrusted(),
|
||||
"Cannot create a worktree from an explicitly untrusted source."
|
||||
);
|
||||
let host = crate::legacy_core::config::load_config_toml_with_layer_stack(
|
||||
&self.config.codex_home,
|
||||
/*cwd*/ None,
|
||||
Vec::new(),
|
||||
akode_config::ConfigLoadOptions::default(),
|
||||
)
|
||||
.await?;
|
||||
let settings = akode_worktree::WorktreeSettings::for_cli(
|
||||
&self.config.codex_home,
|
||||
host.config_toml.desktop.as_ref(),
|
||||
)?;
|
||||
let manager = akode_worktree::WorktreeManager::new(settings);
|
||||
anyhow::Ok(manager)
|
||||
}
|
||||
.await;
|
||||
match setup {
|
||||
Ok(manager) => {
|
||||
self.pending_managed_worktree_creation = true;
|
||||
let source_cwd = self.config.cwd.clone();
|
||||
let sender = self.app_event_tx.clone();
|
||||
tokio::spawn(async move {
|
||||
let create_cwd = source_cwd.to_path_buf();
|
||||
let result = tokio::task::spawn_blocking(move || {
|
||||
manager
|
||||
.create(&akode_worktree::CreateWorktree {
|
||||
source_cwd: create_cwd,
|
||||
base: None,
|
||||
})
|
||||
.map(|checkout| (manager, checkout))
|
||||
.map_err(|error| error.to_string())
|
||||
})
|
||||
.await
|
||||
.unwrap_or_else(|error| {
|
||||
Err(format!("Worktree creation task failed: {error}"))
|
||||
});
|
||||
sender.send(AppEvent::ManagedWorktreeCreated(Box::new(
|
||||
ManagedWorktreeCreated {
|
||||
source_thread_id: thread_id,
|
||||
source_cwd,
|
||||
mode,
|
||||
name,
|
||||
result,
|
||||
},
|
||||
)));
|
||||
});
|
||||
}
|
||||
Err(error) => self.chat_widget.add_error_message(error.to_string()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn finish_managed_worktree(&mut self, created: ManagedWorktreeCreated) {
|
||||
self.pending_managed_worktree_creation = false;
|
||||
let (manager, checkout) = match created.result {
|
||||
Ok(created) => created,
|
||||
Err(error) => return self.working_directory_error(error),
|
||||
};
|
||||
let can_continue = !self.reconnect.offline
|
||||
&& !self.chat_widget.has_misalignment_policy_violation()
|
||||
&& !crate::uses_remote_workspace_or_environment(
|
||||
&self.app_server_target,
|
||||
self.environment_manager.as_ref(),
|
||||
)
|
||||
&& self.primary_thread_id == Some(created.source_thread_id)
|
||||
&& !crate::session_resume::cwds_differ(
|
||||
self.config.cwd.as_path(),
|
||||
created.source_cwd.as_path(),
|
||||
)
|
||||
&& self
|
||||
.chat_widget
|
||||
.can_change_working_directory(created.source_thread_id);
|
||||
if !can_continue {
|
||||
return self.retained_worktree_error(
|
||||
&checkout,
|
||||
"Cannot continue into the new worktree while the source session changed or is unavailable.",
|
||||
);
|
||||
}
|
||||
match self
|
||||
.rebuild_config_for_cwd(created.source_cwd.to_path_buf())
|
||||
.await
|
||||
{
|
||||
Ok(config) if !config.active_project.is_untrusted() => {}
|
||||
Ok(_) | Err(_) => {
|
||||
return self.retained_worktree_error(
|
||||
&checkout,
|
||||
"Cannot continue into the new worktree because source configuration changed.",
|
||||
);
|
||||
}
|
||||
}
|
||||
let config = match self.rebuild_config_for_cwd(checkout.cwd.clone()).await {
|
||||
Ok(config) if config.active_project.trust_level.is_some() => config,
|
||||
Ok(_) => {
|
||||
return self.retained_worktree_error(
|
||||
&checkout,
|
||||
"The new worktree is not trusted; run aKode there.",
|
||||
);
|
||||
}
|
||||
Err(error) => {
|
||||
return self.retained_worktree_error(
|
||||
&checkout,
|
||||
format!("Cannot load the new worktree configuration: {error}"),
|
||||
);
|
||||
}
|
||||
};
|
||||
self.pending_managed_worktree_transition = Some(Box::new(ManagedWorktreeTransition {
|
||||
source_thread_id: created.source_thread_id,
|
||||
source_cwd: created.source_cwd,
|
||||
manager,
|
||||
checkout,
|
||||
config: Box::new(config),
|
||||
mode: created.mode,
|
||||
name: created.name,
|
||||
}));
|
||||
}
|
||||
|
||||
fn retained_worktree_error(
|
||||
&mut self,
|
||||
checkout: &akode_worktree::ManagedWorktree,
|
||||
reason: impl std::fmt::Display,
|
||||
) {
|
||||
self.working_directory_error(format!(
|
||||
"{reason} A checkout was retained at {}; remove it with `git worktree remove <checkout-path>` from the source repository if it is no longer needed.",
|
||||
checkout.root.display()
|
||||
));
|
||||
}
|
||||
}
|
||||
194
akode-rs/tui/src/app/misalignment_policy.rs
Normal file
194
akode-rs/tui/src/app/misalignment_policy.rs
Normal file
@@ -0,0 +1,194 @@
|
||||
//! Continue only the displayed, acknowledged misalignment failure. Submission stays outside
|
||||
//! the ordinary input queue, which must remain blocked until the server accepts the new turn.
|
||||
|
||||
use super::*;
|
||||
use crate::app_server_session::ThreadSettingsOwner;
|
||||
use crate::app_server_session::turn_permissions_overrides;
|
||||
use crate::chatwidget::MisalignmentReview;
|
||||
use crate::chatwidget::MisalignmentTurnSource;
|
||||
use akode_app_server_protocol::ClientRequest;
|
||||
use akode_app_server_protocol::TurnStartParams;
|
||||
use akode_app_server_protocol::TurnStartResponse;
|
||||
use akode_app_server_protocol::UserInput;
|
||||
|
||||
impl App {
|
||||
pub(super) fn open_misalignment_review(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
review: Arc<MisalignmentReview>,
|
||||
) {
|
||||
if !self.chat_widget.is_current_misalignment_review(&review) {
|
||||
return;
|
||||
}
|
||||
self.chat_widget
|
||||
.show_misalignment_review_confirmation(Arc::clone(&review));
|
||||
let mut lines = Vec::new();
|
||||
if let Some(message) = review.continuation_message() {
|
||||
lines.push(Line::from("Continuation request (quoted)").bold());
|
||||
// Keep the submitted text ahead of potentially long findings, without interpreting it.
|
||||
lines.push(Line::from(format!("{message:?}")));
|
||||
lines.push(Line::default());
|
||||
}
|
||||
crate::markdown::append_markdown(
|
||||
review
|
||||
.details
|
||||
.detailed_explanation
|
||||
.as_deref()
|
||||
.unwrap_or_default(),
|
||||
/*width*/ None,
|
||||
Some(self.chat_widget.config_ref().cwd.as_path()),
|
||||
&mut lines,
|
||||
);
|
||||
let _ = tui.enter_alt_screen();
|
||||
self.overlay = Some(Overlay::new_static_with_lines(
|
||||
lines,
|
||||
"What we detected".to_string(),
|
||||
self.keymap.pager.clone(),
|
||||
));
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
|
||||
pub(super) async fn continue_misalignment(
|
||||
&mut self,
|
||||
app_server: &mut AppServerSession,
|
||||
review: Arc<MisalignmentReview>,
|
||||
) {
|
||||
if self.chat_widget.is_current_misalignment_review(&review) {
|
||||
self.chat_widget.show_misalignment_policy_precaution();
|
||||
}
|
||||
// The event store can be newer than the widget while UI actions are queued.
|
||||
if let Some(channel) = self.thread_event_channels.get(&review.thread_id) {
|
||||
let store = channel.store.lock().await;
|
||||
if store.active_turn_id().is_some() {
|
||||
return;
|
||||
}
|
||||
let latest = store.buffer.iter().rev().find_map(|event| {
|
||||
let ThreadBufferedEvent::Notification(notification) = event else {
|
||||
return None;
|
||||
};
|
||||
let (turn_id, error) = match notification.as_ref() {
|
||||
ServerNotification::TurnStarted(_) => return Some(false),
|
||||
ServerNotification::TurnCompleted(n) if n.turn.status == TurnStatus::Failed => {
|
||||
(&n.turn.id, n.turn.error.as_ref())
|
||||
}
|
||||
ServerNotification::TurnCompleted(_) => return Some(false),
|
||||
ServerNotification::Error(n)
|
||||
if !n.will_retry
|
||||
&& (n.turn_id == review.turn_id
|
||||
|| n.error.codex_error_info
|
||||
== Some(
|
||||
AppServerCodexErrorInfo::MisalignmentPolicyViolation,
|
||||
)) =>
|
||||
{
|
||||
(&n.turn_id, Some(&n.error))
|
||||
}
|
||||
_ => return None,
|
||||
};
|
||||
let Some(error) = error else {
|
||||
return Some(false);
|
||||
};
|
||||
if turn_id != &review.turn_id
|
||||
|| error.codex_error_info
|
||||
!= Some(AppServerCodexErrorInfo::MisalignmentPolicyViolation)
|
||||
{
|
||||
return Some(false);
|
||||
}
|
||||
// Empty duplicates do not supersede the latest supplied findings.
|
||||
error
|
||||
.misalignment
|
||||
.as_ref()
|
||||
.map(|details| details == &review.details)
|
||||
});
|
||||
if latest == Some(false) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
if self.current_displayed_thread_id() != Some(review.thread_id)
|
||||
|| self
|
||||
.active_thread_rx
|
||||
.as_ref()
|
||||
.is_some_and(|rx| !rx.is_empty())
|
||||
|| !self.chat_widget.is_current_misalignment_review(&review)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let Some(message) = review.continuation_message() else {
|
||||
return;
|
||||
};
|
||||
let mut params = TurnStartParams {
|
||||
thread_id: review.thread_id.to_string(),
|
||||
input: vec![UserInput::Text {
|
||||
text: message.to_string(),
|
||||
text_elements: Vec::new(),
|
||||
}],
|
||||
responsesapi_client_metadata: Some(HashMap::from([(
|
||||
"misalignment_override".to_string(),
|
||||
serde_json::json!({"timestamp": chrono::Utc::now().timestamp_millis()}).to_string(),
|
||||
)])),
|
||||
..Default::default()
|
||||
};
|
||||
if app_server.thread_params_mode().settings_owner() == ThreadSettingsOwner::Client {
|
||||
let config = self.chat_widget.config_ref();
|
||||
let explicit_profile =
|
||||
self.runtime_permission_profile_override
|
||||
.as_ref()
|
||||
.filter(|profile| {
|
||||
profile.turn_override == RuntimePermissionProfileTurnOverride::LegacySandbox
|
||||
});
|
||||
let permissions_override = Self::turn_permissions_override_from_config(
|
||||
config,
|
||||
explicit_profile.and_then(|profile| profile.active_permission_profile.as_ref()),
|
||||
explicit_profile
|
||||
.and_then(RuntimePermissionProfileOverride::turn_permission_profile),
|
||||
);
|
||||
let Ok((sandbox_policy, permissions)) =
|
||||
turn_permissions_overrides(permissions_override, config.cwd.as_path())
|
||||
else {
|
||||
self.chat_widget.add_error_message(
|
||||
"Couldn’t continue this chat. Review its latest status before trying again."
|
||||
.to_string(),
|
||||
);
|
||||
return;
|
||||
};
|
||||
params.cwd = Some(config.cwd.to_path_buf());
|
||||
params.runtime_workspace_roots =
|
||||
Some(config.permissions.user_visible_workspace_roots().to_vec());
|
||||
params.approval_policy = Some(config.permissions.approval_policy.value().into());
|
||||
params.sandbox_policy = sandbox_policy;
|
||||
params.permissions = permissions;
|
||||
}
|
||||
let result = app_server
|
||||
.request_handle()
|
||||
.request_typed::<TurnStartResponse>(ClientRequest::TurnStart {
|
||||
request_id: app_server.next_request_id(),
|
||||
params,
|
||||
})
|
||||
.await;
|
||||
match result {
|
||||
Ok(response) => {
|
||||
let store = &self.ensure_thread_channel(review.thread_id).store;
|
||||
store.lock().await.active_turn_id = Some(response.turn.id.clone());
|
||||
self.chat_widget.clear_misalignment_for_new_turn(
|
||||
&response.turn.id,
|
||||
MisalignmentTurnSource::AcknowledgedContinuation,
|
||||
);
|
||||
self.chat_widget.handle_server_notification(
|
||||
ServerNotification::TurnStarted(
|
||||
akode_app_server_protocol::TurnStartedNotification {
|
||||
thread_id: review.thread_id.to_string(),
|
||||
turn: response.turn,
|
||||
},
|
||||
),
|
||||
/*replay_kind*/ None,
|
||||
);
|
||||
}
|
||||
Err(_) => {
|
||||
// An RPC diagnostic can contain the submitted steer. Keep the review error generic.
|
||||
self.chat_widget.add_error_message(
|
||||
"Couldn’t continue this chat. Review its latest status before trying again."
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
210
akode-rs/tui/src/app/model_defaults.rs
Normal file
210
akode-rs/tui/src/app/model_defaults.rs
Normal file
@@ -0,0 +1,210 @@
|
||||
//! Apply complete session model choices after server acceptance, separately from saved defaults.
|
||||
//!
|
||||
//! A successful config write can still be overridden. Report that distinction without
|
||||
//! replacing the active task's explicit selection with launch-time configuration.
|
||||
|
||||
use super::App;
|
||||
use crate::app_server_session::AppServerSession;
|
||||
use crate::app_server_session::ThreadSettingsOwner;
|
||||
use crate::service_tier_resolution;
|
||||
use akode_app_server_client::AppServerRequestHandle;
|
||||
use akode_app_server_protocol::ConfigEdit;
|
||||
use akode_app_server_protocol::WriteStatus;
|
||||
use akode_protocol::config_types::ModeKind;
|
||||
use akode_protocol::config_types::SERVICE_TIER_DEFAULT_REQUEST_VALUE;
|
||||
use akode_protocol::config_types::ServiceTier;
|
||||
use akode_protocol::openai_models::ReasoningEffort;
|
||||
use color_eyre::eyre::Result;
|
||||
|
||||
impl App {
|
||||
pub(super) async fn apply_default_model_selection(
|
||||
&mut self,
|
||||
app_server: &mut AppServerSession,
|
||||
model: String,
|
||||
effort: Option<ReasoningEffort>,
|
||||
) {
|
||||
if self
|
||||
.active_thread_model_setting_update_params(model.clone())
|
||||
.is_some_and(|params| params.permissions.is_some())
|
||||
&& self.reject_pending_permission_change()
|
||||
{
|
||||
return;
|
||||
}
|
||||
let model_changed = self.chat_widget.current_model() != model
|
||||
|| self.chat_widget.current_collaboration_mode().model() != model;
|
||||
if model_changed {
|
||||
self.chat_widget.set_model(&model);
|
||||
self.sync_active_thread_model_setting(app_server, model.clone(), /*effort*/ None)
|
||||
.await;
|
||||
self.sync_active_thread_service_tier_to_cached_session()
|
||||
.await;
|
||||
}
|
||||
self.on_update_reasoning_effort(effort.clone());
|
||||
self.sync_active_thread_reasoning_setting(app_server, effort.clone())
|
||||
.await;
|
||||
self.persist_default_model_selection(app_server.request_handle(), model, effort)
|
||||
.await;
|
||||
}
|
||||
|
||||
pub(super) async fn persist_default_model_selection(
|
||||
&mut self,
|
||||
request_handle: AppServerRequestHandle,
|
||||
model: String,
|
||||
effort: Option<ReasoningEffort>,
|
||||
) {
|
||||
self.app_event_tx
|
||||
.send(crate::app_event::AppEvent::FollowTranscript);
|
||||
match self
|
||||
.persist_model_defaults(
|
||||
request_handle,
|
||||
crate::config_update::build_model_selection_edits(model.as_str(), effort.as_ref()),
|
||||
"default model and reasoning effort",
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(()) => {
|
||||
let effort_label = effort
|
||||
.as_ref()
|
||||
.map(std::string::ToString::to_string)
|
||||
.unwrap_or_else(|| "default".to_string());
|
||||
tracing::info!("Selected model: {model}, Selected effort: {effort_label}");
|
||||
let mut message = format!("Model changed to {model}");
|
||||
if let Some(label) = Self::reasoning_label_for(&model, effort.as_ref()) {
|
||||
message.push(' ');
|
||||
message.push_str(&label);
|
||||
}
|
||||
self.chat_widget.add_info_message(message, /*hint*/ None);
|
||||
}
|
||||
Err(err) => {
|
||||
let error = crate::config_update::format_config_error(&err);
|
||||
tracing::error!(error = %error, "failed to persist model selection");
|
||||
self.chat_widget
|
||||
.add_error_message(format!("Failed to save default model: {error}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn select_session_model(
|
||||
&mut self,
|
||||
app_server: &mut AppServerSession,
|
||||
model: String,
|
||||
effort: Option<ReasoningEffort>,
|
||||
service_tier: Option<String>,
|
||||
) {
|
||||
// Changing effort or speed for the effective model must preserve permissions.
|
||||
let model_changed = self.chat_widget.current_model() != model;
|
||||
let params = if model_changed {
|
||||
self.active_thread_model_setting_update_params(model.clone())
|
||||
} else {
|
||||
self.active_thread_reasoning_setting_update_params(effort.clone())
|
||||
};
|
||||
if let Some(mut params) = params {
|
||||
if params.permissions.is_some() && self.reject_pending_permission_change() {
|
||||
return;
|
||||
}
|
||||
params.effort = effort.clone();
|
||||
params.collaboration_mode = Some(
|
||||
self.chat_widget
|
||||
.effective_collaboration_mode()
|
||||
.with_updates(
|
||||
Some(model.clone()),
|
||||
Some(effort.clone()),
|
||||
/*developer_instructions*/ None,
|
||||
),
|
||||
);
|
||||
params.service_tier = match service_tier.as_ref() {
|
||||
Some(tier) => Some(Some(tier.clone())),
|
||||
None => service_tier_resolution::service_tier_update_for_core(
|
||||
self.chat_widget.config_ref(),
|
||||
&self.local_settings.notices,
|
||||
&model,
|
||||
&self.model_catalog.models,
|
||||
),
|
||||
};
|
||||
if !self.send_model_settings_update(app_server, params).await {
|
||||
if app_server.thread_settings_update_supported {
|
||||
return;
|
||||
}
|
||||
if app_server.thread_params_mode().settings_owner() == ThreadSettingsOwner::Server {
|
||||
self.chat_widget.add_error_message(
|
||||
"This cloud conversation does not support changing its model from the TUI."
|
||||
.into(),
|
||||
);
|
||||
return;
|
||||
}
|
||||
if service_tier
|
||||
.as_deref()
|
||||
.is_some_and(|tier| tier != SERVICE_TIER_DEFAULT_REQUEST_VALUE)
|
||||
{
|
||||
self.chat_widget.add_error_message(
|
||||
"Model selection requires an app server with thread/settings/update support."
|
||||
.into(),
|
||||
);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
let in_plan_mode = self.chat_widget.effective_collaboration_mode().mode == ModeKind::Plan;
|
||||
let ultra = effort == Some(ReasoningEffort::Ultra);
|
||||
let clear_default_ultra = self
|
||||
.chat_widget
|
||||
.current_collaboration_mode()
|
||||
.reasoning_effort()
|
||||
== Some(ReasoningEffort::Ultra)
|
||||
&& self.config.model_reasoning_effort != Some(ReasoningEffort::Ultra);
|
||||
let clear_plan_ultra = self.chat_widget.config_ref().plan_mode_reasoning_effort
|
||||
== Some(ReasoningEffort::Ultra)
|
||||
&& self.config.plan_mode_reasoning_effort != Some(ReasoningEffort::Ultra);
|
||||
if model_changed {
|
||||
self.chat_widget.set_model(&model);
|
||||
}
|
||||
if !in_plan_mode
|
||||
|| (self.chat_widget.current_collaboration_mode().model() == model
|
||||
&& (ultra || clear_default_ultra))
|
||||
{
|
||||
self.chat_widget.set_reasoning_effort(effort.clone());
|
||||
}
|
||||
if in_plan_mode || ultra || clear_plan_ultra {
|
||||
self.chat_widget
|
||||
.set_plan_mode_reasoning_effort(effort.clone());
|
||||
}
|
||||
if let Some(service_tier) = service_tier.as_ref() {
|
||||
self.chat_widget
|
||||
.set_service_tier(Some(service_tier.clone()));
|
||||
}
|
||||
self.sync_active_thread_service_tier_to_cached_session()
|
||||
.await;
|
||||
let mut message = format!("Model changed to {model}");
|
||||
if let Some(label) = Self::reasoning_label_for(&model, effort.as_ref()) {
|
||||
message.push(' ');
|
||||
message.push_str(&label);
|
||||
}
|
||||
if let Some(service_tier) = service_tier {
|
||||
message.push(' ');
|
||||
message.push_str(if service_tier == SERVICE_TIER_DEFAULT_REQUEST_VALUE {
|
||||
"standard"
|
||||
} else if service_tier == ServiceTier::Fast.request_value() {
|
||||
"fast"
|
||||
} else {
|
||||
&service_tier
|
||||
});
|
||||
}
|
||||
message.push_str(" for this session only");
|
||||
self.chat_widget.add_info_message(message, /*hint*/ None);
|
||||
}
|
||||
|
||||
pub(super) async fn persist_model_defaults(
|
||||
&mut self,
|
||||
request_handle: AppServerRequestHandle,
|
||||
edits: Vec<ConfigEdit>,
|
||||
setting: &str,
|
||||
) -> Result<()> {
|
||||
let response = crate::config_update::write_config_batch(request_handle, edits).await?;
|
||||
if response.status == WriteStatus::OkOverridden {
|
||||
self.chat_widget.add_warning_message(format!(
|
||||
"Saved {setting}, but a higher-priority configuration layer overrides the saved value."
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
150
akode-rs/tui/src/app/native_history.rs
Normal file
150
akode-rs/tui/src/app/native_history.rs
Normal file
@@ -0,0 +1,150 @@
|
||||
//! Queue native terminal output behind unfinished dynamic tools.
|
||||
//! Fullscreen rendering reads retained cells directly and never queues terminal output.
|
||||
//!
|
||||
//! Entries own their render source independently of the retained view. Consolidation remaps their
|
||||
//! canonical owner, so pagination, pointer reuse, and replacing stream fragments cannot cause a
|
||||
//! second emission. Clearing the transcript starts a new journal; rollback prunes removed owners.
|
||||
|
||||
use super::*;
|
||||
|
||||
const CELLS_PER_FRAME: usize = 32;
|
||||
|
||||
struct PendingCell {
|
||||
source: Arc<dyn HistoryCell>,
|
||||
owner: std::sync::Weak<dyn HistoryCell>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct NativeHistory {
|
||||
pending: VecDeque<PendingCell>,
|
||||
}
|
||||
|
||||
pub(super) fn is_pending(cell: &dyn HistoryCell) -> bool {
|
||||
cell.as_any()
|
||||
.downcast_ref::<history_cell::DynamicToolCallCell>()
|
||||
.is_some_and(history_cell::DynamicToolCallCell::is_active)
|
||||
}
|
||||
|
||||
impl NativeHistory {
|
||||
pub(super) fn contains(&self, cell: &Arc<dyn HistoryCell>) -> bool {
|
||||
self.pending
|
||||
.iter()
|
||||
.any(|entry| Arc::ptr_eq(&entry.source, cell))
|
||||
}
|
||||
|
||||
pub(super) fn insert(&mut self, cell: &Arc<dyn HistoryCell>) -> bool {
|
||||
if is_pending(cell.as_ref()) || !self.pending.is_empty() {
|
||||
self.defer(cell);
|
||||
true
|
||||
} else {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn defer(&mut self, cell: &Arc<dyn HistoryCell>) {
|
||||
self.pending.push_back(PendingCell {
|
||||
source: cell.clone(),
|
||||
owner: Arc::downgrade(cell),
|
||||
});
|
||||
}
|
||||
|
||||
/// Replace an entirely unprinted stream with final source. For a partly printed stream, keep
|
||||
/// only its remaining fragments; never replay the prefix already owned by the terminal.
|
||||
pub(super) fn consolidate(
|
||||
&mut self,
|
||||
previous: &[Arc<dyn HistoryCell>],
|
||||
consolidated: &Arc<dyn HistoryCell>,
|
||||
) {
|
||||
let belongs = |entry: &PendingCell| {
|
||||
previous
|
||||
.iter()
|
||||
.any(|cell| entry.owner.ptr_eq(&Arc::downgrade(cell)))
|
||||
};
|
||||
let all_pending = !previous.is_empty() && previous.iter().all(|cell| self.contains(cell));
|
||||
if all_pending && let Some(index) = self.pending.iter().position(&belongs) {
|
||||
self.pending.retain(|entry| !belongs(entry));
|
||||
// Keep consolidated output before unrelated cells that were queued after it.
|
||||
self.pending.insert(
|
||||
index,
|
||||
PendingCell {
|
||||
source: consolidated.clone(),
|
||||
owner: Arc::downgrade(consolidated),
|
||||
},
|
||||
);
|
||||
} else {
|
||||
for entry in self.pending.iter_mut().filter(|entry| belongs(entry)) {
|
||||
entry.owner = Arc::downgrade(consolidated);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn retain(&mut self, cells: &[Arc<dyn HistoryCell>]) {
|
||||
self.pending.retain(|entry| {
|
||||
cells
|
||||
.iter()
|
||||
.any(|cell| entry.owner.ptr_eq(&Arc::downgrade(cell)))
|
||||
});
|
||||
}
|
||||
|
||||
/// Historical in-progress records are not live blockers: only queued owners can hold replay.
|
||||
pub(super) fn replayable_cells<'a>(
|
||||
&self,
|
||||
cells: &'a [Arc<dyn HistoryCell>],
|
||||
) -> &'a [Arc<dyn HistoryCell>] {
|
||||
let end = self
|
||||
.pending
|
||||
.iter()
|
||||
.find(|entry| entry.owner.strong_count() > 0 && is_pending(entry.source.as_ref()))
|
||||
.and_then(|entry| {
|
||||
cells
|
||||
.iter()
|
||||
.position(|cell| entry.owner.ptr_eq(&Arc::downgrade(cell)))
|
||||
})
|
||||
.unwrap_or(cells.len());
|
||||
&cells[..end]
|
||||
}
|
||||
|
||||
/// A deliberate native resize/rollback replay supersedes queued settled output.
|
||||
pub(super) fn replayed(&mut self) {
|
||||
let mut blocked = false;
|
||||
self.pending.retain(|entry| {
|
||||
blocked |= is_pending(entry.source.as_ref());
|
||||
blocked
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub(super) fn flush_native_history(&mut self, tui: &mut tui::Tui) {
|
||||
if tui.is_owned_screen() || self.overlay.is_some() {
|
||||
return;
|
||||
}
|
||||
let mut ready = Vec::new();
|
||||
while let Some(entry) = self.native_history.pending.front() {
|
||||
if entry.owner.strong_count() == 0 {
|
||||
self.native_history.pending.pop_front();
|
||||
continue;
|
||||
}
|
||||
if ready.len() == CELLS_PER_FRAME || is_pending(entry.source.as_ref()) {
|
||||
break;
|
||||
}
|
||||
ready.push(Arc::clone(&entry.source));
|
||||
self.native_history.pending.pop_front();
|
||||
}
|
||||
for cell in ready {
|
||||
self.render_inserted_history_cell(tui, &cell, /*deferred*/ false);
|
||||
}
|
||||
if self
|
||||
.native_history
|
||||
.pending
|
||||
.front()
|
||||
.is_some_and(|entry| !is_pending(entry.source.as_ref()))
|
||||
{
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "native_history_tests.rs"]
|
||||
mod tests;
|
||||
127
akode-rs/tui/src/app/native_history_tests.rs
Normal file
127
akode-rs/tui/src/app/native_history_tests.rs
Normal file
@@ -0,0 +1,127 @@
|
||||
//! Native output preserves ordering, quota warning visibility, and replay consistency.
|
||||
|
||||
use super::*;
|
||||
use akode_app_server_protocol::DynamicToolCallOutputContentItem;
|
||||
use akode_app_server_protocol::DynamicToolCallStatus;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn quota_warnings_are_emitted_once_and_survive_native_replay() -> Result<()> {
|
||||
for initial_replay in [false, true] {
|
||||
let (mut app, mut events, _ops) = crate::app::tests::make_test_app_with_channels().await;
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
if initial_replay {
|
||||
app.begin_initial_history_replay_buffer();
|
||||
}
|
||||
app.insert_history_cell(
|
||||
&mut tui,
|
||||
Box::new(history_cell::new_warning_event("Hidden diagnostic".into())),
|
||||
);
|
||||
let quota: akode_app_server_protocol::RateLimitSnapshot =
|
||||
serde_json::from_value(serde_json::json!({
|
||||
"primary": {"usedPercent": 80, "windowDurationMins": 300},
|
||||
}))?;
|
||||
for _ in 0..2 {
|
||||
app.chat_widget.on_rate_limit_snapshot(Some(quota.clone()));
|
||||
while let Ok(event) = events.try_recv() {
|
||||
if let AppEvent::InsertHistoryCell(cell) = event {
|
||||
app.insert_history_cell(&mut tui, cell);
|
||||
}
|
||||
}
|
||||
}
|
||||
app.finish_initial_history_replay_buffer(&mut tui);
|
||||
let inserted = tui.pending_history_lines_for_test();
|
||||
insta::allow_duplicates! {
|
||||
insta::assert_snapshot!("native_quota_warning", inserted.iter().map(|line| line.line.to_string()).collect::<Vec<_>>().join("\n"));
|
||||
}
|
||||
assert_eq!(
|
||||
app.render_transcript_lines_for_reflow(/*width*/ 80).lines,
|
||||
inserted
|
||||
);
|
||||
app.flush_native_history(&mut tui);
|
||||
assert_eq!(tui.pending_history_lines_for_test(), inserted);
|
||||
assert_eq!(history_cell::warning_count(&app.transcript_cells), 2);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn settled_tool_precedes_queued_output_and_is_not_emitted_twice() -> Result<()> {
|
||||
let mut app = crate::app::test_support::make_test_app().await;
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
let item = |status| ThreadItemPayload::DynamicToolCall {
|
||||
id: "lookup".into(),
|
||||
namespace: None,
|
||||
tool: "lookup".into(),
|
||||
arguments: serde_json::json!({}),
|
||||
status,
|
||||
success: None,
|
||||
duration_ms: None,
|
||||
content_items: Some(vec![DynamicToolCallOutputContentItem::InputText {
|
||||
text: "unique result".into(),
|
||||
}]),
|
||||
};
|
||||
let cell =
|
||||
history_cell::DynamicToolCallCell::from_item(item(DynamicToolCallStatus::InProgress))
|
||||
.unwrap();
|
||||
// Stale in-progress history is not in the live queue and cannot hide later context.
|
||||
app.transcript_cells.push(Arc::new(cell.clone()));
|
||||
app.transcript_cells
|
||||
.push(Arc::new(history_cell::PlainHistoryCell::new(vec![
|
||||
"past context".into(),
|
||||
])));
|
||||
app.insert_history_cell(&mut tui, Box::new(cell.clone()));
|
||||
app.flush_native_history(&mut tui);
|
||||
assert!(tui.pending_history_lines_for_test().is_empty());
|
||||
// A long-lived tool must not lose output queued behind it.
|
||||
for index in 0..4097 {
|
||||
app.insert_history_cell(
|
||||
&mut tui,
|
||||
Box::new(history_cell::PlainHistoryCell::new(vec![
|
||||
format!("later output {index}").into(),
|
||||
])),
|
||||
);
|
||||
}
|
||||
app.flush_native_history(&mut tui);
|
||||
assert!(tui.pending_history_lines_for_test().is_empty());
|
||||
app.native_history.replayed();
|
||||
assert!(
|
||||
app.render_transcript_lines_for_reflow(/*width*/ 80)
|
||||
.lines
|
||||
.iter()
|
||||
.any(|line| line.line.to_string().contains("past context"))
|
||||
);
|
||||
let historical = app.render_transcript_lines_for_reflow(/*width*/ 80).lines;
|
||||
assert!(
|
||||
historical
|
||||
.iter()
|
||||
.any(|line| line.line.to_string().contains("Calling lookup"))
|
||||
);
|
||||
cell.update_from_item(item(DynamicToolCallStatus::Completed));
|
||||
for _ in 0..=4097 / CELLS_PER_FRAME {
|
||||
app.flush_native_history(&mut tui);
|
||||
}
|
||||
let lines = tui.pending_history_lines_for_test();
|
||||
let text = lines
|
||||
.iter()
|
||||
.map(|line| line.line.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
assert_eq!(text.matches("unique result").count(), 1);
|
||||
assert_eq!(text.matches("later output").count(), 4097);
|
||||
assert!(text.find("unique result").unwrap() < text.find("later output").unwrap());
|
||||
app.flush_native_history(&mut tui);
|
||||
assert_eq!(tui.pending_history_lines_for_test(), lines);
|
||||
// Rollback replay consumes even a queue larger than one frame's drain budget.
|
||||
for cell in app.transcript_cells.iter().rev().take(CELLS_PER_FRAME + 1) {
|
||||
app.native_history.defer(cell);
|
||||
}
|
||||
app.rebuild_transcript_after_backtrack(
|
||||
&mut tui,
|
||||
ratatui::layout::Size::new(/*width*/ 80, /*height*/ 24).into(),
|
||||
)?;
|
||||
let replayed = tui.pending_history_lines_for_test();
|
||||
app.flush_native_history(&mut tui);
|
||||
assert_eq!(tui.pending_history_lines_for_test(), replayed);
|
||||
Ok(())
|
||||
}
|
||||
150
akode-rs/tui/src/app/new_session.rs
Normal file
150
akode-rs/tui/src/app/new_session.rs
Normal file
@@ -0,0 +1,150 @@
|
||||
//! New-session configuration from server defaults and explicit launch settings.
|
||||
//!
|
||||
//! Build the replacement configuration without replacing the active task's settings.
|
||||
|
||||
use super::resume_preparation::BackendSettings;
|
||||
use super::*;
|
||||
use akode_config::ConfigLayerSource;
|
||||
use akode_protocol::config_types::ServiceTier;
|
||||
|
||||
pub(crate) fn has_launch_setting(
|
||||
config: &Config,
|
||||
cli_kv_overrides: &[(String, TomlValue)],
|
||||
key: &str,
|
||||
) -> bool {
|
||||
// A remote server cannot resolve this invocation's explicitly selected local profile.
|
||||
// Only count the profile when it supplies the effective value; project settings can shadow it.
|
||||
cli_kv_overrides.iter().any(|(path, _)| path == key)
|
||||
|| config
|
||||
.config_layer_stack
|
||||
.layers_high_to_low()
|
||||
.find(|layer| layer.config.get(key).is_some())
|
||||
.is_some_and(|layer| {
|
||||
matches!(
|
||||
layer.name,
|
||||
ConfigLayerSource::User {
|
||||
profile: Some(_),
|
||||
..
|
||||
}
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn overlay_new_session_defaults(
|
||||
config: &mut Config,
|
||||
defaults: &akode_app_server_protocol::Config,
|
||||
cli_kv_overrides: &[(String, TomlValue)],
|
||||
harness_overrides: &ConfigOverrides,
|
||||
) {
|
||||
if harness_overrides.model.is_none() && !has_launch_setting(config, cli_kv_overrides, "model") {
|
||||
config.model = defaults.model.clone();
|
||||
}
|
||||
if !has_launch_setting(config, cli_kv_overrides, "model_reasoning_effort") {
|
||||
config.model_reasoning_effort = defaults.model_reasoning_effort.clone();
|
||||
}
|
||||
if harness_overrides.service_tier.is_none()
|
||||
&& !has_launch_setting(config, cli_kv_overrides, "service_tier")
|
||||
{
|
||||
config.service_tier = defaults.service_tier.as_deref().map(|service_tier| {
|
||||
ServiceTier::from_request_value(service_tier)
|
||||
.map(|tier| tier.request_value().to_string())
|
||||
.unwrap_or_else(|| service_tier.to_string())
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub(super) async fn load_new_session_config(
|
||||
&mut self,
|
||||
app_server: &AppServerSession,
|
||||
) -> Result<(Config, crate::local_settings::LocalSettings)> {
|
||||
let settings = self.backend_settings();
|
||||
let cwd = self.chat_widget.config_ref().cwd.to_path_buf();
|
||||
self.load_new_session_config_from(app_server, &settings, cwd, /*cloud_switch*/ None)
|
||||
.await
|
||||
}
|
||||
|
||||
pub(super) async fn load_new_session_config_from(
|
||||
&mut self,
|
||||
app_server: &AppServerSession,
|
||||
settings: &BackendSettings,
|
||||
cwd: PathBuf,
|
||||
mut cloud_switch: Option<&mut tui::Tui>,
|
||||
) -> Result<(Config, crate::local_settings::LocalSettings)> {
|
||||
let defaults_cwd = match app_server.thread_params_mode() {
|
||||
crate::app_server_session::ThreadParamsMode::Embedded => cwd.as_path(),
|
||||
crate::app_server_session::ThreadParamsMode::Remote
|
||||
| crate::app_server_session::ThreadParamsMode::Cloud => {
|
||||
app_server.remote_cwd_override().unwrap_or(Path::new("."))
|
||||
}
|
||||
};
|
||||
let refresh = self.rebuild_config_for_cwd_from(&settings.config, cwd.clone());
|
||||
let load = async {
|
||||
let defaults = crate::config_update::read_effective_config_if_supported(
|
||||
app_server.request_handle(),
|
||||
defaults_cwd,
|
||||
)
|
||||
.await?;
|
||||
Ok::<_, color_eyre::eyre::Report>((defaults, refresh.await))
|
||||
};
|
||||
let (defaults, refreshed_config) = if let Some(tui) = cloud_switch.as_deref_mut() {
|
||||
let events = tui.event_stream();
|
||||
super::cloud_switch_wait::wait_for_cloud_switch(
|
||||
self,
|
||||
tui,
|
||||
load,
|
||||
events,
|
||||
super::cloud_switch_wait::ClipboardHandoff::ContinueEditing,
|
||||
)
|
||||
.await
|
||||
} else {
|
||||
load.await
|
||||
}?;
|
||||
// Stage local preferences and permission carryover without changing the active task.
|
||||
let (mut config, local_settings) = match refreshed_config {
|
||||
Ok(config) => {
|
||||
let local_settings = settings.local_settings.reloaded(&config);
|
||||
(config, local_settings)
|
||||
}
|
||||
Err(err) => {
|
||||
tracing::warn!(%err, "failed to refresh local settings before a new thread");
|
||||
(settings.config.clone(), settings.local_settings.clone())
|
||||
}
|
||||
};
|
||||
if let Some(defaults) = defaults.as_ref() {
|
||||
crate::projectless::apply_defaults(
|
||||
&mut config,
|
||||
&self.harness_overrides,
|
||||
app_server,
|
||||
&self.environment_manager,
|
||||
defaults,
|
||||
);
|
||||
}
|
||||
if let Err(error) = self.apply_runtime_policy_overrides_with_reviewer(
|
||||
&mut config,
|
||||
RuntimePolicyOverrideScope::ExplicitOnly,
|
||||
settings.config.approvals_reviewer,
|
||||
) {
|
||||
if let Some(tui) = cloud_switch {
|
||||
let events = tui.event_stream();
|
||||
super::cloud_switch_wait::finish_failed_cloud_switch(self, tui, events).await;
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
if let Some(defaults) = defaults.as_ref() {
|
||||
overlay_new_session_defaults(
|
||||
&mut config,
|
||||
&defaults.config,
|
||||
&self.cli_kv_overrides,
|
||||
&self.harness_overrides,
|
||||
);
|
||||
}
|
||||
apply_managed_new_thread_defaults(
|
||||
&mut config,
|
||||
app_server.managed_new_thread_defaults(),
|
||||
&self.cli_kv_overrides,
|
||||
&self.harness_overrides,
|
||||
);
|
||||
Ok((config, local_settings))
|
||||
}
|
||||
}
|
||||
1242
akode-rs/tui/src/app/owned_transcript.rs
Normal file
1242
akode-rs/tui/src/app/owned_transcript.rs
Normal file
File diff suppressed because it is too large
Load Diff
607
akode-rs/tui/src/app/owned_transcript_browsing_tests.rs
Normal file
607
akode-rs/tui/src/app/owned_transcript_browsing_tests.rs
Normal file
@@ -0,0 +1,607 @@
|
||||
//! Browsing restores its origin and gives selection/search priority over rewind keys.
|
||||
|
||||
use super::*;
|
||||
use crate::app::tests::make_test_app_with_channels;
|
||||
use crate::history_cell::HistoryRenderMode;
|
||||
use crate::history_cell::PlainHistoryCell;
|
||||
use akode_app_server_protocol::ModelProviderError;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn provider_error_escape_opens_resume_picker() -> Result<()> {
|
||||
for (owned, draft) in [
|
||||
(true, ""),
|
||||
(true, "unsent draft"),
|
||||
(false, ""),
|
||||
(false, "unsent draft"),
|
||||
] {
|
||||
let (mut app, mut events, _operations) = make_test_app_with_channels().await;
|
||||
attach_thread(&mut app, ThreadId::new());
|
||||
app.transcript_cells = vec![user_cell("first prompt"), user_cell("second prompt")];
|
||||
app.chat_widget.apply_external_edit(draft.to_string());
|
||||
app.chat_widget.show_provider_error(
|
||||
ModelProviderError::ModelProviderMismatch {
|
||||
model_provider: "old-provider".into(),
|
||||
current_model_provider: "test-provider".into(),
|
||||
},
|
||||
/*rejected_message_id*/ None,
|
||||
);
|
||||
let mut server = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?;
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
tui.set_owned_screen(owned)?;
|
||||
while events.try_recv().is_ok() {}
|
||||
if owned {
|
||||
app.render_owned_transcript(&mut tui, Size::new(/*width*/ 80, /*height*/ 16))?;
|
||||
app.transcript_view
|
||||
.jump_to_entry(&app.transcript_cells, /*index*/ 0);
|
||||
for search in [true, false] {
|
||||
if search {
|
||||
app.transcript_view.begin_search();
|
||||
} else {
|
||||
assert!(app.transcript_view.begin_select_mode(&app.transcript_cells));
|
||||
}
|
||||
assert!(app.transcript_view.has_active_interaction());
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Esc.into()))
|
||||
.await?;
|
||||
assert!(!app.transcript_view.has_active_interaction());
|
||||
assert!(
|
||||
!std::iter::from_fn(|| events.try_recv().ok())
|
||||
.any(|event| matches!(event, AppEvent::OpenResumePicker))
|
||||
);
|
||||
// Release Escape so selection's exit guard does not consume the next press.
|
||||
app.handle_tui_event(
|
||||
&mut tui,
|
||||
&mut server,
|
||||
TuiEvent::Key(KeyEvent::new_with_kind(
|
||||
KeyCode::Esc,
|
||||
KeyModifiers::NONE,
|
||||
KeyEventKind::Release,
|
||||
)),
|
||||
)
|
||||
.await?;
|
||||
}
|
||||
}
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Esc.into()))
|
||||
.await?;
|
||||
assert_eq!(
|
||||
std::iter::from_fn(|| events.try_recv().ok())
|
||||
.filter(|event| matches!(event, AppEvent::OpenResumePicker))
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
assert_eq!(
|
||||
(
|
||||
app.chat_widget.has_provider_error(),
|
||||
app.backtrack.primed,
|
||||
app.backtrack.overlay_preview_active,
|
||||
app.chat_widget.composer_text_with_pending(),
|
||||
app.transcript_cells.len(),
|
||||
),
|
||||
(true, false, false, draft.to_string(), 2)
|
||||
);
|
||||
tui.set_owned_screen(/*owned*/ false)?;
|
||||
server.shutdown().await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn escape_restores_reading_origin_after_details_navigation_and_resize() -> Result<()> {
|
||||
let mut app = crate::app::test_support::make_test_app().await;
|
||||
attach_thread(&mut app, ThreadId::new());
|
||||
app.transcript_cells = vec![
|
||||
user_cell("first prompt"),
|
||||
Arc::new(PlainHistoryCell::new(
|
||||
(0..30)
|
||||
.map(|row| format!("response row {row}").into())
|
||||
.collect(),
|
||||
)),
|
||||
user_cell("second prompt"),
|
||||
Arc::new(PlainHistoryCell::new(vec!["second response".into(); 30])),
|
||||
];
|
||||
let mut server = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?;
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
tui.set_owned_screen(/*owned*/ true)?;
|
||||
for detailed in [false, true] {
|
||||
app.transcript_view
|
||||
.set_presentation(detailed, HistoryRenderMode::Rich);
|
||||
app.render_owned_transcript(&mut tui, Size::new(/*width*/ 80, /*height*/ 16))?;
|
||||
app.transcript_view
|
||||
.scroll(&app.transcript_cells, /*rows*/ -12);
|
||||
let area = Rect::new(
|
||||
/*x*/ 0, /*y*/ 0, /*width*/ 80, /*height*/ 8,
|
||||
);
|
||||
let mut before = Buffer::empty(area);
|
||||
app.transcript_view
|
||||
.render(area, &mut before, &app.transcript_cells);
|
||||
let escape_count = if detailed { 1 } else { 2 };
|
||||
for _ in 0..escape_count {
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Esc.into()))
|
||||
.await?;
|
||||
}
|
||||
assert_eq!(
|
||||
(
|
||||
app.backtrack.overlay_preview_active,
|
||||
app.transcript_view.is_detailed()
|
||||
),
|
||||
(true, false)
|
||||
);
|
||||
for (key, expected_details) in [
|
||||
(KeyEvent::from(KeyCode::Left), false),
|
||||
(
|
||||
KeyEvent::new(KeyCode::Char('t'), KeyModifiers::CONTROL),
|
||||
true,
|
||||
),
|
||||
(
|
||||
KeyEvent::new(KeyCode::Char('t'), KeyModifiers::CONTROL),
|
||||
false,
|
||||
),
|
||||
] {
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(key))
|
||||
.await?;
|
||||
assert_eq!(app.transcript_view.is_detailed(), expected_details);
|
||||
let mut selected = Buffer::empty(area);
|
||||
app.transcript_view
|
||||
.render(area, &mut selected, &app.transcript_cells);
|
||||
assert!(buffer_text(&selected).contains("first prompt"));
|
||||
}
|
||||
assert_eq!(app.backtrack.nth_user_message, 0);
|
||||
app.render_owned_transcript(&mut tui, Size::new(/*width*/ 40, /*height*/ 12))?;
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Esc.into()))
|
||||
.await?;
|
||||
let mut after = Buffer::empty(area);
|
||||
app.transcript_view
|
||||
.render(area, &mut after, &app.transcript_cells);
|
||||
assert_eq!(buffer_text(&after), buffer_text(&before));
|
||||
assert_eq!(
|
||||
(
|
||||
app.backtrack.overlay_preview_active,
|
||||
app.transcript_view.is_detailed(),
|
||||
app.transcript_view.is_following()
|
||||
),
|
||||
(false, detailed, false)
|
||||
);
|
||||
}
|
||||
server.shutdown().await?;
|
||||
tui.set_owned_screen(/*owned*/ false)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn browsing_search_and_selection_consume_escape_before_mode_exit() -> Result<()> {
|
||||
let mut app = crate::app::test_support::make_test_app().await;
|
||||
attach_thread(&mut app, ThreadId::new());
|
||||
app.transcript_cells = vec![user_cell("first prompt"), user_cell("second prompt")];
|
||||
let mut server = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?;
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
tui.set_owned_screen(/*owned*/ true)?;
|
||||
app.handle_backtrack_esc_key(&mut tui);
|
||||
app.handle_backtrack_esc_key(&mut tui);
|
||||
app.render_owned_transcript(&mut tui, Size::new(/*width*/ 80, /*height*/ 16))?;
|
||||
app.transcript_view.begin_search();
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Paste("first".to_string()))
|
||||
.await?;
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Draw)
|
||||
.await?;
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Enter.into()))
|
||||
.await?;
|
||||
assert_eq!(
|
||||
(
|
||||
app.transcript_view.is_search_editing(),
|
||||
app.backtrack.overlay_preview_active
|
||||
),
|
||||
(false, true)
|
||||
);
|
||||
app.render_owned_transcript(&mut tui, Size::new(/*width*/ 80, /*height*/ 16))?;
|
||||
for key in [
|
||||
KeyEvent::new(KeyCode::Char(' '), KeyModifiers::CONTROL),
|
||||
KeyEvent::new(KeyCode::Right, KeyModifiers::SHIFT),
|
||||
] {
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(key))
|
||||
.await?;
|
||||
}
|
||||
assert!(app.transcript_view.has_active_interaction());
|
||||
assert_eq!(app.backtrack.nth_user_message, 1);
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Esc.into()))
|
||||
.await?;
|
||||
assert!(app.transcript_view.has_active_interaction());
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Esc.into()))
|
||||
.await?;
|
||||
assert_eq!(
|
||||
(
|
||||
app.transcript_view.has_active_interaction(),
|
||||
app.backtrack.overlay_preview_active
|
||||
),
|
||||
(false, true)
|
||||
);
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Esc.into()))
|
||||
.await?;
|
||||
assert!(!app.backtrack.overlay_preview_active);
|
||||
server.shutdown().await?;
|
||||
tui.set_owned_screen(/*owned*/ false)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn browsing_footer_adapts_to_width() -> Result<()> {
|
||||
let mut app = crate::app::test_support::make_test_app().await;
|
||||
attach_thread(&mut app, ThreadId::new());
|
||||
app.transcript_cells = vec![user_cell("first prompt"), user_cell("second prompt")];
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
tui.set_owned_screen(/*owned*/ true)?;
|
||||
app.handle_backtrack_esc_key(&mut tui);
|
||||
app.handle_backtrack_esc_key(&mut tui);
|
||||
for width in [100, 80, 60, 40, 20, 8] {
|
||||
let footer = app
|
||||
.prompt_navigation_footer(width)
|
||||
.expect("browsing footer");
|
||||
assert_eq!(footer.text.lines.len(), 1);
|
||||
assert!(footer.text.width() <= usize::from(width));
|
||||
}
|
||||
app.transcript_view.history = TranscriptHistoryState::Failed;
|
||||
app.render_owned_transcript(&mut tui, Size::new(/*width*/ 80, /*height*/ 12))?;
|
||||
assert!(
|
||||
buffer_text(crate::custom_terminal::test_support::last_rendered_buffer(
|
||||
&tui.terminal,
|
||||
))
|
||||
.contains("Retry history")
|
||||
);
|
||||
app.transcript_view.history = TranscriptHistoryState::Complete;
|
||||
app.cancel_transcript_browsing(&mut tui);
|
||||
tui.set_owned_screen(/*owned*/ false)?;
|
||||
app.handle_backtrack_esc_key(&mut tui);
|
||||
app.handle_backtrack_esc_key(&mut tui);
|
||||
let mut snapshots = Vec::new();
|
||||
for width in [80, 32] {
|
||||
let area = Rect::new(/*x*/ 0, /*y*/ 0, width, /*height*/ 8);
|
||||
let footer = app
|
||||
.prompt_navigation_footer(width.saturating_sub(/*rhs*/ 2))
|
||||
.expect("browsing footer");
|
||||
let Some(Overlay::Transcript(overlay)) = &mut app.overlay else {
|
||||
panic!("expected inline browsing");
|
||||
};
|
||||
overlay.browsing_footer = footer.text.lines.into_iter().next();
|
||||
let mut buffer = Buffer::empty(area);
|
||||
overlay.render(area, &mut buffer);
|
||||
snapshots.push(format!("{width} columns\n{}", buffer_text(&buffer)));
|
||||
}
|
||||
insta::assert_snapshot!("browsing_footer", snapshots.join("\n\n"));
|
||||
let Some(Overlay::Transcript(overlay)) = &mut app.overlay else {
|
||||
panic!("expected inline browsing");
|
||||
};
|
||||
overlay.set_history_state(TranscriptHistoryState::Failed);
|
||||
let footer = app.prompt_navigation_footer(/*width*/ 78);
|
||||
let Some(Overlay::Transcript(overlay)) = &mut app.overlay else {
|
||||
panic!("expected inline browsing");
|
||||
};
|
||||
overlay.browsing_footer = footer.and_then(|footer| footer.text.lines.into_iter().next());
|
||||
let area = Rect::new(
|
||||
/*x*/ 0, /*y*/ 0, /*width*/ 80, /*height*/ 8,
|
||||
);
|
||||
let mut buffer = Buffer::empty(area);
|
||||
overlay.render(area, &mut buffer);
|
||||
assert!(buffer_text(&buffer).contains("Retry history"));
|
||||
app.close_transcript_overlay(&mut tui);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn inline_browsing_is_compact_and_escape_restores_the_existing_overlay() -> Result<()> {
|
||||
let mut app = crate::app::test_support::make_test_app().await;
|
||||
attach_thread(&mut app, ThreadId::new());
|
||||
app.transcript_cells = vec![user_cell("first prompt"), user_cell("second prompt")];
|
||||
let mut server = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?;
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
app.open_transcript_overlay(&mut tui);
|
||||
for (key, expected_details, browsing) in [
|
||||
(KeyEvent::from(KeyCode::Esc), false, true),
|
||||
(
|
||||
KeyEvent::new(KeyCode::Char('t'), KeyModifiers::CONTROL),
|
||||
true,
|
||||
true,
|
||||
),
|
||||
(KeyEvent::from(KeyCode::Esc), true, false),
|
||||
] {
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(key))
|
||||
.await?;
|
||||
let Some(Overlay::Transcript(overlay)) = &app.overlay else {
|
||||
panic!("overlay must remain open")
|
||||
};
|
||||
assert_eq!(
|
||||
(overlay.is_detailed(), app.backtrack.overlay_preview_active),
|
||||
(expected_details, browsing)
|
||||
);
|
||||
}
|
||||
app.close_transcript_overlay(&mut tui);
|
||||
app.handle_backtrack_esc_key(&mut tui);
|
||||
app.handle_backtrack_esc_key(&mut tui);
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Esc.into()))
|
||||
.await?;
|
||||
assert!(app.overlay.is_none());
|
||||
server.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn browsing_details_use_the_remapped_chord_without_cancelling_preview() -> Result<()> {
|
||||
let mut app = crate::app::test_support::make_test_app().await;
|
||||
attach_thread(&mut app, ThreadId::new());
|
||||
app.transcript_cells = vec![
|
||||
user_cell("first prompt"),
|
||||
user_cell(&"second prompt\n".repeat(80)),
|
||||
];
|
||||
let config = toml::from_str(
|
||||
"[global]\nopen_transcript = [\"ctrl-x ctrl-t\", \"left f6\", \"enter f6\"]\ncopy = [\"ctrl-x ctrl-p\"]\n[pager]\nclose_transcript = [\"ctrl-x ctrl-t\"]\nscroll_up = []\nclose = [\"up ctrl-x\"]\npage_down = [\"ctrl-x ctrl-p\"]\njump_top = [\"ctrl-x ctrl-h\"]\n[composer]\nsubmit = []\n[editor]\nmove_left = []\ninsert_newline = []\n[vim_normal]\nmove_left = []",
|
||||
)?;
|
||||
app.keymap = RuntimeKeymap::from_config(&config).expect("valid transcript chord");
|
||||
let mut server = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?;
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
for owned in [true, false] {
|
||||
tui.set_owned_screen(owned)?;
|
||||
app.handle_backtrack_esc_key(&mut tui);
|
||||
app.handle_backtrack_esc_key(&mut tui);
|
||||
assert!(
|
||||
app.prompt_navigation_footer(/*width*/ 100)
|
||||
.expect("footer")
|
||||
.text
|
||||
.to_string()
|
||||
.contains("⌃x ⌃t")
|
||||
);
|
||||
for (keys, expected_details) in [
|
||||
(
|
||||
[
|
||||
KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL),
|
||||
KeyEvent::new(KeyCode::Char('t'), KeyModifiers::CONTROL),
|
||||
],
|
||||
true,
|
||||
),
|
||||
([KeyCode::Left.into(), KeyCode::F(6).into()], false),
|
||||
([KeyCode::Enter.into(), KeyCode::F(6).into()], true),
|
||||
] {
|
||||
for key in keys {
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(key))
|
||||
.await?;
|
||||
assert!(app.backtrack.overlay_preview_active);
|
||||
}
|
||||
let detailed = match &app.overlay {
|
||||
Some(Overlay::Transcript(overlay)) => overlay.is_detailed(),
|
||||
_ => app.transcript_view.is_detailed(),
|
||||
};
|
||||
assert_eq!(detailed, expected_details);
|
||||
}
|
||||
for completion in ['h', 'p'] {
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Draw)
|
||||
.await?;
|
||||
for code in ['x', completion] {
|
||||
app.handle_tui_event(
|
||||
&mut tui,
|
||||
&mut server,
|
||||
TuiEvent::Key(KeyEvent::new(KeyCode::Char(code), KeyModifiers::CONTROL)),
|
||||
)
|
||||
.await?;
|
||||
if code == 'x' {
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Draw)
|
||||
.await?;
|
||||
let text = buffer_text(
|
||||
crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal),
|
||||
);
|
||||
assert!(text.contains("page down"), "pending pager chord is visible");
|
||||
}
|
||||
}
|
||||
}
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Draw)
|
||||
.await?;
|
||||
let text = buffer_text(crate::custom_terminal::test_support::last_rendered_buffer(
|
||||
&tui.terminal,
|
||||
));
|
||||
assert!(
|
||||
!text.contains("first prompt"),
|
||||
"configured page-down moved the viewport"
|
||||
);
|
||||
assert!(text.contains("second prompt"));
|
||||
assert!(app.backtrack.overlay_preview_active);
|
||||
for code in [KeyCode::Char('h'), KeyCode::Right] {
|
||||
if let Some(Overlay::Transcript(overlay)) = &mut app.overlay {
|
||||
overlay.set_history_state(TranscriptHistoryState::LoadingBeginning);
|
||||
} else {
|
||||
app.transcript_view.history = TranscriptHistoryState::LoadingBeginning;
|
||||
}
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(code.into()))
|
||||
.await?;
|
||||
let state = match &app.overlay {
|
||||
Some(Overlay::Transcript(overlay)) => overlay.history_state(),
|
||||
_ => app.transcript_view.history,
|
||||
};
|
||||
assert_eq!(state, TranscriptHistoryState::LoadingOlder);
|
||||
}
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Up.into()))
|
||||
.await?;
|
||||
assert!(app.backtrack.overlay_preview_active);
|
||||
app.handle_tui_event(
|
||||
&mut tui,
|
||||
&mut server,
|
||||
TuiEvent::Key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL)),
|
||||
)
|
||||
.await?;
|
||||
assert!(!app.backtrack.overlay_preview_active);
|
||||
}
|
||||
server.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn browsing_requires_fresh_escape_presses_and_ignores_confirmation_repeats() -> Result<()> {
|
||||
let (mut app, mut events, _operations) = make_test_app_with_channels().await;
|
||||
attach_thread(&mut app, ThreadId::new());
|
||||
app.transcript_cells = vec![user_cell("first prompt"), user_cell("second prompt")];
|
||||
let mut server = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?;
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
tui.set_owned_screen(/*owned*/ true)?;
|
||||
app.transcript_view
|
||||
.set_presentation(/*detailed*/ true, HistoryRenderMode::Rich);
|
||||
app.chat_widget.apply_external_edit("draft".to_string());
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Esc.into()))
|
||||
.await?;
|
||||
assert!(!app.backtrack.overlay_preview_active);
|
||||
assert_eq!(app.chat_widget.composer_text_with_pending(), "draft");
|
||||
app.chat_widget.apply_external_edit(String::new());
|
||||
app.transcript_view
|
||||
.set_presentation(/*detailed*/ false, HistoryRenderMode::Rich);
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Esc.into()))
|
||||
.await?;
|
||||
app.handle_tui_event(
|
||||
&mut tui,
|
||||
&mut server,
|
||||
TuiEvent::Key(KeyEvent::new_with_kind(
|
||||
KeyCode::Esc,
|
||||
KeyModifiers::NONE,
|
||||
KeyEventKind::Repeat,
|
||||
)),
|
||||
)
|
||||
.await?;
|
||||
assert!(!app.backtrack.overlay_preview_active);
|
||||
for key in [KeyCode::PageUp, KeyCode::F(8)] {
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(key.into()))
|
||||
.await?;
|
||||
assert!(!app.backtrack.primed);
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Esc.into()))
|
||||
.await?;
|
||||
assert!(!app.backtrack.overlay_preview_active);
|
||||
}
|
||||
app.handle_tui_event(
|
||||
&mut tui,
|
||||
&mut server,
|
||||
TuiEvent::Mouse(crossterm::event::MouseEvent {
|
||||
kind: crossterm::event::MouseEventKind::Moved,
|
||||
column: 1,
|
||||
row: 1,
|
||||
modifiers: KeyModifiers::NONE,
|
||||
}),
|
||||
)
|
||||
.await?;
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Esc.into()))
|
||||
.await?;
|
||||
for (code, kind) in [
|
||||
(KeyCode::Esc, KeyEventKind::Repeat),
|
||||
(KeyCode::Enter, KeyEventKind::Repeat),
|
||||
(KeyCode::Enter, KeyEventKind::Release),
|
||||
] {
|
||||
app.handle_tui_event(
|
||||
&mut tui,
|
||||
&mut server,
|
||||
TuiEvent::Key(KeyEvent::new_with_kind(code, KeyModifiers::NONE, kind)),
|
||||
)
|
||||
.await?;
|
||||
assert!(app.backtrack.overlay_preview_active);
|
||||
}
|
||||
// Enter during history loading has no selected prompt to confirm.
|
||||
app.backtrack.nth_user_message = usize::MAX;
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Enter.into()))
|
||||
.await?;
|
||||
assert!(app.backtrack.overlay_preview_active);
|
||||
assert!(
|
||||
!std::iter::from_fn(|| events.try_recv().ok())
|
||||
.any(|event| matches!(event, AppEvent::RevertSessionForPromptEdit { .. }))
|
||||
);
|
||||
for (binding, keys) in [
|
||||
("f8", vec![KeyCode::F(8)]),
|
||||
("f8 v", vec![KeyCode::F(8), KeyCode::Char('v')]),
|
||||
] {
|
||||
app.keymap = RuntimeKeymap::from_config(&toml::from_str(&format!(
|
||||
"[chat]\ntoggle_voice = '{binding}'"
|
||||
))?)
|
||||
.expect("valid voice binding");
|
||||
let thread_id = app.chat_widget.thread_id().unwrap();
|
||||
crate::chatwidget::activate_voice_for_thread(&mut app.chat_widget, thread_id);
|
||||
for key in keys {
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(key.into()))
|
||||
.await?;
|
||||
}
|
||||
assert_eq!(
|
||||
(
|
||||
app.backtrack.overlay_preview_active,
|
||||
app.chat_widget.realtime_conversation_is_running()
|
||||
),
|
||||
(false, false)
|
||||
);
|
||||
for _ in 0..2 {
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Esc.into()))
|
||||
.await?;
|
||||
}
|
||||
assert!(app.backtrack.overlay_preview_active);
|
||||
}
|
||||
app.keymap = RuntimeKeymap::from_config(&toml::from_str(
|
||||
"[global]\nopen_external_editor = [\"f6 f7\"]",
|
||||
)?)
|
||||
.expect("valid editor chord");
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::F(6).into()))
|
||||
.await?;
|
||||
assert!(!app.backtrack.overlay_preview_active);
|
||||
assert!(app.key_chord_matcher.is_pending());
|
||||
app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::F(7).into()))
|
||||
.await?;
|
||||
assert_eq!(
|
||||
(
|
||||
app.backtrack.overlay_preview_active,
|
||||
app.chat_widget.external_editor_state()
|
||||
),
|
||||
(false, ExternalEditorState::Requested)
|
||||
);
|
||||
server.shutdown().await?;
|
||||
tui.set_owned_screen(/*owned*/ false)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn browsing_arrows_and_vim_keys_navigate_without_editing_the_draft() -> Result<()> {
|
||||
let mut app = crate::app::test_support::make_test_app().await;
|
||||
attach_thread(&mut app, ThreadId::new());
|
||||
app.transcript_cells = vec![
|
||||
user_cell("first prompt"),
|
||||
Arc::new(PlainHistoryCell::new(
|
||||
(0..30)
|
||||
.map(|row| format!("response row {row}").into())
|
||||
.collect(),
|
||||
)),
|
||||
user_cell("second prompt"),
|
||||
];
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
tui.set_owned_screen(/*owned*/ true)?;
|
||||
app.handle_backtrack_esc_key(&mut tui);
|
||||
app.handle_backtrack_esc_key(&mut tui);
|
||||
app.chat_widget
|
||||
.apply_external_edit("untouched draft".to_string());
|
||||
let size = Size::new(/*width*/ 80, /*height*/ 16);
|
||||
app.render_owned_transcript(&mut tui, size)?;
|
||||
let before = buffer_text(crate::custom_terminal::test_support::last_rendered_buffer(
|
||||
&tui.terminal,
|
||||
));
|
||||
for code in [KeyCode::Up, KeyCode::Char('k')] {
|
||||
assert!(app.handle_owned_backtrack_event(&mut tui, &TuiEvent::Key(code.into()))?);
|
||||
}
|
||||
app.render_owned_transcript(&mut tui, size)?;
|
||||
pretty_assertions::assert_ne!(
|
||||
buffer_text(crate::custom_terminal::test_support::last_rendered_buffer(
|
||||
&tui.terminal
|
||||
)),
|
||||
before
|
||||
);
|
||||
for (code, selected) in [
|
||||
(KeyCode::Down, 1),
|
||||
(KeyCode::Char('j'), 1),
|
||||
(KeyCode::Char('h'), 0),
|
||||
(KeyCode::Char('l'), 1),
|
||||
(KeyCode::Left, 0),
|
||||
(KeyCode::Right, 1),
|
||||
] {
|
||||
assert!(app.handle_owned_backtrack_event(&mut tui, &TuiEvent::Key(code.into()))?);
|
||||
assert_eq!(app.backtrack.nth_user_message, selected);
|
||||
}
|
||||
assert_eq!(
|
||||
app.chat_widget.composer_text_with_pending(),
|
||||
"untouched draft"
|
||||
);
|
||||
assert!(app.backtrack.overlay_preview_active);
|
||||
tui.set_owned_screen(/*owned*/ false)?;
|
||||
Ok(())
|
||||
}
|
||||
212
akode-rs/tui/src/app/owned_transcript_follow_tests.rs
Normal file
212
akode-rs/tui/src/app/owned_transcript_follow_tests.rs
Normal file
@@ -0,0 +1,212 @@
|
||||
//! The return control preserves composer geometry and draft across mouse navigation and resize.
|
||||
|
||||
use super::*;
|
||||
use crate::history_cell::PlainHistoryCell;
|
||||
use crossterm::event::MouseButton;
|
||||
use crossterm::event::MouseEvent;
|
||||
use crossterm::event::MouseEventKind;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[tokio::test]
|
||||
async fn follow_control_click_preserves_draft_caret_and_composer_geometry() -> Result<()> {
|
||||
let mut app = crate::app::test_support::make_test_app().await;
|
||||
app.local_settings.tui.animations = false;
|
||||
let mut server = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?;
|
||||
let mut tui = crate::tui::test_support::make_test_tui()?;
|
||||
tui.set_owned_screen(/*owned*/ true)?;
|
||||
app.chat_widget
|
||||
.apply_external_edit("draft stays here".to_string());
|
||||
app.transcript_cells = vec![Arc::new(PlainHistoryCell::new(
|
||||
(0..40)
|
||||
.map(|row| format!("transcript row {row}").into())
|
||||
.collect(),
|
||||
))];
|
||||
for (width, running) in [(80, false), (40, false), (80, true)] {
|
||||
if running {
|
||||
app.chat_widget.handle_server_notification(
|
||||
akode_app_server_protocol::ServerNotification::TurnStarted(
|
||||
akode_app_server_protocol::TurnStartedNotification {
|
||||
thread_id: ThreadId::new().to_string(),
|
||||
turn: akode_app_server_protocol::Turn {
|
||||
id: "turn".into(),
|
||||
root_turn_id: None,
|
||||
items_view: akode_app_server_protocol::TurnItemsView::Full,
|
||||
items: Vec::new(),
|
||||
status: akode_app_server_protocol::TurnStatus::InProgress,
|
||||
error: None,
|
||||
started_at: None,
|
||||
completed_at: None,
|
||||
duration_ms: None,
|
||||
},
|
||||
},
|
||||
),
|
||||
/*replay_kind*/ None,
|
||||
);
|
||||
}
|
||||
let size = Size::new(width, /*height*/ 12);
|
||||
tui.screen_size_for_event(&TuiEvent::Resize(size))?;
|
||||
app.transcript_view.jump_to_latest();
|
||||
let bottom = app.render_owned_transcript(&mut tui, size)?;
|
||||
let cursor = tui.terminal.last_known_cursor_pos;
|
||||
if running {
|
||||
let buffer = crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal);
|
||||
insta::assert_snapshot!(
|
||||
"running_without_composer_hint",
|
||||
crate::chatwidget::tests::helpers::normalize_snapshot_paths(
|
||||
super::tests::buffer_text(buffer)
|
||||
),
|
||||
);
|
||||
}
|
||||
app.transcript_view
|
||||
.scroll(&app.transcript_cells, /*rows*/ -10);
|
||||
tui.screen_size_for_event(&TuiEvent::Resize(size))?;
|
||||
app.render_owned_transcript(&mut tui, size)?;
|
||||
assert_eq!(tui.terminal.last_known_cursor_pos, cursor);
|
||||
let buffer = crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal);
|
||||
let scrolled = super::tests::buffer_text(buffer);
|
||||
let first_row = scrolled.lines().next().expect("visible transcript row");
|
||||
assert!(first_row.contains("transcript row"));
|
||||
let area = Rect::new(
|
||||
/*x*/ 4, /*y*/ 1, /*width*/ 30, /*height*/ 10,
|
||||
);
|
||||
let frames = tui.frame_requester();
|
||||
let mut painted = Default::default();
|
||||
tui.draw(size.height, |frame| {
|
||||
let prepared = app.prepare_conversation(frame.area(), Some(area), &frames);
|
||||
painted = app.paint_conversation(frame, &prepared);
|
||||
})?;
|
||||
app.finish_conversation(&mut tui, painted)?;
|
||||
let buffer = crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal);
|
||||
let resized = super::tests::buffer_text(buffer);
|
||||
assert_eq!(
|
||||
resized.lines().nth(usize::from(area.y)).map(str::trim),
|
||||
Some(first_row.trim())
|
||||
);
|
||||
assert!(resized.contains("draft stays here"));
|
||||
tui.screen_size_for_event(&TuiEvent::Resize(size))?;
|
||||
let mut painted = Default::default();
|
||||
tui.draw(size.height, |frame| {
|
||||
let prepared =
|
||||
app.prepare_conversation(frame.area(), /*conversation_inset*/ None, &frames);
|
||||
painted = app.paint_conversation(frame, &prepared);
|
||||
})?;
|
||||
app.finish_conversation(&mut tui, painted)?;
|
||||
for height in [24, 9, 8, 12] {
|
||||
let resized = Size::new(width, height);
|
||||
tui.screen_size_for_event(&TuiEvent::Resize(resized))?;
|
||||
app.render_owned_transcript(&mut tui, resized)?;
|
||||
let resized_cursor = tui.terminal.last_known_cursor_pos;
|
||||
assert_eq!(
|
||||
(
|
||||
app.chat_widget.composer_text_with_pending(),
|
||||
resized_cursor.x,
|
||||
resized.height - resized_cursor.y,
|
||||
app.transcript_view.is_following(),
|
||||
),
|
||||
(
|
||||
"draft stays here".to_string(),
|
||||
cursor.x,
|
||||
size.height - cursor.y,
|
||||
false
|
||||
)
|
||||
);
|
||||
if running && height == 9 {
|
||||
let buffer =
|
||||
crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal);
|
||||
insta::assert_snapshot!(
|
||||
"running_follow_control_short_terminal",
|
||||
crate::chatwidget::tests::helpers::normalize_snapshot_paths(
|
||||
super::tests::buffer_text(buffer)
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
let buffer = crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal);
|
||||
if running {
|
||||
insta::assert_snapshot!(
|
||||
"running_follow_control",
|
||||
crate::chatwidget::tests::helpers::normalize_snapshot_paths(
|
||||
super::tests::buffer_text(buffer)
|
||||
),
|
||||
);
|
||||
}
|
||||
let (column, row) = buffer
|
||||
.content()
|
||||
.iter()
|
||||
.position(|cell| cell.symbol() == "↓")
|
||||
.map(|index| buffer.pos_of(index))
|
||||
.expect("return control");
|
||||
for interrupted in [true, false] {
|
||||
for kind in [
|
||||
MouseEventKind::Down(MouseButton::Left),
|
||||
MouseEventKind::Up(MouseButton::Left),
|
||||
] {
|
||||
if interrupted && kind == MouseEventKind::Up(MouseButton::Left) {
|
||||
app.handle_owned_transcript_event(&mut tui, &mut server, &TuiEvent::FocusLost)?;
|
||||
tui.screen_size_for_event(&TuiEvent::Resize(size))?;
|
||||
app.render_owned_transcript(&mut tui, size)?;
|
||||
}
|
||||
tui.screen_size_for_event(&TuiEvent::Resize(size))?;
|
||||
let handled = app.handle_owned_transcript_event(
|
||||
&mut tui,
|
||||
&mut server,
|
||||
&TuiEvent::Mouse(MouseEvent {
|
||||
kind,
|
||||
column,
|
||||
row,
|
||||
modifiers: KeyModifiers::NONE,
|
||||
}),
|
||||
)?;
|
||||
assert!(handled || interrupted);
|
||||
}
|
||||
assert_eq!(app.transcript_view.is_following(), !interrupted);
|
||||
}
|
||||
tui.screen_size_for_event(&TuiEvent::Resize(size))?;
|
||||
assert_eq!(app.render_owned_transcript(&mut tui, size)?, bottom);
|
||||
assert_eq!(
|
||||
(
|
||||
app.chat_widget.composer_text_with_pending(),
|
||||
tui.terminal.last_known_cursor_pos
|
||||
),
|
||||
("draft stays here".to_string(), cursor)
|
||||
);
|
||||
assert!(app.chat_widget.queued_user_message_texts().is_empty());
|
||||
if running {
|
||||
app.transcript_view.show_copy_feedback(
|
||||
&Ok(crate::clipboard_copy::CopyStatus::Confirmed),
|
||||
/*characters*/ 24,
|
||||
);
|
||||
let mut snapshots = Vec::new();
|
||||
for (width, height) in [(80, 12), (18, 14), (6, 18), (80, 6)] {
|
||||
let size = Size::new(width, height);
|
||||
tui.screen_size_for_event(&TuiEvent::Resize(size))?;
|
||||
app.render_owned_transcript(&mut tui, size)?;
|
||||
let buffer =
|
||||
crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal);
|
||||
snapshots.push(format!(
|
||||
"{width} columns, {height} rows\n{}",
|
||||
super::tests::buffer_text(buffer)
|
||||
));
|
||||
}
|
||||
insta::assert_snapshot!(
|
||||
"running_copy_feedback_spacing",
|
||||
crate::chatwidget::tests::helpers::normalize_working_snapshot(
|
||||
snapshots.join("\n\n")
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
tui.set_owned_screen(/*owned*/ false)?;
|
||||
assert!(!app.handle_owned_transcript_event(
|
||||
&mut tui,
|
||||
&mut server,
|
||||
&TuiEvent::Mouse(MouseEvent {
|
||||
kind: MouseEventKind::Down(MouseButton::Left),
|
||||
column: 20,
|
||||
row: 7,
|
||||
modifiers: KeyModifiers::NONE,
|
||||
})
|
||||
)?);
|
||||
server.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
1023
akode-rs/tui/src/app/owned_transcript_input_tests.rs
Normal file
1023
akode-rs/tui/src/app/owned_transcript_input_tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
2276
akode-rs/tui/src/app/owned_transcript_tests.rs
Normal file
2276
akode-rs/tui/src/app/owned_transcript_tests.rs
Normal file
File diff suppressed because it is too large
Load Diff
39
akode-rs/tui/src/app/pane_motion.rs
Normal file
39
akode-rs/tui/src/app/pane_motion.rs
Normal file
@@ -0,0 +1,39 @@
|
||||
//! Slide the sidebar from its last painted width, independently of keyboard focus.
|
||||
|
||||
use std::time::Duration;
|
||||
use tokio::time::Instant;
|
||||
|
||||
use crate::tui::FrameRequester;
|
||||
use crate::tui::TARGET_FRAME_INTERVAL;
|
||||
|
||||
const SLIDE_DURATION: Duration = Duration::from_millis(180);
|
||||
|
||||
#[derive(Clone, Debug, Default)]
|
||||
pub(super) struct PaneMotion {
|
||||
fraction: f64,
|
||||
target: f64,
|
||||
slide: Option<(Instant, f64)>,
|
||||
}
|
||||
|
||||
impl PaneMotion {
|
||||
/// Without a frame requester, snap to the target immediately.
|
||||
pub(super) fn advance(&mut self, open: bool, frames: Option<FrameRequester>) -> f64 {
|
||||
let target = f64::from(open);
|
||||
if self.target != target {
|
||||
self.target = target;
|
||||
self.slide = Some((Instant::now(), self.fraction));
|
||||
}
|
||||
if let (Some((start, from)), Some(frames)) = (self.slide, frames) {
|
||||
let progress = start.elapsed().as_secs_f64() / SLIDE_DURATION.as_secs_f64();
|
||||
if progress < 1.0 && from != target {
|
||||
let eased = progress * progress * (3.0 - 2.0 * progress);
|
||||
self.fraction = from + (target - from) * eased;
|
||||
frames.schedule_frame_in(TARGET_FRAME_INTERVAL);
|
||||
return self.fraction;
|
||||
}
|
||||
}
|
||||
self.slide = None;
|
||||
self.fraction = target;
|
||||
target
|
||||
}
|
||||
}
|
||||
643
akode-rs/tui/src/app/pending_interactive_replay.rs
Normal file
643
akode-rs/tui/src/app/pending_interactive_replay.rs
Normal file
@@ -0,0 +1,643 @@
|
||||
//! Tracks unresolved interactive requests in the thread replay buffer.
|
||||
|
||||
use crate::app_command::AppCommand;
|
||||
use akode_app_server_protocol::RequestId as AppServerRequestId;
|
||||
use akode_app_server_protocol::ServerNotification;
|
||||
use akode_app_server_protocol::ServerRequest;
|
||||
use akode_app_server_protocol::ThreadItemPayload;
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) struct PendingInteractiveReplayState {
|
||||
// In arrival order so an answer addressed to a turn resolves its oldest question.
|
||||
requests: Vec<(AppServerRequestId, PendingInteractiveRequest)>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
enum PendingInteractiveRequest {
|
||||
ExecApproval {
|
||||
turn_id: String,
|
||||
approval_id: String,
|
||||
},
|
||||
PatchApproval {
|
||||
turn_id: String,
|
||||
item_id: String,
|
||||
},
|
||||
Elicitation {
|
||||
server_name: String,
|
||||
request_id: AppServerRequestId,
|
||||
},
|
||||
RequestPermissions {
|
||||
turn_id: String,
|
||||
item_id: String,
|
||||
},
|
||||
RequestUserInput {
|
||||
turn_id: String,
|
||||
item_id: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl PendingInteractiveRequest {
|
||||
fn from_server_request(request: &ServerRequest) -> Option<Self> {
|
||||
Some(match request {
|
||||
ServerRequest::CommandExecutionRequestApproval { params, .. } => Self::ExecApproval {
|
||||
turn_id: params.turn_id.clone(),
|
||||
approval_id: params
|
||||
.approval_id
|
||||
.as_ref()
|
||||
.unwrap_or(¶ms.item_id)
|
||||
.clone(),
|
||||
},
|
||||
ServerRequest::FileChangeRequestApproval { params, .. } => Self::PatchApproval {
|
||||
turn_id: params.turn_id.clone(),
|
||||
item_id: params.item_id.clone(),
|
||||
},
|
||||
ServerRequest::McpServerElicitationRequest { request_id, params } => {
|
||||
Self::Elicitation {
|
||||
server_name: params.server_name.clone(),
|
||||
request_id: request_id.clone(),
|
||||
}
|
||||
}
|
||||
ServerRequest::PermissionsRequestApproval { params, .. } => Self::RequestPermissions {
|
||||
turn_id: params.turn_id.clone(),
|
||||
item_id: params.item_id.clone(),
|
||||
},
|
||||
ServerRequest::ToolRequestUserInput { params, .. } => Self::RequestUserInput {
|
||||
turn_id: params.turn_id.clone(),
|
||||
item_id: params.item_id.clone(),
|
||||
},
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
fn turn_id(&self) -> Option<&str> {
|
||||
match self {
|
||||
Self::ExecApproval { turn_id, .. }
|
||||
| Self::PatchApproval { turn_id, .. }
|
||||
| Self::RequestPermissions { turn_id, .. }
|
||||
| Self::RequestUserInput { turn_id, .. } => Some(turn_id),
|
||||
Self::Elicitation { .. } => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl PendingInteractiveReplayState {
|
||||
pub(super) fn op_can_change_state<T>(op: T) -> bool
|
||||
where
|
||||
T: Into<AppCommand>,
|
||||
{
|
||||
matches!(
|
||||
op.into(),
|
||||
AppCommand::ExecApproval { .. }
|
||||
| AppCommand::PatchApproval { .. }
|
||||
| AppCommand::ResolveElicitation { .. }
|
||||
| AppCommand::ResolveUserVerification { .. }
|
||||
| AppCommand::RequestPermissionsResponse { .. }
|
||||
| AppCommand::UserInputAnswer { .. }
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn note_outbound_op<T>(&mut self, op: T)
|
||||
where
|
||||
T: Into<AppCommand>,
|
||||
{
|
||||
use PendingInteractiveRequest as Request;
|
||||
|
||||
let op = op.into();
|
||||
if let AppCommand::UserInputAnswer { id, .. } = &op {
|
||||
if let Some(index) = self.requests.iter().position(|(_, request)| {
|
||||
matches!(request, Request::RequestUserInput { turn_id, .. } if turn_id == id)
|
||||
}) {
|
||||
let (_, answered) = self.requests.remove(index);
|
||||
self.requests.retain(|(_, request)| request != &answered);
|
||||
}
|
||||
return;
|
||||
}
|
||||
self.requests.retain(|(_, request)| match (&op, request) {
|
||||
(AppCommand::ExecApproval { id, .. }, Request::ExecApproval { approval_id, .. }) => {
|
||||
id != approval_id
|
||||
}
|
||||
(AppCommand::PatchApproval { id, .. }, Request::PatchApproval { item_id, .. })
|
||||
| (
|
||||
AppCommand::RequestPermissionsResponse { id, .. },
|
||||
Request::RequestPermissions { item_id, .. },
|
||||
) => id != item_id,
|
||||
(
|
||||
AppCommand::ResolveElicitation {
|
||||
server_name,
|
||||
request_id,
|
||||
..
|
||||
}
|
||||
| AppCommand::ResolveUserVerification {
|
||||
server_name,
|
||||
request_id,
|
||||
..
|
||||
},
|
||||
Request::Elicitation {
|
||||
server_name: pending_server,
|
||||
request_id: pending_id,
|
||||
},
|
||||
) => server_name != pending_server || request_id != pending_id,
|
||||
_ => true,
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) fn note_server_request(&mut self, request: &ServerRequest) {
|
||||
if let Some(pending) = PendingInteractiveRequest::from_server_request(request)
|
||||
&& !self
|
||||
.requests
|
||||
.iter()
|
||||
.any(|(id, existing)| id == request.id() && existing == &pending)
|
||||
{
|
||||
self.requests.push((request.id().clone(), pending));
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn note_server_notification(&mut self, notification: &ServerNotification) {
|
||||
use PendingInteractiveRequest as Request;
|
||||
|
||||
match notification {
|
||||
ServerNotification::ItemStarted(notification) => {
|
||||
self.requests
|
||||
.retain(|(_, request)| match (¬ification.item.payload, request) {
|
||||
(
|
||||
ThreadItemPayload::CommandExecution { id, .. },
|
||||
Request::ExecApproval { approval_id, .. },
|
||||
) => id != approval_id,
|
||||
(
|
||||
ThreadItemPayload::FileChange { id, .. },
|
||||
Request::PatchApproval { item_id, .. },
|
||||
) => id != item_id,
|
||||
_ => true,
|
||||
});
|
||||
}
|
||||
ServerNotification::TurnCompleted(notification) => self
|
||||
.requests
|
||||
.retain(|(_, request)| request.turn_id() != Some(notification.turn.id.as_str())),
|
||||
ServerNotification::ServerRequestResolved(notification) => {
|
||||
if let Some(index) = self
|
||||
.requests
|
||||
.iter()
|
||||
.rposition(|(id, _)| id == ¬ification.request_id)
|
||||
{
|
||||
let (_, resolved) = self.requests.remove(index);
|
||||
self.requests.retain(|(_, request)| request != &resolved);
|
||||
}
|
||||
}
|
||||
ServerNotification::ThreadClosed(_) => self.requests.clear(),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn note_evicted_server_request(&mut self, request: &ServerRequest) {
|
||||
if let Some(evicted) = PendingInteractiveRequest::from_server_request(request) {
|
||||
self.requests.retain(|(_, request)| request != &evicted);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn should_replay_snapshot_request(&self, request: &ServerRequest) -> bool {
|
||||
PendingInteractiveRequest::from_server_request(request)
|
||||
.is_none_or(|pending| self.requests.iter().any(|(_, request)| request == &pending))
|
||||
}
|
||||
|
||||
pub(super) fn has_pending_thread_approvals(&self) -> bool {
|
||||
self.requests.iter().any(|(_, request)| {
|
||||
!matches!(request, PendingInteractiveRequest::RequestUserInput { .. })
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn has_pending_thread_user_input(&self) -> bool {
|
||||
self.requests.iter().any(|(_, request)| {
|
||||
matches!(request, PendingInteractiveRequest::RequestUserInput { .. })
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::super::ThreadBufferedEvent;
|
||||
use super::super::ThreadEventStore;
|
||||
use crate::app_command::AppCommand as Op;
|
||||
use akode_app_server_protocol::CommandExecutionApprovalDecision;
|
||||
use akode_app_server_protocol::CommandExecutionRequestApprovalParams;
|
||||
use akode_app_server_protocol::FileChangeRequestApprovalParams;
|
||||
use akode_app_server_protocol::McpElicitationObjectType;
|
||||
use akode_app_server_protocol::McpElicitationSchema;
|
||||
use akode_app_server_protocol::McpServerElicitationAction;
|
||||
use akode_app_server_protocol::McpServerElicitationRequest;
|
||||
use akode_app_server_protocol::McpServerElicitationRequestParams;
|
||||
use akode_app_server_protocol::RequestId as AppServerRequestId;
|
||||
use akode_app_server_protocol::ServerNotification;
|
||||
use akode_app_server_protocol::ServerRequest;
|
||||
use akode_app_server_protocol::ServerRequestResolvedNotification;
|
||||
use akode_app_server_protocol::ThreadClosedNotification;
|
||||
use akode_app_server_protocol::ToolRequestUserInputParams;
|
||||
use akode_app_server_protocol::ToolRequestUserInputResponse;
|
||||
use akode_app_server_protocol::Turn;
|
||||
use akode_app_server_protocol::TurnCompletedNotification;
|
||||
use akode_app_server_protocol::TurnStatus;
|
||||
use akode_utils_absolute_path::test_support::PathBufExt;
|
||||
use akode_utils_absolute_path::test_support::test_path_buf;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::HashMap;
|
||||
|
||||
fn request_user_input_request(call_id: &str, turn_id: &str) -> ServerRequest {
|
||||
ServerRequest::ToolRequestUserInput {
|
||||
request_id: AppServerRequestId::Integer(1),
|
||||
params: ToolRequestUserInputParams {
|
||||
thread_id: "thread-1".to_string(),
|
||||
turn_id: turn_id.to_string(),
|
||||
item_id: call_id.to_string(),
|
||||
questions: Vec::new(),
|
||||
is_blocking: true,
|
||||
auto_resolution_ms: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn exec_approval_request(
|
||||
call_id: &str,
|
||||
approval_id: Option<&str>,
|
||||
turn_id: &str,
|
||||
) -> ServerRequest {
|
||||
ServerRequest::CommandExecutionRequestApproval {
|
||||
request_id: AppServerRequestId::Integer(2),
|
||||
params: CommandExecutionRequestApprovalParams {
|
||||
kind: Default::default(),
|
||||
thread_id: "thread-1".to_string(),
|
||||
turn_id: turn_id.to_string(),
|
||||
item_id: call_id.to_string(),
|
||||
started_at_ms: 0,
|
||||
approval_id: approval_id.map(str::to_string),
|
||||
environment_id: None,
|
||||
reason: None,
|
||||
network_approval_context: None,
|
||||
command: Some("echo hi".to_string()),
|
||||
cwd: Some(test_path_buf("/tmp").abs().into()),
|
||||
command_actions: None,
|
||||
additional_permissions: None,
|
||||
proposed_execpolicy_amendment: None,
|
||||
proposed_network_policy_amendments: None,
|
||||
available_decisions: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn patch_approval_request(call_id: &str, turn_id: &str) -> ServerRequest {
|
||||
ServerRequest::FileChangeRequestApproval {
|
||||
request_id: AppServerRequestId::Integer(3),
|
||||
params: FileChangeRequestApprovalParams {
|
||||
thread_id: "thread-1".to_string(),
|
||||
turn_id: turn_id.to_string(),
|
||||
item_id: call_id.to_string(),
|
||||
started_at_ms: 0,
|
||||
reason: None,
|
||||
grant_root: None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn elicitation_request(server_name: &str, request_id: &str, turn_id: &str) -> ServerRequest {
|
||||
ServerRequest::McpServerElicitationRequest {
|
||||
request_id: AppServerRequestId::String(request_id.to_string()),
|
||||
params: McpServerElicitationRequestParams {
|
||||
thread_id: "thread-1".to_string(),
|
||||
turn_id: Some(turn_id.to_string()),
|
||||
server_name: server_name.to_string(),
|
||||
request: McpServerElicitationRequest::Form {
|
||||
meta: None,
|
||||
message: "Please confirm".to_string(),
|
||||
requested_schema: McpElicitationSchema {
|
||||
schema_uri: None,
|
||||
type_: McpElicitationObjectType::Object,
|
||||
properties: BTreeMap::new(),
|
||||
required: None,
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn turn_completed(turn_id: &str) -> ServerNotification {
|
||||
ServerNotification::TurnCompleted(TurnCompletedNotification {
|
||||
thread_id: "thread-1".to_string(),
|
||||
turn: Turn {
|
||||
id: turn_id.to_string(),
|
||||
root_turn_id: None,
|
||||
items_view: akode_app_server_protocol::TurnItemsView::Full,
|
||||
items: Vec::new(),
|
||||
status: TurnStatus::Completed,
|
||||
error: None,
|
||||
started_at: None,
|
||||
completed_at: Some(0),
|
||||
duration_ms: Some(1),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
fn thread_closed() -> ServerNotification {
|
||||
ServerNotification::ThreadClosed(ThreadClosedNotification {
|
||||
thread_id: "thread-1".to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
fn request_resolved(request_id: AppServerRequestId) -> ServerNotification {
|
||||
ServerNotification::ServerRequestResolved(ServerRequestResolvedNotification {
|
||||
thread_id: "thread-1".to_string(),
|
||||
request_id,
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_event_snapshot_keeps_pending_request_user_input() {
|
||||
let mut store = ThreadEventStore::new(/*capacity*/ 8);
|
||||
let request = request_user_input_request("call-1", "turn-1");
|
||||
|
||||
store.push_request(request);
|
||||
|
||||
let snapshot = store.snapshot();
|
||||
assert_eq!(snapshot.events.len(), 1);
|
||||
assert!(matches!(
|
||||
snapshot.events.first(),
|
||||
Some(ThreadBufferedEvent::Request(request))
|
||||
if matches!(
|
||||
request.as_ref(),
|
||||
ServerRequest::ToolRequestUserInput { params, .. }
|
||||
if params.item_id == "call-1"
|
||||
)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_event_snapshot_drops_resolved_request_user_input_after_user_answer() {
|
||||
let mut store = ThreadEventStore::new(/*capacity*/ 8);
|
||||
store.push_request(request_user_input_request("call-1", "turn-1"));
|
||||
|
||||
store.note_outbound_op(&Op::UserInputAnswer {
|
||||
id: "turn-1".to_string(),
|
||||
response: ToolRequestUserInputResponse {
|
||||
answers: HashMap::new(),
|
||||
},
|
||||
});
|
||||
|
||||
let snapshot = store.snapshot();
|
||||
assert!(
|
||||
snapshot.events.is_empty(),
|
||||
"resolved request_user_input prompt should not replay on thread switch"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_event_snapshot_drops_resolved_request_user_input_after_server_resolution() {
|
||||
let mut store = ThreadEventStore::new(/*capacity*/ 8);
|
||||
store.push_request(request_user_input_request("call-1", "turn-1"));
|
||||
|
||||
store.push_notification(request_resolved(AppServerRequestId::Integer(1)));
|
||||
|
||||
let snapshot = store.snapshot();
|
||||
assert!(
|
||||
snapshot.events.iter().all(|event| {
|
||||
!matches!(
|
||||
event,
|
||||
ThreadBufferedEvent::Request(request)
|
||||
if matches!(
|
||||
request.as_ref(),
|
||||
ServerRequest::ToolRequestUserInput { .. }
|
||||
)
|
||||
)
|
||||
}),
|
||||
"server-resolved request_user_input prompt should not replay on thread switch"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_event_snapshot_drops_resolved_exec_approval_after_outbound_approval_id() {
|
||||
let mut store = ThreadEventStore::new(/*capacity*/ 8);
|
||||
store.push_request(exec_approval_request(
|
||||
"call-1",
|
||||
Some("approval-1"),
|
||||
"turn-1",
|
||||
));
|
||||
|
||||
store.note_outbound_op(&Op::ExecApproval {
|
||||
id: "approval-1".to_string(),
|
||||
turn_id: Some("turn-1".to_string()),
|
||||
decision: CommandExecutionApprovalDecision::Accept,
|
||||
});
|
||||
|
||||
let snapshot = store.snapshot();
|
||||
assert!(
|
||||
snapshot.events.is_empty(),
|
||||
"resolved exec approval prompt should not replay on thread switch"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_event_snapshot_drops_resolved_exec_approval_after_server_resolution() {
|
||||
let mut store = ThreadEventStore::new(/*capacity*/ 8);
|
||||
store.push_request(exec_approval_request(
|
||||
"call-1",
|
||||
Some("approval-1"),
|
||||
"turn-1",
|
||||
));
|
||||
|
||||
store.push_notification(request_resolved(AppServerRequestId::Integer(2)));
|
||||
|
||||
let snapshot = store.snapshot();
|
||||
assert!(
|
||||
snapshot.events.iter().all(|event| {
|
||||
!matches!(
|
||||
event,
|
||||
ThreadBufferedEvent::Request(request)
|
||||
if matches!(
|
||||
request.as_ref(),
|
||||
ServerRequest::CommandExecutionRequestApproval { .. }
|
||||
)
|
||||
)
|
||||
}),
|
||||
"server-resolved exec approval prompt should not replay on thread switch"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_event_snapshot_drops_answered_request_user_input_for_multi_prompt_turn() {
|
||||
let mut store = ThreadEventStore::new(/*capacity*/ 8);
|
||||
store.push_request(request_user_input_request("call-1", "turn-1"));
|
||||
|
||||
store.note_outbound_op(&Op::UserInputAnswer {
|
||||
id: "turn-1".to_string(),
|
||||
response: ToolRequestUserInputResponse {
|
||||
answers: HashMap::new(),
|
||||
},
|
||||
});
|
||||
|
||||
store.push_request(request_user_input_request("call-2", "turn-1"));
|
||||
|
||||
let snapshot = store.snapshot();
|
||||
assert_eq!(snapshot.events.len(), 1);
|
||||
assert!(matches!(
|
||||
snapshot.events.first(),
|
||||
Some(ThreadBufferedEvent::Request(request))
|
||||
if matches!(
|
||||
request.as_ref(),
|
||||
ServerRequest::ToolRequestUserInput { params, .. }
|
||||
if params.item_id == "call-2"
|
||||
)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_event_snapshot_keeps_newer_request_user_input_pending_when_same_turn_has_queue() {
|
||||
let mut store = ThreadEventStore::new(/*capacity*/ 8);
|
||||
store.push_request(request_user_input_request("call-1", "turn-1"));
|
||||
store.push_request(request_user_input_request("call-2", "turn-1"));
|
||||
|
||||
store.note_outbound_op(&Op::UserInputAnswer {
|
||||
id: "turn-1".to_string(),
|
||||
response: ToolRequestUserInputResponse {
|
||||
answers: HashMap::new(),
|
||||
},
|
||||
});
|
||||
|
||||
let snapshot = store.snapshot();
|
||||
assert_eq!(snapshot.events.len(), 1);
|
||||
assert!(matches!(
|
||||
snapshot.events.first(),
|
||||
Some(ThreadBufferedEvent::Request(request))
|
||||
if matches!(
|
||||
request.as_ref(),
|
||||
ServerRequest::ToolRequestUserInput { params, .. }
|
||||
if params.item_id == "call-2"
|
||||
)
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_event_snapshot_drops_resolved_patch_approval_after_outbound_approval() {
|
||||
let mut store = ThreadEventStore::new(/*capacity*/ 8);
|
||||
store.push_request(patch_approval_request("call-1", "turn-1"));
|
||||
|
||||
store.note_outbound_op(&Op::PatchApproval {
|
||||
id: "call-1".to_string(),
|
||||
decision: akode_app_server_protocol::FileChangeApprovalDecision::Accept,
|
||||
});
|
||||
|
||||
let snapshot = store.snapshot();
|
||||
assert!(
|
||||
snapshot.events.is_empty(),
|
||||
"resolved patch approval prompt should not replay on thread switch"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_event_snapshot_drops_pending_approvals_when_turn_completes() {
|
||||
let mut store = ThreadEventStore::new(/*capacity*/ 8);
|
||||
store.push_request(exec_approval_request(
|
||||
"exec-call-1",
|
||||
Some("approval-1"),
|
||||
"turn-1",
|
||||
));
|
||||
store.push_request(patch_approval_request("patch-call-1", "turn-1"));
|
||||
store.push_notification(turn_completed("turn-1"));
|
||||
|
||||
let snapshot = store.snapshot();
|
||||
assert!(snapshot.events.iter().all(|event| {
|
||||
!matches!(
|
||||
event,
|
||||
ThreadBufferedEvent::Request(request)
|
||||
if matches!(
|
||||
request.as_ref(),
|
||||
ServerRequest::CommandExecutionRequestApproval { .. }
|
||||
| ServerRequest::FileChangeRequestApproval { .. }
|
||||
)
|
||||
)
|
||||
}));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_event_snapshot_drops_resolved_elicitation_after_outbound_resolution() {
|
||||
let request_id = AppServerRequestId::String("request-1".to_string());
|
||||
for response in [
|
||||
Op::ResolveElicitation {
|
||||
server_name: "server-1".to_string(),
|
||||
request_id: request_id.clone(),
|
||||
decision: McpServerElicitationAction::Accept,
|
||||
content: None,
|
||||
meta: None,
|
||||
},
|
||||
Op::ResolveUserVerification {
|
||||
server_name: "server-1".to_string(),
|
||||
request_id,
|
||||
response: crate::app_command::UserVerificationResponse::Cancel,
|
||||
},
|
||||
] {
|
||||
let mut store = ThreadEventStore::new(/*capacity*/ 8);
|
||||
let mut request = elicitation_request("server-1", "request-1", "turn-1");
|
||||
if matches!(&response, Op::ResolveUserVerification { .. })
|
||||
&& let ServerRequest::McpServerElicitationRequest { params, .. } = &mut request
|
||||
{
|
||||
params.request = McpServerElicitationRequest::UserVerification {
|
||||
meta: None,
|
||||
title: "Verify".to_string(),
|
||||
description: "Approve deployment".to_string(),
|
||||
challenge: "AQID".to_string(),
|
||||
};
|
||||
}
|
||||
store.push_request(request);
|
||||
assert_eq!(store.snapshot().events.len(), 1);
|
||||
store.note_outbound_op(&response);
|
||||
assert!(
|
||||
store.snapshot().events.is_empty(),
|
||||
"resolved elicitation prompt should not replay on thread switch"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_event_store_reports_pending_thread_approvals() {
|
||||
let mut store = ThreadEventStore::new(/*capacity*/ 8);
|
||||
assert_eq!(store.has_pending_thread_approvals(), false);
|
||||
|
||||
store.push_request(exec_approval_request(
|
||||
"call-1", /*approval_id*/ None, "turn-1",
|
||||
));
|
||||
|
||||
assert_eq!(store.has_pending_thread_approvals(), true);
|
||||
|
||||
store.note_outbound_op(&Op::ExecApproval {
|
||||
id: "call-1".to_string(),
|
||||
turn_id: Some("turn-1".to_string()),
|
||||
decision: CommandExecutionApprovalDecision::Accept,
|
||||
});
|
||||
|
||||
assert_eq!(store.has_pending_thread_approvals(), false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn request_user_input_does_not_count_as_pending_thread_approval() {
|
||||
let mut store = ThreadEventStore::new(/*capacity*/ 8);
|
||||
store.push_request(request_user_input_request("call-1", "turn-1"));
|
||||
|
||||
assert_eq!(store.has_pending_thread_approvals(), false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn thread_event_snapshot_drops_pending_requests_when_thread_closes() {
|
||||
let mut store = ThreadEventStore::new(/*capacity*/ 8);
|
||||
store.push_request(exec_approval_request(
|
||||
"call-1", /*approval_id*/ None, "turn-1",
|
||||
));
|
||||
store.push_notification(thread_closed());
|
||||
|
||||
assert!(store.snapshot().events.iter().all(|event| {
|
||||
!matches!(
|
||||
event,
|
||||
ThreadBufferedEvent::Request(request)
|
||||
if matches!(
|
||||
request.as_ref(),
|
||||
ServerRequest::CommandExecutionRequestApproval { .. }
|
||||
)
|
||||
)
|
||||
}));
|
||||
}
|
||||
}
|
||||
21
akode-rs/tui/src/app/permission_shortcuts.rs
Normal file
21
akode-rs/tui/src/app/permission_shortcuts.rs
Normal file
@@ -0,0 +1,21 @@
|
||||
//! Route session-only permission shortcuts through the shared selection flow.
|
||||
|
||||
use super::*;
|
||||
|
||||
impl App {
|
||||
pub(super) async fn apply_permission_shortcut(
|
||||
&mut self,
|
||||
app_server: &mut AppServerSession,
|
||||
thread_id: ThreadId,
|
||||
selection: PermissionProfileSelection,
|
||||
) {
|
||||
if self.current_displayed_thread_id() != Some(thread_id)
|
||||
|| self.chat_widget.thread_id() != Some(thread_id)
|
||||
{
|
||||
self.chat_widget.complete_permission_shortcut(thread_id);
|
||||
return;
|
||||
}
|
||||
self.select_permission_profile(app_server, selection).await;
|
||||
self.chat_widget.complete_permission_shortcut(thread_id);
|
||||
}
|
||||
}
|
||||
219
akode-rs/tui/src/app/pets.rs
Normal file
219
akode-rs/tui/src/app/pets.rs
Normal file
@@ -0,0 +1,219 @@
|
||||
//! App-level handlers for ambient terminal pet events.
|
||||
|
||||
use super::*;
|
||||
|
||||
impl App {
|
||||
pub(super) fn draw_pet_images(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
screen_size: Size,
|
||||
rendered_area: Rect,
|
||||
) -> Result<()> {
|
||||
if self.chat_widget.ambient_pet_image_enabled() {
|
||||
let ambient_pet_area = self.conversation_area(screen_size.into());
|
||||
let request = self
|
||||
.chat_widget
|
||||
.ambient_pet_draw(ambient_pet_area, rendered_area.bottom())
|
||||
.filter(|pet| {
|
||||
self.conversation_frame
|
||||
.leader_hud
|
||||
.is_none_or(|hud| !hud.intersects(pet.area()))
|
||||
});
|
||||
if let Err(err) = tui.draw_ambient_pet_image(request) {
|
||||
self.handle_ambient_pet_image_render_error(tui, err)?;
|
||||
}
|
||||
}
|
||||
if let Some(request) = self.chat_widget.pet_picker_preview_draw() {
|
||||
if let Err(err) = tui.draw_pet_picker_preview_image(Some(request)) {
|
||||
self.handle_pet_picker_preview_image_render_error(tui, err)?;
|
||||
}
|
||||
} else if self.chat_widget.should_clear_pet_picker_preview_image()
|
||||
&& let Err(err) = tui.draw_pet_picker_preview_image(/*request*/ None)
|
||||
{
|
||||
self.handle_pet_picker_preview_image_render_error(tui, err)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn disable_ambient_pet_before_shutdown(&mut self, tui: &mut tui::Tui) -> Result<()> {
|
||||
self.chat_widget.disable_ambient_pet_for_session();
|
||||
if let Err(clear_err) = tui.clear_ambient_pet_image() {
|
||||
match clear_err {
|
||||
crate::pets::PetImageRenderError::Terminal(err) => return Err(err.into()),
|
||||
crate::pets::PetImageRenderError::Asset(err) => {
|
||||
tracing::warn!(
|
||||
error = %err,
|
||||
"failed to clear ambient pet image before shutdown feedback"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn handle_ambient_pet_image_render_error(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
err: crate::pets::PetImageRenderError,
|
||||
) -> Result<()> {
|
||||
match err {
|
||||
crate::pets::PetImageRenderError::Terminal(err) => Err(err.into()),
|
||||
crate::pets::PetImageRenderError::Asset(err) => {
|
||||
tracing::warn!(
|
||||
error = %err,
|
||||
"failed to render ambient pet image; disabling pet for session"
|
||||
);
|
||||
self.chat_widget.disable_ambient_pet_for_session();
|
||||
if let Err(clear_err) = tui.clear_ambient_pet_image() {
|
||||
match clear_err {
|
||||
crate::pets::PetImageRenderError::Terminal(err) => return Err(err.into()),
|
||||
crate::pets::PetImageRenderError::Asset(err) => {
|
||||
tracing::warn!(
|
||||
error = %err,
|
||||
"failed to clear ambient pet image after render failure"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn handle_pet_picker_preview_image_render_error(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
err: crate::pets::PetImageRenderError,
|
||||
) -> Result<()> {
|
||||
match err {
|
||||
crate::pets::PetImageRenderError::Terminal(err) => Err(err.into()),
|
||||
crate::pets::PetImageRenderError::Asset(err) => {
|
||||
tracing::warn!(error = %err, "failed to render pet picker preview image");
|
||||
self.chat_widget
|
||||
.fail_pet_picker_preview_render(err.to_string());
|
||||
if let Err(clear_err) = tui.draw_pet_picker_preview_image(/*request*/ None) {
|
||||
match clear_err {
|
||||
crate::pets::PetImageRenderError::Terminal(err) => return Err(err.into()),
|
||||
crate::pets::PetImageRenderError::Asset(err) => {
|
||||
tracing::warn!(
|
||||
error = %err,
|
||||
"failed to clear pet picker preview image after render failure"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn handle_pet_selected(&mut self, tui: &mut tui::Tui, pet_id: String) {
|
||||
let request_id = self.chat_widget.show_pet_selection_loading_popup();
|
||||
tui.frame_requester().schedule_frame();
|
||||
let codex_home = self.local_settings.codex_home.clone();
|
||||
let frame_requester = tui.frame_requester();
|
||||
let animations_enabled = self.local_settings.tui.animations;
|
||||
let tx = self.app_event_tx.clone();
|
||||
std::mem::drop(tokio::spawn(async move {
|
||||
let result = crate::pets::load_pet_with_assets(
|
||||
pet_id.clone(),
|
||||
codex_home,
|
||||
frame_requester,
|
||||
animations_enabled,
|
||||
)
|
||||
.await
|
||||
.map(Some)
|
||||
.map_err(|err| err.to_string());
|
||||
tx.send(AppEvent::PetSelectionLoaded {
|
||||
request_id,
|
||||
pet_id,
|
||||
result,
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
pub(super) async fn handle_pet_disabled(&mut self, tui: &mut tui::Tui) {
|
||||
let edit = crate::legacy_core::config::edit::tui_pet_edit(crate::pets::DISABLED_PET_ID);
|
||||
let apply_result = ConfigEditsBuilder::new(&self.local_settings.codex_home)
|
||||
.with_edits([edit])
|
||||
.apply()
|
||||
.await;
|
||||
match apply_result {
|
||||
Ok(()) => {
|
||||
self.sync_tui_pet_disabled();
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
Err(err) => {
|
||||
self.chat_widget
|
||||
.add_error_message(format!("Failed to disable pets: {err}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn handle_pet_preview_loaded(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
request_id: u64,
|
||||
result: Result<crate::pets::AmbientPet, String>,
|
||||
) {
|
||||
self.chat_widget
|
||||
.finish_pet_picker_preview_load(request_id, result);
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
|
||||
pub(super) async fn handle_pet_selection_loaded(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
request_id: u64,
|
||||
pet_id: String,
|
||||
result: Result<Option<crate::pets::AmbientPet>, String>,
|
||||
) -> Result<AppRunControl> {
|
||||
if !self
|
||||
.chat_widget
|
||||
.finish_pet_selection_loading_popup(request_id)
|
||||
{
|
||||
return Ok(AppRunControl::Continue);
|
||||
}
|
||||
match result {
|
||||
Ok(ambient_pet) => {
|
||||
let edit = crate::legacy_core::config::edit::tui_pet_edit(&pet_id);
|
||||
match ConfigEditsBuilder::new(&self.local_settings.codex_home)
|
||||
.with_edits([edit])
|
||||
.apply()
|
||||
.await
|
||||
{
|
||||
Ok(()) => {
|
||||
self.local_settings.tui.pet = Some(pet_id.clone());
|
||||
self.chat_widget
|
||||
.set_tui_pet_loaded(Some(pet_id), ambient_pet);
|
||||
}
|
||||
Err(err) => {
|
||||
self.chat_widget
|
||||
.add_error_message(format!("Failed to save pet selection: {err}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(err) => {
|
||||
self.chat_widget
|
||||
.add_error_message(format!("Failed to load pet: {err}"));
|
||||
}
|
||||
}
|
||||
tui.frame_requester().schedule_frame();
|
||||
Ok(AppRunControl::Continue)
|
||||
}
|
||||
|
||||
pub(super) fn handle_configured_pet_loaded(
|
||||
&mut self,
|
||||
tui: &mut tui::Tui,
|
||||
generation: crate::chatwidget::ConfiguredPetLoadGeneration,
|
||||
pet_id: String,
|
||||
result: Result<Option<crate::pets::AmbientPet>, String>,
|
||||
) {
|
||||
if self
|
||||
.chat_widget
|
||||
.finish_configured_pet_load(generation, pet_id, result)
|
||||
{
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
}
|
||||
}
|
||||
301
akode-rs/tui/src/app/platform_actions.rs
Normal file
301
akode-rs/tui/src/app/platform_actions.rs
Normal file
@@ -0,0 +1,301 @@
|
||||
//! Platform-specific app actions and small global shortcuts.
|
||||
//!
|
||||
//! This module owns platform state used by `App`, the side-conversation return shortcut predicate,
|
||||
//! and Windows sandbox helper actions that are compiled only on Windows.
|
||||
|
||||
use super::*;
|
||||
#[cfg(all(test, not(target_os = "windows")))]
|
||||
use crate::app_event::WindowsSandboxEnableMode;
|
||||
#[cfg(target_os = "windows")]
|
||||
use akode_app_server_protocol::WindowsSandboxSetupMode;
|
||||
#[cfg(any(target_os = "windows", test))]
|
||||
use akode_utils_approval_presets::ApprovalPreset;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(crate) enum WindowsSandboxHost {
|
||||
Local,
|
||||
Mixed,
|
||||
Remote,
|
||||
Unknown,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct WindowsSandboxState {
|
||||
pub(super) setup_started_at: Option<Instant>,
|
||||
#[cfg_attr(not(any(target_os = "windows", test)), allow(dead_code))]
|
||||
pub(super) prompt_after_trust: bool,
|
||||
#[cfg(any(target_os = "windows", test))]
|
||||
pub(super) pending_setup: Option<(
|
||||
WindowsSandboxEnableMode,
|
||||
ApprovalPreset,
|
||||
Option<PermissionProfileSelection>,
|
||||
)>,
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
pub(super) async fn windows_sandbox_ready(app_server: &mut AppServerSession) -> bool {
|
||||
let request_id = app_server.next_request_id();
|
||||
matches!(
|
||||
tokio::time::timeout(
|
||||
Duration::from_secs(5),
|
||||
app_server
|
||||
.request_handle()
|
||||
.request_typed(ClientRequest::WindowsSandboxReadiness {
|
||||
request_id,
|
||||
params: None,
|
||||
}),
|
||||
)
|
||||
.await,
|
||||
Ok(Ok(
|
||||
akode_app_server_protocol::WindowsSandboxReadinessResponse {
|
||||
status: akode_app_server_protocol::WindowsSandboxReadiness::Ready,
|
||||
}
|
||||
))
|
||||
)
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub(super) fn windows_sandbox_host(&self) -> WindowsSandboxHost {
|
||||
if self.app_server_target.uses_remote_workspace() {
|
||||
WindowsSandboxHost::Remote
|
||||
} else {
|
||||
self.chat_widget.windows_sandbox_host
|
||||
}
|
||||
}
|
||||
|
||||
/// A local app server owns setup for both embedded and daemon connections.
|
||||
pub(super) fn windows_sandbox_setup_is_local(&self) -> bool {
|
||||
self.chat_widget.windows_sandbox_local_server
|
||||
&& self.windows_sandbox_host() == WindowsSandboxHost::Local
|
||||
}
|
||||
|
||||
pub(super) fn windows_sandbox_blocks_thread_switch(&self) -> bool {
|
||||
#[cfg(any(target_os = "windows", test))]
|
||||
{
|
||||
self.windows_sandbox_setup_is_local()
|
||||
&& (self.windows_sandbox.pending_setup.is_some()
|
||||
|| self.windows_sandbox.setup_started_at.is_some()
|
||||
|| self.chat_widget.initial_user_message.is_some()
|
||||
&& self.chat_widget.windows_sandbox_config.requires_elevated()
|
||||
&& !self.chat_widget.windows_sandbox_elevated_setup_complete)
|
||||
}
|
||||
#[cfg(not(any(target_os = "windows", test)))]
|
||||
{
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "windows", test))]
|
||||
pub(super) async fn refresh_windows_sandbox_for_thread(
|
||||
&mut self,
|
||||
app_server: &mut AppServerSession,
|
||||
thread_id: ThreadId,
|
||||
) {
|
||||
if self.chat_widget.thread_id() == Some(thread_id)
|
||||
&& !self.app_server_target.uses_remote_workspace()
|
||||
&& self.refresh_windows_sandbox_config(app_server).await
|
||||
{
|
||||
#[cfg(target_os = "windows")]
|
||||
if self.windows_sandbox_setup_is_local()
|
||||
&& self.chat_widget.windows_sandbox_config.requires_elevated()
|
||||
&& !self.chat_widget.windows_sandbox_elevated_setup_complete
|
||||
{
|
||||
self.chat_widget.windows_sandbox_elevated_setup_complete =
|
||||
windows_sandbox_ready(app_server).await;
|
||||
}
|
||||
let show_nux = std::mem::take(&mut self.windows_sandbox.prompt_after_trust)
|
||||
&& !self.chat_widget.windows_sandbox_config.is_enabled()
|
||||
|| self.chat_widget.windows_sandbox_config.requires_elevated();
|
||||
if self.windows_sandbox_setup_is_local() {
|
||||
self.chat_widget.maybe_prompt_windows_sandbox_enable(
|
||||
show_nux && !self.chat_widget.windows_sandbox_elevated_setup_complete,
|
||||
);
|
||||
} else if self.windows_sandbox_host() == WindowsSandboxHost::Mixed && show_nux {
|
||||
self.app_event_tx.send(AppEvent::InsertHistoryCell(Box::new(
|
||||
history_cell::StartupWarningsCell::new(vec![
|
||||
"Windows sandbox setup is unavailable when local and remote executors are configured together."
|
||||
.to_string(),
|
||||
]),
|
||||
)));
|
||||
}
|
||||
self.chat_widget.submit_initial_user_message_if_pending();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "windows", test))]
|
||||
pub(super) async fn refresh_windows_sandbox_config(
|
||||
&mut self,
|
||||
app_server: &AppServerSession,
|
||||
) -> bool {
|
||||
match crate::windows_sandbox::WindowsSandboxConfig::read(
|
||||
app_server.request_handle(),
|
||||
self.chat_widget.config_ref().cwd.display().to_string(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(state) => {
|
||||
self.chat_widget.windows_sandbox_config = state;
|
||||
self.chat_widget
|
||||
.set_windows_sandbox_mode(self.chat_widget.windows_sandbox_config.mode);
|
||||
true
|
||||
}
|
||||
Err(_) => {
|
||||
self.chat_widget.windows_sandbox_config = Default::default();
|
||||
self.chat_widget
|
||||
.retain_input_after_failed_permission_selection();
|
||||
self.chat_widget.set_windows_sandbox_mode(/*mode*/ None);
|
||||
self.chat_widget.add_error_message("Could not read Windows sandbox configuration and requirements from the app server.".to_string());
|
||||
false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "windows")]
|
||||
pub(super) async fn begin_windows_sandbox_setup(
|
||||
&mut self,
|
||||
app_server: &mut AppServerSession,
|
||||
preset: ApprovalPreset,
|
||||
profile_selection: Option<PermissionProfileSelection>,
|
||||
mode: WindowsSandboxEnableMode,
|
||||
) {
|
||||
let setup_mode = match mode {
|
||||
WindowsSandboxEnableMode::Elevated => WindowsSandboxSetupMode::Elevated,
|
||||
WindowsSandboxEnableMode::Legacy => WindowsSandboxSetupMode::Unelevated,
|
||||
};
|
||||
if self.windows_sandbox.pending_setup.is_some() {
|
||||
if self.windows_sandbox.setup_started_at.is_none() {
|
||||
self.chat_widget.add_info_message(
|
||||
"Windows sandbox setup is still running. Restart aKode to retry.".to_string(),
|
||||
/*hint*/ None,
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if !self.refresh_windows_sandbox_config(app_server).await {
|
||||
return;
|
||||
}
|
||||
if !self.chat_widget.windows_sandbox_config.allows(setup_mode) {
|
||||
self.chat_widget
|
||||
.retain_input_after_failed_permission_selection();
|
||||
self.chat_widget.add_info_message(
|
||||
"That Windows sandbox option is disallowed by requirements.".to_string(),
|
||||
/*hint*/ None,
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
self.windows_sandbox.pending_setup = Some((mode, preset, profile_selection));
|
||||
self.chat_widget.show_windows_sandbox_setup_status();
|
||||
self.windows_sandbox.setup_started_at = Some(Instant::now());
|
||||
let request_id = app_server.next_request_id();
|
||||
let response = tokio::time::timeout(
|
||||
std::time::Duration::from_secs(15),
|
||||
app_server
|
||||
.request_handle()
|
||||
.request_typed(ClientRequest::WindowsSandboxSetupStart {
|
||||
request_id,
|
||||
params: akode_app_server_protocol::WindowsSandboxSetupStartParams {
|
||||
mode: setup_mode,
|
||||
cwd: Some(self.chat_widget.config_ref().cwd.clone()),
|
||||
},
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
self.finish_windows_sandbox_setup_start(response);
|
||||
}
|
||||
|
||||
#[cfg(any(target_os = "windows", test))]
|
||||
pub(super) fn finish_windows_sandbox_setup_start(
|
||||
&mut self,
|
||||
response: std::result::Result<
|
||||
std::result::Result<
|
||||
akode_app_server_protocol::WindowsSandboxSetupStartResponse,
|
||||
TypedRequestError,
|
||||
>,
|
||||
tokio::time::error::Elapsed,
|
||||
>,
|
||||
) {
|
||||
match response {
|
||||
Ok(Ok(akode_app_server_protocol::WindowsSandboxSetupStartResponse {
|
||||
started: true,
|
||||
})) => {}
|
||||
Err(_) => {
|
||||
self.chat_widget.add_error_message(
|
||||
"Windows sandbox setup request timed out. Waiting for completion; restart aKode if it does not finish."
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
Ok(Err(
|
||||
TypedRequestError::Transport { .. } | TypedRequestError::Deserialize { .. },
|
||||
)) => {
|
||||
self.chat_widget.add_error_message(
|
||||
"Windows sandbox setup response was lost. Waiting for completion or reconnection."
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
Ok(result) => {
|
||||
self.windows_sandbox.pending_setup = None;
|
||||
self.chat_widget
|
||||
.retain_input_after_failed_permission_selection();
|
||||
self.chat_widget.clear_windows_sandbox_setup_status();
|
||||
self.windows_sandbox.setup_started_at = None;
|
||||
let message = match result {
|
||||
Err(TypedRequestError::Server { source, .. }) if source.code == -32601 => {
|
||||
"Update the local app server to set up the Windows sandbox.".to_string()
|
||||
}
|
||||
Err(_) => "Windows sandbox setup failed.".to_string(),
|
||||
Ok(_) => "Windows sandbox setup did not start.".to_string(),
|
||||
};
|
||||
self.chat_widget.add_error_message(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn side_return_shortcut_matches(key_event: KeyEvent) -> bool {
|
||||
matches!(
|
||||
key_event,
|
||||
KeyEvent {
|
||||
code: KeyCode::Char(c),
|
||||
modifiers,
|
||||
kind: KeyEventKind::Press,
|
||||
..
|
||||
} if modifiers.contains(KeyModifiers::CONTROL)
|
||||
&& (c.eq_ignore_ascii_case(&'c') || c.eq_ignore_ascii_case(&'d'))
|
||||
)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn side_return_shortcuts_match_ctrl_c_and_ctrl_d() {
|
||||
assert!(side_return_shortcut_matches(KeyEvent::new(
|
||||
KeyCode::Char('c'),
|
||||
KeyModifiers::CONTROL,
|
||||
)));
|
||||
assert!(side_return_shortcut_matches(KeyEvent::new(
|
||||
KeyCode::Char('C'),
|
||||
KeyModifiers::CONTROL,
|
||||
)));
|
||||
assert!(side_return_shortcut_matches(KeyEvent::new(
|
||||
KeyCode::Char('d'),
|
||||
KeyModifiers::CONTROL,
|
||||
)));
|
||||
assert!(side_return_shortcut_matches(KeyEvent::new(
|
||||
KeyCode::Char('D'),
|
||||
KeyModifiers::CONTROL,
|
||||
)));
|
||||
assert!(!side_return_shortcut_matches(KeyEvent::new_with_kind(
|
||||
KeyCode::Esc,
|
||||
KeyModifiers::NONE,
|
||||
KeyEventKind::Press,
|
||||
)));
|
||||
assert!(!side_return_shortcut_matches(KeyEvent::new_with_kind(
|
||||
KeyCode::Esc,
|
||||
KeyModifiers::NONE,
|
||||
KeyEventKind::Release,
|
||||
)));
|
||||
}
|
||||
}
|
||||
155
akode-rs/tui/src/app/plugin_mentions.rs
Normal file
155
akode-rs/tui/src/app/plugin_mentions.rs
Normal file
@@ -0,0 +1,155 @@
|
||||
//! Plugin mention capability enrichment for the TUI.
|
||||
//!
|
||||
//! Mention inventory comes from app-server `plugin/installed` so loading
|
||||
//! mentions does not fetch the browsable plugin catalog. The API exposes
|
||||
//! plugin-level mention metadata, but not effective per-session capability summaries.
|
||||
|
||||
use super::*;
|
||||
use akode_app_server_protocol::PluginInstalledParams;
|
||||
use akode_app_server_protocol::PluginInstalledResponse;
|
||||
use akode_app_server_protocol::PluginSummary;
|
||||
use akode_app_server_protocol::RequestId;
|
||||
use akode_plugin::PluginCapabilitySummary;
|
||||
|
||||
pub(super) async fn fetch_plugin_mentions(
|
||||
request_handle: AppServerRequestHandle,
|
||||
cwd: PathBuf,
|
||||
) -> Result<Vec<PluginCapabilitySummary>> {
|
||||
let cwd = AbsolutePathBuf::try_from(cwd).wrap_err("plugin installed cwd must be absolute")?;
|
||||
let request_id = RequestId::String(format!("plugin-installed-{}", Uuid::new_v4()));
|
||||
let response = request_handle
|
||||
.request_typed(ClientRequest::PluginInstalled {
|
||||
request_id,
|
||||
params: PluginInstalledParams {
|
||||
cwds: Some(vec![cwd]),
|
||||
install_suggestion_plugin_names: None,
|
||||
},
|
||||
})
|
||||
.await
|
||||
.wrap_err("plugin/installed failed in TUI")?;
|
||||
Ok(plugin_mentions_from_installed_response(response))
|
||||
}
|
||||
|
||||
fn plugin_mentions_from_installed_response(
|
||||
response: PluginInstalledResponse,
|
||||
) -> Vec<PluginCapabilitySummary> {
|
||||
response
|
||||
.marketplaces
|
||||
.into_iter()
|
||||
.flat_map(|marketplace| {
|
||||
let marketplace_name = marketplace.name;
|
||||
marketplace
|
||||
.plugins
|
||||
.into_iter()
|
||||
.filter_map(move |plugin| plugin_mention_from_summary(&marketplace_name, plugin))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn plugin_is_eligible_for_mentions(plugin: &PluginSummary) -> bool {
|
||||
plugin.installed && plugin.enabled
|
||||
}
|
||||
|
||||
fn plugin_mention_from_summary(
|
||||
marketplace_name: &str,
|
||||
plugin: PluginSummary,
|
||||
) -> Option<PluginCapabilitySummary> {
|
||||
if !plugin_is_eligible_for_mentions(&plugin) {
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(PluginCapabilitySummary {
|
||||
config_name: plugin.id.clone(),
|
||||
display_name: plugin_mention_display_name(&plugin),
|
||||
plugin_namespace: Some(plugin.name.clone()),
|
||||
description: plugin_mention_description(marketplace_name, &plugin),
|
||||
has_skills: false,
|
||||
mcp_server_names: Vec::new(),
|
||||
})
|
||||
}
|
||||
|
||||
fn plugin_mention_display_name(plugin: &PluginSummary) -> String {
|
||||
plugin
|
||||
.interface
|
||||
.as_ref()
|
||||
.and_then(|interface| interface.display_name.as_deref())
|
||||
.map(str::trim)
|
||||
.filter(|display_name| !display_name.is_empty())
|
||||
.map(str::to_string)
|
||||
.unwrap_or_else(|| plugin.name.clone())
|
||||
}
|
||||
|
||||
fn plugin_mention_description(marketplace_name: &str, plugin: &PluginSummary) -> Option<String> {
|
||||
plugin
|
||||
.interface
|
||||
.as_ref()
|
||||
.and_then(|interface| interface.short_description.as_deref())
|
||||
.map(str::trim)
|
||||
.filter(|description| !description.is_empty())
|
||||
.map(str::to_string)
|
||||
.or_else(|| {
|
||||
let marketplace_name = marketplace_name.trim();
|
||||
(!marketplace_name.is_empty()).then(|| marketplace_name.to_string())
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use akode_app_server_protocol::PluginAuthPolicy;
|
||||
use akode_app_server_protocol::PluginInstallPolicy;
|
||||
use akode_app_server_protocol::PluginMarketplaceEntry;
|
||||
use akode_app_server_protocol::PluginSource;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
#[test]
|
||||
fn plugin_mentions_use_installed_summaries_and_gui_eligibility() {
|
||||
let active = plugin_summary("active");
|
||||
let active_second = plugin_summary("active-second");
|
||||
let mut disabled = plugin_summary("disabled");
|
||||
disabled.enabled = false;
|
||||
let mut uninstalled = plugin_summary("uninstalled");
|
||||
uninstalled.installed = false;
|
||||
|
||||
let response = PluginInstalledResponse {
|
||||
marketplaces: vec![PluginMarketplaceEntry {
|
||||
name: "server-marketplace".to_string(),
|
||||
path: None,
|
||||
interface: None,
|
||||
plugins: vec![active, active_second, disabled, uninstalled],
|
||||
}],
|
||||
marketplace_load_errors: Vec::new(),
|
||||
};
|
||||
|
||||
assert_eq!(
|
||||
plugin_mentions_from_installed_response(response),
|
||||
["active", "active-second"].map(|name| PluginCapabilitySummary {
|
||||
config_name: format!("{name}@server-marketplace"),
|
||||
display_name: name.to_string(),
|
||||
plugin_namespace: Some(name.to_string()),
|
||||
description: Some("server-marketplace".to_string()),
|
||||
has_skills: false,
|
||||
mcp_server_names: Vec::new(),
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
fn plugin_summary(name: &str) -> PluginSummary {
|
||||
PluginSummary {
|
||||
id: format!("{name}@server-marketplace"),
|
||||
local_version: None,
|
||||
name: name.to_string(),
|
||||
source: PluginSource::Local {
|
||||
path: AbsolutePathBuf::try_from(std::env::temp_dir().join(name))
|
||||
.expect("absolute plugin path"),
|
||||
},
|
||||
installed: true,
|
||||
enabled: true,
|
||||
install_policy: PluginInstallPolicy::Available,
|
||||
auth_policy: PluginAuthPolicy::OnInstall,
|
||||
interface: None,
|
||||
keywords: Vec::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
417
akode-rs/tui/src/app/provider.rs
Normal file
417
akode-rs/tui/src/app/provider.rs
Normal file
@@ -0,0 +1,417 @@
|
||||
//! Browse and edit the connected server's providers and choose a default for new chats.
|
||||
|
||||
use super::App;
|
||||
use crate::app_event::AppEvent;
|
||||
use crate::app_server_session::AppServerSession;
|
||||
use crate::backend_id::BackendId;
|
||||
use crate::bottom_pane::SelectionItem;
|
||||
use crate::bottom_pane::SelectionSecondaryAction;
|
||||
use crate::bottom_pane::SelectionViewParams;
|
||||
use crate::key_hint;
|
||||
use crate::keymap::ListAction;
|
||||
use crate::keymap::ListKeymap;
|
||||
use crate::pager_overlay::Overlay;
|
||||
use crate::pager_overlay::PagerAction;
|
||||
use crate::pager_overlay::StaticOverlay;
|
||||
use crate::tui::Tui;
|
||||
use akode_app_server_protocol::ModelProviderListResponse;
|
||||
use akode_app_server_protocol::ModelProviderSummary;
|
||||
use crossterm::event::KeyCode;
|
||||
use ratatui::style::Stylize;
|
||||
use ratatui::text::Line;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::watch;
|
||||
|
||||
mod editor;
|
||||
pub(crate) use editor::Draft;
|
||||
pub(crate) use editor::ProviderForm;
|
||||
mod fields;
|
||||
pub(crate) mod rpc;
|
||||
mod write;
|
||||
use fields::Field;
|
||||
use fields::provider_fields;
|
||||
|
||||
const LOADING_VIEW: &str = "model_provider_loading";
|
||||
pub(super) const LIST_VIEW: &str = "model_provider_list";
|
||||
pub(crate) const CREATE_CUSTOM_PROVIDER: &str = "Create a custom provider or gateway";
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) enum Event {
|
||||
Load {
|
||||
dismissed: watch::Receiver<()>,
|
||||
notice: Option<String>,
|
||||
},
|
||||
Loaded {
|
||||
backend: BackendId,
|
||||
dismissed: watch::Receiver<()>,
|
||||
result: Result<ModelProviderListResponse, String>,
|
||||
notice: Option<String>,
|
||||
},
|
||||
Details {
|
||||
catalog: Arc<Catalog>,
|
||||
index: usize,
|
||||
dismissed: watch::Receiver<()>,
|
||||
},
|
||||
Edit {
|
||||
catalog: Arc<Catalog>,
|
||||
index: Option<usize>,
|
||||
dismissed: watch::Receiver<()>,
|
||||
},
|
||||
Write {
|
||||
backend: BackendId,
|
||||
dismissed: watch::Receiver<()>,
|
||||
write: write::Write,
|
||||
},
|
||||
Written(write::Completion),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Catalog {
|
||||
backend: BackendId,
|
||||
page: ModelProviderListResponse,
|
||||
}
|
||||
|
||||
fn back() -> SelectionItem {
|
||||
SelectionItem {
|
||||
name: "Back".into(),
|
||||
dismiss_on_select: true,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn load_error(title: &str, error: String) -> SelectionViewParams {
|
||||
SelectionViewParams {
|
||||
title: Some(title.into()),
|
||||
subtitle: Some(error),
|
||||
items: vec![back()],
|
||||
allow_input_when_disconnected: true,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn loading() -> (SelectionViewParams, Event) {
|
||||
loading_with_notice(/*notice*/ None)
|
||||
}
|
||||
|
||||
fn loading_with_notice(notice: Option<String>) -> (SelectionViewParams, Event) {
|
||||
let (view, dismissed) = progress(LOADING_VIEW, "Loading model providers…");
|
||||
(view, Event::Load { dismissed, notice })
|
||||
}
|
||||
|
||||
fn progress(id: &'static str, title: &str) -> (SelectionViewParams, watch::Receiver<()>) {
|
||||
// Destroying a popup invalidates its own request, even if another popup has the same ID.
|
||||
let (dismiss, dismissed) = watch::channel(());
|
||||
let view = SelectionViewParams {
|
||||
view_id: Some(id),
|
||||
title: Some(title.into()),
|
||||
items: vec![back()],
|
||||
allow_input_when_disconnected: true,
|
||||
on_cancel: Some(Box::new(move |_| {
|
||||
dismiss.send_replace(());
|
||||
})),
|
||||
..Default::default()
|
||||
};
|
||||
(view, dismissed)
|
||||
}
|
||||
|
||||
pub(super) fn handle(app: &mut App, tui: &mut Tui, server: &AppServerSession, event: Event) {
|
||||
let backend = server.backend_id();
|
||||
match event {
|
||||
Event::Load {
|
||||
mut dismissed,
|
||||
notice,
|
||||
} => {
|
||||
let tx = app.app_event_tx.clone();
|
||||
let handle = server.request_handle();
|
||||
let offline = app.reconnect.offline;
|
||||
tokio::spawn(async move {
|
||||
let result = if offline {
|
||||
Err("Reconnect to the app server to browse model providers.".into())
|
||||
} else {
|
||||
tokio::select! {
|
||||
_ = dismissed.changed() => return,
|
||||
result = rpc::list_providers(&handle) => result,
|
||||
}
|
||||
};
|
||||
tx.send(AppEvent::Provider(Event::Loaded {
|
||||
backend,
|
||||
dismissed,
|
||||
result,
|
||||
notice,
|
||||
}));
|
||||
});
|
||||
}
|
||||
Event::Loaded {
|
||||
backend: origin,
|
||||
dismissed,
|
||||
result,
|
||||
notice,
|
||||
} => {
|
||||
if origin != backend || !matches!(dismissed.has_changed(), Ok(false)) {
|
||||
return;
|
||||
}
|
||||
let chat = &mut app.chat_widget;
|
||||
let view = match result {
|
||||
Ok(page) => list(
|
||||
chat.thread_id()
|
||||
.map(|_| chat.config_ref().model_provider_id.as_str()),
|
||||
Arc::new(Catalog { backend, page }),
|
||||
server.client_provider_override_for_new_chats(&app.config),
|
||||
&app.keymap.list,
|
||||
notice,
|
||||
),
|
||||
Err(error) => load_error("Model providers", error),
|
||||
};
|
||||
chat.replace_selection_view_if_present(LOADING_VIEW, view);
|
||||
}
|
||||
Event::Details {
|
||||
catalog,
|
||||
index,
|
||||
dismissed,
|
||||
} => {
|
||||
if catalog.backend == backend
|
||||
&& matches!(dismissed.has_changed(), Ok(false))
|
||||
&& app.overlay.is_none()
|
||||
&& app.chat_widget.active_view_is(LIST_VIEW)
|
||||
{
|
||||
let provider = &catalog.page.data[index];
|
||||
let mut pager = StaticOverlay::with_title(
|
||||
details(provider),
|
||||
"Model provider details".into(),
|
||||
app.keymap.pager.clone(),
|
||||
);
|
||||
if provider.can_edit {
|
||||
let tx = app.app_event_tx.clone();
|
||||
pager.action = Some(PagerAction {
|
||||
key: key_hint::plain(KeyCode::Enter),
|
||||
label: "Edit configuration",
|
||||
run: Box::new(move || {
|
||||
tx.send(AppEvent::Provider(Event::Edit {
|
||||
catalog,
|
||||
index: Some(index),
|
||||
dismissed,
|
||||
}));
|
||||
}),
|
||||
});
|
||||
}
|
||||
let _ = tui.enter_alt_screen();
|
||||
app.overlay = Some(Overlay::Static(pager));
|
||||
tui.frame_requester().schedule_frame();
|
||||
}
|
||||
}
|
||||
Event::Edit {
|
||||
catalog,
|
||||
index,
|
||||
dismissed,
|
||||
} => {
|
||||
if backend == catalog.backend
|
||||
&& matches!(dismissed.has_changed(), Ok(false))
|
||||
&& app.overlay.is_none()
|
||||
&& app.chat_widget.active_view_is(LIST_VIEW)
|
||||
{
|
||||
let draft = editor::Draft::new(
|
||||
index.map(|i| catalog.page.data[i].clone()),
|
||||
&catalog.page.data,
|
||||
);
|
||||
let view = edit_view(app, backend, draft, /*error*/ None);
|
||||
app.chat_widget.show_bottom_pane_view(view);
|
||||
}
|
||||
}
|
||||
Event::Write {
|
||||
backend,
|
||||
dismissed,
|
||||
write,
|
||||
} => {
|
||||
if backend == server.backend_id() && matches!(dismissed.has_changed(), Ok(false)) {
|
||||
write.start(app, server);
|
||||
}
|
||||
}
|
||||
Event::Written(completion) => completion.finish(app, backend),
|
||||
}
|
||||
}
|
||||
|
||||
/// Refresh a list opened before the first chat acquired a server-side provider.
|
||||
pub(crate) fn refresh_list_if_present(chat: &mut crate::chatwidget::ChatWidget) -> Option<Event> {
|
||||
if chat.no_modal_or_popup_active() {
|
||||
return None;
|
||||
}
|
||||
let (view, event) = loading();
|
||||
chat.replace_selection_view_if_present(LIST_VIEW, view)
|
||||
.then_some(event)
|
||||
}
|
||||
|
||||
pub(crate) fn provider_item(provider: &ModelProviderSummary, default_id: &str) -> SelectionItem {
|
||||
let is_default = provider.id == default_id;
|
||||
SelectionItem {
|
||||
name: provider.name.clone(),
|
||||
name_prefix_spans: vec![if is_default {
|
||||
"● ".green()
|
||||
} else {
|
||||
"○ ".dim()
|
||||
}],
|
||||
description: Some(provider.id.clone()),
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn list(
|
||||
current: Option<&str>,
|
||||
catalog: Arc<Catalog>,
|
||||
client_override: Option<String>,
|
||||
keymap: &ListKeymap,
|
||||
notice: Option<String>,
|
||||
) -> SelectionViewParams {
|
||||
let current_label = current.unwrap_or("No active chat");
|
||||
let page = &catalog.page;
|
||||
let can_select = page.can_change_default && client_override.is_none();
|
||||
let default_label = if client_override.is_some() {
|
||||
"Server default"
|
||||
} else {
|
||||
"Default for new chats"
|
||||
};
|
||||
let note = match client_override {
|
||||
Some(id) => format!("This client's launch settings select {id} for new chats."),
|
||||
None if !page.can_change_default => {
|
||||
"The server configuration fixes the default provider.".into()
|
||||
}
|
||||
None => "Use /new to start a chat with the selected provider.".into(),
|
||||
};
|
||||
let (dismiss, dismissed) = watch::channel(());
|
||||
let mut items: Vec<_> = page
|
||||
.data
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, provider)| {
|
||||
let is_default = provider.id == page.default_provider_id;
|
||||
let secondary_action = (can_select && !is_default).then(|| {
|
||||
let backend = catalog.backend;
|
||||
let id = provider.id.clone();
|
||||
let dismissed = dismissed.clone();
|
||||
SelectionSecondaryAction {
|
||||
key: key_hint::plain(KeyCode::Char(' ')),
|
||||
footer_hint: provider_hint(keymap, /*select*/ true),
|
||||
action: Box::new(move |tx| {
|
||||
tx.send(AppEvent::Provider(Event::Write {
|
||||
backend,
|
||||
dismissed: dismissed.clone(),
|
||||
write: write::Write::Default(id.clone()),
|
||||
}))
|
||||
}),
|
||||
}
|
||||
});
|
||||
let catalog = Arc::clone(&catalog);
|
||||
let dismissed = dismissed.clone();
|
||||
SelectionItem {
|
||||
is_current: current == Some(provider.id.as_str()),
|
||||
secondary_action,
|
||||
actions: vec![Box::new(move |tx| {
|
||||
tx.send(AppEvent::Provider(Event::Details {
|
||||
catalog: Arc::clone(&catalog),
|
||||
index,
|
||||
dismissed: dismissed.clone(),
|
||||
}));
|
||||
})],
|
||||
..provider_item(provider, &page.default_provider_id)
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
items.push(SelectionItem {
|
||||
name: CREATE_CUSTOM_PROVIDER.into(),
|
||||
footer_hint: Some(crate::bottom_pane::popup_consts::picker_hint_line_for_keymap(keymap)),
|
||||
actions: vec![Box::new({
|
||||
let catalog = Arc::clone(&catalog);
|
||||
move |tx| {
|
||||
tx.send(AppEvent::Provider(Event::Edit {
|
||||
catalog: Arc::clone(&catalog),
|
||||
index: None,
|
||||
dismissed: dismissed.clone(),
|
||||
}));
|
||||
}
|
||||
})],
|
||||
..Default::default()
|
||||
});
|
||||
SelectionViewParams {
|
||||
view_id: Some(LIST_VIEW),
|
||||
title: Some("Model providers".into()),
|
||||
subtitle: Some(format!(
|
||||
"Current chat: {current_label} · {default_label}: {}",
|
||||
if page.default_provider_id.is_empty() {
|
||||
"none"
|
||||
} else {
|
||||
page.default_provider_id.as_str()
|
||||
}
|
||||
)),
|
||||
footer_note: Some(notice.unwrap_or(note).into()),
|
||||
footer_hint: Some(provider_hint(keymap, /*select*/ false)),
|
||||
items,
|
||||
on_cancel: Some(Box::new(move |_| {
|
||||
dismiss.send_replace(());
|
||||
})),
|
||||
allow_input_when_disconnected: true,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn edit_view(
|
||||
app: &App,
|
||||
backend: BackendId,
|
||||
draft: editor::Draft,
|
||||
error: Option<String>,
|
||||
) -> Box<dyn crate::bottom_pane::BottomPaneView> {
|
||||
let tx = app.app_event_tx.clone();
|
||||
let (owner, _) = watch::channel(());
|
||||
editor::view(app, draft, error, move |draft, params| {
|
||||
tx.send(AppEvent::Provider(Event::Write {
|
||||
backend,
|
||||
dismissed: owner.subscribe(),
|
||||
write: write::Write::Settings(Box::new((draft, params))),
|
||||
}));
|
||||
})
|
||||
}
|
||||
|
||||
fn provider_hint(keymap: &ListKeymap, select: bool) -> Line<'static> {
|
||||
let keys = [
|
||||
(keymap.primary_hint(ListAction::Accept), " details"),
|
||||
(
|
||||
select.then(|| key_hint::plain(KeyCode::Char(' ')).into()),
|
||||
" set default",
|
||||
),
|
||||
(keymap.primary_hint(ListAction::Cancel), " back"),
|
||||
];
|
||||
let mut hints = Vec::new();
|
||||
for (key, label) in keys {
|
||||
if let Some(key) = key {
|
||||
if !hints.is_empty() {
|
||||
hints.push(" · ".dim());
|
||||
}
|
||||
hints.extend(key.spans());
|
||||
hints.push(label.dim());
|
||||
}
|
||||
}
|
||||
hints.into()
|
||||
}
|
||||
|
||||
fn details(provider: &ModelProviderSummary) -> Vec<Line<'static>> {
|
||||
let mut lines = vec![Line::from(provider.name.clone().bold()), Line::default()];
|
||||
let mut field = |label: &str, value: &str| {
|
||||
lines.push(Line::from(vec![
|
||||
format!("{label} ").bold(),
|
||||
value.to_owned().into(),
|
||||
]));
|
||||
};
|
||||
field("Provider ID", &provider.id);
|
||||
for (kind, value) in provider_fields(provider) {
|
||||
let absent = match kind {
|
||||
Field::Url | Field::ManagedUrl => "Not reported",
|
||||
Field::ExternalAuth => "Managed externally",
|
||||
Field::Variable => "None",
|
||||
_ => "Not set",
|
||||
};
|
||||
field(kind.label(), value.unwrap_or(absent));
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "provider_tests.rs"]
|
||||
mod tests;
|
||||
374
akode-rs/tui/src/app/provider/editor.rs
Normal file
374
akode-rs/tui/src/app/provider/editor.rs
Normal file
@@ -0,0 +1,374 @@
|
||||
//! Single-screen provider form. Validation preserves the draft and each field owns its editing history.
|
||||
|
||||
use super::CREATE_CUSTOM_PROVIDER;
|
||||
use super::Field;
|
||||
use crate::app::App;
|
||||
use crate::bottom_pane::BottomPaneView;
|
||||
use crate::bottom_pane::CancellationEvent;
|
||||
use crate::bottom_pane::ViewCompletion;
|
||||
use crate::key_hint;
|
||||
use crate::keymap::KeymapContextSet;
|
||||
use crate::line_truncation::truncate_line_to_width;
|
||||
use crate::onboarding::FieldDisplay;
|
||||
use crate::onboarding::ProviderInput;
|
||||
use crate::onboarding::move_provider_field;
|
||||
use crate::render::renderable::Renderable;
|
||||
use crate::wrapping::word_wrap_lines;
|
||||
use akode_app_server_protocol::ModelProviderConfigWriteParams;
|
||||
use crossterm::cursor::SetCursorStyle;
|
||||
use crossterm::event::KeyCode;
|
||||
use crossterm::event::KeyEvent;
|
||||
use crossterm::event::KeyEventKind;
|
||||
use ratatui::buffer::Buffer;
|
||||
use ratatui::layout::Rect;
|
||||
use ratatui::style::Stylize;
|
||||
use ratatui::text::Line;
|
||||
use ratatui::widgets::Paragraph;
|
||||
use ratatui::widgets::Wrap;
|
||||
|
||||
mod form;
|
||||
pub(crate) use form::Draft;
|
||||
|
||||
pub(super) const VIEW_ID: &str = "model_provider_editor";
|
||||
|
||||
pub(crate) fn view(
|
||||
app: &App,
|
||||
draft: Draft,
|
||||
error: Option<String>,
|
||||
on_save: impl Fn(Draft, ModelProviderConfigWriteParams) + Send + 'static,
|
||||
) -> Box<dyn BottomPaneView> {
|
||||
let form = ProviderForm::new(draft, error);
|
||||
for (_, input) in &form.inputs {
|
||||
let mut editor = input.editor();
|
||||
editor.set_keymap_bindings(&app.keymap);
|
||||
if app.chat_widget.composer_is_vim_enabled() {
|
||||
editor.set_vim_enabled(/*enabled*/ true);
|
||||
editor.enter_vim_insert_mode();
|
||||
}
|
||||
}
|
||||
Box::new(Editor {
|
||||
form,
|
||||
on_save: Box::new(on_save),
|
||||
completion: None,
|
||||
})
|
||||
}
|
||||
|
||||
struct Editor {
|
||||
form: ProviderForm,
|
||||
on_save: Box<dyn Fn(Draft, ModelProviderConfigWriteParams) + Send>,
|
||||
completion: Option<ViewCompletion>,
|
||||
}
|
||||
|
||||
pub(crate) struct ProviderForm {
|
||||
inputs: Vec<(Field, ProviderInput)>,
|
||||
draft: Draft,
|
||||
pub(crate) error: Option<String>,
|
||||
}
|
||||
|
||||
struct FormLayout {
|
||||
paragraph: Paragraph<'static>,
|
||||
focus_row: u16,
|
||||
cursor: Option<(u16, u16)>,
|
||||
}
|
||||
|
||||
impl ProviderForm {
|
||||
pub(crate) fn new(draft: Draft, error: Option<String>) -> Self {
|
||||
let inputs = draft
|
||||
.fields()
|
||||
.into_iter()
|
||||
.map(|(field, original)| (field, ProviderInput::from(draft.value(field, original))))
|
||||
.collect();
|
||||
Self {
|
||||
inputs,
|
||||
draft,
|
||||
error,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn active_input_mut(&mut self) -> Option<&mut ProviderInput> {
|
||||
self.inputs
|
||||
.get_mut(self.draft.selected)
|
||||
.map(|(_, input)| input)
|
||||
}
|
||||
|
||||
pub(crate) fn active_input(&self) -> Option<&ProviderInput> {
|
||||
self.inputs.get(self.draft.selected).map(|(_, input)| input)
|
||||
}
|
||||
|
||||
fn changes(&self) -> impl Iterator<Item = (Field, String)> {
|
||||
self.draft
|
||||
.fields()
|
||||
.into_iter()
|
||||
.zip(&self.inputs)
|
||||
.filter_map(|((field, original), (_, input))| {
|
||||
let value = input.value().unwrap_or_default();
|
||||
// A single-line buffer strips line breaks from legacy values on display.
|
||||
let displayed = original.unwrap_or_default().replace(['\r', '\n'], "");
|
||||
(value != displayed.trim()).then_some((field, value))
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn input(&mut self, key: KeyEvent) -> Option<ModelProviderConfigWriteParams> {
|
||||
if move_provider_field(key, &mut self.draft.selected, self.inputs.len() + 1) {
|
||||
return None;
|
||||
}
|
||||
// Holding Enter on a field must not carry its activation onto Save.
|
||||
if key.kind == KeyEventKind::Press && key_hint::plain(KeyCode::Enter).is_press(key) {
|
||||
if self.draft.selected == self.inputs.len() {
|
||||
self.draft.changes = self.changes().collect();
|
||||
match self.draft.patch() {
|
||||
Ok(params) => return Some(params),
|
||||
Err(message) => self.error = Some(message.into()),
|
||||
}
|
||||
} else {
|
||||
self.draft.selected += 1;
|
||||
}
|
||||
return None;
|
||||
}
|
||||
if key_hint::ctrl(KeyCode::Char(' ')).is_press(key)
|
||||
&& let Some(suggestion) = self.suggestion()
|
||||
{
|
||||
let mut editor = self.inputs[self.draft.selected].1.editor();
|
||||
let suffix = &suggestion[editor.cursor()..];
|
||||
editor.insert_str(suffix);
|
||||
return None;
|
||||
}
|
||||
if let Some((_, input)) = self.inputs.get_mut(self.draft.selected) {
|
||||
input.input(key);
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn prefer_esc_to_handle_key_event(&self) -> bool {
|
||||
self.active_input().is_some_and(|input| {
|
||||
input
|
||||
.editor()
|
||||
.should_handle_vim_insert_escape(KeyCode::Esc.into())
|
||||
})
|
||||
}
|
||||
|
||||
fn suggestion(&self) -> Option<&str> {
|
||||
let (Field::Variable, input) = self.inputs.get(self.draft.selected)? else {
|
||||
return None;
|
||||
};
|
||||
let editor = input.editor();
|
||||
let prefix = editor.text();
|
||||
if prefix.is_empty() || editor.cursor() != prefix.len() {
|
||||
return None;
|
||||
}
|
||||
self.draft
|
||||
.variables
|
||||
.iter()
|
||||
.map(String::as_str)
|
||||
.find(|name| *name != prefix && name.starts_with(prefix))
|
||||
}
|
||||
|
||||
fn layout(&self, width: u16) -> FormLayout {
|
||||
let title = self.draft.provider.as_ref().map_or_else(
|
||||
|| CREATE_CUSTOM_PROVIDER.to_owned(),
|
||||
|p| format!("Edit {}", p.name),
|
||||
);
|
||||
let wrap_width = usize::from(width.max(1));
|
||||
let mut lines = word_wrap_lines([Line::from(title.bold())], wrap_width);
|
||||
lines.push(Line::default());
|
||||
let mut cursor = None;
|
||||
let mut focus_row = 0;
|
||||
let key_needs_url = !self.draft.required(Field::Url)
|
||||
&& self
|
||||
.changes()
|
||||
.any(|(field, value)| field == Field::Variable && !value.is_empty());
|
||||
for (index, (field, input)) in self.inputs.iter().enumerate() {
|
||||
let focused = index == self.draft.selected;
|
||||
let marker = if focused { "› " } else { " " };
|
||||
let required = if self.draft.required(*field) || (*field == Field::Url && key_needs_url)
|
||||
{
|
||||
"*"
|
||||
} else {
|
||||
""
|
||||
};
|
||||
let label = format!("{marker}{}{required} ", field.label()).bold();
|
||||
let example = match field {
|
||||
Field::Name => "Team gateway",
|
||||
Field::Url => "https://gateway.example/v1",
|
||||
Field::Variable => "TEAM_API_KEY",
|
||||
_ => "",
|
||||
};
|
||||
let mut line = Line::from(label);
|
||||
// Put the value on its own row when the label would crowd the cursor.
|
||||
if line.width() + 8 > usize::from(width) {
|
||||
lines.extend(word_wrap_lines([line], wrap_width));
|
||||
line = Line::default();
|
||||
}
|
||||
if *field == Field::Variable && width > 1 {
|
||||
line.push_span("$".dim());
|
||||
}
|
||||
let display = if focused {
|
||||
FieldDisplay::Focused
|
||||
} else {
|
||||
FieldDisplay::Unfocused
|
||||
};
|
||||
let x = line.width() as u16;
|
||||
let area = Rect::new(x, lines.len() as u16, width.saturating_sub(x), 1);
|
||||
if focused {
|
||||
focus_row = area.y;
|
||||
cursor = input.editor().cursor_pos(area);
|
||||
}
|
||||
let value = input.line("", example, display, area.width);
|
||||
line.spans.extend(value.spans);
|
||||
lines.push(truncate_line_to_width(line, usize::from(width)));
|
||||
}
|
||||
lines.push(if self.draft.selected == self.inputs.len() {
|
||||
focus_row = lines.len() as u16;
|
||||
"› Save".bold().into()
|
||||
} else {
|
||||
" Save".into()
|
||||
});
|
||||
if let Some(error) = &self.error {
|
||||
lines.push(error.clone().red().into());
|
||||
}
|
||||
lines.push(Line::default());
|
||||
let has = |field| self.inputs.iter().any(|(key, _)| *key == field);
|
||||
if has(Field::Name) {
|
||||
let hint = if has(Field::Variable) {
|
||||
"Enter the environment variable name on the app server."
|
||||
} else {
|
||||
"Authentication is managed on the app server."
|
||||
};
|
||||
lines.extend(["* Required", hint].map(|text| Line::from(text.dim())));
|
||||
}
|
||||
if let Some(suggestion) = self.suggestion() {
|
||||
lines.push(Line::from(vec![
|
||||
key_hint::ctrl(KeyCode::Char(' ')).into(),
|
||||
format!(" complete {suggestion}").dim(),
|
||||
]));
|
||||
}
|
||||
lines.push(Line::from(vec![
|
||||
key_hint::plain(KeyCode::Tab).into(),
|
||||
" move · ".dim(),
|
||||
key_hint::plain(KeyCode::Enter).into(),
|
||||
" next/save · ".dim(),
|
||||
key_hint::plain(KeyCode::Esc).into(),
|
||||
if self.prefer_esc_to_handle_key_event() {
|
||||
" normal mode"
|
||||
} else {
|
||||
" back"
|
||||
}
|
||||
.dim(),
|
||||
]));
|
||||
FormLayout {
|
||||
paragraph: Paragraph::new(lines).wrap(Wrap { trim: false }),
|
||||
focus_row,
|
||||
cursor,
|
||||
}
|
||||
}
|
||||
|
||||
fn visible_layout(&self, area: Rect) -> (Paragraph<'static>, Option<(u16, u16)>) {
|
||||
let FormLayout {
|
||||
paragraph,
|
||||
cursor,
|
||||
focus_row,
|
||||
} = self.layout(area.width);
|
||||
// Show as much feedback below Save as fits while keeping the active action visible.
|
||||
let top = if self.draft.selected == self.inputs.len() {
|
||||
paragraph
|
||||
.desired_height(area.width)
|
||||
.saturating_sub(area.height)
|
||||
.min(focus_row)
|
||||
} else {
|
||||
focus_row.saturating_add(1).saturating_sub(area.height)
|
||||
};
|
||||
(
|
||||
paragraph.scroll((top, 0)),
|
||||
cursor.map(|(x, y)| (x, y.saturating_sub(top))),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Renderable for ProviderForm {
|
||||
fn render(&self, area: Rect, buf: &mut Buffer) {
|
||||
self.visible_layout(area).0.render(area, buf);
|
||||
}
|
||||
|
||||
fn desired_height(&self, width: u16) -> u16 {
|
||||
self.layout(width).paragraph.desired_height(width)
|
||||
}
|
||||
|
||||
fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> {
|
||||
let (x, y) = self.visible_layout(area).1?;
|
||||
(y < area.height).then(|| (area.x.saturating_add(x), area.y.saturating_add(y)))
|
||||
}
|
||||
|
||||
fn cursor_style(&self, _area: Rect) -> SetCursorStyle {
|
||||
if self
|
||||
.active_input()
|
||||
.is_some_and(|input| input.editor().uses_vim_insert_cursor())
|
||||
{
|
||||
SetCursorStyle::SteadyBar
|
||||
} else {
|
||||
SetCursorStyle::DefaultUserShape
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Renderable for Editor {
|
||||
fn render(&self, area: Rect, buf: &mut Buffer) {
|
||||
self.form.render(area, buf);
|
||||
}
|
||||
fn desired_height(&self, width: u16) -> u16 {
|
||||
self.form.desired_height(width)
|
||||
}
|
||||
fn cursor_pos(&self, area: Rect) -> Option<(u16, u16)> {
|
||||
self.form.cursor_pos(area)
|
||||
}
|
||||
fn cursor_style(&self, area: Rect) -> SetCursorStyle {
|
||||
self.form.cursor_style(area)
|
||||
}
|
||||
}
|
||||
|
||||
impl BottomPaneView for Editor {
|
||||
fn view_id(&self) -> Option<&'static str> {
|
||||
Some(VIEW_ID)
|
||||
}
|
||||
|
||||
fn handle_key_event(&mut self, key: KeyEvent) {
|
||||
if let Some(params) = self.form.input(key) {
|
||||
(self.on_save)(self.form.draft.clone(), params);
|
||||
}
|
||||
}
|
||||
|
||||
fn handle_paste(&mut self, pasted: String) -> bool {
|
||||
if let Some(input) = self.form.active_input_mut() {
|
||||
input.paste(&pasted);
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn keymap_contexts(&self) -> KeymapContextSet {
|
||||
self.form
|
||||
.active_input()
|
||||
.map(|input| KeymapContextSet::new(input.editor().keymap_context()))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn prefer_esc_to_handle_key_event(&self) -> bool {
|
||||
self.form.prefer_esc_to_handle_key_event()
|
||||
}
|
||||
|
||||
fn on_ctrl_c(&mut self) -> CancellationEvent {
|
||||
self.completion = Some(ViewCompletion::Cancelled);
|
||||
CancellationEvent::Handled
|
||||
}
|
||||
|
||||
fn is_complete(&self) -> bool {
|
||||
self.completion.is_some()
|
||||
}
|
||||
|
||||
fn completion(&self) -> Option<ViewCompletion> {
|
||||
self.completion
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "editor_tests.rs"]
|
||||
mod tests;
|
||||
101
akode-rs/tui/src/app/provider/editor/form.rs
Normal file
101
akode-rs/tui/src/app/provider/editor/form.rs
Normal file
@@ -0,0 +1,101 @@
|
||||
//! Provider editor drafts retain only changed fields, keeping server-only settings out of writes.
|
||||
|
||||
use super::super::Field;
|
||||
use super::super::provider_fields;
|
||||
use akode_app_server_protocol::CustomGatewaySettingsParams;
|
||||
use akode_app_server_protocol::ModelProviderConfigWriteParams;
|
||||
use akode_app_server_protocol::ModelProviderSummary;
|
||||
use akode_app_server_protocol::ProviderSettingsPatch;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
#[derive(Clone, Default)]
|
||||
pub(crate) struct Draft {
|
||||
pub(super) provider: Option<ModelProviderSummary>,
|
||||
pub(super) changes: BTreeMap<Field, String>,
|
||||
pub(super) variables: BTreeSet<String>,
|
||||
pub(super) selected: usize,
|
||||
}
|
||||
|
||||
impl Draft {
|
||||
pub(crate) fn new(
|
||||
provider: Option<ModelProviderSummary>,
|
||||
catalog: &[ModelProviderSummary],
|
||||
) -> Self {
|
||||
let variables = catalog
|
||||
.iter()
|
||||
.flat_map(provider_fields)
|
||||
.filter(|(field, _)| matches!(field, Field::Variable | Field::ExternalAuth))
|
||||
.filter_map(|(_, name)| name.map(str::to_owned))
|
||||
.collect();
|
||||
Self {
|
||||
provider,
|
||||
variables,
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn fields(&self) -> Vec<(Field, Option<&str>)> {
|
||||
let Some(p) = &self.provider else {
|
||||
return [Field::Name, Field::Url, Field::Variable]
|
||||
.map(|field| (field, None))
|
||||
.into();
|
||||
};
|
||||
provider_fields(p)
|
||||
.into_iter()
|
||||
.filter(|(field, _)| !matches!(field, Field::ManagedUrl | Field::ExternalAuth))
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn value<'a>(&'a self, field: Field, original: Option<&'a str>) -> &'a str {
|
||||
self.changes
|
||||
.get(&field)
|
||||
.map_or(original.unwrap_or_default(), String::as_str)
|
||||
}
|
||||
|
||||
pub(super) fn required(&self, field: Field) -> bool {
|
||||
field == Field::Name
|
||||
|| (field == Field::Url && self.provider.as_ref().is_none_or(|p| p.base_url.is_some()))
|
||||
}
|
||||
|
||||
pub(super) fn patch(&self) -> Result<ModelProviderConfigWriteParams, &'static str> {
|
||||
if self.provider.as_ref().is_some_and(|p| !p.can_edit) {
|
||||
return Err("This provider configuration is read-only.");
|
||||
}
|
||||
for (field, original) in self.fields() {
|
||||
if self.required(field) && self.value(field, original).trim().is_empty() {
|
||||
return Err(if field == Field::Name {
|
||||
"Enter a provider name."
|
||||
} else {
|
||||
"Enter a base URL."
|
||||
});
|
||||
}
|
||||
}
|
||||
if let Some(key) = self.changes.get(&Field::Variable)
|
||||
&& !key.is_empty()
|
||||
{
|
||||
let original_url = self.provider.as_ref().and_then(|p| p.base_url.as_deref());
|
||||
if self.value(Field::Url, original_url).trim().is_empty() {
|
||||
return Err("Enter a base URL to use this API key variable.");
|
||||
}
|
||||
if !(key.starts_with(|c: char| c.is_ascii_alphabetic() || c == '_')
|
||||
&& key.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_'))
|
||||
{
|
||||
return Err("Enter an environment variable name such as TEAM_API_KEY.");
|
||||
}
|
||||
}
|
||||
let changed = |field| {
|
||||
self.changes
|
||||
.get(&field)
|
||||
.map(|s| (!s.is_empty()).then(|| s.clone()))
|
||||
};
|
||||
let provider = self.provider.as_ref();
|
||||
let settings = ProviderSettingsPatch::CustomGateway(CustomGatewaySettingsParams {
|
||||
provider_id: provider.map(|p| p.id.clone()),
|
||||
name: self.changes.get(&Field::Name).cloned(),
|
||||
base_url: changed(Field::Url),
|
||||
env_key: changed(Field::Variable),
|
||||
});
|
||||
Ok(ModelProviderConfigWriteParams { settings })
|
||||
}
|
||||
}
|
||||
144
akode-rs/tui/src/app/provider/editor_tests.rs
Normal file
144
akode-rs/tui/src/app/provider/editor_tests.rs
Normal file
@@ -0,0 +1,144 @@
|
||||
#![cfg(test)]
|
||||
|
||||
use super::*;
|
||||
use crate::app::test_support::make_test_app;
|
||||
use crate::chatwidget::tests::render_bottom_popup;
|
||||
use akode_app_server_protocol::GatewayAuth;
|
||||
use akode_app_server_protocol::ModelProviderSummary;
|
||||
use akode_app_server_protocol::ProviderSettings;
|
||||
use crossterm::event::KeyEventKind;
|
||||
use crossterm::event::KeyModifiers;
|
||||
use pretty_assertions::assert_eq;
|
||||
use serde_json::json;
|
||||
|
||||
fn wire(params: ModelProviderConfigWriteParams) -> serde_json::Value {
|
||||
serde_json::to_value(params.settings).unwrap()
|
||||
}
|
||||
|
||||
fn gateway(auth: GatewayAuth) -> ModelProviderSummary {
|
||||
ModelProviderSummary {
|
||||
id: "team".into(),
|
||||
name: "Team".into(),
|
||||
can_edit: true,
|
||||
base_url: Some("https://old.example".into()),
|
||||
settings: ProviderSettings::CustomGateway { auth },
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn clearing_configured_url_keeps_the_form_open_until_corrected() {
|
||||
let mut app = make_test_app().await;
|
||||
app.chat_widget.toggle_vim_mode_and_notify();
|
||||
let mut provider = gateway(GatewayAuth::EnvironmentVariable {
|
||||
env_key: "TEAM_KEY".into(),
|
||||
});
|
||||
provider.name = "Team\ngateway".into();
|
||||
let draft = Draft::new(Some(provider.clone()), &[provider]);
|
||||
let (tx, rx) = std::sync::mpsc::channel();
|
||||
let mut form = view(&app, draft, /*error*/ None, move |draft, params| {
|
||||
tx.send((draft, params)).unwrap()
|
||||
});
|
||||
assert!(form.prefer_esc_to_handle_key_event());
|
||||
assert_eq!(
|
||||
form.cursor_style(Rect::default()),
|
||||
SetCursorStyle::SteadyBar
|
||||
);
|
||||
form.handle_key_event(KeyCode::Esc.into());
|
||||
assert!(!form.prefer_esc_to_handle_key_event());
|
||||
form.handle_key_event(KeyCode::Char('i').into());
|
||||
assert!(form.prefer_esc_to_handle_key_event());
|
||||
form.handle_key_event(KeyCode::Tab.into());
|
||||
for _ in 0.."https://old.example".len() {
|
||||
form.handle_key_event(KeyCode::Backspace.into());
|
||||
}
|
||||
let area = Rect::new(2, 4, 12, 24);
|
||||
let mut buf = Buffer::empty(area);
|
||||
form.render(area, &mut buf);
|
||||
assert_eq!(buf[form.cursor_pos(area).unwrap()].symbol(), "h");
|
||||
let chat = &mut app.chat_widget;
|
||||
chat.show_bottom_pane_view(form);
|
||||
for key in [KeyCode::Tab, KeyCode::Tab, KeyCode::Enter] {
|
||||
chat.handle_key_event(key.into());
|
||||
}
|
||||
assert!(rx.try_recv().is_err());
|
||||
assert!(render_bottom_popup(chat, /*width*/ 72).contains("Enter a base URL."));
|
||||
for _ in 0..2 {
|
||||
let back = KeyEvent::new(KeyCode::Tab, KeyModifiers::SHIFT);
|
||||
chat.handle_key_event(back);
|
||||
chat.handle_key_event(KeyEvent {
|
||||
kind: KeyEventKind::Release,
|
||||
..back
|
||||
});
|
||||
}
|
||||
chat.handle_paste("https://new.example".into());
|
||||
chat.handle_key_event(KeyCode::Tab.into());
|
||||
chat.handle_key_event(KeyCode::Tab.into());
|
||||
chat.handle_key_event(KeyEvent {
|
||||
kind: KeyEventKind::Repeat,
|
||||
..KeyCode::Enter.into()
|
||||
});
|
||||
assert!(rx.try_recv().is_err());
|
||||
chat.handle_key_event(KeyCode::Enter.into());
|
||||
let (draft, params) = rx.try_recv().unwrap();
|
||||
assert_eq!(
|
||||
wire(params),
|
||||
json!({"type":"customGateway", "providerId":"team", "baseUrl":"https://new.example"})
|
||||
);
|
||||
let error = "Server validation failed.";
|
||||
let retry = view(&app, draft, Some(error.into()), |_, _| {});
|
||||
app.chat_widget
|
||||
.replace_bottom_pane_view_if_present(VIEW_ID, retry);
|
||||
let rendered = render_bottom_popup(&app.chat_widget, /*width*/ 72);
|
||||
assert!(rendered.contains("https://new.example"));
|
||||
assert!(rendered.contains(error));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn hidden_gateway_settings_stay_out_of_rename_patch() {
|
||||
let mut provider = gateway(GatewayAuth::ExternallyConfigured {
|
||||
env_key: Some("EXTERNAL".into()),
|
||||
});
|
||||
provider.base_url = None;
|
||||
let mut draft = Draft::new(Some(provider), &[]);
|
||||
assert_eq!(draft.fields(), vec![(Field::Name, Some("Team"))]);
|
||||
draft.changes.insert(Field::Name, "Renamed".into());
|
||||
assert_eq!(
|
||||
wire(draft.patch().unwrap()),
|
||||
json!({"type":"customGateway", "providerId":"team", "name":"Renamed"})
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn entering_a_key_for_a_legacy_gateway_prompts_for_its_address() {
|
||||
let mut app = make_test_app().await;
|
||||
let mut provider = gateway(GatewayAuth::None);
|
||||
provider.base_url = None;
|
||||
let form = view(
|
||||
&app,
|
||||
Draft::new(Some(provider), &[]),
|
||||
/*error*/ None,
|
||||
|_, _| {
|
||||
panic!("submitted a gateway key without an endpoint");
|
||||
},
|
||||
);
|
||||
let chat = &mut app.chat_widget;
|
||||
chat.show_bottom_pane_view(form);
|
||||
chat.handle_key_event(KeyCode::Tab.into());
|
||||
chat.handle_key_event(KeyCode::Tab.into());
|
||||
chat.handle_paste("TEAM_KEY".into());
|
||||
chat.handle_key_event(KeyCode::Tab.into());
|
||||
chat.handle_key_event(KeyCode::Enter.into());
|
||||
insta::assert_snapshot!(render_bottom_popup(chat, /*width*/ 72), @r"
|
||||
Edit Team
|
||||
|
||||
Name* Team
|
||||
Base URL* https://gateway.example/v1
|
||||
API key variable $TEAM_KEY
|
||||
› Save
|
||||
Enter a base URL to use this API key variable.
|
||||
|
||||
* Required
|
||||
Enter the environment variable name on the app server.
|
||||
tab move · enter next/save · esc back
|
||||
");
|
||||
}
|
||||
45
akode-rs/tui/src/app/provider/fields.rs
Normal file
45
akode-rs/tui/src/app/provider/fields.rs
Normal file
@@ -0,0 +1,45 @@
|
||||
//! Fields reported by the server for each provider, including values it manages externally.
|
||||
|
||||
use akode_app_server_protocol::GatewayAuth;
|
||||
use akode_app_server_protocol::ModelProviderSummary;
|
||||
use akode_app_server_protocol::ProviderSettings;
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
|
||||
pub(super) enum Field {
|
||||
Name,
|
||||
Url,
|
||||
ManagedUrl,
|
||||
Variable,
|
||||
ExternalAuth,
|
||||
}
|
||||
|
||||
impl Field {
|
||||
pub(super) fn label(self) -> &'static str {
|
||||
match self {
|
||||
Self::Name => "Name",
|
||||
Self::Url | Self::ManagedUrl => "Base URL",
|
||||
Self::Variable => "API key variable",
|
||||
Self::ExternalAuth => "External authentication",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn provider_fields(provider: &ModelProviderSummary) -> Vec<(Field, Option<&str>)> {
|
||||
let url = provider.base_url.as_deref();
|
||||
let ProviderSettings::CustomGateway { auth } = &provider.settings;
|
||||
let auth_field = match auth {
|
||||
GatewayAuth::None => (Field::Variable, None),
|
||||
GatewayAuth::EnvironmentVariable { env_key } => (Field::Variable, Some(env_key.as_str())),
|
||||
GatewayAuth::ExternallyConfigured { env_key } => (Field::ExternalAuth, env_key.as_deref()),
|
||||
};
|
||||
let endpoint = if auth_field.0 == Field::ExternalAuth && url.is_none() {
|
||||
Field::ManagedUrl
|
||||
} else {
|
||||
Field::Url
|
||||
};
|
||||
vec![
|
||||
(Field::Name, Some(provider.name.as_str())),
|
||||
(endpoint, url),
|
||||
auth_field,
|
||||
]
|
||||
}
|
||||
106
akode-rs/tui/src/app/provider/rpc.rs
Normal file
106
akode-rs/tui/src/app/provider/rpc.rs
Normal file
@@ -0,0 +1,106 @@
|
||||
//! Provider catalog and config writes used by the settings panel and sign-in wizard.
|
||||
|
||||
use akode_app_server_client::AppServerRequestHandle;
|
||||
use akode_app_server_client::TypedRequestError;
|
||||
use akode_app_server_protocol::ClientRequest;
|
||||
use akode_app_server_protocol::ConfigValueWriteParams;
|
||||
use akode_app_server_protocol::ConfigWriteResponse;
|
||||
use akode_app_server_protocol::MergeStrategy;
|
||||
use akode_app_server_protocol::ModelProviderConfigWriteParams;
|
||||
use akode_app_server_protocol::ModelProviderConfigWriteResponse;
|
||||
use akode_app_server_protocol::ModelProviderListParams;
|
||||
use akode_app_server_protocol::ModelProviderListResponse;
|
||||
use akode_app_server_protocol::ModelProviderSummary;
|
||||
use akode_app_server_protocol::ProviderSettingsPatch;
|
||||
use akode_app_server_protocol::RequestId;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub(crate) const UNCONFIRMED_CREATE: &str =
|
||||
"Could not confirm the save. Check the provider list before adding it again.";
|
||||
|
||||
pub(crate) enum ProviderWrite {
|
||||
Saved(ModelProviderSummary),
|
||||
UnconfirmedCreate,
|
||||
}
|
||||
|
||||
pub(crate) async fn list_providers(
|
||||
handle: &AppServerRequestHandle,
|
||||
) -> Result<ModelProviderListResponse, String> {
|
||||
handle
|
||||
.request_typed(ClientRequest::ModelProviderList {
|
||||
request_id: RequestId::String(Uuid::new_v4().to_string()),
|
||||
params: ModelProviderListParams {},
|
||||
})
|
||||
.await
|
||||
.map_err(request_error)
|
||||
}
|
||||
|
||||
pub(crate) async fn write_provider(
|
||||
handle: &AppServerRequestHandle,
|
||||
params: ModelProviderConfigWriteParams,
|
||||
) -> Result<ProviderWrite, String> {
|
||||
let create = matches!(¶ms.settings, ProviderSettingsPatch::CustomGateway(gateway) if gateway.provider_id.is_none());
|
||||
match handle
|
||||
.request_typed::<ModelProviderConfigWriteResponse>(
|
||||
ClientRequest::ModelProviderConfigWrite {
|
||||
request_id: RequestId::String(Uuid::new_v4().to_string()),
|
||||
params,
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(response) => Ok(ProviderWrite::Saved(response.provider)),
|
||||
// A lost reply or a failed read-back can follow a committed write.
|
||||
Err(err)
|
||||
if create
|
||||
&& match &err {
|
||||
TypedRequestError::Server { source, .. } => source.code == -32603,
|
||||
TypedRequestError::Transport { .. } | TypedRequestError::Deserialize { .. } => {
|
||||
true
|
||||
}
|
||||
} =>
|
||||
{
|
||||
Ok(ProviderWrite::UnconfirmedCreate)
|
||||
}
|
||||
Err(TypedRequestError::Server { source, .. }) => Err(source.message),
|
||||
Err(err) => Err(err.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn set_default_provider(
|
||||
handle: &AppServerRequestHandle,
|
||||
id: &str,
|
||||
) -> Result<ConfigWriteResponse, TypedRequestError> {
|
||||
handle
|
||||
.request_typed(ClientRequest::ConfigValueWrite {
|
||||
request_id: RequestId::String(Uuid::new_v4().to_string()),
|
||||
params: ConfigValueWriteParams {
|
||||
key_path: "model_provider".into(),
|
||||
value: id.into(),
|
||||
merge_strategy: MergeStrategy::Replace,
|
||||
file_path: None,
|
||||
expected_version: None,
|
||||
},
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
pub(crate) fn override_reason(response: ConfigWriteResponse) -> String {
|
||||
response
|
||||
.overridden_metadata
|
||||
.map(|metadata| metadata.message)
|
||||
.unwrap_or_else(|| "A higher-priority setting overrides this choice.".into())
|
||||
}
|
||||
|
||||
pub(super) fn request_error(err: TypedRequestError) -> String {
|
||||
if let TypedRequestError::Server { method, source } = &err
|
||||
&& (source.code == -32601
|
||||
|| (source.code == -32600
|
||||
&& source
|
||||
.message
|
||||
.starts_with(&format!("Invalid request: unknown variant `{method}`"))))
|
||||
{
|
||||
return "Update the connected app server to browse model providers.".into();
|
||||
}
|
||||
format!("Could not load model providers: {err}")
|
||||
}
|
||||
197
akode-rs/tui/src/app/provider/write.rs
Normal file
197
akode-rs/tui/src/app/provider/write.rs
Normal file
@@ -0,0 +1,197 @@
|
||||
//! Persist a provider choice on its originating backend, leaving running threads untouched.
|
||||
|
||||
use super::App;
|
||||
use super::AppEvent;
|
||||
use super::AppServerSession;
|
||||
use super::BackendId;
|
||||
use super::Event;
|
||||
use super::LIST_VIEW;
|
||||
use super::LOADING_VIEW;
|
||||
use super::edit_view;
|
||||
use super::editor;
|
||||
use super::loading_with_notice;
|
||||
use super::progress;
|
||||
use super::rpc;
|
||||
use akode_app_server_client::AppServerRequestHandle;
|
||||
use akode_app_server_client::TypedRequestError;
|
||||
use akode_app_server_protocol::ModelProviderConfigWriteParams;
|
||||
use akode_app_server_protocol::WriteStatus;
|
||||
use tokio::sync::watch;
|
||||
|
||||
const SAVING_VIEW: &str = "model_provider_saving";
|
||||
|
||||
#[derive(derive_more::Debug, Clone)]
|
||||
pub(crate) enum Write {
|
||||
Default(String),
|
||||
#[debug("Settings(..)")]
|
||||
Settings(Box<(editor::Draft, ModelProviderConfigWriteParams)>),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct Completion {
|
||||
backend: BackendId,
|
||||
dismissed: watch::Receiver<()>,
|
||||
write: Write,
|
||||
result: Result<SaveNotice, String>,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
enum SaveNotice {
|
||||
Saved(String),
|
||||
UnconfirmedCreate,
|
||||
}
|
||||
|
||||
impl Write {
|
||||
pub(super) fn start(self, app: &mut App, server: &AppServerSession) {
|
||||
let backend = server.backend_id();
|
||||
let write = app
|
||||
.provider_writes
|
||||
.entry(backend)
|
||||
.or_insert_with(|| app.model_catalog.provider_write.clone());
|
||||
let Ok(mut provider_changed) = write.clone().try_lock_owned() else {
|
||||
app.chat_widget
|
||||
.add_error_message("A provider change is already saving.".into());
|
||||
return;
|
||||
};
|
||||
let (view, dismissed) = progress(SAVING_VIEW, "Saving model provider…");
|
||||
let source = match self {
|
||||
Self::Default(_) => LIST_VIEW,
|
||||
Self::Settings(_) => editor::VIEW_ID,
|
||||
};
|
||||
if !app
|
||||
.chat_widget
|
||||
.replace_selection_view_if_present(source, view)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let handle = server.request_handle();
|
||||
let tx = app.app_event_tx.clone();
|
||||
let offline = app.reconnect.offline;
|
||||
tokio::spawn(async move {
|
||||
let result = if offline {
|
||||
Err("Could not save provider: Reconnect to the app server and try again.".into())
|
||||
} else {
|
||||
self.run(&handle, &mut provider_changed).await
|
||||
};
|
||||
drop(provider_changed);
|
||||
tx.send(AppEvent::Provider(Event::Written(Completion {
|
||||
backend,
|
||||
dismissed,
|
||||
write: self,
|
||||
result,
|
||||
})));
|
||||
});
|
||||
}
|
||||
|
||||
async fn run(
|
||||
&self,
|
||||
handle: &AppServerRequestHandle,
|
||||
provider_changed: &mut bool,
|
||||
) -> Result<SaveNotice, String> {
|
||||
match self {
|
||||
Self::Settings(settings) => {
|
||||
rpc::write_provider(handle, settings.1.clone())
|
||||
.await
|
||||
.map(|result| match result {
|
||||
rpc::ProviderWrite::Saved(_) => {
|
||||
SaveNotice::Saved("Saved provider configuration.".into())
|
||||
}
|
||||
rpc::ProviderWrite::UnconfirmedCreate => SaveNotice::UnconfirmedCreate,
|
||||
})
|
||||
}
|
||||
Self::Default(id) => {
|
||||
let response = rpc::set_default_provider(handle, id)
|
||||
.await
|
||||
.map_err(|error| match error {
|
||||
TypedRequestError::Server { .. } => {
|
||||
format!("Could not save provider: {error}")
|
||||
}
|
||||
TypedRequestError::Transport { .. }
|
||||
| TypedRequestError::Deserialize { .. } => {
|
||||
// The server may have committed the write before its reply was lost.
|
||||
*provider_changed = true;
|
||||
format!("Could not confirm whether {id} was saved: {error}")
|
||||
}
|
||||
})?;
|
||||
match response.status {
|
||||
WriteStatus::Ok => {
|
||||
*provider_changed = true;
|
||||
Ok(SaveNotice::Saved(format!(
|
||||
"/new now uses {id}. Restart the app server and TUI to refresh /model."
|
||||
)))
|
||||
}
|
||||
WriteStatus::OkOverridden => {
|
||||
let reason = rpc::override_reason(response);
|
||||
Ok(SaveNotice::Saved(format!("Saved {id}. {reason}")))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Completion {
|
||||
pub(super) fn finish(self, app: &mut App, backend: BackendId) {
|
||||
if backend != self.backend {
|
||||
return;
|
||||
}
|
||||
let present = matches!(self.dismissed.has_changed(), Ok(false));
|
||||
if app.model_catalog.provider_may_have_changed() {
|
||||
app.chat_widget.dismiss_stale_model_picker();
|
||||
}
|
||||
match self.result {
|
||||
Ok(notice) => {
|
||||
let message = match notice {
|
||||
SaveNotice::Saved(message) => {
|
||||
if !present {
|
||||
app.chat_widget
|
||||
.add_info_message(message.clone(), /*hint*/ None);
|
||||
}
|
||||
message
|
||||
}
|
||||
SaveNotice::UnconfirmedCreate => {
|
||||
let message = rpc::UNCONFIRMED_CREATE.to_string();
|
||||
app.chat_widget.add_error_message(message.clone());
|
||||
message
|
||||
}
|
||||
};
|
||||
if present {
|
||||
let view = match self.write {
|
||||
Write::Default(_) => SAVING_VIEW,
|
||||
Write::Settings(_) => {
|
||||
app.chat_widget.dismiss_provider_view(SAVING_VIEW);
|
||||
LIST_VIEW
|
||||
}
|
||||
};
|
||||
reload(app, view, Some(message));
|
||||
} else if !reload(app, LIST_VIEW, /*notice*/ None) {
|
||||
// A reopened picker may have started reading before this write committed.
|
||||
reload(app, LOADING_VIEW, /*notice*/ None);
|
||||
}
|
||||
}
|
||||
Err(error) if present => {
|
||||
if let Write::Settings(settings) = self.write {
|
||||
let view = edit_view(app, backend, settings.0, Some(error));
|
||||
app.chat_widget
|
||||
.replace_bottom_pane_view_if_present(SAVING_VIEW, view);
|
||||
return;
|
||||
}
|
||||
app.chat_widget.add_error_message(error.clone());
|
||||
reload(app, SAVING_VIEW, Some(error));
|
||||
}
|
||||
Err(error) => app.chat_widget.add_error_message(error),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn reload(app: &mut App, view_id: &'static str, notice: Option<String>) -> bool {
|
||||
let (view, load) = loading_with_notice(notice);
|
||||
if app
|
||||
.chat_widget
|
||||
.replace_selection_view_if_present(view_id, view)
|
||||
{
|
||||
app.app_event_tx.send(AppEvent::Provider(load));
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
500
akode-rs/tui/src/app/provider_tests.rs
Normal file
500
akode-rs/tui/src/app/provider_tests.rs
Normal file
@@ -0,0 +1,500 @@
|
||||
//! Provider browsing through loading, startup attachment, nested views, and dismissal.
|
||||
#![cfg(test)]
|
||||
|
||||
use super::*;
|
||||
use crate::app::tests::make_test_app_with_channels;
|
||||
use crate::app::tests::test_thread_session;
|
||||
use crate::chatwidget::tests::render_bottom_popup;
|
||||
use crate::config_panel::ConfigEditor;
|
||||
use crate::config_panel::ConfigEditorHandoff;
|
||||
use crate::config_panel::ResumeCurrentAvailability;
|
||||
use crate::model_catalog::ModelCatalog;
|
||||
use crate::tui::TuiEvent;
|
||||
use crate::tui::test_support::make_test_tui;
|
||||
use akode_app_server_client::TypedRequestError;
|
||||
use akode_app_server_protocol::GatewayAuth;
|
||||
use akode_app_server_protocol::ProviderSettings;
|
||||
use akode_protocol::ThreadId;
|
||||
use color_eyre::eyre::Result;
|
||||
use crossterm::event::KeyCode;
|
||||
use crossterm::event::KeyEvent;
|
||||
use crossterm::event::KeyModifiers;
|
||||
use pretty_assertions::assert_eq;
|
||||
use ratatui::Terminal;
|
||||
use ratatui::backend::TestBackend;
|
||||
use tokio::sync::mpsc::UnboundedReceiver;
|
||||
|
||||
async fn next_provider_event(rx: &mut UnboundedReceiver<AppEvent>) -> Event {
|
||||
loop {
|
||||
if let AppEvent::Provider(event) = rx.recv().await.expect("open event channel") {
|
||||
return event;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn loading_survives_initial_attachment_and_refreshes_under_an_overlay() -> Result<()> {
|
||||
let (mut app, mut events, _ops) = make_test_app_with_channels().await;
|
||||
let mut tui = make_test_tui()?;
|
||||
std::fs::write(
|
||||
app.config.codex_home.join("config.toml"),
|
||||
r#"model_providers.gateway = { name = "Example Gateway", base_url = "http://127.0.0.1:9/v1" }"#,
|
||||
)?;
|
||||
let mut server = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?;
|
||||
app.chat_widget.open_config_panel();
|
||||
let handoff = ConfigEditorHandoff::new(
|
||||
ConfigEditor::ModelProviders,
|
||||
crate::key_hint::plain(KeyCode::Enter),
|
||||
);
|
||||
handoff.mark_activation_inactive();
|
||||
app.chat_widget
|
||||
.open_config_editor(handoff, ResumeCurrentAvailability::Available);
|
||||
assert!(app.chat_widget.thread_id().is_none());
|
||||
handle(
|
||||
&mut app,
|
||||
&mut tui,
|
||||
&server,
|
||||
next_provider_event(&mut events).await,
|
||||
);
|
||||
let loaded = next_provider_event(&mut events).await;
|
||||
let session = test_thread_session(ThreadId::new(), app.config.cwd.to_path_buf());
|
||||
app.chat_widget.handle_thread_session_quiet(session);
|
||||
app.chat_widget.show_selection_view(SelectionViewParams {
|
||||
view_id: Some("test_overlay"),
|
||||
items: vec![back()],
|
||||
..Default::default()
|
||||
});
|
||||
handle(&mut app, &mut tui, &server, loaded);
|
||||
assert!(app.chat_widget.active_view_is("test_overlay"));
|
||||
app.chat_widget.handle_key_event(KeyCode::Esc.into());
|
||||
assert!(app.chat_widget.active_view_is(LIST_VIEW));
|
||||
app.chat_widget.handle_key_event(KeyCode::Enter.into());
|
||||
handle(
|
||||
&mut app,
|
||||
&mut tui,
|
||||
&server,
|
||||
next_provider_event(&mut events).await,
|
||||
);
|
||||
assert!(matches!(app.overlay, Some(Overlay::Static(_))));
|
||||
app.handle_backtrack_overlay_event(
|
||||
&mut tui,
|
||||
&mut server,
|
||||
TuiEvent::Key(KeyCode::Char('q').into()),
|
||||
)
|
||||
.await?;
|
||||
assert!(app.overlay.is_none());
|
||||
assert!(app.chat_widget.active_view_is(LIST_VIEW));
|
||||
|
||||
// A late result cannot replace a new loading popup after Back and reopen.
|
||||
app.chat_widget.handle_key_event(KeyCode::Esc.into());
|
||||
let (view, load) = loading();
|
||||
app.chat_widget.show_selection_view(view);
|
||||
handle(&mut app, &mut tui, &server, load);
|
||||
let stale = next_provider_event(&mut events).await;
|
||||
app.chat_widget.handle_key_event(KeyCode::Enter.into());
|
||||
let (view, _load) = loading();
|
||||
app.chat_widget.show_selection_view(view);
|
||||
handle(&mut app, &mut tui, &server, stale);
|
||||
assert!(app.chat_widget.active_view_is(LOADING_VIEW));
|
||||
server.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn provider_views_show_reported_endpoints_and_ids_outside_the_catalog() -> Result<()> {
|
||||
let (mut app, mut events, _ops) = make_test_app_with_channels().await;
|
||||
let mut tui = make_test_tui()?;
|
||||
let server = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?;
|
||||
let provider = ModelProviderSummary {
|
||||
id: "office".into(),
|
||||
name: "Office".into(),
|
||||
can_edit: false,
|
||||
base_url: Some(
|
||||
"https://example.test/organization/deployment/region/service/office/v1".into(),
|
||||
),
|
||||
settings: ProviderSettings::CustomGateway {
|
||||
auth: GatewayAuth::ExternallyConfigured { env_key: None },
|
||||
},
|
||||
};
|
||||
let page = ModelProviderListResponse {
|
||||
data: vec![provider],
|
||||
default_provider_id: "lmstudio".into(),
|
||||
can_change_default: true,
|
||||
};
|
||||
app.chat_widget.show_selection_view(list(
|
||||
Some("ollama"),
|
||||
Arc::new(Catalog {
|
||||
backend: server.backend_id(),
|
||||
page,
|
||||
}),
|
||||
/*client_override*/ None,
|
||||
&app.keymap.list,
|
||||
/*notice*/ None,
|
||||
));
|
||||
insta::assert_snapshot!(
|
||||
"provider_list",
|
||||
render_bottom_popup(&app.chat_widget, /*width*/ 80)
|
||||
);
|
||||
|
||||
app.chat_widget.handle_key_event(KeyCode::Enter.into());
|
||||
handle(
|
||||
&mut app,
|
||||
&mut tui,
|
||||
&server,
|
||||
next_provider_event(&mut events).await,
|
||||
);
|
||||
let Some(Overlay::Static(pager)) = &mut app.overlay else {
|
||||
panic!("expected provider details pager");
|
||||
};
|
||||
let mut terminal = Terminal::new(TestBackend::new(/*width*/ 48, /*height*/ 9))?;
|
||||
terminal.draw(|frame| pager.render(frame.area(), frame.buffer_mut()))?;
|
||||
let first_page = terminal.backend().to_string();
|
||||
pager.handle_event(&mut tui, TuiEvent::Key(KeyCode::PageDown.into()))?;
|
||||
terminal.draw(|frame| pager.render(frame.area(), frame.buffer_mut()))?;
|
||||
insta::assert_snapshot!(
|
||||
"read_only_provider_details",
|
||||
format!("{first_page}\n{}", terminal.backend())
|
||||
);
|
||||
server.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "current_thread")]
|
||||
async fn space_saves_once_retries_and_preserves_the_current_chat() -> Result<()> {
|
||||
let (mut app, mut events, _ops) = make_test_app_with_channels().await;
|
||||
let mut tui = make_test_tui()?;
|
||||
std::fs::write(
|
||||
app.config.codex_home.join("config.toml"),
|
||||
concat!(
|
||||
"model_providers.gateway = { name = \"Example Gateway\", base_url = \"http://127.0.0.1:9/v1\" }\n",
|
||||
"model_providers.office = { name = \"Office Gateway\", base_url = \"http://127.0.0.1:9/v1\" }\n",
|
||||
),
|
||||
)?;
|
||||
let server = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?;
|
||||
let session = test_thread_session(ThreadId::new(), app.config.cwd.to_path_buf());
|
||||
let original = session.model_provider_id.clone();
|
||||
app.chat_widget.handle_thread_session_quiet(session);
|
||||
let (view, load) = loading();
|
||||
app.chat_widget.show_selection_view(view);
|
||||
handle(&mut app, &mut tui, &server, load);
|
||||
handle(
|
||||
&mut app,
|
||||
&mut tui,
|
||||
&server,
|
||||
next_provider_event(&mut events).await,
|
||||
);
|
||||
|
||||
// Disconnection after the picker opened must release its write guard for retry.
|
||||
app.chat_widget.handle_key_event(KeyCode::Home.into());
|
||||
app.reconnect.offline = true;
|
||||
app.chat_widget.handle_key_event(KeyCode::Char(' ').into());
|
||||
handle(
|
||||
&mut app,
|
||||
&mut tui,
|
||||
&server,
|
||||
next_provider_event(&mut events).await,
|
||||
);
|
||||
app.reconnect.offline = false;
|
||||
while !app.chat_widget.active_view_is(LIST_VIEW) {
|
||||
handle(
|
||||
&mut app,
|
||||
&mut tui,
|
||||
&server,
|
||||
next_provider_event(&mut events).await,
|
||||
);
|
||||
}
|
||||
let retried = render_bottom_popup(&app.chat_widget, /*width*/ 100);
|
||||
assert!(retried.contains("Could not save provider: Reconnect"));
|
||||
assert!(!app.model_catalog.provider_may_have_changed());
|
||||
|
||||
app.chat_widget.handle_key_event(KeyCode::Home.into());
|
||||
app.chat_widget.handle_key_event(KeyCode::Char(' ').into());
|
||||
handle(
|
||||
&mut app,
|
||||
&mut tui,
|
||||
&server,
|
||||
next_provider_event(&mut events).await,
|
||||
);
|
||||
// The spawned RPC cannot run until this current-thread test yields.
|
||||
write::Write::Default("openai".into()).start(&mut app, &server);
|
||||
assert!(std::iter::from_fn(|| events.try_recv().ok()).any(|event| {
|
||||
matches!(event, AppEvent::InsertHistoryCell(cell) if cell.display_lines(/*width*/ 100)[0]
|
||||
.to_string().contains("A provider change is already saving."))
|
||||
}));
|
||||
|
||||
// Wait for the RPC without dispatching its completion on the original event channel.
|
||||
let backend = server.backend_id();
|
||||
assert!(*app.provider_writes[&backend].lock().await);
|
||||
let other =
|
||||
ModelCatalog::new(Vec::new()).for_backend(BackendId::new(), &mut app.provider_writes);
|
||||
assert!(!other.provider_may_have_changed());
|
||||
let reconnected = ModelCatalog::new(Vec::new()).for_backend(backend, &mut app.provider_writes);
|
||||
assert!(reconnected.provider_may_have_changed());
|
||||
app.chat_widget.show_selection_view(SelectionViewParams {
|
||||
view_id: Some("test_overlay"),
|
||||
items: vec![back()],
|
||||
..Default::default()
|
||||
});
|
||||
handle(
|
||||
&mut app,
|
||||
&mut tui,
|
||||
&server,
|
||||
next_provider_event(&mut events).await,
|
||||
);
|
||||
assert!(app.chat_widget.model_picker_unavailable().is_some());
|
||||
handle(
|
||||
&mut app,
|
||||
&mut tui,
|
||||
&server,
|
||||
next_provider_event(&mut events).await,
|
||||
);
|
||||
handle(
|
||||
&mut app,
|
||||
&mut tui,
|
||||
&server,
|
||||
next_provider_event(&mut events).await,
|
||||
);
|
||||
assert!(app.chat_widget.active_view_is("test_overlay"));
|
||||
app.chat_widget.handle_key_event(KeyCode::Esc.into());
|
||||
app.chat_widget.handle_key_event(KeyCode::Home.into());
|
||||
assert_eq!(app.chat_widget.config_ref().model_provider_id, original);
|
||||
insta::assert_snapshot!(
|
||||
"saved_default_provider",
|
||||
render_bottom_popup(&app.chat_widget, /*width*/ 100)
|
||||
);
|
||||
|
||||
// Switch back, then dismiss the picker before the save result is delivered.
|
||||
app.chat_widget.handle_key_event(KeyCode::End.into());
|
||||
app.chat_widget.handle_key_event(KeyCode::Up.into());
|
||||
app.chat_widget.handle_key_event(KeyCode::Char(' ').into());
|
||||
handle(
|
||||
&mut app,
|
||||
&mut tui,
|
||||
&server,
|
||||
next_provider_event(&mut events).await,
|
||||
);
|
||||
app.chat_widget.handle_key_event(KeyCode::Esc.into());
|
||||
handle(
|
||||
&mut app,
|
||||
&mut tui,
|
||||
&server,
|
||||
next_provider_event(&mut events).await,
|
||||
);
|
||||
let cell = std::iter::from_fn(|| events.try_recv().ok())
|
||||
.filter_map(|event| match event {
|
||||
AppEvent::InsertHistoryCell(cell) => Some(cell),
|
||||
_ => None,
|
||||
})
|
||||
.last()
|
||||
.expect("restart hint in history");
|
||||
insta::assert_snapshot!(cell.display_lines(/*width*/ 160)[0].to_string(), @"• /new now uses office. Restart the app server and TUI to refresh /model.");
|
||||
server.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn only_ambiguous_write_failures_invalidate_the_model_catalog() {
|
||||
use akode_app_server_client::AppServerClient;
|
||||
use akode_app_server_client::CloudClient;
|
||||
use akode_app_server_protocol::JSONRPCErrorError;
|
||||
|
||||
let rejected = Ok(Err(JSONRPCErrorError {
|
||||
code: -32602,
|
||||
message: "Rejected".into(),
|
||||
data: None,
|
||||
}));
|
||||
let overridden = Ok(Ok(serde_json::json!({
|
||||
"status": "okOverridden", "version": "1", "filePath": std::env::temp_dir().join("config.toml")
|
||||
})));
|
||||
let disconnected = Err(std::io::Error::other("connection lost"));
|
||||
let unreadable = Ok(Ok(serde_json::Value::Null));
|
||||
for (reply, stale) in [
|
||||
(rejected, false),
|
||||
(overridden, false),
|
||||
(disconnected, true),
|
||||
(unreadable, true),
|
||||
] {
|
||||
let (mut app, mut events, _ops) = make_test_app_with_channels().await;
|
||||
let (client, mut commands, _server_events) = CloudClient::channel(/*capacity*/ 1);
|
||||
let backend = BackendId::new();
|
||||
let server = AppServerSession::new(
|
||||
backend,
|
||||
AppServerClient::Cloud(client),
|
||||
crate::app_server_session::ThreadParamsMode::Remote,
|
||||
);
|
||||
app.chat_widget.show_selection_view(SelectionViewParams {
|
||||
view_id: Some(LIST_VIEW),
|
||||
items: vec![back()],
|
||||
..Default::default()
|
||||
});
|
||||
write::Write::Default("gateway".into()).start(&mut app, &server);
|
||||
let command = commands.recv().await.expect("config write");
|
||||
command
|
||||
.response
|
||||
.send(reply)
|
||||
.expect("write is awaiting a response");
|
||||
assert!(matches!(
|
||||
next_provider_event(&mut events).await,
|
||||
Event::Written(_)
|
||||
));
|
||||
let reconnected =
|
||||
ModelCatalog::new(Vec::new()).for_backend(backend, &mut app.provider_writes);
|
||||
assert_eq!(reconnected.provider_may_have_changed(), stale);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unsupported_list_method_explains_server_compatibility() {
|
||||
for (code, message) in [
|
||||
(-32601, "Method not found"),
|
||||
(
|
||||
-32600,
|
||||
"Invalid request: unknown variant `modelProvider/list`",
|
||||
),
|
||||
] {
|
||||
let error = TypedRequestError::Server {
|
||||
method: "modelProvider/list".into(),
|
||||
source: akode_app_server_protocol::JSONRPCErrorError {
|
||||
code,
|
||||
message: message.into(),
|
||||
data: None,
|
||||
},
|
||||
};
|
||||
assert_eq!(
|
||||
rpc::request_error(error),
|
||||
"Update the connected app server to browse model providers."
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn list_opened_before_first_attachment_shows_the_attached_provider() -> Result<()> {
|
||||
let (mut app, mut events, _ops) = make_test_app_with_channels().await;
|
||||
let mut tui = make_test_tui()?;
|
||||
let server = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?;
|
||||
let (view, event) = loading();
|
||||
app.chat_widget.show_selection_view(view);
|
||||
handle(&mut app, &mut tui, &server, event);
|
||||
handle(
|
||||
&mut app,
|
||||
&mut tui,
|
||||
&server,
|
||||
next_provider_event(&mut events).await,
|
||||
);
|
||||
assert!(
|
||||
render_bottom_popup(&app.chat_widget, /*width*/ 100)
|
||||
.contains("Current chat: No active chat")
|
||||
);
|
||||
|
||||
let mut session = test_thread_session(ThreadId::new(), app.config.cwd.to_path_buf());
|
||||
session.model_provider_id = "ollama".into();
|
||||
app.chat_widget.handle_thread_session_quiet(session);
|
||||
assert!(app.chat_widget.active_view_is(LOADING_VIEW));
|
||||
handle(
|
||||
&mut app,
|
||||
&mut tui,
|
||||
&server,
|
||||
next_provider_event(&mut events).await,
|
||||
);
|
||||
handle(
|
||||
&mut app,
|
||||
&mut tui,
|
||||
&server,
|
||||
next_provider_event(&mut events).await,
|
||||
);
|
||||
assert!(render_bottom_popup(&app.chat_widget, /*width*/ 100).contains("Current chat: ollama"));
|
||||
server.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn adding_a_custom_provider_saves_to_the_server_and_preserves_the_default() -> Result<()> {
|
||||
let (mut app, mut events, _ops) = make_test_app_with_channels().await;
|
||||
let mut tui = make_test_tui()?;
|
||||
std::fs::write(
|
||||
app.config.codex_home.join("config.toml"),
|
||||
r#"model_providers.seed = { name = "Existing", env_key = "CATALOG_KEY" }"#,
|
||||
)?;
|
||||
let mut server = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?;
|
||||
let (view, load) = loading();
|
||||
app.chat_widget.show_selection_view(view);
|
||||
handle(&mut app, &mut tui, &server, load);
|
||||
handle(
|
||||
&mut app,
|
||||
&mut tui,
|
||||
&server,
|
||||
next_provider_event(&mut events).await,
|
||||
);
|
||||
// Open the existing gateway's scrollable details and enter its editor.
|
||||
app.chat_widget.handle_key_event(KeyCode::End.into());
|
||||
app.chat_widget.handle_key_event(KeyCode::Up.into());
|
||||
app.chat_widget.handle_key_event(KeyCode::Enter.into());
|
||||
handle(
|
||||
&mut app,
|
||||
&mut tui,
|
||||
&server,
|
||||
next_provider_event(&mut events).await,
|
||||
);
|
||||
let Some(Overlay::Static(pager)) = &mut app.overlay else {
|
||||
panic!("expected provider details pager");
|
||||
};
|
||||
let mut terminal = Terminal::new(TestBackend::new(/*width*/ 72, /*height*/ 12))?;
|
||||
terminal.draw(|frame| pager.render(frame.area(), frame.buffer_mut()))?;
|
||||
insta::assert_snapshot!("editable_provider_details", terminal.backend());
|
||||
app.handle_backtrack_overlay_event(&mut tui, &mut server, TuiEvent::Key(KeyCode::Enter.into()))
|
||||
.await?;
|
||||
handle(
|
||||
&mut app,
|
||||
&mut tui,
|
||||
&server,
|
||||
next_provider_event(&mut events).await,
|
||||
);
|
||||
assert!(app.chat_widget.active_view_is(editor::VIEW_ID));
|
||||
assert!(render_bottom_popup(&app.chat_widget, /*width*/ 72).contains("Existing"));
|
||||
app.chat_widget.handle_key_event(KeyCode::Esc.into());
|
||||
|
||||
app.chat_widget.handle_key_event(KeyCode::End.into());
|
||||
app.chat_widget.handle_key_event(KeyCode::Enter.into());
|
||||
handle(
|
||||
&mut app,
|
||||
&mut tui,
|
||||
&server,
|
||||
next_provider_event(&mut events).await,
|
||||
);
|
||||
let chat = &mut app.chat_widget;
|
||||
insta::assert_snapshot!(render_bottom_popup(chat, /*width*/ 72), @r"
|
||||
Create a custom provider or gateway
|
||||
|
||||
› Name* Team gateway
|
||||
Base URL* https://gateway.example/v1
|
||||
API key variable $TEAM_API_KEY
|
||||
Save
|
||||
|
||||
* Required
|
||||
Enter the environment variable name on the app server.
|
||||
tab move · enter next/save · esc back
|
||||
");
|
||||
for value in ["Team gateway", "https://gateway.example.test/v1"] {
|
||||
chat.handle_paste(value.into());
|
||||
chat.handle_key_event(KeyCode::Enter.into());
|
||||
}
|
||||
chat.handle_paste("CAT".into());
|
||||
chat.handle_key_event(KeyEvent::new(KeyCode::Char(' '), KeyModifiers::CONTROL));
|
||||
assert!(render_bottom_popup(chat, /*width*/ 19).contains("$CATALOG_KEY"));
|
||||
chat.handle_key_event(KeyCode::Tab.into());
|
||||
chat.handle_key_event(KeyCode::Enter.into());
|
||||
// Process the write, its completion, and the subsequent catalog reload.
|
||||
for _ in 0..4 {
|
||||
handle(
|
||||
&mut app,
|
||||
&mut tui,
|
||||
&server,
|
||||
next_provider_event(&mut events).await,
|
||||
);
|
||||
}
|
||||
let list = render_bottom_popup(&app.chat_widget, /*width*/ 100);
|
||||
assert!(list.contains("Team gateway"));
|
||||
assert!(list.contains("Default for new chats: none"));
|
||||
server.shutdown().await?;
|
||||
Ok(())
|
||||
}
|
||||
101
akode-rs/tui/src/app/quick_dials.rs
Normal file
101
akode-rs/tui/src/app/quick_dials.rs
Normal file
@@ -0,0 +1,101 @@
|
||||
//! Persist numbered prompts and slash commands in the active user configuration.
|
||||
//! Replace slots owned by the active user config. Clearing must not reveal a
|
||||
//! shadowed slot from another configuration layer.
|
||||
|
||||
use super::App;
|
||||
use crate::chatwidget::quick_dials::QuickDialEditorTarget;
|
||||
use crate::config_update::format_config_error;
|
||||
use crate::legacy_core::config::edit::ConfigEdit;
|
||||
use crate::legacy_core::config::edit::ConfigEditsBuilder;
|
||||
use akode_config::ConfigLayerSource;
|
||||
use akode_config::types::QuickDial;
|
||||
|
||||
impl App {
|
||||
pub(super) async fn save_quick_dial(&mut self, slot: u8, dial: Option<QuickDial>) {
|
||||
let key = slot.to_string();
|
||||
let read_only = {
|
||||
let mut slot_sources = self
|
||||
.config
|
||||
.config_layer_stack
|
||||
.layers_high_to_low()
|
||||
.filter(|layer| {
|
||||
layer
|
||||
.config
|
||||
.get("tui")
|
||||
.and_then(|tui| tui.get("presets"))
|
||||
.and_then(|dials| dials.get(&key))
|
||||
.is_some()
|
||||
})
|
||||
.map(|layer| &layer.name);
|
||||
let outside_user_config = |source: &ConfigLayerSource| {
|
||||
!matches!(source, ConfigLayerSource::User { file, .. }
|
||||
if file == &self.local_settings.user_config_path)
|
||||
};
|
||||
if dial.is_some() {
|
||||
slot_sources.next().is_some_and(outside_user_config)
|
||||
} else {
|
||||
slot_sources.any(outside_user_config)
|
||||
}
|
||||
};
|
||||
if read_only {
|
||||
self.chat_widget.add_error_message(format!(
|
||||
"Preset {slot} is defined outside your user config. Edit its source configuration instead."
|
||||
));
|
||||
self.restore_quick_dial_editor(slot, &dial);
|
||||
return;
|
||||
}
|
||||
let segments = vec!["tui".into(), "presets".into(), key.clone()];
|
||||
let edit = match &dial {
|
||||
Some(candidate) => {
|
||||
if let Err(reason) = candidate.validate() {
|
||||
self.chat_widget.add_error_message(reason.into());
|
||||
self.restore_quick_dial_editor(slot, &dial);
|
||||
return;
|
||||
}
|
||||
let mut table = toml_edit::Table::new();
|
||||
table["input"] = toml_edit::value(&candidate.input);
|
||||
// An explicit empty label masks labels inherited from lower layers.
|
||||
table["label"] = toml_edit::value(candidate.label.as_deref().unwrap_or_default());
|
||||
ConfigEdit::SetPath {
|
||||
segments,
|
||||
value: toml_edit::Item::Table(table),
|
||||
}
|
||||
}
|
||||
None => ConfigEdit::ClearPath { segments },
|
||||
};
|
||||
if let Err(error) =
|
||||
ConfigEditsBuilder::for_config_path(self.local_settings.user_config_path.as_path())
|
||||
.with_edits([edit])
|
||||
.apply()
|
||||
.await
|
||||
{
|
||||
self.chat_widget.add_error_message(format!(
|
||||
"Failed to update preset {slot}: {}",
|
||||
format_config_error(&error)
|
||||
));
|
||||
self.restore_quick_dial_editor(slot, &dial);
|
||||
return;
|
||||
}
|
||||
let message = match dial {
|
||||
Some(mut dial) => {
|
||||
dial.label.get_or_insert_default();
|
||||
self.local_settings.tui.quick_dials.insert(key, dial);
|
||||
format!("Saved preset {slot}.")
|
||||
}
|
||||
None => {
|
||||
self.local_settings.tui.quick_dials.remove(&key);
|
||||
format!("Deleted preset {slot}.")
|
||||
}
|
||||
};
|
||||
self.chat_widget.local_settings.tui.quick_dials =
|
||||
self.local_settings.tui.quick_dials.clone();
|
||||
self.chat_widget.add_info_message(message, /*hint*/ None);
|
||||
}
|
||||
|
||||
fn restore_quick_dial_editor(&mut self, slot: u8, dial: &Option<QuickDial>) {
|
||||
if let Some(dial) = dial {
|
||||
self.chat_widget
|
||||
.open_quick_dial_editor(QuickDialEditorTarget::Slot(slot), Some(dial.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
428
akode-rs/tui/src/app/realtime_delivery.rs
Normal file
428
akode-rs/tui/src/app/realtime_delivery.rs
Normal file
@@ -0,0 +1,428 @@
|
||||
//! Preserve voice answers and accepted transcripts across thread-widget replacement.
|
||||
//!
|
||||
//! A queued speech command can outlive its widget. Retain its bounded final
|
||||
//! item by original thread until replay either renders that item or needs a
|
||||
//! fallback, without adding history to whichever thread is currently visible.
|
||||
|
||||
use super::*;
|
||||
use akode_protocol::models::MessagePhase;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::HashSet;
|
||||
|
||||
type ReplayedVoiceTextCounts = HashMap<(String, String), usize>;
|
||||
const MAX_INACTIVE_REALTIME_REPLAY_THREADS: usize = 16;
|
||||
|
||||
fn normalized_replay_text(text: &str) -> String {
|
||||
text.split_whitespace().collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
fn record_voice_item(
|
||||
item: &ThreadItemPayload,
|
||||
turn_id: &str,
|
||||
delegated: &mut HashSet<String>,
|
||||
items: &mut HashMap<(String, String, &'static str), String>,
|
||||
) {
|
||||
match item {
|
||||
ThreadItemPayload::UserMessage { id, content, .. } => {
|
||||
if let Some(input) = crate::chatwidget::realtime_delegation_input(content) {
|
||||
delegated.insert(turn_id.to_string());
|
||||
let display = crate::chatwidget::realtime_delegation_display_text(input);
|
||||
items.insert(
|
||||
(turn_id.to_string(), id.clone(), "user"),
|
||||
normalized_replay_text(&display),
|
||||
);
|
||||
}
|
||||
}
|
||||
ThreadItemPayload::AgentMessage {
|
||||
id,
|
||||
text,
|
||||
phase: Some(MessagePhase::FinalAnswer) | None,
|
||||
..
|
||||
} if delegated.contains(turn_id)
|
||||
&& !crate::chatwidget::is_private_realtime_agent_item(item)
|
||||
&& !text.trim().is_empty() =>
|
||||
{
|
||||
items.insert(
|
||||
(turn_id.to_string(), id.clone(), "assistant"),
|
||||
normalized_replay_text(text),
|
||||
);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn replayed_voice_texts_from_turns(turns: &[Turn]) -> ReplayedVoiceTextCounts {
|
||||
let mut delegated = HashSet::new();
|
||||
let mut items = HashMap::new();
|
||||
for turn in turns {
|
||||
for item in turn.item_payloads() {
|
||||
record_voice_item(item, &turn.id, &mut delegated, &mut items);
|
||||
}
|
||||
}
|
||||
count_replayed_voice_texts(items)
|
||||
}
|
||||
|
||||
fn count_replayed_voice_texts(
|
||||
items: HashMap<(String, String, &'static str), String>,
|
||||
) -> ReplayedVoiceTextCounts {
|
||||
let mut counts = HashMap::new();
|
||||
for ((_, _, role), text) in items {
|
||||
if !text.is_empty() {
|
||||
*counts.entry((role.to_string(), text)).or_insert(0) += 1;
|
||||
}
|
||||
}
|
||||
counts
|
||||
}
|
||||
|
||||
pub(super) fn replayed_voice_texts(snapshot: &ThreadEventSnapshot) -> ReplayedVoiceTextCounts {
|
||||
let mut delegated = snapshot
|
||||
.delegated_turns
|
||||
.iter()
|
||||
.cloned()
|
||||
.collect::<HashSet<_>>();
|
||||
let mut items = HashMap::new();
|
||||
for turn in &snapshot.turns {
|
||||
for item in turn.item_payloads() {
|
||||
record_voice_item(item, &turn.id, &mut delegated, &mut items);
|
||||
}
|
||||
}
|
||||
for event in &snapshot.events {
|
||||
let ThreadBufferedEvent::Notification(notification) = event else {
|
||||
continue;
|
||||
};
|
||||
match notification.as_ref() {
|
||||
ServerNotification::ItemStarted(n) => {
|
||||
if let ThreadItemPayload::UserMessage { content, .. } = &n.item.payload
|
||||
&& crate::chatwidget::realtime_delegation_input(content).is_some()
|
||||
{
|
||||
delegated.insert(n.turn_id.clone());
|
||||
}
|
||||
}
|
||||
ServerNotification::ItemCompleted(n) => {
|
||||
record_voice_item(&n.item.payload, &n.turn_id, &mut delegated, &mut items);
|
||||
}
|
||||
ServerNotification::TurnCompleted(n) if n.turn.status == TurnStatus::Completed => {
|
||||
if let Some(item) = n.turn.item_payloads().rev().find(|item| {
|
||||
matches!(
|
||||
item,
|
||||
ThreadItemPayload::AgentMessage {
|
||||
phase: Some(MessagePhase::FinalAnswer) | None,
|
||||
..
|
||||
}
|
||||
) && !crate::chatwidget::is_private_realtime_agent_item(item)
|
||||
}) {
|
||||
record_voice_item(item, &n.turn.id, &mut delegated, &mut items);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
count_replayed_voice_texts(items)
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub(super) fn note_realtime_replay_thread(&mut self, thread_id: ThreadId) {
|
||||
if self.realtime_replay_order.contains(&thread_id) {
|
||||
return;
|
||||
}
|
||||
if self.realtime_replay_order.len() >= MAX_INACTIVE_REALTIME_REPLAY_THREADS
|
||||
&& let Some(oldest) = self.realtime_replay_order.pop_front()
|
||||
{
|
||||
self.pending_realtime_transcript_replay.remove(&oldest);
|
||||
self.pending_realtime_speech_replay.remove(&oldest);
|
||||
}
|
||||
self.realtime_replay_order.push_back(thread_id);
|
||||
}
|
||||
|
||||
pub(super) fn forget_realtime_replay_thread(&mut self, thread_id: ThreadId) {
|
||||
self.realtime_replay_order
|
||||
.retain(|saved| *saved != thread_id);
|
||||
self.pending_realtime_transcript_replay.remove(&thread_id);
|
||||
self.pending_realtime_speech_replay.remove(&thread_id);
|
||||
}
|
||||
|
||||
pub(super) fn retain_inactive_realtime_transcript(
|
||||
&mut self,
|
||||
thread_id: ThreadId,
|
||||
notification: &ServerNotification,
|
||||
) {
|
||||
if let ServerNotification::TurnStarted(started) = notification
|
||||
&& let Some(records) = self.pending_realtime_transcript_replay.get_mut(&thread_id)
|
||||
{
|
||||
for record in records {
|
||||
if record.complete && record.before_turn_id.is_none() {
|
||||
record.before_turn_id = Some(started.turn.id.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
let (role, text, complete) = match notification {
|
||||
ServerNotification::ThreadRealtimeTranscriptDelta(n) => {
|
||||
(n.role.as_str(), n.delta.as_str(), false)
|
||||
}
|
||||
ServerNotification::ThreadRealtimeTranscriptDone(n) => {
|
||||
(n.role.as_str(), n.text.as_str(), true)
|
||||
}
|
||||
_ => return,
|
||||
};
|
||||
if !matches!(role, "user" | "assistant") {
|
||||
return;
|
||||
}
|
||||
self.note_realtime_replay_thread(thread_id);
|
||||
let records = self
|
||||
.pending_realtime_transcript_replay
|
||||
.entry(thread_id)
|
||||
.or_default();
|
||||
if complete {
|
||||
if text.trim().is_empty() {
|
||||
if let Some(index) = records
|
||||
.iter()
|
||||
.rposition(|record| record.role == role && !record.complete)
|
||||
{
|
||||
records.remove(index);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let mut bounded = text.to_string();
|
||||
if bounded.len() > crate::chatwidget::MAX_TRANSCRIPT_BYTES {
|
||||
let mut end = crate::chatwidget::MAX_TRANSCRIPT_BYTES;
|
||||
while !bounded.is_char_boundary(end) {
|
||||
end -= 1;
|
||||
}
|
||||
bounded.truncate(end);
|
||||
}
|
||||
if let Some(partial) = records
|
||||
.iter_mut()
|
||||
.rev()
|
||||
.find(|record| record.role == role && !record.complete)
|
||||
{
|
||||
partial.text = bounded;
|
||||
partial.complete = true;
|
||||
return;
|
||||
}
|
||||
if records.len() >= crate::chatwidget::MAX_REPLAY_TRANSCRIPT_CELLS {
|
||||
records.pop_front();
|
||||
}
|
||||
records.push_back(crate::chatwidget::RealtimeTranscriptRecord {
|
||||
role: role.to_string(),
|
||||
text: bounded,
|
||||
complete: true,
|
||||
before_turn_id: None,
|
||||
});
|
||||
} else {
|
||||
if text.is_empty() {
|
||||
return;
|
||||
}
|
||||
let partial = records
|
||||
.iter_mut()
|
||||
.rev()
|
||||
.find(|record| record.role == role && !record.complete);
|
||||
if let Some(partial) = partial {
|
||||
partial.text.push_str(text);
|
||||
if partial.text.len() > crate::chatwidget::MAX_TRANSCRIPT_BYTES {
|
||||
let mut start = partial.text.len() - crate::chatwidget::MAX_TRANSCRIPT_BYTES;
|
||||
while !partial.text.is_char_boundary(start) {
|
||||
start += 1;
|
||||
}
|
||||
partial.text.drain(..start);
|
||||
}
|
||||
} else {
|
||||
let mut bounded = text.to_string();
|
||||
if bounded.len() > crate::chatwidget::MAX_TRANSCRIPT_BYTES {
|
||||
let mut start = bounded.len() - crate::chatwidget::MAX_TRANSCRIPT_BYTES;
|
||||
while !bounded.is_char_boundary(start) {
|
||||
start += 1;
|
||||
}
|
||||
bounded.drain(..start);
|
||||
}
|
||||
if records.len() >= crate::chatwidget::MAX_REPLAY_TRANSCRIPT_CELLS {
|
||||
records.pop_front();
|
||||
}
|
||||
records.push_back(crate::chatwidget::RealtimeTranscriptRecord {
|
||||
role: role.to_string(),
|
||||
text: bounded,
|
||||
complete: false,
|
||||
before_turn_id: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn retain_realtime_replay_state_before_replace(&mut self) {
|
||||
if let Some(thread_id) = self.chat_widget.thread_id() {
|
||||
if self.chat_widget.may_receive_realtime_transcripts() {
|
||||
self.note_realtime_replay_thread(thread_id);
|
||||
// Even a session without captions can receive a final queued caption
|
||||
// after this widget has been replaced.
|
||||
self.pending_realtime_transcript_replay
|
||||
.entry(thread_id)
|
||||
.or_default();
|
||||
}
|
||||
let cells = self.chat_widget.take_realtime_transcript_cells_for_replay();
|
||||
if !cells.is_empty() {
|
||||
self.note_realtime_replay_thread(thread_id);
|
||||
let pending = self
|
||||
.pending_realtime_transcript_replay
|
||||
.entry(thread_id)
|
||||
.or_default();
|
||||
// Only the active widget produces these cells; reattachment consumes them
|
||||
// before another widget for this thread can become active.
|
||||
// Up to 32 accepted cells plus one partial for each speaker.
|
||||
debug_assert!(pending.len() + cells.len() <= 34);
|
||||
pending.extend(cells);
|
||||
}
|
||||
}
|
||||
for (thread_id, turn_id, item) in self
|
||||
.chat_widget
|
||||
.take_undelivered_realtime_speech_for_replay()
|
||||
{
|
||||
self.note_realtime_replay_thread(thread_id);
|
||||
let pending = self
|
||||
.pending_realtime_speech_replay
|
||||
.entry(thread_id)
|
||||
.or_default();
|
||||
// The active widget is the only producer for a thread; selecting
|
||||
// that thread reconciles these records before it can produce more.
|
||||
debug_assert!(pending.len() < 16);
|
||||
pending.push((turn_id, item));
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn prepare_realtime_transcript_replay(
|
||||
&mut self,
|
||||
mut replayed_voice_texts: ReplayedVoiceTextCounts,
|
||||
) -> HashMap<String, usize> {
|
||||
let Some(thread_id) = self.chat_widget.thread_id() else {
|
||||
return HashMap::new();
|
||||
};
|
||||
if let Some(owner) = self.background_voice.as_ref()
|
||||
&& owner.thread_id() == Some(thread_id)
|
||||
{
|
||||
for text in self.chat_widget.prepare_background_voice_replay(owner) {
|
||||
let key = ("assistant".to_string(), normalized_replay_text(text));
|
||||
if let Some(count) = replayed_voice_texts.get_mut(&key) {
|
||||
*count = count.saturating_sub(/*rhs*/ 1);
|
||||
}
|
||||
}
|
||||
self.pending_realtime_transcript_replay
|
||||
.insert(thread_id, owner.realtime_transcript_cells_for_replay());
|
||||
}
|
||||
self.realtime_replay_order
|
||||
.retain(|saved| *saved != thread_id);
|
||||
let mut retained_assistant_captions = HashMap::<String, usize>::new();
|
||||
if let Some(mut cells) = self.pending_realtime_transcript_replay.remove(&thread_id) {
|
||||
cells.retain(|record| {
|
||||
if !record.complete {
|
||||
return true;
|
||||
}
|
||||
let key = (record.role.clone(), normalized_replay_text(&record.text));
|
||||
if let Some(count) = replayed_voice_texts.get_mut(&key)
|
||||
&& *count > 0
|
||||
{
|
||||
*count -= 1;
|
||||
return false;
|
||||
}
|
||||
true
|
||||
});
|
||||
for record in &cells {
|
||||
if record.complete && record.role == "assistant" {
|
||||
*retained_assistant_captions
|
||||
.entry(normalized_replay_text(&record.text))
|
||||
.or_default() += 1;
|
||||
}
|
||||
}
|
||||
self.chat_widget
|
||||
.queue_realtime_transcripts_for_replay(cells);
|
||||
}
|
||||
retained_assistant_captions
|
||||
}
|
||||
|
||||
pub(super) fn restore_realtime_replay_state_after_replay(
|
||||
&mut self,
|
||||
replayed_final_items: &HashMap<(String, String), String>,
|
||||
mut retained_assistant_captions: HashMap<String, usize>,
|
||||
) {
|
||||
let Some(thread_id) = self.chat_widget.thread_id() else {
|
||||
return;
|
||||
};
|
||||
self.chat_widget.finish_realtime_transcript_replay();
|
||||
let Some(pending) = self.pending_realtime_speech_replay.remove(&thread_id) else {
|
||||
return;
|
||||
};
|
||||
for (turn_id, item) in pending {
|
||||
let ThreadItemPayload::AgentMessage { id, text, .. } = &item else {
|
||||
continue;
|
||||
};
|
||||
// A matching ID with empty text did not render the saved answer.
|
||||
// Any nonempty snapshot text is authoritative even if it changed.
|
||||
if replayed_final_items
|
||||
.get(&(turn_id.clone(), id.clone()))
|
||||
.is_none_or(|text| text.trim().is_empty())
|
||||
{
|
||||
// A completed caption restored above already displays this
|
||||
// answer. Consume only one exact match; partial or distinct
|
||||
// captions must not hide an undelivered fallback.
|
||||
let spoken_text = text.trim().strip_prefix("[FINAL]").unwrap_or(text);
|
||||
if let Some(count) =
|
||||
retained_assistant_captions.get_mut(&normalized_replay_text(spoken_text))
|
||||
&& *count > 0
|
||||
{
|
||||
*count -= 1;
|
||||
continue;
|
||||
}
|
||||
self.chat_widget
|
||||
.render_undelivered_realtime_speech(thread_id, turn_id, item);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn completed_agent_items(
|
||||
snapshot: &ThreadEventSnapshot,
|
||||
) -> HashMap<(String, String), String> {
|
||||
let mut completed = completed_agent_items_from_turns(&snapshot.turns);
|
||||
for event in &snapshot.events {
|
||||
let ThreadBufferedEvent::Notification(notification) = event else {
|
||||
continue;
|
||||
};
|
||||
match notification.as_ref() {
|
||||
ServerNotification::ItemCompleted(completed_item) => {
|
||||
if let ThreadItemPayload::AgentMessage { id, text, .. } =
|
||||
&completed_item.item.payload
|
||||
&& !text.trim().is_empty()
|
||||
{
|
||||
completed.insert((completed_item.turn_id.clone(), id.clone()), text.clone());
|
||||
}
|
||||
}
|
||||
ServerNotification::TurnCompleted(completed_turn)
|
||||
if completed_turn.turn.status == TurnStatus::Completed =>
|
||||
{
|
||||
for item in completed_turn.turn.item_payloads() {
|
||||
if let ThreadItemPayload::AgentMessage { id, text, .. } = item
|
||||
&& !text.trim().is_empty()
|
||||
{
|
||||
completed
|
||||
.insert((completed_turn.turn.id.clone(), id.clone()), text.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
completed
|
||||
}
|
||||
|
||||
pub(super) fn completed_agent_items_from_turns(
|
||||
turns: &[Turn],
|
||||
) -> HashMap<(String, String), String> {
|
||||
let mut completed = HashMap::new();
|
||||
for turn in turns {
|
||||
for item in turn.item_payloads() {
|
||||
if let ThreadItemPayload::AgentMessage { id, text, .. } = item
|
||||
&& !text.trim().is_empty()
|
||||
{
|
||||
completed.insert((turn.id.clone(), id.clone()), text.clone());
|
||||
}
|
||||
}
|
||||
}
|
||||
completed
|
||||
}
|
||||
284
akode-rs/tui/src/app/realtime_settings.rs
Normal file
284
akode-rs/tui/src/app/realtime_settings.rs
Normal file
@@ -0,0 +1,284 @@
|
||||
//! Persist server voice preferences and machine-local audio selections before updating the UI.
|
||||
|
||||
use super::*;
|
||||
use crate::legacy_core::config::edit::ConfigEdit;
|
||||
use akode_app_server_protocol::ClientRequest;
|
||||
use akode_app_server_protocol::RequestId;
|
||||
use akode_app_server_protocol::ThreadRealtimeListVoicesParams;
|
||||
use akode_app_server_protocol::ThreadRealtimeListVoicesResponse;
|
||||
use akode_config::config_toml::MicrophoneChannels;
|
||||
use akode_protocol::protocol::RealtimeVoice;
|
||||
use akode_protocol::protocol::RealtimeVoicesList;
|
||||
use akode_realtime_webrtc::AudioDeviceKind;
|
||||
use uuid::Uuid;
|
||||
|
||||
/// Unknown voices belong to newer servers; omit the override instead of blocking audio.
|
||||
/// An unset preference explicitly selects the V1/V3 server default, not a stale thread preference.
|
||||
fn configured_voice(
|
||||
config: &akode_app_server_protocol::Config,
|
||||
default_voice: RealtimeVoice,
|
||||
) -> Result<Option<RealtimeVoice>> {
|
||||
let value = config
|
||||
.additional
|
||||
.get("realtime")
|
||||
.and_then(|realtime| realtime.get("voice"));
|
||||
match value {
|
||||
None | Some(serde_json::Value::Null) => Ok(Some(default_voice)),
|
||||
Some(value @ serde_json::Value::String(_)) => {
|
||||
Ok(serde_json::from_value(value.clone()).ok())
|
||||
}
|
||||
Some(value) => Ok(Some(serde_json::from_value(value.clone())?)),
|
||||
}
|
||||
}
|
||||
|
||||
impl App {
|
||||
pub(super) async fn persist_realtime_input_channel(
|
||||
&mut self,
|
||||
channel: Option<MicrophoneChannels>,
|
||||
) {
|
||||
self.persist_realtime_audio(
|
||||
"microphone_channel",
|
||||
channel.map(|channel| match channel {
|
||||
MicrophoneChannels::Single(channel) => i64::from(channel.get()).into(),
|
||||
MicrophoneChannels::Multiple(channels) => toml::Value::Array(
|
||||
channels
|
||||
.into_iter()
|
||||
.map(|channel| i64::from(channel.get()).into())
|
||||
.collect(),
|
||||
),
|
||||
}),
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
pub(super) async fn persist_realtime_device(
|
||||
&mut self,
|
||||
kind: AudioDeviceKind,
|
||||
name: Option<String>,
|
||||
) {
|
||||
let key = match kind {
|
||||
AudioDeviceKind::Input => "microphone",
|
||||
AudioDeviceKind::Output => "speaker",
|
||||
};
|
||||
self.persist_realtime_audio(key, name.map(Into::into)).await;
|
||||
self.list_realtime_devices(kind);
|
||||
}
|
||||
|
||||
async fn persist_realtime_audio(&mut self, key: &str, value: Option<toml::Value>) {
|
||||
// Audio runs on the TUI's machine, even when the app server is remote.
|
||||
let segments = vec!["audio".to_string(), key.to_string()];
|
||||
let mut edits = vec![match &value {
|
||||
Some(toml::Value::String(value)) => ConfigEdit::SetPath {
|
||||
segments,
|
||||
value: value.clone().into(),
|
||||
},
|
||||
Some(toml::Value::Integer(value)) => ConfigEdit::SetPath {
|
||||
segments,
|
||||
value: (*value).into(),
|
||||
},
|
||||
Some(toml::Value::Array(channels)) => ConfigEdit::SetPath {
|
||||
segments,
|
||||
value: channels
|
||||
.iter()
|
||||
.map(|channel| match channel {
|
||||
toml::Value::Integer(channel) => *channel,
|
||||
_ => unreachable!("audio channel arrays contain only integers"),
|
||||
})
|
||||
.collect::<toml_edit::Array>()
|
||||
.into(),
|
||||
},
|
||||
Some(_) => unreachable!("audio settings are device names or channel numbers"),
|
||||
None => ConfigEdit::ClearPath { segments },
|
||||
}];
|
||||
if key == "microphone" {
|
||||
edits.push(ConfigEdit::ClearPath {
|
||||
segments: vec!["audio".into(), "microphone_channel".into()],
|
||||
});
|
||||
}
|
||||
if let Err(error) =
|
||||
ConfigEditsBuilder::for_config_path(self.local_settings.user_config_path.as_path())
|
||||
.with_edits(edits)
|
||||
.apply()
|
||||
.await
|
||||
{
|
||||
self.chat_widget
|
||||
.add_error_message(format!("Failed to save audio setting: {error}"));
|
||||
return;
|
||||
}
|
||||
match crate::legacy_core::config::load_config_toml_with_layer_stack(
|
||||
self.local_settings.codex_home.as_path(),
|
||||
/*cwd*/ None,
|
||||
self.cli_kv_overrides.clone(),
|
||||
akode_config::ConfigLoadOptions {
|
||||
loader_overrides: self.loader_overrides.clone(),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(config) => {
|
||||
self.config.config_layer_stack = self
|
||||
.config
|
||||
.config_layer_stack
|
||||
.with_user_layer_from(&config.config_layer_stack);
|
||||
let audio = config.config_toml.audio.unwrap_or_default();
|
||||
let effective = toml::Value::try_from(&audio)
|
||||
.ok()
|
||||
.and_then(|audio| audio.get(key).cloned());
|
||||
let channel_overridden = key == "microphone" && audio.microphone_channel.is_some();
|
||||
self.local_settings.audio = Ok(audio);
|
||||
self.chat_widget.local_settings.audio = self.local_settings.audio.clone();
|
||||
if channel_overridden {
|
||||
self.chat_widget.add_error_message("Input device saved, but the input channel is overridden by another configuration layer. Update that override before starting voice.".into());
|
||||
} else if effective == value {
|
||||
self.chat_widget.add_info_message(
|
||||
"Audio setting saved. Applies to your next voice conversation.".to_string(),
|
||||
/*hint*/ None,
|
||||
);
|
||||
} else {
|
||||
self.chat_widget.add_error_message(
|
||||
"Audio setting was saved but is overridden by another configuration layer."
|
||||
.to_string(),
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(error) => self.chat_widget.add_error_message(format!(
|
||||
"Audio setting was saved, but effective settings could not be read: {error}"
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn list_realtime_devices(&self, kind: AudioDeviceKind) {
|
||||
let tx = self.app_event_tx.clone();
|
||||
let origin = self.active_thread_id;
|
||||
tokio::spawn(async move {
|
||||
let result = async {
|
||||
let package = akode_install_context::InstallContext::current()
|
||||
.package_layout
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("voice package unavailable"))?;
|
||||
let mut host = akode_realtime_webrtc::VoiceHost::connect(
|
||||
package,
|
||||
akode_build_info::BuildInfo::get().build_commit(),
|
||||
)
|
||||
.await?;
|
||||
let result = host.list_devices(kind).await;
|
||||
host.close().await?;
|
||||
result
|
||||
}
|
||||
.await;
|
||||
tx.send(AppEvent::RealtimeDevicesListed {
|
||||
origin,
|
||||
kind,
|
||||
result: result.map_err(|_| {
|
||||
"Could not list audio devices. Check your audio device and voice package."
|
||||
.to_owned()
|
||||
}),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
pub(super) async fn realtime_voices(
|
||||
&self,
|
||||
app_server: &AppServerSession,
|
||||
) -> Result<RealtimeVoicesList> {
|
||||
let response = app_server
|
||||
.request_handle()
|
||||
.request_typed::<ThreadRealtimeListVoicesResponse>(
|
||||
ClientRequest::ThreadRealtimeListVoices {
|
||||
request_id: RequestId::String(format!("tui-voice-list-{}", Uuid::new_v4())),
|
||||
params: ThreadRealtimeListVoicesParams {},
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
Ok(response.voices)
|
||||
}
|
||||
|
||||
pub(super) async fn effective_realtime_voice(
|
||||
&self,
|
||||
app_server: &AppServerSession,
|
||||
voices: &RealtimeVoicesList,
|
||||
) -> Result<Option<RealtimeVoice>> {
|
||||
// Session setup installs the active conversation cwd for both server modes.
|
||||
let config = crate::config_update::read_effective_config_if_supported(
|
||||
app_server.request_handle(),
|
||||
&self.chat_widget.config_ref().cwd,
|
||||
)
|
||||
.await?;
|
||||
config
|
||||
.as_ref()
|
||||
.map(|config| configured_voice(&config.config, voices.default_v1))
|
||||
.transpose()
|
||||
.map(Option::flatten)
|
||||
}
|
||||
|
||||
pub(super) async fn open_realtime_voices(&mut self, app_server: &AppServerSession) {
|
||||
let voices = match self.realtime_voices(app_server).await {
|
||||
Ok(voices) => voices,
|
||||
Err(error) => {
|
||||
self.chat_widget
|
||||
.add_error_message(format!("Failed to list voices: {error}"));
|
||||
return;
|
||||
}
|
||||
};
|
||||
match self.effective_realtime_voice(app_server, &voices).await {
|
||||
Ok(voice) => self.chat_widget.open_realtime_voices(voice, voices),
|
||||
Err(error) => self
|
||||
.chat_widget
|
||||
.add_error_message(format!("Failed to read voice settings: {error}")),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) async fn persist_realtime_voice(
|
||||
&mut self,
|
||||
app_server: &AppServerSession,
|
||||
voice: RealtimeVoice,
|
||||
) {
|
||||
match crate::config_update::write_config_batch(
|
||||
app_server.request_handle(),
|
||||
vec![crate::config_update::replace_config_value(
|
||||
"realtime.voice",
|
||||
serde_json::json!(voice),
|
||||
)],
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(response) => {
|
||||
let voices = match self.realtime_voices(app_server).await {
|
||||
Ok(voices) => voices,
|
||||
Err(error) => {
|
||||
self.chat_widget.add_error_message(format!(
|
||||
"Voice preference was saved, but the effective voice could not be confirmed: {error}"
|
||||
));
|
||||
return;
|
||||
}
|
||||
};
|
||||
let effective = crate::config_update::read_effective_config_if_supported(
|
||||
app_server.request_handle(), &self.chat_widget.config_ref().cwd,
|
||||
).await.and_then(|config| match config.as_ref() {
|
||||
Some(config) => configured_voice(&config.config, voices.default_v1),
|
||||
None if response.status == akode_app_server_protocol::WriteStatus::OkOverridden => Err(color_eyre::eyre::eyre!("the saved voice is overridden, but this server cannot read effective settings")),
|
||||
None => Ok(Some(voice)),
|
||||
});
|
||||
match effective {
|
||||
Ok(effective_voice) => {
|
||||
self.config.realtime.voice = effective_voice;
|
||||
self.chat_widget.set_realtime_voice(effective_voice);
|
||||
if effective_voice == Some(voice) {
|
||||
self.chat_widget.on_realtime_voice_saved(voice);
|
||||
} else {
|
||||
self.chat_widget.add_error_message(format!(
|
||||
"Voice preference was saved but not applied: {}",
|
||||
super::config_persistence::overridden_write_message(&response),
|
||||
));
|
||||
}
|
||||
}
|
||||
Err(error) => self.chat_widget.add_error_message(format!("Voice preference was saved, but effective settings could not be read: {error}")),
|
||||
}
|
||||
}
|
||||
Err(error) => self
|
||||
.chat_widget
|
||||
.add_error_message(format!("Failed to save voice: {error}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user