Skip to content

Commit 1d993fb

Browse files
Merge upstream/main (a0d03a0) into fws/u7-tool-wiring
The only conflicted path was src/core/tools/ApplyDiffTool.ts, and it conflicted in the import block: this branch added versionTokenOfStat for the read/observe authorization, upstream 1b9cb7d added isPathOutsideWorkspace for the outside-workspace auto-approve guard. Both imports are kept and both semantics survive in the merged file - upstream's isOutsideWorkspace flag on the appliedDiff payload (:184/:190 and :386/:392) and this branch's version-token authorization (:96-:118). No assertion was deleted to make the merge apply. applyDiffTool.outsideWorkspace.spec.ts came in from upstream with a Task double that predates this branch's tool: it carries only the members main's tool read. The merged tool also stats around its own read and consults the observation registry, so the double now carries stat and observationRegistry too. That is setup only - every row and every assertion in that file is untouched, and all 58 tests across the three applyDiff suites pass on the merged tree. Controls, both run against the merged tree and both reverted: forcing the payload flag to false takes outsideWorkspace.spec.ts to 6 failed (upstream's semantic is pinned), and skipping the stat-around-read block takes failureReporting/guardedWrite to 1 failed (this branch's semantic is pinned). eslint --max-warnings=0 and prettier --check are exit 0 on every file the merge touched, tsc --noEmit -p tsconfig.json is exit 0 on the merged tree, and the suppression records did not rise (265 file records and a summed count of 2866 on this merge, against 2868 on main).
2 parents dc4c848 + a0d03a0 commit 1d993fb

12 files changed

Lines changed: 755 additions & 123 deletions

‎.github/workflows/code-qa.yml‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,11 @@ jobs:
247247
- name: Verify coverage cache inputs
248248
if: matrix.collect-coverage
249249
run: pnpm --dir src run verify:coverage-cache-inputs
250+
# Validate build/static cache inputs (issue #2290 contract) so a
251+
# stale webview or extension bundle is never restored as a hit.
252+
- name: Verify build cache inputs
253+
if: matrix.collect-coverage
254+
run: pnpm --dir src run verify:build-cache-inputs
250255
- name: Save Turbo cache
251256
if: steps.turbo-cache.outputs.cache-hit != 'true'
252257
uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0

‎src/core/tools/ApplyDiffTool.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { type ClineSayTool, DEFAULT_WRITE_DELAY_MS } from "@roo-code/types"
55
import { TelemetryService } from "@roo-code/telemetry"
66

