Skip to content

πŸ™Œ OpenHands: AI-Driven Development

frontend: Remove deprecated V0 conversation APIs (#13963)

Tim O'Farrellfdf5c398fd95
diff --git a/frontend/__tests__/components/features/chat/messages.test.tsx b/frontend/__tests__/components/features/chat/messages.test.tsx
index 194ad1ce46..cfe5008b81 100644
--- a/frontend/__tests__/components/features/chat/messages.test.tsx
+++ b/frontend/__tests__/components/features/chat/messages.test.tsx
@@ -8,8 +8,6 @@ import {
UserMessageAction,
} from "#/types/core/actions";
import { OpenHandsObservation } from "#/types/core/observations";
-import ConversationService from "#/api/conversation-service/conversation-service.api";
-import { Conversation } from "#/api/open-hands.types";
import { useSelectedOrganizationStore } from "#/stores/selected-organization-store";
vi.mock("react-router", async (importOriginal) => ({
@@ -84,23 +82,6 @@ describe("Messages", () => {
});
it("should render a launch to microagent action button on chat messages only if it is a user message", () => {
- const getConversationSpy = vi.spyOn(ConversationService, "getConversation");
- const mockConversation: Conversation = {
- conversation_id: "123",
- title: "Test Conversation",
- status: "RUNNING",
- runtime_status: "STATUS$READY",
- created_at: new Date().toISOString(),
- last_updated_at: new Date().toISOString(),
- selected_branch: null,
- selected_repository: null,
- git_provider: "github",
- session_api_key: null,
- url: null,
- };
-
- getConversationSpy.mockResolvedValue(mockConversation);
-
renderMessages({
messages: [userMessage, assistantMessage],
});
diff --git a/frontend/__tests__/components/features/conversation-panel/conversation-panel.test.tsx b/frontend/__tests__/components/features/conversation-panel/conversation-panel.test.tsx
index cdb60e3319..58243568b4 100644
--- a/frontend/__tests__/components/features/conversation-panel/conversation-panel.test.tsx
+++ b/frontend/__tests__/components/features/conversation-panel/conversation-panel.test.tsx
@@ -367,7 +367,6 @@ describe("ConversationPanel", () => {
// Verify the mutation was called
expect(mockStopConversationMutate).toHaveBeenCalledWith({
conversationId: "1",
- version: "V1",
});
expect(mockStopConversationMutate).toHaveBeenCalledTimes(1);
});
diff --git a/frontend/src/api/conversation-service/conversation-service.api.ts b/frontend/src/api/conversation-service/conversation-service.api.ts
index c48b5475fe..e4a2a77d4e 100644
--- a/frontend/src/api/conversation-service/conversation-service.api.ts
+++ b/frontend/src/api/conversation-service/conversation-service.api.ts
@@ -3,7 +3,6 @@ import {
GetVSCodeUrlResponse,
GetTrajectoryResponse,
FileUploadSuccessResponse,
- Conversation,
} from "../open-hands.types";
import { openHands } from "../open-hands-axios";
import { V1AppConversation } from "./v1-conversation-service.types";
@@ -64,30 +63,6 @@ class ConversationService {
return data;
}
- static async deleteUserConversation(conversationId: string): Promise<void> {
- await openHands.delete(`/api/conversations/${conversationId}`);
- }
-
- static async getConversation(
- conversationId: string,
- ): Promise<Conversation | null> {
- const { data } = await openHands.get<Conversation | null>(
- `/api/conversations/${conversationId}`,
- );
-
- return data;
- }
-
- static async stopConversation(
- conversationId: string,
- ): Promise<Conversation | null> {
- const { data } = await openHands.post<Conversation | null>(
- `/api/conversations/${conversationId}/stop`,
- );
-
- return data;
- }
-
static async getTrajectory(
conversationId: string,
): Promise<GetTrajectoryResponse> {
diff --git a/frontend/src/components/features/conversation-panel/conversation-panel.tsx b/frontend/src/components/features/conversation-panel/conversation-panel.tsx
index faeb2a53eb..03887e292c 100644
--- a/frontend/src/components/features/conversation-panel/conversation-panel.tsx
+++ b/frontend/src/components/features/conversation-panel/conversation-panel.tsx
@@ -42,8 +42,6 @@ export function ConversationPanel({ onClose }: ConversationPanelProps) {
>(null);
const [selectedConversationTitle, setSelectedConversationTitle] =
React.useState<string | null>(null);
- const [selectedConversationVersion, setSelectedConversationVersion] =
- React.useState<"V0" | "V1" | undefined>(undefined);
const [selectedSandboxId, setSelectedSandboxId] = React.useState<
string | null
>(null);
@@ -87,12 +85,10 @@ export function ConversationPanel({ onClose }: ConversationPanelProps) {
const handleStopConversation = (
conversationId: string,
- version?: "V0" | "V1",
sandboxId?: string | null,
) => {
setConfirmStopModalVisible(true);
setSelectedConversationId(conversationId);
- setSelectedConversationVersion(version);
setSelectedSandboxId(sandboxId ?? null);
};
@@ -129,7 +125,6 @@ export function ConversationPanel({ onClose }: ConversationPanelProps) {
if (selectedConversationId) {
pauseConversationSandbox({
conversationId: selectedConversationId,
- version: selectedConversationVersion,
});
}
};
@@ -187,11 +182,7 @@ export function ConversationPanel({ onClose }: ConversationPanelProps) {
handleDeleteProject(conversation.id, conversation.title ?? "")
}
onStop={() =>
- handleStopConversation(
- conversation.id,
- "V1",
- conversation.sandbox_id,
- )
+ handleStopConversation(conversation.id, conversation.sandbox_id)
}
onChangeTitle={(title) =>
handleConversationTitleChange(conversation.id, title)
diff --git a/frontend/src/hooks/mutation/conversation-mutation-utils.ts b/frontend/src/hooks/mutation/conversation-mutation-utils.ts
index 9e176a3712..c4bd80d3ae 100644
--- a/frontend/src/hooks/mutation/conversation-mutation-utils.ts
+++ b/frontend/src/hooks/mutation/conversation-mutation-utils.ts
@@ -1,22 +1,7 @@
import { QueryClient } from "@tanstack/react-query";
-import ConversationService from "#/api/conversation-service/conversation-service.api";
import V1ConversationService from "#/api/conversation-service/v1-conversation-service.api";
import { SandboxService } from "#/api/sandbox-service/sandbox-service.api";
-/**
- * Gets the conversation version from the cache
- */
-export const getConversationVersionFromQueryCache = (
- queryClient: QueryClient,
- conversationId: string,
-): "V0" | "V1" => {
- const conversation = queryClient.getQueryData<{
- conversation_version?: string;
- }>(["user", "conversation", conversationId]);
-
- return conversation?.conversation_version === "V1" ? "V1" : "V0";
-};
-
/**
* Fetches a V1 conversation's sandbox_id and conversation_url
*/
@@ -81,12 +66,6 @@ export const askV1Agent = async (
);
};
-/**
- * Stops a V0 conversation using the legacy API
- */
-export const stopV0Conversation = async (conversationId: string) =>
- ConversationService.stopConversation(conversationId);
-
/**
* Resumes a V1 conversation sandbox by fetching the sandbox_id and resuming it
*/
diff --git a/frontend/src/hooks/mutation/use-delete-conversation.ts b/frontend/src/hooks/mutation/use-delete-conversation.ts
index b28d760e2e..2bbd921f2f 100644
--- a/frontend/src/hooks/mutation/use-delete-conversation.ts
+++ b/frontend/src/hooks/mutation/use-delete-conversation.ts
@@ -1,5 +1,5 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
-import ConversationService from "#/api/conversation-service/conversation-service.api";
+import V1ConversationService from "#/api/conversation-service/v1-conversation-service.api";
import { clearConversationLocalStorage } from "#/utils/conversation-local-storage";
export const useDeleteConversation = () => {
@@ -7,7 +7,7 @@ export const useDeleteConversation = () => {
return useMutation({
mutationFn: (variables: { conversationId: string }) =>
- ConversationService.deleteUserConversation(variables.conversationId),
+ V1ConversationService.deleteConversation(variables.conversationId),
onMutate: async (variables) => {
await queryClient.cancelQueries({ queryKey: ["user", "conversations"] });
const previousConversations = queryClient.getQueryData([
diff --git a/frontend/src/hooks/mutation/use-unified-stop-conversation.ts b/frontend/src/hooks/mutation/use-unified-stop-conversation.ts
index 4ff195cf5a..536a0efb54 100644
--- a/frontend/src/hooks/mutation/use-unified-stop-conversation.ts
+++ b/frontend/src/hooks/mutation/use-unified-stop-conversation.ts
@@ -5,20 +5,14 @@ import { useTranslation } from "react-i18next";
import { TOAST_OPTIONS } from "#/utils/custom-toast-handlers";
import { I18nKey } from "#/i18n/declaration";
import {
- getConversationVersionFromQueryCache,
pauseV1ConversationSandbox,
- stopV0Conversation,
updateConversationSandboxStatusInCache,
} from "./conversation-mutation-utils";
/**
- * Unified hook that automatically routes to the correct pause conversation sandbox
- * implementation based on the conversation version (V0 or V1).
+ * Hook to pause a conversation sandbox.
*
- * This hook checks the cached conversation data to determine the version, then calls
- * the appropriate API directly. Returns a single useMutation instance that all components share.
- *
- * Usage is the same as useStopConversation:
+ * Usage:
* const { mutate: stopConversation } = useUnifiedPauseConversationSandbox();
* stopConversation({ conversationId: "some-id" });
*/
@@ -30,24 +24,8 @@ export const useUnifiedPauseConversationSandbox = () => {
return useMutation({
mutationKey: ["stop-conversation"],
- mutationFn: async (variables: {
- conversationId: string;
- version?: "V0" | "V1";
- }) => {
- // Use provided version or fallback to cache lookup
- const version =
- variables.version ||
- getConversationVersionFromQueryCache(
- queryClient,
- variables.conversationId,
- );
-
- if (version === "V1") {
- return pauseV1ConversationSandbox(variables.conversationId);
- }
-
- return stopV0Conversation(variables.conversationId);
- },
+ mutationFn: async (variables: { conversationId: string }) =>
+ pauseV1ConversationSandbox(variables.conversationId),
onMutate: async () => {
const toastId = toast.loading(
t(I18nKey.TOAST$STOPPING_CONVERSATION),
diff --git a/frontend/src/hooks/use-create-conversation-and-subscribe-multiple.ts b/frontend/src/hooks/use-create-conversation-and-subscribe-multiple.ts
deleted file mode 100644
index 211bde6073..0000000000
--- a/frontend/src/hooks/use-create-conversation-and-subscribe-multiple.ts
+++ /dev/null
@@ -1,193 +0,0 @@
-import React from "react";
-import { useQueries, type Query } from "@tanstack/react-query";
-import toast from "react-hot-toast";
-import { AxiosError } from "axios";
-import { useCreateConversation } from "./mutation/use-create-conversation";
-import { useUserProviders } from "./use-user-providers";
-import { useConversationSubscriptions } from "#/context/conversation-subscriptions-provider";
-import { Provider } from "#/types/settings";
-import { Conversation } from "#/api/open-hands.types";
-import ConversationService from "#/api/conversation-service/conversation-service.api";
-import { renderConversationStartingToast } from "#/components/shared/conversation-toast";
-
-interface ConversationData {
- conversationId: string;
- sessionApiKey: string | null;
- baseUrl: string;
- socketPath: string;
- onEventCallback?: (event: unknown, conversationId: string) => void;
-}
-
-/**
- * Custom hook to create a conversation and subscribe to it, supporting multiple subscriptions.
- * This version waits for conversation status to be "RUNNING" before establishing WebSocket connection.
- * Shows immediate toast feedback and polls conversation status until ready.
- */
-export const useCreateConversationAndSubscribeMultiple = () => {
- const { mutate: createConversation, isPending } = useCreateConversation();
- const { providers } = useUserProviders();
- const {
- subscribeToConversation,
- unsubscribeFromConversation,
- isSubscribedToConversation,
- activeConversationIds,
- } = useConversationSubscriptions();
-
- // Store conversation data immediately after creation
- const [createdConversations, setCreatedConversations] = React.useState<
- Record<string, ConversationData>
- >({});
-
- // Get conversation IDs that need polling
- const conversationIdsToWatch = Object.keys(createdConversations);
-
- // Poll each conversation until it's ready
- const conversationQueries = useQueries({
- queries: conversationIdsToWatch.map((conversationId) => ({
- queryKey: ["conversation-ready-poll", conversationId],
- queryFn: () => ConversationService.getConversation(conversationId),
- enabled: !!conversationId,
- refetchInterval: (query: Query<Conversation | null, AxiosError>) => {
- const status = query.state.data?.status;
- if (status === "STARTING") {
- return 3000; // Poll every 3 seconds while STARTING
- }
- return false; // Stop polling once not STARTING
- },
- retry: false,
- })),
- });
-
- // Extract stable values from queries for dependency array
- const queryStatuses = conversationQueries.map((query) => query.data?.status);
- const queryDataExists = conversationQueries.map((query) => !!query.data);
-
- // Effect to handle subscription when conversations are ready
- React.useEffect(() => {
- conversationQueries.forEach((query, index) => {
- const conversationId = conversationIdsToWatch[index];
- const conversationData = createdConversations[conversationId];
-
- if (!query.data || !conversationData) return;
-
- const { status, url, session_api_key: sessionApiKey } = query.data;
-
- let { baseUrl } = conversationData;
- if (url && !url.startsWith("/")) {
- baseUrl = new URL(url).host;
- }
-
- if (status === "RUNNING") {
- // Conversation is ready - subscribe to WebSocket
- subscribeToConversation({
- conversationId,
- sessionApiKey,
- providersSet: providers as Provider[],
- baseUrl,
- socketPath: conversationData.socketPath,
- onEvent: conversationData.onEventCallback,
- });
-
- // Remove from created conversations (cleanup)
- setCreatedConversations((prev) => {
- const newCreated = { ...prev };
- delete newCreated[conversationId];
- return newCreated;
- });
- } else if (status === "STOPPED") {
- // Dismiss the starting toast
- toast.dismiss(`starting-${conversationId}`);
-
- // Remove from created conversations (cleanup)
- setCreatedConversations((prev) => {
- const newCreated = { ...prev };
- delete newCreated[conversationId];
- return newCreated;
- });
- }
- });
- }, [
- queryStatuses,
- queryDataExists,
- conversationIdsToWatch,
- createdConversations,
- subscribeToConversation,
- providers,
- ]);
-
- const createConversationAndSubscribe = React.useCallback(
- ({
- query,
- conversationInstructions,
- repository,
- onSuccessCallback,
- onEventCallback,
- }: {
- query: string;
- conversationInstructions: string;
- repository: {
- name: string;
- branch?: string;
- gitProvider: Provider;
- };
- onSuccessCallback?: (conversationId: string) => void;
- onEventCallback?: (event: unknown, conversationId: string) => void;
- }) => {
- createConversation(
- {
- query,
- conversationInstructions,
- repository,
- },
- {
- onSuccess: (data) => {
- // Show immediate toast to let user know something is happening
- renderConversationStartingToast(data.conversation_id);
-
- // Call the success callback immediately
- if (onSuccessCallback) {
- onSuccessCallback(data.conversation_id);
- }
-
- // Only handle immediate post-creation tasks here
- let baseUrl = "";
- let socketPath: string;
- if (data?.url && !data.url.startsWith("/")) {
- const u = new URL(data.url);
- baseUrl = u.host;
- const pathBeforeApi =
- u.pathname.split("/api/conversations")[0] || "/";
- socketPath = `${pathBeforeApi.replace(/\/$/, "")}/socket.io`;
- } else {
- baseUrl =
- (import.meta.env.VITE_BACKEND_BASE_URL as string | undefined) ||
- window?.location.host;
- socketPath = "/socket.io";
- }
-
- // Store conversation data for polling and eventual subscription
- setCreatedConversations((prev) => ({
- ...prev,
- [data.conversation_id]: {
- conversationId: data.conversation_id,
- sessionApiKey: data.session_api_key,
- baseUrl,
- socketPath,
- onEventCallback,
- },
- }));
- },
- },
- );
- },
- [createConversation],
- );
-
- return {
- createConversationAndSubscribe,
- unsubscribeFromConversation,
- isSubscribedToConversation,
- activeConversationIds,
- isPending,
- };
-};
diff --git a/openhands/app_server/app_conversation/app_conversation_router.py b/openhands/app_server/app_conversation/app_conversation_router.py
index 157c548fae..2af606250f 100644
--- a/openhands/app_server/app_conversation/app_conversation_router.py
+++ b/openhands/app_server/app_conversation/app_conversation_router.py
@@ -15,6 +15,10 @@ from fastapi import APIRouter, HTTPException, Query, Request, Response, status
from fastapi.responses import JSONResponse, StreamingResponse
from sqlalchemy.ext.asyncio import AsyncSession
+from openhands.agent_server.models import Success
+from openhands.app_server.app_conversation.app_conversation_info_service import (
+ AppConversationInfoService,
+)
from openhands.app_server.app_conversation.app_conversation_models import (
AppConversation,
AppConversationInfo,
@@ -41,6 +45,7 @@ from openhands.app_server.app_conversation.app_conversation_start_task_service i
AppConversationStartTaskService,
)
from openhands.app_server.config import (
+ depends_app_conversation_info_service,
depends_app_conversation_service,
depends_app_conversation_start_task_service,
depends_db_session,
@@ -89,6 +94,7 @@ router = APIRouter(
)
logger = logging.getLogger(__name__)
app_conversation_service_dependency = depends_app_conversation_service()
+app_conversation_info_service_dependency = depends_app_conversation_info_service()
app_conversation_start_task_service_dependency = (
depends_app_conversation_start_task_service()
)
@@ -382,6 +388,105 @@ async def update_app_conversation(
return info
+async def _finalize_sandbox_delete(
+ sandbox_service: SandboxService,
+ app_conversation_info_service: AppConversationInfoService,
+ sandbox_id: str,
+ db_session: AsyncSession,
+ httpx_client: httpx.AsyncClient,
+) -> None:
+ """Delete sandbox if no other conversations reference it, then close connections."""
+ try:
+ conversation_count = (
+ await app_conversation_info_service.count_conversations_by_sandbox_id(
+ sandbox_id
+ )
+ )
+ if conversation_count == 0:
+ await sandbox_service.delete_sandbox(sandbox_id)
+ await db_session.commit()
+ finally:
+ await asyncio.gather(
+ db_session.aclose(),
+ httpx_client.aclose(),
+ )
+
+
[email protected]('/{conversation_id}', responses={404: {'description': 'Item not found'}})
+async def delete_app_conversation(
+ request: Request,
+ conversation_id: str,
+ app_conversation_service: AppConversationService = (
+ app_conversation_service_dependency
+ ),
+ app_conversation_info_service: AppConversationInfoService = (
+ app_conversation_info_service_dependency
+ ),
+ sandbox_service: SandboxService = sandbox_service_dependency,
+ db_session: AsyncSession = db_session_dependency,
+ httpx_client: httpx.AsyncClient = httpx_client_dependency,
+) -> Success:
+ """Delete an app conversation and its associated data.
+
+ This endpoint deletes the conversation and cleans up sandbox resources
+ if no other conversations are using the same sandbox.
+ """
+ try:
+ conversation_uuid = UUID(conversation_id)
+ except ValueError:
+ raise HTTPException(
+ status.HTTP_400_BAD_REQUEST, 'Invalid conversation ID format'
+ )
+
+ # Get conversation info to check if it exists and get sandbox_id
+ app_conversation_info = (
+ await app_conversation_info_service.get_app_conversation_info(conversation_uuid)
+ )
+ if not app_conversation_info:
+ raise HTTPException(status.HTTP_404_NOT_FOUND, 'Conversation not found')
+
+ sandbox_id = app_conversation_info.sandbox_id
+
+ # Check if sandbox is shared with other conversations
+ sandbox_is_shared = False
+ if sandbox_id:
+ conversation_count = (
+ await app_conversation_info_service.count_conversations_by_sandbox_id(
+ sandbox_id
+ )
+ )
+ sandbox_is_shared = conversation_count > 1
+
+ # Delete the conversation (skip agent server DELETE if sandbox is shared)
+ deleted = await app_conversation_service.delete_app_conversation(
+ conversation_uuid,
+ skip_agent_server_delete=sandbox_is_shared,
+ )
+ if not deleted:
+ raise HTTPException(status.HTTP_404_NOT_FOUND, 'Failed to delete conversation')
+
+ # Commit the deletion
+ await db_session.commit()
+
+ # Keep connections open for background task
+ set_db_session_keep_open(request.state, True)
+ set_httpx_client_keep_open(request.state, True)
+
+ # Delete the sandbox in the background if no other conversations reference it
+ if sandbox_id:
+ asyncio.create_task(
+ _finalize_sandbox_delete(
+ sandbox_service,
+ app_conversation_info_service,
+ sandbox_id,
+ db_session,
+ httpx_client,
+ )
+ )
+
+ return Success()
+
+
@router.post('/stream-start')
async def stream_app_conversation_start(
request: AppConversationStartRequest,