Skip to content

Commit eaa9c82

Browse files
committed
[Fix] Keep the queued-feedback row record consistent when say rejects
What: `persistQueuedFeedbackAndAcknowledge` now records the message id in `queuedFeedbackRowWritten` before awaiting `say`, and removes that record in the catch when `clineMessages` did not grow, so the record tracks whether the `user_feedback` row actually landed. The same catch releases the claim through `releaseUnconsumedQueuedMessage`, matching the exhausted-retry path, and rethrows. Why: `say` can reject after `addToClineMessages` pushed the row, because that method pushes synchronously and then emits `RooCodeMessage` event, which a consumer listener can throw from. The previous record-after-return shape left the id unrecorded on that path, so a later reclaim appended a duplicate row; recording before the await alone would instead drop the row when `say` rejects before appending. The array-length delta discriminates the two sub-branches exactly, since the append is synchronous and precedes every await in `addToClineMessages`. Impact: a reclaimed queued message appends exactly one `user_feedback` row in both throw orderings, and the claim stays reclaimable instead of leaking as claimed. No public API change; committed non-test budget stays at 500/500 and the changed-executable-line gate is 230/500. Two regression tests cover the throw-before-append and throw-after-append branches; each naive ordering is killed by the branch it breaks.
1 parent bd2769f commit eaa9c82

3 files changed

Lines changed: 114 additions & 48 deletions

File tree

‎src/core/task/Task.ts‎

Lines changed: 30 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -520,8 +520,8 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
520520
// `ask()` calls in flight. A drain must not submit while one is pending: the
521521
// submission would answer that ask with text written for another turn.
522522
private pendingAskCount = 0
523-
// Queued feedback whose `user_feedback` row is already in `clineMessages`, so
524-
// a retry or reclaim re-saves it instead of appending a duplicate row.
523+
// Queued feedback already appended to `clineMessages`, so a retry or reclaim
524+
// re-saves that row instead of appending a duplicate.
525525
private queuedFeedbackRowWritten = new Set<string>()
526526

