Skip to content

Commit c93aaae

Browse files
fix(tui): degrade gracefully when fs.watch fails (#51536)
1 parent 248bfbe commit c93aaae

5 files changed

Lines changed: 49 additions & 31 deletions

File tree

‎packages/tui/src/config/index.tsx‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import { Vcs } from "@opencode/schema/vcs"
55
import { Schema } from "effect"
66
import { createContext, onCleanup, type JSX, useContext } from "solid-js"
77
import { createStore, reconcile } from "solid-js/store"
8-
import { watch } from "fs"
8+
import { safeWatch } from "../util/watch"
99
import path from "path"
1010
import { TuiKeybind } from "./keybind"
1111

@@ -361,7 +361,7 @@ export function ConfigProvider(props: {
361361
}
362362
let reload = Promise.resolve()
363363
const watcher = host?.path
364-
? watch(path.dirname(host.path), () => {
364+
? safeWatch(path.dirname(host.path), () => {
365365
reload = reload
366366
.then(() => host.get())
367367
.then(apply)

‎packages/tui/src/context/storage.tsx‎

Lines changed: 12 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import { batch, createContext, onCleanup, useContext, type ParentProps } from "solid-js"
22
import { createStore, produce, reconcile, type Store } from "solid-js/store"
33
import path from "path"
4-
import { mkdirSync, readFileSync, watch } from "fs"
4+
import { mkdirSync, readFileSync } from "fs"
55
import { Flock } from "@opencode/util/flock"
66
import { writeJsonAtomic } from "../util/persistence"
7+
import { safeWatch } from "../util/watch"
78
import { useTuiApp, useTuiPaths } from "./runtime"
89

910
type Options<Value extends object> = {
@@ -111,26 +112,16 @@ export function createStorage(root: string, channel: string) {
111112
}
112113

113114
let reloadTimer: ReturnType<typeof setTimeout> | undefined
114-
let watcher: ReturnType<typeof watch> | undefined
115-
try {
116-
watcher = watch(directory, () => {
117-
clearTimeout(reloadTimer)
118-
// Atomic writes notify for the temporary file before its final rename, and some
119-
// platforms coalesce the rename event. Reload after the event burst has settled.
120-
reloadTimer = setTimeout(() => entries.forEach((entry) => entry.reload()), 50)
121-
})
122-
watcher.on("error", (error) => {
123-
clearTimeout(reloadTimer)
124-
watcher?.close()
125-
watcher = undefined
126-
console.error("Storage directory watcher failed, live-reload disabled", { directory, error })
127-
})
128-
} catch (error) {
129-
// fs.watch throws synchronously (e.g. ENOSPC when the inotify watch limit is
130-
// exhausted). Losing cross-process live-reload is recoverable; crashing the
131-
// whole TUI over it is not, so degrade instead of propagating.
132-
console.error("Failed to watch storage directory, live-reload disabled", { directory, error })
133-
}
115+
let watcher = safeWatch(directory, () => {
116+
clearTimeout(reloadTimer)
117+
// Atomic writes notify for the temporary file before its final rename, and some
118+
// platforms coalesce the rename event. Reload after the event burst has settled.
119+
reloadTimer = setTimeout(() => entries.forEach((entry) => entry.reload()), 50)
120+
})
121+
watcher?.on("error", () => {
122+
clearTimeout(reloadTimer)
123+
watcher = undefined
124+
})
134125
return {
135126
storage,
136127
close: () => {

‎packages/tui/src/model-preference.ts‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { readJson, writeJsonAtomic } from "./util/persistence"
22
import { isRecord } from "./util/record"
3+
import { safeWatch } from "./util/watch"
34
import { Flock } from "@opencode/util/flock"
4-
import { watch } from "node:fs"
55
import path from "node:path"
66

77
export type ModelPreferenceModel = {
@@ -103,7 +103,7 @@ function patch(value: Partial<ModelPreference>) {
103103
export function createModelPreferenceRepository(filePath: string) {
104104
let pending = Promise.resolve()
105105
let revision = 0
106-
let watcher: ReturnType<typeof watch> | undefined
106+
let watcher: ReturnType<typeof safeWatch>
107107
let reload: ReturnType<typeof setTimeout> | undefined
108108
const listeners = new Set<(value: ModelPreference) => void>()
109109
const read = () =>
@@ -152,15 +152,14 @@ export function createModelPreferenceRepository(filePath: string) {
152152
listeners.add(listener)
153153
void refresh()
154154
if (!watcher) {
155-
watcher = watch(path.dirname(filePath), (_event, filename) => {
155+
watcher = safeWatch(path.dirname(filePath), (_event, filename) => {
156156
const changed = filename?.toString()
157157
const name = path.basename(filePath)
158158
if (changed !== undefined && changed !== name && !changed.startsWith(name + ".")) return
159159
clearTimeout(reload)
160160
reload = setTimeout(() => void refresh(), 50)
161161
})
162-
watcher.on("error", () => {
163-
watcher?.close()
162+
watcher?.on("error", () => {
164163
watcher = undefined
165164
})
166165
}

‎packages/tui/src/plugin/watch.ts‎

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import path from "path"
2-
import { existsSync, watch } from "fs"
2+
import { existsSync, type FSWatcher } from "fs"
33
import { lstat, realpath, stat } from "fs/promises"
4+
import { safeWatch } from "../util/watch"
45

56
// Watch plugin sources for changes. Files are watched through their parent
67
// directory (editors that save by rename replace the inode, which silently
@@ -14,7 +15,7 @@ import { lstat, realpath, stat } from "fs/promises"
1415
// polled until they can be armed without relying on a racy chain of ancestor
1516
// watches.
1617
export function createSourceWatcher(onChange: () => void) {
17-
const watchers = new Map<string, ReturnType<typeof watch>>()
18+
const watchers = new Map<string, FSWatcher>()
1819
const watched = new Map<string, Set<string> | null>()
1920
const missing = new Set<string>()
2021
const arming = new Map<string, Promise<void>>()
@@ -44,7 +45,7 @@ export function createSourceWatcher(onChange: () => void) {
4445
if (appeared) notify()
4546
return
4647
}
47-
const watcher = watch(dir, (_event, filename) => {
48+
const watcher = safeWatch(dir, (_event, filename) => {
4849
// A replaced directory keeps this watcher on the dead inode (Linux
4950
// emits rename, not error); forget it so a later add() re-arms on
5051
// the recreated path, and still schedule so reconcile runs now.
@@ -58,6 +59,9 @@ export function createSourceWatcher(onChange: () => void) {
5859
if (filename && accept && !accept.has(filename.toString())) return
5960
notify()
6061
})
62+
// Watching is unavailable (opted out or the host refused the watch);
63+
// leave this target unwatched instead of claiming it in the maps.
64+
if (!watcher) return
6165
watched.set(dir, name === null ? null : new Set([name]))
6266
// Reconcile after watcher errors so every source is re-added and any
6367
// temporarily unavailable target moves into the polling set.

‎packages/tui/src/util/watch.ts‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import { watch, type WatchListener } from "node:fs"
2+
3+
/**
4+
* Watch a path without letting a failed watch take down the TUI. fs.watch throws
5+
* synchronously when the host cannot allocate one (e.g. ENOSPC/EMFILE when the
6+
* inotify budget is exhausted) and emits "error" later if the watch breaks; an
7+
* unhandled "error" event crashes the process. Losing live-reload is recoverable,
8+
* so both paths close the watch and log. Honors the server's disable switch.
9+
*/
10+
export function safeWatch(target: string, listener: WatchListener<string>) {
11+
const disabled = process.env.OPENCODE_FILEWATCHER_DISABLE ?? process.env.OPENCODE_DISABLE_FILEWATCHER
12+
if (disabled === "1" || disabled?.toLowerCase() === "true") return
13+
try {
14+
const watcher = watch(target, listener)
15+
watcher.on("error", (error) => {
16+
watcher.close()
17+
console.error("Watch failed, live-reload disabled", { target, error })
18+
})
19+
return watcher
20+
} catch (error) {
21+
console.error("Failed to watch path, live-reload disabled", { target, error })
22+
return
23+
}
24+
}

0 commit comments

Comments
 (0)