Refactor and clean up code across multiple modules
- Simplified token type assignment in OAuth service. - Removed unused session_lock module and re-exported Session from zesdex_entities. - Cleaned up session entity by removing unnecessary comments and code. - Consolidated session handling in HTTP handlers for better readability. - Improved formatting and readability in OAuth repository tests. - Enhanced session lock repository with clearer match statements. - Streamlined session repository error handling. - Refined RNG tests for better clarity. - Adjusted module visibility and organization in lib.rs. - Updated IPC client and connection code for better error handling and clarity. - Improved frame handling in IPC for better readability. - Organized module imports and added test utilities for IPC. - Enhanced database connection error handling. - Simplified JWT token creation error handling. - Improved password verification error handling. - Cleaned up state management code for better readability. - Refactored middleware for session authentication and rate limiting. - Simplified clipboard utility for better error handling. - Enhanced logging initialization for better error reporting. - Improved pagination utility with clearer method annotations. - Cleaned up sanitization functions for filenames and paths. - Enhanced slug generation functions for better clarity and usability.
This commit is contained in:
@@ -1,9 +1,9 @@
|
||||
//! Application-level "miscellaneous" state: scroll, input buffer,
|
||||
//! overlay stack, toasts, editor, and autocomplete.
|
||||
use super::types::Overlay;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::RwLock;
|
||||
use super::types::Overlay;
|
||||
|
||||
/// A shared, async-writable cache of directory entries, used to avoid
|
||||
/// re-reading a directory every render frame.
|
||||
@@ -134,7 +134,6 @@ const COMMANDS: &[&str] = &[
|
||||
"/model",
|
||||
"/model ls",
|
||||
"/model add",
|
||||
|
||||
"/todo",
|
||||
"/usage",
|
||||
"/compact",
|
||||
@@ -211,7 +210,10 @@ impl InputState {
|
||||
return None;
|
||||
}
|
||||
let boundary_ok = at_pos == 0
|
||||
|| before_cursor[..at_pos].chars().next_back().is_some_and(char::is_whitespace);
|
||||
|| before_cursor[..at_pos]
|
||||
.chars()
|
||||
.next_back()
|
||||
.is_some_and(char::is_whitespace);
|
||||
if !boundary_ok {
|
||||
return None;
|
||||
}
|
||||
@@ -225,8 +227,8 @@ impl InputState {
|
||||
/// if none, close and return → otherwise fuzzy-match `query` against
|
||||
/// `files` via `nucleo-matcher`, keep the top 10 by score.
|
||||
pub fn open_mention_autocomplete(&mut self, files: &[String]) {
|
||||
use nucleo_matcher::{Config, Matcher};
|
||||
use nucleo_matcher::pattern::{CaseMatching, Normalization, Pattern};
|
||||
use nucleo_matcher::{Config, Matcher};
|
||||
let Some((start, query)) = self.mention_query_at_cursor() else {
|
||||
self.close_autocomplete();
|
||||
return;
|
||||
@@ -234,7 +236,11 @@ impl InputState {
|
||||
let mut matcher = Matcher::new(Config::DEFAULT.match_paths());
|
||||
let pattern = Pattern::parse(&query, CaseMatching::Smart, Normalization::Smart);
|
||||
let matched_files = pattern.match_list(files.iter(), &mut matcher);
|
||||
self.autocomplete_candidates = matched_files.into_iter().take(10).map(|(f, _)| f.clone()).collect();
|
||||
self.autocomplete_candidates = matched_files
|
||||
.into_iter()
|
||||
.take(10)
|
||||
.map(|(f, _)| f.clone())
|
||||
.collect();
|
||||
self.autocomplete_kind = AutocompleteKind::FileMention;
|
||||
self.mention_start = start;
|
||||
self.autocomplete_idx = 0;
|
||||
@@ -245,11 +251,17 @@ impl InputState {
|
||||
/// Wraps around at the boundaries.
|
||||
pub fn cycle_autocomplete(&mut self, forward: bool) {
|
||||
let n = self.autocomplete_candidates.len();
|
||||
if n == 0 { return; }
|
||||
if n == 0 {
|
||||
return;
|
||||
}
|
||||
if forward {
|
||||
self.autocomplete_idx = (self.autocomplete_idx + 1) % n;
|
||||
} else {
|
||||
self.autocomplete_idx = if self.autocomplete_idx == 0 { n - 1 } else { self.autocomplete_idx - 1 };
|
||||
self.autocomplete_idx = if self.autocomplete_idx == 0 {
|
||||
n - 1
|
||||
} else {
|
||||
self.autocomplete_idx - 1
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -261,7 +273,11 @@ impl InputState {
|
||||
///
|
||||
/// Return: `true` if a candidate was selected, `false` if none existed.
|
||||
pub fn select_autocomplete(&mut self) -> bool {
|
||||
let Some(candidate) = self.autocomplete_candidates.get(self.autocomplete_idx).cloned() else {
|
||||
let Some(candidate) = self
|
||||
.autocomplete_candidates
|
||||
.get(self.autocomplete_idx)
|
||||
.cloned()
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
match self.autocomplete_kind {
|
||||
@@ -282,7 +298,8 @@ impl InputState {
|
||||
return false;
|
||||
}
|
||||
let replacement = format!("@{candidate} ");
|
||||
self.buffer.replace_range(self.mention_start..self.cursor, &replacement);
|
||||
self.buffer
|
||||
.replace_range(self.mention_start..self.cursor, &replacement);
|
||||
self.cursor = self.mention_start + replacement.len();
|
||||
}
|
||||
}
|
||||
@@ -406,8 +423,6 @@ pub struct MiscState {
|
||||
pub selected_index: usize,
|
||||
pub editor: Option<super::super::mode::editor::EditorState>,
|
||||
pub api_connected: bool,
|
||||
#[allow(dead_code)]
|
||||
pub api_context_length: Option<u32>,
|
||||
pub tick_count: u64,
|
||||
pub todo_content: String,
|
||||
pub lesson_running: bool,
|
||||
@@ -427,7 +442,6 @@ impl MiscState {
|
||||
selected_index: 0,
|
||||
editor: None,
|
||||
api_connected: false,
|
||||
api_context_length: None,
|
||||
tick_count: 0,
|
||||
todo_content: String::new(),
|
||||
lesson_running: false,
|
||||
@@ -443,7 +457,12 @@ impl MiscState {
|
||||
///
|
||||
/// Return: the expired toasts (after removal).
|
||||
pub fn drain_expired_toasts(&mut self, now_ms: i64) -> Vec<super::types::Toast> {
|
||||
let expired: Vec<_> = self.toasts.iter().filter(|t| t.expired(now_ms)).cloned().collect();
|
||||
let expired: Vec<_> = self
|
||||
.toasts
|
||||
.iter()
|
||||
.filter(|t| t.expired(now_ms))
|
||||
.cloned()
|
||||
.collect();
|
||||
self.toasts.retain(|t| !t.expired(now_ms));
|
||||
expired
|
||||
}
|
||||
@@ -463,13 +482,19 @@ mod tests {
|
||||
#[test]
|
||||
fn mention_at_buffer_start_triggers() {
|
||||
let input = input_with("@mai", 4);
|
||||
assert_eq!(input.mention_query_at_cursor(), Some((0, "mai".to_string())));
|
||||
assert_eq!(
|
||||
input.mention_query_at_cursor(),
|
||||
Some((0, "mai".to_string()))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mention_after_space_mid_sentence_triggers() {
|
||||
let input = input_with("look at @read", 13);
|
||||
assert_eq!(input.mention_query_at_cursor(), Some((8, "read".to_string())));
|
||||
assert_eq!(
|
||||
input.mention_query_at_cursor(),
|
||||
Some((8, "read".to_string()))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -17,12 +17,12 @@ use crate::app::mcp::manager::McpManager;
|
||||
use crate::app::workflow::engine::WorkflowEngine;
|
||||
use zesdex_cms::domain::app_config::AppConfig;
|
||||
use zesdex_cms::domain::edit_log::EditLog;
|
||||
use zesdex_cms::domain::repository::EditLogRepository;
|
||||
use zesdex_cms::infrastructure::persistence::edit_log_repo::JsonlEditLogRepository;
|
||||
use zesdex_cms::domain::repository::AppConfigRepository;
|
||||
use zesdex_cms::domain::repository::EditLogRepository;
|
||||
use zesdex_cms::domain::repository::SettingsRepository;
|
||||
use zesdex_cms::domain::settings::Settings;
|
||||
use zesdex_cms::infrastructure::persistence::app_config_repo::JsonAppConfigRepository;
|
||||
use zesdex_cms::infrastructure::persistence::edit_log_repo::JsonlEditLogRepository;
|
||||
use zesdex_cms::infrastructure::persistence::settings_repo::JsonSettingsRepository;
|
||||
|
||||
/// A single transcript entry rendered in the TUI chat pane.
|
||||
@@ -51,7 +51,6 @@ impl ChatMessageDisplay {
|
||||
/// other module.
|
||||
#[derive(Clone)]
|
||||
pub struct AppStateRest {
|
||||
|
||||
pub settings: Settings,
|
||||
pub app_config: AppConfig,
|
||||
pub workspace_roots: Vec<PathBuf>,
|
||||
@@ -91,7 +90,11 @@ impl AppStateRest {
|
||||
/// Why: falls back to `memory_dir` itself (with a warning) when it has
|
||||
/// no parent, and to an empty session id when the dir name can't be
|
||||
/// read, so construction never fails.
|
||||
pub fn new(workspace_roots: Vec<PathBuf>, session_dir: &std::path::Path, memory_dir: PathBuf) -> Self {
|
||||
pub fn new(
|
||||
workspace_roots: Vec<PathBuf>,
|
||||
session_dir: &std::path::Path,
|
||||
memory_dir: PathBuf,
|
||||
) -> Self {
|
||||
let store_base_dir = zesdex_entities::seaorm::common::store::Store::new().base_dir;
|
||||
let settings = JsonSettingsRepository::new()
|
||||
.load(&store_base_dir)
|
||||
@@ -99,18 +102,27 @@ impl AppStateRest {
|
||||
let app_config = JsonAppConfigRepository::new()
|
||||
.load(&store_base_dir)
|
||||
.unwrap_or_default();
|
||||
let worktrees_dir = memory_dir.parent().unwrap_or_else(|| {
|
||||
tracing::warn!("[state] memory_dir '{}' has no parent, using it for worktrees", memory_dir.display());
|
||||
&memory_dir
|
||||
}).join("worktrees");
|
||||
let worktrees_dir = memory_dir
|
||||
.parent()
|
||||
.unwrap_or_else(|| {
|
||||
tracing::warn!(
|
||||
"[state] memory_dir '{}' has no parent, using it for worktrees",
|
||||
memory_dir.display()
|
||||
);
|
||||
&memory_dir
|
||||
})
|
||||
.join("worktrees");
|
||||
let dir_cache = DirCache::new();
|
||||
let session_id = session_dir
|
||||
.file_name().map_or_else(|| {
|
||||
tracing::warn!("[state] session_dir has no file_name component, using empty session_id");
|
||||
let session_id = session_dir.file_name().map_or_else(
|
||||
|| {
|
||||
tracing::warn!(
|
||||
"[state] session_dir has no file_name component, using empty session_id"
|
||||
);
|
||||
String::new()
|
||||
}, |n| n.to_string_lossy().to_string());
|
||||
},
|
||||
|n| n.to_string_lossy().to_string(),
|
||||
);
|
||||
let mut state = AppStateRest {
|
||||
|
||||
settings,
|
||||
app_config,
|
||||
workspace_roots,
|
||||
@@ -123,10 +135,15 @@ impl AppStateRest {
|
||||
abort_flag: Arc::new(std::sync::atomic::AtomicBool::new(false)),
|
||||
dir_cache: Arc::new(RwLock::new(dir_cache)),
|
||||
mention_index: MentionIndex::new(),
|
||||
edit_log: JsonlEditLogRepository::new().open(session_dir).unwrap_or_else(|e| {
|
||||
tracing::warn!("[state] failed to open edit log at '{}': {e}", session_dir.display());
|
||||
EditLog::new()
|
||||
}),
|
||||
edit_log: JsonlEditLogRepository::new()
|
||||
.open(session_dir)
|
||||
.unwrap_or_else(|e| {
|
||||
tracing::warn!(
|
||||
"[state] failed to open edit log at '{}': {e}",
|
||||
session_dir.display()
|
||||
);
|
||||
EditLog::new()
|
||||
}),
|
||||
session_runtime: Some(SessionRuntime::new(session_dir.to_path_buf())),
|
||||
workflow_engine: WorkflowEngine::new(),
|
||||
mcp_manager: McpManager::new(),
|
||||
@@ -149,7 +166,9 @@ impl AppStateRest {
|
||||
let mut hasher = sha2::Sha256::new();
|
||||
hasher.update(abs_root.to_string_lossy().as_bytes());
|
||||
let hash_hex = hex::encode(hasher.finalize());
|
||||
let folder_name = abs_root.file_name().map_or_else(|| "root".to_string(), |n| n.to_string_lossy().to_string());
|
||||
let folder_name = abs_root
|
||||
.file_name()
|
||||
.map_or_else(|| "root".to_string(), |n| n.to_string_lossy().to_string());
|
||||
let history_filename = format!("{}-{}.txt", folder_name, &hash_hex[..8]);
|
||||
let history_dir = base_dir.join("history");
|
||||
let _ = std::fs::create_dir_all(&history_dir);
|
||||
@@ -194,9 +213,14 @@ impl AppStateRest {
|
||||
}
|
||||
|
||||
// Wrap the msg_queue in a static-lifetime closure for use as ProgressFn.
|
||||
let progress: provisioner::ProgressFn = Some(&|msg: &str| push_msg(&msg_queue, msg));
|
||||
let progress: provisioner::ProgressFn =
|
||||
Some(&|msg: &str| push_msg(&msg_queue, msg));
|
||||
|
||||
let report = |msg: &str| { if let Some(f) = &progress { f(msg); }};
|
||||
let report = |msg: &str| {
|
||||
if let Some(f) = &progress {
|
||||
f(msg);
|
||||
}
|
||||
};
|
||||
|
||||
report("LSP: provisioning servers...");
|
||||
let results = provisioner::provision_all_with_progress(progress);
|
||||
@@ -204,18 +228,29 @@ impl AppStateRest {
|
||||
let connected = provisioner::auto_connect(&lsp_mgr, &results);
|
||||
for name in &connected {
|
||||
tracing::info!("LSP: {} connected", name);
|
||||
let m = format!("LSP: {name} connected ✓"); push_msg(&msg_queue, &m);
|
||||
let m = format!("LSP: {name} connected ✓");
|
||||
push_msg(&msg_queue, &m);
|
||||
}
|
||||
for r in &results {
|
||||
if let ProvisionResult::Failed { language, server_name, reason, .. } = r {
|
||||
if let ProvisionResult::Failed {
|
||||
language,
|
||||
server_name,
|
||||
reason,
|
||||
..
|
||||
} = r
|
||||
{
|
||||
tracing::warn!("LSP {} ({}): {}", server_name, language, reason);
|
||||
let m = format!("LSP: {server_name} ({language}) ✗ - {reason}"); push_msg(&msg_queue, &m);
|
||||
let m = format!("LSP: {server_name} ({language}) ✗ - {reason}");
|
||||
push_msg(&msg_queue, &m);
|
||||
}
|
||||
}
|
||||
if connected.is_empty() {
|
||||
let m = "LSP: no servers available — install manually or check prerequisites".to_string(); push_msg(&msg_queue, &m);
|
||||
let m = "LSP: no servers available — install manually or check prerequisites"
|
||||
.to_string();
|
||||
push_msg(&msg_queue, &m);
|
||||
} else {
|
||||
let m = format!("LSP: {} server(s) connected", connected.len()); push_msg(&msg_queue, &m);
|
||||
let m = format!("LSP: {} server(s) connected", connected.len());
|
||||
push_msg(&msg_queue, &m);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -259,7 +294,11 @@ impl AppStateRest {
|
||||
}
|
||||
let rel = entry.path().strip_prefix(root).unwrap_or(entry.path());
|
||||
let rel_str = rel.display().to_string();
|
||||
let formatted = if i == 0 { rel_str } else { format!("[{i}]{rel_str}") };
|
||||
let formatted = if i == 0 {
|
||||
rel_str
|
||||
} else {
|
||||
format!("[{i}]{rel_str}")
|
||||
};
|
||||
paths.push(formatted);
|
||||
if paths.len() >= MAX_MENTION_ENTRIES {
|
||||
break 'roots;
|
||||
@@ -275,10 +314,13 @@ impl AppStateRest {
|
||||
/// Return: `false` (and logs a warning) if the mutex is poisoned, rather
|
||||
/// than propagating a panic.
|
||||
pub fn turn_in_flight(&self) -> bool {
|
||||
self.turn_in_flight.lock().map_or_else(|_| {
|
||||
tracing::warn!("[state] turn_in_flight mutex poisoned");
|
||||
false
|
||||
}, |g| *g)
|
||||
self.turn_in_flight.lock().map_or_else(
|
||||
|_| {
|
||||
tracing::warn!("[state] turn_in_flight mutex poisoned");
|
||||
false
|
||||
},
|
||||
|g| *g,
|
||||
)
|
||||
}
|
||||
|
||||
/// Shut down every running LSP server process.
|
||||
@@ -317,14 +359,28 @@ impl AppStateRest {
|
||||
/// `session_dir` itself -- logging a warning at each step down, so this
|
||||
/// never fails even on a shallow path.
|
||||
pub fn store_base_dir(&self) -> std::path::PathBuf {
|
||||
self.session_dir.parent()
|
||||
.and_then(|p| p.parent()).map_or_else(|| {
|
||||
tracing::warn!("[state] session_dir '{}' has no grandparent, using parent", self.session_dir.display());
|
||||
self.session_dir.parent().map_or_else(|| {
|
||||
tracing::warn!("[state] session_dir '{}' has no parent at all, using itself", self.session_dir.display());
|
||||
self.session_dir.clone()
|
||||
}, std::path::Path::to_path_buf)
|
||||
}, std::path::Path::to_path_buf)
|
||||
self.session_dir
|
||||
.parent()
|
||||
.and_then(|p| p.parent())
|
||||
.map_or_else(
|
||||
|| {
|
||||
tracing::warn!(
|
||||
"[state] session_dir '{}' has no grandparent, using parent",
|
||||
self.session_dir.display()
|
||||
);
|
||||
self.session_dir.parent().map_or_else(
|
||||
|| {
|
||||
tracing::warn!(
|
||||
"[state] session_dir '{}' has no parent at all, using itself",
|
||||
self.session_dir.display()
|
||||
);
|
||||
self.session_dir.clone()
|
||||
},
|
||||
std::path::Path::to_path_buf,
|
||||
)
|
||||
},
|
||||
std::path::Path::to_path_buf,
|
||||
)
|
||||
}
|
||||
|
||||
/// Build a `ToolCtx` for tool calls originating from the main agent.
|
||||
|
||||
@@ -4,20 +4,7 @@
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Cumulative token/latency counters for a session, persisted alongside it.
|
||||
#[derive(Debug, Clone, Copy, Serialize, Deserialize, Default)]
|
||||
pub struct UsageStats {
|
||||
pub tokens_in: u64,
|
||||
pub tokens_out: u64,
|
||||
#[serde(default)]
|
||||
pub last_tokens_in: u64,
|
||||
#[serde(default)]
|
||||
pub last_tokens_out: u64,
|
||||
pub api_calls: u64,
|
||||
pub review_tokens: u64,
|
||||
pub total_ms: u64,
|
||||
}
|
||||
|
||||
pub use zesdex_entities::seaorm::common::usage::UsageStats;
|
||||
/// Mutable, serializable state for one session: chat history, tool
|
||||
/// results, pending tools, background jobs, and lesson/review counters
|
||||
/// shown in the TUI status bar.
|
||||
@@ -55,16 +42,7 @@ pub struct SessionRuntime {
|
||||
pub hive_mind_converged: bool,
|
||||
}
|
||||
|
||||
/// Record of one completed tool invocation, kept for transcript/history.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct ToolCallResult {
|
||||
pub tool_call_id: String,
|
||||
pub tool_name: String,
|
||||
pub output: String,
|
||||
pub is_error: bool,
|
||||
pub duration_ms: u64,
|
||||
}
|
||||
|
||||
pub use zesdex_entities::seaorm::common::tool_result::ToolCallResult;
|
||||
/// A tool call awaiting execution, along with which execution model
|
||||
/// (inline, deferred, async) it should run under.
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
|
||||
Reference in New Issue
Block a user