77
import { getReadablePath } from "../../utils/path"
8+
import { isPathOutsideWorkspace } from "../../utils/pathUtils"
89
import { versionTokenOfStat } from "../../utils/versionToken"
910
import { Task } from "../task/Task"
1011
import { formatResponse } from "../prompts/responses"
@@ -180,11 +181,13 @@ export class ApplyDiffTool extends BaseTool<"apply_diff"> {
180181

181182
// Check if file is write-protected
182183
const isWriteProtected = task.rooProtectedController?.isWriteProtected(relPath) || false
184+
const isOutsideWorkspace = isPathOutsideWorkspace(absolutePath)
183185

184186
const sharedMessageProps: ClineSayTool = {
185187
tool: "appliedDiff",
186188
path: getReadablePath(task.cwd, relPath),
187189
diff: diffContent,
190+
isOutsideWorkspace,
188191
}
189192

190193
if (isPreventFocusDisruptionEnabled) {
@@ -379,10 +382,14 @@ export class ApplyDiffTool extends BaseTool<"apply_diff"> {
379382
return
380383
}
381384

385+
// relPath is guaranteed non-null after hasPathStabilized
386+
const absolutePath = path.resolve(task.cwd, relPath!)
387+
382388
const sharedMessageProps: ClineSayTool = {
383389
tool: "appliedDiff",
384390
path: getReadablePath(task.cwd, relPath),
385391
diff: diffContent,
392+
isOutsideWorkspace: isPathOutsideWorkspace(absolutePath),
386393
}
387394

388395
let toolProgressStatus

‎src/core/tools/__tests__/applyDiffTool.failureReporting.spec.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,10 @@ vi.mock("../../../utils/path", () => ({
3636
getReadablePath: vi.fn().mockReturnValue("test/file.txt"),
3737
}))
3838

39+
vi.mock("../../../utils/pathUtils", () => ({
40+
isPathOutsideWorkspace: vi.fn().mockReturnValue(false),
41+
}))
42+
3943
vi.mock("../../prompts/responses", () => ({
4044
formatResponse: {
4145
toolError: vi.fn((message: string) => `Error: ${message}`),
Lines changed: 253 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,253 @@
1+
// npx vitest run core/tools/__tests__/applyDiffTool.outsideWorkspace.spec.ts
2+
3+
import fs from "fs/promises"
4+
import path from "path"
5+
6+
import type { ClineSayTool } from "@roo-code/types"
7+
8+
import type { ToolUse } from "../../../shared/tools"
9+
import { isPathOutsideWorkspace } from "../../../utils/pathUtils"
10+
import { checkAutoApproval } from "../../auto-approval"
11+
import { baseState } from "../../auto-approval/__tests__/fixtures"
12+
import type { Task } from "../../task/Task"
13+
import type { ToolCallbacks } from "../BaseTool"
14+
import { applyDiffTool } from "../ApplyDiffTool"
15+
16+
vi.mock("@roo-code/telemetry", () => ({
17+
TelemetryService: { instance: { captureDiffApplicationError: vi.fn() } },
18+
}))
19+
20+
vi.mock("fs/promises", () => ({
21+
default: {
22+
readFile: vi.fn(),
23+
// apply_diff stats around its own read (this branch's read/observe authorization, the
24+
// same contract as ApplyPatchTool's hunk read). Without this double the stat call is
25+
// undefined and every run below lands in handleError instead of reaching the approval
26+
// the rows assert on. No row and no assertion below is changed by this.
27+
stat: vi.fn().mockResolvedValue({
28+
dev: 7n,
29+
ino: 4242n,
30+
size: 1234n,
31+
mtimeNs: 1_700_000_000_123_456_789n,
32+
ctimeNs: 1_700_000_000_789_999_999n,
33+
}),
34+
},
35+
}))
36+
37+
vi.mock("../../../utils/fs", () => ({
38+
fileExistsAtPath: vi.fn().mockResolvedValue(true),
39+
}))
40+
41+
vi.mock("../../../utils/path", () => ({
42+
getReadablePath: vi.fn((_cwd: string, relPath?: string) => relPath ?? ""),
43+
}))
44+
45+
vi.mock("../../../utils/pathUtils", () => ({
46+
isPathOutsideWorkspace: vi.fn(),
47+
}))
48+
49+
vi.mock("../../prompts/responses", () => ({
50+
formatResponse: {
51+
toolError: vi.fn((message: string) => `Error: ${message}`),
52+
rooIgnoreError: vi.fn((filePath: string) => `Access denied: ${filePath}`),
53+
createPrettyPatch: vi.fn(() => "mock-diff"),
54+
},
55+
}))
56+
57+
vi.mock("../../diff/stats", () => ({
58+
sanitizeUnifiedDiff: vi.fn((diff: string) => diff),
59+
computeDiffStats: vi.fn(() => ({ additions: 1, deletions: 1 })),
60+
}))
61+
62+
vi.mock("vscode", () => ({
63+
window: { showWarningMessage: vi.fn() },
64+
env: { openExternal: vi.fn() },
65+
Uri: { parse: vi.fn() },
66+
workspace: {
67+
get workspaceFolders() {
68+
return [{ uri: { fsPath: path.resolve(CWD) } }]
69+
},
70+
},
71+
}))
72+
73+
const CWD = "/workspace"
74+
const INSIDE_PATH = "src/index.ts"
75+
const OUTSIDE_PATH = "/home/me/.zshrc"
76+
const DIFF = "<<<<<<< SEARCH\nold\n=======\nnew\n>>>>>>> REPLACE"
77+
78+
const cases = [
79+
{ name: "a file outside the workspace", relPath: OUTSIDE_PATH, isOutside: true },
80+
{ name: "a file inside the workspace", relPath: INSIDE_PATH, isOutside: false },
81+
]
82+
83+
const approvalPaths = [
84+
{ name: "diff view", preventFocusDisruption: false },
85+
{ name: "preventFocusDisruption", preventFocusDisruption: true },
86+
]
87+
88+
describe("ApplyDiffTool isOutsideWorkspace", () => {
89+
let askApproval: ReturnType<typeof vi.fn<ToolCallbacks["askApproval"]>>
90+
91+
function createTask(preventFocusDisruption = false): Task {
92+
const task = {
93+
cwd: CWD,
94+
consecutiveMistakeCount: 0,
95+
consecutiveMistakeCountForApplyDiff: new Map<string, number>(),
96+
didEditFile: false,
97+
api: { getModel: () => ({ id: "claude-test" }) },
98+
rooIgnoreController: { validateAccess: vi.fn().mockReturnValue(true) },
99+
rooProtectedController: { isWriteProtected: vi.fn().mockReturnValue(false) },
100+
providerRef: {
101+
deref: vi.fn().mockReturnValue({
102+
getState: vi.fn().mockResolvedValue({
103+
diagnosticsEnabled: false,
104+
writeDelayMs: 0,
105+
experiments: { preventFocusDisruption },
106+
}),
107+
}),
108+
},
109+
// The merged tool consults the observation registry during its pre-save authorization,
110+
// so the double has to carry it. No row below asserts on it.
111+
observationRegistry: {
112+
get: vi.fn().mockReturnValue(undefined),
113+
observe: vi.fn(),
114+
},
115+
diffStrategy: {
116+
getName: () => "test",
117+
applyDiff: vi.fn().mockResolvedValue({ success: true, content: "new\n" }),
118+
},
119+
diffViewProvider: {
120+
editType: undefined,
121+
originalContent: "",
122+
open: vi.fn().mockResolvedValue(undefined),
123+
update: vi.fn().mockResolvedValue(undefined),
124+
reset: vi.fn().mockResolvedValue(undefined),
125+
revertChanges: vi.fn().mockResolvedValue(undefined),
126+
saveChanges: vi.fn().mockResolvedValue(undefined),
127+
saveDirectly: vi.fn().mockResolvedValue(undefined),
128+
scrollToFirstDiff: vi.fn(),
129+
pushToolWriteResult: vi.fn().mockResolvedValue("Changes successfully applied."),
130+
},
131+
fileContextTracker: { trackFileContext: vi.fn().mockResolvedValue(undefined) },
132+
say: vi.fn().mockResolvedValue(undefined),
133+
ask: vi.fn().mockResolvedValue(undefined),
134+
recordToolError: vi.fn(),
135+
processQueuedMessages: vi.fn(),
136+
sayAndCreateMissingParamError: vi.fn().mockResolvedValue("Missing param error"),
137+
}
138+
// The double provides only the Task members that ApplyDiffTool.execute and handlePartial read.
139+
return task as unknown as Task
140+
}
141+
142+
async function runExecute(relPath: string, isOutside: boolean, preventFocusDisruption = false): Promise<string> {
143+
vi.mocked(isPathOutsideWorkspace).mockReturnValue(isOutside)
144+
145+
await applyDiffTool.execute({ path: relPath, diff: DIFF }, createTask(preventFocusDisruption), {
146+
askApproval,
147+
handleError: vi.fn().mockResolvedValue(undefined),
148+
pushToolResult: vi.fn(),
149+
toolCallId: "tool-call-1",
150+
})
151+
152+
expect(askApproval).toHaveBeenCalledTimes(1)
153+
return String(askApproval.mock.calls[0][1])
154+
}
155+
156+
beforeEach(() => {
157+
vi.clearAllMocks()
158+
vi.mocked(isPathOutsideWorkspace).mockReset()
159+
applyDiffTool.resetPartialState()
160+
vi.mocked(fs.readFile).mockResolvedValue("old\n")
161+
askApproval = vi.fn<ToolCallbacks["askApproval"]>().mockResolvedValue(true)
162+
})
163+
164+
describe.each(approvalPaths)("approval payload ($name)", ({ preventFocusDisruption }) => {
165+
it.each(cases)("reports isOutsideWorkspace for $name", async ({ relPath, isOutside }) => {
166+
const payload = JSON.parse(await runExecute(relPath, isOutside, preventFocusDisruption)) as ClineSayTool
167+
168+
expect(isPathOutsideWorkspace).toHaveBeenCalledWith(path.resolve(CWD, relPath))
169+
expect(payload.tool).toBe("appliedDiff")
170+
expect(payload.isOutsideWorkspace).toBe(isOutside)
171+
})
172+
})
173+
174+
it.each(cases)("reports isOutsideWorkspace in the partial preview for $name", async ({ relPath, isOutside }) => {
175+
vi.mocked(isPathOutsideWorkspace).mockReturnValue(isOutside)
176+
const task = createTask()
177+
const block: ToolUse<"apply_diff"> = {
178+
type: "tool_use",
179+
name: "apply_diff",
180+
params: { path: relPath, diff: DIFF },
181+
partial: true,
182+
}
183+
184+
// The first call records the path; the second call sees it stable and asks.
185+
await applyDiffTool.handlePartial(task, block)
186+
await applyDiffTool.handlePartial(task, block)
187+
188+
expect(task.ask).toHaveBeenCalledTimes(1)
189+
const payload = JSON.parse(String(vi.mocked(task.ask).mock.calls[0][1])) as ClineSayTool
190+
expect(isPathOutsideWorkspace).toHaveBeenCalledWith(path.resolve(CWD, relPath))
191+
expect(payload.isOutsideWorkspace).toBe(isOutside)
192+
})
193+
194+
describe("with the real workspace check", () => {
195+
it.each([
196+
{
197+
name: "a ../ path that resolves outside",
198+
relPath: "../outside/config.json",
199+
isOutside: true,
200+
expected: "ask",
201+
},
202+
{ name: "a path inside", relPath: "src/index.ts", isOutside: false, expected: "approve" },
203+
])("marks $name the workspace and returns $expected", async ({ relPath, isOutside, expected }) => {
204+
const actual = await vi.importActual<typeof import("../../../utils/pathUtils")>("../../../utils/pathUtils")
205+
vi.mocked(isPathOutsideWorkspace).mockImplementation(actual.isPathOutsideWorkspace)
206+
207+
await applyDiffTool.execute({ path: relPath, diff: DIFF }, createTask(), {
208+
askApproval,
209+
handleError: vi.fn().mockResolvedValue(undefined),
210+
pushToolResult: vi.fn(),
211+
toolCallId: "tool-call-1",
212+
})
213+
214+
const text = String(askApproval.mock.calls[0][1])
215+
const payload = JSON.parse(text) as ClineSayTool
216+
expect(payload.isOutsideWorkspace).toBe(isOutside)
217+
218+
const result = await checkAutoApproval({
219+
state: { ...baseState, alwaysAllowWrite: true },
220+
cwd: CWD,
221+
ask: "tool",
222+
text,
223+
})
224+
expect(result).toEqual({ decision: expected })
225+
})
226+
})
227+
228+
describe("auto-approval decision with alwaysAllowWrite on", () => {
229+
it.each([
230+
{ ...cases[0], allowOutside: false, expected: "ask" },
231+
{ ...cases[0], allowOutside: true, expected: "approve" },
232+
{ ...cases[1], allowOutside: false, expected: "approve" },
233+
])(
234+
"returns $expected for $name when alwaysAllowWriteOutsideWorkspace is $allowOutside",
235+
async ({ relPath, isOutside, allowOutside, expected }) => {
236+
const text = await runExecute(relPath, isOutside)
237+
238+
const result = await checkAutoApproval({
239+
state: {
240+
...baseState,
241+
alwaysAllowWrite: true,
242+
alwaysAllowWriteOutsideWorkspace: allowOutside,
243+
},
244+
cwd: CWD,
245+
ask: "tool",
246+
text,
247+
})
248+
249+
expect(result).toEqual({ decision: expected })
250+
},
251+
)
252+
})
253+
})

‎src/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -454,6 +454,7 @@
454454
"test": "vitest run",
455455
"verify:coverage-contract": "node scripts/verify-coverage-contract.mjs",
456456
"verify:coverage-cache-inputs": "node --test scripts/verify-coverage-cache-inputs.mjs",
457+
"verify:build-cache-inputs": "node --test scripts/verify-cache-probe.mjs scripts/verify-build-cache-inputs.mjs",
457458
"merge:coverage": "node scripts/merge-lcov.mjs coverage/merged/lcov.info coverage/api/lcov.info coverage/core/lcov.info coverage/services/lcov.info coverage/misc/lcov.info coverage/tree-sitter/lcov.info",
458459
"test:unit": "vitest run --config vitest.unit.config.ts",
459460
"test:dist": "vitest run --config vitest.dist.config.ts",

0 commit comments

Comments
 (0)