Merge pull request #8191 from continuedev/tomasz/con-4203
Background / Async / Remote mode: Kickoff in /agents when you are in the extension
This commit is contained in:
commit
7b9cb65374
11 changed files with 822 additions and 11 deletions
|
|
@ -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 };
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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);
|
||||
});
|
||||
|
|
|
|||
2
core/index.d.ts
vendored
2
core/index.d.ts
vendored
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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 & {
|
||||
|
|
|
|||
|
|
@ -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) => {
|
||||
|
|
|
|||
201
gui/src/components/BackgroundMode/AgentsList.tsx
Normal file
201
gui/src/components/BackgroundMode/AgentsList.tsx
Normal file
|
|
@ -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<Agent[] | null>(null);
|
||||
const [totalCount, setTotalCount] = useState<number>(0);
|
||||
const [error, setError] = useState<string | null>(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 (
|
||||
<div className="text-error px-2 py-4 text-sm">
|
||||
Error loading agents: {error}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (agents === null) {
|
||||
return (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<ArrowPathIcon className="text-description-muted h-6 w-6 animate-spin" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (agents.length === 0) {
|
||||
return (
|
||||
<div className="text-description-muted px-2 py-4 text-center text-sm">
|
||||
No background tasks yet. Submit a message above to create one.
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="text-description-muted px-2 text-xs font-semibold">
|
||||
Background Tasks
|
||||
</div>
|
||||
<div className="flex flex-col gap-1 px-2">
|
||||
{agents.map((agent) => (
|
||||
<div
|
||||
key={agent.id}
|
||||
className="border-command-border bg-input cursor-pointer rounded-md border p-3 shadow-md transition-colors hover:brightness-110"
|
||||
onClick={() => {
|
||||
// Open agent detail in browser
|
||||
ideMessenger.post("controlPlane/openUrl", {
|
||||
path: `agents/${agent.id}`,
|
||||
});
|
||||
}}
|
||||
>
|
||||
<div className="flex items-start justify-between">
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-sm font-medium">
|
||||
{agent.name || "Unnamed Agent"}
|
||||
</div>
|
||||
<div className="text-description mt-0.5 truncate text-xs">
|
||||
{agent.metadata?.github_repo || agent.repoUrl}
|
||||
</div>
|
||||
</div>
|
||||
<div className="ml-2">
|
||||
<AgentStatusBadge status={agent.status} />
|
||||
</div>
|
||||
</div>
|
||||
<div className="text-description-muted mt-1 text-xs">
|
||||
{formatRelativeTime(agent.createdAt)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{totalCount > agents.length && (
|
||||
<div className="mt-2">
|
||||
<button
|
||||
onClick={() => {
|
||||
ideMessenger.post("controlPlane/openUrl", {
|
||||
path: "agents",
|
||||
orgSlug: currentOrg?.slug,
|
||||
});
|
||||
}}
|
||||
className="text-link w-full cursor-pointer border-none bg-transparent p-0 text-center text-sm font-medium no-underline hover:underline"
|
||||
>
|
||||
See all {totalCount} tasks →
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function AgentStatusBadge({ status }: { status: string }) {
|
||||
const statusColors: Record<string, string> = {
|
||||
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 (
|
||||
<span
|
||||
className={`bg-badge inline-flex items-center rounded border px-2 py-0.5 text-xs font-medium ${color}`}
|
||||
>
|
||||
{status}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
150
gui/src/components/BackgroundMode/BackgroundModeView.tsx
Normal file
150
gui/src/components/BackgroundMode/BackgroundModeView.tsx
Normal file
|
|
@ -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 (
|
||||
<div className="flex flex-col items-center justify-center gap-4 px-4 py-8">
|
||||
<RocketLaunchIcon className="text-description-muted h-16 w-16" />
|
||||
<div className="max-w-md text-center">
|
||||
<h3 className="mb-2 text-lg font-semibold">Background Agents</h3>
|
||||
<p className="text-description mb-4 text-sm">
|
||||
Trigger long-running background agents that work on your codebase
|
||||
autonomously. Sign in to Continue to get started.
|
||||
</p>
|
||||
<button
|
||||
onClick={handleSignIn}
|
||||
disabled={isLoggingIn}
|
||||
className="bg-primary text-primary-foreground hover:bg-primary-hover rounded-lg px-6 py-2 disabled:opacity-50"
|
||||
>
|
||||
{isLoggingIn ? "Signing in..." : "Sign In to Continue"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-4 py-4">
|
||||
{!checkingGitHub && showGitHubSetup && (
|
||||
<div className="mx-2 rounded-lg border border-yellow-200 bg-yellow-50 p-4">
|
||||
<div className="flex items-start gap-3">
|
||||
<ExclamationTriangleIcon className="h-5 w-5 flex-shrink-0 text-yellow-600" />
|
||||
<div className="flex-1">
|
||||
<h4 className="text-sm font-semibold text-yellow-900">
|
||||
Connect GitHub
|
||||
</h4>
|
||||
<p className="mt-1 text-sm text-yellow-800">
|
||||
Background agents need access to your GitHub repositories.
|
||||
Connect your GitHub account to get started.
|
||||
</p>
|
||||
<button
|
||||
onClick={handleOpenGitHubSettings}
|
||||
className="mt-3 rounded-md bg-yellow-600 px-4 py-2 text-sm font-medium text-white hover:bg-yellow-700"
|
||||
>
|
||||
Connect GitHub Account
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="px-2">
|
||||
<div className="text-description text-sm">
|
||||
Submit a task above to run a background agent. Your task will appear
|
||||
below in ~30 seconds once the container starts.
|
||||
</div>
|
||||
{isCreatingAgent && (
|
||||
<div className="text-description-muted mt-2 flex items-center gap-2 text-xs">
|
||||
<ArrowPathIcon className="h-3 w-3 animate-spin" />
|
||||
<span>Creating task...</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<AgentsList isCreatingAgent={isCreatingAgent} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,5 +1,6 @@
|
|||
import {
|
||||
ChatBubbleLeftIcon,
|
||||
RocketLaunchIcon,
|
||||
SparklesIcon,
|
||||
SwatchIcon,
|
||||
} from "@heroicons/react/24/outline";
|
||||
|
|
@ -21,5 +22,7 @@ export function ModeIcon({
|
|||
return <SwatchIcon className={className} />;
|
||||
case "chat":
|
||||
return <ChatBubbleLeftIcon className={className} />;
|
||||
case "background":
|
||||
return <RocketLaunchIcon className={className} />;
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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 = (
|
||||
<>
|
||||
<ToolTip
|
||||
|
|
@ -96,7 +112,13 @@ export function ModeSelect() {
|
|||
>
|
||||
<ModeIcon mode={mode} />
|
||||
<span className="hidden sm:block">
|
||||
{mode === "chat" ? "Chat" : mode === "agent" ? "Agent" : "Plan"}
|
||||
{mode === "chat"
|
||||
? "Chat"
|
||||
: mode === "agent"
|
||||
? "Agent"
|
||||
: mode === "background"
|
||||
? "Background"
|
||||
: "Plan"}
|
||||
</span>
|
||||
<ChevronDownIcon
|
||||
className="h-2 w-2 flex-shrink-0"
|
||||
|
|
@ -165,6 +187,31 @@ export function ModeSelect() {
|
|||
/>
|
||||
</ListboxOption>
|
||||
|
||||
<ListboxOption
|
||||
value="background"
|
||||
className={"gap-1"}
|
||||
disabled={isLocalAgent}
|
||||
>
|
||||
<div className="flex flex-row items-center gap-1.5">
|
||||
<ModeIcon mode="background" />
|
||||
<span className="">Background</span>
|
||||
<ToolTip
|
||||
style={{
|
||||
zIndex: 200001,
|
||||
}}
|
||||
content={"Background mode cannot be used with local agents."}
|
||||
>
|
||||
<InformationCircleIcon className="h-2.5 w-2.5 flex-shrink-0" />
|
||||
</ToolTip>
|
||||
</div>
|
||||
{isLocalAgent && (
|
||||
<ExclamationTriangleIcon className="text-warning h-2.5 w-2.5" />
|
||||
)}
|
||||
<CheckIcon
|
||||
className={`ml-auto h-3 w-3 ${mode === "background" ? "" : "opacity-0"}`}
|
||||
/>
|
||||
</ListboxOption>
|
||||
|
||||
<div className="text-description-muted px-2 py-1">
|
||||
{`${metaKeyLabel} . for next mode`}
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -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 = {
|
||||
|
|
|
|||
|
|
@ -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<HTMLInputElement>(null);
|
||||
const stepsDivRef = useRef<HTMLDivElement>(null);
|
||||
const tabsRef = useRef<HTMLDivElement>(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() {
|
|||
</div>
|
||||
<FatalErrorIndicator />
|
||||
{!hasDismissedExploreDialog && <ExploreDialogWatcher />}
|
||||
{history.length === 0 && (
|
||||
<EmptyChatBody showOnboardingCard={onboardingCard.show} />
|
||||
{mode === "background" ? (
|
||||
<BackgroundModeView isCreatingAgent={isCreatingAgent} />
|
||||
) : (
|
||||
history.length === 0 && (
|
||||
<EmptyChatBody showOnboardingCard={onboardingCard.show} />
|
||||
)
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue