agent-hub-runtime 0.6.0

AgentHub desktop and companion CLI runtime for Tauri applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, OnceLock};
use std::time::{Duration, Instant};

use notify::{Config, Event, RecommendedWatcher, RecursiveMode, Watcher};
use tauri::Emitter;

use super::{central_repo, skill_store::SkillStore, tool_adapters};

const APP_FS_CHANGED_EVENT: &str = "app-files-changed";
const WATCH_RESCAN_INTERVAL: Duration = Duration::from_secs(3);
const WATCH_EMIT_DEBOUNCE: Duration = Duration::from_millis(500);

/// How long a single app-initiated write suppresses watcher emits. Covers a
/// batch of back-to-back `sync_skill`/`remove_target` calls plus the latency
/// before the OS delivers their events. Kept short so a genuine external edit
/// made moments after a sync is still surfaced by the next event or rescan.
const SELF_WRITE_MUTE: Duration = Duration::from_millis(1200);

/// Paths the app is currently writing to, plus the monotonic-ms deadline
/// (relative to [`EPOCH`]) until which their watcher echoes are suppressed
/// (#248: the app's own sync writes echoed back as `app-files-changed`,
/// forcing a redundant full `refreshAppData` - and historically refresh
/// storms). Path-scoped so a genuine external edit landing inside the window
/// is still surfaced (deferred) instead of silently dropped. A monotonic base
/// avoids wall-clock jumps breaking the window.
static MUTE_STATE: OnceLock<Mutex<MuteState>> = OnceLock::new();
static EPOCH: OnceLock<Instant> = OnceLock::new();

#[derive(Default)]
struct MuteState {
    deadline_ms: u64,
    roots: Vec<PathBuf>,
}

fn mute_state() -> &'static Mutex<MuteState> {
    MUTE_STATE.get_or_init(|| Mutex::new(MuteState::default()))
}

fn now_ms() -> u64 {
    EPOCH.get_or_init(Instant::now).elapsed().as_millis() as u64
}

