Skip to content

πŸ™Œ OpenHands: AI-Driven Development

feat: add agent status bar. (#941)

Leoeb7b3484fd1b
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index 1063da5405..583b9120c1 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -1,6 +1,5 @@
import React, { useEffect, useState } from "react";
import "./App.css";
-import { useSelector } from "react-redux";
import CogTooth from "./assets/cog-tooth";
import ChatInterface from "./components/ChatInterface";
import Errors from "./components/Errors";
@@ -11,7 +10,8 @@ import { fetchMsgTotal } from "./services/session";
import LoadMessageModal from "./components/LoadMessageModal";
import { ResConfigurations, ResFetchMsgTotal } from "./types/ResponseType";
import { fetchConfigurations, saveSettings } from "./services/settingsService";
-import { RootState } from "./store";
+import Socket from "./services/socket";
+import { getCachedConfig } from "./utils/storage";
interface Props {
setSettingOpen: (isOpen: boolean) => void;
@@ -36,25 +36,24 @@ let initOnce = false;
function App(): JSX.Element {
const [settingOpen, setSettingOpen] = useState(false);
const [loadMsgWarning, setLoadMsgWarning] = useState(false);
- const settings = useSelector((state: RootState) => state.settings);
- useEffect(() => {
- if (initOnce) return;
- initOnce = true;
- // only fetch configurations in the first time
+ const getConfigurations = () => {
fetchConfigurations()
.then((data: ResConfigurations) => {
+ const settings = getCachedConfig();
+
saveSettings(
Object.fromEntries(
Object.entries(data).map(([key, value]) => [key, String(value)]),
),
- Object.fromEntries(
- Object.entries(settings).map(([key, value]) => [key, value]),
- ),
+ settings,
true,
);
})
.catch();
+ };
+
+ const getMsgTotal = () => {
fetchMsgTotal()
.then((data: ResFetchMsgTotal) => {
if (data.msg_total > 0) {
@@ -62,6 +61,16 @@ function App(): JSX.Element {
}
})
.catch();
+ };
+
+ useEffect(() => {
+ if (initOnce) return;
+ initOnce = true;
+
+ Socket.registerCallback("open", [getConfigurations, getMsgTotal]);
+
+ getConfigurations();
+ getMsgTotal();
}, []);
const handleCloseModal = () => {
diff --git a/frontend/src/components/AgentStatusBar.tsx b/frontend/src/components/AgentStatusBar.tsx
new file mode 100644
index 0000000000..73c52ee15d
--- /dev/null
+++ b/frontend/src/components/AgentStatusBar.tsx
@@ -0,0 +1,24 @@
+import React from "react";
+import { useTranslation } from "react-i18next";
+import { I18nKey } from "../i18n/declaration";
+
+function AgentStatusBar() {
+ const { t } = useTranslation();
+
+ // TODO: Extend the agent status, e.g.:
+ // - Agent is typing
+ // - Agent is initializing
+ // - Agent is thinking
+ // - Agent is ready
+ // - 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>
+ </div>
+ );
+}
+
+export default AgentStatusBar;
diff --git a/frontend/src/components/ChatInterface.tsx b/frontend/src/components/ChatInterface.tsx
index 14179ca18e..0b43e72a4b 100644
--- a/frontend/src/components/ChatInterface.tsx
+++ b/frontend/src/components/ChatInterface.tsx
@@ -1,11 +1,9 @@
import { Card, CardBody } from "@nextui-org/react";
import React, { useEffect, useRef } from "react";
-import { useTranslation } from "react-i18next";
import { useSelector } from "react-redux";
import assistantAvatar from "../assets/assistant-avatar.png";
import userAvatar from "../assets/user-avatar.png";
import { useTypingEffect } from "../hooks/useTypingEffect";
-import { I18nKey } from "../i18n/declaration";
import {
addAssistantMessageToChat,
setTypingActive,
@@ -14,6 +12,7 @@ import {
import { Message } from "../state/chatSlice";
import { RootState } from "../store";
import Input from "./Input";
+import AgentStatusBar from "./AgentStatusBar";
interface IChatBubbleProps {
msg: Message;
@@ -120,28 +119,14 @@ function MessageList(): JSX.Element {
);
}
-function InitializingStatus(): JSX.Element {
- const { t } = useTranslation();
-
- return (
- <div className="flex items-center m-auto h-full">
- <img
- src={assistantAvatar}
- alt="assistant avatar"
- className="w-[40px] h-[40px] mx-2.5"
- />
- <div>{t(I18nKey.CHAT_INTERFACE$INITIALZING_AGENT_LOADING_MESSAGE)}</div>
- </div>
- );
-}
-
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="border-b border-neutral-600 text-sm px-4 py-2">Chat</div>
- {initialized ? <MessageList /> : <InitializingStatus />}
+ <MessageList />
+ {initialized ? null : <AgentStatusBar />}
<Input />
</div>
);
diff --git a/frontend/src/components/SettingModal.tsx b/frontend/src/components/SettingModal.tsx
index 60e7261366..94ce7ef01d 100644
--- a/frontend/src/components/SettingModal.tsx
+++ b/frontend/src/components/SettingModal.tsx
@@ -25,7 +25,7 @@ import {
import { RootState } from "../store";
import { I18nKey } from "../i18n/declaration";
import { AvailableLanguages } from "../i18n";
-import ArgConfigType from "../types/ConfigType";
+import { ArgConfigType } from "../types/ConfigType";
interface Props {
isOpen: boolean;
diff --git a/frontend/src/i18n/index.ts b/frontend/src/i18n/index.ts
index 84adcb412f..e34a020455 100644
--- a/frontend/src/i18n/index.ts
+++ b/frontend/src/i18n/index.ts
@@ -2,7 +2,7 @@ import i18n from "i18next";
import Backend from "i18next-http-backend";
import LanguageDetector from "i18next-browser-languagedetector";
import { initReactI18next } from "react-i18next";
-import ArgConfigType from "../types/ConfigType";
+import { ArgConfigType } from "../types/ConfigType";
export const AvailableLanguages = [
{ label: "English", value: "en" },
diff --git a/frontend/src/services/actions.ts b/frontend/src/services/actions.ts
index 4ae2541a65..3e453299aa 100644
--- a/frontend/src/services/actions.ts
+++ b/frontend/src/services/actions.ts
@@ -9,20 +9,9 @@ import { SocketMessage } from "../types/ResponseType";
import { handleObservationMessage } from "./observations";
import ActionType from "../types/ActionType";
-let isInitialized = false;
-
const messageActions = {
[ActionType.INIT]: () => {
store.dispatch(setInitialized(true));
- if (isInitialized) {
- return;
- }
- store.dispatch(
- appendAssistantMessage(
- "Hi! I'm OpenDevin, an AI Software Engineer. What would you like to build with me today?",
- ),
- );
- isInitialized = true;
},
[ActionType.BROWSE]: (message: ActionMessage) => {
const { url, screenshotSrc } = message.args;
diff --git a/frontend/src/services/settingsService.ts b/frontend/src/services/settingsService.ts
index 6bf4dc9661..1633033845 100644
--- a/frontend/src/services/settingsService.ts
+++ b/frontend/src/services/settingsService.ts
@@ -3,9 +3,9 @@ import { setInitialized } from "../state/taskSlice";
import store from "../store";
import ActionType from "../types/ActionType";
import Socket from "./socket";
-import { setByKey } from "../state/settingsSlice";
+import { setAllSettings, setByKey } from "../state/settingsSlice";
import { ResConfigurations } from "../types/ResponseType";
-import ArgConfigType from "../types/ConfigType";
+import { ArgConfigType } from "../types/ConfigType";
export async function fetchConfigurations(): Promise<ResConfigurations> {
const headers = new Headers({
@@ -43,6 +43,7 @@ export const INITIAL_AGENTS = ["MonologueAgent", "CodeActAgent"];
export type Agent = (typeof INITIAL_AGENTS)[number];
+// all available settings in the frontend
// TODO: add the values to i18n to support multi languages
const DISPLAY_MAP = new Map<string, string>([
[ArgConfigType.LLM_MODEL, "model"],
@@ -57,32 +58,45 @@ export function saveSettings(
oldSettings: { [key: string]: string },
isInit: boolean = false,
): void {
- let needToSend = false;
- const updatedSettings: { [key: string]: string } = {};
- const mergedSettings = { ...oldSettings, ...newSettings };
- Object.keys(newSettings).forEach((key) => {
- if (
- Object.hasOwnProperty.call(oldSettings, key) &&
- oldSettings[key] !== String(newSettings[key])
- ) {
- if (isInit && oldSettings[key] !== "") {
- mergedSettings[key] = oldSettings[key];
- return;
+ const { mergedSettings, updatedSettings, needToSend } = Object.keys(
+ newSettings,
+ ).reduce(
+ (acc, key) => {
+ const newValue = String(newSettings[key]);
+ const oldValue = oldSettings[key];
+
+ // key doesn't exist in frontend settings will be overwritten by backend settings
+ if (oldValue === undefined) {
+ acc.mergedSettings[key] = newValue;
+ acc.updatedSettings[key] = newValue;
+ return acc;
+ }
+ if (!DISPLAY_MAP.has(key)) {
+ acc.mergedSettings[key] = newValue;
+ return acc;
}
- needToSend = true;
- updatedSettings[key] = String(newSettings[key]);
- mergedSettings[key] = String(newSettings[key]);
- } else {
- mergedSettings[key] = oldSettings[key];
- }
- });
- if (needToSend || isInit) {
- const event = { action: ActionType.INIT, args: mergedSettings };
- const eventString = JSON.stringify(event);
- store.dispatch(setInitialized(false));
- Socket.send(eventString);
- }
+ if (oldValue === newValue || (isInit && oldValue !== "")) {
+ acc.mergedSettings[key] = oldValue;
+ return acc;
+ }
+
+ acc.mergedSettings[key] = newValue;
+ acc.updatedSettings[key] = newValue;
+ acc.needToSend = true;
+
+ return acc;
+ },
+ {
+ mergedSettings: { ...oldSettings },
+ updatedSettings: {},
+ needToSend: false,
+ } as {
+ mergedSettings: { [key: string]: string };
+ updatedSettings: { [key: string]: string };
+ needToSend: boolean;
+ },
+ );
for (const [key, value] of Object.entries(updatedSettings)) {
if (DISPLAY_MAP.has(key)) {
@@ -92,4 +106,16 @@ export function saveSettings(
);
}
}
+
+ if (isInit) {
+ store.dispatch(setAllSettings(JSON.stringify(newSettings)));
+ }
+
+ delete mergedSettings.ALL_SETTINGS;
+ if (needToSend || isInit) {
+ const event = { action: ActionType.INIT, args: mergedSettings };
+ const eventString = JSON.stringify(event);
+ store.dispatch(setInitialized(false));
+ Socket.send(eventString);
+ }
}
diff --git a/frontend/src/services/socket.ts b/frontend/src/services/socket.ts
index 5755309533..ed114f0b53 100644
--- a/frontend/src/services/socket.ts
+++ b/frontend/src/services/socket.ts
@@ -6,7 +6,23 @@ import { getToken } from "./auth";
class Socket {
private static _socket: WebSocket | null = null;
- public static initialize(): void {
+ // callbacks contain a list of callable functions
+ // event: function, like:
+ // open: [function1, function2]
+ // message: [function1, function2]
+ private static callbacks: {
+ [K in keyof WebSocketEventMap]: ((data: WebSocketEventMap[K]) => void)[];
+ } = {
+ open: [],
+ message: [],
+ error: [],
+ close: [],
+ };
+
+ // prevent it failed in the first run, all related listen events never be called
+ private static isFirstRun = true;
+
+ public static tryInitialize(): void {
getToken()
.then((token) => {
Socket._initialize(token);
@@ -17,43 +33,66 @@ class Socket {
setTimeout(() => {
store.dispatch(removeError(msg));
}, 2000);
+
+ if (this.isFirstRun) {
+ setTimeout(() => {
+ this.tryInitialize();
+ }, 3000);
+ }
});
}
private static _initialize(token: string): void {
- if (!Socket._socket || Socket._socket.readyState !== WebSocket.OPEN) {
- const WS_URL = `ws://${window.location.host}/ws?token=${token}`;
- Socket._socket = new WebSocket(WS_URL);
+ if (Socket.isConnected()) return;
- Socket._socket.onopen = () => {};
+ const WS_URL = `ws://${window.location.host}/ws?token=${token}`;
+ Socket._socket = new WebSocket(WS_URL);
- Socket._socket.onmessage = (e) => {
- handleAssistantMessage(e.data);
- };
+ Socket._socket.onopen = (e) => {
+ Socket.callbacks.open?.forEach((callback) => {
+ callback(e);
+ });
+ };
- Socket._socket.onerror = () => {
- const msg = "Failed connection to server";
- store.dispatch(appendError(msg));
- setTimeout(() => {
- store.dispatch(removeError(msg));
- }, 2000);
- };
+ Socket._socket.onmessage = (e) => {
+ handleAssistantMessage(e.data);
+ };
- Socket._socket.onclose = () => {
- // Reconnect after a delay
- setTimeout(() => {
- Socket.initialize();
- }, 3000); // Reconnect after 3 seconds
- };
- }
+ Socket._socket.onerror = () => {
+ const msg = "Failed connection to server";
+ store.dispatch(appendError(msg));
+ setTimeout(() => {
+ store.dispatch(removeError(msg));
+ }, 2000);
+ };
+
+ Socket._socket.onclose = () => {
+ // Reconnect after a delay
+ setTimeout(() => {
+ Socket.tryInitialize();
+ }, 3000); // Reconnect after 3 seconds
+ };
+
+ this.isFirstRun = false;
+ }
+
+ static isConnected(): boolean {
+ return (
+ Socket._socket !== null && Socket._socket.readyState === WebSocket.OPEN
+ );
}
static send(message: string): void {
- Socket.initialize();
- if (Socket._socket && Socket._socket.readyState === WebSocket.OPEN) {
- Socket._socket.send(message);
+ if (!Socket.isConnected()) Socket.tryInitialize();
+
+ if (Socket.isConnected()) {
+ Socket._socket?.send(message);
} else {
- store.dispatch(appendError("WebSocket connection is not ready."));
+ const msg = "WebSocket connection is not ready.";
+ store.dispatch(appendError(msg));
+ setTimeout(() => {
+ store.dispatch(removeError(msg));
+ }, 2000);
}
}
@@ -76,8 +115,18 @@ class Socket {
): void {
Socket._socket?.removeEventListener(event, listener);
}
+
+ static registerCallback<K extends keyof WebSocketEventMap>(
+ event: K,
+ callbacks: ((data: WebSocketEventMap[K]) => void)[],
+ ): void {
+ if (Socket.callbacks[event] === undefined) {
+ return;
+ }
+ Socket.callbacks[event].push(...callbacks);
+ }
}
-Socket.initialize();
+Socket.tryInitialize();
export default Socket;
diff --git a/frontend/src/state/chatSlice.ts b/frontend/src/state/chatSlice.ts
index 9582811174..94aafe09b2 100644
--- a/frontend/src/state/chatSlice.ts
+++ b/frontend/src/state/chatSlice.ts
@@ -5,7 +5,13 @@ export type Message = {
sender: "user" | "assistant";
};
-const initialMessages: Message[] = [];
+const initialMessages: Message[] = [
+ {
+ content:
+ "Hi! I'm OpenDevin, an AI Software Engineer. What would you like to build with me today?",
+ sender: "assistant",
+ },
+];
export const chatSlice = createSlice({
name: "chat",
initialState: {
@@ -13,7 +19,7 @@ export const chatSlice = createSlice({
typingActive: false,
userMessages: initialMessages,
assistantMessages: initialMessages,
- assistantMessagesTypingQueue: initialMessages,
+ assistantMessagesTypingQueue: [] as Message[],
newChatSequence: initialMessages,
typeThis: { content: "", sender: "assistant" } as Message,
},
diff --git a/frontend/src/state/settingsSlice.ts b/frontend/src/state/settingsSlice.ts
index 482aa93248..3b07bc2746 100644
--- a/frontend/src/state/settingsSlice.ts
+++ b/frontend/src/state/settingsSlice.ts
@@ -1,10 +1,11 @@
import { createSlice } from "@reduxjs/toolkit";
import i18next from "i18next";
-import ArgConfigType from "../types/ConfigType";
+import { ArgConfigType } from "../types/ConfigType";
export const settingsSlice = createSlice({
name: "settings",
initialState: {
+ ALL_SETTINGS: localStorage.getItem("ALL_SETTINGS") || "",
[ArgConfigType.LLM_MODEL]:
localStorage.getItem(ArgConfigType.LLM_MODEL) || "",
[ArgConfigType.AGENT]: localStorage.getItem(ArgConfigType.AGENT) || "",
@@ -17,15 +18,20 @@ export const settingsSlice = createSlice({
setByKey: (state, action) => {
const { key, value } = action.payload;
state[key] = value;
+ console.log("setByKey", key, value);
localStorage.setItem(key, value);
// language is a special case for now.
if (key === ArgConfigType.LANGUAGE) {
i18next.changeLanguage(value);
}
},
+ setAllSettings: (state, action) => {
+ state.ALL_SETTINGS = action.payload;
+ localStorage.setItem("ALL_SETTINGS", action.payload);
+ },
},
});
-export const { setByKey } = settingsSlice.actions;
+export const { setByKey, setAllSettings } = settingsSlice.actions;
export default settingsSlice.reducer;
diff --git a/frontend/src/types/ConfigType.tsx b/frontend/src/types/ConfigType.tsx
index 448b62ae02..725bcae9ac 100644
--- a/frontend/src/types/ConfigType.tsx
+++ b/frontend/src/types/ConfigType.tsx
@@ -15,4 +15,20 @@ enum ArgConfigType {
LANGUAGE = "LANGUAGE",
}
-export default ArgConfigType;
+const SupportedList: string[] = [
+ // ArgConfigType.LLM_API_KEY,
+ // ArgConfigType.LLM_BASE_URL,
+ ArgConfigType.WORKSPACE_DIR,
+ ArgConfigType.LLM_MODEL,
+ // ArgConfigType.SANDBOX_CONTAINER_IMAGE,
+ // ArgConfigType.RUN_AS_DEVIN,
+ // ArgConfigType.LLM_EMBEDDING_MODEL,
+ // ArgConfigType.LLM_NUM_RETRIES,
+ // ArgConfigType.LLM_COOLDOWN_TIME,
+ // ArgConfigType.DIRECTORY_REWRITE,
+ // ArgConfigType.MAX_ITERATIONS,
+ ArgConfigType.AGENT,
+ ArgConfigType.LANGUAGE,
+];
+
+export { ArgConfigType, SupportedList };
diff --git a/frontend/src/utils/storage.tsx b/frontend/src/utils/storage.tsx
new file mode 100644
index 0000000000..b4b2b92e64
--- /dev/null
+++ b/frontend/src/utils/storage.tsx
@@ -0,0 +1,11 @@
+const getCachedConfig = (): { [key: string]: string } => {
+ const config = localStorage.getItem("ALL_SETTINGS");
+ if (config === null || config === undefined) return {};
+ try {
+ return JSON.parse(config);
+ } catch (e) {
+ return {};
+ }
+};
+
+export { getCachedConfig };