🙌 OpenHands: AI-Driven Development
feat: show which identity an automation runs as (#17138)
Hiep Le69b849f12c17
diff --git a/__tests__/api/cloud/organization-service.test.ts b/__tests__/api/cloud/organization-service.test.tsindex 6f6690d493..b64bb55399 100644--- a/__tests__/api/cloud/organization-service.test.ts+++ b/__tests__/api/cloud/organization-service.test.ts@@ -5,6 +5,7 @@ import {setRegisteredBackends,} from "#/api/backend-registry/active-store";import {+ getCloudOrganizationMember,getCloudOrganizations,getCurrentCloudApiKey,} from "#/api/cloud/organization-service.api";@@ -109,4 +110,35 @@ describe("cloud organization-service", () => {HttpError,);});++ it("getCloudOrganizationMember hits /api/organizations/{orgId}/members/{userId} and returns the member", async () => {+ // Arrange+ const member = {+ org_id: "org-1",+ user_id: "user-1",+ email: "[email protected]",+ role: "member",+ status: "active",+ };+ fetchMock.mockResolvedValueOnce(mockJsonResponse(member));++ // Act+ const result = await getCloudOrganizationMember(+ "org-1",+ "user-1",+ cloudBackend,+ );++ // Assert+ expect(fetchMock).toHaveBeenCalledOnce();+ const [url, init] = fetchMock.mock.calls[0]!;+ expect(url).toBe(+ `${cloudBackend.host}/api/organizations/org-1/members/user-1`,+ );+ expect(init).toMatchObject({+ method: "GET",+ headers: { Authorization: "Bearer bearer-token" },+ });+ expect(result).toEqual(member);+ });});diff --git a/__tests__/components/automations/detail/configuration-section.test.tsx b/__tests__/components/automations/detail/configuration-section.test.tsxindex cd76284a31..5f634f8397 100644--- a/__tests__/components/automations/detail/configuration-section.test.tsx+++ b/__tests__/components/automations/detail/configuration-section.test.tsx@@ -131,4 +131,28 @@ describe("ConfigurationSection", () => {screen.queryByText("AUTOMATIONS$DETAIL$EVENT_FILTER"),).not.toBeInTheDocument();});++ it("renders the Automation Runs As field with the resolved identity", () => {+ // Arrange / Act — the route resolves the creator and passes it down.+ render(+ <ConfigurationSection+ automation={cronAutomation}+ runsAs="[email protected]"+ />,+ );++ // Assert+ expect(screen.getByText("AUTOMATIONS$DETAIL$RUNS_AS")).toBeInTheDocument();+ expect(screen.getByText("[email protected]")).toBeInTheDocument();+ });++ it("does not render the Automation Runs As field when no identity is provided", () => {+ // Arrange / Act — local backends and in-flight lookups pass nothing.+ render(<ConfigurationSection automation={cronAutomation} />);++ // Assert+ expect(+ screen.queryByText("AUTOMATIONS$DETAIL$RUNS_AS"),+ ).not.toBeInTheDocument();+ });});diff --git a/__tests__/routes/automation-detail.test.tsx b/__tests__/routes/automation-detail.test.tsxindex 6941dd1484..8cde11f349 100644--- a/__tests__/routes/automation-detail.test.tsx+++ b/__tests__/routes/automation-detail.test.tsx@@ -9,6 +9,7 @@ import { HttpError } from "@openhands/typescript-client";import { I18nKey } from "#/i18n/declaration";import AutomationService from "#/api/automation-service/automation-service.api";+import { getCloudOrganizationMember } from "#/api/cloud/organization-service.api";import ProfilesService from "#/api/profiles-service/profiles-service.api";import {__resetActiveStoreForTests,@@ -48,6 +49,15 @@ vi.mock("#/hooks/use-automation-permissions", () => ({useIsAutomationOwner: () => true,}));+// Mock only the member lookup the "Automation Runs As" field depends on; the+// rest of the cloud organization service keeps its real implementation.+vi.mock("#/api/cloud/organization-service.api", async (importOriginal) => ({+ ...(await importOriginal<+ typeof import("#/api/cloud/organization-service.api")+ >()),+ getCloudOrganizationMember: vi.fn(),+}));+const localBackend: Backend = {id: "local-1",name: "Local 1",@@ -263,3 +273,75 @@ describe("AutomationDetail — backend-change guard", () => {expect(AutomationService.dispatchAutomation).not.toHaveBeenCalled();});});++describe("AutomationDetail — Automation Runs As", () => {+ const creatorId = "3f1c2a54-0b8e-4c1d-9a7e-5d2f6b8c9e01";+ const orgId = "0b93b5f2-5396-49f2-8d98-61f906184270";+ const cloudAutomation: Automation = { ...automation, user_id: creatorId };++ beforeEach(() => {+ vi.mocked(getCloudOrganizationMember).mockReset();+ vi.mocked(AutomationService.getAutomation).mockResolvedValue(+ cloudAutomation,+ );+ });++ it("shows the creator's email on a cloud backend", async () => {+ // Arrange — the creator resolves to an org member with an email.+ setActiveSelection({ backendId: cloudBackend.id, orgId });+ vi.mocked(getCloudOrganizationMember).mockResolvedValue({+ org_id: orgId,+ user_id: creatorId,+ email: "[email protected]",+ });++ // Act+ renderDetail();++ // Assert — the field is labelled and shows the resolved email.+ expect(await screen.findByText("[email protected]")).toBeInTheDocument();+ expect(+ screen.getByText(I18nKey.AUTOMATIONS$DETAIL$RUNS_AS),+ ).toBeInTheDocument();+ expect(getCloudOrganizationMember).toHaveBeenCalledWith(+ orgId,+ creatorId,+ expect.objectContaining({ id: cloudBackend.id }),+ );+ });++ it("falls back to the raw user id when the member lookup fails", async () => {+ // Arrange — e.g. the creator left the org, or an older app-server+ // without the member-by-id route: the lookup 404s.+ setActiveSelection({ backendId: cloudBackend.id, orgId });+ vi.mocked(getCloudOrganizationMember).mockRejectedValue(+ new HttpError(404, "Not Found", { detail: "Member not found" }),+ );++ // Act+ renderDetail();++ // Assert — the field still identifies the run identity by id.+ expect(await screen.findByText(creatorId)).toBeInTheDocument();+ expect(+ screen.getByText(I18nKey.AUTOMATIONS$DETAIL$RUNS_AS),+ ).toBeInTheDocument();+ });++ it("does not show the field or look up the member on a local backend", async () => {+ // Arrange — default beforeEach selects the local backend.+ renderDetail();+ await waitFor(() => {+ expect(AutomationService.getAutomation).toHaveBeenCalledTimes(1);+ });++ // Act — wait for the page to render its configuration.+ expect(await screen.findByText("daily-profile")).toBeInTheDocument();++ // Assert — no identity field and no cloud call for local automations.+ expect(+ screen.queryByText(I18nKey.AUTOMATIONS$DETAIL$RUNS_AS),+ ).not.toBeInTheDocument();+ expect(getCloudOrganizationMember).not.toHaveBeenCalled();+ });+});diff --git a/src/api/cloud/organization-service.api.ts b/src/api/cloud/organization-service.api.tsindex 6553d99511..3aaf94702f 100644--- a/src/api/cloud/organization-service.api.ts+++ b/src/api/cloud/organization-service.api.ts@@ -5,6 +5,7 @@ import { callCloudProxy } from "./proxy";import type {CloudApiKeyMetadata,CloudOrganization,+ CloudOrganizationMember,CloudOrganizationsResponse,} from "./types";@@ -124,3 +125,23 @@ export async function getCloudOrganizationMe(permissions: Array.isArray(data?.permissions) ? data.permissions : null,};}++/**+ * Fetch `GET /api/organizations/{orgId}/members/{userId}`: one member of+ * `orgId` by user id. Any org member may read it (same permission as the+ * members list). The upstream responds 404 when `userId` is not (or no+ * longer) a member of the org, and older app-servers that predate the route+ * 404 as well, so callers should treat a failure as "identity unresolved".+ */+export async function getCloudOrganizationMember(+ orgId: string,+ userId: string,+ backend?: Backend,+): Promise<CloudOrganizationMember> {+ const target = resolveBackend(backend);+ return callCloudProxy<CloudOrganizationMember>({+ backend: target,+ method: "GET",+ path: `/api/organizations/${encodeURIComponent(orgId)}/members/${encodeURIComponent(userId)}`,+ });+}diff --git a/src/components/features/automations/detail/configuration-section.tsx b/src/components/features/automations/detail/configuration-section.tsxindex 9d145761c4..532200161d 100644--- a/src/components/features/automations/detail/configuration-section.tsx+++ b/src/components/features/automations/detail/configuration-section.tsx@@ -7,6 +7,7 @@ import GitBranchIcon from "#/icons/git-branch.svg?react";import CheckCircleIcon from "#/icons/check-circle.svg?react";import CalendarIcon from "#/icons/calendar.svg?react";import SparkleIcon from "#/icons/sparkle.svg?react";+import UserIcon from "#/icons/user.svg?react";import { Zap } from "lucide-react";import BellIcon from "#/icons/bell.svg?react";import CodeTagIcon from "#/icons/code-tag.svg?react";@@ -18,6 +19,12 @@ import { BranchBadge } from "./branch-badge";interface ConfigurationSectionProps {automation: Automation;+ /**+ * Identity the automation runs as — the creator's email, or their raw user+ * id when the email could not be resolved. Omitted/null hides the field+ * (local backends, or while the lookup is still in flight).+ */+ runsAs?: string | null;}const FILTER_TRUNCATE_LENGTH = 60;@@ -52,6 +59,7 @@ function FilterExpression({ filter }: { filter: string }) {export function ConfigurationSection({automation,+ runsAs,}: ConfigurationSectionProps) {const { t } = useTranslation("openhands");const isEvent = automation.trigger.type === "event";@@ -128,6 +136,15 @@ export function ConfigurationSection({</ConfigField>)}+ {runsAs && (+ <ConfigField+ icon={<UserIcon className="size-3.5" />}+ label={t(I18nKey.AUTOMATIONS$DETAIL$RUNS_AS)}+ >+ <span className="break-all">{runsAs}</span>+ </ConfigField>+ )}+<ConfigFieldicon={<SparkleIcon className="size-3.5" />}label={t(I18nKey.AUTOMATIONS$DETAIL$MODEL)}diff --git a/src/hooks/query/use-cloud-org-member.ts b/src/hooks/query/use-cloud-org-member.tsnew file mode 100644index 0000000000..2a28a58b81--- /dev/null+++ b/src/hooks/query/use-cloud-org-member.ts@@ -0,0 +1,30 @@+import { useQuery } from "@tanstack/react-query";+import { getCloudOrganizationMember } from "#/api/cloud/organization-service.api";+import { useActiveBackend } from "#/contexts/active-backend-context";++/**+ * Resolve a single org member by `userId` on the active cloud backend via+ * `GET /api/organizations/{orgId}/members/{userId}` (currently read for the+ * member's email). Disabled on local backends, where there is no org to look+ * the user up in, and until both the active org and the user id are known.+ */+export function useCloudOrgMember(userId: string | undefined) {+ const { backend, orgId } = useActiveBackend();+ const enabled = backend.kind === "cloud" && !!orgId && !!userId;++ // eslint-disable-next-line @tanstack/query/exhaustive-deps+ return useQuery({+ queryKey: [+ "cloud-org-member",+ backend.id,+ orgId,+ userId,+ backend.connectionRevision ?? 0,+ ],+ queryFn: () => getCloudOrganizationMember(orgId!, userId!, backend),+ enabled,+ staleTime: 1000 * 60 * 5,+ retry: false,+ meta: { disableToast: true },+ });+}diff --git a/src/i18n/translation.json b/src/i18n/translation.jsonindex 13362705cd..f555462abb 100644--- a/src/i18n/translation.json+++ b/src/i18n/translation.json@@ -14893,6 +14893,23 @@"uk": "Репозиторії","ca": "Repositoris"},+ "AUTOMATIONS$DETAIL$RUNS_AS": {+ "en": "Automation Runs As",+ "ja": "自動化の実行ユーザー",+ "zh-CN": "自动化运行身份",+ "zh-TW": "自動化執行身分",+ "ko-KR": "자동화 실행 계정",+ "no": "Automatiseringen kjører som",+ "it": "L'automazione viene eseguita come",+ "pt": "A automação é executada como",+ "es": "La automatización se ejecuta como",+ "ar": "تعمل الأتمتة باسم",+ "fr": "L'automatisation s'exécute en tant que",+ "tr": "Otomasyon şu kimlikle çalışır",+ "de": "Automatisierung wird ausgeführt als",+ "uk": "Автоматизація виконується від імені",+ "ca": "L'automatització s'executa com a"+ },"AUTOMATIONS$DETAIL$SCHEDULE": {"en": "Schedule","ja": "スケジュール",diff --git a/src/routes/automation-detail.tsx b/src/routes/automation-detail.tsxindex 076bc0a8cf..5fa1a754f9 100644--- a/src/routes/automation-detail.tsx+++ b/src/routes/automation-detail.tsx@@ -15,6 +15,7 @@ import {useDispatchAutomation,} from "#/hooks/query/use-automations";import { useAutomationHealth } from "#/hooks/query/use-automation-health";+import { useCloudOrgMember } from "#/hooks/query/use-cloud-org-member";import { useActiveBackend } from "#/contexts/active-backend-context";import { useNavigation } from "#/context/navigation-context";import {@@ -121,6 +122,9 @@ export default function AutomationDetail() {// owner check is a no-op while the automation hasn't loaded yet.const { canManage: hasManagePermission } = useAutomationPermissions();const isOwner = useIsAutomationOwner(automation ?? nullAutomation);+ // Creator lookup for "Automation Runs As"; disabled until the automation+ // (and its user_id) has loaded, and on non-cloud backends.+ const creatorQuery = useCloudOrgMember(automation?.user_id);const is404 = isError && getErrorStatus(error) === 404;@@ -219,6 +223,16 @@ export default function AutomationDetail() {// Write actions on a specific automation: manage OR creator (escape hatch).const canManage = hasManagePermission || isOwner;+ // Automations run as their creator (the service mints run credentials for+ // `automation.user_id`). Cloud only: show the creator's email once resolved,+ // fall back to the raw user id when the lookup fails (creator left the org,+ // or an app-server without GET /members/{user_id}), nothing while loading.+ let runsAs: string | null = null;+ if (active.backend.kind === "cloud" && automation.user_id) {+ runsAs =+ creatorQuery.data?.email ??+ (creatorQuery.isError ? automation.user_id : null);+ }// Non-creators may turn an automation off but not back on.const canToggle = automation.enabled ? canManage : isOwner;@@ -242,7 +256,7 @@ export default function AutomationDetail() {canToggle={canToggle}/>{automation.prompt && <PromptSection prompt={automation.prompt} />}- <ConfigurationSection automation={automation} />+ <ConfigurationSection automation={automation} runsAs={runsAs} />{automation.plugins && automation.plugins.length > 0 && (<PluginsSection plugins={automation.plugins} />)}