Skip to content

πŸ™Œ OpenHands: AI-Driven Development

Fixes for listing files, clean up references to tokens (#5718)

Robert Brennana01fb9dca3e6
diff --git a/frontend/__tests__/components/chat/chat-interface.test.tsx b/frontend/__tests__/components/chat/chat-interface.test.tsx
index 2fd6057e15..ed8c448831 100644
--- a/frontend/__tests__/components/chat/chat-interface.test.tsx
+++ b/frontend/__tests__/components/chat/chat-interface.test.tsx
@@ -20,7 +20,7 @@ describe("Empty state", () => {
const { useWsClient: useWsClientMock } = vi.hoisted(() => ({
useWsClient: vi.fn(() => ({
send: sendMock,
- status: WsClientProviderStatus.ACTIVE,
+ status: WsClientProviderStatus.CONNECTED,
isLoadingMessages: false,
})),
}));
@@ -90,7 +90,7 @@ describe("Empty state", () => {
// this is to test that the message is in the UI before the socket is called
useWsClientMock.mockImplementation(() => ({
send: sendMock,
- status: WsClientProviderStatus.ACTIVE,
+ status: WsClientProviderStatus.CONNECTED,
isLoadingMessages: false,
}));
const addUserMessageSpy = vi.spyOn(ChatSlice, "addUserMessage");
@@ -120,7 +120,7 @@ describe("Empty state", () => {
async () => {
useWsClientMock.mockImplementation(() => ({
send: sendMock,
- status: WsClientProviderStatus.ACTIVE,
+ status: WsClientProviderStatus.CONNECTED,
isLoadingMessages: false,
}));
const user = userEvent.setup();
@@ -138,7 +138,7 @@ describe("Empty state", () => {
useWsClientMock.mockImplementation(() => ({
send: sendMock,
- status: WsClientProviderStatus.ACTIVE,
+ status: WsClientProviderStatus.CONNECTED,
isLoadingMessages: false,
}));
rerender(<ChatInterface />);
diff --git a/frontend/__tests__/components/file-explorer/file-explorer.test.tsx b/frontend/__tests__/components/file-explorer/file-explorer.test.tsx
index 5a68fa6787..1385ce4e53 100644
--- a/frontend/__tests__/components/file-explorer/file-explorer.test.tsx
+++ b/frontend/__tests__/components/file-explorer/file-explorer.test.tsx
@@ -3,7 +3,7 @@ import userEvent from "@testing-library/user-event";
import { renderWithProviders } from "test-utils";
import { describe, it, expect, vi, Mock, afterEach } from "vitest";
import toast from "#/utils/toast";
-import AgentState from "#/types/agent-state";
+import { AgentState } from "#/types/agent-state";
import OpenHands from "#/api/open-hands";
import { FileExplorer } from "#/components/features/file-explorer/file-explorer";
diff --git a/frontend/__tests__/services/auth.test.ts b/frontend/__tests__/services/auth.test.ts
deleted file mode 100644
index 6fe67790a0..0000000000
--- a/frontend/__tests__/services/auth.test.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import { beforeEach, describe, expect, it, vi, type Mock } from "vitest";
-import { getToken } from "../../src/services/auth";
-
-Storage.prototype.getItem = vi.fn();
-Storage.prototype.setItem = vi.fn();
-
-describe("Auth Service", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- describe("getToken", () => {
- it("should fetch and return a token", () => {
- (Storage.prototype.getItem as Mock).mockReturnValue("newToken");
-
- const data = getToken();
- expect(localStorage.getItem).toHaveBeenCalledWith("token"); // Used to set Authorization header
- expect(data).toEqual("newToken");
- });
- });
-});
diff --git a/frontend/src/components/agent-status-map.constant.ts b/frontend/src/components/agent-status-map.constant.ts
index 5de965a341..e3c0dcabd9 100644
--- a/frontend/src/components/agent-status-map.constant.ts
+++ b/frontend/src/components/agent-status-map.constant.ts
@@ -1,5 +1,5 @@
import { I18nKey } from "#/i18n/declaration";
-import AgentState from "#/types/agent-state";
+import { AgentState } from "#/types/agent-state";
enum IndicatorColor {
BLUE = "bg-blue-500",
diff --git a/frontend/src/components/features/chat/chat-interface.tsx b/frontend/src/components/features/chat/chat-interface.tsx
index 48710e31f5..bfc65b3e75 100644
--- a/frontend/src/components/features/chat/chat-interface.tsx
+++ b/frontend/src/components/features/chat/chat-interface.tsx
@@ -7,7 +7,7 @@ import { createChatMessage } from "#/services/chat-service";
import { InteractiveChatBox } from "./interactive-chat-box";
import { addUserMessage } from "#/state/chat-slice";
import { RootState } from "#/store";
-import AgentState from "#/types/agent-state";
+import { AgentState } from "#/types/agent-state";
import { generateAgentStateChangeEvent } from "#/services/agent-state-service";
import { FeedbackModal } from "../feedback/feedback-modal";
import { useScrollToBottom } from "#/hooks/use-scroll-to-bottom";
diff --git a/frontend/src/components/features/controls/agent-control-bar.tsx b/frontend/src/components/features/controls/agent-control-bar.tsx
index dad718533f..c69d16e0bf 100644
--- a/frontend/src/components/features/controls/agent-control-bar.tsx
+++ b/frontend/src/components/features/controls/agent-control-bar.tsx
@@ -3,7 +3,7 @@ import PauseIcon from "#/assets/pause";
import PlayIcon from "#/assets/play";
import { generateAgentStateChangeEvent } from "#/services/agent-state-service";
import { RootState } from "#/store";
-import AgentState from "#/types/agent-state";
+import { AgentState } from "#/types/agent-state";
import { useWsClient } from "#/context/ws-client-provider";
import { IGNORE_TASK_STATE_MAP } from "#/ignore-task-state-map.constant";
import { ActionButton } from "#/components/shared/buttons/action-button";
diff --git a/frontend/src/components/features/controls/agent-status-bar.tsx b/frontend/src/components/features/controls/agent-status-bar.tsx
index 6251189715..400c12d023 100644
--- a/frontend/src/components/features/controls/agent-status-bar.tsx
+++ b/frontend/src/components/features/controls/agent-status-bar.tsx
@@ -3,7 +3,7 @@ import { useTranslation } from "react-i18next";
import { useSelector } from "react-redux";
import toast from "react-hot-toast";
import { RootState } from "#/store";
-import AgentState from "#/types/agent-state";
+import { AgentState } from "#/types/agent-state";
import { AGENT_STATUS_MAP } from "../../agent-status-map.constant";
export function AgentStatusBar() {
diff --git a/frontend/src/components/features/file-explorer/file-explorer.tsx b/frontend/src/components/features/file-explorer/file-explorer.tsx
index c818ec52f8..0c489013b1 100644
--- a/frontend/src/components/features/file-explorer/file-explorer.tsx
+++ b/frontend/src/components/features/file-explorer/file-explorer.tsx
@@ -1,7 +1,7 @@
import React from "react";
import { useDispatch, useSelector } from "react-redux";
import { useTranslation } from "react-i18next";
-import AgentState from "#/types/agent-state";
+import { RUNTIME_INACTIVE_STATES } from "#/types/agent-state";
import { ExplorerTree } from "#/components/features/file-explorer/explorer-tree";
import toast from "#/utils/toast";
import { RootState } from "#/store";
@@ -38,7 +38,7 @@ export function FileExplorer({ isOpen, onToggle }: FileExplorerProps) {
const { data: paths, refetch, error } = useListFiles();
const { mutate: uploadFiles } = useUploadFiles();
const { data: vscodeUrl } = useVSCodeUrl({
- enabled: status === WsClientProviderStatus.ACTIVE,
+ enabled: !RUNTIME_INACTIVE_STATES.includes(curAgentState),
});
const handleOpenVSCode = () => {
@@ -96,10 +96,7 @@ export function FileExplorer({ isOpen, onToggle }: FileExplorerProps) {
};
const refreshWorkspace = () => {
- if (
- curAgentState !== AgentState.LOADING &&
- curAgentState !== AgentState.STOPPED
- ) {
+ if (!RUNTIME_INACTIVE_STATES.includes(curAgentState)) {
refetch();
}
};
@@ -170,7 +167,7 @@ export function FileExplorer({ isOpen, onToggle }: FileExplorerProps) {
{isOpen && (
<OpenVSCodeButton
onClick={handleOpenVSCode}
- isDisabled={status === WsClientProviderStatus.OPENING}
+ isDisabled={status === WsClientProviderStatus.DISCONNECTED}
/>
)}
</div>
diff --git a/frontend/src/components/features/sidebar/sidebar.tsx b/frontend/src/components/features/sidebar/sidebar.tsx
index 7229ece49b..7a63b8b1df 100644
--- a/frontend/src/components/features/sidebar/sidebar.tsx
+++ b/frontend/src/components/features/sidebar/sidebar.tsx
@@ -20,7 +20,7 @@ export function Sidebar() {
const user = useGitHubUser();
const { data: isAuthed } = useIsAuthed();
- const { token, logout } = useAuth();
+ const { logout } = useAuth();
const { settingsAreUpToDate } = useUserPrefs();
const [accountSettingsModalOpen, setAccountSettingsModalOpen] =
@@ -68,11 +68,9 @@ export function Sidebar() {
/>
<SettingsButton onClick={() => setSettingsModalIsOpen(true)} />
<DocsButton />
- {!!token && (
- <ExitProjectButton
- onClick={() => setStartNewProjectModalIsOpen(true)}
- />
- )}
+ <ExitProjectButton
+ onClick={() => setStartNewProjectModalIsOpen(true)}
+ />
</nav>
</aside>
{accountSettingsModalOpen && (
diff --git a/frontend/src/components/features/terminal/terminal-status-label.tsx b/frontend/src/components/features/terminal/terminal-status-label.tsx
index 5c245cf5f3..24b55960ee 100644
--- a/frontend/src/components/features/terminal/terminal-status-label.tsx
+++ b/frontend/src/components/features/terminal/terminal-status-label.tsx
@@ -1,20 +1,20 @@
-import {
- useWsClient,
- WsClientProviderStatus,
-} from "#/context/ws-client-provider";
+import { useSelector } from "react-redux";
import { cn } from "#/utils/utils";
+import { AgentState } from "#/types/agent-state";
+import { RootState } from "#/store";
export function TerminalStatusLabel() {
- const { status } = useWsClient();
+ const { curAgentState } = useSelector((state: RootState) => state.agent);
return (
<div className="flex items-center gap-2">
<div
className={cn(
"w-2 h-2 rounded-full",
- status === WsClientProviderStatus.ACTIVE && "bg-green-500",
- status !== WsClientProviderStatus.ACTIVE &&
- "bg-red-500 animate-pulse",
+ curAgentState === AgentState.LOADING ||
+ curAgentState === AgentState.STOPPED
+ ? "bg-red-500 animate-pulse"
+ : "bg-green-500",
)}
/>
Terminal
diff --git a/frontend/src/components/features/terminal/terminal.tsx b/frontend/src/components/features/terminal/terminal.tsx
index 83afc05eaa..f6357def26 100644
--- a/frontend/src/components/features/terminal/terminal.tsx
+++ b/frontend/src/components/features/terminal/terminal.tsx
@@ -2,23 +2,20 @@ import { useSelector } from "react-redux";
import { RootState } from "#/store";
import { useTerminal } from "#/hooks/use-terminal";
import "@xterm/xterm/css/xterm.css";
-import {
- useWsClient,
- WsClientProviderStatus,
-} from "#/context/ws-client-provider";
+import { RUNTIME_INACTIVE_STATES } from "#/types/agent-state";
interface TerminalProps {
secrets: string[];
}
function Terminal({ secrets }: TerminalProps) {
- const { status } = useWsClient();
const { commands } = useSelector((state: RootState) => state.cmd);
+ const { curAgentState } = useSelector((state: RootState) => state.agent);
const ref = useTerminal({
commands,
secrets,
- disabled: status === WsClientProviderStatus.OPENING,
+ disabled: RUNTIME_INACTIVE_STATES.includes(curAgentState),
});
return (
diff --git a/frontend/src/components/shared/buttons/action-button.tsx b/frontend/src/components/shared/buttons/action-button.tsx
index 57c9f62d11..c896f61dd3 100644
--- a/frontend/src/components/shared/buttons/action-button.tsx
+++ b/frontend/src/components/shared/buttons/action-button.tsx
@@ -1,5 +1,5 @@
import { Tooltip } from "@nextui-org/react";
-import AgentState from "#/types/agent-state";
+import { AgentState } from "#/types/agent-state";
interface ActionButtonProps {
isDisabled?: boolean;
diff --git a/frontend/src/components/shared/buttons/confirmation-buttons.tsx b/frontend/src/components/shared/buttons/confirmation-buttons.tsx
index 18ad6c50e8..0ffe67bb43 100644
--- a/frontend/src/components/shared/buttons/confirmation-buttons.tsx
+++ b/frontend/src/components/shared/buttons/confirmation-buttons.tsx
@@ -1,6 +1,6 @@
import { useTranslation } from "react-i18next";
import { I18nKey } from "#/i18n/declaration";
-import AgentState from "#/types/agent-state";
+import { AgentState } from "#/types/agent-state";
import { generateAgentStateChangeEvent } from "#/services/agent-state-service";
import { useWsClient } from "#/context/ws-client-provider";
import { ActionTooltip } from "../action-tooltip";
diff --git a/frontend/src/components/shared/modals/exit-project-confirmation-modal.tsx b/frontend/src/components/shared/modals/exit-project-confirmation-modal.tsx
index c29477f3e0..0151f7d0b4 100644
--- a/frontend/src/components/shared/modals/exit-project-confirmation-modal.tsx
+++ b/frontend/src/components/shared/modals/exit-project-confirmation-modal.tsx
@@ -1,7 +1,7 @@
import { useDispatch } from "react-redux";
import { useEndSession } from "#/hooks/use-end-session";
import { setCurrentAgentState } from "#/state/agent-slice";
-import AgentState from "#/types/agent-state";
+import { AgentState } from "#/types/agent-state";
import { DangerModal } from "./confirmation-modals/danger-modal";
import { ModalBackdrop } from "./modal-backdrop";
diff --git a/frontend/src/context/auth-context.tsx b/frontend/src/context/auth-context.tsx
index 6ae9450c44..e5af8e65d2 100644
--- a/frontend/src/context/auth-context.tsx
+++ b/frontend/src/context/auth-context.tsx
@@ -2,10 +2,8 @@ import posthog from "posthog-js";
import React from "react";
import OpenHands from "#/api/open-hands";
import {
- removeAuthTokenHeader as removeOpenHandsAuthTokenHeader,
removeGitHubTokenHeader as removeOpenHandsGitHubTokenHeader,
setGitHubTokenHeader as setOpenHandsGitHubTokenHeader,
- setAuthTokenHeader as setOpenHandsAuthTokenHeader,
} from "#/api/open-hands-axios";
import {
setAuthTokenHeader as setGitHubAuthTokenHeader,
@@ -14,12 +12,9 @@ import {
} from "#/api/github-axios-instance";
interface AuthContextType {
- token: string | null;
gitHubToken: string | null;
- setToken: (token: string | null) => void;
- setGitHubToken: (token: string | null) => void;
setUserId: (userId: string) => void;
- clearToken: () => void;
+ setGitHubToken: (token: string | null) => void;
clearGitHubToken: () => void;
refreshToken: () => Promise<boolean>;
logout: () => void;
@@ -28,9 +23,6 @@ interface AuthContextType {
const AuthContext = React.createContext<AuthContextType | undefined>(undefined);
function AuthProvider({ children }: React.PropsWithChildren) {
- const [tokenState, setTokenState] = React.useState<string | null>(() =>
- localStorage.getItem("token"),
- );
const [gitHubTokenState, setGitHubTokenState] = React.useState<string | null>(
() => localStorage.getItem("ghToken"),
);
@@ -39,13 +31,6 @@ function AuthProvider({ children }: React.PropsWithChildren) {
() => localStorage.getItem("userId") || "",
);
- const clearToken = () => {
- setTokenState(null);
- localStorage.removeItem("token");
-
- removeOpenHandsAuthTokenHeader();
- };
-
const clearGitHubToken = () => {
setGitHubTokenState(null);
setUserIdState("");
@@ -56,17 +41,6 @@ function AuthProvider({ children }: React.PropsWithChildren) {
removeGitHubAuthTokenHeader();
};
- const setToken = (token: string | null) => {
- setTokenState(token);
-
- if (token) {
- localStorage.setItem("token", token);
- setOpenHandsAuthTokenHeader(token);
- } else {
- clearToken();
- }
- };
-
const setGitHubToken = (token: string | null) => {
setGitHubTokenState(token);
@@ -107,11 +81,10 @@ function AuthProvider({ children }: React.PropsWithChildren) {
};
React.useEffect(() => {
- const storedToken = localStorage.getItem("token");
const storedGitHubToken = localStorage.getItem("ghToken");
+
const userId = localStorage.getItem("userId") || "";
- setToken(storedToken);
setGitHubToken(storedGitHubToken);
setUserId(userId);
setupGithubAxiosInterceptors(refreshToken, logout);
@@ -119,17 +92,14 @@ function AuthProvider({ children }: React.PropsWithChildren) {
const value = React.useMemo(
() => ({
- token: tokenState,
gitHubToken: gitHubTokenState,
- setToken,
setGitHubToken,
setUserId,
- clearToken,
clearGitHubToken,
refreshToken,
logout,
}),
- [tokenState, gitHubTokenState],
+ [gitHubTokenState],
);
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
diff --git a/frontend/src/context/ws-client-provider.tsx b/frontend/src/context/ws-client-provider.tsx
index 021762144a..954932d1fc 100644
--- a/frontend/src/context/ws-client-provider.tsx
+++ b/frontend/src/context/ws-client-provider.tsx
@@ -5,16 +5,13 @@ import { io, Socket } from "socket.io-client";
import EventLogger from "#/utils/event-logger";
import { handleAssistantMessage } from "#/services/actions";
import { useRate } from "#/hooks/use-rate";
-import AgentState from "#/types/agent-state";
const isOpenHandsMessage = (event: Record<string, unknown>) =>
event.action === "message";
export enum WsClientProviderStatus {
- STOPPED,
- OPENING,
- ACTIVE,
- ERROR,
+ CONNECTED,
+ DISCONNECTED,
}
interface UseWsClient {
@@ -25,7 +22,7 @@ interface UseWsClient {
}
const WsClientContext = React.createContext<UseWsClient>({
- status: WsClientProviderStatus.STOPPED,
+ status: WsClientProviderStatus.DISCONNECTED,
isLoadingMessages: true,
events: [],
send: () => {
@@ -34,26 +31,23 @@ const WsClientContext = React.createContext<UseWsClient>({
});
interface WsClientProviderProps {
- enabled: boolean;
conversationId: string;
ghToken: string | null;
- selectedRepository: string | null;
}
export function WsClientProvider({
- enabled,
ghToken,
- selectedRepository,
conversationId,
children,
}: React.PropsWithChildren<WsClientProviderProps>) {
const sioRef = React.useRef<Socket | null>(null);
const ghTokenRef = React.useRef<string | null>(ghToken);
- const selectedRepositoryRef = React.useRef<string | null>(selectedRepository);
const disconnectRef = React.useRef<ReturnType<typeof setTimeout> | null>(
null,
);
- const [status, setStatus] = React.useState(WsClientProviderStatus.STOPPED);
+ const [status, setStatus] = React.useState(
+ WsClientProviderStatus.DISCONNECTED,
+ );
const [events, setEvents] = React.useState<Record<string, unknown>[]>([]);
const lastEventRef = React.useRef<Record<string, unknown> | null>(null);
@@ -68,7 +62,7 @@ export function WsClientProvider({
}
function handleConnect() {
- setStatus(WsClientProviderStatus.OPENING);
+ setStatus(WsClientProviderStatus.CONNECTED);
}
function handleMessage(event: Record<string, unknown>) {
@@ -80,29 +74,16 @@ export function WsClientProvider({
lastEventRef.current = event;
}
- const extras = event.extras as Record<string, unknown>;
- if (extras?.agent_state === AgentState.INIT) {
- setStatus(WsClientProviderStatus.ACTIVE);
- }
-
- if (
- status !== WsClientProviderStatus.ACTIVE &&
- event?.observation === "error"
- ) {
- setStatus(WsClientProviderStatus.ERROR);
- return;
- }
-
handleAssistantMessage(event);
}
function handleDisconnect() {
- setStatus(WsClientProviderStatus.STOPPED);
+ setStatus(WsClientProviderStatus.DISCONNECTED);
}
function handleError() {
posthog.capture("socket_error");
- setStatus(WsClientProviderStatus.ERROR);
+ setStatus(WsClientProviderStatus.DISCONNECTED);
}
React.useEffect(() => {
@@ -112,13 +93,6 @@ export function WsClientProvider({
let sio = sioRef.current;
- if (!enabled) {
- if (sio) {
- sio.disconnect();
- }
- return () => {};
- }
-
const lastEvent = lastEventRef.current;
const query = {
latest_event_id: lastEvent?.id ?? -1,
@@ -143,7 +117,6 @@ export function WsClientProvider({
sioRef.current = sio;
ghTokenRef.current = ghToken;
- selectedRepositoryRef.current = selectedRepository;
return () => {
sio.off("connect", handleConnect);
@@ -152,7 +125,7 @@ export function WsClientProvider({
sio.off("connect_failed", handleError);
sio.off("disconnect", handleDisconnect);
};
- }, [enabled, ghToken, selectedRepository, conversationId]);
+ }, [ghToken, conversationId]);
// Strict mode mounts and unmounts each component twice, so we have to wait in the destructor
// before actually disconnecting the socket and cancel the operation if the component gets remounted.
diff --git a/frontend/src/hooks/query/use-conversation-config.ts b/frontend/src/hooks/query/use-conversation-config.ts
index fb74f25f50..da82d0772e 100644
--- a/frontend/src/hooks/query/use-conversation-config.ts
+++ b/frontend/src/hooks/query/use-conversation-config.ts
@@ -17,7 +17,7 @@ export const useConversationConfig = () => {
if (!conversationId) throw new Error("No conversation ID");
return OpenHands.getRuntimeId(conversationId);
},
- enabled: status === WsClientProviderStatus.ACTIVE && !!conversationId,
+ enabled: status === WsClientProviderStatus.CONNECTED && !!conversationId,
});
React.useEffect(() => {
diff --git a/frontend/src/hooks/query/use-list-files.ts b/frontend/src/hooks/query/use-list-files.ts
index 66b9806f09..8bb30f0e26 100644
--- a/frontend/src/hooks/query/use-list-files.ts
+++ b/frontend/src/hooks/query/use-list-files.ts
@@ -5,7 +5,6 @@ import {
} from "#/context/ws-client-provider";
import OpenHands from "#/api/open-hands";
import { useConversation } from "#/context/conversation-context";
-import { useAuth } from "#/context/auth-context";
interface UseListFilesConfig {
path?: string;
@@ -13,14 +12,13 @@ interface UseListFilesConfig {
}
export const useListFiles = (config?: UseListFilesConfig) => {
- const { token } = useAuth();
const { conversationId } = useConversation();
const { status } = useWsClient();
- const isActive = status === WsClientProviderStatus.ACTIVE;
+ const isActive = status === WsClientProviderStatus.CONNECTED;
return useQuery({
- queryKey: ["files", token, conversationId, config?.path],
+ queryKey: ["files", conversationId, config?.path],
queryFn: () => OpenHands.getFiles(conversationId, config?.path),
- enabled: !!(isActive && config?.enabled && token),
+ enabled: !!(isActive && config?.enabled),
});
};
diff --git a/frontend/src/hooks/use-end-session.ts b/frontend/src/hooks/use-end-session.ts
index 32724c9f22..cd27842ca9 100644
--- a/frontend/src/hooks/use-end-session.ts
+++ b/frontend/src/hooks/use-end-session.ts
@@ -1,6 +1,5 @@
import { useDispatch } from "react-redux";
import { useNavigate } from "react-router";
-import { useAuth } from "#/context/auth-context";
import {
initialState as browserInitialState,
setScreenshotSrc,
@@ -11,13 +10,11 @@ import { clearSelectedRepository } from "#/state/initial-query-slice";
export const useEndSession = () => {
const navigate = useNavigate();
const dispatch = useDispatch();
- const { clearToken } = useAuth();
/**
* End the current session by clearing the token and redirecting to the home page.
*/
const endSession = () => {
- clearToken();
dispatch(clearSelectedRepository());
// Reset browser state to initial values
diff --git a/frontend/src/ignore-task-state-map.constant.ts b/frontend/src/ignore-task-state-map.constant.ts
index 2fc50e7d54..e5fd295b49 100644
--- a/frontend/src/ignore-task-state-map.constant.ts
+++ b/frontend/src/ignore-task-state-map.constant.ts
@@ -1,4 +1,4 @@
-import AgentState from "./types/agent-state";
+import { AgentState } from "./types/agent-state";
export const IGNORE_TASK_STATE_MAP: Record<string, AgentState[]> = {
[AgentState.PAUSED]: [
diff --git a/frontend/src/mocks/handlers.ws.ts b/frontend/src/mocks/handlers.ws.ts
index 82b879879f..d284600381 100644
--- a/frontend/src/mocks/handlers.ws.ts
+++ b/frontend/src/mocks/handlers.ws.ts
@@ -1,5 +1,5 @@
import { delay, WebSocketHandler, ws } from "msw";
-import AgentState from "#/types/agent-state";
+import { AgentState } from "#/types/agent-state";
import {
AgentStateChangeObservation,
CommandObservation,
diff --git a/frontend/src/routes/_oh.app._index/route.tsx b/frontend/src/routes/_oh.app._index/route.tsx
index 1a8528f61a..007f31145a 100644
--- a/frontend/src/routes/_oh.app._index/route.tsx
+++ b/frontend/src/routes/_oh.app._index/route.tsx
@@ -4,7 +4,7 @@ import { useRouteError } from "react-router";
import { editor } from "monaco-editor";
import { EditorProps } from "@monaco-editor/react";
import { RootState } from "#/store";
-import AgentState from "#/types/agent-state";
+import { AgentState } from "#/types/agent-state";
import CodeEditorComponent from "../../components/features/editor/code-editor-component";
import { useFiles } from "#/context/files";
import { useSaveFile } from "#/hooks/mutation/use-save-file";
diff --git a/frontend/src/routes/_oh.app/hooks/use-handle-runtime-active.ts b/frontend/src/routes/_oh.app/hooks/use-handle-runtime-active.ts
index 4fa131fe56..1edba35b67 100644
--- a/frontend/src/routes/_oh.app/hooks/use-handle-runtime-active.ts
+++ b/frontend/src/routes/_oh.app/hooks/use-handle-runtime-active.ts
@@ -2,10 +2,7 @@ import React from "react";
import toast from "react-hot-toast";
import { useDispatch, useSelector } from "react-redux";
import { useAuth } from "#/context/auth-context";
-import {
- useWsClient,
- WsClientProviderStatus,
-} from "#/context/ws-client-provider";
+import { useWsClient } from "#/context/ws-client-provider";
import { getGitHubTokenCommand } from "#/services/terminal-service";
import { setImportedProjectZip } from "#/state/initial-query-slice";
import { RootState } from "#/store";
@@ -13,17 +10,19 @@ import { base64ToBlob } from "#/utils/base64-to-blob";
import { useUploadFiles } from "../../../hooks/mutation/use-upload-files";
import { useGitHubUser } from "../../../hooks/query/use-github-user";
import { isGitHubErrorReponse } from "#/api/github-axios-instance";
+import { RUNTIME_INACTIVE_STATES } from "#/types/agent-state";
export const useHandleRuntimeActive = () => {
const { gitHubToken } = useAuth();
- const { status, send } = useWsClient();
+ const { send } = useWsClient();
+ const { curAgentState } = useSelector((state: RootState) => state.agent);
const dispatch = useDispatch();
const { data: user } = useGitHubUser();
const { mutate: uploadFiles } = useUploadFiles();
- const runtimeActive = status === WsClientProviderStatus.ACTIVE;
+ const runtimeActive = !RUNTIME_INACTIVE_STATES.includes(curAgentState);
const { importedProjectZip } = useSelector(
(state: RootState) => state.initalQuery,
diff --git a/frontend/src/routes/_oh.app/hooks/use-handle-ws-events.ts b/frontend/src/routes/_oh.app/hooks/use-handle-ws-events.ts
index 5dfc7f8ca8..43353ed9f2 100644
--- a/frontend/src/routes/_oh.app/hooks/use-handle-ws-events.ts
+++ b/frontend/src/routes/_oh.app/hooks/use-handle-ws-events.ts
@@ -1,11 +1,10 @@
import React from "react";
import toast from "react-hot-toast";
import { useDispatch } from "react-redux";
-import { useAuth } from "#/context/auth-context";
import { useWsClient } from "#/context/ws-client-provider";
import { generateAgentStateChangeEvent } from "#/services/agent-state-service";
import { addErrorMessage } from "#/state/chat-slice";
-import AgentState from "#/types/agent-state";
+import { AgentState } from "#/types/agent-state";
import { ErrorObservation } from "#/types/core/observations";
import { useEndSession } from "../../../hooks/use-end-session";
@@ -22,7 +21,6 @@ const isErrorObservation = (data: object): data is ErrorObservation =>
export const useHandleWSEvents = () => {
const { events, send } = useWsClient();
- const { setToken } = useAuth();
const endSession = useEndSession();
const dispatch = useDispatch();
@@ -31,10 +29,6 @@ export const useHandleWSEvents = () => {
return;
}
const event = events[events.length - 1];
- if (event.token && typeof event.token === "string") {
- setToken(event.token);
- return;
- }
if (isServerError(event)) {
if (event.error_code === 401) {
diff --git a/frontend/src/routes/_oh.app/hooks/use-ws-status-change.ts b/frontend/src/routes/_oh.app/hooks/use-ws-status-change.ts
index 789af7dadf..0eced2e249 100644
--- a/frontend/src/routes/_oh.app/hooks/use-ws-status-change.ts
+++ b/frontend/src/routes/_oh.app/hooks/use-ws-status-change.ts
@@ -14,11 +14,12 @@ import {
clearInitialQuery,
} from "#/state/initial-query-slice";
import { RootState } from "#/store";
-import AgentState from "#/types/agent-state";
+import { AgentState } from "#/types/agent-state";
export const useWSStatusChange = () => {
const { send, status } = useWsClient();
const { gitHubToken } = useAuth();
+ const { curAgentState } = useSelector((state: RootState) => state.agent);
const dispatch = useDispatch();
const statusRef = React.useRef<WsClientProviderStatus | null>(null);
@@ -47,7 +48,7 @@ export const useWSStatusChange = () => {
dispatch(clearInitialQuery()); // reset initial query
};
- const handleOnWSActive = () => {
+ const handleAgentInit = () => {
let additionalInfo = "";
if (gitHubToken && selectedRepository) {
@@ -63,6 +64,11 @@ export const useWSStatusChange = () => {
dispatchInitialQuery(initialQuery, additionalInfo);
}
};
+ React.useEffect(() => {
+ if (curAgentState === AgentState.INIT) {
+ handleAgentInit();
+ }
+ }, [curAgentState]);
React.useEffect(() => {
if (statusRef.current === status) {
@@ -70,11 +76,7 @@ export const useWSStatusChange = () => {
}
statusRef.current = status;
- if (status === WsClientProviderStatus.ACTIVE) {
- handleOnWSActive();
- }
-
- if (status === WsClientProviderStatus.OPENING && initialQuery) {
+ if (status === WsClientProviderStatus.CONNECTED && initialQuery) {
dispatch(
addUserMessage({
content: initialQuery,
@@ -85,7 +87,7 @@ export const useWSStatusChange = () => {
);
}
- if (status === WsClientProviderStatus.STOPPED) {
+ if (status === WsClientProviderStatus.DISCONNECTED) {
dispatch(setCurrentAgentState(AgentState.STOPPED));
}
}, [status]);
diff --git a/frontend/src/routes/_oh.app/route.tsx b/frontend/src/routes/_oh.app/route.tsx
index bafafd80ca..558db16ed9 100644
--- a/frontend/src/routes/_oh.app/route.tsx
+++ b/frontend/src/routes/_oh.app/route.tsx
@@ -69,12 +69,7 @@ function AppContent() {
} = useDisclosure();
return (
- <WsClientProvider
- enabled
- ghToken={gitHubToken}
- selectedRepository={selectedRepository}
- conversationId={conversationId}
- >
+ <WsClientProvider ghToken={gitHubToken} conversationId={conversationId}>
<EventHandler>
<div className="flex flex-col h-full gap-3">
<div className="flex h-full overflow-auto gap-3">
diff --git a/frontend/src/routes/_oh/route.tsx b/frontend/src/routes/_oh/route.tsx
index 27058be55c..1d07cbcaf7 100644
--- a/frontend/src/routes/_oh/route.tsx
+++ b/frontend/src/routes/_oh/route.tsx
@@ -44,7 +44,7 @@ export function ErrorBoundary() {
}
export default function MainApp() {
- const { gitHubToken, clearToken } = useAuth();
+ const { gitHubToken } = useAuth();
const { settings, settingsAreUpToDate } = useUserPrefs();
const [consentFormIsOpen, setConsentFormIsOpen] = React.useState(
@@ -55,11 +55,7 @@ export default function MainApp() {
React.useState(!settingsAreUpToDate);
const config = useConfig();
- const {
- data: isAuthed,
- isFetched,
- isFetching: isFetchingAuth,
- } = useIsAuthed();
+ const { data: isAuthed, isFetching: isFetchingAuth } = useIsAuthed();
const gitHubAuthUrl = useGitHubAuthUrl({
gitHubToken,
@@ -67,10 +63,6 @@ export default function MainApp() {
gitHubClientId: config.data?.GITHUB_CLIENT_ID || null,
});
- React.useEffect(() => {
- if (isFetched && !isAuthed) clearToken();
- }, [isFetched, isAuthed]);
-
React.useEffect(() => {
if (settings.LANGUAGE) {
i18n.changeLanguage(settings.LANGUAGE);
diff --git a/frontend/src/services/agent-state-service.ts b/frontend/src/services/agent-state-service.ts
index 30a7b7665e..c7624fa643 100644
--- a/frontend/src/services/agent-state-service.ts
+++ b/frontend/src/services/agent-state-service.ts
@@ -1,5 +1,5 @@
import ActionType from "#/types/action-type";
-import AgentState from "#/types/agent-state";
+import { AgentState } from "#/types/agent-state";
export const generateAgentStateChangeEvent = (state: AgentState) => ({
action: ActionType.CHANGE_AGENT_STATE,
diff --git a/frontend/src/services/auth.ts b/frontend/src/services/auth.ts
deleted file mode 100644
index 65d50ab2c5..0000000000
--- a/frontend/src/services/auth.ts
+++ /dev/null
@@ -1,5 +0,0 @@
-const TOKEN_KEY = "token";
-const GITHUB_TOKEN_KEY = "ghToken";
-
-export const getToken = () => localStorage.getItem(TOKEN_KEY);
-export const getGitHubToken = () => localStorage.getItem(GITHUB_TOKEN_KEY);
diff --git a/frontend/src/services/observations.ts b/frontend/src/services/observations.ts
index 83b72b42ae..f2f1de60c4 100644
--- a/frontend/src/services/observations.ts
+++ b/frontend/src/services/observations.ts
@@ -2,7 +2,7 @@ import { setCurrentAgentState } from "#/state/agent-slice";
import { setUrl, setScreenshotSrc } from "#/state/browser-slice";
import store from "#/store";
import { ObservationMessage } from "#/types/message";
-import AgentState from "#/types/agent-state";
+import { AgentState } from "#/types/agent-state";
import { appendOutput } from "#/state/command-slice";
import { appendJupyterOutput } from "#/state/jupyter-slice";
import ObservationType from "#/types/observation-type";
diff --git a/frontend/src/state/agent-slice.tsx b/frontend/src/state/agent-slice.tsx
index ab49af0d1d..24d2ccb364 100644
--- a/frontend/src/state/agent-slice.tsx
+++ b/frontend/src/state/agent-slice.tsx
@@ -1,5 +1,5 @@
import { createSlice } from "@reduxjs/toolkit";
-import AgentState from "#/types/agent-state";
+import { AgentState } from "#/types/agent-state";
export const agentSlice = createSlice({
name: "agent",
diff --git a/frontend/src/types/agent-state.tsx b/frontend/src/types/agent-state.tsx
index d2751627df..74988e4ef3 100644
--- a/frontend/src/types/agent-state.tsx
+++ b/frontend/src/types/agent-state.tsx
@@ -1,4 +1,4 @@
-enum AgentState {
+export enum AgentState {
LOADING = "loading",
INIT = "init",
RUNNING = "running",
@@ -13,4 +13,8 @@ enum AgentState {
USER_REJECTED = "user_rejected",
}
-export default AgentState;
+export const RUNTIME_INACTIVE_STATES = [
+ AgentState.LOADING,
+ AgentState.STOPPED,
+ AgentState.ERROR,
+];
diff --git a/frontend/src/types/core/observations.ts b/frontend/src/types/core/observations.ts
index a1afb72542..9a020d9365 100644
--- a/frontend/src/types/core/observations.ts
+++ b/frontend/src/types/core/observations.ts
@@ -1,4 +1,4 @@
-import AgentState from "../agent-state";
+import { AgentState } from "../agent-state";
import { OpenHandsObservationEvent } from "./base";
export interface AgentStateChangeObservation
diff --git a/openhands/server/listen_socket.py b/openhands/server/listen_socket.py
index fe2ddff723..8943484ad2 100644
--- a/openhands/server/listen_socket.py
+++ b/openhands/server/listen_socket.py
@@ -69,12 +69,10 @@ async def connect(connection_id: str, environ, auth):
):
continue
elif isinstance(event, AgentStateChangedObservation):
- if event.agent_state == 'init':
- await sio.emit('oh_event', event_to_dict(event), to=connection_id)
- else:
- agent_state_changed = event
- continue
+ agent_state_changed = event
+ continue
await sio.emit('oh_event', event_to_dict(event), to=connection_id)
+
if agent_state_changed:
await sio.emit('oh_event', event_to_dict(agent_state_changed), to=connection_id)