Skip to content

Commit 30c4f0c

Browse files
committed
fix(webview): validate mode slugs and unify the mode-change paths
Review of every mode-change entry point surfaced three inconsistencies: - handleModeSwitch accepted any slug (the webview "mode" message sends message.text as Mode with no server-side validation), so unvalidated callers could persist invalid modes into task history and the view's durable pin. Validate the slug against built-in + custom modes and no-op (with a log) on unknown slugs, mirroring selectTaskFollowupSuggestion. - Task.submitUserMessage wrote the mode through setValues (raw global ContextProxy write, no history entry, no TaskModeSwitched/ModeChanged, no view pin) while every other switch goes through handleModeSwitch. Route it through handleModeSwitch(mode, this) so an API-initiated switch is recorded like any other. - delegateParentAndOpenChild passed the child's mode as as any; drop the cast now that handleModeSwitch validates. Test updates: - sticky-mode: the "invalid mode" test now asserts the ignore behavior; the module-level getModeBySlug mock's undefined override (leaked past vi.clearAllMocks, which does not clear implementations) is restored in the top-level beforeEach so later tests validate through the default; the slow-init ordering test settles the restore's early durable write before issuing the mid-init switch, matching the production order in which a user's switch is issued after the restore starts. - Task.spec: the submitUserMessage mode test now expects handleModeSwitch("code", task); the mock provider gains the method. check-types clean; 336/336 across the six affected spec files; eslint --prune-suppressions clean (ClineProvider.ts no-explicit-any 12 -> 11).
1 parent f91e19c commit 30c4f0c

5 files changed

Lines changed: 51 additions & 19 deletions

File tree

‎src/core/task/Task.ts‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1543,7 +1543,11 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
15431543

