Skip to content

Commit 2c5c2c0

Browse files
author
daewoongoh
committed
fix: address second-round CodeRabbit review feedback on task title generation
- Store: re-check abort signal inside per-file lock merge callback to prevent writes after cancellation. Added tests for cancellation during lock wait and storage failure propagation. - Rate-limit: agent countdown re-reads shared clock after waiting, handling case where title request dispatched mid-countdown. Both wait paths exercise in test. - Provider state read: wrap in Promise.race with abort signal for abort-aware reads before rate-limit wait, ensuring clock record precedes request dispatch. - Provider write: handle evicted items (item === undefined) by broadcasting taskHistoryUpdate to refresh task list from store. - Tests: added title-first ordering, agent countdown re-wait, stalled state read cancellation, queued-write cancellation with lock hold, and eviction broadcast. Deferred to follow-up issue: - Propagating abort signal through all provider implementations (11 providers ignore abortSignal, including Poe and Kimi Code). - Cross-host title clear persistence (requires HistoryItem schema change).
1 parent 83936a5 commit 2c5c2c0

6 files changed

Lines changed: 217 additions & 21 deletions

File tree

‎src/core/task-persistence/TaskHistoryStore.ts‎

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1202,8 +1202,9 @@ export class TaskHistoryStore {
12021202
* Deletion by another host is authoritative: when no persisted record
12031203
* exists, or the persisted record is malformed or carries a different task
12041204
* ID, nothing is written, the stale cache entry is dropped, and the result
1205-
* has no item. A signal aborted while the call waits on the store lock
1206-
* skips the write, so a cancelled task's title is never persisted.
1205+
* has no item. A signal aborted while the call waits on the store lock or
1206+
* the per-file lock skips the write, so a cancelled task's title is never
1207+
* persisted.
12071208
*
12081209
* @returns The authoritative record (absent when the write was rejected)
12091210
* and whether the generated title was applied.
@@ -1233,9 +1234,16 @@ export class TaskHistoryStore {
12331234
let applied = !cached.title
12341235
let authoritative: HistoryItem = cached.title ? cached : incoming
12351236
let rejectedDiskRecord = false
1237+
let cancelled = false
12361238
try {
12371239
await safeWriteJson(filePath, incoming, {
12381240
merge: (existing) => {
1241+
// Cancellation can land while waiting on the per-file lock;
1242+
// a throwing merge writes nothing.
1243+
if (options.signal?.aborted) {
1244+
cancelled = true
1245+
throw new Error(`[TaskHistoryStore] setGeneratedTitleIfUnset: task ${taskId} cancelled`)
1246+
}
12391247
// Writing the cached item back would recreate a task another
12401248
// host deleted or overwrite a record that is not this task's,
12411249
// so a missing, malformed, or mismatched record fails closed.
@@ -1263,6 +1271,9 @@ export class TaskHistoryStore {
12631271
},
12641272
})
12651273
} catch (error) {
1274+
if (cancelled) {
1275+
return { item: cached, applied: false }
1276+
}
12661277
if (!rejectedDiskRecord) {
12671278
throw error
12681279
}

‎src/core/task-persistence/__tests__/TaskHistoryStore.realConcurrency.spec.ts‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -526,6 +526,69 @@ describe("TaskHistoryStore real cross-host locking", () => {
526526
expect(store.get("solo-task")?.title).toBeUndefined()
527527
})
528528
})
529+
530+
it("skips the write when cancelled while waiting on the per-file lock", async () => {
531+
const actualFs = await vi.importActual<typeof import("fs/promises")>("fs/promises")
532+
await withSingleStore(async (store, filePath, onWrite) => {
533+
const before = await fs.readFile(filePath, "utf8")
534+
const controller = new AbortController()
535+
let signalReadStarted!: () => void
536+
const readStarted = new Promise<void>((resolve) => {
537+
signalReadStarted = resolve
538+
})
539+
let releaseRead!: () => void
540+
const readCanContinue = new Promise<void>((resolve) => {
541+
releaseRead = resolve
542+
})
543+
// Pause inside the per-file lock's disk read, before the merge.
544+
vi.mocked(fs.readFile).mockImplementation(async (...args: Parameters<typeof fs.readFile>) => {
545+
if (args[0] === filePath) {
546+
signalReadStarted()
547+
await readCanContinue
548+
}
549+
return actualFs.readFile(...args)
550+
})
551+
552+
try {
553+
const write = store.setGeneratedTitleIfUnset("solo-task", "Generated Title", {
554+
signal: controller.signal,
555+
})
556+
await readStarted
557+
controller.abort()
558+
releaseRead()
559+
560+
await expect(write).resolves.toMatchObject({ applied: false })
561+
} finally {
562+
vi.mocked(fs.readFile).mockImplementation(actualFs.readFile)
563+
}
564+
expect(await fs.readFile(filePath, "utf8")).toBe(before)
565+
expect(onWrite).not.toHaveBeenCalled()
566+
expect(store.get("solo-task")?.title).toBeUndefined()
567+
})
568+
})
569+
570+
it("propagates an ordinary storage failure and keeps the cached task", async () => {
571+
const actualFs = await vi.importActual<typeof import("fs/promises")>("fs/promises")
572+
await withSingleStore(async (store, filePath, onWrite) => {
573+
const storageError = Object.assign(new Error("permission denied"), { code: "EACCES" })
574+
vi.mocked(fs.readFile).mockImplementation(async (...args: Parameters<typeof fs.readFile>) => {
575+
if (args[0] === filePath) {
576+
throw storageError
577+
}
578+
return actualFs.readFile(...args)
579+
})
580+
581+
try {
582+
await expect(store.setGeneratedTitleIfUnset("solo-task", "Generated Title")).rejects.toBe(
583+
storageError,
584+
)
585+
} finally {
586+
vi.mocked(fs.readFile).mockImplementation(actualFs.readFile)
587+
}
588+
expect(store.get("solo-task")).toMatchObject({ id: "solo-task" })
589+
expect(onWrite).not.toHaveBeenCalled()
590+
})
591+
})
529592
})
530593

