🙌 OpenHands: AI-Driven Development
feat: ship the featured automations landing dashboard (#16266)
Hiep Le6281c5082a72
diff --git a/__tests__/components/automations/detail/activity-log-section.test.tsx b/__tests__/components/automations/detail/activity-log-section.test.tsxindex 7f89203ac0..e2e28ceee8 100644--- a/__tests__/components/automations/detail/activity-log-section.test.tsx+++ b/__tests__/components/automations/detail/activity-log-section.test.tsx@@ -57,13 +57,16 @@ const run: AutomationRun = {completed_at: "2026-01-01T09:01:00Z",};-function renderSection() {+function renderSection(highlightedRunId: string | null = null) {const client = new QueryClient({defaultOptions: { queries: { retry: false } },});return render(<QueryClientProvider client={client}>- <ActivityLogSection automation={automation} />+ <ActivityLogSection+ automation={automation}+ highlightedRunId={highlightedRunId}+ /></QueryClientProvider>,);}@@ -127,3 +130,59 @@ describe("ActivityLogSection export", () => {expect(screen.getByTestId("activity-log-export-csv")).toBeDisabled();});});++describe("ActivityLogSection ?run= highlight", () => {+ function makeRuns(count: number): AutomationRun[] {+ return Array.from({ length: count }, (_, index) => ({+ ...run,+ id: `r${index + 1}`,+ }));+ }++ beforeEach(() => {+ vi.clearAllMocks();+ window.HTMLElement.prototype.scrollIntoView = vi.fn();+ });++ it("marks the deep-linked run and scrolls it into view", async () => {+ vi.mocked(useAutomationRuns).mockReturnValue({+ data: { runs: [run], total: 1 },+ isLoading: false,+ } as unknown as ReturnType<typeof useAutomationRuns>);++ renderSection("r1");++ expect(+ screen.getByTestId("automation-run-highlight-r1"),+ ).toBeInTheDocument();+ await waitFor(() => {+ expect(window.HTMLElement.prototype.scrollIntoView).toHaveBeenCalled();+ });+ });++ it("stops auto-loading pages for a missing run id at the cap", async () => {+ vi.mocked(useAutomationRuns).mockImplementation(+ (options) =>+ ({+ data: { runs: makeRuns(options.limit ?? 20), total: 500 },+ isLoading: false,+ }) as unknown as ReturnType<typeof useAutomationRuns>,+ );++ renderSection("r-missing");++ await waitFor(() => {+ expect(useAutomationRuns).toHaveBeenCalledWith({+ id: "a1",+ limit: 100,+ offset: 0,+ });+ });++ const requestedLimits = vi+ .mocked(useAutomationRuns)+ .mock.calls.map(([options]) => options.limit ?? 0);+ expect(Math.max(...requestedLimits)).toBe(100);+ expect(window.HTMLElement.prototype.scrollIntoView).not.toHaveBeenCalled();+ });+});diff --git a/__tests__/components/automations/detail/run-status-badge.test.tsx b/__tests__/components/automations/detail/run-status-badge.test.tsxindex d7034c7023..f5dd8ae856 100644--- a/__tests__/components/automations/detail/run-status-badge.test.tsx+++ b/__tests__/components/automations/detail/run-status-badge.test.tsx@@ -22,7 +22,7 @@ describe("RunStatusBadge", () => {[AutomationRunStatus.COMPLETED, "run-status-icon-completed"],[AutomationRunStatus.FAILED, "run-status-icon-failed"],[AutomationRunStatus.PENDING, "run-status-icon-pending"],- [AutomationRunStatus.RUNNING, "run-status-icon-pending"],+ [AutomationRunStatus.RUNNING, "run-status-icon-running"],[AutomationRunStatus.CANCELLED, "run-status-icon-pending"],[AutomationRunStatus.SKIPPED, "run-status-icon-pending"],])(@@ -41,4 +41,32 @@ describe("RunStatusBadge", () => {expect(screen.getByTestId("run-status-icon-pending")).toBeInTheDocument();});++ it("renders an icon-only mark with the status label as aria-label", () => {+ render(+ <RunStatusBadge status={AutomationRunStatus.COMPLETED} iconOnly />,+ );++ expect(screen.queryByText(I18nKey.AUTOMATIONS$DETAIL$SUCCESSFUL)).toBeNull();+ expect(screen.getByTestId("run-status-badge-icon")).toHaveAttribute(+ "aria-label",+ I18nKey.AUTOMATIONS$DETAIL$SUCCESSFUL,+ );+ expect(screen.getByTestId("run-status-icon-completed")).toBeInTheDocument();+ });++ it("renders the status word next to the icon when showLabel is set", () => {+ render(+ <RunStatusBadge+ status={AutomationRunStatus.PENDING}+ iconOnly+ showLabel+ />,+ );++ expect(+ screen.getByText(I18nKey.AUTOMATIONS$DETAIL$PENDING),+ ).toBeInTheDocument();+ expect(screen.getByTestId("run-status-icon-pending")).toBeInTheDocument();+ });});diff --git a/__tests__/components/features/home/automation-run-activity-sparkline.test.ts b/__tests__/components/features/home/automation-run-activity-sparkline.test.tsnew file mode 100644index 0000000000..d9855188f3--- /dev/null+++ b/__tests__/components/features/home/automation-run-activity-sparkline.test.ts@@ -0,0 +1,105 @@+import { describe, expect, it } from "vitest";+import {+ AUTOMATION_RUN_ACTIVITY_MAX_BAR_PX,+ AUTOMATION_RUN_ACTIVITY_MIN_BAR_PX,+ AUTOMATION_RUN_ACTIVITY_UNKNOWN_BAR_PX,+ barColorClassForStatus,+ durationMsToSparklineBarHeightPx,+ formatDurationForTitle,+ getAutomationRunDurationMs,+} from "#/components/features/home/featured-automations/automation-run-activity-metrics";+import { AutomationRunStatus, type AutomationRun } from "#/types/automation";++function makeRun(overrides: Partial<AutomationRun> = {}): AutomationRun {+ return {+ id: "run-1",+ status: AutomationRunStatus.COMPLETED,+ conversation_id: null,+ bash_command_id: null,+ error_detail: null,+ started_at: "2026-08-01T10:00:00.000Z",+ completed_at: "2026-08-01T10:05:00.000Z",+ ...overrides,+ };+}++describe("getAutomationRunDurationMs", () => {+ it("returns completed_at - started_at for finished runs", () => {+ expect(+ getAutomationRunDurationMs(+ makeRun({+ started_at: "2026-08-01T10:00:00.000Z",+ completed_at: "2026-08-01T10:02:30.000Z",+ }),+ ),+ ).toBe(150_000);+ });++ it("uses elapsed time for in-flight runs with a usable start", () => {+ const now = Date.parse("2026-08-01T10:03:00.000Z");+ expect(+ getAutomationRunDurationMs(+ makeRun({+ status: AutomationRunStatus.RUNNING,+ started_at: "2026-08-01T10:00:00.000Z",+ completed_at: null,+ }),+ now,+ ),+ ).toBe(180_000);+ });++ it("returns null when timestamps are missing or invalid", () => {+ expect(+ getAutomationRunDurationMs(+ makeRun({+ status: AutomationRunStatus.FAILED,+ started_at: "2026-08-01T10:00:00.000Z",+ completed_at: null,+ }),+ ),+ ).toBeNull();+ });+});++describe("durationMsToSparklineBarHeightPx", () => {+ it("maps unknown duration to the mid fallback height", () => {+ expect(durationMsToSparklineBarHeightPx(null)).toBe(+ AUTOMATION_RUN_ACTIVITY_UNKNOWN_BAR_PX,+ );+ });++ it("grows with duration between the min and max bar heights", () => {+ const shortBar = durationMsToSparklineBarHeightPx(1_000);+ const mediumBar = durationMsToSparklineBarHeightPx(60_000);+ const longBar = durationMsToSparklineBarHeightPx(30 * 60_000);++ expect(shortBar).toBe(AUTOMATION_RUN_ACTIVITY_MIN_BAR_PX);+ expect(longBar).toBe(AUTOMATION_RUN_ACTIVITY_MAX_BAR_PX);+ expect(mediumBar).toBeGreaterThan(shortBar);+ expect(mediumBar).toBeLessThan(longBar);+ });+});++describe("formatDurationForTitle", () => {+ it("formats seconds, minutes, and hours", () => {+ expect(formatDurationForTitle(12_000)).toBe("12s");+ expect(formatDurationForTitle(180_000)).toBe("3m");+ expect(formatDurationForTitle(7_200_000)).toBe("2.0h");+ });+});++describe("barColorClassForStatus", () => {+ it("uses a pulsing success green for running bars", () => {+ const classes = barColorClassForStatus(AutomationRunStatus.RUNNING);+ expect(classes).toContain("bg-[var(--oh-status-success)]");+ expect(classes).toContain("animate-pulse");+ });++ it("uses a grey diagonal hatch for pending bars", () => {+ const classes = barColorClassForStatus(AutomationRunStatus.PENDING);+ expect(classes).toContain("repeating-linear-gradient");+ expect(classes).toContain("var(--oh-muted)");+ expect(classes).toContain("var(--oh-border)");+ });+});diff --git a/__tests__/components/features/home/build-pinned-automation-menu-items.test.ts b/__tests__/components/features/home/build-pinned-automation-menu-items.test.tsnew file mode 100644index 0000000000..2b11d9bcdb--- /dev/null+++ b/__tests__/components/features/home/build-pinned-automation-menu-items.test.ts@@ -0,0 +1,116 @@+import { describe, expect, it, vi } from "vitest";+import { buildHomeAutomationMenuItems } from "#/components/features/home/featured-automations/build-home-automation-menu-items";+import { I18nKey } from "#/i18n/declaration";+import type { Automation } from "#/types/automation";++function makeAutomation(overrides: Partial<Automation> = {}): Automation {+ return {+ id: "auto-1",+ name: "Daily digest",+ prompt: "Summarize",+ trigger: {+ type: "cron",+ schedule: "0 9 * * *",+ schedule_human: "Daily at 09:00",+ },+ enabled: true,+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ ...overrides,+ };+}++function itemKeys(+ entries: ReturnType<typeof buildHomeAutomationMenuItems>,+): string[] {+ return entries+ .filter((entry) => entry.kind === "item")+ .map((entry) => entry.key);+}++describe("buildHomeAutomationMenuItems", () => {+ it("orders run / view / edit / turn off / pin with a separator", () => {+ const entries = buildHomeAutomationMenuItems({+ automation: makeAutomation(),+ t: (key) => key,+ canManage: true,+ canEdit: true,+ isRunPending: false,+ isCancelPending: false,+ canCancel: false,+ testIdPrefix: "running-automation",+ pinTestId: "running-automation-pin-auto-1",+ isPinned: false,+ onRunNow: vi.fn(),+ onCancelRun: vi.fn(),+ onView: vi.fn(),+ onEdit: vi.fn(),+ onTurnOff: vi.fn(),+ onTogglePin: vi.fn(),+ });++ expect(itemKeys(entries)).toEqual([+ "run-now",+ "view",+ "edit",+ "turn-off",+ "pin",+ ]);+ expect(entries.some((entry) => entry.kind === "separator")).toBe(true);+ const pinItem = entries.find(+ (entry) => entry.kind === "item" && entry.key === "pin",+ );+ expect(pinItem?.kind === "item" && pinItem.label).toBe(+ I18nKey.FEATURED_AUTOMATIONS$PIN,+ );+ });++ it("adds cancel run for in-flight automations and disables run now", () => {+ const entries = buildHomeAutomationMenuItems({+ automation: makeAutomation(),+ t: (key) => key,+ canManage: true,+ canEdit: false,+ isRunPending: false,+ isCancelPending: false,+ canCancel: true,+ testIdPrefix: "pinned-automation",+ pinTestId: "unpin-automation-auto-1",+ isPinned: true,+ onRunNow: vi.fn(),+ onCancelRun: vi.fn(),+ onView: vi.fn(),+ onTurnOff: vi.fn(),+ onTogglePin: vi.fn(),+ });++ expect(itemKeys(entries)).toContain("cancel-run");+ const runNow = entries.find(+ (entry) => entry.kind === "item" && entry.key === "run-now",+ );+ expect(runNow?.kind === "item" && runNow.disabled).toBe(true);+ });++ it("omits manage actions when the user cannot manage automations", () => {+ const entries = buildHomeAutomationMenuItems({+ automation: makeAutomation(),+ t: (key) => key,+ canManage: false,+ canEdit: true,+ isRunPending: false,+ isCancelPending: false,+ canCancel: false,+ testIdPrefix: "running-automation",+ pinTestId: "running-automation-pin-auto-1",+ isPinned: false,+ onRunNow: vi.fn(),+ onCancelRun: vi.fn(),+ onView: vi.fn(),+ onEdit: vi.fn(),+ onTurnOff: vi.fn(),+ onTogglePin: vi.fn(),+ });++ expect(itemKeys(entries)).toEqual(["view", "pin"]);+ });+});diff --git a/__tests__/components/features/home/featured-automations-section.test.tsx b/__tests__/components/features/home/featured-automations-section.test.tsxnew file mode 100644index 0000000000..c75b3149a3--- /dev/null+++ b/__tests__/components/features/home/featured-automations-section.test.tsx@@ -0,0 +1,466 @@+import { beforeEach, describe, expect, it, vi } from "vitest";+import React from "react";+import { render, screen, waitFor, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";++import AutomationService from "#/api/automation-service/automation-service.api";+import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";+import type { AppConversation } from "#/api/conversation-service/agent-server-conversation-service.types";+import { PinnedAutomationsDashboard } from "#/components/features/home/featured-automations/pinned-automations-dashboard";+import { RunningAutomationsList } from "#/components/features/home/featured-automations/running-automations-list";+import { NavigationProvider } from "#/context/navigation-context";+import { HOME_PINNED_AUTOMATIONS_KEY } from "#/hooks/use-home-pinned-automations";+import {+ AutomationRunStatus,+ type Automation,+ type AutomationRun,+} from "#/types/automation";+import { displayErrorToast } from "#/utils/custom-toast-handlers";++vi.mock("react-i18next", () => ({+ useTranslation: () => ({+ t: (key: string, options?: { name?: string; count?: number }) => {+ if (options?.name) return `${key}:${options.name}`;+ if (options?.count != null) return `${key}:${options.count}`;+ return key;+ },+ i18n: { language: "en" },+ }),+}));++vi.mock("#/api/automation-service/automation-service.api", () => ({+ default: {+ checkHealth: vi.fn(),+ getAutomations: vi.fn(),+ getAutomationRuns: vi.fn(),+ dispatchAutomation: vi.fn(),+ toggleAutomation: vi.fn(),+ cancelAutomationRun: vi.fn(),+ },+}));++vi.mock("#/utils/custom-toast-handlers", () => ({+ displaySuccessToast: vi.fn(),+ displayErrorToast: vi.fn(),+}));++vi.mock(+ "#/api/conversation-service/agent-server-conversation-service.api",+ () => ({+ default: { batchGetAppConversations: vi.fn() },+ }),+);++function makeAutomation(overrides: Partial<Automation> = {}): Automation {+ return {+ id: "auto-1",+ name: "Daily digest",+ prompt: "Summarize yesterday's PRs",+ trigger: {+ type: "cron",+ schedule: "0 9 * * *",+ schedule_human: "Daily at 09:00",+ },+ enabled: true,+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ ...overrides,+ };+}++function makeRun(overrides: Partial<AutomationRun> = {}): AutomationRun {+ return {+ id: "run-1",+ status: AutomationRunStatus.COMPLETED,+ conversation_id: "conv-1",+ bash_command_id: "cmd-1",+ error_detail: null,+ started_at: "2026-08-01T10:00:00Z",+ completed_at: "2026-08-01T10:05:00Z",+ ...overrides,+ };+}++function makeConversation(id: string, title: string | null): AppConversation {+ return {+ id,+ created_by_user_id: null,+ selected_repository: null,+ selected_branch: null,+ git_provider: null,+ title,+ trigger: null,+ pr_number: [],+ llm_model: null,+ metrics: null,+ created_at: "2026-01-01T00:00:00Z",+ updated_at: "2026-01-01T00:00:00Z",+ execution_status: null,+ sandbox_status: null,+ conversation_url: "https://sandbox.example.com/api",+ session_api_key: null,+ sandbox_id: null,+ sub_conversation_ids: [],+ };+}++/** Pins are stored under a backend/org-scoped key; find it by prefix. */+function getStoredPinnedIds(): string | null {+ const key = Object.keys(window.localStorage).find((storageKey) =>+ storageKey.startsWith(HOME_PINNED_AUTOMATIONS_KEY),+ );+ return key ? window.localStorage.getItem(key) : null;+}++function renderHomeAutomations(ui: React.ReactElement) {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return render(+ <QueryClientProvider client={queryClient}>+ <NavigationProvider+ value={{+ currentPath: "/",+ conversationId: null,+ isNavigating: false,+ navigate: vi.fn(),+ }}+ >+ {ui}+ </NavigationProvider>+ </QueryClientProvider>,+ );+}++beforeEach(() => {+ vi.clearAllMocks();+ window.localStorage.clear();+ vi.mocked(AutomationService.checkHealth).mockResolvedValue({ status: "ok" });+ vi.mocked(AutomationService.getAutomations).mockResolvedValue({+ automations: [makeAutomation()],+ total: 1,+ });+ vi.mocked(AutomationService.getAutomationRuns).mockResolvedValue({+ runs: [makeRun()],+ total: 1,+ });+ vi.mocked(AutomationService.dispatchAutomation).mockResolvedValue(makeRun());+ vi.mocked(AutomationService.toggleAutomation).mockResolvedValue(+ makeAutomation({ enabled: false }),+ );+ vi.mocked(+ AgentServerConversationService.batchGetAppConversations,+ ).mockResolvedValue([]);+});++describe("home automations composer layout", () => {+ it("lists rows with accessible health labels and a manage control", async () => {+ vi.mocked(AutomationService.getAutomations).mockResolvedValue({+ automations: [+ makeAutomation({ id: "auto-1", name: "Daily digest" }),+ makeAutomation({ id: "auto-2", name: "PR review" }),+ makeAutomation({+ id: "auto-3",+ name: "Disabled sweep",+ enabled: false,+ }),+ ],+ total: 3,+ });+ vi.mocked(AutomationService.getAutomationRuns).mockImplementation(+ async (id: string) => {+ if (id === "auto-2") {+ return {+ runs: [+ makeRun({+ id: "run-2",+ status: AutomationRunStatus.FAILED,+ error_detail: "boom",+ }),+ ],+ total: 1,+ };+ }+ return { runs: [makeRun()], total: 1 };+ },+ );++ renderHomeAutomations(<RunningAutomationsList />);++ expect(+ await screen.findByRole("link", {+ name: /Daily digest\s*FEATURED_AUTOMATIONS\$LAST_RUN_SUCCEEDED/,+ }),+ ).toBeInTheDocument();+ expect(+ await screen.findByRole("link", {+ name: /PR review\s*FEATURED_AUTOMATIONS\$LAST_RUN_FAILED/,+ }),+ ).toBeInTheDocument();+ expect(screen.queryByText("Disabled sweep")).not.toBeInTheDocument();+ expect(screen.getByTestId("home-automations-manage")).toHaveAttribute(+ "href",+ "/automations",+ );+ });++ it("renders nothing when the automation service is unavailable", async () => {+ vi.mocked(AutomationService.checkHealth).mockResolvedValue({+ status: "error",+ message: "unreachable",+ });++ renderHomeAutomations(<RunningAutomationsList />);++ await waitFor(() =>+ expect(AutomationService.checkHealth).toHaveBeenCalledTimes(1),+ );+ expect(+ screen.queryByTestId("running-automations-list"),+ ).not.toBeInTheDocument();+ expect(AutomationService.getAutomations).not.toHaveBeenCalled();+ });++ it("renders nothing when there are no enabled automations", async () => {+ vi.mocked(AutomationService.getAutomations).mockResolvedValue({+ automations: [makeAutomation({ enabled: false })],+ total: 1,+ });++ renderHomeAutomations(<RunningAutomationsList />);++ await waitFor(() =>+ expect(AutomationService.getAutomations).toHaveBeenCalledTimes(1),+ );+ expect(+ screen.queryByTestId("running-automations-list"),+ ).not.toBeInTheDocument();+ });++ it("lists enabled automations with live run status and conversation links", async () => {+ vi.mocked(AutomationService.getAutomations).mockResolvedValue({+ automations: [+ makeAutomation({ id: "auto-1", name: "Daily digest" }),+ makeAutomation({+ id: "auto-2",+ name: "PR review",+ trigger: {+ type: "event",+ source: "github",+ on: "pull_request.opened",+ },+ }),+ ],+ total: 2,+ });+ vi.mocked(AutomationService.getAutomationRuns).mockImplementation(+ async (id: string) => {+ if (id === "auto-2") {+ return {+ runs: [+ makeRun({+ id: "run-2",+ status: AutomationRunStatus.PENDING,+ conversation_id: null,+ started_at: "1970-01-01T00:00:00Z",+ completed_at: null,+ }),+ ],+ total: 1,+ };+ }+ return { runs: [makeRun()], total: 1 };+ },+ );++ renderHomeAutomations(<RunningAutomationsList />);++ expect(+ await screen.findByTestId("running-automations-list"),+ ).toBeInTheDocument();++ expect(screen.getByRole("link", { name: /Daily digest/ })).toHaveAttribute(+ "href",+ "/conversations/conv-1",+ );+ expect(screen.getByRole("link", { name: /PR review/ })).toHaveAttribute(+ "href",+ "/automations/auto-2",+ );+ expect(+ screen.getByText("Daily at 09:00", { exact: false }),+ ).toBeInTheDocument();+ });++ it("previews 10 rows, expands with View more, then offers View All at 20", async () => {+ const automations = Array.from({ length: 20 }, (_, index) =>+ makeAutomation({+ id: `auto-${index + 1}`,+ name: `Automation ${index + 1}`,+ }),+ );+ vi.mocked(AutomationService.getAutomations).mockResolvedValue({+ automations,+ total: 20,+ });+ vi.mocked(AutomationService.getAutomationRuns).mockResolvedValue({+ runs: [makeRun()],+ total: 1,+ });+ const user = userEvent.setup();++ renderHomeAutomations(<RunningAutomationsList />);++ expect(+ await screen.findByTestId("running-automations-list"),+ ).toBeInTheDocument();+ expect(screen.getByText("Automation 1")).toBeInTheDocument();+ expect(screen.getByText("Automation 10")).toBeInTheDocument();+ expect(screen.queryByText("Automation 11")).not.toBeInTheDocument();++ await user.click(screen.getByTestId("home-automations-view-more"));++ expect(screen.getByText("Automation 11")).toBeInTheDocument();+ expect(screen.getByText("Automation 20")).toBeInTheDocument();+ expect(+ screen.queryByTestId("home-automations-view-more"),+ ).not.toBeInTheDocument();+ expect(screen.getByTestId("home-automations-view-all")).toHaveAttribute(+ "href",+ "/automations",+ );+ });++ it("pins from the row menu into a rich dashboard card with conversation title and failure detail", async () => {+ vi.mocked(AutomationService.getAutomations).mockResolvedValue({+ automations: [+ makeAutomation({ id: "auto-1", name: "Daily digest" }),+ makeAutomation({ id: "auto-2", name: "PR review" }),+ ],+ total: 2,+ });+ vi.mocked(AutomationService.getAutomationRuns).mockImplementation(+ async (id: string) => {+ if (id === "auto-2") {+ return {+ runs: [+ makeRun({+ id: "run-2",+ status: AutomationRunStatus.FAILED,+ conversation_id: null,+ error_detail: "sandbox timeout",+ }),+ ],+ total: 1,+ };+ }+ return { runs: [makeRun()], total: 1 };+ },+ );+ vi.mocked(+ AgentServerConversationService.batchGetAppConversations,+ ).mockResolvedValue([+ makeConversation("conv-1", "Reviewed the release PR"),+ ]);+ const user = userEvent.setup();++ renderHomeAutomations(+ <>+ <PinnedAutomationsDashboard />+ <RunningAutomationsList />+ </>,+ );++ expect(+ await screen.findByTestId("running-automations-list"),+ ).toBeInTheDocument();++ await user.click(screen.getByTestId("running-automation-menu-auto-1"));+ expect(+ screen.getByTestId("running-automation-run-auto-1"),+ ).toBeInTheDocument();+ expect(+ screen.getByTestId("running-automation-view-auto-1"),+ ).toBeInTheDocument();+ expect(+ screen.getByTestId("running-automation-edit-auto-1"),+ ).toBeInTheDocument();+ expect(+ screen.getByTestId("running-automation-turn-off-auto-1"),+ ).toBeInTheDocument();+ await user.click(screen.getByTestId("running-automation-pin-auto-1"));++ const dashboard = await screen.findByTestId("pinned-automations-dashboard");+ expect(+ within(dashboard).getByTestId("pinned-automation-card-auto-1"),+ ).toBeInTheDocument();+ expect(+ await within(dashboard).findByRole("link", {+ name: "Reviewed the release PR",+ }),+ ).toHaveAttribute("href", "/conversations/conv-1");++ await user.click(screen.getByTestId("running-automation-menu-auto-2"));+ await user.click(screen.getByTestId("running-automation-pin-auto-2"));+ expect(+ await within(dashboard).findByText("sandbox timeout"),+ ).toBeInTheDocument();+ expect(+ within(dashboard).getByText("AUTOMATIONS$DETAIL$NO_CONVERSATION"),+ ).toBeInTheDocument();++ expect(getStoredPinnedIds()).toContain("auto-1");++ await user.click(screen.getByTestId("pinned-automation-menu-auto-1"));+ expect(+ screen.getByTestId("pinned-automation-run-auto-1"),+ ).toBeInTheDocument();+ expect(+ screen.getByTestId("pinned-automation-view-auto-1"),+ ).toBeInTheDocument();+ expect(+ screen.getByTestId("pinned-automation-edit-auto-1"),+ ).toBeInTheDocument();+ expect(+ screen.getByTestId("pinned-automation-turn-off-auto-1"),+ ).toBeInTheDocument();++ await user.click(screen.getByTestId("pinned-automation-run-auto-1"));+ await waitFor(() => {+ expect(AutomationService.dispatchAutomation).toHaveBeenCalledWith(+ "auto-1",+ );+ });++ await user.click(screen.getByTestId("pinned-automation-menu-auto-1"));+ await user.click(screen.getByTestId("unpin-automation-auto-1"));+ expect(+ screen.queryByTestId("pinned-automation-card-auto-1"),+ ).not.toBeInTheDocument();+ });++ it("shows an error toast when turning an automation off fails", async () => {+ vi.mocked(AutomationService.toggleAutomation).mockRejectedValue(+ new Error("backend unavailable"),+ );+ const user = userEvent.setup();++ renderHomeAutomations(<RunningAutomationsList />);++ await screen.findByTestId("running-automations-list");+ await user.click(screen.getByTestId("running-automation-menu-auto-1"));+ await user.click(screen.getByTestId("running-automation-turn-off-auto-1"));+ await user.click(screen.getByTestId("turn-off-automation-confirm"));++ await waitFor(() => {+ expect(AutomationService.toggleAutomation).toHaveBeenCalledWith(+ "auto-1",+ false,+ );+ });+ await waitFor(() => {+ expect(displayErrorToast).toHaveBeenCalled();+ });+ });+});diff --git a/__tests__/hooks/use-home-pinned-automations.test.ts b/__tests__/hooks/use-home-pinned-automations.test.tsnew file mode 100644index 0000000000..79a28e61d2--- /dev/null+++ b/__tests__/hooks/use-home-pinned-automations.test.ts@@ -0,0 +1,46 @@+import { describe, expect, it } from "vitest";+import {+ applyPinnedOrder,+ getHomePinnedAutomationsKey,+ HOME_PINNED_AUTOMATIONS_KEY,+ movePinnedId,+} from "#/hooks/use-home-pinned-automations";++describe("getHomePinnedAutomationsKey", () => {+ it("scopes the storage key by backend and org", () => {+ expect(getHomePinnedAutomationsKey("backend-a", "org-1")).toBe(+ `${HOME_PINNED_AUTOMATIONS_KEY}:backend-a:org-1`,+ );+ expect(getHomePinnedAutomationsKey("backend-a", null)).toBe(+ `${HOME_PINNED_AUTOMATIONS_KEY}:backend-a:-`,+ );+ expect(getHomePinnedAutomationsKey("backend-a", "org-1")).not.toBe(+ getHomePinnedAutomationsKey("backend-b", "org-1"),+ );+ });+});++describe("movePinnedId", () => {+ it("reorders an id before or after a target", () => {+ expect(movePinnedId(["a", "b", "c"], "c", "a", "before")).toEqual([+ "c",+ "a",+ "b",+ ]);+ expect(movePinnedId(["a", "b", "c"], "a", "b", "after")).toEqual([+ "b",+ "a",+ "c",+ ]);+ });+});++describe("applyPinnedOrder", () => {+ it("applies a preferred order while keeping unknown base ids", () => {+ expect(applyPinnedOrder(["a", "b", "c"], ["c", "a"])).toEqual([+ "c",+ "a",+ "b",+ ]);+ });+});diff --git a/src/api/automation-service/automation-service.api.ts b/src/api/automation-service/automation-service.api.tsindex 101377d30f..2b93e3cc42 100644--- a/src/api/automation-service/automation-service.api.ts+++ b/src/api/automation-service/automation-service.api.ts@@ -432,6 +432,27 @@ class AutomationService {return data;}+ /**+ * Cancel a pending or running automation run.+ * Backend: POST /api/automation/v1/runs/{run_id}/cancel+ */+ static async cancelAutomationRun(runId: string): Promise<AutomationRun> {+ const active = getActiveBackend().backend;+ const path = `${AUTOMATION_BASE_PATH}/v1/runs/${encodeURIComponent(runId)}/cancel`;++ if (active.kind === "cloud") {+ return callCloudProxy<AutomationRun>({+ backend: active,+ method: "POST",+ path,+ headers: await buildAutomationRequestHeaders(),+ });+ }++ const { data } = await localAutomationAxios.post<AutomationRun>(path);+ return data;+ }+static async listAutomationRuns(id: string,params: { limit?: number; offset?: number } = {},diff --git a/src/components/features/automations/automation-card.tsx b/src/components/features/automations/automation-card.tsxindex c13a07d4a3..78af4eeb1b 100644--- a/src/components/features/automations/automation-card.tsx+++ b/src/components/features/automations/automation-card.tsx@@ -7,7 +7,7 @@ import { useHasPermission } from "#/hooks/use-has-permission";import { useNavigation } from "#/context/navigation-context";import PlayIcon from "#/icons/play.svg?react";import ClockIcon from "#/icons/clock.svg?react";-import GlobeIcon from "#/icons/globe.svg?react";+import { Zap } from "lucide-react";import { SkillCardPillRow } from "#/components/features/skills/skill-card-pill-row";import { cn } from "#/utils/utils";import {@@ -88,7 +88,7 @@ export function AutomationCard({<div className="flex min-w-0 flex-1 flex-col gap-1.5"><h3 className="flex items-center gap-2 truncate text-sm font-semibold text-white">{automation.trigger.type === "event" ? (- <GlobeIcon className="size-4 shrink-0 text-muted" />+ <Zap className="size-4 shrink-0 text-muted" aria-hidden="true" />) : (<ClockIcon className="size-4 shrink-0 text-muted" />)}diff --git a/src/components/features/automations/automation-list-row.tsx b/src/components/features/automations/automation-list-row.tsxindex c8e911569e..538b1367ce 100644--- a/src/components/features/automations/automation-list-row.tsx+++ b/src/components/features/automations/automation-list-row.tsx@@ -7,7 +7,7 @@ import { useHasPermission } from "#/hooks/use-has-permission";import { useNavigation } from "#/context/navigation-context";import PlayIcon from "#/icons/play.svg?react";import ClockIcon from "#/icons/clock.svg?react";-import GlobeIcon from "#/icons/globe.svg?react";+import { Zap } from "lucide-react";import { StyledTooltip } from "#/components/shared/buttons/styled-tooltip";import { SkillCardPillRow } from "#/components/features/skills/skill-card-pill-row";import { cn } from "#/utils/utils";@@ -85,7 +85,7 @@ export function AutomationListRow({<td className={automationListCellClassName}><div className="flex min-w-0 items-center gap-1.5">{automation.trigger.type === "event" ? (- <GlobeIcon className="size-4 shrink-0 text-muted" />+ <Zap className="size-4 shrink-0 text-muted" aria-hidden="true" />) : (<ClockIcon className="size-4 shrink-0 text-muted" />)}diff --git a/src/components/features/automations/build-automation-pills.tsx b/src/components/features/automations/build-automation-pills.tsxindex 246bb04ab5..4fa3cc8ca0 100644--- a/src/components/features/automations/build-automation-pills.tsx+++ b/src/components/features/automations/build-automation-pills.tsx@@ -1,7 +1,7 @@import FolderIcon from "#/icons/folder.svg?react";import ClockIcon from "#/icons/clock.svg?react";import SparkleIcon from "#/icons/sparkle.svg?react";-import GlobeIcon from "#/icons/globe.svg?react";+import { Zap } from "lucide-react";import type { SkillCardPill } from "#/components/features/skills/skill-card-pill-row";import type { Automation } from "#/types/automation";import { cn } from "#/utils/utils";@@ -38,7 +38,7 @@ export function buildAutomationMetadataPills(id: "event-trigger",node: (<span className={cn(extensionModuleCardPillClassName, "gap-1")}>- <GlobeIcon className="size-3 shrink-0" />+ <Zap className="size-3 shrink-0" aria-hidden="true" />{eventLabel}</span>),diff --git a/src/components/features/automations/detail/activity-log-item.tsx b/src/components/features/automations/detail/activity-log-item.tsxindex c56735389d..38037f76f5 100644--- a/src/components/features/automations/detail/activity-log-item.tsx+++ b/src/components/features/automations/detail/activity-log-item.tsx@@ -97,8 +97,8 @@ export function ActivityLogItem({ run, automation }: ActivityLogItemProps) {<div className="flex items-center gap-3"><span className="text-sm text-content">{formattedTimestamp}</span>{showNoConversationLabel && (- <span className="text-xs text-muted italic">- ({t(I18nKey.AUTOMATIONS$DETAIL$NO_CONVERSATION)})+ <span className="text-xs text-muted">+ {t(I18nKey.AUTOMATIONS$DETAIL$NO_CONVERSATION)}</span>)}</div>diff --git a/src/components/features/automations/detail/activity-log-section.tsx b/src/components/features/automations/detail/activity-log-section.tsxindex 3458340928..66a9876708 100644--- a/src/components/features/automations/detail/activity-log-section.tsx+++ b/src/components/features/automations/detail/activity-log-section.tsx@@ -1,10 +1,11 @@-import { useState } from "react";+import { useEffect, useRef, useState } from "react";import { useTranslation } from "react-i18next";import { I18nKey } from "#/i18n/declaration";import { useAutomationRuns } from "#/hooks/query/use-automation-detail";import { useActiveBackend } from "#/contexts/active-backend-context";import { useTracking } from "#/hooks/use-tracking";import ActivityIcon from "#/icons/activity.svg?react";+import { cn } from "#/utils/utils";import { displayErrorToast } from "#/utils/custom-toast-handlers";import { getApiErrorMessage } from "#/utils/api-error-message";import { downloadActivityLogExport } from "#/utils/automation-activity-log-export";@@ -13,15 +14,27 @@ import { ActivityLogItem } from "./activity-log-item";interface ActivityLogSectionProps {automation: Automation;+ /** Optional run id from `?run=` to scroll/highlight in the log. */+ highlightedRunId?: string | null;}const PAGE_SIZE = 20;-export function ActivityLogSection({ automation }: ActivityLogSectionProps) {+/**+ * Upper bound on auto-loading while searching for a `?run=` deep link, so a+ * stale or bogus run id cannot page through the entire run history.+ */+const HIGHLIGHT_AUTO_LOAD_MAX_RUNS = 100;++export function ActivityLogSection({+ automation,+ highlightedRunId = null,+}: ActivityLogSectionProps) {const { t } = useTranslation("openhands");const active = useActiveBackend();const { trackAutomationActivityLogExported } = useTracking();const [limit, setLimit] = useState(PAGE_SIZE);+ const highlightedRef = useRef<HTMLDivElement | null>(null);const [isExporting, setIsExporting] = useState(false);const { data, isLoading } = useAutomationRuns({id: automation.id,@@ -57,8 +70,26 @@ export function ActivityLogSection({ automation }: ActivityLogSectionProps) {}};+ useEffect(() => {+ if (!highlightedRunId || !data?.runs.length) return;+ const index = data.runs.findIndex((run) => run.id === highlightedRunId);+ if (index < 0) {+ if (hasMore && limit < HIGHLIGHT_AUTO_LOAD_MAX_RUNS) {+ setLimit((prev) => prev + PAGE_SIZE);+ }+ return;+ }+ highlightedRef.current?.scrollIntoView({+ behavior: "smooth",+ block: "center",+ });+ }, [data?.runs, hasMore, highlightedRunId, limit]);+return (- <div className="rounded-2xl border border-[var(--oh-border)] bg-[var(--oh-surface)]">+ <div+ data-testid="automation-activity-log"+ className="rounded-2xl border border-[var(--oh-border)] bg-[var(--oh-surface)]"+ ><div className="flex items-center gap-2 border-b border-[var(--oh-border)] px-5 py-3"><span className="size-4 text-muted"><ActivityIcon className="size-4" />@@ -110,14 +141,26 @@ export function ActivityLogSection({ automation }: ActivityLogSectionProps) {{!isLoading && data && data.runs.length > 0 && (<div>- {data.runs.map((run, index) => (- <div- key={run.id}- className={index > 0 ? "border-t border-[var(--oh-border)]" : ""}- >- <ActivityLogItem run={run} automation={automation} />- </div>- ))}+ {data.runs.map((run, index) => {+ const isHighlighted = run.id === highlightedRunId;+ return (+ <div+ key={run.id}+ ref={isHighlighted ? highlightedRef : undefined}+ data-testid={+ isHighlighted+ ? `automation-run-highlight-${run.id}`+ : undefined+ }+ className={cn(+ index > 0 ? "border-t border-[var(--oh-border)]" : "",+ isHighlighted && "bg-[var(--oh-focus)]/10",+ )}+ >+ <ActivityLogItem run={run} automation={automation} />+ </div>+ );+ })}{hasMore && (<div className="border-t border-[var(--oh-border)] px-5 py-3">diff --git a/src/components/features/automations/detail/activity-section.tsx b/src/components/features/automations/detail/activity-section.tsxindex f4c63784cb..286c4c4f26 100644--- a/src/components/features/automations/detail/activity-section.tsx+++ b/src/components/features/automations/detail/activity-section.tsx@@ -3,6 +3,7 @@ import { I18nKey } from "#/i18n/declaration";import ActivityIcon from "#/icons/activity.svg?react";import CalendarIcon from "#/icons/calendar.svg?react";import ClockIcon from "#/icons/clock.svg?react";+import { formatDate, formatRelativeTime } from "#/utils/format-relative-time";import { SectionCard } from "./section-card";import { ConfigField } from "./config-field";@@ -11,38 +12,6 @@ interface ActivitySectionProps {lastRunAt: string | null | undefined;}-function formatDate(dateStr: string, locale: string): string {- const date = new Date(dateStr);- return date.toLocaleDateString(locale, {- year: "numeric",- month: "short",- day: "numeric",- });-}--function formatRelativeTime(- dateStr: string,- locale: string,- t: (key: I18nKey, options?: Record<string, unknown>) => string,-): string {- const now = Date.now();- const then = new Date(dateStr).getTime();- const diffMs = now - then;- const diffMins = Math.floor(diffMs / 60_000);- const diffHours = Math.floor(diffMs / 3_600_000);- const diffDays = Math.floor(diffMs / 86_400_000);-- if (diffMins < 1) return t(I18nKey.AUTOMATIONS$DETAIL$TIME_JUST_NOW);- if (diffMins < 60)- return t(I18nKey.AUTOMATIONS$DETAIL$TIME_MINUTES_AGO, { count: diffMins });- if (diffHours < 24)- return t(I18nKey.AUTOMATIONS$DETAIL$TIME_HOURS_AGO, { count: diffHours });- if (diffDays === 1) return t(I18nKey.AUTOMATIONS$DETAIL$TIME_YESTERDAY);- if (diffDays < 7)- return t(I18nKey.AUTOMATIONS$DETAIL$TIME_DAYS_AGO, { count: diffDays });- return formatDate(dateStr, locale);-}-export function ActivitySection({createdAt,lastRunAt,diff --git a/src/components/features/automations/detail/configuration-section.tsx b/src/components/features/automations/detail/configuration-section.tsxindex 9de89c908f..9d145761c4 100644--- a/src/components/features/automations/detail/configuration-section.tsx+++ b/src/components/features/automations/detail/configuration-section.tsx@@ -7,8 +7,8 @@ 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 { Zap } from "lucide-react";import BellIcon from "#/icons/bell.svg?react";-import GlobeIcon from "#/icons/globe.svg?react";import CodeTagIcon from "#/icons/code-tag.svg?react";import LinkExternalIcon from "#/icons/link-external.svg?react";import { formatEventOn } from "#/utils/automation-schedule";@@ -103,7 +103,7 @@ export function ConfigurationSection({{isEvent && automation.trigger.source && (<ConfigField- icon={<GlobeIcon className="size-3.5" />}+ icon={<Zap className="size-3.5" aria-hidden="true" />}label={t(I18nKey.AUTOMATIONS$DETAIL$EVENT_SOURCE)}>{automation.trigger.source}diff --git a/src/components/features/automations/detail/run-status-badge.tsx b/src/components/features/automations/detail/run-status-badge.tsxindex 38b213833b..27b2ade21c 100644--- a/src/components/features/automations/detail/run-status-badge.tsx+++ b/src/components/features/automations/detail/run-status-badge.tsx@@ -1,4 +1,6 @@+import { Loader2 } from "lucide-react";import { useTranslation } from "react-i18next";+import { StyledTooltip } from "#/components/shared/buttons/styled-tooltip";import { I18nKey } from "#/i18n/declaration";import CheckCircleIcon from "#/icons/check-circle.svg?react";import XCircleIcon from "#/icons/x-circle.svg?react";@@ -8,77 +10,152 @@ import { cn } from "#/utils/utils";interface RunStatusBadgeProps {status: AutomationRunStatus;+ /**+ * Icon-only mark (no pill). Status text is available via hover tooltip and+ * `aria-label`, unless {@link showLabel} is also set.+ */+ iconOnly?: boolean;+ /** With `iconOnly`, render the status word next to the icon (still no pill). */+ showLabel?: boolean;+ /** Smaller pill for dense rows (e.g. home activity meta line). */+ compact?: boolean;}const statusConfig: Record<AutomationRunStatus,- { label: I18nKey; style: string }+ { label: I18nKey; style: string; iconTone: string }> = {[AutomationRunStatus.COMPLETED]: {label: I18nKey.AUTOMATIONS$DETAIL$SUCCESSFUL,style:"border-[var(--oh-success)]/50 bg-[var(--oh-success)]/10 text-[var(--oh-success)]",+ iconTone: "text-[var(--oh-success)]",},[AutomationRunStatus.FAILED]: {label: I18nKey.AUTOMATIONS$DETAIL$FAILED,style: "border-[var(--oh-danger)]/50 bg-[var(--oh-danger)]/10 text-danger",+ iconTone: "text-danger",},[AutomationRunStatus.PENDING]: {label: I18nKey.AUTOMATIONS$DETAIL$PENDING,style: "border-[var(--oh-border)] bg-surface-raised text-muted",+ iconTone: "text-muted",},[AutomationRunStatus.RUNNING]: {label: I18nKey.AUTOMATIONS$DETAIL$RUNNING,style: "border-[var(--oh-border)] bg-surface-raised text-muted",+ iconTone: "text-muted",},[AutomationRunStatus.CANCELLED]: {label: I18nKey.AUTOMATIONS$DETAIL$CANCELLED,style: "border-[var(--oh-border)] bg-surface-raised text-muted",+ iconTone: "text-muted",},[AutomationRunStatus.SKIPPED]: {label: I18nKey.AUTOMATIONS$DETAIL$SKIPPED,style: "border-[var(--oh-border)] bg-surface-raised text-muted",+ iconTone: "text-muted",},};-function StatusIcon({ status }: { status: AutomationRunStatus }) {+function StatusIcon({+ status,+ compact = false,+}: {+ status: AutomationRunStatus;+ compact?: boolean;+}) {+ const iconClass = compact ? "size-3" : "size-3.5";switch (status) {case AutomationRunStatus.COMPLETED:return (<CheckCircleIcondata-testid="run-status-icon-completed"- className="size-3.5"+ className={iconClass}/>);case AutomationRunStatus.FAILED:return (<XCircleIcondata-testid="run-status-icon-failed"- className="size-3.5"+ className={iconClass}+ />+ );+ case AutomationRunStatus.RUNNING:+ return (+ <Loader2+ data-testid="run-status-icon-running"+ className={cn(iconClass, "animate-spin motion-reduce:animate-none")}+ aria-hidden="true"/>);default:return (- <ClockIcon data-testid="run-status-icon-pending" className="size-3.5" />+ <ClockIcon+ data-testid="run-status-icon-pending"+ className={iconClass}+ />);}}-export function RunStatusBadge({ status }: RunStatusBadgeProps) {+export function RunStatusBadge({+ status,+ iconOnly = false,+ showLabel = false,+ compact = false,+}: RunStatusBadgeProps) {const { t } = useTranslation("openhands");// Degrade instead of crashing on a status the backend added after this enum.const config =statusConfig[status] ?? statusConfig[AutomationRunStatus.PENDING];+ const label = t(config.label);++ if (iconOnly) {+ if (showLabel) {+ return (+ <span+ data-testid="run-status-badge-icon"+ className={cn(+ "inline-flex min-w-0 shrink-0 items-center gap-1.5 text-xs font-medium",+ config.iconTone,+ )}+ >+ <StatusIcon status={status} compact={compact} />+ <span className="truncate">{label}</span>+ </span>+ );+ }++ return (+ <StyledTooltip content={label} placement="top">+ <span+ role="img"+ aria-label={label}+ data-testid="run-status-badge-icon"+ className={cn(+ "inline-flex shrink-0 cursor-default items-center justify-center",+ config.iconTone,+ )}+ >+ <StatusIcon status={status} compact={compact} />+ </span>+ </StyledTooltip>+ );+ }return (<spanclassName={cn(- "inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs font-medium",+ "inline-flex items-center rounded-full border font-medium",+ compact+ ? "gap-1 px-1.5 py-0 text-[10px] leading-4"+ : "gap-1.5 px-2.5 py-1 text-xs",config.style,)}>- <StatusIcon status={status} />- {t(config.label)}+ <StatusIcon status={status} compact={compact} />+ {label}</span>);}diff --git a/src/components/features/automations/turn-off-confirmation-modal.tsx b/src/components/features/automations/turn-off-confirmation-modal.tsxnew file mode 100644index 0000000000..0e79703f8a--- /dev/null+++ b/src/components/features/automations/turn-off-confirmation-modal.tsx@@ -0,0 +1,80 @@+import { useTranslation } from "react-i18next";+import { I18nKey } from "#/i18n/declaration";+import XMarkIcon from "#/icons/x-mark.svg?react";+import { modalTitleLgMediumClassName } from "#/utils/modal-classes";++interface TurnOffConfirmationModalProps {+ automationName: string;+ isOpen: boolean;+ onConfirm: () => void;+ onCancel: () => void;+}++export function TurnOffConfirmationModal({+ automationName,+ isOpen,+ onConfirm,+ onCancel,+}: TurnOffConfirmationModalProps) {+ const { t } = useTranslation("openhands");++ if (!isOpen) return null;++ return (+ <div className="fixed inset-0 z-50 flex items-center justify-center">+ <div+ className="absolute inset-0 bg-black/60"+ onClick={onCancel}+ onKeyDown={(e) => {+ if (e.key === "Escape") onCancel();+ }}+ role="presentation"+ />+ <div+ role="dialog"+ aria-modal="true"+ aria-labelledby="turn-off-automation-title"+ className="relative w-full max-w-sm rounded-xl border border-[var(--oh-border)] bg-[var(--oh-surface)] p-6"+ >+ <button+ type="button"+ onClick={onCancel}+ className="absolute right-4 top-4 text-muted hover:text-foreground"+ aria-label={t(I18nKey.BUTTON$CLOSE)}+ >+ <XMarkIcon className="size-5" />+ </button>++ <h2+ id="turn-off-automation-title"+ className={modalTitleLgMediumClassName}+ >+ {t(I18nKey.AUTOMATIONS$TURN_OFF_CONFIRM_TITLE)}+ </h2>+ <p className="mt-2 text-sm text-muted">+ {t(I18nKey.AUTOMATIONS$TURN_OFF_CONFIRM_MESSAGE, {+ name: automationName,+ })}+ </p>++ <div className="mt-6 flex justify-end gap-3">+ <button+ type="button"+ onClick={onCancel}+ className="rounded-lg border border-[var(--oh-border)] px-4 py-2 text-sm text-white hover:bg-surface-raised"+ >+ {t(I18nKey.AUTOMATIONS$CANCEL)}+ </button>+ <button+ type="button"+ data-testid="turn-off-automation-confirm"+ onClick={onConfirm}+ className="rounded-lg bg-danger px-4 py-2 text-sm text-white hover:bg-danger/80"+ >+ {t(I18nKey.AUTOMATIONS$TURN_OFF)}+ </button>+ </div>+ </div>+ </div>+ );+}diff --git a/src/components/features/context-menu/context-menu-list-item.tsx b/src/components/features/context-menu/context-menu-list-item.tsxindex c27c1fd841..8e70ed058c 100644--- a/src/components/features/context-menu/context-menu-list-item.tsx+++ b/src/components/features/context-menu/context-menu-list-item.tsx@@ -6,6 +6,7 @@ interface ContextMenuListItemProps {onClick: (event: React.MouseEvent<HTMLButtonElement>) => void;isDisabled?: boolean;className?: string;+ ref?: React.Ref<HTMLButtonElement>;}export function ContextMenuListItem({@@ -14,9 +15,11 @@ export function ContextMenuListItem({onClick,isDisabled,className,+ ref,}: React.PropsWithChildren<ContextMenuListItemProps>) {return (<button+ ref={ref}data-testid={testId || "context-menu-list-item"}type="button"onClick={onClick}diff --git a/src/components/features/home/featured-automations/automation-health-indicator.tsx b/src/components/features/home/featured-automations/automation-health-indicator.tsxnew file mode 100644index 0000000000..07781b3953--- /dev/null+++ b/src/components/features/home/featured-automations/automation-health-indicator.tsx@@ -0,0 +1,44 @@+import { cn } from "#/utils/utils";+import type { AutomationRunHealth } from "./automation-run-health";++interface AutomationHealthIndicatorProps {+ health: AutomationRunHealth;+}++/**+ * Visual-only latest-run health mark. Decorative on purpose: the owning+ * control carries the translated status text (e.g. via sr-only), so the+ * indicator itself is hidden from assistive technology.+ */+export function AutomationHealthIndicator({+ health,+}: AutomationHealthIndicatorProps) {+ if (health === "success") {+ return (+ <svg+ viewBox="0 0 12 12"+ className="h-2.5 w-2.5 shrink-0 stroke-[var(--oh-status-success)]"+ fill="none"+ strokeWidth={2.25}+ strokeLinecap="round"+ strokeLinejoin="round"+ aria-hidden="true"+ >+ <path d="M2.5 6.5 5 9l4.5-5.5" />+ </svg>+ );+ }++ return (+ <span+ aria-hidden="true"+ className={cn(+ "h-1.5 w-1.5 shrink-0 rounded-full",+ health === "failed" && "bg-[var(--oh-status-error)]",+ health === "in_progress" &&+ "animate-pulse bg-[var(--oh-status-success)] motion-reduce:animate-none",+ (health === "none" || health === "unknown") && "bg-[var(--oh-border)]",+ )}+ />+ );+}diff --git a/src/components/features/home/featured-automations/automation-run-activity-metrics.ts b/src/components/features/home/featured-automations/automation-run-activity-metrics.tsnew file mode 100644index 0000000000..996ff005f2--- /dev/null+++ b/src/components/features/home/featured-automations/automation-run-activity-metrics.ts@@ -0,0 +1,118 @@+import { I18nKey } from "#/i18n/declaration";+import { AutomationRunStatus, type AutomationRun } from "#/types/automation";++/** Sparkline track height; bars sit on the baseline inside this. */+export const AUTOMATION_RUN_ACTIVITY_TRACK_PX = 18;+export const AUTOMATION_RUN_ACTIVITY_MIN_BAR_PX = 6;+export const AUTOMATION_RUN_ACTIVITY_MAX_BAR_PX = 15;+/** Used when duration cannot be derived (no timestamps, skipped, etc.). */+export const AUTOMATION_RUN_ACTIVITY_UNKNOWN_BAR_PX = 11;++const MIN_DURATION_MS = 1_000;+/** Log-scale ceiling so multi-hour runs still fit the track. */+const MAX_DURATION_MS = 30 * 60_000;++/**+ * Wall-clock duration for a run, or null when it cannot be measured.+ * In-flight runs use elapsed time since `started_at` when that is usable.+ */+export function getAutomationRunDurationMs(+ run: AutomationRun,+ nowMs: number = Date.now(),+): number | null {+ const startMs = run.started_at ? new Date(run.started_at).getTime() : NaN;+ if (Number.isNaN(startMs) || startMs <= 0) return null;++ if (run.completed_at) {+ const endMs = new Date(run.completed_at).getTime();+ if (Number.isNaN(endMs) || endMs < startMs) return null;+ return endMs - startMs;+ }++ if (+ run.status === AutomationRunStatus.PENDING ||+ run.status === AutomationRunStatus.RUNNING+ ) {+ return Math.max(0, nowMs - startMs);+ }++ return null;+}++/** Map duration → bar height (log scale, clamped). Color stays status-driven. */+export function durationMsToSparklineBarHeightPx(+ durationMs: number | null,+): number {+ if (durationMs == null || durationMs <= 0) {+ return AUTOMATION_RUN_ACTIVITY_UNKNOWN_BAR_PX;+ }++ const clamped = Math.min(+ MAX_DURATION_MS,+ Math.max(MIN_DURATION_MS, durationMs),+ );+ const t =+ Math.log(clamped / MIN_DURATION_MS) /+ Math.log(MAX_DURATION_MS / MIN_DURATION_MS);++ return Math.round(+ AUTOMATION_RUN_ACTIVITY_MIN_BAR_PX ++ t *+ (AUTOMATION_RUN_ACTIVITY_MAX_BAR_PX -+ AUTOMATION_RUN_ACTIVITY_MIN_BAR_PX),+ );+}++export function barColorClassForStatus(+ status: AutomationRunStatus | string,+): string {+ switch (status) {+ case AutomationRunStatus.COMPLETED:+ return "bg-[var(--oh-status-success)]";+ case AutomationRunStatus.FAILED:+ return "bg-[var(--oh-status-error)]";+ case AutomationRunStatus.RUNNING:+ return "bg-[var(--oh-status-success)] animate-pulse motion-reduce:animate-none";+ case AutomationRunStatus.PENDING:+ // Grey hatch so pending reads as queued, distinct from solid cancelled/skipped.+ return "bg-[repeating-linear-gradient(-45deg,var(--oh-muted)_0_1.5px,var(--oh-border)_1.5px_3px)]";+ case AutomationRunStatus.CANCELLED:+ return "bg-[var(--oh-muted)]";+ default:+ return "bg-[var(--oh-border)]";+ }+}++export function getAutomationRunStatusLabelKey(+ status: AutomationRunStatus | string,+): I18nKey {+ switch (status) {+ case AutomationRunStatus.COMPLETED:+ return I18nKey.AUTOMATIONS$DETAIL$SUCCESSFUL;+ case AutomationRunStatus.FAILED:+ return I18nKey.AUTOMATIONS$DETAIL$FAILED;+ case AutomationRunStatus.PENDING:+ return I18nKey.AUTOMATIONS$DETAIL$PENDING;+ case AutomationRunStatus.RUNNING:+ return I18nKey.AUTOMATIONS$DETAIL$RUNNING;+ case AutomationRunStatus.CANCELLED:+ return I18nKey.AUTOMATIONS$DETAIL$CANCELLED;+ case AutomationRunStatus.SKIPPED:+ return I18nKey.AUTOMATIONS$DETAIL$SKIPPED;+ default:+ return I18nKey.FEATURED_AUTOMATIONS$STATUS_UNKNOWN;+ }+}++export function formatDurationForTitle(+ durationMs: number | null,+): string | null {+ if (durationMs == null || durationMs <= 0) return null;+ if (durationMs < 60_000) {+ return `${Math.max(1, Math.round(durationMs / 1000))}s`;+ }+ if (durationMs < 3_600_000) {+ return `${Math.round(durationMs / 60_000)}m`;+ }+ return `${(durationMs / 3_600_000).toFixed(1)}h`;+}diff --git a/src/components/features/home/featured-automations/automation-run-activity-sparkline.tsx b/src/components/features/home/featured-automations/automation-run-activity-sparkline.tsxnew file mode 100644index 0000000000..2b3aadbbd4--- /dev/null+++ b/src/components/features/home/featured-automations/automation-run-activity-sparkline.tsx@@ -0,0 +1,193 @@+import { Tooltip } from "@heroui/react";+import { useEffect, useState, type ReactNode } from "react";+import { useTranslation } from "react-i18next";+import { NavigationLink } from "#/components/shared/navigation-link";+import { AUTOMATION_RUN_ACTIVITY_LIMIT } from "#/hooks/query/use-latest-automation-runs";+import { isInFlightAutomationRun } from "#/hooks/use-home-automation-actions";+import { I18nKey } from "#/i18n/declaration";+import { AutomationRunStatus, type AutomationRun } from "#/types/automation";+import { formatRelativeTime } from "#/utils/format-relative-time";+import { cn } from "#/utils/utils";+import { getLastRunTimestamp } from "./automation-run-health";+import {+ AUTOMATION_RUN_ACTIVITY_TRACK_PX,+ barColorClassForStatus,+ durationMsToSparklineBarHeightPx,+ formatDurationForTitle,+ getAutomationRunDurationMs,+ getAutomationRunStatusLabelKey,+} from "./automation-run-activity-metrics";++interface AutomationRunActivitySparklineProps {+ automationId: string;+ /** Newest-first run list (same order as the runs API). */+ runs: readonly AutomationRun[];+ testId?: string;+}++function TooltipRow({+ label,+ children,+}: {+ label: string;+ children: ReactNode;+}) {+ return (+ <div className="flex items-start gap-2 text-xs">+ <span className="w-16 shrink-0 text-[var(--oh-muted)]">{label}</span>+ <span className="min-w-0 flex-1 break-words text-white">{children}</span>+ </div>+ );+}++function RunActivityBarTooltip({+ run,+ nowMs,+}: {+ run: AutomationRun;+ nowMs: number;+}) {+ const { t, i18n } = useTranslation("openhands");+ const timestamp = getLastRunTimestamp(run);+ const when = timestamp+ ? formatRelativeTime(timestamp, i18n.language, t)+ : null;+ const durationMs = getAutomationRunDurationMs(run, nowMs);+ const durationLabel = formatDurationForTitle(durationMs);+ const statusLabel = t(getAutomationRunStatusLabelKey(run.status));+ const errorDetail =+ run.status === AutomationRunStatus.FAILED+ ? run.error_detail?.trim() || null+ : null;++ return (+ <div className="flex w-[220px] flex-col gap-2 p-3">+ <div className="flex items-center gap-2">+ <span+ aria-hidden="true"+ className={cn(+ "h-3 w-1.5 shrink-0 rounded-[1px]",+ barColorClassForStatus(run.status),+ )}+ />+ <span className="text-sm font-medium text-white">{statusLabel}</span>+ </div>++ <div className="flex flex-col gap-1">+ {when ? (+ <TooltipRow label={t(I18nKey.AUTOMATIONS$DETAIL$LAST_RUN)}>+ {when}+ </TooltipRow>+ ) : null}+ {durationLabel ? (+ <TooltipRow label={t(I18nKey.FEATURED_AUTOMATIONS$RUN_DURATION)}>+ {durationLabel}+ </TooltipRow>+ ) : null}+ </div>++ {errorDetail ? (+ <p className="line-clamp-3 text-xs text-[var(--oh-status-error)]">+ {errorDetail}+ </p>+ ) : null}+ </div>+ );+}++function RunActivityBar({+ automationId,+ run,+ nowMs,+}: {+ automationId: string;+ run: AutomationRun;+ nowMs: number;+}) {+ const { t } = useTranslation("openhands");+ const durationMs = getAutomationRunDurationMs(run, nowMs);+ const statusLabel = t(getAutomationRunStatusLabelKey(run.status));+ const disableAnimation = import.meta.env.MODE === "test";+ const href = `/automations/${encodeURIComponent(automationId)}?run=${encodeURIComponent(run.id)}`;++ return (+ <Tooltip+ content={<RunActivityBarTooltip run={run} nowMs={nowMs} />}+ placement="top"+ closeDelay={80}+ delay={200}+ disableAnimation={disableAnimation}+ className="rounded-xl border border-[var(--oh-border)] bg-base-secondary p-0 text-white shadow-xl"+ >+ {/* Wider hit target than the 4px bar so cancelled/skipped greys are easy to inspect. */}+ <NavigationLink+ to={href}+ aria-label={statusLabel}+ className="group/spark-bar inline-flex h-full cursor-pointer items-end px-[2px] focus:outline-none focus-visible:ring-1 focus-visible:ring-[var(--oh-focus)]"+ onMouseDown={(event) => event.stopPropagation()}+ onClick={(event) => event.stopPropagation()}+ >+ <span+ className={cn(+ "w-1 shrink-0 origin-bottom rounded-[1px]",+ "transition-transform duration-100 ease-out motion-reduce:transition-none",+ // Grow the hovered/focused bar so it reads clearly among neighbors.+ "group-hover/spark-bar:scale-x-[1.4] group-hover/spark-bar:scale-y-[1.15]",+ "group-focus-visible/spark-bar:scale-x-[1.4] group-focus-visible/spark-bar:scale-y-[1.15]",+ barColorClassForStatus(run.status),+ )}+ style={{ height: durationMsToSparklineBarHeightPx(durationMs) }}+ />+ </NavigationLink>+ </Tooltip>+ );+}++/**+ * Colored-bar sparkline of recent automation runs (oldest → newest left to+ * right). Color encodes status; height encodes run duration (log-scaled).+ * Bars link to the automation detail page focused on that run.+ */+export function AutomationRunActivitySparkline({+ automationId,+ runs,+ testId,+}: AutomationRunActivitySparklineProps) {+ const { t } = useTranslation("openhands");+ const hasInFlight = runs.some((run) => isInFlightAutomationRun(run));+ const [nowMs, setNowMs] = useState(() => Date.now());++ useEffect(() => {+ if (!hasInFlight) return undefined;+ // Tick while a run is in flight so bar height tracks elapsed time between+ // the slower runs-list polls.+ const id = window.setInterval(() => setNowMs(Date.now()), 1000);+ return () => window.clearInterval(id);+ }, [hasInFlight]);++ if (runs.length === 0) return null;++ // API is newest-first; reverse so the sparkline reads left→right as time.+ const bars = [...runs].reverse().slice(-AUTOMATION_RUN_ACTIVITY_LIMIT);++ return (+ <span+ data-testid={testId}+ aria-label={t(I18nKey.FEATURED_AUTOMATIONS$RUN_ACTIVITY_LABEL, {+ count: bars.length,+ })}+ className="inline-flex shrink-0 items-end"+ style={{ height: AUTOMATION_RUN_ACTIVITY_TRACK_PX }}+ onMouseDown={(event) => event.preventDefault()}+ >+ {bars.map((run, index) => (+ <RunActivityBar+ key={`${run.id}-${index}`}+ automationId={automationId}+ run={run}+ nowMs={nowMs}+ />+ ))}+ </span>+ );+}diff --git a/src/components/features/home/featured-automations/automation-run-health.ts b/src/components/features/home/featured-automations/automation-run-health.tsnew file mode 100644index 0000000000..01751a63af--- /dev/null+++ b/src/components/features/home/featured-automations/automation-run-health.ts@@ -0,0 +1,136 @@+import type { LatestAutomationRunState } from "#/hooks/query/use-latest-automation-runs";+import { I18nKey } from "#/i18n/declaration";+import {+ AutomationRunStatus,+ type Automation,+ type AutomationRun,+} from "#/types/automation";+import { formatEventOn } from "#/utils/automation-schedule";++export type AutomationRunHealth =+ | "success"+ | "failed"+ | "in_progress"+ | "none"+ | "unknown";++export function deriveRunHealth(+ state: LatestAutomationRunState,+): AutomationRunHealth {+ if (state.isLoading || state.isError) return "unknown";+ if (!state.latestRun) return "none";+ switch (state.latestRun.status) {+ case AutomationRunStatus.COMPLETED:+ return "success";+ case AutomationRunStatus.FAILED:+ return "failed";+ case AutomationRunStatus.PENDING:+ case AutomationRunStatus.RUNNING:+ return "in_progress";+ // CANCELLED, SKIPPED, and any status the backend adds after this enum.+ default:+ return "unknown";+ }+}++export function getRunHealthLabelKey(health: AutomationRunHealth): I18nKey {+ switch (health) {+ case "success":+ return I18nKey.FEATURED_AUTOMATIONS$LAST_RUN_SUCCEEDED;+ case "failed":+ return I18nKey.FEATURED_AUTOMATIONS$LAST_RUN_FAILED;+ case "in_progress":+ return I18nKey.FEATURED_AUTOMATIONS$RUN_IN_PROGRESS;+ case "none":+ return I18nKey.AUTOMATIONS$DETAIL$NO_RUNS;+ default:+ return I18nKey.FEATURED_AUTOMATIONS$STATUS_UNKNOWN;+ }+}++/** Known event sources rendered with brand casing; others title-case. */+const TRIGGER_SOURCE_LABELS: Record<string, string> = {+ github: "GitHub",+ gitlab: "GitLab",+ slack: "Slack",+ linear: "Linear",+ jira: "Jira",+};++export function formatTriggerSourceLabel(source: string): string {+ const key = source.trim().toLowerCase();+ if (!key) return source;+ return (+ TRIGGER_SOURCE_LABELS[key] ??+ key.replace(/\b\w/g, (char) => char.toUpperCase())+ );+}++export function getTriggerEventLabel(automation: Automation): string | null {+ const { trigger } = automation;+ if (trigger.type !== "event") return null;+ return trigger.on ? formatEventOn(trigger.on) : null;+}++export function getTriggerSource(automation: Automation): string | null {+ const { trigger } = automation;+ if (trigger.type !== "event") return null;+ return trigger.source?.trim() || null;+}++export function getTriggerScheduleLabel(automation: Automation): string | null {+ const { trigger } = automation;+ if (trigger.type === "event") return null;+ return trigger.schedule_human || trigger.schedule || trigger.type || null;+}++export function getTriggerSummary(automation: Automation): string {+ const { trigger } = automation;+ if (trigger.type === "event") {+ const source = getTriggerSource(automation);+ return [+ getTriggerEventLabel(automation) ?? "",+ source ? `(${formatTriggerSourceLabel(source)})` : "",+ ]+ .filter(Boolean)+ .join(" ");+ }+ return getTriggerScheduleLabel(automation) ?? trigger.type;+}++/** Inline status-row preview length (keeps the status area to one line). */+const ERROR_DETAIL_INLINE_MAX = 48;++/**+ * Short preview for the pinned-card status row. Prefer the first sentence,+ * then hard-truncate so the row stays single-line.+ */+export function shortenAutomationErrorDetail(detail: string): string {+ const trimmed = detail.trim().replace(/\s+/g, " ");+ if (!trimmed) return trimmed;+ const firstSentence = trimmed.match(/^.*?[.!?](?=\s|$)/)?.[0] ?? trimmed;+ if (firstSentence.length <= ERROR_DETAIL_INLINE_MAX) return firstSentence;+ return `${firstSentence.slice(0, ERROR_DETAIL_INLINE_MAX - 1).trimEnd()}…`;+}++/** True when the inline preview is shortened and the full message belongs in a hovercard. */+export function shouldShowAutomationErrorHovercard(+ detail: string,+ shortDetail: string = shortenAutomationErrorDetail(detail),+): boolean {+ return detail.trim().replace(/\s+/g, " ") !== shortDetail;+}++/**+ * Timestamp to show as the run's "last run" moment, or null when the run+ * has no usable timestamp yet. The backend leaves started_at unset+ * (epoch/zero) while a run is PENDING and only populates it once execution+ * begins.+ */+export function getLastRunTimestamp(run: AutomationRun): string | null {+ const candidate = run.completed_at ?? run.started_at;+ if (!candidate) return null;+ const time = new Date(candidate).getTime();+ if (Number.isNaN(time) || time === 0) return null;+ return candidate;+}diff --git a/src/components/features/home/featured-automations/build-home-automation-menu-items.tsx b/src/components/features/home/featured-automations/build-home-automation-menu-items.tsxnew file mode 100644index 0000000000..e9ec0b4e88--- /dev/null+++ b/src/components/features/home/featured-automations/build-home-automation-menu-items.tsx@@ -0,0 +1,141 @@+import { FileText, Pin, Square } from "lucide-react";+import type { ReactNode } from "react";+import PlayIcon from "#/icons/play.svg?react";+import PowerIcon from "#/icons/power.svg?react";+import EditIcon from "#/icons/u-edit.svg?react";+import { I18nKey } from "#/i18n/declaration";+import type { Automation } from "#/types/automation";++export type HomeAutomationMenuEntry =+ | {+ kind: "item";+ key: string;+ label: string;+ icon: ReactNode;+ onClick: () => void;+ disabled?: boolean;+ testId: string;+ }+ | { kind: "separator"; key: string };++interface BuildHomeAutomationMenuItemsOptions {+ automation: Automation;+ t: (key: I18nKey) => string;+ canManage: boolean;+ canEdit: boolean;+ isRunPending: boolean;+ isCancelPending: boolean;+ canCancel: boolean;+ testIdPrefix: string;+ pinTestId: string;+ isPinned: boolean;+ onRunNow: () => void;+ onCancelRun: () => void;+ onView: () => void;+ onEdit?: () => void;+ onTurnOff: () => void;+ onTogglePin: () => void;+}++/**+ * Home featured-automation kebab (pinned cards + activity rows):+ * quick actions first, separator, then pin/unpin.+ */+export function buildHomeAutomationMenuItems({+ automation,+ t,+ canManage,+ canEdit,+ isRunPending,+ isCancelPending,+ canCancel,+ testIdPrefix,+ pinTestId,+ isPinned,+ onRunNow,+ onCancelRun,+ onView,+ onEdit,+ onTurnOff,+ onTogglePin,+}: BuildHomeAutomationMenuItemsOptions): HomeAutomationMenuEntry[] {+ const items: HomeAutomationMenuEntry[] = [];++ if (canManage) {+ items.push({+ kind: "item",+ key: "run-now",+ label: t(I18nKey.AUTOMATIONS$RUN_NOW),+ icon: <PlayIcon className="size-4" />,+ onClick: onRunNow,+ disabled: isRunPending || !automation.enabled || canCancel,+ testId: `${testIdPrefix}-run-${automation.id}`,+ });+ }++ if (canManage && canCancel) {+ items.push({+ kind: "item",+ key: "cancel-run",+ label: t(I18nKey.AUTOMATIONS$CANCEL_RUN),+ icon: <Square className="size-3.5 fill-current" aria-hidden />,+ onClick: onCancelRun,+ disabled: isCancelPending,+ testId: `${testIdPrefix}-cancel-${automation.id}`,+ });+ }++ items.push({+ kind: "item",+ key: "view",+ label: t(I18nKey.COMMON$VIEW),+ icon: <FileText className="size-4" aria-hidden />,+ onClick: onView,+ testId: `${testIdPrefix}-view-${automation.id}`,+ });++ if (canManage && canEdit && onEdit) {+ items.push({+ kind: "item",+ key: "edit",+ label: t(I18nKey.AUTOMATIONS$EDIT),+ icon: <EditIcon className="size-4" />,+ onClick: onEdit,+ testId: `${testIdPrefix}-edit-${automation.id}`,+ });+ }++ if (canManage) {+ items.push({+ kind: "item",+ key: "turn-off",+ label: t(I18nKey.AUTOMATIONS$TURN_OFF),+ icon: <PowerIcon className="size-4" />,+ onClick: onTurnOff,+ testId: `${testIdPrefix}-turn-off-${automation.id}`,+ });+ }++ items.push(+ { kind: "separator", key: "pin-separator" },+ {+ kind: "item",+ key: "pin",+ label: t(+ isPinned+ ? I18nKey.FEATURED_AUTOMATIONS$UNPIN+ : I18nKey.FEATURED_AUTOMATIONS$PIN,+ ),+ icon: (+ <Pin+ className={isPinned ? "size-3.5 fill-current" : "size-3.5"}+ aria-hidden="true"+ />+ ),+ onClick: onTogglePin,+ testId: pinTestId,+ },+ );++ return items;+}diff --git a/src/components/features/home/featured-automations/build-pinned-automation-menu-items.tsx b/src/components/features/home/featured-automations/build-pinned-automation-menu-items.tsxnew file mode 100644index 0000000000..2253ea63e3--- /dev/null+++ b/src/components/features/home/featured-automations/build-pinned-automation-menu-items.tsx@@ -0,0 +1,40 @@+import type { I18nKey } from "#/i18n/declaration";+import type { Automation } from "#/types/automation";+import {+ buildHomeAutomationMenuItems,+ type HomeAutomationMenuEntry,+} from "./build-home-automation-menu-items";++export type PinnedAutomationMenuItem = HomeAutomationMenuEntry;++interface BuildPinnedAutomationMenuItemsOptions {+ automation: Automation;+ t: (key: I18nKey) => string;+ canManage: boolean;+ canEdit: boolean;+ isRunPending: boolean;+ isCancelPending: boolean;+ canCancel: boolean;+ onRunNow: () => void;+ onCancelRun: () => void;+ onView: () => void;+ onEdit?: () => void;+ onTurnOff: () => void;+ onUnpin: () => void;+}++/** Thin wrapper for pinned cards — always unpin, with card-scoped test ids. */+export function buildPinnedAutomationMenuItems({+ onUnpin,+ automation,+ ...rest+}: BuildPinnedAutomationMenuItemsOptions): PinnedAutomationMenuItem[] {+ return buildHomeAutomationMenuItems({+ ...rest,+ automation,+ testIdPrefix: "pinned-automation",+ pinTestId: `unpin-automation-${automation.id}`,+ isPinned: true,+ onTogglePin: onUnpin,+ });+}diff --git a/src/components/features/home/featured-automations/home-automation-activity.ts b/src/components/features/home/featured-automations/home-automation-activity.tsnew file mode 100644index 0000000000..26f1cf41b7--- /dev/null+++ b/src/components/features/home/featured-automations/home-automation-activity.ts@@ -0,0 +1,91 @@+import type { LatestAutomationRunState } from "#/hooks/query/use-latest-automation-runs";+import { I18nKey } from "#/i18n/declaration";+import { AutomationRunStatus, type Automation } from "#/types/automation";+import { formatRelativeTime } from "#/utils/format-relative-time";+import {+ getLastRunTimestamp,+ getTriggerSummary,+} from "./automation-run-health";++/** Live home-page row/card model derived from an automation + its latest run. */+export interface HomeAutomationActivityItem {+ id: string;+ name: string;+ triggerSummary: string;+ /** Null when the automation has never run (or the run fetch failed). */+ status: AutomationRunStatus | null;+ /** Relative time label, or null when there is no usable timestamp. */+ whenLabel: string | null;+ conversationId: string | null;+}++type Translate = (key: I18nKey, options?: Record<string, unknown>) => string;++export function buildHomeAutomationActivityItem(+ automation: Automation,+ runState: LatestAutomationRunState,+ locale: string,+ t: Translate,+): HomeAutomationActivityItem {+ const { latestRun } = runState;+ const timestamp = latestRun ? getLastRunTimestamp(latestRun) : null;++ return {+ id: automation.id,+ name: automation.name,+ triggerSummary: getTriggerSummary(automation),+ status: latestRun?.status ?? null,+ whenLabel: timestamp ? formatRelativeTime(timestamp, locale, t) : null,+ conversationId: latestRun?.conversation_id ?? null,+ };+}++function activitySortScore(+ automationId: string,+ runStates: Map<string, LatestAutomationRunState>,+): number {+ const state = runStates.get(automationId);+ const status = state?.latestRun?.status;+ if (+ status === AutomationRunStatus.PENDING ||+ status === AutomationRunStatus.RUNNING+ ) {+ return Number.MAX_SAFE_INTEGER;+ }+ const timestamp = state?.latestRun+ ? getLastRunTimestamp(state.latestRun)+ : null;+ return timestamp ? new Date(timestamp).getTime() : 0;+}++/**+ * Map enabled automations + latest-run state into sorted activity rows+ * (in-flight first, then newest last-run timestamp).+ */+export function buildHomeAutomationActivityItems(+ automations: readonly Automation[],+ runStates: Map<string, LatestAutomationRunState>,+ locale: string,+ t: Translate,+ unknownRunState: LatestAutomationRunState,+): HomeAutomationActivityItem[] {+ return [...automations]+ .map((automation) =>+ buildHomeAutomationActivityItem(+ automation,+ runStates.get(automation.id) ?? unknownRunState,+ locale,+ t,+ ),+ )+ .sort(+ (a, b) =>+ activitySortScore(b.id, runStates) - activitySortScore(a.id, runStates),+ );+}++export function hrefForActivityItem(item: HomeAutomationActivityItem): string {+ return item.conversationId+ ? `/conversations/${item.conversationId}`+ : `/automations/${item.id}`;+}diff --git a/src/components/features/home/featured-automations/home-automation-menu.tsx b/src/components/features/home/featured-automations/home-automation-menu.tsxnew file mode 100644index 0000000000..cc6c260936--- /dev/null+++ b/src/components/features/home/featured-automations/home-automation-menu.tsx@@ -0,0 +1,205 @@+import {+ useEffect,+ useLayoutEffect,+ useReducer,+ useRef,+ useState,+} from "react";+import { createPortal } from "react-dom";+import { KebabMenuItemContent } from "#/components/features/automations/kebab-menu-item-content";+import { ContextMenuListItem } from "#/components/features/context-menu/context-menu-list-item";+import { EllipsisButton } from "#/components/features/conversation-panel/ellipsis-button";+import { useClickOutsideElement } from "#/hooks/use-click-outside-element";+import { MenuSeparator } from "#/components/features/conversation-panel/menu-separator";+import { ContextMenu } from "#/ui/context-menu";+import type { HomeAutomationMenuEntry } from "./build-home-automation-menu-items";++interface HomeAutomationMenuProps {+ testId: string;+ panelTestId: string;+ ariaLabel: string;+ items: HomeAutomationMenuEntry[];+ triggerClassName?: string;+}++/**+ * Shared home kebab: portal menu, Escape/arrow keys, focus restore to trigger.+ */+export function HomeAutomationMenu({+ testId,+ panelTestId,+ ariaLabel,+ items,+ triggerClassName,+}: HomeAutomationMenuProps) {+ const [menuOpen, setMenuOpen] = useState(false);+ const [activeIndex, setActiveIndex] = useState(0);+ const anchorRef = useRef<HTMLButtonElement>(null);+ const itemRefs = useRef<Array<HTMLButtonElement | null>>([]);+ const [, bumpPosition] = useReducer((i: number) => i + 1, 0);++ const closeMenu = () => {+ setMenuOpen(false);+ // Restore focus so keyboard users land back on the ellipsis.+ queueMicrotask(() => anchorRef.current?.focus());+ };++ const menuRef = useClickOutsideElement<HTMLUListElement>(+ closeMenu,+ anchorRef,+ );++ const actionableIndexes = items+ .map((entry, index) =>+ entry.kind === "item" && !entry.disabled ? index : -1,+ )+ .filter((index) => index >= 0);++ useLayoutEffect(() => {+ if (!menuOpen) return undefined;+ bumpPosition();+ setActiveIndex(actionableIndexes[0] ?? 0);+ let frame = 0;+ const update = () => {+ if (frame) return;+ frame = window.requestAnimationFrame(() => {+ frame = 0;+ bumpPosition();+ });+ };+ window.addEventListener("resize", update);+ window.addEventListener("scroll", update, true);+ return () => {+ window.removeEventListener("resize", update);+ window.removeEventListener("scroll", update, true);+ if (frame) window.cancelAnimationFrame(frame);+ };+ // actionableIndexes is derived from items; re-run when the menu opens.+ }, [menuOpen]);++ useEffect(() => {+ if (!menuOpen) return;+ itemRefs.current[activeIndex]?.focus();+ }, [activeIndex, menuOpen]);++ const floatingStyle = (() => {+ if (!menuOpen || !anchorRef.current) return undefined;+ const rect = anchorRef.current.getBoundingClientRect();+ const gutter = 8;+ const vw = window.innerWidth;+ const vh = window.innerHeight;+ // The panel's real height is only measurable from the second render+ // pass onward (the open effect forces one via bumpPosition); the first+ // paint falls back to an items-derived estimate (~36px per row, ~9px+ // per separator, plus panel padding).+ const estimatedHeight = items.reduce(+ (total, entry) => total + (entry.kind === "separator" ? 9 : 36),+ 10,+ );+ const menuHeight =+ menuRef.current?.getBoundingClientRect().height ?? estimatedHeight;+ const overflowsBelow = rect.bottom + 4 + menuHeight + gutter > vh;+ return {+ position: "fixed" as const,+ // When the menu would clip at the viewport bottom, flip it above the+ // trigger. Bottom-anchoring (rather than an estimated `top`) keeps+ // the panel hugging the trigger whatever its actual height.+ ...(overflowsBelow+ ? { bottom: vh - rect.top + 4 }+ : { top: rect.bottom + 4 }),+ right: Math.max(gutter, vw - rect.right),+ zIndex: 100_000,+ };+ })();++ const portalTarget = typeof document !== "undefined" ? document.body : null;++ const moveActive = (direction: 1 | -1) => {+ if (actionableIndexes.length === 0) return;+ const currentPos = actionableIndexes.indexOf(activeIndex);+ const nextPos =+ (currentPos + direction + actionableIndexes.length) %+ actionableIndexes.length;+ setActiveIndex(actionableIndexes[nextPos] ?? actionableIndexes[0]);+ };++ return (+ <div className="relative shrink-0">+ <EllipsisButton+ ref={anchorRef}+ testId={testId}+ ariaLabel={ariaLabel}+ className={triggerClassName}+ onClick={(event) => {+ event.preventDefault();+ event.stopPropagation();+ setMenuOpen((open) => !open);+ }}+ />++ {menuOpen && floatingStyle && portalTarget+ ? createPortal(+ <ContextMenu+ ref={menuRef}+ testId={panelTestId}+ theme="popover"+ position="none"+ alignment="none"+ spacing="none"+ style={floatingStyle}+ className="min-w-40"+ onKeyDown={(event) => {+ if (event.key === "Escape") {+ event.preventDefault();+ event.stopPropagation();+ closeMenu();+ return;+ }+ if (event.key === "ArrowDown") {+ event.preventDefault();+ moveActive(1);+ return;+ }+ if (event.key === "ArrowUp") {+ event.preventDefault();+ moveActive(-1);+ }+ }}+ >+ {items.map((entry, index) => {+ if (entry.kind === "separator") {+ return <MenuSeparator key={entry.key} />;+ }++ return (+ <li key={entry.key}>+ <ContextMenuListItem+ ref={(node) => {+ itemRefs.current[index] = node;+ }}+ testId={entry.testId}+ isDisabled={entry.disabled}+ className="group"+ onClick={(event) => {+ event.preventDefault();+ event.stopPropagation();+ if (entry.disabled) return;+ entry.onClick();+ closeMenu();+ }}+ >+ <KebabMenuItemContent+ icon={entry.icon}+ label={entry.label}+ />+ </ContextMenuListItem>+ </li>+ );+ })}+ </ContextMenu>,+ portalTarget,+ )+ : null}+ </div>+ );+}diff --git a/src/components/features/home/featured-automations/home-automation-run-tooltip.tsx b/src/components/features/home/featured-automations/home-automation-run-tooltip.tsxnew file mode 100644index 0000000000..0a7fab9fac--- /dev/null+++ b/src/components/features/home/featured-automations/home-automation-run-tooltip.tsx@@ -0,0 +1,99 @@+import type { ReactNode } from "react";+import { Zap } from "lucide-react";+import { useTranslation } from "react-i18next";+import type { LatestAutomationRunState } from "#/hooks/query/use-latest-automation-runs";+import { I18nKey } from "#/i18n/declaration";+import ClockIcon from "#/icons/clock.svg?react";+import { AutomationRunStatus, type Automation } from "#/types/automation";+import { formatRelativeTime } from "#/utils/format-relative-time";+import { AutomationHealthIndicator } from "./automation-health-indicator";+import {+ deriveRunHealth,+ getLastRunTimestamp,+ getRunHealthLabelKey,+ getTriggerSummary,+} from "./automation-run-health";++export function getRunStatusLabelKey(+ runState: LatestAutomationRunState,+): I18nKey {+ if (runState.isError) return I18nKey.FEATURED_AUTOMATIONS$STATUS_UNAVAILABLE;+ return getRunHealthLabelKey(deriveRunHealth(runState));+}++function PreviewRow({+ label,+ children,+}: {+ label: string;+ children: ReactNode;+}) {+ return (+ <div className="flex items-start gap-2 text-xs">+ <span className="w-20 shrink-0 text-[var(--oh-muted)]">{label}</span>+ <span className="min-w-0 flex-1 break-words text-[var(--oh-foreground)]">+ {children}+ </span>+ </div>+ );+}++/**+ * Left-nav-style hovercard body for an automation's latest-run health.+ * Matches `ConversationCardPreview` layout: title + label/value rows.+ */+export function HomeAutomationRunTooltip({+ automation,+ runState,+}: {+ automation: Automation;+ runState: LatestAutomationRunState;+}) {+ const { t, i18n } = useTranslation("openhands");+ const { latestRun } = runState;+ const timestamp = latestRun ? getLastRunTimestamp(latestRun) : null;+ const TriggerIcon = automation.trigger.type === "event" ? Zap : ClockIcon;+ const health = deriveRunHealth(runState);++ return (+ <div className="flex w-[280px] flex-col gap-3 p-3">+ <span className="break-words text-sm font-medium text-white">+ {automation.name}+ </span>++ <dl className="flex flex-col gap-1.5">+ <PreviewRow label={t(I18nKey.AUTOMATIONS$DETAIL$TRIGGER)}>+ <span className="inline-flex min-w-0 items-start gap-1.5">+ <TriggerIcon+ className="mt-0.5 size-3 shrink-0"+ aria-hidden="true"+ />+ <span className="break-all">{getTriggerSummary(automation)}</span>+ </span>+ </PreviewRow>++ <PreviewRow label={t(I18nKey.COMMON$STATUS)}>+ <span className="inline-flex min-w-0 items-center gap-1.5">+ <AutomationHealthIndicator health={health} />+ <span>{t(getRunStatusLabelKey(runState))}</span>+ </span>+ </PreviewRow>++ {timestamp ? (+ <PreviewRow label={t(I18nKey.AUTOMATIONS$DETAIL$LAST_RUN)}>+ {formatRelativeTime(timestamp, i18n.language, t)}+ </PreviewRow>+ ) : null}++ {latestRun?.status === AutomationRunStatus.FAILED &&+ latestRun.error_detail ? (+ <PreviewRow label={t(I18nKey.STATUS$ERROR)}>+ <span className="line-clamp-3 text-[var(--oh-status-error)]">+ {latestRun.error_detail}+ </span>+ </PreviewRow>+ ) : null}+ </dl>+ </div>+ );+}diff --git a/src/components/features/home/featured-automations/pinned-automation-card.tsx b/src/components/features/home/featured-automations/pinned-automation-card.tsxnew file mode 100644index 0000000000..34dcb52864--- /dev/null+++ b/src/components/features/home/featured-automations/pinned-automation-card.tsx@@ -0,0 +1,347 @@+import { Tooltip } from "@heroui/react";+import { ExternalLink, Zap } from "lucide-react";+import { useRef } from "react";+import { useTranslation } from "react-i18next";+import { EditAutomationModal } from "#/components/features/automations/detail/edit-automation-modal";+import { RunStatusBadge } from "#/components/features/automations/detail/run-status-badge";+import { TurnOffConfirmationModal } from "#/components/features/automations/turn-off-confirmation-modal";+import { NavigationLink } from "#/components/shared/navigation-link";+import type { LatestAutomationRunState } from "#/hooks/query/use-latest-automation-runs";+import { useHomeAutomationActions } from "#/hooks/use-home-automation-actions";+import { getDemoConversationTitle } from "#/fixtures/home-automations-demo";+import { useUserConversation } from "#/hooks/query/use-user-conversation";+import { I18nKey } from "#/i18n/declaration";+import ClockIcon from "#/icons/clock.svg?react";+import { AutomationRunStatus, type Automation } from "#/types/automation";+import { extensionModuleCardPillClassName } from "#/utils/extension-module-card-classes";+import { formatRelativeTime } from "#/utils/format-relative-time";+import { cn } from "#/utils/utils";+import { AutomationRunActivitySparkline } from "./automation-run-activity-sparkline";+import { buildPinnedAutomationMenuItems } from "./build-pinned-automation-menu-items";+import { HomeAutomationMenu } from "./home-automation-menu";+import {+ formatTriggerSourceLabel,+ getLastRunTimestamp,+ getTriggerEventLabel,+ getTriggerScheduleLabel,+ getTriggerSource,+ shortenAutomationErrorDetail,+ shouldShowAutomationErrorHovercard,+} from "./automation-run-health";++interface PinnedAutomationCardProps {+ automation: Automation;+ runState: LatestAutomationRunState;+ onUnpin: (automationId: string) => void;+ onDragStart: (automationId: string) => void;+ onDragOver: (automationId: string, position: "before" | "after") => void;+ onDrop: (automationId: string) => void;+ onDragEnd: () => void;+ isDropTarget: boolean;+ dropPosition: "before" | "after" | null;+ isDragging: boolean;+}++/**+ * Expanded pinned-automation card: status badge, trigger meta,+ * loading/empty/error copy, failure detail, and conversation title link.+ * Quick actions + unpin live in the card's three-dot menu.+ */+export function PinnedAutomationCard({+ automation,+ runState,+ onUnpin,+ onDragStart,+ onDragOver,+ onDrop,+ onDragEnd,+ isDropTarget,+ dropPosition,+ isDragging,+}: PinnedAutomationCardProps) {+ const { t, i18n } = useTranslation("openhands");+ const { latestRun, recentRuns, isLoading, isError } = runState;+ const actions = useHomeAutomationActions(automation, latestRun);+ const conversationId = latestRun?.conversation_id ?? null;+ const demoConversationTitle = conversationId+ ? getDemoConversationTitle(conversationId)+ : undefined;+ const { data: conversation } = useUserConversation(+ demoConversationTitle !== undefined ? null : conversationId,+ );+ const conversationTitle =+ demoConversationTitle !== undefined+ ? demoConversationTitle+ : (conversation?.title ?? null);++ const timestamp = latestRun ? getLastRunTimestamp(latestRun) : null;+ const isTerminal =+ latestRun?.status === AutomationRunStatus.COMPLETED ||+ latestRun?.status === AutomationRunStatus.FAILED;+ const isEventTrigger = automation.trigger.type === "event";+ const TriggerIcon = isEventTrigger ? Zap : ClockIcon;+ const triggerEventLabel = getTriggerEventLabel(automation);+ const triggerScheduleLabel = getTriggerScheduleLabel(automation);+ const triggerSource = getTriggerSource(automation);+ const errorDetail =+ latestRun?.status === AutomationRunStatus.FAILED+ ? latestRun.error_detail?.trim() || null+ : null;+ const shortErrorDetail = errorDetail+ ? shortenAutomationErrorDetail(errorDetail)+ : null;+ const showErrorHovercard =+ errorDetail != null &&+ shortErrorDetail != null &&+ shouldShowAutomationErrorHovercard(errorDetail, shortErrorDetail);+ const disableAnimation = import.meta.env.MODE === "test";+ const cardRef = useRef<HTMLElement>(null);++ const menuItems = buildPinnedAutomationMenuItems({+ automation,+ t,+ canManage: actions.canManage,+ canEdit: actions.canEdit,+ isRunPending: actions.isRunPending,+ isCancelPending: actions.isCancelPending,+ canCancel: actions.canCancel,+ onRunNow: actions.runNow,+ onCancelRun: actions.cancelRun,+ onView: actions.viewDetails,+ onEdit: actions.canEdit ? actions.openEdit : undefined,+ onTurnOff: actions.requestTurnOff,+ onUnpin: () => onUnpin(automation.id),+ });++ return (+ <article+ ref={cardRef}+ role="listitem"+ data-testid={`pinned-automation-card-${automation.id}`}+ onDragOver={(event) => {+ event.preventDefault();+ const { dataTransfer } = event;+ dataTransfer.dropEffect = "move";+ const rect = event.currentTarget.getBoundingClientRect();+ // 2-col grid: prefer horizontal edge when the pointer is clearly+ // left/right of center; otherwise use vertical before/after.+ const xRatio = (event.clientX - rect.left) / rect.width;+ const yRatio = (event.clientY - rect.top) / rect.height;+ const useHorizontal = xRatio < 0.3 || xRatio > 0.7;+ const position = useHorizontal+ ? xRatio < 0.5+ ? "before"+ : "after"+ : yRatio < 0.5+ ? "before"+ : "after";+ onDragOver(automation.id, position);+ }}+ onDrop={(event) => {+ event.preventDefault();+ onDrop(automation.id);+ }}+ onDragEnd={onDragEnd}+ className={cn(+ "group relative flex flex-col rounded-xl border border-[var(--oh-border)] bg-[var(--oh-surface-raised)] p-4",+ isDragging && "opacity-50",+ isDropTarget &&+ dropPosition === "before" &&+ "shadow-[inset_0_2px_0_0_var(--oh-focus)]",+ isDropTarget &&+ dropPosition === "after" &&+ "shadow-[inset_0_-2px_0_0_var(--oh-focus)]",+ )}+ >+ {/*+ Full top chrome (padding above the title + title row) is the drag+ surface. Title is not an <a> so browsers don't steal the gesture;+ click still opens details. Menu is opted out via data-no-drag.+ */}+ <div+ draggable+ data-testid={`pinned-automation-drag-${automation.id}`}+ aria-label={t(I18nKey.FEATURED_AUTOMATIONS$REORDER_HANDLE, {+ name: automation.name,+ })}+ className="-mx-4 -mt-4 mb-0 flex cursor-grab items-start justify-between gap-3 rounded-t-xl px-4 pb-1 pt-4 active:cursor-grabbing"+ onDragStart={(event) => {+ const target = event.target as HTMLElement | null;+ if (target?.closest("[data-no-drag]")) {+ event.preventDefault();+ return;+ }+ const { dataTransfer } = event;+ dataTransfer.effectAllowed = "move";+ dataTransfer.setData("text/plain", automation.id);+ if (cardRef.current) {+ dataTransfer.setDragImage(cardRef.current, 24, 24);+ }+ onDragStart(automation.id);+ }}+ onDragEnd={onDragEnd}+ >+ <span+ role="link"+ tabIndex={0}+ title={t(I18nKey.FEATURED_AUTOMATIONS$VIEW_DETAILS)}+ className="min-w-0 flex-1 cursor-pointer truncate font-medium text-[var(--oh-foreground)] hover:underline focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--oh-focus)]"+ onClick={() => actions.viewDetails()}+ onKeyDown={(event) => {+ if (event.key === "Enter" || event.key === " ") {+ event.preventDefault();+ actions.viewDetails();+ }+ }}+ >+ {automation.name}+ </span>++ <div data-no-drag className="shrink-0">+ <HomeAutomationMenu+ testId={`pinned-automation-menu-${automation.id}`}+ panelTestId={`pinned-automation-menu-panel-${automation.id}`}+ ariaLabel={t(I18nKey.FEATURED_AUTOMATIONS$ROW_MENU_LABEL, {+ name: automation.name,+ })}+ triggerClassName="opacity-70 group-hover:opacity-100"+ items={menuItems}+ />+ </div>+ </div>++ <div className="mt-2 flex items-center justify-between gap-3 text-xs text-[var(--oh-text-secondary)]">+ <span className="flex min-w-0 items-center gap-1.5">+ <TriggerIcon className="size-3 shrink-0" aria-hidden="true" />+ {triggerEventLabel ? (+ <span className="truncate">{triggerEventLabel}</span>+ ) : null}+ {triggerScheduleLabel ? (+ <span className="truncate">{triggerScheduleLabel}</span>+ ) : null}+ {triggerSource ? (+ <span+ className={cn(+ extensionModuleCardPillClassName,+ "px-1.5 py-0 text-[var(--oh-text-secondary)]",+ )}+ >+ {formatTriggerSourceLabel(triggerSource)}+ </span>+ ) : null}+ </span>+ {recentRuns.length > 0 ? (+ <AutomationRunActivitySparkline+ automationId={automation.id}+ runs={recentRuns}+ testId={`pinned-automation-activity-${automation.id}`}+ />+ ) : null}+ </div>++ <div className="mt-3 flex min-h-9 items-center justify-between gap-2 overflow-hidden rounded-md border border-[var(--oh-border-subtle)] bg-[var(--oh-surface)] px-3 py-2 text-xs">+ <div className="flex min-w-0 flex-1 items-center gap-2 overflow-hidden">+ {isLoading ? (+ <div+ className="h-3.5 w-3/4 animate-pulse rounded bg-surface-raised motion-reduce:animate-none"+ aria-hidden="true"+ />+ ) : null}++ {!isLoading && isError ? (+ <p className="truncate text-[var(--oh-text-secondary)]">+ {t(I18nKey.FEATURED_AUTOMATIONS$STATUS_UNAVAILABLE)}+ </p>+ ) : null}++ {!isLoading && !isError && !latestRun ? (+ <p className="truncate text-[var(--oh-text-secondary)]">+ {t(I18nKey.AUTOMATIONS$DETAIL$NO_RUNS)}+ </p>+ ) : null}++ {latestRun ? (+ <>+ <RunStatusBadge+ status={latestRun.status}+ iconOnly+ showLabel={+ latestRun.status === AutomationRunStatus.PENDING ||+ // Running with no conversation title yet → same treatment as Pending.+ (latestRun.status === AutomationRunStatus.RUNNING &&+ !conversationTitle)+ }+ />++ {shortErrorDetail ? (+ showErrorHovercard && errorDetail ? (+ <Tooltip+ content={+ <p className="max-w-xs whitespace-pre-wrap break-words p-2 text-xs">+ {errorDetail}+ </p>+ }+ placement="top"+ closeDelay={100}+ disableAnimation={disableAnimation}+ className="rounded-xl border border-[var(--oh-border)] bg-base-secondary p-0 text-white shadow-xl"+ >+ <span className="min-w-0 flex-1 cursor-default truncate text-[var(--oh-status-error)]">+ {shortErrorDetail}+ </span>+ </Tooltip>+ ) : (+ <p className="min-w-0 flex-1 truncate text-[var(--oh-status-error)]">+ {shortErrorDetail}+ </p>+ )+ ) : null}++ {conversationId && conversationTitle ? (+ <NavigationLink+ to={`/conversations/${conversationId}`}+ aria-label={conversationTitle}+ title={conversationTitle}+ className="group/conversation inline-flex min-w-0 items-center gap-1 text-[var(--oh-foreground)] hover:text-[var(--oh-text-secondary)] focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--oh-focus)]"+ >+ <span className="truncate">{conversationTitle}</span>+ <ExternalLink+ className="size-3 shrink-0 opacity-0 transition-opacity group-hover/conversation:opacity-100 group-focus-visible/conversation:opacity-100"+ aria-hidden="true"+ />+ </NavigationLink>+ ) : null}++ {!conversationId && isTerminal ? (+ <p className="min-w-0 truncate text-[var(--oh-text-secondary)]">+ {t(I18nKey.AUTOMATIONS$DETAIL$NO_CONVERSATION)}+ </p>+ ) : null}+ </>+ ) : null}+ </div>++ {timestamp ? (+ <span className="shrink-0 text-[var(--oh-text-secondary)]">+ {formatRelativeTime(timestamp, i18n.language, t)}+ </span>+ ) : null}+ </div>++ {actions.editOpen ? (+ <EditAutomationModal+ automation={automation}+ isOpen={actions.editOpen}+ onClose={() => actions.setEditOpen(false)}+ />+ ) : null}++ <TurnOffConfirmationModal+ automationName={automation.name}+ isOpen={actions.turnOffConfirmOpen}+ onConfirm={actions.confirmTurnOff}+ onCancel={actions.cancelTurnOff}+ />+ </article>+ );+}diff --git a/src/components/features/home/featured-automations/pinned-automations-dashboard.tsx b/src/components/features/home/featured-automations/pinned-automations-dashboard.tsxnew file mode 100644index 0000000000..52aaaa142a--- /dev/null+++ b/src/components/features/home/featured-automations/pinned-automations-dashboard.tsx@@ -0,0 +1,127 @@+import { useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import {+ UNKNOWN_RUN_STATE,+ useHomeAutomations,+} from "#/hooks/query/use-home-automations";+import {+ HOME_PINNED_PREVIEW_LIMIT,+ useHomePinnedAutomations,+} from "#/hooks/use-home-pinned-automations";+import { I18nKey } from "#/i18n/declaration";+import type { Automation } from "#/types/automation";+import { PinnedAutomationCard } from "./pinned-automation-card";++/**+ * Dashboard grid of pinned automations rendered above Recent Automation+ * Activity on the home page. Empty when nothing pinned resolves against+ * currently enabled live automations.+ */+export function PinnedAutomationsDashboard() {+ const { t } = useTranslation("openhands");+ const { pinnedIds, unpin, reorder, pruneMissing } =+ useHomePinnedAutomations();+ const {+ isBackendHealthy,+ isHealthLoading,+ isError,+ enabledAutomations,+ knownAutomationIds,+ isAutomationListComplete,+ runStates,+ } = useHomeAutomations();+ const [isExpanded, setIsExpanded] = useState(false);+ const [draggedId, setDraggedId] = useState<string | null>(null);+ const [dropTargetId, setDropTargetId] = useState<string | null>(null);+ const [dropPosition, setDropPosition] = useState<"before" | "after" | null>(+ null,+ );++ useEffect(() => {+ // Only prune against a complete id set: a truncated page would look like+ // missing automations and delete valid pins.+ if (!isAutomationListComplete || knownAutomationIds.size === 0) return;+ pruneMissing(knownAutomationIds);+ }, [isAutomationListComplete, knownAutomationIds, pruneMissing]);++ const enabledById = new Map(+ enabledAutomations.map((automation) => [automation.id, automation]),+ );+ const pinnedAutomations = pinnedIds+ .map((id) => enabledById.get(id))+ .filter((automation): automation is Automation => Boolean(automation));++ if (+ isHealthLoading ||+ !isBackendHealthy ||+ isError ||+ pinnedAutomations.length === 0+ ) {+ return null;+ }++ const visibleAutomations =+ isExpanded || pinnedAutomations.length <= HOME_PINNED_PREVIEW_LIMIT+ ? pinnedAutomations+ : pinnedAutomations.slice(0, HOME_PINNED_PREVIEW_LIMIT);+ const canExpand = pinnedAutomations.length > HOME_PINNED_PREVIEW_LIMIT;++ return (+ <section+ data-testid="pinned-automations-dashboard"+ aria-label={t(I18nKey.FEATURED_AUTOMATIONS$PINNED_DASHBOARD_LABEL)}+ className="w-full"+ >+ <h2 className="mb-2 text-sm font-medium text-[var(--oh-foreground)]">+ {t(I18nKey.FEATURED_AUTOMATIONS$PINNED_TITLE)}+ </h2>++ <div role="list" className="grid grid-cols-1 gap-3 sm:grid-cols-2">+ {visibleAutomations.map((automation) => (+ <PinnedAutomationCard+ key={automation.id}+ automation={automation}+ runState={runStates.get(automation.id) ?? UNKNOWN_RUN_STATE}+ onUnpin={unpin}+ onDragStart={setDraggedId}+ onDragOver={(id, position) => {+ setDropTargetId(id);+ setDropPosition(position);+ }}+ onDrop={(targetId) => {+ if (draggedId && dropPosition) {+ reorder(draggedId, targetId, dropPosition);+ }+ setDraggedId(null);+ setDropTargetId(null);+ setDropPosition(null);+ }}+ onDragEnd={() => {+ setDraggedId(null);+ setDropTargetId(null);+ setDropPosition(null);+ }}+ isDropTarget={dropTargetId === automation.id}+ dropPosition={dropTargetId === automation.id ? dropPosition : null}+ isDragging={draggedId === automation.id}+ />+ ))}+ </div>++ {canExpand ? (+ <div className="mt-2 flex justify-start">+ <button+ type="button"+ data-testid="pinned-automations-view-more"+ onClick={() => setIsExpanded((value) => !value)}+ className="text-xs text-[var(--oh-text-secondary)] hover:text-[var(--oh-foreground)]"+ >+ {t(+ isExpanded ? I18nKey.COMMON$VIEW_LESS : I18nKey.COMMON$VIEW_MORE,+ )}+ </button>+ </div>+ ) : null}+ </section>+ );+}diff --git a/src/components/features/home/featured-automations/running-automations-list.tsx b/src/components/features/home/featured-automations/running-automations-list.tsxnew file mode 100644index 0000000000..8eb832a256--- /dev/null+++ b/src/components/features/home/featured-automations/running-automations-list.tsx@@ -0,0 +1,325 @@+import { Tooltip } from "@heroui/react";+import { Plus, Zap } from "lucide-react";+import { useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import { EditAutomationModal } from "#/components/features/automations/detail/edit-automation-modal";+import { RunStatusBadge } from "#/components/features/automations/detail/run-status-badge";+import { TurnOffConfirmationModal } from "#/components/features/automations/turn-off-confirmation-modal";+import { StyledTooltip } from "#/components/shared/buttons/styled-tooltip";+import { NavigationLink } from "#/components/shared/navigation-link";+import type { LatestAutomationRunState } from "#/hooks/query/use-latest-automation-runs";+import {+ HOME_AUTOMATIONS_PREVIEW_LIMIT,+ MAX_HOME_AUTOMATION_CHIPS,+ UNKNOWN_RUN_STATE,+ useHomeAutomations,+} from "#/hooks/query/use-home-automations";+import { useHomeAutomationActions } from "#/hooks/use-home-automation-actions";+import { useHomePinnedAutomations } from "#/hooks/use-home-pinned-automations";+import { I18nKey } from "#/i18n/declaration";+import ClockIcon from "#/icons/clock.svg?react";+import type { Automation } from "#/types/automation";+import { extensionModuleCardPillClassName } from "#/utils/extension-module-card-classes";+import { cn } from "#/utils/utils";+import { AutomationRunActivitySparkline } from "./automation-run-activity-sparkline";+import { AutomationHealthIndicator } from "./automation-health-indicator";+import { buildHomeAutomationMenuItems } from "./build-home-automation-menu-items";+import { HomeAutomationMenu } from "./home-automation-menu";+import {+ deriveRunHealth,+ formatTriggerSourceLabel,+ getTriggerEventLabel,+ getTriggerScheduleLabel,+ getTriggerSource,+} from "./automation-run-health";+import {+ buildHomeAutomationActivityItems,+ hrefForActivityItem,+ type HomeAutomationActivityItem,+} from "./home-automation-activity";+import {+ getRunStatusLabelKey,+ HomeAutomationRunTooltip,+} from "./home-automation-run-tooltip";++interface RunningAutomationRowProps {+ item: HomeAutomationActivityItem;+ automation: Automation;+ runState: LatestAutomationRunState;+}++function RunningAutomationRow({+ item,+ automation,+ runState,+}: RunningAutomationRowProps) {+ const { t } = useTranslation("openhands");+ const { isPinned, togglePin } = useHomePinnedAutomations();+ const actions = useHomeAutomationActions(automation, runState.latestRun);+ const pinned = isPinned(item.id);+ const isEventTrigger = automation.trigger.type === "event";+ const TriggerIcon = isEventTrigger ? Zap : ClockIcon;+ const triggerEventLabel = getTriggerEventLabel(automation);+ const triggerScheduleLabel = getTriggerScheduleLabel(automation);+ const triggerSource = getTriggerSource(automation);+ const hasTriggerMeta = Boolean(+ triggerEventLabel || triggerScheduleLabel || triggerSource,+ );+ const hasMeta =+ hasTriggerMeta || Boolean(item.whenLabel) || Boolean(item.status);+ const health = deriveRunHealth(runState);+ const statusLabelKey = getRunStatusLabelKey(runState);+ const disableAnimation = import.meta.env.MODE === "test";++ const menuItems = buildHomeAutomationMenuItems({+ automation,+ t,+ canManage: actions.canManage,+ canEdit: actions.canEdit,+ isRunPending: actions.isRunPending,+ isCancelPending: actions.isCancelPending,+ canCancel: actions.canCancel,+ testIdPrefix: "running-automation",+ pinTestId: `running-automation-pin-${item.id}`,+ isPinned: pinned,+ onRunNow: actions.runNow,+ onCancelRun: actions.cancelRun,+ onView: actions.viewDetails,+ onEdit: actions.canEdit ? actions.openEdit : undefined,+ onTurnOff: actions.requestTurnOff,+ onTogglePin: () => togglePin(item.id),+ });++ return (+ <li+ data-testid={`running-automation-row-${item.id}`}+ className="group relative flex items-stretch transition-colors hover:bg-[var(--oh-interactive-hover)] has-[:focus-visible]:bg-[var(--oh-interactive-hover)]"+ >+ <Tooltip+ content={+ <HomeAutomationRunTooltip+ automation={automation}+ runState={runState}+ />+ }+ placement="top-start"+ closeDelay={100}+ disableAnimation={disableAnimation}+ className="rounded-xl border border-[var(--oh-border)] bg-base-secondary p-0 text-white shadow-xl"+ >+ <NavigationLink+ to={hrefForActivityItem(item)}+ aria-label={`${item.name} ${t(statusLabelKey)}`}+ className="flex min-w-0 flex-1 items-center justify-between gap-3 px-3 py-2.5 focus:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-[var(--oh-focus)]"+ >+ <div className="grid min-w-0 flex-1 grid-cols-[auto_minmax(0,1fr)] gap-x-2">+ <span className="inline-flex h-5 w-2.5 shrink-0 items-center justify-center">+ <AutomationHealthIndicator health={health} />+ </span>+ <span className="truncate text-sm font-medium leading-5 text-[var(--oh-foreground)]">+ {item.name}+ </span>+ {hasMeta ? (+ <span className="col-start-2 mt-0.5 flex min-w-0 items-center gap-1.5 text-xs leading-4 text-[var(--oh-text-secondary)]">+ <TriggerIcon className="size-3 shrink-0" aria-hidden="true" />+ {triggerEventLabel ? (+ <span className="truncate">{triggerEventLabel}</span>+ ) : null}+ {triggerScheduleLabel ? (+ <span className="truncate">{triggerScheduleLabel}</span>+ ) : null}+ {triggerSource ? (+ <span+ className={cn(+ extensionModuleCardPillClassName,+ "shrink-0 px-1.5 py-0 text-[var(--oh-text-secondary)]",+ )}+ >+ {formatTriggerSourceLabel(triggerSource)}+ </span>+ ) : null}+ {item.whenLabel ? (+ <>+ {hasTriggerMeta ? (+ <span className="shrink-0" aria-hidden="true">+ ·+ </span>+ ) : null}+ <span className="truncate">{item.whenLabel}</span>+ </>+ ) : null}+ {item.status ? (+ <>+ {hasTriggerMeta || item.whenLabel ? (+ <span className="shrink-0" aria-hidden="true">+ ·+ </span>+ ) : null}+ <RunStatusBadge status={item.status} compact />+ </>+ ) : null}+ </span>+ ) : null}+ <span className="sr-only">{t(statusLabelKey)}</span>+ </div>+ </NavigationLink>+ </Tooltip>++ <div className="flex shrink-0 items-center gap-1.5 pr-1.5">+ <AutomationRunActivitySparkline+ automationId={automation.id}+ runs={runState.recentRuns}+ testId={`running-automation-activity-${item.id}`}+ />+ <HomeAutomationMenu+ testId={`running-automation-menu-${item.id}`}+ panelTestId={`running-automation-menu-panel-${item.id}`}+ ariaLabel={t(I18nKey.FEATURED_AUTOMATIONS$ROW_MENU_LABEL, {+ name: item.name,+ })}+ triggerClassName="opacity-70 group-hover:opacity-100"+ items={menuItems}+ />+ </div>++ {actions.editOpen ? (+ <EditAutomationModal+ automation={automation}+ isOpen={actions.editOpen}+ onClose={() => actions.setEditOpen(false)}+ />+ ) : null}++ <TurnOffConfirmationModal+ automationName={automation.name}+ isOpen={actions.turnOffConfirmOpen}+ onConfirm={actions.confirmTurnOff}+ onCancel={actions.cancelTurnOff}+ />+ </li>+ );+}++/**+ * Recent automation activity under the home composer. Driven by live+ * enabled automations + latest-run queries; self-gates when the automation+ * service is unavailable or there are no enabled automations.+ */+export function RunningAutomationsList() {+ const { t, i18n } = useTranslation("openhands");+ const [isExpanded, setIsExpanded] = useState(false);+ const {+ isBackendHealthy,+ isHealthLoading,+ isError,+ enabledAutomations,+ runStates,+ } = useHomeAutomations();++ const language = i18n?.language ?? "en";+ const items = useMemo(+ () =>+ buildHomeAutomationActivityItems(+ enabledAutomations,+ runStates,+ language,+ t,+ UNKNOWN_RUN_STATE,+ ),+ [enabledAutomations, runStates, language, t],+ );++ const automationById = useMemo(+ () =>+ new Map(+ enabledAutomations.map((automation) => [automation.id, automation]),+ ),+ [enabledAutomations],+ );++ const visibleLimit = isExpanded+ ? MAX_HOME_AUTOMATION_CHIPS+ : HOME_AUTOMATIONS_PREVIEW_LIMIT;+ const visibleItems = items.slice(0, visibleLimit);+ const canViewMore =+ !isExpanded && items.length > HOME_AUTOMATIONS_PREVIEW_LIMIT;+ const canViewAll = isExpanded && items.length >= MAX_HOME_AUTOMATION_CHIPS;++ if (isHealthLoading || !isBackendHealthy || isError || items.length === 0) {+ return null;+ }++ return (+ <section+ aria-labelledby="running-automations-heading"+ data-testid="running-automations-list"+ className="mt-8 w-full"+ >+ <div className="mb-2 flex items-center justify-between gap-2">+ <h2+ id="running-automations-heading"+ className="text-sm font-medium text-[var(--oh-foreground)]"+ >+ {t(I18nKey.FEATURED_AUTOMATIONS$SECTION_TITLE)}+ </h2>+ <StyledTooltip+ content={t(I18nKey.FEATURED_AUTOMATIONS$MANAGE)}+ placement="bottom"+ >+ <NavigationLink+ to="/automations"+ data-testid="home-automations-manage"+ aria-label={t(I18nKey.FEATURED_AUTOMATIONS$MANAGE)}+ className="inline-flex items-center gap-1 rounded-md px-1.5 py-0.5 text-xs font-medium text-[var(--oh-text-secondary)] transition-colors hover:bg-[var(--oh-interactive-hover)] hover:text-[var(--oh-foreground)] focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--oh-focus)]"+ >+ <Plus className="size-3" aria-hidden="true" />+ {t(I18nKey.BUTTON$ADD)}+ </NavigationLink>+ </StyledTooltip>+ </div>++ <ul+ aria-label={t(I18nKey.FEATURED_AUTOMATIONS$RECENT_GROUP_LABEL)}+ className="divide-y divide-[var(--oh-border-subtle)] overflow-hidden rounded-xl border border-[var(--oh-border-subtle)] bg-[var(--oh-surface)]"+ >+ {visibleItems.map((item) => {+ const automation = automationById.get(item.id);+ if (!automation) return null;+ return (+ <RunningAutomationRow+ key={item.id}+ item={item}+ automation={automation}+ runState={runStates.get(item.id) ?? UNKNOWN_RUN_STATE}+ />+ );+ })}+ </ul>++ {canViewMore ? (+ <div className="mt-2 flex justify-start">+ <button+ type="button"+ data-testid="home-automations-view-more"+ onClick={() => setIsExpanded(true)}+ className="rounded-md px-1.5 py-0.5 text-xs font-medium text-[var(--oh-text-secondary)] transition-colors hover:bg-[var(--oh-interactive-hover)] hover:text-[var(--oh-foreground)] focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--oh-focus)]"+ >+ {t(I18nKey.COMMON$VIEW_MORE)}+ </button>+ </div>+ ) : null}++ {canViewAll ? (+ <div className="mt-2 flex justify-start">+ <NavigationLink+ to="/automations"+ data-testid="home-automations-view-all"+ className="rounded-md px-1.5 py-0.5 text-xs font-medium text-[var(--oh-text-secondary)] transition-colors hover:bg-[var(--oh-interactive-hover)] hover:text-[var(--oh-foreground)] focus:outline-none focus-visible:ring-2 focus-visible:ring-[var(--oh-focus)]"+ >+ {t(I18nKey.FEATURED_AUTOMATIONS$VIEW_ALL)}+ </NavigationLink>+ </div>+ ) : null}+ </section>+ );+}diff --git a/src/components/features/home/home-chat-launcher.tsx b/src/components/features/home/home-chat-launcher.tsxindex f2a72c16bd..2c7496f7b2 100644--- a/src/components/features/home/home-chat-launcher.tsx+++ b/src/components/features/home/home-chat-launcher.tsx@@ -28,6 +28,8 @@ import { getWorkspacesUnsupportedMessage } from "#/utils/workspaces-compatibilitimport type { PluginSpec } from "#/api/conversation-service/agent-server-conversation-service.types";import { PluginPickerModal } from "#/components/features/plugins/plugin-picker-modal";import { PluginPickerTrigger } from "#/components/features/plugins/plugin-picker-trigger";+import { PinnedAutomationsDashboard } from "./featured-automations/pinned-automations-dashboard";+import { RunningAutomationsList } from "./featured-automations/running-automations-list";import { HomeHeaderTitle } from "./home-header/home-header-title";import { OpenLauncherButton } from "./open-launcher-button";import { OpenWorkspaceDialog } from "./open-workspace-dialog";@@ -217,45 +219,52 @@ export function HomeChatLauncher() {return (<divdata-testid="home-chat-launcher"- className="flex w-full max-w-[800px] flex-col gap-4 md:px-4"+ className="flex w-full flex-col items-center pt-[max(4rem,28vh)] pb-10">- <div className="flex w-full justify-center">- <HomeHeaderTitle />- </div>-- <div className="w-full">- <CustomChatInput- onSubmit={handleSubmitWithModelGuard}- onFilesPaste={handleUpload}- disabled={isCreating || llmBlocked}- />- </div>+ <div className="flex w-full max-w-[800px] flex-col gap-4 md:px-4">+ <div className="flex w-full justify-center">+ <HomeHeaderTitle />+ </div>- <div className="flex items-center justify-start gap-2">- {hasSelection ? (- <HomeGitControlBarPreview- workspace={pendingWorkspace}- repository={pendingRepository}- branch={pendingBranch}- provider={pendingProvider}- workspaceMode={workspaceMode}- backendKind={backend.kind}- onRepoClick={() => setIsDialogOpen(true)}- onWorkspaceModeChange={setWorkspaceMode}+ <div className="w-full">+ <CustomChatInput+ onSubmit={handleSubmitWithModelGuard}+ onFilesPaste={handleUpload}+ disabled={isCreating || llmBlocked}/>- ) : (- <OpenLauncherButton- kind={isLocal ? "local" : "cloud"}- onClick={() => setIsDialogOpen(true)}- disabled={isCreating || Boolean(workspacesUnsupportedMessage)}- disabledTooltip={workspacesUnsupportedMessage}+ </div>++ <div className="flex items-center justify-start gap-2">+ {hasSelection ? (+ <HomeGitControlBarPreview+ workspace={pendingWorkspace}+ repository={pendingRepository}+ branch={pendingBranch}+ provider={pendingProvider}+ workspaceMode={workspaceMode}+ backendKind={backend.kind}+ onRepoClick={() => setIsDialogOpen(true)}+ onWorkspaceModeChange={setWorkspaceMode}+ />+ ) : (+ <OpenLauncherButton+ kind={isLocal ? "local" : "cloud"}+ onClick={() => setIsDialogOpen(true)}+ disabled={isCreating || Boolean(workspacesUnsupportedMessage)}+ disabledTooltip={workspacesUnsupportedMessage}+ />+ )}+ <PluginPickerTrigger+ count={selectedPlugins.length}+ onClick={() => setIsPluginPickerOpen(true)}+ disabled={isCreating}/>- )}- <PluginPickerTrigger- count={selectedPlugins.length}- onClick={() => setIsPluginPickerOpen(true)}- disabled={isCreating}- />+ </div>++ <div className="mt-8 flex w-full flex-col gap-8">+ <PinnedAutomationsDashboard />+ <RunningAutomationsList />+ </div></div>{isLocal ? (diff --git a/src/components/features/home/home-header/home-header-title.tsx b/src/components/features/home/home-header/home-header-title.tsxindex 58cc14f805..54686a948e 100644--- a/src/components/features/home/home-header/home-header-title.tsx+++ b/src/components/features/home/home-header/home-header-title.tsx@@ -6,7 +6,7 @@ export function HomeHeaderTitle() {const { t } = useTranslation("openhands");return (- <div className="flex min-h-[80px] w-full items-center justify-center py-2">+ <div className="flex w-full items-center justify-center py-2"><Typography.H1 className="w-full text-center leading-normal">{t(I18nKey.HOME$LETS_START_BUILDING)}</Typography.H1>diff --git a/src/fixtures/home-automations-demo.ts b/src/fixtures/home-automations-demo.tsnew file mode 100644index 0000000000..1285512a53--- /dev/null+++ b/src/fixtures/home-automations-demo.ts@@ -0,0 +1,491 @@+import {+ AUTOMATION_RUN_ACTIVITY_LIMIT,+ type LatestAutomationRunState,+} from "#/hooks/query/use-latest-automation-runs";+import {+ AutomationRunStatus,+ type Automation,+ type AutomationRun,+} from "#/types/automation";++/** Must stay equal to `MAX_HOME_AUTOMATION_CHIPS` in use-home-automations. */+const DEMO_LIST_LENGTH = 20;++const DEMO_HISTORY_PATTERN: AutomationRunStatus[] = [+ AutomationRunStatus.COMPLETED,+ AutomationRunStatus.COMPLETED,+ AutomationRunStatus.FAILED,+ AutomationRunStatus.COMPLETED,+ AutomationRunStatus.CANCELLED,+ AutomationRunStatus.COMPLETED,+ AutomationRunStatus.COMPLETED,+ AutomationRunStatus.FAILED,+ AutomationRunStatus.COMPLETED,+ AutomationRunStatus.SKIPPED,+ AutomationRunStatus.COMPLETED,+];++/**+ * Local preview of every pinned-card + activity-list state.+ *+ * Enable with any of:+ * - `HOME_AUTOMATIONS_FORCE_DEMO = true` below+ * - `localStorage.setItem("oh:home-automations-demo", "1")`+ * - `?demoAutomations=1` in the URL+ * - `VITE_HOME_AUTOMATIONS_DEMO=true`+ */+export const HOME_AUTOMATIONS_FORCE_DEMO = false;++export const HOME_AUTOMATIONS_DEMO_KEY = "oh:home-automations-demo";++export function isHomeAutomationsDemoEnabled(): boolean {+ if (HOME_AUTOMATIONS_FORCE_DEMO) return true;+ if (import.meta.env.VITE_HOME_AUTOMATIONS_DEMO === "true") return true;+ if (typeof window === "undefined") return false;+ if (window.localStorage.getItem(HOME_AUTOMATIONS_DEMO_KEY) === "1") {+ return true;+ }+ try {+ return (+ new URLSearchParams(window.location.search).get("demoAutomations") === "1"+ );+ } catch {+ return false;+ }+}++const DEMO_CONVERSATION_TITLES: Record<string, string | null> = {+ "demo-conv-titled": "Fix flaky CI on main",+ "demo-conv-untitled": "Summarize open pull requests",+};++/** Returns a demo conversation title, or `undefined` if not a demo id. */+export function getDemoConversationTitle(+ conversationId: string,+): string | null | undefined {+ if (!(conversationId in DEMO_CONVERSATION_TITLES)) return undefined;+ return DEMO_CONVERSATION_TITLES[conversationId];+}++function hoursAgo(hours: number): string {+ return new Date(Date.now() - hours * 3_600_000).toISOString();+}++function makeAutomation(+ id: string,+ name: string,+ trigger: Automation["trigger"],+): Automation {+ return {+ id,+ name,+ trigger,+ enabled: true,+ created_at: hoursAgo(720),+ updated_at: hoursAgo(24),+ prompt: "demo",+ };+}++function makeRun(+ id: string,+ status: AutomationRunStatus,+ options: {+ conversationId?: string | null;+ errorDetail?: string | null;+ startedHoursAgo?: number;+ completedHoursAgo?: number | null;+ } = {},+): AutomationRun {+ const startedHoursAgo = options.startedHoursAgo ?? 2;+ const completedHoursAgo =+ options.completedHoursAgo === undefined ? 1 : options.completedHoursAgo;+ return {+ id,+ status,+ conversation_id:+ options.conversationId === undefined ? null : options.conversationId,+ bash_command_id: null,+ error_detail:+ options.errorDetail === undefined ? null : options.errorDetail,+ started_at: hoursAgo(startedHoursAgo),+ completed_at:+ completedHoursAgo === null ? null : hoursAgo(completedHoursAgo),+ };+}++type DemoRunStateInput = Omit<LatestAutomationRunState, "recentRuns"> & {+ recentRuns?: AutomationRun[];+};++type DemoSpec = {+ automation: Automation;+ runState: DemoRunStateInput;+ /** When true, this automation is pinned in the dashboard. */+ pin?: boolean;+};++function buildDemoRecentRuns(latestRun: AutomationRun | null): AutomationRun[] {+ if (!latestRun) return [];+ // Varied durations (minutes) so sparkline bar heights differ in demo mode.+ const durationMinutes = [2, 8, 45, 3, 15, 1, 25, 90, 5, 12, 6];+ const older = DEMO_HISTORY_PATTERN.slice(+ 0,+ AUTOMATION_RUN_ACTIVITY_LIMIT - 1,+ ).map((status, index) => {+ const startedHoursAgo = 24 + index * 6;+ const durationHours = (durationMinutes[index] ?? 5) / 60;+ return makeRun(`${latestRun.id}-hist-${index}`, status, {+ startedHoursAgo,+ completedHoursAgo: startedHoursAgo - durationHours,+ conversationId: null,+ errorDetail:+ status === AutomationRunStatus.FAILED ? "Prior failure" : null,+ });+ });+ return [latestRun, ...older];+}++function toDemoRunState(state: DemoRunStateInput): LatestAutomationRunState {+ return {+ ...state,+ recentRuns: state.recentRuns ?? buildDemoRecentRuns(state.latestRun),+ };+}++/**+ * Explicit card states first (pinned), then fillers to hit+ * DEMO_LIST_LENGTH for list-length stress.+ */+const DEMO_SPECS: DemoSpec[] = [+ {+ pin: true,+ automation: makeAutomation("demo-pin-loading", "Card: loading skeleton", {+ type: "cron",+ schedule: "0 * * * *",+ schedule_human: "Every hour",+ }),+ runState: { latestRun: null, isLoading: true, isError: false },+ },+ {+ pin: true,+ automation: makeAutomation("demo-pin-error", "Card: status unavailable", {+ type: "cron",+ schedule: "0 9 * * *",+ schedule_human: "Daily at 9am",+ }),+ runState: { latestRun: null, isLoading: false, isError: true },+ },+ {+ pin: true,+ automation: makeAutomation("demo-pin-no-runs", "Card: no runs yet", {+ type: "event",+ source: "github",+ on: "pull_request.opened",+ }),+ runState: { latestRun: null, isLoading: false, isError: false },+ },+ {+ pin: true,+ automation: makeAutomation(+ "demo-pin-failed-detail",+ "Card: failed with error detail",+ {+ type: "cron",+ schedule: "*/15 * * * *",+ schedule_human: "Every 15 min",+ },+ ),+ runState: {+ latestRun: makeRun("run-failed-detail", AutomationRunStatus.FAILED, {+ errorDetail:+ "Sandbox provisioning timed out after 120s while waiting for the runtime to become ready.",+ startedHoursAgo: 3,+ completedHoursAgo: 2.5,+ }),+ isLoading: false,+ isError: false,+ },+ },+ {+ pin: true,+ automation: makeAutomation(+ "demo-pin-completed-title",+ "Card: completed + conversation title",+ { type: "event", source: "github", on: "push" },+ ),+ runState: {+ latestRun: makeRun("run-completed-title", AutomationRunStatus.COMPLETED, {+ conversationId: "demo-conv-titled",+ startedHoursAgo: 5,+ completedHoursAgo: 4,+ }),+ isLoading: false,+ isError: false,+ },+ },+ {+ pin: true,+ automation: makeAutomation(+ "demo-pin-completed-untitled",+ "Card: completed + conversation title",+ {+ type: "cron",+ schedule: "0 0 * * 1",+ schedule_human: "Mondays at midnight",+ },+ ),+ runState: {+ latestRun: makeRun(+ "run-completed-untitled",+ AutomationRunStatus.COMPLETED,+ {+ conversationId: "demo-conv-untitled",+ startedHoursAgo: 8,+ completedHoursAgo: 7,+ },+ ),+ isLoading: false,+ isError: false,+ },+ },+ {+ pin: true,+ automation: makeAutomation(+ "demo-pin-completed-no-conv",+ "Card: completed, no conversation",+ { type: "cron", schedule: "0 12 * * *", schedule_human: "Daily at noon" },+ ),+ runState: {+ latestRun: makeRun(+ "run-completed-no-conv",+ AutomationRunStatus.COMPLETED,+ {+ conversationId: null,+ startedHoursAgo: 10,+ completedHoursAgo: 9,+ },+ ),+ isLoading: false,+ isError: false,+ },+ },+ {+ pin: true,+ automation: makeAutomation(+ "demo-pin-failed-no-conv",+ "Card: failed, no conversation",+ { type: "event", source: "slack", on: "message" },+ ),+ runState: {+ latestRun: makeRun("run-failed-no-conv", AutomationRunStatus.FAILED, {+ conversationId: null,+ errorDetail: null,+ startedHoursAgo: 12,+ completedHoursAgo: 11,+ }),+ isLoading: false,+ isError: false,+ },+ },+ {+ pin: true,+ automation: makeAutomation(+ "demo-pin-pending",+ "Card: pending (empty result panel)",+ {+ type: "cron",+ schedule: "0 */6 * * *",+ schedule_human: "Every 6 hours",+ },+ ),+ runState: {+ latestRun: makeRun("run-pending", AutomationRunStatus.PENDING, {+ conversationId: null,+ startedHoursAgo: 0.1,+ completedHoursAgo: null,+ }),+ isLoading: false,+ isError: false,+ },+ },+ {+ pin: true,+ automation: makeAutomation(+ "demo-pin-running",+ "Card: running (empty result panel)",+ { type: "event", source: "github", on: "issues.opened" },+ ),+ runState: {+ latestRun: makeRun("run-running", AutomationRunStatus.RUNNING, {+ // No conversation yet — status strip shows the "Running" label.+ conversationId: null,+ startedHoursAgo: 0.25,+ completedHoursAgo: null,+ }),+ isLoading: false,+ isError: false,+ },+ },+ // Remaining rows fill the list to MAX_HOME_AUTOMATION_CHIPS.+ {+ automation: makeAutomation("demo-list-cancelled", "List: cancelled run", {+ type: "cron",+ schedule: "30 2 * * *",+ schedule_human: "Daily at 2:30am",+ }),+ runState: {+ latestRun: makeRun("run-cancelled", AutomationRunStatus.CANCELLED, {+ startedHoursAgo: 14,+ completedHoursAgo: 13,+ }),+ isLoading: false,+ isError: false,+ },+ },+ {+ automation: makeAutomation("demo-list-skipped", "List: skipped run", {+ type: "event",+ source: "github",+ on: "pull_request.synchronize",+ }),+ runState: {+ latestRun: makeRun("run-skipped", AutomationRunStatus.SKIPPED, {+ startedHoursAgo: 16,+ completedHoursAgo: 16,+ }),+ isLoading: false,+ isError: false,+ },+ },+ {+ automation: makeAutomation(+ "demo-list-running-2",+ "List: second in-flight run",+ { type: "cron", schedule: "*/5 * * * *", schedule_human: "Every 5 min" },+ ),+ runState: {+ latestRun: makeRun("run-running-2", AutomationRunStatus.RUNNING, {+ conversationId: null,+ startedHoursAgo: 0.5,+ completedHoursAgo: null,+ }),+ isLoading: false,+ isError: false,+ },+ },+ {+ automation: makeAutomation("demo-list-success-old", "List: older success", {+ type: "cron",+ schedule: "0 8 * * 1-5",+ schedule_human: "Weekdays at 8am",+ }),+ runState: {+ latestRun: makeRun("run-success-old", AutomationRunStatus.COMPLETED, {+ conversationId: "demo-conv-titled",+ startedHoursAgo: 48,+ completedHoursAgo: 47,+ }),+ isLoading: false,+ isError: false,+ },+ },+ {+ automation: makeAutomation("demo-list-failed-old", "List: older failure", {+ type: "event",+ source: "github",+ on: "release.published",+ }),+ runState: {+ latestRun: makeRun("run-failed-old", AutomationRunStatus.FAILED, {+ errorDetail: "Model returned an empty completion.",+ startedHoursAgo: 72,+ completedHoursAgo: 71,+ }),+ isLoading: false,+ isError: false,+ },+ },+ {+ automation: makeAutomation("demo-list-no-runs-2", "List: never ran", {+ type: "cron",+ schedule: "0 0 1 * *",+ schedule_human: "Monthly on the 1st",+ }),+ runState: { latestRun: null, isLoading: false, isError: false },+ },+ {+ automation: makeAutomation("demo-list-loading-2", "List: loading status", {+ type: "event",+ source: "linear",+ on: "Issue.create",+ }),+ runState: { latestRun: null, isLoading: true, isError: false },+ },+ {+ automation: makeAutomation("demo-list-error-2", "List: fetch error", {+ type: "cron",+ schedule: "15 * * * *",+ schedule_human: "Hourly at :15",+ }),+ runState: { latestRun: null, isLoading: false, isError: true },+ },+ {+ automation: makeAutomation(+ "demo-list-pending-2",+ "List: pending, long name that should truncate in the activity row when the viewport is narrow",+ { type: "cron", schedule: "0 3 * * 0", schedule_human: "Sundays at 3am" },+ ),+ runState: {+ latestRun: makeRun("run-pending-2", AutomationRunStatus.PENDING, {+ startedHoursAgo: 0.05,+ completedHoursAgo: null,+ }),+ isLoading: false,+ isError: false,+ },+ },+ {+ automation: makeAutomation(+ "demo-list-completed-fallback",+ "List: completed with conversation",+ { type: "event", source: "github", on: "workflow_run.completed" },+ ),+ runState: {+ latestRun: makeRun(+ "run-completed-fallback",+ AutomationRunStatus.COMPLETED,+ {+ conversationId: "demo-conv-untitled",+ startedHoursAgo: 20,+ completedHoursAgo: 19,+ },+ ),+ isLoading: false,+ isError: false,+ },+ },+];++if (DEMO_SPECS.length !== DEMO_LIST_LENGTH) {+ throw new Error(+ `home-automations-demo: expected ${DEMO_LIST_LENGTH} specs, got ${DEMO_SPECS.length}`,+ );+}++export const HOME_AUTOMATIONS_DEMO_PINNED_IDS: string[] = DEMO_SPECS.filter(+ (spec) => spec.pin,+).map((spec) => spec.automation.id);++export const HOME_AUTOMATIONS_DEMO_AUTOMATIONS: Automation[] = DEMO_SPECS.map(+ (spec) => spec.automation,+);++export const HOME_AUTOMATIONS_DEMO_RUN_STATES: Map<+ string,+ LatestAutomationRunState+> = new Map(+ DEMO_SPECS.map(+ (spec) => [spec.automation.id, toDemoRunState(spec.runState)] as const,+ ),+);diff --git a/src/hooks/query/use-automations.ts b/src/hooks/query/use-automations.tsindex cd34aab39f..60b5000738 100644--- a/src/hooks/query/use-automations.ts+++ b/src/hooks/query/use-automations.ts@@ -107,3 +107,18 @@ export function useDispatchAutomation() {},});}++export function useCancelAutomationRun() {+ const queryClient = useQueryClient();+ return useMutation({+ mutationFn: ({ runId }: { automationId: string; runId: string }) =>+ AutomationService.cancelAutomationRun(runId),+ onSuccess: (_run, { automationId }) => {+ queryClient.invalidateQueries({ queryKey: AUTOMATIONS_QUERY_KEY });+ queryClient.invalidateQueries({ queryKey: AUTOMATION_DETAIL_QUERY_KEY });+ queryClient.invalidateQueries({+ queryKey: [...AUTOMATION_RUNS_QUERY_KEY, automationId],+ });+ },+ });+}diff --git a/src/hooks/query/use-home-automations.ts b/src/hooks/query/use-home-automations.tsnew file mode 100644index 0000000000..ed7e501894--- /dev/null+++ b/src/hooks/query/use-home-automations.ts@@ -0,0 +1,89 @@+import { useAutomationHealth } from "#/hooks/query/use-automation-health";+import { useAutomations } from "#/hooks/query/use-automations";+import {+ useLatestAutomationRuns,+ type LatestAutomationRunState,+} from "#/hooks/query/use-latest-automation-runs";+import {+ HOME_AUTOMATIONS_DEMO_AUTOMATIONS,+ HOME_AUTOMATIONS_DEMO_RUN_STATES,+ isHomeAutomationsDemoEnabled,+} from "#/fixtures/home-automations-demo";++/** Initial visible rows in the home automations list before "View more". */+export const HOME_AUTOMATIONS_PREVIEW_LIMIT = 10;++/** Bounds the per-automation latest-run request fan-out on the home page. */+export const MAX_HOME_AUTOMATION_CHIPS = 20;++export const UNKNOWN_RUN_STATE: LatestAutomationRunState = {+ latestRun: null,+ recentRuns: [],+ isLoading: true,+ isError: false,+};++/**+ * Shared home-page automation queries: health gate, enabled automations, and+ * latest-run state for the recent-activity list and pinned dashboard.+ */+export function useHomeAutomations() {+ const demo = isHomeAutomationsDemoEnabled();+ const { data: healthData, isLoading: isHealthLoading } =+ useAutomationHealth();+ const isBackendHealthy = healthData?.status === "ok";+ const {+ data: automationsData,+ isError,+ isLoading: isAutomationsLoading,+ } = useAutomations({+ limit: 50,+ offset: 0,+ enabled: !demo && isBackendHealthy,+ });++ const allAutomations = demo+ ? HOME_AUTOMATIONS_DEMO_AUTOMATIONS+ : (automationsData?.automations ?? []);++ const enabledAutomations = allAutomations+ .filter((automation) => automation.enabled)+ .slice(0, MAX_HOME_AUTOMATION_CHIPS);++ const knownAutomationIds = new Set(+ allAutomations.map((automation) => automation.id),+ );++ // False while loading or when the backend has more automations than the+ // fetched page — consumers must not prune pins against a partial id set.+ const isAutomationListComplete = demo+ ? true+ : automationsData != null && allAutomations.length >= automationsData.total;++ const liveRunStates = useLatestAutomationRuns(demo ? [] : enabledAutomations);+ const runStates = demo ? HOME_AUTOMATIONS_DEMO_RUN_STATES : liveRunStates;++ if (demo) {+ return {+ isBackendHealthy: true,+ isHealthLoading: false,+ isError: false,+ isAutomationsLoading: false,+ enabledAutomations,+ knownAutomationIds,+ isAutomationListComplete,+ runStates,+ };+ }++ return {+ isBackendHealthy,+ isHealthLoading,+ isError,+ isAutomationsLoading,+ enabledAutomations,+ knownAutomationIds,+ isAutomationListComplete,+ runStates,+ };+}diff --git a/src/hooks/query/use-latest-automation-runs.ts b/src/hooks/query/use-latest-automation-runs.tsnew file mode 100644index 0000000000..bafab6645e--- /dev/null+++ b/src/hooks/query/use-latest-automation-runs.ts@@ -0,0 +1,93 @@+import { useQueries } from "@tanstack/react-query";+import AutomationService from "#/api/automation-service/automation-service.api";+import { useActiveBackend } from "#/contexts/active-backend-context";+import {+ AutomationRunStatus,+ type Automation,+ type AutomationRun,+ type AutomationRunsResponse,+} from "#/types/automation";+import { AUTOMATION_RUNS_QUERY_KEY } from "./use-automation-detail";++/**+ * Poll interval while a run is non-terminal. Deliberately slower than the 3s+ * used by `useAutomationRuns`: that hook polls a single automation on its+ * detail page, whereas this one issues one request *per automation* (up to+ * MAX_AUTOMATION_CHIPS). At 15s a fully in-flight home section costs about the+ * same request rate as one open detail page.+ */+const IN_FLIGHT_POLL_INTERVAL_MS = 15_000;++/** Recent runs fetched for the home activity sparkline (newest-first page size). */+export const AUTOMATION_RUN_ACTIVITY_LIMIT = 12;++export interface LatestAutomationRunState {+ /** Newest run of the automation, or null while loading / on error / when none exist. */+ latestRun: AutomationRun | null;+ /** Newest-first recent runs for the activity sparkline (may be empty). */+ recentRuns: AutomationRun[];+ isLoading: boolean;+ isError: boolean;+}++/**+ * Fetch recent runs for each automation (newest-first). The first item is the+ * latest run; the page feeds the home activity sparkline. Each query uses the+ * same key shape as `useAutomationRuns` (distinct `{limit, offset}` part,+ * shared `[...AUTOMATION_RUNS_QUERY_KEY, id]` prefix), so dispatch mutations+ * that invalidate an automation's runs reach these entries too.+ */+export function useLatestAutomationRuns(+ automations: readonly Automation[],+): Map<string, LatestAutomationRunState> {+ const active = useActiveBackend();++ const results = useQueries({+ queries: automations.map((automation) => ({+ queryKey: [+ ...AUTOMATION_RUNS_QUERY_KEY,+ automation.id,+ { limit: AUTOMATION_RUN_ACTIVITY_LIMIT, offset: 0 },+ active.backend.id,+ active.orgId,+ ],+ queryFn: () =>+ AutomationService.getAutomationRuns(+ automation.id,+ AUTOMATION_RUN_ACTIVITY_LIMIT,+ 0,+ ),+ staleTime: 60 * 1000,+ // No retries: the home section settles into its degraded "unknown"+ // indicator instead of hammering an unhealthy automation service.+ retry: false,+ // One request per automation already fans out on mount; refetching the+ // whole set again on every tab focus is not worth the run-health delta.+ refetchOnWindowFocus: false,+ // Poll while the latest run is non-terminal so status and+ // conversation_id transitions appear without a manual refresh.+ refetchInterval: (query: {+ state: { data?: AutomationRunsResponse };+ }) => {+ const latest = query.state.data?.runs[0];+ const isInFlight =+ latest?.status === AutomationRunStatus.PENDING ||+ latest?.status === AutomationRunStatus.RUNNING;+ return isInFlight ? IN_FLIGHT_POLL_INTERVAL_MS : false;+ },+ })),+ });++ const runStates = new Map<string, LatestAutomationRunState>();+ automations.forEach((automation, i) => {+ const result = results[i];+ const recentRuns = result?.data?.runs ?? [];+ runStates.set(automation.id, {+ latestRun: recentRuns[0] ?? null,+ recentRuns,+ isLoading: result?.isPending ?? true,+ isError: result?.isError ?? false,+ });+ });+ return runStates;+}diff --git a/src/hooks/use-home-automation-actions.ts b/src/hooks/use-home-automation-actions.tsnew file mode 100644index 0000000000..05c49bbe48--- /dev/null+++ b/src/hooks/use-home-automation-actions.ts@@ -0,0 +1,152 @@+import { useCallback, useState } from "react";+import { useTranslation } from "react-i18next";+import { useActiveBackend } from "#/contexts/active-backend-context";+import { useNavigation } from "#/context/navigation-context";+import {+ useCancelAutomationRun,+ useDispatchAutomation,+ useToggleAutomation,+} from "#/hooks/query/use-automations";+import { useHasPermission } from "#/hooks/use-has-permission";+import { isHomeAutomationsDemoEnabled } from "#/fixtures/home-automations-demo";+import { I18nKey } from "#/i18n/declaration";+import {+ AutomationRunStatus,+ type Automation,+ type AutomationRun,+} from "#/types/automation";+import { getApiErrorMessage } from "#/utils/api-error-message";+import {+ displayErrorToast,+ displaySuccessToast,+} from "#/utils/custom-toast-handlers";++export function isInFlightAutomationRun(+ run: AutomationRun | null | undefined,+): boolean {+ return (+ run?.status === AutomationRunStatus.PENDING ||+ run?.status === AutomationRunStatus.RUNNING+ );+}++/**+ * Shared home-surface actions for pinned cards and activity rows:+ * run now, view, edit (local), turn off (with confirm), cancel in-flight.+ */+export function useHomeAutomationActions(+ automation: Automation,+ latestRun: AutomationRun | null,+) {+ const { t } = useTranslation("openhands");+ const { navigate } = useNavigation();+ const active = useActiveBackend();+ const canManage = useHasPermission("manage_automations");+ const canEdit = active.backend.kind === "local";+ const isDemo = isHomeAutomationsDemoEnabled();++ const dispatchMutation = useDispatchAutomation();+ const toggleMutation = useToggleAutomation();+ const cancelMutation = useCancelAutomationRun();++ const [editOpen, setEditOpen] = useState(false);+ const [turnOffConfirmOpen, setTurnOffConfirmOpen] = useState(false);++ const isRunPending =+ dispatchMutation.isPending && dispatchMutation.variables === automation.id;+ const isCancelPending =+ cancelMutation.isPending &&+ cancelMutation.variables?.runId === latestRun?.id;+ const canCancel = canManage && isInFlightAutomationRun(latestRun);++ const runNow = useCallback(() => {+ if (isDemo) {+ displaySuccessToast(t(I18nKey.AUTOMATIONS$RUN_NOW_SUCCESS));+ return;+ }+ dispatchMutation.mutate(automation.id, {+ onSuccess: () => {+ displaySuccessToast(t(I18nKey.AUTOMATIONS$RUN_NOW_SUCCESS));+ },+ onError: (error) => {+ displayErrorToast(+ getApiErrorMessage(error, t(I18nKey.AUTOMATIONS$RUN_NOW_ERROR)),+ );+ },+ });+ }, [automation.id, dispatchMutation, isDemo, t]);++ const viewDetails = useCallback(() => {+ navigate?.(`/automations/${automation.id}`);+ }, [automation.id, navigate]);++ const openEdit = useCallback(() => {+ if (!canEdit) {+ viewDetails();+ return;+ }+ setEditOpen(true);+ }, [canEdit, viewDetails]);++ const requestTurnOff = useCallback(() => {+ setTurnOffConfirmOpen(true);+ }, []);++ const confirmTurnOff = useCallback(() => {+ setTurnOffConfirmOpen(false);+ if (isDemo) return;+ toggleMutation.mutate(+ { id: automation.id, enabled: false },+ {+ onError: (error) => {+ displayErrorToast(+ getApiErrorMessage(error, t(I18nKey.AUTOMATIONS$TURN_OFF_ERROR)),+ );+ },+ },+ );+ }, [automation.id, isDemo, t, toggleMutation]);++ const cancelTurnOff = useCallback(() => {+ setTurnOffConfirmOpen(false);+ }, []);++ const cancelRun = useCallback(() => {+ if (!latestRun || !isInFlightAutomationRun(latestRun)) return;+ if (isDemo) {+ displaySuccessToast(t(I18nKey.AUTOMATIONS$CANCEL_RUN_SUCCESS));+ return;+ }+ cancelMutation.mutate(+ { automationId: automation.id, runId: latestRun.id },+ {+ onSuccess: () => {+ displaySuccessToast(t(I18nKey.AUTOMATIONS$CANCEL_RUN_SUCCESS));+ },+ onError: (error) => {+ displayErrorToast(+ getApiErrorMessage(error, t(I18nKey.AUTOMATIONS$CANCEL_RUN_ERROR)),+ );+ },+ },+ );+ }, [automation.id, cancelMutation, isDemo, latestRun, t]);++ return {+ canManage,+ canEdit,+ isRunPending,+ isCancelPending,+ canCancel,+ editOpen,+ setEditOpen,+ turnOffConfirmOpen,+ runNow,+ viewDetails,+ openEdit,+ requestTurnOff,+ confirmTurnOff,+ cancelTurnOff,+ cancelRun,+ };+}diff --git a/src/hooks/use-home-pinned-automations.ts b/src/hooks/use-home-pinned-automations.tsnew file mode 100644index 0000000000..8471b7692b--- /dev/null+++ b/src/hooks/use-home-pinned-automations.ts@@ -0,0 +1,209 @@+import { useLocalStorage } from "@uidotdev/usehooks";+import { useCallback, useMemo, useState } from "react";+import { useActiveBackend } from "#/contexts/active-backend-context";+import {+ HOME_AUTOMATIONS_DEMO_PINNED_IDS,+ isHomeAutomationsDemoEnabled,+} from "#/fixtures/home-automations-demo";++export const HOME_PINNED_AUTOMATIONS_KEY = "oh:home-pinned-automations";++/**+ * Pins are stored per backend + org: automation ids only resolve against the+ * backend that issued them, and `pruneMissing` compares against the active+ * backend's list — a shared key would let one backend wipe another's pins.+ */+export function getHomePinnedAutomationsKey(+ backendId: string,+ orgId: string | null,+): string {+ return `${HOME_PINNED_AUTOMATIONS_KEY}:${backendId}:${orgId ?? "-"}`;+}++/** Soft preview cap for the home pinned dashboard before "View more". */+export const HOME_PINNED_PREVIEW_LIMIT = 6;++function sanitizePinnedIds(value: unknown): string[] {+ if (!Array.isArray(value)) return [];+ const seen = new Set<string>();+ const next: string[] = [];+ for (const entry of value) {+ if (typeof entry !== "string" || !entry || seen.has(entry)) {+ continue;+ }+ seen.add(entry);+ next.push(entry);+ }+ return next;+}++/** Reorder `base` to match `preferred` where possible; append leftovers. */+export function applyPinnedOrder(+ base: readonly string[],+ preferred: readonly string[],+): string[] {+ const remaining = new Set(base);+ const ordered: string[] = [];+ for (const id of preferred) {+ if (remaining.has(id)) {+ ordered.push(id);+ remaining.delete(id);+ }+ }+ for (const id of base) {+ if (remaining.has(id)) ordered.push(id);+ }+ return ordered;+}++export function movePinnedId(+ ids: readonly string[],+ activeId: string,+ targetId: string,+ position: "before" | "after" = "after",+): string[] {+ if (activeId === targetId) return [...ids];+ const fromIndex = ids.indexOf(activeId);+ const toIndex = ids.indexOf(targetId);+ if (fromIndex < 0 || toIndex < 0) return [...ids];++ const next = [...ids];+ next.splice(fromIndex, 1);+ const adjustedTarget = next.indexOf(targetId);+ const insertIndex =+ position === "before" ? adjustedTarget : adjustedTarget + 1;+ next.splice(insertIndex, 0, activeId);+ return next;+}++/**+ * Pin state for home automation activity rows. Persists pinned ids in+ * localStorage so dashboard modules survive reload. Resolution against live+ * automations happens in the consuming components.+ */+export function useHomePinnedAutomations() {+ const demo = isHomeAutomationsDemoEnabled();+ const active = useActiveBackend();+ const [rawPinnedIds, setRawPinnedIds] = useLocalStorage<string[]>(+ getHomePinnedAutomationsKey(active.backend.id, active.orgId),+ [],+ );+ // Demo pins are fixture-backed; keep session order overrides in memory so+ // drag reorder still works while testing with mock data.+ const [demoOrder, setDemoOrder] = useState<string[] | null>(null);++ const pinnedIds = useMemo(() => {+ if (demo) {+ return demoOrder+ ? applyPinnedOrder(HOME_AUTOMATIONS_DEMO_PINNED_IDS, demoOrder)+ : [...HOME_AUTOMATIONS_DEMO_PINNED_IDS];+ }+ return sanitizePinnedIds(rawPinnedIds);+ }, [demo, demoOrder, rawPinnedIds]);++ const isPinned = useCallback(+ (id: string) => pinnedIds.includes(id),+ [pinnedIds],+ );++ const pin = useCallback(+ (id: string) => {+ if (demo) {+ setDemoOrder((current) => {+ const base = current+ ? applyPinnedOrder(HOME_AUTOMATIONS_DEMO_PINNED_IDS, current)+ : [...HOME_AUTOMATIONS_DEMO_PINNED_IDS];+ if (base.includes(id)) return base;+ return [...base, id];+ });+ return;+ }+ setRawPinnedIds((current) => {+ const next = sanitizePinnedIds(current);+ if (next.includes(id)) return next;+ return [...next, id];+ });+ },+ [demo, setRawPinnedIds],+ );++ const unpin = useCallback(+ (id: string) => {+ if (demo) {+ setDemoOrder((current) => {+ const base = current+ ? applyPinnedOrder(HOME_AUTOMATIONS_DEMO_PINNED_IDS, current)+ : [...HOME_AUTOMATIONS_DEMO_PINNED_IDS];+ return base.filter((pinnedId) => pinnedId !== id);+ });+ return;+ }+ setRawPinnedIds((current) =>+ sanitizePinnedIds(current).filter((pinnedId) => pinnedId !== id),+ );+ },+ [demo, setRawPinnedIds],+ );++ const togglePin = useCallback(+ (id: string) => {+ if (isPinned(id)) {+ unpin(id);+ return;+ }+ pin(id);+ },+ [isPinned, pin, unpin],+ );++ const reorder = useCallback(+ (+ activeId: string,+ targetId: string,+ position: "before" | "after" = "after",+ ) => {+ if (demo) {+ setDemoOrder((current) => {+ const base = current+ ? applyPinnedOrder(HOME_AUTOMATIONS_DEMO_PINNED_IDS, current)+ : [...HOME_AUTOMATIONS_DEMO_PINNED_IDS];+ return movePinnedId(base, activeId, targetId, position);+ });+ return;+ }+ setRawPinnedIds((current) =>+ movePinnedId(sanitizePinnedIds(current), activeId, targetId, position),+ );+ },+ [demo, setRawPinnedIds],+ );++ /** Drop pin ids that no longer exist on the backend (deleted automations). */+ const pruneMissing = useCallback(+ (knownIds: ReadonlySet<string>) => {+ if (demo) return;+ setRawPinnedIds((current) => {+ const sanitized = sanitizePinnedIds(current);+ const next = sanitized.filter((id) => knownIds.has(id));+ if (+ next.length === sanitized.length &&+ next.every((id, index) => id === sanitized[index])+ ) {+ return sanitized;+ }+ return next;+ });+ },+ [demo, setRawPinnedIds],+ );++ return {+ pinnedIds,+ isPinned,+ pin,+ unpin,+ togglePin,+ reorder,+ pruneMissing,+ };+}diff --git a/src/i18n/translation.json b/src/i18n/translation.jsonindex 638a4d3dbd..1129b79683 100644--- a/src/i18n/translation.json+++ b/src/i18n/translation.json@@ -14331,21 +14331,21 @@"ca": "Encara no hi ha activitat"},"AUTOMATIONS$DETAIL$NO_CONVERSATION": {- "en": "Conversation not created",- "ja": "会話が作成されていません",- "zh-CN": "对话未创建",- "zh-TW": "對話未建立",- "ko-KR": "대화가 생성되지 않음",- "no": "Samtale ikke opprettet",- "it": "Conversazione non creata",- "pt": "Conversa não criada",- "es": "Conversación no creada",- "ar": "لم يتم إنشاء المحادثة",- "fr": "Conversation non créée",- "tr": "Konuşma oluşturulmadı",- "de": "Konversation nicht erstellt",- "uk": "Розмову не створено",- "ca": "Conversa no creada"+ "en": "No Conversation",+ "ja": "会話なし",+ "zh-CN": "无对话",+ "zh-TW": "無對話",+ "ko-KR": "대화 없음",+ "no": "Ingen samtale",+ "it": "Nessuna conversazione",+ "pt": "Sem conversa",+ "es": "Sin conversación",+ "ar": "لا توجد محادثة",+ "fr": "Aucune conversation",+ "tr": "Konuşma yok",+ "de": "Keine Konversation",+ "uk": "Немає розмови",+ "ca": "Sense conversa"},"AUTOMATIONS$DETAIL$LOGS_VIEW": {"en": "View logs for run on {{timestamp}}",@@ -35036,6 +35036,482 @@"uk": "Запуск…","ca": "S'està iniciant…"},+ "FEATURED_AUTOMATIONS$SECTION_TITLE": {+ "en": "Automations",+ "ja": "オートメーション",+ "zh-CN": "自动化",+ "zh-TW": "自動化",+ "ko-KR": "자동화",+ "no": "Automatiseringer",+ "it": "Automazioni",+ "pt": "Automações",+ "es": "Automatizaciones",+ "ar": "الأتمتة",+ "fr": "Automatisations",+ "tr": "Otomasyonlar",+ "de": "Automatisierungen",+ "uk": "Автоматизації",+ "ca": "Automatitzacions"+ },+ "FEATURED_AUTOMATIONS$CHIP_GROUP_LABEL": {+ "en": "Open automations",+ "ja": "稼働中のオートメーション",+ "zh-CN": "已启用的自动化",+ "zh-TW": "已啟用的自動化",+ "ko-KR": "활성 자동화",+ "no": "Aktive automatiseringer",+ "it": "Automazioni attive",+ "pt": "Automações ativas",+ "es": "Automatizaciones activas",+ "ar": "الأتمتة النشطة",+ "fr": "Automatisations actives",+ "tr": "Etkin otomasyonlar",+ "de": "Aktive Automatisierungen",+ "uk": "Активні автоматизації",+ "ca": "Automatitzacions actives"+ },+ "FEATURED_AUTOMATIONS$FEATURED_HEADING": {+ "en": "Featured",+ "ja": "注目",+ "zh-CN": "精选",+ "zh-TW": "精選",+ "ko-KR": "주요",+ "no": "Fremhevet",+ "it": "In evidenza",+ "pt": "Em destaque",+ "es": "Destacadas",+ "ar": "مميزة",+ "fr": "En vedette",+ "tr": "Öne çıkanlar",+ "de": "Hervorgehoben",+ "uk": "Вибрані",+ "ca": "Destacades"+ },+ "FEATURED_AUTOMATIONS$MANAGE": {+ "en": "Add or manage automations",+ "ja": "オートメーションを追加または管理",+ "zh-CN": "添加或管理自动化",+ "zh-TW": "新增或管理自動化",+ "ko-KR": "자동화 추가 또는 관리",+ "no": "Legg til eller administrer automatiseringer",+ "it": "Aggiungi o gestisci le automazioni",+ "pt": "Adicionar ou gerenciar automações",+ "es": "Añadir o gestionar automatizaciones",+ "ar": "إضافة الأتمتة أو إدارتها",+ "fr": "Ajouter ou gérer des automatisations",+ "tr": "Otomasyon ekle veya yönet",+ "de": "Automatisierungen hinzufügen oder verwalten",+ "uk": "Додати або керувати автоматизаціями",+ "ca": "Afegeix o gestiona automatitzacions"+ },+ "FEATURED_AUTOMATIONS$VIEW_CONVERSATION": {+ "en": "Open most recent conversation",+ "ja": "最新の会話を開く",+ "zh-CN": "打开最近的对话",+ "zh-TW": "開啟最近的對話",+ "ko-KR": "최근 대화 열기",+ "no": "Åpne siste samtale",+ "it": "Apri la conversazione più recente",+ "pt": "Abrir a conversa mais recente",+ "es": "Abrir la conversación más reciente",+ "ar": "فتح أحدث محادثة",+ "fr": "Ouvrir la conversation la plus récente",+ "tr": "En son konuşmayı aç",+ "de": "Neueste Unterhaltung öffnen",+ "uk": "Відкрити останню розмову",+ "ca": "Obre la conversa més recent"+ },+ "FEATURED_AUTOMATIONS$VIEW_DETAILS": {+ "en": "View automation details",+ "ja": "オートメーションの詳細を表示",+ "zh-CN": "查看自动化详情",+ "zh-TW": "檢視自動化詳細資訊",+ "ko-KR": "자동화 세부 정보 보기",+ "no": "Vis automatiseringsdetaljer",+ "it": "Visualizza i dettagli dell'automazione",+ "pt": "Ver detalhes da automação",+ "es": "Ver detalles de la automatización",+ "ar": "عرض تفاصيل الأتمتة",+ "fr": "Voir les détails de l'automatisation",+ "tr": "Otomasyon ayrıntılarını görüntüle",+ "de": "Automatisierungsdetails anzeigen",+ "uk": "Переглянути деталі автоматизації",+ "ca": "Mostra els detalls de l'automatització"+ },+ "FEATURED_AUTOMATIONS$LAST_RUN_SUCCEEDED": {+ "en": "Last run succeeded",+ "ja": "最終実行は成功しました",+ "zh-CN": "上次运行成功",+ "zh-TW": "上次執行成功",+ "ko-KR": "마지막 실행 성공",+ "no": "Siste kjøring var vellykket",+ "it": "Ultima esecuzione riuscita",+ "pt": "Última execução bem-sucedida",+ "es": "Última ejecución exitosa",+ "ar": "نجح آخر تشغيل",+ "fr": "Dernière exécution réussie",+ "tr": "Son çalıştırma başarılı",+ "de": "Letzte Ausführung erfolgreich",+ "uk": "Останнє виконання успішне",+ "ca": "Última execució correcta"+ },+ "FEATURED_AUTOMATIONS$LAST_RUN_FAILED": {+ "en": "Last run failed",+ "ja": "最終実行は失敗しました",+ "zh-CN": "上次运行失败",+ "zh-TW": "上次執行失敗",+ "ko-KR": "마지막 실행 실패",+ "no": "Siste kjøring mislyktes",+ "it": "Ultima esecuzione fallita",+ "pt": "Última execução falhou",+ "es": "Última ejecución fallida",+ "ar": "فشل آخر تشغيل",+ "fr": "Dernière exécution échouée",+ "tr": "Son çalıştırma başarısız",+ "de": "Letzte Ausführung fehlgeschlagen",+ "uk": "Останнє виконання не вдалося",+ "ca": "L'última execució ha fallat"+ },+ "FEATURED_AUTOMATIONS$RUN_IN_PROGRESS": {+ "en": "Run in progress",+ "ja": "実行中",+ "zh-CN": "运行中",+ "zh-TW": "執行中",+ "ko-KR": "실행 진행 중",+ "no": "Kjøring pågår",+ "it": "Esecuzione in corso",+ "pt": "Execução em andamento",+ "es": "Ejecución en curso",+ "ar": "التشغيل قيد التقدم",+ "fr": "Exécution en cours",+ "tr": "Çalıştırma devam ediyor",+ "de": "Ausführung läuft",+ "uk": "Виконання триває",+ "ca": "Execució en curs"+ },+ "FEATURED_AUTOMATIONS$STATUS_UNKNOWN": {+ "en": "Latest run status unknown",+ "ja": "最新の実行状態は不明です",+ "zh-CN": "最近运行状态未知",+ "zh-TW": "最近執行狀態未知",+ "ko-KR": "최근 실행 상태 알 수 없음",+ "no": "Status for siste kjøring er ukjent",+ "it": "Stato dell'ultima esecuzione sconosciuto",+ "pt": "Status da última execução desconhecido",+ "es": "Estado de la última ejecución desconocido",+ "ar": "حالة آخر تشغيل غير معروفة",+ "fr": "Statut de la dernière exécution inconnu",+ "tr": "Son çalıştırma durumu bilinmiyor",+ "de": "Status der letzten Ausführung unbekannt",+ "uk": "Статус останнього виконання невідомий",+ "ca": "Estat de l'última execució desconegut"+ },+ "FEATURED_AUTOMATIONS$STATUS_UNAVAILABLE": {+ "en": "Status unavailable",+ "ja": "ステータスを取得できません",+ "zh-CN": "状态不可用",+ "zh-TW": "狀態無法使用",+ "ko-KR": "상태를 사용할 수 없음",+ "no": "Status utilgjengelig",+ "it": "Stato non disponibile",+ "pt": "Status indisponível",+ "es": "Estado no disponible",+ "ar": "الحالة غير متاحة",+ "fr": "Statut indisponible",+ "tr": "Durum kullanılamıyor",+ "de": "Status nicht verfügbar",+ "uk": "Статус недоступний",+ "ca": "Estat no disponible"+ },+ "FEATURED_AUTOMATIONS$TOASTER_TITLE": {+ "en": "Automate repetitive work",+ "ja": "繰り返し作業を自動化",+ "zh-CN": "自动化重复工作",+ "zh-TW": "自動化重複工作",+ "ko-KR": "반복 작업 자동화",+ "no": "Automate repetitive work",+ "it": "Automatizza il lavoro ripetitivo",+ "pt": "Automatize o trabalho repetitivo",+ "es": "Automatiza el trabajo repetitivo",+ "ar": "Automate repetitive work",+ "fr": "Automatisez le travail répétitif",+ "tr": "Automate repetitive work",+ "de": "Wiederkehrende Arbeit automatisieren",+ "uk": "Automate repetitive work",+ "ca": "Automate repetitive work"+ },+ "FEATURED_AUTOMATIONS$TOASTER_MESSAGE": {+ "en": "Set up automations to run on a schedule or when events happen.",+ "ja": "スケジュールやイベント発生時に実行されるオートメーションを設定しましょう。",+ "zh-CN": "设置按计划或在事件发生时运行的自动化。",+ "zh-TW": "設定依排程或事件觸發的自動化。",+ "ko-KR": "일정에 따라 또는 이벤트가 발생할 때 실행되는 자동화를 설정하세요.",+ "no": "Set up automations to run on a schedule or when events happen.",+ "it": "Configura automazioni da eseguire in base a una pianificazione o quando si verificano eventi.",+ "pt": "Configure automações para rodar em uma agenda ou quando eventos acontecerem.",+ "es": "Configura automatizaciones que se ejecuten según un horario o cuando ocurran eventos.",+ "ar": "Set up automations to run on a schedule or when events happen.",+ "fr": "Configurez des automatisations planifiées ou déclenchées par des événements.",+ "tr": "Set up automations to run on a schedule or when events happen.",+ "de": "Richten Sie Automatisierungen ein, die nach Zeitplan oder bei Ereignissen laufen.",+ "uk": "Set up automations to run on a schedule or when events happen.",+ "ca": "Set up automations to run on a schedule or when events happen."+ },+ "FEATURED_AUTOMATIONS$TOASTER_START": {+ "en": "Start",+ "ja": "開始",+ "zh-CN": "开始",+ "zh-TW": "開始",+ "ko-KR": "시작",+ "no": "Start",+ "it": "Inizia",+ "pt": "Começar",+ "es": "Empezar",+ "ar": "ابدأ",+ "fr": "Commencer",+ "tr": "Başla",+ "de": "Starten",+ "uk": "Почати",+ "ca": "Comença"+ },+ "FEATURED_AUTOMATIONS$TOASTER_DISMISS": {+ "en": "Dismiss",+ "ja": "閉じる",+ "zh-CN": "关闭",+ "zh-TW": "關閉",+ "ko-KR": "닫기",+ "no": "Lukk",+ "it": "Chiudi",+ "pt": "Dispensar",+ "es": "Descartar",+ "ar": "تجاهل",+ "fr": "Fermer",+ "tr": "Kapat",+ "de": "Schließen",+ "uk": "Закрити",+ "ca": "Descarta"+ },+ "FEATURED_AUTOMATIONS$SUGGESTED_TITLE": {+ "en": "Suggested automations",+ "ja": "おすすめのオートメーション",+ "zh-CN": "推荐的自动化",+ "zh-TW": "建議的自動化",+ "ko-KR": "추천 자동화",+ "no": "Foreslåtte automatiseringer",+ "it": "Automazioni consigliate",+ "pt": "Automações sugeridas",+ "es": "Automatizaciones sugeridas",+ "ar": "الأتمتة المقترحة",+ "fr": "Automatisations suggérées",+ "tr": "Önerilen otomasyonlar",+ "de": "Vorgeschlagene Automatisierungen",+ "uk": "Запропоновані автоматизації",+ "ca": "Automatitzacions suggerides"+ },+ "FEATURED_AUTOMATIONS$RUNNING_TITLE": {+ "en": "Running",+ "ja": "実行中",+ "zh-CN": "运行中",+ "zh-TW": "執行中",+ "ko-KR": "실행 중",+ "no": "Kjører",+ "it": "In esecuzione",+ "pt": "Em execução",+ "es": "En ejecución",+ "ar": "قيد التشغيل",+ "fr": "En cours",+ "tr": "Çalışıyor",+ "de": "Läuft",+ "uk": "Виконується",+ "ca": "En execució"+ },+ "FEATURED_AUTOMATIONS$RUNNING_GROUP_LABEL": {+ "en": "Automations currently running",+ "ja": "現在実行中のオートメーション",+ "zh-CN": "当前正在运行的自动化",+ "zh-TW": "目前正在執行的自動化",+ "ko-KR": "현재 실행 중인 자동화",+ "no": "Automatiseringer som kjører nå",+ "it": "Automazioni attualmente in esecuzione",+ "pt": "Automações em execução",+ "es": "Automatizaciones en ejecución",+ "ar": "الأتمتة قيد التشغيل حالياً",+ "fr": "Automatisations en cours d’exécution",+ "tr": "Şu anda çalışan otomasyonlar",+ "de": "Derzeit laufende Automatisierungen",+ "uk": "Автоматизації, що зараз виконуються",+ "ca": "Automatitzacions en execució"+ },+ "FEATURED_AUTOMATIONS$RECENT_TITLE": {+ "en": "Recent Automation Activity",+ "ja": "最近のオートメーションアクティビティ",+ "zh-CN": "最近的自动化活动",+ "zh-TW": "最近的自動化活動",+ "ko-KR": "최근 자동화 활동",+ "no": "Nylig automatiseringsaktivitet",+ "it": "Attività recente delle automazioni",+ "pt": "Atividade recente de automação",+ "es": "Actividad reciente de automatización",+ "ar": "نشاط الأتمتة الأخير",+ "fr": "Activité récente des automatisations",+ "tr": "Son otomasyon etkinliği",+ "de": "Letzte Automatisierungsaktivität",+ "uk": "Недавня активність автоматизацій",+ "ca": "Activitat recent d’automatització"+ },+ "FEATURED_AUTOMATIONS$RECENT_GROUP_LABEL": {+ "en": "Running and recently finished automations",+ "ja": "実行中および最近完了したオートメーション",+ "zh-CN": "正在运行和最近完成的自动化",+ "zh-TW": "執行中與最近完成的自動化",+ "ko-KR": "실행 중 및 최근 완료된 자동화",+ "no": "Running and recently finished automations",+ "it": "Automazioni in esecuzione e terminate di recente",+ "pt": "Automações em execução e concluídas recentemente",+ "es": "Automatizaciones en ejecución y finalizadas recientemente",+ "ar": "Running and recently finished automations",+ "fr": "Automatisations en cours et récemment terminées",+ "tr": "Running and recently finished automations",+ "de": "Laufende und kürzlich beendete Automatisierungen",+ "uk": "Running and recently finished automations",+ "ca": "Running and recently finished automations"+ },+ "FEATURED_AUTOMATIONS$VIEW_ALL": {+ "en": "View All",+ "ja": "すべて表示",+ "zh-CN": "查看全部",+ "zh-TW": "查看全部",+ "ko-KR": "모두 보기",+ "no": "Vis alle",+ "it": "Vedi tutto",+ "pt": "Ver tudo",+ "es": "Ver todo",+ "ar": "عرض الكل",+ "fr": "Tout voir",+ "tr": "Tümünü gör",+ "de": "Alle anzeigen",+ "uk": "Переглянути всі",+ "ca": "Mostra-ho tot"+ },+ "FEATURED_AUTOMATIONS$RUN_ACTIVITY_LABEL": {+ "en": "{{count}} recent runs",+ "ja": "最近の実行 {{count}} 件",+ "zh-CN": "{{count}} 次最近运行",+ "zh-TW": "{{count}} 次最近執行",+ "ko-KR": "최근 실행 {{count}}건",+ "no": "{{count}} nylige kjøringer",+ "it": "{{count}} esecuzioni recenti",+ "pt": "{{count}} execuções recentes",+ "es": "{{count}} ejecuciones recientes",+ "ar": "{{count}} عمليات تشغيل حديثة",+ "fr": "{{count}} exécutions récentes",+ "tr": "{{count}} son çalıştırma",+ "de": "{{count}} letzte Ausführungen",+ "uk": "{{count}} недавніх запусків",+ "ca": "{{count}} execucions recents"+ },+ "FEATURED_AUTOMATIONS$RUN_DURATION": {+ "en": "Duration",+ "ja": "所要時間",+ "zh-CN": "时长",+ "zh-TW": "時長",+ "ko-KR": "소요 시간",+ "no": "Varighet",+ "it": "Durata",+ "pt": "Duração",+ "es": "Duración",+ "ar": "المدة",+ "fr": "Durée",+ "tr": "Süre",+ "de": "Dauer",+ "uk": "Тривалість",+ "ca": "Durada"+ },+ "FEATURED_AUTOMATIONS$RECOMMENDED_GROUP_LABEL": {+ "en": "Recommended automations",+ "ja": "おすすめのオートメーション",+ "zh-CN": "推荐的自动化",+ "zh-TW": "建議的自動化",+ "ko-KR": "추천 자동화",+ "no": "Recommended automations",+ "it": "Automazioni consigliate",+ "pt": "Automações recomendadas",+ "es": "Automatizaciones recomendadas",+ "ar": "Recommended automations",+ "fr": "Automatisations recommandées",+ "tr": "Recommended automations",+ "de": "Empfohlene Automatisierungen",+ "uk": "Recommended automations",+ "ca": "Recommended automations"+ },+ "FEATURED_AUTOMATIONS$RECOMMENDED_PR_REVIEW": {+ "en": "Review pull requests and post AI feedback",+ "ja": "プルリクエストをレビューしてAIフィードバックを投稿",+ "zh-CN": "审查拉取请求并发布 AI 反馈",+ "zh-TW": "審查拉取請求並發布 AI 回饋",+ "ko-KR": "PR을 검토하고 AI 피드백 게시",+ "no": "Review pull requests and post AI feedback",+ "it": "Rivedi le PR e pubblica feedback IA",+ "pt": "Revisar PRs e publicar feedback de IA",+ "es": "Revisar PRs y publicar feedback de IA",+ "ar": "Review pull requests and post AI feedback",+ "fr": "Relire les PR et publier un avis IA",+ "tr": "Review pull requests and post AI feedback",+ "de": "Pull Requests prüfen und KI-Feedback posten",+ "uk": "Review pull requests and post AI feedback",+ "ca": "Review pull requests and post AI feedback"+ },+ "FEATURED_AUTOMATIONS$RECOMMENDED_GITHUB_MENTIONS": {+ "en": "Reply to @OpenHands mentions on GitHub",+ "ja": "GitHubの@OpenHandsメンションに返信",+ "zh-CN": "回复 GitHub 上的 @OpenHands 提及",+ "zh-TW": "回覆 GitHub 上的 @OpenHands 提及",+ "ko-KR": "GitHub @OpenHands 멘션에 응답",+ "no": "Reply to @OpenHands mentions on GitHub",+ "it": "Rispondi alle menzioni @OpenHands su GitHub",+ "pt": "Responder a menções @OpenHands no GitHub",+ "es": "Responder a menciones @OpenHands en GitHub",+ "ar": "Reply to @OpenHands mentions on GitHub",+ "fr": "Répondre aux mentions @OpenHands sur GitHub",+ "tr": "Reply to @OpenHands mentions on GitHub",+ "de": "Auf @OpenHands-Erwähnungen auf GitHub antworten",+ "uk": "Reply to @OpenHands mentions on GitHub",+ "ca": "Reply to @OpenHands mentions on GitHub"+ },+ "FEATURED_AUTOMATIONS$RECOMMENDED_SLACK_STANDUP": {+ "en": "Turn Slack activity into a daily standup",+ "ja": "Slackの活動を日次スタンドアップにまとめる",+ "zh-CN": "将 Slack 活动整理成每日站会",+ "zh-TW": "將 Slack 活動整理成每日站會",+ "ko-KR": "Slack 활동을 일일 스탠드업으로 정리",+ "no": "Turn Slack activity into a daily standup",+ "it": "Trasforma l’attività Slack in uno standup quotidiano",+ "pt": "Transformar a atividade do Slack em um standup diário",+ "es": "Convertir la actividad de Slack en un standup diario",+ "ar": "Turn Slack activity into a daily standup",+ "fr": "Transformer l’activité Slack en standup quotidien",+ "tr": "Turn Slack activity into a daily standup",+ "de": "Slack-Aktivität in ein tägliches Standup verwandeln",+ "uk": "Turn Slack activity into a daily standup",+ "ca": "Turn Slack activity into a daily standup"+ },+ "FEATURED_AUTOMATIONS$RECOMMENDED_LINEAR_TRIAGE": {+ "en": "Triage new Linear issues as they arrive",+ "ja": "新しいLinear issueを到着時にトリアージ",+ "zh-CN": "在新 Linear 问题到达时进行分诊",+ "zh-TW": "在新 Linear 議題到達時進行分診",+ "ko-KR": "새 Linear 이슈가 오면 자동 분류",+ "no": "Triage new Linear issues as they arrive",+ "it": "Classifica i nuovi issue Linear appena arrivano",+ "pt": "Triar novos issues do Linear assim que chegam",+ "es": "Clasificar nuevos issues de Linear al llegar",+ "ar": "Triage new Linear issues as they arrive",+ "fr": "Trier les nouvelles issues Linear à leur arrivée",+ "tr": "Triage new Linear issues as they arrive",+ "de": "Neue Linear-Issues bei Eingang triagieren",+ "uk": "Triage new Linear issues as they arrive",+ "ca": "Triage new Linear issues as they arrive"+ },"CHAT_INTERFACE$LOADING_CONVERSATION": {"en": "Loading conversation","zh-CN": "正在加载会话",@@ -36004,5 +36480,243 @@"de": "owner/repo","uk": "owner/repo","ca": "owner/repo"+ },+ "FEATURED_AUTOMATIONS$PIN": {+ "en": "Pin to dashboard",+ "ja": "ダッシュボードにピン留め",+ "zh-CN": "固定到仪表盘",+ "zh-TW": "釘選到儀表板",+ "ko-KR": "대시보드에 고정",+ "no": "Pin to dashboard",+ "it": "Fissa nella dashboard",+ "pt": "Fixar no painel",+ "es": "Fijar en el panel",+ "ar": "Pin to dashboard",+ "fr": "Épingler au tableau de bord",+ "tr": "Pin to dashboard",+ "de": "Am Dashboard anheften",+ "uk": "Pin to dashboard",+ "ca": "Pin to dashboard"+ },+ "FEATURED_AUTOMATIONS$UNPIN": {+ "en": "Unpin from dashboard",+ "ja": "ダッシュボードからピン留め解除",+ "zh-CN": "从仪表盘取消固定",+ "zh-TW": "從儀表板取消釘選",+ "ko-KR": "대시보드에서 고정 해제",+ "no": "Unpin from dashboard",+ "it": "Rimuovi dalla dashboard",+ "pt": "Desafixar do painel",+ "es": "Quitar del panel",+ "ar": "Unpin from dashboard",+ "fr": "Désépingler du tableau de bord",+ "tr": "Unpin from dashboard",+ "de": "Vom Dashboard lösen",+ "uk": "Unpin from dashboard",+ "ca": "Unpin from dashboard"+ },+ "FEATURED_AUTOMATIONS$ROW_MENU_LABEL": {+ "en": "Actions for {{name}}",+ "ja": "{{name}}の操作",+ "zh-CN": "{{name}} 的操作",+ "zh-TW": "{{name}} 的操作",+ "ko-KR": "{{name}} 작업",+ "no": "Actions for {{name}}",+ "it": "Azioni per {{name}}",+ "pt": "Ações para {{name}}",+ "es": "Acciones para {{name}}",+ "ar": "Actions for {{name}}",+ "fr": "Actions pour {{name}}",+ "tr": "Actions for {{name}}",+ "de": "Aktionen für {{name}}",+ "uk": "Actions for {{name}}",+ "ca": "Actions for {{name}}"+ },+ "FEATURED_AUTOMATIONS$PINNED_TITLE": {+ "en": "Pinned automations",+ "ja": "ピン留めしたオートメーション",+ "zh-CN": "已固定的自动化",+ "zh-TW": "已釘選的自動化",+ "ko-KR": "고정된 자동화",+ "no": "Pinned automations",+ "it": "Automazioni fissate",+ "pt": "Automações fixadas",+ "es": "Automatizaciones fijadas",+ "ar": "Pinned automations",+ "fr": "Automatisations épinglées",+ "tr": "Pinned automations",+ "de": "Angeheftete Automatisierungen",+ "uk": "Pinned automations",+ "ca": "Pinned automations"+ },+ "FEATURED_AUTOMATIONS$PINNED_DASHBOARD_LABEL": {+ "en": "Pinned automation dashboard",+ "ja": "ピン留めオートメーションのダッシュボード",+ "zh-CN": "已固定自动化仪表盘",+ "zh-TW": "已釘選自動化儀表板",+ "ko-KR": "고정된 자동화 대시보드",+ "no": "Pinned automation dashboard",+ "it": "Dashboard delle automazioni fissate",+ "pt": "Painel de automações fixadas",+ "es": "Panel de automatizaciones fijadas",+ "ar": "Pinned automation dashboard",+ "fr": "Tableau de bord des automatisations épinglées",+ "tr": "Pinned automation dashboard",+ "de": "Dashboard angehefteter Automatisierungen",+ "uk": "Pinned automation dashboard",+ "ca": "Pinned automation dashboard"+ },+ "AUTOMATIONS$CANCEL_RUN": {+ "en": "Cancel run",+ "ja": "実行をキャンセル",+ "zh-CN": "取消运行",+ "zh-TW": "取消執行",+ "ko-KR": "실행 취소",+ "no": "Cancel run",+ "it": "Annulla esecuzione",+ "pt": "Cancelar execução",+ "es": "Cancelar ejecución",+ "ar": "Cancel run",+ "fr": "Annuler l'exécution",+ "tr": "Cancel run",+ "de": "Ausführung abbrechen",+ "uk": "Cancel run",+ "ca": "Cancel run"+ },+ "AUTOMATIONS$CANCEL_RUN_SUCCESS": {+ "en": "Automation run cancelled",+ "ja": "オートメーションの実行をキャンセルしました",+ "zh-CN": "已取消自动化运行",+ "zh-TW": "已取消自動化執行",+ "ko-KR": "자동화 실행이 취소되었습니다",+ "no": "Automatiseringskjøring avbrutt",+ "it": "Esecuzione dell'automazione annullata",+ "pt": "Execução da automação cancelada",+ "es": "Ejecución de la automatización cancelada",+ "ar": "تم إلغاء تشغيل الأتمتة",+ "fr": "Exécution de l'automatisation annulée",+ "tr": "Otomasyon çalıştırması iptal edildi",+ "de": "Automatisierungsausführung abgebrochen",+ "uk": "Запуск автоматизації скасовано",+ "ca": "Execució de l'automatització cancel·lada"+ },+ "AUTOMATIONS$CANCEL_RUN_ERROR": {+ "en": "Failed to cancel automation run",+ "ja": "オートメーションの実行をキャンセルできませんでした",+ "zh-CN": "取消自动化运行失败",+ "zh-TW": "取消自動化執行失敗",+ "ko-KR": "자동화 실행을 취소하지 못했습니다",+ "no": "Kunne ikke avbryte automatiseringskjøringen",+ "it": "Impossibile annullare l'esecuzione dell'automazione",+ "pt": "Falha ao cancelar a execução da automação",+ "es": "No se pudo cancelar la ejecución de la automatización",+ "ar": "فشل إلغاء تشغيل الأتمتة",+ "fr": "Échec de l'annulation de l'exécution de l'automatisation",+ "tr": "Otomasyon çalıştırması iptal edilemedi",+ "de": "Automatisierungsausführung konnte nicht abgebrochen werden",+ "uk": "Не вдалося скасувати запуск автоматизації",+ "ca": "No s'ha pogut cancel·lar l'execució de l'automatització"+ },+ "AUTOMATIONS$TURN_OFF_CONFIRM_TITLE": {+ "en": "Turn off automation",+ "ja": "オートメーションをオフにする",+ "zh-CN": "关闭自动化",+ "zh-TW": "關閉自動化",+ "ko-KR": "Turn off automation",+ "no": "Turn off automation",+ "it": "Turn off automation",+ "pt": "Turn off automation",+ "es": "Desactivar automatización",+ "ar": "Turn off automation",+ "fr": "Désactiver l'automatisation",+ "tr": "Turn off automation",+ "de": "Automatisierung ausschalten",+ "uk": "Turn off automation",+ "ca": "Turn off automation"+ },+ "AUTOMATIONS$TURN_OFF_CONFIRM_MESSAGE": {+ "en": "Turn off \"{{name}}\"? It will stop running on its schedule until you turn it back on.",+ "ja": "「{{name}}」をオフにしますか?再度オンにするまで、スケジュールでの実行は停止します。",+ "zh-CN": "关闭“{{name}}”?在重新开启之前,它将不再按计划运行。",+ "zh-TW": "關閉「{{name}}」?在重新開啟之前,它將不再依排程執行。",+ "ko-KR": "\"{{name}}\"을(를) 끌까요? 다시 켤 때까지 예약된 실행이 중지됩니다.",+ "no": "Slå av \"{{name}}\"? Den slutter å kjøre etter planen til du slår den på igjen.",+ "it": "Disattivare \"{{name}}\"? Interromperà l'esecuzione pianificata finché non la riattivi.",+ "pt": "Desativar \"{{name}}\"? Ela deixará de ser executada conforme o agendamento até você reativá-la.",+ "es": "¿Desactivar \"{{name}}\"? Dejará de ejecutarse según su programación hasta que la vuelvas a activar.",+ "ar": "إيقاف \"{{name}}\"؟ سيتوقف عن التشغيل وفق جدولته حتى تعيد تشغيله.",+ "fr": "Désactiver « {{name}} » ? Elle cessera de s'exécuter selon son planning jusqu'à ce que vous la réactiviez.",+ "tr": "\"{{name}}\" kapatılsın mı? Yeniden açana kadar zamanlamasına göre çalışmayı durdurur.",+ "de": "\"{{name}}\" ausschalten? Sie wird nicht mehr nach Zeitplan ausgeführt, bis Sie sie wieder einschalten.",+ "uk": "Вимкнути «{{name}}»? Вона припинить запускатися за розкладом, доки ви знову її не увімкнете.",+ "ca": "Vols desactivar \"{{name}}\"? Deixarà d'executar-se segons la planificació fins que la tornis a activar."+ },+ "AUTOMATIONS$TURN_OFF_ERROR": {+ "en": "Failed to turn off automation",+ "ja": "オートメーションをオフにできませんでした",+ "zh-CN": "关闭自动化失败",+ "zh-TW": "關閉自動化失敗",+ "ko-KR": "자동화를 끄지 못했습니다",+ "no": "Kunne ikke slå av automatiseringen",+ "it": "Impossibile disattivare l'automazione",+ "pt": "Falha ao desativar a automação",+ "es": "No se pudo desactivar la automatización",+ "ar": "فشل إيقاف الأتمتة",+ "fr": "Échec de la désactivation de l'automatisation",+ "tr": "Otomasyon kapatılamadı",+ "de": "Automatisierung konnte nicht ausgeschaltet werden",+ "uk": "Не вдалося вимкнути автоматизацію",+ "ca": "No s'ha pogut desactivar l'automatització"+ },+ "FEATURED_AUTOMATIONS$MOVE_UP": {+ "en": "Move up",+ "ja": "上に移動",+ "zh-CN": "上移",+ "zh-TW": "上移",+ "ko-KR": "Move up",+ "no": "Move up",+ "it": "Move up",+ "pt": "Move up",+ "es": "Subir",+ "ar": "Move up",+ "fr": "Monter",+ "tr": "Move up",+ "de": "Nach oben",+ "uk": "Move up",+ "ca": "Move up"+ },+ "FEATURED_AUTOMATIONS$MOVE_DOWN": {+ "en": "Move down",+ "ja": "下に移動",+ "zh-CN": "下移",+ "zh-TW": "下移",+ "ko-KR": "Move down",+ "no": "Move down",+ "it": "Move down",+ "pt": "Move down",+ "es": "Bajar",+ "ar": "Move down",+ "fr": "Descendre",+ "tr": "Move down",+ "de": "Nach unten",+ "uk": "Move down",+ "ca": "Move down"+ },+ "FEATURED_AUTOMATIONS$REORDER_HANDLE": {+ "en": "Reorder {{name}}",+ "ja": "{{name}}を並べ替え",+ "zh-CN": "重新排序 {{name}}",+ "zh-TW": "重新排序 {{name}}",+ "ko-KR": "{{name}} 순서 변경",+ "no": "Omorganiser {{name}}",+ "it": "Riordina {{name}}",+ "pt": "Reordenar {{name}}",+ "es": "Reordenar {{name}}",+ "ar": "إعادة ترتيب {{name}}",+ "fr": "Réorganiser {{name}}",+ "tr": "{{name}} sırasını değiştir",+ "de": "{{name}} neu anordnen",+ "uk": "Змінити порядок {{name}}",+ "ca": "Reordenar {{name}}"}}diff --git a/src/routes/automation-detail.tsx b/src/routes/automation-detail.tsxindex da820d5cb5..12c478e46b 100644--- a/src/routes/automation-detail.tsx+++ b/src/routes/automation-detail.tsx@@ -1,5 +1,5 @@import { useRef, useState } from "react";-import { useParams } from "react-router";+import { useParams, useSearchParams } from "react-router";import { useTranslation } from "react-i18next";import { I18nKey } from "#/i18n/declaration";import {@@ -42,6 +42,8 @@ import { downloadBlob } from "#/utils/utils";export default function AutomationDetail() {const { t } = useTranslation("openhands");const { automationId } = useParams();+ const [searchParams] = useSearchParams();+ const highlightedRunId = searchParams.get("run");const { navigate } = useNavigation();const [showDeleteModal, setShowDeleteModal] = useState(false);const [showEditModal, setShowEditModal] = useState(false);@@ -206,7 +208,10 @@ export default function AutomationDetail() {createdAt={automation.created_at}lastRunAt={automation.last_triggered_at}/>- <ActivityLogSection automation={automation} />+ <ActivityLogSection+ automation={automation}+ highlightedRunId={highlightedRunId}+ /><DeleteConfirmationModalautomationName={automation.name}isOpen={showDeleteModal}diff --git a/src/routes/home.tsx b/src/routes/home.tsxindex 4cdb0862c1..c524aa4d7f 100644--- a/src/routes/home.tsx+++ b/src/routes/home.tsx@@ -15,15 +15,13 @@ function HomeScreen() {return (<divdata-testid="home-screen"- className="custom-scrollbar-always flex h-full flex-col overflow-y-auto rounded-xl bg-transparent px-4 md:px-0 lg:px-[42px]"+ className="custom-scrollbar-always h-full overflow-y-auto rounded-xl bg-transparent px-4 md:px-0 lg:px-[42px]"><div className="md:px-4 lg:px-0"><LlmNotConfiguredBanner /></div>- <div className="flex flex-1 min-h-0 flex-col items-center justify-center">- <HomeChatLauncher />- </div>+ <HomeChatLauncher />{!isPreview ? <OnboardingHost /> : null}</div>diff --git a/src/ui/context-menu.tsx b/src/ui/context-menu.tsxindex 4b24a8f99f..3825e337db 100644--- a/src/ui/context-menu.tsx+++ b/src/ui/context-menu.tsx@@ -58,6 +58,7 @@ interface ContextMenuProps {children: React.ReactNode;className?: React.HTMLAttributes<HTMLUListElement>["className"];style?: React.CSSProperties;+ onKeyDown?: React.KeyboardEventHandler<HTMLUListElement>;theme?: VariantProps<typeof contextMenuVariants>["theme"];size?: VariantProps<typeof contextMenuVariants>["size"];layout?: VariantProps<typeof contextMenuVariants>["layout"];@@ -71,6 +72,7 @@ export function ContextMenu({children,className,style,+ onKeyDown,ref,theme,size,@@ -80,11 +82,14 @@ export function ContextMenu({alignment,}: ContextMenuProps) {return (+ // Keyboard navigation is opt-in via `onKeyDown` (home automation kebab).+ // eslint-disable-next-line jsx-a11y/no-noninteractive-element-interactions -- popup list hosts Escape/arrow handlers when provided<uldata-testid={testId}data-position={position}ref={ref}style={style}+ onKeyDown={onKeyDown}className={cn(contextMenuVariants({theme,diff --git a/src/utils/format-relative-time.ts b/src/utils/format-relative-time.tsnew file mode 100644index 0000000000..960978381a--- /dev/null+++ b/src/utils/format-relative-time.ts@@ -0,0 +1,33 @@+import { I18nKey } from "#/i18n/declaration";++export function formatDate(dateStr: string, locale: string): string {+ const date = new Date(dateStr);+ return date.toLocaleDateString(locale, {+ year: "numeric",+ month: "short",+ day: "numeric",+ });+}++export function formatRelativeTime(+ dateStr: string,+ locale: string,+ t: (key: I18nKey, options?: Record<string, unknown>) => string,+): string {+ const now = Date.now();+ const then = new Date(dateStr).getTime();+ const diffMs = now - then;+ const diffMins = Math.floor(diffMs / 60_000);+ const diffHours = Math.floor(diffMs / 3_600_000);+ const diffDays = Math.floor(diffMs / 86_400_000);++ if (diffMins < 1) return t(I18nKey.AUTOMATIONS$DETAIL$TIME_JUST_NOW);+ if (diffMins < 60)+ return t(I18nKey.AUTOMATIONS$DETAIL$TIME_MINUTES_AGO, { count: diffMins });+ if (diffHours < 24)+ return t(I18nKey.AUTOMATIONS$DETAIL$TIME_HOURS_AGO, { count: diffHours });+ if (diffDays === 1) return t(I18nKey.AUTOMATIONS$DETAIL$TIME_YESTERDAY);+ if (diffDays < 7)+ return t(I18nKey.AUTOMATIONS$DETAIL$TIME_DAYS_AGO, { count: diffDays });+ return formatDate(dateStr, locale);+}