Skip to content

πŸ™Œ OpenHands: AI-Driven Development

fix(hooks): list workspace hooks in the Available Hooks dialog on local backends (#18031)

Engel Nyst19c7cd2fd6d1
diff --git a/__tests__/api/agent-server-conversation-service.test.ts b/__tests__/api/agent-server-conversation-service.test.ts
index 4444437c49..7a2b143ba4 100644
--- a/__tests__/api/agent-server-conversation-service.test.ts
+++ b/__tests__/api/agent-server-conversation-service.test.ts
@@ -18,6 +18,7 @@ import {
setStoredConversationMetadata,
} from "#/api/conversation-metadata-store";
import type { Backend } from "#/api/backend-registry/types";
+import { clearCachedAgentServerInfo } from "#/api/agent-server-compatibility";
import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
import LLMSubscriptionService from "#/api/llm-subscription-service";
import {
@@ -2005,13 +2006,124 @@ describe("AgentServerConversationService", () => {
expect(proxyRequests).toHaveLength(0);
});
- it("returns an empty hooks result with and without a conversation id", async () => {
- await expect(
- AgentServerConversationService.getHooks(""),
- ).resolves.toEqual({ hooks: [] });
- await expect(
- AgentServerConversationService.getHooks("conv-1"),
- ).resolves.toEqual({ hooks: [] });
+ // @spec #17924 β€” The hooks dialog reads the conversation's workspace hooks.
+ describe("getHooks", () => {
+ // POST /api/hooks as the agent-server serializes it: every event key,
+ // and every HookDefinition field with its default.
+ const workspaceHookConfig = {
+ pre_tool_use: [
+ {
+ matcher: "terminal",
+ hooks: [
+ {
+ type: "command",
+ name: null,
+ command: "true",
+ prompt: null,
+ system_prompt: null,
+ tools: [],
+ timeout: 10,
+ max_iterations: 3,
+ async: false,
+ },
+ ],
+ },
+ ],
+ post_tool_use: [],
+ user_prompt_submit: [],
+ session_start: [],
+ session_end: [],
+ stop: [],
+ };
+
+ function serveWorkspaceHooks(body: object, status = 200) {
+ const projectDirs: unknown[] = [];
+ server.use(
+ http.post("*/api/hooks", async ({ request }) => {
+ const { project_dir: projectDir } = (await request.json()) as {
+ project_dir?: unknown;
+ };
+ projectDirs.push(projectDir);
+ return HttpResponse.json(body, { status });
+ }),
+ );
+ return projectDirs;
+ }
+
+ beforeEach(() => {
+ clearCachedAgentServerInfo();
+ });
+
+ it("lists the hooks of the workspace the conversation was started in", async () => {
+ setStoredConversationMetadata("conv-1", {
+ selected_repository: null,
+ selected_branch: null,
+ git_provider: null,
+ selected_workspace: "/home/user/qa-hooks-repo",
+ workspace_mode: "new_worktree",
+ });
+ const projectDirs = serveWorkspaceHooks({
+ hook_config: workspaceHookConfig,
+ });
+
+ await expect(
+ AgentServerConversationService.getHooks("conv-1"),
+ ).resolves.toEqual({
+ hooks: [
+ {
+ event_type: "pre_tool_use",
+ matchers: [
+ {
+ matcher: "terminal",
+ hooks: [
+ {
+ type: "command",
+ command: "true",
+ timeout: 10,
+ async: false,
+ },
+ ],
+ },
+ ],
+ },
+ ],
+ });
+ // The workspace root, not the per-conversation worktree.
+ expect(projectDirs).toEqual(["/home/user/qa-hooks-repo"]);
+ });
+
+ it("reads the backend workspace root for a conversation without an attached workspace", async () => {
+ const projectDirs = serveWorkspaceHooks({ hook_config: null });
+
+ await expect(
+ AgentServerConversationService.getHooks("conv-1"),
+ ).resolves.toEqual({ hooks: [] });
+ expect(projectDirs).toEqual(["/workspace/project/agent-canvas"]);
+ });
+
+ it("rejects when the agent-server cannot load the workspace hooks", async () => {
+ serveWorkspaceHooks({ detail: "Internal Server Error" }, 500);
+
+ await expect(
+ AgentServerConversationService.getHooks("conv-1"),
+ ).rejects.toThrow();
+ });
+
+ it("resolves to no hooks without a request when there is no conversation id or local backend", async () => {
+ const projectDirs = serveWorkspaceHooks({
+ hook_config: workspaceHookConfig,
+ });
+
+ await expect(
+ AgentServerConversationService.getHooks(""),
+ ).resolves.toEqual({ hooks: [] });
+ setRegisteredBackends([cloudBackend]);
+ setActiveSelection({ backendId: cloudBackend.id });
+ await expect(
+ AgentServerConversationService.getHooks("conv-cloud"),
+ ).resolves.toEqual({ hooks: [] });
+ expect(projectDirs).toEqual([]);
+ });
});
it("normalizes dot segments while keeping a requested file inside the workspace", async () => {
diff --git a/__tests__/api/docker-conversation-boundaries.test.ts b/__tests__/api/docker-conversation-boundaries.test.ts
index 40348081e9..5d0fe84da1 100644
--- a/__tests__/api/docker-conversation-boundaries.test.ts
+++ b/__tests__/api/docker-conversation-boundaries.test.ts
@@ -111,6 +111,13 @@ describe("conversation runtime boundaries", () => {
expect(paths).toEqual(["/server_info"]);
});
+ it("lists no hooks for an isolated conversation without reading host hooks", async () => {
+ expect(await AgentServerConversationService.getHooks(cid)).toEqual({
+ hooks: [],
+ });
+ expect(paths).toEqual(["/server_info"]);
+ });
+
it.each(["/home/user/project", "/workspace", "relative/project"])(
"rejects selected host folder %s rather than discarding it",
async (workingDir) => {
diff --git a/src/api/agent-server-adapter.ts b/src/api/agent-server-adapter.ts
index fa1140d93e..d393fb5da2 100644
--- a/src/api/agent-server-adapter.ts
+++ b/src/api/agent-server-adapter.ts
@@ -1,4 +1,8 @@
-import { ACP_SETTINGS_KEYS } from "@openhands/typescript-client";
+import {
+ ACP_SETTINGS_KEYS,
+ HOOK_EVENT_FIELDS,
+ HookType,
+} from "@openhands/typescript-client";
import type {
ConversationRuntimeInfo,
HookConfig,
@@ -1774,3 +1778,27 @@ export async function buildStartConversationRequestWithEncryptedSettings(options
export function emptyHooksResponse(): GetHooksResponse {
return { hooks: [] };
}
+
+/** The hooks dialog's events: a workspace's configured events in SDK order. */
+export function toHooksResponse(
+ hookConfig: HookConfig | null,
+): GetHooksResponse {
+ if (!hookConfig) return emptyHooksResponse();
+ return {
+ hooks: [...HOOK_EVENT_FIELDS]
+ .filter((eventType) => hookConfig[eventType]?.length)
+ .map((eventType) => ({
+ event_type: eventType,
+ matchers: hookConfig[eventType].map(({ matcher, hooks }) => ({
+ // The SDK's own defaults for fields a hooks.json may omit.
+ matcher: matcher ?? "*",
+ hooks: hooks.map((hook) => ({
+ type: hook.type ?? HookType.COMMAND,
+ command: hook.command,
+ timeout: hook.timeout,
+ async: hook.async,
+ })),
+ })),
+ })),
+ };
+}
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 268c3884cd..4d4e89171b 100644
--- a/src/api/conversation-service/agent-server-conversation-service.api.ts
+++ b/src/api/conversation-service/agent-server-conversation-service.api.ts
@@ -14,7 +14,11 @@ import { v4 as uuidv4 } from "uuid";
import { AgentKind, Provider } from "#/types/settings";
import type { ConversationRuntimeContext } from "#/api/conversation-file-upload.api";
import { getAgentServerWorkingDir } from "../agent-server-config";
-import { resolveNewConversationWorkspace } from "../conversation-workspace";
+import {
+ resolveConversationHooksProjectDir,
+ resolveNewConversationWorkspace,
+} from "../conversation-workspace";
+import HooksService from "../hooks-service";
import {
getActiveBackend,
getEffectiveLocalBackend,
@@ -43,6 +47,7 @@ import {
getDefaultConversationTitle,
toAppConversation,
toConversationPage,
+ toHooksResponse,
} from "../agent-server-adapter";
import { GetVSCodeUrlResponse } from "../open-hands.types";
import {
@@ -876,11 +881,20 @@ class AgentServerConversationService {
);
}
+ /**
+ * Hooks of the workspace a local conversation runs in, re-read on each call
+ * so the dialog's Refresh picks up `.openhands/hooks.json` edits. Cloud has
+ * no per-conversation hooks route, so it keeps an empty list.
+ */
static async getHooks(conversationId: string): Promise<GetHooksResponse> {
- if (!conversationId) {
+ if (!conversationId || !getEffectiveLocalBackend()) {
return emptyHooksResponse();
}
- return emptyHooksResponse();
+ const projectDir = await resolveConversationHooksProjectDir(
+ getStoredConversationMetadata(conversationId)?.selected_workspace,
+ );
+ if (projectDir === null) return emptyHooksResponse();
+ return toHooksResponse(await HooksService.fetchWorkspaceHooks(projectDir));
}
static async getRuntimeConversation(
diff --git a/src/api/conversation-service/agent-server-conversation-service.types.ts b/src/api/conversation-service/agent-server-conversation-service.types.ts
index aee374982c..317a632c84 100644
--- a/src/api/conversation-service/agent-server-conversation-service.types.ts
+++ b/src/api/conversation-service/agent-server-conversation-service.types.ts
@@ -252,7 +252,7 @@ export interface GetSkillsResponse {
export interface HookDefinition {
type: string; // 'command' or 'prompt'
command: string;
- timeout: number;
+ timeout?: number; // Omitted when a server leaves the SDK default implicit
async?: boolean;
}
diff --git a/src/api/conversation-workspace.ts b/src/api/conversation-workspace.ts
index dcf2f8f738..e3f957cde6 100644
--- a/src/api/conversation-workspace.ts
+++ b/src/api/conversation-workspace.ts
@@ -72,10 +72,38 @@ export async function resolveNewConversationWorkspace(options: {
clientOptions.host,
);
const workingDir = await resolveAbsoluteAgentServerPath(base);
- const hooksProjectDir = options.workingDir
- ? workingDir
- : await resolveAbsoluteAgentServerPath(
- getWorkspaceRootForBackend(clientOptions.host),
- );
+ const hooksProjectDir = await resolveHooksProjectDir(
+ options.workingDir,
+ clientOptions.host,
+ );
return { workingDir, hooksProjectDir, isolated: false };
}
+
+/**
+ * Workspace root whose `.openhands/hooks.json` a host-workspace conversation
+ * loads: the folder the user attached, else the backend's workspace root,
+ * never the per-conversation working dir or worktree (#16907).
+ */
+function resolveHooksProjectDir(
+ selectedWorkspace: string | null | undefined,
+ host: string,
+): Promise<string> {
+ return resolveAbsoluteAgentServerPath(
+ selectedWorkspace || getWorkspaceRootForBackend(host),
+ );
+}
+
+/**
+ * The hooks project dir of an existing conversation, resolved as
+ * `resolveNewConversationWorkspace()` resolved it at start from the workspace
+ * the user attached. `null` on an isolated (Docker) backend, whose
+ * conversations never load host hooks.
+ */
+export async function resolveConversationHooksProjectDir(
+ selectedWorkspace: string | null | undefined,
+): Promise<string | null> {
+ const clientOptions = getAgentServerClientOptions();
+ const info = await getConversationServerInfo(clientOptions);
+ if (usesIsolatedWorkspace(info)) return null;
+ return resolveHooksProjectDir(selectedWorkspace, clientOptions.host);
+}
diff --git a/src/api/hooks-service.ts b/src/api/hooks-service.ts
index 828a4fbe3d..89c1a64240 100644
--- a/src/api/hooks-service.ts
+++ b/src/api/hooks-service.ts
@@ -28,12 +28,9 @@ class HooksService {
}
try {
- const response = await new HooksClient(
- getAgentServerClientOptions({ timeout: HOOKS_LOAD_TIMEOUT_MS }),
- ).loadHooks({
- project_dir: projectDir ?? getAgentServerWorkingDir(),
- });
- return response?.hook_config ?? null;
+ return await HooksService.fetchWorkspaceHooks(
+ projectDir ?? getAgentServerWorkingDir(),
+ );
} catch (error) {
// Agent-server may not support the hooks endpoint or may be
// unreachable; gracefully fall back to null.
@@ -44,6 +41,21 @@ class HooksService {
return null;
}
}
+
+ /**
+ * POST /api/hooks for `projectDir` (a workspace root, as above) on the
+ * active local backend. Unlike `loadWorkspaceHooks()` it rejects when the
+ * agent-server is unreachable or lacks the endpoint, so a view can tell a
+ * failure from a workspace without hooks (`null`).
+ */
+ static async fetchWorkspaceHooks(
+ projectDir: string,
+ ): Promise<HookConfig | null> {
+ const response = await new HooksClient(
+ getAgentServerClientOptions({ timeout: HOOKS_LOAD_TIMEOUT_MS }),
+ ).loadHooks({ project_dir: projectDir });
+ return response?.hook_config ?? null;
+ }
}
export default HooksService;
diff --git a/src/components/features/conversation-panel/hook-matcher-content.tsx b/src/components/features/conversation-panel/hook-matcher-content.tsx
index 3c95f3d630..6192b10058 100644
--- a/src/components/features/conversation-panel/hook-matcher-content.tsx
+++ b/src/components/features/conversation-panel/hook-matcher-content.tsx
@@ -45,9 +45,11 @@ export function HookMatcherContent({ matcher }: HookMatcherContentProps) {
<span className={HOOK_PILL_CLASS}>
{t(I18nKey.HOOKS_MODAL$TYPE, { type: hook.type })}
</span>
- <span className={HOOK_PILL_CLASS}>
- {t(I18nKey.HOOKS_MODAL$TIMEOUT, { timeout: hook.timeout })}
- </span>
+ {hook.timeout !== undefined ? (
+ <span className={HOOK_PILL_CLASS}>
+ {t(I18nKey.HOOKS_MODAL$TIMEOUT, { timeout: hook.timeout })}
+ </span>
+ ) : null}
{hook.async ? (
<span className={HOOK_PILL_CLASS}>
{t(I18nKey.HOOKS_MODAL$ASYNC)}