🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
⚡️ perf: shell output optimization (#15777)
Rylan Cai0746a125a924
diff --git a/apps/cli/src/tools/index.test.ts b/apps/cli/src/tools/index.test.tsindex affa7ac85a1..43c174fbb25 100644--- a/apps/cli/src/tools/index.test.ts+++ b/apps/cli/src/tools/index.test.ts@@ -26,6 +26,7 @@ describe('executeToolCall', () => {});afterEach(() => {+ vi.unstubAllEnvs();fs.rmSync(tmpDir, { force: true, recursive: true });});@@ -73,8 +74,8 @@ describe('executeToolCall', () => {expect(result.success).toBe(true);expect(result.content).toContain('dispatched');- const state = result.state as { output?: string; stdout?: string };- expect(state.stdout ?? state.output).toContain('dispatched');+ const state = result.state as { stdout?: string };+ expect(state.stdout).toContain('dispatched');});it('should dispatch listFiles', async () => {@@ -152,26 +153,19 @@ describe('executeToolCall', () => {});it('should dispatch grepContent', async () => {- const workerResult = {- content: 'grep result',- state: { matches: [{ type: 'match' }] },- success: true,- };- const spy = vi- .spyOn(isolatedWorker, 'executeToolCallInWorker')- .mockResolvedValueOnce(workerResult);+ const pattern = `findme-${process.pid}`;+ await writeFile(path.join(tmpDir, 'grep.txt'), `${pattern} here`);+ vi.stubEnv('LOBEHUB_CLI_TOOL_WORKER', '1');const result = await executeToolCall('grepContent',- JSON.stringify({ cwd: tmpDir, pattern: 'findme' }),+ // Use the manifest-facing `scope` field. `directory` is a runtime-only+ // normalized shape and would hide scope->cwd forwarding regressions.+ JSON.stringify({ glob: '*.txt', output_mode: 'files_with_matches', pattern, scope: tmpDir }),);- expect(result).toEqual(workerResult);- expect(spy).toHaveBeenCalledWith(- 'grepContent',- JSON.stringify({ cwd: tmpDir, pattern: 'findme' }),- undefined,- );+ expect(result.success).toBe(true);+ expect((result.state as { totalMatches: number }).totalMatches).toBe(1);});it('should dispatch searchFiles', async () => {diff --git a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.tsindex ed4cf067461..6894b3ecf6e 100644--- a/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/GatewayConnectionCtr.test.ts@@ -193,7 +193,7 @@ vi.mock('node:child_process', async (importOriginal) => {});vi.mock('node:os', () => ({- default: { hostname: vi.fn(() => 'mock-hostname') },+ default: { hostname: vi.fn(() => 'mock-hostname'), tmpdir: vi.fn(() => '/tmp') },}));vi.mock('@lobechat/device-gateway-client', () => ({diff --git a/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.tsindex 1a312814b77..5f6fbf93f26 100644--- a/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/ShellCommandCtr.test.ts@@ -1,3 +1,5 @@+import { writeSync } from 'node:fs';+import { beforeEach, describe, expect, it, vi } from 'vitest';import type { App } from '@/core/App';@@ -46,9 +48,17 @@ describe('ShellCommandCtr (thin wrapper)', () => {let ctr: ShellCommandCtr;let mockSpawn: any;let mockChildProcess: any;+ let mockProcessOutput: string;+ let listeners: Map<string, Set<(...args: any[]) => void>>;++ const emitChildProcess = (event: string, ...args: any[]) => {+ for (const listener of listeners.get(event) ?? []) listener(...args);+ };beforeEach(async () => {vi.clearAllMocks();+ mockProcessOutput = '';+ listeners = new Map();const childProcessModule = await import('node:child_process');mockSpawn = vi.mocked(childProcessModule.spawn);@@ -56,31 +66,50 @@ describe('ShellCommandCtr (thin wrapper)', () => {mockChildProcess = {stdout: { on: vi.fn() },stderr: { on: vi.fn() },- off: vi.fn(),- on: vi.fn(),- once: vi.fn(),+ // ShellProcessManager registers and later removes child process listeners+ // while racing exit/error/timeout and waiting for close. Keep enough+ // EventEmitter semantics here so the test follows the real lifecycle.+ off: vi.fn((event: string, callback: (...args: any[]) => void) => {+ listeners.get(event)?.delete(callback);+ return mockChildProcess;+ }),+ on: vi.fn((event: string, callback: (...args: any[]) => void) => {+ const eventListeners = listeners.get(event) ?? new Set();+ eventListeners.add(callback);+ listeners.set(event, eventListeners);+ return mockChildProcess;+ }),+ once: vi.fn((event: string, callback: (...args: any[]) => void) => {+ const onceCallback = (...args: any[]) => {+ listeners.get(event)?.delete(onceCallback);+ callback(...args);+ };+ const eventListeners = listeners.get(event) ?? new Set();+ eventListeners.add(onceCallback);+ listeners.set(event, eventListeners);+ return mockChildProcess;+ }),kill: vi.fn(),exitCode: null,};- mockSpawn.mockReturnValue(mockChildProcess);+ mockSpawn.mockImplementation((_cmd: string, _args: string[], options: any) => {+ const outputFd = Array.isArray(options?.stdio) ? options.stdio[1] : undefined;+ if (typeof outputFd === 'number' && mockProcessOutput) {+ writeSync(outputFd, mockProcessOutput);+ }+ return mockChildProcess;+ });ctr = new ShellCommandCtr(mockApp);});it('should delegate handleRunCommand to shared runCommand', async () => {- mockChildProcess.on.mockImplementation((event: string, callback: any) => {- if (event === 'exit') setTimeout(() => callback(0), 10);- return mockChildProcess;- });- mockChildProcess.once.mockImplementation((event: string, callback: any) => {- if (event === 'exit') setTimeout(() => callback(0), 10);- return mockChildProcess;- });- mockChildProcess.stdout.on.mockImplementation((event: string, callback: any) => {- if (event === 'data') setTimeout(() => callback(Buffer.from('output\n')), 5);- return mockChildProcess.stdout;- });- mockChildProcess.stderr.on.mockImplementation(() => mockChildProcess.stderr);+ mockProcessOutput = 'output\n';+ setTimeout(() => {+ mockChildProcess.exitCode = 0;+ emitChildProcess('exit', 0);+ emitChildProcess('close', 0);+ }, 10);const result = await ctr.handleRunCommand({command: 'echo test',@@ -88,23 +117,11 @@ describe('ShellCommandCtr (thin wrapper)', () => {});expect(result.success).toBe(true);- expect(result.stdout).toContain('output');+ expect(result.output).toContain('output');});it('should delegate handleGetCommandOutput to processManager', async () => {- mockChildProcess.on.mockImplementation((event: string, callback: any) => {- if (event === 'exit') setTimeout(() => callback(0), 10);- return mockChildProcess;- });- mockChildProcess.once.mockImplementation((event: string, callback: any) => {- if (event === 'exit') setTimeout(() => callback(0), 10);- return mockChildProcess;- });- mockChildProcess.stdout.on.mockImplementation((event: string, callback: any) => {- if (event === 'data') setTimeout(() => callback(Buffer.from('bg output\n')), 5);- return mockChildProcess.stdout;- });- mockChildProcess.stderr.on.mockImplementation(() => mockChildProcess.stderr);+ mockProcessOutput = 'bg output\n';const runResult = await ctr.handleRunCommand({command: 'test',@@ -115,10 +132,11 @@ describe('ShellCommandCtr (thin wrapper)', () => {const result = await ctr.handleGetCommandOutput({shell_id: runResult.shell_id!,+ timeout: 0,});expect(result.success).toBe(true);- expect(result.stdout).toContain('bg output');+ expect(result.output).toContain('bg output');});it('should delegate handleKillCommand to processManager', async () => {@@ -148,7 +166,7 @@ describe('ShellCommandCtr (thin wrapper)', () => {expect(mockCliCtr.runCliCommand).toHaveBeenCalledWith('status --json');expect(result.success).toBe(true);- expect(result.stdout).toContain('cli output');+ expect(result.output).toContain('cli output');expect(mockSpawn).not.toHaveBeenCalled();});diff --git a/apps/server/src/services/sandbox/__tests__/computerRuntime.test.ts b/apps/server/src/services/sandbox/__tests__/computerRuntime.test.tsindex 91add2cf56f..c0e33136810 100644--- a/apps/server/src/services/sandbox/__tests__/computerRuntime.test.ts+++ b/apps/server/src/services/sandbox/__tests__/computerRuntime.test.ts@@ -40,8 +40,7 @@ describe('ComputerRuntime command status mapping', () => {it('uses command output result success when background task transport succeeds', async () => {const runtime = new TestComputerRuntime({result: {- output: 'failed',- running: false,+ stdout: 'failed',success: false,},success: true,@@ -51,8 +50,7 @@ describe('ComputerRuntime command status mapping', () => {expect(result).toMatchObject({state: {- newOutput: 'failed',- running: false,+ stdout: 'failed',success: false,},success: true,diff --git a/packages/builtin-tool-local-system/src/manifest.ts b/packages/builtin-tool-local-system/src/manifest.tsindex 290626593d5..e1ff4f5e34f 100644--- a/packages/builtin-tool-local-system/src/manifest.ts+++ b/packages/builtin-tool-local-system/src/manifest.ts@@ -86,7 +86,7 @@ export const LocalSystemManifest: BuiltinToolManifest = {},scope: {description:- 'Working directory scope. Limits the search to this directory. Defaults to the current working directory.',+ 'Working directory scope. Limits the search to this directory. If you are searching the current project or are unsure, use "." for the current working directory. Use a specific path when the user names one explicitly.',type: 'string',},limit: {@@ -258,7 +258,7 @@ export const LocalSystemManifest: BuiltinToolManifest = {{defaultTimeoutMs: 30_000,description:- 'Retrieve output from a running or completed background shell command. Waits for one output window (up to 30 seconds by default) and returns only new output since the last check.',+ 'Retrieve output from a running or completed background shell command. Waits for one output window (up to 30 seconds by default).',name: LocalSystemApiName.getCommandOutput,parameters: {properties: {@@ -390,7 +390,7 @@ export const LocalSystemManifest: BuiltinToolManifest = {},scope: {description:- 'Working directory scope. When `pattern` is relative, it is joined with this scope. Defaults to the current working directory.',+ 'Working directory scope. When `pattern` is relative, it is joined with this scope. If you are searching the current project or are unsure, use "." for the current working directory. Use a specific path when the user names one explicitly.',type: 'string',},},diff --git a/packages/builtin-tool-local-system/src/systemRole.desktop.ts b/packages/builtin-tool-local-system/src/systemRole.desktop.tsindex 1de0c2eceb2..c6eaf4611be 100644--- a/packages/builtin-tool-local-system/src/systemRole.desktop.ts+++ b/packages/builtin-tool-local-system/src/systemRole.desktop.ts@@ -28,7 +28,7 @@ You have access to a set of tools to interact with the user's local file system:**Shell Commands:**5. **runCommand**: Start a terminal session to execute shell commands and return console output collected during the wait window. When providing a description, always use the same language as the user's input.-6. **getCommandOutput**: Retrieve output from an existing terminal session. Returns only new output since last check.+6. **getCommandOutput**: Retrieve output from an existing terminal session.7. **killCommand**: Terminate a running terminal session by its ID.**Search & Find:**@@ -58,7 +58,7 @@ You have access to a set of tools to interact with the user's local file system:- 'createdAfter' / 'createdBefore': Filter by creation date.- 'modifiedAfter' / 'modifiedBefore': Filter by modification date.- 'fileTypes': Filter by file type (e.g., "public.image", "txt").- - 'scope': Limit the search to a specific directory. **Always set this to the user's relevant folder (e.g., {{downloadsPath}}) when they refer to a known location** — without 'scope' the search spans the entire Spotlight index and is much slower.+ - 'scope': Limit the search to a specific directory. Use "." when searching the current working directory or when unsure. **Always set this to the user's relevant folder (e.g., {{downloadsPath}}) when they refer to a known location** — without 'scope' the search spans the entire Spotlight index and is much slower.- 'exclude': Exclude specific files or directories.- 'limit': Limit the number of results returned.- 'sortBy' / 'sortDirection': Sort the results.@@ -85,7 +85,7 @@ You have access to a set of tools to interact with the user's local file system:- For retrieving output from terminal sessions: Use 'getCommandOutput'. Provide:- 'shell_id': The ID returned from runCommand.- 'filter' (Optional): A regex pattern to filter output lines.- Returns only new output since the last check. Each call observes another wait window, so repeated checks consume real time.+ Returns a current output snapshot.- For killing running terminal sessions: Use 'killCommand' with 'shell_id'.Treat terminal sessions as ongoing resources: when elapsed wait time and observed progress no longer match the command's expected lifecycle, reassess whether the session should continue running.- For remote device execution feedback: 'Device tool call failed (HTTP ...)' describes the remote-device/gateway layer, not necessarily the local operation.@@ -103,7 +103,7 @@ You have access to a set of tools to interact with the user's local file system:- 'head_limit' (Optional): Limit results to first N matches.- For finding files by pattern: Use 'globFiles'. Provide:- 'pattern': Glob pattern (e.g., "**/*.js", "src/**/*.ts").- - 'scope' (Optional): Directory to search in. **Always set this when looking inside a user folder** (e.g. {{downloadsPath}}) — when omitted it falls back to the user's home directory, which can be very slow for broad patterns like "**/*foo*".+ - 'scope' (Optional): Directory to search in. Use "." when searching the current working directory or when unsure. **Always set this when looking inside a user folder** (e.g. {{downloadsPath}}) — when omitted it falls back to the user's home directory, which can be very slow for broad patterns like "**/*foo*".Returns files sorted by modification time (most recent first).</tool_usage_guidelines>diff --git a/packages/builtin-tool-local-system/src/systemRole.ts b/packages/builtin-tool-local-system/src/systemRole.tsindex 3c293b60b60..eb05a9f4082 100644--- a/packages/builtin-tool-local-system/src/systemRole.ts+++ b/packages/builtin-tool-local-system/src/systemRole.ts@@ -17,7 +17,7 @@ You have access to a set of tools to interact with the user's local file system:**Shell Commands:**5. **runCommand**: Start a terminal session to execute shell commands and return console output collected during the wait window. When providing a description, always use the same language as the user's input.-6. **getCommandOutput**: Retrieve output from an existing terminal session. Returns only new output since last check.+6. **getCommandOutput**: Retrieve output from an existing terminal session.7. **killCommand**: Terminate a running terminal session by its ID.**Search & Find:**@@ -47,7 +47,7 @@ You have access to a set of tools to interact with the user's local file system:- 'createdAfter' / 'createdBefore': Filter by creation date.- 'modifiedAfter' / 'modifiedBefore': Filter by modification date.- 'fileTypes': Filter by file type (e.g., "public.image", "txt").- - 'scope': Limit the search to a specific directory. Without 'scope' the search spans the entire Spotlight index and is much slower.+ - 'scope': Limit the search to a specific directory. Use "." when searching the current working directory or when unsure. Without 'scope' the search spans the entire Spotlight index and is much slower.- 'exclude': Exclude specific files or directories.- 'limit': Limit the number of results returned.- 'sortBy' / 'sortDirection': Sort the results.@@ -74,7 +74,7 @@ You have access to a set of tools to interact with the user's local file system:- For retrieving output from terminal sessions: Use 'getCommandOutput'. Provide:- 'shell_id': The ID returned from runCommand.- 'filter' (Optional): A regex pattern to filter output lines.- Returns only new output since the last check. Each call observes another wait window, so repeated checks consume real time.+ Returns a current output snapshot.- For killing running terminal sessions: Use 'killCommand' with 'shell_id'.Treat terminal sessions as ongoing resources: when elapsed wait time and observed progress no longer match the command's expected lifecycle, reassess whether the session should continue running.- For remote device execution feedback: 'Device tool call failed (HTTP ...)' describes the remote-device/gateway layer, not necessarily the local operation.@@ -92,7 +92,7 @@ You have access to a set of tools to interact with the user's local file system:- 'head_limit' (Optional): Limit results to first N matches.- For finding files by pattern: Use 'globFiles'. Provide:- 'pattern': Glob pattern (e.g., "**/*.js", "src/**/*.ts").- - 'scope' (Optional): Directory to search in. **Always set this when looking inside a user folder** — when omitted it falls back to the user's home directory, which can be very slow for broad patterns like "**/*foo*".+ - 'scope' (Optional): Directory to search in. Use "." when searching the current working directory or when unsure. **Always set this when looking inside a user folder** — when omitted it falls back to the user's home directory, which can be very slow for broad patterns like "**/*foo*".Returns files sorted by modification time (most recent first).</tool_usage_guidelines>`;diff --git a/packages/builtin-tool-skills/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-skills/src/ExecutionRuntime/index.test.tsindex 3d8b48f666c..255ceb555fc 100644--- a/packages/builtin-tool-skills/src/ExecutionRuntime/index.test.ts+++ b/packages/builtin-tool-skills/src/ExecutionRuntime/index.test.ts@@ -29,7 +29,7 @@ describe('SkillsExecutionRuntime', () => {const result = await runtime.execScript(args);expect(result.success).toBe(true);- expect(result.content).toBe('hello');+ expect(result.content).toBe('Command completed successfully.\n\nStdout:\nhello');expect(result.state).toEqual({ command: 'echo hello', exitCode: 0, success: true });});@@ -37,8 +37,7 @@ describe('SkillsExecutionRuntime', () => {const service = createMockService({execScript: vi.fn().mockResolvedValue({exitCode: 1,- output: '',- stderr: 'command not found',+ output: 'command not found',success: false,} satisfies CommandResult),});@@ -47,7 +46,9 @@ describe('SkillsExecutionRuntime', () => {const result = await runtime.execScript(args);expect(result.success).toBe(false);- expect(result.content).toBe('command not found');+ expect(result.content).toBe(+ 'Command failed with exit code 1\n\nStdout:\ncommand not found',+ );expect(result.state).toEqual({ command: 'echo hello', exitCode: 1, success: false });});@@ -64,7 +65,9 @@ describe('SkillsExecutionRuntime', () => {const result = await runtime.execScript(args);- expect(result.content).toBe('stdout line\nstderr line');+ expect(result.content).toBe(+ 'Command completed successfully.\n\nStdout:\nstdout line\n\nStderr:\nstderr line',+ );});it('should return "(no output)" when output is empty', async () => {@@ -79,7 +82,7 @@ describe('SkillsExecutionRuntime', () => {const result = await runtime.execScript(args);- expect(result.content).toBe('(no output)');+ expect(result.content).toBe('Command completed successfully.');});it('should return success: false when execScript throws', async () => {@@ -109,15 +112,14 @@ describe('SkillsExecutionRuntime', () => {const result = await runtime.execScript(args);expect(result.success).toBe(true);- expect(result.content).toBe('ok');+ expect(result.content).toBe('Command completed successfully.\n\nStdout:\nok');});it('should return success: false when command fails with non-zero exit code', async () => {const service = createMockService({runCommand: vi.fn().mockResolvedValue({exitCode: 127,- output: '',- stderr: 'not found',+ output: 'not found',success: false,} satisfies CommandResult),});@@ -126,7 +128,7 @@ describe('SkillsExecutionRuntime', () => {const result = await runtime.execScript(args);expect(result.success).toBe(false);- expect(result.content).toBe('not found');+ expect(result.content).toBe('Command failed with exit code 127\n\nStdout:\nnot found');expect(result.state).toEqual({ command: 'echo hello', exitCode: 127, success: false });});diff --git a/packages/electron-client-ipc/src/types/localSystem.ts b/packages/electron-client-ipc/src/types/localSystem.tsindex 6d6287d6c19..073da0eefc7 100644--- a/packages/electron-client-ipc/src/types/localSystem.ts+++ b/packages/electron-client-ipc/src/types/localSystem.ts@@ -272,9 +272,14 @@ export interface RunCommandParams {}export interface RunCommandResult {+ duration_ms?: number;error?: string;exit_code?: number;output?: string;+ output_files?: {+ stderr: { path: string; size: number; truncated: boolean };+ stdout: { path: string; size: number; truncated: boolean };+ };shell_id?: string;stderr?: string;stdout?: string;@@ -292,6 +297,7 @@ export interface GetCommandOutputParams {}export interface GetCommandOutputResult {+ duration_ms?: number;error?: string;/*** Present only after the command has exited.@@ -300,6 +306,10 @@ export interface GetCommandOutputResult {*/exit_code?: number;output: string;+ output_files?: {+ stderr: { path: string; size: number; truncated: boolean };+ stdout: { path: string; size: number; truncated: boolean };+ };stderr: string;stdout: string;success: boolean;diff --git a/packages/local-file-shell/package.json b/packages/local-file-shell/package.jsonindex 32c500947ac..52cb6cfd367 100644--- a/packages/local-file-shell/package.json+++ b/packages/local-file-shell/package.json@@ -10,7 +10,8 @@"debug": "^4.4.3","diff": "^8.0.4","execa": "^9.6.1",- "fast-glob": "^3.3.3"+ "fast-glob": "^3.3.3",+ "tree-kill": "^1.2.2"},"devDependencies": {"@types/debug": "^4.1.13"diff --git a/packages/local-file-shell/src/contentSearch/impl/unix.ts b/packages/local-file-shell/src/contentSearch/impl/unix.tsindex 4833d0b3abe..48470685d01 100644--- a/packages/local-file-shell/src/contentSearch/impl/unix.ts+++ b/packages/local-file-shell/src/contentSearch/impl/unix.ts@@ -150,6 +150,7 @@ export abstract class UnixContentSearch extends BaseContentSearch {const { stdout, stderr, exitCode } = await execa(tool, args, {cwd: searchPath,reject: false,+ stdin: 'ignore',});if (exitCode !== 0 && exitCode !== 1 && stderr) {@@ -225,6 +226,7 @@ export abstract class UnixContentSearch extends BaseContentSearch {const { stdout } = await execa(tool, args, {cwd: this.resolveSearchPath(params),reject: false,+ stdin: 'ignore',});let total = 0;diff --git a/packages/local-file-shell/src/contentSearch/impl/windows.ts b/packages/local-file-shell/src/contentSearch/impl/windows.tsindex 5a18d105540..c6c9edcf5c3 100644--- a/packages/local-file-shell/src/contentSearch/impl/windows.ts+++ b/packages/local-file-shell/src/contentSearch/impl/windows.ts@@ -129,6 +129,7 @@ export class WindowsContentSearchImpl extends BaseContentSearch {const { stdout, stderr, exitCode } = await execa('rg', args, {cwd: searchPath,reject: false,+ stdin: 'ignore',});if (exitCode !== 0 && exitCode !== 1 && stderr) {@@ -200,6 +201,7 @@ export class WindowsContentSearchImpl extends BaseContentSearch {const { stdout } = await execa('rg', args, {cwd: this.resolveSearchPath(params),reject: false,+ stdin: 'ignore',});let total = 0;@@ -242,6 +244,7 @@ export class WindowsContentSearchImpl extends BaseContentSearch {const { stdout, exitCode } = await execa('cmd', ['/c', `findstr ${args.join(' ')}`], {cwd: searchPath,reject: false,+ stdin: 'ignore',});if (exitCode !== 0 && exitCode !== 1) {diff --git a/packages/local-file-shell/src/file/__tests__/file.test.ts b/packages/local-file-shell/src/file/__tests__/file.test.tsindex 6a759cffee4..4ae4771c5d9 100644--- a/packages/local-file-shell/src/file/__tests__/file.test.ts+++ b/packages/local-file-shell/src/file/__tests__/file.test.ts@@ -592,6 +592,15 @@ describe('file operations', () => {expect(result).toHaveProperty('success');expect(result).toHaveProperty('matches');+ expect(result.matches).toContain('./search.txt');+ });++ it('should return matching lines in content mode', async () => {+ await writeFile(path.join(tmpDir, 'search.txt'), 'hello world\nfoo bar\nhello again');++ const result = await grepContent({ cwd: tmpDir, output_mode: 'content', pattern: 'hello' });++ expect(result.matches[0]).toContain('./search.txt:1:1:hello world');});it('should handle no matches', async () => {diff --git a/packages/local-file-shell/src/file/grep.ts b/packages/local-file-shell/src/file/grep.tsindex c77900c419a..f7fc9a606af 100644--- a/packages/local-file-shell/src/file/grep.ts+++ b/packages/local-file-shell/src/file/grep.ts@@ -5,15 +5,15 @@ import { expandTilde } from './expandTilde';import { hasHiddenSegment } from './hasHiddenSegment';/**- * Lightweight grep — spawns `rg` directly and returns the raw `--json`- * events. For the platform-aware fallback chain (rg → ag → grep → nodejs)- * with rich `output_mode` / `-A/-B/-C` support, use+ * Lightweight grep — spawns `rg` directly. For the platform-aware fallback+ * chain (rg → ag → grep → nodejs) with rich `output_mode` / `-A/-B/-C` support, use* `createContentSearchImpl()` from `@lobechat/local-file-shell/contentSearch`.*/export async function grepContent({pattern,cwd,filePattern,+ output_mode = 'files_with_matches',}: GrepContentParams): Promise<GrepContentResult> {const wantsHidden = hasHiddenSegment(filePattern);const hint = wantsHidden@@ -21,14 +21,24 @@ export async function grepContent({: undefined;return new Promise<GrepContentResult>((resolve) => {- const args = ['--json', '-n'];+ const args = ['--color=never', '--no-heading', '--with-filename', '--max-columns', '500'];if (wantsHidden) {args.push('--hidden', '--glob', '!**/.git/**');}+ if (output_mode === 'files_with_matches') {+ args.push('--files-with-matches');+ } else if (output_mode === 'count') {+ args.push('--count');+ } else {+ args.push('--line-number', '--column');+ }if (filePattern) args.push('--glob', filePattern);- args.push(pattern);+ args.push(pattern, '.');- const child = spawn('rg', args, { cwd: expandTilde(cwd) || process.cwd() });+ const child = spawn('rg', args, {+ cwd: expandTilde(cwd) || process.cwd(),+ stdio: ['ignore', 'pipe', 'pipe'],+ });let stdout = '';child.stdout?.on('data', (data) => {@@ -44,29 +54,22 @@ export async function grepContent({return;}- try {- const matches = stdout- .split('\n')- .filter(Boolean)- .map((line) => {- try {- return JSON.parse(line);- } catch {- return null;- }- })- .filter(Boolean);+ const matches = stdout.split('\n').filter(Boolean);+ const totalMatches =+ output_mode === 'count'+ ? matches.reduce((sum, line) => {+ const count = Number.parseInt(line.slice(line.lastIndexOf(':') + 1), 10);+ return sum + (Number.isNaN(count) ? 0 : count);+ }, 0)+ : matches.length;- resolve({- engine: 'rg',- hint,- matches,- success: true,- total_matches: matches.length,- });- } catch {- resolve({ engine: 'rg', hint, matches: [], success: true, total_matches: 0 });- }+ resolve({+ engine: 'rg',+ hint,+ matches,+ success: true,+ total_matches: totalMatches,+ });});child.on('error', () => {diff --git a/packages/local-file-shell/src/shell/__tests__/process-manager.test.ts b/packages/local-file-shell/src/shell/__tests__/process-manager.test.tsindex aa8a8851b70..6b00c79bf6c 100644--- a/packages/local-file-shell/src/shell/__tests__/process-manager.test.ts+++ b/packages/local-file-shell/src/shell/__tests__/process-manager.test.ts@@ -1,11 +1,15 @@import type { ChildProcess } from 'node:child_process';import { EventEmitter } from 'node:events';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';-import { type ShellProcess, ShellProcessManager } from '../process-manager';+import type { ShellProcess } from '../process-manager';+import { ShellProcessManager } from '../process-manager';-function createMockProcess(exitCode: number | null = null): ChildProcess {+function createMockProcess(exitCode: number | null = null, pid?: number): ChildProcess {const process = new EventEmitter() as ChildProcess;// Node types expose `exitCode` as readonly; make the test double writable so// we can simulate the child process exiting.@@ -14,26 +18,44 @@ function createMockProcess(exitCode: number | null = null): ChildProcess {value: exitCode,writable: true,});+ Object.defineProperty(process, 'pid', {+ configurable: true,+ value: pid,+ });process.kill = vi.fn() as unknown as ChildProcess['kill'];return process;}-function createShellProcess(process: ChildProcess): ShellProcess {+function createShellProcess(+ manager: ShellProcessManager,+ shellId: string,+ process: ChildProcess,+): ShellProcess {return {exitCode: process.exitCode,- lastReadStderr: 0,- lastReadStdout: 0,+ outputFiles: manager.createOutputFiles(shellId),process,- stderr: [],- stdout: [],};}+function writeOutput(shellProcess: ShellProcess, content: string): void {+ // Simulate child stdout writing into the inherited output fd.+ const buffer = Buffer.from(content);+ fs.writeSync(shellProcess.outputFiles.stdout.fd, buffer);+}+describe('ShellProcessManager', () => {let manager: ShellProcessManager;+ let tmpDir: string;beforeEach(() => {- manager = new ShellProcessManager();+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'lobehub-shell-process-manager-'));+ manager = new ShellProcessManager(tmpDir);+ });++ afterEach(() => {+ manager.cleanupAll();+ fs.rmSync(tmpDir, { force: true, recursive: true });});describe('getOutput', () => {@@ -44,47 +66,44 @@ describe('ShellProcessManager', () => {expect(result.error).toContain('not found');});- it('should retrieve stdout and stderr', async () => {+ it('should retrieve merged output', async () => {const process = createMockProcess();- manager.register('test-1', {- ...createShellProcess(process),- stderr: ['error line\n'],- stdout: ['line 1\n', 'line 2\n'],- });+ const shellProcess = createShellProcess(manager, 'test-1', process);+ writeOutput(shellProcess, 'line 1\nline 2\n');+ writeOutput(shellProcess, 'error line\n');+ manager.register('test-1', shellProcess);const result = await manager.getOutput({ shell_id: 'test-1', timeout: 0 });expect(result.success).toBe(true);expect(result.stdout).toContain('line 1');expect(result.stdout).toContain('line 2');- expect(result.stderr).toContain('error line');+ expect(result.stdout).toContain('error line');expect(result.exit_code).toBeUndefined();});- it('should return only new buffered output on repeated reads', async () => {+ it('should return a tail snapshot on repeated reads', async () => {const process = createMockProcess();- const shellProcess = {- ...createShellProcess(process),- stdout: ['first\n'],- };+ const shellProcess = createShellProcess(manager, 'test-1', process);+ writeOutput(shellProcess, 'first\n');manager.register('test-1', shellProcess);const first = await manager.getOutput({ shell_id: 'test-1', timeout: 0 });expect(first.stdout).toContain('first');const second = await manager.getOutput({ shell_id: 'test-1', timeout: 0 });- expect(second.stdout).toBe('');+ expect(second.stdout).toContain('first');- shellProcess.stdout.push('second\n');+ writeOutput(shellProcess, 'second\n');const third = await manager.getOutput({ shell_id: 'test-1', timeout: 0 });- expect(third.stdout).toBe('second\n');+ expect(third.stdout).toContain('second');});it('should return the current output snapshot when observation timeout elapses', async () => {vi.useFakeTimers();try {const process = createMockProcess();- const shellProcess = createShellProcess(process);+ const shellProcess = createShellProcess(manager, 'test-1', process);manager.register('test-1', shellProcess);let resolved = false;@@ -94,7 +113,7 @@ describe('ShellProcessManager', () => {});setTimeout(() => {- shellProcess.stdout.push('delayed\n');+ writeOutput(shellProcess, 'delayed\n');}, 20);await vi.advanceTimersByTimeAsync(20);@@ -113,7 +132,7 @@ describe('ShellProcessManager', () => {vi.useFakeTimers();try {const process = createMockProcess();- const shellProcess = createShellProcess(process);+ const shellProcess = createShellProcess(manager, 'test-1', process);manager.register('test-1', shellProcess);let resolved = false;@@ -136,36 +155,94 @@ describe('ShellProcessManager', () => {it('should return done when process exits before new output', async () => {const process = createMockProcess();- manager.register('test-1', createShellProcess(process));+ manager.register('test-1', createShellProcess(manager, 'test-1', process));const pending = manager.getOutput({ shell_id: 'test-1', timeout: 100 });setTimeout(() => {(process as { exitCode: number | null }).exitCode = 0;process.emit('exit', 0);+ process.emit('close', 0);}, 20);const result = await pending;expect(result.exit_code).toBe(0);});+ it('should wait for close before reading final output', async () => {+ const process = createMockProcess();+ const shellProcess = createShellProcess(manager, 'test-1', process);+ manager.register('test-1', shellProcess);++ // A child process can emit "exit" before stdio has fully closed. The+ // manager should wait for "close" before reading the final snapshot so+ // late-flushed output is not missed.+ const pending = manager.getOutput({ shell_id: 'test-1', timeout: 100 });++ setTimeout(() => {+ (process as { exitCode: number | null }).exitCode = 0;+ process.emit('exit', 0);+ writeOutput(shellProcess, 'late output after exit\n');+ process.emit('close', 0);+ }, 20);++ const result = await pending;+ expect(result.exit_code).toBe(0);+ expect(result.stdout).toContain('late output after exit');+ });++ it('should wait for close after the parent output fd has been released', async () => {+ const process = createMockProcess();+ const shellProcess = createShellProcess(manager, 'test-1', process);+ manager.register('test-1', shellProcess);+ manager.closeOutputFiles(shellProcess.outputFiles);++ const pending = manager.getOutput({ shell_id: 'test-1', timeout: 100 });++ setTimeout(() => {+ (process as { exitCode: number | null }).exitCode = 0;+ process.emit('exit', 0);+ fs.appendFileSync(shellProcess.outputFiles.stdout.path, 'late child output after exit\n');+ process.emit('close', 0);+ }, 20);++ const result = await pending;+ expect(result.exit_code).toBe(0);+ expect(result.stdout).toContain('late child output after exit');+ });+it('should filter output with regex', async () => {const process = createMockProcess();- manager.register('test-1', {- ...createShellProcess(process),- stdout: ['line 1\nline 2\nline 3\n'],- });+ const shellProcess = createShellProcess(manager, 'test-1', process);+ writeOutput(shellProcess, 'line 1\nline 2\nline 3\n');+ manager.register('test-1', shellProcess);const result = await manager.getOutput({ filter: 'line 1', shell_id: 'test-1', timeout: 0 });expect(result.success).toBe(true);- expect(result.output).toContain('line 1');- expect(result.output).not.toContain('line 2');+ expect(result.stdout).toContain('line 1');+ expect(result.stdout).not.toContain('line 2');+ });++ it('should filter consecutive matching lines', async () => {+ const process = createMockProcess();+ const shellProcess = createShellProcess(manager, 'test-1', process);+ writeOutput(shellProcess, 'match one\nmatch two\nskip\n');+ manager.register('test-1', shellProcess);++ const result = await manager.getOutput({ filter: '^match', shell_id: 'test-1', timeout: 0 });++ expect(result.success).toBe(true);+ expect(result.stdout).toContain('match one');+ expect(result.stdout).toContain('match two');+ expect(result.stdout).not.toContain('skip');});it('should handle invalid regex filter gracefully', async () => {const process = createMockProcess();- manager.register('test-1', { ...createShellProcess(process), stdout: ['output\n'] });+ const shellProcess = createShellProcess(manager, 'test-1', process);+ writeOutput(shellProcess, 'output\n');+ manager.register('test-1', shellProcess);const result = await manager.getOutput({filter: '[invalid(regex',@@ -174,17 +251,18 @@ describe('ShellProcessManager', () => {});expect(result.success).toBe(true);- expect(result.output).toContain('output');+ expect(result.stdout).toContain('output');});it('should reflect completion via exit_code', async () => {const process = createMockProcess();- manager.register('test-1', createShellProcess(process));+ manager.register('test-1', createShellProcess(manager, 'test-1', process));let result = await manager.getOutput({ shell_id: 'test-1', timeout: 0 });expect(result.exit_code).toBeUndefined();(process as { exitCode: number | null }).exitCode = 0;+ process.emit('close', 0);result = await manager.getOutput({ shell_id: 'test-1', timeout: 0 });expect(result.exit_code).toBe(0);@@ -194,7 +272,7 @@ describe('ShellProcessManager', () => {vi.useFakeTimers();try {const process = createMockProcess();- manager.register('test-1', createShellProcess(process));+ manager.register('test-1', createShellProcess(manager, 'test-1', process));await vi.advanceTimersByTimeAsync(42_000);@@ -210,11 +288,12 @@ describe('ShellProcessManager', () => {vi.useFakeTimers();try {const process = createMockProcess();- manager.register('test-1', createShellProcess(process));+ manager.register('test-1', createShellProcess(manager, 'test-1', process));await vi.advanceTimersByTimeAsync(2500);(process as { exitCode: number | null }).exitCode = 0;process.emit('exit', 0);+ process.emit('close', 0);await vi.advanceTimersByTimeAsync(7500);const result = await manager.getOutput({ shell_id: 'test-1', timeout: 0 });@@ -227,12 +306,12 @@ describe('ShellProcessManager', () => {it('should retain completed output after the process exits', async () => {const process = createMockProcess();- manager.register('test-1', {- ...createShellProcess(process),- stdout: ['done\n'],- });+ const shellProcess = createShellProcess(manager, 'test-1', process);+ writeOutput(shellProcess, 'done\n');+ manager.register('test-1', shellProcess);(process as { exitCode: number | null }).exitCode = 0;+ process.emit('close', 0);const result = await manager.getOutput({ shell_id: 'test-1', timeout: 0 });expect(result.success).toBe(true);@@ -244,12 +323,29 @@ describe('ShellProcessManager', () => {describe('kill', () => {it('should kill process successfully', () => {const process = createMockProcess();- manager.register('test-1', createShellProcess(process));+ manager.register('test-1', createShellProcess(manager, 'test-1', process));const result = manager.kill('test-1');expect(result.success).toBe(true);- expect(process.kill).toHaveBeenCalled();+ expect(process.kill).toHaveBeenCalledWith('SIGKILL');+ });++ it.skipIf(process.platform === 'win32')('should kill the process tree by pid', async () => {+ const killSpy = vi.spyOn(globalThis.process, 'kill').mockImplementation(() => true);+ try {+ const process = createMockProcess(null, 12_345);+ manager.register('test-1', createShellProcess(manager, 'test-1', process));++ const result = manager.kill('test-1');++ expect(result.success).toBe(true);+ await waitUntil(() => killSpy.mock.calls.some(([pid]) => pid === 12_345));+ expect(killSpy).toHaveBeenCalledWith(12_345, 'SIGKILL');+ expect(process.kill).not.toHaveBeenCalled();+ } finally {+ killSpy.mockRestore();+ }});it('should return error for non-existent shell_id', () => {@@ -261,7 +357,7 @@ describe('ShellProcessManager', () => {it('should remove process from registry after killing', async () => {const process = createMockProcess();- manager.register('test-1', createShellProcess(process));+ manager.register('test-1', createShellProcess(manager, 'test-1', process));manager.kill('test-1');@@ -275,7 +371,7 @@ describe('ShellProcessManager', () => {(process.kill as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => {throw new Error('Kill failed');});- manager.register('test-1', createShellProcess(process));+ manager.register('test-1', createShellProcess(manager, 'test-1', process));const result = manager.kill('test-1');@@ -288,13 +384,13 @@ describe('ShellProcessManager', () => {it('should kill all registered processes', async () => {const p1 = createMockProcess();const p2 = createMockProcess();- manager.register('test-1', createShellProcess(p1));- manager.register('test-2', createShellProcess(p2));+ manager.register('test-1', createShellProcess(manager, 'test-1', p1));+ manager.register('test-2', createShellProcess(manager, 'test-2', p2));manager.cleanupAll();- expect(p1.kill).toHaveBeenCalled();- expect(p2.kill).toHaveBeenCalled();+ expect(p1.kill).toHaveBeenCalledWith('SIGKILL');+ expect(p2.kill).toHaveBeenCalledWith('SIGKILL');expect((await manager.getOutput({ shell_id: 'test-1' })).success).toBe(false);expect((await manager.getOutput({ shell_id: 'test-2' })).success).toBe(false);});@@ -304,9 +400,51 @@ describe('ShellProcessManager', () => {(p1.kill as unknown as ReturnType<typeof vi.fn>).mockImplementation(() => {throw new Error('fail');});- manager.register('test-1', createShellProcess(p1));+ manager.register('test-1', createShellProcess(manager, 'test-1', p1));expect(() => manager.cleanupAll()).not.toThrow();});});});++describe('ShellProcessManager default output root', () => {+ it('should keep the default shell output path short and under the system temp dir', () => {+ vi.useFakeTimers();+ try {+ vi.setSystemTime(new Date(2026, 5, 14, 12, 34, 56));+ const manager = new ShellProcessManager();+ const outputFiles = manager.createOutputFiles('sh-1');++ expect(outputFiles.stdout.path).toBe(+ path.join(+ os.tmpdir(),+ 'lobehub',+ 'shell',+ '2026-6-14',+ process.pid.toString(),+ 'sh-1',+ 'stdout.log',+ ),+ );+ expect(fs.existsSync(outputFiles.stdout.path)).toBe(true);+ manager.cleanupAll();+ } finally {+ vi.useRealTimers();+ fs.rmSync(path.join(os.tmpdir(), 'lobehub', 'shell', '2026-6-14', process.pid.toString()), {+ force: true,+ recursive: true,+ });+ }+ });+});++const waitUntil = async (predicate: () => boolean, timeout = 2000): Promise<void> => {+ const startedAt = Date.now();++ while (Date.now() - startedAt < timeout) {+ if (predicate()) return;+ await new Promise((resolve) => setTimeout(resolve, 50));+ }++ throw new Error('Timed out waiting for condition');+};diff --git a/packages/local-file-shell/src/shell/__tests__/runner.test.ts b/packages/local-file-shell/src/shell/__tests__/runner.test.tsindex db193b5c592..5b3c1f37a0c 100644--- a/packages/local-file-shell/src/shell/__tests__/runner.test.ts+++ b/packages/local-file-shell/src/shell/__tests__/runner.test.ts@@ -1,13 +1,24 @@-import { afterEach, describe, expect, it } from 'vitest';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { ShellProcessManager } from '../process-manager';import { runCommand } from '../runner';describe('runCommand', () => {- const processManager = new ShellProcessManager();+ let processManager: ShellProcessManager;+ let tmpDir: string;++ beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'lobehub-shell-runner-'));+ processManager = new ShellProcessManager(tmpDir);+ });afterEach(() => {processManager.cleanupAll();+ fs.rmSync(tmpDir, { force: true, recursive: true });});describe('foreground observation mode', () => {@@ -21,7 +32,7 @@ describe('runCommand', () => {});it('should assign readable incremental shell IDs within a manager', async () => {- const localManager = new ShellProcessManager();+ const localManager = new ShellProcessManager(tmpDir);const first = await runCommand({ command: 'echo first' }, { processManager: localManager });const second = await runCommand({ command: 'echo second' }, { processManager: localManager });@@ -31,7 +42,7 @@ describe('runCommand', () => {localManager.cleanupAll();});- it('should capture stderr', async () => {+ it('should capture stderr output separately', async () => {const result = await runCommand({ command: 'echo error >&2' }, { processManager });expect(result.stderr).toContain('error');@@ -71,7 +82,7 @@ describe('runCommand', () => {{ processManager },);- expect(result.output).not.toContain('\u001B');+ expect(result.stdout).not.toContain('\u001B');});it('should truncate very long output', async () => {@@ -82,7 +93,7 @@ describe('runCommand', () => {{ processManager },);- expect(result.output!.length).toBeLessThanOrEqual(85_000);+ expect(result.stdout!.length).toBeLessThanOrEqual(85_000);}, 15_000);it('should pass cwd to command', async () => {@@ -116,6 +127,8 @@ describe('runCommand', () => {expect(result.success).toBe(true);expect(result.shell_id).toBeDefined();expect(result.exit_code).toBeUndefined();+ expect(result.output_files?.stdout.path).toMatch(/sh-\d+\/stdout\.log$/);+ expect(result.stdout).toBeUndefined();});it('should capture background process output', async () => {@@ -132,7 +145,7 @@ describe('runCommand', () => {expect(output.stdout).toContain('hello');});- it('should return only new buffered output on subsequent reads', async () => {+ it('should return the latest tail snapshot on subsequent reads', async () => {const bgResult = await runCommand({ command: 'echo first && sleep 0.2 && echo second', run_in_background: true },{ processManager },@@ -159,6 +172,43 @@ describe('runCommand', () => {expect(result.success).toBe(true);});+ it.skipIf(process.platform === 'win32')(+ 'should kill nested background process tree',+ async () => {+ // Reproduce the orphaned-child case: the shell command keeps a nested+ // writer alive that appends to a marker file. After kill(), the marker+ // size must stop changing, proving the whole process tree was killed.+ const markerPath = path.join(tmpDir, 'nested-process-marker.log');+ const bgResult = await runCommand(+ {+ command: `sh -c 'while :; do printf "tick\\n" >> "$LOB_TEST_MARKER"; sleep 0.05; done'`,+ env: { LOB_TEST_MARKER: markerPath },+ run_in_background: true,+ },+ { processManager },+ );++ const startedAt = Date.now();+ while (+ Date.now() - startedAt < 2000 &&+ (!fs.existsSync(markerPath) || fs.statSync(markerPath).size === 0)+ ) {+ await new Promise((resolve) => setTimeout(resolve, 50));+ }+ expect(fs.existsSync(markerPath) && fs.statSync(markerPath).size > 0).toBe(true);++ const result = processManager.kill(bgResult.shell_id!);+ expect(result.success).toBe(true);++ await new Promise((r) => setTimeout(r, 100));+ const sizeAfterKill = fs.statSync(markerPath).size;++ await new Promise((r) => setTimeout(r, 300));+ expect(fs.statSync(markerPath).size).toBe(sizeAfterKill);+ },+ 10_000,+ );+it('should return error for unknown shell_id', async () => {const result = await processManager.getOutput({ shell_id: 'unknown-id' });expect(result.success).toBe(false);@@ -185,7 +235,7 @@ describe('runCommand', () => {});expect(output.success).toBe(true);- expect(output.output).toContain('line2');+ expect(output.stdout).toContain('line2');});it('should handle invalid filter regex', async () => {diff --git a/packages/local-file-shell/src/shell/__tests__/utils.test.ts b/packages/local-file-shell/src/shell/__tests__/utils.test.tsindex bd4e7ffa852..39b42998edc 100644--- a/packages/local-file-shell/src/shell/__tests__/utils.test.ts+++ b/packages/local-file-shell/src/shell/__tests__/utils.test.ts@@ -1,66 +1,6 @@import { describe, expect, it } from 'vitest';-import { getShellConfig, MAX_OUTPUT_LENGTH, truncateOutput } from '../utils';--describe('truncateOutput', () => {- it('should return string as-is when within limit', () => {- expect(truncateOutput('short', 100)).toBe('short');- });-- it('should truncate long string with indicator', () => {- const long = 'x'.repeat(200);- const result = truncateOutput(long, 100);-- expect(result.length).toBeLessThan(200);- expect(result).toContain('truncated');- expect(result).toContain('more characters');- });-- it('should preserve ANSI escape codes so the client can render colors', () => {- const colored = '\x1B[31m' + 'x'.repeat(50) + '\x1B[0m';- const result = truncateOutput(colored, 100);- expect(result).toBe(colored);- expect(result).toContain('\x1B[');- });-- it('should reset an open SGR state before the truncation notice', () => {- // A long colored line whose closing \x1B[0m falls beyond the cut boundary.- const colored = '\x1B[31m' + 'x'.repeat(200) + '\x1B[0m';- const result = truncateOutput(colored, 100);-- expect(result).toContain('truncated');- // The reset must sit right before the notice so the color cannot bleed into it.- expect(result).toContain('\x1B[0m\n... [truncated');- // Everything after the reset (the notice) carries no further escape codes.- const notice = result.slice(result.indexOf('\x1B[0m\n'));- expect(notice.slice('\x1B[0m'.length)).not.toContain('\x1B[');- });-- it('should drop a partial escape sequence left dangling at the cut boundary', () => {- // maxLength lands in the middle of the second color sequence (\x1B[32 has no final byte yet).- const input = '\x1B[31mred' + '\x1B[32mgreen';- const cutInsideEscape = ('\x1B[31mred' + '\x1B[32').length;- const result = truncateOutput(input, cutInsideEscape);-- // The incomplete \x1B[32 must be removed, not carried into the output.- expect(result).not.toContain('\x1B[32');- expect(result.startsWith('\x1B[31mred')).toBe(true);- expect(result).toContain('\x1B[0m\n... [truncated');- });-- it('should not inject an ANSI reset into plain (non-colored) output', () => {- const result = truncateOutput('x'.repeat(200), 100);- expect(result).not.toContain('\x1B');- expect(result).toBe('x'.repeat(100) + '\n... [truncated, 100 more characters]');- });-- it('should use MAX_OUTPUT_LENGTH as default', () => {- const long = 'x'.repeat(MAX_OUTPUT_LENGTH + 1000);- const result = truncateOutput(long);- expect(result).toContain('truncated');- expect(result.length).toBeLessThan(long.length);- });-});+import { getShellConfig } from '../utils';describe('getShellConfig', () => {it('should return shell config for current platform', () => {diff --git a/packages/local-file-shell/src/shell/index.ts b/packages/local-file-shell/src/shell/index.tsindex 16dd56f59f1..7546703e956 100644--- a/packages/local-file-shell/src/shell/index.ts+++ b/packages/local-file-shell/src/shell/index.ts@@ -2,4 +2,4 @@ export type { ShellProcess } from './process-manager';export { ShellProcessManager } from './process-manager';export type { RunCommandOptions } from './runner';export { runCommand } from './runner';-export { getShellConfig, MAX_OUTPUT_LENGTH, truncateOutput } from './utils';+export { buildOutputPreview, getShellConfig, INLINE_OUTPUT_MAX_BYTES } from './utils';diff --git a/packages/local-file-shell/src/shell/process-manager.ts b/packages/local-file-shell/src/shell/process-manager.tsindex 4880e433d5d..8f078748c60 100644--- a/packages/local-file-shell/src/shell/process-manager.ts+++ b/packages/local-file-shell/src/shell/process-manager.ts@@ -1,31 +1,103 @@import type { ChildProcess } from 'node:child_process';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import treeKill from 'tree-kill';import type { GetCommandOutputParams, GetCommandOutputResult, KillCommandResult } from '../types';-import { truncateOutput } from './utils';+import { buildOutputPreview } from './utils';const DEFAULT_OBSERVATION_TIMEOUT_MS = 30_000;const MAX_OBSERVATION_TIMEOUT_MS = 120_000;+const RUN_COMMAND_HEAD_RATIO = 0.2;+const GET_COMMAND_OUTPUT_HEAD_RATIO = 0;+const OUTPUT_PREVIEW_TOTAL_MAX_BYTES = 22 * 1024;+const OUTPUT_PREVIEW_STREAM_MAX_BYTES = 18 * 1024;+const OUTPUT_PREVIEW_SECONDARY_MIN_BYTES = 4 * 1024;+const KILL_SIGNAL: NodeJS.Signals = 'SIGKILL';++export interface ShellOutputFile {+ fd: number;+ /** Tracks the parent fd only; child stdio close is tracked by ShellProcess.closedAt. */+ fdClosed?: boolean;+ path: string;+}++export interface ShellOutputFiles {+ stderr: ShellOutputFile;+ stdout: ShellOutputFile;+}export interface ShellProcess {+ closed?: Promise<void>;+ closedAt?: number;endedAt?: number;exitCode: number | null;- lastReadStderr: number;- lastReadStdout: number;+ outputFiles: ShellOutputFiles;process: ChildProcess;startedAt?: number;- stderr: string[];- stdout: string[];}export class ShellProcessManager {private nextShellId = 1;+ private readonly outputRunDir: string;+private processes = new Map<string, ShellProcess>();+ constructor(outputRoot?: string) {+ const date = new Date();++ this.outputRunDir = path.join(+ path.resolve(outputRoot ?? path.join(os.tmpdir(), 'lobehub', 'shell')),+ `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`,+ process.pid.toString(),+ );+ fs.mkdirSync(this.outputRunDir, { mode: 0o700, recursive: true });+ }+createShellId(): string {return `sh-${this.nextShellId++}`;}+ createOutputFiles(shellId: string): ShellOutputFiles {+ const outputDir = path.join(this.outputRunDir, shellId);+ fs.mkdirSync(outputDir, { mode: 0o700, recursive: true });++ return {+ stderr: this.createOutputFile(path.join(outputDir, 'stderr.log')),+ stdout: this.createOutputFile(path.join(outputDir, 'stdout.log')),+ };+ }++ createOutputFile(outputPath: string): ShellOutputFile {+ const fd =+ process.platform === 'win32'+ ? fs.openSync(outputPath, 'w', 0o600)+ : fs.openSync(+ outputPath,+ fs.constants.O_APPEND |+ fs.constants.O_CREAT |+ fs.constants.O_TRUNC |+ fs.constants.O_WRONLY |+ (fs.constants.O_NOFOLLOW ?? 0),+ 0o600,+ );++ return {+ fd,+ path: outputPath,+ };+ }++ getOutputFilesInfo(outputFiles: ShellOutputFiles): GetCommandOutputResult['output_files'] {+ return {+ stderr: this.getOutputFileInfo(outputFiles.stderr),+ stdout: this.getOutputFileInfo(outputFiles.stdout),+ };+ }+register(shellId: string, shellProcess: ShellProcess): void {shellProcess.startedAt ??= Date.now();if (shellProcess.exitCode !== null || shellProcess.process.exitCode !== null) {@@ -38,14 +110,34 @@ export class ShellProcessManager {shellProcess.process.once('exit', markEnded);shellProcess.process.once('error', markEnded);+ // Wait for the child stdio streams to close before reading the final output.+ // The process may emit "exit" before inherited streams finish flushing.+ shellProcess.closed =+ shellProcess.closedAt === undefined+ ? new Promise<void>((resolve) => {+ shellProcess.process.once('close', () => {+ shellProcess.closedAt ??= Date.now();+ shellProcess.endedAt ??= shellProcess.closedAt;+ this.closeOutputFiles(shellProcess.outputFiles);+ resolve();+ });+ })+ : Promise.resolve();this.processes.set(shellId, shellProcess);}- async getOutput({- filter,- shell_id,- timeout,- }: GetCommandOutputParams): Promise<GetCommandOutputResult> {+ async getRunCommandOutput(params: GetCommandOutputParams): Promise<GetCommandOutputResult> {+ return this.observeOutput(params, RUN_COMMAND_HEAD_RATIO);+ }++ async getOutput(params: GetCommandOutputParams): Promise<GetCommandOutputResult> {+ return this.observeOutput(params, GET_COMMAND_OUTPUT_HEAD_RATIO);+ }++ private async observeOutput(+ { filter, shell_id, timeout }: GetCommandOutputParams,+ headRatio: number,+ ): Promise<GetCommandOutputResult> {const shellProcess = this.processes.get(shell_id);if (!shellProcess) {return {@@ -57,7 +149,7 @@ export class ShellProcessManager {};}- const { lastReadStderr, lastReadStdout, process: childProcess, stderr, stdout } = shellProcess;+ const { process: childProcess } = shellProcess;let exitCode = childProcess.exitCode ?? shellProcess.exitCode;if (exitCode === null) {@@ -96,33 +188,62 @@ export class ShellProcessManager {exitCode = childProcess.exitCode ?? shellProcess.exitCode;if (exitCode !== null) {shellProcess.endedAt ??= Date.now();+ await shellProcess.closed;}- const newStdout = stdout.slice(lastReadStdout).join('');- const newStderr = stderr.slice(lastReadStderr).join('');- let output = newStdout + newStderr;+ const stdoutFileInfo = this.getOutputFileInfo(shellProcess.outputFiles.stdout);+ const stderrFileInfo = this.getOutputFileInfo(shellProcess.outputFiles.stderr);+ const previewBytes = allocateOutputPreviewBytes(stdoutFileInfo.size, stderrFileInfo.size);+ const stdoutPreview = buildOutputPreview(+ shellProcess.outputFiles.stdout.path,+ headRatio,+ previewBytes.stdout,+ );+ const stderrPreview = buildOutputPreview(+ shellProcess.outputFiles.stderr.path,+ headRatio,+ previewBytes.stderr,+ );+ let stdout = stdoutPreview.content;+ let stderr = stderrPreview.content;if (filter) {try {- const regex = new RegExp(filter, 'gm');- const lines = output.split('\n');- output = lines.filter((line) => regex.test(line)).join('\n');+ const regex = new RegExp(filter, 'm');+ stdout = stdout+ .split('\n')+ .filter((line) => regex.test(line))+ .join('\n');+ stderr = stderr+ .split('\n')+ .filter((line) => regex.test(line))+ .join('\n');} catch {// Invalid filter regex, use unfiltered output}}- shellProcess.lastReadStdout = stdout.length;- shellProcess.lastReadStderr = stderr.length;const startedAt = shellProcess.startedAt ?? Date.now();const durationMs = Math.max(0, (shellProcess.endedAt ?? Date.now()) - startedAt);return {duration_ms: durationMs,exit_code: exitCode ?? undefined,- output: truncateOutput(output),- stderr: truncateOutput(newStderr),- stdout: truncateOutput(newStdout),+ output: stdout + stderr,+ output_files: {+ stderr: {+ path: shellProcess.outputFiles.stderr.path,+ size: stderrPreview.size,+ truncated: stderrPreview.truncated,+ },+ stdout: {+ path: shellProcess.outputFiles.stdout.path,+ size: stdoutPreview.size,+ truncated: stdoutPreview.truncated,+ },+ },+ stderr,+ stdout,success: true,};}@@ -134,7 +255,8 @@ export class ShellProcessManager {}try {- shellProcess.process.kill();+ killProcessTree(shellProcess.process);+ this.closeOutputFiles(shellProcess.outputFiles);this.processes.delete(shell_id);return { success: true };} catch (error) {@@ -145,11 +267,85 @@ export class ShellProcessManager {cleanupAll(): void {for (const [id, sp] of this.processes) {try {- sp.process.kill();+ killProcessTree(sp.process);} catch {// Ignore}+ this.closeOutputFiles(sp.outputFiles);this.processes.delete(id);}}++ closeOutputFiles(outputFiles: ShellOutputFiles): void {+ for (const outputFile of [outputFiles.stdout, outputFiles.stderr]) {+ if (outputFile.fdClosed) continue;+ outputFile.fdClosed = true;+ try {+ fs.closeSync(outputFile.fd);+ } catch {+ // Ignore repeated close attempts.+ }+ }+ }++ private getOutputFileInfo(+ outputFile: ShellOutputFile,+ ): NonNullable<GetCommandOutputResult['output_files']>['stdout'] {+ let size = 0;+ try {+ size = fs.statSync(outputFile.path).size;+ } catch {+ // Keep the metadata shape stable even if the file was removed externally.+ }++ return {+ path: outputFile.path,+ size,+ truncated: false,+ };+ }}++const killProcessTree = (childProcess: ChildProcess): void => {+ const { pid } = childProcess;++ if (pid) {+ treeKill(pid, KILL_SIGNAL);+ return;+ }++ childProcess.kill(KILL_SIGNAL);+};++// Keep the inline preview under the model-facing budget while preserving both+// streams when stdout and stderr are both present.+const allocateOutputPreviewBytes = (+ stdoutSize: number,+ stderrSize: number,+): { stderr: number; stdout: number } => {+ if (stdoutSize + stderrSize <= OUTPUT_PREVIEW_TOTAL_MAX_BYTES) {+ return { stderr: stderrSize, stdout: stdoutSize };+ }++ if (stdoutSize <= 0) {+ return { stderr: Math.min(stderrSize, OUTPUT_PREVIEW_STREAM_MAX_BYTES), stdout: 0 };+ }++ if (stderrSize <= 0) {+ return { stderr: 0, stdout: Math.min(stdoutSize, OUTPUT_PREVIEW_STREAM_MAX_BYTES) };+ }++ const stdoutIsPrimary = stdoutSize >= stderrSize;+ const primarySize = stdoutIsPrimary ? stdoutSize : stderrSize;+ const secondarySize = stdoutIsPrimary ? stderrSize : stdoutSize;+ const secondaryBudget = Math.min(secondarySize, OUTPUT_PREVIEW_SECONDARY_MIN_BYTES);+ const primaryBudget = Math.min(+ primarySize,+ OUTPUT_PREVIEW_STREAM_MAX_BYTES,+ OUTPUT_PREVIEW_TOTAL_MAX_BYTES - secondaryBudget,+ );++ return stdoutIsPrimary+ ? { stderr: secondaryBudget, stdout: primaryBudget }+ : { stderr: primaryBudget, stdout: secondaryBudget };+};diff --git a/packages/local-file-shell/src/shell/runner.ts b/packages/local-file-shell/src/shell/runner.tsindex a43ba2ec31a..db0a99f7a6e 100644--- a/packages/local-file-shell/src/shell/runner.ts+++ b/packages/local-file-shell/src/shell/runner.ts@@ -1,7 +1,7 @@import { spawn } from 'node:child_process';import type { RunCommandParams, RunCommandResult } from '../types';-import type { ShellProcess, ShellProcessManager } from './process-manager';+import type { ShellOutputFiles, ShellProcess, ShellProcessManager } from './process-manager';import { getShellConfig } from './utils';export interface RunCommandOptions {@@ -33,32 +33,26 @@ export async function runCommand(const shellConfig = getShellConfig(command);const childEnv = extraEnv ? { ...process.env, ...extraEnv } : process.env;+ let outputFiles: ShellOutputFiles | undefined;try {const shellId = processManager.createShellId();+ const shellOutputFiles = processManager.createOutputFiles(shellId);+ outputFiles = shellOutputFiles;const childProcess = spawn(shellConfig.cmd, shellConfig.args, {cwd,+ detached: process.platform !== 'win32',env: childEnv,shell: false,+ stdio: ['pipe', shellOutputFiles.stdout.fd, shellOutputFiles.stderr.fd],});const shellProcess: ShellProcess = {exitCode: null,- lastReadStderr: 0,- lastReadStdout: 0,+ outputFiles: shellOutputFiles,process: childProcess,- stderr: [],- stdout: [],};- childProcess.stdout?.on('data', (data) => {- shellProcess.stdout.push(data.toString());- });-- childProcess.stderr?.on('data', (data) => {- shellProcess.stderr.push(data.toString());- });-childProcess.on('exit', (code) => {logger?.debug(`${logPrefix} Process exited`, { code, shellId });shellProcess.exitCode = code ?? 0;@@ -66,18 +60,24 @@ export async function runCommand(childProcess.on('error', (error) => {logger?.error(`${logPrefix} Command failed:`, error);- shellProcess.stderr.push(error.message);shellProcess.exitCode = 1;});processManager.register(shellId, shellProcess);+ // Close our fd copy only after error/close listeners are registered; spawn errors are asynchronous.+ processManager.closeOutputFiles(shellOutputFiles);logger?.info?.(`${logPrefix} Started session`, { background: run_in_background, shellId });if (run_in_background) {- return { shell_id: shellId, success: true };+ return {+ output: '',+ output_files: processManager.getOutputFilesInfo(shellOutputFiles),+ shell_id: shellId,+ success: true,+ };}- const observation = await processManager.getOutput({+ const observation = await processManager.getRunCommandOutput({shell_id: shellId,timeout,});@@ -87,6 +87,7 @@ export async function runCommand(shell_id: shellId,};} catch (error) {+ if (outputFiles) processManager.closeOutputFiles(outputFiles);return { error: (error as Error).message, success: false };}}diff --git a/packages/local-file-shell/src/shell/utils.ts b/packages/local-file-shell/src/shell/utils.tsindex 672070e57d0..58fe23b71da 100644--- a/packages/local-file-shell/src/shell/utils.ts+++ b/packages/local-file-shell/src/shell/utils.ts@@ -1,38 +1,86 @@-/** Maximum output length to prevent context explosion */-export const MAX_OUTPUT_LENGTH = 80_000;+import fs from 'node:fs';-/** ANSI SGR reset, closes any open color/style state */-const ANSI_RESET = '\u001B[0m';+/** Maximum preview bytes returned inline to prevent context explosion */+export const INLINE_OUTPUT_MAX_BYTES = 25 * 1024;++export interface OutputPreview {+ content: string;+ size: number;+ truncated: boolean;+}-/** Matches a complete ANSI escape sequence anchored at the start of the string */// eslint-disable-next-line no-control-regex, regexp/no-obscure-range-const ANSI_ESCAPE_AT_START = /^\u001B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/;--/**- * Truncate string to max length with indicator.- *- * ANSI escape codes are preserved so the client can render colored output, but a- * naive slice can (a) cut across an escape sequence and (b) stop while a color or- * style is still open. Either would bleed styling into the truncation notice and- * anything the client renders afterwards. So we drop a dangling partial sequence- * at the cut boundary and append a reset before the notice.- */-export const truncateOutput = (str: string, maxLength: number = MAX_OUTPUT_LENGTH): string => {- if (str.length <= maxLength) return str;-- let slice = str.slice(0, maxLength);-- // Drop a partial escape sequence left dangling at the cut boundary, otherwise- // it would consume the leading characters of the truncation notice.- const lastEsc = slice.lastIndexOf('\u001B');- if (lastEsc !== -1 && !ANSI_ESCAPE_AT_START.test(slice.slice(lastEsc))) {- slice = slice.slice(0, lastEsc);+const ANSI_ESCAPE = /\u001B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])/g;++const stripAnsi = (str: string): string => str.replaceAll(ANSI_ESCAPE, '');++const formatBytes = (bytes: number): string => {+ const kb = bytes / 1024;+ if (kb < 1) return `${bytes} bytes`;+ if (kb < 1024) return `${kb.toFixed(1).replace(/\.0$/, '')}KB`;+ const mb = kb / 1024;+ if (mb < 1024) return `${mb.toFixed(1).replace(/\.0$/, '')}MB`;+ const gb = mb / 1024;+ return `${gb.toFixed(1).replace(/\.0$/, '')}GB`;+};++export const buildOutputPreview = (+ filePath: string,+ headRatio: number,+ maxBytes = INLINE_OUTPUT_MAX_BYTES,+): OutputPreview => {+ let stat: fs.Stats;+ try {+ stat = fs.statSync(filePath);+ } catch {+ return { content: '', size: 0, truncated: false };}- // Reset any still-open SGR state so it cannot leak into the notice.- const reset = slice.includes('\u001B') ? ANSI_RESET : '';+ const size = stat.size;+ if (size <= 0 || maxBytes <= 0) {+ return { content: '', size, truncated: false };+ }- return slice + reset + '\n... [truncated, ' + (str.length - maxLength) + ' more characters]';+ const fd = fs.openSync(filePath, 'r');+ try {+ if (size <= maxBytes) {+ const buffer = Buffer.alloc(size);+ fs.readSync(fd, buffer, 0, size, 0);+ return {+ content: stripAnsi(buffer.toString('utf8')),+ size,+ truncated: false,+ };+ }++ const normalizedHeadRatio = Math.min(Math.max(headRatio, 0), 1);+ const headBytes = Math.floor(maxBytes * normalizedHeadRatio);+ const tailBytes = Math.max(0, maxBytes - headBytes);+ const omittedBytes = Math.max(0, size - headBytes - tailBytes);++ if (headBytes <= 0) {+ const tail = Buffer.alloc(Math.min(maxBytes, size));+ fs.readSync(fd, tail, 0, tail.length, Math.max(0, size - tail.length));+ return {+ content: `... [showing last ${formatBytes(tail.length)} of ${formatBytes(size)}; full output saved to: ${filePath}]\n${stripAnsi(tail.toString('utf8'))}`,+ size,+ truncated: true,+ };+ }++ const head = Buffer.alloc(headBytes);+ const tail = Buffer.alloc(tailBytes);+ fs.readSync(fd, head, 0, headBytes, 0);+ fs.readSync(fd, tail, 0, tailBytes, Math.max(0, size - tailBytes));++ return {+ content: `${stripAnsi(head.toString('utf8'))}\n... [omitted ${formatBytes(omittedBytes)}; full output saved to: ${filePath}]\n${stripAnsi(tail.toString('utf8'))}`,+ size,+ truncated: true,+ };+ } finally {+ fs.closeSync(fd);+ }};/** Get cross-platform shell configuration */diff --git a/packages/local-file-shell/src/types.ts b/packages/local-file-shell/src/types.tsindex f6064eb1b24..60d7d1ecddf 100644--- a/packages/local-file-shell/src/types.ts+++ b/packages/local-file-shell/src/types.ts@@ -14,6 +14,7 @@ export interface RunCommandParams {}export interface RunCommandResult {+ duration_ms?: number;error?: string;/*** Present only after the command has exited.@@ -22,6 +23,10 @@ export interface RunCommandResult {*/exit_code?: number;output?: string;+ output_files?: {+ stderr: { path: string; size: number; truncated: boolean };+ stdout: { path: string; size: number; truncated: boolean };+ };/*** Session identifier. Present for background commands and foreground commands* that can be resumed with `getCommandOutput`.@@ -61,6 +66,10 @@ export interface GetCommandOutputResult {*/exit_code?: number;output: string;+ output_files?: {+ stderr: { path: string; size: number; truncated: boolean };+ stdout: { path: string; size: number; truncated: boolean };+ };stderr: string;stdout: string;/**diff --git a/packages/prompts/src/prompts/fileSystem/formatCommandOutput.test.ts b/packages/prompts/src/prompts/fileSystem/formatCommandOutput.test.tsindex ed01796fe4c..eff09534919 100644--- a/packages/prompts/src/prompts/fileSystem/formatCommandOutput.test.ts+++ b/packages/prompts/src/prompts/fileSystem/formatCommandOutput.test.ts@@ -75,4 +75,87 @@ describe('formatCommandOutput', () => {Error: Warning message"`);});++ it('should format output as-is when it contains saved file metadata', () => {+ const result = formatCommandOutput({+ output:+ 'head\n... [omitted 12000 bytes; full output saved to: /tmp/lobehub-shell/output.log]\ntail',+ success: true,+ });++ expect(result).toMatchInlineSnapshot(`+ "Output retrieved.++ Output:+ head+ ... [omitted 12000 bytes; full output saved to: /tmp/lobehub-shell/output.log]+ tail"+ `);+ });++ it('should keep small saved output as normal output', () => {+ const result = formatCommandOutput({+ output: 'small output',+ success: true,+ });++ expect(result).toMatchInlineSnapshot(`+ "Output retrieved.++ Output:+ small output"+ `);+ });++ it('should format output file metadata', () => {+ const result = formatCommandOutput({+ output: 'preview output',+ outputFiles: {+ stdout: { path: '/tmp/lobehub-shell/stdout.log', size: 1536, truncated: false },+ },+ success: true,+ });++ expect(result).toMatchInlineSnapshot(`+ "Output retrieved.++ Full stdout saved to: /tmp/lobehub-shell/stdout.log (1.5KB)++ Output:+ preview output"+ `);+ });++ it('should format truncated output file metadata', () => {+ const result = formatCommandOutput({+ output: 'preview output',+ outputFiles: {+ stdout: { path: '/tmp/lobehub-shell/stdout.log', size: 1536, truncated: true },+ },+ success: true,+ });++ expect(result).toMatchInlineSnapshot(`+ "Output retrieved.++ Stdout too large (1.5KB). Full stdout saved to: /tmp/lobehub-shell/stdout.log++ Output:+ preview output"+ `);+ });++ it('should not special-case missing exit code when formatting output', () => {+ const result = formatCommandOutput({+ output: 'still running',+ success: true,+ });++ expect(result).toMatchInlineSnapshot(`+ "Output retrieved.++ Output:+ still running"+ `);+ });});diff --git a/packages/prompts/src/prompts/fileSystem/formatCommandOutput.ts b/packages/prompts/src/prompts/fileSystem/formatCommandOutput.tsindex 361ef243dda..b01b6211e3c 100644--- a/packages/prompts/src/prompts/fileSystem/formatCommandOutput.ts+++ b/packages/prompts/src/prompts/fileSystem/formatCommandOutput.ts@@ -3,6 +3,12 @@ export interface FormatCommandOutputParams {error?: string;exitCode?: number;output?: string;+ outputFiles?: {+ stderr?: { path: string; size?: number; truncated?: boolean };+ stdout?: { path: string; size?: number; truncated?: boolean };+ };+ stderr?: string;+ stdout?: string;success: boolean;}@@ -11,11 +17,25 @@ const formatDuration = (durationMs: number): string => {return `${seconds}s`;};+export const formatCommandOutputFileSize = (size?: number): string => {+ if (typeof size !== 'number' || !Number.isFinite(size)) return 'unknown size';+ const kb = size / 1024;+ if (kb < 1) return `${size} bytes`;+ if (kb < 1024) return `${kb.toFixed(1).replace(/\.0$/, '')}KB`;+ const mb = kb / 1024;+ if (mb < 1024) return `${mb.toFixed(1).replace(/\.0$/, '')}MB`;+ const gb = mb / 1024;+ return `${gb.toFixed(1).replace(/\.0$/, '')}GB`;+};+export const formatCommandOutput = ({durationMs,success,exitCode,output,+ outputFiles,+ stderr,+ stdout,error,}: FormatCommandOutputParams): string => {const message = success ? 'Output retrieved.' : `Failed: ${error}`;@@ -25,7 +45,25 @@ export const formatCommandOutput = ({if (durationMs !== undefined && Number.isFinite(durationMs)) {parts.push(`Duration: ${formatDuration(durationMs)}`);}+ if (outputFiles?.stdout?.path) {+ const size = formatCommandOutputFileSize(outputFiles.stdout.size);+ parts.push(+ outputFiles.stdout.truncated+ ? `Stdout too large (${size}). Full stdout saved to: ${outputFiles.stdout.path}`+ : `Full stdout saved to: ${outputFiles.stdout.path} (${size})`,+ );+ }+ if (outputFiles?.stderr?.path) {+ const size = formatCommandOutputFileSize(outputFiles.stderr.size);+ parts.push(+ outputFiles.stderr.truncated+ ? `Stderr too large (${size}). Full stderr saved to: ${outputFiles.stderr.path}`+ : `Full stderr saved to: ${outputFiles.stderr.path} (${size})`,+ );+ }if (output) parts.push(`Output:\n${output}`);+ if (stdout) parts.push(`Stdout:\n${stdout}`);+ if (stderr) parts.push(`Stderr:\n${stderr}`);if (error && success) parts.push(`Error: ${error}`);return parts.join('\n\n');diff --git a/packages/prompts/src/prompts/fileSystem/formatCommandResult.test.ts b/packages/prompts/src/prompts/fileSystem/formatCommandResult.test.tsindex 27a8d967e27..7ed7290ce7c 100644--- a/packages/prompts/src/prompts/fileSystem/formatCommandResult.test.ts+++ b/packages/prompts/src/prompts/fileSystem/formatCommandResult.test.ts@@ -19,7 +19,23 @@ describe('formatCommandResult', () => {`);});- it('should format successful command with stdout', () => {+ it('should format still-running command with output file path', () => {+ const result = formatCommandResult({+ outputFiles: {+ stdout: { path: '/tmp/lobehub-shell/stdout.log', size: 1536, truncated: false },+ },+ shellId: 'shell-123',+ success: true,+ });+ expect(result).toMatchInlineSnapshot(`+ "Command is still running after the wait window.+ shell_id: shell-123++ Full stdout saved to: /tmp/lobehub-shell/stdout.log (1.5KB)"+ `);+ });++ it('should format successful command with output', () => {const result = formatCommandResult({exitCode: 0,stdout: 'Hello World',@@ -28,22 +44,66 @@ describe('formatCommandResult', () => {expect(result).toMatchInlineSnapshot(`"Command completed successfully.- Output:+ Stdout:Hello World"`);});- it('should format successful command with stderr', () => {+ it('should format command output when it contains saved file metadata', () => {+ const result = formatCommandResult({+ exitCode: 0,+ stdout:+ 'first lines\n... [omitted 12000 bytes; full output saved to: /tmp/lobehub-shell/output.log]\nlast lines',+ success: true,+ });++ expect(result).toMatchInlineSnapshot(`+ "Command completed successfully.++ Stdout:+ first lines+ ... [omitted 12000 bytes; full output saved to: /tmp/lobehub-shell/output.log]+ last lines"+ `);+ });++ it('should format command output file metadata without large-output wording when not truncated', () => {+ const result = formatCommandResult({+ exitCode: 0,+ stdout: 'small output',+ outputFiles: {+ stdout: { path: '/tmp/lobehub-shell/stdout.log', size: 1536, truncated: false },+ },+ success: true,+ });++ expect(result).toMatchInlineSnapshot(`+ "Command completed successfully.++ Full stdout saved to: /tmp/lobehub-shell/stdout.log (1.5KB)++ Stdout:+ small output"+ `);+ });++ it('should format truncated command output file metadata', () => {const result = formatCommandResult({exitCode: 0,- stderr: 'Warning: deprecated',+ stdout: 'preview output',+ outputFiles: {+ stdout: { path: '/tmp/lobehub-shell/stdout.log', size: 1536, truncated: true },+ },success: true,});+expect(result).toMatchInlineSnapshot(`"Command completed successfully.- Stderr:- Warning: deprecated"+ Stdout too large (1.5KB). Full stdout saved to: /tmp/lobehub-shell/stdout.log++ Stdout:+ preview output"`);});@@ -73,7 +133,7 @@ describe('formatCommandResult', () => {expect(result).toMatchInlineSnapshot(`"Command failed with exit code 137- Output:+ Stdout:partial output"`);});@@ -90,18 +150,14 @@ describe('formatCommandResult', () => {const result = formatCommandResult({error: 'Command error',exitCode: 1,- stderr: 'Error occurred',stdout: 'Some output',success: false,});expect(result).toMatchInlineSnapshot(`"Command failed with exit code 1: Command error- Output:- Some output-- Stderr:- Error occurred"+ Stdout:+ Some output"`);});});diff --git a/packages/prompts/src/prompts/fileSystem/formatCommandResult.ts b/packages/prompts/src/prompts/fileSystem/formatCommandResult.tsindex 032c3da249c..36c01f85a85 100644--- a/packages/prompts/src/prompts/fileSystem/formatCommandResult.ts+++ b/packages/prompts/src/prompts/fileSystem/formatCommandResult.ts@@ -1,6 +1,12 @@+import { formatCommandOutputFileSize } from './formatCommandOutput';+export interface FormatCommandResultParams {error?: string;exitCode?: number;+ outputFiles?: {+ stderr?: { path: string; size?: number; truncated?: boolean };+ stdout?: { path: string; size?: number; truncated?: boolean };+ };shellId?: string;stderr?: string;stdout?: string;@@ -13,6 +19,7 @@ export const formatCommandResult = ({error,stdout,stderr,+ outputFiles,exitCode,}: FormatCommandResultParams): string => {const parts: string[] = [];@@ -34,7 +41,23 @@ export const formatCommandResult = ({parts.push('Command completed successfully.');}- if (stdout) parts.push(`Output:\n${stdout}`);+ if (outputFiles?.stdout?.path) {+ const size = formatCommandOutputFileSize(outputFiles.stdout.size);+ parts.push(+ outputFiles.stdout.truncated+ ? `Stdout too large (${size}). Full stdout saved to: ${outputFiles.stdout.path}`+ : `Full stdout saved to: ${outputFiles.stdout.path} (${size})`,+ );+ }+ if (outputFiles?.stderr?.path) {+ const size = formatCommandOutputFileSize(outputFiles.stderr.size);+ parts.push(+ outputFiles.stderr.truncated+ ? `Stderr too large (${size}). Full stderr saved to: ${outputFiles.stderr.path}`+ : `Full stderr saved to: ${outputFiles.stderr.path} (${size})`,+ );+ }+ if (stdout) parts.push(`Stdout:\n${stdout}`);if (stderr) parts.push(`Stderr:\n${stderr}`);return parts.join('\n\n');diff --git a/packages/shared-tool-ui/src/Render/RunCommand/index.tsx b/packages/shared-tool-ui/src/Render/RunCommand/index.tsxindex 36fd3fbb817..1aaf3aae456 100644--- a/packages/shared-tool-ui/src/Render/RunCommand/index.tsx+++ b/packages/shared-tool-ui/src/Render/RunCommand/index.tsx@@ -25,7 +25,8 @@ interface RunCommandArgs {const RunCommand = memo<BuiltinRenderProps<RunCommandArgs, RunCommandState>>(({ args, content, pluginState }) => {- const output = pluginState?.output || pluginState?.stdout || content;+ const output = pluginState?.stdout || pluginState?.output || content;+ const stderr = pluginState?.stderr;const command = getRunCommandDisplayCommand(args?.command);return (@@ -41,7 +42,7 @@ const RunCommand = memo<BuiltinRenderProps<RunCommandArgs, RunCommandState>>({command}</Highlighter>{output && <AnsiOutput text={output} />}- {pluginState?.stderr && <AnsiOutput text={pluginState.stderr} />}+ {stderr?.trim() && <AnsiOutput text={stderr} />}</Block></Flexbox>);diff --git a/packages/tool-runtime/src/ComputerRuntime.ts b/packages/tool-runtime/src/ComputerRuntime.tsindex 2f465daf510..d317c5afda9 100644--- a/packages/tool-runtime/src/ComputerRuntime.ts+++ b/packages/tool-runtime/src/ComputerRuntime.ts@@ -308,6 +308,7 @@ export abstract class ComputerRuntime {const r = result.result || {};const commandSuccess = typeof r.success === 'boolean' ? r.success : result.success;+ const outputFiles = r.outputFiles ?? r.output_files;const state: RunCommandState = {commandId: r.commandId || r.shell_id,@@ -315,6 +316,7 @@ export abstract class ComputerRuntime {exitCode: r.exitCode ?? r.exit_code,isBackground: args.background || false,output: r.output,+ outputFiles,stderr: r.stderr,stdout: r.stdout,success: commandSuccess,@@ -323,6 +325,7 @@ export abstract class ComputerRuntime {const content = formatCommandResult({error: r.error,exitCode: r.exitCode ?? r.exit_code,+ outputFiles,shellId: r.commandId || r.shell_id,stderr: r.stderr,stdout: r.stdout || r.output,@@ -348,13 +351,16 @@ export abstract class ComputerRuntime {const r = result.result || {};const outputSuccess = typeof r.success === 'boolean' ? r.success : result.success;+ const outputFiles = r.outputFiles ?? r.output_files;const state: GetCommandOutputState = {durationMs: r.durationMs ?? r.duration_ms,error: r.error,exitCode: r.exitCode ?? r.exit_code,- newOutput: r.newOutput || r.output,+ outputFiles,running: r.running ?? false,+ stderr: r.stderr,+ stdout: r.stdout,success: outputSuccess,};@@ -363,6 +369,9 @@ export abstract class ComputerRuntime {error: r.error,exitCode: r.exitCode ?? r.exit_code,output: r.newOutput || r.output,+ outputFiles,+ stderr: r.stderr,+ stdout: r.stdout,success: outputSuccess,});diff --git a/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts b/packages/tool-runtime/src/LocalSystemExecutionRuntime.tsindex 540a6e7246a..42f0f1b0646 100644--- a/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts+++ b/packages/tool-runtime/src/LocalSystemExecutionRuntime.ts@@ -138,6 +138,15 @@ export class LocalSystemExecutionRuntime extends ComputerRuntime {};}+ case 'grepContent': {+ return {+ cwd: params.directory ?? params.path ?? params.scope ?? params.cwd,+ filePattern: params.filePattern ?? params.glob,+ output_mode: params.output_mode,+ pattern: params.pattern,+ };+ }+default: {return params;}@@ -176,6 +185,8 @@ export class LocalSystemExecutionRuntime extends ComputerRuntime {exitCode: raw.exit_code,output: raw.output,commandId: raw.shell_id,+ durationMs: raw.duration_ms,+ outputFiles: raw.output_files,stderr: raw.stderr,stdout: raw.stdout,success: raw.success,@@ -190,7 +201,9 @@ export class LocalSystemExecutionRuntime extends ComputerRuntime {durationMs: raw.duration_ms,exitCode: raw.exit_code,error: raw.error,- newOutput: raw.output,+ outputFiles: raw.output_files,+ stderr: raw.stderr,+ stdout: raw.stdout,success: raw.success,},success: raw.success,diff --git a/packages/tool-runtime/src/types.ts b/packages/tool-runtime/src/types.tsindex 801be6cf5c2..9656f8df312 100644--- a/packages/tool-runtime/src/types.ts+++ b/packages/tool-runtime/src/types.ts@@ -188,6 +188,10 @@ export interface RunCommandState {exitCode?: number;isBackground: boolean;output?: string;+ outputFiles?: {+ stderr: { path: string; size: number; truncated: boolean };+ stdout: { path: string; size: number; truncated: boolean };+ };stderr?: string;stdout?: string;success: boolean;@@ -197,8 +201,13 @@ export interface GetCommandOutputState {durationMs?: number;error?: string;exitCode?: number;- newOutput?: string;+ outputFiles?: {+ stderr: { path: string; size: number; truncated: boolean };+ stdout: { path: string; size: number; truncated: boolean };+ };running?: boolean;+ stderr?: string;+ stdout?: string;success: boolean;}