π OpenHands: AI-Driven Development
refactor: Replace load_custom_secrets_names with search_custom_secrets (#13985)
Tim O'Farrell385122e2602d
diff --git a/frontend/__tests__/routes/secrets-settings.test.tsx b/frontend/__tests__/routes/secrets-settings.test.tsxindex cec49b0626..a47c2ca847 100644--- a/frontend/__tests__/routes/secrets-settings.test.tsx+++ b/frontend/__tests__/routes/secrets-settings.test.tsx@@ -5,7 +5,10 @@ import userEvent from "@testing-library/user-event";import { createRoutesStub, Outlet } from "react-router";import SecretsSettingsScreen, { clientLoader } from "#/routes/secrets-settings";import { SecretsService } from "#/api/secrets-service";-import { GetSecretsResponse } from "#/api/secrets-service.types";+import {+ CustomSecretPage,+ CustomSecretWithoutValue,+} from "#/api/secrets-service.types";import SettingsService from "#/api/settings-service/settings-service.api";import OptionService from "#/api/option-service/option-service.api";import { MOCK_DEFAULT_USER_SETTINGS } from "#/mocks/handlers";@@ -13,7 +16,7 @@ import { OrganizationMember } from "#/types/org";import * as orgStore from "#/stores/selected-organization-store";import { organizationService } from "#/api/organization-service/organization-service.api";-const MOCK_GET_SECRETS_RESPONSE: GetSecretsResponse["custom_secrets"] = [+const MOCK_SECRETS: CustomSecretWithoutValue[] = [{name: "My_Secret_1",description: "My first secret",@@ -24,6 +27,13 @@ const MOCK_GET_SECRETS_RESPONSE: GetSecretsResponse["custom_secrets"] = [},];+const createMockSecretsPage = (+ secrets: CustomSecretWithoutValue[],+): CustomSecretPage => ({+ items: secrets,+ next_page_id: null,+});+const renderSecretsSettings = () => {const RouterStub = createRoutesStub([{@@ -146,7 +156,7 @@ describe("Content", () => {it("should NOT render a button to connect with git if they havent already in oss", async () => {const getConfigSpy = vi.spyOn(OptionService, "getConfig");const getSettingsSpy = vi.spyOn(SettingsService, "getSettings");- const getSecretsSpy = vi.spyOn(SecretsService, "getSecrets");+ const searchSecretsSpy = vi.spyOn(SecretsService, "searchSecrets");// @ts-expect-error - only return the config we needgetConfigSpy.mockResolvedValue({app_mode: "oss",@@ -159,13 +169,13 @@ describe("Content", () => {renderSecretsSettings();expect(getConfigSpy).toHaveBeenCalled();- await waitFor(() => expect(getSecretsSpy).toHaveBeenCalled());+ await waitFor(() => expect(searchSecretsSpy).toHaveBeenCalled());expect(screen.queryByTestId("connect-git-button")).not.toBeInTheDocument();});it("should render add secret button in saas mode", async () => {const getConfigSpy = vi.spyOn(OptionService, "getConfig");- const getSecretsSpy = vi.spyOn(SecretsService, "getSecrets");+ const searchSecretsSpy = vi.spyOn(SecretsService, "searchSecrets");// @ts-expect-error - only return the config we needgetConfigSpy.mockResolvedValue({app_mode: "saas",@@ -173,33 +183,37 @@ describe("Content", () => {renderSecretsSettings();- // In SAAS mode, getSecrets is called and add secret button should be available- await waitFor(() => expect(getSecretsSpy).toHaveBeenCalled());+ // In SAAS mode, searchSecrets is called and add secret button should be available+ await waitFor(() => expect(searchSecretsSpy).toHaveBeenCalled());const button = await screen.findByTestId("add-secret-button");expect(button).toBeInTheDocument();expect(screen.queryByTestId("connect-git-button")).not.toBeInTheDocument();});it("should render an empty table when there are no existing secrets", async () => {- const getSecretsSpy = vi.spyOn(SecretsService, "getSecrets");- getSecretsSpy.mockResolvedValue([]);+ const searchSecretsSpy = vi.spyOn(SecretsService, "searchSecrets");+ searchSecretsSpy.mockResolvedValue(createMockSecretsPage([]));renderSecretsSettings();// Should show the add secret buttonawait screen.findByTestId("add-secret-button");+ // Wait for loading to complete and table headers to appear+ await waitFor(() => {+ expect(screen.getByText("SETTINGS$NAME")).toBeInTheDocument();+ });+// Should show an empty table with headers but no secret itemsexpect(screen.queryAllByTestId("secret-item")).toHaveLength(0);// Should still show the table headers- expect(screen.getByText("SETTINGS$NAME")).toBeInTheDocument();expect(screen.getByText("SECRETS$DESCRIPTION")).toBeInTheDocument();expect(screen.getByText("SETTINGS$ACTIONS")).toBeInTheDocument();});it("should render existing secrets", async () => {- const getSecretsSpy = vi.spyOn(SecretsService, "getSecrets");- getSecretsSpy.mockResolvedValue(MOCK_GET_SECRETS_RESPONSE);+ const searchSecretsSpy = vi.spyOn(SecretsService, "searchSecrets");+ searchSecretsSpy.mockResolvedValue(createMockSecretsPage(MOCK_SECRETS));renderSecretsSettings();const secrets = await screen.findAllByTestId("secret-item");@@ -210,7 +224,7 @@ describe("Content", () => {describe("Secret actions", () => {it("should create a new secret", async () => {const createSecretSpy = vi.spyOn(SecretsService, "createSecret");- const getSecretsSpy = vi.spyOn(SecretsService, "getSecrets");+ const searchSecretsSpy = vi.spyOn(SecretsService, "searchSecrets");createSecretSpy.mockResolvedValue(true);renderSecretsSettings();@@ -251,13 +265,13 @@ describe("Secret actions", () => {// hide form & render itemsexpect(screen.queryByTestId("add-secret-form")).not.toBeInTheDocument();- expect(getSecretsSpy).toHaveBeenCalled();+ expect(searchSecretsSpy).toHaveBeenCalled();});it("should edit a secret", async () => {- const getSecretsSpy = vi.spyOn(SecretsService, "getSecrets");+ const searchSecretsSpy = vi.spyOn(SecretsService, "searchSecrets");const updateSecretSpy = vi.spyOn(SecretsService, "updateSecret");- getSecretsSpy.mockResolvedValue(MOCK_GET_SECRETS_RESPONSE);+ searchSecretsSpy.mockResolvedValue(createMockSecretsPage(MOCK_SECRETS));updateSecretSpy.mockResolvedValue(true);renderSecretsSettings();@@ -293,6 +307,13 @@ describe("Secret actions", () => {await userEvent.clear(descriptionInput);await userEvent.type(descriptionInput, "My edited secret description");+ // Mock updated response for after edit+ const updatedSecrets = [+ { name: "My_Edited_Secret", description: "My edited secret description" },+ MOCK_SECRETS[1],+ ];+ searchSecretsSpy.mockResolvedValue(createMockSecretsPage(updatedSecrets));+await userEvent.click(submitButton);// make POST request@@ -302,18 +323,20 @@ describe("Secret actions", () => {"My edited secret description",);- // hide form- expect(screen.queryByTestId("edit-secret-form")).not.toBeInTheDocument();+ // hide form and show updated list+ await waitFor(() => {+ expect(screen.queryByTestId("edit-secret-form")).not.toBeInTheDocument();+ });- // optimistic update- const updatedSecrets = await screen.findAllByTestId("secret-item");- expect(updatedSecrets).toHaveLength(2);- expect(updatedSecrets[0]).toHaveTextContent(/my_edited_secret/i);+ // Wait for updated data after query invalidation+ const secretsAfterEdit = await screen.findAllByTestId("secret-item");+ expect(secretsAfterEdit).toHaveLength(2);+ expect(secretsAfterEdit[0]).toHaveTextContent(/my_edited_secret/i);});it("should be able to cancel the create or edit form", async () => {- const getSecretsSpy = vi.spyOn(SecretsService, "getSecrets");- getSecretsSpy.mockResolvedValue(MOCK_GET_SECRETS_RESPONSE);+ const searchSecretsSpy = vi.spyOn(SecretsService, "searchSecrets");+ searchSecretsSpy.mockResolvedValue(createMockSecretsPage(MOCK_SECRETS));renderSecretsSettings();// render form & hide items@@ -348,9 +371,9 @@ describe("Secret actions", () => {});it("should undo the optimistic update if the request fails", async () => {- const getSecretsSpy = vi.spyOn(SecretsService, "getSecrets");+ const searchSecretsSpy = vi.spyOn(SecretsService, "searchSecrets");const updateSecretSpy = vi.spyOn(SecretsService, "updateSecret");- getSecretsSpy.mockResolvedValue(MOCK_GET_SECRETS_RESPONSE);+ searchSecretsSpy.mockResolvedValue(createMockSecretsPage(MOCK_SECRETS));updateSecretSpy.mockRejectedValue(new Error("Failed to update secret"));renderSecretsSettings();@@ -396,9 +419,9 @@ describe("Secret actions", () => {});it("should remove the secret from the list after deletion", async () => {- const getSecretsSpy = vi.spyOn(SecretsService, "getSecrets");+ const searchSecretsSpy = vi.spyOn(SecretsService, "searchSecrets");const deleteSecretSpy = vi.spyOn(SecretsService, "deleteSecret");- getSecretsSpy.mockResolvedValue(MOCK_GET_SECRETS_RESPONSE);+ searchSecretsSpy.mockResolvedValue(createMockSecretsPage(MOCK_SECRETS));deleteSecretSpy.mockResolvedValue(true);renderSecretsSettings();@@ -412,21 +435,29 @@ describe("Secret actions", () => {const confirmationModal = screen.getByTestId("confirmation-modal");const confirmButton =within(confirmationModal).getByTestId("confirm-button");++ // Mock updated response after deletion+ searchSecretsSpy.mockResolvedValue(+ createMockSecretsPage([MOCK_SECRETS[0]]),+ );+await userEvent.click(confirmButton);// make DELETE requestexpect(deleteSecretSpy).toHaveBeenCalledWith("My_Secret_2");expect(screen.queryByTestId("confirmation-modal")).not.toBeInTheDocument();- // optimistic update- expect(screen.queryAllByTestId("secret-item")).toHaveLength(1);+ // Wait for updated list after query invalidation+ await waitFor(() => {+ expect(screen.queryAllByTestId("secret-item")).toHaveLength(1);+ });expect(screen.queryByText("My_Secret_2")).not.toBeInTheDocument();});it("should be able to cancel the delete confirmation modal", async () => {- const getSecretsSpy = vi.spyOn(SecretsService, "getSecrets");+ const searchSecretsSpy = vi.spyOn(SecretsService, "searchSecrets");const deleteSecretSpy = vi.spyOn(SecretsService, "deleteSecret");- getSecretsSpy.mockResolvedValue(MOCK_GET_SECRETS_RESPONSE);+ searchSecretsSpy.mockResolvedValue(createMockSecretsPage(MOCK_SECRETS));deleteSecretSpy.mockResolvedValue(true);renderSecretsSettings();@@ -448,9 +479,9 @@ describe("Secret actions", () => {});it("should revert the optimistic update if the request fails", async () => {- const getSecretsSpy = vi.spyOn(SecretsService, "getSecrets");+ const searchSecretsSpy = vi.spyOn(SecretsService, "searchSecrets");const deleteSecretSpy = vi.spyOn(SecretsService, "deleteSecret");- getSecretsSpy.mockResolvedValue(MOCK_GET_SECRETS_RESPONSE);+ searchSecretsSpy.mockResolvedValue(createMockSecretsPage(MOCK_SECRETS));deleteSecretSpy.mockRejectedValue(new Error("Failed to delete secret"));renderSecretsSettings();@@ -476,13 +507,15 @@ describe("Secret actions", () => {});it("should hide the table and add button when in form view", async () => {- const getSecretsSpy = vi.spyOn(SecretsService, "getSecrets");- getSecretsSpy.mockResolvedValue([]);+ const searchSecretsSpy = vi.spyOn(SecretsService, "searchSecrets");+ searchSecretsSpy.mockResolvedValue(createMockSecretsPage([]));renderSecretsSettings();- // Initially should show the add button and table+ // Initially should show the add button and wait for table to loadconst button = await screen.findByTestId("add-secret-button");- expect(screen.getByText("SETTINGS$NAME")).toBeInTheDocument(); // table header+ await waitFor(() => {+ expect(screen.getByText("SETTINGS$NAME")).toBeInTheDocument(); // table header+ });await userEvent.click(button);@@ -530,8 +563,8 @@ describe("Secret actions", () => {it("should not allow existing secret names", async () => {const createSecretSpy = vi.spyOn(SecretsService, "createSecret");- const getSecretsSpy = vi.spyOn(SecretsService, "getSecrets");- getSecretsSpy.mockResolvedValue(MOCK_GET_SECRETS_RESPONSE.slice(0, 1));+ const searchSecretsSpy = vi.spyOn(SecretsService, "searchSecrets");+ searchSecretsSpy.mockResolvedValue(createMockSecretsPage(MOCK_SECRETS.slice(0, 1)));renderSecretsSettings();// render form & hide items@@ -577,8 +610,8 @@ describe("Secret actions", () => {it("should not submit whitespace secret names or values", async () => {const createSecretSpy = vi.spyOn(SecretsService, "createSecret");- const getSecretsSpy = vi.spyOn(SecretsService, "getSecrets");- getSecretsSpy.mockResolvedValue([]);+ const searchSecretsSpy = vi.spyOn(SecretsService, "searchSecrets");+ searchSecretsSpy.mockResolvedValue(createMockSecretsPage([]));renderSecretsSettings();// render form & hide items@@ -618,9 +651,9 @@ describe("Secret actions", () => {});it("should not reset ipout values on an invalid submit", async () => {- const getSecretsSpy = vi.spyOn(SecretsService, "getSecrets");+ const searchSecretsSpy = vi.spyOn(SecretsService, "searchSecrets");const createSecretSpy = vi.spyOn(SecretsService, "createSecret");- getSecretsSpy.mockResolvedValue(MOCK_GET_SECRETS_RESPONSE);+ searchSecretsSpy.mockResolvedValue(createMockSecretsPage(MOCK_SECRETS));renderSecretsSettings();@@ -637,7 +670,7 @@ describe("Secret actions", () => {const valueInput = within(secretForm).getByTestId("value-input");const submitButton = within(secretForm).getByTestId("submit-button");- await userEvent.type(nameInput, MOCK_GET_SECRETS_RESPONSE[0].name);+ await userEvent.type(nameInput, MOCK_SECRETS[0].name);await userEvent.type(valueInput, "my-custom-secret-value");await userEvent.click(submitButton);@@ -647,7 +680,7 @@ describe("Secret actions", () => {screen.queryByText("SECRETS$SECRET_ALREADY_EXISTS"),).toBeInTheDocument();- expect(nameInput).toHaveValue(MOCK_GET_SECRETS_RESPONSE[0].name);+ expect(nameInput).toHaveValue(MOCK_SECRETS[0].name);expect(valueInput).toHaveValue("my-custom-secret-value");});});diff --git a/frontend/src/api/secrets-service.ts b/frontend/src/api/secrets-service.tsindex fd247ec9bd..dbd755b77c 100644--- a/frontend/src/api/secrets-service.ts+++ b/frontend/src/api/secrets-service.ts@@ -1,15 +1,61 @@import { openHands } from "./open-hands-axios";import {CustomSecret,- GetSecretsResponse,+ CustomSecretPage,+ CustomSecretWithoutValue,POSTProviderTokens,+ SearchSecretsParams,} from "./secrets-service.types";import { Provider, ProviderToken } from "#/types/settings";export class SecretsService {- static async getSecrets() {- const { data } = await openHands.get<GetSecretsResponse>("/api/secrets");- return data.custom_secrets;+ /**+ * Search/list custom secrets with pagination support.+ * Uses the new V1 API endpoint: GET /api/v1/secrets/search+ */+ static async searchSecrets(+ params: SearchSecretsParams = {},+ ): Promise<CustomSecretPage> {+ const queryParams = new URLSearchParams();++ if (params.name__contains) {+ queryParams.set("name__contains", params.name__contains);+ }+ if (params.page_id) {+ queryParams.set("page_id", params.page_id);+ }+ if (params.limit) {+ queryParams.set("limit", params.limit.toString());+ }++ const queryString = queryParams.toString();+ const url = `/api/v1/secrets/search${queryString ? `?${queryString}` : ""}`;++ const { data } = await openHands.get<CustomSecretPage>(url);+ return data;+ }++ /**+ * @deprecated Use searchSecrets instead. This method uses the deprecated V0 API.+ */+ static async getSecrets(): Promise<CustomSecretWithoutValue[]> {+ // Fetch all secrets by iterating through pages+ const allSecrets: CustomSecretWithoutValue[] = [];+ let pageId: string | null = null;++ // eslint-disable-next-line no-await-in-loop+ for (;;) {+ // eslint-disable-next-line no-await-in-loop+ const page = await SecretsService.searchSecrets({+ page_id: pageId ?? undefined,+ limit: 100,+ });+ allSecrets.push(...page.items);+ pageId = page.next_page_id;+ if (!pageId) break;+ }++ return allSecrets;}static async createSecret(name: string, value: string, description?: string) {@@ -19,22 +65,22 @@ export class SecretsService {description,};- const { status } = await openHands.post("/api/secrets", secret);+ const { status } = await openHands.post("/api/v1/secrets", secret);return status === 201;}static async updateSecret(id: string, name: string, description?: string) {- const secret: Omit<CustomSecret, "value"> = {+ const secret: CustomSecretWithoutValue = {name,description,};- const { status } = await openHands.put(`/api/secrets/${id}`, secret);+ const { status } = await openHands.put(`/api/v1/secrets/${id}`, secret);return status === 200;}static async deleteSecret(id: string) {- const { status } = await openHands.delete<boolean>(`/api/secrets/${id}`);+ const { status } = await openHands.delete<boolean>(`/api/v1/secrets/${id}`);return status === 200;}@@ -43,7 +89,7 @@ export class SecretsService {provider_tokens: providers,};const { data } = await openHands.post<boolean>(- "/api/add-git-providers",+ "/api/v1/secrets/git-providers",tokens,);return data;diff --git a/frontend/src/api/secrets-service.types.ts b/frontend/src/api/secrets-service.types.tsindex 888d1a1fea..44faba23db 100644--- a/frontend/src/api/secrets-service.types.ts+++ b/frontend/src/api/secrets-service.types.ts@@ -6,10 +6,25 @@ export type CustomSecret = {description?: string;};+export type CustomSecretWithoutValue = Omit<CustomSecret, "value">;++/** Paginated response from GET /api/v1/secrets/search */+export interface CustomSecretPage {+ items: CustomSecretWithoutValue[];+ next_page_id: string | null;+}++/** @deprecated Use CustomSecretPage instead */export interface GetSecretsResponse {- custom_secrets: Omit<CustomSecret, "value">[];+ custom_secrets: CustomSecretWithoutValue[];}export interface POSTProviderTokens {provider_tokens: Record<Provider, ProviderToken>;}++export interface SearchSecretsParams {+ name__contains?: string;+ page_id?: string;+ limit?: number;+}diff --git a/frontend/src/components/features/settings/secrets-settings/secret-form.tsx b/frontend/src/components/features/settings/secrets-settings/secret-form.tsxindex 9987faced2..047341b80e 100644--- a/frontend/src/components/features/settings/secrets-settings/secret-form.tsx+++ b/frontend/src/components/features/settings/secrets-settings/secret-form.tsx@@ -7,8 +7,7 @@ import { useUpdateSecret } from "#/hooks/mutation/use-update-secret";import { SettingsInput } from "../settings-input";import { cn } from "#/utils/utils";import { BrandButton } from "../brand-button";-import { useGetSecrets } from "#/hooks/query/use-get-secrets";-import { GetSecretsResponse } from "#/api/secrets-service.types";+import { useSearchSecrets } from "#/hooks/query/use-get-secrets";import { OptionalTag } from "../optional-tag";import { useSelectedOrganizationId } from "#/context/use-selected-organization";@@ -27,7 +26,7 @@ export function SecretForm({const { t } = useTranslation();const { organizationId } = useSelectedOrganizationId();- const { data: secrets } = useGetSecrets();+ const { data: secrets } = useSearchSecrets();const { mutate: createSecret } = useCreateSecret();const { mutate: updateSecret } = useUpdateSecret();@@ -41,6 +40,16 @@ export function SecretForm({?.description?.trim()) ||"";+ const invalidateSecrets = () => {+ // Invalidate both the new infinite query and the legacy query for compatibility+ queryClient.invalidateQueries({+ queryKey: ["secrets-search"],+ });+ queryClient.invalidateQueries({+ queryKey: ["secrets", organizationId],+ });+ };+const handleCreateSecret = (name: string,value: string,@@ -50,53 +59,21 @@ export function SecretForm({{ name, value, description },{onSettled: onCancel,- onSuccess: async () => {- await queryClient.invalidateQueries({- queryKey: ["secrets", organizationId],- });- },+ onSuccess: invalidateSecrets,},);};- const updateSecretOptimistically = (- oldName: string,- name: string,- description?: string,- ) => {- queryClient.setQueryData<GetSecretsResponse["custom_secrets"]>(- ["secrets", organizationId],- (oldSecrets) => {- if (!oldSecrets) return [];- return oldSecrets.map((secret) => {- if (secret.name === oldName) {- return {- ...secret,- name,- description,- };- }- return secret;- });- },- );- };-- const revertOptimisticUpdate = () => {- queryClient.invalidateQueries({ queryKey: ["secrets", organizationId] });- };-const handleEditSecret = (secretToEdit: string,name: string,description?: string,) => {- updateSecretOptimistically(secretToEdit, name, description);updateSecret({ secretToEdit, name, description },{onSettled: onCancel,- onError: revertOptimisticUpdate,+ onSuccess: invalidateSecrets,},);};diff --git a/frontend/src/hooks/query/use-get-secrets.ts b/frontend/src/hooks/query/use-get-secrets.tsindex 9c402e1c39..cee52e915a 100644--- a/frontend/src/hooks/query/use-get-secrets.ts+++ b/frontend/src/hooks/query/use-get-secrets.ts@@ -1,9 +1,17 @@-import { useQuery } from "@tanstack/react-query";+import {+ useQuery,+ useInfiniteQuery,+ InfiniteData,+} from "@tanstack/react-query";import { SecretsService } from "#/api/secrets-service";import { useConfig } from "./use-config";import { useIsAuthed } from "#/hooks/query/use-is-authed";import { useSelectedOrganizationId } from "#/context/use-selected-organization";+import { CustomSecretPage } from "#/api/secrets-service.types";+/**+ * @deprecated Use useSearchSecrets instead for paginated access+ */export const useGetSecrets = () => {const { data: config } = useConfig();const { data: isAuthed } = useIsAuthed();@@ -17,3 +25,63 @@ export const useGetSecrets = () => {enabled: isOss || (isAuthed && !!organizationId),});};++interface UseSearchSecretsOptions {+ nameContains?: string;+ pageSize?: number;+ enabled?: boolean;+}++/**+ * Hook for searching/listing secrets with infinite scroll pagination support.+ */+export const useSearchSecrets = (options: UseSearchSecretsOptions = {}) => {+ const { nameContains, pageSize = 30, enabled = true } = options;+ const { data: config } = useConfig();+ const { data: isAuthed } = useIsAuthed();+ const { organizationId } = useSelectedOrganizationId();++ const isOss = config?.app_mode === "oss";+ const isEnabled = enabled && (isOss || (isAuthed && !!organizationId));++ const query = useInfiniteQuery<+ CustomSecretPage,+ Error,+ InfiniteData<CustomSecretPage>,+ [string, string | null, string | undefined, number],+ string | null+ >({+ queryKey: ["secrets-search", organizationId, nameContains, pageSize],+ queryFn: async ({ pageParam }) =>+ SecretsService.searchSecrets({+ name__contains: nameContains,+ page_id: pageParam ?? undefined,+ limit: pageSize,+ }),+ getNextPageParam: (lastPage) => lastPage.next_page_id,+ initialPageParam: null,+ enabled: isEnabled,+ staleTime: 1000 * 60 * 5, // 5 minutes+ gcTime: 1000 * 60 * 15, // 15 minutes+ });++ const onLoadMore = () => {+ if (query.hasNextPage && !query.isFetchingNextPage) {+ query.fetchNextPage();+ }+ };++ // Flatten all pages into a single array of secrets+ const secrets = query.data?.pages?.flatMap((page) => page.items) ?? [];++ return {+ data: secrets,+ isLoading: query.isLoading,+ isError: query.isError,+ hasNextPage: query.hasNextPage ?? false,+ isFetchingNextPage: query.isFetchingNextPage,+ fetchNextPage: query.fetchNextPage,+ onLoadMore,+ refetch: query.refetch,+ };+};diff --git a/frontend/src/mocks/secrets-handlers.ts b/frontend/src/mocks/secrets-handlers.tsindex 18c4dc98fd..0d6d6120db 100644--- a/frontend/src/mocks/secrets-handlers.ts+++ b/frontend/src/mocks/secrets-handlers.ts@@ -1,5 +1,10 @@import { http, HttpResponse } from "msw";-import { CustomSecret, GetSecretsResponse } from "#/api/secrets-service.types";+import {+ CustomSecret,+ CustomSecretPage,+ CustomSecretWithoutValue,+ GetSecretsResponse,+} from "#/api/secrets-service.types";const DEFAULT_SECRETS: CustomSecret[] = [{@@ -19,9 +24,52 @@ const secrets = new Map<string, CustomSecret>();export const SECRETS_HANDLERS = [+ // V1 API - Search endpoint with pagination+ http.get("/api/v1/secrets/search", async ({ request }) => {+ const url = new URL(request.url);+ const nameContains = url.searchParams.get("name__contains");+ const pageId = url.searchParams.get("page_id");+ const limit = parseInt(url.searchParams.get("limit") || "100", 10);++ // Get all secrets and filter by name if needed+ let secretsArray = Array.from(secrets.values());+ if (nameContains) {+ secretsArray = secretsArray.filter((s) =>+ s.name.toLowerCase().includes(nameContains.toLowerCase()),+ );+ }++ // Sort alphabetically for consistent pagination+ secretsArray.sort((a, b) => a.name.localeCompare(b.name));++ // Apply pagination+ let startIndex = 0;+ if (pageId) {+ const pageIndex = secretsArray.findIndex((s) => s.name === pageId);+ if (pageIndex >= 0) {+ startIndex = pageIndex + 1;+ }+ }++ const pageItems = secretsArray.slice(startIndex, startIndex + limit);+ const hasMore = startIndex + limit < secretsArray.length;++ const items: CustomSecretWithoutValue[] = pageItems.map(+ ({ value, ...rest }) => rest,+ );++ const data: CustomSecretPage = {+ items,+ next_page_id: hasMore ? (items[items.length - 1]?.name ?? null) : null,+ };++ return HttpResponse.json(data);+ }),++ // Legacy V0 API - deprecated but kept for compatibilityhttp.get("/api/secrets", async () => {const secretsArray = Array.from(secrets.values());- const secretsWithoutValue: Omit<CustomSecret, "value">[] = secretsArray.map(+ const secretsWithoutValue: CustomSecretWithoutValue[] = secretsArray.map(({ value, ...rest }) => rest,);@@ -32,19 +80,50 @@ export const SECRETS_HANDLERS = [return HttpResponse.json(data);}),+ // V1 API - Create secret+ http.post("/api/v1/secrets", async ({ request }) => {+ const body = (await request.json()) as CustomSecret;+ if (typeof body === "object" && body?.name) {+ secrets.set(body.name, body);+ return new HttpResponse(null, { status: 201 });+ }++ return HttpResponse.json(false, { status: 400 });+ }),++ // Legacy V0 API - Create secret (deprecated)http.post("/api/secrets", async ({ request }) => {const body = (await request.json()) as CustomSecret;if (typeof body === "object" && body?.name) {secrets.set(body.name, body);- return HttpResponse.json(true);+ return new HttpResponse(null, { status: 201 });}return HttpResponse.json(false, { status: 400 });}),+ // V1 API - Update secret+ http.put("/api/v1/secrets/:id", async ({ params, request }) => {+ const { id } = params;+ const body = (await request.json()) as CustomSecretWithoutValue;++ if (typeof id === "string" && typeof body === "object") {+ const secret = secrets.get(id);+ if (secret && body?.name) {+ const newSecret: CustomSecret = { ...secret, ...body };+ secrets.delete(id);+ secrets.set(body.name, newSecret);+ return HttpResponse.json(true);+ }+ }++ return HttpResponse.json(false, { status: 400 });+ }),++ // Legacy V0 API - Update secret (deprecated)http.put("/api/secrets/:id", async ({ params, request }) => {const { id } = params;- const body = (await request.json()) as Omit<CustomSecret, "value">;+ const body = (await request.json()) as CustomSecretWithoutValue;if (typeof id === "string" && typeof body === "object") {const secret = secrets.get(id);@@ -59,6 +138,19 @@ export const SECRETS_HANDLERS = [return HttpResponse.json(false, { status: 400 });}),+ // V1 API - Delete secret+ http.delete("/api/v1/secrets/:id", async ({ params }) => {+ const { id } = params;++ if (typeof id === "string") {+ secrets.delete(id);+ return HttpResponse.json(true);+ }++ return HttpResponse.json(false, { status: 400 });+ }),++ // Legacy V0 API - Delete secret (deprecated)http.delete("/api/secrets/:id", async ({ params }) => {const { id } = params;diff --git a/frontend/src/routes/secrets-settings.tsx b/frontend/src/routes/secrets-settings.tsxindex 48cda5ecbb..82aa0a4960 100644--- a/frontend/src/routes/secrets-settings.tsx+++ b/frontend/src/routes/secrets-settings.tsx@@ -1,7 +1,7 @@import { useQueryClient } from "@tanstack/react-query";-import React from "react";+import React, { useCallback, useRef } from "react";import { useTranslation } from "react-i18next";-import { useGetSecrets } from "#/hooks/query/use-get-secrets";+import { useSearchSecrets } from "#/hooks/query/use-get-secrets";import { useDeleteSecret } from "#/hooks/mutation/use-delete-secret";import { SecretForm } from "#/components/features/settings/secrets-settings/secret-form";import {@@ -10,10 +10,10 @@ import {} from "#/components/features/settings/secrets-settings/secret-list-item";import { BrandButton } from "#/components/features/settings/brand-button";import { ConfirmationModal } from "#/components/shared/modals/confirmation-modal";-import { GetSecretsResponse } from "#/api/secrets-service.types";import { I18nKey } from "#/i18n/declaration";import { createPermissionGuard } from "#/utils/org/permission-guard";import { useSelectedOrganizationId } from "#/context/use-selected-organization";+import { LoadingSpinner } from "#/components/shared/loading-spinner";export const clientLoader = createPermissionGuard("manage_secrets");@@ -21,8 +21,16 @@ function SecretsSettingsScreen() {const queryClient = useQueryClient();const { t } = useTranslation();const { organizationId } = useSelectedOrganizationId();+ const tableContainerRef = useRef<HTMLDivElement>(null);++ const {+ data: secrets,+ isLoading: isLoadingSecrets,+ hasNextPage,+ isFetchingNextPage,+ onLoadMore,+ } = useSearchSecrets({ pageSize: 30 });- const { data: secrets, isLoading: isLoadingSecrets } = useGetSecrets();const { mutate: deleteSecret } = useDeleteSecret();const [view, setView] = React.useState<@@ -34,27 +42,37 @@ function SecretsSettingsScreen() {const [confirmationModalIsVisible, setConfirmationModalIsVisible] =React.useState(false);- const deleteSecretOptimistically = (secret: string) => {- queryClient.setQueryData<GetSecretsResponse["custom_secrets"]>(- ["secrets", organizationId],- (oldSecrets) => {- if (!oldSecrets) return [];- return oldSecrets.filter((s) => s.name !== secret);- },- );- };+ // Handle scroll for infinite loading+ const handleScroll = useCallback(+ (e: React.UIEvent<HTMLDivElement>) => {+ const target = e.currentTarget;+ const isNearBottom =+ target.scrollHeight - target.scrollTop <= target.clientHeight + 100;++ if (isNearBottom && hasNextPage && !isFetchingNextPage) {+ onLoadMore();+ }+ },+ [hasNextPage, isFetchingNextPage, onLoadMore],+ );- const revertOptimisticUpdate = () => {- queryClient.invalidateQueries({ queryKey: ["secrets", organizationId] });+ const invalidateSecrets = () => {+ // Invalidate both the new infinite query and the legacy query for compatibility+ queryClient.invalidateQueries({+ queryKey: ["secrets-search"],+ });+ queryClient.invalidateQueries({+ queryKey: ["secrets", organizationId],+ });};const handleDeleteSecret = (secret: string) => {- deleteSecretOptimistically(secret);deleteSecret(secret, {onSettled: () => {setConfirmationModalIsVisible(false);},- onError: revertOptimisticUpdate,+ onSuccess: invalidateSecrets,+ onError: invalidateSecrets,});};@@ -88,10 +106,14 @@ function SecretsSettingsScreen() {</BrandButton>)}- {view === "list" && (- <div className="border border-tertiary rounded-md overflow-hidden">+ {view === "list" && !isLoadingSecrets && (+ <div+ ref={tableContainerRef}+ className="border border-tertiary rounded-md overflow-auto max-h-[60vh]"+ onScroll={handleScroll}+ ><table className="w-full min-w-full table-fixed">- <thead className="bg-base-tertiary">+ <thead className="bg-base-tertiary sticky top-0"><tr><th className="w-1/4 text-left p-3 text-sm font-medium">{t(I18nKey.SETTINGS$NAME)}@@ -122,6 +144,13 @@ function SecretsSettingsScreen() {))}</tbody></table>++ {/* Loading indicator for infinite scroll */}+ {isFetchingNextPage && (+ <div className="flex justify-center p-4">+ <LoadingSpinner size="small" />+ </div>+ )}</div>)}diff --git a/openhands/app_server/secrets/secrets_models.py b/openhands/app_server/secrets/secrets_models.pynew file mode 100644index 0000000000..fd383dcb8f--- /dev/null+++ b/openhands/app_server/secrets/secrets_models.py@@ -0,0 +1,23 @@+"""Models for the secrets API."""++from pydantic import BaseModel, SecretStr+++class CustomSecretWithoutValue(BaseModel):+ """Custom secret model without value (for listing secrets)."""++ name: str+ description: str | None = None+++class CustomSecretCreate(CustomSecretWithoutValue):+ """Custom secret model with value (for creating secrets)."""++ value: SecretStr+++class CustomSecretPage(BaseModel):+ """Paginated response for custom secrets search."""++ items: list[CustomSecretWithoutValue]+ next_page_id: str | None = Nonediff --git a/openhands/app_server/secrets/secrets_router.py b/openhands/app_server/secrets/secrets_router.pyindex 0da621deb9..97269b7f49 100644--- a/openhands/app_server/secrets/secrets_router.py+++ b/openhands/app_server/secrets/secrets_router.py@@ -3,9 +3,16 @@This module provides the V1 API routes for secrets under /api/v1/secrets."""-from fastapi import APIRouter, Depends, HTTPException, status+from typing import Annotated++from fastapi import APIRouter, Depends, HTTPException, Query, statusfrom openhands.app_server.errors import AuthError+from openhands.app_server.secrets.secrets_models import (+ CustomSecretCreate,+ CustomSecretPage,+ CustomSecretWithoutValue,+)from openhands.app_server.utils.dependencies import get_dependenciesfrom openhands.app_server.utils.models import EditResponsefrom openhands.integrations.provider import (@@ -15,9 +22,6 @@ from openhands.integrations.provider import ()from openhands.integrations.utils import validate_provider_tokenfrom openhands.server.settings import (- CustomSecretModel,- CustomSecretWithoutValueModel,- GETCustomSecrets,POSTProviderModel,)from openhands.server.user_auth import (@@ -162,35 +166,73 @@ async def unset_provider_tokens(# =================================================[email protected]('', response_model=GETCustomSecrets)-async def load_custom_secrets_names([email protected]('/search')+async def search_custom_secrets(+ name__contains: Annotated[+ str | None,+ Query(title='Filter by name containing this string'),+ ] = None,+ page_id: Annotated[+ str | None,+ Query(title='Optional next_page_id from the previously returned page'),+ ] = None,+ limit: Annotated[+ int,+ Query(+ title='The max number of results in the page',+ gt=0,+ le=100,+ ),+ ] = 100,user_secrets: Secrets | None = Depends(get_secrets),-) -> GETCustomSecrets:- """Load custom secret names.+) -> CustomSecretPage:+ """Search / List custom secrets.- Retrieves the names and descriptions of all custom secrets for the authenticated user.+ Retrieves the names and descriptions of custom secrets for the authenticated user.+ Results are paginated and can be filtered by name.Returns:- GETCustomSecrets: List of custom secrets (without values)+ CustomSecretPage: Paginated list of custom secrets (without values)"""- if not user_secrets:- return GETCustomSecrets(custom_secrets=[])-- custom_secrets: list[CustomSecretWithoutValueModel] = []- if user_secrets.custom_secrets:- for secret_name, secret_value in user_secrets.custom_secrets.items():- custom_secret = CustomSecretWithoutValueModel(+ if not user_secrets or not user_secrets.custom_secrets:+ return CustomSecretPage(items=[], next_page_id=None)++ # Build list of all secrets, optionally filtered by name+ all_secrets: list[CustomSecretWithoutValue] = []+ for secret_name, secret_value in sorted(user_secrets.custom_secrets.items()):+ if name__contains and name__contains.lower() not in secret_name.lower():+ continue+ all_secrets.append(+ CustomSecretWithoutValue(name=secret_name,description=secret_value.description,)- custom_secrets.append(custom_secret)+ )++ # Apply pagination+ start_index = 0+ if page_id:+ # Find the index after the page_id secret+ for i, secret in enumerate(all_secrets):+ if secret.name == page_id:+ start_index = i + 1+ break++ # Get the page of results+ end_index = start_index + limit+ page_items = all_secrets[start_index:end_index]++ # Determine next_page_id+ next_page_id = None+ if end_index < len(all_secrets):+ next_page_id = page_items[-1].name if page_items else None- return GETCustomSecrets(custom_secrets=custom_secrets)+ return CustomSecretPage(items=page_items, next_page_id=next_page_id)@router.post('', status_code=status.HTTP_201_CREATED)async def create_custom_secret(- incoming_secret: CustomSecretModel,+ incoming_secret: CustomSecretCreate,secrets_store: SecretsStore = Depends(get_secrets_store),) -> EditResponse:"""Create a custom secret.@@ -236,7 +278,7 @@ async def create_custom_secret(@router.put('/{secret_id}')async def update_custom_secret(secret_id: str,- incoming_secret: CustomSecretWithoutValueModel,+ incoming_secret: CustomSecretWithoutValue,secrets_store: SecretsStore = Depends(get_secrets_store),) -> EditResponse:"""Update a custom secret.diff --git a/openhands/server/routes/secrets.py b/openhands/server/routes/secrets.pyindex a2cc0a34d8..3d55ae51c7 100644--- a/openhands/server/routes/secrets.py+++ b/openhands/server/routes/secrets.py@@ -14,9 +14,7 @@ from openhands.app_server.secrets.secrets_router import (from openhands.app_server.secrets.secrets_router import (delete_custom_secret as v1_delete_custom_secret,)-from openhands.app_server.secrets.secrets_router import (- load_custom_secrets_names as v1_load_custom_secrets_names,-)+from openhands.app_server.secrets.secrets_router import search_custom_secretsfrom openhands.app_server.secrets.secrets_router import (store_provider_tokens as v1_store_provider_tokens,)@@ -29,6 +27,7 @@ from openhands.app_server.secrets.secrets_router import (from openhands.app_server.utils.dependencies import get_dependenciesfrom openhands.app_server.utils.models import EditResponsefrom openhands.integrations.provider import PROVIDER_TOKEN_TYPE+from openhands.sdk.utils.paging import page_iteratorfrom openhands.server.settings import (CustomSecretModel,CustomSecretWithoutValueModel,@@ -81,6 +80,12 @@ async def store_provider_tokens(secrets_store: SecretsStore = Depends(get_secrets_store),provider_tokens: PROVIDER_TOKEN_TYPE | None = Depends(get_provider_tokens),) -> EditResponse:+ """Store git provider tokens.++ .. deprecated::+ Use ``POST /api/v1/secrets/git-providers`` instead. This V0 endpoint will be removed+ April 1, 2026.+ """return await v1_store_provider_tokens(provider_info, secrets_store, provider_tokens)@@ -88,6 +93,12 @@ async def store_provider_tokens(async def unset_provider_tokens(secrets_store: SecretsStore = Depends(get_secrets_store),) -> EditResponse:+ """Unset (delete) all git provider tokens.++ .. deprecated::+ Use ``DELETE /api/v1/secrets/git-providers`` instead. This V0 endpoint will be removed+ April 1, 2026.+ """return await v1_unset_provider_tokens(secrets_store)@@ -100,7 +111,23 @@ async def unset_provider_tokens(async def load_custom_secrets_names(user_secrets: Secrets | None = Depends(get_secrets),) -> GETCustomSecrets:- return await v1_load_custom_secrets_names(user_secrets)+ """Load custom secret names.++ .. deprecated::+ Use ``GET /api/v1/secrets/search`` instead. This V0 endpoint will be removed+ April 1, 2026. The V1 endpoint provides pagination and filtering support.+ """+ custom_secrets = []+ async for custom_secret in page_iterator(+ search_custom_secrets, user_secrets=user_secrets+ ):+ custom_secrets.append(+ CustomSecretWithoutValueModel(+ name=custom_secret.name, description=custom_secret.description+ )+ )+ result = GETCustomSecrets(custom_secrets=custom_secrets)+ return result@app.post('/secrets', status_code=status.HTTP_201_CREATED, deprecated=True)@@ -108,6 +135,12 @@ async def create_custom_secret(incoming_secret: CustomSecretModel,secrets_store: SecretsStore = Depends(get_secrets_store),) -> EditResponse:+ """Create a custom secret.++ .. deprecated::+ Use ``POST /api/v1/secrets`` instead. This V0 endpoint will be removed+ April 1, 2026.+ """return await v1_create_custom_secret(incoming_secret, secrets_store)@@ -117,6 +150,12 @@ async def update_custom_secret(incoming_secret: CustomSecretWithoutValueModel,secrets_store: SecretsStore = Depends(get_secrets_store),) -> EditResponse:+ """Update a custom secret.++ .. deprecated::+ Use ``PUT /api/v1/secrets/{secret_id}`` instead. This V0 endpoint will be removed+ April 1, 2026.+ """return await v1_update_custom_secret(secret_id, incoming_secret, secrets_store)@@ -125,4 +164,10 @@ async def delete_custom_secret(secret_id: str,secrets_store: SecretsStore = Depends(get_secrets_store),) -> EditResponse:+ """Delete a custom secret.++ .. deprecated::+ Use ``DELETE /api/v1/secrets/{secret_id}`` instead. This V0 endpoint will be removed+ April 1, 2026.+ """return await v1_delete_custom_secret(secret_id, secrets_store)diff --git a/tests/unit/app_server/test_secrets_api.py b/tests/unit/app_server/test_secrets_api.pyindex 40e5800cf3..401a4114ff 100644--- a/tests/unit/app_server/test_secrets_api.py+++ b/tests/unit/app_server/test_secrets_api.py@@ -52,8 +52,8 @@ def file_secrets_store(temp_dir):@pytest.mark.asyncio-async def test_load_custom_secrets_names(test_client, file_secrets_store):- """Test loading custom secrets names."""+async def test_search_custom_secrets(test_client, file_secrets_store):+ """Test searching custom secrets."""# Create initial settings with custom secretscustom_secrets = {'API_KEY': CustomSecret(secret=SecretStr('api-key-value')),@@ -70,16 +70,18 @@ async def test_load_custom_secrets_names(test_client, file_secrets_store):await file_secrets_store.store(user_secrets)# Make the GET request- response = test_client.get('/secrets')+ response = test_client.get('/secrets/search')print(response)assert response.status_code == 200# Check the responsedata = response.json()- assert 'custom_secrets' in data+ assert 'items' in data# Extract just the names from the list of custom secrets- secret_names = [secret['name'] for secret in data['custom_secrets']]+ secret_names = [secret['name'] for secret in data['items']]assert sorted(secret_names) == ['API_KEY', 'DB_PASSWORD']+ # Verify pagination field exists+ assert 'next_page_id' in data# Verify that the original settings were not modifiedstored_settings = await file_secrets_store.load()@@ -95,8 +97,8 @@ async def test_load_custom_secrets_names(test_client, file_secrets_store):@pytest.mark.asyncio-async def test_load_custom_secrets_names_empty(test_client, file_secrets_store):- """Test loading custom secrets names when there are no custom secrets."""+async def test_search_custom_secrets_empty(test_client, file_secrets_store):+ """Test searching custom secrets when there are no custom secrets."""# Create initial settings with no custom secretsprovider_tokens = {ProviderType.GITHUB: ProviderToken(token=SecretStr('github-token'))@@ -107,13 +109,79 @@ async def test_load_custom_secrets_names_empty(test_client, file_secrets_store):await file_secrets_store.store(user_secrets)# Make the GET request- response = test_client.get('/secrets')+ response = test_client.get('/secrets/search')assert response.status_code == 200# Check the responsedata = response.json()- assert 'custom_secrets' in data- assert data['custom_secrets'] == []+ assert 'items' in data+ assert data['items'] == []+ assert data['next_page_id'] is None+++async def test_search_custom_secrets_with_filter(test_client, file_secrets_store):+ """Test searching custom secrets with name filter."""+ # Create initial settings with custom secrets+ custom_secrets = {+ 'API_KEY': CustomSecret(secret=SecretStr('api-key-value')),+ 'DB_PASSWORD': CustomSecret(secret=SecretStr('db-password-value')),+ 'DB_USER': CustomSecret(secret=SecretStr('db-user-value')),+ }+ user_secrets = Secrets(custom_secrets=custom_secrets)++ # Store the initial settings+ await file_secrets_store.store(user_secrets)++ # Make the GET request with filter+ response = test_client.get('/secrets/search', params={'name__contains': 'DB'})+ assert response.status_code == 200++ # Check the response+ data = response.json()+ assert 'items' in data+ secret_names = [secret['name'] for secret in data['items']]+ assert sorted(secret_names) == ['DB_PASSWORD', 'DB_USER']+++async def test_search_custom_secrets_pagination(test_client, file_secrets_store):+ """Test searching custom secrets with pagination."""+ # Create initial settings with many custom secrets+ custom_secrets = {+ f'SECRET_{i:02d}': CustomSecret(secret=SecretStr(f'value-{i}'))+ for i in range(5)+ }+ user_secrets = Secrets(custom_secrets=custom_secrets)++ # Store the initial settings+ await file_secrets_store.store(user_secrets)++ # Make the first GET request with limit+ response = test_client.get('/secrets/search', params={'limit': 2})+ assert response.status_code == 200++ # Check the response+ data = response.json()+ assert 'items' in data+ assert len(data['items']) == 2+ # Results should be sorted alphabetically+ assert data['items'][0]['name'] == 'SECRET_00'+ assert data['items'][1]['name'] == 'SECRET_01'+ # Since there are more items, next_page_id should be set+ assert data['next_page_id'] == 'SECRET_01'++ # Make the second GET request with page_id+ response = test_client.get(+ '/secrets/search', params={'limit': 2, 'page_id': data['next_page_id']}+ )+ assert response.status_code == 200++ # Check the response+ data = response.json()+ assert len(data['items']) == 2+ assert data['items'][0]['name'] == 'SECRET_02'+ assert data['items'][1]['name'] == 'SECRET_03'@pytest.mark.asyncio