Skip to content

Commit d130eb1

Browse files
committed
fix(diagnostics): address review feedback on error recording and memory use
1 parent d930b12 commit d130eb1

4 files changed

Lines changed: 116 additions & 60 deletions

File tree

‎src/services/diagnostics/__tests__/persistence.spec.ts‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,8 @@ import type { HistoryItem } from "@roo-code/types"
66

77
import { collectPersistenceDiagnostics } from "../persistence"
88

9+
vi.mock("fs/promises", { spy: true })
10+
911
describe("collectPersistenceDiagnostics", () => {
1012
let storagePath: string
1113

@@ -14,6 +16,7 @@ describe("collectPersistenceDiagnostics", () => {
1416
})
1517

1618
afterEach(async () => {
19+
vi.restoreAllMocks()
1720
await fs.rm(storagePath, { recursive: true, force: true })
1821
})
1922

@@ -74,6 +77,52 @@ describe("collectPersistenceDiagnostics", () => {
7477
expect(serialized).not.toContain("raw-child-id")
7578
})
7679

80+
it("reads task files sequentially across the delegation tree", async () => {
81+
const history: HistoryItem[] = Array.from({ length: 10 }, (_, index) => ({
82+
id: `task-${index}`,
83+
number: index,
84+
ts: index,
85+
task: "not reported",
86+
tokensIn: 0,
87+
tokensOut: 0,
88+
totalCost: 0,
89+
childIds: index === 0 ? Array.from({ length: 9 }, (_, child) => `task-${child + 1}`) : [],
90+
}))
91+
for (const item of history) {
92+
const taskPath = path.join(storagePath, "tasks", item.id)
93+
await fs.mkdir(taskPath, { recursive: true })
94+
await fs.writeFile(path.join(taskPath, "history_item.json"), JSON.stringify(item))
95+
await fs.writeFile(path.join(taskPath, "ui_messages.json"), JSON.stringify([{ ts: 10 }, { ts: 20 }]))
96+
}
97+
98+
const { readFile } = await vi.importActual<typeof fs>("fs/promises")
99+
let activeReads = 0
100+
let maxActiveReads = 0
101+
const readSpy = vi.spyOn(fs, "readFile").mockImplementation(async (...args: Parameters<typeof fs.readFile>) => {
102+
activeReads++
103+
maxActiveReads = Math.max(maxActiveReads, activeReads)
104+
try {
105+
await new Promise((resolve) => setTimeout(resolve, 5))
106+
return await readFile(...args)
107+
} finally {
108+
activeReads--
109+
}
110+
})
111+
112+
readSpy.mockClear()
113+
const result = await collectPersistenceDiagnostics({
114+
storagePath,
115+
history,
116+
currentTaskIds: ["task-0"],
117+
pseudonymize: (value) => value,
118+
})
119+
120+
expect(readSpy).toHaveBeenCalledTimes(20)
121+
expect(maxActiveReads).toBe(1)
122+
expect(result.tasks).toHaveLength(10)
123+
expect(result.tasks.every((task) => task.uiMessages.messageCount === 2)).toBe(true)
124+
})
125+
77126
it("reports corrupt and missing files without throwing", async () => {
78127
const history: HistoryItem[] = [
79128
{

‎src/services/diagnostics/persistence.ts‎

Lines changed: 41 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -123,54 +123,47 @@ export async function collectPersistenceDiagnostics(options: {
123123
}
124124
const indexIds = new Set(indexEntries?.filter(isHistoryItem).map((item) => item.id) ?? [])
125125

126-
const tasks = await Promise.all(
127-
relevant.map(async (item) => {
128-
const taskPath = path.join(tasksPath, item.id)
129-
const [historyItemResult, uiMessagesResult] = await Promise.all([
130-
inspectJson(path.join(taskPath, GlobalFileNames.historyItem)),
131-
inspectJson(path.join(taskPath, GlobalFileNames.uiMessages)),
132-
])
133-
const messages = Array.isArray(uiMessagesResult.value) ? uiMessagesResult.value : undefined
134-
const timestamps = (messages ?? [])
135-
.map((message) =>
136-
message !== null && typeof message === "object" && "ts" in message && typeof message.ts === "number"
137-
? message.ts
138-
: undefined,
139-
)
140-
.filter((timestamp): timestamp is number => timestamp !== undefined)
141-
const findings: string[] = []
142-
for (const related of [
143-
item.rootTaskId,
144-
item.parentTaskId,
145-
item.awaitingChildId,
146-
...(item.childIds ?? []),
147-
]) {
148-
if (related && !byId.has(related)) findings.push("missingReferencedTask")
149-
}
150-
if (item.awaitingChildId && item.status !== "delegated") findings.push("awaitingChildStatusMismatch")
151-
if (item.parentTaskId && !byId.get(item.parentTaskId)?.childIds?.includes(item.id)) {
152-
findings.push("parentChildMismatch")
153-
}
154-
if (hasParentCycle(item, byId)) findings.push("parentCycle")
155-
156-
return {
157-
id: pseudonymize(item.id),
158-
rootTask: item.rootTaskId ? pseudonymize(item.rootTaskId) : undefined,
159-
parentTask: item.parentTaskId ? pseudonymize(item.parentTaskId) : undefined,
160-
children: (item.childIds ?? []).slice(0, MAX_TASKS).map(pseudonymize),
161-
status: item.status,
162-
number: item.number,
163-
historyItem: historyItemResult.inspection,
164-
uiMessages: {
165-
...uiMessagesResult.inspection,
166-
messageCount: messages?.length,
167-
firstTimestamp: timestamps[0],
168-
lastTimestamp: timestamps.at(-1),
169-
},
170-
integrityFindings: Array.from(new Set(findings)),
171-
}
172-
}),
173-
)
126+
// Inspect sequentially to avoid retaining parsed histories for multiple tasks.
127+
const tasks: DiagnosticsPersistenceReport["tasks"] = []
128+
for (const item of relevant) {
129+
const taskPath = path.join(tasksPath, item.id)
130+
const historyItemResult = await inspectJson(path.join(taskPath, GlobalFileNames.historyItem))
131+
const uiMessagesResult = await inspectJson(path.join(taskPath, GlobalFileNames.uiMessages))
132+
const messages = Array.isArray(uiMessagesResult.value) ? uiMessagesResult.value : undefined
133+
const timestamps = (messages ?? [])
134+
.map((message) =>
135+
message !== null && typeof message === "object" && "ts" in message && typeof message.ts === "number"
136+
? message.ts
137+
: undefined,
138+
)
139+
.filter((timestamp): timestamp is number => timestamp !== undefined)
140+
const findings: string[] = []
141+
for (const related of [item.rootTaskId, item.parentTaskId, item.awaitingChildId, ...(item.childIds ?? [])]) {
142+
if (related && !byId.has(related)) findings.push("missingReferencedTask")
143+
}
144+
if (item.awaitingChildId && item.status !== "delegated") findings.push("awaitingChildStatusMismatch")
145+
if (item.parentTaskId && !byId.get(item.parentTaskId)?.childIds?.includes(item.id)) {
146+
findings.push("parentChildMismatch")
147+
}
148+
if (hasParentCycle(item, byId)) findings.push("parentCycle")
149+
150+
tasks.push({
151+
id: pseudonymize(item.id),
152+
rootTask: item.rootTaskId ? pseudonymize(item.rootTaskId) : undefined,
153+
parentTask: item.parentTaskId ? pseudonymize(item.parentTaskId) : undefined,
154+
children: (item.childIds ?? []).slice(0, MAX_TASKS).map(pseudonymize),
155+
status: item.status,
156+
number: item.number,
157+
historyItem: historyItemResult.inspection,
158+
uiMessages: {
159+
...uiMessagesResult.inspection,
160+
messageCount: messages?.length,
161+
firstTimestamp: timestamps[0],
162+
lastTimestamp: timestamps.at(-1),
163+
},
164+
integrityFindings: Array.from(new Set(findings)),
165+
})
166+
}
174167

175168
return {
176169
cacheEntryCount: history.length,

‎webview-ui/src/__tests__/ErrorBoundary.spec.tsx‎

Lines changed: 25 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import React from "react"
22
import { render, screen } from "@testing-library/react"
33
import ErrorBoundary from "../components/ErrorBoundary"
4+
import { recordDiagnosticsError } from "@src/utils/diagnostics"
45
import { EXTERNAL_LINKS } from "../constants/externalLinks"
56

67
// Mock telemetry client
@@ -10,19 +11,18 @@ vi.mock("@src/utils/TelemetryClient", () => ({
1011
},
1112
}))
1213

13-
// Mock translation function
14-
vi.mock("react-i18next", () => {
15-
const tFunction = (key: string) => key
16-
return {
17-
withTranslation: () => (Component: any) => {
18-
const MockedComponent = (props: any) => {
19-
return <Component t={tFunction} i18n={{ t: tFunction }} tReady {...props} />
20-
}
21-
MockedComponent.displayName = `withTranslation(${Component.displayName || Component.name || "Component"})`
14+
vi.mock("react-i18next", () => ({
15+
withTranslation:
16+
() => (Component: React.ComponentType<{ children: React.ReactNode; t: (key: string) => string }>) => {
17+
const MockedComponent = (props: { children: React.ReactNode }) => <Component {...props} t={(key) => key} />
2218
return MockedComponent
2319
},
24-
}
25-
})
20+
}))
21+
22+
vi.mock("@src/utils/diagnostics", () => ({ recordDiagnosticsError: vi.fn() }))
23+
vi.mock("@src/utils/sourceMapUtils", () => ({
24+
enhanceErrorWithSourceMaps: vi.fn(async (error: Error) => error),
25+
}))
2626

2727
// Test component that can throw errors on demand
2828
const ErrorThrower = ({ shouldThrow = false, message = "Test error" }: { shouldThrow?: boolean; message?: string }) => {
@@ -36,6 +36,7 @@ describe("ErrorBoundary", () => {
3636
// Suppress console errors during tests
3737
beforeEach(() => {
3838
vi.spyOn(console, "error").mockImplementation(() => {})
39+
vi.mocked(recordDiagnosticsError).mockClear()
3940
})
4041

4142
afterEach(() => {
@@ -53,6 +54,19 @@ describe("ErrorBoundary", () => {
5354
expect(screen.getByText("Test Content")).toBeInTheDocument()
5455
})
5556

57+
it("records a caught error once under StrictMode", () => {
58+
render(
59+
<React.StrictMode>
60+
<ErrorBoundary>
61+
<ErrorThrower shouldThrow message="StrictMode error" />
62+
</ErrorBoundary>
63+
</React.StrictMode>,
64+
)
65+
66+
expect(recordDiagnosticsError).toHaveBeenCalledTimes(1)
67+
expect(recordDiagnosticsError).toHaveBeenCalledWith("errorBoundary", expect.any(Error))
68+
})
69+
5670
it("renders error UI when a child component throws", () => {
5771
vi.stubEnv("PKG_VERSION", "1.2.3")
5872

‎webview-ui/src/components/ErrorBoundary.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@ class ErrorBoundary extends Component<ErrorProps, ErrorState> {
2222
}
2323

2424
static getDerivedStateFromError(error: unknown) {
25-
recordDiagnosticsError("errorBoundary", error)
2625
let errorMessage = ""
2726

2827
if (error instanceof Error) {
@@ -38,6 +37,7 @@ class ErrorBoundary extends Component<ErrorProps, ErrorState> {
3837
}
3938

4039
async componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
40+
recordDiagnosticsError("errorBoundary", error)
4141
const componentStack = errorInfo.componentStack || ""
4242
const enhancedError = await enhanceErrorWithSourceMaps(error, componentStack)
4343

0 commit comments

Comments
 (0)