Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 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
44 changes: 43 additions & 1 deletion packages/cli/src/acp-integration/service/filesystem.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,39 @@ describe('AcpFileSystemService', () => {
});
});

it('converts core-only read params at the ACP boundary', async () => {
const mockResponse = {
content: 'slice',
_meta: { bom: false, encoding: 'utf-8' },
};
const client = {
readTextFile: vi.fn().mockResolvedValue(mockResponse),
} as unknown as AgentSideConnection;
const signal = new AbortController().signal;

const svc = new AcpFileSystemService(
client,
'session-1',
{ readTextFile: true, writeTextFile: true },
createFallback(),
);

await svc.readTextFile({
path: '/some/file.txt',
line: 0,
limit: 5,
maxOutputBytes: 1024,
signal,
});

expect(client.readTextFile).toHaveBeenCalledWith({
path: '/some/file.txt',
line: 1,
limit: 5,
sessionId: 'session-1',
});
});

it('converts RESOURCE_NOT_FOUND error to ENOENT', async () => {
const resourceNotFoundError = {
code: RESOURCE_NOT_FOUND_CODE,
Expand Down Expand Up @@ -953,11 +986,20 @@ describe('AcpFileSystemService', () => {
fallback,
);

const result = await svc.readTextFile({ path: '/some/file.txt' });
const signal = new AbortController().signal;
const result = await svc.readTextFile({
path: '/some/file.txt',
line: 0,
maxOutputBytes: 2048,
signal,
});

expect(result).toEqual(fallbackResponse);
expect(fallback.readTextFile).toHaveBeenCalledWith({
path: '/some/file.txt',
line: 0,
maxOutputBytes: 2048,
signal,
});
expect(client.readTextFile).not.toHaveBeenCalled();
});
Expand Down
32 changes: 27 additions & 5 deletions packages/cli/src/acp-integration/service/filesystem.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import type {
} from '@agentclientprotocol/sdk';
import { RequestError } from '@agentclientprotocol/sdk';
import type {
CoreReadTextFileRequest,
FileSystemService,
ReadTextFileResponse,
} from '@qwen-code/qwen-code-core';
Expand Down Expand Up @@ -105,6 +106,28 @@ async function resolveRealPath(value: string): Promise<string | undefined> {
}
}

function toAcpReadTextFileRequest(
params: CoreReadTextFileRequest,
sessionId: string,
): ReadTextFileRequest {
// `maxOutputBytes` and `signal` are core-local concerns that the current ACP
// schema cannot represent. Keep this boundary explicit if the schema grows.
const request: ReadTextFileRequest = {
path: params.path,
sessionId,
};
if (params._meta !== undefined) {
request._meta = params._meta;
}
if (params.limit !== undefined) {
request.limit = params.limit;
}
if (params.line != null) {
request.line = params.line + 1;
}
return request;
}

export class AcpFileSystemService implements FileSystemService {
constructor(
private readonly connection: AgentSideConnection,
Expand All @@ -115,18 +138,17 @@ export class AcpFileSystemService implements FileSystemService {
) {}

async readTextFile(
params: Omit<ReadTextFileRequest, 'sessionId'>,
params: CoreReadTextFileRequest,
): Promise<ReadTextFileResponse> {
if (!this.capabilities.readTextFile) {
return this.fallback.readTextFile(params);
}

let response: ReadTextFileResponse;
try {
response = await this.connection.readTextFile({
...params,
sessionId: this.sessionId,
});
response = await this.connection.readTextFile(
toAcpReadTextFileRequest(params, this.sessionId),
);
} catch (error) {
const errorCode = getErrorCode(error);

Expand Down
12 changes: 6 additions & 6 deletions packages/cli/src/serve/fs/policy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,12 +17,12 @@ import type { Intent, ResolvedPath } from './paths.js';
* typical source files, small enough that an SSE replay buffer
* doesn't fill on a single read.
*
* Files **above** this cap are refused with `file_too_large` rather
* than truncated — the underlying `readFileWithLineAndLimit`
* reads the whole file into memory before slicing lines, so soft
* truncation past the cap would still OOM the daemon. Files
* **at or below** the cap honor a tighter `opts.maxBytes` via
* post-decode truncation (`enforceReadSize`); that's where the
* Full-snapshot reads above this cap are refused with `file_too_large`
* rather than truncated. `readText` can serve explicit line windows
* from larger files, but the default read/edit contract still needs a
* bounded snapshot for hash stability, SSE buffering, and oldText
* matching. Files at or below the cap honor a tighter `opts.maxBytes`
* via post-decode truncation (`enforceReadSize`); that's where the
* `meta.truncated = true` flag fires.
*
* `enforceReadBytesSize` (the `readBytes` gate) and `edit()` use the
Expand Down
34 changes: 34 additions & 0 deletions packages/cli/src/ui/hooks/atCommandProcessor.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,40 @@ describe('handleAtCommand', () => {
expect(result.toolDisplays![0].status).toBe(ToolCallStatus.Success);
});

it('should attach a truncated text file larger than 10MB', async () => {
const filePath = await createTestFile(
path.join(testRootDir, 'large.log'),
'x'.repeat(11 * 1024 * 1024),
);

const result = await handleAtCommand({
query: `@${filePath}`,
config: mockConfig,
onDebugMessage: mockOnDebugMessage,
messageId: 626,
signal: abortController.signal,
});

const processedText = Array.isArray(result.processedQuery)
? result.processedQuery
.map((part) =>
typeof part === 'string'
? part
: 'text' in part
? part.text
: JSON.stringify(part),
)
.join('')
: '';

expect(processedText).toContain(
'Showing lines 1-1 of at least 1 total lines',
);
expect(processedText).toContain('... [truncated]');
expect(result.shouldProceed).toBe(true);
expect(result.toolDisplays![0].status).toBe(ToolCallStatus.Success);
});

it('should only allow actual temp directory paths outside the workspace', async () => {
const tempParentDir = await fsPromises.mkdtemp(
path.join(os.tmpdir(), 'at-command-temp-'),
Expand Down
25 changes: 25 additions & 0 deletions packages/core/src/services/fileSystemService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,31 @@ describe('StandardFileSystemService', () => {
expect(result._meta?.originalLineCount).toBe(100);
});

it('should pass maxOutputBytes and return byte-truncation metadata', async () => {
vi.mocked(readFileWithLineAndLimit).mockResolvedValue({
content: 'partial',
bom: false,
encoding: 'utf-8',
originalLineCount: 100,
truncatedByBytes: true,
});

const result = await fileSystem.readTextFile({
path: '/test/file.txt',
limit: 10,
line: 5,
maxOutputBytes: 128,
});

expect(readFileWithLineAndLimit).toHaveBeenCalledWith({
path: '/test/file.txt',
limit: 10,
line: 5,
maxOutputBytes: 128,
});
expect(result._meta?.truncatedByBytes).toBe(true);
});

it('should return encoding info for GBK file', async () => {
vi.mocked(readFileWithLineAndLimit).mockResolvedValue({
content: '你好世界',
Expand Down
54 changes: 40 additions & 14 deletions packages/core/src/services/fileSystemService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,25 @@ export type ReadTextFileResponse = {
bom?: boolean;
encoding?: string;
originalLineCount?: number;
originalLineCountExact?: boolean;
lineEnding?: LineEnding;
truncatedByBytes?: boolean;
};
};

export type CoreReadTextFileRequest = Omit<
ReadTextFileRequest,
'sessionId' | 'line'
> & {
/**
* Core-local callers use 0-based line offsets. ACP protocol boundaries remain
* 1-based and convert explicitly before remote calls.
*/
line?: number | null;
maxOutputBytes?: number;
signal?: AbortSignal;
};

/**
* Supported file encodings for new files.
*/
Expand All @@ -50,9 +65,7 @@ export type FileEncodingType = (typeof FileEncoding)[keyof typeof FileEncoding];
* Interface for file system operations that may be delegated to different implementations
*/
export interface FileSystemService {
readTextFile(
params: Omit<ReadTextFileRequest, 'sessionId'>,
): Promise<ReadTextFileResponse>;
readTextFile(params: CoreReadTextFileRequest): Promise<ReadTextFileResponse>;

writeTextFile(
params: Omit<WriteTextFileRequest, 'sessionId'>,
Expand Down Expand Up @@ -261,18 +274,31 @@ export function encodeTextFileContent(
*/
export class StandardFileSystemService implements FileSystemService {
async readTextFile(
params: Omit<ReadTextFileRequest, 'sessionId'>,
params: CoreReadTextFileRequest,
): Promise<ReadTextFileResponse> {
const { path, limit, line } = params;
// Use encoding-aware reader that handles BOM and non-UTF-8 encodings (e.g. GBK)
const { content, bom, encoding, originalLineCount } =
await readFileWithLineAndLimit({
path,
limit: limit ?? Number.POSITIVE_INFINITY,
line: line || 0,
});
const lineEnding = detectLineEnding(content);
return { content, _meta: { bom, encoding, originalLineCount, lineEnding } };
const { path, limit, line, maxOutputBytes, signal } = params;
const readResult = await readFileWithLineAndLimit({
path,
limit: limit ?? Number.POSITIVE_INFINITY,
line: line || 0,
...(maxOutputBytes !== undefined ? { maxOutputBytes } : {}),
...(signal !== undefined ? { signal } : {}),
});
const detectedLineEnding =
readResult.lineEnding ?? detectLineEnding(readResult.content);
return {
content: readResult.content,
_meta: {
bom: readResult.bom,
encoding: readResult.encoding,
originalLineCount: readResult.originalLineCount,
originalLineCountExact: readResult.originalLineCountExact,
lineEnding: detectedLineEnding,
...(readResult.truncatedByBytes !== undefined
? { truncatedByBytes: readResult.truncatedByBytes }
: {}),
},
};
}

async writeTextFile(
Expand Down
12 changes: 10 additions & 2 deletions packages/core/src/tools/artifact/artifact-tool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,9 +130,17 @@ class ArtifactToolInvocation extends BaseToolInvocation<
// Read the fragment the model wrote.
let fragment: string;
try {
const { content } = await this.config
const { content, _meta } = await this.config
.getFileSystemService()
.readTextFile({ path: file_path });
.readTextFile({ path: file_path, maxOutputBytes: MAX_ARTIFACT_BYTES });
if (_meta?.truncatedByBytes === true) {
const message = `Artifact is too large (source exceeds the ${MAX_ARTIFACT_BYTES} byte limit). Trim the content or split it across multiple artifacts.`;
return {
llmContent: message,
returnDisplay: message,
error: { message, type: ToolErrorType.FILE_TOO_LARGE },
};
}
fragment = content;
} catch (err) {
const notFound = isNodeError(err) && err.code === 'ENOENT';
Expand Down
29 changes: 23 additions & 6 deletions packages/core/src/tools/read-file.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -382,9 +382,8 @@ describe('ReadFileTool', () => {
});
});

it('should return error for a file that is too large', async () => {
it('should read and truncate a text file larger than 10MB', async () => {
const filePath = path.join(tempRootDir, 'largefile.txt');
// 11MB of content exceeds 10MB limit
const largeContent = 'x'.repeat(11 * 1024 * 1024);
await fsp.writeFile(filePath, largeContent, 'utf-8');
const params: ReadFileToolParams = { file_path: filePath };
Expand All @@ -394,10 +393,28 @@ describe('ReadFileTool', () => {
>;

const result = await invocation.execute(abortSignal);
expect(result).toHaveProperty('error');
expect(result.error?.type).toBe(ToolErrorType.FILE_TOO_LARGE);
expect(result.error?.message).toContain(
'File size exceeds the 10MB limit',
expect(result.error).toBeUndefined();
expect(result.returnDisplay).toBe(
'Read lines 1-1 of at least 1 from largefile.txt (truncated)',
);
expect(result.llmContent).toContain(
'Showing lines 1-1 of at least 1 total lines',
);
expect(result.llmContent).toContain('... [truncated]');
});

it('should propagate an aborted signal before reading', async () => {
const filePath = path.join(tempRootDir, 'abort.txt');
await fsp.writeFile(filePath, 'content', 'utf-8');
const invocation = tool.build({ file_path: filePath }) as ToolInvocation<
ReadFileToolParams,
ToolResult
>;
const controller = new AbortController();
controller.abort();

await expect(invocation.execute(controller.signal)).rejects.toThrow(
/abort/i,
);
});

Expand Down
7 changes: 5 additions & 2 deletions packages/core/src/tools/read-file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,7 @@ class ReadFileToolInvocation extends BaseToolInvocation<
return 'ask';
}

async execute(): Promise<ToolResult> {
async execute(signal: AbortSignal): Promise<ToolResult> {
const absPath = path.resolve(this.params.file_path);
const projectRoot = this.config.getTargetDir();
// Auto-memory files (AGENTS.md and friends under the auto-memory
Expand Down Expand Up @@ -207,6 +207,7 @@ class ReadFileToolInvocation extends BaseToolInvocation<
offset: this.params.offset,
limit: this.params.limit,
pages: this.params.pages,
signal,
},
);

Expand Down Expand Up @@ -285,7 +286,9 @@ class ReadFileToolInvocation extends BaseToolInvocation<
) {
const [start, end] = result.linesShown!;
const total = result.originalLineCount!;
llmContent = `Showing lines ${start}-${end} of ${total} total lines.\n\n---\n\n${result.llmContent}`;
const totalLabel =
result.originalLineCountExact === false ? `at least ${total}` : total;
llmContent = `Showing lines ${start}-${end} of ${totalLabel} total lines.\n\n---\n\n${result.llmContent}`;
} else {
llmContent = result.llmContent || '';
}
Expand Down
Loading
Loading