Skip to content

πŸ™Œ OpenHands: AI-Driven Development

fix(api): auto-load workspace hooks on conversation start (#16971)

aashikantkumar021206dc6a8e
diff --git a/__tests__/api/agent-server-adapter.test.ts b/__tests__/api/agent-server-adapter.test.ts
index aa43678562..e88144cca8 100644
--- a/__tests__/api/agent-server-adapter.test.ts
+++ b/__tests__/api/agent-server-adapter.test.ts
@@ -1,4 +1,5 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import type { MockInstance } from "vitest";
import { CANVAS_UI_CLIENT_TOOL_NAME } from "#/constants/canvas-ui";
import { LAUNCH_CHILD_CONVERSATION_TOOL_NAME } from "#/constants/child-conversation";
@@ -8,18 +9,24 @@ import {
CLIENT_SOURCE_TAG_KEY,
buildRuntimeServicesSystemSuffix,
buildStartConversationRequest,
+ buildStartConversationRequestWithEncryptedSettings,
fetchBackendRuntimeServicesInfo,
getDefaultConversationTitle,
parseRuntimeServicesInfo,
toAppConversation,
type DirectConversationInfo,
} from "#/api/agent-server-adapter";
+import SettingsService from "#/api/settings-service/settings-service.api";
+import { SecretsService } from "#/api/secrets-service";
import {
removeStoredConversationMetadata,
setStoredConversationMetadata,
} from "#/api/conversation-metadata-store";
+import { HookType } from "@openhands/typescript-client";
+import type { HookConfig } from "@openhands/typescript-client";
import { ACP_VERTEX_SAFE_MODEL } from "#/constants/acp-providers";
import { DEFAULT_SETTINGS } from "#/services/settings";
+import type { SettingsValue } from "#/types/settings";
import {
LLM_AUTH_TYPE_SUBSCRIPTION,
OPENAI_SUBSCRIPTION_VENDOR,
@@ -31,6 +38,8 @@ const {
mockGetEffectiveLocalBackend,
mockGetCachedAgentServerInfo,
mockGetServerInfo,
+ mockGetActiveBackend,
+ mockLoadHooks,
} = vi.hoisted(() => ({
mockGetAgentServerWorkingDir: vi.fn(() => "/workspace/project/agent-canvas"),
mockIsAgentServerToolAvailable: vi.fn((_toolName: string) => true),
@@ -43,6 +52,16 @@ const {
})),
mockGetCachedAgentServerInfo: vi.fn<() => unknown>(() => null),
mockGetServerInfo: vi.fn(),
+ mockGetActiveBackend: vi.fn(() => ({
+ backend: {
+ id: "default-local",
+ name: "Local backend",
+ host: "http://127.0.0.1:8000",
+ apiKey: "session-key",
+ kind: "local" as const,
+ },
+ })),
+ mockLoadHooks: vi.fn(),
}));
vi.mock("@openhands/typescript-client/clients", () => ({
@@ -51,6 +70,9 @@ vi.mock("@openhands/typescript-client/clients", () => ({
getServerInfo: mockGetServerInfo,
};
}),
+ HooksClient: vi.fn(function HooksClientMock() {
+ return { loadHooks: mockLoadHooks };
+ }),
}));
vi.mock("#/api/agent-server-config", () => ({
@@ -68,8 +90,39 @@ vi.mock("#/api/agent-server-compatibility", () => ({
vi.mock("#/api/backend-registry/active-store", () => ({
getEffectiveLocalBackend: mockGetEffectiveLocalBackend,
+ getActiveBackend: mockGetActiveBackend,
+ isNoBackend: (backend: { id: string }) => backend.id === "no-backend",
}));
+// `HookConfig` requires every event key, so build fixtures from a complete base.
+const makeHookConfig = (overrides: Partial<HookConfig> = {}): HookConfig => ({
+ pre_tool_use: [],
+ post_tool_use: [],
+ user_prompt_submit: [],
+ session_start: [],
+ session_end: [],
+ stop: [],
+ ...overrides,
+});
+
+const WORKSPACE_HOOK_CONFIG = makeHookConfig({
+ session_start: [
+ {
+ matcher: "*",
+ hooks: [{ command: "cat AGENTS.md", type: HookType.COMMAND }],
+ },
+ ],
+});
+
+const EXPLICIT_HOOK_CONFIG = makeHookConfig({
+ session_start: [
+ {
+ matcher: "*",
+ hooks: [{ command: "echo explicit", type: HookType.COMMAND }],
+ },
+ ],
+});
+
beforeEach(() => {
mockIsAgentServerToolAvailable.mockReturnValue(true);
mockGetCachedAgentServerInfo.mockReturnValue(null);
@@ -470,6 +523,30 @@ describe("buildStartConversationRequest", () => {
});
});
+ it("uses workspaceHookConfig when conversation_settings.hook_config is omitted", () => {
+ const payload = buildStartConversationRequest({
+ settings: DEFAULT_SETTINGS,
+ workspaceHookConfig: WORKSPACE_HOOK_CONFIG,
+ }) as Record<string, unknown>;
+
+ expect(payload.hook_config).toEqual(WORKSPACE_HOOK_CONFIG);
+ });
+
+ it("prioritizes conversation_settings.hook_config over workspaceHookConfig", () => {
+ const payload = buildStartConversationRequest({
+ settings: {
+ ...DEFAULT_SETTINGS,
+ conversation_settings: {
+ ...DEFAULT_SETTINGS.conversation_settings,
+ hook_config: EXPLICIT_HOOK_CONFIG as unknown as SettingsValue,
+ },
+ },
+ workspaceHookConfig: WORKSPACE_HOOK_CONFIG,
+ }) as Record<string, unknown>;
+
+ expect(payload.hook_config).toEqual(EXPLICIT_HOOK_CONFIG);
+ });
+
it("serializes custom secrets as host-relative LookupSecret entries", () => {
const payload = buildStartConversationRequest({
settings: {
@@ -1774,3 +1851,82 @@ describe("buildStartConversationRequest β€” ACP discriminator", () => {
expect(acpPayload.agent_settings.condenser).toBeUndefined();
});
});
+
+describe("buildStartConversationRequestWithEncryptedSettings", () => {
+ let settingsSpy: MockInstance;
+ let secretsSpy: MockInstance;
+
+ beforeEach(() => {
+ mockLoadHooks.mockReset();
+ // Stub only the collaborators; the hooks lookup is what's under test.
+ settingsSpy = vi
+ .spyOn(SettingsService, "getSettingsForConversation")
+ .mockResolvedValue({
+ agentSettings: (DEFAULT_SETTINGS.agent_settings ?? {}) as Record<
+ string,
+ SettingsValue
+ >,
+ conversationSettings: (DEFAULT_SETTINGS.conversation_settings ??
+ {}) as Record<string, SettingsValue>,
+ secretsEncrypted: true,
+ });
+ secretsSpy = vi.spyOn(SecretsService, "getSecrets").mockResolvedValue([]);
+ });
+
+ // vitest is not configured with `restoreMocks`, so restore explicitly.
+ afterEach(() => {
+ settingsSpy.mockRestore();
+ secretsSpy.mockRestore();
+ });
+
+ it("looks hooks up in hooksProjectDir, not the conversation working dir", async () => {
+ mockLoadHooks.mockResolvedValue({ hook_config: WORKSPACE_HOOK_CONFIG });
+
+ const payload = await buildStartConversationRequestWithEncryptedSettings({
+ settings: DEFAULT_SETTINGS,
+ workingDir: "/workspace/my-project/0f1e2d3c",
+ hooksProjectDir: "/workspace/my-project",
+ });
+
+ expect(mockLoadHooks).toHaveBeenCalledWith({
+ project_dir: "/workspace/my-project",
+ });
+ expect(payload.hook_config).toEqual(WORKSPACE_HOOK_CONFIG);
+ });
+
+ it("falls back to the configured working dir when no hooksProjectDir is given", async () => {
+ mockLoadHooks.mockResolvedValue({ hook_config: null });
+
+ await buildStartConversationRequestWithEncryptedSettings({
+ settings: DEFAULT_SETTINGS,
+ workingDir: "/workspace/my-project/0f1e2d3c",
+ });
+
+ expect(mockLoadHooks).toHaveBeenCalledWith({
+ project_dir: "/workspace/project/agent-canvas",
+ });
+ });
+
+ it("omits hook_config when the workspace has no hooks", async () => {
+ mockLoadHooks.mockResolvedValue({ hook_config: null });
+
+ const payload = await buildStartConversationRequestWithEncryptedSettings({
+ settings: DEFAULT_SETTINGS,
+ hooksProjectDir: "/workspace/my-project",
+ });
+
+ expect(payload.hook_config).toBeUndefined();
+ });
+
+ it("starts the conversation without hooks when the lookup fails", async () => {
+ mockLoadHooks.mockRejectedValue(new Error("500 Internal Server Error"));
+
+ const payload = await buildStartConversationRequestWithEncryptedSettings({
+ settings: DEFAULT_SETTINGS,
+ hooksProjectDir: "/workspace/my-project",
+ });
+
+ expect(payload.hook_config).toBeUndefined();
+ expect(payload.agent_settings).toBeDefined();
+ });
+});
diff --git a/__tests__/api/agent-server-conversation-service.test.ts b/__tests__/api/agent-server-conversation-service.test.ts
index c97cd07325..b84eff16bf 100644
--- a/__tests__/api/agent-server-conversation-service.test.ts
+++ b/__tests__/api/agent-server-conversation-service.test.ts
@@ -33,6 +33,7 @@ const {
mockActivateProfile,
mockListProfiles,
mockGetTelemetryDistinctId,
+ mockLoadHooks,
} = vi.hoisted(() => ({
mockHttpGet: vi.fn(),
mockHttpPost: vi.fn(),
@@ -48,6 +49,7 @@ const {
mockActivateProfile: vi.fn(),
mockListProfiles: vi.fn(),
mockGetTelemetryDistinctId: vi.fn(),
+ mockLoadHooks: vi.fn(),
}));
const originalFetch = global.fetch;
@@ -78,6 +80,9 @@ vi.mock("@openhands/typescript-client/clients", async () => {
VSCodeClient: vi.fn(function VSCodeClientMock() {
return { getUrl: vi.fn() };
}),
+ HooksClient: vi.fn(function HooksClientMock() {
+ return { loadHooks: mockLoadHooks };
+ }),
};
});
@@ -86,6 +91,7 @@ vi.mock("#/api/agent-server-config", () => ({
getAgentServerBaseUrl: vi.fn(() => "http://localhost:54928"),
getAgentServerSessionApiKey: vi.fn(() => "test-api-key"),
getAgentServerWorkingDir: vi.fn(() => "/workspace/project/agent-canvas"),
+ getWorkspaceRootForBackend: vi.fn(() => "/workspace/project/agent-canvas"),
buildConversationWorkingDirForBackend: vi.fn(
(id: string) => `/state/workspaces/${id.replace(/-/g, "")}`,
),
@@ -482,6 +488,68 @@ describe("AgentServerConversationService", () => {
expect(payload.worktree).toBe(false);
});
+ // Regression for #16907 β€” the conversation's own `<workspace>/<hex>` dir
+ // does not exist yet, so hooks looked up there are never found.
+ it("looks project hooks up in the workspace root, not the conversation dir", async () => {
+ mockGetSettings.mockResolvedValue({
+ agent_settings: { llm: { model: "gpt-4o" } },
+ conversation_settings: {},
+ });
+ mockGetSettingsForConversation.mockResolvedValue({
+ agentSettings: { llm: { model: "gpt-4o" } },
+ conversationSettings: {},
+ secretsEncrypted: true,
+ });
+ mockHttpPost.mockResolvedValue({
+ data: {
+ id: "ignored-server-id",
+ created_at: "2024-01-01",
+ updated_at: "2024-01-01",
+ },
+ });
+
+ await AgentServerConversationService.createConversation();
+
+ const [payloadCall] = mockHttpPost.mock.calls;
+ const payload = payloadCall[1] as {
+ workspace: { working_dir: string };
+ };
+ expect(mockLoadHooks).toHaveBeenCalledWith({
+ project_dir: "/workspace/project/agent-canvas",
+ });
+ expect(mockLoadHooks).not.toHaveBeenCalledWith({
+ project_dir: payload.workspace.working_dir,
+ });
+ });
+
+ // An explicit pick is the project, so hooks belong there.
+ it("looks project hooks up in an explicitly picked workspace", async () => {
+ mockGetSettings.mockResolvedValue({
+ agent_settings: { llm: { model: "gpt-4o" } },
+ conversation_settings: {},
+ });
+ mockGetSettingsForConversation.mockResolvedValue({
+ agentSettings: { llm: { model: "gpt-4o" } },
+ conversationSettings: {},
+ secretsEncrypted: true,
+ });
+ mockHttpPost.mockResolvedValue({
+ data: {
+ id: "ignored-server-id",
+ created_at: "2024-01-01",
+ updated_at: "2024-01-01",
+ },
+ });
+
+ await AgentServerConversationService.createConversation({
+ workingDirOverride: "/Users/jane/projects/foo",
+ });
+
+ expect(mockLoadHooks).toHaveBeenCalledWith({
+ project_dir: "/Users/jane/projects/foo",
+ });
+ });
+
it("honors an explicit new-worktree mode for a selected workspace", async () => {
mockGetSettings.mockResolvedValue({
agent_settings: { llm: { model: "gpt-4o" } },
diff --git a/__tests__/api/hooks-service.test.ts b/__tests__/api/hooks-service.test.ts
new file mode 100644
index 0000000000..f89f78bfa8
--- /dev/null
+++ b/__tests__/api/hooks-service.test.ts
@@ -0,0 +1,136 @@
+import { HooksClient } from "@openhands/typescript-client/clients";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ __resetActiveStoreForTests,
+ setActiveSelection,
+ setRegisteredBackends,
+} from "#/api/backend-registry/active-store";
+import { DEFAULT_WORKING_DIR } from "#/api/agent-server-config";
+import type { Backend } from "#/api/backend-registry/types";
+
+const { mockLoadHooks } = vi.hoisted(() => ({
+ mockLoadHooks: vi.fn(),
+}));
+
+vi.mock("@openhands/typescript-client/clients", () => ({
+ HooksClient: vi.fn(function HooksClientMock() {
+ return { loadHooks: mockLoadHooks };
+ }),
+}));
+
+import HooksService from "#/api/hooks-service";
+
+const localBackend: Backend = {
+ id: "local",
+ name: "Local",
+ host: "http://127.0.0.1:8000",
+ apiKey: "",
+ kind: "local",
+};
+
+const cloudBackend: Backend = {
+ id: "cloud",
+ name: "Cloud",
+ host: "https://openhands.dev",
+ apiKey: "cloud-key",
+ kind: "cloud",
+};
+
+beforeEach(() => {
+ window.localStorage.clear();
+ __resetActiveStoreForTests();
+ setRegisteredBackends([localBackend]);
+ setActiveSelection({ backendId: localBackend.id });
+ mockLoadHooks.mockReset();
+ vi.mocked(HooksClient).mockClear();
+});
+
+afterEach(() => {
+ __resetActiveStoreForTests();
+});
+
+describe("HooksService.loadWorkspaceHooks", () => {
+ it("loads workspace hooks from the agent-server when present", async () => {
+ const mockHookConfig = {
+ session_start: [
+ {
+ matcher: "*",
+ hooks: [{ command: "cat AGENTS.md", type: "command" }],
+ },
+ ],
+ pre_tool_use: [],
+ post_tool_use: [],
+ user_prompt_submit: [],
+ session_end: [],
+ stop: [],
+ };
+
+ mockLoadHooks.mockResolvedValue({ hook_config: mockHookConfig });
+
+ const result = await HooksService.loadWorkspaceHooks(
+ "/workspace/test-project",
+ );
+
+ expect(mockLoadHooks).toHaveBeenCalledTimes(1);
+ expect(mockLoadHooks).toHaveBeenCalledWith({
+ project_dir: "/workspace/test-project",
+ });
+ expect(result).toEqual(mockHookConfig);
+ });
+
+ it("defaults project_dir to getAgentServerWorkingDir() when omitted", async () => {
+ mockLoadHooks.mockResolvedValue({ hook_config: null });
+
+ const result = await HooksService.loadWorkspaceHooks();
+
+ expect(mockLoadHooks).toHaveBeenCalledTimes(1);
+ expect(mockLoadHooks).toHaveBeenCalledWith({
+ project_dir: DEFAULT_WORKING_DIR,
+ });
+ expect(result).toBeNull();
+ });
+
+ it("gracefully returns null and warns when the agent-server throws an error", async () => {
+ const warn = vi.spyOn(console, "warn").mockImplementation(() => {});
+ mockLoadHooks.mockRejectedValue(new Error("500 Internal Server Error"));
+
+ const result = await HooksService.loadWorkspaceHooks("/workspace/broken");
+
+ expect(result).toBeNull();
+ expect(warn).toHaveBeenCalled();
+ warn.mockRestore();
+ });
+
+ // The lookup is on the launch critical path; the SDK's 60s default would
+ // stall a launch against a wedged agent-server.
+ it("bounds the request so a wedged agent-server cannot stall a launch", async () => {
+ mockLoadHooks.mockResolvedValue({ hook_config: null });
+
+ await HooksService.loadWorkspaceHooks("/workspace/test-project");
+
+ const [clientOptions] = vi.mocked(HooksClient).mock.calls[0];
+ expect(clientOptions.timeout).toBeLessThanOrEqual(10_000);
+ });
+
+ it("returns null immediately for cloud backend without calling HooksClient", async () => {
+ setRegisteredBackends([cloudBackend]);
+ setActiveSelection({ backendId: cloudBackend.id });
+
+ const result = await HooksService.loadWorkspaceHooks("/workspace/cloud");
+
+ expect(mockLoadHooks).not.toHaveBeenCalled();
+ expect(result).toBeNull();
+ });
+
+ it("returns null for unseeded/empty registry (NO_BACKEND sentinel) without calling HooksClient", async () => {
+ // Simulate a fresh install with no backends registered.
+ // setRegisteredBackends([]) computes the snapshot with NO_BACKEND,
+ // so getEffectiveLocalBackend() returns null.
+ setRegisteredBackends([]);
+
+ const result = await HooksService.loadWorkspaceHooks("/workspace/test");
+
+ expect(mockLoadHooks).not.toHaveBeenCalled();
+ expect(result).toBeNull();
+ });
+});
diff --git a/__tests__/api/use-create-conversation-metadata.test.ts b/__tests__/api/use-create-conversation-metadata.test.ts
index 5f18c2858c..4bd4dd75ab 100644
--- a/__tests__/api/use-create-conversation-metadata.test.ts
+++ b/__tests__/api/use-create-conversation-metadata.test.ts
@@ -53,6 +53,7 @@ vi.mock("#/api/agent-server-config", () => ({
getBakedSessionApiKey: vi.fn(() => "test-session-key"),
getAgentServerSessionApiKey: vi.fn(() => "test-session-key"),
getAgentServerWorkingDir: vi.fn(() => "/workspace/project/agent-canvas"),
+ getWorkspaceRootForBackend: vi.fn(() => "/workspace/project/agent-canvas"),
buildConversationWorkingDirForBackend: vi.fn(
(id: string) => `/state/workspaces/${id.replace(/-/g, "")}`,
),
diff --git a/src/api/agent-server-adapter.ts b/src/api/agent-server-adapter.ts
index eb99c0389a..9585602de4 100644
--- a/src/api/agent-server-adapter.ts
+++ b/src/api/agent-server-adapter.ts
@@ -1,4 +1,5 @@
import { ACP_SETTINGS_KEYS } from "@openhands/typescript-client";
+import type { HookConfig } from "@openhands/typescript-client";
import { ServerClient } from "@openhands/typescript-client/clients";
import { SKILLS_CATALOG } from "@openhands/extensions/skills";
import { DEFAULT_SETTINGS } from "#/services/settings";
@@ -1080,6 +1081,7 @@ export interface StartConversationOptions {
agentProfileKind?: AgentKind;
titleLlmProfile?: string;
runtimeServicesInfo?: RuntimeServicesInfo | null;
+ workspaceHookConfig?: HookConfig | null;
}
export function buildStartConversationRequest(
@@ -1218,6 +1220,8 @@ export function buildStartConversationRequest(
if (conversationSettings.hook_config) {
payload.hook_config = conversationSettings.hook_config;
+ } else if (options.workspaceHookConfig) {
+ payload.hook_config = options.workspaceHookConfig;
}
const toolModuleQualnames = {
@@ -1295,19 +1299,29 @@ export async function buildStartConversationRequestWithEncryptedSettings(options
conversationId?: string;
parentConversationId?: string;
workingDir?: string;
+ /** Workspace root for the hooks lookup, not the per-conversation `workingDir` (#16907). */
+ hooksProjectDir?: string;
worktree?: boolean;
agentProfileId?: string;
agentProfileKind?: AgentKind;
titleLlmProfile?: string;
}): Promise<Record<string, unknown>> {
- const { SecretsService } = await import("./secrets-service");
+ const [{ SecretsService }, { default: HooksService }] = await Promise.all([
+ import("./secrets-service"),
+ import("./hooks-service"),
+ ]);
- const [settingsResult, customSecrets, runtimeServicesInfo] =
- await Promise.all([
- SettingsService.getSettingsForConversation(),
- SecretsService.getSecrets(),
- fetchBackendRuntimeServicesInfo(),
- ]);
+ const [
+ settingsResult,
+ customSecrets,
+ runtimeServicesInfo,
+ workspaceHookConfig,
+ ] = await Promise.all([
+ SettingsService.getSettingsForConversation(),
+ SecretsService.getSecrets(),
+ fetchBackendRuntimeServicesInfo(),
+ HooksService.loadWorkspaceHooks(options.hooksProjectDir),
+ ]);
const { agentSettings, conversationSettings, secretsEncrypted } =
settingsResult;
@@ -1325,6 +1339,7 @@ export async function buildStartConversationRequestWithEncryptedSettings(options
secretsEncrypted,
customSecrets,
runtimeServicesInfo,
+ workspaceHookConfig,
});
}
diff --git a/src/api/agent-server-config.ts b/src/api/agent-server-config.ts
index 739b7c2379..7e5175a2ac 100644
--- a/src/api/agent-server-config.ts
+++ b/src/api/agent-server-config.ts
@@ -257,6 +257,19 @@ export function buildConversationWorkingDirForBackend(
: buildRelativeConversationWorkingDir(conversationId);
}
+/**
+ * Workspace root for `backendHost` β€” the dir each conversation's `<root>/<hex>`
+ * working dir is created under. Same per-backend rule as
+ * `buildConversationWorkingDirForBackend()`.
+ */
+export function getWorkspaceRootForBackend(
+ backendHost: string | null | undefined,
+): string {
+ return isServedOriginHost(backendHost)
+ ? getAgentServerWorkingDir()
+ : DEFAULT_WORKING_DIR;
+}
+
export function getAgentServerHeaders(): Record<string, string> {
const sessionApiKey = getAgentServerSessionApiKey();
return sessionApiKey ? { "X-Session-API-Key": sessionApiKey } : {};
diff --git a/src/api/conversation-service/agent-server-conversation-service.api.ts b/src/api/conversation-service/agent-server-conversation-service.api.ts
index ac1958ca8f..ea76dd530f 100644
--- a/src/api/conversation-service/agent-server-conversation-service.api.ts
+++ b/src/api/conversation-service/agent-server-conversation-service.api.ts
@@ -17,6 +17,7 @@ import { buildHttpBaseUrl } from "#/utils/websocket-url";
import {
buildConversationWorkingDirForBackend,
getAgentServerWorkingDir,
+ getWorkspaceRootForBackend,
} from "../agent-server-config";
import { resolveAbsoluteAgentServerPath } from "../agent-server-home";
import {
@@ -478,13 +479,19 @@ class AgentServerConversationService {
// on the active backend's host (not its id): the seeded `default-local`
// entry is mutable, so a user can edit it to point at a remote host while
// its id stays `default-local`.
+ const backendHost = getActiveBackend().backend.host;
const baseWorkingDir =
workingDirOverride ??
- buildConversationWorkingDirForBackend(
- conversationId,
- getActiveBackend().backend.host,
- );
+ buildConversationWorkingDirForBackend(conversationId, backendHost);
const workingDir = await resolveAbsoluteAgentServerPath(baseWorkingDir);
+ // The agent-server checks `<project_dir>/.openhands/hooks.json` literally,
+ // so hooks need the workspace root: the per-conversation subdir below it is
+ // created only after this request (#16907). An explicit pick is the root.
+ const hooksProjectDir = workingDirOverride
+ ? workingDir
+ : await resolveAbsoluteAgentServerPath(
+ getWorkspaceRootForBackend(backendHost),
+ );
const resolvedWorkspaceMode =
workspaceMode ?? (workingDirOverride ? "local_repo" : "new_worktree");
@@ -501,6 +508,7 @@ class AgentServerConversationService {
// older than 1.37.1 ignore the field and create an unlinked conversation.
parentConversationId,
workingDir,
+ hooksProjectDir,
worktree: resolvedWorkspaceMode === "new_worktree",
agentProfileId,
agentProfileKind,
diff --git a/src/api/hooks-service.ts b/src/api/hooks-service.ts
new file mode 100644
index 0000000000..828a4fbe3d
--- /dev/null
+++ b/src/api/hooks-service.ts
@@ -0,0 +1,49 @@
+import { HooksClient } from "@openhands/typescript-client/clients";
+import type { HookConfig } from "@openhands/typescript-client";
+import { getAgentServerWorkingDir } from "./agent-server-config";
+import { getEffectiveLocalBackend } from "./backend-registry/active-store";
+import { getAgentServerClientOptions } from "./agent-server-client-options";
+
+// `loadHooks()` spends this twice (version probe, then the call) on the
+// conversation-start critical path; the SDK's 60s default would stall a launch.
+const HOOKS_LOAD_TIMEOUT_MS = 5000;
+
+class HooksService {
+ /**
+ * Load workspace hooks from the agent-server by calling POST /api/hooks.
+ * Returns the HookConfig if the workspace has hooks, or null.
+ * Gracefully returns null when no usable local backend is available
+ * (cloud backend, unseeded registry, or older agent-server).
+ * `projectDir` must be the workspace root: the agent-server checks
+ * `<project_dir>/.openhands/hooks.json` literally and never walks parents.
+ */
+ static async loadWorkspaceHooks(
+ projectDir?: string,
+ ): Promise<HookConfig | null> {
+ // getEffectiveLocalBackend() returns null for cloud backends AND for the
+ // NO_BACKEND sentinel (unseeded/empty registry), avoiding the silent
+ // NoBackendAvailableError that getActiveBackend() would cause.
+ if (!getEffectiveLocalBackend()) {
+ return null;
+ }
+
+ try {
+ const response = await new HooksClient(
+ getAgentServerClientOptions({ timeout: HOOKS_LOAD_TIMEOUT_MS }),
+ ).loadHooks({
+ project_dir: projectDir ?? getAgentServerWorkingDir(),
+ });
+ return response?.hook_config ?? null;
+ } catch (error) {
+ // Agent-server may not support the hooks endpoint or may be
+ // unreachable; gracefully fall back to null.
+ console.warn(
+ "Failed to load workspace hooks, continuing without:",
+ error,
+ );
+ return null;
+ }
+ }
+}
+
+export default HooksService;