Skip to content

🙌 OpenHands: AI-Driven Development

Refactor: Enhance file handling and code editing functionality (#2646)

PierrunoYTbfa1de4a6b18
diff --git a/frontend/src/components/CodeEditor.tsx b/frontend/src/components/CodeEditor.tsx
deleted file mode 100644
index a14b8650fd..0000000000
--- a/frontend/src/components/CodeEditor.tsx
+++ /dev/null
@@ -1,82 +0,0 @@
-import Editor, { Monaco } from "@monaco-editor/react";
-import { Tab, Tabs } from "@nextui-org/react";
-import type { editor } from "monaco-editor";
-import React, { useMemo } from "react";
-import { useTranslation } from "react-i18next";
-import { VscCode } from "react-icons/vsc";
-import { useSelector } from "react-redux";
-import { I18nKey } from "#/i18n/declaration";
-import { RootState } from "#/store";
-import FileExplorer from "./file-explorer/FileExplorer";
-
-function CodeEditor(): JSX.Element {
- const { t } = useTranslation();
- const code = useSelector((state: RootState) => state.code.code);
- const activeFilepath = useSelector((state: RootState) => state.code.path);
-
- const selectedFileName = useMemo(() => {
- const paths = activeFilepath.split("/");
- return paths[paths.length - 1];
- }, [activeFilepath]);
-
- const handleEditorDidMount = (
- editor: editor.IStandaloneCodeEditor,
- monaco: Monaco,
- ) => {
- // 定义一个自定义主题 - English: Define a custom theme
- monaco.editor.defineTheme("my-theme", {
- base: "vs-dark",
- inherit: true,
- rules: [],
- colors: {
- "editor.background": "#171717",
- },
- });
-
- // 应用自定义主题 - English: apply custom theme
- monaco.editor.setTheme("my-theme");
- };
-
- return (
- <div className="flex h-full w-full bg-neutral-900 transition-all duration-500 ease-in-out">
- <FileExplorer />
- <div className="flex flex-col min-h-0 w-full">
- <Tabs
- disableCursorAnimation
- classNames={{
- base: "border-b border-divider border-neutral-600 mb-4",
- tabList:
- "w-full relative rounded-none bg-neutral-900 p-0 border-divider",
- cursor: "w-full bg-neutral-600 rounded-none",
- tab: "max-w-fit px-4 h-[36px]",
- tabContent: "group-data-[selected=true]:text-white",
- }}
- aria-label="Options"
- >
- <Tab
- key={selectedFileName.toLocaleLowerCase()}
- title={selectedFileName}
- />
- </Tabs>
- <div className="flex grow items-center justify-center">
- {selectedFileName === "" ? (
- <div className="flex flex-col items-center text-neutral-400">
- <VscCode size={100} />
- {t(I18nKey.CODE_EDITOR$EMPTY_MESSAGE)}
- </div>
- ) : (
- <Editor
- height="100%"
- path={selectedFileName.toLocaleLowerCase()}
- defaultValue=""
- value={code}
- onMount={handleEditorDidMount}
- />
- )}
- </div>
- </div>
- </div>
- );
-}
-
-export default CodeEditor;
diff --git a/frontend/src/components/Workspace.tsx b/frontend/src/components/Workspace.tsx
index c387299426..4d4d5ecf5c 100644
--- a/frontend/src/components/Workspace.tsx
+++ b/frontend/src/components/Workspace.tsx
@@ -10,7 +10,7 @@ import { initialState as initialCodeState } from "#/state/codeSlice";
import { RootState } from "#/store";
import { TabOption, TabType } from "#/types/TabOption";
import Browser from "./Browser";
-import CodeEditor from "./CodeEditor";
+import CodeEditor from "./file-explorer/CodeEditor";
import Planner from "./Planner";
import Jupyter from "./Jupyter";
import { getSettings } from "#/services/settings";
diff --git a/frontend/src/components/file-explorer/CodeEditor.tsx b/frontend/src/components/file-explorer/CodeEditor.tsx
new file mode 100644
index 0000000000..b7096d48c0
--- /dev/null
+++ b/frontend/src/components/file-explorer/CodeEditor.tsx
@@ -0,0 +1,199 @@
+import React, { useMemo, useState, useCallback, useEffect } from "react";
+import { useTranslation } from "react-i18next";
+import { useDispatch, useSelector } from "react-redux";
+import Editor, { Monaco } from "@monaco-editor/react";
+import { Tab, Tabs, Button } from "@nextui-org/react";
+import { VscCode, VscSave, VscCheck } from "react-icons/vsc";
+import type { editor } from "monaco-editor";
+import { I18nKey } from "#/i18n/declaration";
+import { RootState } from "#/store";
+import FileExplorer from "./FileExplorer";
+import { setCode } from "#/state/codeSlice";
+import toast from "#/utils/toast";
+import { saveFile } from "#/services/fileService";
+import AgentState from "#/types/AgentState";
+
+function CodeEditor(): JSX.Element {
+ const { t } = useTranslation();
+ const dispatch = useDispatch();
+ const code = useSelector((state: RootState) => state.code.code);
+ const activeFilepath = useSelector((state: RootState) => state.code.path);
+ const agentState = useSelector(
+ (state: RootState) => state.agent.curAgentState,
+ );
+ const [saveStatus, setSaveStatus] = useState<
+ "idle" | "saving" | "saved" | "error"
+ >("idle");
+ const [showSaveNotification, setShowSaveNotification] = useState(false);
+ const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false);
+ const [lastSavedContent, setLastSavedContent] = useState(code);
+
+ const selectedFileName = useMemo(() => {
+ const paths = activeFilepath.split("/");
+ return paths[paths.length - 1];
+ }, [activeFilepath]);
+
+ const isEditingAllowed = useMemo(
+ () =>
+ agentState === AgentState.INIT ||
+ agentState === AgentState.PAUSED ||
+ agentState === AgentState.FINISHED ||
+ agentState === AgentState.AWAITING_USER_INPUT,
+ [agentState],
+ );
+
+ useEffect(() => {
+ setSaveStatus("idle");
+ setHasUnsavedChanges(false);
+ setLastSavedContent(code);
+ }, [activeFilepath]);
+
+ useEffect(() => {
+ setHasUnsavedChanges(code !== lastSavedContent);
+ }, [code, lastSavedContent]);
+
+ const handleEditorChange = useCallback(
+ (value: string | undefined): void => {
+ if (value !== undefined && isEditingAllowed) {
+ dispatch(setCode(value));
+ setHasUnsavedChanges(true);
+ }
+ },
+ [dispatch, isEditingAllowed],
+ );
+
+ const handleEditorDidMount = useCallback(
+ (editor: editor.IStandaloneCodeEditor, monaco: Monaco): void => {
+ monaco.editor.defineTheme("my-theme", {
+ base: "vs-dark",
+ inherit: true,
+ rules: [],
+ colors: {
+ "editor.background": "#171717",
+ },
+ });
+
+ monaco.editor.setTheme("my-theme");
+ },
+ [],
+ );
+
+ const handleSave = useCallback(async (): Promise<void> => {
+ if (saveStatus === "saving" || !isEditingAllowed) return;
+
+ setSaveStatus("saving");
+
+ try {
+ await saveFile(activeFilepath, code);
+ setSaveStatus("saved");
+ setShowSaveNotification(true);
+ setLastSavedContent(code);
+ setHasUnsavedChanges(false);
+ setTimeout(() => setShowSaveNotification(false), 2000);
+ toast.success(
+ "file-save-success",
+ t(I18nKey.CODE_EDITOR$FILE_SAVED_SUCCESSFULLY),
+ );
+ } catch (error) {
+ setSaveStatus("error");
+ if (error instanceof Error) {
+ toast.error(
+ "file-save-error",
+ `${t(I18nKey.CODE_EDITOR$FILE_SAVE_ERROR)}: ${error.message}`,
+ );
+ } else {
+ toast.error("file-save-error", t(I18nKey.CODE_EDITOR$FILE_SAVE_ERROR));
+ }
+ }
+ }, [
+ saveStatus,
+ activeFilepath,
+ code,
+ isEditingAllowed,
+ t,
+ hasUnsavedChanges,
+ ]);
+
+ const getSaveButtonColor = () => {
+ switch (saveStatus) {
+ case "saving":
+ return "bg-yellow-600";
+ case "saved":
+ return "bg-green-600";
+ case "error":
+ return "bg-red-600";
+ default:
+ return "bg-blue-600";
+ }
+ };
+
+ return (
+ <div className="flex h-full w-full bg-neutral-900 transition-all duration-500 ease-in-out relative">
+ <FileExplorer />
+ <div className="flex flex-col min-h-0 w-full">
+ <div className="flex justify-between items-center border-b border-neutral-600 mb-4">
+ <Tabs
+ disableCursorAnimation
+ classNames={{
+ base: "w-full",
+ tabList:
+ "w-full relative rounded-none bg-neutral-900 p-0 border-divider",
+ cursor: "w-full bg-neutral-600 rounded-none",
+ tab: "max-w-fit px-4 h-[36px]",
+ tabContent: "group-data-[selected=true]:text-white",
+ }}
+ aria-label={t(I18nKey.CODE_EDITOR$OPTIONS)}
+ >
+ <Tab
+ key={selectedFileName}
+ title={selectedFileName || t(I18nKey.CODE_EDITOR$EMPTY_MESSAGE)}
+ />
+ </Tabs>
+ {selectedFileName && hasUnsavedChanges && (
+ <div className="flex items-center mr-2">
+ <Button
+ onClick={handleSave}
+ className={`${getSaveButtonColor()} text-white transition-colors duration-300 mr-2`}
+ size="sm"
+ startContent={<VscSave />}
+ disabled={saveStatus === "saving" || !isEditingAllowed}
+ >
+ {saveStatus === "saving"
+ ? t(I18nKey.CODE_EDITOR$SAVING_LABEL)
+ : t(I18nKey.CODE_EDITOR$SAVE_LABEL)}
+ </Button>
+ </div>
+ )}
+ </div>
+ <div className="flex grow items-center justify-center">
+ {!selectedFileName ? (
+ <div className="flex flex-col items-center text-neutral-400">
+ <VscCode size={100} />
+ {t(I18nKey.CODE_EDITOR$EMPTY_MESSAGE)}
+ </div>
+ ) : (
+ <Editor
+ height="100%"
+ path={selectedFileName.toLowerCase()}
+ defaultValue=""
+ value={code}
+ onMount={handleEditorDidMount}
+ onChange={handleEditorChange}
+ options={{ readOnly: !isEditingAllowed }}
+ />
+ )}
+ </div>
+ </div>
+ {showSaveNotification && (
+ <div className="absolute bottom-4 left-1/2 transform -translate-x-1/2">
+ <div className="bg-green-500 text-white px-4 py-2 rounded-lg flex items-center justify-center animate-pulse">
+ <VscCheck className="mr-2 text-xl" />
+ <span>{t(I18nKey.CODE_EDITOR$FILE_SAVED_SUCCESSFULLY)}</span>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+}
+
+export default CodeEditor;
diff --git a/frontend/src/components/file-explorer/FileExplorer.tsx b/frontend/src/components/file-explorer/FileExplorer.tsx
index 32508d4a3d..3404193763 100644
--- a/frontend/src/components/file-explorer/FileExplorer.tsx
+++ b/frontend/src/components/file-explorer/FileExplorer.tsx
@@ -244,7 +244,7 @@ function FileExplorer() {
</div>
<div className="overflow-auto flex-grow">
<div style={{ display: isHidden ? "none" : "block" }}>
- <ExplorerTree files={files} defaultOpen />
+ <ExplorerTree files={files} />
</div>
</div>
</div>
diff --git a/frontend/src/i18n/translation.json b/frontend/src/i18n/translation.json
index bcd9bf8676..745fffb97e 100644
--- a/frontend/src/i18n/translation.json
+++ b/frontend/src/i18n/translation.json
@@ -26,6 +26,136 @@
"fr": "Terminal",
"tr": "Terminal"
},
+ "CODE_EDITOR$FILE_SAVED_SUCCESSFULLY": {
+ "en": "File saved successfully",
+ "zh-CN": "文件保存成功",
+ "de": "Datei erfolgreich gespeichert",
+ "ko-KR": "파일이 성공적으로 저장되었습니다",
+ "no": "Fil lagret vellykket",
+ "zh-TW": "檔案儲存成功",
+ "it": "File salvato con successo",
+ "pt": "Arquivo salvo com sucesso",
+ "es": "Archivo guardado exitosamente",
+ "ar": "تم حفظ الملف بنجاح",
+ "fr": "Fichier enregistré avec succès",
+ "tr": "Dosya başarıyla kaydedildi"
+ },
+ "CODE_EDITOR$SAVING_LABEL": {
+ "en": "Saving...",
+ "zh-CN": "保存中...",
+ "de": "Speichern...",
+ "ko-KR": "저장 중...",
+ "no": "Lagrer...",
+ "zh-TW": "保存中...",
+ "it": "Salvataggio in corso...",
+ "pt": "Salvando...",
+ "es": "Guardando...",
+ "ar": "حفظ مؤقت",
+ "fr": "Enregistrement en cours...",
+ "tr": "Kayıt yapılıyor..."
+ },
+ "CODE_EDITOR$SAVE_LABEL": {
+ "en": "Save",
+ "zh-CN": "保存",
+ "de": "Speichern",
+ "ko-KR": "저장",
+ "no": "Lagrer",
+ "zh-TW": "保存",
+ "it": "Salva",
+ "pt": "Salvar",
+ "es": "Guardar",
+ "ar": "حفظ",
+ "fr": "Enregistrer",
+ "tr": "Kayıt"
+ },
+ "CODE_EDITOR$OPTIONS": {
+ "en": "Options",
+ "zh-CN": "选项",
+ "zh-TW": "選項",
+ "de": "Optionen"
+ },
+ "CODE_EDITOR$FILE_SAVE_ERROR": {
+ "en": "An unknown error occurred while saving the file",
+ "zh-CN": "文件保存时发生未知错误",
+ "zh-TW": "文件保存時發生未知錯誤",
+ "de": "Beim Speichern der Datei ist ein unbekannter Fehler aufgetreten"
+ },
+ "CODE_EDITOR$EMPTY_MESSAGE": {
+ "en": "No file selected.",
+ "zh-CN": "文件未选中",
+ "zh-TW": "未選取任何文件。",
+ "de": "Keine Datei ausgewählt."
+ },
+ "FILE_SERVICE$SELECT_FILE_ERROR": {
+ "en": "Error selecting file. Please try again.",
+ "zh-CN": "选择文件时出错。请重试。",
+ "de": "Fehler beim Auswählen der Datei. Bitte versuchen Sie es erneut.",
+ "ko-KR": "파일 선택 중 오류가 발생했습니다. 다시 시도해 주세요.",
+ "no": "Feil ved valg av fil. Vennligst prøv igjen.",
+ "zh-TW": "選擇文件時出錯。請重試。",
+ "it": "Errore durante la selezione del file. Riprova.",
+ "pt": "Erro ao selecionar o arquivo. Por favor, tente novamente.",
+ "es": "Error al seleccionar el archivo. Por favor, inténtelo de nuevo.",
+ "ar": "خطأ في اختيار الملف. يرجى المحاولة مرة أخرى.",
+ "fr": "Erreur lors de la sélection du fichier. Veuillez réessayer.",
+ "tr": "Dosya seçiminde hata oluştu. Lütfen tekrar deneyin."
+ },
+ "FILE_SERVICE$UPLOAD_FILES_ERROR": {
+ "en": "Error uploading files. Please try again.",
+ "zh-CN": "上传文件时出错。请重试。",
+ "de": "Fehler beim Hochladen der Dateien. Bitte versuchen Sie es erneut.",
+ "ko-KR": "파일 업로드 중 오류가 발생했습니다. 다시 시도해 주세요.",
+ "no": "Feil ved opplasting av filer. Vennligst prøv igjen.",
+ "zh-TW": "上傳文件時出錯。請重試。",
+ "it": "Errore durante il caricamento dei file. Riprova.",
+ "pt": "Erro ao fazer upload dos arquivos. Por favor, tente novamente.",
+ "es": "Error al subir los archivos. Por favor, inténtelo de nuevo.",
+ "ar": "خطأ في تحميل الملفات. يرجى المحاولة مرة أخرى.",
+ "fr": "Erreur lors du téléchargement des fichiers. Veuillez réessayer.",
+ "tr": "Dosyalar yüklenirken hata oluştu. Lütfen tekrar deneyin."
+ },
+ "FILE_SERVICE$LIST_FILES_ERROR": {
+ "en": "Error listing files. Please try again.",
+ "zh-CN": "列出文件时出错。请重试。",
+ "de": "Fehler beim Auflisten der Dateien. Bitte versuchen Sie es erneut.",
+ "ko-KR": "파일 목록을 가져오는 중 오류가 발생했습니다. 다시 시도해 주세요.",
+ "no": "Feil ved listing av filer. Vennligst prøv igjen.",
+ "zh-TW": "列出文件時出錯。請重試。",
+ "it": "Errore durante l'elenco dei file. Riprova.",
+ "pt": "Erro ao listar arquivos. Por favor, tente novamente.",
+ "es": "Error al listar los archivos. Por favor, inténtelo de nuevo.",
+ "ar": "خطأ في سرد الملفات. يرجى المحاولة مرة أخرى.",
+ "fr": "Erreur lors de la liste des fichiers. Veuillez réessayer.",
+ "tr": "Dosyalar listelenirken hata oluştu. Lütfen tekrar deneyin."
+ },
+ "FILE_SERVICE$SAVE_FILE_ERROR": {
+ "en": "Error saving file. Please try again.",
+ "zh-CN": "保存文件时出错。请重试。",
+ "de": "Fehler beim Speichern der Datei. Bitte versuchen Sie es erneut.",
+ "ko-KR": "파일 저장 중 오류가 발생했습니다. 다시 시도해 주세요.",
+ "no": "Feil ved lagring av fil. Vennligst prøv igjen.",
+ "zh-TW": "保存文件時出錯。請重試。",
+ "it": "Errore durante il salvataggio del file. Riprova.",
+ "pt": "Erro ao salvar o arquivo. Por favor, tente novamente.",
+ "es": "Error al guardar el archivo. Por favor, inténtelo de nuevo.",
+ "ar": "خطأ في حفظ الملف. يرجى المحاولة مرة أخرى.",
+ "fr": "Erreur lors de l'enregistrement du fichier. Veuillez réessayer.",
+ "tr": "Dosya kaydedilirken hata oluştu. Lütfen tekrar deneyin."
+ },
+ "FILE_SERVICE$INVALID_FILE_PATH": {
+ "en": "Invalid file path. Please check the file name and try again.",
+ "zh-CN": "文件路径无效。请检查文件名并重试。",
+ "de": "Ungültiger Dateipfad. Bitte überprüfen Sie den Dateinamen und versuchen Sie es erneut.",
+ "ko-KR": "잘못된 파일 경로입니다. 파일 이름을 확인하고 다시 시도해 주세요.",
+ "no": "Ugyldig filbane. Vennligst sjekk filnavnet og prøv igjen.",
+ "zh-TW": "文件路徑無效。請檢查文件名並重試。",
+ "it": "Percorso del file non valido. Controlla il nome del file e riprova.",
+ "pt": "Caminho de arquivo inválido. Por favor, verifique o nome do arquivo e tente novamente.",
+ "es": "Ruta de archivo inválida. Por favor, verifique el nombre del archivo e inténtelo de nuevo.",
+ "ar": "مسار الملف غير صالح. يرجى التحقق من اسم الملف والمحاولة مرة أخرى.",
+ "fr": "Chemin de fichier invalide. Veuillez vérifier le nom du fichier et réessayer.",
+ "tr": "Geçersiz dosya yolu. Lütfen dosya adını kontrol edin ve tekrar deneyin."
+ },
"WORKSPACE$PLANNER_TAB_LABEL": {
"en": "Planner",
"zh-CN": "规划器",
@@ -551,12 +681,6 @@
"zh-TW": "輸入您的 API 金鑰。",
"de": "Modell API Schlüssel."
},
- "CODE_EDITOR$EMPTY_MESSAGE": {
- "en": "No file selected.",
- "zh-CN": "文件未选中",
- "zh-TW": "未選取任何文件。",
- "de": "Keine Datei ausgewählt."
- },
"BROWSER$EMPTY_MESSAGE": {
"en": "No page loaded.",
"zh-CN": "页面未加载",
diff --git a/frontend/src/services/fileService.ts b/frontend/src/services/fileService.ts
index d8933e02df..bdbae8991e 100644
--- a/frontend/src/services/fileService.ts
+++ b/frontend/src/services/fileService.ts
@@ -1,5 +1,9 @@
+import i18next from "i18next";
+import { I18nKey } from "#/i18n/declaration";
import { request } from "./api";
+const translate = (key: I18nKey) => i18next.t(key);
+
export async function selectFile(file: string): Promise<string> {
const encodedFile = encodeURIComponent(file);
const data = await request(`/api/select-file?file=${encodedFile}`);
@@ -64,11 +68,28 @@ export async function uploadFiles(files: FileList): Promise<UploadResult> {
}
export async function listFiles(path: string = "/"): Promise<string[]> {
- try {
- const encodedPath = encodeURIComponent(path);
- const data = await request(`/api/list-files?path=${encodedPath}`);
- return data as string[];
- } catch (error) {
- return [];
+ const data = await request(
+ `/api/list-files?path=${encodeURIComponent(path)}`,
+ );
+ if (!Array.isArray(data)) {
+ throw new Error("Invalid response format: data is not an array");
+ }
+ return data;
+}
+
+export async function saveFile(
+ filePath: string,
+ content: string,
+): Promise<void> {
+ if (!filePath || filePath.includes("..")) {
+ throw new Error(translate(I18nKey.FILE_SERVICE$INVALID_FILE_PATH));
}
+
+ await request("/api/save-file", {
+ method: "POST",
+ body: JSON.stringify({ filePath, content }),
+ headers: {
+ "Content-Type": "application/json",
+ },
+ });
}
diff --git a/frontend/src/utils/beep.tsx b/frontend/src/utils/beep.tsx
index 0323db8a6e..3fc726ef14 100644
--- a/frontend/src/utils/beep.tsx
+++ b/frontend/src/utils/beep.tsx
@@ -1,9 +1,6 @@
const beep = () => {
const snd = new Audio("/beep.wav");
snd.addEventListener("canplaythrough", () => snd.play());
- snd.addEventListener("error", (e) =>
- console.error("Audio file could not be loaded", e),
- );
};
export default beep;
diff --git a/opendevin/server/listen.py b/opendevin/server/listen.py
index 265049ed78..e0ab17de6d 100644
--- a/opendevin/server/listen.py
+++ b/opendevin/server/listen.py
@@ -12,7 +12,15 @@ with warnings.catch_warnings():
warnings.simplefilter('ignore')
import litellm
-from fastapi import FastAPI, Request, Response, UploadFile, WebSocket, status
+from fastapi import (
+ FastAPI,
+ HTTPException,
+ Request,
+ Response,
+ UploadFile,
+ WebSocket,
+ status,
+)
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from fastapi.security import HTTPBearer
@@ -22,6 +30,7 @@ import agenthub # noqa F401 (we import this to get the agents registered)
from opendevin.controller.agent import Agent
from opendevin.core.config import config
from opendevin.core.logger import opendevin_logger as logger
+from opendevin.core.schema import AgentState # Add this import
from opendevin.events.action import ChangeAgentStateAction, NullAction
from opendevin.events.observation import (
AgentStateChangedObservation,
@@ -67,13 +76,12 @@ def load_file_upload_config() -> tuple[int, bool, list[str]]:
restrict_file_types = config.file_uploads_restrict_file_types
allowed_extensions = config.file_uploads_allowed_extensions
- max_file_size_mb = (
- max_file_size_mb
- if (isinstance(max_file_size_mb, int) and max_file_size_mb >= 0)
- else 0
- )
- if max_file_size_mb == 0:
- logger.warning('Using unlimited (0) file size for uploads.')
+ # Sanity check for max_file_size_mb
+ if not isinstance(max_file_size_mb, int) or max_file_size_mb < 0:
+ logger.warning(
+ f'Invalid max_file_size_mb: {max_file_size_mb}. Setting to 0 (no limit).'
+ )
+ max_file_size_mb = 0
# Sanity check for allowed_extensions
if not isinstance(allowed_extensions, (list, set)) or not allowed_extensions:
@@ -92,7 +100,7 @@ def load_file_upload_config() -> tuple[int, bool, list[str]]:
if not restrict_file_types:
allowed_extensions = ['.*']
- logger.info(
+ logger.debug(
f'File upload config: max_size={max_file_size_mb}MB, '
f'restrict_types={restrict_file_types}, '
f'allowed_extensions={allowed_extensions}'
@@ -131,6 +139,19 @@ def is_extension_allowed(filename):
@app.middleware('http')
async def attach_session(request: Request, call_next):
+ """
+ Middleware to attach session information to the request.
+
+ This middleware checks for the Authorization header, validates the token,
+ and attaches the corresponding session to the request state.
+
+ Args:
+ request (Request): The incoming request object.
+ call_next (Callable): The next middleware or route handler in the chain.
+
+ Returns:
+ Response: The response from the next middleware or route handler.
+ """
if request.url.path.startswith('/api/options/') or not request.url.path.startswith(
'/api/'
):
@@ -138,11 +159,10 @@ async def attach_session(request: Request, call_next):
return response
if not request.headers.get('Authorization'):
- response = JSONResponse(
+ return JSONResponse(
status_code=status.HTTP_401_UNAUTHORIZED,
content={'error': 'Missing Authorization header'},
)
- return response
auth_token = request.headers.get('Authorization')
if 'Bearer' in auth_token:
@@ -150,35 +170,34 @@ async def attach_session(request: Request, call_next):
request.state.sid = get_sid_from_token(auth_token)
if request.state.sid == '':
- response = JSONResponse(
+ return JSONResponse(
status_code=status.HTTP_401_UNAUTHORIZED,
content={'error': 'Invalid token'},
)
- return response
request.state.session = session_manager.get_session(request.state.sid)
if request.state.session is None:
- response = JSONResponse(
+ return JSONResponse(
status_code=status.HTTP_404_NOT_FOUND,
content={'error': 'Session not found'},
)
- return response
response = await call_next(request)
return response
-# This endpoint receives events from the client (i.e. the browser)
@app.websocket('/ws')
async def websocket_endpoint(websocket: WebSocket):
"""
WebSocket endpoint for receiving events from the client (i.e., the browser).
-
Once connected, you can send various actions:
- Initialize the agent:
+ session management, and event streaming.
```json
{"action": "initialize", "args": {"LLM_MODEL": "ollama/llama3", "AGENT": "CodeActAgent", "LANGUAGE": "en", "LLM_API_KEY": "ollama"}}
+ Args:
```
+ websocket (WebSocket): The WebSocket connection object.
- Start a new development task:
```json
{"action": "start", "args": {"task": "write a bash script that prints hello"}}
@@ -256,10 +275,14 @@ async def websocket_endpoint(websocket: WebSocket):
for event in session.agent_session.event_stream.get_events(
start_id=latest_event_id + 1
):
- if isinstance(event, NullAction) or isinstance(event, NullObservation):
- continue
- if isinstance(event, ChangeAgentStateAction) or isinstance(
- event, AgentStateChangedObservation
+ if isinstance(
+ event,
+ (
+ NullAction,
+ NullObservation,
+ ChangeAgentStateAction,
+ AgentStateChangedObservation,
+ ),
):
continue
await websocket.send_json(event_to_dict(event))
@@ -272,10 +295,16 @@ async def get_litellm_models():
"""
Get all models supported by LiteLLM.
+ This function combines models from litellm and Bedrock, removing any
+ error-prone Bedrock models.
+
To get the models:
```sh
curl http://localhost:3000/api/litellm-models
```
+
+ Returns:
+ list: A sorted list of unique model names.
"""
litellm_model_list = litellm.model_list + list(litellm.model_cost.keys())
litellm_model_list_without_bedrock = bedrock.remove_error_modelId(
@@ -296,6 +325,9 @@ async def get_agents():
```sh
curl http://localhost:3000/api/agents
```
+
+ Returns:
+ list: A sorted list of agent names.
"""
agents = sorted(Agent.list_agents())
return agents
@@ -304,12 +336,25 @@ async def get_agents():
@app.get('/api/list-files')
def list_files(request: Request, path: str = '/'):
"""
- List files.
+ List files in the specified path.
+
+ This function retrieves a list of files from the agent's runtime file store,
+ excluding certain system and hidden files/directories.
To list files:
```sh
curl http://localhost:3000/api/list-files
```
+
+ Args:
+ request (Request): The incoming request object.
+ path (str, optional): The path to list files from. Defaults to '/'.
+
+ Returns:
+ list: A list of file names in the specified path.
+
+ Raises:
+ HTTPException: If there's an error listing the files.
"""
if not request.state.session.agent_session.runtime:
return JSONResponse(
@@ -401,12 +446,22 @@ def list_files(request: Request, path: str = '/'):
@app.get('/api/select-file')
def select_file(file: str, request: Request):
"""
- Select a file.
+ Retrieve the content of a specified file.
To select a file:
```sh
curl http://localhost:3000/api/select-file?file=<file_path>
```
+
+ Args:
+ file (str): The path of the file to be retrieved.
+ request (Request): The incoming request object.
+
+ Returns:
+ dict: A dictionary containing the file content.
+
+ Raises:
+ HTTPException: If there's an error opening the file.
"""
try:
content = request.state.session.agent_session.runtime.file_store.read(file)
@@ -439,12 +494,22 @@ def sanitize_filename(filename):
@app.post('/api/upload-files')
async def upload_file(request: Request, files: list[UploadFile]):
"""
- Upload files to the workspace.
+ Upload a list of files to the workspace.
- To upload files:
+ To upload a files:
```sh
curl -X POST -F "file=@<file_path1>" -F "file=@<file_path2>" http://localhost:3000/api/upload-files
```
+
+ Args:
+ request (Request): The incoming request object.
+ files (list[UploadFile]): A list of files to be uploaded.
+
+ Returns:
+ dict: A message indicating the success of the upload operation.
+
+ Raises:
+ HTTPException: If there's an error saving the files.
"""
try:
uploaded_files = []
@@ -508,12 +573,24 @@ async def upload_file(request: Request, files: list[UploadFile]):
@app.post('/api/submit-feedback')
async def submit_feedback(request: Request, feedback: FeedbackDataModel):
"""
- Upload feedback data to the feedback site.
+ Submit user feedback.
+
+ This function stores the provided feedback data.
- To upload files:
+ To submit feedback:
```sh
curl -X POST -F "[email protected]" -F "token=abc" -F "feedback=positive" -F "permissions=private" -F "trajectory={}" http://localhost:3000/api/submit-feedback
```
+
+ Args:
+ request (Request): The incoming request object.
+ feedback (FeedbackDataModel): The feedback data to be stored.
+
+ Returns:
+ dict: The stored feedback data.
+
+ Raises:
+ HTTPException: If there's an error submitting the feedback.
"""
# Assuming the storage service is already configured in the backend
# and there is a function to handle the storage.
@@ -530,12 +607,21 @@ async def submit_feedback(request: Request, feedback: FeedbackDataModel):
@app.get('/api/root_task')
def get_root_task(request: Request):
"""
- Get root_task.
+ Retrieve the root task of the current agent session.
To get the root_task:
```sh
curl -H "Authorization: Bearer <TOKEN>" http://localhost:3000/api/root_task
```
+
+ Args:
+ request (Request): The incoming request object.
+
+ Returns:
+ dict: The root task data if available.
+
+ Raises:
+ HTTPException: If the root task is not available.
"""
controller = request.state.session.agent_session.controller
if controller is not None:
@@ -551,14 +637,77 @@ def get_root_task(request: Request):
@app.get('/api/defaults')
async def appconfig_defaults():
"""
- Get default configurations.
+ Retrieve the default configuration settings.
To get the default configurations:
```sh
curl http://localhost:3000/api/defaults
```
+
+ Returns:
+ dict: The default configuration settings.
"""
return config.defaults_dict
[email protected]('/api/save-file')
+async def save_file(request: Request):
+ """
+ Save a file to the agent's runtime file store.
+
+ This endpoint allows saving a file when the agent is in a paused, finished,
+ or awaiting user input state. It checks the agent's state before proceeding
+ with the file save operation.
+
+ Args:
+ request (Request): The incoming FastAPI request object.
+
+ Returns:
+ JSONResponse: A JSON response indicating the success of the operation.
+
+ Raises:
+ HTTPException:
+ - 403 error if the agent is not in an allowed state for editing.
+ - 400 error if the file path or content is missing.
+ - 500 error if there's an unexpected error during the save operation.
+ """
+ try:
+ # Get the agent's current state
+ controller = request.state.session.agent_session.controller
+ agent_state = controller.get_agent_state()
+
+ # Check if the agent is in an allowed state for editing
+ if agent_state not in [
+ AgentState.INIT,
+ AgentState.PAUSED,
+ AgentState.FINISHED,
+ AgentState.AWAITING_USER_INPUT,
+ ]:
+ raise HTTPException(
+ status_code=403,
+ detail='Code editing is only allowed when the agent is paused, finished, or awaiting user input',
+ )
+
+ # Extract file path and content from the request
+ data = await request.json()
+ file_path = data.get('filePath')
+ content = data.get('content')
+
+ # Validate the presence of required data
+ if not file_path or content is None:
+ raise HTTPException(status_code=400, detail='Missing filePath or content')
+
+ # Save the file to the agent's runtime file store
+ request.state.session.agent_session.runtime.file_store.write(file_path, content)
+
+ # Return a success response
+ return JSONResponse(
+ status_code=200, content={'message': 'File saved successfully'}
+ )
+ except Exception as e:
+ # Log the error and return a 500 response
+ logger.error(f'Error saving file: {e}', exc_info=True)
+ raise HTTPException(status_code=500, detail=f'Error saving file: {e}')
+
+
app.mount('/', StaticFiles(directory='./frontend/dist', html=True), name='dist')