Skip to content

Commit 37607ce

Browse files
author
Zoo (VP)
committed
Merge branch 'pr/b09-task-org-ipc-v2' into pr/b10-task-org-ui-v2
# Conflicts: # src/core/task-persistence/__tests__/TaskOrganizationStore.spec.ts
2 parents 04577e2 + 7d3f50f commit 37607ce

4 files changed

Lines changed: 193 additions & 12 deletions

File tree

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

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -39,9 +39,9 @@ export interface TaskOrganizationError {
3939
*/
4040
export interface TaskOrganizationStoreOptions {
4141
/**
42-
* Optional callback invoked when the on-disk aggregate changes with a
43-
* greater revision than the in-memory snapshot. Called during watcher
44-
* reloads and after each local mutation.
42+
* Optional callback invoked when the reloaded on-disk aggregate differs
43+
* from the in-memory snapshot (compared by content, not just revision).
44+
* Called during watcher reloads and after each local mutation.
4545
*/
4646
onChange?: (state: TaskOrganizationStateV1) => Promise<void> | void
4747

@@ -68,8 +68,8 @@ export interface TaskOrganizationStoreOptions {
6868
* are serialized and the revision monotonically increases.
6969
*
7070
* The in-memory state is a projection of the on-disk aggregate. A file watcher
71-
* reloads greater revisions written by other extension instances and triggers
72-
* the onChange callback.
71+
* reloads changes written by other extension instances and triggers the
72+
* onChange callback whenever the reloaded content differs.
7373
*/
7474
export class TaskOrganizationStore {
7575
private readonly globalStoragePath: string
@@ -176,7 +176,7 @@ export class TaskOrganizationStore {
176176
const revisionAtCallTime = this.state.revision
177177
const requestId =
178178
"requestId" in mutation && typeof (mutation as Record<string, unknown>).requestId === "string"
179-
? (mutation as Record<string, unknown>).requestId as string
179+
? ((mutation as Record<string, unknown>).requestId as string)
180180
: ""
181181

182182
try {
@@ -267,8 +267,11 @@ export class TaskOrganizationStore {
267267
this.state = createEmptyTaskOrganizationState(this.now)
268268
return
269269
}
270+
// Transient read errors (e.g. the watcher firing while our own
271+
// temp+rename write replaces the file) must not wipe the in-memory
272+
// state: resetting to empty would make the next mutation compute
273+
// from an empty aggregate and fail to save.
270274
console.error("[TaskOrganizationStore] Failed to read organization file:", err)
271-
this.state = createEmptyTaskOrganizationState(this.now)
272275
return
273276
}
274277

@@ -314,8 +317,10 @@ export class TaskOrganizationStore {
314317
if (current && current.schemaVersion > 1) {
315318
throw this.createError("TASK_ORG/FUTURE_SCHEMA/007", "Organization data is from a newer version.")
316319
}
317-
if (current && current.revision > next.revision) {
318-
// Another process wrote a newer revision while we held the lock.
320+
if (current && current.revision >= next.revision) {
321+
// Another process wrote the same or a newer revision while we
322+
// held the lock. Same-revision writes lose: two processes that
323+
// both computed `next` from the same base must not both commit.
319324
throw this.createError("TASK_ORG/PERSISTENCE/005", "Concurrent modification detected.")
320325
}
321326
return next
@@ -871,9 +876,12 @@ export class TaskOrganizationStore {
871876
}
872877

873878
private async reloadFromWatcher(): Promise<void> {
874-
const previousRevision = this.state.revision
879+
const previous = this.state
875880
await this.load()
876-
if (this.state.revision > previousRevision && this.onChange) {
881+
// Notify on any actual content change, not just a revision increase:
882+
// a same-revision overwrite (lost update from another process)
883+
// changes the aggregate without bumping its revision.
884+
if (this.stateHasChanged(previous, this.state) && this.onChange) {
877885
await this.onChange(this.getState())
878886
}
879887
}

‎src/core/task-persistence/__tests__/TaskOrganizationStore.spec.ts‎

Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -714,5 +714,138 @@ describe("TaskOrganizationStore", () => {
714714
expect(successful).toHaveLength(5)
715715
expect(successful.map((result) => result.committedRevision)).toEqual([1, 2, 3, 4, 5])
716716
})
717+
718+
describe("cross-process writes", () => {
719+
it("rejects a same-revision write from another instance (lost update)", async () => {
720+
await store.initialize()
721+
// A second instance sharing the same backing file.
722+
const other = new TaskOrganizationStore(tmpDir, { taskHistory: history, now: () => 1000 })
723+
await other.initialize()
724+
725+
const first = await store.mutate(
726+
{
727+
kind: "createFolder",
728+
folderId: "folder-a",
729+
name: "A",
730+
source: { kind: "task", taskId: "t1" },
731+
destination: { kind: "task", taskId: "t2" },
732+
},
733+
0,
734+
)
735+
expect(first.success).toBe(true)
736+
737+
// `other` still holds revision 0 in memory and computes next = 1,
738+
// the same revision the first instance just committed.
739+
const second = await other.mutate(
740+
{
741+
kind: "createFolder",
742+
folderId: "folder-b",
743+
name: "B",
744+
source: { kind: "task", taskId: "t3" },
745+
destination: { kind: "task", taskId: "t4" },
746+
},
747+
0,
748+
)
749+
expect(second.success).toBe(false)
750+
expect(second.error?.code).toBe("TASK_ORG/PERSISTENCE/005")
751+
752+
// The first instance's write must survive on disk.
753+
const raw = JSON.parse(
754+
await fs.readFile(path.join(tmpDir, "tasks", GlobalFileNames.taskOrganization), "utf8"),
755+
)
756+
expect(raw.folders.map((f: { folderId: string }) => f.folderId)).toEqual(["folder-a"])
757+
758+
other.dispose()
759+
})
760+
})
761+
762+
describe("watcher reload resilience", () => {
763+
it("keeps in-memory state on transient read errors", async () => {
764+
await store.initialize()
765+
await store.mutate(
766+
{
767+
kind: "createFolder",
768+
folderId: "folder-1",
769+
name: "A",
770+
source: { kind: "task", taskId: "t1" },
771+
destination: { kind: "task", taskId: "t2" },
772+
},
773+
0,
774+
)
775+
expect(store.getState().revision).toBe(1)
776+
777+
// Simulate a transient read failure (e.g. the watcher firing while a
778+
// temp+rename write replaces the file): swap the file for a
779+
// directory so readFile rejects with a non-ENOENT error.
780+
const filePath = path.join(tmpDir, "tasks", GlobalFileNames.taskOrganization)
781+
await fs.rm(filePath)
782+
await fs.mkdir(filePath)
783+
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {})
784+
try {
785+
await store["reloadFromWatcher"]()
786+
} finally {
787+
errorSpy.mockRestore()
788+
await fs.rmdir(filePath)
789+
}
790+
791+
// The loaded state must survive; the next mutation computes from it.
792+
expect(store.getState().revision).toBe(1)
793+
expect(store.getState().folders).toHaveLength(1)
794+
const result = await store.mutate(
795+
{ kind: "setPinned", target: { kind: "task", taskId: "t9" }, pinned: true },
796+
1,
797+
)
798+
expect(result.success).toBe(true)
799+
expect(result.committedRevision).toBe(2)
800+
})
801+
802+
it("fires onChange when reloaded content differs at the same revision", async () => {
803+
const onChange = vi.fn()
804+
const watched = new TaskOrganizationStore(tmpDir, { taskHistory: history, now: () => 1000, onChange })
805+
await watched.initialize()
806+
await watched.mutate(
807+
{
808+
kind: "createFolder",
809+
folderId: "folder-1",
810+
name: "A",
811+
source: { kind: "task", taskId: "t1" },
812+
destination: { kind: "task", taskId: "t2" },
813+
},
814+
0,
815+
)
816+
onChange.mockClear()
817+
818+
// Simulate another process overwriting the file with different
819+
// content at the SAME revision (a lost update).
820+
const filePath = path.join(tmpDir, "tasks", GlobalFileNames.taskOrganization)
821+
const diverged = watched.getState()
822+
diverged.folders = [
823+
{ folderId: "folder-other", name: "Other", taskIds: ["t9"], createdAt: 1000, updatedAt: 1000 },
824+
]
825+
await fs.writeFile(filePath, JSON.stringify(diverged), "utf8")
826+
827+
await watched["reloadFromWatcher"]()
828+
829+
expect(onChange).toHaveBeenCalledTimes(1)
830+
expect(onChange).toHaveBeenCalledWith(expect.objectContaining({ revision: 1 }))
831+
expect(watched.getState().folders[0].folderId).toBe("folder-other")
832+
watched.dispose()
833+
})
834+
835+
it("does not fire onChange when the reloaded content is identical", async () => {
836+
const onChange = vi.fn()
837+
const watched = new TaskOrganizationStore(tmpDir, { taskHistory: history, now: () => 1000, onChange })
838+
await watched.initialize()
839+
await watched.mutate({ kind: "setPinned", target: { kind: "task", taskId: "t1" }, pinned: true }, 0)
840+
onChange.mockClear()
841+
842+
// A watcher reload of unchanged content (e.g. our own write's event)
843+
// must not notify again.
844+
await watched["reloadFromWatcher"]()
845+
846+
expect(onChange).not.toHaveBeenCalled()
847+
watched.dispose()
848+
})
849+
})
717850
})
718851
})

‎src/core/webview/ClineProvider.ts‎

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,14 @@ export class ClineProvider
252252
// Reconcile organization state after task history changes (deletion,
253253
// new child, etc.). Failures are logged but do not block history writes.
254254
try {
255-
await this.taskOrganizationStore.reconcile()
255+
// The organization store is assigned immediately after the
256+
// history store below; a history write landing in that
257+
// window must not throw a TypeError dereferencing the
258+
// not-yet-assigned field.
259+
const organizationStore: TaskOrganizationStore | undefined = this.taskOrganizationStore
260+
if (organizationStore) {
261+
await organizationStore.reconcile()
262+
}
256263
} catch (error) {
257264
this.log(
258265
`[TaskHistoryStore.onWrite] Task organization reconciliation failed: ${

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

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -847,4 +847,37 @@ describe("ClineProvider Task History Synchronization", () => {
847847
expect(logSpy).toHaveBeenCalledWith(expect.stringContaining("[onTaskCompleted] Failed to write"))
848848
})
849849
})
850+
describe("taskHistoryStore onWrite reconciliation", () => {
851+
const getOnWrite = () => {
852+
const onWrite = provider.taskHistoryStore["onWrite"]
853+
expect(onWrite).toBeDefined()
854+
return onWrite!
855+
}
856+
857+
it("reconciles the organization store after a history write", async () => {
858+
const reconcileSpy = vi.spyOn(provider.taskOrganizationStore, "reconcile").mockResolvedValue(undefined)
859+
860+
await getOnWrite()([])
861+
862+
expect(reconcileSpy).toHaveBeenCalledTimes(1)
863+
})
864+
865+
it("skips reconciliation without logging a failure when the organization store is not yet assigned", async () => {
866+
// Simulate the constructor-order window in which TaskHistoryStore
867+
// exists but taskOrganizationStore has not been assigned yet.
868+
const appendLineSpy = vi.spyOn(mockOutputChannel, "appendLine")
869+
const original = provider.taskOrganizationStore
870+
Object.assign(provider, { taskOrganizationStore: undefined })
871+
try {
872+
await getOnWrite()([])
873+
} finally {
874+
Object.assign(provider, { taskOrganizationStore: original })
875+
}
876+
877+
const reconciliationFailures = appendLineSpy.mock.calls.filter((call) =>
878+
String(call[0]).includes("Task organization reconciliation failed"),
879+
)
880+
expect(reconciliationFailures).toHaveLength(0)
881+
})
882+
})
850883
})

0 commit comments

Comments
 (0)