15441544
if (provider) {
15451545
if (mode) {
1546-
await provider.setMode(mode)
1546+
// Route through the shared mode-switch handler so the switch is
1547+
// validated and recorded like any other mode change (task history,
1548+
// TaskModeSwitched, and — when this is the focused task — the view's
1549+
// durable mode pin + ModeChanged broadcast).
1550+
await provider.handleModeSwitch(mode, this)
15471551
this._taskMode = mode
15481552
}
15491553

‎src/core/task/__tests__/Task.spec.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1231,6 +1231,7 @@ describe("Cline", () => {
12311231
getMcpHub: vi.fn().mockReturnValue(undefined),
12321232
getSkillsManager: vi.fn().mockReturnValue(undefined),
12331233
say: vi.fn(),
1234+
handleModeSwitch: vi.fn().mockResolvedValue(undefined),
12341235
postStateToWebview: vi.fn().mockResolvedValue(undefined),
12351236
postStateToWebviewWithoutTaskHistory: vi.fn().mockResolvedValue(undefined),
12361237
postStateToWebviewThrottled: vi.fn().mockResolvedValue(undefined),
@@ -1786,7 +1787,7 @@ describe("Cline", () => {
17861787
mode: "ask",
17871788
mcpEnabled: false,
17881789
} as unknown as ProviderState)
1789-
vi.spyOn(mockProvider, "setMode").mockResolvedValue(undefined)
1790+
vi.spyOn(mockProvider, "handleModeSwitch").mockResolvedValue(undefined)
17901791
const task = new Task({
17911792
provider: mockProvider,
17921793
apiConfiguration: mockApiConfig,
@@ -1807,7 +1808,7 @@ describe("Cline", () => {
18071808

18081809
await task.attemptApiRequest().next()
18091810

1810-
expect(mockProvider.setMode).toHaveBeenCalledWith("code")
1811+
expect(mockProvider.handleModeSwitch).toHaveBeenCalledWith("code", task)
18111812
expect(requireDefined(createMessage.mock.calls[0])[2]?.mode).toBe("code")
18121813
})
18131814

‎src/core/webview/ClineProvider.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1942,8 +1942,17 @@ export class ClineProvider
19421942
* A task that is not this view's focused task only receives the task-scoped effects
19431943
* (history entry + in-memory mode): the view's durable mode, the ModeChanged
19441944
* broadcast, and profile activation keep applying to the focused task's selection.
1945+
* Unknown mode slugs are ignored (logged + no-op) so unvalidated callers (the webview
1946+
* "mode" message sends message.text as Mode) cannot persist invalid modes.
19451947
*/
19461948
public async handleModeSwitch(newMode: Mode, targetTask: Task | null | undefined = this.getCurrentTask()) {
1949+
const targetMode = getModeBySlug(newMode, await this.customModesManager.getCustomModes())
1950+
1951+
if (!targetMode) {
1952+
this.log(`[ClineProvider#handleModeSwitch] ignoring unknown mode "${newMode}"`)
1953+
return
1954+
}
1955+
19471956
return this.enqueueProviderProfileMutation((signal) =>
19481957
this.handleModeSwitchUnlocked(newMode, targetTask, signal),
19491958
)
@@ -4278,7 +4287,8 @@ export class ClineProvider
42784287
// The mode switch must happen before createTask() because the Task constructor
42794288
// initializes its mode from provider.getState() during initializeTaskMode().
42804289
try {
4281-
await this.handleModeSwitch(mode as any)
4290+
// handleModeSwitch validates the slug and no-ops on unknown modes.
4291+
await this.handleModeSwitch(mode)
42824292
} catch (e) {
42834293
this.log(
42844294
`[delegateParentAndOpenChild] handleModeSwitch failed for mode '${mode}': ${

‎src/core/webview/__tests__/ClineProvider.sticky-mode.spec.ts‎

Lines changed: 31 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -215,6 +215,18 @@ describe("ClineProvider - Sticky Mode", () => {
215215
beforeEach(async () => {
216216
vi.clearAllMocks()
217217

218+
// The "mode deletion between sessions" test overrides the module-level
219+
// getModeBySlug mock to return undefined; vi.clearAllMocks() does not clear
220+
// mock implementations, so restore the factory default per-test. handleModeSwitch
221+
// validates slugs through getModeBySlug, so later tests rely on the default.
222+
const { getModeBySlug } = await import("../../../shared/modes")
223+
vi.mocked(getModeBySlug).mockReturnValue({
224+
slug: "code",
225+
name: "Code Mode",
226+
roleDefinition: "You are a code assistant",
227+
groups: ["read", "edit"],
228+
})
229+
218230
if (!TelemetryService.hasInstance()) {
219231
TelemetryService.createInstance([])
220232
}
@@ -954,11 +966,9 @@ describe("ClineProvider - Sticky Mode", () => {
954966
})
955967

956968
describe("Mode switch failure scenarios", () => {
957-
it("should handle invalid mode gracefully", async () => {
969+
it("should ignore invalid modes", async () => {
958970
await provider.resolveWebviewView(mockWebviewView)
959971

960-
// The provider actually does switch to invalid modes
961-
// This test should verify that behavior
962972
const mockTask = {
963973
taskId: "test-task-id",
964974
_taskMode: "code",
@@ -972,22 +982,23 @@ describe("ClineProvider - Sticky Mode", () => {
972982
// Add task to provider stack
973983
await provider.addClineToStack(mockTask as any)
974984

985+
// Register a stable view id so a durable write would be observable
986+
await provider["setViewStateId"]("stable-test-view")
987+
975988
// Clear previous calls
976989
vi.mocked(mockContext.globalState.update).mockClear()
977990

978-
// Register a stable view id so the durable per-view write is persisted
979-
await provider["setViewStateId"]("stable-test-view")
991+
// Simulate an unknown slug: the module mock resolves nothing for it.
992+
// (The outer beforeEach restores the mock's default return per test, so
993+
// this override does not leak into later tests.)
994+
const { getModeBySlug } = await import("../../../shared/modes")
995+
vi.mocked(getModeBySlug).mockReturnValue(undefined)
980996

981-
// Try to switch to invalid mode - it will actually switch
982-
await provider.handleModeSwitch("invalid-mode" as any)
997+
// An unknown mode slug is ignored: no durable write and no in-memory change
998+
await provider.handleModeSwitch("invalid-mode")
983999

984-
// The mode WILL be updated to invalid-mode (this is the actual behavior)
985-
expect(mockContext.globalState.update).toHaveBeenCalledWith(
986-
"viewStates",
987-
expect.objectContaining({
988-
["stable-test-view"]: expect.objectContaining({ mode: "invalid-mode" }),
989-
}),
990-
)
1000+
expect(mockContext.globalState.update).not.toHaveBeenCalled()
1001+
expect((mockTask as any)._taskMode).toBe("code")
9911002
})
9921003

9931004
it("should handle errors during mode switch gracefully", async () => {
@@ -1243,6 +1254,12 @@ describe("ClineProvider - Sticky Mode", () => {
12431254
// Start initialization
12441255
const initPromise = provider.createTaskWithHistoryItem(historyItem)
12451256

1257+
// Let the restore's early durable mode write settle first (its custom-mode
1258+
// resolution completes in microtasks with the mocked fs). In production the
1259+
// user's switch is issued after the restore's early write, and both durable
1260+
// writes then land in that order, so the mid-init switch wins.
1261+
await new Promise((resolve) => setTimeout(resolve, 10))
1262+
12461263
// Try to switch mode during initialization
12471264
await provider.handleModeSwitch("code")
12481265

‎src/eslint-suppressions.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1026,7 +1026,7 @@
10261026
},
10271027
"core/webview/ClineProvider.ts": {
10281028
"@typescript-eslint/no-explicit-any": {
1029-
"count": 12
1029+
"count": 11
10301030
}
10311031
},
10321032
"core/webview/__tests__/ClineProvider.apiHandlerRebuild.spec.ts": {

0 commit comments

Comments
 (0)