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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
@staticmethod
async def get_user_by_id_async(user_id: str) -> Optional[User]:
"""Get user by Keycloak user ID (async version).
This is the preferred method when calling from an async context as it
avoids event loop conflicts that can occur with the sync version.
"""
with... | **question (non-blocking):** Is there a better approach to prevent the query from running twice?. Thank you! 🙏 | async def get_user_by_id_async(user_id: str) -> Optional[User]:
"""Get user by Keycloak user ID (async version).
This is the preferred method when calling from an async context as it
avoids event loop conflicts that can occur with the sync version.
"""
with session_maker() a... | @@ -361,6 +366,64 @@ def get_user_by_id(user_id: str) -> Optional[User]:
else:
return None
+ @staticmethod
+ async def get_user_by_id_async(user_id: str) -> Optional[User]:
+ """Get user by Keycloak user ID (async version).
+
+ This is the preferred method when callin... | enterprise/storage/user_store.py | 26 | Python | 0.429 | suggestion | 110 | 51 | 51 | false | Fix asyncio event loop conflict in get_user_by_id | 12,475 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | chuckbutkus |
logger.info(
'saas_settings_store:create_default_settings:waiting_for_lock',
extra={'user_id': user_id},
)
await asyncio.sleep(_RETRY_LOAD_DELAY_SECONDS)
# Check for user again as migration could have happened while try... | **question (non-blocking):** Would it be possible to move this import to the top of the file, or is it intentionally placed here to avoid a circular import? Thank you! 🙏 | 'saas_settings_store:create_default_settings:waiting_for_lock',
extra={'user_id': user_id},
)
await asyncio.sleep(_RETRY_LOAD_DELAY_SECONDS)
# Check for user again as migration could have happened while trying to get the lock.
... | @@ -361,6 +366,64 @@ def get_user_by_id(user_id: str) -> Optional[User]:
else:
return None
+ @staticmethod
+ async def get_user_by_id_async(user_id: str) -> Optional[User]:
+ """Get user by Keycloak user ID (async version).
+
+ This is the preferred method when callin... | enterprise/storage/user_store.py | 26 | Python | 0.429 | refactor | 170 | 51 | 51 | false | Fix asyncio event loop conflict in get_user_by_id | 12,475 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | chuckbutkus |
);
// Reset hasConnected flags and history loading state when conversation changes
useEffect(() => {
hasConnectedRefPlanning.current = false;
setIsLoadingHistoryMain(true);
setExpectedEventCountMain(null);
receivedEventCountRefMain.current = 0;
// Reset the tracked event ref when conversation... | ```suggestion
useEffect(() => {
if (!preloadedEvents || preloadedEvents.length === 0) {
setIsLoadingHistoryMain(false);
return;
}
for (const event of preloadedEvents) {
addEvent(event);
}
setIsLoadingHistoryMain(false);
}, [preloadedEvents, addEvent]);
```
`useEventStore` al... | );
// Reset hasConnected flags and history loading state when conversation changes
useEffect(() => {
hasConnectedRefPlanning.current = false;
setIsLoadingHistoryMain(true);
setExpectedEventCountMain(null);
receivedEventCountRefMain.current = 0;
// Reset the tracked event ref when conversation... | @@ -306,6 +307,20 @@ export function ConversationWebSocketProvider({
latestPlanningFileEventRef.current = null;
}, [conversationId]);
+ const { data: preloadedEvents } = useConversationHistory(conversationId);
+
+ useEffect(() => {
+ if (!preloadedEvents || preloadedEvents.length === 0) return;
+
+ us... | frontend/src/contexts/conversation-websocket-context.tsx | 26 | TypeScript | 1 | bug | 421 | 51 | 51 | false | feat: preload conversation history before websocket connection | 12,488 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | mo-abdulai |
* @param conversationUrl The conversation URL (e.g., "http://localhost:54928/api/conversations/...")
* @param sessionApiKey Session API key for authentication (required for V1)
* @returns The event count
*/
static async getEventCount(
conversationId: string,
conversationUrl: string,
sessionApi... | ```suggestion
items: OpenHandsEvent[];
``` | * @param conversationId The conversation ID
* @param conversationUrl The conversation URL (e.g., "http://localhost:54928/api/conversations/...")
* @param sessionApiKey Session API key for authentication (required for V1)
* @returns The event count
*/
static async getEventCount(
conversationId: stri... | @@ -61,5 +62,27 @@ class EventService {
);
return data;
}
+
+ // V1 conversations — App Server REST endpoint
+ static async searchEventsV1(conversationId: string, limit = 100) {
+ const { data } = await openHands.get<{
+ items: unknown[]; | frontend/src/api/event-service/event-service.api.ts | 26 | TypeScript | 0.429 | suggestion | 48 | 46 | 47 | false | feat: preload conversation history before websocket connection | 12,488 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | mo-abdulai |
// Build session headers for authentication
const headers = buildSessionHeaders(sessionApiKey);
const { data } = await axios.get<number>(
`${runtimeUrl}/api/conversations/${conversationId}/events/count`,
{ headers },
);
return data;
}
// V1 conversations — App Server REST endpoint... | ```suggestion
events: OpenHandsParsedEvent[];
``` | const runtimeUrl = buildHttpBaseUrl(conversationUrl);
// Build session headers for authentication
const headers = buildSessionHeaders(sessionApiKey);
const { data } = await axios.get<number>(
`${runtimeUrl}/api/conversations/${conversationId}/events/count`,
{ headers },
);
return d... | @@ -61,5 +62,27 @@ class EventService {
);
return data;
}
+
+ // V1 conversations — App Server REST endpoint
+ static async searchEventsV1(conversationId: string, limit = 100) {
+ const { data } = await openHands.get<{
+ items: unknown[];
+ }>(`/api/v1/conversation/${conversationId}/events/sea... | frontend/src/api/event-service/event-service.api.ts | 26 | TypeScript | 0.571 | suggestion | 55 | 35 | 36 | false | feat: preload conversation history before websocket connection | 12,488 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | mo-abdulai |
// @vitest-environment happy-dom
import { describe, it, expect, afterEach, vi } from "vitest";
// Mock axios client before EventService import
vi.mock("#/api/open-hands-axios", () => ({
openHands: { get: vi.fn() },
}));
import React from "react";
import { renderHook, waitFor } from "@testing-library/react";
import... | ```suggestion
```
Any specific reason to set this here? | // @vitest-environment happy-dom
import { describe, it, expect, afterEach, vi } from "vitest";
import React from "react";
import { renderHook, waitFor } from "@testing-library/react";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { useConversationHistory } from "#/hooks/query/use-co... | @@ -0,0 +1,85 @@
+// @vitest-environment happy-dom
+ | frontend/__tests__/hooks/query/use-conversation-history.test.tsx | 2 | TypeScript | 0.571 | question | 56 | 27 | 27 | false | feat: preload conversation history before websocket connection | 12,488 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | mo-abdulai |
// --------------------
vi.mock("#/api/event-service/event-service.api");
vi.mock("#/hooks/query/use-user-conversation");
const queryClient = new QueryClient();
function wrapper({ children }: { children: React.ReactNode }) {
return (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
)... | ```suggestion
const v1SearchEventsSpy = vi.spyOn(EventService, "searchEventsV1");
vi.mocked(useUserConversation).mockReturnValue({
data: { conversation_version: "V1" },
});
v1SearchEventsSpy.mockResolvedValue([{ id: "event-1" }]);
``` | };
}
function makeEvent(): OpenHandsEvent {
return {
id: "evt-1",
} as OpenHandsEvent;
}
// --------------------
// Mocks
// --------------------
vi.mock("#/api/open-hands-axios", () => ({
openHands: {
get: vi.fn(),
},
}));
vi.mock("#/api/event-service/event-service.api");
vi.mock("#/hooks/query/us... | @@ -0,0 +1,85 @@
+// @vitest-environment happy-dom
+
+import { describe, it, expect, afterEach, vi } from "vitest";
+
+// Mock axios client before EventService import
+vi.mock("#/api/open-hands-axios", () => ({
+ openHands: { get: vi.fn() },
+}));
+
+import React from "react";
+import { renderHook, waitFor } from "@te... | frontend/__tests__/hooks/query/use-conversation-history.test.tsx | 26 | TypeScript | 0.857 | suggestion | 258 | 51 | 51 | false | feat: preload conversation history before websocket connection | 12,488 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | mo-abdulai |
it("calls V1 REST endpoint for V1 conversations", async () => {
(useUserConversation as any).mockReturnValue({
data: { conversation_version: "V1" },
});
(EventService.searchEventsV1 as any).mockResolvedValue([{ id: "event-1" }]);
const { result } = renderHook(() => useConversationHistory("con... | ```suggestion
const v0SearchEventsSpy = vi.spyOn(EventService, "searchEventsV0");
vi.mocked(useUserConversation).mockReturnValue({
data: { conversation_version: "V0" },
});
v0SearchEventsSpy.mockResolvedValue([{ id: 1 }]);
``` | vi.mock("#/hooks/query/use-user-conversation");
const queryClient = new QueryClient();
function wrapper({ children }: { children: React.ReactNode }) {
return (
<QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
);
}
// --------------------
// Tests
// --------------------
describe("us... | @@ -0,0 +1,85 @@
+// @vitest-environment happy-dom
+
+import { describe, it, expect, afterEach, vi } from "vitest";
+
+// Mock axios client before EventService import
+vi.mock("#/api/open-hands-axios", () => ({
+ openHands: { get: vi.fn() },
+}));
+
+import React from "react";
+import { renderHook, waitFor } from "@te... | frontend/__tests__/hooks/query/use-conversation-history.test.tsx | 26 | TypeScript | 0.857 | suggestion | 250 | 40 | 51 | false | feat: preload conversation history before websocket connection | 12,488 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | mo-abdulai |
// Merged loading history state - true if either connection is still loading
const isLoadingHistory = useMemo(
() => isLoadingHistoryMain || isLoadingHistoryPlanning,
[isLoadingHistoryMain, isLoadingHistoryPlanning],
);
// Reset hasConnected flags and history loading state when conversation changes
u... | ```suggestion
addEvent(event);
```
No longer required since `preloadedEvents` are no longer `unknown` | // Merged loading history state - true if either connection is still loading
const isLoadingHistory = useMemo(
() => isLoadingHistoryMain || isLoadingHistoryPlanning,
[isLoadingHistoryMain, isLoadingHistoryPlanning],
);
// Reset hasConnected flags and history loading state when conversation changes
u... | @@ -306,6 +307,21 @@ export function ConversationWebSocketProvider({
latestPlanningFileEventRef.current = null;
}, [conversationId]);
+ const { data: preloadedEvents } = useConversationHistory(conversationId);
+
+ useEffect(() => {
+ if (!preloadedEvents || preloadedEvents.length === 0) {
+ setIsLoa... | frontend/src/contexts/conversation-websocket-context.tsx | 26 | TypeScript | 0.714 | suggestion | 108 | 51 | 51 | false | feat: preload conversation history before websocket connection | 12,488 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | mo-abdulai |
import React, {
createContext,
useContext,
useEffect,
useState,
useCallback,
useMemo,
useRef,
} from "react";
import { useTranslation } from "react-i18next";
import { useQueryClient } from "@tanstack/react-query";
import { useWebSocket, WebSocketHookOptions } from "#/hooks/use-websocket";
import { OHEvent... | ```suggestion
import { useEventStore } from "#/stores/use-event-store";
``` | import React, {
createContext,
useContext,
useEffect,
useState,
useCallback,
useMemo,
useRef,
} from "react";
import { useTranslation } from "react-i18next";
import { useQueryClient } from "@tanstack/react-query";
import { useWebSocket, WebSocketHookOptions } from "#/hooks/use-websocket";
import { useEven... | @@ -10,7 +10,7 @@ import React, {
import { useTranslation } from "react-i18next";
import { useQueryClient } from "@tanstack/react-query";
import { useWebSocket, WebSocketHookOptions } from "#/hooks/use-websocket";
-import { useEventStore } from "#/stores/use-event-store";
+import { OHEvent, useEventStore } from "#/s... | frontend/src/contexts/conversation-websocket-context.tsx | 13 | TypeScript | 0.643 | suggestion | 75 | 38 | 38 | false | feat: preload conversation history before websocket connection | 12,488 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | mo-abdulai |
if (isNearBottom && hasNextPage && !isFetchingNextPage) {
fetchNextPage();
}
},
[hasNextPage, isFetchingNextPage, fetchNextPage],
);
const {
isOpen,
getToggleButtonProps,
getMenuProps,
getInputProps,
highlightedIndex,
getItemProps,
selectedItem,
} = useComb... | **suggestion:** Could you please consider adding an inline comment to explain the purpose of the stateReducer? This would help future developers better understand why it is needed. Thank you! 🙏
| if (isNearBottom && hasNextPage && !isFetchingNextPage) {
fetchNextPage();
}
},
[hasNextPage, isFetchingNextPage, fetchNextPage],
);
const {
isOpen,
getToggleButtonProps,
getMenuProps,
getInputProps,
highlightedIndex,
getItemProps,
selectedItem,
} = useComb... | @@ -220,8 +212,12 @@ export function GitRepoDropdown({
onSelectedItemChange: ({ selectedItem: newSelectedItem }) => {
handleSelectionChange(newSelectedItem);
},
- onInputValueChange: handleInputValueChange,
inputValue,
+ stateReducer: (state, actionAndChanges) => | frontend/src/components/features/home/git-repo-dropdown/git-repo-dropdown.tsx | 26 | TypeScript | 0.429 | suggestion | 241 | 51 | 51 | false | Fix: branch/repo dropdown reset on click | 12,501 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | abhayymishraa |
import { render, screen, waitFor } from "@testing-library/react";
import { describe, expect, vi, beforeEach, it } from "vitest";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import userEvent from "@testing-library/user-event";
import { GitRepoDropdown } from "../../../../src/components/feat... | **question:** Would it be possible to use a pattern like this? Thank you! 🙏
```ts
vi.mock("#/components/.../use-repository-data", ...)
``` | import { render, screen, waitFor } from "@testing-library/react";
import { describe, expect, vi, beforeEach, it } from "vitest";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import userEvent from "@testing-library/user-event";
import { GitRepoDropdown } from "../../../../src/components/feat... | @@ -0,0 +1,237 @@
+import { render, screen, waitFor } from "@testing-library/react";
+import { describe, expect, vi, beforeEach, it } from "vitest";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import userEvent from "@testing-library/user-event";
+import { GitRepoDropdown } from "../../..... | frontend/__tests__/components/features/home/git-repo-dropdown.test.tsx | 11 | TypeScript | 0.786 | suggestion | 144 | 36 | 36 | false | Fix: branch/repo dropdown reset on click | 12,501 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | abhayymishraa |
#
# Once the initial deploy is complete and every user has been logged out
# after this change (12 hrs max), this should be changed to check
# "if accepted_tos is not None" as there should not be any users with
# accepted_tos equal to "None"
if accepted_tos is False and r... | **question:** If we make this endpoint public, could it introduce any potential security risks? As we prepare to release the shared conversation feature, I would appreciate your guidance on whether someone who receives a shared conversation might have any way of accessing sensitive information or secrets. Thank you! 🙏... | #
# Once the initial deploy is complete and every user has been logged out
# after this change (12 hrs max), this should be changed to check
# "if accepted_tos is not None" as there should not be any users with
# accepted_tos equal to "None"
if accepted_tos is False and r... | @@ -163,6 +163,7 @@ def _should_attach(self, request: Request) -> bool:
'/oauth/device/authorize',
'/oauth/device/token',
'/api/v1/web-client/config',
+ '/api/v1/webhooks/secrets', | enterprise/server/middleware.py | 26 | Python | 0.643 | security | 320 | 48 | 49 | false | fix: remove keycloak_auth cookie requirement for webhook secrets endpoint | 12,525 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | tofarr |
import posthog from "posthog-js";
import { create } from "zustand";
interface ErrorMessageState {
errorMessage: string | null;
}
interface ErrorMessageActions {
setErrorMessage: (
message: string,
metadata?: Record<string, unknown>,
) => void;
removeErrorMessage: () => void;
}
type ErrorMessageStore ... | **suggestion:** Stephan has worked on PostHog, but if I remember correctly, we should be using posthog-js/react instead of posthog-js.
---
Hello @amanape, could you please help confirm if that is the recommended approach? | import { create } from "zustand";
interface ErrorMessageState {
errorMessage: string | null;
}
interface ErrorMessageActions {
setErrorMessage: (message: string) => void;
removeErrorMessage: () => void;
}
type ErrorMessageStore = ErrorMessageState & ErrorMessageActions;
const initialState: ErrorMessageState =... | @@ -1,11 +1,15 @@
+import posthog from "posthog-js"; | frontend/src/stores/error-message-store.ts | 1 | TypeScript | 0.5 | question | 224 | 26 | 26 | false | fix: Add PostHog error tracking for V1 AgentErrorEvent and ConversationErrorEvent | 12,543 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | neubig |
token_manager = TokenManager()
user_info = call_async_from_sync(
token_manager.get_user_info_from_user_id,
GENERAL_TIMEOUT,
user_id,
)
user = call_async_from_sync(
UserStore.mi... | **question:** Could you please clarify whether we are planning to introduce the TRACE: prefix when logging in our codebase? Thank you! 🙏 | token_manager = TokenManager()
user_info = call_async_from_sync(
token_manager.get_user_info_from_user_id,
GENERAL_TIMEOUT,
user_id,
)
user = call_async_from_sync(
UserStore.mi... | @@ -372,13 +372,15 @@ async def get_user_by_id_async(user_id: str) -> Optional[User]:
This is the preferred method when calling from an async context as it
avoids event loop conflicts that can occur with the sync version.
"""
- with session_maker() as session:
- user = (
- ... | enterprise/storage/user_store.py | 26 | Python | 0.429 | suggestion | 137 | 51 | 51 | false | Fix org billing | 12,562 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | tofarr |
UserStore.migrate_user,
GENERAL_TIMEOUT,
user_id,
user_settings,
user_info,
)
return user
else:
return None
@staticmethod
async def get_user_by_id_asyn... | **question:** Could you please confirm whether we are planning to log the entire set of user data? I just want to ensure we are mindful of any sensitive information that may be included. Thank you! 🙏 | UserStore.migrate_user,
GENERAL_TIMEOUT,
user_id,
user_settings,
user_info,
)
return user
else:
return None
@staticmethod
async def get_user_by_id_asyn... | @@ -372,13 +372,15 @@ async def get_user_by_id_async(user_id: str) -> Optional[User]:
This is the preferred method when calling from an async context as it
avoids event loop conflicts that can occur with the sync version.
"""
- with session_maker() as session:
- user = (
- ... | enterprise/storage/user_store.py | 26 | Python | 0.429 | security | 200 | 51 | 51 | false | Fix org billing | 12,562 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | tofarr |
from fastapi import APIRouter, Depends, HTTPException, Request, status
from fastapi.responses import RedirectResponse
from integrations import stripe_service
from pydantic import BaseModel
from server.constants import (
STRIPE_API_KEY,
)
from server.logger import logger
from starlette.datastructures import URL
from... | **question:** Could we consider moving this import statement to the top of the file? I was wondering if it was placed here to help avoid a circular import. Thank you! 🙏 | from fastapi import APIRouter, Depends, HTTPException, Request, status
from fastapi.responses import RedirectResponse
from integrations import stripe_service
from pydantic import BaseModel
from server.constants import (
STRIPE_API_KEY,
)
from server.logger import logger
from starlette.datastructures import URL
from... | @@ -25,31 +26,15 @@
billing_router = APIRouter(prefix='/api/billing')
-# TODO: Add a new app_mode named "ON_PREM" to support self-hosted customers instead of doing this
-# and members should comment out the "validate_saas_environment" function if they are developing and testing locally.
-def is_all_hands_saas_envi... | enterprise/server/routes/billing.py | 26 | Python | 0.429 | suggestion | 169 | 51 | 51 | false | Fix org billing | 12,562 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | tofarr |
)
new_max_budget = max_budget + add_credits
await LiteLlmManager.update_team_and_users_budget(
str(user.current_org_id), new_max_budget
)
# Store transaction status
billing_session.status = 'completed'
billing_session.price = add_credits
bill... | **question:** The success_callback function currently uses request.base_url directly, while the cancel_callback uses _get_base_url(request). Could you please clarify whether this difference is intentional? Thank you! 🙏 | max_budget = (user_team_info.get('litellm_budget_table') or {}).get(
'max_budget', 0
)
new_max_budget = max_budget + add_credits
await LiteLlmManager.update_team_and_users_budget(
str(user.current_org_id), new_max_budget
)
# Store transaction sta... | enterprise/server/routes/billing.py | 26 | Python | 0.5 | suggestion | 219 | 51 | 51 | false | Fix org billing | 12,562 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | tofarr | |
from server.logger import logger
from starlette.datastructures import URL
from storage.billing_session import BillingSession
from storage.database import session_maker
from storage.lite_llm_manager import LiteLlmManager
from storage.subscription_access import SubscriptionAccess
from storage.user_store import UserStore
... | **suggestion:** The error message still references ‘All Hands SaaS environments,’ which reflects the previous domain-based check. Would it be possible to update it to reference the billing feature flag instead? I believe this would make the message more accurate. Thank you! 🙏 | from server.logger import logger
from starlette.datastructures import URL
from storage.billing_session import BillingSession
from storage.database import session_maker
from storage.lite_llm_manager import LiteLlmManager
from storage.subscription_access import SubscriptionAccess
from storage.user_store import UserStore
... | @@ -25,31 +26,15 @@
billing_router = APIRouter(prefix='/api/billing')
-# TODO: Add a new app_mode named "ON_PREM" to support self-hosted customers instead of doing this
-# and members should comment out the "validate_saas_environment" function if they are developing and testing locally.
-def is_all_hands_saas_envi... | enterprise/server/routes/billing.py | 26 | Python | 0.643 | suggestion | 277 | 51 | 51 | false | Fix org billing | 12,562 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | tofarr |
onClose,
}: AccountSettingsContextMenuProps) {
const ref = useClickOutsideElement<HTMLUListElement>(onClose);
const { t } = useTranslation();
const posthog = usePostHog();
const { data: config } = useConfig();
const isAddTeamMemberEnabled = useFeatureFlagEnabled(
"exp_add_team_member_button",
);
// ... | @OpenHands please extend the `useTracking` hook instead of doing this | onLogout,
onClose,
}: AccountSettingsContextMenuProps) {
const ref = useClickOutsideElement<HTMLUListElement>(onClose);
const { t } = useTranslation();
const { trackAddTeamMembersButtonClick } = useTracking();
const { data: config } = useConfig();
const isAddTeamMemberEnabled = useFeatureFlagEnabled(
... | @@ -33,13 +44,30 @@ export function AccountSettingsContextMenu({
}));
const handleNavigationClick = () => onClose();
+ const handleAddTeamMembers = () => {
+ posthog.capture("exp_add_team_members"); | frontend/src/components/features/context-menu/account-settings-context-menu.tsx | 26 | TypeScript | 0.429 | suggestion | 69 | 51 | 51 | false | Experiment - Add 'Add Team Members' button to Avatar menu in SaaS mode | 12,647 | All-Hands-AI/OpenHands | 55,974 | Python | amanape | jpelletier1 |
Grab ConversationInfo and all events from the agent server and make sure they
exist in the app server."""
_logger.debug(f'Started Refreshing Conversation {app_conversation_info.id}')
try:
url = runtime['url']
# TODO: Maybe we can use RemoteConversation here?
# First get convers... | I think we want to use `updated_conversation_info.stats.get_combined_metrics()` here (to aggregate the total convo cost) | Grab ConversationInfo and all events from the agent server and make sure they
exist in the app server."""
_logger.debug(f'Started Refreshing Conversation {app_conversation_info.id}')
try:
url = runtime['url']
# TODO: Maybe we can use RemoteConversation here?
# First get convers... | @@ -711,8 +711,18 @@ async def refresh_conversation(
updated_conversation_info = ConversationInfo.model_validate(response.json())
- # TODO: As of writing, ConversationInfo from AgentServer does not have a title to update...
app_conversation_info.updated_at = updated_conversation_info.update... | openhands/app_server/sandbox/remote_sandbox_service.py | 26 | Python | 0.571 | suggestion | 120 | 51 | 51 | false | fix(frontend): Support V1 conversations in MetricsModal | 12,678 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 | tofarr |
export function MetricsModal({ isOpen, onOpenChange }: MetricsModalProps) {
const { t } = useTranslation();
const storeMetrics = useMetricsStore();
const { data: conversation } = useActiveConversation();
const isV1 = conversation?.conversation_version === "V1";
const conversationId = conversation?.conversat... | ```suggestion
v1Metrics.accumulated_token_usage.prompt_tokens,
```
NIT: do we need the conditional checks for the token values?
|
export function MetricsModal({ isOpen, onOpenChange }: MetricsModalProps) {
const { t } = useTranslation();
const storeMetrics = useMetricsStore();
const { data: conversation } = useActiveConversation();
const isV1 = conversation?.conversation_version === "V1";
const conversationId = conversation?.conversat... | @@ -16,7 +19,50 @@ interface MetricsModalProps {
export function MetricsModal({ isOpen, onOpenChange }: MetricsModalProps) {
const { t } = useTranslation();
- const metrics = useMetricsStore();
+ const storeMetrics = useMetricsStore();
+ const { data: conversation } = useActiveConversation();
+
+ const isV1 =... | frontend/src/components/features/conversation/metrics-modal/metrics-modal.tsx | 26 | TypeScript | 0.714 | question | 148 | 51 | 51 | false | fix(frontend): Support V1 conversations in MetricsModal | 12,678 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 | tofarr |
import logging
import os
from logging.config import fileConfig
# Suppress alembic INFO logs during import to prevent non-JSON logs in production
# These plugin setup messages would otherwise appear before logging is configured
logging.getLogger('alembic').setLevel(logging.WARNING)
from alembic import context
from goo... | 🔴 Critical: This implementation does not match the PR description. The description says "Configure `alembic`, `alembic.runtime`, and `alembic.runtime.plugins` loggers with JsonFormatter to stdout before the alembic import" but this code only suppresses logs by setting level to WARNING.
This approach has two major pro... | import logging
import os
from logging.config import fileConfig
# Suppress alembic.runtime.plugins INFO logs during import to prevent non-JSON logs in production
# These plugin setup messages would otherwise appear before logging is configured
logging.getLogger('alembic.runtime.plugins').setLevel(logging.WARNING)
from... | @@ -1,6 +1,11 @@
+import logging
import os
from logging.config import fileConfig
+# Suppress alembic INFO logs during import to prevent non-JSON logs in production
+# These plugin setup messages would otherwise appear before logging is configured
+logging.getLogger('alembic').setLevel(logging.WARNING) | enterprise/migrations/env.py | 7 | Python | 0.786 | bug | 657 | 32 | 32 | false | fix: suppress alembic INFO logs before import to prevent Datadog misclassification | 12,691 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | neubig |
import logging
import os
import sys
from logging.config import fileConfig
from pathlib import Path
# Suppress alembic INFO logs during import to prevent non-JSON logs in production
# These plugin setup messages would otherwise appear before logging is configured
logging.getLogger('alembic').setLevel(logging.WARNING)
... | 🔴 Critical: Same issue as in enterprise/migrations/env.py - this only suppresses logs rather than configuring JSON formatting.
The PR description mentions following the LiteLLM logging fix pattern (commit 2f364b0d9). Consider looking at that commit to see how JSON logging was properly configured there, and apply the ... | import logging
import os
import sys
from logging.config import fileConfig
from pathlib import Path
# Suppress alembic.runtime.plugins INFO logs during import to prevent non-JSON logs in production
# These plugin setup messages would otherwise appear before logging is configured
logging.getLogger('alembic.runtime.plugi... | @@ -1,8 +1,14 @@
+import logging
+import os
import sys
from logging.config import fileConfig
from pathlib import Path
-from alembic import context
+# Suppress alembic INFO logs during import to prevent non-JSON logs in production
+# These plugin setup messages would otherwise appear before logging is configured
+l... | openhands/app_server/app_lifespan/alembic/env.py | 9 | Python | 0.5 | suggestion | 337 | 34 | 34 | false | fix: suppress alembic INFO logs before import to prevent Datadog misclassification | 12,691 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | neubig |
import logging
import os
from logging.config import fileConfig
# Suppress alembic INFO logs during import to prevent non-JSON logs in production
# These plugin setup messages would otherwise appear before logging is configured
logging.getLogger('alembic').setLevel(logging.WARNING)
from alembic import context # noqa:... | 🟠 Important: The logger name is too broad. Using `'alembic'` suppresses ALL alembic INFO logs (including migration execution, environment setup, DDL statements, etc.), not just the plugin setup messages mentioned in the PR description.
Use the specific logger that emits the problematic logs:
```suggestion
logging.ge... | import logging
import os
from logging.config import fileConfig
# Suppress alembic.runtime.plugins INFO logs during import to prevent non-JSON logs in production
# These plugin setup messages would otherwise appear before logging is configured
logging.getLogger('alembic.runtime.plugins').setLevel(logging.WARNING)
from... | @@ -1,10 +1,15 @@
+import logging
import os
from logging.config import fileConfig
-from alembic import context
-from google.cloud.sql.connector import Connector
-from sqlalchemy import create_engine
-from storage.base import Base
+# Suppress alembic INFO logs during import to prevent non-JSON logs in production
+# ... | enterprise/migrations/env.py | 7 | Python | 0.857 | suggestion | 507 | 32 | 32 | false | fix: suppress alembic INFO logs before import to prevent Datadog misclassification | 12,691 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | neubig |
import logging
import os
import sys
from logging.config import fileConfig
from pathlib import Path
# Suppress alembic INFO logs during import to prevent non-JSON logs in production
# These plugin setup messages would otherwise appear before logging is configured
logging.getLogger('alembic').setLevel(logging.WARNING)
... | 🟠 Important: Same issue as enterprise/migrations/env.py - the logger name is too broad. Using `'alembic'` suppresses ALL alembic INFO logs, not just the plugin setup messages.
```suggestion
logging.getLogger('alembic.runtime.plugins').setLevel(logging.WARNING)
```
This more precisely targets the `INFO:alembic.runtim... | import logging
import os
import sys
from logging.config import fileConfig
from pathlib import Path
# Suppress alembic.runtime.plugins INFO logs during import to prevent non-JSON logs in production
# These plugin setup messages would otherwise appear before logging is configured
logging.getLogger('alembic.runtime.plugi... | @@ -1,8 +1,14 @@
+import logging
+import os
import sys
from logging.config import fileConfig
from pathlib import Path
-from alembic import context
+# Suppress alembic INFO logs during import to prevent non-JSON logs in production
+# These plugin setup messages would otherwise appear before logging is configured
+l... | openhands/app_server/app_lifespan/alembic/env.py | 9 | Python | 0.786 | suggestion | 433 | 34 | 34 | false | fix: suppress alembic INFO logs before import to prevent Datadog misclassification | 12,691 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | neubig |
page_id_data = json.dumps({'v0': None, 'v1': 'test_v1_page_id'})
encoded_page_id = base64.b64encode(page_id_data.encode()).decode()
# Call search_conversations with include_sub_conversations and other filters
await search_conversations(
... | NIT: maybe we can parameterize these tests | page_id_data = json.dumps({'v0': None, 'v1': 'test_v1_page_id'})
encoded_page_id = base64.b64encode(page_id_data.encode()).decode()
# Call search_conversations with include_sub_conversations and other filters
await search_conversations(
... | @@ -1459,3 +1465,211 @@ async def get_agent_loop_info(*args, **kwargs):
assert call_kwargs.get('include_sub_conversations') is True
assert call_kwargs.get('page_id') == 'test_v1_page_id'
assert call_kwargs.get('limit') == 50
+
+
+@pytest.mark.asyncio
+async def test_ge... | tests/unit/server/routes/test_conversation_routes.py | 26 | Python | 0.071 | nitpick | 42 | 51 | 51 | false | Fix runtime status error on conversation resume | 12,718 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 | tofarr |
has_suspicious_labels = bool(set(account_defender_labels) & SUSPICIOUS_LABELS)
# Block if: invalid token, wrong action, low score, OR suspicious Account Defender labels
allowed = (
valid
and action_valid
and score >= RECAPTCHA_BLOCK_THRESHOLD
and ... | We may have a policy about logging email in the future, fine for now. |
# Check if any suspicious labels are present
has_suspicious_labels = bool(set(account_defender_labels) & SUSPICIOUS_LABELS)
# Block if: invalid token, wrong action, low score, OR suspicious Account Defender labels
allowed = (
valid
and action_valid
a... | @@ -143,6 +145,8 @@ def create_assessment(
'has_suspicious_labels': has_suspicious_labels,
'allowed': allowed,
'user_ip': user_ip,
+ 'user_id': user_id,
+ 'email': email, | enterprise/server/auth/recaptcha_service.py | 26 | Python | 0.214 | suggestion | 69 | 38 | 42 | false | feat(recaptcha): add user_id and email to assessment log | 12,749 | All-Hands-AI/OpenHands | 55,974 | Python | raymyers | saurya |
from datetime import UTC, datetime
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, field_validator
from storage.api_key_store import ApiKeyStore
from storage.lite_llm_manager import LiteLlmManager
from storage.org_member import OrgMember
from storage.org_member_store impor... | **suggestion:** I think it would be better to move this function to the org_service.py file rather than defining it in the router file. Thank you! 🙏 | from datetime import UTC, datetime
from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel, field_validator
from storage.api_key_store import ApiKeyStore
from storage.lite_llm_manager import LiteLlmManager
from storage.org_member import OrgMember
from storage.org_member_store impor... | @@ -6,12 +6,30 @@
from storage.lite_llm_manager import LiteLlmManager
from storage.org_member import OrgMember
from storage.org_member_store import OrgMemberStore
+from storage.org_store import OrgStore
from storage.user_store import UserStore
from openhands.core.logger import openhands_logger as logger
from op... | enterprise/server/routes/api_keys.py | 16 | Python | 0.429 | refactor | 149 | 41 | 41 | false | feat: Add BYOR export flag to org for LLM key access control | 12,753 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | tofarr |
key: str | None
@api_router.post('', response_model=ApiKeyCreateResponse)
async def create_api_key(key_data: ApiKeyCreate, user_id: str = Depends(get_user_id)):
"""Create a new API key for the authenticated user."""
try:
api_key = await api_key_store.create_api_key(
user_id, key_data.n... | **suggestion:** It appears that we may be missing tests for this endpoint. Thank you! 🙏 | raise ValueError('Expiration date cannot be in the past')
return v
class ApiKeyResponse(BaseModel):
id: int
name: str | None = None
created_at: str
last_used_at: str | None = None
expires_at: str | None = None
class ApiKeyCreateResponse(ApiKeyResponse):
key: str
class L... | @@ -148,6 +165,26 @@ class LlmApiKeyResponse(BaseModel):
key: str | None
+class ByorPermittedResponse(BaseModel):
+ permitted: bool
+
+
+@api_router.get('/llm/byor/permitted', response_model=ByorPermittedResponse)
+async def check_byor_permitted(user_id: str = Depends(get_user_id)): | enterprise/server/routes/api_keys.py | 26 | Python | 0.214 | suggestion | 88 | 51 | 51 | false | feat: Add BYOR export flag to org for LLM key access control | 12,753 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | tofarr |
request.sandbox_id = parent_info.sandbox_id
# Inherit git parameters from parent if not provided
if not request.selected_repository:
request.selected_repository = parent_info.selected_repository
if not request.selected_branch:
request.selected_branch = parent... | 🟡 Suggestion: Consider adding validation to ensure `get_prompt_for_task()` returns a non-empty prompt. This would make the code more robust against malformed suggested tasks:
```python
prompt = suggested_task.get_prompt_for_task()
if not prompt:
raise ValueError(
f"Suggested task returned empty prompt for... | request.sandbox_id = parent_info.sandbox_id
# Inherit git parameters from parent if not provided
if not request.selected_repository:
request.selected_repository = parent_info.selected_repository
if not request.selected_branch:
request.selected_branch = parent... | @@ -569,6 +574,29 @@ def _inherit_configuration_from_parent(
if not request.llm_model and parent_info.llm_model:
request.llm_model = parent_info.llm_model
+ def _apply_suggested_task(self, request: AppConversationStartRequest) -> None:
+ """Apply suggested task defaults to the start re... | openhands/app_server/app_conversation/live_status_app_conversation_service.py | 26 | Python | 1 | suggestion | 367 | 51 | 51 | false | fix: wire suggested task prompts for V1 | 12,787 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | enyst |
issue_number=42,
title='Handle review comments',
)
request = AppConversationStartRequest(suggested_task=suggested_task)
self.service._apply_suggested_task(request)
assert request.initial_message is not None
assert (
request.initial_message.co... | 🟡 Suggestion: Move this import to the top of the file with other imports. Per the project's code quality guidelines, all imports should be at the module level unless there's a specific technical reason (circular imports, conditional imports, etc.). | repo='owner/repo',
issue_number=42,
title='Handle review comments',
)
request = AppConversationStartRequest(suggested_task=suggested_task)
self.service._apply_suggested_task(request)
assert request.initial_message is not None
assert (
... | @@ -112,7 +114,50 @@ def setup_method(self):
self.mock_sandbox.id = uuid4()
self.mock_sandbox.status = SandboxStatus.RUNNING
- @pytest.mark.asyncio
+ def test_apply_suggested_task_sets_prompt_and_trigger(self):
+ """Test suggested task prompts populate initial message and trigger."""
+ ... | tests/unit/app_server/test_live_status_app_conversation_service.py | 26 | Python | 0.5 | refactor | 248 | 51 | 51 | false | fix: wire suggested task prompts for V1 | 12,787 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | enyst |
suggested_task = SuggestedTask(
git_provider=ProviderType.GITHUB,
task_type=TaskType.UNRESOLVED_COMMENTS,
repo='owner/repo',
issue_number=42,
title='Handle review comments',
)
request = AppConversationStartRequest(suggested_task=suggest... | **suggestion:** It appears that this field may be redundant. Thank you! 🙏 | suggested_task = SuggestedTask(
git_provider=ProviderType.GITHUB,
task_type=TaskType.UNRESOLVED_COMMENTS,
repo='owner/repo',
issue_number=42,
title='Handle review comments',
)
request = AppConversationStartRequest(suggested_task=suggest... | @@ -112,7 +115,49 @@ def setup_method(self):
self.mock_sandbox.id = uuid4()
self.mock_sandbox.status = SandboxStatus.RUNNING
- @pytest.mark.asyncio
+ def test_apply_suggested_task_sets_prompt_and_trigger(self):
+ """Test suggested task prompts populate initial message and trigger."""
+ ... | tests/unit/app_server/test_live_status_app_conversation_service.py | 26 | Python | 0.214 | suggestion | 74 | 51 | 51 | false | fix: wire suggested task prompts for V1 | 12,787 | All-Hands-AI/OpenHands | 55,974 | Python | hieptl | enyst |
import { LoaderCircle } from "lucide-react";
import { useTranslation } from "react-i18next";
import { I18nKey } from "#/i18n/declaration";
export function ConversationLoading() {
const { t } = useTranslation();
return (
<div className="bg-[#25272D] flex flex-col items-center justify-center h-full w-full">
... | 🟡 **Suggestion**: While this PR correctly adds the border radius fix, I notice the hardcoded color `bg-[#25272D]` could benefit from using a Tailwind theme variable instead (e.g., `bg-neutral-800` or a custom theme color). This would improve consistency and make theming easier.
However, this is **pre-existing code** ... | import { LoaderCircle } from "lucide-react";
import { useTranslation } from "react-i18next";
import { I18nKey } from "#/i18n/declaration";
import { cn } from "#/utils/utils";
type ConversationLoadingProps = {
className?: string;
};
export function ConversationLoading({ className }: ConversationLoadingProps) {
con... | @@ -1,12 +1,22 @@
import { LoaderCircle } from "lucide-react";
import { useTranslation } from "react-i18next";
import { I18nKey } from "#/i18n/declaration";
+import { cn } from "#/utils/utils";
-export function ConversationLoading() {
+type ConversationLoadingProps = {
+ className?: string;
+};
+
+export function... | frontend/src/components/features/conversation/conversation-loading.tsx | 15 | TypeScript | 0.643 | suggestion | 407 | 17 | 27 | false | fix(frontend): add missing border radius to conversation loading on first load | 12,796 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
import { LoaderCircle } from "lucide-react";
import { useTranslation } from "react-i18next";
import { I18nKey } from "#/i18n/declaration";
export function ConversationLoading() {
const { t } = useTranslation();
return (
<div className="bg-[#25272D] flex flex-col items-center justify-center h-full w-full">
... | 🟢 **Nit**: Good use of TypeScript - the optional className prop with proper typing is the right approach. Well done. | import { LoaderCircle } from "lucide-react";
import { useTranslation } from "react-i18next";
import { I18nKey } from "#/i18n/declaration";
import { cn } from "#/utils/utils";
type ConversationLoadingProps = {
className?: string;
};
export function ConversationLoading({ className }: ConversationLoadingProps) {
con... | @@ -1,12 +1,22 @@
import { LoaderCircle } from "lucide-react";
import { useTranslation } from "react-i18next";
import { I18nKey } from "#/i18n/declaration";
+import { cn } from "#/utils/utils";
-export function ConversationLoading() {
+type ConversationLoadingProps = {
+ className?: string;
+};
+
+export function... | frontend/src/components/features/conversation/conversation-loading.tsx | 10 | TypeScript | 0.571 | suggestion | 116 | 17 | 27 | false | fix(frontend): add missing border radius to conversation loading on first load | 12,796 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
},
terminal: {
component: Terminal,
titleKey: I18nKey.COMMON$TERMINAL,
},
planner: {
component: PlannerTab,
titleKey: I18nKey.COMMON$PLANNER,
},
};
export function ConversationTabContent() {
const { selectedTab, shouldShownAgentLoading } = useConversationStore();
const { conversationId } ... | ✅ This is exactly where the fix needs to be. The `rounded-xl` class will properly apply the border radius during loading. Good catch on this visual bug. | },
terminal: {
component: Terminal,
titleKey: I18nKey.COMMON$TERMINAL,
},
planner: {
component: PlannerTab,
titleKey: I18nKey.COMMON$PLANNER,
},
};
export function ConversationTabContent() {
const { selectedTab, shouldShownAgentLoading } = useConversationStore();
const { conversationId } ... | @@ -58,7 +58,7 @@ export function ConversationTabContent() {
const conversationTabTitle = t(activeTab.titleKey);
if (shouldShownAgentLoading) {
- return <ConversationLoading />;
+ return <ConversationLoading className="rounded-xl" />; | frontend/src/components/features/conversation/conversation-tabs/conversation-tab-content/conversation-tab-content.tsx | 26 | TypeScript | 0.643 | bug | 152 | 51 | 51 | false | fix(frontend): add missing border radius to conversation loading on first load | 12,796 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
@staticmethod
def list_users() -> list[User]:
"""List all users."""
with session_maker() as session:
return session.query(User).all()
@staticmethod
def update_current_org(user_id: str, org_id: UUID) -> Optional[User]:
"""Update the user's current organization.
... | 🔴 Critical: Race condition risk. If two concurrent requests call `update_current_org` for the same user, they could both read the user, then both update `current_org_id`, leading to the last write winning without proper validation.
**Solution**: Use database-level locking:
```suggestion
user = session.que... |
@staticmethod
def list_users() -> list[User]:
"""List all users."""
with session_maker() as session:
return session.query(User).all()
@staticmethod
def update_current_org(user_id: str, org_id: UUID) -> Optional[User]:
"""Update the user's current organization.
... | @@ -773,6 +774,27 @@ def list_users() -> list[User]:
with session_maker() as session:
return session.query(User).all()
+ @staticmethod
+ def update_current_org(user_id: str, org_id: UUID) -> Optional[User]:
+ """Update the user's current organization.
+
+ Args:
+ u... | enterprise/storage/user_store.py | 26 | Python | 1 | bug | 494 | 51 | 51 | false | feat(backend): add api for switching between orgs | 12,799 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
@staticmethod
def list_users() -> list[User]:
"""List all users."""
with session_maker() as session:
return session.query(User).all()
@staticmethod
def update_current_org(user_id: str, org_id: UUID) -> Optional[User]:
"""Update the user's current organization.
... | 🟡 Suggestion: No error handling for invalid UUID format. If `user_id` is not a valid UUID string, this will raise a ValueError.
**Recommendation**: Add try/except or validate the UUID format earlier in the call chain:
```suggestion
try:
user_uuid = uuid.UUID(user_id)
except Val... |
@staticmethod
def list_users() -> list[User]:
"""List all users."""
with session_maker() as session:
return session.query(User).all()
@staticmethod
def update_current_org(user_id: str, org_id: UUID) -> Optional[User]:
"""Update the user's current organization.
... | @@ -773,6 +774,27 @@ def list_users() -> list[User]:
with session_maker() as session:
return session.query(User).all()
+ @staticmethod
+ def update_current_org(user_id: str, org_id: UUID) -> Optional[User]:
+ """Update the user's current organization.
+
+ Args:
+ u... | enterprise/storage/user_store.py | 26 | Python | 1 | suggestion | 435 | 51 | 51 | false | feat(backend): add api for switching between orgs | 12,799 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
from typing import Annotated
from uuid import UUID
from fastapi import APIRouter, Depends, HTTPException, Query, status
from server.email_validation import get_admin_user_id
from server.routes.org_models import (
LiteLLMIntegrationError,
MeResponse,
OrgAuthorizationError,
OrgCreate,
OrgDatabaseErro... | Do you need any sort of invite to join an org? | organization. The user must be a member of the target organization.
Args:
org_id: Organization ID to switch to (UUID)
user_id: Authenticated user ID (injected by dependency)
Returns:
OrgResponse: The organization details that was switched to
Raises:
HTTPException: 422 ... | @@ -603,3 +603,78 @@ async def remove_org_member(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to remove member',
)
+
+
+@org_router.post(
+ '/{org_id}/switch', response_model=OrgResponse, status_code=status.HTTP_200_OK
+)
+async def switch_org(
+ org_id: UU... | enterprise/server/routes/orgs.py | 26 | Python | 0.071 | question | 46 | 606 | 51 | false | feat(backend): add api for switching between orgs | 12,799 | All-Hands-AI/OpenHands | 55,974 | Python | tofarr | hieptl |
token_manager = TokenManager()
user_info = await token_manager.get_user_info_from_user_id(user_id)
logger.info(
'user_store:get_user_by_id_async:calling_migrate_user',
extra={'user_id': user_id},
... | Should we make this method async? | if user_settings:
token_manager = TokenManager()
user_info = await token_manager.get_user_info_from_user_id(user_id)
logger.info(
'user_store:get_user_by_id_async:calling_migrate_user',
extra={'us... | @@ -773,6 +774,32 @@ def list_users() -> list[User]:
with session_maker() as session:
return session.query(User).all()
+ @staticmethod
+ def update_current_org(user_id: str, org_id: UUID) -> Optional[User]: | enterprise/storage/user_store.py | 26 | Python | 0.143 | question | 33 | 51 | 51 | false | feat(backend): add api for switching between orgs | 12,799 | All-Hands-AI/OpenHands | 55,974 | Python | tofarr | hieptl |
import logging
import os
from playwright.sync_api import Page, expect
logger = logging.getLogger(__name__)
def test_github_token_configuration(page: Page, base_url: str):
"""
Test the GitHub token configuration flow:
1. Navigate to OpenHands
2. Configure LLM API key if needed
3. Check if GitHub... | 🟠 Important: Using f-strings in logging is not best practice. It evaluates the string even when the log level is disabled. Use lazy formatting instead:
```suggestion
logger.info("Step 1: Navigating to OpenHands application at %s...", base_url)
```
This pattern should be applied to **all logger calls in this file... | import logging
import os
from playwright.sync_api import Page, expect
logger = logging.getLogger(__name__)
def test_github_token_configuration(page: Page, base_url: str):
"""
Test the GitHub token configuration flow:
1. Navigate to OpenHands
2. Configure LLM API key if needed
3. Check if GitHub ... | @@ -28,87 +32,87 @@ def test_github_token_configuration(page: Page, base_url: str):
base_url = 'http://localhost:12000'
# Navigate to the OpenHands application
- print(f'Step 1: Navigating to OpenHands application at {base_url}...')
+ logger.info(f'Step 1: Navigating to OpenHands application at {b... | tests/e2e/test_settings.py | 26 | Python | 1 | performance | 499 | 51 | 51 | false | fix: add missing type hints and improve test logging | 12,810 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hobostay |
for exposed_url in sandbox_info.exposed_urls
if exposed_url.name == AGENT_SERVER
)
try:
# When running in Docker, replace localhost hostname with host.docker.internal for internal requests
app_server_url = replace_localhost_hostname... | 🟡 Suggestion: Inconsistent spacing around colon. In `sandbox_service.py` line 148, the format is `}: {exc}` (no space before colon), but here you have ` : {exc}` (spaces on both sides). Consider removing the extra spaces:
`f"{app_server_url}: {exc}"`
This matches the format used in the other debug log message. | for exposed_url in sandbox_info.exposed_urls
if exposed_url.name == AGENT_SERVER
)
try:
# When running in Docker, replace localhost hostname with host.docker.internal for internal requests
app_server_url = replace_localhost_hostname... | @@ -239,6 +239,10 @@ async def _container_to_checked_sandbox_info(self, container) -> SandboxInfo | N
)
sandbox_info.status = SandboxStatus.ERROR
else:
+ _logger.debug(
+ f'Sandbox server not yet available (still starti... | openhands/app_server/sandbox/docker_sandbox_service.py | 26 | Python | 0.786 | bug | 313 | 51 | 51 | false | Add debug logging for sandbox startup health checks | 12,814 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | tofarr |
import asyncio
import time
from abc import ABC, abstractmethod
import httpx
from openhands.app_server.errors import SandboxError
from openhands.app_server.sandbox.sandbox_models import (
AGENT_SERVER,
SandboxInfo,
SandboxPage,
SandboxStatus,
)
from openhands.app_server.services.injector import Injecto... | 🟢 Nit: Consider placing the `logging` import alphabetically between `asyncio` and `time` for better organization of standard library imports. | import asyncio
import logging
import time
from abc import ABC, abstractmethod
import httpx
from openhands.app_server.errors import SandboxError
from openhands.app_server.sandbox.sandbox_models import (
AGENT_SERVER,
SandboxInfo,
SandboxPage,
SandboxStatus,
)
from openhands.app_server.services.injector... | @@ -1,4 +1,5 @@
import asyncio
+import logging | openhands/app_server/sandbox/sandbox_service.py | 2 | Python | 0.571 | suggestion | 141 | 27 | 27 | false | Add debug logging for sandbox startup health checks | 12,814 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | tofarr |
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='An unexpected error occurred',
)
except Exception as e:
logger.exception(
'Unexpected error retrieving member details',
extra={'user_id': user_id, 'org_id': str(org... | 🔴 **Critical**: This changes authorization from `get_admin_user_id` to `get_user_id`, which is a significant security change that is **not mentioned in the PR description**.
**Questions:**
1. Was this change intentional?
2. If intentional, why was it made?
3. Is there proper owner authorization in `OrgService.delete_... | 'Role not found for org member',
extra={
'user_id': user_id,
'org_id': str(org_id),
'role_id': e.role_id,
},
)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='An un... | @@ -304,7 +298,7 @@ async def get_me(
@org_router.delete('/{org_id}', status_code=status.HTTP_200_OK)
async def delete_org(
org_id: UUID,
- user_id: str = Depends(get_admin_user_id),
+ user_id: str = Depends(get_user_id), | enterprise/server/routes/orgs.py | 26 | Python | 0.786 | security | 642 | 51 | 51 | false | fix(backend): prevent org deletion from setting current_org_id to NULL | 12,817 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
class OrgDatabaseError(OrgCreationError):
"""Raised when database operations fail."""
pass
class OrgDeletionError(Exception):
"""Base exception for organization deletion errors."""
pass
class OrgAuthorizationError(OrgDeletionError):
"""Raised when user is not authorized to delete organization.... | 🟢 **Nit**: Good design storing the user IDs for logging purposes. This will be helpful for debugging and audit trails. | class OrgDatabaseError(OrgCreationError):
"""Raised when database operations fail."""
pass
class OrgDeletionError(Exception):
"""Base exception for organization deletion errors."""
pass
class OrgAuthorizationError(OrgDeletionError):
"""Raised when user is not authorized to delete organization.... | @@ -45,6 +45,16 @@ def __init__(self, message: str = 'Not authorized to delete organization'):
super().__init__(message)
+class OrphanedUserError(OrgDeletionError):
+ """Raised when deleting an org would leave users without any organization."""
+
+ def __init__(self, user_ids: list[str]):
+ se... | enterprise/server/routes/org_models.py | 26 | Python | 0.571 | bug | 118 | 51 | 51 | false | fix(backend): prevent org deletion from setting current_org_id to NULL | 12,817 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
Args:
payload: The GitHub webhook payload dictionary
oh_label: The OpenHands label for issues (e.g., "openhands" or "openhands-exp")
inline_oh_label: The inline OpenHands mention (e.g., "@openhands" or "@openhands-exp")
enable_proactive_conversations: Whether proactive conversation s... | 🟠 Important: This function does not handle `pull_request_review` events (when someone submits a review with a body comment containing @openhands).
PR review events have a `review` field instead of `comment`:
```json
{
"action": "submitted",
"review": {
"body": "@openhands please review this"
}
}
```
If PR ... | 'Unknown error: No agent state observations found',
extra={'conversation_link': conversation_link},
)
return unknown_error_msg
observation: AgentStateChangedObservation = observations[0]
state = observation.agent_state
if state == AgentState.RATE_LIMITED:
lo... | @@ -158,6 +158,73 @@ def has_exact_mention(text: str, mention: str) -> bool:
return bool(re.search(rf'(?:^|[^\w@]){pattern}(?![\w-])', text_lower))
+def github_webhook_has_openhands_mention(text: str, inline_oh_label: str) -> bool:
+ """Check if text contains an @openhands mention for GitHub webhook filteri... | enterprise/integrations/utils.py | 26 | Python | 1 | suggestion | 787 | 51 | 51 | false | Check event types before making expensive API calls in GitHub webhook handler | 12,819 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | tofarr |
# Convert both text and mention to lowercase for case-insensitive matching
text_lower = text.lower()
mention_lower = mention.lower()
pattern = re.escape(mention_lower)
# Match mention that is not part of a larger word
return bool(re.search(rf'(?:^|[^\w@]){pattern}(?![\w-])', text_lower))
def ... | 🟡 Suggestion: Add documentation mapping GitHub webhook event types to the checks performed. This will make maintenance easier:
```suggestion
def github_webhook_is_potentially_relevant(
payload: dict,
oh_label: str,
inline_oh_label: str,
enable_proactive_conversations: bool = False,
) -> bool:
"""L... | # Convert both text and mention to lowercase for case-insensitive matching
text_lower = text.lower()
mention_lower = mention.lower()
pattern = re.escape(mention_lower)
# Match mention that is not part of a larger word
return bool(re.search(rf'(?:^|[^\w@]){pattern}(?![\w-])', text_lower))
def ... | @@ -158,6 +158,73 @@ def has_exact_mention(text: str, mention: str) -> bool:
return bool(re.search(rf'(?:^|[^\w@]){pattern}(?![\w-])', text_lower))
+def github_webhook_has_openhands_mention(text: str, inline_oh_label: str) -> bool:
+ """Check if text contains an @openhands mention for GitHub webhook filteri... | enterprise/integrations/utils.py | 26 | Python | 1 | performance | 1,558 | 51 | 51 | false | Check event types before making expensive API calls in GitHub webhook handler | 12,819 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | tofarr |
"""Check if the text contains an exact mention (not part of a larger word).
Args:
text: The text to check for mentions
mention: The mention to look for (e.g. "@openhands")
Returns:
bool: True if the exact mention is found, False otherwise
Example:
>>> has_exact_mention... | 🟢 Nit: This wrapper function is mostly redundant since `has_exact_mention` already handles falsy text values. Consider either:
1. Removing it and calling `has_exact_mention` directly, or
2. Adding more GitHub-specific logic (like checking for bot mentions to exclude)
Current implementation is fine, just a minor obse... | """Check if the text contains an exact mention (not part of a larger word).
Args:
text: The text to check for mentions
mention: The mention to look for (e.g. "@openhands")
Returns:
bool: True if the exact mention is found, False otherwise
Example:
>>> has_exact_mention... | @@ -158,6 +158,73 @@ def has_exact_mention(text: str, mention: str) -> bool:
return bool(re.search(rf'(?:^|[^\w@]){pattern}(?![\w-])', text_lower))
+def github_webhook_has_openhands_mention(text: str, inline_oh_label: str) -> bool: | enterprise/integrations/utils.py | 26 | Python | 0.786 | refactor | 355 | 51 | 51 | false | Check event types before making expensive API calls in GitHub webhook handler | 12,819 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | tofarr |
async def is_job_requested(self, message: Message) -> bool:
self._confirm_incoming_source_type(message)
installation_id = message.message['installation']
payload = message.message.get('payload', {})
repo_obj = payload.get('repository')
if not repo_obj:
return Fal... | 🟢 Nit: The logic flow is correct, but the comment "FILTER FIRST (cheap operations)" is a bit misleading since conversation starter eligibility might not be that cheap depending on what `is_eligible_for_conversation_starter()` does internally. Consider rephrasing to "CHECK EVENT TYPES FIRST (before API calls)". | async def is_job_requested(self, message: Message) -> bool:
self._confirm_incoming_source_type(message)
installation_id = message.message['installation']
payload = message.message.get('payload', {})
repo_obj = payload.get('repository')
if not repo_obj:
return Fal... | @@ -137,30 +137,49 @@ async def is_job_requested(self, message: Message) -> bool:
username = payload.get('sender', {}).get('login')
repo_name = self._get_full_repo_name(repo_obj)
- # Suggestions contain `@openhands` macro; avoid kicking off jobs for system recommendations
- if GithubFa... | enterprise/integrations/github/github_manager.py | 26 | Python | 0.786 | suggestion | 311 | 51 | 51 | false | Check event types before making expensive API calls in GitHub webhook handler | 12,819 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | tofarr |
Args:
payload: The GitHub webhook payload dictionary
oh_label: The OpenHands label for issues (e.g., "openhands" or "openhands-exp")
inline_oh_label: The inline OpenHands mention (e.g., "@openhands" or "@openhands-exp")
enable_proactive_conversations: Whether proactive conversation s... | 🟠 **Important**: This function does not handle `pull_request_review` events (when someone submits a review with a body comment containing @openhands).
PR review events have a `review` field instead of `comment`:
```json
{
"action": "submitted",
"review": {
"body": "@openhands please review this"
}
}
```
If... | 'Unknown error: No agent state observations found',
extra={'conversation_link': conversation_link},
)
return unknown_error_msg
observation: AgentStateChangedObservation = observations[0]
state = observation.agent_state
if state == AgentState.RATE_LIMITED:
lo... | @@ -158,6 +158,73 @@ def has_exact_mention(text: str, mention: str) -> bool:
return bool(re.search(rf'(?:^|[^\w@]){pattern}(?![\w-])', text_lower))
+def github_webhook_has_openhands_mention(text: str, inline_oh_label: str) -> bool:
+ """Check if text contains an @openhands mention for GitHub webhook filteri... | enterprise/integrations/utils.py | 26 | Python | 1 | suggestion | 791 | 51 | 51 | false | Check event types before making expensive API calls in GitHub webhook handler | 12,819 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | tofarr |
# Convert both text and mention to lowercase for case-insensitive matching
text_lower = text.lower()
mention_lower = mention.lower()
pattern = re.escape(mention_lower)
# Match mention that is not part of a larger word
return bool(re.search(rf'(?:^|[^\w@]){pattern}(?![\w-])', text_lower))
def ... | 🟡 **Suggestion**: Add documentation mapping GitHub webhook event types to the checks performed. This will make maintenance easier.
Consider adding to the docstring:
```
Supported GitHub webhook events:
- pull_request (action: closed) - for data collection
- issues (action: labeled) - when labeled with openhands labe... | # Convert both text and mention to lowercase for case-insensitive matching
text_lower = text.lower()
mention_lower = mention.lower()
pattern = re.escape(mention_lower)
# Match mention that is not part of a larger word
return bool(re.search(rf'(?:^|[^\w@]){pattern}(?![\w-])', text_lower))
def ... | @@ -158,6 +158,73 @@ def has_exact_mention(text: str, mention: str) -> bool:
return bool(re.search(rf'(?:^|[^\w@]){pattern}(?![\w-])', text_lower))
+def github_webhook_has_openhands_mention(text: str, inline_oh_label: str) -> bool:
+ """Check if text contains an @openhands mention for GitHub webhook filteri... | enterprise/integrations/utils.py | 26 | Python | 1 | suggestion | 569 | 51 | 51 | false | Check event types before making expensive API calls in GitHub webhook handler | 12,819 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | tofarr |
"""Check if the text contains an exact mention (not part of a larger word).
Args:
text: The text to check for mentions
mention: The mention to look for (e.g. "@openhands")
Returns:
bool: True if the exact mention is found, False otherwise
Example:
>>> has_exact_mention... | 🟢 **Nit**: This wrapper function is mostly redundant since `has_exact_mention` already handles falsy text values. Consider either:
1. Removing it and calling `has_exact_mention` directly, or
2. Adding more GitHub-specific logic (like checking for bot mentions to exclude)
Current implementation is fine, just a minor ... | """Check if the text contains an exact mention (not part of a larger word).
Args:
text: The text to check for mentions
mention: The mention to look for (e.g. "@openhands")
Returns:
bool: True if the exact mention is found, False otherwise
Example:
>>> has_exact_mention... | @@ -158,6 +158,73 @@ def has_exact_mention(text: str, mention: str) -> bool:
return bool(re.search(rf'(?:^|[^\w@]){pattern}(?![\w-])', text_lower))
+def github_webhook_has_openhands_mention(text: str, inline_oh_label: str) -> bool: | enterprise/integrations/utils.py | 26 | Python | 0.786 | refactor | 359 | 51 | 51 | false | Check event types before making expensive API calls in GitHub webhook handler | 12,819 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | tofarr |
if collaborator in ['admin', 'write']:
return True
except Exception:
pass
# If the above fails, check if the user is an owner or member
org = repository.organization
if org:
user = org.get_members(userna... | 🟢 **Nit**: The logic flow is correct, but the comment "FILTER FIRST (cheap operations)" is a bit misleading since conversation starter eligibility might not be that cheap depending on what `is_eligible_for_conversation_starter()` does internally.
Consider rephrasing to "CHECK EVENT TYPES FIRST (before API calls)" to... | if collaborator in ['admin', 'write']:
return True
except Exception:
pass
# If the above fails, check if the user is an owner or member
org = repository.organization
if org:
user = org.get_members(userna... | @@ -137,30 +137,49 @@ async def is_job_requested(self, message: Message) -> bool:
username = payload.get('sender', {}).get('login')
repo_name = self._get_full_repo_name(repo_obj)
- # Suggestions contain `@openhands` macro; avoid kicking off jobs for system recommendations
- if GithubFa... | enterprise/integrations/github/github_manager.py | 26 | Python | 0.786 | suggestion | 337 | 51 | 51 | false | Check event types before making expensive API calls in GitHub webhook handler | 12,819 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | tofarr |
mention_lower = mention.lower()
pattern = re.escape(mention_lower)
# Match mention that is not part of a larger word
return bool(re.search(rf'(?:^|[^\w@]){pattern}(?![\w-])', text_lower))
def github_webhook_has_openhands_mention(text: str, inline_oh_label: str) -> bool:
"""Check if text contains ... | All these checks could be done early in `receive_message` method
I'd like to avoid this since
1. the match conditions should be defined in one place
2. the early return check can happen in one place
Right now it seems like we're duplicating logic, unless I'm missing something | mention_lower = mention.lower()
pattern = re.escape(mention_lower)
# Match mention that is not part of a larger word
return bool(re.search(rf'(?:^|[^\w@]){pattern}(?![\w-])', text_lower))
def confirm_event_type(event: Event):
return isinstance(event, AgentStateChangedObservation) and not (
... | @@ -158,6 +158,86 @@ def has_exact_mention(text: str, mention: str) -> bool:
return bool(re.search(rf'(?:^|[^\w@]){pattern}(?![\w-])', text_lower))
+def github_webhook_has_openhands_mention(text: str, inline_oh_label: str) -> bool:
+ """Check if text contains an @openhands mention for GitHub webhook filteri... | enterprise/integrations/utils.py | 26 | Python | 0.643 | suggestion | 282 | 51 | 51 | false | Check event types before making expensive API calls in GitHub webhook handler | 12,819 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 | tofarr |
# If the above fails, check if the user is an owner or member
org = repository.organization
if org:
user = org.get_members(username)
return user is not None
return False
async def is_job_requested(self, message: Message) -> bool:
... | These early checks look good to me! I think the changes in just this method should be enough, and all the checks/utils elsewhere can be removed |
# If the above fails, check if the user is an owner or member
org = repository.organization
if org:
user = org.get_members(username)
return user is not None
return False
async def is_job_requested(self, message: Message) -> bool:
... | @@ -137,30 +137,49 @@ async def is_job_requested(self, message: Message) -> bool:
username = payload.get('sender', {}).get('login')
repo_name = self._get_full_repo_name(repo_obj)
- # Suggestions contain `@openhands` macro; avoid kicking off jobs for system recommendations
- if GithubFa... | enterprise/integrations/github/github_manager.py | 26 | Python | 0.429 | suggestion | 144 | 51 | 51 | false | Check event types before making expensive API calls in GitHub webhook handler | 12,819 | All-Hands-AI/OpenHands | 55,974 | Python | malhotra5 | tofarr |
message
) and GithubFailingAction.unqiue_suggestions_header in payload.get(
'comment', {}
).get('body', ''):
return False
# Check event types before making expensive API calls (e.g., _user_has_write_access_to_repo)
if not (
GithubFactory.i... | 🟠 **Important**: Redundant API call - `_user_has_write_access_to_repo()` is called twice when conversation starters are triggered (once on line 158 and again here on line 163). This expensive GitHub API call should be cached.
```suggestion
user_has_write_access = self._user_has_write_access_to_repo(installati... | message
) and GithubFailingAction.unqiue_suggestions_header in payload.get(
'comment', {}
).get('body', ''):
return False
# Check event types before making expensive API calls (e.g., _user_has_write_access_to_repo)
if not (
GithubFactory.i... | @@ -158,6 +154,11 @@ async def is_job_requested(self, message: Message) -> bool:
):
return False
+ if GithubFactory.is_eligible_for_conversation_starter(
+ message
+ ) and self._user_has_write_access_to_repo(installation_id, repo_name, username):
+ await Githu... | enterprise/integrations/github/github_manager.py | 26 | Python | 0.857 | security | 735 | 51 | 51 | false | Check event types before making expensive API calls in GitHub webhook handler | 12,819 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | tofarr |
// Here are the list of verified models and providers that we know work well with OpenHands.
export const VERIFIED_PROVIDERS = [
"openhands",
"anthropic",
"openai",
"mistral",
"lemonade",
"clarifai",
];
export const VERIFIED_MODELS = [
"claude-opus-4-5-20251101",
"claude-sonnet-4-5-20250929",
"gpt-5.2... | 🔴 Critical: This PR removes most of the verified models (o3, o4-mini, claude-3-5-sonnet, gemini-2.5-pro, gpt-4o, etc.) but the PR description only mentions adding MiniMax-M2.5. This is a massive breaking change that will remove support for many models users may be actively using.
**Required action**: Either:
1. Updat... | // Here are the list of verified models and providers that we know work well with OpenHands.
export const VERIFIED_PROVIDERS = [
"openhands",
"anthropic",
"openai",
"mistral",
"lemonade",
"clarifai",
];
export const VERIFIED_MODELS = [
"claude-opus-4-5-20251101",
"claude-sonnet-4-5-20250929",
"gpt-5.2... | @@ -8,86 +8,50 @@ export const VERIFIED_PROVIDERS = [
"clarifai",
];
export const VERIFIED_MODELS = [
- "o3-mini-2025-01-31", | frontend/src/utils/verified-models.ts | 11 | TypeScript | 0.5 | suggestion | 527 | 36 | 36 | false | Add MiniMax-M2.5 model support | 12,835 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | neubig |
// Here are the list of verified models and providers that we know work well with OpenHands.
export const VERIFIED_PROVIDERS = [
"openhands",
"anthropic",
"openai",
"mistral",
"lemonade",
"clarifai",
];
export const VERIFIED_MODELS = [
"claude-opus-4-5-20251101",
"claude-sonnet-4-5-20250929",
"gpt-5.2... | 🟠 Important: The model name uses PascalCase with capital "M" (`MiniMax-M2.5`), which is inconsistent with all other models in this file that use lowercase (e.g., `gpt-5.2`, `claude-opus-4-5-20251101`, `gemini-3-pro-preview`, `deepseek-chat`).
```suggestion
"minimax-m2.5",
```
Please verify this is the correct casi... | // Here are the list of verified models and providers that we know work well with OpenHands.
export const VERIFIED_PROVIDERS = [
"openhands",
"anthropic",
"openai",
"mistral",
"lemonade",
"clarifai",
];
export const VERIFIED_MODELS = [
"claude-opus-4-5-20251101",
"claude-sonnet-4-5-20250929",
"gpt-5.2... | @@ -8,86 +8,50 @@ export const VERIFIED_PROVIDERS = [
"clarifai",
];
export const VERIFIED_MODELS = [
- "o3-mini-2025-01-31",
- "o3-2025-04-16",
- "o3",
- "o4-mini-2025-04-16",
- "claude-3-5-sonnet-20241022", | frontend/src/utils/verified-models.ts | 15 | TypeScript | 0.857 | suggestion | 350 | 40 | 40 | false | Add MiniMax-M2.5 model support | 12,835 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | neubig |
// Here are the list of verified models and providers that we know work well with OpenHands.
export const VERIFIED_PROVIDERS = [
"openhands",
"anthropic",
"openai",
"mistral",
"lemonade",
"clarifai",
];
export const VERIFIED_MODELS = [
"claude-opus-4-5-20251101",
"claude-sonnet-4-5-20250929",
"gpt-5.2... | 🟠 Important: `deepseek-chat` is listed in VERIFIED_MODELS but there is no corresponding `openhands/deepseek-chat` entry in the backend `openhands_models` list in `llm.py`. This inconsistency will cause issues if users try to select this model. | // Here are the list of verified models and providers that we know work well with OpenHands.
export const VERIFIED_PROVIDERS = [
"openhands",
"anthropic",
"openai",
"mistral",
"lemonade",
"clarifai",
];
export const VERIFIED_MODELS = [
"claude-opus-4-5-20251101",
"claude-sonnet-4-5-20250929",
"gpt-5.2... | @@ -8,86 +8,50 @@ export const VERIFIED_PROVIDERS = [
"clarifai",
];
export const VERIFIED_MODELS = [
- "o3-mini-2025-01-31",
- "o3-2025-04-16",
- "o3",
- "o4-mini-2025-04-16",
- "claude-3-5-sonnet-20241022",
- "claude-3-7-sonnet-20250219",
- "claude-sonnet-4-20250514", | frontend/src/utils/verified-models.ts | 17 | TypeScript | 0.643 | style | 243 | 42 | 42 | false | Add MiniMax-M2.5 model support | 12,835 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | neubig |
and llm_config.aws_secret_access_key
):
bedrock_model_list = bedrock.list_foundation_models(
llm_config.aws_region_name,
llm_config.aws_access_key_id.get_secret_value(),
llm_config.aws_secret_access_key.get_secret_value(),
)
model_list = litellm_model_... | 🟠 Important: Same casing issue here - `MiniMax-M2.5` uses PascalCase with capital "M", which is inconsistent with other models in the list that use lowercase.
```suggestion
'openhands/minimax-m2.5',
```
Verify the correct casing with the LiteLLM provider configuration. | and llm_config.aws_secret_access_key
):
bedrock_model_list = bedrock.list_foundation_models(
llm_config.aws_region_name,
llm_config.aws_access_key_id.get_secret_value(),
llm_config.aws_secret_access_key.get_secret_value(),
)
model_list = litellm_model_... | @@ -111,18 +111,14 @@ def get_supported_llm_models(config: OpenHandsConfig) -> list[str]:
# Add OpenHands provider models
openhands_models = [
- 'openhands/claude-sonnet-4-20250514',
- 'openhands/claude-sonnet-4-5-20250929',
- 'openhands/gpt-5-2025-08-07',
- 'openhands/gpt-5-mini... | openhands/utils/llm.py | 26 | Python | 0.857 | suggestion | 279 | 51 | 51 | false | Add MiniMax-M2.5 model support | 12,835 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | neubig |
import { useTranslation } from "react-i18next";
import { ModalBackdrop } from "#/components/shared/modals/modal-backdrop";
import { SettingsInput } from "#/components/features/settings/settings-input";
import { BrandButton } from "#/components/features/settings/brand-button";
import { LoadingSpinner } from "#/component... | 🟠 **Important**: Missing `onError` callback. If the API call fails, the modal stays open with no feedback to the user. Consider adding error handling:
```suggestion
if (orgName?.trim()) {
updateOrganization(orgName, {
onSuccess: () => {
onClose();
},
onError: (error) => {
... | import { useTranslation } from "react-i18next";
import { ModalBackdrop } from "#/components/shared/modals/modal-backdrop";
import { SettingsInput } from "#/components/features/settings/settings-input";
import { BrandButton } from "#/components/features/settings/brand-button";
import { LoadingSpinner } from "#/component... | @@ -0,0 +1,75 @@
+import { useTranslation } from "react-i18next";
+import { ModalBackdrop } from "#/components/shared/modals/modal-backdrop";
+import { SettingsInput } from "#/components/features/settings/settings-input";
+import { BrandButton } from "#/components/features/settings/brand-button";
+import { LoadingSpinn... | frontend/src/components/features/org/change-org-name-modal.tsx | 23 | TypeScript | 1 | bug | 460 | 48 | 48 | false | feat(frontend): allow users to change organization name | 12,842 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
if (orgName?.trim()) {
updateOrganization(orgName, {
onSuccess: () => {
onClose();
},
});
}
};
return (
<ModalBackdrop onClose={onClose}>
<form
action={formAction}
data-testid="update-org-name-form"
className="bg-base rounded-xl p-4 b... | 🟡 **Suggestion**: Consider showing the current organization name as a default value or placeholder. This improves UX by letting users edit the existing name rather than typing from scratch. You could pass the current org name as a prop:
```typescript
interface ChangeOrgNameModalProps {
onClose: () => void;
curren... | const orgName = formData.get("org-name")?.toString();
if (orgName?.trim()) {
updateOrganization(orgName, {
onSuccess: () => {
onClose();
},
});
}
};
return (
<ModalBackdrop onClose={onClose}>
<form
action={formAction}
data-testid="update-... | @@ -0,0 +1,75 @@
+import { useTranslation } from "react-i18next";
+import { ModalBackdrop } from "#/components/shared/modals/modal-backdrop";
+import { SettingsInput } from "#/components/features/settings/settings-input";
+import { BrandButton } from "#/components/features/settings/brand-button";
+import { LoadingSpinn... | frontend/src/components/features/org/change-org-name-modal.tsx | 26 | TypeScript | 1 | suggestion | 388 | 51 | 51 | false | feat(frontend): allow users to change organization name | 12,842 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
import { SettingsInput } from "#/components/features/settings/settings-input";
import { BrandButton } from "#/components/features/settings/brand-button";
import { LoadingSpinner } from "#/components/shared/loading-spinner";
import { I18nKey } from "#/i18n/declaration";
import { useUpdateOrganization } from "#/hooks/mut... | 🟡 **Suggestion**: Consider adding client-side validation for organization names (e.g., minimum length, no special characters, etc.). This provides instant feedback before making an API call:
```typescript
if (!orgName?.trim()) {
// Show error: "Organization name cannot be empty"
return;
}
if (orgName.length < 3) ... | import { SettingsInput } from "#/components/features/settings/settings-input";
import { BrandButton } from "#/components/features/settings/brand-button";
import { LoadingSpinner } from "#/components/shared/loading-spinner";
import { I18nKey } from "#/i18n/declaration";
import { useUpdateOrganization } from "#/hooks/mut... | @@ -0,0 +1,75 @@
+import { useTranslation } from "react-i18next";
+import { ModalBackdrop } from "#/components/shared/modals/modal-backdrop";
+import { SettingsInput } from "#/components/features/settings/settings-input";
+import { BrandButton } from "#/components/features/settings/brand-button";
+import { LoadingSpinn... | frontend/src/components/features/org/change-org-name-modal.tsx | 26 | TypeScript | 1 | suggestion | 403 | 51 | 51 | false | feat(frontend): allow users to change organization name | 12,842 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
import { ModalBody } from "#/components/shared/modals/modal-body";
import { BrandButton } from "#/components/features/settings/brand-button";
import { LoadingSpinner } from "#/components/shared/loading-spinner";
import { I18nKey } from "#/i18n/declaration";
import { useDeleteOrganization } from "#/hooks/mutation/use-de... | 🔴 Critical: Missing error handling for deletion failure.
If `deleteOrganization` fails (network error, permission denied, etc.), the user gets no feedback and the modal remains open in a stuck state. Add an `onError` handler:
```suggestion
const handleConfirm = () => {
deleteOrganization(undefined, {
onS... | import { ModalBody } from "#/components/shared/modals/modal-body";
import { BrandButton } from "#/components/features/settings/brand-button";
import { LoadingSpinner } from "#/components/shared/loading-spinner";
import { I18nKey } from "#/i18n/declaration";
import { useDeleteOrganization } from "#/hooks/mutation/use-de... | @@ -0,0 +1,80 @@
+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/... | frontend/src/components/features/org/delete-org-confirmation-modal.tsx | 26 | TypeScript | 1 | bug | 494 | 51 | 51 | false | feat(frontend): integrate with the delete organization api | 12,845 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
}: DeleteOrgConfirmationModalProps) {
const { t } = useTranslation();
const { mutate: deleteOrganization, isPending } = useDeleteOrganization();
const { data: organization } = useOrganization();
const handleConfirm = () => {
deleteOrganization(undefined, {
onSuccess: onClose,
});
};
const co... | 🟠 Important: Modal can be closed during deletion operation.
The backdrop allows closing while `isPending` is true, which could leave the deletion in an inconsistent state. Disable closing during the operation:
```suggestion
<ModalBackdrop onClose={isPending ? undefined : onClose}>
``` | onClose,
}: DeleteOrgConfirmationModalProps) {
const { t } = useTranslation();
const { mutate: deleteOrganization, isPending } = useDeleteOrganization();
const { data: organization } = useOrganization();
const handleConfirm = () => {
deleteOrganization(undefined, {
onSuccess: onClose,
onError... | @@ -0,0 +1,80 @@
+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/... | frontend/src/components/features/org/delete-org-confirmation-modal.tsx | 26 | TypeScript | 1 | suggestion | 291 | 51 | 51 | false | feat(frontend): integrate with the delete organization api | 12,845 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
const handleConfirm = () => {
deleteOrganization(undefined, {
onSuccess: onClose,
});
};
const confirmationMessage = organization?.name ? (
<Trans
i18nKey={I18nKey.ORG$DELETE_ORGANIZATION_WARNING_WITH_NAME}
values={{ name: organization.name }}
components={{ name: <span classNa... | 🟡 Suggestion: `stopPropagation` appears unnecessary here.
This event handler prevents event bubbling, but the buttons already handle their own clicks. If the intent was to prevent backdrop clicks from closing the modal, that should be on the `ModalBody` itself (which likely already handles this). Consider removing th... |
const handleConfirm = () => {
deleteOrganization(undefined, {
onSuccess: onClose,
onError: () => {
displayErrorToast(t(I18nKey.ORG$DELETE_ORGANIZATION_ERROR));
},
});
};
const confirmationMessage = organization?.name ? (
<Trans
i18nKey={I18nKey.ORG$DELETE_ORGANIZATION... | @@ -0,0 +1,80 @@
+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/... | frontend/src/components/features/org/delete-org-confirmation-modal.tsx | 26 | TypeScript | 0.786 | suggestion | 355 | 51 | 51 | false | feat(frontend): integrate with the delete organization api | 12,845 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
export function DeleteOrgConfirmationModal({
onClose,
}: DeleteOrgConfirmationModalProps) {
const { t } = useTranslation();
const { mutate: deleteOrganization, isPending } = useDeleteOrganization();
const { data: organization } = useOrganization();
const handleConfirm = () => {
deleteOrganization(undefi... | 🟡 Suggestion: Add ARIA label for accessibility.
The modal should announce its purpose to screen readers:
```suggestion
<ModalBackdrop onClose={onClose} aria-label={t(I18nKey.ORG$DELETE_ORGANIZATION)}>
``` | }
export function DeleteOrgConfirmationModal({
onClose,
}: DeleteOrgConfirmationModalProps) {
const { t } = useTranslation();
const { mutate: deleteOrganization, isPending } = useDeleteOrganization();
const { data: organization } = useOrganization();
const handleConfirm = () => {
deleteOrganization(unde... | @@ -0,0 +1,80 @@
+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/... | frontend/src/components/features/org/delete-org-confirmation-modal.tsx | 26 | TypeScript | 0.857 | suggestion | 210 | 51 | 51 | false | feat(frontend): integrate with the delete organization api | 12,845 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
);
return (
<ModalBackdrop onClose={onClose}>
<ModalBody className="items-start border border-tertiary">
<div className="flex flex-col gap-2">
<BaseModalTitle title={t(I18nKey.ORG$DELETE_ORGANIZATION)} />
<BaseModalDescription>{confirmationMessage}</BaseModalDescription>
... | 🟡 Suggestion: Verify `isDisabled` is the correct prop.
Most React components use `disabled` rather than `isDisabled`. Double-check that `BrandButton` accepts this prop name, or consider standardizing to `disabled` if not. | components={{ name: <span className="text-white" /> }}
/>
) : (
t(I18nKey.ORG$DELETE_ORGANIZATION_WARNING)
);
return (
<ModalBackdrop
onClose={isPending ? undefined : onClose}
aria-label={t(I18nKey.ORG$DELETE_ORGANIZATION)}
>
<ModalBody
className="items-start borde... | @@ -0,0 +1,80 @@
+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/... | frontend/src/components/features/org/delete-org-confirmation-modal.tsx | 26 | TypeScript | 0.643 | suggestion | 222 | 43 | 49 | false | feat(frontend): integrate with the delete organization api | 12,845 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
);
// Auto-select the first organization when data loads and no org is selected
React.useEffect(() => {
if (!organizationId && organizations && organizations.length > 0) {
setOrganizationId(organizations[0].id);
}
}, [organizationId, organizations, setOrganizationId]);
const selectedOrg = Reac... | 🟡 **Suggestion**: This effect-based state synchronization is the root cause of the race condition. With the custom hook approach, you can replace this entire block with:
```typescript
const shouldHide = useShouldHideOrgSelector();
if (shouldHide) {
return null;
}
```
No effects, no external state, no timing issue... | );
// Auto-select the first organization when data loads and no org is selected
React.useEffect(() => {
if (!organizationId && organizations && organizations.length > 0) {
setOrganizationId(organizations[0].id);
}
}, [organizationId, organizations, setOrganizationId]);
const selectedOrg = Reac... | @@ -35,6 +37,17 @@ export function OrgSelector() {
return organizations?.[0];
}, [organizationId, organizations]);
+ // Hide selector when user only has a personal workspace (nothing to switch to)
+ React.useEffect(() => {
+ const shouldHide =
+ organizations?.length === 1 && organizations[0]?.is_pe... | frontend/src/components/features/org/org-selector.tsx | 26 | TypeScript | 1 | bug | 321 | 51 | 46 | false | feat(frontend): hide org selector when only personal workspace exists | 12,847 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | 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**: With the custom hook approach, this would become:
```typescript
const shouldHideSelector = useShouldHideOrgSelector();
```
This ensures consistent behavior without depending on `OrgSelector` having mounted first. | 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... | @@ -20,6 +21,7 @@ export function SettingsNavigation({
navigationItems,
}: SettingsNavigationProps) {
const { t } = useTranslation();
+ const { shouldHideSelector } = useOrganizationStore(); | frontend/src/components/features/settings/settings-navigation.tsx | 24 | TypeScript | 1 | suggestion | 232 | 49 | 49 | false | feat(frontend): hide org selector when only personal workspace exists | 12,847 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
mock_billing_session.user_id = 'mock_user'
with (
patch('server.routes.billing.session_maker') as mock_session_maker,
patch('stripe.checkout.Session.retrieve') as mock_stripe_retrieve,
patch(
'storage.user_store.UserStore.get_user_by_id_async',
new_callable=Async... | 🟡 Suggestion: This line is now redundant since `side_effect` (set below at line 332) overrides `return_value`. When `query()` is called, the mock will use the side_effect behavior instead, so this line will be ignored.
```suggestion
# First query: BillingSession (query().filter().filter().first())
# S... | mock_billing_session.user_id = 'mock_user'
mock_org = MagicMock()
with (
patch('server.routes.billing.session_maker') as mock_session_maker,
patch('stripe.checkout.Session.retrieve') as mock_stripe_retrieve,
patch(
'storage.user_store.UserStore.get_user_by_id_async',
... | @@ -317,10 +319,19 @@ async def test_success_callback_success():
patch(
'storage.lite_llm_manager.LiteLlmManager.update_team_and_users_budget'
) as mock_update_budget,
- patch('server.routes.billing.OrgStore.update_org') as mock_update_org,
):
mock_db_session = MagicM... | enterprise/tests/unit/test_billing.py | 26 | Python | 0.857 | suggestion | 454 | 51 | 51 | false | fix(backend): enable byor key export after purchasing credits | 12,862 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
extra={
'checkout_session_id': session_id,
'stripe_customer_id': stripe_session.customer,
},
)
raise HTTPException(status.HTTP_400_BAD_REQUEST)
user = await UserStore.get_user_by_id_async(billing_session.user_id)
... | 🟡 Suggestion: Consider adding logging or error handling if the org is not found. While this scenario is unlikely (the user's org should exist after successful authentication), failing silently could make debugging difficult if it does occur.
Example approach:
```python
if org:
org.byor_export_enabled = True
else:... | extra={
'checkout_session_id': session_id,
'stripe_customer_id': stripe_session.customer,
},
)
raise HTTPException(status.HTTP_400_BAD_REQUEST)
user = await UserStore.get_user_by_id_async(billing_session.user_id)
... | @@ -261,7 +261,10 @@ async def success_callback(session_id: str, request: Request):
)
# Enable BYOR export for the org now that they've purchased credits
- OrgStore.update_org(user.current_org_id, {'byor_export_enabled': True})
+ # Update within the same session to avoid nested session... | enterprise/server/routes/billing.py | 26 | Python | 1 | bug | 534 | 51 | 51 | false | fix(backend): enable byor key export after purchasing credits | 12,862 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
# support AWS Bedrock provider
kwargs['aws_region_name'] = self.config.aws_region_name
if self.config.aws_access_key_id:
kwargs['aws_access_key_id'] = (
self.config.aws_access_key_id.get_secret_value()
)
if self.config.aws_secret_access_key:
... | 🟡 Suggestion: Consider a pattern-based check like `"claude-opus-4" in _model_lower` to automatically cover future 4.x versions without code changes. However, the explicit approach is safer if future versions might have different behavior. | # support AWS Bedrock provider
kwargs['aws_region_name'] = self.config.aws_region_name
if self.config.aws_access_key_id:
kwargs['aws_access_key_id'] = (
self.config.aws_access_key_id.get_secret_value()
)
if self.config.aws_secret_access_key:
... | @@ -198,13 +198,14 @@ def __init__(
if 'claude-opus-4-1' in self.config.model.lower():
kwargs['thinking'] = {'type': 'disabled'}
- # Anthropic constraint: Opus 4.1, Opus 4.5, and Sonnet 4 models cannot accept both temperature and top_p
+ # Anthropic constraint: Opus 4.1, Opus 4.5, ... | openhands/llm/llm.py | 26 | Python | 0.643 | suggestion | 238 | 51 | 51 | false | fix: add claude-opus-4-6 to temperature/top_p guard | 12,874 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | 314clay |
const filePrompt = `${t("CHAT_INTERFACE$AUGMENTED_PROMPT_FILES_TITLE")}: ${uploadedFiles.join("\n\n")}`;
const prompt =
uploadedFiles.length > 0 ? `${content}\n\n${filePrompt}` : content;
send(createChatMessage(prompt, imageUrls, uploadedFiles, timestamp));
setOptimisticUserMessage(content);
... | 🟡 Suggestion: Consider including `autoScroll` in the dependency array instead of disabling the linter.
While the current implementation works (the effect will see the current `autoScroll` value from each render), excluding it violates React best practices. The exhaustive-deps rule exists to prevent subtle bugs.
Incl... |
const filePrompt = `${t("CHAT_INTERFACE$AUGMENTED_PROMPT_FILES_TITLE")}: ${uploadedFiles.join("\n\n")}`;
const prompt =
uploadedFiles.length > 0 ? `${content}\n\n${filePrompt}` : content;
send(createChatMessage(prompt, imageUrls, uploadedFiles, timestamp));
setOptimisticUserMessage(content);
... | @@ -209,6 +209,21 @@ export function ChatInterface() {
setFeedbackPolarity(polarity);
};
+ // Auto-scroll to bottom when new messages arrive
+ React.useEffect(() => {
+ if (autoScroll) {
+ scrollDomToBottom();
+ }
+ // Note: We intentionally exclude autoScroll from deps because we only want
+ ... | frontend/src/components/features/chat/chat-interface.tsx | 26 | TypeScript | 0.786 | bug | 774 | 51 | 51 | false | fix(frontend): add auto-scroll when new messages arrive in chat | 12,885 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
uploadedFiles.length > 0 ? `${content}\n\n${filePrompt}` : content;
send(createChatMessage(prompt, imageUrls, uploadedFiles, timestamp));
setOptimisticUserMessage(content);
setMessageToSend("");
};
const onClickShareFeedbackActionButton = async (
polarity: "positive" | "negative",
) => {
... | 🟡 Suggestion: Verify that `optimisticUserMessage` has a stable reference.
If `getOptimisticUserMessage()` returns a new object reference on every render, this effect will run on every render even when the message content hasn't changed. Consider:
1. Tracking a specific property like `optimisticUserMessage?.id` or `op... | uploadedFiles.length > 0 ? `${content}\n\n${filePrompt}` : content;
send(createChatMessage(prompt, imageUrls, uploadedFiles, timestamp));
setOptimisticUserMessage(content);
setMessageToSend("");
};
const onClickShareFeedbackActionButton = async (
polarity: "positive" | "negative",
) => {
... | @@ -209,6 +209,21 @@ export function ChatInterface() {
setFeedbackPolarity(polarity);
};
+ // Auto-scroll to bottom when new messages arrive
+ React.useEffect(() => {
+ if (autoScroll) {
+ scrollDomToBottom();
+ }
+ // Note: We intentionally exclude autoScroll from deps because we only want
+ ... | frontend/src/components/features/chat/chat-interface.tsx | 26 | TypeScript | 0.643 | suggestion | 485 | 51 | 51 | false | fix(frontend): add auto-scroll when new messages arrive in chat | 12,885 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
import asyncio # noqa: I001
# This must be before the import of storage
# to set up logging and prevent alembic from
# running it's mouth.
from openhands.core.logger import openhands_logger
from storage.proactive_conversation_store import (
ProactiveConversationStore,
)
OLDER_THAN = 30 # 30 minutes
async def... | 🟡 Suggestion: The `# noqa: I001` is placed on the `asyncio` import, but the import that's actually out of alphabetical order is the `openhands.core.logger` import (which intentionally comes before `storage`).
You may want to verify that this placement suppresses the isort warning as intended. If it doesn't, consider:... | import asyncio # noqa: I001
# This must be before the import of storage
# to set up logging and prevent alembic from
# running its mouth.
from openhands.core.logger import openhands_logger
from storage.proactive_conversation_store import (
ProactiveConversationStore,
)
OLDER_THAN = 30 # 30 minutes
async def ... | @@ -1,9 +1,14 @@
-import asyncio
-
-from storage.proactive_conversation_store import ProactiveConversationStore
+import asyncio # noqa: I001 | enterprise/sync/clean_proactive_convo_table.py | 1 | Python | 0.643 | suggestion | 596 | 23 | 23 | false | fix: preserve import order in clean_proactive_convo_table.py | 12,901 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | tofarr |
import asyncio # noqa: I001
# This must be before the import of storage
# to set up logging and prevent alembic from
# running it's mouth.
from openhands.core.logger import openhands_logger
from storage.proactive_conversation_store import (
ProactiveConversationStore,
)
OLDER_THAN = 30 # 30 minutes
async def... | 🟢 Nit: Typo - "it's mouth" should be "its mouth" (possessive, not contraction).
```suggestion
# running its mouth.
``` | import asyncio # noqa: I001
# This must be before the import of storage
# to set up logging and prevent alembic from
# running its mouth.
from openhands.core.logger import openhands_logger
from storage.proactive_conversation_store import (
ProactiveConversationStore,
)
OLDER_THAN = 30 # 30 minutes
async def ... | @@ -1,9 +1,14 @@
-import asyncio
-
-from storage.proactive_conversation_store import ProactiveConversationStore
+import asyncio # noqa: I001
+# This must be before the import of storage
+# to set up logging and prevent alembic from
+# running it's mouth. | enterprise/sync/clean_proactive_convo_table.py | 5 | Python | 0.786 | suggestion | 119 | 23 | 23 | false | fix: preserve import order in clean_proactive_convo_table.py | 12,901 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | tofarr |
sandbox_runtime_container_image: str | None = None
mcp_config: dict | None = None
sandbox_api_key: str | None = None
max_budget_per_task: float | None = Field(default=None, gt=0)
enable_solvability_analysis: bool | None = None
v1_enabled: bool | None = None
# LLM settings (require admin/own... | 🔴 **Critical: Breaking API Change**
This field rename changes the JSON response from `role_name` to `role` for the following API endpoints:
- `GET /orgs/{org_id}/members` (returns `OrgMemberPage` containing list of `OrgMemberResponse`)
- `PATCH /orgs/{org_id}/members/{user_id}` (returns `OrgMemberResponse`)
**Action... | sandbox_runtime_container_image: str | None = None
mcp_config: dict | None = None
sandbox_api_key: str | None = None
max_budget_per_task: float | None = Field(default=None, gt=0)
enable_solvability_analysis: bool | None = None
v1_enabled: bool | None = None
# LLM settings (require admin/own... | @@ -257,7 +257,7 @@ class OrgMemberResponse(BaseModel):
user_id: str
email: str | None
role_id: int
- role_name: str
+ role: str | enterprise/server/routes/org_models.py | 26 | Python | 0.857 | suggestion | 924 | 51 | 51 | false | refactor(backend): rename orgmemberresponse.role_name to role | 12,914 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
if page_id is not None:
try:
offset = int(page_id)
if offset < 0:
return False, 'invalid_page_id', None
except ValueError:
return False, 'invalid_page_id', None
# Call store to get paginated members
memb... | ✅ **Verification Complete**: All three instantiations of `OrgMemberResponse` in this service have been properly updated:
- Line 107: `get_org_members` - ✓
- Line 243: `update_org_member_role` (existing member) - ✓
- Line 283: `update_org_member_role` (updated member) - ✓
The implementation is consistent throughout. | if page_id is not None:
try:
offset = int(page_id)
if offset < 0:
return False, 'invalid_page_id', None
except ValueError:
return False, 'invalid_page_id', None
# Call store to get paginated members
memb... | @@ -104,7 +104,7 @@ async def get_org_members(
user_id=str(member.user_id),
email=user.email if user else None,
role_id=member.role_id,
- role_name=role.name if role else '',
+ role=role.name if role else '', | enterprise/server/services/org_member_service.py | 26 | Python | 0.571 | suggestion | 317 | 51 | 51 | false | refactor(backend): rename orgmemberresponse.role_name to role | 12,914 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
page_id: Optional page ID (offset) for pagination
limit: Maximum number of organizations to return (1-100, default 100)
user_id: Authenticated user ID (injected by dependency)
Returns:
OrgPage: Paginated list of organizations
Raises:
HTTPException: 500 if retrieval fail... | 🟡 Suggestion: This adds an additional database query to every organization list request. Consider if the user object is already available from the authentication context (e.g., via the request state or middleware) to avoid the extra query. If this endpoint is frequently called, the performance impact could be noticeab... | Args:
page_id: Optional page ID (offset) for pagination
limit: Maximum number of organizations to return (1-100, default 100)
user_id: Authenticated user ID (injected by dependency)
Returns:
OrgPage: Paginated list of organizations
Raises:
HTTPException: 500 if retr... | @@ -78,6 +79,12 @@ async def list_user_orgs(
)
try:
+ # Fetch user to get current_org_id
+ user = await UserStore.get_user_by_id_async(user_id)
+ current_org_id = (
+ str(user.current_org_id) if user and user.current_org_id else None
+ ) | enterprise/server/routes/orgs.py | 26 | Python | 0.643 | security | 322 | 51 | 51 | false | refactor(backend): include current_org_id in organization list response | 12,915 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
response = client.get('/api/organizations?page_id=0&limit=2')
# Assert
assert response.status_code == status.HTTP_200_OK
response_data = response.json()
assert len(response_data['items']) == 2
assert response_data['next_page_id'] == '2'
assert response_data['item... | 🟠 Important: Missing test case for when `user.current_org_id` is `None`. This is a realistic scenario when a user hasn't selected an organization yet. Please add a test that verifies the API returns `"current_org_id": null` in this case.
Example test:
```python
@pytest.mark.asyncio
async def test_list_user_orgs_null_... | contact_name='Jane Doe',
contact_email='jane@example.com',
)
mock_user = MagicMock()
mock_user.current_org_id = current_org_id
with (
patch(
'server.routes.orgs.UserStore.get_user_by_id_async',
AsyncMock(return_value=mock_user),
),
patch(
... | @@ -536,6 +544,54 @@ async def test_list_user_orgs_success(mock_app_list):
assert response_data['items'][0]['credits'] is None
+@pytest.mark.asyncio
+async def test_list_user_orgs_returns_current_org_id(mock_app_list):
+ """
+ GIVEN: User has a current organization set
+ WHEN: GET /api/organizatio... | enterprise/tests/unit/server/routes/test_orgs.py | 26 | Python | 1 | suggestion | 1,103 | 51 | 51 | false | refactor(backend): include current_org_id in organization list response | 12,915 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
"""
# Arrange
client = TestClient(mock_app_list)
# Act
response = client.get('/api/organizations?limit=0')
# Assert
assert response.status_code == status.HTTP_422_UNPROCESSABLE_ENTITY
@pytest.mark.asyncio
async def test_list_user_orgs_service_error(mock_app_list):
"""
GIVEN: Serv... | 🟢 Nit: This test mocks a user with a `current_org_id` even though the organization list is empty. For better test realism, consider setting `mock_user.current_org_id = None` here since a user with no organizations likely wouldn't have a current org selected. | return_value=([org1, org2], '2'),
),
):
client = TestClient(mock_app_list)
# Act
response = client.get('/api/organizations?page_id=0&limit=2')
# Assert
assert response.status_code == status.HTTP_200_OK
response_data = response.json()
asse... | @@ -583,9 +647,18 @@ async def test_list_user_orgs_empty(mock_app_list):
THEN: Empty list is returned with 200 status
"""
# Arrange
- with patch(
- 'server.routes.orgs.OrgService.get_user_orgs_paginated',
- return_value=([], None),
+ mock_user = MagicMock() | enterprise/tests/unit/server/routes/test_orgs.py | 26 | Python | 0.643 | suggestion | 258 | 51 | 51 | false | refactor(backend): include current_org_id in organization list response | 12,915 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
pending_free_credits=True,
)
session.add(org)
settings = await UserStore.create_default_settings(
org_id=str(org.id), user_id=user_id
)
if not settings:
return None
from storage.org_store import Or... | 🟠 **Important**: Setting fields after object creation is inconsistent with the existing pattern. These values should be included in `user_kwargs` before creating the User object, similar to how other fields are handled.
This approach could also bypass SQLAlchemy validators or default value logic that runs during `__i... | )
session.add(org)
settings = await UserStore.create_default_settings(
org_id=str(org.id), user_id=user_id
)
if not settings:
return None
from storage.org_store import OrgStore
org_kwargs = OrgStore.g... | @@ -83,6 +84,8 @@ async def create_user(
role_id=role_id,
**user_kwargs,
)
+ user.email = user_info.get('email') | enterprise/storage/user_store.py | 26 | Python | 1 | suggestion | 720 | 51 | 51 | false | fix(backend): set user email fields from user_info during create_user | 12,921 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
v1_enabled=True,
pending_free_credits=True,
)
session.add(org)
settings = await UserStore.create_default_settings(
org_id=str(org.id), user_id=user_id
)
if not settings:
return None
... | 🟡 **Suggestion**: Using `.get()` will set the fields to `None` if the keys are missing. Consider whether this is the desired behavior or if there should be validation:
- Should `email` be required from Keycloak?
- Should there be a fallback or warning if email is missing?
- Is `None` an acceptable value for these dat... | v1_enabled=True,
)
session.add(org)
settings = await UserStore.create_default_settings(
org_id=str(org.id), user_id=user_id
)
if not settings:
return None
from storage.org_store import OrgStore
... | @@ -83,6 +84,8 @@ async def create_user(
role_id=role_id,
**user_kwargs,
) | enterprise/storage/user_store.py | 26 | Python | 0.643 | question | 333 | 51 | 51 | false | fix(backend): set user email fields from user_info during create_user | 12,921 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
class SaasSQLAppConversationInfoService(SQLAppConversationInfoService):
"""Extended SQLAppConversationInfoService with user and organization-based filtering and SAAS metadata handling."""
async def _secure_select(self):
query = (
select(StoredConversationMetadata)
.join(
... | 🟠 Important: This user lookup and org filtering logic is duplicated in three places (_secure_select, _secure_select_with_saas_metadata, and count_app_conversation_info). Consider extracting it into a helper method like `_apply_org_filter(query, user_id_str)` to reduce duplication and improve maintainability.
```sugge... |
class SaasSQLAppConversationInfoService(SQLAppConversationInfoService):
"""Extended SQLAppConversationInfoService with user and organization-based filtering and SAAS metadata handling."""
async def _get_current_user(self) -> User | None:
"""Get the current user using the existing db_session.
... | @@ -44,6 +45,13 @@ async def _secure_select(self):
user_id_uuid = UUID(user_id_str)
query = query.where(StoredConversationMetadataSaas.user_id == user_id_uuid)
+ # Filter by organization ID to ensure conversations are isolated per organization
+ user = await UserStore.g... | enterprise/server/utils/saas_app_conversation_info_injector.py | 26 | Python | 0.857 | refactor | 554 | 51 | 51 | false | fix(backend): add organization filtering to V1 conversation queries | 12,923 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
assert user1_id != user2_id
@pytest.mark.asyncio
async def test_secure_select_includes_user_filtering(
self,
saas_service_user1: SaasSQLAppConversationInfoService,
):
"""Test that _secure_select method includes user filtering."""
from unittest.mock import AsyncMock, ... | 🟡 Suggestion: Consider adding test cases for edge scenarios:
- User with `current_org_id = None`
- `UserStore.get_user_by_id_async()` returns None
- User switching between organizations (same user_id, different org_ids at different times)
These edge cases would ensure the filtering behavior is correct in all scenario... | """Create user context for user2."""
return SpecifyUserContext(user_id='b2222222-2222-2222-2222-222222222222')
@pytest.fixture
def saas_service_user1(mock_db_session, user1_context):
"""Create a SaasSQLAppConversationInfoService instance for user1."""
return SaasSQLAppConversationInfoService(
... | @@ -183,10 +183,24 @@ async def test_secure_select_includes_user_filtering(
saas_service_user1: SaasSQLAppConversationInfoService,
):
"""Test that _secure_select method includes user filtering."""
- # This test verifies that the _secure_select method exists and can be called
- # The... | enterprise/tests/unit/storage/test_saas_sql_app_conversation_info_service.py | 26 | Python | 0.786 | bug | 321 | 51 | 51 | false | fix(backend): add organization filtering to V1 conversation queries | 12,923 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026
# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.
# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application ser... | 🟠 Important: This endpoint is redundant with the existing `/alive` endpoint (line 15-17), which is already used as a readiness probe in the Kubernetes runtime (`openhands/runtime/impl/kubernetes/kubernetes_runtime.py:509`).
Consider:
1. Using the existing `/alive` endpoint for readiness checks instead of creating a n... |
from openhands.runtime.utils.system_stats import get_system_info
def add_health_endpoints(app: FastAPI):
@app.get('/alive')
async def alive():
"""Endpoint for liveness probes. If this responds then the server is
considered alive."""
return {'status': 'ok'}
@app.get('/health')
... | @@ -23,3 +23,7 @@ async def health() -> str:
@app.get('/server_info')
async def get_server_info():
return get_system_info()
+
+ @app.get('/ready')
+ async def ready() -> str:
+ return 'OK' | openhands/server/routes/health.py | 26 | Python | 0.643 | suggestion | 542 | 30 | 27 | false | Added endpoint for readiness probe | 12,927 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | tofarr |
# IMPORTANT: LEGACY V0 CODE - Deprecated since version 1.0.0, scheduled for removal April 1, 2026
# This file is part of the legacy (V0) implementation of OpenHands and will be removed soon as we complete the migration to V1.
# OpenHands V1 uses the Software Agent SDK for the agentic core and runs a new application ser... | 🟡 Suggestion: A proper readiness probe should verify that the system is actually ready to serve traffic (e.g., check database connections, required services are up). Currently, this always returns OK, making it functionally identical to a liveness check.
If the simple implementation is intentional (e.g., matching age... |
from openhands.runtime.utils.system_stats import get_system_info
def add_health_endpoints(app: FastAPI):
@app.get('/alive')
async def alive():
"""Endpoint for liveness probes. If this responds then the server is
considered alive."""
return {'status': 'ok'}
@app.get('/health')
... | @@ -23,3 +23,7 @@ async def health() -> str:
@app.get('/server_info')
async def get_server_info():
return get_system_info()
+
+ @app.get('/ready')
+ async def ready() -> str:
+ return 'OK' | openhands/server/routes/health.py | 26 | Python | 0.5 | suggestion | 397 | 30 | 27 | false | Added endpoint for readiness probe | 12,927 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | tofarr |
className={cn(
"w-72 flex flex-col gap-3 bg-tertiary border border-tertiary rounded-xl p-4",
"text-sm absolute left-full bottom-0 z-60",
)}
>
{inviteMemberModalIsOpen &&
ReactDOM.createPortal(
<InviteOrganizationMemberModal
onClose={() => setInviteMemb... | 🟡 Suggestion: The wrapper div pattern `className="flex flex-col items-start gap-0 w-full"` is repeated three times (lines 103, 132, 152). Consider extracting it to reduce duplication:
```suggestion
const menuSectionClassName = "flex flex-col items-start gap-0 w-full";
```
Then use: `<div className={menuSectionClassN... | className={cn(
"w-72 flex flex-col gap-3 bg-tertiary border border-tertiary rounded-xl p-4",
"text-sm absolute left-full bottom-0 z-101",
)}
>
{inviteMemberModalIsOpen &&
ReactDOM.createPortal(
<InviteOrganizationMemberModal
onClose={() => setInviteMem... | @@ -101,7 +100,7 @@ export function UserContextMenu({ type, onClose }: UserContextMenuProps) {
)}
{!isMember && !isPersonalOrg && (
- <>
+ <div className="flex flex-col items-start gap-0 w-full"> | frontend/src/components/features/user/user-context-menu.tsx | 26 | TypeScript | 0.857 | refactor | 325 | 51 | 51 | false | refactor(frontend): update user context menu styling | 12,929 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
import { useQuery } from "@tanstack/react-query";
import React from "react";
import { usePostHog } from "posthog-js/react";
import { useConfig } from "./use-config";
import UserService from "#/api/user-service/user-service.api";
import { useShouldShowUserFeatures } from "#/hooks/use-should-show-user-features";
import {... | 🔴 Critical: `onError` is not supported in TanStack Query v5 (this project uses v5.90.19). This callback was removed in v5 and only exists for mutations, not queries. This code will not execute as intended.
The correct approach is to use a `useEffect` to watch the error property:
```typescript
const user = useQuery({... | import { useQuery } from "@tanstack/react-query";
import React from "react";
import { usePostHog } from "posthog-js/react";
import { useConfig } from "./use-config";
import UserService from "#/api/user-service/user-service.api";
import { useShouldShowUserFeatures } from "#/hooks/use-should-show-user-features";
import {... | @@ -19,6 +22,11 @@ export const useGitUser = () => {
retry: false,
staleTime: 1000 * 60 * 5, // 5 minutes
gcTime: 1000 * 60 * 15, // 15 minutes
+ onError: (error: AxiosError) => { | frontend/src/hooks/query/use-git-user.ts | 25 | TypeScript | 1 | suggestion | 737 | 46 | 48 | false | Fix: Logout on 401 error in useGitUser; downgrade provider error to warning | 12,935 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | tofarr |
def get_service(self, provider: ProviderType) -> GitService:
"""Helper method to instantiate a service for a given provider"""
token = self.provider_tokens[provider]
service_class = self.service_class_map[provider]
return service_class(
user_id=token.user_id,
... | 🟡 Suggestion: Inconsistent indentation - these lines use 2 spaces instead of 4. Should align with the rest of the file using 4-space indentation. | def get_service(self, provider: ProviderType) -> GitService:
"""Helper method to instantiate a service for a given provider"""
token = self.provider_tokens[provider]
service_class = self.service_class_map[provider]
return service_class(
user_id=token.user_id,
... | @@ -172,9 +172,9 @@ async def get_user(self) -> User:
exceptions.append((provider, e))
continue
for provider, exc in exceptions:
- logger.error(
- f'Failed to get user from provider {provider}: {exc}',
- exc_info=(type(exc), exc, exc.__... | openhands/integrations/provider.py | 26 | Python | 0.429 | suggestion | 145 | 51 | 51 | false | Fix: Logout on 401 error in useGitUser; downgrade provider error to warning | 12,935 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | tofarr |
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to check BYOR export permission',
)
@api_router.post('', response_model=ApiKeyCreateResponse)
async def create_api_key(
key_data: ApiKeyCreate, user_id: str = Depends(get_user_id)
) -> Ap... | 🟠 Important: This function does not handle the case where the newly created key is not found in the list. If the for loop completes without finding a matching key, the function will return `None`, causing FastAPI to raise an unclear validation error.
While this should never happen in normal operation, it could occur ... | 'Error checking BYOR export permission', extra={'error': str(e)}
)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail='Failed to check BYOR export permission',
)
@api_router.post('', tags=['Keys'])
async def create_api_key(
ke... | @@ -178,20 +196,15 @@ async def create_api_key(key_data: ApiKeyCreate, user_id: str = Depends(get_user
# Get the created key details
keys = await api_key_store.list_api_keys(user_id)
for key in keys:
- if key['name'] == key_data.name:
- return {
- ... | enterprise/server/routes/api_keys.py | 26 | Python | 1 | bug | 1,029 | 51 | 51 | false | Add type hints and use model objects in api_keys.py endpoints | 12,939 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | tofarr |
}
};
const availableRolesToChangeTo = getAvailableRolesAUserCanAssign(
rolePermissions[currentUserRole],
);
const canAssignUserRole = (member: OrganizationMember) =>
user != null &&
user?.user_id !== member.user_id &&
user?.role !== member.role &&
hasPermission(`change_user_role:${memb... | 🔴 **Critical**: Hardcoded hex colors (`#737373`, `#171717`, `#262626`, `#525252`) scattered throughout. This violates the design system approach.
**Problem**: When the design system changes (and it will), you have magic strings to hunt down instead of semantic tokens.
**Fix**: Define these as CSS variables or Tailwi... | { onSettled: () => setMemberToRemove(null) },
);
}
};
const availableRolesToChangeTo = getAvailableRolesAUserCanAssign(
rolePermissions[currentUserRole],
);
const canAssignUserRole = (member: OrganizationMember) =>
user != null &&
user?.user_id !== member.user_id &&
user?.rol... | @@ -92,19 +93,22 @@ function ManageOrganizationMembers() {
return (
<div
data-testid="manage-organization-members-settings"
- className="flex flex-col gap-2"
+ className="flex flex-col gap-2 h-full"
>
- {hasPermissionToInvite && (
- <BrandButton
- type="button"
- ... | frontend/src/routes/manage-organization-members.tsx | 26 | TypeScript | 1 | suggestion | 637 | 51 | 51 | false | refactor(frontend): enhance the organization members page user interface | 12,957 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
if (
!user ||
!rolePermissions[role].includes(requiredPermission) ||
isPersonalOrg
) {
return redirect("/settings");
}
}
return null;
};
function SettingsScreen() {
const { t } = useTranslation();
const location = useLocation();
const navItems = useSettingsNavItems();
/... | 🔴 **Critical**: Path string comparison is fragile and violates separation of concerns.
**Problem**:
1. Routes change → breaks silently
2. Settings layout now knows about specific child route implementation
3. Next developer adds another route that needs this → copy-pastes this pattern
**Better approach**: Let the c... | if (
!user ||
!rolePermissions[role].includes(requiredPermission) ||
isPersonalOrg
) {
return redirect("/settings");
}
}
return null;
};
function SettingsScreen() {
const { t } = useTranslation();
const location = useLocation();
const matches = useMatches();
const navIt... | @@ -105,11 +105,16 @@ function SettingsScreen() {
: (navItems[0]?.text ?? "SETTINGS$TITLE");
}, [navItems, location.pathname]);
+ const isManageOrganizationMembers = | frontend/src/routes/settings.tsx | 26 | TypeScript | 1 | nitpick | 744 | 46 | 49 | false | refactor(frontend): enhance the organization members page user interface | 12,957 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
};
return (
<div className="flex items-center justify-between py-4">
<div className="flex items-center gap-2">
<span
className={cn(
"text-sm font-semibold leading-6",
status === "invited" && "text-gray-400",
)}
>
{email}
</span... | 🟠 **Important**: Another hardcoded color (`#A3A3A3`) mixed with Tailwind utilities.
Either commit to Tailwind (`text-neutral-400`) or define semantic tokens. Mixing both creates inconsistency - half your grays are in the theme, half are magic strings. | };
return (
<div className="flex items-center justify-between py-4">
<div className="flex items-center gap-2">
<span
className={cn(
"text-sm font-semibold leading-6",
status === "invited" && "text-gray-400",
)}
>
{email}
</span... | @@ -63,7 +63,7 @@ export function OrganizationMemberListItem({
<span
onClick={handleRoleClick}
className={cn(
- "text-xs text-gray-400 flex items-center gap-1 capitalize",
+ "text-xs font-normal leading-4 text-[#A3A3A3] flex items-center gap-1 capitalize", | frontend/src/components/features/org/organization-member-list-item.tsx | 26 | TypeScript | 0.571 | style | 252 | 46 | 46 | false | refactor(frontend): enhance the organization members page user interface | 12,957 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
const canAssignUserRole = (member: OrganizationMember) =>
user != null &&
user?.user_id !== member.user_id &&
user?.role !== member.role &&
hasPermission(`change_user_role:${member.role}`);
return (
<div
data-testid="manage-organization-members-settings"
className="flex flex-col ga... | 🟠 **Important**: You're applying extensive inline styles to a `BrandButton` component, including `border-none` to override its default border.
**Smell**: If BrandButton needs this many overrides, it's the wrong abstraction.
**Options**:
1. Add a proper `variant` prop to BrandButton for this style
2. Create a separat... | rolePermissions[currentUserRole],
);
const canAssignUserRole = (member: OrganizationMember) =>
user != null &&
user?.user_id !== member.user_id &&
user?.role !== member.role &&
hasPermission(`change_user_role:${member.role}`);
return (
<div
data-testid="manage-organization-members-... | @@ -92,19 +93,22 @@ function ManageOrganizationMembers() {
return (
<div
data-testid="manage-organization-members-settings"
- className="flex flex-col gap-2"
+ className="flex flex-col gap-2 h-full"
>
- {hasPermissionToInvite && (
- <BrandButton
- type="button"
- ... | frontend/src/routes/manage-organization-members.tsx | 26 | TypeScript | 0.643 | bug | 474 | 51 | 51 | false | refactor(frontend): enhance the organization members page user interface | 12,957 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
// Seed organizations into the module-level queryClient used by clientLoader
mockQueryClient.setQueryData(["organizations"], {
items: [MOCK_TEAM_ORG_ACME],
currentOrgId: MOCK_TEAM_ORG_ACME.id,
});
const getConfigSpy = vi.spyOn(OptionService, "getConfig");
// @ts-expect-error - partial m... | 🟡 **Suggestion**: Good fix for the race condition, but add a comment explaining WHY.
```suggestion
// Pre-seed organizations to avoid race condition where the component
// tries to render before the API call completes, causing test flakiness
queryClient.setQueryData(["organizations"], {
```
Future you (o... | });
// Seed organizations into the module-level queryClient used by clientLoader
mockQueryClient.setQueryData(["organizations"], {
items: [MOCK_TEAM_ORG_ACME],
currentOrgId: MOCK_TEAM_ORG_ACME.id,
});
const getConfigSpy = vi.spyOn(OptionService, "getConfig");
// @ts-expect-error - p... | @@ -111,6 +112,12 @@ describe("Manage Organization Members Route", () => {
queryClient = new QueryClient();
+ // Pre-seed organizations so org selector renders immediately (avoids flaky race with API fetch)
+ queryClient.setQueryData(["organizations"], {
+ items: INITIAL_MOCK_ORGS,
+ currentOrg... | frontend/__tests__/routes/manage-organization-members.test.tsx | 26 | TypeScript | 1 | bug | 414 | 51 | 51 | false | refactor(frontend): enhance the organization members page user interface | 12,957 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
className="flex flex-col gap-2 h-full"
>
<div className="flex items-center justify-between pb-6">
<Typography.H2>{t(I18nKey.ORG$ORGANIZATION_MEMBERS)}</Typography.H2>
{hasPermissionToInvite && (
<BrandButton
type="button"
variant="secondary"
... | 🟢 **Nit**: `table-box-shadow` is a reasonable abstraction for this complex shadow, unlike the hardcoded colors. | <div
data-testid="manage-organization-members-settings"
className="flex flex-col gap-2 h-full"
>
<div className="flex items-center justify-between pb-6">
<Typography.H2>{t(I18nKey.ORG$ORGANIZATION_MEMBERS)}</Typography.H2>
{hasPermissionToInvite && (
<BrandButton
... | @@ -114,27 +118,34 @@ function ManageOrganizationMembers() {
document.getElementById("portal-root") || document.body,
)}
- {organizationMembers && (
- <ul>
- {organizationMembers.map((member) => (
- <li
- key={member.user_id}
- data-testid=... | frontend/src/routes/manage-organization-members.tsx | 26 | TypeScript | 0.5 | refactor | 111 | 51 | 51 | false | refactor(frontend): enhance the organization members page user interface | 12,957 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | hieptl |
"""
Database connection module for enterprise storage.
This is for backwards compatibility with V0.
This module provides database engines and session makers by delegating to the
centralized DbSessionInjector from app_server/config.py. This ensures a single
source of truth for database connection configuration.
"""
i... | 🔴 **Critical**: This fixed a production bug (Slack login TypeError), but where are the tests? There should be a regression test that calls `session_maker(expire_on_commit=False)` to prove this works.
The bug affected real code at `enterprise/server/routes/integration/slack.py:242`. Add a test like:
```python
def tes... | """
Database connection module for enterprise storage.
This is for backwards compatibility with V0.
This module provides database engines and session makers by delegating to the
centralized DbSessionInjector from app_server/config.py. This ensures a single
source of truth for database connection configuration.
"""
i... | @@ -18,10 +18,10 @@ def _get_db_session_injector():
return _config.db_session
-def session_maker():
+def session_maker(**kwargs):
db_session_injector = _get_db_session_injector()
session_maker = db_session_injector.get_session_maker()
- return session_maker()
+ return session_maker(**kwargs) | enterprise/storage/database.py | 24 | Python | 1 | bug | 665 | 39 | 39 | false | Fix session_maker to accept kwargs for backward compatibility | 12,960 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | tofarr |
"""
Database connection module for enterprise storage.
This is for backwards compatibility with V0.
This module provides database engines and session makers by delegating to the
centralized DbSessionInjector from app_server/config.py. This ensures a single
source of truth for database connection configuration.
"""
i... | 🟡 **Suggestion**: Variable `session_maker` shadows the function name. While it works, it violates good taste and makes the code harder to reason about.
```suggestion
factory = db_session_injector.get_session_maker()
```
Then update line 24 to `return factory(**kwargs)`. Same issue exists in `a_session_maker()` b... | """
Database connection module for enterprise storage.
This is for backwards compatibility with V0.
This module provides database engines and session makers by delegating to the
centralized DbSessionInjector from app_server/config.py. This ensures a single
source of truth for database connection configuration.
"""
i... | @@ -18,10 +18,10 @@ def _get_db_session_injector():
return _config.db_session
-def session_maker():
+def session_maker(**kwargs):
db_session_injector = _get_db_session_injector()
session_maker = db_session_injector.get_session_maker() | enterprise/storage/database.py | 23 | Python | 0.929 | suggestion | 335 | 39 | 39 | false | Fix session_maker to accept kwargs for backward compatibility | 12,960 | All-Hands-AI/OpenHands | 55,974 | Python | all-hands-bot | tofarr |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.