Skip to content

Commit 96c9157

Browse files
fix(config): tell an unreadable mode file from an absent one before registering a batch
The Zoo-Code-Org#2236 row objects to a rollback snapshot that cannot distinguish 'there was nothing to restore' from 'I could not read what to restore'. loadModesFromFile returned [] for every non-success path: ENOENT into its catch, corrupt YAML through parseYamlSafely returning an empty object, and a schema-validation failure after its toast. getCustomModeDefinitions passed that straight into ClineProvider.createTask's snapshot, so a corrupt definition file looked exactly like an empty one, registration went ahead, and the rollback had nothing to restore. The loader now reports an outcome -- absent, unreadable, invalid or ok -- and getCustomModeDefinitions returns { definitions, failures }, each failure naming the path that produced it. An absent file is an empty definition list with no failure, which is a legitimate thing to register against; unreadable and invalid are failures, and createTask refuses the batch before any write when there is one. The merged read behind getCustomModes still receives [] from every failure case, so its behaviour and its toasts are unchanged, and parsedAtAll honours the .roomodes JSON fallback parseYamlSafely relies on, so a .roomodes that is valid JSON but not valid YAML stays readable instead of becoming a new refusal. What a refused registration does to the task, because this is behavioural in a ClineProvider write path: createTask rejects before either definition file is touched. Nothing is registered, nothing is removed, setValues does not run, and no task is constructed -- it does not carry on with the definitions it did manage to read. The assertions that pin that are expect(manager.updateCustomMode).not.toHaveBeenCalled() and expect(setValuesSpy).not.toHaveBeenCalled() against the same call as the rejects. The second new case pins the other side: an empty snapshot with no failure (an absent file) still registers, so a missing file does not become a refusal. Measured in one run; the numstat line below is from git show of this commit in the same run. Controls keep every case and take production files from 41bd742: both production files at 41bd742, manager suite Test Files 1 failed (1) Tests 3 failed | 50 passed (53) (exit 1) both production files at 41bd742, provider suite Test Files 1 failed (1) Tests 5 failed | 380 passed (385) (exit 1) provider file at 41bd742 only, provider suite Test Files 1 failed (1) Tests 5 failed | 380 passed (385) (exit 1) manager file at 41bd742 only, manager suite Test Files 1 failed (1) Tests 3 failed | 50 passed (53) (exit 1) This commit's shapes: manager suite Test Files 1 passed (1) Tests 53 passed (53) (exit 0) provider suite Test Files 1 passed (1) Tests 385 passed (385) (exit 0) whole core/config Test Files 10 passed (10) Tests 324 passed (324) (exit 0) whole core/webview Test Files 34 passed (34) Tests 970 passed (970) (exit 0) tsc --noEmit -p . exit 0, eslint --max-warnings=0 --no-warn-ignored exit 0, prettier --check 0,0,0,0 on the committed sources and 0 on the committed suppressions file; the same invocation reports 0,0,0,0 for the four HEAD copies. The pre-commit and commit-msg hooks executed with the content commit (lint-staged ran over the four staged sources); the message-only amend that follows had nothing staged for lint-staged. Diff 116/40 in CustomModesManager.ts, 55/0 in CustomModesManager.spec.ts, 16/3 in ClineProvider.ts, 70/3 in ClineProvider.spec.ts, 2/2 in eslint-suppressions.json -- 307 changed lines, 175 of them in executable production code. Three existing cases (ClineProvider.spec.ts:6966, 7006, 7042) were re-pointed from the array-returning reader to the outcome-returning reader; their assertions are untouched, and the provider-only control above shows they go red without the provider change rather than passing quietly. Two no-explicit-any counts went 5 -> 4, for core/config/CustomModesManager.ts and core/config/__tests__/ContextProxy.spec.ts. CustomModesManager.ts drops the dead alreadyHandled branch (parseYamlSafely never throws). The ContextProxy.spec.ts entry was already stale at 677e5e3 -- --prune-suppressions against that commit writes 4 for it -- and this commit carries the correction because eslint exits 2 while an old count stands. Both edits were made by hand because --prune-suppressions leaves the same per-file numbers but rewrites all 1441 lines of eslint-suppressions.json. After the edit the file reads CustomModesManager.ts {"@typescript-eslint/no-explicit-any":{"count":4}}, ClineProvider.ts {"@typescript-eslint/no-explicit-any":{"count":7}}, CustomModesManager.spec.ts {"@typescript-eslint/no-explicit-any":{"count":12}}, ClineProvider.spec.ts {"@typescript-eslint/no-explicit-any":{"count":195}}, nothing else moved, and eslint exits 0 against it (it exits 2 while the old counts stand).
1 parent 677e5e3 commit 96c9157

