The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
fix(files): reading a binary base64-encoded the whole file to throw it away
David51724c62b79e
diff --git a/src-tauri/src/commands/filesystem.rs b/src-tauri/src/commands/filesystem.rsindex da3e0901..6bd0692a 100644--- a/src-tauri/src/commands/filesystem.rs+++ b/src-tauri/src/commands/filesystem.rs@@ -175,13 +175,19 @@ pub fn fs_read(path: String, chatId: Option<String>, workingDirectory: Option<Streturn Err(format!("File not found: {}", full.display()));}- // Try text first, fall back to base64 for binary+ // Text, or a binary MARKER — never the binary payload.+ //+ // This used to base64-encode the whole file and ship it over IPC. Every+ // consumer discards it: the model-facing file_read turns it into a "binary,+ // not shown" line, and both file_edit paths refuse outright. So a 500 MB+ // model file cost ~667 MB of base64 in Rust plus the JSON and JS copies of+ // it, all to be thrown away — the desktop half of a guard the phone relay+ // already had (f3542ff).match fs::read_to_string(&full) {Ok(content) => Ok(serde_json::json!({ "content": content, "encoding": "utf8" })),Err(_) => {- let bytes = fs::read(&full).map_err(|e| format!("Read error: {}", e))?;- let b64 = base64::engine::general_purpose::STANDARD.encode(&bytes);- Ok(serde_json::json!({ "content": b64, "encoding": "base64" }))+ let bytes = fs::metadata(&full).map(|m| m.len()).unwrap_or(0);+ Ok(serde_json::json!({ "encoding": "binary", "bytes": bytes }))}}}@@ -749,3 +755,70 @@ mod jail_adversarial_tests {assert!(contain_within(root, root).is_ok());}}++#[cfg(test)]+mod binary_read_tests {+ use super::*;+ use std::fs;++ fn ws(tag: &str) -> PathBuf {+ let d = std::env::temp_dir().join(format!("lu-fsread-{}-{}", tag, std::process::id()));+ let _ = fs::remove_dir_all(&d);+ fs::create_dir_all(&d).unwrap();+ d+ }++ /// A binary must come back as a MARKER, not as a payload. Every consumer+ /// discards the bytes, so encoding them only bought a memory spike+ /// proportional to the file — the phone relay already refused to do it.+ #[test]+ fn a_binary_file_reports_its_size_and_no_content() {+ let dir = ws("bin");+ // Invalid UTF-8 — what read_to_string rejects.+ fs::write(dir.join("model.gguf"), [0xff, 0xfe, 0x00, 0x01, 0x80]).unwrap();++ let v = fs_read(+ "model.gguf".into(),+ None,+ Some(dir.to_string_lossy().to_string()),+ )+ .expect("read");++ assert_eq!(v["encoding"], "binary");+ assert_eq!(v["bytes"], 5);+ assert!(v.get("content").is_none(), "the payload must not be shipped");+ let _ = fs::remove_dir_all(&dir);+ }++ #[test]+ fn a_text_file_still_comes_back_verbatim() {+ let dir = ws("txt");+ fs::write(dir.join("a.txt"), "hallo\nwelt\n").unwrap();++ let v = fs_read("a.txt".into(), None, Some(dir.to_string_lossy().to_string()))+ .expect("read");++ assert_eq!(v["encoding"], "utf8");+ assert_eq!(v["content"], "hallo\nwelt\n");+ let _ = fs::remove_dir_all(&dir);+ }++ /// The whole point: cost must not scale with the file any more.+ #[test]+ fn a_large_binary_is_cheap_to_read() {+ let dir = ws("big");+ let mut big = vec![0x80u8; 8 * 1024 * 1024]; // 8 MiB, invalid UTF-8+ big[0] = 0xff;+ fs::write(dir.join("big.bin"), &big).unwrap();++ let started = std::time::Instant::now();+ let v = fs_read("big.bin".into(), None, Some(dir.to_string_lossy().to_string()))+ .expect("read");+ let took = started.elapsed();++ assert_eq!(v["bytes"], 8 * 1024 * 1024_u64);+ assert!(v.get("content").is_none());+ assert!(took < std::time::Duration::from_millis(200), "took {took:?}");+ let _ = fs::remove_dir_all(&dir);+ }+}diff --git a/src/api/mcp/builtin-tools.ts b/src/api/mcp/builtin-tools.tsindex 4c3df390..8fdae68f 100644--- a/src/api/mcp/builtin-tools.ts+++ b/src/api/mcp/builtin-tools.ts@@ -695,14 +695,14 @@ async function executeWebFetch(args: Record<string, any>): Promise<string> {async function executeFileRead(args: Record<string, any>): Promise<string> {const data = await backendCall('fs_read', { path: args.path, ...chatCtx() })- // Binary files come back base64-encoded (encoding: 'base64'). Returning that- // raw base64 as if it were the file's text is a corruption trap: the model- // treats it as content and a later file_write persists the base64 STRING,- // silently mangling the binary. Surface a clear marker instead so the model- // knows it is binary and leaves it alone.- if (data.encoding === 'base64') {- const approxBytes = Math.floor((String(data.content || '').length * 3) / 4)- return `[binary file — ${formatBytes(approxBytes)}, not shown. This tool reads text only; do not write binary content back through file_write.]`+ // A binary file comes back as a marker with its size, never as content.+ // Handing the model raw bytes-as-text is a corruption trap: it treats them as+ // content and a later file_write persists that string, mangling the file.+ if (data.encoding === 'binary' || data.encoding === 'base64') {+ const bytes = typeof data.bytes === 'number'+ ? data.bytes+ : Math.floor((String(data.content || '').length * 3) / 4)+ return `[binary file — ${formatBytes(bytes)}, not shown. This tool reads text only; do not write binary content back through file_write.]`}return data.content || ''}@@ -771,7 +771,7 @@ async function executeFileEdit(args: Record<string, any>): Promise<string> {} catch (e) {return `Error: file_edit could not read ${path}: ${e instanceof Error ? e.message : String(e)}. To create a new file use file_write.`}- if (data.encoding === 'base64') return `Error: file_edit cannot edit a binary file (${path}).`+ if (data.encoding === 'binary' || data.encoding === 'base64') return `Error: file_edit cannot edit a binary file (${path}).`const content = typeof data.content === 'string' ? data.content : ''const res = applyUniqueEdit(content, oldString, newString)diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.tsindex a24abb6d..af407d61 100644--- a/src/hooks/useCodex.ts+++ b/src/hooks/useCodex.ts@@ -1394,7 +1394,7 @@ export function useCodex() {} else {try {const r = await backendCall<{ content?: string; encoding?: string }>('fs_read', { path: resolvedPath, ...stageReadCtx })- if (r?.encoding === 'base64') return `file_edit: cannot edit a binary file (${path}).`+ if (r?.encoding === 'binary' || r?.encoding === 'base64') return `file_edit: cannot edit a binary file (${path}).`baseContent = diskContent = r?.content ?? ''} catch {return `file_edit: could not read ${path}. To create a new file use file_write.`