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
99 changes: 99 additions & 0 deletions sdk/src/__tests__/change-file.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,37 @@ describe('changeFile', () => {
)
})

test('tolerates absolute paths inside the project for string replacements', async () => {
const fs = createMockFs({
files: {
'/repo/src/file.ts': 'const value = 1\n',
},
})

const result = await changeFile({
parameters: {
type: 'patch',
path: '/repo/src/file.ts',
content: '@@ -1,1 +1,1 @@\n-const value = 1\n+const value = 2\n',
},
cwd: '/repo',
fs,
})

expect(result).toEqual([
{
type: 'json',
value: {
file: 'src/file.ts',
message: 'String replace applied successfully.',
},
},
])
expect(await fs.readFile('/repo/src/file.ts', 'utf-8')).toBe(
'const value = 2\n',
)
})

test('returns a simple success message for new file writes', async () => {
const fs = createMockFs()

Expand Down Expand Up @@ -63,6 +94,58 @@ describe('changeFile', () => {
)
})

test('tolerates absolute paths inside the project for file writes', async () => {
const fs = createMockFs()

const result = await changeFile({
parameters: {
type: 'file',
path: '/repo/src/file.ts',
content: 'const value = 1\n',
},
cwd: '/repo',
fs,
})

expect(result).toEqual([
{
type: 'json',
value: {
file: 'src/file.ts',
message: 'Created file successfully.',
},
},
])
expect(await fs.readFile('/repo/src/file.ts', 'utf-8')).toBe(
'const value = 1\n',
)
})

test('accepts paths whose file names start with two dots inside the project', async () => {
const fs = createMockFs()

const result = await changeFile({
parameters: {
type: 'file',
path: '/repo/..config',
content: 'value = true\n',
},
cwd: '/repo',
fs,
})

expect(result).toEqual([
{
type: 'json',
value: {
file: '..config',
message: 'Created file successfully.',
},
},
])
expect(await fs.readFile('/repo/..config', 'utf-8')).toBe('value = true\n')
})

test('returns a simple success message for overwritten file writes', async () => {
const fs = createMockFs({
files: {
Expand Down Expand Up @@ -93,4 +176,20 @@ describe('changeFile', () => {
'const value = 2\n',
)
})

test('rejects absolute paths outside the project', async () => {
const fs = createMockFs()

await expect(
changeFile({
parameters: {
type: 'file',
path: '/outside/file.ts',
content: 'const value = 1\n',
},
cwd: '/repo',
fs,
}),
).rejects.toThrow('file path is outside the project directory')
})
})
58 changes: 58 additions & 0 deletions sdk/src/__tests__/path-utils.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { describe, expect, test } from 'bun:test'

import {
getProjectPathLookupKeys,
resolveFilePathWithinProject,
} from '../tools/path-utils'

describe('resolveFilePathWithinProject', () => {
test('normalizes relative paths to full and project-relative paths', () => {
expect(resolveFilePathWithinProject('/repo', 'src/file.ts')).toEqual({
fullPath: '/repo/src/file.ts',
relativePath: 'src/file.ts',
})
})

test('normalizes absolute paths inside the project', () => {
expect(resolveFilePathWithinProject('/repo', '/repo/src/file.ts')).toEqual({
fullPath: '/repo/src/file.ts',
relativePath: 'src/file.ts',
})
})

test('allows file names that start with two dots inside the project', () => {
expect(resolveFilePathWithinProject('/repo', '/repo/..config')).toEqual({
fullPath: '/repo/..config',
relativePath: '..config',
})
})

test('rejects paths outside the project', () => {
expect(resolveFilePathWithinProject('/repo', '../outside.ts')).toBeNull()
expect(resolveFilePathWithinProject('/repo', '/outside.ts')).toBeNull()
expect(
resolveFilePathWithinProject('/repo', '/repo-sibling/file.ts'),
).toBeNull()
})
})

describe('getProjectPathLookupKeys', () => {
test('returns the normalized relative key before the original absolute key', () => {
expect(getProjectPathLookupKeys('/repo', '/repo/src/file.ts')).toEqual([
'src/file.ts',
'/repo/src/file.ts',
])
})

test('dedupes relative paths that are already normalized', () => {
expect(getProjectPathLookupKeys('/repo', 'src/file.ts')).toEqual([
'src/file.ts',
])
})

test('returns only the original key for paths outside the project', () => {
expect(getProjectPathLookupKeys('/repo', '/outside.ts')).toEqual([
'/outside.ts',
])
})
})
36 changes: 27 additions & 9 deletions sdk/src/__tests__/read-files.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,11 @@ import {
spyOn,
} from 'bun:test'


import { getFiles } from '../tools/read-files'

import type { CodebuffFileSystem } from '@codebuff/common/types/filesystem'
import type { PathLike } from 'node:fs'


// Helper to create a mock filesystem
function createMockFs(config: {
files?: Record<string, { content: string; size?: number }>
Expand Down Expand Up @@ -75,9 +73,10 @@ describe('getFiles', () => {

beforeEach(() => {
// Default: no files are ignored
isFileIgnoredSpy = spyOn(projectFileTree, 'isFileIgnored').mockResolvedValue(
false,
)
isFileIgnoredSpy = spyOn(
projectFileTree,
'isFileIgnored',
).mockResolvedValue(false)
})

afterEach(() => {
Expand Down Expand Up @@ -320,9 +319,7 @@ describe('getFiles', () => {

test('should handle mix of ignored and non-ignored files', async () => {
// First call returns false (not ignored), second returns true (ignored)
isFileIgnoredSpy
.mockResolvedValueOnce(false)
.mockResolvedValueOnce(true)
isFileIgnoredSpy.mockResolvedValueOnce(false).mockResolvedValueOnce(true)

const mockFs = createMockFs({
files: {
Expand Down Expand Up @@ -393,7 +390,10 @@ describe('getFiles', () => {
const mockFs = createMockFs({
files: {},
errors: {
'/project/broken.ts': { code: 'EACCES', message: 'Permission denied' },
'/project/broken.ts': {
code: 'EACCES',
message: 'Permission denied',
},
},
})

Expand Down Expand Up @@ -423,6 +423,24 @@ describe('getFiles', () => {

expect(result['src/index.ts']).toBe('content')
})

test('should reject absolute paths in sibling directories with matching prefixes', async () => {
const mockFs = createMockFs({
files: {
'/project-other/src/index.ts': { content: 'outside' },
},
})

const result = await getFiles({
filePaths: ['/project-other/src/index.ts'],
cwd: '/project',
fs: mockFs,
})

expect(result['/project-other/src/index.ts']).toBe(
FILE_READ_STATUS.OUTSIDE_PROJECT,
)
})
})

describe('fileFilter option', () => {
Expand Down
90 changes: 74 additions & 16 deletions sdk/src/__tests__/run-file-filter.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@

import * as mainPromptModule from '@codebuff/agent-runtime/main-prompt'
import { FILE_READ_STATUS } from '@codebuff/common/old-constants'
import * as projectFileTree from '@codebuff/common/project-file-tree'
Expand Down Expand Up @@ -91,9 +90,7 @@ describe('CodebuffClientOptions fileFilter', () => {
let requestedFiles: Record<string, string | null> = {}

spyOn(mainPromptModule, 'callMainPrompt').mockImplementation(
async (
params: Parameters<typeof mainPromptModule.callMainPrompt>[0],
) => {
async (params: Parameters<typeof mainPromptModule.callMainPrompt>[0]) => {
const { sendAction, promptId, requestFiles } = params
const sessionState = getInitialSessionState(getStubProjectFileContext())

Expand Down Expand Up @@ -177,9 +174,7 @@ describe('CodebuffClientOptions fileFilter', () => {
let requestedFiles: Record<string, string | null> = {}

spyOn(mainPromptModule, 'callMainPrompt').mockImplementation(
async (
params: Parameters<typeof mainPromptModule.callMainPrompt>[0],
) => {
async (params: Parameters<typeof mainPromptModule.callMainPrompt>[0]) => {
const { sendAction, promptId, requestFiles } = params
const sessionState = getInitialSessionState(getStubProjectFileContext())

Expand Down Expand Up @@ -259,9 +254,7 @@ describe('CodebuffClientOptions fileFilter', () => {
let optionalFileResult: string | null = null

spyOn(mainPromptModule, 'callMainPrompt').mockImplementation(
async (
params: Parameters<typeof mainPromptModule.callMainPrompt>[0],
) => {
async (params: Parameters<typeof mainPromptModule.callMainPrompt>[0]) => {
const { sendAction, promptId, requestOptionalFile } = params
const sessionState = getInitialSessionState(getStubProjectFileContext())

Expand Down Expand Up @@ -319,6 +312,75 @@ describe('CodebuffClientOptions fileFilter', () => {
expect(optionalFileResult).toBeNull()
})

it('should tolerate absolute requestOptionalFile paths inside cwd', async () => {
spyOn(databaseModule, 'getUserInfoFromApiKey').mockResolvedValue({
id: 'user-123',
email: 'test@example.com',
discord_id: null,
stripe_customer_id: null,
banned: false,
created_at: new Date('2024-01-01T00:00:00Z'),
})
spyOn(databaseModule, 'fetchAgentFromDatabase').mockResolvedValue(null)
spyOn(databaseModule, 'startAgentRun').mockResolvedValue('run-1')
spyOn(databaseModule, 'finishAgentRun').mockResolvedValue(undefined)
spyOn(databaseModule, 'addAgentStep').mockResolvedValue('step-1')
spyOn(projectFileTree, 'isFileIgnored').mockResolvedValue(false)

const mockFs = createMockFs({
files: {
'/project/src/index.ts': { content: 'normal file content' },
},
})

const optionalFileResult: { current: string | null } = { current: null }

spyOn(mainPromptModule, 'callMainPrompt').mockImplementation(
async (params: Parameters<typeof mainPromptModule.callMainPrompt>[0]) => {
const { sendAction, promptId, requestOptionalFile } = params
const sessionState = getInitialSessionState(getStubProjectFileContext())

optionalFileResult.current = await requestOptionalFile({
filePath: '/project/src/index.ts',
})

await sendAction({
action: {
type: 'prompt-response',
promptId,
sessionState,
output: {
type: 'lastMessage',
value: [],
},
},
})

return {
sessionState,
output: {
type: 'lastMessage' as const,
value: [],
},
}
},
)

const client = new CodebuffClient({
apiKey: 'test-key',
cwd: '/project',
fsSource: mockFs,
})

const result = await client.run({
agent: 'base2',
prompt: 'read optional file',
})

expect(result.output.type).toBe('lastMessage')
expect(optionalFileResult.current).toBe('normal file content')
})

it('should allow all files when no fileFilter is provided', async () => {
spyOn(databaseModule, 'getUserInfoFromApiKey').mockResolvedValue({
id: 'user-123',
Expand All @@ -343,9 +405,7 @@ describe('CodebuffClientOptions fileFilter', () => {
let requestedFiles: Record<string, string | null> = {}

spyOn(mainPromptModule, 'callMainPrompt').mockImplementation(
async (
params: Parameters<typeof mainPromptModule.callMainPrompt>[0],
) => {
async (params: Parameters<typeof mainPromptModule.callMainPrompt>[0]) => {
const { sendAction, promptId, requestFiles } = params
const sessionState = getInitialSessionState(getStubProjectFileContext())

Expand Down Expand Up @@ -417,9 +477,7 @@ describe('CodebuffClientOptions fileFilter', () => {
})

spyOn(mainPromptModule, 'callMainPrompt').mockImplementation(
async (
params: Parameters<typeof mainPromptModule.callMainPrompt>[0],
) => {
async (params: Parameters<typeof mainPromptModule.callMainPrompt>[0]) => {
const { sendAction, promptId, requestFiles } = params
const sessionState = getInitialSessionState(getStubProjectFileContext())

Expand Down
Loading
Loading