Skip to content

Commit f528dcc

Browse files
fix: roll back task-side mode writes when the view mode pin write fails,
rebuild re-pinned siblings' tasks, keep headless task creation working Review-round fixes on the shared code this unit carries: (1) when the view's durable mode pin write rejected inside handleModeSwitchUnlocked, the task-history write and the in-memory task mode had already landed and the caller delivered the submitted message with the new task mode against the view's unchanged mode and mode-linked API configuration - the failure now restores the pre-switch task mode and history entry before rethrowing. (2) rePinViewLocalStateForDeletedProfile updated each sibling's buffer but not its running task: the posted state prefers the task's own apiConfiguration, so a conversation in a view pinned to the deleted profile kept sending the deleted profile's settings - the re-pin now rebuilds the sibling's API handler with the replacement's settings and re-points the task's sticky profile name. (3) The view-state readiness bound rejected every startNewTask whose webview never launched, breaking headless API callers - the bound now only rejects when the webview has launched, and the IPC StartNewTask listener catches rejections since IpcServer does not await async listeners. (4) The mode-ordering test only checked the end state - it now asserts the switch has not been called before the pending initialization state is released. Proofs: ClineProvider.spec 294/294, sticky-mode 34/34 (new pin-write- failure rollback test), parallel-mode 40/40 (sibling re-pin test asserts the task handler rebuild and sticky-name re-point), Task.spec 187/187, api-task-control 25/25 (headless-fallback and launched-stuck tests); negative controls: dropping the rollback call reddens exactly the rollback test, dropping the rebuild reddens exactly the re-pin test, dropping the waitForModeInitialization await reddens exactly the ordering test's in-flight assertion, making the readiness timeout unconditional reddens exactly the headless-fallback test, restores byte-exact (hash match); eslint --max-warnings=0 clean; prettier clean.
1 parent 726e230 commit f528dcc

6 files changed

Lines changed: 220 additions & 21 deletions