/// Pure predicate split out so the mute window is unit-testable without touching
/// the process-global clock or state.
fn muted_at(now_ms: u64, suppress_until_ms: u64) -> bool {
    now_ms < suppress_until_ms
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum MuteVerdict {
    /// Outside any mute window.
    Live,
    /// Inside the window and every event path is under a dir the app itself
    /// just wrote: the echo the mute exists to swallow.
    SelfWrite,
    /// Inside the window but touching paths the app did NOT write (or a
    /// path-less rescan): someone else changed something while we were noisy.
    Foreign,
}

/// Pure classification split out for unit tests. `event_paths` empty means
/// "no path information" (watch-set rescan) — treated as Foreign so it defers
/// rather than vanishes.
fn classify_mute(
    now_ms: u64,
    deadline_ms: u64,
    roots: &[PathBuf],
    event_paths: &[PathBuf],
) -> MuteVerdict {
    if !muted_at(now_ms, deadline_ms) {
        return MuteVerdict::Live;
    }
    if !event_paths.is_empty()
        && event_paths
            .iter()
            .all(|path| roots.iter().any(|root| path.starts_with(root)))
    {
        MuteVerdict::SelfWrite
    } else {
        MuteVerdict::Foreign
    }
}

fn classify_event_paths(event_paths: &[PathBuf]) -> MuteVerdict {
    let state = mute_state().lock().unwrap();
    classify_mute(now_ms(), state.deadline_ms, &state.roots, event_paths)
}

#[derive(Debug, PartialEq, Eq, Clone, Copy)]
enum EmitAction {
    /// Forward the change to the frontend now.
    Emit,
    /// A real change arrived during the self-write mute: remember it and emit
    /// once the window closes. Dropping it outright would leave the UI stale
    /// when a user/external edit lands within the mute window (the whole point
    /// of the mute is to hide OUR writes, not theirs).
    Defer,
    /// Nothing to forward (irrelevant event, our own write echo, or debounce
    /// coalesces it into an emit that already happened).
    Skip,
}

/// Pure routing for one observed change, split out for unit tests. `relevant`
/// = the event/rescan actually warrants a refresh; `debounced` = an emit fired
/// less than the debounce ago.
fn decide_emit(relevant: bool, mute: MuteVerdict, debounced: bool) -> EmitAction {
    if !relevant {
        return EmitAction::Skip;
    }
    match mute {
        // The frontend already refreshed after the user action that caused
        // our write; its echo is pure redundant work (#248).
        MuteVerdict::SelfWrite => EmitAction::Skip,
        MuteVerdict::Foreign => EmitAction::Defer,
        MuteVerdict::Live => {
            if debounced {
                EmitAction::Skip
            } else {
                EmitAction::Emit
            }
        }
    }
}

/// Suppress the watcher echo of an app write under `target` for
/// [`SELF_WRITE_MUTE`]. The frontend already refreshes after the user action
/// that triggered the write, so echoing it back is pure redundant work.
/// Extends (never shrinks) an in-flight window and accumulates the batch's
/// roots, so a burst of writes keeps its own echoes quiet until it settles;
/// once the window expires the root list resets. Only paths under a recorded
/// root are treated as self-writes — anything else observed during the window
/// is deferred, not dropped. A no-op when no watcher is running (e.g. the
/// CLI), since nothing reads the state.
pub fn mute_self_writes(target: &Path) {
    let now = now_ms();
    let mut state = mute_state().lock().unwrap();
    if !muted_at(now, state.deadline_ms) {
        state.roots.clear();
    }
    state.deadline_ms = state
        .deadline_ms
        .max(now.saturating_add(SELF_WRITE_MUTE.as_millis() as u64));
    if !state.roots.iter().any(|root| target.starts_with(root)) {
        state.roots.push(target.to_path_buf());
    }
}

fn self_write_muted() -> bool {
    muted_at(now_ms(), mute_state().lock().unwrap().deadline_ms)
}

fn collect_watch_paths(store: &SkillStore) -> Vec<PathBuf> {
    let mut paths = vec![central_repo::skills_dir(), central_repo::scenarios_dir()];

    for adapter in tool_adapters::all_tool_adapters(store) {
        paths.push(adapter.skills_dir());
        paths.extend(adapter.all_scan_dirs());
    }

    if let Ok(projects) = store.get_all_projects() {
        let adapters = tool_adapters::all_tool_adapters(store);
        let mut seen_dirs = std::collections::HashSet::new();
        for project in projects {
            if project.workspace_type == "linked" {
                let skills_dir = PathBuf::from(&project.path);
                paths.push(skills_dir);
                if let Some(disabled_path) = project.disabled_path {
                    let disabled_dir = PathBuf::from(disabled_path);
                    paths.push(disabled_dir);
                }
                continue;
            }

            let project_path = PathBuf::from(&project.path);
            seen_dirs.clear();
            for adapter in &adapters {
                let project_dir = adapter.project_relative_skills_dir();
                if project_dir.is_empty() {
                    continue;
                }
                if !seen_dirs.insert(project_dir.to_string()) {
                    continue;
                }
                let skills_dir = project_path.join(project_dir);
                let disabled_dir = project_path.join(format!("{}-disabled", project_dir));
                // Only watch dirs that actually have skills inside. Watching the parent
                // or empty leaf dirs would hold OS handles (Windows ReadDirectoryChangesW)
                // and prevent users from deleting the agent-config folder (e.g. .codex)
                // after they remove all skills from it. Newly-populated dirs are picked
                // up by the polling rescan within WATCH_RESCAN_INTERVAL.
                if dir_has_entries(&skills_dir) {
                    paths.push(skills_dir);
                }
                if dir_has_entries(&disabled_dir) {
                    paths.push(disabled_dir);
                }
            }
        }
    }

    paths.sort();
    paths.dedup();
    paths
}

fn watch_target(path: &Path) -> Option<PathBuf> {
    if path.exists() {
        Some(path.to_path_buf())
    } else {
        None
    }
}

fn dir_has_entries(path: &Path) -> bool {
    std::fs::read_dir(path)
        .map(|mut iter| iter.next().is_some())
        .unwrap_or(false)
}

fn sync_watch_set(
    watcher: &mut RecommendedWatcher,
    watched: &mut HashSet<PathBuf>,
    store: &SkillStore,
) -> bool {
    let desired: HashSet<PathBuf> = collect_watch_paths(store)
        .into_iter()
        .filter_map(|path| watch_target(&path))
        .collect();
    let mut changed = false;

    for stale in watched.difference(&desired).cloned().collect::<Vec<_>>() {
        if let Err(err) = watcher.unwatch(&stale) {
            log::debug!("Failed to unwatch {}: {err}", stale.display());
        }
        watched.remove(&stale);
        changed = true;
    }

    for path in desired {
        if watched.contains(&path) {
            continue;
        }
        match watcher.watch(&path, RecursiveMode::Recursive) {
            Ok(()) => {
                watched.insert(path);
                changed = true;
            }
            Err(err) => {
                log::debug!("Failed to watch {}: {err}", path.display());
            }
        }
    }

    changed
}

fn should_emit(event: &Event) -> bool {
    if event.paths.is_empty() {
        return false;
    }
    // Drop events that come exclusively from `.git/` subtrees. `git fetch`
    // writes FETCH_HEAD/refs/packed-refs every time refreshGitStatus runs;
    // forwarding those to the UI causes refreshAppData → setManagedSkills →
    // refreshGitStatus to loop back into another fetch.
    event.paths.iter().any(|p| !is_in_git_dir(p))
}

fn is_in_git_dir(path: &Path) -> bool {
    path.components()
        .any(|c| c.as_os_str() == std::ffi::OsStr::new(".git"))
}

/// Whether the event touches the central repository's working tree (the part
/// auto-backup cares about). `.git` internals don't count — commits, fetches
/// and pushes must not re-arm the auto-backup debounce.
fn touches_central_repo(event: &Event) -> bool {
    let skills_dir = central_repo::skills_dir();
    event
        .paths
        .iter()
        .any(|p| p.starts_with(&skills_dir) && !is_in_git_dir(p))
}

pub fn start_file_watcher<R: tauri::Runtime>(app: tauri::AppHandle<R>, store: Arc<SkillStore>) {
    std::thread::spawn(move || {
        let (tx, rx) = std::sync::mpsc::channel();
        let mut watcher = match RecommendedWatcher::new(
            move |result| {
                let _ = tx.send(result);
            },
            Config::default().with_poll_interval(Duration::from_secs(2)),
        ) {
            Ok(watcher) => watcher,
            Err(err) => {
                log::error!("Failed to create filesystem watcher: {err}");
                return;
            }
        };

        let mut data_version = store.data_version().ok();
        let mut watched = HashSet::new();
        let mut last_sync = Instant::now() - WATCH_RESCAN_INTERVAL;
        let mut last_emit = Instant::now() - WATCH_EMIT_DEBOUNCE;
        // A relevant change arrived while self-writes were muted; emit it once
        // the window closes (the loop ticks at least every 500ms, so the flush
        // below needs no extra timer).
        let mut pending_emit = false;
        let automation_root = super::automation::watch_dir();
        let mut automation_watched = false;
        let config_root = super::user_config::root();
        let mut config_watched = false;

        let emit_now = |last_emit: &mut Instant| {
            if let Err(err) = app.emit(APP_FS_CHANGED_EVENT, ()) {
                log::debug!("Failed to emit app-files-changed: {err}");
            } else {
                *last_emit = Instant::now();
            }
        };

        loop {
            // Watch only this app's registry directory, without descending into
            // execution output or user workspaces. CLI edits use atomic rename.
            if !automation_watched && automation_root.is_absolute() {
                match std::fs::create_dir_all(&automation_root).and_then(|()| {
                    watcher
                        .watch(&automation_root, RecursiveMode::NonRecursive)
                        .map_err(std::io::Error::other)
                }) {
                    Ok(()) => automation_watched = true,
                    Err(error) => log::debug!("Cannot watch automation definitions: {error}"),
                }
            }
            if !config_watched || last_sync.elapsed() >= WATCH_RESCAN_INTERVAL {
                if config_watched {
                    let _ = watcher.unwatch(&config_root);
                }
                match super::user_config::checked(&config_root).and_then(|()| {
                    watcher
                        .watch(&config_root, RecursiveMode::Recursive)
                        .map_err(|e| e.to_string())
                }) {
                    Ok(()) => config_watched = true,
                    Err(error) => {
                        config_watched = false;
                        log::debug!("Cannot watch user configuration: {error}");
                    }
                }
            }
            if last_sync.elapsed() >= WATCH_RESCAN_INTERVAL {
                let external_write = store.data_version().is_ok_and(|version| {
                    data_version
                        .replace(version)
                        .is_some_and(|previous| previous != version)
                });
                let changed = sync_watch_set(&mut watcher, &mut watched, &store) || external_write;
                // No path information here, so a mute window classifies as
                // Foreign: the change defers instead of vanishing.
                match decide_emit(
                    changed,
                    classify_event_paths(&[]),
                    last_emit.elapsed() < WATCH_EMIT_DEBOUNCE,
                ) {
                    EmitAction::Emit => emit_now(&mut last_emit),
                    EmitAction::Defer => pending_emit = true,
                    EmitAction::Skip => {}
                }
                last_sync = Instant::now();
            }

            // Flush a deferred emit once the mute window has closed.
            if pending_emit && !self_write_muted() && last_emit.elapsed() >= WATCH_EMIT_DEBOUNCE {
                pending_emit = false;
                emit_now(&mut last_emit);
            }

            match rx.recv_timeout(Duration::from_millis(500)) {
                Ok(Ok(event)) => {
                    let automation_event = event.paths.iter().any(|path| {
                        path == &automation_root || path == &automation_root.join("tasks.json")
                    });
                    if automation_event && super::automation::has_pending_backup() {
                        super::cloud_sync::notify_central_change();
                    }
                    if touches_central_repo(&event)
                        || event
                            .paths
                            .iter()
                            .any(|path| path.starts_with(&config_root))
                    {
                        super::cloud_sync::notify_central_change();
                    }
                    match decide_emit(
                        should_emit(&event)
                            && (automation_event
                                || event
                                    .paths
                                    .iter()
                                    .any(|path| !path.starts_with(&automation_root))),
                        classify_event_paths(&event.paths),
                        last_emit.elapsed() < WATCH_EMIT_DEBOUNCE,
                    ) {
                        EmitAction::Emit => emit_now(&mut last_emit),
                        EmitAction::Defer => pending_emit = true,
                        EmitAction::Skip => {}
                    }
                }
                Ok(Err(err)) => {
                    log::debug!("Filesystem watcher error: {err}");
                }
                Err(std::sync::mpsc::RecvTimeoutError::Timeout) => {}
                Err(std::sync::mpsc::RecvTimeoutError::Disconnected) => break,
            }
        }
    });
}

#[cfg(test)]
mod tests;