diff --git a/.github/workflows/respond-to-cubic-dev-ai.yml b/.github/workflows/respond-to-cubic-dev-ai.yml
index a20a53b96..e5100057c 100644
--- a/.github/workflows/respond-to-cubic-dev-ai.yml
+++ b/.github/workflows/respond-to-cubic-dev-ai.yml
@@ -58,13 +58,10 @@ jobs:
uses: actions/setup-node@v4
with:
node-version: "20"
- cache: "npm"
- - name: Install dependencies and build CLI
+ - name: Install Continue CLI globally
if: steps.check-mention.outputs.contains_mention == 'true'
- run: |
- npm ci
- npm run build
+ run: npm i -g @continuedev/cli
- name: Start remote session
if: steps.check-mention.outputs.contains_mention == 'true'
@@ -72,7 +69,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 }}
@@ -80,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
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/commands/remote.test.ts b/src/commands/remote.test.ts
index 435de1213..a5d80976d 100644
--- a/src/commands/remote.test.ts
+++ b/src/commands/remote.test.ts
@@ -67,6 +67,7 @@ describe("remote command", () => {
mockFetch.mockResolvedValue({
ok: true,
json: async () => ({
+ id: "test-agent-id",
url: "ws://test-url.com",
port: 8080,
}),
@@ -130,6 +131,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";
@@ -169,6 +188,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";
@@ -217,8 +291,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 7515087d7..54a45ad3e 100644
--- a/src/commands/remote.ts
+++ b/src/commands/remote.ts
@@ -1,20 +1,38 @@
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";
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,
- options: { url?: string; idempotencyKey?: string; start?: boolean } = {},
+ options: {
+ url?: string;
+ idempotencyKey?: string;
+ start?: boolean;
+ 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) {
@@ -40,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();
}
@@ -50,7 +68,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."),
);
@@ -62,10 +81,15 @@ export async function remote(
const requestBody: any = {
repoUrl: getRepoUrl(),
name: `devbox-${Date.now()}`,
- prompt: prompt,
+ prompt: actualPrompt,
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: {
@@ -90,8 +114,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",
}),
@@ -115,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/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);
});
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 {
+ beforeEach(() => {
+ // Clean up service container state before each test
+ const services = [
+ SERVICE_NAMES.TOOL_PERMISSIONS,
+ SERVICE_NAMES.AUTH,
+ SERVICE_NAMES.API_CLIENT,
+ SERVICE_NAMES.CONFIG,
+ SERVICE_NAMES.MODEL,
+ SERVICE_NAMES.MCP
+ ];
+
+ services.forEach(service => {
+ // Reset service state
+ (serviceContainer as any).services.delete(service);
+ (serviceContainer as any).factories.delete(service);
+ (serviceContainer as any).dependencies.delete(service);
+ });
+ });
+
test('should exclude Bash tool in plan mode after service initialization', async () => {
// Initialize services in plan mode (simulating `cn -p`)
await initializeServices({
@@ -19,12 +38,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 = await 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');
@@ -118,7 +137,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
}
});
@@ -128,9 +147,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');
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..39e9ca1f9 100644
--- a/src/tools/edit.ts
+++ b/src/tools/edit.ts
@@ -178,7 +178,14 @@ 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..1c2b7795e 100644
--- a/src/tools/multiEdit.ts
+++ b/src/tools/multiEdit.ts
@@ -309,8 +309,15 @@ 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..296fec6e3 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];
@@ -57,7 +57,9 @@ const ToolResultSummary: React.FC = ({
{toolName === "Edit"
? " File edited successfully"
- : " File written 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"}`;
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;
}