Skip to content

Commit 53cb5b5

Browse files
unit 2 of the #1914 split (5 files, whole-file module cut) (#2384)
1 parent 766b906 commit 53cb5b5

5 files changed

Lines changed: 349 additions & 0 deletions

File tree

‎src/core/task/Task.ts‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@ import { buildNativeToolsArrayWithRestrictions } from "./build-tools"
106106
import { ToolRepetitionDetector } from "../tools/ToolRepetitionDetector"
107107
import { restoreTodoListForTask } from "../tools/UpdateTodoListTool"
108108
import { FileContextTracker } from "../context-tracking/FileContextTracker"
109+
import { ObservationRegistry } from "./observationRegistry"
109110
import { RooIgnoreController } from "../ignore/RooIgnoreController"
110111
import { RooProtectedController } from "../protect/RooProtectedController"
111112
import { type AssistantMessageContent, presentAssistantMessage } from "../assistant-message"
@@ -296,6 +297,10 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
296297
readonly instanceId: string
297298
readonly metadata: TaskMetadata
298299

300+
// The observed on-disk version of each file this task has read. Declared here so the
301+
// read tools can record it; a write guard later compares a token against this registry.
302+
readonly observationRegistry = new ObservationRegistry()
303+
299304
todoList?: TodoItem[]
300305

301306
readonly rootTask: Task | undefined = undefined
@@ -392,6 +397,11 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
392397

