Skip to content

Commit e9a44b2

Browse files
committed
fix(webview): address review findings and harden viewStateId mutation coverage
1 parent 98615c2 commit e9a44b2

8 files changed

Lines changed: 161 additions & 38 deletions

File tree

‎apps/vscode-e2e/src/suite/view-state.test.ts‎

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -177,11 +177,18 @@ suite("Roo Code View State", function () {
177177
assert.ok(suggestion, `Expected pending suggestion for task ${taskId}`)
178178
pendingSuggestions.delete(taskId)
179179
answeredSuggestions.add(suggestionKey(taskId, suggestion.answer))
180-
void globalThis.api.selectTaskFollowupSuggestion({ taskId, ...suggestion }).then((delivered) => {
181-
if (!delivered) {
182-
deliveryFailures.push(`${taskId}:${suggestion.answer}`)
183-
}
184-
})
180+
void globalThis.api
181+
.selectTaskFollowupSuggestion({ taskId, ...suggestion })
182+
.then((delivered) => {
183+
if (!delivered) {
184+
deliveryFailures.push(`${taskId}:${suggestion.answer}`)
185+
}
186+
})
187+
.catch((error: unknown) => {
188+
deliveryFailures.push(
189+
`${taskId}:${suggestion.answer}:${error instanceof Error ? error.message : String(error)}`,
190+
)
191+
})
185192
}
186193
}
187194

‎src/core/task/Task.ts‎

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1662,7 +1662,16 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
16621662
// durable mode pin + ModeChanged broadcast). The handler writes this
16631663
// task's mode only after validation and persistence, so an unknown
16641664
// slug leaves the task mode untouched instead of recording a bad one.
1665-
await provider.handleModeSwitch(mode, this)
1665+
// A mode-switch failure (e.g. a task-history write failure) must not
1666+
// swallow the submitted message: log it locally and continue delivery.
1667+
try {
1668+
await provider.handleModeSwitch(mode, this)
1669+
} catch (error) {
1670+
console.error(
1671+
`[Task#submitUserMessage] Mode switch to ${mode} failed (taskId=${this.taskId}):`,
1672+
error,
1673+
)
1674+
}
16661675
}
16671676