527527
// Streaming
@@ -1119,10 +1119,23 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
11191119
images?: string[],
11201120
): Promise<boolean> {
11211121
// Append the row once, before the retry loop: a retry only re-attempts the
1122-
// durable save, and a reclaimed message already has its row.
1122+
// durable save, and a reclaimed message already has its row. `say` can
1123+
// throw after `addToClineMessages` pushed the row (its `Message` emit runs
1124+
// post-push), so the record is dropped only when the row did not land.
11231125
if (!this.queuedFeedbackRowWritten.has(messageId)) {
1124-
await this.say("user_feedback", text ?? "", images)
1126+
const appended = this.clineMessages.length
11251127
this.queuedFeedbackRowWritten.add(messageId)
1128+
try {
1129+
await this.say("user_feedback", text ?? "", images)
1130+
} catch (error) {
1131+
// Released like the exhausted-retry path: the row's durability is
1132+
// unknown, so the message stays reclaimable.
1133+
if (this.clineMessages.length === appended) {
1134+
this.queuedFeedbackRowWritten.delete(messageId)
1135+
}
1136+
this.releaseUnconsumedQueuedMessage(messageId)
1137+
throw error
1138+
}
11261139
}
11271140
for (let attempt = 0; attempt <= QUEUED_FEEDBACK_SAVE_RETRY_DELAYS_MS.length; attempt++) {
11281141
if (this.abort) {
@@ -1266,9 +1279,8 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
12661279
}
12671280

12681281
/**
1269-
* Settle a consumed queued message: drop it from the queue and clear its
1270-
* retention record on this one edge, so the record can never outlive the
1271-
* message. A consume whose persistence fails never reaches here.
1282+
* Settle a consumed queued message on this one edge, so no record can outlive
1283+
* its message. A consume whose persistence fails never reaches here.
12721284
*/
12731285
private consumeQueuedMessage(messageId: string): void {
12741286
this.messageQueueService.removeMessage(messageId)
@@ -1427,10 +1439,9 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
14271439
// so neither record can outlive its message.
14281440
const queuedIds = new Set(this.messageQueueService.messages.map((message) => message.id))
14291441
for (const id of this.drainRetainedQueuedMessageIds) {
1430-
if (!queuedIds.has(id)) {
1431-
this.drainRetainedQueuedMessageIds.delete(id)
1432-
this.queuedFeedbackRowWritten.delete(id)
1433-
}
1442+
if (queuedIds.has(id)) continue
1443+
this.drainRetainedQueuedMessageIds.delete(id)
1444+
this.queuedFeedbackRowWritten.delete(id)
14341445
}
14351446

14361447
return this.drainRetainedQueuedMessageIds.size > 0 &&
@@ -2499,8 +2510,8 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
24992510
this.askResponseText = text
25002511
this.askResponseImages = images
25012512
// No retention bookkeeping here: a direct response overwrites the slot a
2502-
// drain submitted into, so that submission was NOT consumed and the
2503-
// message stays queued and excluded from approval asks.
2513+
// drain submitted into, so that submission was NOT consumed: the message
2514+
// stays queued and excluded from approval asks.
25042515

25052516
// Create a checkpoint whenever the user sends a message.
25062517
// Use allowEmpty=true to ensure a checkpoint is recorded even if there are no file changes.
@@ -2640,7 +2651,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
26402651
* Submit a user message through the ask-response channel.
26412652
*
26422653
* @returns false when there was nothing to submit, the task is stopping, or
2643-
* the provider reference was lost. Callers draining the queue must check it.
2654+
* the provider reference was lost. Draining callers must check it.
26442655
*/
26452656
public async submitUserMessage(
26462657
text: string,
@@ -6555,9 +6566,8 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
65556566
* The message is claimed, not dequeued, and the claim is released after the
65566567
* submission handoff so the message STAYS queued: removal is tied to
65576568
* ask-consumption, not to submit-return, so a message submitted between turns
6558-
* survives a failed turn or restart. When submission throws, the claim is
6559-
* released and the error propagates; when the handoff reports nothing
6560-
* delivered, the claim is released and the run resolves false.
6569+
* survives a failed turn or restart. A throw releases the claim and
6570+
* propagates; a handoff that delivered nothing releases it and resolves false.
65616571
*
65626572
* Retention is restricted to conversational consumption: a retained ID is
65636573
* recorded in `drainRetainedQueuedMessageIds`, and every ask whose
@@ -6591,7 +6601,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
65916601
}
65926602
// An ask is waiting for its response. Submitting now would resolve that
65936603
// prompt with text written for another turn, bypassing the ask's claim gate,
6594-
// blanket-deny latch, and protected-ask exemption. Defer it instead.
6604+
// blanket-deny latch, and protected-ask exemption.
65956605
if (this.pendingAskCount > 0) {
65966606
return false
65976607
}
@@ -6601,8 +6611,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
66016611
}
66026612
// An earlier drain already submitted this message and no ask has consumed
66036613
// it yet: re-posting would overwrite a distinct pending response and lose
6604-
// it, so release the claim and keep the message queued. Nothing was
6605-
// submitted, so this reports false.
6614+
// it, so release the claim and report false with the message still queued.
66066615
if (this.drainRetainedQueuedMessageIds.has(queued.id)) {
66076616
this.messageQueueService.releaseMessage(queued.id)
66086617
return false
@@ -6621,8 +6630,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
66216630
throw error
66226631
}
66236632
// Record the ID before releasing the claim: a later drain must tell
6624-
// "already submitted, still pending" from "not submitted yet", and an
6625-
// execution-gating ask must refuse to claim it.
6633+
// "already submitted, still pending" from "not submitted yet".
66266634
this.drainRetainedQueuedMessageIds.add(queued.id)
66276635
this.messageQueueService.releaseMessage(queued.id)
66286636
return true

‎src/core/task/__tests__/ask-queued-message-drain.spec.ts‎

Lines changed: 68 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { Task } from "../Task"
33
type QueueTaskTestAccess = {
44
say: Task["say"]
55
saveClineMessages: () => Promise<boolean>
6-
addToClineMessages: () => Promise<void>
6+
addToClineMessages: (message: import("@roo-code/types").ClineMessage) => Promise<void>
77
lastMessageTs?: number
88
abort: boolean
99
}
@@ -27,7 +27,11 @@ describe("Task.ask queued message drain", () => {
2727
task["queuedFeedbackRowWritten"] = new Set<string>()
2828
return import("../../message-queue/MessageQueueService").then(({ MessageQueueService }) => {
2929
;(task as any).messageQueueService = new MessageQueueService()
30-
;(task as any).addToClineMessages = vi.fn(async () => {})
30+
// Mirrors the real `addToClineMessages`, which pushes synchronously before
31+
// its own awaits: the tests below depend on that ordering.
32+
;(task as any).addToClineMessages = vi.fn(async (message: import("@roo-code/types").ClineMessage) => {
33+
task["clineMessages"].push(message)
34+
})
3135
;(task as any).saveClineMessages = vi.fn(async () => {})
3236
;(task as any).updateClineMessage = vi.fn(async () => {})
3337
;(task as any).cancelAutoApprovalTimeout = vi.fn(() => {})
@@ -496,4 +500,66 @@ describe("Task.ask queued message drain", () => {
496500
expect(say).toHaveBeenCalledTimes(1)
497501
expect(task.messageQueueService.isEmpty()).toBe(true)
498502
})
503+
504+
it("keeps a message reclaimable and appends once when say throws before the row lands", async () => {
505+
const task = await createTask()
506+
task.messageQueueService.addMessage("Row never landed")
507+
const result = await task.ask("completion_result", "Done", false)
508+
const access = getQueueTaskTestAccess(task)
509+
access.saveClineMessages = vi.fn().mockResolvedValue(true)
510+
// The ask above left its own row; only rows added from here count.
511+
const rowsBefore = task["clineMessages"].length
512+
513+
// The real `say` guard rejects before `addToClineMessages` runs, so no row
514+
// exists and the message must stay reclaimable.
515+
access.abort = true
516+
await expect(
517+
task.persistQueuedFeedbackAndAcknowledge(result.queuedMessageId!, result.text, result.images),
518+
).rejects.toThrow("aborted")
519+
expect(task["clineMessages"]).toHaveLength(rowsBefore)
520+
expect(task.messageQueueService.messages.map((message) => message.text)).toEqual(["Row never landed"])
521+
// Released, not left claimed: a later consumer can still claim it.
522+
expect(task.messageQueueService.claimNextMessage()?.text).toBe("Row never landed")
523+
task.messageQueueService.releaseMessage(result.queuedMessageId!)
524+
525+
// A later reclaim appends exactly one row, because the failed attempt left
526+
// no record behind.
527+
access.abort = false
528+
await expect(
529+
task.persistQueuedFeedbackAndAcknowledge(result.queuedMessageId!, result.text, result.images),
530+
).resolves.toBe(true)
531+
expect(task["clineMessages"]).toHaveLength(rowsBefore + 1)
532+
expect(task.messageQueueService.isEmpty()).toBe(true)
533+
})
534+
535+
it("does not double-append when say throws after the row landed", async () => {
536+
const task = await createTask()
537+
task.messageQueueService.addMessage("Row landed then threw")
538+
const result = await task.ask("completion_result", "Done", false)
539+
const access = getQueueTaskTestAccess(task)
540+
access.saveClineMessages = vi.fn().mockResolvedValue(true)
541+
const rowsBefore = task["clineMessages"].length
542+
// The row is pushed the way `addToClineMessages` pushes it (synchronously,
543+
// before its own awaits), then the call rejects the way a throwing
544+
// `Message` listener makes `say` reject.
545+
access.addToClineMessages = vi.fn(async (message: import("@roo-code/types").ClineMessage) => {
546+
task["clineMessages"].push(message)
547+
throw new Error("listener threw")
548+
})
549+
550+
await expect(
551+
task.persistQueuedFeedbackAndAcknowledge(result.queuedMessageId!, result.text, result.images),
552+
).rejects.toThrow("listener threw")
553+
expect(task["clineMessages"]).toHaveLength(rowsBefore + 1)
554+
555+
// The row is retained in history, so the reclaim must not append a second
556+
// one, and the release must leave the message reclaimable rather than
557+
// leaked as claimed.
558+
await expect(
559+
task.persistQueuedFeedbackAndAcknowledge(result.queuedMessageId!, result.text, result.images),
560+
).resolves.toBe(true)
561+
expect(task["clineMessages"]).toHaveLength(rowsBefore + 1)
562+
expect(task.messageQueueService.isEmpty()).toBe(true)
563+
expect(task["drainRetainedQueuedMessageIds"].size).toBe(0)
564+
})
499565
})

‎src/core/tools/ExecuteCommandTool.ts‎

Lines changed: 16 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -332,8 +332,7 @@ export class ExecuteCommandTool extends BaseTool<"execute_command"> {
332332
// through `publishToolResult`, which settles the signal with the
333333
// publication outcome, so the drain waits on a structural signal and
334334
// skips after a failed publication. Every throw path must settle it
335-
// too: the drain awaits it, so an unsettled promise would hang that
336-
// chain and hold task references forever. Settling is idempotent.
335+
// too, or the awaiting drain would hang and hold task references.
337336
let settleToolResultPublished: ((published: boolean) => void) | undefined
338337
const toolResultPublished = new Promise<boolean>((resolve) => {
339338
settleToolResultPublished = resolve
@@ -368,9 +367,8 @@ export class ExecuteCommandTool extends BaseTool<"execute_command"> {
368367
}
369368

370369
publishToolResult(result)
371-
// Only drain queued messages when the command actually ran
372-
// (early validation failures end the turn without an execution,
373-
// matching file tools' error-path behavior).
370+
// Only drain when the command actually ran: early validation
371+
// failures end the turn without an execution.
374372
shouldDrainQueuedMessages = commandSubmitted
375373
} catch (error: unknown) {
376374
// Invalidate pending ask from first execution to prevent race condition
@@ -406,13 +404,11 @@ export class ExecuteCommandTool extends BaseTool<"execute_command"> {
406404
"Command was submitted in the VS Code terminal, but shell integration did not report its output or completion status. Do not run the command again automatically.",
407405
)
408406
} catch (warningError) {
409-
// A throw before publishToolResult leaves the signal unsettled.
410407
settleToolResultPublished?.(false)
411408
throw warningError
412409
}
413-
// The command did run, so this arm owes the same drain the normal
414-
// and fallback arms give. Set only after the warning result
415-
// published, so a failed publication still skips the drain.
410+
// This arm owes the same drain the normal and fallback arms give,
411+
// set only after the warning result published.
416412
shouldDrainQueuedMessages = error.commandSubmitted
417413
} else {
418414
// Ordinary execution error (e.g. the terminal failed to start) —
@@ -455,9 +451,9 @@ export type ExecuteCommandOptions = {
455451
commandExecutionTimeout?: number
456452
agentTimeout?: number
457453
/**
458-
* Resolves true on successful publication and false when it failed. The
454+
* Resolves true on successful publication, false when it failed. The
459455
* background-completion drain awaits this so queued messages are never
460-
* submitted ahead of the current tool result, and skips after a failure.
456+
* submitted ahead of the tool result, and skips after a failure.
461457
*/
462458
toolResultPublished?: Promise<boolean>
463459
toolCallId: string
@@ -653,27 +649,23 @@ export async function executeCommandInTerminal(
653649
.then(async () => {
654650
// The tool returned a "still running" result and drained when the
655651
// agent timeout moved the command to the background; process
656-
// messages queued since then so they are not held until an
657-
// unrelated path drains them. Wait on the per-invocation
658-
// publication signal: completion can land inside the settle
659-
// delay while the tool result is still pending.
652+
// messages queued since then. Wait on the per-invocation
653+
// publication signal: completion can land inside the settle delay.
660654
if (!runInBackground) {
661655
return
662656
}
663657
const published = await toolResultPublished
664-
// A task cancelled while the command finished in the background
665-
// must not drain: the guards inside processQueuedMessages would
666-
// no-op anyway, and skipping avoids error-log noise on the dying
667-
// task. A failed publication must not drain either: handleError
668-
// reports the command error first.
658+
// A cancelled task must not drain (the guards inside
659+
// processQueuedMessages would no-op anyway, and skipping avoids
660+
// error-log noise on a dying task), and neither must a failed
661+
// publication: handleError reports that error first.
669662
if (task.abort || task.abandoned || !published) {
670663
return
671664
}
672665
// The final `command_output` say is part of what the drain depends
673-
// on: #937 requires queued feedback to be considered together
674-
// with the finished command's output. A rejected say is swallowed
675-
// by the chain's `.catch`, so read the recorded outcome instead
676-
// of assuming the chain resolved.
666+
// on: #937 requires queued feedback to be considered together with
667+
// the finished command's output. A rejected say is swallowed by the
668+
// chain's `.catch`, so read the recorded outcome instead.
677669
if (commandOutputPublishFailed) {
678670
return
679671
}

0 commit comments

Comments
 (0)