🙌 OpenHands: AI-Driven Development
Runtime Status Fixes (#9050)
Tim O'Farrell47209e794ad5
diff --git a/docs/usage/how-to/gui-mode.mdx b/docs/usage/how-to/gui-mode.mdxindex 06c6457eef..0a96b34ebf 100644--- a/docs/usage/how-to/gui-mode.mdx+++ b/docs/usage/how-to/gui-mode.mdx@@ -132,6 +132,20 @@ toggle `Advanced` options to access additional settings.For an overview of the key features available inside a conversation, please refer to the [Key Features](/usage/key-features)section of the documentation.+### Status Indicator++The status indicator located in the bottom left of the screen will cycle through a number of states as a new conversation+is loaded. Typically these include:++* `Disconnected` : The frontend is not connected to any conversation+* `Connecting` : The frontend is connecting a websocket to a conversation.+* `Building Runtime...` : The server is building a runtime. This is typically in development mode only while building a docker image.+* `Starting Runtime...` : The server is starting a new runtime instance - probably a new docker container or remote runtime.+* `Initializing Agent...` : The server is starting the agent loop. (This step does not appear at present with Nested runtimes)+* `Setting up workspace...` : Usually this means a `git clone ...` operation.+* `Setting up git hooks` : Setting up the git pre commit hooks for the workspace.+* `Agent is awaiting user input...` : Ready to go!+## Tips for Effective Use- Be specific in your requests to get the most accurate and helpful responses, as described in the [prompting best practices](../prompting/prompting-best-practices).diff --git a/frontend/__tests__/components/features/conversation-panel/conversation-card.test.tsx b/frontend/__tests__/components/features/conversation-panel/conversation-card.test.tsxindex 32bde1cb50..d54fe3e604 100644--- a/frontend/__tests__/components/features/conversation-panel/conversation-card.test.tsx+++ b/frontend/__tests__/components/features/conversation-panel/conversation-card.test.tsx@@ -478,7 +478,7 @@ describe("ConversationCard", () => {title="Conversation 1"selectedRepository={null}lastUpdatedAt="2021-10-01T12:00:00Z"- status="RUNNING"+ conversationStatus="RUNNING"/>,);diff --git a/frontend/__tests__/components/features/conversation-panel/conversation-panel.test.tsx b/frontend/__tests__/components/features/conversation-panel/conversation-panel.test.tsxindex 45cd05eaa9..8219d66d50 100644--- a/frontend/__tests__/components/features/conversation-panel/conversation-panel.test.tsx+++ b/frontend/__tests__/components/features/conversation-panel/conversation-panel.test.tsx@@ -48,6 +48,7 @@ describe("ConversationPanel", () => {last_updated_at: "2021-10-01T12:00:00Z",created_at: "2021-10-01T12:00:00Z",status: "STOPPED" as const,+ runtime_status: null,url: null,session_api_key: null,},@@ -60,6 +61,7 @@ describe("ConversationPanel", () => {last_updated_at: "2021-10-02T12:00:00Z",created_at: "2021-10-02T12:00:00Z",status: "STOPPED" as const,+ runtime_status: null,url: null,session_api_key: null,},@@ -72,6 +74,7 @@ describe("ConversationPanel", () => {last_updated_at: "2021-10-03T12:00:00Z",created_at: "2021-10-03T12:00:00Z",status: "STOPPED" as const,+ runtime_status: null,url: null,session_api_key: null,},@@ -158,6 +161,7 @@ describe("ConversationPanel", () => {last_updated_at: "2021-10-01T12:00:00Z",created_at: "2021-10-01T12:00:00Z",status: "STOPPED" as const,+ runtime_status: null,url: null,session_api_key: null,},@@ -170,6 +174,7 @@ describe("ConversationPanel", () => {last_updated_at: "2021-10-02T12:00:00Z",created_at: "2021-10-02T12:00:00Z",status: "STOPPED" as const,+ runtime_status: null,url: null,session_api_key: null,},@@ -182,6 +187,7 @@ describe("ConversationPanel", () => {last_updated_at: "2021-10-03T12:00:00Z",created_at: "2021-10-03T12:00:00Z",status: "STOPPED" as const,+ runtime_status: null,url: null,session_api_key: null,},diff --git a/frontend/__tests__/context/ws-client-provider.test.tsx b/frontend/__tests__/context/ws-client-provider.test.tsxindex 00de1947ba..55a27732fc 100644--- a/frontend/__tests__/context/ws-client-provider.test.tsx+++ b/frontend/__tests__/context/ws-client-provider.test.tsx@@ -65,6 +65,7 @@ describe("WsClientProvider", () => {last_updated_at: "2021-10-01T12:00:00Z",created_at: "2021-10-01T12:00:00Z",status: "RUNNING" as const,+ runtime_status: "STATUS$READY",url: null,session_api_key: null,}}},diff --git a/frontend/scripts/check-unlocalized-strings.cjs b/frontend/scripts/check-unlocalized-strings.cjsindex 86425d61fb..9115d5913d 100755--- a/frontend/scripts/check-unlocalized-strings.cjs+++ b/frontend/scripts/check-unlocalized-strings.cjs@@ -117,6 +117,9 @@ const EXCLUDED_TECHNICAL_STRINGS = ["edit-secret-form", // Test ID for secret form"search-api-key-input", // Input name for search API key"noopener,noreferrer", // Options for window.open+ "STATUS$READY",+ "STATUS$STOPPED",+ "STATUS$ERROR",];function isExcludedTechnicalString(str) {diff --git a/frontend/src/api/open-hands.types.ts b/frontend/src/api/open-hands.types.tsindex 25a3dbb00a..b11ac91d48 100644--- a/frontend/src/api/open-hands.types.ts+++ b/frontend/src/api/open-hands.types.ts@@ -1,4 +1,5 @@-import { ProjectStatus } from "#/components/features/conversation-panel/conversation-state-indicator";+import { ConversationStatus } from "#/types/conversation-status";+import { RuntimeStatus } from "#/types/runtime-status";export interface ErrorResponse {error: string;@@ -80,7 +81,8 @@ export interface Conversation {git_provider: string | null;last_updated_at: string;created_at: string;- status: ProjectStatus;+ status: ConversationStatus;+ runtime_status: RuntimeStatus | null;trigger?: ConversationTrigger;url: string | null;session_api_key: string | null;diff --git a/frontend/src/components/agent-status-map.constant.ts b/frontend/src/components/agent-status-map.constant.tsdeleted file mode 100644index 346186bb1a..0000000000--- a/frontend/src/components/agent-status-map.constant.ts+++ /dev/null@@ -1,68 +0,0 @@-import { I18nKey } from "#/i18n/declaration";-import { AgentState } from "#/types/agent-state";--export enum IndicatorColor {- BLUE = "bg-blue-500",- GREEN = "bg-green-500",- ORANGE = "bg-orange-500",- YELLOW = "bg-yellow-500",- RED = "bg-red-500",- DARK_ORANGE = "bg-orange-800",-}--export const AGENT_STATUS_MAP: {- [k: string]: { message: string; indicator: IndicatorColor };-} = {- [AgentState.INIT]: {- message: I18nKey.CHAT_INTERFACE$AGENT_INIT_MESSAGE,- indicator: IndicatorColor.BLUE,- },- [AgentState.RUNNING]: {- message: I18nKey.CHAT_INTERFACE$AGENT_RUNNING_MESSAGE,- indicator: IndicatorColor.GREEN,- },- [AgentState.AWAITING_USER_INPUT]: {- message: I18nKey.CHAT_INTERFACE$AGENT_AWAITING_USER_INPUT_MESSAGE,- indicator: IndicatorColor.BLUE,- },- [AgentState.PAUSED]: {- message: I18nKey.CHAT_INTERFACE$AGENT_PAUSED_MESSAGE,- indicator: IndicatorColor.YELLOW,- },- [AgentState.LOADING]: {- message: I18nKey.CHAT_INTERFACE$INITIALIZING_AGENT_LOADING_MESSAGE,- indicator: IndicatorColor.DARK_ORANGE,- },- [AgentState.STOPPED]: {- message: I18nKey.CHAT_INTERFACE$AGENT_STOPPED_MESSAGE,- indicator: IndicatorColor.RED,- },- [AgentState.FINISHED]: {- message: I18nKey.CHAT_INTERFACE$AGENT_FINISHED_MESSAGE,- indicator: IndicatorColor.GREEN,- },- [AgentState.REJECTED]: {- message: I18nKey.CHAT_INTERFACE$AGENT_REJECTED_MESSAGE,- indicator: IndicatorColor.YELLOW,- },- [AgentState.ERROR]: {- message: I18nKey.CHAT_INTERFACE$AGENT_ERROR_MESSAGE,- indicator: IndicatorColor.RED,- },- [AgentState.AWAITING_USER_CONFIRMATION]: {- message: I18nKey.CHAT_INTERFACE$AGENT_AWAITING_USER_CONFIRMATION_MESSAGE,- indicator: IndicatorColor.ORANGE,- },- [AgentState.USER_CONFIRMED]: {- message: I18nKey.CHAT_INTERFACE$AGENT_ACTION_USER_CONFIRMED_MESSAGE,- indicator: IndicatorColor.GREEN,- },- [AgentState.USER_REJECTED]: {- message: I18nKey.CHAT_INTERFACE$AGENT_ACTION_USER_REJECTED_MESSAGE,- indicator: IndicatorColor.RED,- },- [AgentState.RATE_LIMITED]: {- message: I18nKey.CHAT_INTERFACE$AGENT_RATE_LIMITED_MESSAGE,- indicator: IndicatorColor.YELLOW,- },-};diff --git a/frontend/src/components/features/controls/agent-status-bar.tsx b/frontend/src/components/features/controls/agent-status-bar.tsxindex 21eab23379..c96b57c6f0 100644--- a/frontend/src/components/features/controls/agent-status-bar.tsx+++ b/frontend/src/components/features/controls/agent-status-bar.tsx@@ -1,18 +1,14 @@import React from "react";import { useTranslation } from "react-i18next";import { useSelector } from "react-redux";-import { I18nKey } from "#/i18n/declaration";import { showErrorToast } from "#/utils/error-handler";import { RootState } from "#/store";import { AgentState } from "#/types/agent-state";-import {- AGENT_STATUS_MAP,- IndicatorColor,-} from "../../agent-status-map.constant";import { useWsClient } from "#/context/ws-client-provider";import { useNotification } from "#/hooks/useNotification";import { browserTab } from "#/utils/browser-tab";import { useActiveConversation } from "#/hooks/query/use-active-conversation";+import { getIndicatorColor, getStatusCode } from "#/utils/status";const notificationStates = [AgentState.AWAITING_USER_INPUT,@@ -24,38 +20,60 @@ export function AgentStatusBar() {const { t, i18n } = useTranslation();const { curAgentState } = useSelector((state: RootState) => state.agent);const { curStatusMessage } = useSelector((state: RootState) => state.status);- const { status } = useWsClient();- const { notify } = useNotification();+ const { webSocketStatus } = useWsClient();const { data: conversation } = useActiveConversation();+ const indicatorColor = getIndicatorColor(+ webSocketStatus,+ conversation?.status || null,+ conversation?.runtime_status || null,+ curAgentState,+ );+ const statusCode = getStatusCode(+ curStatusMessage,+ webSocketStatus,+ conversation?.status || null,+ conversation?.runtime_status || null,+ curAgentState,+ );+ const { notify } = useNotification();- const [statusMessage, setStatusMessage] = React.useState<string>("");-- const updateStatusMessage = () => {+ // Show error toast if required+ React.useEffect(() => {+ if (curStatusMessage?.type !== "error") {+ return;+ }let message = curStatusMessage.message || "";if (curStatusMessage?.id) {const id = curStatusMessage.id.trim();+ if (id === "STATUS$READY") {+ message = "awaiting_user_input";+ }if (i18n.exists(id)) {message = t(curStatusMessage.id.trim()) || message;}}- if (curStatusMessage?.type === "error") {- showErrorToast({- message,- source: "agent-status",- metadata: { ...curStatusMessage },- });- return;- }- if (message.trim()) {- setStatusMessage(message);- } else {- setStatusMessage(AGENT_STATUS_MAP[curAgentState].message);- }- };+ showErrorToast({+ message,+ source: "agent-status",+ metadata: { ...curStatusMessage },+ });+ }, [curStatusMessage.id]);+ // Handle notifyReact.useEffect(() => {- updateStatusMessage();- }, [curStatusMessage.id]);+ if (notificationStates.includes(curAgentState)) {+ const message = t(statusCode);+ notify(message, {+ body: t(`Agent state changed to ${curAgentState}`),+ playSound: true,+ });++ // Update browser tab if window exists and is not focused+ if (typeof document !== "undefined" && !document.hasFocus()) {+ browserTab.startNotification(message);+ }+ }+ }, [curAgentState, statusCode]);// Handle window focus/blurReact.useEffect(() => {@@ -72,45 +90,13 @@ export function AgentStatusBar() {};}, []);- const [indicatorColor, setIndicatorColor] = React.useState<string>(- AGENT_STATUS_MAP[curAgentState].indicator,- );-- React.useEffect(() => {- if (conversation?.status === "CONNECTING") {- setStatusMessage(t(I18nKey.STATUS$CONNECTING_TO_RUNTIME));- setIndicatorColor(IndicatorColor.YELLOW);- } else if (conversation?.status === "STARTING") {- setStatusMessage(t(I18nKey.STATUS$STARTING_RUNTIME));- setIndicatorColor(IndicatorColor.RED);- } else if (status === "DISCONNECTED") {- setStatusMessage(t(I18nKey.STATUS$WEBSOCKET_CLOSED));- setIndicatorColor(IndicatorColor.RED);- } else {- setStatusMessage(AGENT_STATUS_MAP[curAgentState].message);- setIndicatorColor(AGENT_STATUS_MAP[curAgentState].indicator);- if (notificationStates.includes(curAgentState)) {- const message = t(AGENT_STATUS_MAP[curAgentState].message);- notify(t(AGENT_STATUS_MAP[curAgentState].message), {- body: t(`Agent state changed to ${curAgentState}`),- playSound: true,- });-- // Update browser tab if window exists and is not focused- if (typeof document !== "undefined" && !document.hasFocus()) {- browserTab.startNotification(message);- }- }- }- }, [curAgentState, status, notify, t, conversation?.status]);-return (<div className="flex flex-col items-center"><div className="flex items-center bg-base-secondary px-2 py-1 text-gray-400 rounded-[100px] text-sm gap-[6px]"><divclassName={`w-2 h-2 rounded-full animate-pulse ${indicatorColor}`}/>- <span className="text-sm text-stone-400">{t(statusMessage)}</span>+ <span className="text-sm text-stone-400">{t(statusCode)}</span></div></div>);diff --git a/frontend/src/components/features/controls/controls.tsx b/frontend/src/components/features/controls/controls.tsxindex 3afe4cdf30..03c3c70fd7 100644--- a/frontend/src/components/features/controls/controls.tsx+++ b/frontend/src/components/features/controls/controls.tsx@@ -30,7 +30,7 @@ export function Controls({ setSecurityOpen, showSecurityLock }: ControlsProps) {title={conversation?.title ?? ""}lastUpdatedAt={conversation?.created_at ?? ""}selectedRepository={conversation?.selected_repository ?? null}- status={conversation?.status}+ conversationStatus={conversation?.status}conversationId={conversation?.conversation_id}/></div>diff --git a/frontend/src/components/features/conversation-panel/conversation-card.tsx b/frontend/src/components/features/conversation-panel/conversation-card.tsxindex 4938e4a931..e9c275d16d 100644--- a/frontend/src/components/features/conversation-panel/conversation-card.tsx+++ b/frontend/src/components/features/conversation-panel/conversation-card.tsx@@ -4,10 +4,7 @@ import posthog from "posthog-js";import { useTranslation } from "react-i18next";import { formatTimeDelta } from "#/utils/format-time-delta";import { ConversationRepoLink } from "./conversation-repo-link";-import {- ProjectStatus,- ConversationStateIndicator,-} from "./conversation-state-indicator";+import { ConversationStateIndicator } from "./conversation-state-indicator";import { EllipsisButton } from "./ellipsis-button";import { ConversationCardContextMenu } from "./conversation-card-context-menu";import { SystemMessageModal } from "./system-message-modal";@@ -20,6 +17,7 @@ import { transformVSCodeUrl } from "#/utils/vscode-url-helper";import OpenHands from "#/api/open-hands";import { useWsClient } from "#/context/ws-client-provider";import { isSystemMessage } from "#/types/core/guards";+import { ConversationStatus } from "#/types/conversation-status";interface ConversationCardProps {onClick?: () => void;@@ -31,7 +29,7 @@ interface ConversationCardProps {selectedRepository: string | null;lastUpdatedAt: string; // ISO 8601createdAt?: string; // ISO 8601- status?: ProjectStatus;+ conversationStatus?: ConversationStatus;variant?: "compact" | "default";conversationId?: string; // Optional conversation ID for VS Code URL}@@ -50,7 +48,7 @@ export function ConversationCard({// eslint-disable-next-line @typescript-eslint/no-unused-varslastUpdatedAt,createdAt,- status = "STOPPED",+ conversationStatus = "STOPPED",variant = "default",conversationId,}: ConversationCardProps) {@@ -206,7 +204,9 @@ export function ConversationCard({</div><div className="flex items-center">- <ConversationStateIndicator status={status} />+ <ConversationStateIndicator+ conversationStatus={conversationStatus}+ />{hasContextMenu && (<div className="pl-2"><EllipsisButtondiff --git a/frontend/src/components/features/conversation-panel/conversation-panel.tsx b/frontend/src/components/features/conversation-panel/conversation-panel.tsxindex 17a9cb6a6b..decf9e6cd3 100644--- a/frontend/src/components/features/conversation-panel/conversation-panel.tsx+++ b/frontend/src/components/features/conversation-panel/conversation-panel.tsx@@ -91,7 +91,7 @@ export function ConversationPanel({ onClose }: ConversationPanelProps) {selectedRepository={project.selected_repository}lastUpdatedAt={project.last_updated_at}createdAt={project.created_at}- status={project.status}+ conversationStatus={project.status}conversationId={project.conversation_id}/>)}diff --git a/frontend/src/components/features/conversation-panel/conversation-state-indicator.tsx b/frontend/src/components/features/conversation-panel/conversation-state-indicator.tsxindex 028c099ce2..2fdec49473 100644--- a/frontend/src/components/features/conversation-panel/conversation-state-indicator.tsx+++ b/frontend/src/components/features/conversation-panel/conversation-state-indicator.tsx@@ -1,38 +1,27 @@-import ColdIcon from "./state-indicators/cold.svg?react";+import { ConversationStatus } from "#/types/conversation-status";import RunningIcon from "./state-indicators/running.svg?react";+import StartingIcon from "./state-indicators/starting.svg?react";+import StoppedIcon from "./state-indicators/stopped.svg?react";type SVGIcon = React.FunctionComponent<React.SVGProps<SVGSVGElement>>;-export type ProjectStatus =- | "RUNNING"- | "STOPPED"- | "STARTING"- | "CONNECTING"- | "CONNECTED"- | "DISCONNECTED";-type ProjectStatusWithIcon = Exclude<- ProjectStatus,- "CONNECTING" | "CONNECTED" | "DISCONNECTED"->;--const INDICATORS: Record<ProjectStatusWithIcon, SVGIcon> = {- STOPPED: ColdIcon,+const CONVERSATION_STATUS_INDICATORS: Record<ConversationStatus, SVGIcon> = {+ STOPPED: StoppedIcon,RUNNING: RunningIcon,- STARTING: ColdIcon,+ STARTING: StartingIcon,};interface ConversationStateIndicatorProps {- status: ProjectStatus;+ conversationStatus: ConversationStatus;}export function ConversationStateIndicator({- status,+ conversationStatus,}: ConversationStateIndicatorProps) {- // @ts-expect-error - Type 'ProjectStatus' is not assignable to type 'ProjectStatusWithIcon'.- const StateIcon = INDICATORS[status];+ const StateIcon = CONVERSATION_STATUS_INDICATORS[conversationStatus];return (- <div data-testid={`${status}-indicator`}>+ <div data-testid={`${conversationStatus}-indicator`}><StateIcon /></div>);diff --git a/frontend/src/components/features/conversation-panel/state-indicators/finished.svg b/frontend/src/components/features/conversation-panel/state-indicators/finished.svgdeleted file mode 100644index 311d524d17..0000000000--- a/frontend/src/components/features/conversation-panel/state-indicators/finished.svg+++ /dev/null@@ -1,4 +0,0 @@-<svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">-<path d="M9 16.8599C13.4183 16.8599 17 13.2781 17 8.85986C17 4.44159 13.4183 0.859863 9 0.859863C4.58172 0.859863 1 4.44159 1 8.85986C1 13.2781 4.58172 16.8599 9 16.8599Z" fill="#779FD4"/>-<path d="M4.61035 8.43014L7.86035 12.0301L13.3904 6.64014" stroke="#231F20" stroke-width="2" stroke-miterlimit="10" stroke-linecap="round"/>-</svg>diff --git a/frontend/src/components/features/conversation-panel/state-indicators/cooling.svg b/frontend/src/components/features/conversation-panel/state-indicators/starting.svgsimilarity index 100%rename from frontend/src/components/features/conversation-panel/state-indicators/cooling.svgrename to frontend/src/components/features/conversation-panel/state-indicators/starting.svgdiff --git a/frontend/src/components/features/conversation-panel/state-indicators/cold.svg b/frontend/src/components/features/conversation-panel/state-indicators/stopped.svgsimilarity index 100%rename from frontend/src/components/features/conversation-panel/state-indicators/cold.svgrename to frontend/src/components/features/conversation-panel/state-indicators/stopped.svgdiff --git a/frontend/src/components/features/conversation-panel/state-indicators/waiting.svg b/frontend/src/components/features/conversation-panel/state-indicators/waiting.svgdeleted file mode 100644index a73aa2b276..0000000000--- a/frontend/src/components/features/conversation-panel/state-indicators/waiting.svg+++ /dev/null@@ -1,4 +0,0 @@-<svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">-<path d="M6.76039 6.99002C8.478 6.99002 9.87039 5.59763 9.87039 3.88002C9.87039 2.16241 8.478 0.77002 6.76039 0.77002C5.04279 0.77002 3.65039 2.16241 3.65039 3.88002C3.65039 5.59763 5.04279 6.99002 6.76039 6.99002Z" fill="#FFE165"/>-<path d="M1.0802 17.0799C1.0802 17.0799 0.610196 11.5499 3.0102 9.67992C4.7902 8.29992 7.3302 9.44992 9.7802 7.95992C11.5802 6.86992 13.6102 4.10992 14.5202 2.49992C14.9302 1.77992 15.9102 1.62992 16.6102 2.05992C17.3802 2.51992 17.6102 3.53992 17.1102 4.28992C16.2302 5.58992 14.1802 8.85992 13.1202 10.3699C10.7602 13.7599 11.4302 17.0799 11.4302 17.0799H1.0702H1.0802Z" fill="#FFE165"/>-</svg>diff --git a/frontend/src/components/features/conversation-panel/state-indicators/warm.svg b/frontend/src/components/features/conversation-panel/state-indicators/warm.svgdeleted file mode 100644index e7432e7531..0000000000--- a/frontend/src/components/features/conversation-panel/state-indicators/warm.svg+++ /dev/null@@ -1,4 +0,0 @@-<svg width="18" height="18" viewBox="0 0 18 18" fill="none" xmlns="http://www.w3.org/2000/svg">-<path d="M9.87012 2.08984C9.87012 1.53756 9.4224 1.08984 8.87012 1.08984C8.31783 1.08984 7.87012 1.53756 7.87012 2.08984V8.08984C7.87012 8.64213 8.31783 9.08984 8.87012 9.08984C9.4224 9.08984 9.87012 8.64213 9.87012 8.08984V2.08984Z" fill="#60BB46"/>-<path d="M10.8702 2.50988V2.64988C10.8702 3.01988 11.0702 3.36988 11.4102 3.51988C13.6802 4.51988 15.2202 6.88988 14.9702 9.56988C14.7002 12.5599 12.1002 14.9599 9.09021 15.0099C5.74021 15.0599 2.99021 12.3499 2.99021 9.00988C2.99021 6.65988 4.35021 4.62988 6.31021 3.64988C6.64021 3.48988 6.86021 3.16988 6.86021 2.80988V2.63988C6.86021 1.94988 6.14021 1.51988 5.51021 1.81988C2.42021 3.30988 0.430214 6.71988 1.12021 10.5199C1.69021 13.6799 4.22021 16.2499 7.37021 16.8699C12.4902 17.8699 16.9802 13.9699 16.9802 9.02988C16.9802 5.71988 14.9702 2.88988 12.1002 1.66988C11.5102 1.41988 10.8502 1.88988 10.8502 2.52988L10.8702 2.50988Z" fill="#60BB46"/>-</svg>diff --git a/frontend/src/context/ws-client-provider.tsx b/frontend/src/context/ws-client-provider.tsxindex 5716a1439a..ffb5e54a64 100644--- a/frontend/src/context/ws-client-provider.tsx+++ b/frontend/src/context/ws-client-provider.tsx@@ -28,7 +28,8 @@ import {} from "#/types/core/guards";import { useOptimisticUserMessage } from "#/hooks/use-optimistic-user-message";import { useWSErrorMessage } from "#/hooks/use-ws-error-message";-import { ProjectStatus } from "#/components/features/conversation-panel/conversation-state-indicator";++export type WebSocketStatus = "CONNECTING" | "CONNECTED" | "DISCONNECTED";const hasValidMessageProperty = (obj: unknown): obj is { message: string } =>typeof obj === "object" &&@@ -69,7 +70,7 @@ const isMessageAction = (isUserMessage(event) || isAssistantMessage(event);interface UseWsClient {- status: ProjectStatus;+ webSocketStatus: WebSocketStatus;isLoadingMessages: boolean;events: Record<string, unknown>[];parsedEvents: (OpenHandsAction | OpenHandsObservation)[];@@ -77,7 +78,7 @@ interface UseWsClient {}const WsClientContext = React.createContext<UseWsClient>({- status: "DISCONNECTED",+ webSocketStatus: "DISCONNECTED",isLoadingMessages: true,events: [],parsedEvents: [],@@ -134,7 +135,8 @@ export function WsClientProvider({const { setErrorMessage, removeErrorMessage } = useWSErrorMessage();const queryClient = useQueryClient();const sioRef = React.useRef<Socket | null>(null);- const [status, setStatus] = React.useState<ProjectStatus>("CONNECTING");+ const [webSocketStatus, setWebSocketStatus] =+ React.useState<WebSocketStatus>("DISCONNECTED");const [events, setEvents] = React.useState<Record<string, unknown>[]>([]);const [parsedEvents, setParsedEvents] = React.useState<(OpenHandsAction | OpenHandsObservation)[]@@ -155,7 +157,7 @@ export function WsClientProvider({}function handleConnect() {- setStatus("CONNECTED");+ setWebSocketStatus("CONNECTED");removeErrorMessage();}@@ -254,7 +256,7 @@ export function WsClientProvider({}function handleDisconnect(data: unknown) {- setStatus("DISCONNECTED");+ setWebSocketStatus("DISCONNECTED");const sio = sioRef.current;if (!sio) {return;@@ -268,7 +270,7 @@ export function WsClientProvider({function handleError(data: unknown) {// set status- setStatus("DISCONNECTED");+ setWebSocketStatus("DISCONNECTED");updateStatusWhenErrorMessagePresent(data);setErrorMessage(@@ -287,17 +289,14 @@ export function WsClientProvider({// reset events when conversationId changessetEvents([]);setParsedEvents([]);- setStatus("CONNECTING");+ setWebSocketStatus("CONNECTING");}, [conversationId]);React.useEffect(() => {if (!conversationId) {throw new Error("No conversation ID provided");}- if (- !conversation ||- ["STOPPED", "STARTING"].includes(conversation.status)- ) {+ if (conversation?.status !== "RUNNING" && !conversation?.runtime_status) {return () => undefined; // conversation not yet loaded}@@ -307,6 +306,9 @@ export function WsClientProvider({sio.disconnect();}+ // Set initial status...+ setWebSocketStatus("CONNECTING");+const lastEvent = lastEventRef.current;const query = {latest_event_id: lastEvent?.id ?? -1,@@ -341,7 +343,12 @@ export function WsClientProvider({sio.off("connect_failed", handleError);sio.off("disconnect", handleDisconnect);};- }, [conversationId, conversation?.url, conversation?.status]);+ }, [+ conversationId,+ conversation?.url,+ conversation?.status,+ conversation?.runtime_status,+ ]);React.useEffect(() => () => {@@ -356,13 +363,18 @@ export function WsClientProvider({const value = React.useMemo<UseWsClient>(() => ({- status,+ webSocketStatus,isLoadingMessages: messageRateHandler.isUnderThreshold,events,parsedEvents,send,}),- [status, messageRateHandler.isUnderThreshold, events, parsedEvents],+ [+ webSocketStatus,+ messageRateHandler.isUnderThreshold,+ events,+ parsedEvents,+ ],);return <WsClientContext value={value}>{children}</WsClientContext>;diff --git a/frontend/src/hooks/query/use-conversation-config.ts b/frontend/src/hooks/query/use-conversation-config.tsindex 86d4f17b17..3a6443c094 100644--- a/frontend/src/hooks/query/use-conversation-config.ts+++ b/frontend/src/hooks/query/use-conversation-config.ts@@ -1,12 +1,12 @@import { useQuery } from "@tanstack/react-query";import React from "react";-import { useWsClient } from "#/context/ws-client-provider";import { useConversationId } from "#/hooks/use-conversation-id";import OpenHands from "#/api/open-hands";+import { useRuntimeIsReady } from "../use-runtime-is-ready";export const useConversationConfig = () => {- const { status } = useWsClient();const { conversationId } = useConversationId();+ const runtimeIsReady = useRuntimeIsReady();const query = useQuery({queryKey: ["conversation_config", conversationId],@@ -14,7 +14,7 @@ export const useConversationConfig = () => {if (!conversationId) throw new Error("No conversation ID");return OpenHands.getRuntimeId(conversationId);},- enabled: status !== "DISCONNECTED" && !!conversationId,+ enabled: runtimeIsReady && !!conversationId,staleTime: 1000 * 60 * 5, // 5 minutesgcTime: 1000 * 60 * 15, // 15 minutes});diff --git a/frontend/src/i18n/declaration.ts b/frontend/src/i18n/declaration.tsindex 9770feef91..8694683f1d 100644--- a/frontend/src/i18n/declaration.ts+++ b/frontend/src/i18n/declaration.ts@@ -248,6 +248,9 @@ export enum I18nKey {INVARIANT$TRACE_EXPORTED_MESSAGE = "INVARIANT$TRACE_EXPORTED_MESSAGE",INVARIANT$POLICY_UPDATED_MESSAGE = "INVARIANT$POLICY_UPDATED_MESSAGE",INVARIANT$SETTINGS_UPDATED_MESSAGE = "INVARIANT$SETTINGS_UPDATED_MESSAGE",+ CHAT_INTERFACE$DISCONNECTED = "CHAT_INTERFACE$DISCONNECTED",+ CHAT_INTERFACE$CONNECTING = "CHAT_INTERFACE$CONNECTING",+ CHAT_INTERFACE$STOPPED = "CHAT_INTERFACE$STOPPED",CHAT_INTERFACE$INITIALIZING_AGENT_LOADING_MESSAGE = "CHAT_INTERFACE$INITIALIZING_AGENT_LOADING_MESSAGE",CHAT_INTERFACE$AGENT_INIT_MESSAGE = "CHAT_INTERFACE$AGENT_INIT_MESSAGE",CHAT_INTERFACE$AGENT_RUNNING_MESSAGE = "CHAT_INTERFACE$AGENT_RUNNING_MESSAGE",@@ -368,9 +371,6 @@ export enum I18nKey {SIDEBAR$CONVERSATIONS = "SIDEBAR$CONVERSATIONS",STATUS$CONNECTING_TO_RUNTIME = "STATUS$CONNECTING_TO_RUNTIME",STATUS$STARTING_RUNTIME = "STATUS$STARTING_RUNTIME",- STATUS$STARTING_CONTAINER = "STATUS$STARTING_CONTAINER",- STATUS$PREPARING_CONTAINER = "STATUS$PREPARING_CONTAINER",- STATUS$CONTAINER_STARTED = "STATUS$CONTAINER_STARTED",STATUS$SETTING_UP_WORKSPACE = "STATUS$SETTING_UP_WORKSPACE",STATUS$SETTING_UP_GIT_HOOKS = "STATUS$SETTING_UP_GIT_HOOKS",ACCOUNT_SETTINGS_MODAL$DISCONNECT = "ACCOUNT_SETTINGS_MODAL$DISCONNECT",@@ -461,7 +461,7 @@ export enum I18nKey {CONVERSATION$NO_CONVERSATIONS = "CONVERSATION$NO_CONVERSATIONS",LANDING$SELECT_GIT_REPO = "LANDING$SELECT_GIT_REPO",BUTTON$SEND = "BUTTON$SEND",- STATUS$WAITING_FOR_CLIENT = "STATUS$WAITING_FOR_CLIENT",+ STATUS$BUILDING_RUNTIME = "STATUS$BUILDING_RUNTIME",SUGGESTIONS$WHAT_TO_BUILD = "SUGGESTIONS$WHAT_TO_BUILD",SETTINGS_FORM$ENABLE_DEFAULT_CONDENSER_SWITCH_LABEL = "SETTINGS_FORM$ENABLE_DEFAULT_CONDENSER_SWITCH_LABEL",BUTTON$MARK_HELPFUL = "BUTTON$MARK_HELPFUL",diff --git a/frontend/src/i18n/translation.json b/frontend/src/i18n/translation.jsonindex 455cbd5932..a240e83237 100644--- a/frontend/src/i18n/translation.json+++ b/frontend/src/i18n/translation.json@@ -3967,21 +3967,69 @@"ja": "設定を更新しました","uk": "Налаштування оновлено"},+ "CHAT_INTERFACE$DISCONNECTED": {+ "en": "Disconnected",+ "ja": "切断されました",+ "zh-CN": "已断开连接",+ "zh-TW": "已斷開連接",+ "ko-KR": "연결 끊김",+ "no": "Frakoblet",+ "it": "Disconnesso",+ "pt": "Desconectado",+ "es": "Desconectado",+ "ar": "تم قطع الاتصال",+ "fr": "Déconnecté",+ "tr": "Bağlantı kesildi",+ "de": "Getrennt",+ "uk": "Від'єднано"+ },+ "CHAT_INTERFACE$CONNECTING": {+ "en": "Connecting",+ "ja": "接続中",+ "zh-CN": "正在连接",+ "zh-TW": "正在連接",+ "ko-KR": "연결 중",+ "no": "Kobler til",+ "it": "Connessione in corso",+ "pt": "Conectando",+ "es": "Conectando",+ "ar": "جاري الاتصال",+ "fr": "Connexion en cours",+ "tr": "Bağlanıyor",+ "de": "Verbindung wird hergestellt",+ "uk": "З'єднання"+ },+ "CHAT_INTERFACE$STOPPED": {+ "en": "Stopped",+ "ja": "停止しました",+ "zh-CN": "已停止",+ "zh-TW": "已停止",+ "ko-KR": "중지됨",+ "no": "Stoppet",+ "it": "Fermato",+ "pt": "Parado",+ "es": "Detenido",+ "ar": "توقف",+ "fr": "Arrêté",+ "tr": "Durduruldu",+ "de": "Angehalten",+ "uk": "Зупинено"+ },"CHAT_INTERFACE$INITIALIZING_AGENT_LOADING_MESSAGE": {- "en": "Starting up!",- "de": "Wird gestartet!",- "zh-CN": "正在启动!",- "zh-TW": "正在啟動!",- "ko-KR": "시작 중입니다!",- "no": "Starter opp!",- "it": "Avvio in corso!",- "pt": "Iniciando!",- "es": "¡Iniciando!",- "ar": "جارٍ البدء!",- "fr": "Démarrage en cours !",- "tr": "Başlatılıyor!",- "ja": "起動中!",- "uk": "Запуск!"+ "en": "Initializing Agent...",+ "de": "Agent wird initialisiert...",+ "zh-CN": "正在初始化智能体...",+ "zh-TW": "正在初始化智能體...",+ "ko-KR": "에이전트 초기화 중...",+ "no": "Initialiserer agent...",+ "it": "Inizializzazione dell'agente...",+ "pt": "Inicializando o Agente...",+ "es": "Inicializando Agente...",+ "ar": "جارٍ تهيئة الوكيل...",+ "fr": "Initialisation de l'agent...",+ "tr": "Ajan başlatılıyor...",+ "ja": "エージェントを初期化中...",+ "uk": "Ініціалізація агента..."},"CHAT_INTERFACE$AGENT_INIT_MESSAGE": {"en": "Agent is initialized, waiting for task...",@@ -5887,54 +5935,6 @@"ja": "ランタイムを開始中","uk": "Запуск середовища виконання..."},- "STATUS$STARTING_CONTAINER": {- "en": "Preparing container, this might take a few minutes...",- "zh-CN": "正在准备容器,这可能需要几分钟...",- "zh-TW": "正在準備容器,這可能需要幾分鐘...",- "de": "Container wird vorbereitet, dies kann einige Minuten dauern...",- "ko-KR": "컨테이너를 준비 중입니다. 몇 분 정도 걸릴 수 있습니다...",- "no": "Forbereder container, dette kan ta noen minutter...",- "it": "Preparazione del container in corso, potrebbe richiedere alcuni minuti...",- "pt": "Preparando o container, isso pode levar alguns minutos...",- "es": "Preparando el contenedor, esto puede tardar unos minutos...",- "ar": "جارٍ إعداد الحاوية، قد يستغرق هذا بضع دقائق...",- "fr": "Préparation du conteneur, cela peut prendre quelques minutes...",- "tr": "Konteyner hazırlanıyor, bu işlem birkaç dakika sürebilir...",- "ja": "コンテナを開始中",- "uk": "Підготовка контейнера, це може тривати кілька хвилин..."- },- "STATUS$PREPARING_CONTAINER": {- "en": "Preparing to start container...",- "zh-CN": "正在准备启动容器...",- "zh-TW": "正在準備啟動容器...",- "de": "Vorbereitung zum Starten des Containers...",- "ko-KR": "컨테이너 시작 준비 중...",- "no": "Forbereder å starte container...",- "it": "Preparazione all'avvio del container...",- "pt": "Preparando para iniciar o container...",- "es": "Preparando para iniciar el contenedor...",- "ar": "جارٍ التحضير لبدء الحاوية...",- "fr": "Préparation du démarrage du conteneur...",- "tr": "Konteyner başlatılmaya hazırlanıyor...",- "ja": "コンテナを準備中",- "uk": "Preparing to start container..."- },- "STATUS$CONTAINER_STARTED": {- "en": "Container started.",- "zh-CN": "容器已启动。",- "zh-TW": "容器已啟動。",- "de": "Container gestartet.",- "ko-KR": "컨테이너가 시작되었습니다.",- "no": "Container startet.",- "it": "Container avviato.",- "pt": "Container iniciado.",- "es": "Contenedor iniciado.",- "ar": "تم بدء الحاوية.",- "fr": "Conteneur démarré.",- "tr": "Konteyner başlatıldı.",- "ja": "コンテナが開始されました",- "uk": "Контейнер запущено."- },"STATUS$SETTING_UP_WORKSPACE": {"en": "Setting up workspace...","zh-CN": "正在设置工作区...",@@ -7375,21 +7375,21 @@"tr": "Gönder","uk": "Надіслати"},- "STATUS$WAITING_FOR_CLIENT": {- "en": "Waiting for client to become ready...",- "zh-CN": "等待客户端准备就绪...",- "zh-TW": "等待客戶端準備就緒...",- "de": "Warten auf Bereitschaft des Clients...",- "ko-KR": "클라이언트가 준비될 때까지 기다리는 중...",- "no": "Venter på at klienten skal bli klar...",- "it": "In attesa che il client sia pronto...",- "pt": "Aguardando o cliente ficar pronto...",- "es": "Esperando a que el cliente esté listo...",- "ar": "في انتظار جاهزية العميل...",- "fr": "En attente que le client soit prêt...",- "tr": "İstemcinin hazır olması bekleniyor...",- "ja": "クライアントの準備を待機中",- "uk": "Чекаємо на готовність клієнта..."+ "STATUS$BUILDING_RUNTIME": {+ "en": "Building Runtime...",+ "ja": "ランタイムを構築中...",+ "zh-CN": "正在构建运行时...",+ "zh-TW": "正在構建運行時...",+ "ko-KR": "런타임 구축 중...",+ "no": "Bygger kjøretidsmiljø...",+ "it": "Costruzione del runtime in corso...",+ "pt": "Construindo ambiente de execução...",+ "es": "Construyendo entorno de ejecución...",+ "ar": "جاري بناء بيئة التشغيل...",+ "fr": "Construction de l'environnement d'exécution...",+ "tr": "Çalışma ortamı oluşturuluyor...",+ "de": "Laufzeitumgebung wird erstellt...",+ "uk": "Створення середовища виконання..."},"SUGGESTIONS$WHAT_TO_BUILD": {"en": "What do you want to build?",diff --git a/frontend/src/mocks/handlers.ts b/frontend/src/mocks/handlers.tsindex f9ff8bfe4a..d7929464dc 100644--- a/frontend/src/mocks/handlers.ts+++ b/frontend/src/mocks/handlers.ts@@ -57,6 +57,7 @@ const conversations: Conversation[] = [last_updated_at: new Date().toISOString(),created_at: new Date().toISOString(),status: "RUNNING",+ runtime_status: "STATUS$READY",url: null,session_api_key: null,},@@ -72,6 +73,7 @@ const conversations: Conversation[] = [).toISOString(),created_at: new Date(Date.now() - 2 * 24 * 60 * 60 * 1000).toISOString(),status: "STOPPED",+ runtime_status: null,url: null,session_api_key: null,},@@ -87,6 +89,7 @@ const conversations: Conversation[] = [).toISOString(),created_at: new Date(Date.now() - 5 * 24 * 60 * 60 * 1000).toISOString(),status: "STOPPED",+ runtime_status: null,url: null,session_api_key: null,},@@ -282,6 +285,7 @@ export const handlers = [last_updated_at: new Date().toISOString(),created_at: new Date().toISOString(),status: "RUNNING",+ runtime_status: "STATUS$READY",url: null,session_api_key: null,};diff --git a/frontend/src/types/conversation-status.ts b/frontend/src/types/conversation-status.tsnew file mode 100644index 0000000000..3b4fa99064--- /dev/null+++ b/frontend/src/types/conversation-status.ts@@ -0,0 +1 @@+export type ConversationStatus = "STARTING" | "RUNNING" | "STOPPED";diff --git a/frontend/src/types/runtime-status.ts b/frontend/src/types/runtime-status.tsnew file mode 100644index 0000000000..982a2d8d2a--- /dev/null+++ b/frontend/src/types/runtime-status.ts@@ -0,0 +1,8 @@+export type RuntimeStatus =+ | "STATUS$STOPPED"+ | "STATUS$BUILDING_RUNTIME"+ | "STATUS$STARTING_RUNTIME"+ | "STATUS$RUNTIME_STARTED"+ | "STATUS$SETTING_UP_WORKSPACE"+ | "STATUS$SETTING_UP_GIT_HOOKS"+ | "STATUS$READY";diff --git a/frontend/src/utils/status.ts b/frontend/src/utils/status.tsnew file mode 100644index 0000000000..93c941077c--- /dev/null+++ b/frontend/src/utils/status.ts@@ -0,0 +1,121 @@+import { WebSocketStatus } from "#/context/ws-client-provider";+import { I18nKey } from "#/i18n/declaration";+import { AgentState } from "#/types/agent-state";+import { ConversationStatus } from "#/types/conversation-status";+import { StatusMessage } from "#/types/message";+import { RuntimeStatus } from "#/types/runtime-status";++export enum IndicatorColor {+ BLUE = "bg-blue-500",+ GREEN = "bg-green-500",+ ORANGE = "bg-orange-500",+ YELLOW = "bg-yellow-500",+ RED = "bg-red-500",+ DARK_ORANGE = "bg-orange-800",+}++export const AGENT_STATUS_MAP: {+ [k: string]: string;+} = {+ [AgentState.INIT]: I18nKey.CHAT_INTERFACE$AGENT_INIT_MESSAGE,+ [AgentState.RUNNING]: I18nKey.CHAT_INTERFACE$AGENT_RUNNING_MESSAGE,+ [AgentState.AWAITING_USER_INPUT]:+ I18nKey.CHAT_INTERFACE$AGENT_AWAITING_USER_INPUT_MESSAGE,+ [AgentState.PAUSED]: I18nKey.CHAT_INTERFACE$AGENT_PAUSED_MESSAGE,+ [AgentState.LOADING]:+ I18nKey.CHAT_INTERFACE$INITIALIZING_AGENT_LOADING_MESSAGE,+ [AgentState.STOPPED]: I18nKey.CHAT_INTERFACE$AGENT_STOPPED_MESSAGE,+ [AgentState.FINISHED]: I18nKey.CHAT_INTERFACE$AGENT_FINISHED_MESSAGE,+ [AgentState.REJECTED]: I18nKey.CHAT_INTERFACE$AGENT_REJECTED_MESSAGE,+ [AgentState.ERROR]: I18nKey.CHAT_INTERFACE$AGENT_ERROR_MESSAGE,+ [AgentState.AWAITING_USER_CONFIRMATION]:+ I18nKey.CHAT_INTERFACE$AGENT_AWAITING_USER_CONFIRMATION_MESSAGE,+ [AgentState.USER_CONFIRMED]:+ I18nKey.CHAT_INTERFACE$AGENT_ACTION_USER_CONFIRMED_MESSAGE,+ [AgentState.USER_REJECTED]:+ I18nKey.CHAT_INTERFACE$AGENT_ACTION_USER_REJECTED_MESSAGE,+ [AgentState.RATE_LIMITED]: I18nKey.CHAT_INTERFACE$AGENT_RATE_LIMITED_MESSAGE,+};++export function getIndicatorColor(+ webSocketStatus: WebSocketStatus,+ conversationStatus: ConversationStatus | null,+ runtimeStatus: RuntimeStatus | null,+ agentState: AgentState | null,+) {+ if (+ webSocketStatus === "DISCONNECTED" ||+ conversationStatus === "STOPPED" ||+ runtimeStatus === "STATUS$STOPPED" ||+ agentState === AgentState.STOPPED+ ) {+ return IndicatorColor.RED;+ }+ // Display a yellow working icon while the runtime is starting+ if (+ conversationStatus === "STARTING" ||+ !["STATUS$READY", null].includes(runtimeStatus) ||+ (agentState != null &&+ [+ AgentState.LOADING,+ AgentState.PAUSED,+ AgentState.REJECTED,+ AgentState.RATE_LIMITED,+ ].includes(agentState))+ ) {+ return IndicatorColor.YELLOW;+ }++ if (agentState === AgentState.AWAITING_USER_CONFIRMATION) {+ return IndicatorColor.ORANGE;+ }++ if (agentState === AgentState.AWAITING_USER_INPUT) {+ return IndicatorColor.BLUE;+ }++ // All other agent states are green+ return IndicatorColor.GREEN;+}++export function getStatusCode(+ statusMessage: StatusMessage,+ webSocketStatus: WebSocketStatus,+ conversationStatus: ConversationStatus | null,+ runtimeStatus: RuntimeStatus | null,+ agentState: AgentState | null,+) {+ if (conversationStatus === "STOPPED" || runtimeStatus === "STATUS$STOPPED") {+ return I18nKey.CHAT_INTERFACE$STOPPED;+ }+ if (runtimeStatus === "STATUS$BUILDING_RUNTIME") {+ return I18nKey.STATUS$BUILDING_RUNTIME;+ }+ if (runtimeStatus === "STATUS$STARTING_RUNTIME") {+ return I18nKey.STATUS$STARTING_RUNTIME;+ }+ if (webSocketStatus === "DISCONNECTED") {+ return I18nKey.CHAT_INTERFACE$DISCONNECTED;+ }+ if (webSocketStatus === "CONNECTING") {+ return I18nKey.CHAT_INTERFACE$CONNECTING;+ }++ if (+ agentState === AgentState.LOADING &&+ statusMessage?.id &&+ statusMessage.id !== "STATUS$READY"+ ) {+ return statusMessage.id;+ }++ if (agentState) {+ return AGENT_STATUS_MAP[agentState];+ }++ if (runtimeStatus && runtimeStatus !== "STATUS$READY" && !agentState) {+ return runtimeStatus;+ }++ return "STATUS$ERROR"; // illegal state+}diff --git a/openhands/runtime/base.py b/openhands/runtime/base.pyindex fbd26b5522..658c76c652 100644--- a/openhands/runtime/base.py+++ b/openhands/runtime/base.py@@ -59,6 +59,7 @@ from openhands.runtime.plugins import (PluginRequirement,VSCodeRequirement,)+from openhands.runtime.runtime_status import RuntimeStatusfrom openhands.runtime.utils.edit import FileEditRuntimeMixinfrom openhands.runtime.utils.git_handler import CommandResult, GitHandlerfrom openhands.utils.async_utils import (@@ -67,16 +68,6 @@ from openhands.utils.async_utils import (call_sync_from_async,)-STATUS_MESSAGES = {- 'STATUS$STARTING_RUNTIME': 'Starting runtime...',- 'STATUS$STARTING_CONTAINER': 'Starting container...',- 'STATUS$PREPARING_CONTAINER': 'Preparing container...',- 'STATUS$CONTAINER_STARTED': 'Container started.',- 'STATUS$WAITING_FOR_CLIENT': 'Waiting for client...',- 'STATUS$SETTING_UP_WORKSPACE': 'Setting up workspace...',- 'STATUS$SETTING_UP_GIT_HOOKS': 'Setting up git hooks...',-}-def _default_env_vars(sandbox_config: SandboxConfig) -> dict[str, str]:ret = {}@@ -124,6 +115,7 @@ class Runtime(FileEditRuntimeMixin):initial_env_vars: dict[str, str]attach_to_existing: boolstatus_callback: Callable[[str, str, str], None] | None+ runtime_status: RuntimeStatus | None_runtime_initialized: bool = Falsedef __init__(@@ -187,6 +179,7 @@ class Runtime(FileEditRuntimeMixin):self.user_id = user_idself.git_provider_tokens = git_provider_tokens+ self.runtime_status = None@propertydef runtime_initialized(self) -> bool:@@ -215,11 +208,12 @@ class Runtime(FileEditRuntimeMixin):message = f'[runtime {self.sid}] {message}'getattr(logger, level)(message, stacklevel=2)- def send_status_message(self, message_id: str):+ def set_runtime_status(self, runtime_status: RuntimeStatus):"""Sends a status message if the callback function was provided."""+ self.runtime_status = runtime_statusif self.status_callback:- msg = STATUS_MESSAGES.get(message_id, '')- self.status_callback('info', message_id, msg)+ msg_id: str = runtime_status.value # type: ignore+ self.status_callback('info', msg_id, runtime_status.message)def send_error_message(self, message_id: str, message: str):if self.status_callback:diff --git a/openhands/runtime/impl/cli/cli_runtime.py b/openhands/runtime/impl/cli/cli_runtime.pyindex 8947aad3d2..0b1283ee79 100644--- a/openhands/runtime/impl/cli/cli_runtime.py+++ b/openhands/runtime/impl/cli/cli_runtime.py@@ -49,6 +49,7 @@ from openhands.events.observation import (from openhands.integrations.provider import PROVIDER_TOKEN_TYPEfrom openhands.runtime.base import Runtimefrom openhands.runtime.plugins import PluginRequirement+from openhands.runtime.runtime_status import RuntimeStatusclass CLIRuntime(Runtime):@@ -126,7 +127,7 @@ class CLIRuntime(Runtime):async def connect(self) -> None:"""Initialize the runtime connection."""- self.send_status_message('STATUS$STARTING_RUNTIME')+ self.set_runtime_status(RuntimeStatus.STARTING_RUNTIME)# Ensure workspace directory existsos.makedirs(self._workspace_path, exist_ok=True)@@ -138,7 +139,7 @@ class CLIRuntime(Runtime):await asyncio.to_thread(self.setup_initial_env)self._runtime_initialized = True- self.send_status_message('STATUS$CONTAINER_STARTED')+ self.set_runtime_status(RuntimeStatus.RUNTIME_STARTED)logger.info(f'CLIRuntime initialized with workspace at {self._workspace_path}')def add_env_vars(self, env_vars: dict[str, Any]) -> None:diff --git a/openhands/runtime/impl/daytona/daytona_runtime.py b/openhands/runtime/impl/daytona/daytona_runtime.pyindex 6507a89098..3087915a54 100644--- a/openhands/runtime/impl/daytona/daytona_runtime.py+++ b/openhands/runtime/impl/daytona/daytona_runtime.py@@ -17,6 +17,7 @@ from openhands.runtime.impl.action_execution.action_execution_client import (ActionExecutionClient,)from openhands.runtime.plugins.requirement import PluginRequirement+from openhands.runtime.runtime_status import RuntimeStatusfrom openhands.runtime.utils.command import get_action_execution_server_startup_commandfrom openhands.runtime.utils.request import RequestHTTPErrorfrom openhands.utils.async_utils import call_sync_from_async@@ -170,7 +171,7 @@ class DaytonaRuntime(ActionExecutionClient):super().check_if_alive()async def connect(self):- self.send_status_message('STATUS$STARTING_RUNTIME')+ self.set_runtime_status(RuntimeStatus.STARTING_RUNTIME)should_start_action_execution_server = Falseif self.attach_to_existing:@@ -179,7 +180,7 @@ class DaytonaRuntime(ActionExecutionClient):should_start_action_execution_server = Trueif self.workspace is None:- self.send_status_message('STATUS$PREPARING_CONTAINER')+ self.set_runtime_status(RuntimeStatus.BUILDING_RUNTIME)self.workspace = await call_sync_from_async(self._create_workspace)self.log('info', f'Created new workspace with id: {self.workspace_id}')@@ -205,7 +206,7 @@ class DaytonaRuntime(ActionExecutionClient):)self.log('info', 'Waiting for client to become ready...')- self.send_status_message('STATUS$WAITING_FOR_CLIENT')+ self.set_runtime_status(RuntimeStatus.STARTING_RUNTIME)await call_sync_from_async(self._wait_until_alive)if should_start_action_execution_server:@@ -217,7 +218,7 @@ class DaytonaRuntime(ActionExecutionClient):)if should_start_action_execution_server:- self.send_status_message(' ')+ self.set_runtime_status(RuntimeStatus.READY)self._runtime_initialized = True@tenacity.retry(diff --git a/openhands/runtime/impl/docker/docker_runtime.py b/openhands/runtime/impl/docker/docker_runtime.pyindex 3f0e1c72c9..5a31e6f863 100644--- a/openhands/runtime/impl/docker/docker_runtime.py+++ b/openhands/runtime/impl/docker/docker_runtime.py@@ -23,6 +23,7 @@ from openhands.runtime.impl.action_execution.action_execution_client import ()from openhands.runtime.impl.docker.containers import stop_all_containersfrom openhands.runtime.plugins import PluginRequirement+from openhands.runtime.runtime_status import RuntimeStatusfrom openhands.runtime.utils import find_available_tcp_portfrom openhands.runtime.utils.command import (DEFAULT_MAIN_MODULE,@@ -145,7 +146,7 @@ class DockerRuntime(ActionExecutionClient):return self.api_urlasync def connect(self) -> None:- self.send_status_message('STATUS$STARTING_RUNTIME')+ self.set_runtime_status(RuntimeStatus.STARTING_RUNTIME)try:await call_sync_from_async(self._attach_to_container)except docker.errors.NotFound as e:@@ -172,7 +173,7 @@ class DockerRuntime(ActionExecutionClient):if not self.attach_to_existing:self.log('info', f'Waiting for client to become ready at {self.api_url}...')- self.send_status_message('STATUS$WAITING_FOR_CLIENT')+ self.set_runtime_status(RuntimeStatus.STARTING_RUNTIME)await call_sync_from_async(self.wait_until_alive)@@ -187,7 +188,7 @@ class DockerRuntime(ActionExecutionClient):f'Container initialized with plugins: {[plugin.name for plugin in self.plugins]}. VSCode URL: {self.vscode_url}',)if not self.attach_to_existing:- self.send_status_message(' ')+ self.set_runtime_status(RuntimeStatus.READY)self._runtime_initialized = Truedef maybe_build_runtime_container_image(self):@@ -196,7 +197,7 @@ class DockerRuntime(ActionExecutionClient):raise ValueError('Neither runtime container image nor base container image is set')- self.send_status_message('STATUS$STARTING_CONTAINER')+ self.set_runtime_status(RuntimeStatus.BUILDING_RUNTIME)self.runtime_container_image = build_runtime_image(self.base_container_image,self.runtime_builder,@@ -267,7 +268,7 @@ class DockerRuntime(ActionExecutionClient):def init_container(self) -> None:self.log('debug', 'Preparing to start container...')- self.send_status_message('STATUS$PREPARING_CONTAINER')+ self.set_runtime_status(RuntimeStatus.STARTING_RUNTIME)self._host_port = self._find_available_port(EXECUTION_SERVER_PORT_RANGE)self._container_port = self._host_port# Use the configured vscode_port if provided, otherwise find an available port@@ -376,7 +377,7 @@ class DockerRuntime(ActionExecutionClient):**(self.config.sandbox.docker_runtime_kwargs or {}),)self.log('debug', f'Container started. Server url: {self.api_url}')- self.send_status_message('STATUS$CONTAINER_STARTED')+ self.set_runtime_status(RuntimeStatus.RUNTIME_STARTED)except Exception as e:self.log('error',diff --git a/openhands/runtime/impl/local/local_runtime.py b/openhands/runtime/impl/local/local_runtime.pyindex 939bbdcc9d..835a87ba5c 100644--- a/openhands/runtime/impl/local/local_runtime.py+++ b/openhands/runtime/impl/local/local_runtime.py@@ -35,6 +35,7 @@ from openhands.runtime.impl.docker.docker_runtime import (VSCODE_PORT_RANGE,)from openhands.runtime.plugins import PluginRequirement+from openhands.runtime.runtime_status import RuntimeStatusfrom openhands.runtime.utils import find_available_tcp_portfrom openhands.runtime.utils.command import get_action_execution_server_startup_commandfrom openhands.utils.async_utils import call_sync_from_async@@ -206,7 +207,7 @@ class LocalRuntime(ActionExecutionClient):async def connect(self) -> None:"""Start the action_execution_server on the local machine or connect to an existing one."""- self.send_status_message('STATUS$STARTING_RUNTIME')+ self.set_runtime_status(RuntimeStatus.STARTING_RUNTIME)# Check if there's already a server running for this session IDif self.sid in _RUNNING_SERVERS:@@ -383,7 +384,7 @@ class LocalRuntime(ActionExecutionClient):)self.log('info', f'Waiting for server to become ready at {self.api_url}...')- self.send_status_message('STATUS$WAITING_FOR_CLIENT')+ self.set_runtime_status(RuntimeStatus.STARTING_RUNTIME)await call_sync_from_async(self._wait_until_alive)@@ -395,7 +396,7 @@ class LocalRuntime(ActionExecutionClient):f'Server initialized with plugins: {[plugin.name for plugin in self.plugins]}',)if not self.attach_to_existing:- self.send_status_message(' ')+ self.set_runtime_status(RuntimeStatus.READY)self._runtime_initialized = Truedef _find_available_port(diff --git a/openhands/runtime/impl/modal/modal_runtime.py b/openhands/runtime/impl/modal/modal_runtime.pyindex c37e28dd30..ac0444227c 100644--- a/openhands/runtime/impl/modal/modal_runtime.py+++ b/openhands/runtime/impl/modal/modal_runtime.py@@ -13,6 +13,7 @@ from openhands.runtime.impl.action_execution.action_execution_client import (ActionExecutionClient,)from openhands.runtime.plugins import PluginRequirement+from openhands.runtime.runtime_status import RuntimeStatusfrom openhands.runtime.utils.command import get_action_execution_server_startup_commandfrom openhands.runtime.utils.runtime_build import (BuildFromImageType,@@ -102,7 +103,7 @@ class ModalRuntime(ActionExecutionClient):)async def connect(self):- self.send_status_message('STATUS$STARTING_RUNTIME')+ self.set_runtime_status(RuntimeStatus.STARTING_RUNTIME)self.log('debug', f'ModalRuntime `{self.sid}`')@@ -120,14 +121,14 @@ class ModalRuntime(ActionExecutionClient):sandbox_id, client=self.modal_client)else:- self.send_status_message('STATUS$PREPARING_CONTAINER')+ self.set_runtime_status(RuntimeStatus.STARTING_RUNTIME)await call_sync_from_async(self._init_sandbox,sandbox_workspace_dir=self.config.workspace_mount_path_in_sandbox,plugins=self.plugins,)- self.send_status_message('STATUS$CONTAINER_STARTED')+ self.set_runtime_status(RuntimeStatus.RUNTIME_STARTED)if self.sandbox is None:raise Exception('Sandbox not initialized')@@ -137,13 +138,13 @@ class ModalRuntime(ActionExecutionClient):if not self.attach_to_existing:self.log('debug', 'Waiting for client to become ready...')- self.send_status_message('STATUS$WAITING_FOR_CLIENT')+ self.set_runtime_status(RuntimeStatus.STARTING_RUNTIME)self._wait_until_alive()self.setup_initial_env()if not self.attach_to_existing:- self.send_status_message(' ')+ self.set_runtime_status(RuntimeStatus.READY)self._runtime_initialized = True@propertydiff --git a/openhands/runtime/impl/remote/remote_runtime.py b/openhands/runtime/impl/remote/remote_runtime.pyindex 063bd236f2..31e7b3fcea 100644--- a/openhands/runtime/impl/remote/remote_runtime.py+++ b/openhands/runtime/impl/remote/remote_runtime.py@@ -24,6 +24,7 @@ from openhands.runtime.impl.action_execution.action_execution_client import (ActionExecutionClient,)from openhands.runtime.plugins import PluginRequirement+from openhands.runtime.runtime_status import RuntimeStatusfrom openhands.runtime.utils.command import (DEFAULT_MAIN_MODULE,get_action_execution_server_startup_command,@@ -139,7 +140,7 @@ class RemoteRuntime(ActionExecutionClient):)else:self.log('info', 'No existing runtime found, starting a new one')- self.send_status_message('STATUS$STARTING_CONTAINER')+ self.set_runtime_status(RuntimeStatus.BUILDING_RUNTIME)if self.config.sandbox.runtime_container_image is None:self.log('info',@@ -159,13 +160,13 @@ class RemoteRuntime(ActionExecutionClient):assert self.runtime_url is not None, ('Runtime URL is not set. This should never happen.')- self.send_status_message('STATUS$WAITING_FOR_CLIENT')+ self.set_runtime_status(RuntimeStatus.STARTING_RUNTIME)if not self.attach_to_existing:self.log('info', 'Waiting for runtime to be alive...')self._wait_until_alive()if not self.attach_to_existing:self.log('info', 'Runtime is ready.')- self.send_status_message(' ')+ self.set_runtime_status(RuntimeStatus.READY)def _check_existing_runtime(self) -> bool:self.log('info', f'Checking for existing runtime with session ID: {self.sid}')@@ -307,7 +308,7 @@ class RemoteRuntime(ActionExecutionClient):4. Update env vars"""self.log('info', f'Attempting to resume runtime with ID: {self.runtime_id}')- self.send_status_message('STATUS$STARTING_RUNTIME')+ self.set_runtime_status(RuntimeStatus.STARTING_RUNTIME)try:response = self._send_runtime_api_request('POST',diff --git a/openhands/runtime/impl/runloop/runloop_runtime.py b/openhands/runtime/impl/runloop/runloop_runtime.pyindex 5d057caf4a..9de58a4404 100644--- a/openhands/runtime/impl/runloop/runloop_runtime.py+++ b/openhands/runtime/impl/runloop/runloop_runtime.py@@ -13,6 +13,7 @@ from openhands.runtime.impl.action_execution.action_execution_client import (ActionExecutionClient,)from openhands.runtime.plugins import PluginRequirement+from openhands.runtime.runtime_status import RuntimeStatusfrom openhands.runtime.utils.command import get_action_execution_server_startup_commandfrom openhands.utils.tenacity_stop import stop_if_should_exit@@ -114,7 +115,7 @@ class RunloopRuntime(ActionExecutionClient):return self._wait_for_devbox(devbox)async def connect(self):- self.send_status_message('STATUS$STARTING_RUNTIME')+ self.set_runtime_status(RuntimeStatus.STARTING_RUNTIME)if self.attach_to_existing:active_devboxes = self.runloop_api_client.devboxes.list(@@ -139,7 +140,7 @@ class RunloopRuntime(ActionExecutionClient):# End Runloop connect# NOTE: Copied from DockerRuntimelogger.info('Waiting for client to become ready...')- self.send_status_message('STATUS$WAITING_FOR_CLIENT')+ self.set_runtime_status(RuntimeStatus.STARTING_RUNTIME)self._wait_until_alive()if not self.attach_to_existing:@@ -148,7 +149,7 @@ class RunloopRuntime(ActionExecutionClient):logger.info(f'Container initialized with plugins: {[plugin.name for plugin in self.plugins]}')- self.send_status_message(' ')+ self.set_runtime_status(RuntimeStatus.READY)@tenacity.retry(stop=tenacity.stop_after_delay(120) | stop_if_should_exit(),diff --git a/openhands/runtime/runtime_status.py b/openhands/runtime/runtime_status.pynew file mode 100644index 0000000000..de9b3b6c43--- /dev/null+++ b/openhands/runtime/runtime_status.py@@ -0,0 +1,15 @@+from enum import Enum+++class RuntimeStatus(Enum):+ def __init__(self, value: str, message: str):+ self._value_ = value+ self.message = message++ STOPPED = 'STATUS$STOPPED', 'Stopped'+ BUILDING_RUNTIME = 'STATUS$BUILDING_RUNTIME', 'Building runtime...'+ STARTING_RUNTIME = 'STATUS$STARTING_RUNTIME', 'Starting runtime...'+ RUNTIME_STARTED = 'STATUS$RUNTIME_STARTED', 'Runtime started...'+ SETTING_UP_WORKSPACE = 'STATUS$SETTING_UP_WORKSPACE', 'Setting up workspace...'+ SETTING_UP_GIT_HOOKS = 'STATUS$SETTING_UP_GIT_HOOKS', 'Setting up git hooks...'+ READY = 'STATUS$READY', 'Ready...'diff --git a/openhands/server/conversation_manager/standalone_conversation_manager.py b/openhands/server/conversation_manager/standalone_conversation_manager.pyindex 2082fdb3e0..6fdfa46211 100644--- a/openhands/server/conversation_manager/standalone_conversation_manager.py+++ b/openhands/server/conversation_manager/standalone_conversation_manager.py@@ -20,6 +20,7 @@ from openhands.server.session.conversation import ServerConversationfrom openhands.server.session.session import ROOM_KEY, Sessionfrom openhands.storage.conversation.conversation_store import ConversationStorefrom openhands.storage.data_models.conversation_metadata import ConversationMetadata+from openhands.storage.data_models.conversation_status import ConversationStatusfrom openhands.storage.data_models.settings import Settingsfrom openhands.storage.files import FileStorefrom openhands.utils.async_utils import GENERAL_TIMEOUT, call_async_from_sync, wait_all@@ -506,12 +507,21 @@ class StandaloneConversationManager(ConversationManager):url=self._get_conversation_url(session.sid),session_api_key=None,event_store=session.agent_session.event_stream,+ status=_get_status_from_session(session),+ runtime_status=getattr(session.agent_session.runtime, 'runtime_status', None),)def _get_conversation_url(self, conversation_id: str):return f'/api/conversations/{conversation_id}'+def _get_status_from_session(session: Session) -> ConversationStatus:+ agent_session = session.agent_session+ if agent_session.runtime and agent_session.runtime.runtime_initialized:+ return ConversationStatus.RUNNING+ return ConversationStatus.STARTING++def _last_updated_at_key(conversation: ConversationMetadata) -> float:last_updated_at = conversation.last_updated_atif last_updated_at is None:diff --git a/openhands/server/data_models/agent_loop_info.py b/openhands/server/data_models/agent_loop_info.pyindex 3f743335b0..1d5fc01e95 100644--- a/openhands/server/data_models/agent_loop_info.py+++ b/openhands/server/data_models/agent_loop_info.py@@ -1,6 +1,7 @@from dataclasses import dataclass, fieldfrom openhands.events.event_store_abc import EventStoreABC+from openhands.runtime.runtime_status import RuntimeStatusfrom openhands.storage.data_models.conversation_status import ConversationStatus@@ -15,3 +16,4 @@ class AgentLoopInfo:session_api_key: str | Noneevent_store: EventStoreABC | Nonestatus: ConversationStatus = field(default=ConversationStatus.RUNNING)+ runtime_status: RuntimeStatus | None = Nonediff --git a/openhands/server/data_models/conversation_info.py b/openhands/server/data_models/conversation_info.pyindex 24affd071d..d8a22f8c63 100644--- a/openhands/server/data_models/conversation_info.py+++ b/openhands/server/data_models/conversation_info.py@@ -1,7 +1,9 @@from dataclasses import dataclass, fieldfrom datetime import datetime, timezone+from openhands.core.schema.agent import AgentStatefrom openhands.integrations.service_types import ProviderType+from openhands.runtime.runtime_status import RuntimeStatusfrom openhands.storage.data_models.conversation_metadata import ConversationTriggerfrom openhands.storage.data_models.conversation_status import ConversationStatus@@ -17,6 +19,7 @@ class ConversationInfo:title: strlast_updated_at: datetime | None = Nonestatus: ConversationStatus = ConversationStatus.STOPPED+ runtime_status: RuntimeStatus | None = Noneselected_repository: str | None = Noneselected_branch: str | None = Nonegit_provider: ProviderType | None = Nonediff --git a/openhands/server/routes/manage_conversations.py b/openhands/server/routes/manage_conversations.pyindex 821c2ced40..f8855b038f 100644--- a/openhands/server/routes/manage_conversations.py+++ b/openhands/server/routes/manage_conversations.py@@ -379,16 +379,11 @@ async def _get_conversation_info(selected_repository=conversation.selected_repository,selected_branch=conversation.selected_branch,git_provider=conversation.git_provider,- status=(- agent_loop_info.status- if agent_loop_info- else ConversationStatus.STOPPED- ),+ status=getattr(agent_loop_info, 'status', ConversationStatus.STOPPED),+ runtime_status=getattr(agent_loop_info, 'runtime_status', None),num_connections=num_connections,url=agent_loop_info.url if agent_loop_info else None,- session_api_key=agent_loop_info.session_api_key- if agent_loop_info- else None,+ session_api_key=getattr(agent_loop_info, 'session_api_key', None),)except Exception as e:logger.error(