16681677
if (providerProfile) {

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

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1825,6 +1825,30 @@ describe("Cline", () => {
18251825
expect(requireDefined(createMessage.mock.calls[0])[2]?.mode).toBe("code")
18261826
})
18271827

1828+
it("still delivers the user message when the mode switch fails", async () => {
1829+
const task = new Task({
1830+
provider: mockProvider,
1831+
apiConfiguration: mockApiConfig,
1832+
task: "initial task",
1833+
startTask: false,
1834+
})
1835+
const switchError = new Error("task history write failed")
1836+
vi.spyOn(mockProvider, "handleModeSwitch").mockRejectedValue(switchError)
1837+
const handleResponseSpy = vi.spyOn(task, "handleWebviewAskResponse").mockImplementation(() => {})
1838+
const consoleErrorSpy = vi.spyOn(console, "error").mockImplementation(() => {})
1839+
1840+
await task.submitUserMessage("still delivered", undefined, "code")
1841+
1842+
// The mode-switch rejection is caught and logged locally...
1843+
expect(consoleErrorSpy).toHaveBeenCalledWith(
1844+
`[Task#submitUserMessage] Mode switch to code failed (taskId=${task.taskId}):`,
1845+
switchError,
1846+
)
1847+
// ...and the pending ask is still answered, so the submitted text is not lost.
1848+
expect(handleResponseSpy).toHaveBeenCalledWith("messageResponse", "still delivered", [])
1849+
consoleErrorSpy.mockRestore()
1850+
})
1851+
18281852
it("stores a provider profile selected through submitUserMessage", async () => {
18291853
const selectedConfiguration: ProviderSettings = {
18301854
...mockApiConfig,

‎src/core/tools/SwitchModeTool.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import delay from "delay"
22

33
import { Task } from "../task/Task"
44
import { formatResponse } from "../prompts/responses"
5-
import { defaultModeSlug, getModeBySlug } from "../../shared/modes"
5+
import { getModeBySlug } from "../../shared/modes"
66
import { BaseTool, ToolCallbacks } from "./BaseTool"
77
import type { ToolUse } from "../../shared/tools"
88

@@ -39,7 +39,9 @@ export class SwitchModeTool extends BaseTool<"switch_mode"> {
3939
}
4040

4141
// Check if already in requested mode
42-
const currentMode = (await task.providerRef.deref()?.getState())?.mode ?? defaultModeSlug
42+
// the task's own mode (awaits taskModeReady and applies the default slug) instead of the provider
43+
// state, which may be stale or focused on another task.
44+
const currentMode = await task.getTaskMode()
4345

4446
if (currentMode === mode_slug) {
4547
task.recordToolError("switch_mode")

‎src/core/tools/__tests__/switchModeTool.spec.ts‎

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -33,19 +33,22 @@ describe("SwitchModeTool", () => {
3333
let mockCallbacks: ToolCallbacks
3434
let mockHandleModeSwitch: ReturnType<typeof vi.fn>
3535
let mockGetState: ReturnType<typeof vi.fn>
36+
let mockGetTaskMode: ReturnType<typeof vi.fn>
3637

3738
beforeEach(() => {
3839
vi.clearAllMocks()
3940

4041
mockHandleModeSwitch = vi.fn().mockResolvedValue(undefined)
4142
mockGetState = vi.fn().mockResolvedValue({ mode: "code", customModes: [] })
43+
mockGetTaskMode = vi.fn().mockResolvedValue("code")
4244

4345
mockTask = {
4446
consecutiveMistakeCount: 0,
4547
recordToolError: vi.fn(),
4648
didToolFailInCurrentTurn: false,
4749
sayAndCreateMissingParamError: vi.fn().mockResolvedValue("Missing parameter error"),
4850
ask: vi.fn().mockResolvedValue({}),
51+
getTaskMode: mockGetTaskMode,
4952
providerRef: {
5053
deref: vi.fn().mockReturnValue({
5154
getState: mockGetState,
@@ -325,31 +328,36 @@ describe("SwitchModeTool", () => {
325328
expect(mockCallbacks.askApproval).toHaveBeenCalledWith("tool", expectedMessage)
326329
})
327330

328-
// ===== getState with custom modes =====
331+
// ===== current mode source =====
329332

330-
it("should read current mode from providerRef state", async () => {
331-
// Set current mode to "architect"
332-
mockGetState.mockResolvedValue({ mode: "architect", customModes: [] })
333+
it("should read the current mode from task.getTaskMode, not provider state", async () => {
334+
// The provider state still reports the stale "code" mode while the task is actually in
335+
// "architect". The switch report must use the task's own mode.
336+
mockGetState.mockResolvedValue({ mode: "code", customModes: [] })
337+
mockGetTaskMode.mockResolvedValue("architect")
333338

334339
const block = createBlock({ mode_slug: "code", reason: "switching back" })
335340

336341
await switchModeTool.handle(mockTask, block, mockCallbacks)
337342

343+
expect(mockGetTaskMode).toHaveBeenCalledTimes(1)
338344
expect(mockHandleModeSwitch).toHaveBeenCalledWith("code", mockTask)
339345
expect(mockCallbacks.pushToolResult).toHaveBeenCalledWith(
340346
"Successfully switched from Architect mode to Code mode because: switching back.",
341347
)
342348
})
343349

344-
it("should use defaultModeSlug when getState returns no mode", async () => {
345-
mockGetState.mockResolvedValue({})
350+
it("should use the default slug reported by task.getTaskMode when no mode is active", async () => {
351+
// task.getTaskMode applies the default slug when the task has no explicit mode, so the
352+
// tool reports switching from the default (Code) mode.
353+
mockGetState.mockResolvedValue({ customModes: [] })
354+
mockGetTaskMode.mockResolvedValue("code")
346355

347356
const block = createBlock({ mode_slug: "ask", reason: "test" })
348357

349358
await switchModeTool.handle(mockTask, block, mockCallbacks)
350359

351-
// defaultModeSlug is "code" (from mock)
352-
// Should report switching from Code mode
360+
expect(mockGetTaskMode).toHaveBeenCalledTimes(1)
353361
expect(mockCallbacks.pushToolResult).toHaveBeenCalledWith(
354362
"Successfully switched from Code mode to Ask mode because: test.",
355363
)

‎src/core/webview/ClineProvider.ts‎

Lines changed: 39 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -712,13 +712,13 @@ export class ClineProvider
712712
* The identifier is sanitized so it remains a safe object key in the shared viewStates map.
713713
*/
714714
public async setViewStateId(viewStateId: string | undefined): Promise<void> {
715-
const normalizedViewStateId = viewStateId?.trim()
715+
const normalizedViewStateId = viewStateId?.trim().replace(/[^A-Za-z0-9_-]/g, "_")
716716

717717
if (!normalizedViewStateId || normalizedViewStateId === this.viewStateId) {
718718
return
719719
}
720720

721-
this.viewStateId = normalizedViewStateId.replace(/[^A-Za-z0-9_-]/g, "_")
721+
this.viewStateId = normalizedViewStateId
722722

723723
// Re-key any durable entry written under the temporary pre-launch id before
724724
// loading, so the load sees the view's own pre-registration selections.
@@ -2254,6 +2254,29 @@ export class ClineProvider
22542254
throw new Error("You cannot delete the last profile")
22552255
}
22562256

2257+
// Remove the profile from the settings store (context.secrets) so it cannot be
2258+
// resurrected by a later listApiConfigMeta sync.
2259+
await this.providerSettingsManager.deleteConfig(profileToDelete.name)
2260+
2261+
// Re-point any persisted view pin that referenced the deleted profile so views
2262+
// do not rehydrate a missing profile name after a reload.
2263+
await this.repointPersistedViewStates(profileToDelete.name, profileToActivate)
2264+
2265+
const viewPinsDeletedProfile =
2266+
this.viewLocalState.currentApiConfigName === undefined ||
2267+
this.viewLocalState.currentApiConfigName === profileToDelete.name
2268+
2269+
if (viewPinsDeletedProfile) {
2270+
// Apply the replacement through the activation path so this view's
2271+
// viewLocalState.apiConfiguration and the current task's api handler are
2272+
// refreshed; a name-only update would leave the deleted profile's settings
2273+
// behind in both.
2274+
await this.activateProviderProfile({ name: profileToActivate })
2275+
return
2276+
}
2277+
2278+
// This view pins an unrelated profile, which must survive the deletion: sync the
2279+
// shared profile list and post the updated state only.
22572280
const entries = this.getProviderProfileEntries().filter(({ name }) => name !== profileToDelete.name)
22582281

22592282
await this.contextProxy.setValues({
@@ -2262,22 +2285,6 @@ export class ClineProvider
22622285
listApiConfigMeta: entries,
22632286
})
22642287

2265-
// Sync this view's in-memory buffer only when it was pointing at the deleted
2266-
// profile (or had no pin of its own): an unrelated pin must survive the deletion.
2267-
if (
2268-
this.viewLocalState.currentApiConfigName === undefined ||
2269-
this.viewLocalState.currentApiConfigName === profileToDelete.name
2270-
) {
2271-
this._updateViewLocalStateFromMutation({
2272-
currentApiConfigName: profileToActivate,
2273-
listApiConfigMeta: entries,
2274-
})
2275-
}
2276-
2277-
// Re-point any persisted view pin that referenced the deleted profile so views
2278-
// do not rehydrate a missing profile name after a reload.
2279-
await this.repointPersistedViewStates(profileToDelete.name, profileToActivate)
2280-
22812288
await this.postStateToWebview()
22822289
}
22832290

@@ -3543,8 +3550,20 @@ export class ClineProvider
35433550
}
35443551

35453552
public async setValues(values: RooCodeSettings) {
3546-
await this.contextProxy.setValues(values)
3547-
await this._saveViewLocalStateFromMutation(values)
3553+
const sanitizedValues = { ...values }
3554+
3555+
if (
3556+
typeof sanitizedValues.mode === "string" &&
3557+
!getModeBySlug(sanitizedValues.mode, await this.customModesManager.getCustomModes())
3558+
) {
3559+
// An unknown mode (e.g. from an API payload) must not be persisted: a new Task
3560+
// would read it from getState() and persist it into task history.
3561+
this.log(`[ClineProvider#setValues] Ignoring unknown mode "${sanitizedValues.mode}"`)
3562+
delete sanitizedValues.mode
3563+
}
3564+
3565+
await this.contextProxy.setValues(sanitizedValues)
3566+
await this._saveViewLocalStateFromMutation(sanitizedValues)
35483567
}
35493568

35503569
/**

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

Lines changed: 35 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -521,6 +521,7 @@ vi.mock("../../config/ProviderSettingsManager", () => ({
521521
setModeConfig: vi.fn().mockResolvedValue(undefined),
522522
getModeConfigId: vi.fn().mockResolvedValue(undefined),
523523
resetAllConfigs: vi.fn().mockResolvedValue(undefined),
524+
deleteConfig: vi.fn().mockResolvedValue(undefined),
524525
}
525526
}),
526527
}))
@@ -1160,6 +1161,22 @@ describe("ClineProvider - Parallel Mode Support", () => {
11601161
await provider.dispose()
11611162
})
11621163

1164+
it("should drop an unknown mode from setValues while keeping valid modes", async () => {
1165+
const provider = new ClineProvider(mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext))
1166+
1167+
await provider.setValues({ mode: "not-a-real-mode" })
1168+
1169+
expect(provider.contextProxy.getValue("mode")).toBe("code")
1170+
expect(provider["viewLocalState"].mode).toBeUndefined()
1171+
1172+
await provider.setValues({ mode: "architect" })
1173+
1174+
expect(provider.contextProxy.getValue("mode")).toBe("architect")
1175+
expect(provider["viewLocalState"].mode).toBe("architect")
1176+
1177+
await provider.dispose()
1178+
})
1179+
11631180
it("should sanitize raw viewStateId before using it as persisted viewStates key", async () => {
11641181
const provider = new ClineProvider(mockContext, mockOutputChannel, "sidebar", new ContextProxy(mockContext))
11651182

@@ -1233,7 +1250,7 @@ describe("ClineProvider - Parallel Mode Support", () => {
12331250
// Simulate a concurrent writer (another view's provider) updating the shared
12341251
// map directly in storage, bypassing this proxy's cache.
12351252
const stored = (await mockContext.globalState.get<Record<string, unknown>>("viewStates")) ?? {}
1236-
mockContext.globalState.update("viewStates", {
1253+
await mockContext.globalState.update("viewStates", {
12371254
...stored,
12381255
"view-b": { mode: "debug", updatedAt: 1 },
12391256
})
@@ -1413,6 +1430,15 @@ describe("ClineProvider - Parallel Mode Support", () => {
14131430
currentApiConfigName: "deleted-profile",
14141431
apiConfiguration: { apiProvider: providerIdentifiers.anthropic },
14151432
}
1433+
vi.spyOn(provider.providerSettingsManager, "listConfig").mockResolvedValue([
1434+
{ id: "replacement-id", name: "replacement-profile", apiProvider: providerIdentifiers.openrouter },
1435+
])
1436+
vi.spyOn(provider.providerSettingsManager, "activateProfile").mockResolvedValue({
1437+
name: "replacement-profile",
1438+
id: "replacement-id",
1439+
apiProvider: providerIdentifiers.openrouter,
1440+
openRouterApiKey: "replacement-key",
1441+
} as unknown as Awaited<ReturnType<typeof provider.providerSettingsManager.getProfile>>)
14161442

14171443
await provider.deleteProviderProfile({
14181444
id: "deleted-id",
@@ -1425,6 +1451,13 @@ describe("ClineProvider - Parallel Mode Support", () => {
14251451
expect(state.listApiConfigMeta).toEqual([
14261452
{ id: "replacement-id", name: "replacement-profile", apiProvider: providerIdentifiers.openrouter },
14271453
])
1454+
// The view-local buffer must hold the replacement profile's settings rather
1455+
// than the deleted profile's.
1456+
expect(provider["viewLocalState"].apiConfiguration).toEqual({
1457+
apiProvider: providerIdentifiers.openrouter,
1458+
openRouterApiKey: "replacement-key",
1459+
})
1460+
expect(vi.mocked(provider.providerSettingsManager.deleteConfig)).toHaveBeenCalledWith("deleted-profile")
14281461

14291462
await provider.dispose()
14301463
})
@@ -1437,7 +1470,7 @@ describe("ClineProvider - Parallel Mode Support", () => {
14371470
{ id: "doomed-id", name: "doomed-profile", apiProvider: providerIdentifiers.openrouter },
14381471
])
14391472
// Two views have durable pins; one pins the profile about to be deleted.
1440-
mockContext.globalState.update("viewStates", {
1473+
await mockContext.globalState.update("viewStates", {
14411474
"view-keeps": { mode: "code", currentApiConfigName: "keeper-profile", updatedAt: 1 },
14421475
"view-deleted": { mode: "architect", currentApiConfigName: "doomed-profile", updatedAt: 2 },
14431476
})

‎webview-ui/src/utils/__tests__/vscode.spec.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,27 @@ describe("VSCodeAPIWrapper", () => {
143143
expect(JSON.parse(storage.getItem("vscodeState")!)).toMatchObject({ viewStateId: "loyw3v28-zk00000ytu" })
144144
})
145145

146+
it("falls back to a timestamp-random id when the crypto object lacks randomUUID", () => {
147+
Object.defineProperty(globalThis, "crypto", {
148+
configurable: true,
149+
value: { "": 1 },
150+
})
151+
vi.spyOn(Date, "now").mockReturnValue(1700000000000)
152+
vi.spyOn(Math, "random").mockReturnValue(0.987654321)
153+
const storage = createMockStorage()
154+
Object.defineProperty(globalThis, "localStorage", {
155+
configurable: true,
156+
value: storage,
157+
})
158+
const wrapper = new VSCodeAPIWrapper()
159+
160+
// A truthy crypto global without a randomUUID member must still take the
161+
// deterministic fallback: 1700000000000.toString(36) === "loyw3v28" and
162+
// (0.987654321).toString(36) === "0.zk00000ytu", so the id drops the "0." prefix.
163+
expect(wrapper.getViewStateId()).toBe("loyw3v28-zk00000ytu")
164+
expect(JSON.parse(storage.getItem("vscodeState")!)).toMatchObject({ viewStateId: "loyw3v28-zk00000ytu" })
165+
})
166+
146167
it("creates a new viewStateId when the stored state parses to JSON null", () => {
147168
Object.defineProperty(globalThis, "crypto", {
148169
configurable: true,

0 commit comments

Comments
 (0)