Skip to content

πŸ™Œ OpenHands: AI-Driven Development

feat: support controlling agent task state. (#1094)

Leo1356da8795a7
diff --git a/agenthub/monologue_agent/utils/memory.py b/agenthub/monologue_agent/utils/memory.py
index 9cdc6c92c0..e14fdf1e08 100644
--- a/agenthub/monologue_agent/utils/memory.py
+++ b/agenthub/monologue_agent/utils/memory.py
@@ -84,7 +84,7 @@ class LongTermMemory:
},
)
self.thought_idx += 1
- logger.debug("Adding %s event to memory: %d", t, self.thought_idx)
+ logger.debug('Adding %s event to memory: %d', t, self.thought_idx)
self.index.insert(doc)
def search(self, query: str, k: int = 10):
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 039a53929d..448ef7709b 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -12,9 +12,7 @@ import Workspace from "./components/Workspace";
import { fetchMsgTotal } from "./services/session";
import { initializeAgent } from "./services/settingsService";
import Socket from "./services/socket";
-import { ResConfigurations, ResFetchMsgTotal } from "./types/ResponseType";
-import ActionType from "./types/ActionType";
-import { getCachedConfig } from "./utils/storage";
+import { ResFetchMsgTotal } from "./types/ResponseType";
interface Props {
setSettingOpen: (isOpen: boolean) => void;
@@ -38,13 +36,16 @@ let initOnce = false;
function App(): JSX.Element {
const [settingOpen, setSettingOpen] = useState(false);
+ const [isWarned, setIsWarned] = useState(false);
const [loadMsgWarning, setLoadMsgWarning] = useState(false);
const getMsgTotal = () => {
+ if (isWarned) return;
fetchMsgTotal()
.then((data: ResFetchMsgTotal) => {
if (data.msg_total > 0) {
setLoadMsgWarning(true);
+ setIsWarned(true);
}
})
.catch();
diff --git a/frontend/src/assets/arrow.tsx b/frontend/src/assets/arrow.tsx
new file mode 100644
index 0000000000..b4d4036725
--- /dev/null
+++ b/frontend/src/assets/arrow.tsx
@@ -0,0 +1,22 @@
+import React from "react";
+
+function ArrowIcon(): JSX.Element {
+ return (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ fill="none"
+ viewBox="0 0 24 24"
+ strokeWidth={1.5}
+ stroke="currentColor"
+ className="w-5 h-5"
+ >
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ d="M16.023 9.348h4.992v-.001M2.985 19.644v-4.992m0 0h4.992m-4.993 0 3.181 3.183a8.25 8.25 0 0 0 13.803-3.7M4.031 9.865a8.25 8.25 0 0 1 13.803-3.7l3.181 3.182m0-4.991v4.99"
+ />
+ </svg>
+ );
+}
+
+export default ArrowIcon;
diff --git a/frontend/src/assets/pause.tsx b/frontend/src/assets/pause.tsx
new file mode 100644
index 0000000000..dbf0d278d2
--- /dev/null
+++ b/frontend/src/assets/pause.tsx
@@ -0,0 +1,22 @@
+import React from "react";
+
+function PauseIcon(): JSX.Element {
+ return (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ fill="none"
+ viewBox="0 0 24 24"
+ strokeWidth={1.5}
+ stroke="currentColor"
+ className="w-5 h-5"
+ >
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ d="M15.75 5.25v13.5m-7.5-13.5v13.5"
+ />
+ </svg>
+ );
+}
+
+export default PauseIcon;
diff --git a/frontend/src/assets/play.tsx b/frontend/src/assets/play.tsx
new file mode 100644
index 0000000000..ce77bfecf5
--- /dev/null
+++ b/frontend/src/assets/play.tsx
@@ -0,0 +1,22 @@
+import React from "react";
+
+function PlayIcon(): JSX.Element {
+ return (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ fill="none"
+ viewBox="0 0 24 24"
+ strokeWidth={1.5}
+ stroke="currentColor"
+ className="w-5 h-5"
+ >
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ d="M5.25 5.653c0-.856.917-1.398 1.667-.986l11.54 6.347a1.125 1.125 0 0 1 0 1.972l-11.54 6.347a1.125 1.125 0 0 1-1.667-.986V5.653Z"
+ />
+ </svg>
+ );
+}
+
+export default PlayIcon;
diff --git a/frontend/src/assets/stop.tsx b/frontend/src/assets/stop.tsx
new file mode 100644
index 0000000000..8982edf8de
--- /dev/null
+++ b/frontend/src/assets/stop.tsx
@@ -0,0 +1,22 @@
+import React from "react";
+
+function StopIcon(): JSX.Element {
+ return (
+ <svg
+ xmlns="http://www.w3.org/2000/svg"
+ fill="none"
+ viewBox="0 0 24 24"
+ strokeWidth={1.5}
+ stroke="currentColor"
+ className="w-5 h-5"
+ >
+ <path
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ d="M5.25 7.5A2.25 2.25 0 0 1 7.5 5.25h9a2.25 2.25 0 0 1 2.25 2.25v9a2.25 2.25 0 0 1-2.25 2.25h-9a2.25 2.25 0 0 1-2.25-2.25v-9Z"
+ />
+ </svg>
+ );
+}
+
+export default StopIcon;
diff --git a/frontend/src/components/AgentControlBar.tsx b/frontend/src/components/AgentControlBar.tsx
new file mode 100644
index 0000000000..e4c2abdc71
--- /dev/null
+++ b/frontend/src/components/AgentControlBar.tsx
@@ -0,0 +1,152 @@
+import React, { useEffect } from "react";
+import { Button, ButtonGroup, Tooltip } from "@nextui-org/react";
+import { useSelector } from "react-redux";
+import PauseIcon from "../assets/pause";
+import PlayIcon from "../assets/play";
+import AgentTaskAction from "../types/AgentTaskAction";
+import { changeTaskState } from "../services/agentStateService";
+import store, { RootState } from "../store";
+import AgentTaskState from "../types/AgentTaskState";
+import ArrowIcon from "../assets/arrow";
+import { clearMsgs } from "../services/session";
+import { clearMessages } from "../state/chatSlice";
+
+const TaskStateActionMap = {
+ [AgentTaskAction.START]: AgentTaskState.RUNNING,
+ [AgentTaskAction.PAUSE]: AgentTaskState.PAUSED,
+ [AgentTaskAction.RESUME]: AgentTaskState.RUNNING,
+ [AgentTaskAction.STOP]: AgentTaskState.STOPPED,
+};
+
+const IgnoreTaskStateMap: { [k: string]: AgentTaskState[] } = {
+ [AgentTaskAction.PAUSE]: [
+ AgentTaskState.INIT,
+ AgentTaskState.PAUSED,
+ AgentTaskState.STOPPED,
+ AgentTaskState.FINISHED,
+ ],
+ [AgentTaskAction.RESUME]: [
+ AgentTaskState.INIT,
+ AgentTaskState.RUNNING,
+ AgentTaskState.STOPPED,
+ AgentTaskState.FINISHED,
+ ],
+ [AgentTaskAction.STOP]: [
+ AgentTaskState.INIT,
+ AgentTaskState.STOPPED,
+ AgentTaskState.FINISHED,
+ ],
+};
+
+interface ButtonProps {
+ isLoading: boolean;
+ isDisabled: boolean;
+ content: string;
+ action: AgentTaskAction;
+ handleAction: (action: AgentTaskAction) => void;
+}
+
+function ActionButton({
+ isLoading = false,
+ isDisabled = false,
+ content,
+ action,
+ handleAction,
+ children,
+}: React.PropsWithChildren<ButtonProps>): React.ReactNode {
+ return (
+ <Tooltip content={content} closeDelay={100}>
+ <Button
+ isIconOnly
+ onClick={() => handleAction(action)}
+ isLoading={isLoading}
+ isDisabled={isDisabled}
+ >
+ {children}
+ </Button>
+ </Tooltip>
+ );
+}
+
+function AgentControlBar() {
+ const { curTaskState } = useSelector((state: RootState) => state.agent);
+ const [desiredState, setDesiredState] = React.useState(AgentTaskState.INIT);
+ const [isLoading, setIsLoading] = React.useState(false);
+
+ const handleAction = (action: AgentTaskAction) => {
+ if (IgnoreTaskStateMap[action].includes(curTaskState)) {
+ return;
+ }
+
+ let act = action;
+
+ if (act === AgentTaskAction.STOP) {
+ act = AgentTaskAction.STOP;
+ clearMsgs().then().catch();
+ store.dispatch(clearMessages());
+ } else {
+ setIsLoading(true);
+ }
+
+ setDesiredState(TaskStateActionMap[act]);
+ changeTaskState(act);
+ };
+
+ useEffect(() => {
+ if (curTaskState === desiredState) {
+ if (curTaskState === AgentTaskState.STOPPED) {
+ clearMsgs().then().catch();
+ store.dispatch(clearMessages());
+ }
+ setIsLoading(false);
+ } else if (curTaskState === AgentTaskState.RUNNING) {
+ setDesiredState(AgentTaskState.RUNNING);
+ }
+ }, [curTaskState]);
+
+ return (
+ <div className="ml-5 mt-3">
+ <ButtonGroup size="sm" variant="ghost">
+ <ActionButton
+ isLoading={false}
+ isDisabled={isLoading}
+ content="Restart a new agent task"
+ action={AgentTaskAction.STOP}
+ handleAction={handleAction}
+ >
+ <ArrowIcon />
+ </ActionButton>
+
+ {curTaskState === AgentTaskState.PAUSED ? (
+ <ActionButton
+ isLoading={isLoading}
+ isDisabled={
+ isLoading ||
+ IgnoreTaskStateMap[AgentTaskAction.RESUME].includes(curTaskState)
+ }
+ content="Resume the agent task"
+ action={AgentTaskAction.RESUME}
+ handleAction={handleAction}
+ >
+ <PlayIcon />
+ </ActionButton>
+ ) : (
+ <ActionButton
+ isLoading={isLoading}
+ isDisabled={
+ isLoading ||
+ IgnoreTaskStateMap[AgentTaskAction.PAUSE].includes(curTaskState)
+ }
+ content="Pause the agent task"
+ action={AgentTaskAction.PAUSE}
+ handleAction={handleAction}
+ >
+ <PauseIcon />
+ </ActionButton>
+ )}
+ </ButtonGroup>
+ </div>
+ );
+}
+
+export default AgentControlBar;
diff --git a/frontend/src/components/AgentStatusBar.tsx b/frontend/src/components/AgentStatusBar.tsx
index 73c52ee15d..e95a2eab4d 100644
--- a/frontend/src/components/AgentStatusBar.tsx
+++ b/frontend/src/components/AgentStatusBar.tsx
@@ -1,9 +1,38 @@
import React from "react";
import { useTranslation } from "react-i18next";
+import { useSelector } from "react-redux";
import { I18nKey } from "../i18n/declaration";
+import { RootState } from "../store";
+import AgentTaskState from "../types/AgentTaskState";
+
+const AgentStatusMap: { [k: string]: { message: string; indicator: string } } =
+ {
+ [AgentTaskState.INIT]: {
+ message: "Agent is initialized, waiting for task...",
+ indicator: "bg-blue-500",
+ },
+ [AgentTaskState.RUNNING]: {
+ message: "Agent is running task...",
+ indicator: "bg-green-500",
+ },
+ [AgentTaskState.PAUSED]: {
+ message: "Agent has paused.",
+ indicator: "bg-yellow-500",
+ },
+ [AgentTaskState.STOPPED]: {
+ message: "Agent has stopped.",
+ indicator: "bg-red-500",
+ },
+ [AgentTaskState.FINISHED]: {
+ message: "Agent has finished the task.",
+ indicator: "bg-green-500",
+ },
+ };
function AgentStatusBar() {
const { t } = useTranslation();
+ const { initialized } = useSelector((state: RootState) => state.task);
+ const { curTaskState } = useSelector((state: RootState) => state.agent);
// TODO: Extend the agent status, e.g.:
// - Agent is typing
@@ -13,10 +42,23 @@ function AgentStatusBar() {
// - Agent is not available
return (
<div className="flex items-center space-x-3 ml-6">
- <div className="w-3 h-3 bg-blue-500 rounded-full animate-pulse" />
- <span className="text-sm text-stone-400">
- {t(I18nKey.CHAT_INTERFACE$INITIALZING_AGENT_LOADING_MESSAGE)}
- </span>
+ {initialized ? (
+ <>
+ <div
+ className={`w-3 h-3 rounded-full animate-pulse ${AgentStatusMap[curTaskState].indicator}`}
+ />
+ <span className="text-sm text-stone-400">
+ {AgentStatusMap[curTaskState].message}
+ </span>
+ </>
+ ) : (
+ <>
+ <div className="w-3 h-3 bg-orange-800 rounded-full animate-pulse" />
+ <span className="text-sm text-stone-400">
+ {t(I18nKey.CHAT_INTERFACE$INITIALZING_AGENT_LOADING_MESSAGE)}
+ </span>
+ </>
+ )}
</div>
);
}
diff --git a/frontend/src/components/ChatInterface.tsx b/frontend/src/components/ChatInterface.tsx
index 971f280a21..005fa3f202 100644
--- a/frontend/src/components/ChatInterface.tsx
+++ b/frontend/src/components/ChatInterface.tsx
@@ -12,6 +12,7 @@ import { Message } from "../state/chatSlice";
import { RootState } from "../store";
import AgentStatusBar from "./AgentStatusBar";
import Input from "./Input";
+import AgentControlBar from "./AgentControlBar";
interface IChatBubbleProps {
msg: Message;
@@ -113,8 +114,6 @@ function MessageList(): JSX.Element {
}
function ChatInterface(): JSX.Element {
- const { initialized } = useSelector((state: RootState) => state.task);
-
return (
<div className="flex flex-col h-full p-0 bg-neutral-800">
<div className="flex items-center gap-2 border-b border-neutral-600 text-sm px-4 py-2">
@@ -122,7 +121,8 @@ function ChatInterface(): JSX.Element {
Chat
</div>
<MessageList />
- {initialized ? null : <AgentStatusBar />}
+ <AgentStatusBar />
+ <AgentControlBar />
<Input />
</div>
);
diff --git a/frontend/src/components/Input.tsx b/frontend/src/components/Input.tsx
index 2fc01ea8e5..33a53580ed 100644
--- a/frontend/src/components/Input.tsx
+++ b/frontend/src/components/Input.tsx
@@ -44,7 +44,7 @@ function Input() {
return (
<div className="w-full relative text-base">
<Textarea
- className="py-4 px-4"
+ className="pt-2 pb-4 px-4"
classNames={{
inputWrapper: "bg-neutral-700",
input: "pr-16 py-2",
diff --git a/frontend/src/services/actions.ts b/frontend/src/services/actions.ts
index 3e453299aa..cdbfb3d4d6 100644
--- a/frontend/src/services/actions.ts
+++ b/frontend/src/services/actions.ts
@@ -8,6 +8,7 @@ import { ActionMessage } from "../types/Message";
import { SocketMessage } from "../types/ResponseType";
import { handleObservationMessage } from "./observations";
import ActionType from "../types/ActionType";
+import { changeTaskState } from "../state/agentSlice";
const messageActions = {
[ActionType.INIT]: () => {
@@ -32,6 +33,9 @@ const messageActions = {
[ActionType.RUN]: (message: ActionMessage) => {
store.dispatch(appendInput(message.args.command));
},
+ [ActionType.CHANGE_TASK_STATE]: (message: ActionMessage) => {
+ store.dispatch(changeTaskState(message.args.task_state));
+ },
};
export function handleActionMessage(message: ActionMessage) {
diff --git a/frontend/src/services/agentStateService.ts b/frontend/src/services/agentStateService.ts
new file mode 100644
index 0000000000..e55e45cdff
--- /dev/null
+++ b/frontend/src/services/agentStateService.ts
@@ -0,0 +1,11 @@
+import ActionType from "../types/ActionType";
+import Socket from "./socket";
+import AgentTaskAction from "../types/AgentTaskAction";
+
+export function changeTaskState(message: AgentTaskAction): void {
+ const eventString = JSON.stringify({
+ action: ActionType.CHANGE_TASK_STATE,
+ args: { task_state_action: message },
+ });
+ Socket.send(eventString);
+}
diff --git a/frontend/src/state/agentSlice.tsx b/frontend/src/state/agentSlice.tsx
new file mode 100644
index 0000000000..308f34503b
--- /dev/null
+++ b/frontend/src/state/agentSlice.tsx
@@ -0,0 +1,18 @@
+import { createSlice } from "@reduxjs/toolkit";
+import AgentTaskState from "../types/AgentTaskState";
+
+export const agentSlice = createSlice({
+ name: "agent",
+ initialState: {
+ curTaskState: AgentTaskState.INIT,
+ },
+ reducers: {
+ changeTaskState: (state, action) => {
+ state.curTaskState = action.payload;
+ },
+ },
+});
+
+export const { changeTaskState } = agentSlice.actions;
+
+export default agentSlice.reducer;
diff --git a/frontend/src/state/chatSlice.ts b/frontend/src/state/chatSlice.ts
index 70fbda84fe..292d606b7f 100644
--- a/frontend/src/state/chatSlice.ts
+++ b/frontend/src/state/chatSlice.ts
@@ -62,6 +62,15 @@ export const chatSlice = createSlice({
state.typeThis = state.assistantMessagesTypingQueue.shift() as Message;
}
},
+ clearMessages: (state) => {
+ state.messages = initialMessages;
+ state.userMessages = initialMessages;
+ state.assistantMessages = initialMessages;
+ state.newChatSequence = initialMessages;
+ state.assistantMessagesTypingQueue = [];
+ state.typingActive = false;
+ state.typeThis = { content: "", sender: "assistant" };
+ },
},
});
@@ -71,6 +80,7 @@ export const {
toggleTypingActive,
appendToNewChatSequence,
takeOneTypeIt,
+ clearMessages,
} = chatSlice.actions;
export default chatSlice.reducer;
diff --git a/frontend/src/store.ts b/frontend/src/store.ts
index f74c8ec7b8..5fa4128088 100644
--- a/frontend/src/store.ts
+++ b/frontend/src/store.ts
@@ -6,6 +6,7 @@ import commandReducer from "./state/commandSlice";
import taskReducer from "./state/taskSlice";
import errorsReducer from "./state/errorsSlice";
import settingsReducer from "./state/settingsSlice";
+import agentReducer from "./state/agentSlice";
export const rootReducer = combineReducers({
browser: browserReducer,
@@ -15,6 +16,7 @@ export const rootReducer = combineReducers({
task: taskReducer,
errors: errorsReducer,
settings: settingsReducer,
+ agent: agentReducer,
});
const store = configureStore({
diff --git a/frontend/src/types/ActionType.tsx b/frontend/src/types/ActionType.tsx
index fa668549b5..773d591491 100644
--- a/frontend/src/types/ActionType.tsx
+++ b/frontend/src/types/ActionType.tsx
@@ -29,6 +29,8 @@ enum ActionType {
// If you're absolutely certain that you've completed your task and have tested your work,
// use the finish action to stop working.
FINISH = "finish",
+
+ CHANGE_TASK_STATE = "change_task_state",
}
export default ActionType;
diff --git a/frontend/src/types/AgentTaskAction.tsx b/frontend/src/types/AgentTaskAction.tsx
new file mode 100644
index 0000000000..3fd1b67768
--- /dev/null
+++ b/frontend/src/types/AgentTaskAction.tsx
@@ -0,0 +1,15 @@
+enum AgentTaskAction {
+ // Starts the task.
+ START = "start",
+
+ // Pauses the task.
+ PAUSE = "pause",
+
+ // Resumes the task.
+ RESUME = "resume",
+
+ // Stops the task.
+ STOP = "stop",
+}
+
+export default AgentTaskAction;
diff --git a/frontend/src/types/AgentTaskState.tsx b/frontend/src/types/AgentTaskState.tsx
new file mode 100644
index 0000000000..d7aa9c80bd
--- /dev/null
+++ b/frontend/src/types/AgentTaskState.tsx
@@ -0,0 +1,10 @@
+enum AgentTaskState {
+ INIT = "init",
+ RUNNING = "running",
+ PAUSED = "paused",
+ STOPPED = "stopped",
+ FINISHED = "finished",
+ ERROR = "error",
+}
+
+export default AgentTaskState;
diff --git a/frontend/src/utils/toast.tsx b/frontend/src/utils/toast.tsx
index b4250c39d0..08debd1574 100644
--- a/frontend/src/utils/toast.tsx
+++ b/frontend/src/utils/toast.tsx
@@ -56,4 +56,17 @@ export default {
},
});
},
+
+ info: (msg: string) => {
+ toast(msg, {
+ position: "top-center",
+ className: "bg-neutral-700",
+
+ style: {
+ background: "#333",
+ color: "#fff",
+ lineBreak: "anywhere",
+ },
+ });
+ },
};
diff --git a/opendevin/action/tasks.py b/opendevin/action/tasks.py
index 2bdcace4f8..96c6fb8f53 100644
--- a/opendevin/action/tasks.py
+++ b/opendevin/action/tasks.py
@@ -1,6 +1,6 @@
from dataclasses import dataclass, field
-from .base import ExecutableAction
+from .base import ExecutableAction, NotExecutableAction
from opendevin.schema import ActionType
from opendevin.observation import NullObservation
@@ -17,7 +17,8 @@ class AddTaskAction(ExecutableAction):
action: str = ActionType.ADD_TASK
async def run(self, controller: 'AgentController') -> NullObservation: # type: ignore
- controller.state.plan.add_subtask(self.parent, self.goal, self.subtasks)
+ if controller.state is not None:
+ controller.state.plan.add_subtask(self.parent, self.goal, self.subtasks)
return NullObservation('')
@property
@@ -32,9 +33,21 @@ class ModifyTaskAction(ExecutableAction):
action: str = ActionType.MODIFY_TASK
async def run(self, controller: 'AgentController') -> NullObservation: # type: ignore
- controller.state.plan.set_subtask_state(self.id, self.state)
+ if controller.state is not None:
+ controller.state.plan.set_subtask_state(self.id, self.state)
return NullObservation('')
@property
def message(self) -> str:
return f'Set task {self.id} to {self.state}'
+
+
+@dataclass
+class TaskStateChangedAction(NotExecutableAction):
+ """Fake action, just to notify the client that a task state has changed."""
+ task_state: str
+ action: str = ActionType.CHANGE_TASK_STATE
+
+ @property
+ def message(self) -> str:
+ return f'Task state changed to {self.task_state}'
diff --git a/opendevin/controller/agent_controller.py b/opendevin/controller/agent_controller.py
index 72bce23be1..f7603b893b 100644
--- a/opendevin/controller/agent_controller.py
+++ b/opendevin/controller/agent_controller.py
@@ -20,6 +20,8 @@ from opendevin.action import (
AgentFinishAction,
)
from opendevin.exceptions import AgentNoActionError
+from ..action.tasks import TaskStateChangedAction
+from ..schema import TaskState
MAX_ITERATIONS = config.get('MAX_ITERATIONS')
MAX_CHARS = config.get('MAX_CHARS')
@@ -32,6 +34,12 @@ class AgentController:
action_manager: ActionManager
callbacks: List[Callable]
+ state: State | None = None
+
+ _task_state: TaskState = TaskState.INIT
+ _finished: bool = False
+ _cur_step: int = 0
+
def __init__(
self,
agent: Agent,
@@ -49,44 +57,104 @@ class AgentController:
self.callbacks = callbacks
def update_state_for_step(self, i):
+ if self.state is None:
+ return
self.state.iteration = i
self.state.background_commands_obs = self.action_manager.get_background_obs()
def update_state_after_step(self):
+ if self.state is None:
+ return
self.state.updated_info = []
def add_history(self, action: Action, observation: Observation):
+ if self.state is None:
+ return
if not isinstance(action, Action):
raise TypeError(
- f'action must be an instance of Action, got {type(action).__name__} instead')
+ f'action must be an instance of Action, got {type(action).__name__} instead'
+ )
if not isinstance(observation, Observation):
raise TypeError(
- f'observation must be an instance of Observation, got {type(observation).__name__} instead')
+ f'observation must be an instance of Observation, got {type(observation).__name__} instead'
+ )
self.state.history.append((action, observation))
self.state.updated_info.append((action, observation))
- async def start_loop(self, task: str):
- finished = False
- plan = Plan(task)
- self.state = State(plan)
- for i in range(self.max_iterations):
+ async def _run(self):
+ if self.state is None:
+ return
+
+ if self._task_state != TaskState.RUNNING:
+ raise ValueError('Task is not in running state')
+
+ for i in range(self._cur_step, self.max_iterations):
try:
- finished = await self.step(i)
+ self._finished = await self.step(i)
except Exception as e:
logger.error('Error in loop', exc_info=True)
raise e
- if finished:
- break
- if not finished:
+
+ match self._task_state:
+ case TaskState.FINISHED, TaskState.STOPPED:
+ await self.reset_task() # type: ignore[unreachable]
+ break
+ case TaskState.PAUSED:
+ # save current state for resuming
+ self._cur_step = i + 1 # type: ignore[unreachable]
+ await self.notify_task_state_changed()
+ break
+
+ if not self._finished:
logger.info('Exited before finishing the task.')
self.agent.reset()
+ async def start(self, task: str):
+ """Starts the agent controller with a task.
+ If task already run before, it will continue from the last step.
+ """
+ self._task_state = TaskState.RUNNING
+ await self.notify_task_state_changed()
+
+ self.state = State(Plan(task))
+
+ await self._run()
+
+ async def resume(self):
+ if self.state is None:
+ raise ValueError('No task to resume')
+
+ self._task_state = TaskState.RUNNING
+ await self.notify_task_state_changed()
+
+ await self._run()
+
+ async def reset_task(self):
+ self.state = None
+ self._cur_step = 0
+ self._task_state = TaskState.INIT
+ await self.notify_task_state_changed()
+
+ async def set_task_state_to(self, state: TaskState):
+ self._task_state = state
+ if state == TaskState.STOPPED:
+ await self.reset_task()
+ logger.info(f'Task state set to {state}')
+
+ def get_task_state(self):
+ """Returns the current state of the agent task."""
+ return self._task_state
+
+ async def notify_task_state_changed(self):
+ await self._run_callbacks(TaskStateChangedAction(self._task_state))
+
async def step(self, i: int):
+ if self.state is None:
+ return
logger.info(f'STEP {i}', extra={'msg_type': 'STEP'})
logger.info(self.state.plan.main_goal, extra={'msg_type': 'PLAN'})
if self.state.num_of_chars > self.max_chars:
- raise MaxCharsExceedError(
- self.state.num_of_chars, self.max_chars)
+ raise MaxCharsExceedError(self.state.num_of_chars, self.max_chars)
log_obs = self.action_manager.get_background_obs()
for obs in log_obs:
@@ -142,7 +210,7 @@ class AgentController:
for callback in self.callbacks:
idx = self.callbacks.index(callback)
try:
- callback(event)
+ await callback(event)
except Exception as e:
logger.exception(f'Callback error: {e}, idx: {idx}')
await asyncio.sleep(
diff --git a/opendevin/main.py b/opendevin/main.py
index f49630165e..3fecc801e7 100644
--- a/opendevin/main.py
+++ b/opendevin/main.py
@@ -98,7 +98,7 @@ async def main():
agent=agent, max_iterations=args.max_iterations, max_chars=args.max_chars
)
- await controller.start_loop(task)
+ await controller.start(task)
if __name__ == '__main__':
diff --git a/opendevin/schema/__init__.py b/opendevin/schema/__init__.py
index 16c69a9c63..73010c3772 100644
--- a/opendevin/schema/__init__.py
+++ b/opendevin/schema/__init__.py
@@ -1,5 +1,6 @@
from .action import ActionType
from .config import ConfigType
from .observation import ObservationType
+from .task import TaskState, TaskStateAction
-__all__ = ['ActionType', 'ObservationType', 'ConfigType']
+__all__ = ['ActionType', 'ObservationType', 'ConfigType', 'TaskState', 'TaskStateAction']
diff --git a/opendevin/schema/action.py b/opendevin/schema/action.py
index ef8536081e..7f55e4c70f 100644
--- a/opendevin/schema/action.py
+++ b/opendevin/schema/action.py
@@ -52,3 +52,17 @@ class ActionType(str, Enum):
MODIFY_TASK = 'modify_task'
NULL = 'null'
+
+ PAUSE = 'pause'
+ """Pauses the task.
+ """
+
+ RESUME = 'resume'
+ """Resumes the task.
+ """
+
+ STOP = 'stop'
+ """Stops the task. Must send a start action to restart a new task.
+ """
+
+ CHANGE_TASK_STATE = 'change_task_state'
diff --git a/opendevin/schema/task.py b/opendevin/schema/task.py
new file mode 100644
index 0000000000..010af9b188
--- /dev/null
+++ b/opendevin/schema/task.py
@@ -0,0 +1,45 @@
+from enum import Enum
+
+
+class TaskState(str, Enum):
+ INIT = 'init'
+ """Initial state of the task.
+ """
+
+ RUNNING = 'running'
+ """The task is running.
+ """
+
+ PAUSED = 'paused'
+ """The task is paused.
+ """
+
+ STOPPED = 'stopped'
+ """The task is stopped.
+ """
+
+ FINISHED = 'finished'
+ """The task is finished.
+ """
+
+ ERROR = 'error'
+ """An error occurred during the task.
+ """
+
+
+class TaskStateAction(str, Enum):
+ START = 'start'
+ """Starts the task.
+ """
+
+ PAUSE = 'pause'
+ """Pauses the task.
+ """
+
+ RESUME = 'resume'
+ """Resumes the task.
+ """
+
+ STOP = 'stop'
+ """Stops the task.
+ """
diff --git a/opendevin/server/agent/agent.py b/opendevin/server/agent/agent.py
index fd87d6884f..98e23ae0f7 100644
--- a/opendevin/server/agent/agent.py
+++ b/opendevin/server/agent/agent.py
@@ -1,5 +1,5 @@
import asyncio
-from typing import Optional
+from typing import Optional, Dict, List
from opendevin import config
from opendevin.action import (
@@ -11,9 +11,37 @@ from opendevin.controller import AgentController
from opendevin.llm.llm import LLM
from opendevin.logger import opendevin_logger as logger
from opendevin.observation import NullObservation, Observation, UserMessageObservation
-from opendevin.schema import ActionType, ConfigType
+from opendevin.schema import ActionType, ConfigType, TaskState, TaskStateAction
from opendevin.server.session import session_manager
+# new task state to valid old task states
+VALID_TASK_STATE_MAP: Dict[TaskStateAction, List[TaskState]] = {
+ TaskStateAction.PAUSE: [TaskState.RUNNING],
+ TaskStateAction.RESUME: [TaskState.PAUSED],
+ TaskStateAction.STOP: [TaskState.RUNNING, TaskState.PAUSED],
+}
+IGNORED_TASK_STATE_MAP: Dict[TaskStateAction, List[TaskState]] = {
+ TaskStateAction.PAUSE: [
+ TaskState.INIT,
+ TaskState.PAUSED,
+ TaskState.STOPPED,
+ TaskState.FINISHED,
+ ],
+ TaskStateAction.RESUME: [
+ TaskState.INIT,
+ TaskState.RUNNING,
+ TaskState.STOPPED,
+ TaskState.FINISHED,
+ ],
+ TaskStateAction.STOP: [TaskState.INIT, TaskState.STOPPED, TaskState.FINISHED],
+}
+TASK_STATE_ACTION_MAP: Dict[TaskStateAction, TaskState] = {
+ TaskStateAction.START: TaskState.RUNNING,
+ TaskStateAction.PAUSE: TaskState.PAUSED,
+ TaskStateAction.RESUME: TaskState.RUNNING,
+ TaskStateAction.STOP: TaskState.STOPPED,
+}
+
class AgentUnit:
"""Represents a session with an agent.
@@ -63,9 +91,22 @@ class AgentUnit:
match action:
case ActionType.INIT:
+ # FIXME: the parameters need be compared, to confirm whether reinit is needed
+ if self.controller is not None:
+ # Agent already started, no need to create a new one
+ if data.get('args', {}).get('reconnect', 'false') != 'true':
+ await self.controller.reset_task()
+ await self.init_done()
+ return
await self.create_controller(data)
case ActionType.START:
await self.start_task(data)
+ case ActionType.CHANGE_TASK_STATE:
+ task_state_action = data.get('args', {}).get('task_state_action', None)
+ if task_state_action is None:
+ await self.send_error('No task state action specified.')
+ return
+ await self.set_task_state(TaskStateAction(task_state_action))
case ActionType.CHAT:
if self.controller is None:
await self.send_error('No agent started. Please wait a second...')
@@ -105,8 +146,7 @@ class AgentUnit:
api_key = config.get(ConfigType.LLM_API_KEY)
api_base = config.get(ConfigType.LLM_BASE_URL)
container_image = config.get(ConfigType.SANDBOX_CONTAINER_IMAGE)
- max_iterations = self.get_arg_or_default(
- args, ConfigType.MAX_ITERATIONS)
+ max_iterations = self.get_arg_or_default(args, ConfigType.MAX_ITERATIONS)
max_chars = self.get_arg_or_default(args, ConfigType.MAX_CHARS)
llm = LLM(model=model, api_key=api_key, base_url=api_base)
@@ -128,7 +168,16 @@ class AgentUnit:
await self.init_done()
async def init_done(self):
- await self.send({'action': ActionType.INIT, 'message': 'Control loop started.'})
+ if self.controller is None:
+ await self.send_error('No agent started.')
+ return
+ await self.send(
+ {
+ 'action': ActionType.INIT,
+ 'message': 'Control loop started.',
+ }
+ )
+ await self.controller.notify_task_state_changed()
async def start_task(self, start_event):
"""Starts a task for the agent.
@@ -145,13 +194,43 @@ class AgentUnit:
await self.send_error('No agent started. Please wait a second...')
return
try:
- self.agent_task = await asyncio.create_task(
- self.controller.start_loop(task), name='agent loop'
+ if self.agent_task:
+ self.agent_task.cancel()
+ self.agent_task = asyncio.create_task(
+ self.controller.start(task), name='agent start task loop'
)
except Exception as e:
await self.send_error(f'Error during task loop: {e}')
- def on_agent_event(self, event: Observation | Action):
+ async def set_task_state(self, new_state_action: TaskStateAction):
+ """Sets the state of the agent task."""
+ if self.controller is None:
+ await self.send_error('No agent started.')
+ return
+
+ cur_state = self.controller.get_task_state()
+ new_state = TASK_STATE_ACTION_MAP.get(new_state_action)
+ if new_state is None:
+ await self.send_error('Invalid task state action.')
+ return
+ if cur_state in VALID_TASK_STATE_MAP.get(new_state_action, []):
+ await self.controller.set_task_state_to(new_state)
+ elif cur_state in IGNORED_TASK_STATE_MAP.get(new_state_action, []):
+ # notify once again.
+ await self.controller.notify_task_state_changed()
+ return
+ else:
+ await self.send_error('Current task state not recognized.')
+ return
+
+ if new_state_action == TaskStateAction.RESUME:
+ if self.agent_task:
+ self.agent_task.cancel()
+ self.agent_task = asyncio.create_task(
+ self.controller.resume(), name='agent resume task loop'
+ )
+
+ async def on_agent_event(self, event: Observation | Action):
"""Callback function for agent events.
Args:
@@ -161,9 +240,7 @@ class AgentUnit:
return
if isinstance(event, NullObservation):
return
- event_dict = event.to_dict()
- asyncio.create_task(self.send(event_dict),
- name='send event in callback')
+ await self.send(event.to_dict())
def close(self):
if self.agent_task:
diff --git a/opendevin/server/session/msg_stack.py b/opendevin/server/session/msg_stack.py
index 334db524f4..22d2c6e45d 100644
--- a/opendevin/server/session/msg_stack.py
+++ b/opendevin/server/session/msg_stack.py
@@ -63,7 +63,7 @@ class MessageStack:
cnt = 0
for msg in self._messages[sid]:
# Ignore assistant init message for now.
- if 'action' in msg.payload and msg.payload['action'] == ActionType.INIT:
+ if 'action' in msg.payload and msg.payload['action'] in [ActionType.INIT, ActionType.CHANGE_TASK_STATE]:
continue
cnt += 1
return cnt