5 files changed

Lines changed: 259 additions & 48 deletions

File tree

‎src/core/config/CustomModesManager.ts‎

Lines changed: 116 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,20 @@ interface ImportResult {
4343
slug?: string
4444
error?: string
4545
}
46+
// A single read of a single mode file. Absent and unreadable both yield no modes, but only one of
47+
// them means there was nothing to lose, so a caller that has to restore definitions cannot merge
48+
// them together. Invalid means the file parsed and the definitions in it are not trustworthy.
49+
type ModeFileRead =
50+
| { status: "ok"; modes: ModeConfig[] }
51+
| { status: "absent" }
52+
| { status: "unreadable"; reason: string }
53+
| { status: "invalid"; reason: string }
54+
55+
/** The definitions a rollback would restore, plus the sources it could not be taken from. */
56+
export type CustomModesSnapshot = {
57+
definitions: ModeConfig[]
58+
failures: Array<{ path: string; reason: "unreadable" | "invalid" }>
59+
}
4660

4761
export class CustomModesManager {
4862
private static readonly cacheTTL = 10_000
@@ -180,47 +194,89 @@ export class CustomModesManager {
180194
}
181195
}
182196

183-
private async loadModesFromFile(filePath: string): Promise<ModeConfig[]> {
197+
/**
198+
* Whether parseYamlSafely actually parsed this content. It swallows a parse failure and returns
199+
* an empty object, which is indistinguishable from a file that parses fine and simply has no
200+
* customModes key. The .roomodes JSON fallback parseYamlSafely relies on is honoured here too, so
201+
* a .roomodes that is valid JSON but not valid YAML is still a readable file.
202+
*/
203+
private parsedAtAll(content: string, filePath: string): boolean {
204+
const cleaned = this.cleanInvisibleCharacters(stripBom(content))
184205
try {
185-
const content = await fs.readFile(filePath, "utf-8")
186-
const settings = this.parseYamlSafely(content, filePath)
206+
yaml.parse(cleaned)
207+
return true
208+
} catch {
209+
if (filePath.endsWith(ROOMODES_FILENAME)) {
210+
try {
211+
JSON.parse(content)
212+
return true
213+
} catch {
214+
// Neither YAML nor the JSON fallback worked: this file has no readable definitions.
215+
}
216+
}
217+
return false
218+
}
219+
}
187220

188-
// Ensure settings has customModes property
189-
if (!settings || typeof settings !== "object" || !settings.customModes) {
190-
return []
221+
/**
222+
* One read of one mode file, with the outcome kept distinguishable. An absent file is an empty
223+
* definition list; a file that cannot be parsed has no definition list at all; a file that parses
224+
* but fails the schema holds definitions nobody should act on.
225+
*/
226+
private async readModeFile(filePath: string): Promise<ModeFileRead> {
227+
let content: string
228+
try {
229+
content = await fs.readFile(filePath, "utf-8")
230+
} catch (error) {
231+
if (error instanceof Error && (error as NodeJS.ErrnoException).code === "ENOENT") {
232+
// Not there is not the same as unreadable: an absent file has no definition to lose.
233+
return { status: "absent" }
191234
}
235+
const errorMsg = error instanceof Error ? error.message : String(error)
236+
console.error(`[CustomModesManager] Failed to load modes from ${filePath}: ${errorMsg}`)
237+
return { status: "unreadable", reason: errorMsg }
238+
}
192239

193-
const result = customModesSettingsSchema.safeParse(settings)
240+
const settings = this.parseYamlSafely(content, filePath)
194241

195-
if (!result.success) {
196-
console.error(`[CustomModesManager] Schema validation failed for ${filePath}:`, result.error)
242+
if (!this.parsedAtAll(content, filePath)) {
243+
return { status: "unreadable", reason: "the file is not valid YAML" }
244+
}
197245

198-
// Show user-friendly error for .roomodes files
199-
if (filePath.endsWith(ROOMODES_FILENAME)) {
200-
const issues = result.error.issues
201-
.map((issue) => `• ${issue.path.join(".")}: ${issue.message}`)
202-
.join("\n")
246+
// Ensure settings has customModes property
247+
if (!settings || typeof settings !== "object" || !settings.customModes) {
248+
return { status: "ok", modes: [] }
249+
}
203250

204-
vscode.window.showErrorMessage(t("common:customModes.errors.schemaValidationError", { issues }))
205-
}
251+
const result = customModesSettingsSchema.safeParse(settings)
206252

207-
return []
208-
}
253+
if (!result.success) {
254+
console.error(`[CustomModesManager] Schema validation failed for ${filePath}:`, result.error)
209255

210-
// Determine source based on file path
211-
const isRoomodes = filePath.endsWith(ROOMODES_FILENAME)
212-
const source = isRoomodes ? ("project" as const) : ("global" as const)
256+
// Show user-friendly error for .roomodes files
257+
if (filePath.endsWith(ROOMODES_FILENAME)) {
258+
const issues = result.error.issues
259+
.map((issue) => `• ${issue.path.join(".")}: ${issue.message}`)
260+
.join("\n")
213261

214-
// Add source to each mode
215-
return result.data.customModes.map((mode) => ({ ...mode, source }))
216-
} catch (error) {
217-
// Only log if the error wasn't already handled in parseYamlSafely
218-
if (!(error as any).alreadyHandled) {
219-
const errorMsg = `Failed to load modes from ${filePath}: ${error instanceof Error ? error.message : String(error)}`
220-
console.error(`[CustomModesManager] ${errorMsg}`)
262+
vscode.window.showErrorMessage(t("common:customModes.errors.schemaValidationError", { issues }))
221263
}
222-
return []
264+
265+
const reason = result.error.issues.map((issue) => `${issue.path.join(".")}: ${issue.message}`).join("; ")
266+
return { status: "invalid", reason }
223267
}
268+
269+
// Determine source based on file path
270+
const isRoomodes = filePath.endsWith(ROOMODES_FILENAME)
271+
const source = isRoomodes ? ("project" as const) : ("global" as const)
272+
273+
// Add source to each mode
274+
return { status: "ok", modes: result.data.customModes.map((mode) => ({ ...mode, source })) }
275+
}
276+
277+
private async loadModesFromFile(filePath: string): Promise<ModeConfig[]> {
278+
const read = await this.readModeFile(filePath)
279+
return read.status === "ok" ? read.modes : []
224280
}
225281

226282
private async mergeCustomModes(projectModes: ModeConfig[], globalModes: ModeConfig[]): Promise<ModeConfig[]> {
@@ -358,22 +414,42 @@ export class CustomModesManager {
358414
* `getCustomModes` applies. A rollback has to restore both: a batch that overwrites a global
359415
* definition through a slug that also exists as a project mode would otherwise leave the global
360416
* copy permanently replaced by the batch's version.
417+
*
418+
* A source that could not be read is reported in failures rather than folded into an empty
419+
* definition list. An absent file genuinely has nothing to restore; an unreadable or invalid one
420+
* has definitions the caller cannot know about, and only the second case should stop a rollback.
361421
*/
362-
public async getCustomModeDefinitions(slugs: readonly string[]): Promise<ModeConfig[]> {
422+
public async getCustomModeDefinitions(slugs: readonly string[]): Promise<CustomModesSnapshot> {
363423
const wanted = new Set(slugs)
364424
const settingsPath = await this.getCustomModesFilePath()
365-
const settingsModes = await this.loadModesFromFile(settingsPath)
366425
const roomodesPath = await this.getWorkspaceRoomodes()
367-
const roomodesModes = roomodesPath ? await this.loadModesFromFile(roomodesPath) : []
368426

369-
return [
370-
...roomodesModes
371-
.filter((mode) => wanted.has(mode.slug))
372-
.map((mode) => ({ ...mode, source: "project" as const })),
373-
...settingsModes
374-
.filter((mode) => wanted.has(mode.slug))
375-
.map((mode) => ({ ...mode, source: "global" as const })),
376-
]
427+
const reads: Array<{ path: string; source: "project" | "global"; read: ModeFileRead }> = []
428+
if (roomodesPath) {
429+
reads.push({
430+
path: roomodesPath,
431+
source: "project",
432+
read: await this.readModeFile(roomodesPath),
433+
})
434+
}
435+
reads.push({ path: settingsPath, source: "global", read: await this.readModeFile(settingsPath) })
436+
437+
const definitions: ModeConfig[] = []
438+
const failures: CustomModesSnapshot["failures"] = []
439+
for (const entry of reads) {
440+
const read = entry.read
441+
if (read.status === "ok") {
442+
for (const mode of read.modes) {
443+
if (wanted.has(mode.slug)) {
444+
definitions.push({ ...mode, source: entry.source })
445+
}
446+
}
447+
} else if (read.status !== "absent") {
448+
failures.push({ path: entry.path, reason: read.status })
449+
}
450+
}
451+
452+
return { definitions, failures }
377453
}
378454
public async getCustomModes(): Promise<ModeConfig[]> {
379455
// Check if we have a valid cached result.

‎src/core/config/__tests__/CustomModesManager.spec.ts‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -828,6 +828,61 @@ describe("CustomModesManager", () => {
828828
})
829829
})
830830

831+
describe("getCustomModeDefinitions (the rollback snapshot)", () => {
832+
const enoent = () => Object.assign(new Error("ENOENT: no such file or directory"), { code: "ENOENT" })
833+
834+
it("reports an absent definition file as an empty snapshot with no failure", async () => {
835+
;(fs.readFile as Mock).mockRejectedValue(enoent())
836+
;(fileExistsAtPath as Mock).mockResolvedValue(false)
837+
838+
const snapshot = await manager.getCustomModeDefinitions(["any-mode"])
839+
840+
// A file that is not there really is a definition list of length zero, so a rollback that
841+
// restores nothing against it is correct rather than a lost snapshot.
842+
expect(snapshot.definitions).toEqual([])
843+
expect(snapshot.failures).toEqual([])
844+
})
845+
846+
it("reports a corrupt definition file as unreadable instead of an empty snapshot", async () => {
847+
;(fs.readFile as Mock).mockImplementation(async (filePath: string) => {
848+
if (filePath === mockSettingsPath) {
849+
return "customModes: [invalid yaml content"
850+
}
851+
throw enoent()
852+
})
853+
;(fileExistsAtPath as Mock).mockResolvedValue(false)
854+
855+
const snapshot = await manager.getCustomModeDefinitions(["any-mode"])
856+
857+
// Same empty definition list as an absent file, but the rollback has to be able to tell them
858+
// apart: registering against this snapshot would overwrite a definition nobody could read.
859+
expect(snapshot.definitions).toEqual([])
860+
expect(snapshot.failures).toEqual([{ path: mockSettingsPath, reason: "unreadable" }])
861+
})
862+
863+
it("reports a schema-invalid definition file as invalid and keeps the source that read cleanly", async () => {
864+
const projectMode = {
865+
slug: "project-only",
866+
name: "Project",
867+
roleDefinition: "r",
868+
groups: ["read"] as const,
869+
}
870+
;(fs.readFile as Mock).mockImplementation(async (filePath: string) => {
871+
if (filePath === mockRoomodes) {
872+
return yaml.stringify({ customModes: [projectMode] })
873+
}
874+
// No roleDefinition: the file parses, so this is not a read failure, it is a definition
875+
// the schema rejects.
876+
return yaml.stringify({ customModes: [{ slug: "broken", name: "Broken", groups: ["read"] }] })
877+
})
878+
;(fileExistsAtPath as Mock).mockResolvedValue(true)
879+
880+
const snapshot = await manager.getCustomModeDefinitions(["project-only", "broken"])
881+
882+
expect(snapshot.failures).toEqual([{ path: mockSettingsPath, reason: "invalid" }])
883+
expect(snapshot.definitions.map((mode) => mode.slug)).toEqual(["project-only"])
884+
})
885+
})
831886
describe("updateModesInFile", () => {
832887
it("handles corrupted YAML content gracefully", async () => {
833888
const corruptedYaml = "customModes: [invalid yaml content"

‎src/core/webview/ClineProvider.ts‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ import { forceFullModelDetailsLoad, hasLoadedFullDetails } from "../../api/provi
135135
import { ContextProxy } from "../config/ContextProxy"
136136
import { withoutInvalidDisplaySettings } from "../config/displaySettings"
137137
import { ProviderSettingsManager } from "../config/ProviderSettingsManager"
138-
import { CustomModesManager } from "../config/CustomModesManager"
138+
import { CustomModesManager, type CustomModesSnapshot } from "../config/CustomModesManager"
139139
import { PendingActionSettlementError, Task } from "../task/Task"
140140

141141
import { webviewMessageHandler } from "./webviewMessageHandler"
@@ -5005,11 +5005,24 @@ export class ClineProvider
50055005
// Snapshot every definition of every slug this batch touches, one per source file. Filtering
50065006
// the merged list would keep only the project copy of a slug that exists in both files, and
50075007
// the rollback would then restore that copy while the global definition stayed overwritten.
5008-
const savedCustomModes = configuration.customModes?.length
5008+
const snapshot: CustomModesSnapshot = configuration.customModes?.length
50095009
? await this.customModesManager.getCustomModeDefinitions(
50105010
configuration.customModes.map((candidate) => candidate.slug),
50115011
)
5012-
: []
5012+
: { definitions: [], failures: [] }
5013+
5014+
// A snapshot taken from a file that could not be read has nothing to roll back to, so the
5015+
// batch would be installed with no way to put the previous definitions back. Refuse before any
5016+
// write: nothing is registered, nothing is removed, setValues does not run, and createTask does
5017+
// not go on to construct the task with modes it cannot restore.
5018+
if (snapshot.failures.length > 0) {
5019+
const unread = snapshot.failures.map((failure) => `${failure.path} (${failure.reason})`).join(", ")
5020+
throw new Error(
5021+
`createTask: custom mode definitions could not be read before registering the batch: ${unread}`,
5022+
)
5023+
}
5024+
5025+
const savedCustomModes = snapshot.definitions
50135026

50145027
// Registration lives inside the try below: a mode whose write fails partway through
50155028
// the batch must trigger the same rollback as a failure after setValues.

‎src/core/webview/__tests__/ClineProvider.spec.ts‎

Lines changed: 70 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6963,7 +6963,9 @@ describe("ClineProvider", () => {
69636963
// The merged read hides the global copy behind the project one; the rollback snapshot must
69646964
// not, or restoring it would write the project definition to the global file as well.
69656965
getCustomModes: vi.fn().mockResolvedValue([projectCopy]),
6966-
getCustomModeDefinitions: vi.fn().mockResolvedValue([projectCopy, globalCopy]),
6966+
getCustomModeDefinitions: vi
6967+
.fn()
6968+
.mockResolvedValue({ definitions: [projectCopy, globalCopy], failures: [] }),
69676969
updateCustomMode: vi.fn().mockResolvedValue(undefined),
69686970
removeCustomModeEntry: vi.fn().mockResolvedValue(true),
69696971
})
@@ -7003,7 +7005,7 @@ describe("ClineProvider", () => {
70037005
Object.assign(manager, {
70047006
getCustomModes: vi.fn().mockResolvedValue([savedMode]),
70057007
// The rollback snapshot reads both source files, so the double answers that reader too.
7006-
getCustomModeDefinitions: vi.fn().mockResolvedValue([savedMode]),
7008+
getCustomModeDefinitions: vi.fn().mockResolvedValue({ definitions: [savedMode], failures: [] }),
70077009
updateCustomMode: vi.fn().mockResolvedValue(undefined),
70087010
removeCustomModeEntry: vi.fn().mockResolvedValue(true),
70097011
})
@@ -7039,7 +7041,7 @@ describe("ClineProvider", () => {
70397041
Object.assign(manager, {
70407042
getCustomModes: vi.fn().mockResolvedValue([savedMode]),
70417043
// The rollback snapshot reads both source files, so the double answers that reader too.
7042-
getCustomModeDefinitions: vi.fn().mockResolvedValue([savedMode]),
7044+
getCustomModeDefinitions: vi.fn().mockResolvedValue({ definitions: [savedMode], failures: [] }),
70437045
updateCustomMode: vi.fn((slug: string, mode: typeof savedMode) => {
70447046
calls.push([slug, mode.name])
70457047
// The batch's second registration is the one that throws.
@@ -7071,6 +7073,71 @@ describe("ClineProvider", () => {
70717073
await provider.dispose()
70727074
})
70737075

7076+
it("refuses the batch when a definition file could not be read, before registering anything", async () => {
7077+
const provider = new ClineProvider(
7078+
mockContext,
7079+
mockOutputChannel,
7080+
"sidebar",
7081+
new ContextProxy(mockContext),
7082+
new WebviewFocusTracker(),
7083+
)
7084+
const batchMode = { slug: "batch-mode", name: "Batch", roleDefinition: "r", groups: ["read" as const] }
7085+
const manager = provider["customModesManager"]
7086+
Object.assign(manager, {
7087+
getCustomModes: vi.fn().mockResolvedValue([]),
7088+
// The definition file exists but does not validate, so there is no trustworthy snapshot to
7089+
// roll back to.
7090+
getCustomModeDefinitions: vi.fn().mockResolvedValue({
7091+
definitions: [],
7092+
failures: [{ path: "/mock/settings/custom_modes.yaml", reason: "invalid" }],
7093+
}),
7094+
updateCustomMode: vi.fn().mockResolvedValue(undefined),
7095+
removeCustomModeEntry: vi.fn().mockResolvedValue(true),
7096+
})
7097+
const setValuesSpy = vi.spyOn(provider, "setValues").mockResolvedValue(undefined)
7098+
7099+
await expect(
7100+
provider.createTask("text", undefined, undefined, {}, { customModes: [batchMode] }),
7101+
).rejects.toThrow("custom mode definitions could not be read")
7102+
7103+
// The batch never reaches storage: no registration, no rules-folder removal, no setValues, and
7104+
// createTask does not go on to construct a task with modes it cannot restore.
7105+
expect(manager.updateCustomMode).not.toHaveBeenCalled()
7106+
expect(manager.removeCustomModeEntry).not.toHaveBeenCalled()
7107+
expect(setValuesSpy).not.toHaveBeenCalled()
7108+
7109+
await provider.dispose()
7110+
})
7111+
7112+
it("registers the batch when the snapshot reports no failure, even with an absent definition file", async () => {
7113+
const provider = new ClineProvider(
7114+
mockContext,
7115+
mockOutputChannel,
7116+
"sidebar",
7117+
new ContextProxy(mockContext),
7118+
new WebviewFocusTracker(),
7119+
)
7120+
const batchMode = { slug: "batch-mode", name: "Batch", roleDefinition: "r", groups: ["read" as const] }
7121+
const manager = provider["customModesManager"]
7122+
Object.assign(manager, {
7123+
getCustomModes: vi.fn().mockResolvedValue([]),
7124+
// An absent file is an empty snapshot with no failure, which is a legitimate thing to
7125+
// register against.
7126+
getCustomModeDefinitions: vi.fn().mockResolvedValue({ definitions: [], failures: [] }),
7127+
updateCustomMode: vi.fn().mockResolvedValue(undefined),
7128+
removeCustomModeEntry: vi.fn().mockResolvedValue(true),
7129+
})
7130+
vi.spyOn(provider, "setValues").mockRejectedValue(new Error("configuration write failed"))
7131+
7132+
await expect(
7133+
provider.createTask("text", undefined, undefined, {}, { customModes: [batchMode] }),
7134+
).rejects.toThrow("configuration write failed")
7135+
7136+
expect(manager.updateCustomMode).toHaveBeenCalledWith("batch-mode", batchMode)
7137+
7138+
await provider.dispose()
7139+
})
7140+
70747141
it("should keep a prototype key carried by a payload out of the rollback write", async () => {
70757142
const provider = new ClineProvider(
70767143
mockContext,

0 commit comments

Comments
 (0)