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(shell): stop commands that read stdin from hanging the agent shell (#23430)

Arvin Xu734ebd6e12ae
diff --git a/apps/cli/src/commands/agent.test.ts b/apps/cli/src/commands/agent.test.ts
index aa231b5a6e8..b4c53c43ac9 100644
--- a/apps/cli/src/commands/agent.test.ts
+++ b/apps/cli/src/commands/agent.test.ts
@@ -1854,46 +1854,6 @@ describe('agent command', () => {
});
});
- it('should read write content from stdin when no content option is provided', async () => {
- const stdinDescriptor = Object.getOwnPropertyDescriptor(process.stdin, 'isTTY');
- Object.defineProperty(process.stdin, 'isTTY', { configurable: true, value: false });
- mockReadStdinText.mockResolvedValue('# Piped Content');
- mockTrpcClient.agentDocument.statDocumentByPath.query.mockRejectedValue({
- data: { code: 'NOT_FOUND' },
- });
- mockTrpcClient.agentDocument.writeDocumentByPath.mutate.mockResolvedValue({
- path: './notes/piped.md',
- });
-
- try {
- const program = createProgram();
- await program.parseAsync([
- 'node',
- 'test',
- 'agent',
- 'space',
- 'fs',
- 'write',
- '--agent-id',
- 'a1',
- 'agent:/notes/piped.md',
- ]);
-
- expect(mockReadStdinText).toHaveBeenCalledWith(process.stdin);
- expect(mockTrpcClient.agentDocument.writeDocumentByPath.mutate).toHaveBeenCalledWith({
- agentId: 'a1',
- content: '# Piped Content',
- createMode: 'if-missing',
- path: './notes/piped.md',
- topicId: undefined,
- });
- } finally {
- if (stdinDescriptor) {
- Object.defineProperty(process.stdin, 'isTTY', stdinDescriptor);
- }
- }
- });
-
it('should create directories through the generic mkdir path API', async () => {
mockTrpcClient.agentDocument.mkdirDocumentByPath.mutate.mockResolvedValue({
path: './notes/archive',
diff --git a/apps/cli/src/commands/agent/spaceFs.test.ts b/apps/cli/src/commands/agent/spaceFs.test.ts
new file mode 100644
index 00000000000..3deb2ca18db
--- /dev/null
+++ b/apps/cli/src/commands/agent/spaceFs.test.ts
@@ -0,0 +1,88 @@
+import type * as NodeFs from 'node:fs';
+
+import { Command } from 'commander';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { registerAgentSpaceFsCommand } from './spaceFs';
+
+const { mockFstatSync, mockReadStdinText, mockTrpcClient } = vi.hoisted(() => ({
+ mockFstatSync: vi.fn(),
+ mockReadStdinText: vi.fn(),
+ mockTrpcClient: {
+ agentDocument: {
+ statDocumentByPath: { query: vi.fn() },
+ writeDocumentByPath: { mutate: vi.fn() },
+ },
+ },
+}));
+
+vi.mock('node:fs', async (importOriginal) => {
+ const actual = await importOriginal<typeof NodeFs>();
+ return { ...actual, fstatSync: mockFstatSync };
+});
+vi.mock('node:stream/consumers', () => ({ text: mockReadStdinText }));
+vi.mock('../../api/client', () => ({ getTrpcClient: async () => mockTrpcClient }));
+
+const run = (...args: string[]) => {
+ const program = new Command();
+ program.exitOverride();
+ registerAgentSpaceFsCommand(program.command('agent'));
+ return program.parseAsync(['node', 'test', 'agent', 'space', 'fs', ...args]);
+};
+
+const stdinOf = (kind: 'fifo' | 'file' | 'null') => ({
+ isFIFO: () => kind === 'fifo',
+ isFile: () => kind === 'file',
+});
+
+describe('agent space fs content from stdin', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ mockTrpcClient.agentDocument.statDocumentByPath.query.mockRejectedValue({
+ data: { code: 'NOT_FOUND' },
+ });
+ mockTrpcClient.agentDocument.writeDocumentByPath.mutate.mockResolvedValue({
+ path: './notes/a.md',
+ });
+ });
+
+ // Node leaves `isTTY` undefined for a pipe, so only fstat can tell one apart.
+ it.each(['fifo', 'file'] as const)(
+ 'reads %s stdin when no content option is given',
+ async (kind) => {
+ mockFstatSync.mockReturnValue(stdinOf(kind));
+ mockReadStdinText.mockResolvedValue('# Piped Content');
+
+ await run('write', '--agent-id', 'a1', 'agent:/notes/a.md');
+
+ expect(mockFstatSync).toHaveBeenCalledWith(0);
+ expect(mockReadStdinText).toHaveBeenCalledWith(process.stdin);
+ expect(mockTrpcClient.agentDocument.writeDocumentByPath.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({ agentId: 'a1', content: '# Piped Content' }),
+ );
+ },
+ );
+
+ it('does not wait on stdin bound to /dev/null, as in an agent shell', async () => {
+ mockFstatSync.mockReturnValue(stdinOf('null'));
+
+ await run('touch', '--agent-id', 'a1', 'agent:/notes/a.md');
+
+ expect(mockReadStdinText).not.toHaveBeenCalled();
+ expect(mockTrpcClient.agentDocument.writeDocumentByPath.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({ content: '' }),
+ );
+ });
+
+ it('prefers --content over piped stdin', async () => {
+ mockFstatSync.mockReturnValue(stdinOf('fifo'));
+
+ await run('write', '--agent-id', 'a1', '--content', 'inline', 'agent:/notes/a.md');
+
+ expect(mockReadStdinText).not.toHaveBeenCalled();
+ expect(mockTrpcClient.agentDocument.writeDocumentByPath.mutate).toHaveBeenCalledWith(
+ expect.objectContaining({ content: 'inline' }),
+ );
+ });
+});
diff --git a/apps/cli/src/commands/agent/spaceFs.ts b/apps/cli/src/commands/agent/spaceFs.ts
index 4935c9a3347..5572c4c3283 100644
--- a/apps/cli/src/commands/agent/spaceFs.ts
+++ b/apps/cli/src/commands/agent/spaceFs.ts
@@ -1,4 +1,4 @@
-import { readFileSync } from 'node:fs';
+import { fstatSync, readFileSync } from 'node:fs';
import { text } from 'node:stream/consumers';
import type { Command } from 'commander';
@@ -279,13 +279,26 @@ async function readFsContentInput(options: { content?: string; contentFile?: str
// NOTICE:
// CLI write commands should compose with shell pipelines without blocking interactive runs.
- // Node marks piped stdin with `isTTY === false`, while normal terminals are `true` or undefined in tests.
+ // `isTTY` cannot tell a pipe apart: Node leaves it undefined for pipes, files and /dev/null alike.
// Remove this branch only if Commander gains first-class stdin option support for these commands.
- if (process.stdin.isTTY === false) return text(process.stdin);
+ if (isStdinRedirected()) return text(process.stdin);
return '';
}
+/**
+ * Whether stdin was piped (`echo x | lh …`) or redirected from a file (`< x`).
+ * A terminal, a closed stdin or `/dev/null` (an agent shell) is not input.
+ */
+function isStdinRedirected(): boolean {
+ try {
+ const stat = fstatSync(0);
+ return stat.isFIFO() || stat.isFile();
+ } catch {
+ return false;
+ }
+}
+
async function resolveAgentFsContext(client: AgentFsClient, options: AgentFsOptions) {
const agentId = await resolveAgentId(client, options);
return { agentId, topicId: options.topicId };
diff --git a/apps/cli/src/utils/format.test.ts b/apps/cli/src/utils/format.test.ts
index 3bc827caa75..d2081e944ea 100644
--- a/apps/cli/src/utils/format.test.ts
+++ b/apps/cli/src/utils/format.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it, vi } from 'vitest';
import {
+ confirm,
formatCost,
formatNumber,
outputJson,
@@ -211,3 +212,17 @@ describe('timeUntil', () => {
expect(timeUntil('not a date')).toBe('-');
});
});
+
+describe('confirm', () => {
+ it('rejects instead of waiting on stdin when there is no terminal', async () => {
+ const isTTY = Object.getOwnPropertyDescriptor(process.stdin, 'isTTY');
+ Object.defineProperty(process.stdin, 'isTTY', { configurable: true, value: undefined });
+
+ try {
+ await expect(confirm('Delete it?')).rejects.toThrow(/Re-run with --yes/);
+ } finally {
+ if (isTTY) Object.defineProperty(process.stdin, 'isTTY', isTTY);
+ else delete (process.stdin as { isTTY?: boolean }).isTTY;
+ }
+ });
+});
diff --git a/apps/cli/src/utils/format.ts b/apps/cli/src/utils/format.ts
index 8aa9fd73966..85ab470c0de 100644
--- a/apps/cli/src/utils/format.ts
+++ b/apps/cli/src/utils/format.ts
@@ -516,7 +516,23 @@ export function printKanban(columns: KanbanColumn[]) {
console.log(bottomBorder);
}
+/**
+ * Ask a `(y/N)` question on the terminal.
+ *
+ * Without a terminal there is nobody to answer: an agent's shell, a pipe or CI
+ * either never closes stdin (the command hangs until it is killed) or closes it
+ * empty (the action is silently cancelled). Fail loudly instead, so the caller
+ * learns it has to pass `--yes`.
+ */
export function confirm(message: string): Promise<boolean> {
+ if (!process.stdin.isTTY) {
+ return Promise.reject(
+ new Error(
+ `${message}\nRefusing to continue without an interactive terminal to confirm. Re-run with --yes to skip the prompt.`,
+ ),
+ );
+ }
+
const rl = createInterface({ input: process.stdin, output: process.stderr });
return new Promise((resolve) => {
rl.question(`${message} (y/N) `, (answer: string) => {
diff --git a/packages/local-file-shell/src/shell/__tests__/runner.test.ts b/packages/local-file-shell/src/shell/__tests__/runner.test.ts
index 28d404a1d0d..85de4dcc3ef 100644
--- a/packages/local-file-shell/src/shell/__tests__/runner.test.ts
+++ b/packages/local-file-shell/src/shell/__tests__/runner.test.ts
@@ -103,6 +103,22 @@ describe('runCommand', () => {
expect(result.exit_code).toBe(1);
});
+ // A `(y/N)` prompt (e.g. `lh gen delete` without `--yes`) used to wait on
+ // an open stdin pipe nobody writes to, until the shell timeout.
+ it.skipIf(process.platform === 'win32')(
+ 'should give a command reading stdin EOF instead of hanging',
+ async () => {
+ const result = await runCommand(
+ { command: 'read answer; echo "read-exit=$? answer=[$answer]"', timeout: 3_000 },
+ { processManager },
+ );
+
+ expect(result.exit_code).toBe(0);
+ expect(result.stdout).toContain('read-exit=1 answer=[]');
+ },
+ 10_000,
+ );
+
it('should handle command not found', async () => {
const result = await runCommand(
{ command: 'nonexistent_command_xyz_123' },
diff --git a/packages/local-file-shell/src/shell/child-process-backend.ts b/packages/local-file-shell/src/shell/child-process-backend.ts
index a7436a8c40b..e80f65ac26f 100644
--- a/packages/local-file-shell/src/shell/child-process-backend.ts
+++ b/packages/local-file-shell/src/shell/child-process-backend.ts
@@ -15,8 +15,13 @@ import type {
const KILL_SIGNAL: NodeJS.Signals = 'SIGKILL';
/**
- * Non-interactive backend: a plain `child_process` with stdin left as an
- * unused pipe and stdout/stderr inherited straight into the output files.
+ * Non-interactive backend: a plain `child_process` with stdin bound to the
+ * null device and stdout/stderr inherited straight into the output files.
+ *
+ * Nothing ever writes to a command's stdin here, so it must not be an open
+ * pipe: a command that reads stdin (a `(y/N)` confirm, `read`, a CLI that falls
+ * back to piped input) would wait on it until the shell timeout. With `ignore`
+ * it reads EOF at once and fails or cancels instead of hanging.
*/
export class ChildProcessBackend implements ShellBackend {
readonly capabilities: ShellBackendCapabilities = {
@@ -55,7 +60,7 @@ export class ChildProcessBackend implements ShellBackend {
detached: process.platform !== 'win32',
env: env as NodeJS.ProcessEnv,
shell: false,
- stdio: ['pipe', outputFiles.stdout.fd, outputFiles.stderr.fd],
+ stdio: ['ignore', outputFiles.stdout.fd, outputFiles.stderr.fd],
// The Electron main process is a GUI process without a console, so on
// Windows spawning a console program (powershell.exe / cmd.exe) allocates
// a new console window that flashes up for every command. windowsHide