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:
asepharyana
2026-07-17 09:08:41 +07:00
parent 22dd6fdda7
commit 1f0ae9f551
95 changed files with 1792 additions and 2131 deletions
+94 -38
View File
@@ -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.