Skip to content

🙌 OpenHands: AI-Driven Development

feat(secrets): let the agent request a secret through an in-conversation modal (#18408)

Vasco Schiavoda4c7564dcf4
diff --git a/__tests__/api/agent-server-adapter.test.ts b/__tests__/api/agent-server-adapter.test.ts
index 93f21d1bb3..36357279a0 100644
--- a/__tests__/api/agent-server-adapter.test.ts
+++ b/__tests__/api/agent-server-adapter.test.ts
@@ -3,6 +3,7 @@ import type { MockInstance } from "vitest";
import { getAcpProvider as getClientAcpProvider } from "@openhands/typescript-client";
import { CANVAS_UI_CLIENT_TOOL_NAME } from "#/constants/canvas-ui";
import { LAUNCH_CHILD_CONVERSATION_TOOL_NAME } from "#/constants/child-conversation";
+import { REQUEST_SECRET_TOOL_NAME } from "#/constants/secret-request";
import { AUTOMATION_FORM_UPDATE_TOOL_NAME } from "#/constants/automation-form";
import {
@@ -854,6 +855,7 @@ describe("buildStartConversationRequest", () => {
expect(payload.client_tools.map((tool) => tool.name)).toEqual([
CANVAS_UI_CLIENT_TOOL_NAME,
LAUNCH_CHILD_CONVERSATION_TOOL_NAME,
+ REQUEST_SECRET_TOOL_NAME,
]);
});
@@ -883,6 +885,7 @@ describe("buildStartConversationRequest", () => {
expectedTools: [
CANVAS_UI_CLIENT_TOOL_NAME,
LAUNCH_CHILD_CONVERSATION_TOOL_NAME,
+ REQUEST_SECRET_TOOL_NAME,
],
},
{
@@ -890,6 +893,7 @@ describe("buildStartConversationRequest", () => {
expectedTools: [
CANVAS_UI_CLIENT_TOOL_NAME,
LAUNCH_CHILD_CONVERSATION_TOOL_NAME,
+ REQUEST_SECRET_TOOL_NAME,
AUTOMATION_FORM_UPDATE_TOOL_NAME,
],
},
@@ -917,6 +921,7 @@ describe("buildStartConversationRequest", () => {
expect(payload.client_tools.map((tool) => tool.name)).toEqual([
CANVAS_UI_CLIENT_TOOL_NAME,
LAUNCH_CHILD_CONVERSATION_TOOL_NAME,
+ REQUEST_SECRET_TOOL_NAME,
]);
});
diff --git a/__tests__/components/conversation-events/chat/event-content-helpers/should-render-event.test.ts b/__tests__/components/conversation-events/chat/event-content-helpers/should-render-event.test.ts
index 9920ec6f3b..94cb59a258 100644
--- a/__tests__/components/conversation-events/chat/event-content-helpers/should-render-event.test.ts
+++ b/__tests__/components/conversation-events/chat/event-content-helpers/should-render-event.test.ts
@@ -1,6 +1,7 @@
import { describe, expect, it } from "vitest";
import { shouldRenderEvent } from "#/components/conversation-events/chat/event-content-helpers/should-render-event";
import { CHILD_CONVERSATION_RESULT_PREFIX } from "#/constants/child-conversation";
+import { SECRET_REQUEST_RESULT_PREFIX } from "#/constants/secret-request";
import {
createPlanningFileEditorActionEvent,
createOtherActionEvent,
@@ -279,13 +280,10 @@ describe("shouldRenderEvent - /goal loop re-prompts", () => {
expect(shouldRenderEvent(makeUserMessage("hello"))).toBe(true);
});
- it("hides the child-conversation launch result the frontend posts back", () => {
- expect(
- shouldRenderEvent(
- makeUserMessage(
- `${CHILD_CONVERSATION_RESULT_PREFIX}{"status":"launched","target":"local"}`,
- ),
- ),
- ).toBe(false);
+ it.each([
+ `${CHILD_CONVERSATION_RESULT_PREFIX}{"status":"launched","target":"local"}`,
+ `${SECRET_REQUEST_RESULT_PREFIX}{"status":"saved","name":"GITHUB_TOKEN"}`,
+ ])("hides the client tool result the frontend posts back: %s", (text) => {
+ expect(shouldRenderEvent(makeUserMessage(text))).toBe(false);
});
});
diff --git a/__tests__/components/features/conversation/secret-request-modal.test.tsx b/__tests__/components/features/conversation/secret-request-modal.test.tsx
new file mode 100644
index 0000000000..e9e2bda131
--- /dev/null
+++ b/__tests__/components/features/conversation/secret-request-modal.test.tsx
@@ -0,0 +1,115 @@
+import { screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { SecretsService } from "#/api/secrets-service";
+import { SecretRequestModal } from "#/components/features/conversation/secret-request-modal";
+import {
+ type SecretRequest,
+ useSecretRequestStore,
+} from "#/stores/secret-request-store";
+import { renderWithProviders } from "../../../../test-utils";
+
+const { mockCompleteSecretRequest } = vi.hoisted(() => ({
+ mockCompleteSecretRequest: vi.fn(),
+}));
+
+vi.mock("#/services/secret-request", () => ({
+ completeSecretRequest: mockCompleteSecretRequest,
+}));
+
+// renderWithProviders navigates to this conversation by default.
+const request: SecretRequest = {
+ conversationId: "test-conversation-id",
+ toolCallId: "tool-call-1",
+ name: "GITHUB_TOKEN",
+ reason: "Push the factory branch; needs repo scope.",
+};
+
+const renderModal = async (requests: SecretRequest[] = [request]) => {
+ useSecretRequestStore.setState({ requests });
+ renderWithProviders(<SecretRequestModal />);
+ if (requests.some((r) => r.conversationId === request.conversationId)) {
+ await screen.findByTestId("secret-request-modal");
+ }
+};
+
+describe("SecretRequestModal", () => {
+ beforeEach(() => {
+ vi.restoreAllMocks();
+ // Like the real service, completing a request removes it from the queue.
+ mockCompleteSecretRequest
+ .mockReset()
+ .mockImplementation((r: SecretRequest) =>
+ useSecretRequestStore.getState().dismiss(r.toolCallId),
+ );
+ vi.spyOn(SecretsService, "getSecrets").mockResolvedValue([]);
+ });
+
+ it("asks for the requested secret with the agent's reason", async () => {
+ await renderModal();
+
+ expect(screen.getByText(request.reason!)).toBeInTheDocument();
+ expect(screen.getByTestId("name-input")).toHaveValue("GITHUB_TOKEN");
+ expect(screen.getByTestId("value-input")).toHaveValue("");
+ });
+
+ it("ignores requests from other conversations", async () => {
+ await renderModal([{ ...request, conversationId: "other-conversation" }]);
+
+ expect(
+ screen.queryByTestId("secret-request-modal"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("saves the value to the secrets store and completes with the secret's identity", async () => {
+ const user = userEvent.setup();
+ const createSecret = vi
+ .spyOn(SecretsService, "createSecret")
+ .mockResolvedValue(undefined);
+ await renderModal();
+
+ await user.type(screen.getByTestId("value-input"), "ghp_example");
+ await user.click(screen.getByTestId("submit-button"));
+
+ await waitFor(() =>
+ expect(
+ screen.queryByTestId("secret-request-modal"),
+ ).not.toBeInTheDocument(),
+ );
+ // The form's later onCancel is a no-op for the real, already-completed
+ // request (covered in secret-request.test.ts).
+ expect(mockCompleteSecretRequest).toHaveBeenNthCalledWith(1, request, {
+ name: "GITHUB_TOKEN",
+ description: undefined,
+ });
+ expect(createSecret).toHaveBeenCalledWith(
+ "GITHUB_TOKEN",
+ "ghp_example",
+ undefined,
+ );
+ });
+
+ it("stays open after a failed save so the user can retry or cancel", async () => {
+ const user = userEvent.setup();
+ vi.spyOn(SecretsService, "createSecret").mockRejectedValue(
+ new Error("Save failed"),
+ );
+ await renderModal();
+
+ await user.type(screen.getByTestId("value-input"), "ghp_example");
+ await user.click(screen.getByTestId("submit-button"));
+
+ await waitFor(() =>
+ expect(screen.getByTestId("cancel-button")).toBeEnabled(),
+ );
+ expect(screen.getByTestId("secret-request-modal")).toBeInTheDocument();
+ expect(mockCompleteSecretRequest).not.toHaveBeenCalled();
+
+ await user.click(screen.getByTestId("cancel-button"));
+
+ expect(mockCompleteSecretRequest).toHaveBeenCalledExactlyOnceWith(
+ request,
+ null,
+ );
+ });
+});
diff --git a/__tests__/components/features/settings/secrets-settings/secret-form-behavior.test.tsx b/__tests__/components/features/settings/secrets-settings/secret-form-behavior.test.tsx
index 60d280a8ae..5c4e161a00 100644
--- a/__tests__/components/features/settings/secrets-settings/secret-form-behavior.test.tsx
+++ b/__tests__/components/features/settings/secrets-settings/secret-form-behavior.test.tsx
@@ -37,12 +37,16 @@ interface RenderFormOptions {
mode?: "add" | "edit";
selectedSecret?: string | null;
onCancel?: () => void;
+ onSaved?: (secret: { name: string; description?: string }) => void;
+ keepOpenOnError?: boolean;
}
function renderForm({
mode = "add",
selectedSecret = null,
onCancel = vi.fn(),
+ onSaved = vi.fn(),
+ keepOpenOnError,
}: RenderFormOptions = {}) {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
@@ -54,10 +58,12 @@ function renderForm({
mode={mode}
selectedSecret={selectedSecret}
onCancel={onCancel}
+ onSaved={onSaved}
+ keepOpenOnError={keepOpenOnError}
/>
</QueryClientProvider>,
);
- return { ...view, invalidate, onCancel };
+ return { ...view, invalidate, onCancel, onSaved };
}
beforeEach(() => {
@@ -250,7 +256,7 @@ describe("Secret form behavior", () => {
it("creates a trimmed secret, refreshes both secret lists, and closes after settlement", async () => {
const user = userEvent.setup();
- const { invalidate, onCancel } = renderForm();
+ const { invalidate, onCancel, onSaved } = renderForm();
await user.type(screen.getByTestId("name-input"), "NEW_SECRET");
await user.type(screen.getByTestId("value-input"), " secret value ");
@@ -269,11 +275,16 @@ describe("Secret form behavior", () => {
expect(invalidate).not.toHaveBeenCalled();
expect(onCancel).not.toHaveBeenCalled();
+ expect(onSaved).not.toHaveBeenCalled();
await act(async () => options.onSuccess());
expect(invalidate).toHaveBeenCalledWith({ queryKey: ["secrets-search"] });
expect(invalidate).toHaveBeenCalledWith({ queryKey: ["secrets"] });
+ expect(onSaved).toHaveBeenCalledExactlyOnceWith({
+ name: "NEW_SECRET",
+ description: "for deployments",
+ });
expect(onCancel).not.toHaveBeenCalled();
options.onSettled();
@@ -281,6 +292,26 @@ describe("Secret form behavior", () => {
expect(onCancel).toHaveBeenCalledOnce();
});
+ it.each([
+ { keepOpenOnError: undefined, closes: true },
+ { keepOpenOnError: true, closes: false },
+ ])(
+ "closes after a failed save unless kept open (keepOpenOnError=$keepOpenOnError)",
+ async ({ keepOpenOnError, closes }) => {
+ const user = userEvent.setup();
+ const { onCancel, onSaved } = renderForm({ keepOpenOnError });
+
+ await user.type(screen.getByTestId("name-input"), "NEW_SECRET");
+ await user.type(screen.getByTestId("value-input"), "value");
+ await user.click(screen.getByTestId("submit-button"));
+ const options = mocks.create.mock.calls[0][1];
+ options.onSettled(undefined, new Error("Save failed"));
+
+ expect(onSaved).not.toHaveBeenCalled();
+ expect(onCancel).toHaveBeenCalledTimes(closes ? 1 : 0);
+ },
+ );
+
it("omits an empty optional description when creating", async () => {
const user = userEvent.setup();
renderForm();
diff --git a/__tests__/hooks/mutation/conversation-mutation-utils.test.ts b/__tests__/hooks/mutation/conversation-mutation-utils.test.ts
index a1f4bb40b7..e0642acacb 100644
--- a/__tests__/hooks/mutation/conversation-mutation-utils.test.ts
+++ b/__tests__/hooks/mutation/conversation-mutation-utils.test.ts
@@ -12,6 +12,7 @@ import {
resumeGoal,
startGoal,
stopGoal,
+ updateConversationSecrets,
} from "#/hooks/mutation/conversation-mutation-utils";
import { ExecutionStatus } from "#/types/agent-server/core/base/common";
@@ -26,6 +27,7 @@ const mocks = vi.hoisted(() => ({
runConversation: vi.fn(),
startGoal: vi.fn(),
stopGoal: vi.fn(),
+ updateSecrets: vi.fn(),
}));
vi.mock("@openhands/typescript-client/clients", () => ({
@@ -37,12 +39,14 @@ vi.mock("@openhands/typescript-client/clients", () => ({
runConversation: mocks.runConversation,
startGoal: mocks.startGoal,
stopGoal: mocks.stopGoal,
+ updateSecrets: mocks.updateSecrets,
};
}),
}));
vi.mock("#/api/backend-registry/active-store", () => ({
getActiveBackend: mocks.getActiveBackend,
+ getEffectiveLocalBackend: () => null,
}));
vi.mock("#/api/cloud/conversation-service.api", () => ({
@@ -261,6 +265,40 @@ describe("conversation runtime commands", () => {
expect(mocks.runConversation).toHaveBeenCalledOnce();
expect(mocks.runConversation).toHaveBeenCalledWith(CONV_ID);
});
+ it("hands saved secrets to a local conversation as value-free lookups", async () => {
+ const conversation = prepareRuntimeConversation();
+ mocks.getActiveBackend.mockReturnValueOnce({ backend: { kind: "local" } });
+ mocks.updateSecrets.mockResolvedValueOnce({ success: true });
+
+ await expect(
+ updateConversationSecrets(CONV_ID, [
+ { name: "GITHUB_TOKEN", description: "Factory repo access" },
+ ]),
+ ).resolves.toBeUndefined();
+
+ expectRuntimeClient(CONV_ID, conversation);
+ expect(mocks.updateSecrets).toHaveBeenCalledOnce();
+ expect(mocks.updateSecrets).toHaveBeenCalledWith(CONV_ID, {
+ secrets: {
+ GITHUB_TOKEN: {
+ kind: "LookupSecret",
+ url: "/api/settings/secrets/GITHUB_TOKEN",
+ description: "Factory repo access",
+ },
+ },
+ });
+ });
+
+ it("leaves cloud conversations to resolve secrets server-side", async () => {
+ mocks.getActiveBackend.mockReturnValueOnce({ backend: { kind: "cloud" } });
+
+ await expect(
+ updateConversationSecrets(CONV_ID, [{ name: "GITHUB_TOKEN" }]),
+ ).resolves.toBeUndefined();
+
+ expect(mocks.batchGetAppConversations).not.toHaveBeenCalled();
+ expect(mocks.updateSecrets).not.toHaveBeenCalled();
+ });
});
describe("conversation cache synchronization", () => {
diff --git a/__tests__/services/secret-request.test.ts b/__tests__/services/secret-request.test.ts
new file mode 100644
index 0000000000..0aecf4a834
--- /dev/null
+++ b/__tests__/services/secret-request.test.ts
@@ -0,0 +1,188 @@
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+import {
+ REQUEST_SECRET_ACTION_KIND,
+ SECRET_REQUEST_RESULT_PREFIX,
+} from "#/constants/secret-request";
+import {
+ completeSecretRequest,
+ handleRequestSecretAction,
+} from "#/services/secret-request";
+import { useGoalStore } from "#/stores/goal-store";
+import {
+ type SecretRequest,
+ useSecretRequestStore,
+} from "#/stores/secret-request-store";
+import type { RequestSecretAction } from "#/types/agent-server/core";
+
+const {
+ mockSendMessage,
+ mockUpdateConversationSecrets,
+ mockGetSecretsOrThrow,
+ mockDisplayErrorToast,
+} = vi.hoisted(() => ({
+ mockSendMessage: vi.fn(),
+ mockUpdateConversationSecrets: vi.fn(),
+ mockGetSecretsOrThrow: vi.fn(),
+ mockDisplayErrorToast: vi.fn(),
+}));
+
+vi.mock("#/api/secrets-service", () => ({
+ SecretsService: { getSecretsOrThrow: mockGetSecretsOrThrow },
+}));
+
+vi.mock("#/utils/custom-toast-handlers", () => ({
+ displayErrorToast: mockDisplayErrorToast,
+}));
+
+vi.mock(
+ "#/api/conversation-service/agent-server-conversation-service.api",
+ () => ({ default: { sendMessage: mockSendMessage } }),
+);
+
+vi.mock("#/hooks/mutation/conversation-mutation-utils", () => ({
+ updateConversationSecrets: mockUpdateConversationSecrets,
+}));
+
+const CONVERSATION_ID = "conversation-1";
+
+const action: RequestSecretAction = {
+ kind: REQUEST_SECRET_ACTION_KIND,
+ name: "GITHUB_TOKEN",
+ reason: "Push the factory branch; needs repo scope.",
+};
+
+const request: SecretRequest = {
+ conversationId: CONVERSATION_ID,
+ toolCallId: "tool-call-1",
+ name: "GITHUB_TOKEN",
+ reason: "Push the factory branch; needs repo scope.",
+};
+
+/** The text the service posted back into the conversation. */
+function reportedText(): string {
+ const [conversationId, message] = mockSendMessage.mock.calls.at(-1) as [
+ string,
+ { content: { text: string }[] },
+ ];
+ expect(conversationId).toBe(CONVERSATION_ID);
+ return message.content[0].text;
+}
+
+function reportedResult() {
+ const text = reportedText();
+ expect(text.startsWith(SECRET_REQUEST_RESULT_PREFIX)).toBe(true);
+ return JSON.parse(text.slice(SECRET_REQUEST_RESULT_PREFIX.length));
+}
+
+beforeEach(() => {
+ window.localStorage.clear();
+ useGoalStore.setState({ statusByConversation: {} });
+ useSecretRequestStore.setState({ requests: [request] });
+ vi.clearAllMocks();
+ mockSendMessage.mockResolvedValue(undefined);
+ mockUpdateConversationSecrets.mockResolvedValue(undefined);
+ mockGetSecretsOrThrow.mockResolvedValue([]);
+});
+
+describe("handleRequestSecretAction", () => {
+ it("queues one modal per tool call, ignoring replays", async () => {
+ useSecretRequestStore.setState({ requests: [] });
+ await handleRequestSecretAction(action, CONVERSATION_ID, "tool-call-1");
+ await handleRequestSecretAction(action, CONVERSATION_ID, "tool-call-1");
+
+ expect(useSecretRequestStore.getState().requests).toEqual([request]);
+ });
+
+ it("attaches a secret the user already saved without asking again", async () => {
+ useSecretRequestStore.setState({ requests: [] });
+ mockGetSecretsOrThrow.mockResolvedValueOnce([
+ { name: "GITHUB_TOKEN", description: "Saved in Settings" },
+ ]);
+
+ await handleRequestSecretAction(action, CONVERSATION_ID, "tool-call-1");
+
+ expect(useSecretRequestStore.getState().requests).toEqual([]);
+ expect(mockUpdateConversationSecrets).toHaveBeenCalledExactlyOnceWith(
+ CONVERSATION_ID,
+ [{ name: "GITHUB_TOKEN", description: "Saved in Settings" }],
+ );
+ expect(reportedResult()).toEqual({ status: "saved", name: "GITHUB_TOKEN" });
+ });
+});
+
+describe("completeSecretRequest", () => {
+ it("attaches a saved secret and reports its name, never its value", async () => {
+ await completeSecretRequest(request, {
+ name: "GH_FACTORY_TOKEN",
+ description: "Factory repo access",
+ });
+
+ expect(useSecretRequestStore.getState().requests).toEqual([]);
+ expect(mockUpdateConversationSecrets).toHaveBeenCalledExactlyOnceWith(
+ CONVERSATION_ID,
+ [{ name: "GH_FACTORY_TOKEN", description: "Factory repo access" }],
+ );
+ expect(reportedResult()).toEqual({
+ status: "saved",
+ name: "GH_FACTORY_TOKEN",
+ });
+ });
+
+ it("reports a closed form as not saved without attaching anything", async () => {
+ await completeSecretRequest(request, null);
+
+ expect(mockUpdateConversationSecrets).not.toHaveBeenCalled();
+ expect(reportedResult()).toMatchObject({
+ status: "not_saved",
+ name: "GITHUB_TOKEN",
+ });
+ });
+
+ it("reports an error when the saved secret cannot reach the conversation", async () => {
+ mockUpdateConversationSecrets.mockRejectedValueOnce(
+ new Error("Conversation not found"),
+ );
+
+ await completeSecretRequest(request, { name: "GITHUB_TOKEN" });
+
+ expect(reportedResult()).toMatchObject({
+ status: "error",
+ name: "GITHUB_TOKEN",
+ error: "Conversation not found",
+ });
+ expect(mockDisplayErrorToast).toHaveBeenCalledWith(
+ "Conversation not found",
+ );
+ });
+
+ it("reports a request only once when the form settles after a cancel", async () => {
+ await completeSecretRequest(request, null);
+ await completeSecretRequest(request, { name: "GITHUB_TOKEN" });
+
+ expect(mockUpdateConversationSecrets).not.toHaveBeenCalled();
+ expect(mockSendMessage).toHaveBeenCalledOnce();
+ expect(reportedResult()).toMatchObject({ status: "not_saved" });
+ });
+
+ // The agent server cancels an active /goal loop on any inbound message.
+ it("does not post the result while a goal loop is running", async () => {
+ useGoalStore.setState({
+ statusByConversation: {
+ [CONVERSATION_ID]: {
+ active: true,
+ status: "running",
+ iteration: 1,
+ max_iterations: 5,
+ objective: "ship it",
+ verdict: null,
+ },
+ },
+ });
+
+ await completeSecretRequest(request, { name: "GITHUB_TOKEN" });
+
+ expect(mockUpdateConversationSecrets).toHaveBeenCalledOnce();
+ expect(mockSendMessage).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/api/agent-server-adapter.test.ts b/src/api/agent-server-adapter.test.ts
index 03781758f4..4abd64a6cc 100644
--- a/src/api/agent-server-adapter.test.ts
+++ b/src/api/agent-server-adapter.test.ts
@@ -1,6 +1,7 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import { CANVAS_UI_CLIENT_TOOL_NAME } from "#/constants/canvas-ui";
import { LAUNCH_CHILD_CONVERSATION_TOOL_NAME } from "#/constants/child-conversation";
+import { REQUEST_SECRET_TOOL_NAME } from "#/constants/secret-request";
import { DEFAULT_SETTINGS } from "#/services/settings";
import type { Settings } from "#/types/settings";
import {
@@ -746,6 +747,7 @@ describe("buildStartConversationRequest — agentProfileId path", () => {
expect(payload.client_tools.map((tool) => tool.name)).toEqual([
CANVAS_UI_CLIENT_TOOL_NAME,
LAUNCH_CHILD_CONVERSATION_TOOL_NAME,
+ REQUEST_SECRET_TOOL_NAME,
]);
});
diff --git a/src/api/agent-server-adapter.ts b/src/api/agent-server-adapter.ts
index 4b1a0e93e9..6726e8b9f7 100644
--- a/src/api/agent-server-adapter.ts
+++ b/src/api/agent-server-adapter.ts
@@ -69,6 +69,7 @@ import {
LAUNCH_CHILD_CONVERSATION_TOOL_NAME,
} from "./launch-child-conversation-client-tool";
import { AUTOMATION_FORM_UPDATE_CLIENT_TOOL } from "./automation-form-client-tool";
+import { REQUEST_SECRET_CLIENT_TOOL } from "./request-secret-client-tool";
import {
buildPlanPath,
LOCAL_PLANNER_PARENT_TAG_KEY,
@@ -1378,6 +1379,7 @@ export function buildStartConversationRequest(
? [
CANVAS_UI_CLIENT_TOOL,
LAUNCH_CHILD_CONVERSATION_CLIENT_TOOL,
+ REQUEST_SECRET_CLIENT_TOOL,
...(options.automationSetup
? [AUTOMATION_FORM_UPDATE_CLIENT_TOOL]
: []),
diff --git a/src/api/request-secret-client-tool.ts b/src/api/request-secret-client-tool.ts
new file mode 100644
index 0000000000..1ae18f1f00
--- /dev/null
+++ b/src/api/request-secret-client-tool.ts
@@ -0,0 +1,52 @@
+import {
+ REQUEST_SECRET_TOOL_NAME,
+ SECRET_REQUEST_RESULT_PREFIX,
+} from "#/constants/secret-request";
+import type { ClientToolSpec } from "./canvas-ui-client-tool";
+
+const REQUEST_SECRET_DESCRIPTION = `Ask the user to securely provide a secret you need (an API key, token, password or other credential) through a form shown over this conversation, without sending them to Settings.
+
+Call this when a task needs a credential that is not among your available
+secrets — for example a GitHub token to push to a repository. Never ask the
+user to paste a secret into the chat, and never put a secret value in this
+tool's arguments. It is not for connecting MCP servers or OAuth sign-ins.
+
+The value is stored in the user's secrets and exposed to this conversation as
+an environment variable named after the secret. Reference it as $NAME in
+commands; never print or echo it. One call per missing secret.
+
+What comes back: this tool is acknowledged immediately, before the user has
+answered. End your turn after calling it and wait. The outcome arrives as a
+follow-up message starting with "${SECRET_REQUEST_RESULT_PREFIX.trim()}". On "saved",
+continue using the secret by the name it reports (the user may have renamed
+it). Otherwise, follow the guidance in the message; do not call this tool again
+unless the user asks you to.`;
+
+export const REQUEST_SECRET_CLIENT_TOOL: ClientToolSpec = {
+ name: REQUEST_SECRET_TOOL_NAME,
+ description: REQUEST_SECRET_DESCRIPTION,
+ parameters: {
+ type: "object",
+ additionalProperties: false,
+ properties: {
+ name: {
+ type: "string",
+ description:
+ "Environment variable name for the secret, e.g. 'GITHUB_TOKEN'. Starts with a letter; letters, digits and underscores only; at most 64 characters.",
+ },
+ reason: {
+ type: "string",
+ description:
+ "One sentence shown to the user explaining what the secret is for and which permissions or scopes it needs.",
+ },
+ },
+ required: ["name", "reason"],
+ },
+ annotations: {
+ readOnlyHint: false,
+ destructiveHint: false,
+ // Each call prompts the user again.
+ idempotentHint: false,
+ openWorldHint: false,
+ },
+};
diff --git a/src/components/conversation-events/chat/event-content-helpers/get-action-event-title.ts b/src/components/conversation-events/chat/event-content-helpers/get-action-event-title.ts
index 95d68e0e57..847009803f 100644
--- a/src/components/conversation-events/chat/event-content-helpers/get-action-event-title.ts
+++ b/src/components/conversation-events/chat/event-content-helpers/get-action-event-title.ts
@@ -1,5 +1,6 @@
import { CANVAS_UI_CLIENT_ACTION_KIND } from "#/constants/canvas-ui";
import { LAUNCH_CHILD_CONVERSATION_ACTION_KIND } from "#/constants/child-conversation";
+import { REQUEST_SECRET_ACTION_KIND } from "#/constants/secret-request";
import type { ActionEvent } from "#/types/agent-server/core";
export type EventTitleDescriptor =
@@ -138,6 +139,12 @@ export const getActionEventTitleDescriptor = (
key: "ACTION_MESSAGE$LAUNCH_CHILD_CONVERSATION",
values: {},
};
+ case REQUEST_SECRET_ACTION_KIND:
+ return {
+ kind: "translation",
+ key: "ACTION_MESSAGE$REQUEST_SECRET",
+ values: { name: event.action.name },
+ };
default:
return {
kind: "text",
diff --git a/src/components/conversation-events/chat/event-content-helpers/get-event-content.tsx b/src/components/conversation-events/chat/event-content-helpers/get-event-content.tsx
index 59d1dad0b8..2b6eac270e 100644
--- a/src/components/conversation-events/chat/event-content-helpers/get-event-content.tsx
+++ b/src/components/conversation-events/chat/event-content-helpers/get-event-content.tsx
@@ -2,6 +2,7 @@ import { Trans } from "react-i18next";
import React from "react";
import { CANVAS_UI_CLIENT_TOOL_NAME } from "#/constants/canvas-ui";
import { LAUNCH_CHILD_CONVERSATION_TOOL_NAME } from "#/constants/child-conversation";
+import { REQUEST_SECRET_TOOL_NAME } from "#/constants/secret-request";
import {
OpenHandsEvent,
ObservationEvent,
@@ -230,6 +231,10 @@ const getObservationEventTitle = (
observationKey = "OBSERVATION_MESSAGE$LAUNCH_CHILD_CONVERSATION";
break;
}
+ if (event.tool_name === REQUEST_SECRET_TOOL_NAME) {
+ observationKey = "OBSERVATION_MESSAGE$REQUEST_SECRET";
+ break;
+ }
return observationType.replace("Observation", "").toUpperCase();
case "SwitchLLMObservation":
observationKey = event.observation.is_error
diff --git a/src/components/conversation-events/chat/event-content-helpers/should-render-event.ts b/src/components/conversation-events/chat/event-content-helpers/should-render-event.ts
index eab2513e6e..a6d9bff898 100644
--- a/src/components/conversation-events/chat/event-content-helpers/should-render-event.ts
+++ b/src/components/conversation-events/chat/event-content-helpers/should-render-event.ts
@@ -1,4 +1,5 @@
import { CHILD_CONVERSATION_RESULT_PREFIX } from "#/constants/child-conversation";
+import { SECRET_REQUEST_RESULT_PREFIX } from "#/constants/secret-request";
import { MessageEvent, OpenHandsEvent } from "#/types/agent-server/core";
import {
isActionEvent,
@@ -51,13 +52,24 @@ export const isCorrectiveNudge = (event: MessageEvent): boolean =>
event.source === "environment" &&
(userMessageText(event)?.startsWith(CORRECTIVE_NUDGE_PREFIX) ?? false);
-// The frontend posts the outcome of a `launch_child_conversation` call back as
-// a `user` message because client tools have no result channel (see
-// `services/child-conversation-launch.ts`). It is a JSON payload addressed to
-// the agent, which reports the child's id and link in its own reply, so the
-// raw message does not belong in the chat.
-const isChildConversationResult = (event: MessageEvent): boolean =>
- userMessageText(event)?.startsWith(CHILD_CONVERSATION_RESULT_PREFIX) ?? false;
+// The frontend posts the outcome of a `launch_child_conversation` or
+// `request_secret` call back as a `user` message because client tools have no
+// result channel (see `services/child-conversation-launch.ts` and
+// `services/secret-request.ts`). It is a JSON payload addressed to the agent,
+// which relays the outcome in its own reply, so the raw message does not
+// belong in the chat.
+const CLIENT_TOOL_RESULT_PREFIXES = [
+ CHILD_CONVERSATION_RESULT_PREFIX,
+ SECRET_REQUEST_RESULT_PREFIX,
+];
+
+const isClientToolResult = (event: MessageEvent): boolean => {
+ const text = userMessageText(event);
+ return (
+ text !== null &&
+ CLIENT_TOOL_RESULT_PREFIXES.some((prefix) => text.startsWith(prefix))
+ );
+};
export const shouldRenderEvent = (event: OpenHandsEvent) => {
if (isConversationStateUpdateEvent(event)) {
@@ -124,10 +136,10 @@ export const shouldRenderEvent = (event: OpenHandsEvent) => {
// Render message events (user and assistant messages), except the goal loop's
// injected re-prompts — the judge feedback they carry is shown in the goal
// banner, so otherwise they leak into the chat as fake user turns — and the
- // child-conversation launch results, which are machine payloads the agent
- // relays in its own reply.
+ // client tool results, which are machine payloads the agent relays in its
+ // own reply.
if (isMessageEvent(event)) {
- return !isGoalLoopReprompt(event) && !isChildConversationResult(event);
+ return !isGoalLoopReprompt(event) && !isClientToolResult(event);
}
// Render agent error events
diff --git a/src/components/features/conversation/secret-request-modal.tsx b/src/components/features/conversation/secret-request-modal.tsx
new file mode 100644
index 0000000000..31c674775d
--- /dev/null
+++ b/src/components/features/conversation/secret-request-modal.tsx
@@ -0,0 +1,59 @@
+import { useTranslation } from "react-i18next";
+import { SecretForm } from "#/components/features/settings/secrets-settings/secret-form";
+import {
+ BaseModalDescription,
+ BaseModalTitle,
+} from "#/components/shared/modals/confirmation-modals/base-modal";
+import { ModalBackdrop } from "#/components/shared/modals/modal-backdrop";
+import { ModalBody } from "#/components/shared/modals/modal-body";
+import { useOptionalConversationId } from "#/hooks/use-conversation-id";
+import { I18nKey } from "#/i18n/declaration";
+import { completeSecretRequest } from "#/services/secret-request";
+import { useSecretRequestStore } from "#/stores/secret-request-store";
+
+/**
+ * Collects a secret the agent asked for with `request_secret`, over the
+ * current conversation. The value goes straight to the secrets store; the
+ * agent only learns the outcome.
+ */
+export function SecretRequestModal() {
+ const { t } = useTranslation("openhands");
+ const { conversationId } = useOptionalConversationId();
+ const request = useSecretRequestStore((s) =>
+ s.requests.find((r) => r.conversationId === conversationId),
+ );
+
+ if (!request) return null;
+
+ const title = t(I18nKey.SECRETS$REQUEST_TITLE);
+
+ return (
+ <ModalBackdrop
+ closeOnEscape={false}
+ closeOnBackdropClick={false}
+ aria-label={title}
+ >
+ <ModalBody testID="secret-request-modal" width="md">
+ <div className="flex flex-col gap-2 self-start">
+ <BaseModalTitle title={title} />
+ {request.reason ? (
+ <BaseModalDescription description={request.reason} />
+ ) : null}
+ </div>
+ <div className="w-full">
+ {/* SecretForm also calls onCancel after a successful save; the
+ request is already complete by then, so that call is a no-op. */}
+ <SecretForm
+ key={request.toolCallId}
+ mode="add"
+ selectedSecret={null}
+ defaultName={request.name}
+ keepOpenOnError
+ onSaved={(secret) => void completeSecretRequest(request, secret)}
+ onCancel={() => void completeSecretRequest(request, null)}
+ />
+ </div>
+ </ModalBody>
+ </ModalBackdrop>
+ );
+}
diff --git a/src/components/features/settings/secrets-settings/secret-form.tsx b/src/components/features/settings/secrets-settings/secret-form.tsx
index 6edf0eea6c..ded9c1724d 100644
--- a/src/components/features/settings/secrets-settings/secret-form.tsx
+++ b/src/components/features/settings/secrets-settings/secret-form.tsx
@@ -13,28 +13,38 @@ import {
import { BrandButton } from "../brand-button";
import { useSearchSecrets } from "#/hooks/query/use-get-secrets";
import { OptionalTag } from "../optional-tag";
+import type { CustomSecretInput } from "#/api/agent-server-adapter";
interface SecretFormProps {
mode: "add" | "edit";
selectedSecret: string | null;
onCancel: () => void;
+ onSaved?: (secret: CustomSecretInput) => void;
+ /** Name to prefill in add mode. */
+ defaultName?: string;
+ /** Keep the form open after a failed save so the user can retry. */
+ keepOpenOnError?: boolean;
}
export function SecretForm({
mode,
selectedSecret,
onCancel,
+ onSaved,
+ defaultName = "",
+ keepOpenOnError = false,
}: SecretFormProps) {
const queryClient = useQueryClient();
const { t } = useTranslation("openhands");
const { data: secrets } = useSearchSecrets();
- const { mutate: createSecret } = useCreateSecret();
- const { mutate: updateSecret } = useUpdateSecret();
+ const { mutate: createSecret, isPending: isCreating } = useCreateSecret();
+ const { mutate: updateSecret, isPending: isUpdating } = useUpdateSecret();
+ const isSaving = isCreating || isUpdating;
const [error, setError] = React.useState<string | null>(null);
const [name, setName] = React.useState(
- mode === "edit" && selectedSecret ? selectedSecret : "",
+ mode === "edit" && selectedSecret ? selectedSecret : defaultName,
);
const [value, setValue] = React.useState("");
const [description, setDescription] = React.useState("");
@@ -49,11 +59,15 @@ export function SecretForm({
const initialName = mode === "edit" && selectedSecret ? selectedSecret : "";
React.useEffect(() => {
- setName(mode === "edit" && selectedSecret ? selectedSecret : "");
+ setName(mode === "edit" && selectedSecret ? selectedSecret : defaultName);
setValue("");
setDescription(secretDescription);
setError(null);
- }, [mode, selectedSecret, secretDescription]);
+ }, [mode, selectedSecret, secretDescription, defaultName]);
+
+ const closeUnlessKeptOpen = (_data: unknown, error: Error | null) => {
+ if (!error || !keepOpenOnError) onCancel();
+ };
const invalidateSecrets = () => {
queryClient.invalidateQueries({
@@ -72,8 +86,11 @@ export function SecretForm({
createSecret(
{ name, value, description },
{
- onSettled: onCancel,
- onSuccess: invalidateSecrets,
+ onSettled: closeUnlessKeptOpen,
+ onSuccess: () => {
+ invalidateSecrets();
+ onSaved?.({ name, description });
+ },
},
);
};
@@ -87,8 +104,11 @@ export function SecretForm({
updateSecret(
{ secretToEdit, name, description, value },
{
- onSettled: onCancel,
- onSuccess: invalidateSecrets,
+ onSettled: closeUnlessKeptOpen,
+ onSuccess: () => {
+ invalidateSecrets();
+ onSaved?.({ name, description });
+ },
},
);
};
@@ -211,6 +231,7 @@ export function SecretForm({
type="button"
variant="secondary"
onClick={onCancel}
+ isDisabled={isSaving}
>
{t(I18nKey.BUTTON$CANCEL)}
</BrandButton>
@@ -218,7 +239,7 @@ export function SecretForm({
testId="submit-button"
type="submit"
variant="primary"
- isDisabled={isSubmitDisabled}
+ isDisabled={isSubmitDisabled || isSaving}
>
{mode === "add" && t(I18nKey.SECRETS$ADD_SECRET)}
{mode === "edit" && t(I18nKey.SECRETS$EDIT_SECRET)}
diff --git a/src/constants/secret-request.ts b/src/constants/secret-request.ts
new file mode 100644
index 0000000000..e1390df231
--- /dev/null
+++ b/src/constants/secret-request.ts
@@ -0,0 +1,18 @@
+export const REQUEST_SECRET_TOOL_NAME = "request_secret";
+
+/**
+ * Action discriminator generated by the SDK for the client-defined secret
+ * request tool (`ClientAction_<tool-name>`). Keep the SDK naming convention
+ * contained here instead of repeating its generated class name.
+ */
+export const REQUEST_SECRET_ACTION_KIND =
+ `ClientAction_${REQUEST_SECRET_TOOL_NAME}` as const;
+
+/**
+ * Prefix of the message the frontend posts back once the user closes the
+ * secret request modal. Client tools are acknowledged before the user acts, so
+ * this message is the only way to tell the agent whether the secret is now
+ * available. It carries the outcome only, never the value, and the chat hides
+ * it (see `should-render-event.ts`).
+ */
+export const SECRET_REQUEST_RESULT_PREFIX = "[secret-request] ";
diff --git a/src/contexts/conversation-websocket-context.tsx b/src/contexts/conversation-websocket-context.tsx
index 770c837a0e..09a4ea62da 100644
--- a/src/contexts/conversation-websocket-context.tsx
+++ b/src/contexts/conversation-websocket-context.tsx
@@ -42,6 +42,7 @@ import {
isCanvasUIActionEvent,
isAutomationFormUpdateActionEvent,
isLaunchChildConversationActionEvent,
+ isRequestSecretActionEvent,
} from "#/types/agent-server/type-guards";
import {
asSessionFrame,
@@ -54,6 +55,7 @@ import {
import { handleCanvasUIAction } from "#/services/canvas-ui";
import { handleAutomationFormUpdateAction } from "#/services/automation-form";
import { handleLaunchChildConversationAction } from "#/services/child-conversation-launch";
+import { handleRequestSecretAction } from "#/services/secret-request";
import { ConversationStateUpdateEventStats } from "#/types/agent-server/core/events/conversation-state-event";
import type {
ConversationErrorEvent,
@@ -870,6 +872,16 @@ export function ConversationWebSocketProvider({
event.tool_call_id,
);
}
+
+ // Same pattern again: the user answers in a modal, and the outcome
+ // is posted back once they close it.
+ if (conversationId && isRequestSecretActionEvent(event)) {
+ void handleRequestSecretAction(
+ event.action,
+ conversationId,
+ event.tool_call_id,
+ );
+ }
}
} catch (error) {
console.warn("Failed to parse WebSocket message as JSON:", error);
diff --git a/src/hooks/mutation/conversation-mutation-utils.ts b/src/hooks/mutation/conversation-mutation-utils.ts
index 32d929650b..9ef87cab60 100644
--- a/src/hooks/mutation/conversation-mutation-utils.ts
+++ b/src/hooks/mutation/conversation-mutation-utils.ts
@@ -4,6 +4,10 @@ import type { StartGoalRequest } from "@openhands/typescript-client";
import { getActiveBackend } from "#/api/backend-registry/active-store";
import { pauseCloudSandbox } from "#/api/cloud/conversation-service.api";
import { getAgentServerClientOptions } from "#/api/agent-server-client-options";
+import {
+ buildCustomSecrets,
+ type CustomSecretInput,
+} from "#/api/agent-server-adapter";
import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
import { AppConversation } from "#/api/conversation-service/agent-server-conversation-service.types";
@@ -114,6 +118,27 @@ export const resumeGoal = async (conversationId: string): Promise<void> => {
).resumeGoal(conversationId);
};
+/**
+ * Hand saved secrets to a running conversation. Conversations receive their
+ * secrets once at start, so a secret saved mid-conversation is otherwise
+ * invisible to the agent. Secrets ride as LookupSecrets, never as values.
+ * Cloud resolves secrets server-side, so this is local-only.
+ */
+export const updateConversationSecrets = async (
+ conversationId: string,
+ customSecrets: CustomSecretInput[],
+): Promise<void> => {
+ if (getActiveBackend().backend.kind === "cloud") return;
+ const secrets = buildCustomSecrets(customSecrets);
+ if (!secrets) return;
+
+ const { conversationUrl, sessionApiKey } =
+ await fetchConversationData(conversationId);
+ await new ConversationClient(
+ getAgentServerClientOptions({ conversationUrl, sessionApiKey }),
+ ).updateSecrets(conversationId, { secrets });
+};
+
export const resumeConversation = async (conversationId: string) => {
const { conversationUrl, sessionApiKey } =
await fetchConversationData(conversationId);
diff --git a/src/i18n/translation.json b/src/i18n/translation.json
index 0b22315a02..dc94129e0d 100644
--- a/src/i18n/translation.json
+++ b/src/i18n/translation.json
@@ -1457,6 +1457,24 @@
"ca": "Afegeix un secret",
"id": "Tambah rahasia"
},
+ "SECRETS$REQUEST_TITLE": {
+ "en": "The agent needs a secret",
+ "ja": "エージェントがシークレットを必要としています",
+ "zh-CN": "代理需要一个密钥",
+ "zh-TW": "代理需要一個密鑰",
+ "ko-KR": "에이전트에 시크릿이 필요합니다",
+ "no": "Agenten trenger en hemmelighet",
+ "it": "L'agente ha bisogno di un segreto",
+ "pt": "O agente precisa de um segredo",
+ "es": "El agente necesita un secreto",
+ "ar": "يحتاج الوكيل إلى سر",
+ "fr": "L'agent a besoin d'un secret",
+ "tr": "Ajanın bir gizli anahtara ihtiyacı var",
+ "de": "Der Agent benötigt ein Secret",
+ "uk": "Агенту потрібен секрет",
+ "ca": "L'agent necessita un secret",
+ "id": "Agen membutuhkan secret"
+ },
"SECRETS$EDIT_SECRET": {
"en": "Edit secret",
"ja": "シークレットを編集",
@@ -45359,6 +45377,24 @@
"ca": "S'està iniciant una conversa filla",
"id": "Meluncurkan percakapan anak"
},
+ "ACTION_MESSAGE$REQUEST_SECRET": {
+ "en": "Requesting secret <cmd>{{name}}</cmd>",
+ "ja": "シークレットをリクエスト中: <cmd>{{name}}</cmd>",
+ "zh-CN": "正在请求密钥 <cmd>{{name}}</cmd>",
+ "zh-TW": "正在請求密鑰 <cmd>{{name}}</cmd>",
+ "ko-KR": "시크릿 요청 중 <cmd>{{name}}</cmd>",
+ "no": "Ber om hemmelighet <cmd>{{name}}</cmd>",
+ "it": "Richiesta del segreto <cmd>{{name}}</cmd>",
+ "pt": "Solicitando segredo <cmd>{{name}}</cmd>",
+ "es": "Solicitando secreto <cmd>{{name}}</cmd>",
+ "ar": "جارٍ طلب السر <cmd>{{name}}</cmd>",
+ "fr": "Demande du secret <cmd>{{name}}</cmd>",
+ "tr": "Gizli anahtar isteniyor <cmd>{{name}}</cmd>",
+ "de": "Secret wird angefordert <cmd>{{name}}</cmd>",
+ "uk": "Запит секрету <cmd>{{name}}</cmd>",
+ "ca": "S'està sol·licitant el secret <cmd>{{name}}</cmd>",
+ "id": "Meminta secret <cmd>{{name}}</cmd>"
+ },
"OBSERVATION_MESSAGE$LAUNCH_CHILD_CONVERSATION": {
"en": "Requested a child conversation",
"ja": "子会話をリクエストしました",
@@ -45377,6 +45413,24 @@
"ca": "S'ha sol·licitat una conversa filla",
"id": "Telah meminta percakapan anak"
},
+ "OBSERVATION_MESSAGE$REQUEST_SECRET": {
+ "en": "Requested a secret",
+ "ja": "シークレットをリクエストしました",
+ "zh-CN": "已请求密钥",
+ "zh-TW": "已請求密鑰",
+ "ko-KR": "시크릿을 요청했습니다",
+ "no": "Ba om en hemmelighet",
+ "it": "Segreto richiesto",
+ "pt": "Segredo solicitado",
+ "es": "Secreto solicitado",
+ "ar": "تم طلب سر",
+ "fr": "Secret demandé",
+ "tr": "Gizli anahtar istendi",
+ "de": "Secret angefordert",
+ "uk": "Запитано секрет",
+ "ca": "S'ha sol·licitat un secret",
+ "id": "Secret diminta"
+ },
"SIDEBAR$ONBOARDING_CHECKLIST_TITLE": {
"en": "Getting started",
"ja": "はじめに",
diff --git a/src/routes/conversation.tsx b/src/routes/conversation.tsx
index 6167d20563..dbd34834e2 100644
--- a/src/routes/conversation.tsx
+++ b/src/routes/conversation.tsx
@@ -25,6 +25,7 @@ import { useTaskPollingController } from "#/hooks/query/use-task-polling";
import { displayErrorToast } from "#/utils/custom-toast-handlers";
import { useIsAuthed } from "#/hooks/query/use-is-authed";
import { ConversationMain } from "#/components/features/conversation/conversation-main/conversation-main";
+import { SecretRequestModal } from "#/components/features/conversation/secret-request-modal";
import { ConversationMobilePanelPage } from "#/components/features/conversation/conversation-main/conversation-mobile-panel-page";
import { ConversationOverviewDrawerProvider } from "#/components/features/conversation/conversation-overview-drawer-context";
@@ -217,6 +218,7 @@ function AppContent() {
<ConversationMain />
)}
</div>
+ <SecretRequestModal />
</ConversationOverviewDrawerProvider>
</EventHandler>
);
diff --git a/src/services/child-conversation-launch.ts b/src/services/child-conversation-launch.ts
index bd8e5ad548..28bc4f18e0 100644
--- a/src/services/child-conversation-launch.ts
+++ b/src/services/child-conversation-launch.ts
@@ -28,9 +28,10 @@ import {
type ChildConversationIsolation,
type ChildConversationTarget,
} from "#/constants/child-conversation";
-import { useGoalStore } from "#/stores/goal-store";
import type { LaunchChildConversationAction } from "#/types/agent-server/core";
import { buildAgentCanvasUrl } from "#/utils/base-path";
+import { claimClientToolCall } from "#/utils/claim-client-tool-call";
+import { postClientToolResult } from "./client-tool-result";
import {
displayErrorToast,
displaySuccessToastWithLink,
@@ -199,39 +200,6 @@ function validateLaunchParams(
};
}
-/**
- * Remember which tool calls have already been acted on.
- *
- * Unlike the Canvas UI tool, a launch is not idempotent: replaying its
- * ActionEvent (a socket reconnect that falls back to `resend_mode: "all"`, or a
- * REST/WebSocket race after a reload) would start a second — on Cloud, billable
- * — conversation. Claim the tool call before any network work so a replay that
- * arrives mid-flight is dropped too.
- */
-function claimToolCall(parentConversationId: string, toolCallId: string) {
- const key = `${LEDGER_STORAGE_KEY_PREFIX}${parentConversationId}`;
- let handled: string[] = [];
- try {
- const raw = window.localStorage.getItem(key);
- const parsed: unknown = raw ? JSON.parse(raw) : null;
- if (Array.isArray(parsed)) {
- handled = parsed.filter((id): id is string => typeof id === "string");
- }
- } catch {
- // A corrupt ledger must not block the launch; start a fresh one.
- }
-
- if (handled.includes(toolCallId)) return false;
-
- try {
- window.localStorage.setItem(key, JSON.stringify([...handled, toolCallId]));
- } catch {
- // Storage full or unavailable — proceed, accepting replay risk over never
- // launching at all.
- }
- return true;
-}
-
function absoluteCanvasUrl(path: string) {
return buildAgentCanvasUrl(path);
}
@@ -504,22 +472,12 @@ async function reportLaunchResult(
);
}
- // The agent-server cancels an active `/goal` loop on any inbound message, so
- // a launch must not silently end one. The toast above still tells the user
- // what happened.
- const goalStatus =
- useGoalStore.getState().statusByConversation[parentConversationId];
- if (goalStatus?.active) return;
-
- await AgentServerConversationService.sendMessage(parentConversationId, {
- role: "user",
- content: [
- {
- type: "text",
- text: `${CHILD_CONVERSATION_RESULT_PREFIX}${JSON.stringify(result)}`,
- },
- ],
- });
+ // Skipped during a `/goal` loop; the toast above still tells the user.
+ await postClientToolResult(
+ parentConversationId,
+ CHILD_CONVERSATION_RESULT_PREFIX,
+ result,
+ );
}
/**
@@ -533,7 +491,16 @@ export async function handleLaunchChildConversationAction(
parentConversationId: string,
toolCallId: string,
): Promise<void> {
- if (!claimToolCall(parentConversationId, toolCallId)) return;
+ // A launch is not idempotent — on Cloud, a replay would start a second,
+ // billable conversation.
+ if (
+ !claimClientToolCall(
+ `${LEDGER_STORAGE_KEY_PREFIX}${parentConversationId}`,
+ toolCallId,
+ )
+ ) {
+ return;
+ }
const validation = validateLaunchParams(action);
let result: LaunchChildConversationResult;
diff --git a/src/services/client-tool-result.ts b/src/services/client-tool-result.ts
new file mode 100644
index 0000000000..09b7b7e534
--- /dev/null
+++ b/src/services/client-tool-result.ts
@@ -0,0 +1,29 @@
+import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
+import { useGoalStore } from "#/stores/goal-store";
+
+/**
+ * Hand a client tool's outcome back to the agent.
+ *
+ * Client tools are acknowledged by the agent-server before the browser does any
+ * work, so a prefixed `user` message is the only result channel. Sending it
+ * runs the agent, which relays the outcome in its next turn; the chat hides the
+ * raw message (see `should-render-event.ts`).
+ *
+ * The agent-server cancels an active `/goal` loop on any inbound message, so
+ * nothing is posted while one runs; callers surface the outcome to the user
+ * themselves.
+ */
+export async function postClientToolResult(
+ conversationId: string,
+ prefix: string,
+ result: unknown,
+): Promise<void> {
+ const goalStatus =
+ useGoalStore.getState().statusByConversation[conversationId];
+ if (goalStatus?.active) return;
+
+ await AgentServerConversationService.sendMessage(conversationId, {
+ role: "user",
+ content: [{ type: "text", text: `${prefix}${JSON.stringify(result)}` }],
+ });
+}
diff --git a/src/services/secret-request.ts b/src/services/secret-request.ts
new file mode 100644
index 0000000000..8529fdd7e9
--- /dev/null
+++ b/src/services/secret-request.ts
@@ -0,0 +1,127 @@
+import type { CustomSecretInput } from "#/api/agent-server-adapter";
+import { SecretsService } from "#/api/secrets-service";
+import {
+ REQUEST_SECRET_TOOL_NAME,
+ SECRET_REQUEST_RESULT_PREFIX,
+} from "#/constants/secret-request";
+import { updateConversationSecrets } from "#/hooks/mutation/conversation-mutation-utils";
+import {
+ type SecretRequest,
+ useSecretRequestStore,
+} from "#/stores/secret-request-store";
+import type { RequestSecretAction } from "#/types/agent-server/core";
+import { claimClientToolCall } from "#/utils/claim-client-tool-call";
+import { displayErrorToast } from "#/utils/custom-toast-handlers";
+import { postClientToolResult } from "./client-tool-result";
+
+const LEDGER_STORAGE_KEY_PREFIX = "openhands-secret-requests:";
+
+type SecretRequestResult =
+ | { status: "saved"; name: string }
+ | { status: "not_saved"; name: string; guidance: string }
+ | { status: "error"; name: string; error: string; guidance: string };
+
+async function findSavedSecret(
+ name: string,
+): Promise<CustomSecretInput | null> {
+ try {
+ const secrets = await SecretsService.getSecretsOrThrow();
+ return secrets.find((secret) => secret.name === name) ?? null;
+ } catch {
+ // Unknown — let the user answer; the form reports a duplicate name.
+ return null;
+ }
+}
+
+/**
+ * Execute a `request_secret` tool call. A secret the user already saved (for
+ * example in Settings after this conversation started) is attached straight
+ * away, as every saved secret is at conversation start; otherwise the request
+ * is queued for the modal, which reports through {@link completeSecretRequest}.
+ */
+export async function handleRequestSecretAction(
+ action: RequestSecretAction,
+ conversationId: string,
+ toolCallId: string,
+): Promise<void> {
+ // A replayed call would ask again and report the outcome twice.
+ if (
+ !claimClientToolCall(
+ `${LEDGER_STORAGE_KEY_PREFIX}${conversationId}`,
+ toolCallId,
+ )
+ ) {
+ return;
+ }
+
+ const request: SecretRequest = {
+ conversationId,
+ toolCallId,
+ name: action.name,
+ reason: action.reason ?? null,
+ };
+ const savedSecret = await findSavedSecret(request.name);
+ useSecretRequestStore.getState().enqueue(request);
+ if (savedSecret) {
+ await completeSecretRequest(request, savedSecret);
+ }
+}
+
+async function resolveResult(
+ request: SecretRequest,
+ savedSecret: CustomSecretInput | null,
+): Promise<SecretRequestResult> {
+ if (!savedSecret) {
+ return {
+ status: "not_saved",
+ name: request.name,
+ guidance:
+ "The user dismissed the form without saving the secret. Ask them how they want to proceed; never ask them to paste it into the chat.",
+ };
+ }
+
+ try {
+ await updateConversationSecrets(request.conversationId, [savedSecret]);
+ return { status: "saved", name: savedSecret.name };
+ } catch (error) {
+ return {
+ status: "error",
+ name: savedSecret.name,
+ error: error instanceof Error ? error.message : String(error),
+ guidance:
+ "The secret was saved to the user's settings but could not be attached to this conversation. It will be available in new conversations; tell the user.",
+ };
+ }
+}
+
+/**
+ * Hand the outcome of a secret request back to the agent. It never carries the
+ * value. Each request is reported once, whichever of the modal and the
+ * already-saved shortcut finishes first.
+ *
+ * Never rejects: the user has already answered, so a failure to report is
+ * logged rather than surfaced.
+ */
+export async function completeSecretRequest(
+ request: SecretRequest,
+ savedSecret: CustomSecretInput | null,
+): Promise<void> {
+ const store = useSecretRequestStore.getState();
+ if (!store.requests.some((r) => r.toolCallId === request.toolCallId)) return;
+ store.dismiss(request.toolCallId);
+
+ const result = await resolveResult(request, savedSecret);
+ // Tell the user even when the agent cannot be told (an active `/goal` loop).
+ if (result.status === "error") displayErrorToast(result.error);
+
+ await postClientToolResult(
+ request.conversationId,
+ SECRET_REQUEST_RESULT_PREFIX,
+ result,
+ ).catch((error) => {
+ console.warn(
+ `[${REQUEST_SECRET_TOOL_NAME}] Failed to report the request result:`,
+ error,
+ );
+ });
+}
diff --git a/src/stores/secret-request-store.ts b/src/stores/secret-request-store.ts
new file mode 100644
index 0000000000..941f24074b
--- /dev/null
+++ b/src/stores/secret-request-store.ts
@@ -0,0 +1,44 @@
+import { create } from "zustand";
+import { createJSONStorage, persist } from "zustand/middleware";
+
+export interface SecretRequest {
+ conversationId: string;
+ toolCallId: string;
+ name: string;
+ reason: string | null;
+}
+
+interface SecretRequestState {
+ /** Pending requests, oldest first; the modal shows one at a time. */
+ requests: SecretRequest[];
+}
+
+interface SecretRequestActions {
+ enqueue: (request: SecretRequest) => void;
+ dismiss: (toolCallId: string) => void;
+}
+
+// Persisted so a reload reopens a pending request: its tool call is already
+// claimed, so the replayed ActionEvent will not queue it again.
+export const useSecretRequestStore = create<
+ SecretRequestState & SecretRequestActions
+>()(
+ persist(
+ (set) => ({
+ requests: [],
+ enqueue: (request) =>
+ set((s) => ({ requests: [...s.requests, request] })),
+ dismiss: (toolCallId) =>
+ set((s) => ({
+ requests: s.requests.filter((r) => r.toolCallId !== toolCallId),
+ })),
+ }),
+ {
+ name: "openhands-pending-secret-requests",
+ storage: createJSONStorage(() => localStorage),
+ partialize: (state): SecretRequestState => ({
+ requests: state.requests,
+ }),
+ },
+ ),
+);
diff --git a/src/types/agent-server/core/base/action.ts b/src/types/agent-server/core/base/action.ts
index 52b4c03c81..3ec9e94310 100644
--- a/src/types/agent-server/core/base/action.ts
+++ b/src/types/agent-server/core/base/action.ts
@@ -1,6 +1,7 @@
import { AUTOMATION_FORM_UPDATE_ACTION_KIND } from "#/constants/automation-form";
import { CANVAS_UI_CLIENT_ACTION_KIND } from "#/constants/canvas-ui";
import { LAUNCH_CHILD_CONVERSATION_ACTION_KIND } from "#/constants/child-conversation";
+import { REQUEST_SECRET_ACTION_KIND } from "#/constants/secret-request";
import { ActionBase } from "./base";
import { TaskItem } from "./common";
@@ -353,6 +354,18 @@ export interface LaunchChildConversationAction extends ActionBase<
isolation?: string | null;
}
+/**
+ * Request for the user to provide a secret, emitted over the existing
+ * WebSocket and intercepted by handleRequestSecretAction. Carries the secret's
+ * name and purpose only — the value never passes through the agent.
+ */
+export interface RequestSecretAction extends ActionBase<
+ typeof REQUEST_SECRET_ACTION_KIND
+> {
+ name: string;
+ reason?: string | null;
+}
+
export type Action =
| MCPToolAction
| FinishAction
@@ -380,4 +393,5 @@ export type Action =
| SwitchLLMAction
| CanvasUIAction
| AutomationFormUpdateAction
- | LaunchChildConversationAction;
+ | LaunchChildConversationAction
+ | RequestSecretAction;
diff --git a/src/types/agent-server/core/base/base.ts b/src/types/agent-server/core/base/base.ts
index 3a90a2e411..077fb6d558 100644
--- a/src/types/agent-server/core/base/base.ts
+++ b/src/types/agent-server/core/base/base.ts
@@ -1,6 +1,7 @@
import { AUTOMATION_FORM_UPDATE_ACTION_KIND } from "#/constants/automation-form";
import { CANVAS_UI_CLIENT_ACTION_KIND } from "#/constants/canvas-ui";
import { LAUNCH_CHILD_CONVERSATION_ACTION_KIND } from "#/constants/child-conversation";
+import { REQUEST_SECRET_ACTION_KIND } from "#/constants/secret-request";
type EventType =
| "MCPTool"
@@ -42,7 +43,8 @@ type ActionEventType =
| "TaskAction"
| typeof CANVAS_UI_CLIENT_ACTION_KIND
| typeof AUTOMATION_FORM_UPDATE_ACTION_KIND
- | typeof LAUNCH_CHILD_CONVERSATION_ACTION_KIND;
+ | typeof LAUNCH_CHILD_CONVERSATION_ACTION_KIND
+ | typeof REQUEST_SECRET_ACTION_KIND;
type ObservationEventType =
| `${ObservationOnlyType}Observation`
| `${EventType}Observation`
diff --git a/src/types/agent-server/type-guards.ts b/src/types/agent-server/type-guards.ts
index a3150f9f5a..166bcf5feb 100644
--- a/src/types/agent-server/type-guards.ts
+++ b/src/types/agent-server/type-guards.ts
@@ -4,6 +4,7 @@ import {
LEGACY_CANVAS_UI_TOOL_NAME,
} from "#/constants/canvas-ui";
import { LAUNCH_CHILD_CONVERSATION_TOOL_NAME } from "#/constants/child-conversation";
+import { REQUEST_SECRET_TOOL_NAME } from "#/constants/secret-request";
import {
OpenHandsEvent,
@@ -21,6 +22,7 @@ import {
AutomationFormUpdateAction,
CanvasUIAction,
LaunchChildConversationAction,
+ RequestSecretAction,
} from "./core";
import {
AgentErrorEvent,
@@ -231,6 +233,12 @@ export const isLaunchChildConversationActionEvent = (
isActionEvent(event) &&
event.tool_name === LAUNCH_CHILD_CONVERSATION_TOOL_NAME;
+/** Type guard for request-secret tool ActionEvents. */
+export const isRequestSecretActionEvent = (
+ event: OpenHandsEvent,
+): event is ActionEvent<RequestSecretAction> =>
+ isActionEvent(event) && event.tool_name === REQUEST_SECRET_TOOL_NAME;
+
/**
* Type guard function to check if an event is a system prompt event
*/
diff --git a/src/utils/claim-client-tool-call.ts b/src/utils/claim-client-tool-call.ts
new file mode 100644
index 0000000000..5046960b8a
--- /dev/null
+++ b/src/utils/claim-client-tool-call.ts
@@ -0,0 +1,34 @@
+/**
+ * Remember which client tool calls have already been acted on.
+ *
+ * Unlike the Canvas UI tool, some client tools are not idempotent: replaying
+ * their ActionEvent (a socket reconnect that falls back to `resend_mode:
+ * "all"`, or a REST/WebSocket race after a reload) would repeat real work.
+ * Claim the tool call before doing any so a replay that arrives mid-flight is
+ * dropped too. Returns false when the call was already claimed.
+ */
+export function claimClientToolCall(ledgerKey: string, toolCallId: string) {
+ let handled: string[] = [];
+ try {
+ const raw = window.localStorage.getItem(ledgerKey);
+ const parsed: unknown = raw ? JSON.parse(raw) : null;
+ if (Array.isArray(parsed)) {
+ handled = parsed.filter((id): id is string => typeof id === "string");
+ }
+ } catch {
+ // A corrupt ledger must not block the call; start a fresh one.
+ }
+
+ if (handled.includes(toolCallId)) return false;
+
+ try {
+ window.localStorage.setItem(
+ ledgerKey,
+ JSON.stringify([...handled, toolCallId]),
+ );
+ } catch {
+ // Storage full or unavailable — proceed, accepting replay risk over never
+ // acting at all.
+ }
+ return true;
+}