Skip to content

πŸ™Œ OpenHands: AI-Driven Development

chore: remove dead OSS-cleanup leftovers (~560 LoC) (#290)

Robert Brennan860309f45750
diff --git a/AGENTS.md b/AGENTS.md
index 6b0a4292bb..5fc675707e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -5,7 +5,7 @@
- `option-service` fabricates an OSS web-client config and reads models/providers from `agent_server` LLM endpoints.
- `settings-service` uses agent server `/api/settings` endpoints for persistence; reads schemas from `/api/settings/agent-schema` and `/api/settings/conversation-schema`, fetches settings with optional `X-Expose-Secrets: encrypted` header for conversation start payloads, and saves settings via PATCH with diffs.
- `agent-server-conversation-service`, `event-service`, `agent-server-git-service`, and `skills-service` are mapped directly to `agent_server` REST endpoints.
- - `open-hands-axios` injects the optional `X-Session-API-Key` from env/local config for all requests.
+ - Shared REST calls should use `createHttpClient()` / typed adapters from `src/api/typescript-client.ts`, which handle backend URL and optional `X-Session-API-Key` resolution.
- Supported env vars for deployment:
- `VITE_BACKEND_BASE_URL` for the agent server base URL.
- `VITE_SESSION_API_KEY` for optional session auth.
@@ -30,7 +30,7 @@
- `__tests__/i18n/library-namespace.test.ts` imports the full library entry and can exceed Vitest's default 5s timeout under full-suite load; keep an explicit higher timeout on that case unless the test is substantially narrowed.
- `@openhands/typescript-client` is consumed directly from `github:OpenHands/typescript-client#6b9603f`; that package ships the needed subpath exports for `client/http-client`, `events/remote-events-list`, and `workspace/remote-workspace`. `RemoteWorkspace.gitChanges`/`gitDiff` accept an optional `{ ref }` option; agent-canvas passes `'HEAD'` so the changes panel reflects working-tree + index versus the latest commit (i.e. staged + unstaged) instead of a diff against the upstream/default branch.
-- Shared TypeScript-client adapters live in `src/api/typescript-client.ts`; prefer those helpers for agent-server-backed REST/workspace/event/VS Code calls before falling back to `open-hands-axios`.
+- Shared TypeScript-client adapters live in `src/api/typescript-client.ts`; prefer those helpers for agent-server-backed REST/workspace/event/VS Code calls instead of adding new bespoke axios clients.
- Local verification/build gotchas:
- `npm run typecheck` assumes generated translation types exist; run `npm run make-i18n` first if `src/i18n/declaration.ts` is missing.
- Merge note: `main` removed the old project-management integration subcomponents/hooks and their related feature-flag/i18n surface. If a feature branch still keeps the top-level `/integrations` git-token page, retain `src/routes/git-settings.tsx` plus the git-provider token inputs/hooks, but do **not** blindly restore `src/components/features/settings/project-management/*` or the old integration mutation/query hooks unless the corresponding option types and i18n keys are also reintroduced.
diff --git a/__tests__/api/open-hands-axios-active-backend.test.ts b/__tests__/api/open-hands-axios-active-backend.test.ts
deleted file mode 100644
index 196283c1a8..0000000000
--- a/__tests__/api/open-hands-axios-active-backend.test.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
-import { openHands } from "#/api/open-hands-axios";
-import {
- __resetActiveStoreForTests,
- setActiveSelection,
- setRegisteredBackends,
-} from "#/api/backend-registry/active-store";
-import type { Backend } from "#/api/backend-registry/types";
-
-const localBackend: Backend = {
- id: "local-1",
- name: "Local 1",
- host: "http://localhost:9099",
- apiKey: "session-key-local",
- kind: "local",
-};
-
-const cloudBackend: Backend = {
- id: "prod",
- name: "Production",
- host: "https://app.all-hands.dev",
- apiKey: "bearer-token-cloud",
- kind: "cloud",
-};
-
-beforeEach(() => {
- window.localStorage.clear();
- __resetActiveStoreForTests();
-});
-
-afterEach(() => {
- window.localStorage.clear();
- __resetActiveStoreForTests();
-});
-
-async function runInterceptors() {
- const { AxiosHeaders } = await import("axios");
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const config: any = { headers: new AxiosHeaders({}) };
-
- // Walk the registered request handlers; axios stores them as
- // { fulfilled, rejected } objects on the manager.
- const { handlers } = openHands.interceptors.request as unknown as {
- handlers: Array<{
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- fulfilled: (c: any) => any;
- } | null>;
- };
- let next = config;
- for (const handler of handlers) {
- if (handler && typeof handler.fulfilled === "function") {
- // Interceptors are an explicit chain β€” each input depends on the prior
- // output, so awaiting in order is correct here.
- // eslint-disable-next-line no-await-in-loop
- next = await handler.fulfilled(next);
- }
- }
- return next;
-}
-
-describe("openHands axios β€” active backend interceptor", () => {
- it("rewrites baseURL + sends X-Session-API-Key for a local backend", async () => {
- setRegisteredBackends([localBackend]);
- setActiveSelection({ backendId: localBackend.id });
-
- const config = await runInterceptors();
-
- expect(config.baseURL).toBe(localBackend.host);
- expect(config.headers.get("X-Session-API-Key")).toBe(localBackend.apiKey);
- expect(config.headers.get("Authorization")).toBeFalsy();
- });
-
- it("falls back to the bundled local backend when active is cloud (cloud calls go via callCloudProxy)", async () => {
- setRegisteredBackends([cloudBackend]);
- setActiveSelection({ backendId: cloudBackend.id });
-
- const config = await runInterceptors();
-
- // Must NOT route default openHands traffic to the cloud host β€” those
- // endpoints don't exist on the SaaS and would CORS-fail. Cloud-only
- // calls use callCloudProxy directly and bypass this interceptor.
- expect(config.baseURL).not.toBe(cloudBackend.host);
- expect(config.baseURL).not.toContain("all-hands.dev");
- expect(config.headers.get("Authorization")).toBeFalsy();
- });
-});
diff --git a/__tests__/api/open-hands-axios.test.ts b/__tests__/api/open-hands-axios.test.ts
deleted file mode 100644
index da0dce52c2..0000000000
--- a/__tests__/api/open-hands-axios.test.ts
+++ /dev/null
@@ -1,20 +0,0 @@
-import { describe, expect, it } from "vitest";
-import { openHands } from "#/api/open-hands-axios";
-
-describe("openHands axios client", () => {
- it("serializes array query params without bracket suffixes", () => {
- const uri = openHands.getUri({
- url: "/api/conversations",
- params: {
- ids: ["conversation-1", "conversation-2"],
- limit: 10,
- },
- });
-
- expect(uri).toContain("/api/conversations?");
- expect(uri).toContain("ids=conversation-1");
- expect(uri).toContain("ids=conversation-2");
- expect(uri).toContain("limit=10");
- expect(uri).not.toContain("ids%5B%5D=");
- });
-});
diff --git a/__tests__/hooks/query/use-conversation-history.test.tsx b/__tests__/hooks/query/use-conversation-history.test.tsx
index 0b238a719d..11547a673e 100644
--- a/__tests__/hooks/query/use-conversation-history.test.tsx
+++ b/__tests__/hooks/query/use-conversation-history.test.tsx
@@ -44,12 +44,6 @@ function makePage(
// --------------------
// Mocks
// --------------------
-vi.mock("#/api/open-hands-axios", () => ({
- openHands: {
- get: vi.fn(),
- },
-}));
-
vi.mock("#/api/event-service/event-service.api");
vi.mock("#/hooks/query/use-user-conversation");
diff --git a/__tests__/hooks/use-load-older-events.test.tsx b/__tests__/hooks/use-load-older-events.test.tsx
index 21a423dcf5..953b132d1f 100644
--- a/__tests__/hooks/use-load-older-events.test.tsx
+++ b/__tests__/hooks/use-load-older-events.test.tsx
@@ -12,7 +12,6 @@ import type { Conversation } from "#/api/open-hands.types";
import type { OpenHandsEvent } from "#/types/agent-server/core";
import type { EventSearchPage } from "#/api/event-service/event-service.types";
-vi.mock("#/api/open-hands-axios", () => ({ openHands: { get: vi.fn() } }));
vi.mock("#/api/event-service/event-service.api");
vi.mock("#/hooks/query/use-user-conversation");
diff --git a/src/api/README.md b/src/api/README.md
index 1337c5a1f1..08cfd983d4 100644
--- a/src/api/README.md
+++ b/src/api/README.md
@@ -2,7 +2,7 @@
## Overview
-Services are the abstraction layer between frontend components and backend APIs. They encapsulate HTTP requests using the shared `openHands` axios instance and provide typed methods for each endpoint.
+Services are the abstraction layer between frontend components and backend APIs. They encapsulate HTTP requests using `createHttpClient()` from `@openhands/typescript-client` (wrapped in `src/api/typescript-client.ts`, which resolves the active backend's host + `X-Session-API-Key`) and provide typed methods for each endpoint.
Each service is a plain object with async methods.
@@ -15,7 +15,7 @@ src/api/
β”œβ”€β”€ feature-service/
β”‚ β”œβ”€β”€ feature-service.api.ts # Service methods
β”‚ └── feature.types.ts # Types and interfaces
-└── open-hands-axios.ts # Shared axios instance
+└── typescript-client.ts # `createHttpClient` + typed SDK clients
```
## Creating a Service
@@ -24,21 +24,23 @@ Use an object literal with named export. Use object destructuring for parameters
```typescript
// feature-service/feature-service.api.ts
-import { openHands } from "../open-hands-axios";
+import { createHttpClient } from "../typescript-client";
import { Feature, CreateFeatureParams } from "./feature.types";
export const featureService = {
getFeature: async ({ id }: { id: string }) => {
- const { data } = await openHands.get<Feature>(`/api/features/${id}`);
- return data;
+ const response = await createHttpClient().get<Feature>(
+ `/api/features/${id}`,
+ );
+ return response.data;
},
createFeature: async ({ name, description }: CreateFeatureParams) => {
- const { data } = await openHands.post<Feature>("/api/features", {
+ const response = await createHttpClient().post<Feature>("/api/features", {
name,
description,
});
- return data;
+ return response.data;
},
};
```
diff --git a/src/api/api-keys.ts b/src/api/api-keys.ts
deleted file mode 100644
index cfcad2fede..0000000000
--- a/src/api/api-keys.ts
+++ /dev/null
@@ -1,49 +0,0 @@
-import { openHands } from "./open-hands-axios";
-
-export interface ApiKey {
- id: string;
- name: string;
- prefix: string;
- created_at: string;
- last_used_at: string | null;
-}
-
-export interface CreateApiKeyResponse {
- id: string;
- name: string;
- key: string; // Full key, only returned once upon creation
- prefix: string;
- created_at: string;
-}
-
-class ApiKeysClient {
- /**
- * Get all API keys for the current user
- */
- static async getApiKeys(): Promise<ApiKey[]> {
- const { data } = await openHands.get<unknown>("/api/keys");
- // Ensure we always return an array, even if the API returns something else
- return Array.isArray(data) ? (data as ApiKey[]) : [];
- }
-
- /**
- * Create a new API key
- * @param name - A descriptive name for the API key
- */
- static async createApiKey(name: string): Promise<CreateApiKeyResponse> {
- const { data } = await openHands.post<CreateApiKeyResponse>("/api/keys", {
- name,
- });
- return data;
- }
-
- /**
- * Delete an API key
- * @param id - The ID of the API key to delete
- */
- static async deleteApiKey(id: string): Promise<void> {
- await openHands.delete(`/api/keys/${id}`);
- }
-}
-
-export default ApiKeysClient;
diff --git a/src/api/automation-service/automation-service.api.ts b/src/api/automation-service/automation-service.api.ts
index fe27e82583..10e771e58b 100644
--- a/src/api/automation-service/automation-service.api.ts
+++ b/src/api/automation-service/automation-service.api.ts
@@ -21,7 +21,7 @@ export interface AutomationHealthResponse {
// `scripts/dev-with-automation.mjs` mounts behind the local agent-server.
// That sidecar authenticates via its own `VITE_AUTOMATION_API_KEY` Bearer
// token β€” NOT the agent-server's `X-Session-API-Key` β€” so we cannot reuse
-// the shared `openHands` axios for these calls.
+// the shared `createHttpClient()` instance for these calls.
const localAutomationAxios = axios.create();
localAutomationAxios.interceptors.request.use((config) => {
diff --git a/src/api/cloud/proxy.ts b/src/api/cloud/proxy.ts
index 0346c0475d..8ef6c29812 100644
--- a/src/api/cloud/proxy.ts
+++ b/src/api/cloud/proxy.ts
@@ -76,9 +76,10 @@ export async function callCloudProxy<TResponse = unknown>(
};
const upstreamHost = req.hostOverride ?? req.backend.host;
- // Talk directly to the local agent-server, bypassing the global
- // openHands axios interceptor (which would otherwise read host + auth
- // from the active backend β€” wrong for this call).
+ // Talk directly to the local agent-server, bypassing the shared
+ // `createHttpClient()` resolver (which would otherwise read host + auth
+ // from the active backend β€” wrong for this call: we need the local
+ // backend's host and session key explicitly, not the active one).
const response = await axios.post<TResponse>(
`${local.host.replace(/\/+$/, "")}/api/cloud-proxy`,
{
diff --git a/src/api/invariant-service.ts b/src/api/invariant-service.ts
deleted file mode 100644
index 324aa4ea86..0000000000
--- a/src/api/invariant-service.ts
+++ /dev/null
@@ -1,30 +0,0 @@
-import { openHands } from "./open-hands-axios";
-
-class InvariantService {
- static async getPolicy() {
- const { data } = await openHands.get("/api/security/policy");
- return data.policy;
- }
-
- static async getRiskSeverity() {
- const { data } = await openHands.get("/api/security/settings");
- return data.RISK_SEVERITY;
- }
-
- static async getTraces() {
- const { data } = await openHands.get("/api/security/export-trace");
- return data;
- }
-
- static async updatePolicy(policy: string) {
- await openHands.post("/api/security/policy", { policy });
- }
-
- static async updateRiskSeverity(riskSeverity: number) {
- await openHands.post("/api/security/settings", {
- RISK_SEVERITY: riskSeverity,
- });
- }
-}
-
-export default InvariantService;
diff --git a/src/api/open-hands-axios.ts b/src/api/open-hands-axios.ts
deleted file mode 100644
index 09bef75248..0000000000
--- a/src/api/open-hands-axios.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-import axios, {
- AxiosError,
- AxiosResponse,
- InternalAxiosRequestConfig,
-} from "axios";
-import {
- getActiveBackend,
- getEffectiveLocalBackend,
-} from "./backend-registry/active-store";
-import { buildAuthHeaders } from "./backend-registry/auth";
-
-function serializeParams(
- params: Record<string, unknown> | URLSearchParams,
-): string {
- if (params instanceof URLSearchParams) {
- return params.toString();
- }
-
- const searchParams = new URLSearchParams();
-
- Object.entries(params).forEach(([key, value]) => {
- if (value === undefined || value === null) {
- return;
- }
-
- if (Array.isArray(value)) {
- value.forEach((item) => {
- if (item !== undefined && item !== null) {
- searchParams.append(key, String(item));
- }
- });
- return;
- }
-
- searchParams.append(key, String(value));
- });
-
- return searchParams.toString();
-}
-
-export const openHands = axios.create({
- paramsSerializer: { serialize: serializeParams },
-});
-
-openHands.interceptors.request.use((config: InternalAxiosRequestConfig) => {
- // The default openHands axios speaks the *local agent-server's* protocol
- // (X-Session-API-Key auth, /api/* paths). When the active backend is
- // cloud, fall back to the first registered local backend β€” cloud-
- // specific calls go through `callCloudProxy` (which uses axios directly)
- // and never hit this interceptor.
- const active = getActiveBackend().backend;
- const backend = active.kind === "cloud" ? getEffectiveLocalBackend() : active;
-
- // Mutating the per-request config is the canonical axios interceptor pattern.
- // eslint-disable-next-line no-param-reassign
- if (!config.baseURL) config.baseURL = backend.host;
-
- const headers = buildAuthHeaders(backend);
- Object.entries(headers).forEach(([key, value]) => {
- config.headers.set(key, value);
- });
- return config;
-});
-
-// Helper function to check if a response contains an email verification error
-// eslint-disable-next-line @typescript-eslint/no-explicit-any
-const checkForEmailVerificationError = (data: any): boolean => {
- const EMAIL_NOT_VERIFIED = "EmailNotVerifiedError";
-
- if (typeof data === "string") {
- return data.includes(EMAIL_NOT_VERIFIED);
- }
-
- if (typeof data === "object" && data !== null) {
- if ("message" in data) {
- const { message } = data;
- if (typeof message === "string") {
- return message.includes(EMAIL_NOT_VERIFIED);
- }
- if (Array.isArray(message)) {
- return message.some(
- (msg) => typeof msg === "string" && msg.includes(EMAIL_NOT_VERIFIED),
- );
- }
- }
-
- return Object.values(data).some(
- (value) =>
- (typeof value === "string" && value.includes(EMAIL_NOT_VERIFIED)) ||
- (Array.isArray(value) &&
- value.some(
- (v) => typeof v === "string" && v.includes(EMAIL_NOT_VERIFIED),
- )),
- );
- }
-
- return false;
-};
-
-openHands.interceptors.response.use(
- (response: AxiosResponse) => response,
- (error: AxiosError) => {
- if (
- error.response?.status === 403 &&
- checkForEmailVerificationError(error.response?.data)
- ) {
- if (window.location.pathname !== "/settings/user") {
- window.location.reload();
- }
- }
-
- return Promise.reject(error);
- },
-);
diff --git a/src/components/features/settings/api-key-modal-base.tsx b/src/components/features/settings/api-key-modal-base.tsx
deleted file mode 100644
index 43d8ba89f0..0000000000
--- a/src/components/features/settings/api-key-modal-base.tsx
+++ /dev/null
@@ -1,33 +0,0 @@
-import React, { ReactNode } from "react";
-import { ModalBackdrop } from "#/components/shared/modals/modal-backdrop";
-
-interface ApiKeyModalBaseProps {
- isOpen: boolean;
- title: string;
- width?: string;
- children: ReactNode;
- footer: ReactNode;
-}
-
-export function ApiKeyModalBase({
- isOpen,
- title,
- width = "500px",
- children,
- footer,
-}: ApiKeyModalBaseProps) {
- if (!isOpen) return null;
-
- return (
- <ModalBackdrop>
- <div
- className="bg-base-secondary p-6 rounded-xl flex flex-col gap-4 border border-tertiary"
- style={{ width }}
- >
- <h3 className="text-xl font-bold">{title}</h3>
- {children}
- <div className="w-full flex gap-2 mt-2">{footer}</div>
- </div>
- </ModalBackdrop>
- );
-}
diff --git a/src/components/features/settings/new-api-key-modal.tsx b/src/components/features/settings/new-api-key-modal.tsx
deleted file mode 100644
index d3e527a6ff..0000000000
--- a/src/components/features/settings/new-api-key-modal.tsx
+++ /dev/null
@@ -1,61 +0,0 @@
-import React from "react";
-import { useTranslation } from "react-i18next";
-import { I18nKey } from "#/i18n/declaration";
-import { BrandButton } from "#/components/features/settings/brand-button";
-import { CreateApiKeyResponse } from "#/api/api-keys";
-import { displaySuccessToast } from "#/utils/custom-toast-handlers";
-import { ApiKeyModalBase } from "./api-key-modal-base";
-
-interface NewApiKeyModalProps {
- isOpen: boolean;
- newlyCreatedKey: CreateApiKeyResponse | null;
- onClose: () => void;
-}
-
-export function NewApiKeyModal({
- isOpen,
- newlyCreatedKey,
- onClose,
-}: NewApiKeyModalProps) {
- const { t } = useTranslation("openhands");
-
- const handleCopyToClipboard = () => {
- if (newlyCreatedKey) {
- navigator.clipboard.writeText(newlyCreatedKey.key);
- displaySuccessToast(t(I18nKey.SETTINGS$API_KEY_COPIED));
- }
- };
-
- if (!newlyCreatedKey) return null;
-
- const modalFooter = (
- <>
- <BrandButton
- type="button"
- variant="primary"
- onClick={handleCopyToClipboard}
- >
- {t(I18nKey.BUTTON$COPY_TO_CLIPBOARD)}
- </BrandButton>
- <BrandButton type="button" variant="secondary" onClick={onClose}>
- {t(I18nKey.BUTTON$CLOSE)}
- </BrandButton>
- </>
- );
-
- return (
- <ApiKeyModalBase
- isOpen={isOpen && !!newlyCreatedKey}
- title={t(I18nKey.SETTINGS$API_KEY_CREATED)}
- width="600px"
- footer={modalFooter}
- >
- <div data-testid="new-api-key-modal">
- <p className="text-sm">{t(I18nKey.SETTINGS$API_KEY_WARNING)}</p>
- <div className="bg-base-tertiary p-4 rounded-md font-mono text-sm break-all mt-4">
- {newlyCreatedKey.key}
- </div>
- </div>
- </ApiKeyModalBase>
- );
-}
diff --git a/src/hooks/mutation/use-accept-tos.ts b/src/hooks/mutation/use-accept-tos.ts
deleted file mode 100644
index a159b1458c..0000000000
--- a/src/hooks/mutation/use-accept-tos.ts
+++ /dev/null
@@ -1,54 +0,0 @@
-import { useMutation } from "@tanstack/react-query";
-import { usePostHog } from "posthog-js/react";
-import { useNavigate } from "react-router";
-import { openHands } from "#/api/open-hands-axios";
-import { handleCaptureConsent } from "#/utils/handle-capture-consent";
-import { useTracking } from "#/hooks/use-tracking";
-
-interface AcceptTosVariables {
- redirectUrl: string;
-}
-
-interface AcceptTosResponse {
- redirect_url?: string;
-}
-
-export const useAcceptTos = () => {
- const posthog = usePostHog();
- const navigate = useNavigate();
- const { trackUserSignupCompleted } = useTracking();
-
- return useMutation({
- mutationFn: async ({ redirectUrl }: AcceptTosVariables) => {
- // Set consent for analytics
- handleCaptureConsent(posthog, true);
-
- // Call the API to record TOS acceptance in the database
- return openHands.post<AcceptTosResponse>("/api/accept_tos", {
- redirect_url: redirectUrl,
- });
- },
- onSuccess: (response, { redirectUrl }) => {
- // Track user signup completion
- trackUserSignupCompleted();
-
- // Get the redirect URL from the response
- const finalRedirectUrl = response.data.redirect_url || redirectUrl;
-
- // Check if the redirect URL is an external URL (starts with http or https)
- if (
- finalRedirectUrl.startsWith("http://") ||
- finalRedirectUrl.startsWith("https://")
- ) {
- // For external URLs, redirect using window.location
- window.location.href = finalRedirectUrl;
- } else {
- // For internal routes, use navigate
- navigate(finalRedirectUrl);
- }
- },
- onError: () => {
- window.location.href = "/";
- },
- });
-};
diff --git a/src/hooks/mutation/use-logout.ts b/src/hooks/mutation/use-logout.ts
deleted file mode 100644
index b507ee9628..0000000000
--- a/src/hooks/mutation/use-logout.ts
+++ /dev/null
@@ -1,23 +0,0 @@
-import { useMutation, useQueryClient } from "@tanstack/react-query";
-import { usePostHog } from "posthog-js/react";
-import { openHands } from "#/api/open-hands-axios";
-import { SETTINGS_QUERY_KEYS } from "#/hooks/query/query-keys";
-
-export const useLogout = () => {
- const posthog = usePostHog();
- const queryClient = useQueryClient();
-
- return useMutation({
- mutationFn: async () => {
- await openHands.post("/api/unset-provider-tokens");
- },
- onSuccess: async () => {
- queryClient.removeQueries({ queryKey: ["tasks"] });
- queryClient.removeQueries({ queryKey: SETTINGS_QUERY_KEYS.all });
- queryClient.removeQueries({ queryKey: ["user"] });
- queryClient.removeQueries({ queryKey: ["secrets"] });
- posthog.reset();
- window.location.reload();
- },
- });
-};
diff --git a/src/mocks/api-keys-handlers.ts b/src/mocks/api-keys-handlers.ts
deleted file mode 100644
index 2227ea9166..0000000000
--- a/src/mocks/api-keys-handlers.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-import { http, HttpResponse } from "msw";
-import { ApiKey, CreateApiKeyResponse } from "#/api/api-keys";
-
-let nextId = 2;
-
-const DEFAULT_API_KEYS: ApiKey[] = [
- {
- id: "1",
- name: "My Dev Key",
- prefix: "oh_dev_",
- created_at: "2025-12-01T10:00:00Z",
- last_used_at: "2026-02-18T14:30:00Z",
- },
- {
- id: "2",
- name: "CI/CD Pipeline",
- prefix: "oh_ci_",
- created_at: "2026-01-15T08:00:00Z",
- last_used_at: null,
- },
-];
-
-const apiKeys = new Map<string, ApiKey>(
- DEFAULT_API_KEYS.map((key) => [key.id, key]),
-);
-
-export const API_KEYS_HANDLERS = [
- // GET /api/keys - List all API keys
- http.get("*/api/keys", () => HttpResponse.json(Array.from(apiKeys.values()))),
-
- // POST /api/keys - Create a new API key
- http.post("*/api/keys", async ({ request }) => {
- const body = (await request.json()) as { name: string };
-
- if (!body?.name?.trim()) {
- return HttpResponse.json({ error: "Name is required" }, { status: 400 });
- }
-
- nextId += 1;
- const id = String(nextId);
- const newKey: ApiKey = {
- id,
- name: body.name,
- prefix: `oh_${id}_`,
- created_at: new Date().toISOString(),
- last_used_at: null,
- };
- apiKeys.set(id, newKey);
-
- const response: CreateApiKeyResponse = {
- id: newKey.id,
- name: newKey.name,
- key: `oh_${id}_sk_mock_${Math.random().toString(36).slice(2, 14)}`,
- prefix: newKey.prefix,
- created_at: newKey.created_at,
- };
-
- return HttpResponse.json(response);
- }),
-
- // DELETE /api/keys/:id - Delete an API key
- http.delete("*/api/keys/:id", ({ params }) => {
- const { id } = params;
-
- if (typeof id === "string" && apiKeys.has(id)) {
- apiKeys.delete(id);
- return HttpResponse.json({ success: true });
- }
-
- return HttpResponse.json({ error: "Key not found" }, { status: 404 });
- }),
-
- // GET /api/keys/llm/byor - Get LLM API key
- http.get("*/api/keys/llm/byor", () =>
- HttpResponse.json({
- key: "sk-mock-llm-api-key-1234567890abcdef",
- }),
- ),
-
- // POST /api/keys/llm/byor/refresh - Refresh LLM API key
- http.post("*/api/keys/llm/byor/refresh", () =>
- HttpResponse.json({
- key: `sk-mock-llm-refreshed-${Math.random().toString(36).slice(2, 14)}`,
- }),
- ),
-];
diff --git a/src/mocks/handlers.ts b/src/mocks/handlers.ts
index f5f9c5f7c6..865343fa51 100644
--- a/src/mocks/handlers.ts
+++ b/src/mocks/handlers.ts
@@ -1,4 +1,3 @@
-import { API_KEYS_HANDLERS } from "./api-keys-handlers";
import { FILE_SERVICE_HANDLERS } from "./file-service-handlers";
import { TASK_SUGGESTIONS_HANDLERS } from "./task-suggestions-handlers";
import { SECRETS_HANDLERS } from "./secrets-handlers";
@@ -18,7 +17,6 @@ import {
} from "./automation-handlers";
export const handlers = [
- ...API_KEYS_HANDLERS,
...FILE_SERVICE_HANDLERS,
...TASK_SUGGESTIONS_HANDLERS,
...SECRETS_HANDLERS,