Skip to content

🙌 OpenHands: AI-Driven Development

chore: remove unused hooks (#555)

Hiep Le1a1d5556b3b8
diff --git a/__tests__/components/chat/chat-interface.test.tsx b/__tests__/components/chat/chat-interface.test.tsx
index 658c34305b..a630ae81bc 100644
--- a/__tests__/components/chat/chat-interface.test.tsx
+++ b/__tests__/components/chat/chat-interface.test.tsx
@@ -26,7 +26,6 @@ import {
import { useErrorMessageStore } from "#/stores/error-message-store";
import { useOptimisticUserMessageStore } from "#/stores/optimistic-user-message-store";
import { useConfig } from "#/hooks/query/use-config";
-import { useGetTrajectory } from "#/hooks/mutation/use-get-trajectory";
import { useUnifiedUploadFiles } from "#/hooks/mutation/use-unified-upload-files";
import type { MessageEvent } from "#/types/agent-server/core";
import { useEventStore } from "#/stores/use-event-store";
@@ -42,7 +41,6 @@ vi.mock("#/hooks/use-send-message", () => ({
}));
vi.mock("#/hooks/query/use-config");
-vi.mock("#/hooks/mutation/use-get-trajectory");
vi.mock("#/hooks/mutation/use-unified-upload-files");
vi.mock("#/hooks/use-conversation-id", () => ({
useConversationId: vi.fn(),
@@ -143,11 +141,6 @@ describe("ChatInterface - Chat Suggestions", () => {
(useConfig as unknown as ReturnType<typeof vi.fn>).mockReturnValue({
data: {},
});
- (useGetTrajectory as unknown as ReturnType<typeof vi.fn>).mockReturnValue({
- mutate: vi.fn(),
- mutateAsync: vi.fn(),
- isLoading: false,
- });
(
useUnifiedUploadFiles as unknown as ReturnType<typeof vi.fn>
).mockReturnValue({
@@ -230,11 +223,6 @@ describe("ChatInterface - Scroll-up loads older events", () => {
(useConfig as unknown as ReturnType<typeof vi.fn>).mockReturnValue({
data: {},
});
- (useGetTrajectory as unknown as ReturnType<typeof vi.fn>).mockReturnValue({
- mutate: vi.fn(),
- mutateAsync: vi.fn(),
- isLoading: false,
- });
(
useUnifiedUploadFiles as unknown as ReturnType<typeof vi.fn>
).mockReturnValue({
@@ -529,11 +517,6 @@ describe("ChatInterface - Pending message queue", () => {
(useConfig as unknown as ReturnType<typeof vi.fn>).mockReturnValue({
data: {},
});
- (useGetTrajectory as unknown as ReturnType<typeof vi.fn>).mockReturnValue({
- mutate: vi.fn(),
- mutateAsync: vi.fn(),
- isLoading: false,
- });
(
useUnifiedUploadFiles as unknown as ReturnType<typeof vi.fn>
).mockReturnValue({
diff --git a/__tests__/components/chat/message-display-continuity.test.tsx b/__tests__/components/chat/message-display-continuity.test.tsx
index 1bea6f6c4e..fbe7475487 100644
--- a/__tests__/components/chat/message-display-continuity.test.tsx
+++ b/__tests__/components/chat/message-display-continuity.test.tsx
@@ -13,7 +13,6 @@ import {
import { useActiveConversation } from "#/hooks/query/use-active-conversation";
import { useConversationWebSocket } from "#/contexts/conversation-websocket-context";
import { useConfig } from "#/hooks/query/use-config";
-import { useGetTrajectory } from "#/hooks/mutation/use-get-trajectory";
import { useUnifiedUploadFiles } from "#/hooks/mutation/use-unified-upload-files";
import { useEventStore } from "#/stores/use-event-store";
import { useAgentState } from "#/hooks/use-agent-state";
@@ -21,7 +20,6 @@ import { AgentState } from "#/types/agent-state";
// Module-level mocks
vi.mock("#/hooks/query/use-config");
-vi.mock("#/hooks/mutation/use-get-trajectory");
vi.mock("#/hooks/mutation/use-unified-upload-files");
vi.mock("#/hooks/use-conversation-id", () => ({
useConversationId: vi.fn(),
@@ -112,11 +110,6 @@ describe("ChatInterface – message display continuity (spec 3.1)", () => {
(useConfig as unknown as ReturnType<typeof vi.fn>).mockReturnValue({
data: { app_mode: "local" },
});
- (useGetTrajectory as unknown as ReturnType<typeof vi.fn>).mockReturnValue({
- mutate: vi.fn(),
- mutateAsync: vi.fn(),
- isLoading: false,
- });
(
useUnifiedUploadFiles as unknown as ReturnType<typeof vi.fn>
).mockReturnValue({
diff --git a/__tests__/hooks/query/use-workspace-session.test.tsx b/__tests__/hooks/query/use-workspace-session.test.tsx
deleted file mode 100644
index 751f193159..0000000000
--- a/__tests__/hooks/query/use-workspace-session.test.tsx
+++ /dev/null
@@ -1,189 +0,0 @@
-import React from "react";
-import { RemoteWorkspace } from "@openhands/typescript-client/workspace/remote-workspace";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { renderHook, waitFor } from "@testing-library/react";
-import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
-
-import {
- joinWorkspaceUrl,
- useWorkspaceSession,
-} from "#/hooks/query/use-workspace-session";
-
-// We mock the SDK workspace rather than the lower-level HttpClient:
-// that's where our wiring contract lives (we hand the typescript-client a
-// conversation id and trust it to do the right POST + return a base URL).
-const startWorkspaceSessionMock = vi.fn();
-
-vi.mock("@openhands/typescript-client/workspace/remote-workspace", () => ({
- RemoteWorkspace: vi.fn(function RemoteWorkspaceMock() {
- return {
- startWorkspaceSession: startWorkspaceSessionMock,
- };
- }),
-}));
-
-const useActiveConversationMock = vi.fn();
-vi.mock("#/hooks/query/use-active-conversation", () => ({
- useActiveConversation: () => useActiveConversationMock(),
-}));
-
-const useRuntimeIsReadyMock = vi.fn();
-vi.mock("#/hooks/use-runtime-is-ready", () => ({
- useRuntimeIsReady: () => useRuntimeIsReadyMock(),
-}));
-
-function makeWrapper() {
- const client = new QueryClient({
- defaultOptions: { queries: { retry: false } },
- });
- const Wrapper = function WorkspaceSessionTestWrapper({
- children,
- }: {
- children: React.ReactNode;
- }) {
- return (
- <QueryClientProvider client={client}>{children}</QueryClientProvider>
- );
- };
- return Wrapper;
-}
-
-// Yields back to the event loop a few microtasks deep so react-query has a
-// chance to schedule (and, in the negative-path tests, to NOT schedule) the
-// query. ESLint forbids returning the timer id from `new Promise(...)`, so
-// we wrap setTimeout in a void callback.
-function flushScheduler(ms = 10): Promise<void> {
- return new Promise((resolve) => {
- setTimeout(resolve, ms);
- });
-}
-
-beforeEach(() => {
- startWorkspaceSessionMock.mockReset();
- vi.mocked(RemoteWorkspace).mockClear();
- useActiveConversationMock.mockReset();
- useRuntimeIsReadyMock.mockReset();
- useRuntimeIsReadyMock.mockReturnValue(true);
-});
-
-afterEach(() => {
- vi.restoreAllMocks();
-});
-
-describe("useWorkspaceSession", () => {
- it("calls startWorkspaceSession and exposes the returned baseUrl", async () => {
- useActiveConversationMock.mockReturnValue({
- data: {
- id: "conv-1",
- conversation_url: "https://agent.example.com/api/conversations/conv-1",
- session_api_key: "key-abc",
- },
- });
- startWorkspaceSessionMock.mockResolvedValue(
- "https://agent.example.com/api/conversations/conv-1/workspace/",
- );
-
- const { result } = renderHook(() => useWorkspaceSession(), {
- wrapper: makeWrapper(),
- });
-
- await waitFor(() => {
- expect(result.current.data?.baseUrl).toBe(
- "https://agent.example.com/api/conversations/conv-1/workspace/",
- );
- });
-
- expect(RemoteWorkspace).toHaveBeenCalledTimes(1);
- expect(RemoteWorkspace).toHaveBeenCalledWith({
- host: "http://agent.example.com",
- apiKey: "key-abc",
- workingDir: "workspace/project",
- });
- expect(startWorkspaceSessionMock).toHaveBeenCalledTimes(1);
- expect(startWorkspaceSessionMock).toHaveBeenCalledWith("conv-1");
- });
-
- it("does not call startWorkspaceSession until the runtime is ready", async () => {
- useActiveConversationMock.mockReturnValue({
- data: {
- id: "conv-1",
- conversation_url: "https://agent.example.com/api/conversations/conv-1",
- session_api_key: "key-abc",
- },
- });
- useRuntimeIsReadyMock.mockReturnValue(false);
-
- const { result } = renderHook(() => useWorkspaceSession(), {
- wrapper: makeWrapper(),
- });
-
- // Give react-query a tick to schedule (it shouldn't).
- await flushScheduler();
- expect(startWorkspaceSessionMock).not.toHaveBeenCalled();
- expect(result.current.data).toBeNull();
- });
-
- it("does not call startWorkspaceSession without a conversation id", async () => {
- useActiveConversationMock.mockReturnValue({ data: undefined });
-
- renderHook(() => useWorkspaceSession(), { wrapper: makeWrapper() });
-
- await flushScheduler();
- expect(startWorkspaceSessionMock).not.toHaveBeenCalled();
- });
-
- it("surfaces the error when the workspace-session POST fails", async () => {
- useActiveConversationMock.mockReturnValue({
- data: {
- id: "conv-1",
- conversation_url: "https://agent.example.com/api/conversations/conv-1",
- session_api_key: "bad-key",
- },
- });
- startWorkspaceSessionMock.mockRejectedValue(new Error("401 Unauthorized"));
-
- const { result } = renderHook(() => useWorkspaceSession(), {
- wrapper: makeWrapper(),
- });
-
- await waitFor(() => expect(result.current.isError).toBe(true));
- expect(result.current.error?.message).toMatch(/401/);
- expect(result.current.data).toBeNull();
- });
-});
-
-describe("joinWorkspaceUrl", () => {
- const base = "https://agent.example.com/api/conversations/c1/workspace/";
-
- it("returns the base URL when no relative path is supplied", () => {
- expect(joinWorkspaceUrl(base)).toBe(base);
- expect(joinWorkspaceUrl(base, "")).toBe(base);
- expect(joinWorkspaceUrl(base, null)).toBe(base);
- });
-
- it("appends a single-segment path", () => {
- expect(joinWorkspaceUrl(base, "index.html")).toBe(`${base}index.html`);
- });
-
- it("appends nested paths preserving separators", () => {
- expect(joinWorkspaceUrl(base, "src/components/App.tsx")).toBe(
- `${base}src/components/App.tsx`,
- );
- });
-
- it("strips leading slashes on the relative path", () => {
- expect(joinWorkspaceUrl(base, "/index.html")).toBe(`${base}index.html`);
- expect(joinWorkspaceUrl(base, "///deep/path.md")).toBe(
- `${base}deep/path.md`,
- );
- });
-
- it("URL-encodes individual segments but not the separators", () => {
- expect(joinWorkspaceUrl(base, "my files/has spaces.txt")).toBe(
- `${base}my%20files/has%20spaces.txt`,
- );
- expect(joinWorkspaceUrl(base, "tëst/résumé.pdf")).toBe(
- `${base}t%C3%ABst/r%C3%A9sum%C3%A9.pdf`,
- );
- });
-});
diff --git a/__tests__/hooks/use-rate.test.ts b/__tests__/hooks/use-rate.test.ts
deleted file mode 100644
index cade3e6554..0000000000
--- a/__tests__/hooks/use-rate.test.ts
+++ /dev/null
@@ -1,93 +0,0 @@
-import { act, renderHook } from "@testing-library/react";
-import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { useRate } from "#/hooks/use-rate";
-
-describe("useRate", () => {
- beforeEach(() => {
- vi.useFakeTimers();
- });
-
- afterEach(() => {
- vi.useRealTimers();
- });
-
- it("should initialize", () => {
- const { result } = renderHook(() => useRate());
-
- expect(result.current.items).toHaveLength(0);
- expect(result.current.rate).toBeNull();
- expect(result.current.lastUpdated).toBeNull();
- expect(result.current.isUnderThreshold).toBe(true);
- });
-
- it("should handle the case of a single element", () => {
- const { result } = renderHook(() => useRate());
-
- act(() => {
- result.current.record(123);
- });
-
- expect(result.current.items).toHaveLength(1);
- expect(result.current.lastUpdated).not.toBeNull();
- });
-
- it("should return the difference between the last two elements", () => {
- const { result } = renderHook(() => useRate());
-
- vi.setSystemTime(500);
- act(() => {
- result.current.record(4);
- });
-
- vi.advanceTimersByTime(500);
- act(() => {
- result.current.record(9);
- });
-
- expect(result.current.items).toHaveLength(2);
- expect(result.current.rate).toBe(5);
- expect(result.current.lastUpdated).toBe(1000);
- });
-
- it("should update isUnderThreshold after [threshold]ms of no activity", () => {
- const { result } = renderHook(() => useRate({ threshold: 500 }));
-
- expect(result.current.isUnderThreshold).toBe(true);
-
- act(() => {
- // not sure if fake timers is buggy with intervals,
- // but I need to call it twice to register
- vi.advanceTimersToNextTimer();
- vi.advanceTimersToNextTimer();
- });
-
- expect(result.current.isUnderThreshold).toBe(false);
- });
-
- it("should return an isUnderThreshold boolean", () => {
- const { result } = renderHook(() => useRate({ threshold: 500 }));
-
- vi.setSystemTime(500);
- act(() => {
- result.current.record(400);
- });
- act(() => {
- result.current.record(1000);
- });
-
- expect(result.current.isUnderThreshold).toBe(false);
-
- act(() => {
- result.current.record(1500);
- });
-
- expect(result.current.isUnderThreshold).toBe(true);
-
- act(() => {
- vi.advanceTimersToNextTimer();
- vi.advanceTimersToNextTimer();
- });
-
- expect(result.current.isUnderThreshold).toBe(false);
- });
-});
diff --git a/__tests__/hooks/use-visibility-recovery.test.ts b/__tests__/hooks/use-visibility-recovery.test.ts
deleted file mode 100644
index 301d910fa2..0000000000
--- a/__tests__/hooks/use-visibility-recovery.test.ts
+++ /dev/null
@@ -1,286 +0,0 @@
-import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
-import { renderHook, act } from "@testing-library/react";
-import { useVisibilityChange } from "#/hooks/use-visibility-change";
-
-describe("useVisibilityChange", () => {
- beforeEach(() => {
- // Reset document.visibilityState to visible
- Object.defineProperty(document, "visibilityState", {
- value: "visible",
- writable: true,
- configurable: true,
- });
- });
-
- afterEach(() => {
- vi.restoreAllMocks();
- });
-
- describe("initial state", () => {
- it("should return isVisible=true when document is visible", () => {
- Object.defineProperty(document, "visibilityState", {
- value: "visible",
- writable: true,
- });
-
- const { result } = renderHook(() => useVisibilityChange());
-
- expect(result.current.isVisible).toBe(true);
- });
-
- it("should return isVisible=false when document is hidden", () => {
- Object.defineProperty(document, "visibilityState", {
- value: "hidden",
- writable: true,
- });
-
- const { result } = renderHook(() => useVisibilityChange());
-
- expect(result.current.isVisible).toBe(false);
- });
- });
-
- describe("visibility change events", () => {
- it("should update isVisible when visibility changes to hidden", () => {
- const { result } = renderHook(() => useVisibilityChange());
-
- expect(result.current.isVisible).toBe(true);
-
- // Simulate tab becoming hidden
- Object.defineProperty(document, "visibilityState", {
- value: "hidden",
- writable: true,
- });
-
- act(() => {
- document.dispatchEvent(new Event("visibilitychange"));
- });
-
- expect(result.current.isVisible).toBe(false);
- });
-
- it("should update isVisible when visibility changes to visible", () => {
- Object.defineProperty(document, "visibilityState", {
- value: "hidden",
- writable: true,
- });
-
- const { result } = renderHook(() => useVisibilityChange());
-
- expect(result.current.isVisible).toBe(false);
-
- // Simulate tab becoming visible
- Object.defineProperty(document, "visibilityState", {
- value: "visible",
- writable: true,
- });
-
- act(() => {
- document.dispatchEvent(new Event("visibilitychange"));
- });
-
- expect(result.current.isVisible).toBe(true);
- });
- });
-
- describe("callbacks", () => {
- it("should call onVisibilityChange with the new state", () => {
- const onVisibilityChange = vi.fn();
-
- renderHook(() => useVisibilityChange({ onVisibilityChange }));
-
- // Simulate tab becoming hidden
- Object.defineProperty(document, "visibilityState", {
- value: "hidden",
- writable: true,
- });
-
- act(() => {
- document.dispatchEvent(new Event("visibilitychange"));
- });
-
- expect(onVisibilityChange).toHaveBeenCalledWith("hidden");
-
- // Simulate tab becoming visible
- Object.defineProperty(document, "visibilityState", {
- value: "visible",
- writable: true,
- });
-
- act(() => {
- document.dispatchEvent(new Event("visibilitychange"));
- });
-
- expect(onVisibilityChange).toHaveBeenCalledWith("visible");
- });
-
- it("should call onVisible only when tab becomes visible", () => {
- const onVisible = vi.fn();
- const onHidden = vi.fn();
-
- renderHook(() => useVisibilityChange({ onVisible, onHidden }));
-
- // Simulate tab becoming hidden
- Object.defineProperty(document, "visibilityState", {
- value: "hidden",
- writable: true,
- });
-
- act(() => {
- document.dispatchEvent(new Event("visibilitychange"));
- });
-
- expect(onVisible).not.toHaveBeenCalled();
- expect(onHidden).toHaveBeenCalledTimes(1);
-
- // Simulate tab becoming visible
- Object.defineProperty(document, "visibilityState", {
- value: "visible",
- writable: true,
- });
-
- act(() => {
- document.dispatchEvent(new Event("visibilitychange"));
- });
-
- expect(onVisible).toHaveBeenCalledTimes(1);
- expect(onHidden).toHaveBeenCalledTimes(1);
- });
-
- it("should call onHidden only when tab becomes hidden", () => {
- const onHidden = vi.fn();
-
- renderHook(() => useVisibilityChange({ onHidden }));
-
- // Simulate tab becoming hidden
- Object.defineProperty(document, "visibilityState", {
- value: "hidden",
- writable: true,
- });
-
- act(() => {
- document.dispatchEvent(new Event("visibilitychange"));
- });
-
- expect(onHidden).toHaveBeenCalledTimes(1);
-
- // Simulate tab becoming visible (should not call onHidden)
- Object.defineProperty(document, "visibilityState", {
- value: "visible",
- writable: true,
- });
-
- act(() => {
- document.dispatchEvent(new Event("visibilitychange"));
- });
-
- expect(onHidden).toHaveBeenCalledTimes(1);
- });
- });
-
- describe("enabled option", () => {
- it("should not listen for events when enabled=false", () => {
- const onVisible = vi.fn();
-
- renderHook(() => useVisibilityChange({ onVisible, enabled: false }));
-
- // Simulate tab becoming visible
- Object.defineProperty(document, "visibilityState", {
- value: "visible",
- writable: true,
- });
-
- act(() => {
- document.dispatchEvent(new Event("visibilitychange"));
- });
-
- expect(onVisible).not.toHaveBeenCalled();
- });
-
- it("should start listening when enabled changes from false to true", () => {
- const onVisible = vi.fn();
-
- const { rerender } = renderHook(
- ({ enabled }) => useVisibilityChange({ onVisible, enabled }),
- { initialProps: { enabled: false } },
- );
-
- // Simulate event while disabled
- act(() => {
- document.dispatchEvent(new Event("visibilitychange"));
- });
-
- expect(onVisible).not.toHaveBeenCalled();
-
- // Enable the hook
- rerender({ enabled: true });
-
- // Now events should be captured
- act(() => {
- document.dispatchEvent(new Event("visibilitychange"));
- });
-
- expect(onVisible).toHaveBeenCalledTimes(1);
- });
- });
-
- describe("cleanup", () => {
- it("should remove event listener on unmount", () => {
- const addEventListenerSpy = vi.spyOn(document, "addEventListener");
- const removeEventListenerSpy = vi.spyOn(document, "removeEventListener");
-
- const { unmount } = renderHook(() => useVisibilityChange());
-
- expect(addEventListenerSpy).toHaveBeenCalledWith(
- "visibilitychange",
- expect.any(Function),
- );
-
- unmount();
-
- expect(removeEventListenerSpy).toHaveBeenCalledWith(
- "visibilitychange",
- expect.any(Function),
- );
- });
-
- it("should remove event listener when enabled changes to false", () => {
- const removeEventListenerSpy = vi.spyOn(document, "removeEventListener");
-
- const { rerender } = renderHook(
- ({ enabled }) => useVisibilityChange({ enabled }),
- { initialProps: { enabled: true } },
- );
-
- rerender({ enabled: false });
-
- expect(removeEventListenerSpy).toHaveBeenCalledWith(
- "visibilitychange",
- expect.any(Function),
- );
- });
- });
-
- describe("callback stability", () => {
- it("should handle callback updates without missing events", () => {
- const onVisible1 = vi.fn();
- const onVisible2 = vi.fn();
-
- const { rerender } = renderHook(
- ({ onVisible }) => useVisibilityChange({ onVisible }),
- { initialProps: { onVisible: onVisible1 } },
- );
-
- // Update callback
- rerender({ onVisible: onVisible2 });
-
- // Simulate visibility change
- act(() => {
- document.dispatchEvent(new Event("visibilitychange"));
- });
-
- expect(onVisible1).not.toHaveBeenCalled();
- expect(onVisible2).toHaveBeenCalledTimes(1);
- });
- });
-});
diff --git a/src/hooks/mutation/use-get-trajectory.ts b/src/hooks/mutation/use-get-trajectory.ts
deleted file mode 100644
index 9969a710b9..0000000000
--- a/src/hooks/mutation/use-get-trajectory.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-import { useMutation } from "@tanstack/react-query";
-import ConversationService from "#/api/conversation-service/conversation-service.api";
-
-export const useGetTrajectory = () =>
- useMutation({
- mutationFn: (cid: string) => ConversationService.getTrajectory(cid),
- });
diff --git a/src/hooks/mutation/use-upload-files.ts b/src/hooks/mutation/use-upload-files.ts
deleted file mode 100644
index 2132ba4a33..0000000000
--- a/src/hooks/mutation/use-upload-files.ts
+++ /dev/null
@@ -1,16 +0,0 @@
-import { useMutation } from "@tanstack/react-query";
-import ConversationService from "#/api/conversation-service/conversation-service.api";
-
-export const useUploadFiles = () =>
- useMutation({
- mutationKey: ["upload-files"],
- mutationFn: (variables: { conversationId: string; files: File[] }) =>
- ConversationService.uploadFiles(
- variables.conversationId!,
- variables.files,
- ),
- onSuccess: async () => {},
- meta: {
- disableToast: true,
- },
- });
diff --git a/src/hooks/query/use-ai-config-options.ts b/src/hooks/query/use-ai-config-options.ts
deleted file mode 100644
index c431a56fd1..0000000000
--- a/src/hooks/query/use-ai-config-options.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import { useQuery } from "@tanstack/react-query";
-
-export const useAIConfigOptions = () =>
- useQuery({
- queryKey: ["ai-config-options"],
- queryFn: () => ["llm", "pattern", "policy_rail"],
- staleTime: 1000 * 60 * 5,
- gcTime: 1000 * 60 * 15,
- });
diff --git a/src/hooks/query/use-batch-app-conversations.ts b/src/hooks/query/use-batch-app-conversations.ts
deleted file mode 100644
index 9cb05c2379..0000000000
--- a/src/hooks/query/use-batch-app-conversations.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { useQuery } from "@tanstack/react-query";
-import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
-import { useActiveBackend } from "#/contexts/active-backend-context";
-
-export const useBatchAppConversations = (ids: string[]) => {
- const active = useActiveBackend();
-
- return useQuery({
- // Backend-keyed so cross-backend switches do not return another
- // backend's cached results. Same invariant as
- // `useUserConversation` and `usePaginatedConversations`.
- queryKey: [
- "v1-batch-get-app-conversations",
- ids,
- active.backend.id,
- active.orgId,
- ],
- queryFn: () => AgentServerConversationService.batchGetAppConversations(ids),
- enabled: ids.length > 0,
- staleTime: 1000 * 60 * 5, // 5 minutes
- gcTime: 1000 * 60 * 15, // 15 minutes
- });
-};
diff --git a/src/hooks/query/use-get-secrets.ts b/src/hooks/query/use-get-secrets.ts
index 3fe1233831..381d7546be 100644
--- a/src/hooks/query/use-get-secrets.ts
+++ b/src/hooks/query/use-get-secrets.ts
@@ -4,14 +4,6 @@ import { SecretsService } from "#/api/secrets-service";
import { CustomSecretWithoutValue } from "#/api/secrets-service.types";
import { useActiveBackend } from "#/contexts/active-backend-context";
-export const useGetSecrets = () => {
- const active = useActiveBackend();
- return useQuery({
- queryKey: ["secrets", active.backend.id, active.orgId],
- queryFn: SecretsService.getSecrets,
- });
-};
-
interface UseSearchSecretsOptions {
nameContains?: string;
enabled?: boolean;
diff --git a/src/hooks/query/use-verified-models.ts b/src/hooks/query/use-verified-models.ts
index e8c9e7a214..438049ce24 100644
--- a/src/hooks/query/use-verified-models.ts
+++ b/src/hooks/query/use-verified-models.ts
@@ -1,4 +1,3 @@
-import { useQuery } from "@tanstack/react-query";
import { LLMMetadataClient } from "@openhands/typescript-client/clients";
import { getAgentServerClientOptions } from "#/api/agent-server-client-options";
@@ -12,11 +11,3 @@ export async function fetchVerifiedModelsByProvider(): Promise<
const client = new LLMMetadataClient(getAgentServerClientOptions());
return (await client.getVerifiedModels()) ?? {};
}
-
-export const useVerifiedModelsByProvider = () =>
- useQuery({
- queryKey: VERIFIED_MODELS_QUERY_KEY,
- queryFn: fetchVerifiedModelsByProvider,
- staleTime: VERIFIED_MODELS_STALE_TIME,
- gcTime: VERIFIED_MODELS_GC_TIME,
- });
diff --git a/src/hooks/query/use-workspace-session.ts b/src/hooks/query/use-workspace-session.ts
deleted file mode 100644
index 524e7c01d2..0000000000
--- a/src/hooks/query/use-workspace-session.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-import { RemoteWorkspace } from "@openhands/typescript-client/workspace/remote-workspace";
-import { useQuery } from "@tanstack/react-query";
-
-import { getAgentServerClientOptions } from "#/api/agent-server-client-options";
-import { useActiveConversation } from "#/hooks/query/use-active-conversation";
-import { useRuntimeIsReady } from "#/hooks/use-runtime-is-ready";
-
-export interface WorkspaceSession {
- /**
- * Absolute URL prefix for the conversation's static workspace fileserver,
- * always ending in a `/`. Append a relative path to address a single file
- * (e.g. `${baseUrl}index.html`).
- */
- baseUrl: string;
-}
-
-/**
- * Mint a workspace static-asset session for the active conversation.
- *
- * Calling `POST /api/auth/workspace-session` exchanges the conversation's
- * `X-Session-API-Key` for an `oh_workspace_session_key` cookie scoped to
- * `/api/conversations`. Once that cookie is set the browser can embed
- * workspace artifacts directly as `<iframe src>` / `<img src>` / top-level
- * navigations — which it cannot do when the only credential is a custom
- * request header.
- *
- * We treat the call as cache-once-per-conversation: the cookie lives in
- * the browser jar, so re-issuing the POST on every component remount is
- * wasted work. `staleTime: Infinity` keeps the cached `baseUrl` in place
- * for the lifetime of the conversation; only switching conversations (a
- * different `conversationId` in the query key) re-runs it.
- *
- * Returns `null` from `data` until the session has been minted, so
- * callers can gate iframe / img rendering on a definite "the cookie is
- * set" signal rather than guessing.
- */
-export function useWorkspaceSession(): {
- data: WorkspaceSession | null;
- isLoading: boolean;
- isError: boolean;
- error: Error | null;
-} {
- const { data: conversation } = useActiveConversation();
- const runtimeIsReady = useRuntimeIsReady();
-
- const conversationId = conversation?.id;
- const conversationUrl = conversation?.conversation_url;
- const sessionApiKey = conversation?.session_api_key;
-
- const enabled = runtimeIsReady && !!conversationId;
-
- const query = useQuery<WorkspaceSession>({
- queryKey: [
- "workspace-session",
- conversationId,
- conversationUrl,
- sessionApiKey,
- ],
- queryFn: async () => {
- const workspace = new RemoteWorkspace(
- getAgentServerClientOptions({
- conversationUrl,
- sessionApiKey,
- }),
- );
- const baseUrl = await workspace.startWorkspaceSession(conversationId!);
- return { baseUrl };
- },
- enabled,
- // The cookie is sticky; minting it once per page-load is plenty.
- staleTime: Infinity,
- gcTime: Infinity,
- // No auto-retry: a 401 here means the session API key isn't valid for
- // this conversation, which won't fix itself on a second POST. The
- // user can re-trigger by reloading or switching conversation.
- retry: false,
- });
-
- return {
- data: query.data ?? null,
- isLoading: query.isLoading,
- isError: query.isError,
- error: (query.error as Error | null) ?? null,
- };
-}
-
-/**
- * Append a workspace-relative path to a base URL produced by
- * {@link useWorkspaceSession}, URL-encoding each segment but preserving
- * `/` separators. Pass an empty / undefined `relativePath` to get the
- * directory base back (server then falls back to its `index.html`).
- */
-export function joinWorkspaceUrl(
- baseUrl: string,
- relativePath?: string | null,
-): string {
- const cleaned = (relativePath ?? "").replace(/^\/+/, "");
- if (!cleaned) return baseUrl;
- const encoded = cleaned
- .split("/")
- .map((segment) => encodeURIComponent(segment))
- .join("/");
- // baseUrl is guaranteed to end with a single trailing slash by the
- // server's contract (startWorkspaceSession returns `${host}/api/.../workspace/`).
- return `${baseUrl}${encoded}`;
-}
diff --git a/src/hooks/use-is-on-tos-page.ts b/src/hooks/use-is-on-tos-page.ts
deleted file mode 100644
index f2c9b253b4..0000000000
--- a/src/hooks/use-is-on-tos-page.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-import { useLocation } from "react-router";
-
-/**
- * Hook to check if the current page is the Terms of Service acceptance page.
- *
- * @returns {boolean} True if the current page is the TOS acceptance page, false otherwise.
- */
-export const useIsOnTosPage = (): boolean => {
- const { pathname } = useLocation();
- return pathname === "/accept-tos";
-};
diff --git a/src/hooks/use-rate.ts b/src/hooks/use-rate.ts
deleted file mode 100644
index 859d1d1686..0000000000
--- a/src/hooks/use-rate.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-import React from "react";
-
-interface UseRateProps {
- threshold: number;
-}
-
-const DEFAULT_CONFIG: UseRateProps = { threshold: 1000 };
-
-export const useRate = (config = DEFAULT_CONFIG) => {
- const [items, setItems] = React.useState<number[]>([]);
- const [rate, setRate] = React.useState<number | null>(null);
- const [lastUpdated, setLastUpdated] = React.useState<number | null>(null);
- const [isUnderThreshold, setIsUnderThreshold] = React.useState(true);
-
- /**
- * Record an entry in order to calculate the rate
- * @param entry Entry to record
- *
- * @example
- * record(new Date().getTime());
- */
- const record = (entry: number) => {
- setItems((prev) => [...prev, entry]);
- setLastUpdated(new Date().getTime());
- };
-
- /**
- * Update the rate based on the last two entries (if available)
- */
- const updateRate = () => {
- if (items.length > 1) {
- const newRate = items[items.length - 1] - items[items.length - 2];
- setRate(newRate);
-
- if (newRate <= config.threshold) setIsUnderThreshold(true);
- else setIsUnderThreshold(false);
- }
- };
-
- React.useEffect(() => {
- updateRate();
- }, [items]);
-
- React.useEffect(() => {
- // Set up an interval to check if the time since the last update exceeds the threshold
- // If it does, set isUnderThreshold to false, otherwise set it to true
- // This ensures that the component can react to periods of inactivity
- const intervalId = setInterval(() => {
- if (lastUpdated !== null) {
- const timeSinceLastUpdate = new Date().getTime() - lastUpdated;
- setIsUnderThreshold(timeSinceLastUpdate <= config.threshold);
- } else {
- setIsUnderThreshold(false);
- }
- }, config.threshold);
-
- return () => clearInterval(intervalId);
- }, [lastUpdated, config.threshold]);
-
- return {
- items,
- rate,
- lastUpdated,
- isUnderThreshold,
- record,
- };
-};
diff --git a/src/hooks/use-visibility-change.ts b/src/hooks/use-visibility-change.ts
deleted file mode 100644
index 1ee929cf6c..0000000000
--- a/src/hooks/use-visibility-change.ts
+++ /dev/null
@@ -1,64 +0,0 @@
-import React from "react";
-
-type VisibilityState = "visible" | "hidden";
-
-interface UseVisibilityChangeOptions {
- /** Callback fired when visibility changes to the specified state */
- onVisibilityChange?: (state: VisibilityState) => void;
- /** Callback fired only when tab becomes visible */
- onVisible?: () => void;
- /** Callback fired only when tab becomes hidden */
- onHidden?: () => void;
- /** Whether to listen for visibility changes (default: true) */
- enabled?: boolean;
-}
-
-/**
- * Hook that listens for browser tab visibility changes.
- *
- * Useful for:
- * - Resuming operations when user returns to the tab
- * - Pausing expensive operations when tab is hidden
- * - Tracking user engagement
- *
- * @param options.onVisibilityChange - Callback with the new visibility state
- * @param options.onVisible - Callback fired only when tab becomes visible
- * @param options.onHidden - Callback fired only when tab becomes hidden
- * @param options.enabled - Whether to listen for changes (default: true)
- * @returns isVisible - Current visibility state of the tab
- */
-export function useVisibilityChange({
- onVisibilityChange,
- onVisible,
- onHidden,
- enabled = true,
-}: UseVisibilityChangeOptions = {}) {
- const [isVisible, setIsVisible] = React.useState(
- () => document.visibilityState === "visible",
- );
-
- React.useEffect(() => {
- if (!enabled) return undefined;
-
- const handleVisibilityChange = () => {
- const state = document.visibilityState as VisibilityState;
- setIsVisible(state === "visible");
-
- onVisibilityChange?.(state);
-
- if (state === "visible") {
- onVisible?.();
- } else {
- onHidden?.();
- }
- };
-
- document.addEventListener("visibilitychange", handleVisibilityChange);
-
- return () => {
- document.removeEventListener("visibilitychange", handleVisibilityChange);
- };
- }, [enabled, onVisibilityChange, onVisible, onHidden]);
-
- return { isVisible };
-}