import { EventEmitter } from 'events'; import fs from 'fs'; import path from 'path'; import { CONFIG } from '../config'; import { log } from './logger'; export type WorkspaceEvent = | { type: 'file'; kind: 'add' | 'change' | 'unlink' | 'addDir' | 'unlinkDir'; path: string; ts: number; containerId?: string } | { type: 'git'; ts: number } | { type: 'container'; containerId: string; status: string; ts: number } | { type: 'job'; jobId: string; status: string; scope: 'workspace' | 'container'; ts: number } | { type: 'heartbeat'; ts: number }; const IGNORE_DIR_NAMES = new Set([ 'node_modules', '.next', 'dist', 'build', 'out', '.turbo', '.cache', '.parcel-cache', '.vercel', 'coverage', '__pycache__', '.venv', 'venv', 'target', ]); // Paths inside .git that should emit git events (branch/index/HEAD mutations). const GIT_INTEREST = [ /\/\.git\/HEAD$/, /\/\.git\/index$/, /\/\.git\/refs\/heads\//, /\/\.git\/packed-refs$/, /\/\.git\/MERGE_HEAD$/, /\/\.git\/COMMIT_EDITMSG$/, ]; function isIgnored(rel: string): boolean { // rel is relative to mount root; normalise separators const parts = rel.split(path.sep); // Ignore any path containing a blocked directory — except inside .git, // where we explicitly whitelist specific files above. const inGit = parts.includes('.git'); if (inGit) { return !GIT_INTEREST.some((re) => re.test('/' + rel.replace(/\\/g, '/'))); } return parts.some((p) => IGNORE_DIR_NAMES.has(p)); } class WorkspaceWatcher { private emitter = new EventEmitter(); private watcher: fs.FSWatcher | null = null; private started = false; private debounceMap = new Map>(); private gitDebounce: ReturnType | null = null; constructor() { // Many subscribers: one per open Nekodo session per tab. this.emitter.setMaxListeners(0); } start(): void { if (this.started) return; this.started = true; const root = CONFIG.WORKSPACE.MOUNT_PATH; try { if (!fs.existsSync(root)) { log.warn({ root }, 'workspace-watcher: mount path does not exist yet; watcher disabled'); return; } this.watcher = fs.watch(root, { recursive: true, persistent: false }, (eventType, filename) => { if (!filename) return; const rel = typeof filename === 'string' ? filename : Buffer.from(filename as Buffer).toString('utf8'); if (isIgnored(rel)) return; const absPath = path.join(root, rel); const fullRel = '/' + rel.replace(/\\/g, '/'); // Git-meta change → emit a single debounced 'git' event. if (GIT_INTEREST.some((re) => re.test(fullRel))) { if (this.gitDebounce) clearTimeout(this.gitDebounce); this.gitDebounce = setTimeout(() => this.emit({ type: 'git', ts: Date.now() }), 200); return; } // File change — debounce per-path so editors that save with a // rename+replace dance (Vim, VSCode atomic save) don't spam. const key = absPath; const prev = this.debounceMap.get(key); if (prev) clearTimeout(prev); const timer = setTimeout(() => { this.debounceMap.delete(key); // Determine kind by stat. `rename` on POSIX can mean either create // or unlink; stat tells us which. fs.stat(absPath, (err, stats) => { if (err) { this.emit({ type: 'file', kind: eventType === 'rename' ? 'unlink' : 'change', path: fullRel, ts: Date.now(), }); return; } const kind = stats.isDirectory() ? 'addDir' : eventType === 'rename' ? 'add' : 'change'; this.emit({ type: 'file', kind, path: fullRel, ts: Date.now() }); }); }, 80); this.debounceMap.set(key, timer); }); this.watcher.on('error', (err) => { log.error({ err: err.message }, 'workspace-watcher error'); }); log.info({ root }, 'workspace-watcher started'); } catch (err: any) { log.error({ err: err?.message }, 'workspace-watcher failed to start'); } } stop(): void { this.watcher?.close(); this.watcher = null; for (const t of this.debounceMap.values()) clearTimeout(t); this.debounceMap.clear(); if (this.gitDebounce) clearTimeout(this.gitDebounce); this.started = false; } // External producers (API handlers, ContainerManager) push events through this. emit(event: WorkspaceEvent): void { this.emitter.emit('event', event); } subscribe(listener: (event: WorkspaceEvent) => void): () => void { this.emitter.on('event', listener); return () => this.emitter.off('event', listener); } subscriberCount(): number { return this.emitter.listenerCount('event'); } } export const workspaceWatcher = new WorkspaceWatcher();