Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 9 additions & 6 deletions src/core/task/Task.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ import { mergeConsecutiveApiMessages } from "./mergeConsecutiveApiMessages"
import { prepareApiConversationMessage } from "./apiConversationHistory"
import { shouldAddUserMessageToHistory } from "./messageCounting"
import { type TaskExecutionContext } from "./providerHandoff"
import { initialRunState, type Ask, type RunEvent, type RunState } from "./run-state/runState"
import { abort, abortReason, initialRunState, type Ask, type RunEvent, type RunState } from "./run-state/runState"
import { applyRunEvent, type RunRejection } from "./run-state/runStateShadow"
import {
divergenceKey,
Expand Down Expand Up @@ -389,7 +389,6 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {

providerRef: WeakRef<ClineProvider>
private readonly globalStoragePath: string
abort: boolean = false
currentRequestAbortController?: AbortController
/**
* Controller for the waiter on an in-flight `ensureModelFetched()` call (see
Expand All @@ -407,7 +406,6 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {

didFinishAbortingStream = false
abandoned = false
abortReason?: ClineApiReqCancelReason
isInitialized = false

runState: RunState = initialRunState
Expand Down Expand Up @@ -3528,16 +3526,22 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
this.driveRunEvent({ tag: "completionAccepted", askTs })
}

get abort(): boolean {
return abort(this.runState)
}

get abortReason(): ClineApiReqCancelReason | undefined {
return abortReason(this.runState)
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

setAbortReason(reason: ClineApiReqCancelReason): void {
this.abortReason ??= reason
this.driveRunEvent({ tag: "reasonSet", reason })
}

requestAbort(isAbandoned: boolean): void {
if (isAbandoned) {
this.abandoned = true
}
this.abort = true
this.driveRunEvent({ tag: "abortRequested", abandoned: isAbandoned })
}

Expand All @@ -3547,7 +3551,6 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
}

requestDispose(): void {
this.abort = true
this.driveRunEvent({ tag: "disposeRequested" })
}

Expand Down
3 changes: 2 additions & 1 deletion src/core/task/__tests__/Task.persistence.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import { ContextProxy } from "../../config/ContextProxy"
import { providerIdentifiers } from "@roo-code/types/provider-identifiers"
import { attemptCompletionTool, type AttemptCompletionCallbacks } from "../../tools/AttemptCompletionTool"
import type { ToolUse } from "../../../shared/tools"
import { setAbortLatch } from "../../../test-utils/run-state"

type TaskPersistenceAccess = {
addToApiConversationHistory: (message: Anthropic.MessageParam) => Promise<void>
Expand Down Expand Up @@ -909,7 +910,7 @@ describe("Task persistence", () => {
task: "test task",
startTask: false,
})
task.abort = true
setAbortLatch(task, true)
task.userMessageContent = [{ type: "tool_result", tool_use_id: "tool-1", content: "done" }]
const waitForPersistence = vi.spyOn(task, "waitForCurrentAssistantMessagePersistence")

Expand Down
13 changes: 8 additions & 5 deletions src/core/task/__tests__/Task.run-shadow.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,14 +101,14 @@ describe("Task run-state write helpers", () => {
task.requestAbort(false)

expect([task.abort, task.abandoned]).toEqual([true, false])
expect(task.runState.latches).toMatchObject({ abort: true, abandoned: false })
expect(task.runState.latches.abandoned).toBe(false)
})

it("requestAbort(true) sets abort and abandoned", () => {
task.requestAbort(true)

expect([task.abort, task.abandoned]).toEqual([true, true])
expect(task.runState.latches).toMatchObject({ abort: true, abandoned: true })
expect(task.runState.latches.abandoned).toBe(true)
})

it("requestAbandon sets abandoned after an abort", () => {
Expand All @@ -124,7 +124,7 @@ describe("Task run-state write helpers", () => {
task.requestDispose()

expect(task.abort).toBe(true)
expect(task.runState.latches).toMatchObject({ abort: true, disposed: true })
expect(task.runState.latches.disposed).toBe(true)
})

it("drives the ask events", () => {
Expand All @@ -149,12 +149,15 @@ describe("Task run-state write helpers", () => {
expect(task.runRejections).toEqual([{ event: { tag: "abandonRequested" }, state: initialRunState }])
})

it("keeps the first abort reason in the field and in the kernel", () => {
it("has no abort reason before one is set", () => {
expect(task.abortReason).toBeUndefined()
})

it("keeps the first abort reason", () => {
task.setAbortReason("user_cancelled")
task.setAbortReason("streaming_failed")

expect(task.abortReason).toBe("user_cancelled")
expect(task.runState.latches.reason).toBe("user_cancelled")
expect(task.runRejections).toEqual([])
})
})
Expand Down
11 changes: 6 additions & 5 deletions src/core/task/__tests__/Task.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,7 @@ vi.mock("delay", () => ({

import delay from "delay"
import pWaitFor from "p-wait-for"
import { setAbortLatch } from "../../../test-utils/run-state"

vi.mock("uuid", async (importOriginal) => {
const actual = await importOriginal<typeof import("uuid")>()
Expand Down Expand Up @@ -1018,7 +1019,7 @@ describe("Cline", () => {
const saySpy = vi.spyOn(task, "say").mockImplementation(async (...args) => {
const [type, _text, _images, partial] = args
if (type === "text" && partial === false) {
task.abort = true
setAbortLatch(task, true)
throw new Error("presenter text failed while aborting")
}
return say(...args)
Expand Down Expand Up @@ -4613,7 +4614,7 @@ describe("Cline", () => {
const abortTaskSpy = vi.spyOn(task, "abortTask").mockResolvedValue(undefined)

// Test Case 1: Stream failure should NOT abort task
task.abort = false
setAbortLatch(task, false)
task.abandoned = false

// Simulate the catch block behavior for stream failure
Expand All @@ -4634,7 +4635,7 @@ describe("Cline", () => {
expect(abortTaskSpy).not.toHaveBeenCalled()

// Test Case 2: User cancellation SHOULD abort task
task.abort = true
setAbortLatch(task, true)

// For user cancellation, abortTask SHOULD be called
if (task.abort) {
Expand Down Expand Up @@ -7035,7 +7036,7 @@ describe("Cline", () => {
await flushMicrotasks()
consoleErrorSpy.mockClear()

task.abort = true
setAbortLatch(task, true)
getTaskTestAccess(task).presentAssistantMessageSafe()
await flushMicrotasks()

Expand Down Expand Up @@ -7089,7 +7090,7 @@ describe("Cline", () => {
consoleErrorSpy.mockClear()

// Simulate the TOCTOU race: abort flips between throw and catch.
task.abort = true
setAbortLatch(task, true)
getTaskTestAccess(task).presentAssistantMessageSafe()
await flushMicrotasks()

Expand Down
11 changes: 6 additions & 5 deletions src/core/task/__tests__/ask-abort-race.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { ClineMessage } from "@roo-code/types"
import { checkAutoApproval } from "../../auto-approval"
import { MessageQueueService } from "../../message-queue/MessageQueueService"
import { Task } from "../Task"
import { setAbortLatch } from "../../../test-utils/run-state"

vi.mock("../../auto-approval", async (importOriginal) => {
const actual = await importOriginal<typeof import("../../auto-approval")>()
Expand All @@ -11,7 +12,7 @@ vi.mock("../../auto-approval", async (importOriginal) => {

function buildTask(getState: () => Promise<Record<string, unknown>>) {
const task = Object.create(Task.prototype) as Task
task["abort"] = false
setAbortLatch(task, false)
task["clineMessages"] = []
task["lastMessageTs"] = undefined
task["addToClineMessages"] = vi.fn(async () => {})
Expand Down Expand Up @@ -44,7 +45,7 @@ describe("Task.ask abort during the auto-approval await", () => {
})

const askPromise = task.ask("tool", JSON.stringify({ tool: "readFile" }), partial)
task["abort"] = true
setAbortLatch(task, true)
gate.release()

await expect(askPromise).rejects.toThrow(/aborted/)
Expand All @@ -62,7 +63,7 @@ describe("Task.ask abort during the auto-approval await", () => {

const askPromise = task.ask("tool", JSON.stringify({ tool: "readFile" }), false)
await vi.waitFor(() => expect(checkAutoApproval).toHaveBeenCalled())
task["abort"] = true
setAbortLatch(task, true)
gate.release()

await expect(askPromise).rejects.toThrow(/aborted/)
Expand All @@ -83,7 +84,7 @@ describe("Task.ask abort during the auto-approval await", () => {
task["clineMessages"] = [{ ...original }]

const askPromise = task.ask("followup", "new", partial)
task["abort"] = true
setAbortLatch(task, true)
gate.release()

await expect(askPromise).rejects.toThrow(/aborted/)
Expand All @@ -102,7 +103,7 @@ describe("Task.ask abort during the auto-approval await", () => {
task.messageQueueService.addMessage("queued feedback")

const askPromise = task.ask("followup", "Q?", false)
task["abort"] = true
setAbortLatch(task, true)
gate.release()

await expect(askPromise).rejects.toThrow(/aborted/)
Expand Down
3 changes: 2 additions & 1 deletion src/core/task/__tests__/ask-allowlist-cwd.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import type { ExtensionState } from "@roo-code/types"

import { Task } from "../Task"
import { setAbortLatch } from "../../../test-utils/run-state"

// The allowlist patterns are resolved against a workspace root, and the path in
// the tool message was made relative by `getReadablePath(task.cwd, ...)`. So the
Expand All @@ -23,7 +24,7 @@ type ProviderStub = {

function buildTask(provider: ProviderStub, taskCwd: string) {
const task = Object.create(Task.prototype) as Task
task["abort"] = false
setAbortLatch(task, false)
task["clineMessages"] = []
task["askResponse"] = undefined
task["askResponseText"] = undefined
Expand Down
11 changes: 6 additions & 5 deletions src/core/task/__tests__/ask-auto-deny.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { type ClineMessage, type ExtensionState, RooCodeEventName } from "@roo-c
import * as autoApprovalModule from "../../auto-approval"
import { createRateLimitClock } from "../RateLimitClock"
import { Task } from "../Task"
import { setAbortLatch } from "../../../test-utils/run-state"

// The streaming-loop drive below never asserts on environment details; the
// real collector reaches into the VS Code window API, which this file's
Expand All @@ -31,7 +32,7 @@ type ProviderStub = {

function buildTask(provider: ProviderStub, taskCwd: string) {
const task = Object.create(Task.prototype) as Task
task["abort"] = false
setAbortLatch(task, false)
task["clineMessages"] = []
task["askResponse"] = undefined
task["askResponseText"] = undefined
Expand Down Expand Up @@ -743,7 +744,7 @@ describe("Task.ask queue path cannot bypass blanket deny", () => {
await vi.waitFor(() => expect(getStateCalls).toBe(2))
expect(queue.hasUnclaimed()).toBe(false)

task["abort"] = true
setAbortLatch(task, true)

// `ask()` must reject on abort; racing a deadline distinguishes a wrong
// settle from a hang on the pending read.
Expand Down Expand Up @@ -830,7 +831,7 @@ describe("Task.ask queue path cannot bypass blanket deny", () => {
// longer this wait runs, the less event-loop-stall slack is left before
// the 2 s timer could legitimately fire while the task is still live.
await vi.waitFor(() => expect(Date.now() - armedAt).toBeGreaterThanOrEqual(300), { timeout: 2_000 })
task["abort"] = true
setAbortLatch(task, true)

const outcome = await toolAsk.then(
() => "resolved",
Expand Down Expand Up @@ -931,7 +932,7 @@ describe("Task.ask queue path cannot bypass blanket deny", () => {
await vi.waitFor(() => expect(getStateCalls).toBe(2))
expect(queue.hasUnclaimed()).toBe(false)

task["abort"] = true
setAbortLatch(task, true)

// `ask()` must reject on abort; racing a deadline distinguishes a wrong
// settle from a hang on the pending read.
Expand Down Expand Up @@ -993,7 +994,7 @@ describe("Task.ask queue path cannot bypass blanket deny", () => {
await vi.waitFor(() => expect(getStateCalls).toBe(2))
expect(queue.hasUnclaimed()).toBe(false)

task["abort"] = true
setAbortLatch(task, true)

// `ask()` must reject on abort; racing a deadline distinguishes a wrong
// settle from a hang on the pending read.
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Task } from "../Task"
import { setAbortLatch } from "../../../test-utils/run-state"

// When the backend auto-resolves an interactive ask, isAnswered:true is stamped
// on the ClineMessage before it is added so the webview state snapshot already
Expand All @@ -12,7 +13,7 @@ type ProviderStub = {

function buildTask(provider: ProviderStub | undefined) {
const task = Object.create(Task.prototype) as Task
;(task as any).abort = false
setAbortLatch(task, false)
;(task as any).clineMessages = []
;(task as any).askResponse = undefined
;(task as any).askResponseText = undefined
Expand Down
8 changes: 4 additions & 4 deletions src/core/task/__tests__/ask-queued-message-drain.spec.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { Task } from "../Task"
import { setAbortLatch } from "../../../test-utils/run-state"

type QueueTaskTestAccess = {
say: Task["say"]
saveClineMessages: () => Promise<boolean>
addToClineMessages: () => Promise<void>
lastMessageTs?: number
abort: boolean
}

const getQueueTaskTestAccess = (task: Task) => task as unknown as QueueTaskTestAccess
Expand All @@ -16,7 +16,7 @@ const getQueueTaskTestAccess = (task: Task) => task as unknown as QueueTaskTestA
describe("Task.ask queued message drain", () => {
function createTask(provider?: { getState: () => Promise<Record<string, boolean>> }) {
const task = Object.create(Task.prototype) as Task
;(task as any).abort = false
setAbortLatch(task, false)
;(task as any).clineMessages = []
;(task as any).askResponse = undefined
;(task as any).askResponseText = undefined
Expand Down Expand Up @@ -346,7 +346,7 @@ describe("Task.ask queued message drain", () => {
task.messageQueueService.addMessage("Persist me later")
const ask = task.ask("completion_result", "Done", false)
await Promise.resolve()
access.abort = true
setAbortLatch(task, true)
finishAddingAsk()

await expect(ask).rejects.toThrow("aborted")
Expand Down Expand Up @@ -398,7 +398,7 @@ describe("Task.ask queued message drain", () => {
await vi.advanceTimersByTimeAsync(0)
expect(access.saveClineMessages).toHaveBeenCalledTimes(1)

access.abort = true
setAbortLatch(task, true)
await vi.advanceTimersByTimeAsync(250)

await expect(persistence).resolves.toBe(false)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { Task } from "../Task"
import { ClineProvider } from "../../webview/ClineProvider"
import { ContextProxy } from "../../config/ContextProxy"
import { providerIdentifiers } from "@roo-code/types/provider-identifiers"
import { setAbortLatch } from "../../../test-utils/run-state"

// Mock delay before any imports that might use it
vi.mock("delay", () => ({
Expand Down Expand Up @@ -458,7 +459,7 @@ describe("flushPendingToolResultsToHistory", () => {

const waitForPersistence = vi.spyOn(task, "waitForCurrentAssistantMessagePersistence")

task.abort = true
setAbortLatch(task, true)

await task.flushPendingToolResultsToHistory()

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -85,7 +85,7 @@ describe("findDivergences", () => {
expect(divergence.raceId).toBeUndefined()
})

it("compares the latch and phase fields by default and skips the stream fields", () => {
it("compares the abandoned and phase fields by default and skips the kernel-read and stream fields", () => {
const [divergence, ...rest] = findDivergences({
event: { tag: "initialized" },
state: initialRunState,
Expand All @@ -101,7 +101,7 @@ describe("findDivergences", () => {
})
expect(rest).toEqual([])
expect(divergence).toMatchObject({ kind: "mismatch" })
expect([...divergence.mismatched].sort()).toEqual(["abandoned", "abort", "abortReason", "isInitialized"])
expect([...divergence.mismatched].sort()).toEqual(["abandoned", "isInitialized"])
})

it("ignores a field that is not routed", () => {
Expand Down
2 changes: 1 addition & 1 deletion src/core/task/run-state/runStateDivergence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export type Divergence = {
mismatched: Array<keyof RunStateFields>
}

export const ROUTED_FIELDS: ReadonlyArray<keyof RunStateFields> = ["abort", "abandoned", "abortReason", "isInitialized"]
export const ROUTED_FIELDS: ReadonlyArray<keyof RunStateFields> = ["abandoned", "isInitialized"]

export type KnownRace = { id: RaceId; matches: (divergence: Divergence) => boolean }

Expand Down
Loading
Loading