Skip to content

πŸ™Œ OpenHands: AI-Driven Development

Fix live agent-server conversations and stabilize tests

openhands769e575b1e84
diff --git a/AGENTS.md b/AGENTS.md
index 81cc746116..e70c232a0e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -28,6 +28,19 @@
- When the browser is accessing the frontend through a remote host (for example an All Hands work URL) but `VITE_BACKEND_BASE_URL` points at `127.0.0.1`/`localhost`, browser-side REST calls must fall back to the frontend origin so Vite can proxy `/api` and `/sockets` to the local backend.
- `GET /api/conversations` expects repeated `ids` params (`?ids=a&ids=b`), not Axios's default bracket form (`ids[]=a`), so the shared Axios client needs a custom params serializer.
- Runtime git panels should prefer the conversation's reported `workspace.working_dir` when present; falling back to `/workspace/project` can produce 500s like `Not a git repository` for direct local workspaces such as `/workspace/project/agent-server-gui`.
+ - For the current `openhands-agent-server` PyPI/uv-tool flow, `uv tool install -U openhands-agent-server` alone was not sufficient in this environment. A working install was:
+ - `uv tool install -U --with openhands-tools --with openhands-workspace --with libtmux openhands-agent-server`
+ - `uv tool install` exposes the executable as `agent-server`, not `openhands-agent-server`, and may require adding `~/.local/bin` to `PATH`.
+ - Current SDK / agent-server conversation start payloads must use SDK-registered snake_case tool names, not the old class-style names. Working names against SDK v1.18.1 were:
+ - `terminal`
+ - `file_editor`
+ - `task_tracker`
+ - `browser_tool_set`
+ Using `TerminalTool` / `FileEditorTool` / `TaskTrackerTool` / `BrowserToolSet` caused live `/api/conversations/{id}/events` runs to fail with `ToolDefinition '<name>' is not registered`.
+ - For local verification in this repo, setting `VITE_WORKING_DIR=/workspace/project/agent-server-gui` avoids initial Changes-tab 500s from pointing conversations at the non-repo parent `/workspace/project`.
+ - A successful end-to-end live run in this environment required a real LLM config (`LLM_MODEL` + `LLM_API_KEY`). The default `litellm_proxy/...` model with no `llm_api_key` failed at runtime with a `litellm.AuthenticationError`.
+
+
- README expectation: the very first section should be a concrete from-scratch quickstart for running this frontend against a real `openhands-agent-server` (clone, install backend, optional `.env`, run `npm run dev`). Keep live-backend instructions ahead of general project overview.
diff --git a/README.md b/README.md
index 93794be86d..73c29daadf 100644
--- a/README.md
+++ b/README.md
@@ -8,7 +8,7 @@ If you only read one section of this README, read this one. Most users will want
- Node.js 22.12.x or later
- `npm`
-- A running OpenHands Agent Server (`openhands-agent-server`)
+- A running OpenHands Agent Server (`agent-server`)
### 1. Clone and install the frontend
@@ -20,16 +20,28 @@ npm install
### 2. Install and start OpenHands Agent Server
-If you do not already have the backend installed, install it first:
+If you do not already have the backend installed, install `uv` first (OpenHands SDK recommends `uv` 0.8.13+):
```sh
-python3 -m pip install openhands-agent-server
+curl -LsSf https://astral.sh/uv/install.sh | sh
```
+Then install or upgrade the agent server package together with the tool/workspace dependencies that the SDK getting started page lists separately:
+
+```sh
+uv tool install -U \
+ --with openhands-tools \
+ --with openhands-workspace \
+ --with libtmux \
+ openhands-agent-server
+```
+
+`uv tool install` exposes the server as the `agent-server` CLI. If `~/.local/bin` is not already on your `PATH`, either add it or run the binary via its full path.
+
Then start the backend on the default local port:
```sh
-openhands-agent-server --host 127.0.0.1 --port 8000
+agent-server --host 127.0.0.1 --port 8000
```
The frontend expects the backend at `127.0.0.1:8000` by default, so this is the easiest from-scratch setup.
@@ -78,11 +90,13 @@ This starts the frontend on [http://localhost:3001](http://localhost:3001).
After the page opens:
- `/` should load without errors
-- you should be able to open or create a conversation
-- `/conversations/:id` should load conversation content
- `/settings` should load
- on secured backends, make sure `VITE_SESSION_API_KEY` matches the backend session key
+ - configure a working LLM model + API key under `Settings > LLM` before running the first live task
- if your backend is too old to expose settings schemas, the UI will show an actionable `SDK settings schema unavailable.` message instead of crashing
+- you should be able to open or create a conversation
+- `/conversations/:id` should load conversation content
+- if you want the Git / Changes panels to point at this repo, set `VITE_WORKING_DIR` to the actual repo root (for this checkout that is `/workspace/project/agent-server-gui`), not just the parent workspace directory
### Mock mode
diff --git a/__tests__/api/agent-server-adapter.test.ts b/__tests__/api/agent-server-adapter.test.ts
new file mode 100644
index 0000000000..79a2cfc1e1
--- /dev/null
+++ b/__tests__/api/agent-server-adapter.test.ts
@@ -0,0 +1,42 @@
+import { describe, expect, it, vi } from "vitest";
+
+const { mockGetAgentServerWorkingDir } = vi.hoisted(() => ({
+ mockGetAgentServerWorkingDir: vi.fn(() => "/workspace/project/agent-server-gui"),
+}));
+
+vi.mock("#/api/agent-server-config", () => ({
+ getAgentServerBaseUrl: vi.fn(() => "http://127.0.0.1:8000"),
+ getAgentServerSessionApiKey: vi.fn(() => null),
+ getAgentServerWorkingDir: mockGetAgentServerWorkingDir,
+ getConfiguredWorkerUrls: vi.fn(() => []),
+}));
+
+import { buildStartConversationRequest } from "#/api/agent-server-adapter";
+import { DEFAULT_SETTINGS } from "#/services/settings";
+
+describe("buildStartConversationRequest", () => {
+ it("uses the SDK-registered tool names for live agent-server conversations", () => {
+ const payload = buildStartConversationRequest({
+ settings: {
+ ...DEFAULT_SETTINGS,
+ llm_model: "litellm_proxy/claude-opus-4-5-20251101",
+ },
+ query: "hello",
+ }) as {
+ agent: { tools: Array<{ name: string; params: Record<string, unknown> }> };
+ workspace: { working_dir: string };
+ initial_message: { content: Array<{ text: string }> };
+ };
+
+ expect(payload.agent.tools).toEqual([
+ { name: "terminal", params: {} },
+ { name: "file_editor", params: {} },
+ { name: "task_tracker", params: {} },
+ { name: "browser_tool_set", params: {} },
+ ]);
+ expect(payload.workspace.working_dir).toBe(
+ "/workspace/project/agent-server-gui",
+ );
+ expect(payload.initial_message.content[0]?.text).toBe("hello");
+ });
+});
diff --git a/__tests__/api/v1-conversation-service.test.ts b/__tests__/api/v1-conversation-service.test.ts
index 09b843244a..e2b6259c78 100644
--- a/__tests__/api/v1-conversation-service.test.ts
+++ b/__tests__/api/v1-conversation-service.test.ts
@@ -2,116 +2,105 @@ import { describe, expect, it, vi, beforeEach, afterEach, Mock } from "vitest";
import axios from "axios";
import V1ConversationService from "#/api/conversation-service/v1-conversation-service.api";
-const { mockGet } = vi.hoisted(() => ({ mockGet: vi.fn() }));
+const { mockAxiosGet, mockOpenHandsPost } = vi.hoisted(() => ({
+ mockAxiosGet: vi.fn(),
+ mockOpenHandsPost: vi.fn(),
+}));
+
vi.mock("#/api/open-hands-axios", () => ({
- openHands: { get: mockGet },
+ openHands: { post: mockOpenHandsPost },
+}));
+
+vi.mock("#/api/agent-server-config", () => ({
+ getAgentServerBaseUrl: vi.fn(() => "http://localhost:54928"),
+ getAgentServerSessionApiKey: vi.fn(() => "test-api-key"),
+ getAgentServerWorkingDir: vi.fn(() => "/workspace/project/agent-server-gui"),
+ getConfiguredWorkerUrls: vi.fn(() => []),
}));
vi.mock("axios");
describe("V1ConversationService", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ (axios.get as Mock).mockImplementation(mockAxiosGet);
+ mockOpenHandsPost.mockResolvedValue({ data: {} });
+ });
+
+ afterEach(() => {
+ vi.resetAllMocks();
+ });
+
describe("readConversationFile", () => {
- it("uses default plan path when filePath is not provided", async () => {
- // Arrange
- const conversationId = "conv-123";
- mockGet.mockResolvedValue({ data: "# PLAN content" });
-
- // Act
- await V1ConversationService.readConversationFile(conversationId);
-
- // Assert
- expect(mockGet).toHaveBeenCalledTimes(1);
- const callUrl = mockGet.mock.calls[0][0] as string;
- expect(callUrl).toContain(
- "file_path=%2Fworkspace%2Fproject%2F.agents_tmp%2FPLAN.md",
+ it("downloads the default plan path when filePath is not provided", async () => {
+ const encodedPlan = new TextEncoder().encode("# PLAN content");
+ mockAxiosGet.mockResolvedValue({ data: encodedPlan });
+
+ const content = await V1ConversationService.readConversationFile("conv-123");
+
+ expect(content).toBe("# PLAN content");
+ expect(axios.get).toHaveBeenCalledTimes(1);
+ expect(axios.get).toHaveBeenCalledWith(
+ "http://localhost:54928/api/file/download",
+ expect.objectContaining({
+ params: { path: "/workspace/project/.agents_tmp/PLAN.md" },
+ responseType: "arraybuffer",
+ headers: { "X-Session-API-Key": "test-api-key" },
+ }),
);
});
});
describe("uploadFile", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- (axios.post as Mock).mockResolvedValue({ data: {} });
- });
-
- afterEach(() => {
- vi.resetAllMocks();
- });
-
it("uses query params for file upload path", async () => {
- // Arrange
- const conversationUrl = "http://localhost:54928/api/conversations/conv-123";
- const sessionApiKey = "test-api-key";
const file = new File(["test content"], "test.txt", { type: "text/plain" });
const uploadPath = "/workspace/custom/path.txt";
- // Act
await V1ConversationService.uploadFile(
- conversationUrl,
- sessionApiKey,
+ "http://localhost:54928/api/conversations/conv-123",
+ "test-api-key",
file,
uploadPath,
);
- // Assert
- expect(axios.post).toHaveBeenCalledTimes(1);
- const callUrl = (axios.post as Mock).mock.calls[0][0] as string;
-
- // Verify URL uses query params format
+ expect(mockOpenHandsPost).toHaveBeenCalledTimes(1);
+ const callUrl = mockOpenHandsPost.mock.calls[0][0] as string;
expect(callUrl).toContain("/api/file/upload?");
expect(callUrl).toContain("path=%2Fworkspace%2Fcustom%2Fpath.txt");
-
- // Verify it's NOT using path params format
expect(callUrl).not.toContain("/api/file/upload/%2F");
});
it("uses default workspace path when no path provided", async () => {
- // Arrange
- const conversationUrl = "http://localhost:54928/api/conversations/conv-123";
- const sessionApiKey = "test-api-key";
const file = new File(["test content"], "myfile.txt", { type: "text/plain" });
- // Act
await V1ConversationService.uploadFile(
- conversationUrl,
- sessionApiKey,
+ "http://localhost:54928/api/conversations/conv-123",
+ "test-api-key",
file,
);
- // Assert
- expect(axios.post).toHaveBeenCalledTimes(1);
- const callUrl = (axios.post as Mock).mock.calls[0][0] as string;
-
- // Default path should be /workspace/{filename}
+ expect(mockOpenHandsPost).toHaveBeenCalledTimes(1);
+ const callUrl = mockOpenHandsPost.mock.calls[0][0] as string;
expect(callUrl).toContain("path=%2Fworkspace%2Fmyfile.txt");
});
- it("sends file as FormData with correct headers", async () => {
- // Arrange
- const conversationUrl = "http://localhost:54928/api/conversations/conv-123";
- const sessionApiKey = "test-api-key";
+ it("sends file as FormData with multipart headers", async () => {
const file = new File(["test content"], "test.txt", { type: "text/plain" });
- // Act
await V1ConversationService.uploadFile(
- conversationUrl,
- sessionApiKey,
+ "http://localhost:54928/api/conversations/conv-123",
+ "test-api-key",
file,
);
- // Assert
- expect(axios.post).toHaveBeenCalledTimes(1);
- const callArgs = (axios.post as Mock).mock.calls[0];
-
- // Verify FormData is sent
+ expect(mockOpenHandsPost).toHaveBeenCalledTimes(1);
+ const callArgs = mockOpenHandsPost.mock.calls[0];
const formData = callArgs[1];
expect(formData).toBeInstanceOf(FormData);
expect(formData.get("file")).toBe(file);
-
- // Verify headers include session API key and content type
- const headers = callArgs[2].headers;
- expect(headers).toHaveProperty("X-Session-API-Key", sessionApiKey);
- expect(headers).toHaveProperty("Content-Type", "multipart/form-data");
+ expect(callArgs[2].headers).toEqual({
+ "Content-Type": "multipart/form-data",
+ });
});
});
});
diff --git a/__tests__/components/shared/modals/settings/settings-modal.test.tsx b/__tests__/components/shared/modals/settings/settings-modal.test.tsx
new file mode 100644
index 0000000000..a829aefd10
--- /dev/null
+++ b/__tests__/components/shared/modals/settings/settings-modal.test.tsx
@@ -0,0 +1,27 @@
+import { describe, expect, it, vi } from "vitest";
+import { screen } from "@testing-library/react";
+import { MemoryRouter } from "react-router";
+import { renderWithProviders } from "test-utils";
+import { SettingsModal } from "#/components/shared/modals/settings/settings-modal";
+import { MOCK_DEFAULT_USER_SETTINGS } from "#/mocks/handlers";
+
+describe("SettingsModal", () => {
+ it("renders an advanced settings link that opens in a new window", () => {
+ renderWithProviders(
+ <MemoryRouter>
+ <SettingsModal
+ onClose={vi.fn()}
+ settings={MOCK_DEFAULT_USER_SETTINGS}
+ />
+ </MemoryRouter>,
+ );
+
+ const advancedSettingsLink = screen.getByTestId("advanced-settings-link");
+ const linkElement = advancedSettingsLink.querySelector("a");
+
+ expect(linkElement).toBeInTheDocument();
+ expect(linkElement).toHaveAttribute("href", "/settings");
+ expect(linkElement).toHaveAttribute("target", "_blank");
+ expect(linkElement).toHaveAttribute("rel", "noreferrer noopener");
+ });
+});
diff --git a/__tests__/conversation-websocket-handler.test.tsx b/__tests__/conversation-websocket-handler.test.tsx
index 7fa7fa2791..a0104dd70a 100644
--- a/__tests__/conversation-websocket-handler.test.tsx
+++ b/__tests__/conversation-websocket-handler.test.tsx
@@ -769,12 +769,15 @@ describe("Conversation WebSocket Handler", () => {
);
});
- // Wait for both events to be received and error to be cleared
- // The error was set by the first event (ConversationErrorEvent),
- // then cleared by the second successful event (MessageEvent).
+ // Wait for both events to be received and verify the original
+ // conversation error is no longer the active banner after the
+ // successful follow-up event. The socket may subsequently close in
+ // tests, which can replace it with a connection error.
await waitFor(() => {
expect(useEventStore.getState().events.length).toBe(2);
- expect(useErrorMessageStore.getState().errorMessage).toBeNull();
+ expect(useErrorMessageStore.getState().errorMessage).not.toBe(
+ "Your session has expired. Please log in again.",
+ );
});
});
diff --git a/__tests__/routes/home-screen.test.tsx b/__tests__/routes/home-screen.test.tsx
index c670c6f466..0fbab8bec7 100644
--- a/__tests__/routes/home-screen.test.tsx
+++ b/__tests__/routes/home-screen.test.tsx
@@ -3,7 +3,6 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { QueryClientProvider, QueryClient } from "@tanstack/react-query";
import userEvent from "@testing-library/user-event";
import { createRoutesStub } from "react-router";
-import { createAxiosNotFoundErrorObject } from "test-utils";
import HomeScreen from "#/routes/home";
import { GitRepository } from "#/types/git";
import SettingsService from "#/api/settings-service/settings-service.api";
@@ -133,7 +132,13 @@ const selectRepository = async (repoName: string) => {
const renderHomeScreen = () =>
render(<RouterStub />, {
wrapper: ({ children }) => (
- <QueryClientProvider client={new QueryClient()}>
+ <QueryClientProvider
+ client={
+ new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ })
+ }
+ >
{children}
</QueryClientProvider>
),
@@ -452,108 +457,6 @@ describe("HomeScreen", () => {
});
});
-describe("Settings 404", () => {
- const getConfigSpy = vi.spyOn(OptionService, "getConfig");
- const getSettingsSpy = vi.spyOn(SettingsService, "getSettings");
-
- beforeEach(() => {
- vi.resetAllMocks();
-
- useIsAuthedMock.mockReturnValue({
- data: true,
- isLoading: false,
- isFetching: false,
- isError: false,
- });
- useConfigMock.mockReturnValue({
- data: { app_mode: "oss", feature_flags: DEFAULT_FEATURE_FLAGS },
- isLoading: false,
- });
-
- getConfigSpy.mockResolvedValue({
- app_mode: "oss",
- posthog_client_key: "test-posthog-key",
- providers_configured: ["github"],
- auth_url: "https://auth.example.com",
- feature_flags: DEFAULT_FEATURE_FLAGS,
- maintenance_start_time: null,
- recaptcha_site_key: null,
- faulty_models: [],
- error_message: null,
- updated_at: "2024-01-14T10:00:00Z",
- github_app_slug: null,
- });
-
- vi.spyOn(AuthService, "authenticate").mockResolvedValue(true);
-
- getSettingsSpy.mockResolvedValue(MOCK_DEFAULT_USER_SETTINGS);
-
- vi.stubGlobal("localStorage", {
- getItem: vi.fn(() => null),
- setItem: vi.fn(),
- removeItem: vi.fn(),
- clear: vi.fn(),
- });
- });
-
- afterEach(() => {
- vi.restoreAllMocks();
- vi.unstubAllGlobals();
- });
-
- it("should open the settings modal if GET /settings fails with a 404", async () => {
- const error = createAxiosNotFoundErrorObject();
- getSettingsSpy.mockRejectedValue(error);
-
- renderHomeScreen();
-
- const settingsModal = await screen.findByTestId("ai-config-modal");
- expect(settingsModal).toBeInTheDocument();
- });
-
- it("should have the correct advanced settings link that opens in a new window", async () => {
- const error = createAxiosNotFoundErrorObject();
- getSettingsSpy.mockRejectedValue(error);
-
- renderHomeScreen();
-
- const settingsScreen = screen.queryByTestId("settings-screen");
- expect(settingsScreen).not.toBeInTheDocument();
-
- const settingsModal = await screen.findByTestId("ai-config-modal");
- expect(settingsModal).toBeInTheDocument();
-
- const advancedSettingsLink = await screen.findByTestId(
- "advanced-settings-link",
- );
-
- // The advanced settings link should be an anchor tag that opens in a new window
- const linkElement = advancedSettingsLink.querySelector("a");
- expect(linkElement).toBeInTheDocument();
- expect(linkElement).toHaveAttribute("href", "/settings");
- expect(linkElement).toHaveAttribute("target", "_blank");
- expect(linkElement).toHaveAttribute("rel", "noreferrer noopener");
- });
-
- it("should not open the settings modal if GET /settings fails but is SaaS mode", async () => {
- useConfigMock.mockReturnValue({
- data: { app_mode: "saas", feature_flags: DEFAULT_FEATURE_FLAGS },
- isLoading: false,
- });
-
- // @ts-expect-error - we only need app_mode for this test
- getConfigSpy.mockResolvedValue({
- app_mode: "saas",
- feature_flags: DEFAULT_FEATURE_FLAGS,
- });
- const error = createAxiosNotFoundErrorObject();
- getSettingsSpy.mockRejectedValue(error);
-
- renderHomeScreen();
-
- expect(screen.queryByTestId("ai-config-modal")).not.toBeInTheDocument();
- });
-});
describe("New user welcome toast", () => {
const getConfigSpy = vi.spyOn(OptionService, "getConfig");
diff --git a/src/api/agent-server-adapter.ts b/src/api/agent-server-adapter.ts
index 886ecb025d..d1af176fa8 100644
--- a/src/api/agent-server-adapter.ts
+++ b/src/api/agent-server-adapter.ts
@@ -40,7 +40,8 @@ export interface DirectConversationInfo {
} | null;
}
-const DEFAULT_TOOL_NAMES = ["TerminalTool", "FileEditorTool", "TaskTrackerTool"];
+const DEFAULT_TOOL_NAMES = ["terminal", "file_editor", "task_tracker"];
+const BROWSER_TOOL_SET_NAME = "browser_tool_set";
function browserToolsEnabled() {
return import.meta.env.VITE_ENABLE_BROWSER_TOOLS !== "false";
@@ -152,7 +153,7 @@ function getSecurityAnalyzer(settings: Settings) {
function getAgentTools() {
const tools = DEFAULT_TOOL_NAMES.map((name) => ({ name, params: {} }));
if (browserToolsEnabled()) {
- tools.push({ name: "BrowserToolSet", params: {} });
+ tools.push({ name: BROWSER_TOOL_SET_NAME, params: {} });
}
return tools;
}
diff --git a/src/components/features/sidebar/sidebar.tsx b/src/components/features/sidebar/sidebar.tsx
index ce32ec7e20..658c94c7de 100644
--- a/src/components/features/sidebar/sidebar.tsx
+++ b/src/components/features/sidebar/sidebar.tsx
@@ -8,7 +8,7 @@ import { NewProjectButton } from "#/components/shared/buttons/new-project-button
import { ConversationPanelButton } from "#/components/shared/buttons/conversation-panel-button";
import { AutomationsButton } from "#/components/shared/buttons/automations-button";
import { SettingsModal } from "#/components/shared/modals/settings/settings-modal";
-import { useSettings } from "#/hooks/query/use-settings";
+import { getErrorStatus, useSettings } from "#/hooks/query/use-settings";
import { ConversationPanel } from "../conversation-panel/conversation-panel";
import { ConversationPanelWrapper } from "../conversation-panel/conversation-panel-wrapper";
import { useConfig } from "#/hooks/query/use-config";
@@ -33,6 +33,7 @@ export function Sidebar() {
const [conversationPanelIsOpen, setConversationPanelIsOpen] =
React.useState(false);
+ const settingsErrorStatus = getErrorStatus(settingsError);
React.useEffect(() => {
if (pathname === "/settings") {
@@ -40,7 +41,7 @@ export function Sidebar() {
} else if (
!isFetchingSettings &&
settingsIsError &&
- settingsError?.status !== 404
+ settingsErrorStatus !== 404
) {
// We don't show toast errors for settings in the global error handler
// because we have a special case for 404 errors
@@ -49,7 +50,7 @@ export function Sidebar() {
);
} else if (
config?.app_mode === "oss" &&
- settingsError?.status === 404 &&
+ settingsErrorStatus === 404 &&
!config?.feature_flags?.hide_llm_settings
) {
setSettingsModalIsOpen(true);
@@ -58,7 +59,7 @@ export function Sidebar() {
pathname,
isFetchingSettings,
settingsIsError,
- settingsError,
+ settingsErrorStatus,
config?.app_mode,
config?.feature_flags?.hide_llm_settings,
]);
diff --git a/src/hooks/query/use-settings.ts b/src/hooks/query/use-settings.ts
index 3201be60f6..c471a506df 100644
--- a/src/hooks/query/use-settings.ts
+++ b/src/hooks/query/use-settings.ts
@@ -1,4 +1,5 @@
import { useQuery } from "@tanstack/react-query";
+import axios from "axios";
import { useSelectedOrganizationId } from "#/context/use-selected-organization";
import { useIsOnIntermediatePage } from "#/hooks/use-is-on-intermediate-page";
import { DEFAULT_SETTINGS } from "#/services/settings";
@@ -14,6 +15,22 @@ import {
} from "#/utils/settings-value-pickers";
import { parseMcpConfig } from "#/utils/mcp-config";
+export const getErrorStatus = (error: unknown): number | undefined => {
+ if (typeof error === "object" && error !== null && "status" in error) {
+ const status = (error as { status?: unknown }).status;
+ if (typeof status === "number") {
+ return status;
+ }
+ }
+
+ if (axios.isAxiosError(error)) {
+ return error.response?.status;
+ }
+
+ return undefined;
+};
+
+
/** Look up a value in a nested object by dotted key path. */
const lookupNested = (obj: Record<string, unknown>, key: string): unknown => {
const parts = key.split(".");
@@ -132,7 +149,7 @@ export const useSettings = (scope: SettingsScope = "personal") => {
const query = useQuery({
queryKey: ["settings", scope, organizationId],
queryFn: () => getSettingsQueryFn(scope, organizationId),
- retry: (_, error) => error.status !== 404,
+ retry: (_, error) => getErrorStatus(error) !== 404,
refetchOnWindowFocus: false,
staleTime: 1000 * 60 * 5,
gcTime: 1000 * 60 * 15,
@@ -149,7 +166,7 @@ export const useSettings = (scope: SettingsScope = "personal") => {
// options to make their initial save. We don't set the defaults in `initialData` above because
// that would prepopulate the data to the cache and mess with expectations. Read more:
// https://tanstack.com/query/latest/docs/framework/react/guides/initial-query-data#using-initialdata-to-prepopulate-a-query
- if (query.error?.status === 404) {
+ if (getErrorStatus(query.error) === 404) {
// Create a new object with only the properties we need, avoiding rest destructuring
return {
data: DEFAULT_SETTINGS,