Feat: cancel-run buttons [manager, planner, programmer] (#330)

* cancel run: manager, programmer, planner

* improve error handling + useCancelStream hook abstraction

* cancel stream button

* minor format

* Code review

* CR: remove duplicate stream

* Apply suggestions from code review

* cr

* use cancelStreamButton

* cleanup and fix flash

* cr

---------

Co-authored-by: Brace Sproul <braceasproul@gmail.com>
This commit is contained in:
Dylan Boudro 2025-07-08 08:04:27 -07:00 • committed by GitHub
parent 3210da1ac4
commit 4793ee3d3a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 217 additions and 13 deletions

View file

@ -3,6 +3,7 @@ import { UseStream, useStream } from "@langchain/langgraph-sdk/react";
import { AssistantMessage } from "../thread/messages/ai";
import { Dispatch, SetStateAction, useEffect, useRef, useState } from "react";
import { ManagerGraphState } from "@open-swe/shared/open-swe/manager/types";
import { useCancelStream } from "@/hooks/useCancelStream";
import {
isCustomNodeEvent,
CustomNodeEvent,
@ -67,6 +68,7 @@ interface ActionsRendererProps {
) => void;
programmerSession?: ManagerGraphState["programmerSession"];
setSelectedTab?: Dispatch<SetStateAction<"planner" | "programmer">>;
onStreamReady: (cancelFn: (() => void) | undefined) => void;
}
const getCustomNodeEventsFromMessages = (
@ -98,6 +100,7 @@ export function ActionsRenderer<State extends PlannerGraphState | GraphState>({
setProgrammerSession,
programmerSession,
setSelectedTab,
onStreamReady,
}: ActionsRendererProps) {
const [customNodeEvents, setCustomNodeEvents] = useState<CustomNodeEvent[]>(
[],
@ -114,6 +117,13 @@ export function ActionsRenderer<State extends PlannerGraphState | GraphState>({
},
});
const { cancelRun } = useCancelStream<State>({
stream,
threadId,
runId,
streamName: graphId === "planner" ? "Planner" : "Programmer",
});
const initializeEvents = customNodeEvents.filter(
(e) => e.nodeId === INITIALIZE_NODE_ID,
);
@ -167,6 +177,14 @@ export function ActionsRenderer<State extends PlannerGraphState | GraphState>({
}
}, [runId]);
useEffect(() => {
if (stream.isLoading) {
onStreamReady(cancelRun);
} else {
onStreamReady(undefined);
}
}, [onStreamReady, runId]); // Depend on runId instead of cancelRun to avoid infinite loops
// Filter out human & do not render messages
const filteredMessages = stream.messages?.filter(
(m) =>

View file

@ -0,0 +1,43 @@
import { Button } from "@/components/ui/button";
import { Loader2 } from "lucide-react";
import { UseStream } from "@langchain/langgraph-sdk/react";
import { useCancelStream } from "@/hooks/useCancelStream";
interface CancelStreamButtonProps {
stream: UseStream<any>;
threadId?: string;
runId?: string;
streamName: "Planner" | "Programmer";
}
export function CancelStreamButton({
stream,
threadId,
runId,
streamName,
}: CancelStreamButtonProps) {
const { cancelRun } = useCancelStream({
stream,
threadId,
runId,
streamName,
});
const shouldShow = stream.isLoading && threadId && runId;
if (!shouldShow) {
return null;
}
return (
<Button
onClick={cancelRun}
size="sm"
variant="destructive"
className="h-8 px-3 text-xs"
>
<Loader2 className="mr-1 h-3 w-3 animate-spin" />
Stop {streamName}
</Button>
);
}

View file

@ -5,10 +5,12 @@ import { useState } from "react";
import { StickToBottom } from "use-stick-to-bottom";
import { TooltipIconButton } from "../ui/tooltip-icon-button";
import { AnimatePresence, motion } from "framer-motion";
import { Bot, Copy, CopyCheck, Send, User } from "lucide-react";
import { Bot, Copy, CopyCheck, Send, User, Loader2 } from "lucide-react";
import { Textarea } from "../ui/textarea";
import { Button } from "../ui/button";
import { useStream } from "@langchain/langgraph-sdk/react";
import { ManagerGraphState } from "@open-swe/shared/open-swe/manager/types";
import { cn } from "@/lib/utils";
function MessageCopyButton({ content }: { content: string }) {
const [copied, setCopied] = useState(false);
@ -61,6 +63,8 @@ interface ManagerChatProps {
chatInput: string;
setChatInput: (input: string) => void;
handleSendMessage: () => void;
isLoading: boolean;
cancelRun: () => void;
}
export function ManagerChat({
@ -68,6 +72,8 @@ export function ManagerChat({
chatInput,
setChatInput,
handleSendMessage,
isLoading,
cancelRun,
}: ManagerChatProps) {
return (
<div className="border-border bg-muted/30 flex h-full w-1/3 flex-col border-r dark:bg-gray-950">
@ -133,19 +139,27 @@ export function ManagerChat({
placeholder="Type your message..."
className="border-border bg-background text-foreground placeholder:text-muted-foreground min-h-[60px] flex-1 resize-none text-sm dark:bg-gray-900"
onKeyDown={(e) => {
if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
if (e.key === "Enter" && (e.metaKey || e.ctrlKey) && !isLoading) {
e.preventDefault();
handleSendMessage();
}
}}
/>
<Button
onClick={handleSendMessage}
disabled={!chatInput.trim()}
size="icon"
variant="brand"
onClick={isLoading ? cancelRun : handleSendMessage}
disabled={isLoading ? false : !chatInput.trim()}
size={isLoading ? "sm" : "icon"}
variant={isLoading ? "destructive" : "brand"}
className={cn(isLoading ? "h-12 px-4 py-2" : "")}
>
<Send className="size-4" />
{isLoading ? (
<>
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
Cancel
</>
) : (
<Send className="size-4" />
)}
</Button>
</div>
<div className="text-muted-foreground mt-2 text-xs">

View file

@ -24,6 +24,34 @@ The file should not contain any other content besides those tags, and the rules/
With all of this in mind, please explore the repository and write this single \`AGENTS.md\` file with the rules/context/instructions gathered!`;
const DEV_README_PROMPT = `Please add a new callout to the root readme in the repository:
"Welcome to Open SWE!"
Make it a 'tip' callout`;
function DevReadmePromptQuickAction({
setQuickActionPrompt,
}: QuickActionsProps) {
const nodeEnv = process.env.NODE_ENV;
if (nodeEnv === "production") {
return null;
}
return (
<Card
onClick={() => setQuickActionPrompt(DEV_README_PROMPT)}
className="border-border bg-card hover:bg-muted cursor-pointer py-3 transition-shadow hover:shadow-lg dark:bg-gray-950"
>
<CardHeader className="px-3">
<CardTitle className="text-foreground text-sm">
[DEV] Add Welcome Callout
</CardTitle>
<CardDescription className="text-muted-foreground text-xs">
Add a welcome callout to the root readme.
</CardDescription>
</CardHeader>
</Card>
);
}
interface QuickActionsProps {
setQuickActionPrompt: Dispatch<SetStateAction<string>>;
}
@ -35,6 +63,9 @@ export function QuickActions({ setQuickActionPrompt }: QuickActionsProps) {
Quick Actions
</h2>
<div className="grid gap-3 md:grid-cols-3">
<DevReadmePromptQuickAction
setQuickActionPrompt={setQuickActionPrompt}
/>
<Card
onClick={() => setQuickActionPrompt(GENERATE_RULES_PROMPT)}
className="border-border bg-card hover:bg-muted cursor-pointer py-3 transition-shadow hover:shadow-lg dark:bg-gray-950"

View file

@ -1,7 +1,7 @@
"use client";
import { v4 as uuidv4 } from "uuid";
import { useState } from "react";
import { useState, useEffect, useRef } from "react";
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { ArrowLeft, GitBranch, Terminal, Clock } from "lucide-react";
@ -26,6 +26,7 @@ import {
ScrollToBottom,
} from "../../utils/scroll-utils";
import { ManagerChat } from "./manager-chat";
import { CancelStreamButton } from "./cancel-stream-button";
interface ThreadViewProps {
stream: ReturnType<typeof useStream<ManagerGraphState>>;
@ -49,6 +50,14 @@ export function ThreadView({
const [programmerSession, setProgrammerSession] =
useState<ManagerGraphState["programmerSession"]>();
const plannerCancelRef = useRef<(() => void) | null>(null);
const programmerCancelRef = useRef<(() => void) | null>(null);
const cancelRun = () => {
// TODO: ideally this calls stream.client.runs.cancel(threadId, runId)
stream.stop();
};
const handleSendMessage = () => {
if (chatInput.trim()) {
const newHumanMessage = new HumanMessage({
@ -126,6 +135,8 @@ export function ThreadView({
chatInput={chatInput}
setChatInput={setChatInput}
handleSendMessage={handleSendMessage}
isLoading={stream.isLoading}
cancelRun={cancelRun}
/>
{/* Right Side - Actions & Plan */}
<div className="flex h-full flex-1 flex-col">
@ -146,10 +157,35 @@ export function ThreadView({
setSelectedTab(value as "planner" | "programmer")
}
>
<TabsList className="bg-muted/70 dark:bg-gray-800">
<TabsTrigger value="planner">Planner</TabsTrigger>
<TabsTrigger value="programmer">Programmer</TabsTrigger>
</TabsList>
<div className="flex items-center justify-between">
<TabsList className="bg-muted/70 dark:bg-gray-800">
<TabsTrigger value="planner">Planner</TabsTrigger>
<TabsTrigger value="programmer">Programmer</TabsTrigger>
</TabsList>
<div className="flex gap-2">
{selectedTab === "planner" &&
plannerCancelRef.current && (
<CancelStreamButton
stream={stream}
threadId={plannerThreadId}
runId={plannerRunId}
streamName="Planner"
/>
)}
{selectedTab === "programmer" &&
programmerCancelRef.current && (
<CancelStreamButton
stream={stream}
threadId={plannerThreadId}
runId={plannerRunId}
streamName="Programmer"
/>
)}
</div>
</div>
<TabsContent value="planner">
<Card className="border-border bg-card px-0 py-4 dark:bg-gray-950">
<CardContent className="space-y-2 p-3 pt-0">
@ -161,6 +197,13 @@ export function ThreadView({
setProgrammerSession={setProgrammerSession}
programmerSession={programmerSession}
setSelectedTab={setSelectedTab}
onStreamReady={(cancelFn) => {
if (cancelFn) {
plannerCancelRef.current = cancelFn;
} else {
plannerCancelRef.current = null;
}
}}
/>
)}
{!(plannerThreadId && plannerRunId) && (
@ -182,6 +225,13 @@ export function ThreadView({
graphId={PROGRAMMER_GRAPH_ID}
threadId={programmerSession.threadId}
runId={programmerSession.runId}
onStreamReady={(cancelFn) => {
if (cancelFn) {
programmerCancelRef.current = cancelFn;
} else {
programmerCancelRef.current = null;
}
}}
/>
)}
{!programmerSession && (

View file

@ -0,0 +1,48 @@
import { UseStream } from "@langchain/langgraph-sdk/react";
import { PlannerGraphState } from "@open-swe/shared/open-swe/planner/types";
import { GraphState } from "@open-swe/shared/open-swe/types";
import { toast } from "sonner";
interface UseCancelStreamProps<State extends PlannerGraphState | GraphState> {
stream: UseStream<State>;
threadId?: string;
runId?: string;
streamName: "Planner" | "Programmer";
}
export function useCancelStream<State extends PlannerGraphState | GraphState>({
stream,
threadId,
runId,
streamName,
}: UseCancelStreamProps<State>) {
const cancelRun = async () => {
if (!threadId || !runId) {
toast.error(`Cannot cancel ${streamName}: Missing thread or run ID`);
return;
}
try {
await stream.client.runs.cancel(threadId, runId);
toast.success(`${streamName} cancelled successfully`, {
description: "The running operation has been stopped",
});
} catch (error) {
const errorStr = String(error);
const isAbortError = errorStr.toLowerCase().includes("abort");
if (isAbortError) {
toast.info(`${streamName} operation cancelled`, {
description: "The stream was successfully stopped",
});
} else {
console.error(`Error cancelling ${streamName} run:`, error);
toast.error(`Failed to cancel ${streamName}`, {
description: errorStr || "Unknown error occurred",
});
}
}
};
return { cancelRun };
}