531594
describe("setGeneratedTitleIfUnset with a rejected disk record", () => {

‎src/core/task/Task.ts‎

Lines changed: 37 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3229,6 +3229,18 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
32293229
// records on the shared clock so subsequent task/subtask requests
32303230
// honour it. `startTask` schedules this method with `void`, so the
32313231
// agent never waits on the title result.
3232+
//
3233+
// A saved TASK_TITLE support prompt replaces the built-in template. The
3234+
// state is read before the rate-limit wait so nothing awaits between
3235+
// recording on the shared clock and dispatching; an unreadable state
3236+
// falls back to the built-in template, and cancellation ends the read.
3237+
const state = await Promise.race([
3238+
provider.getState().catch(() => undefined),
3239+
new Promise<undefined>((resolve) => {
3240+
controller.signal.addEventListener("abort", () => resolve(undefined), { once: true })
3241+
}),
3242+
])
3243+
32323244
await this.waitForProviderRateLimitWindow(controller.signal)
32333245

32343246
if (controller.signal.aborted || this.abort || this.abandoned) {
@@ -3237,10 +3249,6 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
32373249

32383250
this.rateLimitClock.recordRequest()
32393251

3240-
// A saved TASK_TITLE support prompt replaces the built-in template;
3241-
// an unreadable state falls back to the built-in template.
3242-
const state = await provider.getState().catch(() => undefined)
3243-
32443252
const generated = await generateTaskTitle(taskText, this.apiConfiguration, {
32453253
abortSignal: controller.signal,
32463254
timeoutMs: DEFAULT_TITLE_TIMEOUT_MS,
@@ -5797,25 +5805,41 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
57975805
private async maybeWaitForProviderRateLimit(retryAttempt: number): Promise<void> {
57985806
const rateLimitSeconds = this.apiConfiguration?.rateLimitSeconds ?? 0
57995807

5800-
const lastRequestTime = this.rateLimitClock.getLastRequestTime()
5801-
if (rateLimitSeconds <= 0 || !lastRequestTime) {
5808+
let lastRequestTime = this.rateLimitClock.getLastRequestTime()
5809+
// Only show the countdown UX on the first attempt. Retry flows have their own delay messaging.
5810+
if (rateLimitSeconds <= 0 || !lastRequestTime || retryAttempt !== 0) {
58025811
return
58035812
}
58045813

5805-
const now = performance.now()
5806-
const timeSinceLastRequest = now - lastRequestTime
5807-
const rateLimitDelay = Math.ceil(
5808-
Math.min(rateLimitSeconds, Math.max(0, rateLimitSeconds * 1000 - timeSinceLastRequest) / 1000),
5809-
)
5814+
let waited = false
5815+
while (lastRequestTime) {
5816+
const timeSinceLastRequest = performance.now() - lastRequestTime
5817+
const rateLimitDelay = Math.ceil(
5818+
Math.min(rateLimitSeconds, Math.max(0, rateLimitSeconds * 1000 - timeSinceLastRequest) / 1000),
5819+
)
5820+
if (rateLimitDelay <= 0) {
5821+
break
5822+
}
58105823

5811-
// Only show the countdown UX on the first attempt. Retry flows have their own delay messaging.
5812-
if (rateLimitDelay > 0 && retryAttempt === 0) {
5824+
waited = true
58135825
for (let i = rateLimitDelay; i > 0; i--) {
58145826
// Send structured JSON data for i18n-safe transport
58155827
const delayMessage = JSON.stringify({ seconds: i })
58165828
await this.say("api_req_rate_limit_wait", delayMessage, undefined, true)
58175829
await delay(1000)
58185830
}
5831+
5832+
// A background title request can dispatch on the shared clock during
5833+
// the countdown; re-wait from that dispatch instead of proceeding
5834+
// from the stale deadline.
5835+
const latestRequestTime = this.rateLimitClock.getLastRequestTime()
5836+
if (latestRequestTime === lastRequestTime) {
5837+
break
5838+
}
5839+
lastRequestTime = latestRequestTime
5840+
}
5841+
5842+
if (waited) {
58195843
// Finalize the partial message so the UI doesn't keep rendering an in-progress spinner.
58205844
await this.say("api_req_rate_limit_wait", undefined, undefined, false)
58215845
}

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

Lines changed: 62 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,7 @@ type TaskTitleAccess = {
3333
cancelCurrentRequest(): void
3434
requestAbort(isAbandoned: boolean): void
3535
cancelTitleGeneration(): void
36+
maybeWaitForProviderRateLimit(retryAttempt: number): Promise<void>
3637
titleAbortController?: AbortController
3738
abort: boolean
3839
abandoned: boolean
@@ -227,6 +228,20 @@ describe("Task title generation", () => {
227228
expect(mockSetGeneratedTaskTitle).not.toHaveBeenCalled()
228229
})
229230

231+
it("stops without a title request when cancelled during a stalled state read", async () => {
232+
mockProvider.getState.mockReturnValueOnce(new Promise(() => {}))
233+
const task = createTestTask()
234+
const access = getTaskTitleAccess(task)
235+
236+
const generation = access.generateTitleInBackground("Initial prompt message")
237+
await vi.waitFor(() => expect(mockProvider.getState).toHaveBeenCalled())
238+
access.cancelTitleGeneration()
239+
await generation
240+
241+
expect(taskTitleGen.generateTaskTitle).not.toHaveBeenCalled()
242+
expect(mockSetGeneratedTaskTitle).not.toHaveBeenCalled()
243+
})
244+
230245
it("skips title generation and the title write in ExtensionMode.Test", async () => {
231246
mockProvider.context.extensionMode = vscode.ExtensionMode.Test
232247
const task = createTestTask()
@@ -447,6 +462,53 @@ describe("Task title generation", () => {
447462
expect(taskDispatchTime).toBeDefined()
448463
expect((titleDispatchTime ?? 0) - (taskDispatchTime ?? 0)).toBeGreaterThanOrEqual(10_000)
449464
})
465+
466+
it("re-waits the agent countdown when a title request dispatches during it", async () => {
467+
const clock = createRateLimitClock()
468+
const task = createTestTask({
469+
rateLimitClock: clock,
470+
apiConfiguration: { ...mockApiConfig, rateLimitSeconds: 10 },
471+
})
472+
let titleDispatchTime: number | undefined
473+
let countdownTicks = 0
474+
// Each countdown tick advances one second; midway through the agent's
475+
// countdown, the title request's wait ends and it dispatches first.
476+
vi.mocked(delay).mockImplementation((ms: number) => {
477+
now += ms
478+
countdownTicks++
479+
if (countdownTicks === 5) {
480+
clock.recordRequest()
481+
titleDispatchTime = now
482+
}
483+
return Promise.resolve(undefined)
484+
})
485+
clock.recordRequest()
486+
487+
await getTaskTitleAccess(task).maybeWaitForProviderRateLimit(0)
488+
const agentDispatchTime = now
489+
490+
// The agent is spaced a full window from the title dispatch instead
491+
// of proceeding from the deadline it computed before the countdown.
492+
expect(titleDispatchTime).toBeDefined()
493+
expect(agentDispatchTime - (titleDispatchTime ?? 0)).toBeGreaterThanOrEqual(10_000)
494+
})
495+
496+
it("reads the support prompts before the rate-limit wait", async () => {
497+
const clock = createRateLimitClock()
498+
const task = createTestTask({
499+
rateLimitClock: clock,
500+
apiConfiguration: { ...mockApiConfig, rateLimitSeconds: 10 },
501+
})
502+
vi.mocked(taskTitleGen.generateTaskTitle).mockResolvedValueOnce("Summarized Title")
503+
clock.recordRequest()
504+
505+
await getTaskTitleAccess(task).generateTitleInBackground("Initial prompt message")
506+
507+
// Nothing awaits between recording on the shared clock and dispatching.
508+
expect(mockProvider.getState.mock.invocationCallOrder[0]).toBeLessThan(
509+
vi.mocked(delay).mock.invocationCallOrder[0],
510+
)
511+
})
450512
})
451513

452514
describe("cancellation and abort handling", () => {

‎src/core/webview/ClineProvider.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2843,7 +2843,8 @@ export class ClineProvider
28432843
* provider's store after this store's cache was last refreshed is never
28442844
* overwritten by the generated title. The store's authoritative item is
28452845
* published even when the generated title is not applied, so a title
2846-
* preserved from another host reaches the local header and task list. A
2846+
* preserved from another host reaches the local header and task list; a
2847+
* task the store dropped as deleted on disk refreshes the task list. A
28472848
* signal aborted while the write is queued skips it. Returns true when the
28482849
* title was applied, false otherwise. Throws when the task is not in the
28492850
* store yet so the caller can retry.
@@ -2856,7 +2857,12 @@ export class ClineProvider
28562857

28572858
const { item, applied } = await this.taskHistoryStore.setGeneratedTitleIfUnset(id, trimmed, { signal })
28582859

2859-
if (item && item.title) {
2860+
if (!item) {
2861+
// The store dropped a task deleted or invalidated on disk by another
2862+
// host; refresh the task list so it no longer shows the stale entry.
2863+
this.recentTasksCache = undefined
2864+
await this.broadcastTaskHistoryUpdate()
2865+
} else if (item.title) {
28602866
this.recentTasksCache = undefined
28612867

28622868
if (this.isViewLaunched) {

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

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -792,18 +792,48 @@ describe("ClineProvider Task History Synchronization", () => {
792792
expect(cancelTitleGeneration).toHaveBeenCalledTimes(1)
793793
})
794794

795-
it("skips the write when the signal is aborted before the queued write runs", async () => {
795+
it("skips a queued write when the task is cancelled before the write runs", async () => {
796796
await provider.updateTaskHistory(createHistoryItem({ id: "task-gen-abort", task: "Original prompt" }), {
797797
broadcast: false,
798798
})
799+
// Hold the store lock so the generated-title write queues behind it.
800+
let releaseLock: (() => void) | undefined
801+
const held = provider.taskHistoryStore["withLock"](
802+
() =>
803+
new Promise<void>((resolve) => {
804+
releaseLock = resolve
805+
}),
806+
)
807+
await vi.waitFor(() => expect(releaseLock).toBeDefined())
808+
const controller = new AbortController()
799809

800-
await expect(
801-
provider.setGeneratedTaskTitle("task-gen-abort", "Generated Title", AbortSignal.abort()),
802-
).resolves.toBe(false)
810+
const generated = provider.setGeneratedTaskTitle("task-gen-abort", "Generated Title", controller.signal)
811+
controller.abort()
812+
releaseLock?.()
813+
await held
803814

815+
await expect(generated).resolves.toBe(false)
804816
expect(getStored("task-gen-abort")?.title).toBeUndefined()
805817
})
806818

819+
it("refreshes the task list when the store drops a task deleted by another host", async () => {
820+
await provider.resolveWebviewView(mockWebviewView)
821+
provider.isViewLaunched = true
822+
await provider.updateTaskHistory(createHistoryItem({ id: "task-gen-deleted", task: "Original prompt" }), {
823+
broadcast: false,
824+
})
825+
vi.spyOn(provider.taskHistoryStore, "setGeneratedTitleIfUnset").mockResolvedValueOnce({
826+
item: undefined,
827+
applied: false,
828+
})
829+
mockPostMessage.mockClear()
830+
831+
await expect(provider.setGeneratedTaskTitle("task-gen-deleted", "Generated Title")).resolves.toBe(false)
832+
833+
expect(findCallsByType(mockPostMessage.mock.calls, "taskHistoryUpdated")).toHaveLength(1)
834+
expect(findCallsByType(mockPostMessage.mock.calls, "taskHistoryItemUpdated")).toHaveLength(0)
835+
})
836+
807837
it("throws when the task is not yet recorded so the caller can retry", async () => {
808838
await expect(provider.setGeneratedTaskTitle("missing-task", "Generated Title")).rejects.toThrow(
809839
"missing-task",

0 commit comments

Comments
 (0)