Skip to content

🀯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

πŸ› fix(local-system): surface total line count on truncated readFile results (#19748)

Arvin Xu6ef5d593e92d
diff --git a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.readFile.test.ts b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.readFile.test.ts
index 7076409e3b0..5295a08b5c0 100644
--- a/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.readFile.test.ts
+++ b/apps/desktop/src/main/controllers/__tests__/LocalFileCtr.readFile.test.ts
@@ -65,7 +65,7 @@ describe('LocalFileCtr β€” readFile / readFiles (real fs)', () => {
fileType: 'txt',
filename: 'test.txt',
lineCount: 5,
- loc: [0, 200],
+ loc: [0, 5],
modifiedTime: expect.any(Date),
totalCharCount: 29,
totalLineCount: 5,
@@ -265,7 +265,7 @@ describe('LocalFileCtr β€” readFile / readFiles (real fs)', () => {
fileType: 'txt',
filename: 'a.txt',
lineCount: 1,
- loc: [0, 200],
+ loc: [0, 1],
modifiedTime: expect.any(Date),
totalCharCount: 9,
totalLineCount: 1,
@@ -277,7 +277,7 @@ describe('LocalFileCtr β€” readFile / readFiles (real fs)', () => {
fileType: 'txt',
filename: 'b.txt',
lineCount: 1,
- loc: [0, 200],
+ loc: [0, 1],
modifiedTime: expect.any(Date),
totalCharCount: 9,
totalLineCount: 1,
diff --git a/packages/builtin-tool-cloud-sandbox/src/systemRole.ts b/packages/builtin-tool-cloud-sandbox/src/systemRole.ts
index 6d794cbfd74..ccd95674d23 100644
--- a/packages/builtin-tool-cloud-sandbox/src/systemRole.ts
+++ b/packages/builtin-tool-cloud-sandbox/src/systemRole.ts
@@ -168,7 +168,7 @@ When the user requests a file deliverable or download, export the finalized file
<tool_usage_guidelines>
- For listing directory contents: Use 'listFiles' with the target directory path.
-- For reading a file: Use 'readFile' with the file path. Optionally specify startLine/endLine for partial reads.
+- For reading a file: Use 'readFile' with the file path. Optionally specify startLine/endLine (both 1-based, endLine inclusive) for partial reads. Each line in the response is prefixed with its 1-based line number; if the window doesn't reach the end of the file, the response starts with a '(lines 1-200 of 2545)' marker showing the total β€” continue with a later startLine.
- For writing files: Use 'writeFile' with the file path and content. Set createDirectories: true if needed.
- For editing files: Use 'editFile'. Always read the file first to verify content before editing.
- For executing code directly: Use 'executeCode' with the code and optional language (python/javascript/typescript). This is preferred over runCommand for simple code execution.
diff --git a/packages/builtin-tool-local-system/src/manifest.ts b/packages/builtin-tool-local-system/src/manifest.ts
index d443d11bcfa..9d265d32b5b 100644
--- a/packages/builtin-tool-local-system/src/manifest.ts
+++ b/packages/builtin-tool-local-system/src/manifest.ts
@@ -27,7 +27,7 @@ export const LocalSystemManifest: BuiltinToolManifest = {
properties: {
loc: {
description:
- 'Optional range of lines to read [startLine, endLine]. Defaults to [0, 200] if not specified.',
+ "Optional range of lines to read [startLine, endLine], 0-based and end-exclusive (e.g. [0, 1000] reads the first 1000 lines). Defaults to [0, 1000] if not specified; request a wider window to read more at once β€” output is capped at 500K chars. Each line is prefixed with its 1-based line number; a window that doesn't reach the end of the file starts with a '(lines 1-1000 of 2545)' marker showing the total.",
items: {
type: 'number',
},
diff --git a/packages/builtin-tool-local-system/src/systemRole.desktop.ts b/packages/builtin-tool-local-system/src/systemRole.desktop.ts
index 4ea0050f63c..290a3359b0c 100644
--- a/packages/builtin-tool-local-system/src/systemRole.desktop.ts
+++ b/packages/builtin-tool-local-system/src/systemRole.desktop.ts
@@ -50,9 +50,11 @@ You have access to a set of tools to interact with the user's local file system:
<tool_usage_guidelines>
- For reading a file: Use 'readFile'. Provide the following parameters:
- 'path': The exact file path.
- - 'loc' (Optional): A two-element array [startLine, endLine] to specify a line range to read (e.g., '[301, 400]' reads lines 301 to 400).
- - If 'loc' is omitted, it defaults to reading the first 200 lines ('[0, 200]').
- - To read the entire file: First call 'readFile' (potentially without 'loc'). The response includes 'totalLineCount'. Then, call 'readFile' again with 'loc: [0, totalLineCount]' to get the full content.
+ - 'loc' (Optional): A two-element array [startLine, endLine], 0-based and end-exclusive: '[0, 1000]' reads the first 1000 lines, '[1000, 2000]' reads the next 1000. Request a wider window to read more at once β€” output is capped at 500K chars.
+ - If 'loc' is omitted, it defaults to '[0, 1000]'. Each line in the response is prefixed with its 1-based line number (e.g. ' 42 ...') β€” never include these prefixes in 'editFile' old_string/new_string or 'writeFile' content.
+ - If the returned window doesn't reach the end of the file, the response starts with a '(lines 1-1000 of 2545)' marker showing the returned window and the file's total line count.
+ - 'grepContent' line numbers are 1-based while 'loc' is 0-based: to read around a grep hit at line N, use 'loc: [N - 1, ...]'. The line-number prefixes in 'readFile' output are 1-based, so they match 'grepContent'.
+ - To read the entire file: check the total line count in the marker, then call 'readFile' again with 'loc: [0, totalLineCount]' to get the full content.
- For a local image path, call 'readFile' directly. Never use shell commands to convert the image to base64/data URI text or copy encoded image data between tools.
- For searching files: Use 'searchFiles' with the 'keywords' parameter (search string). 'keywords' is split on whitespace and every token must appear as a substring of the filename (case- and diacritic-insensitive, order-independent). Pass only the discriminating words β€” long phrases full of optional words will return nothing. You can optionally add the following filter parameters to narrow down the search:
- 'contentContains': Find files whose content includes specific text.
diff --git a/packages/builtin-tool-local-system/src/systemRole.ts b/packages/builtin-tool-local-system/src/systemRole.ts
index a1761588a0c..b9de0092dd9 100644
--- a/packages/builtin-tool-local-system/src/systemRole.ts
+++ b/packages/builtin-tool-local-system/src/systemRole.ts
@@ -49,9 +49,11 @@ You have access to a set of tools to interact with the user's local file system:
<tool_usage_guidelines>
- For reading a file: Use 'readFile'. Provide the following parameters:
- 'path': The exact file path.
- - 'loc' (Optional): A two-element array [startLine, endLine] to specify a line range to read (e.g., '[301, 400]' reads lines 301 to 400).
- - If 'loc' is omitted, it defaults to reading the first 200 lines ('[0, 200]').
- - To read the entire file: First call 'readFile' (potentially without 'loc'). The response includes 'totalLineCount'. Then, call 'readFile' again with 'loc: [0, totalLineCount]' to get the full content.
+ - 'loc' (Optional): A two-element array [startLine, endLine], 0-based and end-exclusive: '[0, 1000]' reads the first 1000 lines, '[1000, 2000]' reads the next 1000. Request a wider window to read more at once β€” output is capped at 500K chars.
+ - If 'loc' is omitted, it defaults to '[0, 1000]'. Each line in the response is prefixed with its 1-based line number (e.g. ' 42 ...') β€” never include these prefixes in 'editFile' old_string/new_string or 'writeFile' content.
+ - If the returned window doesn't reach the end of the file, the response starts with a '(lines 1-1000 of 2545)' marker showing the returned window and the file's total line count.
+ - 'grepContent' line numbers are 1-based while 'loc' is 0-based: to read around a grep hit at line N, use 'loc: [N - 1, ...]'. The line-number prefixes in 'readFile' output are 1-based, so they match 'grepContent'.
+ - To read the entire file: check the total line count in the marker, then call 'readFile' again with 'loc: [0, totalLineCount]' to get the full content.
- For searching files: Use 'searchFiles' with the 'keywords' parameter (search string). 'keywords' is split on whitespace and every token must appear as a substring of the filename (case- and diacritic-insensitive, order-independent). Pass only the discriminating words β€” long phrases full of optional words will return nothing. You can optionally add the following filter parameters to narrow down the search:
- 'contentContains': Find files whose content includes specific text.
- 'createdAfter' / 'createdBefore': Filter by creation date.
diff --git a/packages/electron-client-ipc/src/types/localSystem.ts b/packages/electron-client-ipc/src/types/localSystem.ts
index 1fc584098a4..5a6b28c0299 100644
--- a/packages/electron-client-ipc/src/types/localSystem.ts
+++ b/packages/electron-client-ipc/src/types/localSystem.ts
@@ -240,6 +240,11 @@ export interface LocalReadFileResult {
* Total line count of the entire file.
*/
totalLineCount: number;
+ /**
+ * True when the content was cut at the output character cap before the
+ * requested `loc` window ended.
+ */
+ truncated?: boolean;
}
export interface LocalSearchFilesParams {
diff --git a/packages/local-file-shell/src/file/__tests__/file.test.ts b/packages/local-file-shell/src/file/__tests__/file.test.ts
index 74a430c8544..e64879132c6 100644
--- a/packages/local-file-shell/src/file/__tests__/file.test.ts
+++ b/packages/local-file-shell/src/file/__tests__/file.test.ts
@@ -31,20 +31,42 @@ describe('file operations', () => {
// ─── readLocalFile ───
describe('readLocalFile', () => {
- it('should read file with default line range (0-200)', async () => {
+ it('should read file with default line range (0-1000)', async () => {
const filePath = path.join(tmpDir, 'test.txt');
- const lines = Array.from({ length: 300 }, (_, i) => `line ${i}`);
+ const lines = Array.from({ length: 1200 }, (_, i) => `line ${i}`);
await writeFile(filePath, lines.join('\n'));
const result = await readLocalFile({ path: filePath });
- expect(result.lineCount).toBe(200);
- expect(result.totalLineCount).toBe(300);
- expect(result.loc).toEqual([0, 200]);
+ expect(result.lineCount).toBe(1000);
+ expect(result.totalLineCount).toBe(1200);
+ expect(result.loc).toEqual([0, 1000]);
expect(result.filename).toBe('test.txt');
expect(result.fileType).toBe('txt');
});
+ it('should clamp the reported window at EOF for short files', async () => {
+ const filePath = path.join(tmpDir, 'short.txt');
+ await writeFile(filePath, 'a\nb\nc\nd\ne');
+
+ const result = await readLocalFile({ path: filePath });
+
+ expect(result.lineCount).toBe(5);
+ expect(result.loc).toEqual([0, 5]);
+ });
+
+ it('should clamp an explicit range that extends past EOF', async () => {
+ const filePath = path.join(tmpDir, 'past-eof.txt');
+ const lines = Array.from({ length: 10 }, (_, i) => `line ${i}`);
+ await writeFile(filePath, lines.join('\n'));
+
+ const result = await readLocalFile({ loc: [5, 100], path: filePath });
+
+ expect(result.lineCount).toBe(5);
+ expect(result.content).toBe('line 5\nline 6\nline 7\nline 8\nline 9');
+ expect(result.loc).toEqual([5, 10]);
+ });
+
it('should read full content when fullContent is true', async () => {
const filePath = path.join(tmpDir, 'full.txt');
const lines = Array.from({ length: 300 }, (_, i) => `line ${i}`);
diff --git a/packages/local-file-shell/src/file/read.ts b/packages/local-file-shell/src/file/read.ts
index 15047667464..d7e64ff7611 100644
--- a/packages/local-file-shell/src/file/read.ts
+++ b/packages/local-file-shell/src/file/read.ts
@@ -19,6 +19,8 @@ const MAX_PDF_FILE_SIZE_BYTES = 50 * 1024 * 1024;
const MAX_OUTPUT_CHARS = 500_000;
/** Cap on chars per line. Keeps a single 27KB base64 line from blowing up the response. */
const MAX_LINE_CHARS = 8_000;
+/** Lines returned when the caller passes no `loc`. Larger windows are allowed explicitly. */
+const DEFAULT_WINDOW_LINE_COUNT = 1_000;
const inferFileType = (filePath: string): string =>
path.extname(filePath).toLowerCase().replace('.', '') || 'unknown';
@@ -51,7 +53,7 @@ export async function readLocalFile({
cwd,
}: ReadFileParams): Promise<ReadFileResult> {
const filePath = resolveAgainstCwd(rawPath, cwd) ?? rawPath;
- const effectiveLoc = fullContent ? undefined : (loc ?? [0, 200]);
+ const effectiveLoc = fullContent ? undefined : (loc ?? [0, DEFAULT_WINDOW_LINE_COUNT]);
let stats;
try {
@@ -131,9 +133,14 @@ export async function readLocalFile({
workingLines = lines;
actualLoc = [0, totalLineCount];
} else {
+ // Report the window actually covered: clamp at EOF (and at 0) so a
+ // default `[0, 1000]` read of a 5-line file reports `[0, 5]`, not the
+ // requested range.
const [startLine, endLine] = effectiveLoc;
- workingLines = lines.slice(startLine, endLine);
- actualLoc = effectiveLoc;
+ const start = Math.min(Math.max(startLine, 0), totalLineCount);
+ const end = Math.min(Math.max(endLine, start), totalLineCount);
+ workingLines = lines.slice(start, end);
+ actualLoc = [start, end];
}
let linesTruncated = 0;
diff --git a/packages/prompts/src/prompts/fileSystem/formatFileContent.test.ts b/packages/prompts/src/prompts/fileSystem/formatFileContent.test.ts
index ddac02fcc35..1cf6066128e 100644
--- a/packages/prompts/src/prompts/fileSystem/formatFileContent.test.ts
+++ b/packages/prompts/src/prompts/fileSystem/formatFileContent.test.ts
@@ -3,57 +3,135 @@ import { describe, expect, it } from 'vitest';
import { formatFileContent } from './formatFileContent';
describe('formatFileContent', () => {
- it('should format file content without line range', () => {
+ it('should return content unchanged without line numbers', () => {
const result = formatFileContent({
content: 'console.log("hello");',
- path: '/src/index.ts',
});
- expect(result).toMatchInlineSnapshot(`
- "File: /src/index.ts
+ expect(result).toBe('console.log("hello");');
+ });
- console.log("hello");"
- `);
+ it('should handle empty content', () => {
+ const result = formatFileContent({
+ content: '',
+ firstLineNumber: 1,
+ });
+ expect(result).toBe('');
});
- it('should format file content with line range', () => {
+ it('should prefix each line with its 1-based line number', () => {
const result = formatFileContent({
content: 'function test() {\n return true;\n}',
- lineRange: [10, 12],
- path: '/src/utils.ts',
+ firstLineNumber: 11,
+ lineRange: [10, 13],
+ totalLines: 13,
});
expect(result).toMatchInlineSnapshot(`
- "File: /src/utils.ts (lines 10-12)
-
- function test() {
- return true;
- }"
+ "11 function test() {
+ 12 return true;
+ 13 }"
`);
});
- it('should handle empty content', () => {
+ it('should pad line numbers to the width of the last line', () => {
const result = formatFileContent({
- content: '',
- path: '/empty.txt',
+ content: 'a\nb\nc',
+ firstLineNumber: 9,
});
expect(result).toMatchInlineSnapshot(`
- "File: /empty.txt
+ " 9 a
+ 10 b
+ 11 c"
+ `);
+ });
- "
+ it('should mark a window that stops before the end of the file', () => {
+ const result = formatFileContent({
+ content: 'line 1\nline 2',
+ firstLineNumber: 1,
+ lineRange: [0, 1000],
+ totalLines: 2545,
+ });
+ expect(result).toMatchInlineSnapshot(`
+ "(lines 1-1000 of 2545)
+ 1 line 1
+ 2 line 2"
`);
});
- it('should handle multiline content', () => {
- const content = 'line 1\nline 2\nline 3';
+ it('should not mark a window that reaches the end of the file', () => {
+ const result = formatFileContent({
+ content: 'last line',
+ firstLineNumber: 2501,
+ lineRange: [2500, 2545],
+ totalLines: 2545,
+ });
+ expect(result).toBe('2501 last line');
+ });
+
+ it('should not mark a window clamped at the total line count', () => {
+ const result = formatFileContent({
+ content: 'a\nb',
+ firstLineNumber: 1,
+ lineRange: [0, 1000],
+ totalLines: 2,
+ });
+ expect(result).not.toContain('(lines');
+ });
+
+ it('should not mark a service-truncated window even when it stops before EOF', () => {
+ const result = formatFileContent({
+ content: 'partial\n[content truncated: response was 600000 chars, kept first 500000.]',
+ firstLineNumber: 1,
+ lineRange: [0, 1000],
+ totalLines: 2545,
+ truncated: true,
+ });
+ expect(result).not.toContain('(lines');
+ });
+
+ it('should not number a synthetic line from a trailing newline', () => {
+ const result = formatFileContent({
+ content: 'a\nb\n',
+ firstLineNumber: 1,
+ lineRange: [0, 2],
+ totalLines: 2,
+ });
+ expect(result).toBe('1 a\n2 b');
+ });
+
+ it('should preserve a genuine blank line at the window boundary', () => {
+ // `a\n\nb` read with loc [0, 2] arrives as `a\n` β€” the terminal empty
+ // element is the real second line, not a trailing-newline artifact.
+ const result = formatFileContent({
+ content: 'a\n',
+ firstLineNumber: 1,
+ lineRange: [0, 2],
+ totalLines: 3,
+ });
+ expect(result).toBe('(lines 1-2 of 3)\n1 a\n2 ');
+ });
+
+ it('should cap the output after adding line numbers', () => {
+ // 100K blank lines: ~100KB raw, ~700KB after numbering.
+ const content = Array.from({ length: 100_000 }, () => '').join('\n');
const result = formatFileContent({
content,
- path: '/test.txt',
+ firstLineNumber: 1,
+ lineRange: [0, 100_000],
+ totalLines: 200_000,
});
- expect(result).toMatchInlineSnapshot(`
- "File: /test.txt
+ expect(result).toContain('[output truncated at 500000 chars after adding line numbers.');
+ expect(result.length).toBeLessThan(501_000);
+ // A capped payload must not claim the full window.
+ expect(result).not.toContain('(lines');
+ });
- line 1
- line 2
- line 3"
- `);
+ it('should not mark a window without a total line count', () => {
+ const result = formatFileContent({
+ content: 'some lines',
+ firstLineNumber: 1,
+ lineRange: [0, 200],
+ });
+ expect(result).toBe('1 some lines');
});
});
diff --git a/packages/prompts/src/prompts/fileSystem/formatFileContent.ts b/packages/prompts/src/prompts/fileSystem/formatFileContent.ts
index f29a5371a82..8a87f62f706 100644
--- a/packages/prompts/src/prompts/fileSystem/formatFileContent.ts
+++ b/packages/prompts/src/prompts/fileSystem/formatFileContent.ts
@@ -1,14 +1,93 @@
export interface FormatFileContentParams {
content: string;
+ /**
+ * 1-based line number of the first content line. When set, every line is
+ * prefixed with its line number (right-aligned, space-separated) so the
+ * reader can refer to exact positions without counting.
+ */
+ firstLineNumber?: number;
lineRange?: [number, number];
- path: string;
+ totalLines?: number;
+ /**
+ * The service cut the content at its character cap, so the window's tail
+ * was never delivered. The window marker is suppressed β€” it would claim
+ * coverage the payload doesn't have; the embedded truncation warning
+ * already tells the reader to narrow the range.
+ */
+ truncated?: boolean;
}
+/**
+ * Mirrors the service's 500K char cap, re-applied after the gutter expands
+ * the payload: numbering 500K blank lines would otherwise balloon the output
+ * to several megabytes.
+ */
+const MAX_FORMATTED_CHARS = 500_000;
+
+const numberLines = (
+ content: string,
+ firstLineNumber: number,
+ expectedLineCount?: number,
+): string => {
+ if (content === '') return content;
+ const lines = content.split('\n');
+ // A trailing newline produces a synthetic empty element that isn't a real
+ // line β€” but a window ending on a genuine blank line has the same shape
+ // (e.g. `a\n\nb` read with loc [0, 2] arrives as `a\n`). Only drop the
+ // terminal element when the line metadata confirms it is phantom.
+ if (
+ expectedLineCount !== undefined &&
+ lines.length === expectedLineCount + 1 &&
+ lines.at(-1) === ''
+ ) {
+ lines.pop();
+ }
+ const width = String(firstLineNumber + lines.length - 1).length;
+ return lines
+ .map((line, index) => `${String(firstLineNumber + index).padStart(width)} ${line}`)
+ .join('\n');
+};
+
export const formatFileContent = ({
- path,
content,
lineRange,
+ totalLines,
+ firstLineNumber,
+ truncated,
}: FormatFileContentParams): string => {
- const lineInfo = lineRange ? ` (lines ${lineRange[0]}-${lineRange[1]})` : '';
- return `File: ${path}${lineInfo}\n\n${content}`;
+ // Never display a window past EOF: some services echo the requested range
+ // even when the file is shorter.
+ const end =
+ lineRange && totalLines !== undefined ? Math.min(lineRange[1], totalLines) : lineRange?.[1];
+ const expectedLineCount = lineRange && end !== undefined ? end - lineRange[0] : totalLines;
+
+ let body =
+ firstLineNumber === undefined
+ ? content
+ : numberLines(content, firstLineNumber, expectedLineCount);
+
+ let capped = false;
+ if (body.length > MAX_FORMATTED_CHARS) {
+ body = `${body.slice(0, MAX_FORMATTED_CHARS)}\n[output truncated at ${MAX_FORMATTED_CHARS} chars after adding line numbers. Use a smaller line range or grep to narrow down.]`;
+ capped = true;
+ }
+
+ // Only a window that stops before EOF gets a marker β€” that's the one piece
+ // of information the numbered lines can't convey (how much is left). A
+ // capped payload never claims the full window.
+ if (
+ truncated ||
+ capped ||
+ !lineRange ||
+ totalLines === undefined ||
+ end === undefined ||
+ end >= totalLines
+ ) {
+ return body;
+ }
+
+ const start = firstLineNumber ?? lineRange[0];
+ const marker = `(lines ${start}-${start + (end - lineRange[0]) - 1} of ${totalLines})`;
+
+ return `${marker}\n${body}`;
};
diff --git a/packages/tool-runtime/src/ComputerRuntime.ts b/packages/tool-runtime/src/ComputerRuntime.ts
index a209af66b08..a1867f5af82 100644
--- a/packages/tool-runtime/src/ComputerRuntime.ts
+++ b/packages/tool-runtime/src/ComputerRuntime.ts
@@ -160,17 +160,43 @@ export abstract class ComputerRuntime {
startLine: args.startLine,
totalCharCount: r.totalCharCount,
totalLines: r.totalLineCount ?? r.totalLines,
+ truncated: r.truncated === true ? true : undefined,
};
- const lineRange: [number, number] | undefined =
- args.startLine !== undefined && args.endLine !== undefined
- ? [args.startLine, args.endLine]
+ // Number every returned line (1-based gutter) and, when the window
+ // stops before EOF, prefix a `(lines 1-1000 of 2545)` marker. Rendering
+ // only the caller-supplied args here meant a default-window read looked
+ // identical to a full read, and the model had to burn extra turns
+ // discovering the file was truncated.
+ const hasLoc = Array.isArray(r.loc) && r.loc.length === 2;
+ // The loc-less fallback is the cloud sandbox path (local reads always
+ // return `loc`): its `startLine`/`endLine` args are 1-based inclusive
+ // and independently optional, so normalize to the 0-based
+ // end-exclusive window the formatter computes with β€” passing [1, 200]
+ // through raw would label a full 200-line read as "(lines 1-199 of
+ // ...)". An endLine-only read stops mid-file and needs the marker; a
+ // startLine-only read runs to EOF (window end = totalLines).
+ const fallbackEnd = args.endLine ?? r.totalLineCount ?? r.totalLines;
+ const lineRange: [number, number] | undefined = hasLoc
+ ? [r.loc[0], r.loc[1]]
+ : (args.startLine !== undefined || args.endLine !== undefined) && fallbackEnd !== undefined
+ ? [Math.max((args.startLine ?? 1) - 1, 0), fallbackEnd]
: undefined;
+ // `loc` is 0-based end-exclusive while the cloud sandbox's
+ // `startLine`/`endLine` args are 1-based inclusive; either way the first
+ // returned line's 1-based number is loc[0] + 1 or startLine.
+ const firstLineNumber = hasLoc ? r.loc[0] + 1 : (args.startLine ?? 1);
+
const content = formatFileContent({
content: fileContent,
+ firstLineNumber,
lineRange,
- path: args.path,
+ totalLines: r.totalLineCount ?? r.totalLines,
+ // When the service cut the content at its char cap, the window's tail
+ // was never delivered β€” a "(lines 1-1000 of N)" marker would claim
+ // coverage the payload doesn't have, so it is suppressed.
+ truncated: r.truncated === true,
});
return { content, state, success: true };
diff --git a/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts b/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts
index 475700f6c56..8cc7ec107c7 100644
--- a/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts
+++ b/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts
@@ -172,6 +172,7 @@ export class LocalSystemExecutionRuntime extends ComputerRuntime {
return this.readFile({
cwd,
endLine: args.loc?.[1],
+ loc: args.loc,
path: args.path,
startLine: args.loc?.[0],
});
@@ -341,9 +342,10 @@ export class LocalSystemExecutionRuntime extends ComputerRuntime {
case 'readLocalFile': {
const loc: [number, number] | undefined =
- params.startLine !== undefined || params.endLine !== undefined
- ? [params.startLine ?? 0, params.endLine ?? 200]
- : undefined;
+ params.loc ??
+ (params.startLine !== undefined || params.endLine !== undefined
+ ? [params.startLine ?? 0, params.endLine ?? (params.startLine ?? 0) + 1_000]
+ : undefined);
return { cwd: params.cwd, fullContent: params.fullContent, loc, path: params.path };
}
@@ -524,6 +526,10 @@ export class LocalSystemExecutionRuntime extends ComputerRuntime {
loc: raw.loc,
totalCharCount: raw.totalCharCount,
totalLineCount: raw.totalLineCount,
+ // The char-cap flag β€” ComputerRuntime suppresses the continuation
+ // hint on truncated reads so it never points past undelivered
+ // content.
+ truncated: raw.truncated,
},
success: true,
};
diff --git a/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts b/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts
index 6a32ec9cd9a..3118c90adf7 100644
--- a/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts
+++ b/packages/tool-runtime/src/__tests__/LocalSystemExecutionRuntime.test.ts
@@ -275,6 +275,158 @@ describe('LocalSystemExecutionRuntime.readFile', () => {
expect(output.state?.images).toBeUndefined();
expect(output.content).toContain('hello');
});
+
+ // Regression: a default-window read used to render a bare `File: <path>`
+ // header with no hint that only the first 200 lines were returned, so the
+ // model re-read the file over and over to discover it was truncated. The
+ // service always reports the actual window (`loc`) and `totalLineCount`;
+ // a window that stops before EOF must open with a marker carrying both.
+ it('marks the returned window and total line count on truncated reads', async () => {
+ const service = createService({
+ readLocalFile: vi.fn().mockResolvedValue({
+ content: 'first 200 lines…',
+ fileType: 'txt',
+ filename: 'big.txt',
+ loc: [0, 200],
+ totalCharCount: 148_370,
+ totalLineCount: 2545,
+ }),
+ });
+ const runtime = new LocalSystemExecutionRuntime(service);
+
+ const output = await runtime.readFile({ path: '/tmp/big.txt' });
+
+ expect(output.content).toBe('(lines 1-200 of 2545)\n1 first 200 lines…');
+ });
+
+ it('omits the window marker when the window reaches the end of the file', async () => {
+ const service = createService({
+ readLocalFile: vi.fn().mockResolvedValue({
+ content: 'tail',
+ fileType: 'txt',
+ filename: 'big.txt',
+ loc: [2500, 2545],
+ totalCharCount: 148_370,
+ totalLineCount: 2545,
+ }),
+ });
+ const runtime = new LocalSystemExecutionRuntime(service);
+
+ const output = await runtime.readFile({ endLine: 2545, path: '/tmp/big.txt', startLine: 2500 });
+
+ expect(output.content).toBe('2501 tail');
+ expect(output.content).not.toContain('(lines');
+ });
+
+ it('prefixes each content line with its 1-based line number', async () => {
+ const service = createService({
+ readLocalFile: vi.fn().mockResolvedValue({
+ content: 'alpha\nbeta\ngamma',
+ fileType: 'txt',
+ filename: 'a.txt',
+ loc: [10, 13],
+ totalCharCount: 15,
+ totalLineCount: 13,
+ }),
+ });
+ const runtime = new LocalSystemExecutionRuntime(service);
+
+ const output = await runtime.readFile({ loc: [10, 13], path: '/tmp/a.txt' });
+
+ expect(output.content).toContain('11 alpha');
+ expect(output.content).toContain('12 beta');
+ expect(output.content).toContain('13 gamma');
+ // State keeps the raw content for UI rendering; only the agent-facing
+ // text carries the gutter.
+ expect(output.state?.content).toBe('alpha\nbeta\ngamma');
+ });
+
+ // Regression: when the service cut the content at its char cap, the window
+ // marker would claim coverage that was never delivered, silently skipping
+ // the window's tail. The embedded truncation warning already tells the
+ // model to narrow the range.
+ it('suppresses the window marker when the service truncated the content', async () => {
+ const service = createService({
+ readLocalFile: vi.fn().mockResolvedValue({
+ content:
+ 'partial\n[content truncated: response was 600000 chars, kept first 500000. Use a smaller line range or grep to narrow down.]',
+ fileType: 'txt',
+ filename: 'big.txt',
+ loc: [0, 1000],
+ totalCharCount: 3_000_000,
+ totalLineCount: 2545,
+ truncated: true,
+ }),
+ });
+ const runtime = new LocalSystemExecutionRuntime(service);
+
+ const output = await runtime.readFile({ path: '/tmp/big.txt' });
+
+ expect(output.content).not.toContain('(lines');
+ expect(output.content).toContain('content truncated');
+ expect(output.state?.truncated).toBe(true);
+ });
+
+ // The cloud sandbox reader returns no `loc` and its startLine/endLine args
+ // are 1-based inclusive; the fallback window must be normalized before the
+ // formatter's end-exclusive math, or a full 200-line read is labeled
+ // "(lines 1-199 of ...)" and the gutter contradicts the marker.
+ it('normalizes a loc-less 1-based inclusive window (cloud sandbox shape)', async () => {
+ const service = createService({
+ readLocalFile: vi.fn().mockResolvedValue({
+ content: 'some lines',
+ fileType: 'txt',
+ filename: 'big.txt',
+ totalCharCount: 148_370,
+ totalLineCount: 2545,
+ }),
+ });
+ const runtime = new LocalSystemExecutionRuntime(service);
+
+ const output = await runtime.readFile({ endLine: 200, path: '/tmp/big.txt', startLine: 1 });
+
+ expect(output.content).toContain('(lines 1-200 of 2545)');
+ expect(output.content).toContain('1 some lines');
+ });
+
+ // The cloud manifest makes startLine/endLine independently optional: an
+ // endLine-only read stops mid-file and must still get the window marker,
+ // a startLine-only read runs to EOF and must not.
+ it('marks an endLine-only loc-less read (cloud sandbox shape)', async () => {
+ const service = createService({
+ readLocalFile: vi.fn().mockResolvedValue({
+ content: 'some lines',
+ fileType: 'txt',
+ filename: 'big.txt',
+ totalCharCount: 148_370,
+ totalLineCount: 2545,
+ }),
+ });
+ const runtime = new LocalSystemExecutionRuntime(service);
+
+ const output = await runtime.readFile({ endLine: 200, path: '/tmp/big.txt' });
+
+ expect(output.content).toContain('(lines 1-200 of 2545)');
+ expect(output.content).toContain('1 some lines');
+ });
+
+ it('does not mark a startLine-only loc-less read that runs to EOF', async () => {
+ const service = createService({
+ readLocalFile: vi.fn().mockResolvedValue({
+ content: 'tail',
+ fileType: 'txt',
+ filename: 'big.txt',
+ totalCharCount: 148_370,
+ totalLineCount: 2545,
+ }),
+ });
+ const runtime = new LocalSystemExecutionRuntime(service);
+
+ const output = await runtime.readFile({ path: '/tmp/big.txt', startLine: 2001 });
+
+ expect(output.content).not.toContain('(lines');
+ expect(output.content).toContain('2001 tail');
+ });
});
describe('LocalSystemExecutionRuntime.executeToolCall β€” working directory anchoring', () => {
diff --git a/packages/tool-runtime/src/types.ts b/packages/tool-runtime/src/types.ts
index 15aa99bf1ca..0a35e6a0a2e 100644
--- a/packages/tool-runtime/src/types.ts
+++ b/packages/tool-runtime/src/types.ts
@@ -32,6 +32,8 @@ export interface ReadFileParams {
/** Working directory a relative `path` resolves against on the service side. */
cwd?: string;
endLine?: number;
+ /** 0-based end-exclusive line window (local-system). */
+ loc?: [number, number];
path: string;
startLine?: number;
}
@@ -209,6 +211,8 @@ export interface ReadFileState {
totalCharCount?: number;
/** Total line count of the entire file */
totalLines?: number;
+ /** The service cut the content at its character cap before the window ended */
+ truncated?: boolean;
}
export interface WriteFileState {
diff --git a/src/store/chat/slices/agentRun/actions/transports/client/localSystemToolSnapshots.ts b/src/store/chat/slices/agentRun/actions/transports/client/localSystemToolSnapshots.ts
index b6f49e7b4c2..fd7d42f4f5f 100644
--- a/src/store/chat/slices/agentRun/actions/transports/client/localSystemToolSnapshots.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/client/localSystemToolSnapshots.ts
@@ -22,6 +22,7 @@ const normalizeReadResult = (result: LocalReadFileResult) => ({
loc: result.loc,
totalCharCount: result.totalCharCount,
totalLineCount: result.totalLineCount,
+ truncated: result.truncated,
});
const createReadSnapshot = async (
@@ -35,8 +36,10 @@ const createReadSnapshot = async (
const result = await localFileService.readLocalFile(args);
const content = formatFileContent({
content: result.content,
+ firstLineNumber: result.loc[0] + 1,
lineRange: result.loc,
- path: reference.path,
+ totalLines: result.totalLineCount,
+ truncated: result.truncated,
});
const state = {
charCount: result.charCount,