before_code stringlengths 14 465k | reviewer_comment stringlengths 16 64.5k | after_code stringlengths 9 467k | diff_context stringlengths 0 97k | file_path stringlengths 5 226 | comment_line int32 0 26 | language stringclasses 37
values | quality_score float32 0.07 1 | comment_type stringclasses 9
values | comment_length int32 16 64.5k | before_lines int32 1 17.2k | after_lines int32 1 12.1k | is_negative bool 2
classes | pr_title stringlengths 1 308 | pr_number int32 1 299k | repo_name stringclasses 533
values | repo_stars int64 321 419k | repo_language stringclasses 27
values | reviewer_username stringlengths 0 39 | author_username stringlengths 2 39 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
);
if (exists) return t(I18nKey.SETTINGS$MCP_ERROR_URL_DUPLICATE);
return null;
};
const validateEnvFormat = (envString: string): string | null => {
if (!envString.trim()) return null;
const lines = envString.split("\n");
for (let i = 0; i < lines.length; i += 1) {
const trimmed = lin... | I think we should handle i18n for these error messages, maybe you can refer to validate methods above for example. | );
if (exists) return t(I18nKey.SETTINGS$MCP_ERROR_URL_DUPLICATE);
return null;
};
const validateEnvFormat = (envString: string): string | null => {
if (!envString.trim()) return null;
const lines = envString.split("\n");
for (let i = 0; i < lines.length; i += 1) {
const trimmed = lin... | @@ -120,6 +121,22 @@ export function MCPServerForm({
return null;
};
+ const validateTimeout = (timeoutStr: string): string | null => {
+ if (!timeoutStr.trim()) return null; // Optional field
+
+ const timeout = parseInt(timeoutStr.trim(), 10);
+ if (Number.isNaN(timeout)) {
+ return "Timeout ... | frontend/src/components/features/settings/mcp-settings/mcp-server-form.tsx | 26 | TypeScript | 0.571 | suggestion | 114 | 51 | 51 | false | feat: Add configurable timeouts for MCP tool invocations (Good first issues: #10684) | 11,029 | All-Hands-AI/OpenHands | 55,974 | Python | ryanhoangt | tejas-goyal |
import { useCallback, useEffect, RefObject, useRef } from "react";
import { IMessageToSend } from "#/state/conversation-store";
import { useDragResize } from "./use-drag-resize";
// Constants
const DEFAULT_MIN_HEIGHT = 20;
const DEFAULT_MAX_HEIGHT = 120;
const HEIGHT_INCREMENT = 20;
const MANUAL_OVERSIZE_THRESHOLD = 5... | **suggestion:** It is recommended to use a more descriptive variable name, such as elementHeight, to enhance code readability and maintainability. | import { useCallback, useEffect, RefObject, useRef } from "react";
import { IMessageToSend } from "#/state/conversation-store";
import { EPS } from "#/utils/constants";
import { getStyleHeightPx, setStyleHeightPx } from "#/utils/utils";
import { useDragResize } from "./use-drag-resize";
// Constants
const DEFAULT_MIN_... | @@ -8,6 +8,27 @@ const DEFAULT_MAX_HEIGHT = 120;
const HEIGHT_INCREMENT = 20;
const MANUAL_OVERSIZE_THRESHOLD = 50;
+const EPS = 1.5; // px tolerance for "near min"
+
+const getStyleHeightPx = (el: HTMLElement, fallback: number) => {
+ const h = parseFloat(el.style.height || "");
+ return Number.isFinite(h) ? h :... | frontend/src/hooks/use-auto-resize.ts | 15 | TypeScript | 0.429 | suggestion | 146 | 40 | 40 | false | fix(frontend): Fixed prompt box resizing behavior (fixes #11025) | 11,035 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | patilatharv |
import { useCallback, useEffect, RefObject, useRef } from "react";
import { IMessageToSend } from "#/state/conversation-store";
import { useDragResize } from "./use-drag-resize";
// Constants
const DEFAULT_MIN_HEIGHT = 20;
const DEFAULT_MAX_HEIGHT = 120;
const HEIGHT_INCREMENT = 20;
const MANUAL_OVERSIZE_THRESHOLD = 5... | **suggestion:** It appears that this ESLint rule can be resolved through proper code adjustments rather than being disabled.
```ts
el.style.setProperty('height', `${elementHeight}px`);
``` | import { useCallback, useEffect, RefObject, useRef } from "react";
import { IMessageToSend } from "#/state/conversation-store";
import { EPS } from "#/utils/constants";
import { getStyleHeightPx, setStyleHeightPx } from "#/utils/utils";
import { useDragResize } from "./use-drag-resize";
// Constants
const DEFAULT_MIN_... | @@ -8,6 +8,27 @@ const DEFAULT_MAX_HEIGHT = 120;
const HEIGHT_INCREMENT = 20;
const MANUAL_OVERSIZE_THRESHOLD = 50;
+const EPS = 1.5; // px tolerance for "near min"
+
+const getStyleHeightPx = (el: HTMLElement, fallback: number) => {
+ const h = parseFloat(el.style.height || "");
+ return Number.isFinite(h) ? h :... | frontend/src/hooks/use-auto-resize.ts | 20 | TypeScript | 0.714 | suggestion | 193 | 45 | 45 | false | fix(frontend): Fixed prompt box resizing behavior (fixes #11025) | 11,035 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | patilatharv |
minHeight,
maxHeight,
onGripDragStart: enableManualResize
? () => {
hasUserResizedRef.current = true;
onGripDragStart?.();
}
: undefined,
onGripDragEnd: enableManualResize
? () => {
// Clear manual mode if dragged to minimum height
const ... | **question:** Why does this function have an empty body? Could it be removed or made optional instead? | manualHeightRef.current = null;
}
}
onGripDragEnd?.();
}, [minHeight, onGripDragEnd]);
// Use the drag resize hook for manual resizing functionality
const { handleGripMouseDown, handleGripTouchStart } = useDragResize({
elementRef,
minHeight,
maxHeight,
onGripDragStart: enabl... | @@ -189,72 +144,184 @@ export const useAutoResize = (
} = options;
const constraints: HeightConstraints = { minHeight, maxHeight };
+ const { hasUserResizedRef, manualHeightRef } = useManualHeight();
+
+ const resetManualResize = () => {
+ hasUserResizedRef.current = false;
+ manualHeightRef.current = n... | frontend/src/hooks/use-auto-resize.ts | 26 | TypeScript | 0.429 | question | 102 | 51 | 51 | false | fix(frontend): Fixed prompt box resizing behavior (fixes #11025) | 11,035 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | patilatharv |
(h: number) => {
onHeightChange?.(h);
if (hasUserResizedRef.current) {
manualHeightRef.current = h;
}
},
[onHeightChange],
);
// Use the drag resize hook for manual resizing functionality
const { handleGripMouseDown, handleGripTouchStart } = useDragResize({
elementRef,
... | **suggestion:** Please refactor the logic within onGripDragStart and onGripDragEnd into separate, dedicated functions for better code organization and readability. | const handleDragStart = useCallback(() => {
hasUserResizedRef.current = true;
onGripDragStart?.();
}, [onGripDragStart]);
// Handle drag end - clear manual mode if at minimum height
const handleDragEnd = useCallback(() => {
const textareaElement = elementRef.current;
if (textareaElement) {
... | @@ -189,72 +144,184 @@ export const useAutoResize = (
} = options;
const constraints: HeightConstraints = { minHeight, maxHeight };
+ const { hasUserResizedRef, manualHeightRef } = useManualHeight();
+
+ const resetManualResize = () => {
+ hasUserResizedRef.current = false;
+ manualHeightRef.current = n... | frontend/src/hooks/use-auto-resize.ts | 26 | TypeScript | 0.429 | refactor | 163 | 51 | 51 | false | fix(frontend): Fixed prompt box resizing behavior (fixes #11025) | 11,035 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | patilatharv |
// DOM manipulation utilities
export const useAutoResize = (
elementRef: RefObject<HTMLElement | null>,
options: UseAutoResizeOptions = {},
): UseAutoResizeReturn => {
const {
minHeight = DEFAULT_MIN_HEIGHT,
maxHeight = DEFAULT_MAX_HEIGHT,
enableManualResize = false,
value,
onGripDragStart,
... | **suggestion:** Please use a more descriptive parameter name instead of a single-character identifier to improve code clarity and readability. | onGripDragStart,
onGripDragEnd,
onHeightChange,
} = options;
const constraints: HeightConstraints = { minHeight, maxHeight };
const { hasUserResizedRef, manualHeightRef } = useManualHeight();
const resetManualResize = () => {
hasUserResizedRef.current = false;
manualHeightRef.current = nul... | @@ -189,72 +144,184 @@ export const useAutoResize = (
} = options;
const constraints: HeightConstraints = { minHeight, maxHeight };
+ const { hasUserResizedRef, manualHeightRef } = useManualHeight();
+
+ const resetManualResize = () => {
+ hasUserResizedRef.current = false;
+ manualHeightRef.current = n... | frontend/src/hooks/use-auto-resize.ts | 26 | TypeScript | 0.429 | suggestion | 142 | 51 | 51 | false | fix(frontend): Fixed prompt box resizing behavior (fixes #11025) | 11,035 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | patilatharv |
// Constants
const DEFAULT_MIN_HEIGHT = 20;
const DEFAULT_MAX_HEIGHT = 120;
const HEIGHT_INCREMENT = 20;
const MANUAL_OVERSIZE_THRESHOLD = 50;
const EPS = 1.5; // px tolerance for "near min"
const getStyleHeightPx = (el: HTMLElement, fallback: number) => {
const h = parseFloat(el.style.height || "");
return Numbe... | **suggestion:** Please remove this comment. | import { useDragResize } from "./use-drag-resize";
// Constants
const DEFAULT_MIN_HEIGHT = 20;
const DEFAULT_MAX_HEIGHT = 120;
const HEIGHT_INCREMENT = 20;
const MANUAL_OVERSIZE_THRESHOLD = 50;
// Manual height tracking utilities
const useManualHeight = () => {
const hasUserResizedRef = useRef(false);
const manua... | @@ -8,6 +8,27 @@ const DEFAULT_MAX_HEIGHT = 120;
const HEIGHT_INCREMENT = 20;
const MANUAL_OVERSIZE_THRESHOLD = 50;
+const EPS = 1.5; // px tolerance for "near min"
+
+const getStyleHeightPx = (el: HTMLElement, fallback: number) => {
+ const h = parseFloat(el.style.height || "");
+ return Number.isFinite(h) ? h :... | frontend/src/hooks/use-auto-resize.ts | 26 | TypeScript | 0.143 | refactor | 43 | 51 | 51 | false | fix(frontend): Fixed prompt box resizing behavior (fixes #11025) | 11,035 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | patilatharv |
import { useCallback, useEffect, RefObject, useRef } from "react";
import { IMessageToSend } from "#/state/conversation-store";
import { useDragResize } from "./use-drag-resize";
// Constants
const DEFAULT_MIN_HEIGHT = 20;
const DEFAULT_MAX_HEIGHT = 120;
const HEIGHT_INCREMENT = 20;
const MANUAL_OVERSIZE_THRESHOLD = 5... | **suggestion:** Please use a more descriptive parameter name instead of a single-character identifier to improve code clarity and readability. | import { useCallback, useEffect, RefObject, useRef } from "react";
import { IMessageToSend } from "#/state/conversation-store";
import { EPS } from "#/utils/constants";
import { getStyleHeightPx, setStyleHeightPx } from "#/utils/utils";
import { useDragResize } from "./use-drag-resize";
// Constants
const DEFAULT_MIN_... | @@ -8,6 +8,27 @@ const DEFAULT_MAX_HEIGHT = 120;
const HEIGHT_INCREMENT = 20;
const MANUAL_OVERSIZE_THRESHOLD = 50;
+const EPS = 1.5; // px tolerance for "near min"
+
+const getStyleHeightPx = (el: HTMLElement, fallback: number) => {
+ const h = parseFloat(el.style.height || "");
+ return Number.isFinite(h) ? h :... | frontend/src/hooks/use-auto-resize.ts | 18 | TypeScript | 0.429 | suggestion | 142 | 43 | 43 | false | fix(frontend): Fixed prompt box resizing behavior (fixes #11025) | 11,035 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | patilatharv |
executeHeightCallback(manualHeightRef.current, onHeightChange);
return;
}
// Measure element heights
const measurements = measureElementHeights(element, minHeight);
const { currentHeight, contentHeight } = measurements;
// If content fits within current height
if (contentHeight <= ... | **suggestion:** please move this ref to the top of the hook.
```ts
export const useAutoResize = (
elementRef: RefObject<HTMLElement | null>,
options: UseAutoResizeOptions = {},
): UseAutoResizeReturn => {
const pendingSmartRef = useRef<number | null>(null);
...
}
``` | const { currentHeight, contentHeight } = measurements;
// If content fits within current height
if (contentHeight <= currentHeight) {
handleContentFitsInCurrentHeight(element, currentHeight, contentHeight);
return;
}
// If content exceeds current height but within max
if (contentHe... | @@ -189,72 +144,184 @@ export const useAutoResize = (
} = options;
const constraints: HeightConstraints = { minHeight, maxHeight };
+ const { hasUserResizedRef, manualHeightRef } = useManualHeight();
+
+ const resetManualResize = () => {
+ hasUserResizedRef.current = false;
+ manualHeightRef.current = n... | frontend/src/hooks/use-auto-resize.ts | 26 | TypeScript | 1 | refactor | 286 | 51 | 51 | false | fix(frontend): Fixed prompt box resizing behavior (fixes #11025) | 11,035 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | patilatharv |
import { RefObject } from "react";
import { isMobileDevice } from "#/utils/utils";
// Drag handling hook
interface UseDragResizeOptions {
elementRef: RefObject<HTMLElement | null>;
minHeight: number;
maxHeight: number;
onGripDragStart?: () => void;
onGripDragEnd?: () => void;
onHeightChange?: (height: numb... | **suggestion:** It appears that the use-auto-resize.ts file contains a constant with the same value:
```ts
const EPS = 1.5; // px tolerance for "near min"
```
To improve maintainability, consider defining this constant once in constants.ts (frontend/src/utils) and reusing it across both files. | import { RefObject } from "react";
import { EPS } from "#/utils/constants";
import { isMobileDevice } from "#/utils/utils";
// Drag handling hook
interface UseDragResizeOptions {
elementRef: RefObject<HTMLElement | null>;
minHeight: number;
maxHeight: number;
onGripDragStart?: () => void;
onGripDragEnd?: () ... | @@ -18,7 +19,9 @@ export const useDragResize = ({
onGripDragStart,
onGripDragEnd,
onHeightChange,
+ onReachedMinHeight,
}: UseDragResizeOptions) => {
+ const NEAR = 1.5; // px tolerance for "at min" | frontend/src/hooks/use-drag-resize.ts | 24 | TypeScript | 0.857 | suggestion | 302 | 49 | 49 | false | fix(frontend): Fixed prompt box resizing behavior (fixes #11025) | 11,035 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | patilatharv |
import { useCallback, useEffect, RefObject, useRef } from "react";
import { IMessageToSend } from "#/state/conversation-store";
import { useDragResize } from "./use-drag-resize";
// Constants
const DEFAULT_MIN_HEIGHT = 20;
const DEFAULT_MAX_HEIGHT = 120;
const HEIGHT_INCREMENT = 20;
const MANUAL_OVERSIZE_THRESHOLD = 5... | **suggestion:** Please relocate this function to utils.ts (frontend/src/utils) to facilitate potential reuse in other parts of the codebase. | import { useCallback, useEffect, RefObject, useRef } from "react";
import { IMessageToSend } from "#/state/conversation-store";
import { EPS } from "#/utils/constants";
import { getStyleHeightPx, setStyleHeightPx } from "#/utils/utils";
import { useDragResize } from "./use-drag-resize";
// Constants
const DEFAULT_MIN_... | @@ -8,6 +8,27 @@ const DEFAULT_MAX_HEIGHT = 120;
const HEIGHT_INCREMENT = 20;
const MANUAL_OVERSIZE_THRESHOLD = 50;
+const EPS = 1.5; // px tolerance for "near min"
+
+const getStyleHeightPx = (el: HTMLElement, fallback: number) => { | frontend/src/hooks/use-auto-resize.ts | 13 | TypeScript | 0.429 | suggestion | 140 | 38 | 38 | false | fix(frontend): Fixed prompt box resizing behavior (fixes #11025) | 11,035 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | patilatharv |
import { useCallback, useEffect, RefObject, useRef } from "react";
import { IMessageToSend } from "#/state/conversation-store";
import { useDragResize } from "./use-drag-resize";
// Constants
const DEFAULT_MIN_HEIGHT = 20;
const DEFAULT_MAX_HEIGHT = 120;
const HEIGHT_INCREMENT = 20;
const MANUAL_OVERSIZE_THRESHOLD = 5... | **suggestion:** Please relocate this function to utils.ts (frontend/src/utils) to facilitate potential reuse in other parts of the codebase. | import { useCallback, useEffect, RefObject, useRef } from "react";
import { IMessageToSend } from "#/state/conversation-store";
import { EPS } from "#/utils/constants";
import { getStyleHeightPx, setStyleHeightPx } from "#/utils/utils";
import { useDragResize } from "./use-drag-resize";
// Constants
const DEFAULT_MIN_... | @@ -8,6 +8,27 @@ const DEFAULT_MAX_HEIGHT = 120;
const HEIGHT_INCREMENT = 20;
const MANUAL_OVERSIZE_THRESHOLD = 50;
+const EPS = 1.5; // px tolerance for "near min"
+
+const getStyleHeightPx = (el: HTMLElement, fallback: number) => {
+ const h = parseFloat(el.style.height || "");
+ return Number.isFinite(h) ? h :... | frontend/src/hooks/use-auto-resize.ts | 18 | TypeScript | 0.429 | suggestion | 140 | 43 | 43 | false | fix(frontend): Fixed prompt box resizing behavior (fixes #11025) | 11,035 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | patilatharv |
// Handle drag end - clear manual mode if at minimum height
const handleDragEnd = useCallback(() => {
const textareaElement = elementRef.current;
if (textareaElement) {
const currentHeight = getStyleHeightPx(textareaElement, minHeight);
if (Math.abs(currentHeight - minHeight) <= EPS) {
... | question: Why does this function return a boolean value? It appears that the return value is not being used anywhere. |
// Handle drag end - clear manual mode if at minimum height
const handleDragEnd = useCallback(() => {
const textareaElement = elementRef.current;
if (textareaElement) {
const currentHeight = getStyleHeightPx(textareaElement, minHeight);
if (Math.abs(currentHeight - minHeight) <= EPS) {
... | @@ -189,72 +134,181 @@ export const useAutoResize = (
} = options;
const constraints: HeightConstraints = { minHeight, maxHeight };
+ const { hasUserResizedRef, manualHeightRef } = useManualHeight();
+
+ const resetManualResize = () => {
+ hasUserResizedRef.current = false;
+ manualHeightRef.current = n... | frontend/src/hooks/use-auto-resize.ts | 26 | TypeScript | 0.429 | suggestion | 117 | 51 | 51 | false | fix(frontend): Fixed prompt box resizing behavior (fixes #11025) | 11,035 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | patilatharv |
if (hasUserResizedRef.current && currentHeight > minHeight) {
applyResizeStrategy(element, {
finalHeight: currentHeight,
overflowY: "hidden",
});
executeHeightCallback(currentHeight, onHeightChange);
return true;
}
// Otherwise allow shrinking towar... | question: Why does this function return a boolean value? It appears that the return value is not being used anywhere. | currentHeight: number,
contentHeight: number,
): void => {
// If user manually resized and we're above min height, preserve their chosen height
if (hasUserResizedRef.current && currentHeight > minHeight) {
applyResizeStrategy(element, {
finalHeight: currentHeight,
... | @@ -189,72 +134,181 @@ export const useAutoResize = (
} = options;
const constraints: HeightConstraints = { minHeight, maxHeight };
+ const { hasUserResizedRef, manualHeightRef } = useManualHeight();
+
+ const resetManualResize = () => {
+ hasUserResizedRef.current = false;
+ manualHeightRef.current = n... | frontend/src/hooks/use-auto-resize.ts | 26 | TypeScript | 0.429 | suggestion | 117 | 51 | 51 | false | fix(frontend): Fixed prompt box resizing behavior (fixes #11025) | 11,035 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | patilatharv |
mcp_config = MCPConfig.from_file(Path(user_mcp_config_path))
return mcp_config.to_dict()['mcpServers']
except ValueError as e:
print_formatted_text(HTML(f"\n<red>Error loading MCP servers from json file {user_mcp_config_path}: {e}!</red>"))
return {}
def load... | should we do the otherway around? updating the exitsing one with loaded? |
def load(self) -> Agent | None:
try:
str_spec = self.file_store.read(AGENT_SETTINGS_PATH)
agent = Agent.model_validate_json(str_spec)
# Update tools with most recent working directory
updated_tools = get_default_tools(
working_dir=WORK_DIR,
... | @@ -23,14 +39,19 @@ def load(self) -> Agent | None:
persistence_dir=PERSISTENCE_DIR,
enable_browser=False
)
-
- # Create agent context with current working directory
+
agent_context = AgentContext(
system_message_suffix=... | openhands-cli/openhands_cli/tui/settings/store.py | 26 | Python | 0.286 | question | 72 | 45 | 40 | false | Add /mcp command for MCP server configuration in CLI | 11,105 | All-Hands-AI/OpenHands | 55,974 | Python | xingyaoww | malhotra5 |
import os
# Configuration directory for storing agent settings and CLI configuration
PERSISTENCE_DIR = os.path.expanduser("~/.openhands")
# Working directory for agent operations (current directory where CLI is run)
WORK_DIR = os.getcwd()
AGENT_SETTINGS_PATH = "agent_settings.json"
MCP_CONFIG_POINTER_FILE = "mcp_co... | I'm thinking.. we should just ask user to put mcp.json under `~/.openhands` instead maintaining a pointer here, wdyt? | import os
from uuid import UUID
# Configuration directory for storing agent settings and CLI configuration
PERSISTENCE_DIR = os.path.expanduser("~/.openhands")
# Working directory for agent operations (current directory where CLI is run)
WORK_DIR = os.getcwd()
AGENT_SETTINGS_PATH = "agent_settings.json"
# MCP confi... | @@ -7,3 +7,5 @@
WORK_DIR = os.getcwd()
AGENT_SETTINGS_PATH = "agent_settings.json"
+
+MCP_CONFIG_POINTER_FILE = "mcp_config_pointer.txt" | openhands-cli/openhands_cli/locations.py | 11 | Python | 0.571 | question | 117 | 12 | 17 | false | Add /mcp command for MCP server configuration in CLI | 11,105 | All-Hands-AI/OpenHands | 55,974 | Python | xingyaoww | malhotra5 |
class MCPScreen:
def __init__(self):
self.agent_store = AgentStore()
self.file_store = LocalFileStore(PERSISTENCE_DIR)
def mcp_action_menu(self):
try:
settings_type = mcp_action_menu()
if settings_type == MCPActionType.LIST:
self.list_mcp_serv... | nit but these two empty lines are killing my eyes 😭 | from openhands.sdk import Agent
class MCPScreen:
"""
MCP Screen
1. Display information about setting up MCP
2. See existing servers that are setup
3. Debug additional servers passed via mcp.json
4. Identify servers waiting to sync on session restart
"""
# ---------- server spec handl... | @@ -0,0 +1,76 @@
+from openhands_cli.locations import MCP_CONFIG_POINTER_FILE, PERSISTENCE_DIR
+from openhands_cli.tui.settings.store import AgentStore
+from openhands_cli.user_actions.mcp_action import (
+ MCPActionType,
+ mcp_action_menu,
+ propmt_mcp_json_config_file
+)
+from prompt_toolkit import HTML, pri... | openhands-cli/openhands_cli/tui/settings/mcp_screen.py | 26 | Python | 0.214 | nitpick | 52 | 51 | 51 | false | Add /mcp command for MCP server configuration in CLI | 11,105 | All-Hands-AI/OpenHands | 55,974 | Python | xingyaoww | malhotra5 |
from openhands_cli.runner import ConversationRunner
from openhands_cli.setup import setup_agent
from openhands_cli.tui.settings.settings_screen import SettingsScreen
from openhands_cli.tui.tui import (
CommandCompleter,
display_help,
display_welcome,
)
from openhands_cli.user_actions import UserConfirmation... | Could we place this inside setup_agent itself, instead of making it an arg
Also it seems when loading the agent back in `AgentStore` we'd similarly need to update the agent context | from openhands_cli.runner import ConversationRunner
from openhands_cli.setup import setup_conversation, MissingAgentSpec
from openhands_cli.tui.settings.settings_screen import SettingsScreen
from openhands_cli.tui.tui import (
CommandCompleter,
display_help,
display_welcome,
)
from openhands_cli.user_action... | @@ -37,12 +39,16 @@ def run_cli_entry() -> None:
EOFError: If EOF is encountered
"""
- conversation = setup_agent()
+ agent_context = AgentContext(
+ system_message_suffix=f"You current working directory is: {WORK_DIR}",
+ ) | openhands-cli/openhands_cli/agent_chat.py | 26 | Python | 0.571 | suggestion | 182 | 51 | 51 | false | v1 cli: provide information on CWD | 11,108 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 | xingyaoww |
# Confirm save
save_settings_confirmation()
except KeyboardInterrupt:
print_formatted_text(HTML('\n<red>Cancelled settings change.</red>'))
return
# Store the collected settings for persistence
self._save_advanced_settings(
custom_mod... | ```suggestion
service_id="agent"
``` |
# Confirm save
save_settings_confirmation()
except KeyboardInterrupt:
print_formatted_text(HTML('\n<red>Cancelled settings change.</red>'))
return
# Store the collected settings for persistence
self._save_advanced_settings(
custom_mod... | @@ -162,7 +162,8 @@ def _save_llm_settings(
llm = LLM(
model=model,
api_key=api_key,
- base_url=base_url
+ base_url=base_url,
+ service_id="openhands-cli" | openhands-cli/openhands_cli/tui/settings/settings_screen.py | 26 | Python | 0.429 | suggestion | 48 | 51 | 51 | false | v1 cli: provide information on CWD | 11,108 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 | xingyaoww |
display_welcome(session_id)
continue
elif command == "/resume":
if not (
conversation.state.agent_status == AgentExecutionStatus.PAUSED
or conversation.state.agent_status
== AgentExecutionStatus.WAITI... | I think we should do this?
```suggestion
break
``` | display_welcome(session_id)
continue
elif command == "/resume":
if not (
conversation.state.agent_status == AgentExecutionStatus.PAUSED
or conversation.state.agent_status
== AgentExecutionStatus.WAITI... | @@ -143,4 +153,9 @@ def run_cli_entry() -> None:
exit_confirmation = exit_session_confirmation()
if exit_confirmation == UserConfirmation.ACCEPT:
print_formatted_text(HTML("\n<yellow>Goodbye! 👋</yellow>"))
- break
+ break | openhands-cli/openhands_cli/agent_chat.py | 26 | Python | 0.643 | suggestion | 66 | 32 | 32 | false | CLI(V1): restore terminal state | 11,127 | All-Hands-AI/OpenHands | 55,974 | Python | xingyaoww | malhotra5 |
return reason.strip()
def get_session_prompter(
input: Input | None = None, # strictly for unit testing
output: Output | None = None, # strictly for unit testing
) -> PromptSession:
bindings = KeyBindings()
@bindings.add("\\", "enter")
def _(event: KeyPressEvent) -> None:
# Typing '... | Can we put this to default style? | return reason.strip()
def get_session_prompter(
input: Input | None = None, # strictly for unit testing
output: Output | None = None, # strictly for unit testing
) -> PromptSession:
bindings = KeyBindings()
@bindings.add("\\", "enter")
def _(event: KeyPressEvent) -> None:
# Typing '... | @@ -155,20 +157,45 @@ def _handle_enter(event: KeyPressEvent):
return reason.strip()
-def get_session_prompter() -> PromptSession:
+def get_session_prompter(
+ input: Input | None = None, # strictly for unit testing
+ output: Output | None = None, # strictly for unit testing
+) -> PromptSession:
b... | openhands-cli/openhands_cli/user_actions/utils.py | 26 | Python | 0.071 | question | 33 | 51 | 50 | false | CLI(V1): Multiline inputs | 11,131 | All-Hands-AI/OpenHands | 55,974 | Python | xingyaoww | malhotra5 |
#!/usr/bin/env python3
"""
Simple main entry point for OpenHands CLI.
This is a simplified version that demonstrates the TUI functionality.
"""
import logging
import os
debug_env = os.getenv('DEBUG', 'false').lower()
if debug_env != '1' and debug_env != 'true':
logging.disable(logging.CRITICAL)
from prompt_toolk... | Shall we still show warnings and error? We should have VERY small set of them in agent SDK. These could be useful to warn user about the configuration error | #!/usr/bin/env python3
"""
Simple main entry point for OpenHands CLI.
This is a simplified version that demonstrates the TUI functionality.
"""
import logging
import os
debug_env = os.getenv('DEBUG', 'false').lower()
if debug_env != '1' and debug_env != 'true':
logging.disable(logging.WARNING)
from prompt_toolki... | @@ -4,18 +4,27 @@
This is a simplified version that demonstrates the TUI functionality.
"""
+import logging
+import os
+
+debug_env = os.getenv('DEBUG', 'false').lower()
+if debug_env != '1' and debug_env != 'true':
+ logging.disable(logging.CRITICAL)
+
from prompt_toolkit import print_formatted_text | openhands-cli/openhands_cli/simple_main.py | 14 | Python | 0.571 | suggestion | 156 | 39 | 39 | false | CLI(V1): Add loading screen + suppress extraneous logs | 11,134 | All-Hands-AI/OpenHands | 55,974 | Python | xingyaoww | malhotra5 |
interface ErrorMessageState {
errorMessage: string | null;
}
interface ErrorMessageActions {
setErrorMessage: (message: string) => void;
getErrorMessage: () => string | null;
removeErrorMessage: () => void;
}
type ErrorMessageStore = ErrorMessageState & ErrorMessageActions;
const initialState: ErrorMessageS... | Same as the other PR, maybe we can get rid of this and retrieve the latest state through `const { errorMessage } = useErrorMessageStore()` directly |
interface ErrorMessageState {
errorMessage: string | null;
}
interface ErrorMessageActions {
setErrorMessage: (message: string) => void;
removeErrorMessage: () => void;
}
type ErrorMessageStore = ErrorMessageState & ErrorMessageActions;
const initialState: ErrorMessageState = {
errorMessage: null,
};
expor... | @@ -0,0 +1,33 @@
+import { create } from "zustand";
+
+interface ErrorMessageState {
+ errorMessage: string | null;
+}
+
+interface ErrorMessageActions {
+ setErrorMessage: (message: string) => void;
+ getErrorMessage: () => string | null;
+ removeErrorMessage: () => void;
+}
+
+type ErrorMessageStore = ErrorMessag... | frontend/src/stores/error-message-store.ts | 26 | TypeScript | 0.714 | suggestion | 147 | 33 | 30 | false | refactor(frontend): migration of use-ws-error-message.ts to zustand | 11,147 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | hieptl |
import argparse
import logging
import os
debug_env = os.getenv('DEBUG', 'false').lower()
if debug_env != '1' and debug_env != 'true':
logging.disable(logging.WARNING)
from prompt_toolkit import print_formatted_text
from prompt_toolkit.formatted_text import HTML
from openhands_cli.agent_chat import run_cli_entry
... | ```suggestion
"--resume",
```
Maybe just call it resume? |
import argparse
import logging
import os
debug_env = os.getenv('DEBUG', 'false').lower()
if debug_env != '1' and debug_env != 'true':
logging.disable(logging.WARNING)
from prompt_toolkit import print_formatted_text
from prompt_toolkit.formatted_text import HTML
from openhands_cli.agent_chat import run_cli_entry
... | @@ -16,18 +17,27 @@
from openhands_cli.agent_chat import run_cli_entry
-
def main() -> None:
"""Main entry point for the OpenHands CLI.
Raises:
ImportError: If agent chat dependencies are missing
Exception: On other error conditions
"""
+ parser = argparse.ArgumentParser(
+ ... | openhands-cli/openhands_cli/simple_main.py | 26 | Python | 0.571 | question | 64 | 51 | 51 | false | CLI(V1): resume conversations | 11,154 | All-Hands-AI/OpenHands | 55,974 | Python | xingyaoww | malhotra5 |
to start a conversation. If the conversation is already running, it will
return the existing agent loop info.
"""
logger.info(f'Starting conversation: {conversation_id}')
try:
# Check that the conversation exists
try:
await conversation_store.get_metadata(conversation_id... | Do we need to param `providers_set` if we already have the actual provider tokens?
I think they should always exists in saas? | )
else:
logger.warning(
'/start endpoint: No provider tokens fetched (provider_tokens is None/empty)',
extra={'session_id': conversation_id},
)
try:
# Check that the conversation exists
try:
await conversation_store.get_metadata(conver... | @@ -504,6 +505,10 @@ async def start_conversation(
user_id, conversation_id, providers_set.providers_set or []
)
+ # Override with real provider tokens
+ if provider_tokens:
+ conversation_init_data.git_provider_tokens = provider_tokens | openhands/server/routes/manage_conversations.py | 26 | Python | 0.571 | question | 127 | 51 | 51 | false | fix: add provider tokens to resume conversation endpoint | 11,155 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 | ak684 |
image_urls,
replay_json,
conversation_metadata.conversation_id,
conversation_metadata,
conversation_instructions,
mcp_config,
)
def create_provider_tokens_object(
providers_set: list[ProviderType],
) -> PROVIDER_TOKEN_TYPE:
"""Create provider tokens object f... | this line and the following logic is the fix, everything else in this pr is logs or tests | image_urls,
replay_json,
conversation_metadata.conversation_id,
conversation_metadata,
conversation_instructions,
mcp_config,
)
def create_provider_tokens_object(
providers_set: list[ProviderType],
) -> PROVIDER_TOKEN_TYPE:
"""Create provider tokens object f... | @@ -215,14 +215,18 @@ def create_provider_tokens_object(
async def setup_init_conversation_settings(
- user_id: str | None, conversation_id: str, providers_set: list[ProviderType]
+ user_id: str | None,
+ conversation_id: str,
+ providers_set: list[ProviderType],
+ provider_tokens: PROVIDER_TOKEN_TY... | openhands/server/services/conversation_service.py | 26 | Python | 0.214 | suggestion | 89 | 51 | 51 | false | fix: add provider tokens to resume conversation endpoint | 11,155 | All-Hands-AI/OpenHands | 55,974 | Python | ak684 | ak684 |
condenser_updates = {}
if agent.condenser and isinstance(agent.condenser, LLMSummarizingCondenser):
condenser_updates["llm"] = agent.condenser.llm.model_copy(update={"metadata": get_llm_metadata(
model_name=agent.condenser.llm.model,
llm_t... | We didn't raise and error here so the user could be re-directed into the settings setup flow. The current logic will require the user to manually delete their settings file to use the CLI again |
condenser_updates = {}
if agent.condenser and isinstance(agent.condenser, LLMSummarizingCondenser):
condenser_updates["llm"] = agent.condenser.llm.model_copy(update={"metadata": get_llm_metadata(
model_name=agent.condenser.llm.model,
llm_t... | @@ -44,17 +43,38 @@ def load(self) -> Agent | None:
mcp_config: dict = agent.mcp_config.copy().get('mcpServers', {})
mcp_config.update(additional_mcp_config)
+ # Update LLM metadata with current information
+ agent_llm_metadata = get_llm_metadata(
+ model... | openhands-cli/openhands_cli/tui/settings/store.py | 26 | Python | 0.571 | bug | 193 | 32 | 31 | false | Update OpenHands CLI for agent SDK refactor | 11,165 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 | xingyaoww |
import RepoIcon from "#/icons/repo.svg?react";
import { useHomeStore } from "#/stores/home-store";
import { Typography } from "#/ui/typography";
export interface GitRepoDropdownProps {
provider: Provider;
value?: string | null;
repositoryName?: string | null;
placeholder?: string;
className?: string;
disab... | ```suggestion
const { recentRepositories } = useHomeStore();
```
Couldn’t we just get `recentRepositories` instead of a getter that we’d have to call? That way we don’t have to call the fn in order to get the latest state | import RepoIcon from "#/icons/repo.svg?react";
import { useHomeStore } from "#/stores/home-store";
import { Typography } from "#/ui/typography";
export interface GitRepoDropdownProps {
provider: Provider;
value?: string | null;
repositoryName?: string | null;
placeholder?: string;
className?: string;
disab... | @@ -45,6 +47,7 @@ export function GitRepoDropdown({
}: GitRepoDropdownProps) {
const { t } = useTranslation();
const { data: config } = useConfig();
+ const { getRecentRepositories } = useHomeStore(); | frontend/src/components/features/home/git-repo-dropdown/git-repo-dropdown.tsx | 26 | TypeScript | 0.857 | suggestion | 224 | 51 | 51 | false | feat(frontend): persist recent repos | 11,171 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | hieptl |
json={
'name': key,
'description': secret.description,
'value': secret.secret.get_secret_value(),
},
)
response.raise_for_status()
def _get_mcp_config(self, user_id: str) ... | So many control flow directives are a little wonky but it seems behaviorally correct, can go with this. I don't have a specific change. | if custom_secrets:
for key, secret in custom_secrets.items():
try:
response = await client.post(
f'{api_url}/api/secrets',
json={
'name': key,
'description': se... | @@ -349,18 +349,48 @@ async def _setup_custom_secrets(
api_url: str,
custom_secrets: MappingProxyType[str, Any] | None,
):
- """Setup custom secrets for the nested conversation."""
+ """Setup custom secrets for the nested conversation.
+
+ Note: When resuming conversations, s... | enterprise/server/saas_nested_conversation_manager.py | 26 | Python | 0.429 | suggestion | 135 | 51 | 51 | false | increase remote_runtime_api_timeout and handle duplicate secrets | 11,239 | All-Hands-AI/OpenHands | 55,974 | Python | raymyers | ak684 |
}
for k, v in provider_tokens.items()
if v.token
}
response = await client.post(
f'{api_url}/api/add-git-providers',
json={
'provider_tokens': provider_tokens_json,
},
... | Nice work!
Any chance we could reduce the nesting here? | }
for k, v in provider_tokens.items()
if v.token
}
response = await client.post(
f'{api_url}/api/add-git-providers',
json={
'provider_tokens': provider_tokens_json,
},
... | @@ -349,18 +349,48 @@ async def _setup_custom_secrets(
api_url: str,
custom_secrets: MappingProxyType[str, Any] | None,
):
- """Setup custom secrets for the nested conversation."""
+ """Setup custom secrets for the nested conversation.
+
+ Note: When resuming conversations, s... | enterprise/server/saas_nested_conversation_manager.py | 26 | Python | 0.286 | question | 56 | 51 | 51 | false | increase remote_runtime_api_timeout and handle duplicate secrets | 11,239 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 | ak684 |
self.memory_monitor = MemoryMonitor(
enable=os.environ.get('RUNTIME_MEMORY_MONITOR', 'False').lower()
in ['true', '1', 'yes']
)
self.memory_monitor.start_monitoring()
@property
def initial_cwd(self):
return self._initial_cwd
async def _init_browser_a... | logger.exception is equivalent to error with exc_info=True |
self.memory_monitor = MemoryMonitor(
enable=os.environ.get('RUNTIME_MEMORY_MONITOR', 'False').lower()
in ['true', '1', 'yes']
)
self.memory_monitor.start_monitoring()
@property
def initial_cwd(self):
return self._initial_cwd
async def _init_browser_... | @@ -241,7 +240,7 @@ async def _init_browser_async(self):
self.browser = BrowserEnv(self.browsergym_eval_env)
logger.debug('Browser initialized asynchronously')
except Exception as e:
- logger.error(f'Failed to initialize browser: {e}')
+ logger.error(f'Failed to ... | openhands/runtime/action_execution_server.py | 26 | Python | 0.357 | suggestion | 58 | 51 | 51 | false | feat(logging): JSON log config for Uvicorn when LOG_JSON=1 | 11,264 | All-Hands-AI/OpenHands | 55,974 | Python | raymyers | neubig |
full_entry_path = os.path.join(full_path, entry_relative)
if os.path.exists(full_entry_path):
is_dir = os.path.isdir(full_entry_path)
if is_dir:
# add trailing slash to directories
# required by FE to... | This log config is rather long to be sitting in the middle of the flow here. Probably it should be extracted into a constant or function and referenced from here. | if os.path.exists(full_entry_path):
is_dir = os.path.isdir(full_entry_path)
if is_dir:
# add trailing slash to directories
# required by FE to differentiate directories and files
entry = entry... | @@ -1067,8 +1068,69 @@ async def list_files(request: Request):
return JSONResponse(content=sorted_entries)
except Exception as e:
- logger.error(f'Error listing files: {e}')
+ logger.error(f'Error listing files: {e}', exc_info=True)
return JSONResponse(content=... | openhands/runtime/action_execution_server.py | 26 | Python | 0.429 | refactor | 162 | 51 | 29 | false | feat(logging): JSON log config for Uvicorn when LOG_JSON=1 | 11,264 | All-Hands-AI/OpenHands | 55,974 | Python | raymyers | neubig |
return AsyncAdapt_asyncpg_connection(
engine.dialect.dbapi,
await self._create_async_gcp_db_connection(),
prepared_statement_cache_size=100,
)
async def _create_async_gcp_engine(self):
from sqlalchemy.dialects.postgresql.asyncpg import (
Asyn... | The NullPool is a cause for concern to me here - it disables connection pooling which slows things down a bit |
return AsyncAdapt_asyncpg_connection(
engine.dialect.dbapi,
await self._create_async_gcp_db_connection(),
prepared_statement_cache_size=100,
)
async def _create_async_gcp_engine(self):
from sqlalchemy.dialects.postgresql.asyncpg import (
Asyn... | @@ -118,12 +121,24 @@ async def _create_async_gcp_creator(self):
)
async def _create_async_gcp_engine(self):
+ from sqlalchemy.dialects.postgresql.asyncpg import (
+ AsyncAdapt_asyncpg_connection,
+ )
+
+ base_engine = self._create_gcp_engine()
+ dbapi = base_engin... | openhands/app_server/services/db_session_injector.py | 26 | Python | 0.571 | performance | 109 | 51 | 51 | false | Fix PostgreSQL readiness in app server without dependency changes | 11,267 | All-Hands-AI/OpenHands | 55,974 | Python | tofarr | enyst |
This ensures that when tokens are refreshed on resume, git operations
(push, pull, fetch) will use the new valid tokens instead of expired ones.
"""
workspace_root = os.getenv('WORKSPACE_MOUNT_PATH_IN_SANDBOX', '/workspace')
if not os.path.exists(workspace_root):
logger.debug(
... | @ak684 this only works on the nested server, it won't work on the main server or in SaaS mode. You need to attach to the runtime and run the command in there | existing_provider_tokens.get(token_type, None)
if existing_provider_tokens
else None
)
if (
existing_token
and (existing_token.host != token_value.host)
and existing_token.token
):
... | @@ -25,6 +30,129 @@
app = APIRouter(prefix='/api', dependencies=get_dependencies())
+# =================================================
+# SECTION: Git URL update helpers
+# =================================================
+
+
+def get_provider_from_url(url: str) -> ProviderType | None:
+ """Extract provider ... | openhands/server/routes/secrets.py | 26 | Python | 0.357 | suggestion | 157 | 51 | 51 | false | fix: refresh provider tokens proactively and update git URLs on resume | 11,296 | All-Hands-AI/OpenHands | 55,974 | Python | rbren | ak684 |
provider = ProviderType.GITLAB
elif 'bitbucket.org' in old_url:
provider = ProviderType.BITBUCKET
if not provider or provider not in git_provider_tokens:
return
# Get fresh token
token_info = git_provider_tokens[provider]
... | Two small questions here:
- it seems we only embed it in the URL, so iirc the old one remains in env? And in other remotes than `origin`. I do see how this helps, though... this is the most used case 🤔
- could we test that this works or doesn't break on OpenHands? (not Saas) I think V0 doesn't have token refresh. Th... | random_str = ''.join(
random.choices(string.ascii_lowercase + string.digits, k=8)
)
openhands_workspace_branch = f'openhands-workspace-{random_str}'
repo_path = self.workspace_root / dir_name
quoted_repo_path = shlex.quote(str(repo_path))
quoted_remote_repo_u... | @@ -406,6 +406,105 @@ async def _handle_action(self, event: Action) -> None:
return
self.event_stream.add_event(observation, source) # type: ignore[arg-type]
+ async def _update_git_remote_url_with_fresh_token(
+ self,
+ repo_dir: str,
+ git_provider_tokens: PROVIDER_TOK... | openhands/runtime/base.py | 26 | Python | 0.643 | suggestion | 362 | 51 | 51 | false | fix: refresh provider tokens proactively and update git URLs on resume | 11,296 | All-Hands-AI/OpenHands | 55,974 | Python | enyst | ak684 |
# Determine provider from URL
provider = None
if 'github.com' in old_url:
provider = ProviderType.GITHUB
elif 'gitlab.com' in old_url:
provider = ProviderType.GITLAB
elif 'bitbucket.org' in old_url:
provider = P... | Nit: we could probably make this top-level, all imports are, if possible | 'info', RuntimeStatus.SETTING_UP_WORKSPACE, 'Setting up workspace...'
)
dir_name = selected_repository.split('/')[-1]
# Generate a random branch name to avoid conflicts
random_str = ''.join(
random.choices(string.ascii_lowercase + string.digits, k=8)
... | @@ -406,6 +406,105 @@ async def _handle_action(self, event: Action) -> None:
return
self.event_stream.add_event(observation, source) # type: ignore[arg-type]
+ async def _update_git_remote_url_with_fresh_token(
+ self,
+ repo_dir: str,
+ git_provider_tokens: PROVIDER_TOK... | openhands/runtime/base.py | 26 | Python | 0.286 | nitpick | 72 | 51 | 51 | false | fix: refresh provider tokens proactively and update git URLs on resume | 11,296 | All-Hands-AI/OpenHands | 55,974 | Python | enyst | ak684 |
"""OpenHands package."""
__version__ = '1.0.1'
| Does this version need to get updated everytime as well now? | """OpenHands package."""
from importlib.metadata import version, PackageNotFoundError
try:
__version__ = version("openhands")
except PackageNotFoundError:
__version__ = "0.0.0"
| @@ -1,3 +1,3 @@
-"""OpenHands CLI package."""
+"""OpenHands package."""
-__version__ = '0.1.0'
+__version__ = '1.0.1' | openhands-cli/openhands_cli/__init__.py | 3 | Python | 0.214 | question | 60 | 4 | 9 | false | CLI(V1): Patch release | 11,349 | All-Hands-AI/OpenHands | 55,974 | Python | mamoodi | malhotra5 |
url = f'{self.BASE_URL}/search/repositories'
params = {
'per_page': per_page,
'sort': sort,
'order': order,
}
if public:
url_parts = query.split('/')
if len(url_parts) < 4:
return []
org = url_parts... | Would this work locally (we only have installations in saas mode)?
Maybe we still call `get_user_organizations()` when running locally? | per_page: int,
sort: str,
order: str,
public: bool,
app_mode: AppMode,
) -> list[Repository]:
url = f'{self.BASE_URL}/search/repositories'
params = {
'per_page': per_page,
'sort': sort,
'order': order,
}
if ... | @@ -206,9 +229,9 @@ async def search_repositories(
query_with_user = f'org:{org} in:name {repo_query}'
params['q'] = query_with_user
elif not public:
- # Expand search scope to include user's repositories and organizations they're a member of
+ # Expand search sc... | openhands/integrations/github/service/repos.py | 26 | Python | 0.571 | question | 138 | 51 | 51 | false | fix(backend): repository search is not working in the production environment | 11,386 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 | hieptl |
_waiting_times = 1
if self.sio:
# Get timeout from configuration, default to 30 seconds
client_wait_timeout = self.config.client_wait_timeout
self.logger.debug(
f'Using client wait timeout: {client_wait_timeout}s for session {s... | ```suggestion
self.logger.debug(
``` | _waiting_times = 1
if self.sio:
# Get timeout from configuration, default to 30 seconds
client_wait_timeout = self.config.client_wait_timeout
self.logger.debug(
f'Using client wait timeout: {client_wait_timeout}s for session {s... | @@ -390,22 +390,34 @@ async def _send(self, data: dict[str, object]) -> bool:
_waiting_times = 1
if self.sio:
+ # Get timeout from configuration, default to 30 seconds
+ client_wait_timeout = self.config.client_wait_timeout
+ self.logger.debug(
+ ... | openhands/server/session/session.py | 26 | Python | 0.714 | bug | 60 | 51 | 51 | false | feat: make websocket client wait timeout configurable | 11,405 | All-Hands-AI/OpenHands | 55,974 | Python | neubig | olyashok |
def check_cmd_action_for_provider_token_ref(
cls, event: Action
) -> list[ProviderType]:
"""Detect if agent run action is using a provider token (e.g $GITHUB_TOKEN)
Returns a list of providers which are called by the agent
"""
if not isinstance(event, CmdRunAction):
... | NIT: maybe rename `is_optional` so its more obvious its only related to logging level | def check_cmd_action_for_provider_token_ref(
cls, event: Action
) -> list[ProviderType]:
"""Detect if agent run action is using a provider token (e.g $GITHUB_TOKEN)
Returns a list of providers which are called by the agent
"""
if not isinstance(event, CmdRunAction):
... | @@ -449,7 +449,10 @@ def get_provider_env_key(cls, provider: ProviderType) -> str:
return f'{provider.value}_token'.lower()
async def verify_repo_provider(
- self, repository: str, specified_provider: ProviderType | None = None
+ self,
+ repository: str,
+ specified_provider:... | openhands/integrations/provider.py | 26 | Python | 0.429 | nitpick | 85 | 51 | 51 | false | Fix excessive error logging for missing org-level microagents | 11,425 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 | neubig |
print_formatted_text(
HTML(f'<grey> {i}. {tool_name}: {html.escape(action_content)}...</grey>')
)
question = 'Choose an option:'
options = [
'Yes, proceed',
'Reject',
"Always proceed (don't ask again)",
]
if not using_risk_based_policy:
opti... | ```suggestion
reason = cli_text_input('Reason (and let OpenHands know why): ').strip()
```
It's always possible to enter an empty user message, if people want to, right? I don't know if we need to document that. I'd guess most of the time one doesn't want the LLM to do the thing, so they'd say something.... | print_formatted_text(
HTML(f'<grey> {i}. {tool_name}: {html.escape(action_content)}...</grey>')
)
question = 'Choose an option:'
options = [
'Yes, proceed',
'Reject',
"Always proceed (don't ask again)",
]
if not using_risk_based_policy:
opti... | @@ -61,32 +60,18 @@ def ask_user_confirmation(
if index == 0:
return ConfirmationResult(decision=UserConfirmation.ACCEPT)
elif index == 1:
- return ConfirmationResult(decision=UserConfirmation.REJECT)
- elif index == 2:
+ # Handle "Reject" option with optional reason
try:
- ... | openhands-cli/openhands_cli/user_actions/agent_action.py | 26 | Python | 0.857 | suggestion | 401 | 42 | 42 | false | Simplify security analyzer confirmation: replace two reject options with single 'Reject' option | 11,443 | All-Hands-AI/OpenHands | 55,974 | Python | enyst | malhotra5 |
parser.add_argument(
'--git-user-email',
type=str,
default='openhands@all-hands.dev',
help='Git user email for commits',
)
my_args = parser.parse_args()
token = my_args.token or os.getenv('GITHUB_TOKEN') or os.getenv('GITLAB_TOKEN')
if not token:
raise ValueE... | ```suggestion
base_url = my_args.llm_base_url or os.environ.get('LLM_BASE_URL')
``` | parser.add_argument(
'--git-user-email',
type=str,
default='openhands@all-hands.dev',
help='Git user email for commits',
)
my_args = parser.parse_args()
token = my_args.token or os.getenv('GITHUB_TOKEN') or os.getenv('GITLAB_TOKEN')
if not token:
raise ValueE... | @@ -707,10 +708,22 @@ def main() -> None:
)
api_key = my_args.llm_api_key or os.environ['LLM_API_KEY']
+ model_name = my_args.llm_model or os.environ['LLM_MODEL']
+ env_base_url = os.environ.get('LLM_BASE_URL')
+ configured_base_url = my_args.llm_base_url | openhands/resolver/send_pull_request.py | 26 | Python | 0.571 | suggestion | 87 | 51 | 51 | false | localhost base_url fixup when running in a docker container | 11,474 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 | eddierichter-amd |
await conversation_store.delete_metadata(conversation_id)
return True
@app.get('/conversations/{conversation_id}/remember-prompt')
async def get_prompt(
event_id: int,
conversation_id: str = Depends(validate_conversation_id),
user_settings: SettingsStore = Depends(get_user_settings_store),
met... | ```suggestion
```
We don't use global envs for settings (except for the resolver); `settings.llm_base_url` should be enough! | await conversation_store.delete_metadata(conversation_id)
return True
@app.get('/conversations/{conversation_id}/remember-prompt')
async def get_prompt(
event_id: int,
conversation_id: str = Depends(validate_conversation_id),
user_settings: SettingsStore = Depends(get_user_settings_store),
met... | @@ -501,10 +502,21 @@ async def get_prompt(
# placeholder for error handling
raise ValueError('Settings not found')
+ env_base_url = os.environ.get('LLM_BASE_URL') | openhands/server/routes/manage_conversations.py | 26 | Python | 0.786 | suggestion | 125 | 51 | 51 | false | localhost base_url fixup when running in a docker container | 11,474 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 | eddierichter-amd |
my_args = parser.parse_args()
token = my_args.token or os.getenv('GITHUB_TOKEN') or os.getenv('GITLAB_TOKEN')
if not token:
raise ValueError(
'token is not set, set via --token or GITHUB_TOKEN or GITLAB_TOKEN environment variable.'
)
username = my_args.username if my_args.us... | NIT: this conditional logic seems to appear in multiple places
Could we dedup this by having `get_effective_llm_base_url` early return the `base_url` param if `base_url not in (None, ''):` | my_args = parser.parse_args()
token = my_args.token or os.getenv('GITHUB_TOKEN') or os.getenv('GITLAB_TOKEN')
if not token:
raise ValueError(
'token is not set, set via --token or GITHUB_TOKEN or GITLAB_TOKEN environment variable.'
)
username = my_args.username if my_args.us... | @@ -707,10 +708,19 @@ def main() -> None:
)
api_key = my_args.llm_api_key or os.environ['LLM_API_KEY']
+ model_name = my_args.llm_model or os.environ['LLM_MODEL']
+ base_url = my_args.llm_base_url or os.environ.get('LLM_BASE_URL')
+ if base_url not in (None, ''):
+ resolved_base_url = base_u... | openhands/resolver/send_pull_request.py | 26 | Python | 0.571 | nitpick | 190 | 51 | 51 | false | localhost base_url fixup when running in a docker container | 11,474 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 | eddierichter-amd |
* @returns True if the user is on a mobile device, false otherwise
*/
export const isMobileDevice = (): boolean =>
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
navigator.userAgent,
) ||
"ontouchstart" in window ||
navigator.maxTouchPoints > 0;
/**
* Checks if the current domain... | Convert into a hook `useIsAllHandsSaaSEnvironment` so we don’t have to do manual fn calls to get this data
```tsx
const isAllHandsSaaSEnvironment = useIsAllHandsSaaSEnvironment()
``` | * @returns True if the user is on a mobile device, false otherwise
*/
export const isMobileDevice = (): boolean =>
/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(
navigator.userAgent,
) ||
"ontouchstart" in window ||
navigator.maxTouchPoints > 0;
/**
* Checks if the current domain... | @@ -57,6 +57,17 @@ export const isMobileDevice = (): boolean =>
export const isProductionDomain = (): boolean =>
window.location.origin === PRODUCT_URL.PRODUCTION;
+/**
+ * Checks if the current domain is an All Hands SaaS environment
+ * @returns True if the current domain contains "all-hands.dev" or "openhands.... | frontend/src/utils/utils.ts | 26 | TypeScript | 0.786 | suggestion | 183 | 51 | 51 | false | fix: disable pro subscription upgrade on LLM page for self-hosted installs | 11,479 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | hieptl |
SUBSCRIPTION_PRICE_DATA,
get_default_litellm_model,
)
from server.logger import logger
from storage.billing_session import BillingSession
from storage.database import session_maker
from storage.subscription_access import SubscriptionAccess
from storage.user_settings import UserSettings
from openhands.server.us... | I think there is a flag you can use to figure this out:
```
server_config = load_server_config()
...
if server_config.app_mode == AppMode.SAAS:
...
``` | SUBSCRIPTION_PRICE_DATA,
get_default_litellm_model,
)
from server.logger import logger
from storage.billing_session import BillingSession
from storage.database import session_maker
from storage.subscription_access import SubscriptionAccess
from storage.user_settings import UserSettings
from openhands.server.us... | @@ -31,6 +31,35 @@
billing_router = APIRouter(prefix='/api/billing')
+def is_all_hands_saas_environment(request: Request) -> bool:
+ """Check if the current domain is an All Hands SaaS environment.
+
+ Args:
+ request: FastAPI Request object
+
+ Returns:
+ True if the current domain contains... | enterprise/server/routes/billing.py | 26 | Python | 0.786 | suggestion | 166 | 51 | 51 | false | fix: disable pro subscription upgrade on LLM page for self-hosted installs | 11,479 | All-Hands-AI/OpenHands | 55,974 | Python | tofarr | hieptl |
DEFAULT_INITIAL_BUDGET,
LITE_LLM_API_KEY,
LITE_LLM_API_URL,
LITE_LLM_TEAM_ID,
REQUIRE_PAYMENT,
get_default_litellm_model,
)
from server.logger import logger
from sqlalchemy.orm import sessionmaker
from storage.database import session_maker
from storage.user_settings import UserSettings
from ope... | https://github.com/All-Hands-AI/OpenHands/pull/11265/files#diff-2bb9732bc146221a2682c8cb7a36af5185a6cdc741808206d84221f1a18cd167R25
In the diff above we're changing `user_id` from `string` to `UUID`
This PR ensures that any casting between `user_id` to `UUID` and vice versa will be isolated to this util method | DEFAULT_INITIAL_BUDGET,
LITE_LLM_API_KEY,
LITE_LLM_API_URL,
LITE_LLM_TEAM_ID,
REQUIRE_PAYMENT,
get_default_litellm_model,
)
from server.logger import logger
from sqlalchemy.orm import sessionmaker
from storage.database import session_maker
from storage.user_settings import UserSettings
from ope... | @@ -39,15 +39,46 @@ class SaasSettingsStore(SettingsStore):
session_maker: sessionmaker
config: OpenHandsConfig
+ def get_user_settings_by_keycloak_id( | enterprise/storage/saas_settings_store.py | 26 | Python | 0.786 | suggestion | 314 | 51 | 51 | false | SAAS: dedup fetching user settings from keycloak id | 11,480 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 | malhotra5 |
import { useQueries, useQuery } from "@tanstack/react-query";
import axios from "axios";
import React from "react";
import ConversationService from "#/api/conversation-service/conversation-service.api";
import { useConversationId } from "#/hooks/use-conversation-id";
import { useRuntimeIsReady } from "#/hooks/use-runti... | **suggestion:** To obtain the sandbox_id, instead of making an additional API call, we can reuse the useConversationConfig hook. In this case, the runtime_id can serve as the sandbox_id. | import { useQueries, useQuery } from "@tanstack/react-query";
import axios from "axios";
import React from "react";
import ConversationService from "#/api/conversation-service/conversation-service.api";
import { useConversationId } from "#/hooks/use-conversation-id";
import { useRuntimeIsReady } from "#/hooks/use-runti... | @@ -0,0 +1,105 @@
+import { useQueries, useQuery } from "@tanstack/react-query";
+import axios from "axios";
+import React from "react";
+import ConversationService from "#/api/conversation-service/conversation-service.api";
+import { useConversationId } from "#/hooks/use-conversation-id";
+import { useRuntimeIsReady }... | frontend/src/hooks/query/use-unified-active-host.ts | 25 | TypeScript | 0.429 | suggestion | 186 | 50 | 50 | false | chore(frontend): Add unified hooks for V1 sandbox URLs (VSCode and served hosts) | 11,511 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | amanape |
assert 'wget curl sudo apt-utils git' not in dockerfile_content
assert '-c conda-forge' not in dockerfile_content
assert 'python=3.12' not in dockerfile_content
assert 'https://micro.mamba.pm/install.sh' not in dockerfile_content
# this SHOULD exist when build from versioned
assert 'poetry inst... | @openhands-agent , You need also assert https://github.com/OpenHands/OpenHands/blob/b5e00f577c408867c23a92e61c5b323018828ba0/openhands/runtime/utils/runtime_templates/Dockerfile.j2#L291
To be ensured it is not using https://conda.anaconda.org and openhands package is available in the mirror. | assert 'wget curl sudo apt-utils git' not in dockerfile_content
assert '-c conda-forge' not in dockerfile_content
assert 'python=3.12' not in dockerfile_content
assert 'https://micro.mamba.pm/install.sh' not in dockerfile_content
# this SHOULD exist when build from versioned
assert 'poetry inst... | @@ -218,6 +218,20 @@ def test_generate_dockerfile_build_from_versioned():
)
+def test_generate_dockerfile_channel_alias(monkeypatch):
+ base_image = 'debian:11'
+ alias = 'https://repo.prefix.dev'
+ monkeypatch.setenv('OH_CONDA_CHANNEL_ALIAS', alias)
+ dockerfile_content = _generate_dockerfile(
+ ... | tests/unit/runtime/builder/test_runtime_build.py | 26 | Python | 0.429 | suggestion | 293 | 51 | 51 | false | Configurable conda/mamba channel_alias for runtime builds | 11,516 | All-Hands-AI/OpenHands | 55,974 | Python | marscod | enyst |
if not agent:
raise MissingAgentSpec(
'Agent specification not found. Please configure your agent settings.'
)
return agent
def verify_agent_exists_or_setup_agent() -> Agent:
"""Verify agent specs exists by attempting to load it.
Args:
resume_conversation_id: Conve... | It seems that below in code and docstring, we still assume this is optional?
```
# Use provided conversation_id or generate a random one
if conversation_id is None:
conversation_id = uuid.uuid4()
``` | if not agent:
raise MissingAgentSpec(
'Agent specification not found. Please configure your agent settings.'
)
return agent
def verify_agent_exists_or_setup_agent() -> Agent:
"""Verify agent specs exists by attempting to load it.
"""
settings_screen = SettingsScreen()
... | @@ -26,8 +26,43 @@ class MissingAgentSpec(Exception):
pass
-def setup_conversation(
+
+def load_agent_specs(
conversation_id: str | None = None,
+) -> Agent:
+ agent_store = AgentStore()
+ agent = agent_store.load(session_id=conversation_id)
+ if not agent:
+ raise MissingAgentSpec(
+ ... | openhands-cli/openhands_cli/setup.py | 26 | Python | 0.857 | suggestion | 216 | 51 | 51 | false | CLI: Create conversation last minute | 11,576 | All-Hands-AI/OpenHands | 55,974 | Python | enyst | malhotra5 |
# Translate status
status = None
pod_status = runtime['pod_status'].lower()
if pod_status:
status = POD_STATUS_MAPPING.get(pod_status, None)
# If we failed to get the status from the pod status, fall back to status
if status is Non... | do we really want to hard code this? |
if runtime:
# Translate status
status = None
pod_status = runtime['pod_status'].lower()
if pod_status:
status = POD_STATUS_MAPPING.get(pod_status, None)
# If we failed to get the status from the pod status, fall back to status
... | @@ -150,7 +150,7 @@ async def _to_sandbox_info(
exposed_urls.append(ExposedUrl(name=AGENT_SERVER, url=url))
vscode_url = (
_build_service_url(url, 'vscode')
- + f'/?tkn={session_api_key}&folder={runtime["working_dir"]}'
+ ... | openhands/app_server/sandbox/remote_sandbox_service.py | 26 | Python | 0.071 | question | 36 | 51 | 51 | false | Fix remote sandbox permissions | 11,582 | All-Hands-AI/OpenHands | 55,974 | Python | rbren | tofarr |
<Link key={to} to={to} className="text-decoration-none">
<ContextMenuListItem
onClick={() => handleNavigationClick()}
className="flex items-center gap-2 p-2 hover:bg-[#5C5D62] rounded h-[30px]"
>
{icon}
<span className="text-white text-sm">{t(t... | It would be a good idea to add some external icon as well to let the user know it’ll open in a new tab. | {navItems.map(({ to, text, icon }) => (
<Link key={to} to={to} className="text-decoration-none">
<ContextMenuListItem
onClick={() => handleNavigationClick()}
className="flex items-center gap-2 p-2 hover:bg-[#5C5D62] rounded h-[30px]"
>
{icon}
... | @@ -58,6 +59,21 @@ export function AccountSettingsContextMenu({
<Divider />
+ <a
+ href="https://docs.openhands.dev"
+ target="_blank"
+ rel="noopener noreferrer"
+ className="text-decoration-none"
+ >
+ <ContextMenuListItem
+ onClick={onClose}
+ ... | frontend/src/components/features/context-menu/account-settings-context-menu.tsx | 26 | TypeScript | 0.429 | suggestion | 103 | 26 | 42 | false | Add Documentation link to profile context menu | 11,583 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | jpshackelford |
@pytest.mark.parametrize(
'step_to_cancel',
['type', 'provider', 'model', 'apikey', 'save'],
)
def test_workflow_cancellation_at_each_step(tmp_path: Path, step_to_cancel: str):
screen = make_screen_with_conversation()
# Base happy-path patches
patches = {
'settings_type_confirmation': Magi... | Noting that the test will fail here without the patch introduced to the application code |
def test_all_llms_in_agent_are_updated():
"""Test that modifying LLM settings creates multiple LLMs with same API key but different usage_ids."""
# Create a screen with existing agent settings
screen = SettingsScreen(conversation=None)
initial_llm = LLM(model='openai/gpt-3.5-turbo', api_key=SecretStr('... | @@ -121,6 +121,38 @@ def test_update_existing_settings_workflow(tmp_path: Path):
assert True # If we get here, the workflow completed successfully
+def test_all_llms_in_agent_are_updated():
+ """Test that modifying LLM settings creates multiple LLMs with same API key but different usage_ids."""
+ # Crea... | openhands-cli/tests/settings/test_settings_workflow.py | 26 | Python | 0.214 | bug | 89 | 51 | 51 | false | Hotfix(CLI): make sure to update condenser credentials | 11,587 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 | malhotra5 |
# Confirm save
save_settings_confirmation()
except KeyboardInterrupt:
print_formatted_text(HTML('\n<red>Cancelled settings change.</red>'))
return
# Store the collected settings for persistence
self._save_advanced_settings(
custom_mod... | I think maybe this is the other way around... no, actually the user saves here "global" settings, so I tend to agree it should apply by default to all other LLMs 🤔
I think sooner or later, we'll have the request to update them separately (we had it on V0). Not in scope here, I think maybe [LLM profiles](https://gi... |
# Confirm save
save_settings_confirmation()
except KeyboardInterrupt:
print_formatted_text(HTML('\n<red>Cancelled settings change.</red>'))
return
# Store the collected settings for persistence
self._save_advanced_settings(
custom_mod... | @@ -182,7 +182,14 @@ def _save_llm_settings(self, model, api_key, base_url: str | None = None) -> Non
if not agent:
agent = get_default_cli_agent(llm=llm)
+ # Must update all LLMs | openhands-cli/openhands_cli/tui/settings/settings_screen.py | 26 | Python | 0.643 | suggestion | 414 | 42 | 49 | false | Hotfix(CLI): make sure to update condenser credentials | 11,587 | All-Hands-AI/OpenHands | 55,974 | Python | enyst | malhotra5 |
# Test the executable
if not args.no_test:
dummy_agent = get_default_cli_agent(
llm=LLM(
model='dummy-model',
api_key='dummy-key',
metadata=get_llm_metadata(model_name='dummy-model', llm_type='openhands'),
)
)
if no... | ```suggestion
print('❌ Executable test failed')
``` |
# Test the executable
if not args.no_test:
dummy_agent = get_default_cli_agent(
llm=LLM(
model='dummy-model',
api_key='dummy-key',
metadata=get_llm_metadata(model_name='dummy-model', llm_type='openhands'),
)
)
if no... | @@ -285,4 +283,10 @@ def main() -> int:
if __name__ == '__main__':
- sys.exit(main())
+ try:
+ sys.exit(main())
+ except Exception as e:
+ print(e)
+ print('❌ Executable test failed, build process failed') | openhands-cli/build.py | 26 | Python | 0.571 | bug | 59 | 29 | 29 | false | CLI: fix binary build | 11,591 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 | malhotra5 |
This script packages the OpenHands CLI into a standalone executable binary
using PyInstaller with the custom spec file.
"""
import argparse
import os
import select
import shutil
import subprocess
import sys
import time
from pathlib import Path
from openhands_cli.utils import get_llm_metadata, get_default_cli_agent
f... | This extra `cli_mode` param was causing the build to fail silently |
This script packages the OpenHands CLI into a standalone executable binary
using PyInstaller with the custom spec file.
"""
import argparse
import os
import select
import shutil
import subprocess
import sys
import time
from pathlib import Path
from openhands_cli.utils import get_llm_metadata, get_default_cli_agent
f... | @@ -20,15 +20,6 @@
from openhands.sdk import LLM
-dummy_agent = get_default_cli_agent(
- llm=LLM(
- model='dummy-model',
- api_key='dummy-key',
- metadata=get_llm_metadata(model_name='dummy-model', llm_type='openhands'),
- ),
- cli_mode=True, | openhands-cli/build.py | 26 | Python | 0.357 | bug | 66 | 51 | 51 | false | CLI: fix binary build | 11,591 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 | malhotra5 |
def test_fail_obs_break_O5_O1(self, stuck_detector_mcdc: StuckDetector):
# O5(Oi) != O1(Odi)
history: list[Event] = [
Ai, Odi, Ap, Op, # A1,O1(Odi), A2,O2
Ai, Oi, Ap, Op, # A3,O3(Oi), A4,O4
Ai, Oi, Ap, Op # A5(Oi),O5, A6,O6
]
assert stuc... | Sorry @phenric26 , could we please use English? 😄 | history: list[Event] = [
read_file1_action,
read_file1_observation,
cmd_ls_action,
cmd_ls_observation, # action_1,obs_1, action_2,obs_2
read_file1_action,
read_file2_observation,
cmd_ls_action,
cmd_ls_observation, ... | @@ -793,6 +825,149 @@ def test_is_not_stuck_context_window_error_in_non_headless(self, stuck_detector)
assert stuck_detector.is_stuck(headless_mode=False) is False
mock_warning.assert_not_called()
+ @pytest.fixture
+ def stuck_detector_mcdc(self):
+
+ return StuckDetector(state=... | tests/unit/controller/test_is_stuck.py | 26 | Python | 0.286 | suggestion | 51 | 51 | 51 | false | test: Add MC/DC tests for loop pattern detector (stuck_detector) | 11,600 | All-Hands-AI/OpenHands | 55,974 | Python | enyst | phenric26 |
mock_agent = MagicMock()
mock_verify_agent.return_value = mock_agent
# Mock conversation - only one is created when /new is called
conv1 = MagicMock()
conv1.id = UUID("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")
mock_setup_conversation.return_value = conv1
# One runner instance for the conversa... | ```suggestion
# Trigger /new
# First user message should trigger runner creation
# Then /exit (exit will be auto-accepted)
``` | mock_agent = MagicMock()
mock_verify_agent.return_value = mock_agent
# Mock conversation - only one is created when /new is called
conv1 = MagicMock()
conv1.id = UUID("aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa")
mock_setup_conversation.return_value = conv1
# One runner instance for the conversa... | @@ -74,27 +76,33 @@ def test_new_command_resets_confirmation_mode(
mock_verify_agent.return_value = mock_agent
# Mock conversation - only one is created when /new is called
- conv1 = MagicMock(); conv1.id = UUID('aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa')
+ conv1 = MagicMock()
+ conv1.id = UUID("aaaaaa... | openhands-cli/tests/commands/test_new_command.py | 26 | Python | 0.786 | suggestion | 150 | 35 | 37 | false | CLI: lazy load conversation for `/new` command | 11,601 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 | malhotra5 |
str(conversation_id) for conversation_id in conversation_ids
]
query = await self._secure_select()
query = query.where(
StoredConversationMetadata.conversation_id.in_(conversation_id_strs)
)
result = await self.db_session.execute(query)
rows = resu... | oof scary, hopefully with org changes everything is UUID | str(conversation_id) for conversation_id in conversation_ids
]
query = await self._secure_select()
query = query.where(
StoredConversationMetadata.conversation_id.in_(conversation_id_strs)
)
result = await self.db_session.execute(query)
rows = resu... | @@ -273,7 +273,7 @@ async def save_app_conversation_info(
user_id = await self.user_context.get_user_id()
if user_id:
query = select(StoredConversationMetadata).where(
- StoredConversationMetadata.conversation_id == info.id
+ StoredConversationMetadata.conver... | openhands/app_server/app_conversation/sql_app_conversation_info_service.py | 26 | Python | 0.286 | suggestion | 56 | 51 | 51 | false | Fix for issue where conversations won't start | 11,633 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 | tofarr |
api_key = prompt_api_key(
step_counter,
custom_model.split('/')[0] if len(custom_model.split('/')) > 1 else '',
self.conversation.state.agent.llm.api_key if self.conversation else None,
escapable=escapable,
)
memory_cond... | 🤔 @malhotra5 Did we need this for something in particular? We renamed it and made it a little more of a litellm auxiliary logging helper : `litellm_extra_body`. It was (and is) sent to litellm as extra_body if the litellm proxy is used, and nothing else, I think.
Please see https://github.com/OpenHands/software-ag... | api_key = prompt_api_key(
step_counter,
custom_model.split('/')[0] if len(custom_model.split('/')) > 1 else '',
self.conversation.state.agent.llm.api_key if self.conversation else None,
escapable=escapable,
)
memory_cond... | @@ -180,7 +180,6 @@ def _save_llm_settings(self, model, api_key, base_url: str | None = None) -> Non
api_key=api_key,
base_url=base_url,
usage_id='agent',
- metadata=get_llm_metadata(model_name=model, llm_type='agent'), | openhands-cli/openhands_cli/tui/settings/settings_screen.py | 26 | Python | 0.643 | refactor | 337 | 51 | 51 | false | CLI: align with agent-sdk renames | 11,643 | All-Hands-AI/OpenHands | 55,974 | Python | enyst | enyst |
api_key = prompt_api_key(
step_counter,
custom_model.split('/')[0] if len(custom_model.split('/')) > 1 else '',
self.conversation.state.agent.llm.api_key if self.conversation else None,
escapable=escapable,
)
memory_cond... | @OpenHands please replace all extra_body argument to LLM class with `litellm_extra_body` | api_key = prompt_api_key(
step_counter,
custom_model.split('/')[0] if len(custom_model.split('/')) > 1 else '',
self.conversation.state.agent.llm.api_key if self.conversation else None,
escapable=escapable,
)
memory_cond... | @@ -180,7 +180,7 @@ def _save_llm_settings(self, model, api_key, base_url: str | None = None) -> Non
api_key=api_key,
base_url=base_url,
usage_id='agent',
- metadata=get_llm_metadata(model_name=model, llm_type='agent'),
+ extra_body={"metadata": get_llm_metad... | openhands-cli/openhands_cli/tui/settings/settings_screen.py | 26 | Python | 0.429 | suggestion | 88 | 51 | 51 | false | CLI: align with agent-sdk renames | 11,643 | All-Hands-AI/OpenHands | 55,974 | Python | xingyaoww | enyst |
#!/usr/bin/env python3
"""
Agent chat functionality for OpenHands CLI.
Provides a conversation interface with an AI agent using OpenHands patterns.
"""
import sys
from datetime import datetime
import uuid
from openhands.sdk import (
Message,
TextContent,
)
from openhands.sdk.conversation.state import AgentExe... | @openhands
Read how ConversationExecutionStatus is defined in the repository https://github.com/OpenHands/software-agent-sdk
and how it is used in the current repository at openhands-cli package.
There seems to be a dependency issue: the openhands CLI is dependent on what looks like internal classes from the software... | #!/usr/bin/env python3
"""
Agent chat functionality for OpenHands CLI.
Provides a conversation interface with an AI agent using OpenHands patterns.
"""
import sys
from datetime import datetime
import uuid
from openhands.sdk import (
Message,
TextContent,
)
from openhands.sdk.conversation.state import Conversa... | @@ -12,7 +12,7 @@
Message,
TextContent,
)
-from openhands.sdk.conversation.state import AgentExecutionStatus
+from openhands.sdk.conversation.state import ConversationExecutionStatus | openhands-cli/openhands_cli/agent_chat.py | 15 | Python | 0.5 | suggestion | 560 | 40 | 40 | false | CLI: align with agent-sdk renames | 11,643 | All-Hands-AI/OpenHands | 55,974 | Python | simonrosenberg | enyst |
import { VSCodeTooltipContent } from "./vscode-tooltip-content";
import {
useConversationStore,
type ConversationTab,
} from "#/state/conversation-store";
import { USE_PLANNING_AGENT } from "#/utils/feature-flags";
export function ConversationTabs() {
const {
selectedTab,
isRightPanelShown,
setHasRig... | ```suggestion
const shouldUsePlanningAgent = USE_PLANNING_AGENT();
``` | import { VSCodeTooltipContent } from "./vscode-tooltip-content";
import {
useConversationStore,
type ConversationTab,
} from "#/state/conversation-store";
import { USE_PLANNING_AGENT } from "#/utils/feature-flags";
export function ConversationTabs() {
const {
selectedTab,
isRightPanelShown,
setHasRig... | @@ -34,6 +36,8 @@ export function ConversationTabs() {
const [persistedIsRightPanelShown, setPersistedIsRightPanelShown] =
useLocalStorage<boolean>("conversation-right-panel-shown", true);
+ const usePlanningAgent = USE_PLANNING_AGENT(); | frontend/src/components/features/conversation/conversation-tabs/conversation-tabs.tsx | 26 | TypeScript | 0.643 | suggestion | 72 | 51 | 51 | false | feat(frontend): create new planner tab in the interface | 11,646 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | hieptl |
icon: TerminalIcon,
onClick: () => onTabSelected("terminal"),
tooltipContent: t(I18nKey.COMMON$TERMINAL),
tooltipAriaLabel: t(I18nKey.COMMON$TERMINAL),
label: t(I18nKey.COMMON$TERMINAL),
className: "pl-2",
},
{
isActive: isTabActive("served"),
icon: ServerIcon,
... | ```suggestion
if (shouldUsePlanningAgent) {
``` | icon: TerminalIcon,
onClick: () => onTabSelected("terminal"),
tooltipContent: t(I18nKey.COMMON$TERMINAL),
tooltipAriaLabel: t(I18nKey.COMMON$TERMINAL),
label: t(I18nKey.COMMON$TERMINAL),
className: "pl-2",
},
{
isActive: isTabActive("served"),
icon: ServerIcon,
... | @@ -129,6 +133,17 @@ export function ConversationTabs() {
},
];
+ if (usePlanningAgent) { | frontend/src/components/features/conversation/conversation-tabs/conversation-tabs.tsx | 26 | TypeScript | 0.5 | suggestion | 49 | 51 | 51 | false | feat(frontend): create new planner tab in the interface | 11,646 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | hieptl |
const getInitialRightPanelState = (): boolean => {
const stored = localStorage.getItem("conversation-right-panel-shown");
return stored !== null ? JSON.parse(stored) : true;
};
export const useConversationStore = create<ConversationStore>()(
devtools(
(set) => ({
// Initial state
isRightPanelShow... | Is this hardcoded prompt here intentionally left in? |
type ConversationStore = ConversationState & ConversationActions;
// Helper function to get initial right panel state from localStorage
const getInitialRightPanelState = (): boolean => {
const stored = localStorage.getItem("conversation-right-panel-shown");
return stored !== null ? JSON.parse(stored) : true;
};
... | @@ -74,6 +75,91 @@ export const useConversationStore = create<ConversationStore>()(
submittedMessage: null,
shouldHideSuggestions: false,
hasRightPanelToggled: true,
+ planContent: `
+# Improve Developer Onboarding and Examples | frontend/src/state/conversation-store.ts | 26 | TypeScript | 0.214 | question | 52 | 51 | 51 | false | feat(frontend): display plan content within the planner tab | 11,658 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | hieptl |
i18nKey: I18nKey.COMMON$BROWSER,
},
];
if (shouldUsePlanningAgent) {
tabConfig.unshift({
tab: "planner",
icon: LessonPlanIcon,
i18nKey: I18nKey.COMMON$PLANNER,
});
}
if (!isOpen) return null;
const handleTabClick = (tab: string) => {
const tabString = tab;
if (un... | ```suggestion
```
I think it’d be better to close only when the user clicks away | i18nKey: I18nKey.COMMON$BROWSER,
},
];
if (shouldUsePlanningAgent) {
tabConfig.unshift({
tab: "planner",
icon: LessonPlanIcon,
i18nKey: I18nKey.COMMON$PLANNER,
});
}
if (!isOpen) return null;
const handleTabClick = (tab: string) => {
const tabString = tab;
if (un... | @@ -0,0 +1,117 @@
+import { useTranslation } from "react-i18next";
+import { useLocalStorage } from "@uidotdev/usehooks";
+import { ContextMenu } from "#/ui/context-menu";
+import { ContextMenuListItem } from "../../context-menu/context-menu-list-item";
+import { useClickOutsideElement } from "#/hooks/use-click-outside... | frontend/src/components/features/conversation/conversation-tabs/conversation-tabs-context-menu.tsx | 26 | TypeScript | 0.643 | suggestion | 81 | 51 | 51 | false | feat(frontend): enable pinning and unpinning of conversation tabs | 11,659 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | hieptl |
removeFile: (index: number) => void;
clearImages: () => void;
clearFiles: () => void;
clearAllFiles: () => void;
addFileLoading: (fileName: string) => void;
removeFileLoading: (fileName: string) => void;
addImageLoading: (imageName: string) => void;
removeImageLoading: (imageName: string) => void;
cle... | Wouldn’t we want to get `conversation-right-panel-shown-${conversationId}` now instead of always showing the right panel on initial render? | removeImage: (index: number) => void;
removeFile: (index: number) => void;
clearImages: () => void;
clearFiles: () => void;
clearAllFiles: () => void;
addFileLoading: (fileName: string) => void;
removeFileLoading: (fileName: string) => void;
addImageLoading: (imageName: string) => void;
removeImageLoa... | @@ -58,17 +58,11 @@ interface ConversationActions {
type ConversationStore = ConversationState & ConversationActions;
-// Helper function to get initial right panel state from localStorage
-const getInitialRightPanelState = (): boolean => {
- const stored = localStorage.getItem("conversation-right-panel-shown");
... | frontend/src/state/conversation-store.ts | 26 | TypeScript | 0.571 | question | 139 | 51 | 51 | false | fix: conversation tab state sync across browser tabs | 11,680 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | naaa760 |
useActiveConversation();
function flushPendingEvents(socket: Socket | null = sioRef.current) {
if (!socket || pendingEventsRef.current.length === 0) {
return;
}
pendingEventsRef.current.forEach((queuedEvent) => {
socket.emit("oh_user_action", queuedEvent);
});
pendingEventsRef.cu... | ```suggestion
EventLogger.error("WebSocket is not connected, queuing message...");
pendingEventsRef.current.push(event);
``` | const [webSocketStatus, setWebSocketStatus] =
React.useState<V0_WebSocketStatus>("DISCONNECTED");
const lastEventRef = React.useRef<Record<string, unknown> | null>(null);
const { providers } = useUserProviders();
const messageRateHandler = useRate({ threshold: 250 });
const { data: conversation, refetch:... | @@ -145,17 +145,36 @@ export function WsClientProvider({
const { data: conversation, refetch: refetchConversation } =
useActiveConversation();
+ function flushPendingEvents(socket: Socket | null = sioRef.current) {
+ if (!socket || pendingEventsRef.current.length === 0) {
+ return;
+ }
+
+ pend... | frontend/src/context/ws-client-provider.tsx | 26 | TypeScript | 0.857 | suggestion | 136 | 51 | 51 | false | feat: queue chat messages during runtime connection | 11,687 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | naaa760 |
/* eslint-disable react/react-in-jsx-scope */
/**
* By default, Remix will handle hydrating your app on the client for you.
* You are free to delete this file if you'd like to, but if you ever want it revealed again, you can run `npx remix reveal` ✨
* For more information, see https://remix.run/file-conventions/entr... | **suggestion (non-blocking):** We specify a type when defining the posthogClientKey state. To maintain consistency, we should also specify a type when defining the isLoading state.
```js
const [isLoading, setIsLoading] = React.useState<boolean>(true);
``` | /* eslint-disable react/react-in-jsx-scope */
/**
* By default, Remix will handle hydrating your app on the client for you.
* You are free to delete this file if you'd like to, but if you ever want it revealed again, you can run `npx remix reveal` ✨
* For more information, see https://remix.run/file-conventions/entr... | @@ -8,17 +8,18 @@
import { HydratedRouter } from "react-router/dom";
import React, { startTransition, StrictMode } from "react";
import { hydrateRoot } from "react-dom/client";
-import posthog from "posthog-js";
+import { PostHogProvider } from "posthog-js/react";
import "./i18n";
import { QueryClientProvider } fr... | frontend/src/entry.client.tsx | 22 | TypeScript | 1 | suggestion | 262 | 47 | 47 | false | refactor(frontend): migrate from direct posthog imports to usePostHog hook | 11,703 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | amanape |
import OptionService from "./api/option-service/option-service.api";
import { displayErrorToast } from "./utils/custom-toast-handlers";
import { queryClient } from "./query-client-config";
function PostHogWrapper({ children }: { children: React.ReactNode }) {
const [posthogClientKey, setPosthogClientKey] = React.use... | **suggestion (non-blocking):** The two if statements return the same result, so they can be combined to simplify the code.
```js
if (isLoading || !posthogClientKey) {
return children;
}
``` | import OptionService from "./api/option-service/option-service.api";
import { displayErrorToast } from "./utils/custom-toast-handlers";
import { queryClient } from "./query-client-config";
function PostHogWrapper({ children }: { children: React.ReactNode }) {
const [posthogClientKey, setPosthogClientKey] = React.use... | @@ -27,20 +28,31 @@ function PosthogInit() {
setPosthogClientKey(config.POSTHOG_CLIENT_KEY);
} catch {
displayErrorToast("Error fetching PostHog client key");
+ } finally {
+ setIsLoading(false);
}
})();
}, []);
- React.useEffect(() => {
- if (posthogClientKey) ... | frontend/src/entry.client.tsx | 26 | TypeScript | 0.786 | refactor | 198 | 51 | 51 | false | refactor(frontend): migrate from direct posthog imports to usePostHog hook | 11,703 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | amanape |
function PostHogWrapper({ children }: { children: React.ReactNode }) {
const [posthogClientKey, setPosthogClientKey] = React.useState<string | null>(
null,
);
const [isLoading, setIsLoading] = React.useState(true);
React.useEffect(() => {
(async () => {
try {
const config = await OptionSe... | ```suggestion
if (isLoading || !posthogClientKey) {
return children;
}
``` | function PostHogWrapper({ children }: { children: React.ReactNode }) {
const [posthogClientKey, setPosthogClientKey] = React.useState<string | null>(
null,
);
const [isLoading, setIsLoading] = React.useState(true);
React.useEffect(() => {
(async () => {
try {
const config = await OptionSe... | @@ -27,20 +28,31 @@ function PosthogInit() {
setPosthogClientKey(config.POSTHOG_CLIENT_KEY);
} catch {
displayErrorToast("Error fetching PostHog client key");
+ } finally {
+ setIsLoading(false);
}
})();
}, []);
- React.useEffect(() => {
- if (posthogClientKey) ... | frontend/src/entry.client.tsx | 26 | TypeScript | 0.571 | suggestion | 82 | 51 | 51 | false | refactor(frontend): migrate from direct posthog imports to usePostHog hook | 11,703 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | amanape |
Returns:
The parent conversation info if valid
Raises:
ValueError: If parent conversation not found or access denied
"""
parent_info = (
await self.app_conversation_info_service.get_app_conversation_info(
parent_conversation_id
... | I love this! I take it we are considering to support the user choosing a different model in some way, when they use planning agent? ❤️ | ) -> None:
"""Inherit configuration from parent conversation if not explicitly provided.
This ensures sub-conversations automatically inherit:
- Sandbox ID (to share the same workspace/environment)
- Git parameters (repository, branch, provider)
- LLM model
Args:
... | @@ -452,11 +466,72 @@ def _get_agent_server_url(self, sandbox: SandboxInfo) -> str:
)
return agent_server_url
+ async def _validate_and_get_parent_conversation(
+ self, parent_conversation_id: UUID, user_id: str | None = None
+ ) -> AppConversationInfo:
+ """Validate and retrieve... | openhands/app_server/app_conversation/live_status_app_conversation_service.py | 26 | Python | 0.429 | suggestion | 134 | 51 | 51 | false | feat(backend): enable sub-conversation creation using a different agent | 11,715 | All-Hands-AI/OpenHands | 55,974 | Python | enyst | hieptl |
return agent_server_url
async def _validate_and_get_parent_conversation(
self, parent_conversation_id: UUID, user_id: str | None = None
) -> AppConversationInfo:
"""Validate and retrieve parent conversation info.
Args:
parent_conversation_id: The ID of the parent co... | Is this necessary here, in `openhands/app_server/app_conversation/live_status_app_conversation_service.py` ?
It seems to me that authorization code should happen before it gets here. Hopefully in the creation/validation of the request, that is, somewhere in or where `UserContext` is injected | assert exposed_urls is not None
agent_server_url = next(
exposed_url.url
for exposed_url in exposed_urls
if exposed_url.name == AGENT_SERVER
)
return agent_server_url
def _inherit_configuration_from_parent(
self, request: AppConversationSt... | @@ -452,11 +466,72 @@ def _get_agent_server_url(self, sandbox: SandboxInfo) -> str:
)
return agent_server_url
+ async def _validate_and_get_parent_conversation(
+ self, parent_conversation_id: UUID, user_id: str | None = None
+ ) -> AppConversationInfo:
+ """Validate and retrieve... | openhands/app_server/app_conversation/live_status_app_conversation_service.py | 26 | Python | 0.786 | security | 295 | 51 | 51 | false | feat(backend): enable sub-conversation creation using a different agent | 11,715 | All-Hands-AI/OpenHands | 55,974 | Python | enyst | hieptl |
) -> list[AppConversation | None]:
info = await self.app_conversation_info_service.batch_get_app_conversation_info(
conversation_ids
)
conversations = await self._build_app_conversations(info)
return conversations
async def start_app_conversation(
self, reque... | Ah, I see why… 🤔
The thing is, in `_validate_and…` method, the `validate` section is authorization, is security related. So it feels to me that like maybe that validatio code could be up in the stack a bit, where the rest of the auth/authz parameters are validated.
Cc: @tofarr I could be wrong though? | ) -> list[AppConversation | None]:
info = await self.app_conversation_info_service.batch_get_app_conversation_info(
conversation_ids
)
conversations = await self._build_app_conversations(info)
return conversations
async def start_app_conversation(
self, reque... | @@ -168,6 +170,14 @@ async def _start_app_conversation(
) -> AsyncGenerator[AppConversationStartTask, None]:
# Create and yield the start task
user_id = await self.user_context.get_user_id()
+
+ # Validate and inherit from parent conversation if provided
+ if request.parent_conversa... | openhands/app_server/app_conversation/live_status_app_conversation_service.py | 26 | Python | 0.786 | bug | 308 | 51 | 51 | false | feat(backend): enable sub-conversation creation using a different agent | 11,715 | All-Hands-AI/OpenHands | 55,974 | Python | enyst | hieptl |
raise SandboxError(f'Sandbox not startable: {sandbox.id}')
start = time()
while time() - start <= self.sandbox_startup_timeout:
await asyncio.sleep(self.sandbox_startup_poll_frequency)
sandbox_info = await self.sandbox_service.get_sandbox(sandbox.id)
if s... | Since we removed the `validate_` part of the code, we only retrieve the parent conversation now, could we do this directly in the caller, and perhaps remove this method? Just because well, it only does a call now | await self.sandbox_service.resume_sandbox(sandbox.id)
if sandbox.status in (None, SandboxStatus.ERROR):
raise SandboxError(f'Sandbox status: {sandbox.status}')
if sandbox.status == SandboxStatus.RUNNING:
return
if sandbox.status != SandboxStatus.STARTING:
... | @@ -452,11 +466,66 @@ def _get_agent_server_url(self, sandbox: SandboxInfo) -> str:
)
return agent_server_url
+ async def _validate_and_get_parent_conversation( | openhands/app_server/app_conversation/live_status_app_conversation_service.py | 26 | Python | 0.643 | refactor | 212 | 51 | 51 | false | feat(backend): enable sub-conversation creation using a different agent | 11,715 | All-Hands-AI/OpenHands | 55,974 | Python | enyst | hieptl |
const { t } = useTranslation();
const isAgentRunning = curAgentState === AgentState.RUNNING;
const { data: conversation } = useActiveConversation();
const { mutate: createConversation, isPending: isCreatingConversation } =
useCreateConversation();
// Close context menu when agent starts running
useE... | Are we checking by “plan” here? It just looks like we’re checking if `sub_conversation_ids` is not empty or there is no conversation ID. Or do “plan” conversations not have any conversation IDs and that is why we are checking it here? |
const { t } = useTranslation();
const isAgentRunning = curAgentState === AgentState.RUNNING;
const { data: conversation } = useActiveConversation();
const { mutate: createConversation, isPending: isCreatingConversation } =
useCreateConversation();
// Close context menu when agent starts running
useE... | @@ -28,15 +30,55 @@ export function ChangeAgentButton() {
const { curAgentState } = useAgentState();
+ const { t } = useTranslation();
+
const isAgentRunning = curAgentState === AgentState.RUNNING;
+ const { data: conversation } = useActiveConversation();
+ const { mutate: createConversation, isPending: ... | frontend/src/components/features/chat/change-agent-button.tsx | 26 | TypeScript | 0.571 | question | 234 | 51 | 51 | false | feat(frontend): integrate with the API to create a sub-conversation for the planning agent | 11,730 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | hieptl |
app_conversation_info_service: AppConversationInfoService,
sandbox_service: SandboxService,
db_session: AsyncSession,
httpx_client: httpx.AsyncClient,
) -> bool | None:
"""Try to delete a V1 conversation. Returns None if not a V1 conversation."""
result = None
try:
conversation_uuid ... | **question:** Am I correct in understanding that if we proceed this way, deleting the sandbox will occur in a separate transaction, rather than in the same transaction as deleting app_conversation? | conversation_id: str,
app_conversation_service: AppConversationService,
app_conversation_info_service: AppConversationInfoService,
sandbox_service: SandboxService,
db_session: AsyncSession,
httpx_client: httpx.AsyncClient,
) -> bool | None:
"""Try to delete a V1 conversation. Returns None if... | @@ -527,10 +536,14 @@ async def _try_delete_v1_conversation(
result = await app_conversation_service.delete_app_conversation(
app_conversation_info.id
)
+
+ # Manually commit so that the conversation will vanish from the list
+ await db_session.commit() | openhands/server/routes/manage_conversations.py | 26 | Python | 0.357 | question | 197 | 51 | 51 | false | Bumped Software Agent SDK and fixed V1 Delete | 11,768 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | tofarr |
settings?.CONFIRMATION_MODE ?? DEFAULT_SETTINGS.CONFIRMATION_MODE,
);
// Track selected security analyzer for form submission
const [selectedSecurityAnalyzer, setSelectedSecurityAnalyzer] =
React.useState(
settings?.SECURITY_ANALYZER === null
? "none"
: (settings?.SECURITY_ANALYZER ... | I think we should not use BYOR Key? I remember there's another LiteLLM API key exist in additional to BYOR key. @OpenHands search in this repo and tell me if that's true. do not change any code, just answer questions |
// Track selected security analyzer for form submission
const [selectedSecurityAnalyzer, setSelectedSecurityAnalyzer] =
React.useState(
settings?.SECURITY_ANALYZER === null
? "none"
: (settings?.SECURITY_ANALYZER ?? DEFAULT_SETTINGS.SECURITY_ANALYZER),
);
const [selectedProvider, s... | @@ -102,10 +104,22 @@ function LlmSettingsScreen() {
: (settings?.SECURITY_ANALYZER ?? DEFAULT_SETTINGS.SECURITY_ANALYZER),
);
+ const [selectedProvider, setSelectedProvider] = React.useState<string | null>(
+ null,
+ );
+
const modelsAndProviders = organizeModelsAndProviders(
resources?.mo... | frontend/src/routes/llm-settings.tsx | 26 | TypeScript | 0.5 | suggestion | 216 | 51 | 51 | false | fix(frontend): hide api key field for openhands provider and auto-populate the key | 11,791 | All-Hands-AI/OpenHands | 55,974 | Python | xingyaoww | hieptl |
const planningAgentConversation = subConversations?.[0];
const currentConversationId =
planningAgentConversation?.id || "test-conversation-id"; // TODO: Get from context
handleActionEventCacheInvalidation(
event,
currentConversationId,
... | Shall we also update it here? I had this PR: https://github.com/OpenHands/software-agent-sdk/pull/1159
which should allow us to stream more fine-grained metrics later |
// Clear optimistic user message when a user message is confirmed
if (isUserMessageEvent(event)) {
removeOptimisticUserMessage();
}
// Handle cache invalidation for ActionEvent
if (isActionEvent(event)) {
const planningAgentConversation = subCo... | @@ -372,6 +407,7 @@ export function ConversationWebSocketProvider({
if (isConversationStateUpdateEvent(event)) {
if (isFullStateConversationStateUpdateEvent(event)) {
setExecutionStatus(event.value.execution_status);
+ updateMetricsFromFullState(event);
}... | frontend/src/contexts/conversation-websocket-context.tsx | 26 | TypeScript | 0.429 | suggestion | 167 | 51 | 51 | false | fix(frontend): resolve issue preventing cost from displaying (V1) | 11,798 | All-Hands-AI/OpenHands | 55,974 | Python | xingyaoww | hieptl |
{
parentConversationId: conversation.conversation_id,
agentType: "plan",
},
{
onSuccess: (data) => {
displaySuccessToast(
t(I18nKey.PLANNING_AGENTT$PLANNING_AGENT_INITIALIZED),
);
// Track the task ID to poll for sub-conversation creati... | Maybe we can define `handlePlanClick` within the conversation store? That way we can avoid implicitly calling it via a use effect and just have it called directly.
| };
document.addEventListener("keydown", handleKeyDown);
return () => {
document.removeEventListener("keydown", handleKeyDown);
};
}, [
isButtonDisabled,
conversationMode,
setConversationMode,
handlePlanClick,
]);
const handleButtonClick = (event: React.MouseEvent<HTMLButto... | @@ -95,6 +97,15 @@ export function ChangeAgentButton() {
);
};
+ // Trigger handlePlanClick when isCreateAPlanClicked becomes true
+ useEffect(() => {
+ if (isCreateAPlanClicked) {
+ handlePlanClick();
+ // Reset the flag after triggering
+ setIsCreateAPlanClicked(false);
+ }
+ }, [isC... | frontend/src/components/features/chat/change-agent-button.tsx | 26 | TypeScript | 0.714 | suggestion | 164 | 51 | 51 | false | feat(frontend): add handler for 'create a plan' button click | 11,806 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | hieptl |
}
/>
</NavLink>
))}
{/* Loading indicator for fetching more conversations */}
{isFetchingNextPage && (
<div className="flex justify-center py-4">
<LoadingSpinner size="small" />
</div>
)}
{confirmDeleteModalVisible && (
<Con... | **suggestion:** Instead of traversing the list of conversations to locate the selected conversation’s title, we can follow the steps below:
**Step 1:** Define a new state variable named selectedConversationTitle:
```ts
const [selectedConversationTitle, setSelectedConversationTitle] =
React.useState<string |... | conversationId={project.conversation_id}
conversationVersion={project.conversation_version}
contextMenuOpen={openContextMenuId === project.conversation_id}
onContextMenuToggle={(isOpen) =>
setOpenContextMenuId(isOpen ? project.conversation_id : null)
... | @@ -214,6 +214,13 @@ export function ConversationPanel({ onClose }: ConversationPanelProps) {
setConfirmDeleteModalVisible(false);
}}
onCancel={() => setConfirmDeleteModalVisible(false)}
+ conversationTitle={
+ selectedConversationId
+ ? conversations.... | frontend/src/components/features/conversation-panel/conversation-panel.tsx | 26 | TypeScript | 1 | suggestion | 1,119 | 51 | 51 | false | fix: display conversation title in delete confirmation modal | 11,818 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | naaa760 |
import { useTranslation } from "react-i18next";
import {
BaseModalDescription,
BaseModalTitle,
} from "#/components/shared/modals/confirmation-modals/base-modal";
import { ModalBackdrop } from "#/components/shared/modals/modal-backdrop";
import { ModalBody } from "#/components/shared/modals/modal-body";
import { Br... | Hello @naaa760,
Could you please add support for multiple languages to this text? You may refer to the translation.json and declaration.ts files for additional details.
Thank you! 🙏 | import { Trans, useTranslation } from "react-i18next";
import {
BaseModalDescription,
BaseModalTitle,
} from "#/components/shared/modals/confirmation-modals/base-modal";
import { ModalBackdrop } from "#/components/shared/modals/modal-backdrop";
import { ModalBody } from "#/components/shared/modals/modal-body";
impo... | @@ -11,22 +11,26 @@ import { I18nKey } from "#/i18n/declaration";
interface ConfirmDeleteModalProps {
onConfirm: () => void;
onCancel: () => void;
+ conversationTitle?: string;
}
export function ConfirmDeleteModal({
onConfirm,
onCancel,
+ conversationTitle,
}: ConfirmDeleteModalProps) {
const { t... | frontend/src/components/features/conversation-panel/confirm-delete-modal.tsx | 25 | TypeScript | 0.429 | suggestion | 188 | 50 | 50 | false | fix: display conversation title in delete confirmation modal | 11,818 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | naaa760 |
>
{!isLoading && (
<div className="flex flex-col">
{shouldRenderExternalConfigureButtons && !isLoading && (
<>
<div className="pb-1 flex flex-col">
<h3 className="text-xl font-medium text-white">
{t(I18nKey.SETTINGS$GITHUB)}
... | Does this remove it entirely? From Local and Cloud? Or just from Cloud? | {!isLoading && (
<div className="flex flex-col">
{shouldRenderExternalConfigureButtons && !isLoading && (
<>
<div className="pb-1 flex flex-col">
<h3 className="text-xl font-medium text-white">
{t(I18nKey.SETTINGS$GITHUB)}
... | @@ -153,18 +152,6 @@ function GitSettingsScreen() {
</>
)}
- {shouldRenderExternalConfigureButtons && !isLoading && (
- <>
- <div className="pb-1 mt-6 flex flex-col">
- <h3 className="text-xl font-medium text-white">
- {t(I18nKey... | frontend/src/routes/git-settings.tsx | 26 | TypeScript | 0.286 | question | 71 | 51 | 51 | false | fix(frontend): Remove azure devops integration button from cloud settings | 11,826 | All-Hands-AI/OpenHands | 55,974 | Python | mamoodi | hieptl |
// SkillReadyEvent is not an observation event, so skip the observation checks
if (!isSkillReadyEvent(event)) {
if (isObservationEvent(event)) {
if (event.observation.kind === "TaskTrackerObservation") {
return <div>{details}</div>;
}
if (event.observation.kind === "FinishObservation")... | If this is copy-pasted code from elsewhere, we should probably move it to it’s own component and reuse it in both places | import { OpenHandsEvent } from "#/types/v1/core";
import { GenericEventMessage } from "../../../features/chat/generic-event-message";
import { getEventContent } from "../event-content-helpers/get-event-content";
import { getObservationResult } from "../event-content-helpers/get-observation-result";
import { isObservati... | @@ -23,11 +38,32 @@ export function GenericEventMessageWrapper({
// SkillReadyEvent is not an observation event, so skip the observation checks
if (!isSkillReadyEvent(event)) {
- if (
- isObservationEvent(event) &&
- event.observation.kind === "TaskTrackerObservation"
- ) {
- return <div>{d... | frontend/src/components/v1/chat/event-message-components/generic-event-message-wrapper.tsx | 26 | TypeScript | 0.429 | suggestion | 120 | 51 | 62 | false | fix(frontend): the content of the FinishObservation event is not being rendered correctly. | 11,846 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | hieptl |
== 'https://mcp.tavily.com/mcp/?tavilyApiKey=env_tavily_key'
)
@patch(
'openhands.app_server.app_conversation.live_status_app_conversation_service.get_planning_tools'
)
@patch(
'openhands.app_server.app_conversation.app_conversation_service_base.AppConversationServiceBas... | Could we have a test that actually tests for the `max_size` that this PR proposes to add? | == 'https://mcp.tavily.com/mcp/?tavilyApiKey=env_tavily_key'
)
@patch(
'openhands.app_server.app_conversation.live_status_app_conversation_service.get_planning_tools'
)
@patch(
'openhands.app_server.app_conversation.app_conversation_service_base.AppConversationServiceBas... | @@ -421,23 +422,25 @@ async def test_configure_llm_and_mcp_tavily_with_whitespace_user_search_key(self
'openhands.app_server.app_conversation.live_status_app_conversation_service.get_planning_tools'
)
@patch(
- 'openhands.app_server.app_conversation.live_status_app_conversation_service.get_pla... | tests/unit/app_server/test_live_status_app_conversation_service.py | 26 | Python | 0.429 | question | 89 | 51 | 51 | false | fix(backend): apply user-defined condenser_max_size in new v1 conversations | 11,862 | All-Hands-AI/OpenHands | 55,974 | Python | enyst | hieptl |
return
_logger.info('Git pre-commit hook installed successfully')
def _create_condenser(
self,
llm: LLM,
agent_type: AgentType,
user: UserInfo,
) -> LLMSummarizingCondenser:
"""Create a condenser based on user settings and agent type.
Args:
... | IMHO this isn't a significant difference (100 compared to 80, 6 to 4), and maybe it shouldn't be any difference.
I was looking at the tests and it seems that creating condenser needs multiple mocks from Agent, which... doesn't really make a lot sense to me.
Maybe the method creating a `condenser` could be indepen... | workspace: AsyncRemoteWorkspace,
):
"""Set up git hooks if .openhands/pre-commit.sh exists in the workspace or repository."""
command = 'mkdir -p .git/hooks && chmod +x .openhands/pre-commit.sh'
result = await workspace.execute_command(command, workspace.working_dir)
if resul... | @@ -300,3 +304,52 @@ async def maybe_setup_git_hooks(
return
_logger.info('Git pre-commit hook installed successfully')
+
+ def _create_condenser(
+ self,
+ llm: LLM,
+ agent_type: AgentType,
+ user: UserInfo,
+ ) -> LLMSummarizingCondenser:
+ """Create a... | openhands/app_server/app_conversation/app_conversation_service_base.py | 26 | Python | 0.786 | question | 560 | 51 | 51 | false | fix(backend): apply user-defined condenser_max_size in new v1 conversations | 11,862 | All-Hands-AI/OpenHands | 55,974 | Python | enyst | hieptl |
_logger.error(f'Failed to make pre-commit hook executable: {result.stderr}')
return
_logger.info('Git pre-commit hook installed successfully')
def _create_condenser(
self,
llm: LLM,
agent_type: AgentType,
user: UserInfo,
) -> LLMSummarizingConden... | Actually, @hieptl , we have the defaults in `LLMSummarizingCondenser` itself:
https://github.com/OpenHands/software-agent-sdk/blob/a106684194dc5e2a5869e4f06888e8d66489d4ae/openhands-sdk/openhands/sdk/context/condenser/llm_summarizing_condenser.py#L16
Maybe we don't need to hardcode them again? | self,
workspace: AsyncRemoteWorkspace,
):
"""Set up git hooks if .openhands/pre-commit.sh exists in the workspace or repository."""
command = 'mkdir -p .git/hooks && chmod +x .openhands/pre-commit.sh'
result = await workspace.execute_command(command, workspace.working_dir)
... | @@ -300,3 +304,47 @@ async def maybe_setup_git_hooks(
return
_logger.info('Git pre-commit hook installed successfully')
+
+ def _create_condenser(
+ self,
+ llm: LLM,
+ agent_type: AgentType,
+ user: UserInfo,
+ ) -> LLMSummarizingCondenser:
+ """Create a... | openhands/app_server/app_conversation/app_conversation_service_base.py | 26 | Python | 0.571 | question | 301 | 49 | 51 | false | fix(backend): apply user-defined condenser_max_size in new v1 conversations | 11,862 | All-Hands-AI/OpenHands | 55,974 | Python | enyst | hieptl |
if tavily_api_key:
_logger.info('Adding search engine to MCP config')
mcp_config['tavily'] = {
'url': f'https://mcp.tavily.com/mcp/?tavilyApiKey={tavily_api_key}'
}
else:
_logger.info('No search engine API key fo... | ```suggestion
settings: Settings like condenser_max_size
```
Totally a nit, but we were really going in the opposite direction here with some PRs (like the org PR), where we consider "user stuff" to be just "stuff". It seems to me now that it's unfortunate that we have a model named `UserInfo` that doesn... | if tavily_api_key:
_logger.info('Adding search engine to MCP config')
mcp_config['tavily'] = {
'url': f'https://mcp.tavily.com/mcp/?tavilyApiKey={tavily_api_key}'
}
else:
_logger.info('No search engine API key fo... | @@ -651,20 +650,22 @@ def _create_agent_with_context(
agent_type: Type of agent to create (PLAN or DEFAULT)
system_message_suffix: Optional suffix for system messages
mcp_config: MCP configuration dictionary
+ user: User information containing settings like condenser_ma... | openhands/app_server/app_conversation/live_status_app_conversation_service.py | 26 | Python | 0.857 | suggestion | 632 | 51 | 51 | false | fix(backend): apply user-defined condenser_max_size in new v1 conversations | 11,862 | All-Hands-AI/OpenHands | 55,974 | Python | enyst | hieptl |
if (!searchQuery.trim()) {
return true;
}
const sanitizedQuery = sanitizeQuery(searchQuery);
const sanitizedRepoName = sanitizeQuery(repo.full_name);
return sanitizedRepoName.includes(sanitizedQuery);
};
/**
* Get the OpenHands query string based on the provider
* @param provider The git provider
* @... | ```suggestion
const providerRepositorySuffix: Record<string, string> = {
gitlab: "openhands-config",
azure_devops: "openhands-config",
default: ".openhands",
} as const;
return provider && provider in providerRepositorySuffix
? providerRepositorySuffix[provider]
: providerRepositoryS... | if (!searchQuery.trim()) {
return true;
}
const sanitizedQuery = sanitizeQuery(searchQuery);
const sanitizedRepoName = sanitizeQuery(repo.full_name);
return sanitizedRepoName.includes(sanitizedQuery);
};
/**
* Get the OpenHands query string based on the provider
* @param provider The git provider
* @... | @@ -606,10 +606,17 @@ export const shouldIncludeRepository = (
* @returns The query string for searching OpenHands repositories
*/
export const getOpenHandsQuery = (provider: Provider | null): string => {
- if (provider === "gitlab") {
- return "openhands-config";
- }
- return ".openhands";
+ const provider... | frontend/src/utils/utils.ts | 26 | TypeScript | 0.786 | suggestion | 415 | 51 | 51 | false | refactor/bugfix: simplify hasOpenHandsSuffix with provider lookup for gitlab/azure | 11,877 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | vinisdl |
return (
<div className="flex items-center justify-between py-4">
<div className="flex items-center gap-2">
<span
className={cn(
"text-sm font-semibold",
status === "invited" && "text-gray-400",
)}
>
{email}
</span>
{statu... | You an use Tailwind's capitalize: https://tailwindcss.com/docs/text-transform | return (
<div className="flex items-center justify-between py-4">
<div className="flex items-center gap-2">
<span
className={cn(
"text-sm font-semibold",
status === "invited" && "text-gray-400",
)}
>
{email}
</span>
{statu... | @@ -51,42 +55,25 @@ export function OrganizationMemberListItem({
</span>
)}
</div>
- <span
- onClick={() => setRoleSelectionOpen(true)}
- className={cn(
- "text-xs text-gray-400 uppercase flex items-center gap-1",
- roleSelectionIsPermitted ? "cursor-point... | frontend/src/components/features/org/organization-member-list-item.tsx | 26 | TypeScript | 0.286 | suggestion | 77 | 40 | 40 | false | refactor(frontend): update role dropdown styles in the team page (org support) | 11,906 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | hieptl |
else:
# Use static token for environments without web URL access
static_token = await self.user_context.get_latest_token(git_provider)
if static_token:
secrets[secret_name] = StaticSecret(value=static_token)
return secrets
async def _configure_ll... | Do we want to give user the ability to overwrite this base url? probably not? | )
else:
# Use static token for environments without web URL access
static_token = await self.user_context.get_latest_token(git_provider)
if static_token:
secrets[secret_name] = StaticSecret(value=static_token)
return secrets
async def... | @@ -586,9 +587,12 @@ async def _configure_llm_and_mcp(
"""
# Configure LLM
model = llm_model or user.llm_model
+ base_url = user.llm_base_url
+ if model and model.startswith('openhands/'):
+ base_url = user.llm_base_url or self.openhands_provider_base_url | openhands/app_server/app_conversation/live_status_app_conversation_service.py | 26 | Python | 0.286 | question | 77 | 51 | 51 | false | fix: switching from own model to breaks functionality | 11,916 | All-Hands-AI/OpenHands | 55,974 | Python | xingyaoww | hieptl |
await user.type(amountInput, "9");
await waitFor(() => {
const errorMessage = screen.getByTestId("amount-error");
expect(errorMessage).toHaveTextContent(
"PAYMENT$ERROR_MINIMUM_AMOUNT",
);
});
});
it("should display error message for amoun... | Hmm, I haven’t thought of this before, but I think we do want to support decimal values. Unless we don’t? |
const addCreditsForm = screen.getByTestId("add-credits-form");
expect(addCreditsForm).toBeInTheDocument();
return { user, addCreditsForm };
};
describe("Button State Management", () => {
it("should enable submit button initially when modal opens", async () => {
await openAddCr... | @@ -162,6 +162,511 @@ describe("Manage Org Route", () => {
expect(createCheckoutSessionSpy).not.toHaveBeenCalled();
});
+ describe("AddCreditsModal", () => {
+ const openAddCreditsModal = async () => {
+ const user = userEvent.setup();
+ renderManageOrg();
+ await screen.findByTestId("manag... | frontend/__tests__/routes/manage-org.test.tsx | 26 | TypeScript | 0.357 | question | 105 | 51 | 51 | false | refactor(frontend): ensure proper validation in organization add credits modal (org support) | 11,917 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | hieptl |
import { useTranslation } from "react-i18next";
import { NavLink } from "react-router";
import { cn } from "#/utils/utils";
import { Typography } from "#/ui/typography";
import { I18nKey } from "#/i18n/declaration";
import SettingsIcon from "#/icons/settings-gear.svg?react";
import CloseIcon from "#/icons/close.svg?rea... | ```suggestion
navigationItems: SettingsNavItem[];
``` | import { useTranslation } from "react-i18next";
import { NavLink } from "react-router";
import { cn } from "#/utils/utils";
import { Typography } from "#/ui/typography";
import { I18nKey } from "#/i18n/declaration";
import SettingsIcon from "#/icons/settings-gear.svg?react";
import CloseIcon from "#/icons/close.svg?rea... | @@ -5,17 +5,12 @@ import { Typography } from "#/ui/typography";
import { I18nKey } from "#/i18n/declaration";
import SettingsIcon from "#/icons/settings-gear.svg?react";
import CloseIcon from "#/icons/close.svg?react";
-
-interface NavigationItem {
- to: string;
- icon: React.ReactNode;
- text: string;
-}
+import... | frontend/src/components/features/settings/settings-navigation.tsx | 13 | TypeScript | 0.571 | suggestion | 55 | 38 | 38 | false | refactor(frontend): consolidate settings navigation items logic into shared custom hook | 11,950 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | AVBharath10 |
import { useTranslation } from "react-i18next";
import { NavLink } from "react-router";
import { cn } from "#/utils/utils";
import { Typography } from "#/ui/typography";
import { I18nKey } from "#/i18n/declaration";
import SettingsIcon from "#/icons/settings-gear.svg?react";
import CloseIcon from "#/icons/close.svg?rea... | ```suggestion
{/* Mobile backdrop */}
``` | import { useTranslation } from "react-i18next";
import { NavLink } from "react-router";
import { cn } from "#/utils/utils";
import { Typography } from "#/ui/typography";
import { I18nKey } from "#/i18n/declaration";
import SettingsIcon from "#/icons/settings-gear.svg?react";
import CloseIcon from "#/icons/close.svg?rea... | @@ -27,14 +22,13 @@ export function SettingsNavigation({
return (
<>
- {/* Mobile backdrop */}
+ {/* Mobila backdrop */} | frontend/src/components/features/settings/settings-navigation.tsx | 25 | TypeScript | 0.429 | suggestion | 47 | 50 | 50 | false | refactor(frontend): consolidate settings navigation items logic into shared custom hook | 11,950 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | AVBharath10 |
import { render, screen } from "@testing-library/react";
import { describe, expect, vi, beforeEach, it } from "vitest";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { RepositorySelectionForm } from "../../../../src/components/features/home/repo-selection-form";
import UserService fro... | You do not need to mock Zustand stores, see https://github.com/OpenHands/OpenHands/issues/11951 | import { render, screen } from "@testing-library/react";
import { describe, expect, vi, beforeEach, it } from "vitest";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { RepositorySelectionForm } from "../../../../src/components/features/home/repo-selection-form";
import GitService from... | frontend/__tests__/components/features/home/repo-selection-form.test.tsx | 1 | TypeScript | 0.214 | suggestion | 95 | 26 | 26 | false | feat: remember last selected git provider in homepage dropdown | 11,979 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | tofarr | |
from __future__ import annotations
from typing import overload
from pydantic import BaseModel
from openhands.core.logger import openhands_logger as logger
from openhands.events.action.agent import CondensationAction, CondensationRequestAction
from openhands.events.event import Event
from openhands.events.observation... | Note for v1: the `View` class now maintains all `Condensation` events, which themselves have a `forgotten_event_ids` field. No updates necessary. | from __future__ import annotations
from typing import overload
from pydantic import BaseModel
from openhands.core.logger import openhands_logger as logger
from openhands.events.action.agent import CondensationAction, CondensationRequestAction
from openhands.events.event import Event
from openhands.events.observation... | @@ -18,6 +18,8 @@ class View(BaseModel):
events: list[Event]
unhandled_condensation_request: bool = False
+ # Set of event IDs that have been forgotten/condensed
+ forgotten_event_ids: set[int] = set() | openhands/memory/view.py | 22 | Python | 0.5 | suggestion | 145 | 47 | 47 | false | fix: Prevent old instructions from being re-executed after conversation condensation | 11,982 | All-Hands-AI/OpenHands | 55,974 | Python | csmith49 | nathannewyen |
return
# We expect events[0] to be SystemMessageAction after _ensure_system_message
if len(events) == 1:
# Only system message exists
logger.info(
'Initial user message action was missing. Inserting the initial user message.'
)
... | Note for v1: since the `ConversationMemory` class no longer exists, there is no mechanism for inserting the initial user message. It exists in the event stream like any other message would. No updates necessary. | self,
events: list[Event],
initial_user_action: MessageAction,
forgotten_event_ids: set[int],
) -> None:
"""Checks if the second event is a user MessageAction and inserts the provided one if needed.
IMPORTANT: If the initial user action has been condensed (its ID is ... | @@ -827,16 +835,41 @@ def _ensure_system_message(self, events: list[Event]) -> None:
)
def _ensure_initial_user_message(
- self, events: list[Event], initial_user_action: MessageAction
+ self,
+ events: list[Event],
+ initial_user_action: MessageAction,
+ forgo... | openhands/memory/conversation_memory.py | 26 | Python | 0.786 | suggestion | 211 | 28 | 51 | false | fix: Prevent old instructions from being re-executed after conversation condensation | 11,982 | All-Hands-AI/OpenHands | 55,974 | Python | csmith49 | nathannewyen |
)
if system_prompt:
system_message = SystemMessageAction(content=system_prompt)
# Insert the system message directly at the beginning of the events list
events.insert(0, system_message)
logger.info(
'[Conversatio... | Ahh. Not a review comment, just a note, it shouldn’t have been condensed I think | # Legacy behavior: If no SystemMessageAction is found, add one
if not has_system_message:
logger.debug(
'[ConversationMemory] No SystemMessageAction found in events. '
'Adding one for backward compatibility. '
)
system_prompt = self.pro... | @@ -827,16 +835,41 @@ def _ensure_system_message(self, events: list[Event]) -> None:
)
def _ensure_initial_user_message(
- self, events: list[Event], initial_user_action: MessageAction
+ self,
+ events: list[Event],
+ initial_user_action: MessageAction,
+ forgo... | openhands/memory/conversation_memory.py | 26 | Python | 0.286 | suggestion | 80 | 46 | 51 | false | fix: Prevent old instructions from being re-executed after conversation condensation | 11,982 | All-Hands-AI/OpenHands | 55,974 | Python | enyst | nathannewyen |
import logging
import os
import tempfile
from abc import ABC
from dataclasses import dataclass
from pathlib import Path
from typing import AsyncGenerator
import base62
from openhands.app_server.app_conversation.app_conversation_models import (
AgentType,
AppConversationStartTask,
AppConversationStartTaskS... | I went looking for this specifically - good job! | session_api_key: str | None,
conversation_id: UUID,
security_analyzer_str: str | None,
httpx_client: 'httpx.AsyncClient',
) -> None:
"""Set security analyzer on conversation using only the analyzer string.
Args:
agent_server_url: URL of the agent server
... | @@ -379,3 +391,95 @@ def _create_condenser(
condenser = LLMSummarizingCondenser(**condenser_kwargs)
return condenser
+
+ def _create_security_analyzer_from_string(
+ self, security_analyzer_str: str | None
+ ) -> SecurityAnalyzerBase | None:
+ """Convert security analyzer string ... | openhands/app_server/app_conversation/app_conversation_service_base.py | 26 | Python | 0.071 | suggestion | 48 | 382 | 49 | false | feat: support security analyzer settings for v1 conversations | 12,008 | All-Hands-AI/OpenHands | 55,974 | Python | tofarr | hieptl |
getConfigSpy.mockRestore();
});
it("should not show Add Credits modal when HIDE_BILLING is true even if state is set", async () => {
// Arrange
const getConfigSpy = vi.spyOn(OptionService, "getConfig");
getConfigSpy.mockResolvedValue({
APP_MODE: "saas",
GITHUB_CLIENT_ID:... | The test never sets `addCreditsFormVisible` to true. Since the `”Add"` button is already hidden when `HIDE_BILLING` is `true`, this is redundant with the previous test (see `"should hide Add Credits button when HIDE_BILLING is true”`). I verified this by removing the `!isBillingHidden` guard — test still passes. Sugges... | getConfigSpy.mockRestore();
});
it("should show all billing-related elements when HIDE_BILLING is false", async () => {
// Arrange
const getConfigSpy = vi.spyOn(OptionService, "getConfig");
getConfigSpy.mockResolvedValue({
APP_MODE: "saas",
GITHUB_CLIENT_ID: "test",
... | @@ -707,4 +707,163 @@ describe("Manage Org Route", () => {
expect(screen.getByTestId("delete-org-confirmation")).toBeInTheDocument();
});
});
+
+ describe("HIDE_BILLING feature flag", () => {
+ it("should hide credits section when HIDE_BILLING is true", async () => {
+ // Arrange
+ const ge... | frontend/__tests__/routes/manage-org.test.tsx | 26 | TypeScript | 0.643 | suggestion | 331 | 51 | 37 | false | feat(frontend): hide billing section in organization settings page for self-hosted (org support) | 12,019 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | hieptl |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.