Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 5 additions & 7 deletions src-tauri/src/agent/sessions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -167,7 +167,7 @@ pub(crate) fn list_agent_sessions_in_dir(
summaries.push(session_summary(&record));
}

summaries.sort_by(|a, b| b.saved_at.cmp(&a.saved_at));
summaries.sort_by_key(|s| std::cmp::Reverse(s.saved_at));
Ok(summaries)
}

Expand Down Expand Up @@ -666,11 +666,10 @@ fn close_unclosed_json_containers(text: &str) -> String {
'"' => in_string = true,
'{' => stack.push('}'),
'[' => stack.push(']'),
'}' | ']' => {
if stack.last() == Some(&current) {
'}' | ']'
if stack.last() == Some(&current) => {
stack.pop();
}
}
_ => {}
}
}
Expand Down Expand Up @@ -1740,11 +1739,10 @@ async fn run_background_items_stream_task(
},
);
}
crate::models::AnthropicStreamEvent::MessageDelta { stop_reason } => {
if stop_reason.as_deref() == Some("max_tokens") {
crate::models::AnthropicStreamEvent::MessageDelta { stop_reason }
if stop_reason.as_deref() == Some("max_tokens") => {
truncated = true;
}
}
_ => {}
}
}
Expand Down
27 changes: 11 additions & 16 deletions src-tauri/src/book_travel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -601,22 +601,17 @@ async fn execute_book_travel_stream(
let chunk = chunk.map_err(|e| format!("网络流读取失败:{}", e))?;
buffer.push_str(&String::from_utf8_lossy(&chunk));
crate::llm::process_sse_buffer(&mut buffer, |data| {
if let Some(event) = crate::llm::parse_anthropic_stream_event(data) {
match event {
crate::models::AnthropicStreamEvent::Text(delta) => {
full_content.push_str(&delta);
let _ = app.emit(
"book-travel-stream",
BookTravelStreamEvent {
run_id: run_id.to_string(),
event_type: "delta".to_string(),
delta: Some(delta),
message: None,
},
);
}
_ => {}
}
if let Some(crate::models::AnthropicStreamEvent::Text(delta)) = crate::llm::parse_anthropic_stream_event(data) {
full_content.push_str(&delta);
let _ = app.emit(
"book-travel-stream",
BookTravelStreamEvent {
run_id: run_id.to_string(),
event_type: "delta".to_string(),
delta: Some(delta),
message: None,
},
);
}
});
}
Expand Down
42 changes: 20 additions & 22 deletions src-tauri/src/commands/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,28 +20,26 @@ pub fn list_dir(path: String) -> Result<Vec<FileNode>, String> {

match fs::read_dir(dir_path) {
Ok(entries) => {
for entry in entries {
if let Ok(entry) = entry {
let path_buf = entry.path();
let name = entry
.file_name()
.into_string()
.unwrap_or_else(|_| String::from("unknown"));
if name.starts_with('.') {
continue;
}
let is_dir = path_buf.is_dir();
if !is_dir && !is_supported_content_file(&path_buf) {
continue;
}

nodes.push(FileNode {
name,
path: path_buf.to_string_lossy().into_owned(),
is_dir,
children: if is_dir { Some(vec![]) } else { None },
});
for entry in entries.flatten() {
let path_buf = entry.path();
let name = entry
.file_name()
.into_string()
.unwrap_or_else(|_| String::from("unknown"));
if name.starts_with('.') {
continue;
}
let is_dir = path_buf.is_dir();
if !is_dir && !is_supported_content_file(&path_buf) {
continue;
}

nodes.push(FileNode {
name,
path: path_buf.to_string_lossy().into_owned(),
is_dir,
children: if is_dir { Some(vec![]) } else { None },
});
}
nodes.sort_by(|a, b| b.is_dir.cmp(&a.is_dir).then(a.name.cmp(&b.name)));
Ok(nodes)
Expand Down Expand Up @@ -75,7 +73,7 @@ fn decode_text_bytes(bytes: &[u8]) -> Result<String, String> {
}

fn decode_utf16_bytes(bytes: &[u8], little_endian: bool) -> Result<String, String> {
if bytes.len() % 2 != 0 {
if !bytes.len().is_multiple_of(2) {
return Err("UTF-16 文件字节长度不完整".to_string());
}

Expand Down
19 changes: 9 additions & 10 deletions src-tauri/src/crawler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ fn decrypt_text(text: &str) -> String {

let has_pua = text.chars().any(|c| {
let u = c as u32;
u >= 58344 && u <= 58716
(58344..=58716).contains(&u)
});

if !has_pua {
Expand Down Expand Up @@ -277,7 +277,7 @@ pub fn crawl_fanqie_article(
for a in document.select(&a_sel) {
let href = a.value().attr("href").unwrap_or("");
if href.contains("/reader/") {
chapter_id = href.split('/').last().unwrap_or("").to_string();
chapter_id = href.split('/').next_back().unwrap_or("").to_string();
break;
}
}
Expand All @@ -300,20 +300,19 @@ pub fn crawl_fanqie_article(

fs::write(&file_path, md_content).map_err(|e| format!("保存文件失败: {}", e))?;

return Ok(format!("成功爬取短篇小说并保存至: {}", file_path.display()));
Ok(format!("成功爬取短篇小说并保存至: {}", file_path.display()))
} else {
// Long novel
let mut chapters = Vec::new();
let a_sel = Selector::parse("a.chapter-item-title").unwrap();
for a in document.select(&a_sel) {
let title = a.text().collect::<String>().trim().to_string();
let href = a.value().attr("href").unwrap_or("");
let chapter_id = href.split('/').last().unwrap_or("").to_string();
if !chapter_id.is_empty() && !title.is_empty() {
if !title.contains("最近更新") && !title.contains("开始阅读") {
let chapter_id = href.split('/').next_back().unwrap_or("").to_string();
if !chapter_id.is_empty() && !title.is_empty()
&& !title.contains("最近更新") && !title.contains("开始阅读") {
chapters.push((title, chapter_id));
}
}
}

if chapters.is_empty() {
Expand All @@ -322,7 +321,7 @@ pub fn crawl_fanqie_article(
let title = a.text().collect::<String>().trim().to_string();
let href = a.value().attr("href").unwrap_or("");
if href.contains("/reader/") {
let chapter_id = href.split('/').last().unwrap_or("").to_string();
let chapter_id = href.split('/').next_back().unwrap_or("").to_string();
if !chapters.iter().any(|(_, id)| id == &chapter_id) {
chapters.push((title, chapter_id));
}
Expand Down Expand Up @@ -386,12 +385,12 @@ pub fn crawl_fanqie_article(
std::thread::sleep(Duration::from_millis(300));
}

return Ok(format!(
Ok(format!(
"成功抓取《{}》前{}章及目录,存至: {}",
novel_name,
success_count,
book_folder.display()
));
))
}
}

Expand Down
6 changes: 2 additions & 4 deletions src-tauri/src/llm/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use crate::agent::parse_tool_arguments;
use crate::models::*;

pub fn approximate_token_count(text: &str) -> usize {
(text.chars().count() + 3) / 4
text.chars().count().div_ceil(4)
}

pub fn chat_message_token_estimate(message: &ChatMessage) -> usize {
Expand Down Expand Up @@ -455,14 +455,12 @@ fn select_compaction_boundary(

let mut start = history.len();
let mut total = 0usize;
let mut kept = 0usize;
for index in (0..history.len()).rev() {
for (kept, index) in (0..history.len()).rev().enumerate() {
let cost = chat_message_token_estimate(&history[index]);
if kept >= 4 && total + cost > recent_budget {
break;
}
total += cost;
kept += 1;
start = index;
}
if start == 0 || start >= history.len() {
Expand Down
13 changes: 5 additions & 8 deletions src-tauri/src/mobile_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -126,7 +126,7 @@ pub fn get_lan_ip() -> Option<IpAddr> {
#[cfg(target_os = "macos")]
fn get_mac_interface_ip(interface: &str) -> Option<IpAddr> {
let output = std::process::Command::new("ipconfig")
.args(&["getifaddr", interface])
.args(["getifaddr", interface])
.output()
.ok()?;
if output.status.success() {
Expand Down Expand Up @@ -1491,13 +1491,10 @@ pub async fn start_server<R: Runtime>(app_handle: AppHandle<R>) -> Result<(), St

for p in 4080..=4085 {
let addr = SocketAddr::from(([0, 0, 0, 0], p));
match tokio::net::TcpListener::bind(&addr).await {
Ok(l) => {
listener = Some(l);
port = p;
break;
}
Err(_) => {}
if let Ok(l) = tokio::net::TcpListener::bind(&addr).await {
listener = Some(l);
port = p;
break;
}
}

Expand Down
6 changes: 2 additions & 4 deletions src-tauri/src/tools/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -455,10 +455,8 @@ pub fn tool_glob(pattern: String, path: Option<String>, workspace: Option<String

let full_pattern = base.join(&pattern).to_string_lossy().into_owned();
let mut hits = Vec::new();
for entry in glob(&full_pattern).map_err(|e| e.to_string())? {
if let Ok(path) = entry {
hits.push(path);
}
for path in glob(&full_pattern).map_err(|e| e.to_string())?.flatten() {
hits.push(path);
}

hits.sort_by(|a, b| {
Expand Down
9 changes: 4 additions & 5 deletions src-tauri/src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -324,7 +324,7 @@ pub fn get_python_info() -> &'static str {
pub fn copy_dir_recursive(src: &Path, dst: &Path) -> std::io::Result<()> {
fs::create_dir_all(dst)?;
for entry in walkdir::WalkDir::new(src) {
let entry = entry.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
let entry = entry.map_err(std::io::Error::other)?;
let ty = entry.file_type();
let dest_path = dst.join(entry.path().strip_prefix(src).unwrap());
if ty.is_dir() {
Expand All @@ -338,7 +338,7 @@ pub fn copy_dir_recursive(src: &Path, dst: &Path) -> std::io::Result<()> {
pub fn copy_md_dir_recursive(src: &Path, dst: &Path) -> std::io::Result<()> {
fs::create_dir_all(dst)?;
for entry in walkdir::WalkDir::new(src) {
let entry = entry.map_err(|e| std::io::Error::new(std::io::ErrorKind::Other, e))?;
let entry = entry.map_err(std::io::Error::other)?;
if entry
.path()
.components()
Expand All @@ -354,14 +354,13 @@ pub fn copy_md_dir_recursive(src: &Path, dst: &Path) -> std::io::Result<()> {
}

let dest_path = dst.join(relative_path);
if ty.is_file() {
if is_supported_content_file(entry.path()) {
if ty.is_file()
&& is_supported_content_file(entry.path()) {
if let Some(parent) = dest_path.parent() {
fs::create_dir_all(parent)?;
}
fs::copy(entry.path(), &dest_path)?;
}
}
}
Ok(())
}
Expand Down
Loading