diff --git a/core/control-plane/client.ts b/core/control-plane/client.ts index fff0d615b..216b5c8bc 100644 --- a/core/control-plane/client.ts +++ b/core/control-plane/client.ts @@ -439,4 +439,138 @@ export class ControlPlaneClient { ); } } + + /** + * Create a new background agent + */ + public async createBackgroundAgent( + prompt: string, + repoUrl: string, + name: string, + branch?: string, + organizationId?: string, + contextItems?: any[], + selectedCode?: any[], + agent?: string, + ): Promise<{ id: string }> { + if (!(await this.isSignedIn())) { + throw new Error("Not signed in to Continue"); + } + + const requestBody: any = { + prompt, + repoUrl, + name, + branchName: branch, + }; + + if (organizationId) { + requestBody.organizationId = organizationId; + } + + // Include context items if provided + if (contextItems && contextItems.length > 0) { + requestBody.contextItems = contextItems.map((item) => ({ + content: item.content, + description: item.description, + name: item.name, + uri: item.uri, + })); + } + + // Include selected code if provided + if (selectedCode && selectedCode.length > 0) { + requestBody.selectedCode = selectedCode.map((code) => ({ + filepath: code.filepath, + range: code.range, + contents: code.contents, + })); + } + + // Include agent configuration if provided + if (agent) { + requestBody.agent = agent; + } + + const resp = await this.requestAndHandleError("agents", { + method: "POST", + headers: { + "Content-Type": "application/json", + }, + body: JSON.stringify(requestBody), + }); + + return (await resp.json()) as { id: string }; + } + + /** + * List all background agents for the current user or organization + * @param organizationId - Optional organization ID to filter agents by organization scope + * @param limit - Optional limit for number of agents to return (default: 5) + */ + public async listBackgroundAgents( + organizationId?: string, + limit?: number, + ): Promise<{ + agents: Array<{ + id: string; + name: string | null; + status: string; + repoUrl: string; + createdAt: string; + metadata?: { + github_repo?: string; + }; + }>; + totalCount: number; + }> { + if (!(await this.isSignedIn())) { + return { agents: [], totalCount: 0 }; + } + + try { + // Build URL with query parameters + const params = new URLSearchParams(); + if (organizationId) { + params.set("organizationId", organizationId); + } + if (limit !== undefined) { + params.set("limit", limit.toString()); + } + + const url = `agents${params.toString() ? `?${params.toString()}` : ""}`; + + const resp = await this.requestAndHandleError(url, { + method: "GET", + }); + + const result = (await resp.json()) as { + agents: any[]; + totalCount: number; + }; + + return { + agents: result.agents.map((agent: any) => ({ + id: agent.id, + name: agent.name || agent.metadata?.name || null, + 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(), + metadata: { + github_repo: + agent.metadata?.github_repo || agent.metadata?.repo_url, + }, + })), + totalCount: result.totalCount, + }; + } catch (e) { + Logger.error(e, { + context: "control_plane_list_background_agents", + }); + return { agents: [], totalCount: 0 }; + } + } } diff --git a/core/core.ts b/core/core.ts index 87512ccf5..03b1efc5b 100644 --- a/core/core.ts +++ b/core/core.ts @@ -472,9 +472,11 @@ export class Core { const urlPath = msg.data.path.startsWith("/") ? msg.data.path.slice(1) : msg.data.path; - let url = `${env.APP_URL}${urlPath}`; + let url; if (msg.data.orgSlug) { - url += `?org=${msg.data.orgSlug}`; + url = `${env.APP_URL}organizations/${msg.data.orgSlug}/${urlPath}`; + } else { + url = `${env.APP_URL}${urlPath}`; } await this.messenger.request("openUrl", url); }); diff --git a/core/index.d.ts b/core/index.d.ts index 685b8ade1..ae5e5cd95 100644 --- a/core/index.d.ts +++ b/core/index.d.ts @@ -462,7 +462,7 @@ export interface PromptLog { completion: string; } -export type MessageModes = "chat" | "agent" | "plan"; +export type MessageModes = "chat" | "agent" | "plan" | "background"; export type ToolStatus = | "generating" // Tool call arguments are being streamed from the LLM diff --git a/core/protocol/ideWebview.ts b/core/protocol/ideWebview.ts index 79e7de10b..c61844cca 100644 --- a/core/protocol/ideWebview.ts +++ b/core/protocol/ideWebview.ts @@ -6,8 +6,10 @@ import { AddToChatPayload, ApplyState, ApplyToFilePayload, + ContextItemWithId, HighlightedCodePayload, MessageContent, + RangeInFile, RangeInFileWithContents, SetCodeToEditPayload, ShowFilePayload, @@ -50,6 +52,32 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & { "edit/addCurrentSelection": [undefined, void]; "edit/clearDecorations": [undefined, void]; "session/share": [{ sessionId: string }, void]; + createBackgroundAgent: [ + { + content: MessageContent; + contextItems: ContextItemWithId[]; + selectedCode: RangeInFile[]; + organizationId?: string; + agent?: string; + }, + void, + ]; + listBackgroundAgents: [ + { organizationId?: string; limit?: number }, + { + agents: Array<{ + id: string; + name: string | null; + status: string; + repoUrl: string; + createdAt: string; + metadata?: { + github_repo?: string; + }; + }>; + totalCount: number; + }, + ]; }; export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & { diff --git a/extensions/vscode/src/extension/VsCodeMessenger.ts b/extensions/vscode/src/extension/VsCodeMessenger.ts index ac6427f5b..7c855100c 100644 --- a/extensions/vscode/src/extension/VsCodeMessenger.ts +++ b/extensions/vscode/src/extension/VsCodeMessenger.ts @@ -31,6 +31,7 @@ import { getExtensionUri } from "../util/vscode"; import { VsCodeIde } from "../VsCodeIde"; import { VsCodeWebviewProtocol } from "../webviewProtocol"; +import { encodeFullSlug } from "../../../../packages/config-yaml/dist"; import { VsCodeExtension } from "./VsCodeExtension"; type ToIdeOrWebviewFromCoreProtocol = ToIdeFromCoreProtocol & @@ -263,6 +264,167 @@ export class VsCodeMessenger { ); }); + this.onWebview("createBackgroundAgent", async (msg) => { + const configHandler = await configHandlerPromise; + const { content, contextItems, selectedCode, organizationId } = msg.data; + + // Convert resolved content to plain text prompt + const prompt = stripImages(content); + + if (!prompt || prompt.trim().length === 0) { + vscode.window.showErrorMessage( + "Please enter a prompt to create a background agent", + ); + return; + } + + // Get workspace information + const workspaceDirs = await this.ide.getWorkspaceDirs(); + if (workspaceDirs.length === 0) { + vscode.window.showErrorMessage( + "No workspace folder found. Please open a workspace to create a background agent.", + ); + return; + } + + const workspaceDir = workspaceDirs[0]; + let repoUrl = ""; + let branch = ""; + + try { + // 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; + } + } + + // Get current branch + const branchInfo = await this.ide.getBranch(workspaceDir); + if (branchInfo) { + branch = branchInfo; + } + } catch (e) { + console.error("Error getting repo info:", e); + } + + if (!repoUrl) { + vscode.window.showErrorMessage( + "Unable to determine repository URL. Make sure you're in a git repository.", + ); + return; + } + + // Generate a name from the prompt (first 50 chars, cleaned up) + let name = prompt.substring(0, 50).replace(/\n/g, " ").trim(); + if (prompt.length > 50) { + name += "..."; + } + // Fallback to a generic name if prompt is too short + if (name.length < 3) { + const repoName = await this.ide.getRepoName(workspaceDir); + name = `Agent for ${repoName || "repository"}`; + } + + // debugger; + + // Get the current agent configuration from the selected profile + let agent: string | undefined; + try { + const currentProfile = configHandler.currentProfile; + if ( + currentProfile && + currentProfile.profileDescription.profileType !== "local" + ) { + // Encode the full slug to pass as the agent parameter + agent = encodeFullSlug(currentProfile.profileDescription.fullSlug); + } + } catch (e) { + console.error("Error getting agent configuration from profile:", e); + // Continue without agent config - will use default + } + + // Create the background agent + try { + console.log("Creating background agent with:", { + name, + prompt: prompt.substring(0, 50) + "...", + repoUrl, + branch, + contextItemsCount: contextItems?.length || 0, + selectedCodeCount: selectedCode?.length || 0, + agent: agent || "default", + }); + + const result = + await configHandler.controlPlaneClient.createBackgroundAgent( + prompt, + repoUrl, + name, + branch, + organizationId, + contextItems, + selectedCode, + agent, + ); + + vscode.window.showInformationMessage( + `Background agent created successfully! Agent ID: ${result.id}`, + ); + } catch (e) { + console.error("Failed to create background agent:", e); + const errorMessage = + e instanceof Error ? e.message : "Unknown error occurred"; + + // Check if this is a GitHub authorization error + if ( + errorMessage.includes("GitHub token") || + errorMessage.includes("GitHub App") + ) { + const selection = await vscode.window.showErrorMessage( + "Background agents need GitHub access. Please connect your GitHub account to Continue.", + "Connect GitHub", + "Cancel", + ); + + if (selection === "Connect GitHub") { + await this.inProcessMessenger.externalRequest( + "controlPlane/openUrl", + { + path: "settings/integrations", + orgSlug: configHandler.currentOrg?.slug, + }, + ); + } + } else { + vscode.window.showErrorMessage( + `Failed to create background agent: ${errorMessage}`, + ); + } + } + }); + + this.onWebview("listBackgroundAgents", async (msg) => { + const configHandler = await configHandlerPromise; + const { organizationId, limit } = msg.data; + + try { + const result = + await configHandler.controlPlaneClient.listBackgroundAgents( + organizationId, + limit, + ); + return result; + } catch (e) { + console.error("Error listing background agents:", e); + return { agents: [], totalCount: 0 }; + } + }); + /** 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 new file mode 100644 index 000000000..2af6400bb --- /dev/null +++ b/gui/src/components/BackgroundMode/AgentsList.tsx @@ -0,0 +1,201 @@ +import { ArrowPathIcon } from "@heroicons/react/24/outline"; +import { useContext, useEffect, useState } from "react"; +import { useAuth } from "../../context/Auth"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { useAppSelector } from "../../redux/hooks"; +import { selectCurrentOrg } from "../../redux/slices/profilesSlice"; + +interface Agent { + id: string; + name: string | null; + status: string; + repoUrl: string; + createdAt: string; + metadata?: { + github_repo?: string; + }; +} + +interface AgentsListProps { + isCreatingAgent?: boolean; +} + +export function AgentsList({ isCreatingAgent = false }: AgentsListProps) { + const { session } = useAuth(); + const ideMessenger = useContext(IdeMessengerContext); + const currentOrg = useAppSelector(selectCurrentOrg); + const [agents, setAgents] = useState(null); + const [totalCount, setTotalCount] = useState(0); + const [error, setError] = useState(null); + + useEffect(() => { + async function fetchAgents() { + if (!session) { + setAgents([]); + setTotalCount(0); + return; + } + + try { + const organizationId = + currentOrg?.id !== "personal" ? currentOrg?.id : undefined; + const result = await ideMessenger.request("listBackgroundAgents", { + organizationId, + limit: 5, + }); + + if ("status" in result && result.status === "success") { + const content = result.content as { + agents: Agent[]; + totalCount: number; + }; + setAgents(content.agents || []); + setTotalCount(content.totalCount || 0); + setError(null); + } else if ("error" in result) { + setError(result.error); + setAgents([]); + setTotalCount(0); + } else { + setAgents([]); + setTotalCount(0); + } + } catch (err: any) { + console.error("Failed to fetch agents:", err); + setError(err.message || "Failed to load agents"); + setAgents([]); + setTotalCount(0); + } + } + + void fetchAgents(); + + // Poll for updates every 10 seconds + const interval = setInterval(() => { + void fetchAgents(); + }, 10000); + + return () => clearInterval(interval); + }, [session, ideMessenger, currentOrg]); + + if (error) { + return ( +
+ Error loading agents: {error} +
+ ); + } + + if (agents === null) { + return ( +
+ +
+ ); + } + + if (agents.length === 0) { + return ( +
+ No background tasks yet. Submit a message above to create one. +
+ ); + } + + return ( +
+
+ Background Tasks +
+
+ {agents.map((agent) => ( +
{ + // Open agent detail in browser + ideMessenger.post("controlPlane/openUrl", { + path: `agents/${agent.id}`, + }); + }} + > +
+
+
+ {agent.name || "Unnamed Agent"} +
+
+ {agent.metadata?.github_repo || agent.repoUrl} +
+
+
+ +
+
+
+ {formatRelativeTime(agent.createdAt)} +
+
+ ))} + {totalCount > agents.length && ( +
+ +
+ )} +
+
+ ); +} + +function AgentStatusBadge({ status }: { status: string }) { + const statusColors: Record = { + running: "border-success text-success", + pending: "border-warning text-warning", + creating: "border-info text-info", + failure: "border-error text-error", + suspended: "border-description text-description", + }; + + const color = statusColors[status] || "border-description text-description"; + + return ( + + {status} + + ); +} + +function formatRelativeTime(dateString: string): string { + try { + const date = new Date(dateString); + const now = new Date(); + const diffMs = now.getTime() - date.getTime(); + const diffMins = Math.floor(diffMs / 60000); + const diffHours = Math.floor(diffMs / 3600000); + const diffDays = Math.floor(diffMs / 86400000); + + if (diffMins < 1) { + return "just now"; + } else if (diffMins < 60) { + return `${diffMins}m ago`; + } else if (diffHours < 24) { + return `${diffHours}h ago`; + } else { + return `${diffDays}d ago`; + } + } catch { + return dateString; + } +} diff --git a/gui/src/components/BackgroundMode/BackgroundModeView.tsx b/gui/src/components/BackgroundMode/BackgroundModeView.tsx new file mode 100644 index 000000000..db917b651 --- /dev/null +++ b/gui/src/components/BackgroundMode/BackgroundModeView.tsx @@ -0,0 +1,150 @@ +import { + ArrowPathIcon, + ExclamationTriangleIcon, + RocketLaunchIcon, +} from "@heroicons/react/24/outline"; +import { useCallback, useContext, useEffect, useState } from "react"; +import { useAuth } from "../../context/Auth"; +import { IdeMessengerContext } from "../../context/IdeMessenger"; +import { useAppSelector } from "../../redux/hooks"; +import { selectCurrentOrg } from "../../redux/slices/profilesSlice"; +import { AgentsList } from "./AgentsList"; + +interface BackgroundModeViewProps { + isCreatingAgent?: boolean; +} + +export function BackgroundModeView({ + isCreatingAgent = false, +}: BackgroundModeViewProps) { + const { session, login } = useAuth(); + const ideMessenger = useContext(IdeMessengerContext); + const currentOrg = useAppSelector(selectCurrentOrg); + const [isLoggingIn, setIsLoggingIn] = useState(false); + const [showGitHubSetup, setShowGitHubSetup] = useState(false); + const [checkingGitHub, setCheckingGitHub] = useState(true); + + const handleSignIn = useCallback(async () => { + setIsLoggingIn(true); + try { + await login(false); + } catch (error) { + console.error("Login failed:", error); + } finally { + setIsLoggingIn(false); + } + }, [login]); + + const handleOpenGitHubSettings = useCallback(() => { + // Open the hub settings page for GitHub integration + ideMessenger.post("controlPlane/openUrl", { + path: "settings/integrations/github", + orgSlug: currentOrg?.slug, + }); + }, [ideMessenger, currentOrg]); + + // Check if user has GitHub installations when signed in + useEffect(() => { + async function checkGitHubAuth() { + if (!session) { + setCheckingGitHub(false); + return; + } + + try { + 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", {}); + + // Check for error response + if ("error" in result) { + // Check if error is related to GitHub token + if ( + result.error?.includes("GitHub token") || + result.error?.includes("GitHub App") + ) { + setShowGitHubSetup(true); + } + } else { + // If we got here without error, GitHub is connected + setShowGitHubSetup(false); + } + } catch (error: any) { + // Check if error is related to GitHub token + if ( + error?.message?.includes("GitHub token") || + error?.message?.includes("GitHub App") + ) { + setShowGitHubSetup(true); + } + } finally { + setCheckingGitHub(false); + } + } + + void checkGitHubAuth(); + }, [session, ideMessenger]); + + if (!session) { + return ( +
+ +
+

Background Agents

+

+ Trigger long-running background agents that work on your codebase + autonomously. Sign in to Continue to get started. +

+ +
+
+ ); + } + + return ( +
+ {!checkingGitHub && showGitHubSetup && ( +
+
+ +
+

+ Connect GitHub +

+

+ Background agents need access to your GitHub repositories. + Connect your GitHub account to get started. +

+ +
+
+
+ )} +
+
+ Submit a task above to run a background agent. Your task will appear + below in ~30 seconds once the container starts. +
+ {isCreatingAgent && ( +
+ + Creating task... +
+ )} +
+ +
+ ); +} diff --git a/gui/src/components/ModeSelect/ModeIcon.tsx b/gui/src/components/ModeSelect/ModeIcon.tsx index 92dfc1723..074185886 100644 --- a/gui/src/components/ModeSelect/ModeIcon.tsx +++ b/gui/src/components/ModeSelect/ModeIcon.tsx @@ -1,5 +1,6 @@ import { ChatBubbleLeftIcon, + RocketLaunchIcon, SparklesIcon, SwatchIcon, } from "@heroicons/react/24/outline"; @@ -21,5 +22,7 @@ export function ModeIcon({ return ; case "chat": return ; + case "background": + return ; } } diff --git a/gui/src/components/ModeSelect/ModeSelect.tsx b/gui/src/components/ModeSelect/ModeSelect.tsx index 88a549012..4a9c2616a 100644 --- a/gui/src/components/ModeSelect/ModeSelect.tsx +++ b/gui/src/components/ModeSelect/ModeSelect.tsx @@ -8,6 +8,7 @@ import { MessageModes } from "core"; import { isRecommendedAgentModel } from "core/llm/toolSupport"; import { capitalize } from "lodash"; import { useCallback, useEffect, useMemo } from "react"; +import { useAuth } from "../../context/Auth"; import { useAppDispatch, useAppSelector } from "../../redux/hooks"; import { selectSelectedChatModel } from "../../redux/slices/configSlice"; import { setMode } from "../../redux/slices/sessionSlice"; @@ -21,6 +22,7 @@ export function ModeSelect() { const dispatch = useAppDispatch(); const mode = useAppSelector((store) => store.session.mode); const selectedModel = useAppSelector(selectSelectedChatModel); + const { selectedProfile } = useAuth(); const isGoodAtAgentMode = useMemo(() => { if (!selectedModel) { @@ -29,6 +31,10 @@ export function ModeSelect() { return isRecommendedAgentModel(selectedModel.model); }, [selectedModel]); + const isLocalAgent = useMemo(() => { + return selectedProfile?.profileType === "local"; + }, [selectedProfile]); + const { mainEditor } = useMainEditor(); const metaKeyLabel = useMemo(() => { return getMetaKeyLabel(); @@ -39,6 +45,9 @@ export function ModeSelect() { dispatch(setMode("plan")); } else if (mode === "plan") { dispatch(setMode("agent")); + } else if (mode === "agent") { + // Skip background mode if local agent is selected + dispatch(setMode(isLocalAgent ? "chat" : "background")); } else { dispatch(setMode("chat")); } @@ -46,7 +55,7 @@ export function ModeSelect() { if (!document.activeElement?.classList?.contains("ProseMirror")) { mainEditor?.commands.focus(); } - }, [mode, mainEditor]); + }, [mode, mainEditor, isLocalAgent]); const selectMode = useCallback( (newMode: MessageModes) => { @@ -73,6 +82,13 @@ export function ModeSelect() { return () => document.removeEventListener("keydown", handleKeyDown); }, [cycleMode]); + // Auto-switch from background mode when local agent is selected + useEffect(() => { + if (mode === "background" && isLocalAgent) { + dispatch(setMode("agent")); + } + }, [mode, isLocalAgent, dispatch]); + const notGreatAtAgent = ( <> - {mode === "chat" ? "Chat" : mode === "agent" ? "Agent" : "Plan"} + {mode === "chat" + ? "Chat" + : mode === "agent" + ? "Agent" + : mode === "background" + ? "Background" + : "Plan"} + +
+ + Background + + + +
+ {isLocalAgent && ( + + )} + +
+
{`${metaKeyLabel} . for next mode`}
diff --git a/gui/src/context/MockIdeMessenger.ts b/gui/src/context/MockIdeMessenger.ts index e3ab3fb58..e7f78252d 100644 --- a/gui/src/context/MockIdeMessenger.ts +++ b/gui/src/context/MockIdeMessenger.ts @@ -55,14 +55,37 @@ const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = { }, }, "config/getSerializedProfileInfo": { - organizations: [], - profileId: "test-profile", + organizations: [ + { + id: "personal", + profiles: [ + { + title: "Local Agent", + id: "local", + errors: [], + profileType: "local", + uri: "", + iconUrl: "", + fullSlug: { + ownerSlug: "", + packageSlug: "", + versionSlug: "", + }, + }, + ], + slug: "", + selectedProfileId: "local", + name: "Personal", + iconUrl: "", + }, + ], + profileId: "local", result: { config: undefined, errors: [], configLoadInterrupted: false, }, - selectedOrgId: "local", + selectedOrgId: "personal", }, "chatDescriber/describe": "Session summary", applyToFile: undefined, @@ -101,6 +124,7 @@ const DEFAULT_MOCK_CORE_RESPONSES: MockResponses = { }, }, ], + listBackgroundAgents: { agents: [], totalCount: 0 }, }; const DEFAULT_MOCK_CORE_RESPONSE_HANDLERS: MockResponseHandlers = { diff --git a/gui/src/pages/gui/Chat.tsx b/gui/src/pages/gui/Chat.tsx index c6948674b..521c46bdc 100644 --- a/gui/src/pages/gui/Chat.tsx +++ b/gui/src/pages/gui/Chat.tsx @@ -31,6 +31,7 @@ import { selectDoneApplyStates, selectPendingToolCalls, } from "../../redux/selectors/selectToolCalls"; +import { selectCurrentOrg } from "../../redux/slices/profilesSlice"; import { cancelToolCall, ChatHistoryItemWithMessageId, @@ -44,10 +45,12 @@ import { isJetBrains, isMetaEquivalentKeyPressed } from "../../util"; import { ToolCallDiv } from "./ToolCallDiv"; import { useStore } from "react-redux"; +import { BackgroundModeView } from "../../components/BackgroundMode/BackgroundModeView"; import { CliInstallBanner } from "../../components/CliInstallBanner"; import { FatalErrorIndicator } from "../../components/config/FatalErrorNotice"; import InlineErrorMessage from "../../components/mainInput/InlineErrorMessage"; +import { resolveEditorContent } from "../../components/mainInput/TipTapEditor/utils/resolveEditorContent"; import { RootState } from "../../redux/store"; import { cancelStream } from "../../redux/thunks/cancelStream"; import { EmptyChatBody } from "./EmptyChatBody"; @@ -109,6 +112,7 @@ export function Chat() { ); const isStreaming = useAppSelector((state) => state.session.isStreaming); const [stepsOpen] = useState<(boolean | undefined)[]>([]); + const [isCreatingAgent, setIsCreatingAgent] = useState(false); const mainTextInputRef = useRef(null); const stepsDivRef = useRef(null); const tabsRef = useRef(null); @@ -126,6 +130,8 @@ export function Chat() { const hasDismissedExploreDialog = useAppSelector( (state) => state.ui.hasDismissedExploreDialog, ); + const mode = useAppSelector((state) => state.session.mode); + const currentOrg = useAppSelector(selectCurrentOrg); const jetbrains = useMemo(() => { return isJetBrains(); }, []); @@ -170,6 +176,56 @@ export function Chat() { const codeToEditSnapshot = stateSnapshot.editModeState.codeToEdit; const selectedModelByRole = stateSnapshot.config.config.selectedModelByRole; + const currentMode = stateSnapshot.session.mode; + + // Handle background mode specially + if (currentMode === "background" && !isCurrentlyInEdit) { + // Background mode triggers agent creation instead of chat + const currentOrg = selectCurrentOrg(stateSnapshot); + const organizationId = + currentOrg?.id !== "personal" ? currentOrg?.id : undefined; + + setIsCreatingAgent(true); + + // Clear input immediately for better UX + if (editorToClearOnSend) { + editorToClearOnSend.commands.clearContent(); + } + + // Create agent and track loading state + void (async () => { + try { + // Resolve context items from editor content (same as normal chat) + const defaultContextProviders = + stateSnapshot.config.config.experimental?.defaultContext ?? []; + + const { selectedContextItems, selectedCode, content } = + await resolveEditorContent({ + editorState, + modifiers, + ideMessenger, + defaultContextProviders, + availableSlashCommands: + stateSnapshot.config.config.slashCommands, + dispatch, + getState: () => reduxStore.getState(), + }); + + await ideMessenger.request("createBackgroundAgent", { + content, + contextItems: selectedContextItems, + selectedCode, + organizationId, + }); + setIsCreatingAgent(false); + } catch (error) { + console.error("Failed to create background agent:", error); + setIsCreatingAgent(false); + } + })(); + + return; + } // Cancel all pending tool calls latestPendingToolCalls.forEach((toolCallState) => { @@ -213,7 +269,7 @@ export function Chat() { } } }, - [dispatch, ideMessenger, reduxStore], + [dispatch, ideMessenger, reduxStore, setIsCreatingAgent], ); useWebviewListener( @@ -430,8 +486,12 @@ export function Chat() { {!hasDismissedExploreDialog && } - {history.length === 0 && ( - + {mode === "background" ? ( + + ) : ( + history.length === 0 && ( + + ) )}