From c65fd58279eb3d92d461c829463eb81755378c48 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 14 Aug 2025 22:07:01 -0700 Subject: [PATCH 01/10] update --- .github/workflows/respond-to-cubic-dev-ai.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/respond-to-cubic-dev-ai.yml b/.github/workflows/respond-to-cubic-dev-ai.yml index a20a53b96..f2dbe0c47 100644 --- a/.github/workflows/respond-to-cubic-dev-ai.yml +++ b/.github/workflows/respond-to-cubic-dev-ai.yml @@ -72,7 +72,7 @@ jobs: env: CONTINUE_API_KEY: ${{ secrets.CONTINUE_API_KEY }} run: | - # Create the prompt for the remote session + # Create the prompt for remote session PROMPT="Please help with the following request from @${{ github.event.comment.user.login }} on PR #${{ github.event.issue.number }}: ${{ github.event.comment.body }} From fbe95baf7e82e4ea432caf0857f21fc86f453d68 Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 14 Aug 2025 22:12:23 -0700 Subject: [PATCH 02/10] fix --- src/commands/remote.ts | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/src/commands/remote.ts b/src/commands/remote.ts index 7515087d7..ac73b3699 100644 --- a/src/commands/remote.ts +++ b/src/commands/remote.ts @@ -1,10 +1,6 @@ import chalk from "chalk"; -import { - getAccessToken, - isAuthenticatedConfig, - loadAuthConfig, -} from "../auth/workos.js"; +import { getAccessToken, loadAuthConfig } from "../auth/workos.js"; import { env } from "../env.js"; import { telemetryService } from "../telemetry/telemetryService.js"; import { startRemoteTUIChat } from "../ui/index.js"; @@ -50,7 +46,8 @@ export async function remote( try { const authConfig = loadAuthConfig(); - if (!isAuthenticatedConfig(authConfig)) { + // Check if we have any valid authentication (file-based or environment variable) + if (!authConfig || !getAccessToken(authConfig)) { console.error( chalk.red("Not authenticated. Please run 'cn login' first."), ); From 8ba8449c8ac7442d2bbaa3abf30acd024d7644ce Mon Sep 17 00:00:00 2001 From: Nate Date: Thu, 14 Aug 2025 22:14:53 -0700 Subject: [PATCH 03/10] cache --- .github/workflows/respond-to-cubic-dev-ai.yml | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/.github/workflows/respond-to-cubic-dev-ai.yml b/.github/workflows/respond-to-cubic-dev-ai.yml index f2dbe0c47..b5e0d4a79 100644 --- a/.github/workflows/respond-to-cubic-dev-ai.yml +++ b/.github/workflows/respond-to-cubic-dev-ai.yml @@ -60,12 +60,28 @@ jobs: node-version: "20" cache: "npm" - - name: Install dependencies and build CLI + - name: Cache build output if: steps.check-mention.outputs.contains_mention == 'true' + id: cache-build + uses: actions/cache@v4 + with: + path: | + dist/ + node_modules/ + key: ${{ runner.os }}-build-${{ hashFiles('package-lock.json', 'src/**/*', 'tsconfig*.json') }} + restore-keys: | + ${{ runner.os }}-build- + + - name: Install dependencies and build CLI + if: steps.check-mention.outputs.contains_mention == 'true' && steps.cache-build.outputs.cache-hit != 'true' run: | npm ci npm run build + - name: Install dependencies only (cache hit) + if: steps.check-mention.outputs.contains_mention == 'true' && steps.cache-build.outputs.cache-hit == 'true' + run: npm ci --prefer-offline + - name: Start remote session if: steps.check-mention.outputs.contains_mention == 'true' id: remote-session From 985db547691e99eeb54ba5ab5cda2ea3deedf309 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 15 Aug 2025 12:39:46 -0700 Subject: [PATCH 04/10] updates to remote --- src/commands/remote.test.ts | 79 ++++++++++++++++++++++++++++++++++++- src/commands/remote.ts | 17 ++++++-- src/index.ts | 4 ++ 3 files changed, 95 insertions(+), 5 deletions(-) diff --git a/src/commands/remote.test.ts b/src/commands/remote.test.ts index af464b099..0962781b0 100644 --- a/src/commands/remote.test.ts +++ b/src/commands/remote.test.ts @@ -68,6 +68,7 @@ describe("remote command", () => { mockFetch.mockResolvedValue({ ok: true, json: async () => ({ + id: "test-agent-id", url: "ws://test-url.com", port: 8080, }), @@ -131,6 +132,24 @@ describe("remote command", () => { ); }); + it("should ignore --start flag when --url is provided without --start", async () => { + const testUrl = "ws://direct-url.com"; + + await remote("test prompt", { url: testUrl }); + + // Should not make POST request when connecting directly to URL + expect(mockFetch).not.toHaveBeenCalled(); + + // Should connect directly to the provided URL and start TUI + expect(mockStartRemoteTUIChat.startRemoteTUIChat).toHaveBeenCalledWith( + testUrl, + "test prompt" + ); + + // Should not output JSON + expect(mockConsoleLog).not.toHaveBeenCalled(); + }); + it("should handle proper request body structure with all fields", async () => { const testIdempotencyKey = "structured-test-key"; @@ -170,6 +189,61 @@ describe("remote command", () => { expect(requestBody.idempotencyKey).toBe("github-actions-key"); }); + it("should include branchName in request body when branch option is provided", async () => { + const testBranch = "feature/new-feature"; + + await remote("test prompt", { branch: testBranch }); + + expect(mockFetch).toHaveBeenCalledWith( + new URL("agents/devboxes", mockEnv.env.apiBase), + expect.objectContaining({ + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-token", + }, + body: expect.stringContaining(`"branchName":"${testBranch}"`), + }) + ); + }); + + it("should not include branchName in request body when branch option is not provided", async () => { + await remote("test prompt", {}); + + expect(mockFetch).toHaveBeenCalledWith( + new URL("agents/devboxes", mockEnv.env.apiBase), + expect.objectContaining({ + method: "POST", + headers: { + "Content-Type": "application/json", + Authorization: "Bearer test-token", + }, + body: expect.not.stringContaining("branchName"), + }) + ); + }); + + it("should handle proper request body structure with branch field", async () => { + const testBranch = "main"; + const testIdempotencyKey = "test-with-branch"; + + await remote("test prompt", { + branch: testBranch, + idempotencyKey: testIdempotencyKey + }); + + const fetchCall = mockFetch.mock.calls[0]; + const requestBody = JSON.parse(fetchCall[1].body); + + expect(requestBody).toEqual({ + repoUrl: "https://github.com/user/test-repo.git", + name: expect.stringMatching(/^devbox-\d+$/), + prompt: "test prompt", + idempotencyKey: testIdempotencyKey, + branchName: testBranch, + }); + }); + describe("start mode (-s / --start flag)", () => { it("should output JSON and exit without starting TUI when using --start with direct URL", async () => { const testUrl = "ws://test-url.com"; @@ -218,8 +292,9 @@ describe("remote command", () => { expect(outputJson).toEqual({ status: "success", message: "Remote development environment created successfully", - url: "ws://test-url.com", - port: 8080, + url: "https://test.example.com/agents/test-agent-id", + containerUrl: "ws://test-url.com", + containerPort: 8080, name: expect.stringMatching(/^devbox-\d+$/), mode: "new_environment" }); diff --git a/src/commands/remote.ts b/src/commands/remote.ts index ac73b3699..63cabe6a8 100644 --- a/src/commands/remote.ts +++ b/src/commands/remote.ts @@ -9,7 +9,12 @@ import { logger } from "../util/logger.js"; export async function remote( prompt: string | undefined, - options: { url?: string; idempotencyKey?: string; start?: boolean } = {}, + options: { + url?: string; + idempotencyKey?: string; + start?: boolean; + branch?: string; + } = {}, ) { // If --url is provided, connect directly to that URL if (options.url) { @@ -63,6 +68,11 @@ export async function remote( idempotencyKey: options.idempotencyKey, }; + // Add branchName to request body if branch option is provided + if (options.branch) { + requestBody.branchName = options.branch; + } + const response = await fetch(new URL("agents/devboxes", env.apiBase), { method: "POST", headers: { @@ -87,8 +97,9 @@ export async function remote( JSON.stringify({ status: "success", message: "Remote development environment created successfully", - url: result.url, - port: result.port, + url: `${env.appUrl}/agents/${result.id}`, + containerUrl: result.url, + containerPort: result.port, name: requestBody.name, mode: "new_environment", }), diff --git a/src/index.ts b/src/index.ts index bb739e517..b5155eaa7 100644 --- a/src/index.ts +++ b/src/index.ts @@ -164,6 +164,10 @@ program "-s, --start", "Create remote environment and print connection details without starting TUI", ) + .option( + "--branch ", + "Specify the git branch name to use in the remote environment", + ) .action(async (prompt: string | undefined, options) => { await remote(prompt, options); }); From 09d3805e035569985181012be0deb2ebb85fdd93 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 15 Aug 2025 12:55:03 -0700 Subject: [PATCH 05/10] fix: remote stdin and restore diff display --- src/commands/remote.ts | 23 ++++++++-- src/e2e/remote-stdin.test.ts | 83 ++++++++++++++++++++++++++++++++++++ src/tools/edit.test.ts | 2 +- src/tools/edit.ts | 5 ++- src/tools/multiEdit.test.ts | 6 +-- src/tools/multiEdit.ts | 5 ++- src/tools/writeFile.ts | 5 ++- src/ui/ToolResultSummary.tsx | 9 +++- 8 files changed, 126 insertions(+), 12 deletions(-) create mode 100644 src/e2e/remote-stdin.test.ts diff --git a/src/commands/remote.ts b/src/commands/remote.ts index 63cabe6a8..54a45ad3e 100644 --- a/src/commands/remote.ts +++ b/src/commands/remote.ts @@ -6,6 +6,7 @@ import { telemetryService } from "../telemetry/telemetryService.js"; import { startRemoteTUIChat } from "../ui/index.js"; import { getRepoUrl } from "../util/git.js"; import { logger } from "../util/logger.js"; +import { readStdinSync } from "../util/stdin.js"; export async function remote( prompt: string | undefined, @@ -16,6 +17,22 @@ export async function remote( branch?: string; } = {}, ) { + // Check if prompt should come from stdin instead of parameter + let actualPrompt = prompt; + if (prompt) { + // If prompt is provided, still check for stdin and combine them + const stdinInput = readStdinSync(); + if (stdinInput) { + // Combine stdin and prompt argument - stdin comes first in XML block + actualPrompt = `\n${stdinInput}\n\n\n${prompt}`; + } + } else { + // Try to read from stdin (for piped input like: echo "hello" | cn remote -s) + const stdinInput = readStdinSync(); + if (stdinInput) { + actualPrompt = stdinInput; + } + } // If --url is provided, connect directly to that URL if (options.url) { if (options.start) { @@ -41,7 +58,7 @@ export async function remote( try { // Start the TUI in remote mode - await startRemoteTUIChat(options.url, prompt); + await startRemoteTUIChat(options.url, actualPrompt); } finally { telemetryService.stopActiveTime(); } @@ -64,7 +81,7 @@ export async function remote( const requestBody: any = { repoUrl: getRepoUrl(), name: `devbox-${Date.now()}`, - prompt: prompt, + prompt: actualPrompt, idempotencyKey: options.idempotencyKey, }; @@ -123,7 +140,7 @@ export async function remote( try { // Start the TUI in remote mode (prompt is optional) - await startRemoteTUIChat(remoteUrl, prompt); + await startRemoteTUIChat(remoteUrl, actualPrompt); } finally { telemetryService.stopActiveTime(); } diff --git a/src/e2e/remote-stdin.test.ts b/src/e2e/remote-stdin.test.ts new file mode 100644 index 000000000..ae8b43fb3 --- /dev/null +++ b/src/e2e/remote-stdin.test.ts @@ -0,0 +1,83 @@ +import { createTestContext, cleanupTestContext, runCLI } from "../test-helpers/cli-helpers.js"; + +describe("E2E: Remote Command - Stdin Support", () => { + let context: any; + + beforeEach(async () => { + context = await createTestContext(); + }); + + afterEach(async () => { + await cleanupTestContext(context); + }); + + it("should work correctly when prompt is provided via stdin with remote -s flag", async () => { + const result = await runCLI(context, { + args: ["remote", "-s", "--url", "http://example.com"], + input: "Hello from stdin", + expectError: false, + timeout: 5000, + }); + + // Should succeed with direct URL connection + expect(result.exitCode).toBe(0); + + // Should output JSON response for --start mode + const output = result.stdout; + expect(output).toContain('"status":"success"'); + expect(output).toContain('"url":"http://example.com"'); + expect(output).toContain('"mode":"direct_url"'); + }); + + it("should combine stdin and command line prompt when both are provided", async () => { + const result = await runCLI(context, { + args: ["remote", "-s", "--url", "http://example.com", "Command line prompt"], + input: "Stdin input", + expectError: false, + timeout: 5000, + }); + + // Should succeed with direct URL connection + expect(result.exitCode).toBe(0); + + // Should output JSON response for --start mode + const output = result.stdout; + expect(output).toContain('"status":"success"'); + expect(output).toContain('"url":"http://example.com"'); + expect(output).toContain('"mode":"direct_url"'); + }); + + it("should work with just command line prompt (no stdin)", async () => { + const result = await runCLI(context, { + args: ["remote", "-s", "--url", "http://example.com", "Just command line"], + expectError: false, + timeout: 5000, + }); + + // Should succeed with direct URL connection + expect(result.exitCode).toBe(0); + + // Should output JSON response for --start mode + const output = result.stdout; + expect(output).toContain('"status":"success"'); + expect(output).toContain('"url":"http://example.com"'); + expect(output).toContain('"mode":"direct_url"'); + }); + + it("should work with no prompt at all", async () => { + const result = await runCLI(context, { + args: ["remote", "-s", "--url", "http://example.com"], + expectError: false, + timeout: 5000, + }); + + // Should succeed with direct URL connection + expect(result.exitCode).toBe(0); + + // Should output JSON response for --start mode + const output = result.stdout; + expect(output).toContain('"status":"success"'); + expect(output).toContain('"url":"http://example.com"'); + expect(output).toContain('"mode":"direct_url"'); + }); +}); \ No newline at end of file diff --git a/src/tools/edit.test.ts b/src/tools/edit.test.ts index 1ad8f7d23..088738d29 100644 --- a/src/tools/edit.test.ts +++ b/src/tools/edit.test.ts @@ -170,7 +170,7 @@ describe("editTool", () => { const result = await editTool.run(args); - expect(result).toBe(`Successfully edited ${testFilePath}`); + expect(result).toBe(`Successfully edited ${testFilePath}\nDiff:\nmocked diff`); expect(fs.writeFileSync).toHaveBeenCalledWith(testFilePath, newContent, "utf-8"); }); diff --git a/src/tools/edit.ts b/src/tools/edit.ts index 9b073adfe..f45acf6cc 100644 --- a/src/tools/edit.ts +++ b/src/tools/edit.ts @@ -178,7 +178,10 @@ parameter is useful if you want to rename a variable for instance.`, ); } - return `Successfully edited ${args.file_path}`; + // Generate diff for result display + const diff = generateDiff(args.oldContent, args.newContent, args.file_path); + + return `Successfully edited ${args.file_path}\nDiff:\n${diff}`; } catch (error) { throw new Error( `Error: failed to edit ${args.file_path}: ${ diff --git a/src/tools/multiEdit.test.ts b/src/tools/multiEdit.test.ts index e4547a5e7..39b43642b 100644 --- a/src/tools/multiEdit.test.ts +++ b/src/tools/multiEdit.test.ts @@ -327,7 +327,7 @@ describe("multiEditTool", () => { const result = await multiEditTool.run(args); - expect(result).toBe(`Successfully edited ${testFilePath} with 1 edit`); + expect(result).toBe(`Successfully edited ${testFilePath} with 1 edit\nDiff:\nmocked diff`); expect(fs.writeFileSync).toHaveBeenCalledWith(testFilePath, newContent, "utf-8"); }); @@ -342,7 +342,7 @@ describe("multiEditTool", () => { const result = await multiEditTool.run(args); - expect(result).toBe(`Successfully edited ${testFilePath} with 3 edits`); + expect(result).toBe(`Successfully edited ${testFilePath} with 3 edits\nDiff:\nmocked diff`); }); it("should return correct message for new file creation", async () => { @@ -356,7 +356,7 @@ describe("multiEditTool", () => { const result = await multiEditTool.run(args); - expect(result).toBe(`Successfully created /tmp/new-file.txt with 1 edit`); + expect(result).toBe(`Successfully created /tmp/new-file.txt with 1 edit\nDiff:\nmocked diff`); }); it("should throw error if file write fails", async () => { diff --git a/src/tools/multiEdit.ts b/src/tools/multiEdit.ts index 2e5ac024f..bc7b8298a 100644 --- a/src/tools/multiEdit.ts +++ b/src/tools/multiEdit.ts @@ -309,8 +309,11 @@ If you want to create a new file, use: ); } + // Generate diff for result display + const diff = generateDiff(args.originalContent, args.newContent, args.file_path); + const action = args.isCreatingNewFile ? "created" : "edited"; - return `Successfully ${action} ${args.file_path} with ${args.editCount} edit${args.editCount === 1 ? "" : "s"}`; + return `Successfully ${action} ${args.file_path} with ${args.editCount} edit${args.editCount === 1 ? "" : "s"}\nDiff:\n${diff}`; } catch (error) { throw new Error( `Error: failed to edit ${args.file_path}: ${ diff --git a/src/tools/writeFile.ts b/src/tools/writeFile.ts index 2d3ad8377..f1404386f 100644 --- a/src/tools/writeFile.ts +++ b/src/tools/writeFile.ts @@ -139,7 +139,10 @@ export const writeFileTool: Tool = { ); } - return `Successfully wrote to file: ${args.filepath}`; + // Generate diff for result display + const diff = generateDiff(oldContent, args.content, args.filepath); + + return `Successfully wrote to file: ${args.filepath}\nDiff:\n${diff}`; } else { // New file creation - count all lines as added const lineCount = args.content.split("\n").length; diff --git a/src/ui/ToolResultSummary.tsx b/src/ui/ToolResultSummary.tsx index 4c7a439f8..c608d298b 100644 --- a/src/ui/ToolResultSummary.tsx +++ b/src/ui/ToolResultSummary.tsx @@ -43,9 +43,9 @@ const ToolResultSummary: React.FC = ({ ); } - // Handle Write/Edit with diff specially + // Handle Write/Edit/MultiEdit with diff specially if ( - (toolName === "Write" || toolName === "Edit") && + (toolName === "Write" || toolName === "Edit" || toolName === "MultiEdit") && content.includes("Diff:\n") ) { const diffSection = content.split("Diff:\n")[1]; @@ -56,6 +56,8 @@ const ToolResultSummary: React.FC = ({ ⎿ {toolName === "Edit" + ? " File edited successfully" + : toolName === "MultiEdit" ? " File edited successfully" : " File written successfully"} @@ -147,6 +149,9 @@ const ToolResultSummary: React.FC = ({ case "Edit": return "File edited successfully"; + case "MultiEdit": + return "File edited successfully"; + case "List": return `Listed ${lines} ${lines === 1 ? "item" : "items"}`; From d716d749781fc29862d6271ce0f21d7b20b841f9 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 15 Aug 2025 13:01:11 -0700 Subject: [PATCH 06/10] update workflow --- .github/workflows/respond-to-cubic-dev-ai.yml | 25 +++---------------- 1 file changed, 3 insertions(+), 22 deletions(-) diff --git a/.github/workflows/respond-to-cubic-dev-ai.yml b/.github/workflows/respond-to-cubic-dev-ai.yml index b5e0d4a79..e5100057c 100644 --- a/.github/workflows/respond-to-cubic-dev-ai.yml +++ b/.github/workflows/respond-to-cubic-dev-ai.yml @@ -58,29 +58,10 @@ jobs: uses: actions/setup-node@v4 with: node-version: "20" - cache: "npm" - - name: Cache build output + - name: Install Continue CLI globally if: steps.check-mention.outputs.contains_mention == 'true' - id: cache-build - uses: actions/cache@v4 - with: - path: | - dist/ - node_modules/ - key: ${{ runner.os }}-build-${{ hashFiles('package-lock.json', 'src/**/*', 'tsconfig*.json') }} - restore-keys: | - ${{ runner.os }}-build- - - - name: Install dependencies and build CLI - if: steps.check-mention.outputs.contains_mention == 'true' && steps.cache-build.outputs.cache-hit != 'true' - run: | - npm ci - npm run build - - - name: Install dependencies only (cache hit) - if: steps.check-mention.outputs.contains_mention == 'true' && steps.cache-build.outputs.cache-hit == 'true' - run: npm ci --prefer-offline + run: npm i -g @continuedev/cli - name: Start remote session if: steps.check-mention.outputs.contains_mention == 'true' @@ -96,7 +77,7 @@ jobs: Please analyze the current PR, understand the request, implement the necessary changes, and commit them to this branch." # Start remote session and capture JSON output - SESSION_OUTPUT=$(node dist/index.js remote -s "$PROMPT") + SESSION_OUTPUT=$(echo "$PROMPT" | cn remote -s --branch ${{ steps.pr-info.outputs.head_ref }}) echo "Raw session output: $SESSION_OUTPUT" # Extract URL from JSON output From fef14917c6aeff30aeaefa8af5726f70452fc190 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 15 Aug 2025 13:04:36 -0700 Subject: [PATCH 07/10] chore: format --- src/tools/edit.ts | 6 +++++- src/tools/multiEdit.ts | 6 +++++- src/ui/ToolResultSummary.tsx | 4 ++-- 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/tools/edit.ts b/src/tools/edit.ts index f45acf6cc..39e9ca1f9 100644 --- a/src/tools/edit.ts +++ b/src/tools/edit.ts @@ -179,7 +179,11 @@ parameter is useful if you want to rename a variable for instance.`, } // Generate diff for result display - const diff = generateDiff(args.oldContent, args.newContent, args.file_path); + const diff = generateDiff( + args.oldContent, + args.newContent, + args.file_path, + ); return `Successfully edited ${args.file_path}\nDiff:\n${diff}`; } catch (error) { diff --git a/src/tools/multiEdit.ts b/src/tools/multiEdit.ts index bc7b8298a..1c2b7795e 100644 --- a/src/tools/multiEdit.ts +++ b/src/tools/multiEdit.ts @@ -310,7 +310,11 @@ If you want to create a new file, use: } // Generate diff for result display - const diff = generateDiff(args.originalContent, args.newContent, args.file_path); + const diff = generateDiff( + args.originalContent, + args.newContent, + args.file_path, + ); const action = args.isCreatingNewFile ? "created" : "edited"; return `Successfully ${action} ${args.file_path} with ${args.editCount} edit${args.editCount === 1 ? "" : "s"}\nDiff:\n${diff}`; diff --git a/src/ui/ToolResultSummary.tsx b/src/ui/ToolResultSummary.tsx index c608d298b..296fec6e3 100644 --- a/src/ui/ToolResultSummary.tsx +++ b/src/ui/ToolResultSummary.tsx @@ -58,8 +58,8 @@ const ToolResultSummary: React.FC = ({ {toolName === "Edit" ? " File edited successfully" : toolName === "MultiEdit" - ? " File edited successfully" - : " File written successfully"} + ? " File edited successfully" + : " File written successfully"} From d4de89ea85c24032a18fef85c0a22d5cb30b315b Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 15 Aug 2025 13:10:36 -0700 Subject: [PATCH 08/10] remove unecessary test --- src/e2e/remote-stdin.test.ts | 83 ------------------------------------ 1 file changed, 83 deletions(-) delete mode 100644 src/e2e/remote-stdin.test.ts diff --git a/src/e2e/remote-stdin.test.ts b/src/e2e/remote-stdin.test.ts deleted file mode 100644 index ae8b43fb3..000000000 --- a/src/e2e/remote-stdin.test.ts +++ /dev/null @@ -1,83 +0,0 @@ -import { createTestContext, cleanupTestContext, runCLI } from "../test-helpers/cli-helpers.js"; - -describe("E2E: Remote Command - Stdin Support", () => { - let context: any; - - beforeEach(async () => { - context = await createTestContext(); - }); - - afterEach(async () => { - await cleanupTestContext(context); - }); - - it("should work correctly when prompt is provided via stdin with remote -s flag", async () => { - const result = await runCLI(context, { - args: ["remote", "-s", "--url", "http://example.com"], - input: "Hello from stdin", - expectError: false, - timeout: 5000, - }); - - // Should succeed with direct URL connection - expect(result.exitCode).toBe(0); - - // Should output JSON response for --start mode - const output = result.stdout; - expect(output).toContain('"status":"success"'); - expect(output).toContain('"url":"http://example.com"'); - expect(output).toContain('"mode":"direct_url"'); - }); - - it("should combine stdin and command line prompt when both are provided", async () => { - const result = await runCLI(context, { - args: ["remote", "-s", "--url", "http://example.com", "Command line prompt"], - input: "Stdin input", - expectError: false, - timeout: 5000, - }); - - // Should succeed with direct URL connection - expect(result.exitCode).toBe(0); - - // Should output JSON response for --start mode - const output = result.stdout; - expect(output).toContain('"status":"success"'); - expect(output).toContain('"url":"http://example.com"'); - expect(output).toContain('"mode":"direct_url"'); - }); - - it("should work with just command line prompt (no stdin)", async () => { - const result = await runCLI(context, { - args: ["remote", "-s", "--url", "http://example.com", "Just command line"], - expectError: false, - timeout: 5000, - }); - - // Should succeed with direct URL connection - expect(result.exitCode).toBe(0); - - // Should output JSON response for --start mode - const output = result.stdout; - expect(output).toContain('"status":"success"'); - expect(output).toContain('"url":"http://example.com"'); - expect(output).toContain('"mode":"direct_url"'); - }); - - it("should work with no prompt at all", async () => { - const result = await runCLI(context, { - args: ["remote", "-s", "--url", "http://example.com"], - expectError: false, - timeout: 5000, - }); - - // Should succeed with direct URL connection - expect(result.exitCode).toBe(0); - - // Should output JSON response for --start mode - const output = result.stdout; - expect(output).toContain('"status":"success"'); - expect(output).toContain('"url":"http://example.com"'); - expect(output).toContain('"mode":"direct_url"'); - }); -}); \ No newline at end of file From a3cd7de581ea0dbfab1f0c96b5fb8e30e1fb68a8 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 15 Aug 2025 14:02:21 -0700 Subject: [PATCH 09/10] fix: allow bash in plan mode --- spec/modes.md | 6 +++--- src/services/ToolPermissionService.modes.test.ts | 4 ++-- src/services/ToolPermissionService.real.test.ts | 4 ++-- src/services/ToolPermissionService.test.ts | 4 ++-- src/services/ToolPermissionService.ts | 6 +++--- src/streamChatResponse.getAllTools.test.ts | 14 ++++++++------ 6 files changed, 20 insertions(+), 18 deletions(-) diff --git a/spec/modes.md b/spec/modes.md index 0bf32c7cf..7296a19eb 100644 --- a/spec/modes.md +++ b/spec/modes.md @@ -15,12 +15,12 @@ The default mode that follows configured permission policies from `permissions.y ### `plan` -Planning mode that **completely overrides all user permissions** to enforce read-only access. This mode absolutely prevents any write operations, file modifications, or command execution, regardless of user configuration. +Planning mode that **completely overrides all user permissions** to enforce read-only access with command execution. This mode prevents file modifications but allows command execution for analysis, regardless of user configuration. - **Command-line flag:** `--readonly` (for backward compatibility) - **UI Indicator:** `[plan]` shown in blue - **Current directory:** Hidden to save space and focus on analysis -- **Permission override:** **Absolute** - excludes all write tools (Write, Edit, Bash, etc.) and allows only read tools (Read, Grep, LS, etc.) +- **Permission override:** **Absolute** - excludes write tools (Write, Edit, etc.) and allows read tools (Read, Grep, LS, etc.) and Bash for command execution - **User config ignored:** Any user `--allow` flags for write tools are overridden ### `auto` @@ -80,5 +80,5 @@ Modes are implemented through the permission system: ### Mode-Specific Behaviors - **normal**: No mode policies applied, uses existing user configuration; shows current directory -- **plan**: **Absolute override** - excludes all write tools (Write, Edit, Bash), allows only read tools (Read, Grep, LS); hides current directory +- **plan**: **Absolute override** - excludes write tools (Write, Edit), allows read tools (Read, Grep, LS) and Bash; hides current directory - **auto**: **Absolute override** - allows all tools with `*: allow` policy; hides current directory diff --git a/src/services/ToolPermissionService.modes.test.ts b/src/services/ToolPermissionService.modes.test.ts index 9a83f758d..9303c006c 100644 --- a/src/services/ToolPermissionService.modes.test.ts +++ b/src/services/ToolPermissionService.modes.test.ts @@ -27,7 +27,7 @@ describe('ToolPermissionService - Mode Functionality', () => { // Should have specific policies for write tools (excluded) expect(policies.some(p => p.tool === 'Write' && p.permission === 'exclude')).toBe(true); expect(policies.some(p => p.tool === 'Edit' && p.permission === 'exclude')).toBe(true); - expect(policies.some(p => p.tool === 'Bash' && p.permission === 'exclude')).toBe(true); + expect(policies.some(p => p.tool === 'Bash' && p.permission === 'allow')).toBe(true); // Should have specific policies for read tools (allowed) expect(policies.some(p => p.tool === 'Read' && p.permission === 'allow')).toBe(true); @@ -187,7 +187,7 @@ describe('ToolPermissionService - Mode Functionality', () => { // Mode policies should override user config - Write should be excluded despite being in allow list expect(policies.some(p => p.tool === 'Write' && p.permission === 'exclude')).toBe(true); expect(policies.some(p => p.tool === 'Edit' && p.permission === 'exclude')).toBe(true); - expect(policies.some(p => p.tool === 'Bash' && p.permission === 'exclude')).toBe(true); + expect(policies.some(p => p.tool === 'Bash' && p.permission === 'allow')).toBe(true); // Read tools should be allowed expect(policies.some(p => p.tool === 'Read' && p.permission === 'allow')).toBe(true); diff --git a/src/services/ToolPermissionService.real.test.ts b/src/services/ToolPermissionService.real.test.ts index 3901cc08e..f854490dc 100644 --- a/src/services/ToolPermissionService.real.test.ts +++ b/src/services/ToolPermissionService.real.test.ts @@ -40,7 +40,7 @@ describe('ToolPermissionService - Real Tool Permission Test', () => { expect(result.permission).toBe('exclude'); }); - it('should deny Bash tool in plan mode', () => { + it('should allow Bash tool in plan mode', () => { const permissions = service.getPermissions(); const toolCall = { name: 'Bash', @@ -49,7 +49,7 @@ describe('ToolPermissionService - Real Tool Permission Test', () => { const result = checkToolPermission(toolCall, permissions); console.log(`Bash permission check result:`, result); - expect(result.permission).toBe('exclude'); + expect(result.permission).toBe('allow'); }); it('should allow Read tool in plan mode', () => { diff --git a/src/services/ToolPermissionService.test.ts b/src/services/ToolPermissionService.test.ts index 836893ee6..3eebb96bf 100644 --- a/src/services/ToolPermissionService.test.ts +++ b/src/services/ToolPermissionService.test.ts @@ -111,9 +111,9 @@ describe("ToolPermissionService", () => { // Should exclude write tools expect(policies).toContainEqual({ tool: 'Write', permission: 'exclude' }); expect(policies).toContainEqual({ tool: 'Edit', permission: 'exclude' }); - expect(policies).toContainEqual({ tool: 'Bash', permission: 'exclude' }); - // Should allow read tools + // Should allow read tools and bash + expect(policies).toContainEqual({ tool: 'Bash', permission: 'allow' }); expect(policies).toContainEqual({ tool: 'Read', permission: 'allow' }); expect(policies).toContainEqual({ tool: 'Grep', permission: 'allow' }); expect(policies).toContainEqual({ tool: 'LS', permission: 'allow' }); diff --git a/src/services/ToolPermissionService.ts b/src/services/ToolPermissionService.ts index fbbbeb766..8271b044e 100644 --- a/src/services/ToolPermissionService.ts +++ b/src/services/ToolPermissionService.ts @@ -36,15 +36,15 @@ export class ToolPermissionService extends BaseService { }); }); - test('should exclude Bash tool in plan mode after service initialization', async () => { + test('should allow Bash tool in plan mode after service initialization', async () => { // Initialize services in plan mode (simulating `cn -p`) await initializeServices({ headless: true, @@ -39,12 +39,12 @@ describe('getAllTools - Tool Filtering', () => { expect(serviceResult.state).toBe('ready'); expect(serviceResult.value?.currentMode).toBe('plan'); - // Get available tools - this should exclude Bash in plan mode + // Get available tools - this should include Bash in plan mode const tools = getAllTools(); const toolNames = tools.map(t => t.function.name); - // Bash should be excluded in plan mode - expect(toolNames).not.toContain('Bash'); + // Bash should be allowed in plan mode + expect(toolNames).toContain('Bash'); // Read-only tools should still be available expect(toolNames).toContain('Read'); @@ -145,7 +145,7 @@ describe('getAllTools - Tool Filtering', () => { headless: true, toolPermissionOverrides: { mode: 'plan', - allow: ['Write', 'Bash'] // These should be ignored in plan mode + allow: ['Write', 'Edit'] // These should be ignored in plan mode } }); @@ -155,9 +155,11 @@ describe('getAllTools - Tool Filtering', () => { // Plan mode should still exclude write tools despite --allow flags // This tests that plan mode policies have absolute precedence expect(toolNames).not.toContain('Write'); - expect(toolNames).not.toContain('Bash'); expect(toolNames).not.toContain('Edit'); + // Bash should be available in plan mode + expect(toolNames).toContain('Bash'); + // Read-only tools should be available expect(toolNames).toContain('Read'); expect(toolNames).toContain('List'); From 644934f9b877a35a3c160c3ee95e2aa1297364f9 Mon Sep 17 00:00:00 2001 From: Nate Date: Fri, 15 Aug 2025 14:25:25 -0700 Subject: [PATCH 10/10] adjust stdin.ts for tests --- src/util/stdin.ts | 42 +++++++++++++++++++++++++++++------------- 1 file changed, 29 insertions(+), 13 deletions(-) diff --git a/src/util/stdin.ts b/src/util/stdin.ts index b5eae1ffa..83e775779 100644 --- a/src/util/stdin.ts +++ b/src/util/stdin.ts @@ -6,27 +6,43 @@ import * as fs from "fs"; */ export function readStdinSync(): string | null { try { + // In test environments, don't attempt to read stdin to avoid hanging + if ( + process.env.NODE_ENV === "test" || + process.env.VITEST === "true" || + process.env.JEST_WORKER_ID !== undefined || + process.env.CI === "true" + ) { + return null; + } + // Check if stdin is a TTY (interactive terminal) - // On some systems process.stdin.isTTY might be undefined, so we also check if it's not false - if (process.stdin.isTTY !== false) { - // If it's true or undefined, assume it's a TTY unless we can prove otherwise + if (process.stdin.isTTY === true) { + // Definitely a TTY, don't read + return null; + } + + // If isTTY is false, we likely have piped input + if (process.stdin.isTTY === false) { + // Try to read stdin with a fallback try { - // Try to read with a non-blocking approach const stdinData = fs.readFileSync(0, "utf8"); return stdinData.trim(); - } catch (error: any) { - // If we get EAGAIN or similar, it means no data is available (TTY) - if (error.code === "EAGAIN" || error.code === "EWOULDBLOCK") { - return null; - } - // For other errors, also return null + } catch { return null; } } - // If isTTY is explicitly false, try to read stdin - const stdinData = fs.readFileSync(0, "utf8"); - return stdinData.trim(); + // If isTTY is undefined, be cautious and check if we can read non-blockingly + // This handles cases where TTY detection is unreliable + try { + // Use readFileSync with fd 0 but wrap in timeout logic + const stdinData = fs.readFileSync(0, "utf8"); + return stdinData.trim(); + } catch { + // If we can't read (EAGAIN, EWOULDBLOCK, etc.), assume no piped input + return null; + } } catch { return null; }