(feat) Add button to export trajectory on chat panel (#6378)

This commit is contained in:
Boxuan Li 2025-01-21 06:10:00 -08:00 committed by GitHub
parent 210eeee94a
commit b7f34c3f8d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
11 changed files with 184 additions and 0 deletions

View File

@ -10,6 +10,7 @@ import {
AuthenticateResponse,
Conversation,
ResultSet,
GetTrajectoryResponse,
} from "./open-hands.types";
import { openHands } from "./open-hands-axios";
import { ApiSettings } from "#/services/settings";
@ -354,6 +355,15 @@ class OpenHands {
return response.data.items;
}
static async getTrajectory(
conversationId: string,
): Promise<GetTrajectoryResponse> {
const { data } = await openHands.get<GetTrajectoryResponse>(
`/api/conversations/${conversationId}/trajectory`,
);
return data;
}
}
export default OpenHands;

View File

@ -55,6 +55,11 @@ export interface GetVSCodeUrlResponse {
error?: string;
}
export interface GetTrajectoryResponse {
trajectory: unknown[] | null;
error?: string;
}
export interface AuthenticateResponse {
message?: string;
error?: string;

View File

@ -1,8 +1,11 @@
import { useDispatch, useSelector } from "react-redux";
import toast from "react-hot-toast";
import React from "react";
import posthog from "posthog-js";
import { useParams } from "react-router";
import { convertImageToBase64 } from "#/utils/convert-image-to-base-64";
import { FeedbackActions } from "../feedback/feedback-actions";
import { ExportActions } from "../export/export-actions";
import { createChatMessage } from "#/services/chat-service";
import { InteractiveChatBox } from "./interactive-chat-box";
import { addUserMessage } from "#/state/chat-slice";
@ -19,6 +22,8 @@ import { ActionSuggestions } from "./action-suggestions";
import { ContinueButton } from "#/components/shared/buttons/continue-button";
import { ScrollToBottomButton } from "#/components/shared/buttons/scroll-to-bottom-button";
import { LoadingSpinner } from "#/components/shared/loading-spinner";
import { useGetTrajectory } from "#/hooks/mutation/use-get-trajectory";
import { downloadTrajectory } from "#/utils/download-files";
function getEntryPoint(
hasRepository: boolean | null,
@ -47,6 +52,8 @@ export function ChatInterface() {
const { selectedRepository, importedProjectZip } = useSelector(
(state: RootState) => state.initialQuery,
);
const params = useParams();
const { mutate: getTrajectory } = useGetTrajectory();
const handleSendMessage = async (content: string, files: File[]) => {
if (messages.length === 0) {
@ -90,6 +97,25 @@ export function ChatInterface() {
setFeedbackPolarity(polarity);
};
const onClickExportTrajectoryButton = () => {
if (!params.conversationId) {
toast.error("ConversationId unknown, cannot download trajectory");
return;
}
getTrajectory(params.conversationId, {
onSuccess: async (data) => {
await downloadTrajectory(
params.conversationId ?? "unknown",
data.trajectory,
);
},
onError: (error) => {
toast.error(error.message);
},
});
};
const isWaitingForUserInput =
curAgentState === AgentState.AWAITING_USER_INPUT ||
curAgentState === AgentState.FINISHED;
@ -137,6 +163,9 @@ export function ChatInterface() {
onClickShareFeedbackActionButton("negative")
}
/>
<ExportActions
onExportTrajectory={() => onClickExportTrajectoryButton()}
/>
<div className="absolute left-1/2 transform -translate-x-1/2 bottom-0">
{messages.length > 2 &&

View File

@ -0,0 +1,17 @@
import ExportIcon from "#/icons/export.svg?react";
import { ExportActionButton } from "#/components/shared/buttons/export-action-button";
interface ExportActionsProps {
onExportTrajectory: () => void;
}
export function ExportActions({ onExportTrajectory }: ExportActionsProps) {
return (
<div data-testid="export-actions" className="flex gap-1">
<ExportActionButton
onClick={onExportTrajectory}
icon={<ExportIcon width={15} height={15} />}
/>
</div>
);
}

View File

@ -0,0 +1,17 @@
interface ExportActionButtonProps {
onClick: () => void;
icon: React.ReactNode;
}
export function ExportActionButton({ onClick, icon }: ExportActionButtonProps) {
return (
<button
type="button"
onClick={onClick}
className="button-base p-1 hover:bg-neutral-500"
title="Export trajectory"
>
{icon}
</button>
);
}

View File

@ -0,0 +1,7 @@
import { useMutation } from "@tanstack/react-query";
import OpenHands from "#/api/open-hands";
export const useGetTrajectory = () =>
useMutation({
mutationFn: (cid: string) => OpenHands.getTrajectory(cid),
});

View File

@ -0,0 +1,5 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 15 16" fill="none">
<path
d="M11.875 9.5h-2.5V3.25c0-.16576-.0658-.32473-.1831-.44194-.1172-.11721-.276-.18306-.4419-.18306h-2.5c-.16576 0-.32473.06585-.44194.18306C5.68585 2.92527 5.62 3.08424 5.62 3.25V9.5h-2.5c-.13855 0-.27293.0483-.38002.1367-.10708.0883-.18294.2124-.21493.3508-.03199.1385-.01839.2839.03873.4142.05712.1304.15543.2397.27872.3108l4.375 2.5c.09664.0552.20607.0842.3175.0842.11144 0 .22087-.029.3175-.0842l4.375-2.5c.1233-.0711.2216-.1804.2787-.3108.0571-.1303.0707-.2757.0387-.4142-.032-.1384-.1078-.2625-.2149-.3508-.1071-.0884-.2415-.1367-.38-.1367zM3.75 13.375v1.25c0 .1658.06585.3247.18306.4419.11721.1172.27618.1831.44194.1831h6.25c.1657 0 .3247-.0659.4419-.1831.1172-.1172.1831-.2761.1831-.4419v-1.25c0-.1657-.0659-.3247-.1831-.4419-.1172-.1172-.2762-.1831-.4419-.1831h-6.25c-.16576 0-.32473.0659-.44194.1831C3.81585 13.0503 3.75 13.2093 3.75 13.375z"
fill="white"/>
</svg>

After

Width:  |  Height:  |  Size: 963 B

View File

@ -26,6 +26,18 @@ interface FileSystemDirectoryHandle {
): Promise<FileSystemFileHandle>;
}
interface SaveFilePickerOptions {
suggestedName?: string;
types?: Array<{
description?: string;
accept: Record<string, string[]>;
}>;
excludeAcceptAllOption?: boolean;
}
interface Window {
showDirectoryPicker(): Promise<FileSystemDirectoryHandle>;
showSaveFilePicker(
options?: SaveFilePickerOptions,
): Promise<FileSystemFileHandle>;
}

View File

@ -22,6 +22,13 @@ function isFileSystemAccessSupported(): boolean {
return "showDirectoryPicker" in window;
}
/**
* Checks if the Save File Picker API is supported
*/
function isSaveFilePickerSupported(): boolean {
return "showSaveFilePicker" in window;
}
/**
* Creates subdirectories and returns the final directory handle
*/
@ -162,6 +169,39 @@ async function processBatch(
};
}
export async function downloadTrajectory(
conversationId: string,
data: unknown[] | null,
): Promise<void> {
try {
if (!isSaveFilePickerSupported()) {
throw new Error(
"Your browser doesn't support downloading folders. Please use Chrome, Edge, or another browser that supports the File System Access API.",
);
}
const options = {
suggestedName: `trajectory-${conversationId}.json`,
types: [
{
description: "JSON File",
accept: {
"application/json": [".json"],
},
},
],
};
const handle = await window.showSaveFilePicker(options);
const writable = await handle.createWritable();
await writable.write(JSON.stringify(data, null, 2));
await writable.close();
} catch (error) {
throw new Error(
`Failed to download file: ${error instanceof Error ? error.message : String(error)}`,
);
}
}
/**
* Downloads files from the workspace one by one
* @param initialPath Initial path to start downloading from. If not provided, downloads from root

View File

@ -27,6 +27,7 @@ from openhands.server.routes.manage_conversations import (
from openhands.server.routes.public import app as public_api_router
from openhands.server.routes.security import app as security_api_router
from openhands.server.routes.settings import app as settings_router
from openhands.server.routes.trajectory import app as trajectory_router
from openhands.server.shared import openhands_config, session_manager
from openhands.utils.import_utils import get_impl
@ -69,6 +70,7 @@ app.include_router(conversation_api_router)
app.include_router(manage_conversation_api_router)
app.include_router(settings_router)
app.include_router(github_api_router)
app.include_router(trajectory_router)
AttachConversationMiddlewareImpl = get_impl(
AttachConversationMiddleware, openhands_config.attach_conversation_middleware_path

View File

@ -0,0 +1,40 @@
from fastapi import APIRouter, Request
from fastapi.responses import JSONResponse
from openhands.core.logger import openhands_logger as logger
from openhands.events.serialization import event_to_trajectory
from openhands.events.stream import AsyncEventStreamWrapper
app = APIRouter(prefix='/api/conversations/{conversation_id}')
@app.get('/trajectory')
async def get_trajectory(request: Request):
"""Get trajectory.
This function retrieves the current trajectory and returns it.
Args:
request (Request): The incoming request object.
Returns:
JSONResponse: A JSON response containing the trajectory as a list of
events.
"""
try:
async_stream = AsyncEventStreamWrapper(
request.state.conversation.event_stream, filter_hidden=True
)
trajectory = []
async for event in async_stream:
trajectory.append(event_to_trajectory(event))
return JSONResponse(status_code=200, content={'trajectory': trajectory})
except Exception as e:
logger.error(f'Error getting trajectory: {e}', exc_info=True)
return JSONResponse(
status_code=500,
content={
'trajectory': None,
'error': f'Error getting trajectory: {e}',
},
)