File tree

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

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3839,6 +3839,14 @@ describe("Cline", () => {
38393839

38403840
const submitted = task.submitUserMessage("select while initializing", undefined, "architect")
38413841

3842+
// Flush microtasks: the switch must still wait for the pending
3843+
// initialization. Without the await, the mocked switch would already have
3844+
// run here and the end-state assertion could not tell the orders apart.
3845+
for (let i = 0; i < 5; i++) {
3846+
await Promise.resolve()
3847+
}
3848+
expect(mockProvider.handleModeSwitch).not.toHaveBeenCalled()
3849+
38423850
// Resolve the pending provider state only after the submission has started,
38433851
// carrying the provider's pre-switch mode.
38443852
releaseState(Object.assign({} as ProviderState, { mode: "ask" }))

‎src/core/webview/ClineProvider.ts‎

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2268,6 +2268,10 @@ export class ClineProvider
22682268
): Promise<void> {
22692269
const task = targetTask
22702270

2271+
// Captured for the pin-write rollback below: the mode this task held before
2272+
// the switch (bracket access: _taskMode is private to Task).
2273+
const previousTaskMode = task ? task["_taskMode"] : undefined
2274+
let rollbackTaskWrites: (() => Promise<void>) | undefined
22712275
// A cancelled or timed-out switch must not be partially applied: bail out
22722276
// before the task history / _taskMode writes as well as the durable mode
22732277
// write below. Aborts that land while the history write is in flight are
@@ -2313,6 +2317,21 @@ export class ClineProvider
23132317

23142318
// Only update the task's mode after successful persistence.
23152319
;(task as any)._taskMode = newMode
2320+
2321+
// If the view's durable mode pin below fails after these task-side writes
2322+
// landed, restore them: the caller delivers the message on the caught
2323+
// error, and the new task mode must not run against the view's unchanged
2324+
// mode and mode-linked API configuration.
2325+
const historyItemBefore = taskHistoryItem
2326+
rollbackTaskWrites = async () => {
2327+
task["_taskMode"] = previousTaskMode
2328+
if (historyItemBefore) {
2329+
// Restore only the field this switch changed: re-read the item so
2330+
// fields the running task persisted during the write survive.
2331+
const latest = this.getTaskHistoryItem(task.taskId) ?? historyItemBefore
2332+
await this.updateTaskHistory({ ...latest, mode: historyItemBefore.mode })
2333+
}
2334+
}
23162335
} catch (error) {
23172336
// If persistence fails, log the error but don't update the in-memory state.
23182337
this.log(
@@ -2339,7 +2358,26 @@ export class ClineProvider
23392358
if (viewScopedSwitch) {
23402359
// Pin the view's durable per-view mode first: the pin is this view's own
23412360
// selection and must not be undone if the shared write later fails.
2342-
await this.saveViewState("mode", newMode)
2361+
// If the pin write itself fails, the task-side writes above are already
2362+
// applied: roll them back before rethrowing so the caller cannot deliver
2363+
// the message with the new task mode while the view's mode and mode-linked
2364+
// API configuration stayed old.
2365+
try {
2366+
await this.saveViewState("mode", newMode)
2367+
} catch (error) {
2368+
if (rollbackTaskWrites) {
2369+
try {
2370+
await rollbackTaskWrites()
2371+
} catch (rollbackError) {
2372+
this.log(
2373+
`[handleModeSwitch] Failed to roll back task mode writes after the view mode pin write failed: ${
2374+
rollbackError instanceof Error ? rollbackError.message : String(rollbackError)
2375+
}`,
2376+
)
2377+
}
2378+
}
2379+
throw error
2380+
}
23432381

23442382
// setValue (not the deprecated updateGlobalState) so the in-memory viewLocalState
23452383
// buffer stays in sync with the durable global write: getValues() merges
@@ -2961,6 +2999,16 @@ export class ClineProvider
29612999

29623000
// Direct private access: compile-time safe across sibling instances.
29633001
await instance._saveViewLocalStateFromMutation(values)
3002+
// The active task of a view pinned to the deleted profile holds its own API
3003+
// handler and sticky profile name built from the deleted profile: rebuild
3004+
// the handler with the replacement's settings and re-point the sticky name,
3005+
// or the running conversation keeps sending the deleted profile's
3006+
// configuration even though the view's buffer was re-pointed (the posted
3007+
// state prefers the task's own apiConfiguration).
3008+
if (replacementSettings) {
3009+
instance.updateTaskApiHandlerIfNeeded(replacementSettings, { forceRebuild: true })
3010+
}
3011+
await instance.persistStickyProviderProfileToCurrentTask(replacementName)
29643012
await instance.postStateToWebview()
29653013
}),
29663014
)

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

Lines changed: 25 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1380,7 +1380,19 @@ describe("ClineProvider - Parallel Mode Support", () => {
13801380
vi.spyOn(providerA.providerSettingsManager, "listConfig").mockResolvedValue([
13811381
{ id: "replacement-id", name: "replacement-profile", apiProvider: providerIdentifiers.openrouter },
13821382
])
1383-
// The pre-return re-pin resolves the replacement's settings through the manager.
1383+
// B has an active task built from the doomed profile's settings: the posted
1384+
// state prefers the task's own apiConfiguration, so the re-pin must rebuild
1385+
// the task's handler and re-point its sticky profile name too.
1386+
const siblingTask = {
1387+
apiConfiguration: { apiProvider: providerIdentifiers.anthropic, apiKey: "doomed-key" },
1388+
updateApiConfiguration: vi.fn(),
1389+
setTaskApiConfigName: vi.fn(),
1390+
}
1391+
vi.spyOn(providerB, "getCurrentTask").mockReturnValue(
1392+
siblingTask as unknown as ReturnType<typeof providerB.getCurrentTask>,
1393+
)
1394+
1395+
// The pre-return re-pin // The pre-return re-pin resolves the replacement's settings through the manager.
13841396
vi.spyOn(providerA.providerSettingsManager, "getProfile").mockImplementation(
13851397
async (_args: { name?: string; id?: string }) =>
13861398
({
@@ -1405,6 +1417,18 @@ describe("ClineProvider - Parallel Mode Support", () => {
14051417
openRouterBaseUrl: "repl-url",
14061418
})
14071419
expect((await providerB.getState()).currentApiConfigName).toBe("replacement-profile")
1420+
// The active task's handler is rebuilt with the replacement's settings and
1421+
// its sticky profile name re-points to the replacement: without this the
1422+
// running conversation keeps sending the deleted profile's configuration.
1423+
// objectContaining: the replacement's settings carry the profile id alongside
1424+
// the provider fields (the name is stripped, the id is not).
1425+
expect(siblingTask.updateApiConfiguration).toHaveBeenCalledWith(
1426+
expect.objectContaining({
1427+
apiProvider: providerIdentifiers.openrouter,
1428+
openRouterBaseUrl: "repl-url",
1429+
}),
1430+
)
1431+
expect(siblingTask.setTaskApiConfigName).toHaveBeenCalledWith("replacement-profile")
14081432

14091433
await providerA.dispose()
14101434
await providerB.dispose()

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

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -627,6 +627,55 @@ describe("ClineProvider - Sticky Mode", () => {
627627
expect(mockContext.globalState.update).not.toHaveBeenCalledWith("mode", "architect")
628628
})
629629

630+
it("rolls back the task mode and history when the view mode pin write fails", async () => {
631+
// Same typed double as the abort rollback test: the private members stay
632+
// out of the Object.assign intersection type.
633+
const mockTask = Object.assign(
634+
{} as Task,
635+
{
636+
taskId: "test-task-id",
637+
taskMode: "code",
638+
_taskMode: "code",
639+
emit: vi.fn(),
640+
saveClineMessages: vi.fn(),
641+
clineMessages: [],
642+
apiConversationHistory: [],
643+
updateApiConfiguration: vi.fn(),
644+
} as Partial<Task>,
645+
)
646+
647+
const historyItem: HistoryItem = {
648+
id: "test-task-id",
649+
ts: Date.now(),
650+
task: "Test task",
651+
mode: "code",
652+
number: 1,
653+
tokensIn: 0,
654+
tokensOut: 0,
655+
cacheWrites: 0,
656+
cacheReads: 0,
657+
totalCost: 0,
658+
}
659+
vi.spyOn(provider.taskHistoryStore, "get").mockReturnValue(historyItem)
660+
661+
// The task-history write lands; the view's durable mode pin write then
662+
// rejects. The caller (submitUserMessage) logs the failure and delivers the
663+
// message, so the task-side writes must not stand.
664+
const updateTaskHistorySpy = vi.spyOn(provider, "updateTaskHistory").mockResolvedValue([])
665+
vi.spyOn(provider, "saveViewState").mockRejectedValueOnce(new Error("pin write failed"))
666+
await provider.addClineToStack(mockTask)
667+
668+
await expect(provider["handleModeSwitchUnlocked"]("architect", mockTask)).rejects.toThrow(
669+
"pin write failed",
670+
)
671+
672+
// No partial application: the task keeps its previous mode and the history
673+
// entry is restored, so the delivered message cannot run the new task mode
674+
// against the view's unchanged mode and mode-linked API configuration.
675+
expect(mockTask["_taskMode"]).toBe("code")
676+
expect(updateTaskHistorySpy).toHaveBeenLastCalledWith(historyItem)
677+
})
678+
630679
it("keeps the cancellation result when the abort rollback write itself fails", async () => {
631680
const mockTask = Object.assign(
632681
{} as Task,

‎src/extension/__tests__/api-task-control.spec.ts‎

Lines changed: 54 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -198,21 +198,68 @@ describe("API task controls", () => {
198198
})
199199

200200
it("cancels the readiness timeout when the view becomes ready within the bound", async () => {
201-
const clearSpy = vi.spyOn(globalThis, "clearTimeout")
201+
// Fake timers pin the exact timer surface: a global clearTimeout spy would
202+
// also fire for the flush sleep and library internals, so it could not
203+
// prove the readiness bound's own timer was cancelled.
204+
vi.useFakeTimers()
202205
let resolveReady!: () => void
203206
sidebarProvider.viewStateReadiness = new Promise<void>((resolve) => {
204207
resolveReady = resolve
205208
})
206209

207210
const started = api.startNewTask({ configuration, text: "ready task" })
208-
await new Promise((resolve) => setTimeout(resolve, 50))
211+
await vi.advanceTimersByTimeAsync(50)
209212
resolveReady()
210213

211-
await expect(started).resolves.toBe("sidebar-task")
212-
// The bound's timer must be cancelled once readiness wins: a live timer would
213-
// later reject an unawaited promise and surface as an unhandled rejection.
214-
expect(clearSpy).toHaveBeenCalled()
215-
clearSpy.mockRestore()
214+
try {
215+
await expect(started).resolves.toBe("sidebar-task")
216+
// The readiness bound's timer must be gone once readiness wins: a live
217+
// timer would later reject an unawaited promise and surface as an
218+
// unhandled rejection.
219+
expect(vi.getTimerCount()).toBe(0)
220+
// No late rejection can fire after the bound either.
221+
await vi.advanceTimersByTimeAsync(3000)
222+
} finally {
223+
vi.useRealTimers()
224+
}
225+
})
226+
227+
it("continues with the shared-state fallback when the webview never launches", async () => {
228+
// Headless API callers create tasks without ever launching a webview: the
229+
// readiness bound expiring must not reject them - the pre-existing
230+
// shared-state fallback still applies.
231+
vi.useFakeTimers()
232+
sidebarProvider.viewLaunched = false
233+
sidebarProvider.viewStateReadiness = new Promise<void>(() => {})
234+
235+
const started = api.startNewTask({ configuration, text: "headless task" })
236+
await vi.advanceTimersByTimeAsync(3000)
237+
238+
try {
239+
await expect(started).resolves.toBe("sidebar-task")
240+
} finally {
241+
vi.useRealTimers()
242+
}
243+
})
244+
245+
it("still rejects when the webview launched but the readiness bound expires", async () => {
246+
// A launched view whose readiness never settles is a real failure: the
247+
// task must not consume shared defaults behind a live view.
248+
vi.useFakeTimers()
249+
sidebarProvider.viewStateReadiness = new Promise<void>(() => {})
250+
251+
const started = api.startNewTask({ configuration, text: "stuck view task" })
252+
// Attach the rejection handler before advancing: with fake timers the
253+
// bound fires during the advance, and a handler attached afterwards would
254+
// see the rejection briefly unhandled.
255+
const settled = expect(started).rejects.toThrow("Timed out waiting for the view state to become ready")
256+
await vi.advanceTimersByTimeAsync(3000)
257+
258+
try {
259+
await settled
260+
} finally {
261+
vi.useRealTimers()
262+
}
216263
})
217264

218265
it("fails task creation when the provider is disposed while the readiness wait is pending", async () => {

‎src/extension/api.ts‎

Lines changed: 35 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,15 @@ export class API extends EventEmitter<RooCodeEvents> implements RooCodeAPI, RooC
107107
this.log(
108108
`[API] StartNewTask -> ${command.data.text}, ${JSON.stringify(command.data.configuration)}`,
109109
)
110-
await this.startNewTask(command.data)
110+
try {
111+
await this.startNewTask(command.data)
112+
} catch (error) {
113+
// IpcServer does not await async listeners: an uncaught rejection here
114+
// would surface as an unhandled rejection in the extension host.
115+
this.log(
116+
`[API] StartNewTask failed: ${error instanceof Error ? error.message : String(error)}`,
117+
)
118+
}
111119
break
112120
case TaskCommandName.CancelTask:
113121
this.log(`[API] CancelTask`)
@@ -231,17 +239,32 @@ export class API extends EventEmitter<RooCodeEvents> implements RooCodeAPI, RooC
231239
// hang task creation; if the bound expires, fail task creation rather than start
232240
// the task against stale shared defaults.
233241
let readinessTimer: ReturnType<typeof setTimeout> | undefined
234-
await Promise.race([
235-
provider.viewStateReadiness,
236-
new Promise<never>((_, reject) => {
237-
readinessTimer = setTimeout(
238-
() => reject(new Error("Timed out waiting for the view state to become ready")),
239-
3000,
240-
)
241-
}),
242-
]).finally(() => {
243-
clearTimeout(readinessTimer)
244-
})
242+
try {
243+
await Promise.race([
244+
provider.viewStateReadiness,
245+
new Promise<never>((_, reject) => {
246+
readinessTimer = setTimeout(
247+
() => reject(new Error("Timed out waiting for the view state to become ready")),
248+
3000,
249+
)
250+
}),
251+
]).finally(() => {
252+
clearTimeout(readinessTimer)
253+
})
254+
} catch (error) {
255+
if (
256+
provider.viewLaunched ||
257+
!(error instanceof Error) ||
258+
error.message !== "Timed out waiting for the view state to become ready"
259+
) {
260+
throw error
261+
}
262+
// Headless API callers create tasks without ever launching a webview: the
263+
// readiness bound expiring keeps the pre-existing shared-state fallback.
264+
// A launched view whose readiness failed is a real failure and rethrows.
265+
this.log("[API#startNewTask] webview not launched; continuing in headless mode")
266+
}
267+
245268
// Disposal resolves viewStateReadiness to release waiters: a provider torn down while
246269
// the wait was pending must fail task creation rather than create a task against the
247270
// disposed view (its posts and task registration would be orphaned).

0 commit comments

Comments
 (0)