use std::fs::OpenOptions;
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
use chrono::{DateTime, Utc};
use fs2::FileExt;
use serde::Serialize;
use tauri::{AppHandle, Emitter, Runtime};
use crate::commands::skills::{
check_skill_update_internal_with_remote, prefetch_skill_remote, update_git_skill_internal,
};
use crate::core::repo_lock::RepoLock;
use crate::core::skill_store::SkillStore;
const SETTING_INTERVAL: &str = "auto_update_check_interval";
const SETTING_LAST_RUN: &str = "auto_update_last_run_at";
const SETTING_APPLY: &str = "auto_update_apply";
pub(super) const ROUND_LOCK: &str = ".skill-auto-update.lock";
const EVENT_AUTO_UPDATED: &str = "skills-auto-updated";
const INITIAL_DELAY: Duration = Duration::from_secs(60);
const POLL_INTERVAL: Duration = Duration::from_secs(15 * 60);
const FOREGROUND_YIELD: Duration = Duration::from_millis(200);
#[derive(Serialize, Clone)]
struct AutoUpdatePayload {
ran_at: String,
}
pub fn start<R: Runtime>(app: AppHandle<R>, store: Arc<SkillStore>) {
if !crate::core::git_credentials::background_access_enabled() {
log::info!(
"skill auto-updater: disabled for debug builds; set AGENT_HUB_DEV_KEYCHAIN=1 to opt in"
);
return;
}
tauri::async_runtime::spawn(async move {
tokio::time::sleep(INITIAL_DELAY).await;
loop {
if round_due(&store) {
let store_for_task = store.clone();
match tauri::async_runtime::spawn_blocking(move || {
run_due_round(&store_for_task, &crate::core::central_repo::home_base_dir())
})
.await
{
Ok(Ok(Some(now))) => emit_round_completion(&app, now),
Ok(Ok(None)) => {}
Ok(Err(error)) => log::warn!("skill auto-updater: round errored: {error}"),
Err(error) => log::warn!("skill auto-updater: worker failed: {error}"),
}
}
tokio::time::sleep(POLL_INTERVAL).await;
}
});
}
pub fn record_round_completion<R: Runtime>(app: &AppHandle<R>, store: &SkillStore) {
let now = Utc::now();
write_last_run(store, now);
emit_round_completion(app, now);
}
fn emit_round_completion<R: Runtime>(app: &AppHandle<R>, now: DateTime<Utc>) {
let payload = AutoUpdatePayload {
ran_at: now.to_rfc3339(),
};
if let Err(err) = app.emit(EVENT_AUTO_UPDATED, payload) {
log::debug!("skill auto-updater: emit failed: {err}");
}
if let Err(err) = crate::refresh_tray_menu(app) {
log::debug!("skill auto-updater: refresh_tray_menu failed: {err}");
}
}
fn read_interval(store: &SkillStore) -> Option<Duration> {
let raw = store.get_setting(SETTING_INTERVAL).ok().flatten()?;
parse_interval(raw.trim())
}
fn parse_interval(raw: &str) -> Option<Duration> {
match raw.to_ascii_lowercase().as_str() {
"" | "off" | "manual" | "disabled" => None,
"1h" | "hourly" => Some(Duration::from_secs(60 * 60)),
"6h" => Some(Duration::from_secs(6 * 60 * 60)),
"24h" | "1d" | "daily" => Some(Duration::from_secs(24 * 60 * 60)),
_ => None,
}
}
fn read_last_run(store: &SkillStore) -> Option<DateTime<Utc>> {
let raw = store.get_setting(SETTING_LAST_RUN).ok().flatten()?;
DateTime::parse_from_rfc3339(raw.trim())
.ok()
.map(|dt| dt.with_timezone(&Utc))
}
fn write_last_run(store: &SkillStore, at: DateTime<Utc>) {
if let Err(err) = store.set_setting(SETTING_LAST_RUN, &at.to_rfc3339()) {
log::warn!("skill auto-updater: failed to persist {SETTING_LAST_RUN}: {err}");
}
}
fn is_due(last_run: Option<DateTime<Utc>>, interval: Duration) -> bool {
let Some(last) = last_run else {
return true;
};
let elapsed = Utc::now().signed_duration_since(last);
let Some(interval_chrono) = chrono::Duration::from_std(interval).ok() else {
log::warn!(
"skill auto-updater: failed to convert interval to chrono::Duration ({}s)",
interval.as_secs()
);
return false;
};
elapsed >= interval_chrono
}
fn round_due(store: &SkillStore) -> bool {
read_interval(store).is_some_and(|interval| is_due(read_last_run(store), interval))
}
fn run_due_round(store: &SkillStore, data_home: &Path) -> Result<Option<DateTime<Utc>>, String> {
let file = OpenOptions::new()
.create(true)
.truncate(false)
.read(true)
.write(true)
.open(data_home.join(ROUND_LOCK))
.map_err(|error| error.to_string())?;
match FileExt::try_lock_exclusive(&file) {
Ok(()) => {}
Err(error) if error.raw_os_error() == fs2::lock_contended_error().raw_os_error() => {
return Ok(None)
}
Err(error) => return Err(error.to_string()),
}
if !round_due(store) {
return Ok(None);
}
run_round_blocking(store)?;
let now = Utc::now();
write_last_run(store, now);
Ok(Some(now))
}
fn apply_enabled(store: &SkillStore) -> bool {
matches!(
store.get_setting(SETTING_APPLY).ok().flatten().as_deref(),
Some("on")
)
}
fn run_round_blocking(store: &SkillStore) -> Result<(), String> {
let proxy = store.proxy_url();
let apply = apply_enabled(store);
let ids: Vec<String> = store
.get_all_skills()
.map_err(|err| format!("get_all_skills failed: {err}"))?
.into_iter()
.map(|s| s.id)
.collect();
let (mut checked, mut available, mut updated, mut held_back, mut failed) =
(0usize, 0usize, 0usize, 0usize, 0usize);
for skill_id in ids {
std::thread::sleep(FOREGROUND_YIELD);
checked += 1;
let prefetched = prefetch_skill_remote(store, &skill_id, true, proxy.as_deref());
let status = {
let _lock = match RepoLock::acquire("auto-update check") {
Ok(lock) => lock,
Err(_) => {
failed += 1;
log::info!("skill auto-updater: skipping {skill_id} (repo busy)");
continue;
}
};
match check_skill_update_internal_with_remote(store, &skill_id, true, prefetched) {
Ok(dto) => dto.update_status,
Err(err) => {
failed += 1;
log::warn!("skill auto-updater: check failed for {skill_id}: {err}");
continue;
}
}
};
if status != "update_available" {
continue;
}
available += 1;
if apply {
match update_git_skill_internal(store, &skill_id, proxy.as_deref(), None, None) {
Ok(result) if !result.pending_removals.is_empty() => {
held_back += 1;
log::info!(
"skill auto-updater: holding back {skill_id} — updating would remove {} \
path(s) the new version does not have; update it by hand to review",
result.pending_removals.len()
);
}
Ok(result) if result.skill.update_status == "central_newer" => held_back += 1,
Ok(_) => updated += 1,
Err(err) => {
failed += 1;
log::warn!(
"skill auto-updater: update failed for {skill_id}: {}",
err.message
);
}
}
}
}
log::info!(
"skill auto-updater: round done — checked={checked} available={available} updated={updated} held_back={held_back} failed={failed}"
);
Ok(())
}
#[cfg(test)]
mod tests;