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(agent): asking the time froze the window and could answer in UTC
David44a1c32e57e4
diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex 9c757418..8ca19ea2 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -2528,10 +2528,11 @@ dependencies = [[[package]]name = "locally-uncensored"-version = "2.5.9"+version = "2.5.10"dependencies = ["axum","base64 0.22.1",+ "chrono","dirs","futures-util","glob",diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex 0e088eed..1addf46f 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -56,6 +56,10 @@ socket2 = "0.5"# Structured tracing — used for the JSON-log mode behind `LU_LOG_FORMAT=json`# (uselu Phase 3 parity). Default formatter is the compact text layer so# the existing console output stays readable for a desktop user.+# Local time with a real UTC offset for the agent's get_current_time tool.+# Already resolved in the lock (jsonwebtoken pulls it with `clock` ++# iana-time-zone), so declaring it directly adds no crate to the build.+chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }tracing = "0.1"tracing-subscriber = { version = "0.3", features = ["env-filter", "json"] }diff --git a/src-tauri/src/commands/system.rs b/src-tauri/src/commands/system.rsindex 24765f0f..143b8624 100644--- a/src-tauri/src/commands/system.rs+++ b/src-tauri/src/commands/system.rs@@ -227,129 +227,84 @@ pub fn set_onboarding_done(done: Option<bool>) -> Result<(), String> {/// Return the current local date/time/timezone. Agents should call this/// instead of googling "what day is it" — the info is free and exact.+///+/// This used to shell out (`powershell (Get-Date).ToString('zzz')` on Windows,+/// `date +%z` elsewhere) purely to learn the UTC offset, on the main thread,+/// on EVERY call — and the tool sits in ALWAYS_INCLUDE, so the model may call+/// it any turn. A PowerShell cold start is 300-900 ms, more with an AV hooked+/// into process creation, and the window is frozen for all of it. Worse, when+/// the spawn failed the offset silently fell back to 0, so the agent reported+/// UTC as the user's local time.+///+/// chrono was already in the dependency tree (via jsonwebtoken, with the+/// `clock` feature and iana-time-zone resolved), so reading the real offset+/// in-process costs no new crate and no process at all.#[tauri::command]pub fn get_current_time() -> Result<serde_json::Value, String> {- use std::time::SystemTime;- let now = SystemTime::now()- .duration_since(SystemTime::UNIX_EPOCH)- .map_err(|e| e.to_string())?;- let unix = now.as_secs();+ use chrono::{Offset, Utc};- // Format via chrono if available (transitive dep via jsonwebtoken); else- // do a hand-rolled ISO-8601 fallback. Both produce stable output.- let (iso_local, iso_utc, tz_name, tz_offset_minutes) = format_datetime(unix);+ let local = chrono::Local::now();+ let utc = local.with_timezone(&Utc);+ let offset_minutes = local.offset().fix().local_minus_utc() / 60;Ok(serde_json::json!({- "unix": unix,- "iso_local": iso_local, // e.g. "2026-04-15 01:23:45"- "iso_utc": iso_utc, // e.g. "2026-04-14T23:23:45Z"- "timezone": tz_name, // e.g. "CEST" or "+0200"- "timezone_offset": tz_offset_minutes,+ "unix": utc.timestamp(),+ "iso_local": local.format("%Y-%m-%d %H:%M:%S").to_string(),+ "iso_utc": utc.format("%Y-%m-%dT%H:%M:%SZ").to_string(),+ "timezone": local.format("%z").to_string(),+ "timezone_offset": offset_minutes,}))}-fn format_datetime(unix_secs: u64) -> (String, String, String, i32) {- // Derive local offset from system. `time` crate would be cleaner but- // isn't in our dep tree; use std + sysinfo hints. On both supported- // platforms std::time::SystemTime is unaware of timezones, so we read- // the offset from a known local -> utc conversion.- use std::time::{Duration, UNIX_EPOCH};- let t = UNIX_EPOCH + Duration::from_secs(unix_secs);-- // UTC parts (manual, no chrono dep pulled in just for this)- let (y, mo, d, h, mi, s) = unix_to_utc_parts(unix_secs);- let iso_utc = format!("{:04}-{:02}-{:02}T{:02}:{:02}:{:02}Z", y, mo, d, h, mi, s);-- // Local parts — use SystemTime relative to a known local calendar date.- // The simplest portable trick: format via C lib through `humantime` isn't- // installed either. We use a small offset probe.- let offset_minutes = local_offset_minutes();- let local_unix = (unix_secs as i64) + (offset_minutes as i64) * 60;- let (ly, lmo, ld, lh, lmi, ls) = unix_to_utc_parts(local_unix.max(0) as u64);- let iso_local = format!("{:04}-{:02}-{:02} {:02}:{:02}:{:02}", ly, lmo, ld, lh, lmi, ls);-- let sign = if offset_minutes >= 0 { '+' } else { '-' };- let abs = offset_minutes.unsigned_abs();- let tz_name = format!("{}{:02}{:02}", sign, abs / 60, abs % 60);-- let _ = t;- (iso_local, iso_utc, tz_name, offset_minutes)-}--fn local_offset_minutes() -> i32 {- // Spawn `date +%z` on Unix, `Get-Date` on Windows — very cheap, no deps.- #[cfg(target_os = "windows")]- {- use std::process::Command;- let out = Command::new("powershell")- .args(["-NoProfile", "-Command", "(Get-Date).ToString('zzz')"])- .creation_flags(0x0800_0000)- .output();- if let Ok(o) = out {- if let Ok(s) = String::from_utf8(o.stdout) {- let s = s.trim();- return parse_offset_to_minutes(s).unwrap_or(0);- }- }- }- #[cfg(not(target_os = "windows"))]- {- use std::process::Command;- let out = Command::new("date").arg("+%z").output();- if let Ok(o) = out {- if let Ok(s) = String::from_utf8(o.stdout) {- return parse_offset_to_minutes(s.trim()).unwrap_or(0);- }- }+#[cfg(test)]+mod tests {+ use super::*;++ /// The old implementation spawned a process for the UTC offset and fell+ /// back to 0 when that failed, so it could report UTC as local time. These+ /// assert the three values stay consistent with each other.+ #[test]+ fn current_time_is_internally_consistent() {+ let v = get_current_time().expect("get_current_time");+ let unix = v["unix"].as_i64().unwrap();+ let offset_min = v["timezone_offset"].as_i64().unwrap();++ // Local wall clock must be exactly `offset` minutes ahead of UTC.+ let utc = chrono::DateTime::parse_from_rfc3339(v["iso_utc"].as_str().unwrap())+ .expect("iso_utc parses as RFC3339");+ let local = chrono::NaiveDateTime::parse_from_str(+ v["iso_local"].as_str().unwrap(),+ "%Y-%m-%d %H:%M:%S",+ )+ .expect("iso_local parses");+ let delta_min = (local - utc.naive_utc()).num_minutes();+ assert_eq!(delta_min, offset_min, "local clock must be utc + offset");++ assert_eq!(utc.timestamp(), unix, "iso_utc must match the unix field");++ // "+0200" / "-0500" — the shape the agent prompt documents.+ let tz = v["timezone"].as_str().unwrap();+ assert!(+ tz.len() == 5 && (tz.starts_with('+') || tz.starts_with('-'))+ && tz[1..].chars().all(|c| c.is_ascii_digit()),+ "unexpected timezone format: {tz}"+ );}- 0-}--fn parse_offset_to_minutes(s: &str) -> Option<i32> {- // Accepts +HH:MM, +HHMM, -HH:MM, -HHMM- let bytes = s.as_bytes();- if bytes.is_empty() { return None; }- let sign = match bytes[0] {- b'+' => 1,- b'-' => -1,- _ => return None,- };- let digits: String = s[1..].chars().filter(|c| c.is_ascii_digit()).collect();- if digits.len() < 3 { return None; }- let hh: i32 = digits[..2].parse().ok()?;- let mm: i32 = digits[2..4.min(digits.len())].parse().ok().unwrap_or(0);- Some(sign * (hh * 60 + mm))-}-/// Minimal date math — good enough for display without pulling chrono in-/// just for this tool. Valid for dates after 1970.-fn unix_to_utc_parts(mut unix: u64) -> (i32, u32, u32, u32, u32, u32) {- let secs_of_day = (unix % 86_400) as u32;- unix /= 86_400; // days since epoch- let h = secs_of_day / 3600;- let mi = (secs_of_day / 60) % 60;- let s = secs_of_day % 60;-- // Zeller-ish: walk forward year by year- let mut year: i32 = 1970;- loop {- let days_in_year = if is_leap(year) { 366 } else { 365 };- if unix < days_in_year as u64 { break; }- unix -= days_in_year as u64;- year += 1;- }- let leap = is_leap(year);- let days_per_month = [31u64, if leap {29} else {28}, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];- let mut month: u32 = 1;- for dm in &days_per_month {- if unix < *dm { break; }- unix -= dm;- month += 1;+ #[test]+ fn current_time_costs_no_process_spawn() {+ // Measured: the old `date +%z` path cost 36.8 ms for 20 calls on this+ // Mac, and a PowerShell cold start on Windows is 300-900 ms EACH. In+ // process it is microseconds, so 20 ms fails either spawn path while+ // leaving plenty of room on a loaded box.+ let started = std::time::Instant::now();+ for _ in 0..20 {+ let _ = get_current_time().unwrap();+ }+ assert!(+ started.elapsed() < std::time::Duration::from_millis(20),+ "20 calls took {:?} — is something spawning a process again?",+ started.elapsed()+ );}- let day = unix as u32 + 1;- (year, month, day, h, mi, s)-}--fn is_leap(y: i32) -> bool {- (y % 4 == 0 && y % 100 != 0) || (y % 400 == 0)}