393398
providerRef: WeakRef<ClineProvider>
394399
private readonly globalStoragePath: string
400+
// Monotonic cancellation counter. `requestAbort()` and `requestDispose()` advance
401+
// this fence, and the guarded-write path compares the value it captured when the
402+
// write was queued with the value at publish time, so a queued write cannot publish
403+
// after the task was cancelled or disposed.
404+
cancellationGeneration: number = 0
395405
currentRequestAbortController?: AbortController
396406
/**
397407
* Controller for the waiter on an in-flight `ensureModelFetched()` call (see
@@ -3595,6 +3605,13 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
35953605
if (isAbandoned) {
35963606
this.abandoned = true
35973607
}
3608+
// The S4a write guard compares this counter with the value a queued write
3609+
// captured when it started, so every cancellation must advance it and it
3610+
// must never go backwards. Main moved the abort flag into the run-state
3611+
// reducer (see the abort(this.runState) getter above), so this counter is
3612+
// the only thing left that separates a cancelled run's queued writes from
3613+
// the resumed run's, and only if it advances monotonically.
3614+
this.cancellationGeneration++
35983615
this.driveRunEvent({ tag: "abortRequested", abandoned: isAbandoned })
35993616
}
36003617

@@ -3604,6 +3621,10 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
36043621
}
36053622

36063623
requestDispose(): void {
3624+
// A host teardown never calls abortTask(): disposal has to raise the same
3625+
// counter, or a write still parked on its path chain publishes after the
3626+
// task is gone.
3627+
this.cancellationGeneration++
36073628
this.driveRunEvent({ tag: "disposeRequested" })
36083629
}
36093630

@@ -3632,6 +3653,7 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
36323653

36333654
public abortTask(isAbandoned = false): Promise<void> {
36343655
this.requestAbort(isAbandoned)
3656+
36353657
this.cancelAssistantMessagePersistence()
36363658
this.abortPromise ??= this.abortTaskOnce()
36373659
return this.abortPromise
@@ -3754,6 +3776,13 @@ export class Task extends EventEmitter<TaskEvents> implements TaskLike {
37543776
console.error("Error removing event listeners:", error)
37553777
}
37563778

3779+
// A disposed task is no longer authoritative for what it read. The registry holds
3780+
// version tokens captured while the task was alive, and a disposed task can still be
3781+
// reachable through a parent/subtask reference; a guarded write must not accept one of
3782+
// those tokens for a file this task has not re-read since. Clearing also stops a long
3783+
// task from pinning every file it ever read.
3784+
this.observationRegistry.close()
3785+
37573786
// Release any terminals associated with this task.
37583787
try {
37593788
// Release any terminals associated with this task.

‎src/core/task/__tests__/Task.dispose.test.ts‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import path from "node:path"
33
import { type ProviderSettings, RooCodeEventName } from "@roo-code/types"
44

55
import { Task } from "../Task"
6+
import { ObservationRegistry } from "../observationRegistry"
67
import { ClineProvider } from "../../webview/ClineProvider"
78
import { OutputInterceptor } from "../../../integrations/terminal/OutputInterceptor"
89
import { providerIdentifiers } from "@roo-code/types/provider-identifiers"
@@ -118,6 +119,55 @@ describe("Task dispose method", () => {
118119
expect(disposalComplete).toBe(true)
119120
})
120121

122+
test("owns a per-Task observation registry", () => {
123+
// ReadFileTool and the guarded-write path reach the registry only through the Task,
124+
// so a Task that never built one - or shared one across Tasks - would silently drop
125+
// read observations. The registry's own tests only exercise standalone instances, and
126+
// the tool tests inject their own doubles, so nothing else pins this wiring.
127+
expect(task.observationRegistry).toBeInstanceOf(ObservationRegistry)
128+
129+
const other = new Task({
130+
provider: mockProvider as unknown as ClineProvider,
131+
apiConfiguration: mockApiConfiguration,
132+
startTask: false,
133+
})
134+
try {
135+
expect(other.observationRegistry).toBeInstanceOf(ObservationRegistry)
136+
expect(other.observationRegistry).not.toBe(task.observationRegistry)
137+
138+
// Observing in one Task must not be visible from another: parent and subtask
139+
// authority over a file has to stay separate.
140+
other.observationRegistry.observe("/workspace/a.ts", "v1", true)
141+
expect(other.observationRegistry.get("/workspace/a.ts")?.version).toBe("v1")
142+
expect(task.observationRegistry.has("/workspace/a.ts")).toBe(false)
143+
expect(task.observationRegistry.size).toBe(0)
144+
} finally {
145+
void other.dispose().catch(() => {})
146+
}
147+
})
148+
149+
test("clears the per-Task observation registry on disposal", async () => {
150+
// The registry holds on-disk version tokens for files this task read. Disposal does not
151+
// free the Task object - a parent or subtask reference can outlive it - so a token
152+
// captured before teardown must not survive as authority for a guarded write.
153+
task.observationRegistry.observe("/workspace/a.ts", "v1", true)
154+
task.observationRegistry.observe("/workspace/b.ts", "v2", false)
155+
expect(task.observationRegistry.size).toBe(2)
156+
157+
await task.dispose()
158+
159+
expect(task.observationRegistry.size).toBe(0)
160+
expect(task.observationRegistry.has("/workspace/a.ts")).toBe(false)
161+
expect(task.observationRegistry.get("/workspace/b.ts")).toBeUndefined()
162+
163+
// A read that was still awaiting I/O when disposal began resumes afterwards. Its
164+
// observation must not land in a retired registry, or the disposed Task would be
165+
// authoritative for that file again.
166+
expect(task.observationRegistry.closed).toBe(true)
167+
task.observationRegistry.observe("/workspace/late.ts", "v3", true)
168+
expect(task.observationRegistry.size).toBe(0)
169+
})
170+
121171
test("should reject the memoized completion promise when disposal cannot start", async () => {
122172
const disposalError = new Error("disposal failed")
123173
skipCleanup = true

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

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4769,6 +4769,57 @@ describe("Cline", () => {
47694769
).toHaveLength(1)
47704770
})
47714771

4772+
it("advances the cancellation generation on each cancellation and keeps it advanced across a resume", async () => {
4773+
// The S4a write guard compares the cancellation generation a queued write
4774+
// captured against the generation at publish time. The abort FLAG cannot do
4775+
// that on its own: it is set on cancellation and no resume path clears it,
4776+
// so on a resumed task it says only that some cancellation happened, not
4777+
// which run a queued write belongs to. Only the generation keeps the two
4778+
// runs apart, so it must never go backwards.
4779+
const task = new Task({
4780+
provider: mockProvider,
4781+
apiConfiguration: mockApiConfig,
4782+
task: "test task",
4783+
startTask: false,
4784+
})
4785+
vi.spyOn(task, "dispose").mockResolvedValue(undefined)
4786+
4787+
expect(task.cancellationGeneration).toBe(0)
4788+
4789+
await task.abortTask()
4790+
expect(task.abort).toBe(true)
4791+
expect(task.cancellationGeneration).toBe(1)
4792+
4793+
await task.resumeAfterDelegation()
4794+
// The run-state model (RSK-06) no longer clears the legacy `abort` flag
4795+
// on resume: that is exactly why the generation exists. Only the
4796+
// generation keeps the cancelled run and the resumed run apart.
4797+
expect(task.cancellationGeneration).toBe(1)
4798+
4799+
await task.abortTask()
4800+
expect(task.abort).toBe(true)
4801+
expect(task.cancellationGeneration).toBe(2)
4802+
})
4803+
4804+
it("advances the cancellation generation on disposal, without any explicit cancel", async () => {
4805+
// A task torn down by the host never sees abortTask(). Disposal has to raise the
4806+
// same generation, or a write still parked on its path chain publishes after the
4807+
// task is gone.
4808+
const task = new Task({
4809+
provider: mockProvider,
4810+
apiConfiguration: mockApiConfig,
4811+
task: "test task",
4812+
startTask: false,
4813+
})
4814+
4815+
expect(task.cancellationGeneration).toBe(0)
4816+
4817+
await task.dispose()
4818+
4819+
expect(task.abort).toBe(true)
4820+
expect(task.cancellationGeneration).toBe(1)
4821+
})
4822+
47724823
it("flushes pending state before TaskAborted and disposal while queue state is intact", async () => {
47734824
const task = new Task({
47744825
provider: mockProvider,
@@ -7762,6 +7813,9 @@ describe("Cline", () => {
77627813
// task directory to exist (uuid v7 is mocked to the fixed id below).
77637814
const taskDir = path.join(os.tmpdir(), "test-storage", "tasks", "00000000-0000-7000-8000-000000000000")
77647815
fsReal.mkdirSync(taskDir, { recursive: true })
7816+
// Earlier tests in this file can leave a ui_messages.json for the fixed task id;
7817+
// merge=true would read it here and fail the first save stage for an unrelated reason.
7818+
fsReal.rmSync(path.join(taskDir, "ui_messages.json"), { force: true })
77657819
// Declared outside the try so the finally block can restore them.
77667820
const updateSpy = vi
77677821
.spyOn(getTaskTestAccess(Task.prototype), "updateClineMessage")
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
import { describe, it, expect, vi } from "vitest"
2+
3+
import { ObservationRegistry } from "../observationRegistry"
4+
5+
describe("ObservationRegistry", () => {
6+
it("observe → get returns the recorded version and observedAt", () => {
7+
const reg = new ObservationRegistry()
8+
reg.observe("/a/b/c.ts", "1:2:300:4000000000:5000000000")
9+
10+
const obs = reg.get("/a/b/c.ts")
11+
expect(obs).toBeDefined()
12+
expect(obs!.version).toBe("1:2:300:4000000000:5000000000")
13+
expect(typeof obs!.observedAt).toBe("number")
14+
})
15+
16+
it("re-observe replaces the entry with a fresh observedAt", () => {
17+
vi.useFakeTimers()
18+
const reg = new ObservationRegistry()
19+
reg.observe("/a/b/c.ts", "v1")
20+
const first = reg.get("/a/b/c.ts")!
21+
expect(first.version).toBe("v1")
22+
23+
vi.advanceTimersByTime(50)
24+
reg.observe("/a/b/c.ts", "v2")
25+
const second = reg.get("/a/b/c.ts")!
26+
expect(second.version).toBe("v2")
27+
expect(second.observedAt).toBeGreaterThan(first.observedAt)
28+
29+
vi.useRealTimers()
30+
})
31+
32+
it("has returns true for observed paths, false otherwise", () => {
33+
const reg = new ObservationRegistry()
34+
reg.observe("/x.ts", "t1")
35+
expect(reg.has("/x.ts")).toBe(true)
36+
expect(reg.has("/y.ts")).toBe(false)
37+
})
38+
39+
it("size reflects the number of observed entries", () => {
40+
const reg = new ObservationRegistry()
41+
expect(reg.size).toBe(0)
42+
reg.observe("/a.ts", "t1")
43+
reg.observe("/b.ts", "t2")
44+
expect(reg.size).toBe(2)
45+
})
46+
47+
it("clear removes all entries and resets size to 0", () => {
48+
const reg = new ObservationRegistry()
49+
reg.observe("/a.ts", "t1")
50+
reg.observe("/b.ts", "t2")
51+
reg.clear()
52+
expect(reg.size).toBe(0)
53+
expect(reg.get("/a.ts")).toBeUndefined()
54+
expect(reg.has("/b.ts")).toBe(false)
55+
})
56+
57+
it("get on empty registry returns undefined", () => {
58+
const reg = new ObservationRegistry()
59+
expect(reg.get("/any.ts")).toBeUndefined()
60+
})
61+
62+
it("separate instances are independent — observing in one does not appear in the other", () => {
63+
const regA = new ObservationRegistry()
64+
const regB = new ObservationRegistry()
65+
regA.observe("/shared.ts", "v1")
66+
expect(regA.get("/shared.ts")).toBeDefined()
67+
expect(regB.get("/shared.ts")).toBeUndefined()
68+
regB.observe("/shared.ts", "v2")
69+
expect(regA.get("/shared.ts")!.version).toBe("v1")
70+
expect(regB.get("/shared.ts")!.version).toBe("v2")
71+
})
72+
73+
describe("completeness scope (S4b follow-up #46)", () => {
74+
it("defaults to a complete observation when the read scope is not given", () => {
75+
const reg = new ObservationRegistry()
76+
reg.observe("/a/b/c.ts", "v1")
77+
78+
expect(reg.get("/a/b/c.ts")!.complete).toBe(true)
79+
})
80+
81+
it("records a partial observation when the read only returned a view of the file", () => {
82+
const reg = new ObservationRegistry()
83+
reg.observe("/a/b/c.ts", "v1", false)
84+
85+
expect(reg.get("/a/b/c.ts")!.complete).toBe(false)
86+
})
87+
88+
it("re-observing replaces the entry's completeness with the new read's scope", () => {
89+
const reg = new ObservationRegistry()
90+
reg.observe("/a/b/c.ts", "v1", false)
91+
reg.observe("/a/b/c.ts", "v2")
92+
93+
const obs = reg.get("/a/b/c.ts")!
94+
expect(obs.version).toBe("v2")
95+
expect(obs.complete).toBe(true)
96+
})
97+
98+
it("re-observing with a partial scope downgrades a previously complete entry", () => {
99+
const reg = new ObservationRegistry()
100+
reg.observe("/a/b/c.ts", "v1")
101+
reg.observe("/a/b/c.ts", "v2", false)
102+
103+
const obs = reg.get("/a/b/c.ts")!
104+
expect(obs.version).toBe("v2")
105+
expect(obs.complete).toBe(false)
106+
})
107+
})
108+
109+
describe("closure on task disposal", () => {
110+
it("close drops every entry and reports the registry closed", () => {
111+
const reg = new ObservationRegistry()
112+
reg.observe("/a/b/c.ts", "v1")
113+
expect(reg.closed).toBe(false)
114+
115+
reg.close()
116+
117+
expect(reg.size).toBe(0)
118+
expect(reg.get("/a/b/c.ts")).toBeUndefined()
119+
expect(reg.closed).toBe(true)
120+
})
121+
122+
it("observe is a no-op after close, so a read resuming after disposal records nothing", () => {
123+
const reg = new ObservationRegistry()
124+
reg.close()
125+
126+
reg.observe("/late.ts", "v1")
127+
128+
expect(reg.size).toBe(0)
129+
expect(reg.has("/late.ts")).toBe(false)
130+
})
131+
})
132+
})

0 commit comments

Comments
 (0)