🙌 OpenHands: AI-Driven Development
feat(automations): add logs modal to activity log items (#600)
Tim O'Farrell048e3904199b
diff --git a/__tests__/api/bash-service.test.ts b/__tests__/api/bash-service.test.tsnew file mode 100644index 0000000000..98a89ee827--- /dev/null+++ b/__tests__/api/bash-service.test.ts@@ -0,0 +1,175 @@+import { BashClient } from "@openhands/typescript-client/clients";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ __resetActiveStoreForTests,+ setActiveSelection,+ setRegisteredBackends,+} from "#/api/backend-registry/active-store";+import BashService from "#/api/bash-service/bash-service.api";+import { callCloudProxy } from "#/api/cloud/proxy";+import type { Backend } from "#/api/backend-registry/types";++const { searchEventsMock } = vi.hoisted(() => ({+ searchEventsMock: vi.fn(),+}));++vi.mock("@openhands/typescript-client/clients", () => ({+ BashClient: vi.fn(function BashClientMock() {+ return { searchEvents: searchEventsMock };+ }),+}));++vi.mock("#/api/agent-server-client-options", () => ({+ getAgentServerClientOptions: vi.fn(() => ({+ host: "http://local-agent.example.com",+ apiKey: "local-key",+ workingDir: "/workspace/project",+ })),+}));++vi.mock("#/api/cloud/proxy", () => ({+ callCloudProxy: vi.fn(),+}));++const localBackend: Backend = {+ id: "local-1",+ name: "Local 1",+ host: "http://local-agent.example.com",+ apiKey: "local-key",+ kind: "local",+};++const cloudBackend: Backend = {+ id: "cloud-1",+ name: "Production",+ host: "https://app.all-hands.dev",+ apiKey: "cloud-api-key",+ kind: "cloud",+};++const CONVERSATION_URL = "https://runtime.example.com/api/conversations/conv-1";+const SESSION_KEY = "session-key-abc";+const BASH_CMD_ID = "cmd-123";++const OUTPUT_1 = {+ id: "out-1",+ timestamp: "2026-01-01T10:00:00.100Z",+ kind: "BashOutput",+ command_id: BASH_CMD_ID,+ order: 0,+ stdout: "hello\n",+ stderr: null,+ exit_code: null,+};++const OUTPUT_2 = {+ id: "out-2",+ timestamp: "2026-01-01T10:00:00.200Z",+ kind: "BashOutput",+ command_id: BASH_CMD_ID,+ order: 1,+ stdout: null,+ stderr: "boom\n",+ exit_code: 1,+};++beforeEach(() => {+ window.localStorage.clear();+ __resetActiveStoreForTests();+ vi.mocked(BashClient).mockClear();+ searchEventsMock.mockReset();+ vi.mocked(callCloudProxy).mockReset();+});++afterEach(() => {+ window.localStorage.clear();+ __resetActiveStoreForTests();+});++describe("BashService.listOutputs — local backend", () => {+ beforeEach(() => {+ setRegisteredBackends([localBackend]);+ setActiveSelection({ backendId: localBackend.id, orgId: null });+ });++ it("pages BashOutput events via BashClient with command_id__eq filter", async () => {+ searchEventsMock+ .mockResolvedValueOnce({+ items: [OUTPUT_1],+ next_page_id: "next",+ })+ .mockResolvedValueOnce({ items: [OUTPUT_2] });++ const outputs = await BashService.listOutputs(+ CONVERSATION_URL,+ SESSION_KEY,+ BASH_CMD_ID,+ );++ expect(BashClient).toHaveBeenCalled();+ expect(searchEventsMock).toHaveBeenCalledTimes(2);+ expect(searchEventsMock.mock.calls[0][0]).toMatchObject({+ kind__eq: "BashOutput",+ command_id__eq: BASH_CMD_ID,+ sort_order: "TIMESTAMP",+ });+ expect(searchEventsMock.mock.calls[1][0]).toMatchObject({+ page_id: "next",+ });+ expect(callCloudProxy).not.toHaveBeenCalled();+ expect(outputs).toEqual([OUTPUT_1, OUTPUT_2]);+ });++ it("works without a conversation URL (falls back to backend host)", async () => {+ searchEventsMock.mockResolvedValueOnce({ items: [OUTPUT_1] });++ const outputs = await BashService.listOutputs(null, null, BASH_CMD_ID);++ expect(BashClient).toHaveBeenCalled();+ expect(callCloudProxy).not.toHaveBeenCalled();+ expect(outputs).toEqual([OUTPUT_1]);+ });+});++describe("BashService.listOutputs — cloud backend", () => {+ beforeEach(() => {+ setRegisteredBackends([cloudBackend]);+ setActiveSelection({ backendId: cloudBackend.id, orgId: null });+ });++ it("routes through callCloudProxy with hostOverride and session-api-key", async () => {+ vi.mocked(callCloudProxy).mockResolvedValueOnce({+ items: [OUTPUT_1, OUTPUT_2],+ });++ const outputs = await BashService.listOutputs(+ CONVERSATION_URL,+ SESSION_KEY,+ BASH_CMD_ID,+ );++ expect(BashClient).not.toHaveBeenCalled();+ const proxyCall = vi.mocked(callCloudProxy).mock.calls[0][0];+ expect(proxyCall.method).toBe("GET");+ expect(proxyCall.path).toMatch(/^\/api\/bash\/bash_events\/search\?/);+ expect(proxyCall.hostOverride).toBe("http://runtime.example.com");+ expect(proxyCall.authMode).toBe("session-api-key");+ expect(proxyCall.sessionApiKey).toBe(SESSION_KEY);++ const searchUrl = new URL(+ `http://x.example.com${proxyCall.path as string}`,+ );+ expect(searchUrl.searchParams.get("kind__eq")).toBe("BashOutput");+ expect(searchUrl.searchParams.get("command_id__eq")).toBe(BASH_CMD_ID);+ expect(searchUrl.searchParams.get("sort_order")).toBe("TIMESTAMP");++ expect(outputs).toEqual([OUTPUT_1, OUTPUT_2]);+ });++ it("throws when no conversation URL is provided on cloud backends", async () => {+ await expect(+ BashService.listOutputs(null, SESSION_KEY, BASH_CMD_ID),+ ).rejects.toThrow(/requires a conversation URL/);+ expect(callCloudProxy).not.toHaveBeenCalled();+ });+});diff --git a/__tests__/components/automations/detail/activity-log-item.test.tsx b/__tests__/components/automations/detail/activity-log-item.test.tsxnew file mode 100644index 0000000000..7bfcf17609--- /dev/null+++ b/__tests__/components/automations/detail/activity-log-item.test.tsx@@ -0,0 +1,136 @@+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { render, screen, fireEvent } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { MemoryRouter } from "react-router";++import { ActivityLogItem } from "#/components/features/automations/detail/activity-log-item";+import {+ AutomationRunStatus,+ type AutomationRun,+} from "#/types/automation";+import {+ __resetActiveStoreForTests,+ setActiveSelection,+ setRegisteredBackends,+} from "#/api/backend-registry/active-store";+import { ActiveBackendProvider } from "#/contexts/active-backend-context";+import type { Backend } from "#/api/backend-registry/types";+import { I18nKey } from "#/i18n/declaration";++// In tests the i18n backend doesn't resolve translation values, so the+// aria-label resolves to the raw key string. Match it explicitly.+const LOGS_BUTTON_NAME = (name: string) =>+ name.includes(I18nKey.AUTOMATIONS$DETAIL$LOGS_VIEW);++// The modal is wired to react-query + the conversation lookup. The+// ActivityLogItem tests focus on the trigger button; we mock the modal so+// they don't need to bring up the entire query stack.+vi.mock(+ "#/components/features/automations/detail/run-logs-modal",+ () => ({+ RunLogsModal: ({+ isOpen,+ onClose,+ bashCommandId,+ }: {+ isOpen: boolean;+ onClose: () => void;+ bashCommandId: string | null;+ }) =>+ isOpen ? (+ <div data-testid="logs-modal" data-bash-command-id={bashCommandId}>+ <button type="button" onClick={onClose}>+ close+ </button>+ </div>+ ) : null,+ }),+);++const localBackend: Backend = {+ id: "local-1",+ name: "Local 1",+ host: "http://localhost:8000",+ apiKey: "k",+ kind: "local",+};++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-01-01T10:00:00Z",+ completed_at: "2026-01-01T10:02:00Z",+ ...overrides,+ };+}++function renderItem(run: AutomationRun) {+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return render(+ <QueryClientProvider client={queryClient}>+ <ActiveBackendProvider>+ <MemoryRouter>+ <ActivityLogItem run={run} />+ </MemoryRouter>+ </ActiveBackendProvider>+ </QueryClientProvider>,+ );+}++describe("ActivityLogItem — logs button", () => {+ beforeEach(() => {+ __resetActiveStoreForTests();+ setRegisteredBackends([localBackend]);+ setActiveSelection({ backendId: localBackend.id });+ });++ afterEach(() => {+ __resetActiveStoreForTests();+ });++ it("renders a logs button when the run has a bash_command_id", () => {+ renderItem(makeRun());+ // Use the short tooltip label to find the button.+ expect(+ screen.getByRole("button", { name: LOGS_BUTTON_NAME }),+ ).toBeInTheDocument();+ });++ it("does not render a logs button when bash_command_id is null", () => {+ renderItem(makeRun({ bash_command_id: null }));+ expect(+ screen.queryByRole("button", { name: LOGS_BUTTON_NAME }),+ ).not.toBeInTheDocument();+ });++ it("opens the logs modal when the button is clicked and passes the bash_command_id through", () => {+ renderItem(makeRun({ bash_command_id: "cmd-xyz" }));++ expect(screen.queryByTestId("logs-modal")).not.toBeInTheDocument();++ fireEvent.click(screen.getByRole("button", { name: LOGS_BUTTON_NAME }));++ const modal = screen.getByTestId("logs-modal");+ expect(modal).toBeInTheDocument();+ expect(modal.getAttribute("data-bash-command-id")).toBe("cmd-xyz");+ });++ it("renders the logs button inside the row link without breaking its href", () => {+ renderItem(makeRun({ conversation_id: "conv-abc" }));++ const link = screen.getByRole("link") as HTMLAnchorElement;+ expect(link.getAttribute("href")).toBe("/conversations/conv-abc");+ // The button lives inside the link, so the click handler must+ // preventDefault + stopPropagation (implementation contract verified+ // by the modal-opens test above) to avoid following the link.+ expect(+ link.contains(screen.getByRole("button", { name: LOGS_BUTTON_NAME })),+ ).toBe(true);+ });+});diff --git a/__tests__/components/automations/detail/run-logs-modal.test.tsx b/__tests__/components/automations/detail/run-logs-modal.test.tsxnew file mode 100644index 0000000000..5b30f3dc7c--- /dev/null+++ b/__tests__/components/automations/detail/run-logs-modal.test.tsx@@ -0,0 +1,276 @@+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";+import { render, screen, fireEvent } from "@testing-library/react";+import { I18nKey } from "#/i18n/declaration";+import { RunLogsModal } from "#/components/features/automations/detail/run-logs-modal";++const { useBashCommandLogsMock } = vi.hoisted(() => ({+ useBashCommandLogsMock: vi.fn(),+}));++vi.mock("#/hooks/query/use-bash-command-logs", () => ({+ useBashCommandLogs: useBashCommandLogsMock,+}));++function makeHookResult(+ overrides: Partial<ReturnType<typeof baseResult>> = {},+) {+ return { ...baseResult(), ...overrides };+}++function baseResult() {+ return {+ data: undefined as unknown,+ error: null as Error | null,+ isFetching: false,+ isPending: false,+ isResolvingConversation: false,+ sandboxIssue: null as+ | null+ | "missing"+ | "paused"+ | "starting"+ | "errored"+ | "unreachable",+ conversationMissing: false,+ };+}++beforeEach(() => {+ useBashCommandLogsMock.mockReset();+});++afterEach(() => {+ vi.clearAllMocks();+});++describe("RunLogsModal", () => {+ it("renders nothing when closed", () => {+ useBashCommandLogsMock.mockReturnValue(makeHookResult());+ const { container } = render(+ <RunLogsModal+ isOpen={false}+ conversationId="conv-1"+ bashCommandId="cmd-1"+ onClose={() => {}}+ />,+ );+ expect(container).toBeEmptyDOMElement();+ });++ it("uses the 'Logs' title (not 'Run logs')", () => {+ useBashCommandLogsMock.mockReturnValue(makeHookResult());+ render(+ <RunLogsModal+ isOpen+ conversationId="conv-1"+ bashCommandId="cmd-1"+ onClose={() => {}}+ />,+ );+ // The heading uses the LOGS_TITLE key — in the test environment+ // the resolved value IS "Logs" because translation.json's "en"+ // entry is "Logs". (The key itself is rendered if the runtime+ // can't resolve it; we want the human label.)+ expect(+ screen.getByRole("heading", {+ name: I18nKey.AUTOMATIONS$DETAIL$LOGS_TITLE,+ }),+ ).toBeInTheDocument();+ });++ it("shows two tabs (Output, Error) with Output active by default", () => {+ useBashCommandLogsMock.mockReturnValue(+ makeHookResult({+ data: [+ {+ id: "o1",+ kind: "BashOutput",+ timestamp: "2026-01-01T10:00:00Z",+ command_id: "cmd-1",+ order: 0,+ stdout: "hello",+ stderr: null,+ },+ ],+ }),+ );+ render(+ <RunLogsModal+ isOpen+ conversationId="conv-1"+ bashCommandId="cmd-1"+ onClose={() => {}}+ />,+ );++ const tabs = screen.getAllByRole("tab");+ expect(tabs).toHaveLength(2);+ expect(tabs[0]).toHaveAttribute("aria-selected", "true");+ expect(tabs[1]).toHaveAttribute("aria-selected", "false");+ });++ it("concatenates stdout across multiple BashOutput events for the Output tab", () => {+ useBashCommandLogsMock.mockReturnValue(+ makeHookResult({+ data: [+ {+ id: "o2",+ kind: "BashOutput",+ timestamp: "2026-01-01T10:00:00.200Z",+ command_id: "cmd-1",+ order: 1,+ stdout: "world\n",+ stderr: null,+ },+ {+ id: "o1",+ kind: "BashOutput",+ timestamp: "2026-01-01T10:00:00.100Z",+ command_id: "cmd-1",+ order: 0,+ stdout: "hello ",+ stderr: null,+ },+ ],+ }),+ );+ render(+ <RunLogsModal+ isOpen+ conversationId="conv-1"+ bashCommandId="cmd-1"+ onClose={() => {}}+ />,+ );+ // Outputs must be sorted by (timestamp, order), so the+ // chronological concatenation is "hello world\n" — proves the+ // sort is happening regardless of input order.+ expect(screen.getByTestId("run-logs-output-stdout")).toHaveTextContent(+ "hello world",+ );+ });++ it("concatenates stderr when the Error tab is selected", () => {+ useBashCommandLogsMock.mockReturnValue(+ makeHookResult({+ data: [+ {+ id: "o1",+ kind: "BashOutput",+ timestamp: "2026-01-01T10:00:00.100Z",+ command_id: "cmd-1",+ order: 0,+ stdout: "ok\n",+ stderr: "err-1\n",+ },+ {+ id: "o2",+ kind: "BashOutput",+ timestamp: "2026-01-01T10:00:00.200Z",+ command_id: "cmd-1",+ order: 1,+ stdout: null,+ stderr: "err-2\n",+ },+ ],+ }),+ );+ render(+ <RunLogsModal+ isOpen+ conversationId="conv-1"+ bashCommandId="cmd-1"+ onClose={() => {}}+ />,+ );++ const errorTab = screen.getAllByRole("tab")[1];+ fireEvent.click(errorTab);++ expect(errorTab).toHaveAttribute("aria-selected", "true");+ expect(screen.getByTestId("run-logs-output-stderr")).toHaveTextContent(+ "err-1 err-2",+ );+ });++ it("shows the loading message while the query is fetching", () => {+ useBashCommandLogsMock.mockReturnValue(+ makeHookResult({ isFetching: true, data: undefined }),+ );+ render(+ <RunLogsModal+ isOpen+ conversationId="conv-1"+ bashCommandId="cmd-1"+ onClose={() => {}}+ />,+ );+ expect(+ screen.getByText(I18nKey.AUTOMATIONS$DETAIL$LOGS_LOADING),+ ).toBeInTheDocument();+ });++ it.each([+ ["missing", I18nKey.AUTOMATIONS$DETAIL$LOGS_SANDBOX_MISSING],+ ["paused", I18nKey.AUTOMATIONS$DETAIL$LOGS_SANDBOX_PAUSED],+ ["starting", I18nKey.AUTOMATIONS$DETAIL$LOGS_SANDBOX_STARTING],+ ["errored", I18nKey.AUTOMATIONS$DETAIL$LOGS_SANDBOX_ERROR],+ ["unreachable", I18nKey.AUTOMATIONS$DETAIL$LOGS_SANDBOX_UNREACHABLE],+ ] as const)(+ "renders the matching message for sandboxIssue=%s instead of the log output",+ (issue, key) => {+ useBashCommandLogsMock.mockReturnValue(+ makeHookResult({+ sandboxIssue: issue,+ // Even if outputs are somehow present in the cache, the+ // sandbox-issue branch should still render — the issue+ // takes precedence.+ data: [+ {+ id: "o1",+ kind: "BashOutput",+ timestamp: "2026-01-01T10:00:00Z",+ command_id: "cmd-1",+ order: 0,+ stdout: "stale",+ stderr: null,+ },+ ],+ }),+ );+ render(+ <RunLogsModal+ isOpen+ conversationId="conv-1"+ bashCommandId="cmd-1"+ onClose={() => {}}+ />,+ );++ expect(+ screen.getByTestId(`run-logs-sandbox-issue-${issue}`),+ ).toHaveTextContent(key);+ // The stdout tab should not be rendered when a sandbox issue+ // is set — we don't want stale "Output" content competing with+ // the empty-state message.+ expect(+ screen.queryByTestId("run-logs-output-stdout"),+ ).not.toBeInTheDocument();+ },+ );++ it("invokes onClose when Escape is pressed", () => {+ useBashCommandLogsMock.mockReturnValue(makeHookResult());+ const onClose = vi.fn();+ render(+ <RunLogsModal+ isOpen+ conversationId="conv-1"+ bashCommandId="cmd-1"+ onClose={onClose}+ />,+ );+ fireEvent.keyDown(window, { key: "Escape" });+ expect(onClose).toHaveBeenCalledTimes(1);+ });+});diff --git a/__tests__/hooks/query/use-bash-command-logs.test.tsx b/__tests__/hooks/query/use-bash-command-logs.test.tsxnew file mode 100644index 0000000000..4e4edb278a--- /dev/null+++ b/__tests__/hooks/query/use-bash-command-logs.test.tsx@@ -0,0 +1,293 @@+/**+ * Tests the error-tolerance logic in useBashCommandLogs.+ *+ * Cloud sandboxes can be paused, starting, errored, or deleted entirely+ * — and even when `sandbox_status` says "RUNNING" the runtime can be+ * unreachable for a moment. The hook is responsible for translating+ * each of these states into a stable `sandboxIssue` code so the modal+ * can render a targeted empty state instead of a raw axios error.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { renderHook, waitFor } from "@testing-library/react";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { AxiosError, AxiosHeaders } from "axios";+import type { AppConversation } from "#/api/conversation-service/agent-server-conversation-service.types";+import { useBashCommandLogs } from "#/hooks/query/use-bash-command-logs";++// ── Mocks ─────────────────────────────────────────────────────────────────────++const { useUserConversationMock, useActiveBackendMock, listOutputsMock } =+ vi.hoisted(() => ({+ useUserConversationMock: vi.fn(),+ useActiveBackendMock: vi.fn(),+ listOutputsMock: vi.fn(),+ }));++vi.mock("#/hooks/query/use-user-conversation", () => ({+ useUserConversation: (...args: unknown[]) => useUserConversationMock(...args),+}));++vi.mock("#/contexts/active-backend-context", () => ({+ useActiveBackend: () => useActiveBackendMock(),+}));++vi.mock("#/api/bash-service/bash-service.api", () => ({+ default: { listOutputs: (...args: unknown[]) => listOutputsMock(...args) },+}));++// ── Helpers ───────────────────────────────────────────────────────────────────++function wrapper({ children }: { children: React.ReactNode }) {+ const client = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ return <QueryClientProvider client={client}>{children}</QueryClientProvider>;+}++function setActiveBackend(kind: "cloud" | "local") {+ useActiveBackendMock.mockReturnValue({+ backend: { id: "bk-1", kind },+ orgId: null,+ });+}++function setConversation(partial: Partial<AppConversation> | null) {+ useUserConversationMock.mockReturnValue({+ data: partial,+ isFetched: true,+ isPending: false,+ });+}++beforeEach(() => {+ useUserConversationMock.mockReset();+ useActiveBackendMock.mockReset();+ listOutputsMock.mockReset();+});++afterEach(() => {+ vi.clearAllMocks();+});++// ── Tests ─────────────────────────────────────────────────────────────────────++describe("useBashCommandLogs — cloud sandbox state handling", () => {+ beforeEach(() => setActiveBackend("cloud"));++ it.each([+ { status: "MISSING" as const, issue: "missing" },+ { status: "PAUSED" as const, issue: "paused" },+ { status: "STARTING" as const, issue: "starting" },+ { status: "ERROR" as const, issue: "errored" },+ ])(+ "reports sandboxIssue=$issue and skips the fetch when sandbox_status=$status",+ async ({ status, issue }) => {+ setConversation({+ conversation_url: "https://runtime.example.com",+ sandbox_status: status,+ });++ const { result } = renderHook(+ () =>+ useBashCommandLogs({+ conversationId: "conv-1",+ bashCommandId: "cmd-1",+ }),+ { wrapper },+ );++ expect(result.current.sandboxIssue).toBe(issue);+ // Critical: we did NOT fire a doomed request at a known-bad sandbox.+ expect(listOutputsMock).not.toHaveBeenCalled();+ },+ );++ it("reports sandboxIssue=missing when conversation has no runtime URL", () => {+ setConversation({+ conversation_url: null,+ sandbox_status: "RUNNING",+ });++ const { result } = renderHook(+ () =>+ useBashCommandLogs({+ conversationId: "conv-1",+ bashCommandId: "cmd-1",+ }),+ { wrapper },+ );++ expect(result.current.sandboxIssue).toBe("missing");+ expect(listOutputsMock).not.toHaveBeenCalled();+ });++ it("reports conversationMissing when the lookup returns null", () => {+ setConversation(null);++ const { result } = renderHook(+ () =>+ useBashCommandLogs({+ conversationId: "conv-1",+ bashCommandId: "cmd-1",+ }),+ { wrapper },+ );++ expect(result.current.conversationMissing).toBe(true);+ expect(result.current.sandboxIssue).toBeNull();+ expect(listOutputsMock).not.toHaveBeenCalled();+ });++ it("fires the fetch and returns data when sandbox is RUNNING", async () => {+ setConversation({+ conversation_url: "https://runtime.example.com",+ sandbox_status: "RUNNING",+ });+ listOutputsMock.mockResolvedValueOnce([+ { kind: "BashOutput", stdout: "hi", stderr: null },+ ]);++ const { result } = renderHook(+ () =>+ useBashCommandLogs({+ conversationId: "conv-1",+ bashCommandId: "cmd-1",+ }),+ { wrapper },+ );++ await waitFor(() => expect(result.current.data).toBeTruthy());+ expect(result.current.sandboxIssue).toBeNull();+ expect(listOutputsMock).toHaveBeenCalledTimes(1);+ });++ it.each([+ { status: 404, label: "404 not-found" },+ { status: 502, label: "502 bad-gateway" },+ { status: 503, label: "503 unavailable" },+ { status: 504, label: "504 gateway-timeout" },+ ])(+ "classifies $label responses as sandboxIssue=unreachable",+ async ({ status }) => {+ setConversation({+ conversation_url: "https://runtime.example.com",+ sandbox_status: "RUNNING",+ });+ const headers = new AxiosHeaders();+ listOutputsMock.mockRejectedValueOnce(+ new AxiosError(+ `Request failed with status code ${status}`,+ "ERR",+ {+ headers,+ } as never,+ null,+ {+ status,+ data: {},+ statusText: "",+ headers,+ config: { headers },+ } as never,+ ),+ );++ const { result } = renderHook(+ () =>+ useBashCommandLogs({+ conversationId: "conv-1",+ bashCommandId: "cmd-1",+ }),+ { wrapper },+ );++ await waitFor(() =>+ expect(result.current.sandboxIssue).toBe("unreachable"),+ );+ // Don't double-report: when an issue is detected we hide the raw+ // error so the modal doesn't render both the empty state AND the+ // generic "Failed: AxiosError" line.+ expect(result.current.error).toBeNull();+ },+ );++ it("classifies network errors (no response) as sandboxIssue=unreachable", async () => {+ setConversation({+ conversation_url: "https://runtime.example.com",+ sandbox_status: "RUNNING",+ });+ const err = new AxiosError("Network Error", "ERR_NETWORK");+ err.response = undefined;+ listOutputsMock.mockRejectedValueOnce(err);++ const { result } = renderHook(+ () =>+ useBashCommandLogs({+ conversationId: "conv-1",+ bashCommandId: "cmd-1",+ }),+ { wrapper },+ );++ await waitFor(() =>+ expect(result.current.sandboxIssue).toBe("unreachable"),+ );+ });++ it("does NOT collapse 401/403 into unreachable (auth bugs surface as errors)", async () => {+ setConversation({+ conversation_url: "https://runtime.example.com",+ sandbox_status: "RUNNING",+ });+ const headers = new AxiosHeaders();+ listOutputsMock.mockRejectedValueOnce(+ new AxiosError("Forbidden", "ERR", { headers } as never, null, {+ status: 403,+ data: {},+ statusText: "Forbidden",+ headers,+ config: { headers },+ } as never),+ );++ const { result } = renderHook(+ () =>+ useBashCommandLogs({+ conversationId: "conv-1",+ bashCommandId: "cmd-1",+ }),+ { wrapper },+ );++ await waitFor(() => expect(result.current.error).toBeTruthy());+ expect(result.current.sandboxIssue).toBeNull();+ });+});++describe("useBashCommandLogs — local backend", () => {+ beforeEach(() => setActiveBackend("local"));++ it("never reports a sandboxIssue (local has no sandbox lifecycle)", async () => {+ setConversation({+ conversation_url: null,+ sandbox_status: null,+ });+ listOutputsMock.mockResolvedValueOnce([]);++ const { result } = renderHook(+ () =>+ useBashCommandLogs({+ conversationId: "conv-1",+ bashCommandId: "cmd-1",+ }),+ { wrapper },+ );++ await waitFor(() => expect(result.current.data).toEqual([]));+ expect(result.current.sandboxIssue).toBeNull();+ // Even network/5xx errors stay as raw errors in local mode — they+ // typically mean the local agent-server is misconfigured, not a+ // sandbox lifecycle issue.+ expect(listOutputsMock).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/api/bash-service/bash-service.api.ts b/src/api/bash-service/bash-service.api.tsnew file mode 100644index 0000000000..a8cab102d0--- /dev/null+++ b/src/api/bash-service/bash-service.api.ts@@ -0,0 +1,121 @@+import { BashClient } from "@openhands/typescript-client/clients";+import type {+ BashEvent,+ BashEventPage,+ BashOutput,+} from "@openhands/typescript-client";+import { buildHttpBaseUrl } from "#/utils/websocket-url";+import { getActiveBackend } from "../backend-registry/active-store";+import { callCloudProxy } from "../cloud/proxy";+import { getAgentServerClientOptions } from "../agent-server-client-options";++interface SearchOptions {+ kind__eq?: "BashCommand" | "BashOutput";+ command_id__eq?: string;+ sort_order?: "TIMESTAMP" | "TIMESTAMP_DESC";+ page_id?: string;+ limit?: number;+}++const MAX_OUTPUT_PAGES = 20; // safety cap; >2000 output events is unlikely.++function isBashOutput(event: BashEvent): event is BashOutput {+ return event.kind === "BashOutput";+}++/**+ * Cloud-aware bash event reads.+ *+ * Bash events live on the agent-server runtime that owns the+ * conversation. In **local** mode we talk to the active backend's+ * agent-server directly with the SDK's `BashClient` (a per-conversation+ * URL is honoured when known, otherwise we fall back to the backend+ * host — a single local agent-server hosts all conversations). In+ * **cloud** mode we tunnel through `callCloudProxy` with the runtime URL+ * as `hostOverride`: direct browser calls to `*.prod-runtime.all-hands.dev`+ * are blocked by CORS, and runtime endpoints authenticate with the+ * conversation's `X-Session-API-Key`.+ *+ * Note on the search filter name: the agent-server API uses+ * `command_id__eq` (not `bash_command_id__eq`) — that's the parameter the+ * `BashService.search_bash_events` Python implementation declares and+ * what the typescript-client's `BashEventSearchOptions` exposes.+ */+class BashService {+ /**+ * Fetch all `BashOutput` events for a bash command, paginated and+ * sorted by timestamp. Returns events in command-emission order so+ * callers can concatenate `stdout` / `stderr` values directly.+ */+ static async listOutputs(+ conversationUrl: string | null,+ sessionApiKey: string | null | undefined,+ bashCommandId: string,+ ): Promise<BashOutput[]> {+ const outputs: BashOutput[] = [];+ let pageId: string | undefined;+ for (let i = 0; i < MAX_OUTPUT_PAGES; i += 1) {+ const page = await BashService.searchEvents(+ conversationUrl,+ sessionApiKey,+ {+ kind__eq: "BashOutput",+ command_id__eq: bashCommandId,+ sort_order: "TIMESTAMP",+ ...(pageId ? { page_id: pageId } : {}),+ },+ );+ page.items.forEach((event) => {+ if (isBashOutput(event)) outputs.push(event);+ });+ if (!page.next_page_id) break;+ pageId = page.next_page_id;+ }+ return outputs;+ }++ private static async searchEvents(+ conversationUrl: string | null,+ sessionApiKey: string | null | undefined,+ options: SearchOptions,+ ): Promise<BashEventPage> {+ const active = getActiveBackend().backend;++ if (active.kind === "cloud") {+ // Cloud requires the per-conversation runtime URL — there is no+ // shared cloud host that owns bash events. Callers must wait for+ // the conversation to be hydrated before invoking this method on+ // a cloud backend.+ if (!conversationUrl) {+ throw new Error(+ "BashService.listOutputs requires a conversation URL on cloud backends",+ );+ }+ const params = new URLSearchParams();+ Object.entries(options).forEach(([k, v]) => {+ if (v !== undefined && v !== null) params.set(k, String(v));+ });+ return callCloudProxy<BashEventPage>({+ backend: active,+ method: "GET",+ hostOverride: buildHttpBaseUrl(conversationUrl),+ path: `/api/bash/bash_events/search?${params.toString()}`,+ authMode: "session-api-key",+ sessionApiKey,+ });+ }++ // Local mode: the active backend's agent-server hosts the bash+ // events. The optional `conversationUrl` is used when present (lets+ // us target a per-conversation sub-host), otherwise we fall through+ // to `backend.host` via `getAgentServerClientOptions`.+ return new BashClient(+ getAgentServerClientOptions({+ ...(conversationUrl ? { conversationUrl } : {}),+ sessionApiKey,+ }),+ ).searchEvents(options);+ }+}++export default BashService;diff --git a/src/components/features/automations/detail/activity-log-item.tsx b/src/components/features/automations/detail/activity-log-item.tsxindex 46fc028f46..48a42802ff 100644--- a/src/components/features/automations/detail/activity-log-item.tsx+++ b/src/components/features/automations/detail/activity-log-item.tsx@@ -1,7 +1,10 @@+import { useState } from "react";import { useTranslation } from "react-i18next";import { I18nKey } from "#/i18n/declaration";+import TerminalIcon from "#/icons/terminal.svg?react";import type { AutomationRun } from "#/types/automation";import { RunStatusBadge } from "./run-status-badge";+import { RunLogsModal } from "./run-logs-modal";interface ActivityLogItemProps {run: AutomationRun;@@ -27,38 +30,78 @@ function getConversationUrl(conversationId: string): string {export function ActivityLogItem({ run }: ActivityLogItemProps) {const { t, i18n } = useTranslation("openhands");const hasConversation = !!run.conversation_id;+ const hasBashCommand = !!run.bash_command_id;+ const [logsOpen, setLogsOpen] = useState(false);++ const formattedTimestamp = formatRunTimestamp(run.started_at, i18n.language);++ const handleLogsClick = (+ e:+ | React.MouseEvent<HTMLButtonElement>+ | React.KeyboardEvent<HTMLButtonElement>,+ ) => {+ // Stop the click bubbling up to the parent <a> so the user stays on+ // the automation detail page instead of navigating to the conversation.+ e.stopPropagation();+ e.preventDefault();+ setLogsOpen(true);+ };++ const logsButton = hasBashCommand ? (+ <button+ type="button"+ onClick={handleLogsClick}+ className="rounded-md p-1 text-muted hover:bg-surface-raised hover:text-foreground focus:bg-surface-raised focus:outline-none"+ aria-label={t(I18nKey.AUTOMATIONS$DETAIL$LOGS_VIEW, {+ timestamp: formattedTimestamp,+ })}+ title={t(I18nKey.AUTOMATIONS$DETAIL$LOGS_VIEW_SHORT)}+ >+ <TerminalIcon className="size-4" />+ </button>+ ) : null;const content = (<><div className="flex items-center gap-3">- <span className="text-sm text-content">- {formatRunTimestamp(run.started_at, i18n.language)}- </span>+ <span className="text-sm text-content">{formattedTimestamp}</span>{!hasConversation && (<span className="text-xs text-muted italic">({t(I18nKey.AUTOMATIONS$DETAIL$NO_CONVERSATION)})</span>)}</div>- <RunStatusBadge status={run.status} />+ <div className="flex items-center gap-2">+ {logsButton}+ <RunStatusBadge status={run.status} />+ </div></>);- if (hasConversation && run.conversation_id) {- return (- <a- href={getConversationUrl(run.conversation_id)}- className="flex items-center justify-between px-5 py-3 transition-colors cursor-pointer hover:bg-surface-raised focus:bg-surface-raised focus:outline-none"- aria-label={`View conversation for run at ${formatRunTimestamp(run.started_at, i18n.language)}`}- >- {content}- </a>- );- }-return (- <div className="flex items-center justify-between px-5 py-3 cursor-default">- {content}- </div>+ <>+ {hasConversation && run.conversation_id ? (+ <a+ href={getConversationUrl(run.conversation_id)}+ className="flex items-center justify-between px-5 py-3 transition-colors cursor-pointer hover:bg-surface-raised focus:bg-surface-raised focus:outline-none"+ aria-label={`View conversation for run at ${formattedTimestamp}`}+ >+ {content}+ </a>+ ) : (+ <div className="flex items-center justify-between px-5 py-3 cursor-default">+ {content}+ </div>+ )}++ {hasBashCommand && (+ <RunLogsModal+ conversationId={run.conversation_id}+ bashCommandId={run.bash_command_id}+ isOpen={logsOpen}+ onClose={() => setLogsOpen(false)}+ />+ )}+ </>);}diff --git a/src/components/features/automations/detail/run-logs-modal.tsx b/src/components/features/automations/detail/run-logs-modal.tsxnew file mode 100644index 0000000000..717d9174d7--- /dev/null+++ b/src/components/features/automations/detail/run-logs-modal.tsx@@ -0,0 +1,235 @@+import { useEffect, useMemo, useState } from "react";+import { useTranslation } from "react-i18next";+import { I18nKey } from "#/i18n/declaration";+import XMarkIcon from "#/icons/x-mark.svg?react";+import {+ useBashCommandLogs,+ type SandboxIssue,+} from "#/hooks/query/use-bash-command-logs";+import type { BashOutput } from "@openhands/typescript-client";++/**+ * Localized empty-state message key for each `SandboxIssue` reason.+ * Centralised so we don't sprinkle conditional renders for each code.+ */+const SANDBOX_ISSUE_I18N: Record<SandboxIssue, I18nKey> = {+ missing: I18nKey.AUTOMATIONS$DETAIL$LOGS_SANDBOX_MISSING,+ paused: I18nKey.AUTOMATIONS$DETAIL$LOGS_SANDBOX_PAUSED,+ starting: I18nKey.AUTOMATIONS$DETAIL$LOGS_SANDBOX_STARTING,+ errored: I18nKey.AUTOMATIONS$DETAIL$LOGS_SANDBOX_ERROR,+ unreachable: I18nKey.AUTOMATIONS$DETAIL$LOGS_SANDBOX_UNREACHABLE,+};++type LogTab = "stdout" | "stderr";++interface RunLogsModalProps {+ /** Conversation that owns the bash command. */+ conversationId: string | null;+ /** Bash command id to fetch logs for. */+ bashCommandId: string | null;+ isOpen: boolean;+ onClose: () => void;+}++function concatStream(outputs: BashOutput[], key: "stdout" | "stderr"): string {+ // Outputs come back from the API sorted by timestamp, but pages can+ // arrive out-of-order, so re-sort by (timestamp, order) before+ // concatenating to keep the stream chronological.+ return [...outputs]+ .sort((a, b) => {+ const ts = a.timestamp.localeCompare(b.timestamp);+ if (ts !== 0) return ts;+ return (a.order ?? 0) - (b.order ?? 0);+ })+ .map((output) => output[key] ?? "")+ .join("");+}++export function RunLogsModal({+ conversationId,+ bashCommandId,+ isOpen,+ onClose,+}: RunLogsModalProps) {+ const { t } = useTranslation("openhands");+ const [activeTab, setActiveTab] = useState<LogTab>("stdout");++ const {+ data: outputs,+ isFetching,+ isResolvingConversation,+ sandboxIssue,+ conversationMissing,+ error,+ } = useBashCommandLogs({+ conversationId,+ bashCommandId,+ enabled: isOpen,+ });++ // Reset to the default tab whenever the modal opens for a different run.+ useEffect(() => {+ if (isOpen) setActiveTab("stdout");+ }, [isOpen, bashCommandId]);++ // Close on Escape.+ useEffect(() => {+ if (!isOpen) return undefined;+ const handler = (e: KeyboardEvent) => {+ if (e.key === "Escape") onClose();+ };+ window.addEventListener("keydown", handler);+ return () => window.removeEventListener("keydown", handler);+ }, [isOpen, onClose]);++ const { stdout, stderr } = useMemo(() => {+ if (!outputs) return { stdout: "", stderr: "" };+ return {+ stdout: concatStream(outputs, "stdout"),+ stderr: concatStream(outputs, "stderr"),+ };+ }, [outputs]);++ if (!isOpen) return null;++ const loading = isResolvingConversation || (isFetching && !outputs);+ const noBashCommand = !bashCommandId;+ const activeBody = activeTab === "stdout" ? stdout : stderr;++ const tabBaseClass =+ "border-b-2 px-3 py-2 text-sm font-medium transition-colors focus:outline-none";+ const tabActiveClass = "border-[var(--oh-primary)] text-white";+ const tabInactiveClass = "border-transparent text-muted hover:text-content";++ return (+ <div+ className="fixed inset-0 z-50 flex items-center justify-center p-4"+ role="dialog"+ aria-modal="true"+ aria-label={t(I18nKey.AUTOMATIONS$DETAIL$LOGS_TITLE)}+ >+ <div+ className="absolute inset-0 bg-black/60"+ onClick={onClose}+ onKeyDown={(e) => {+ if (e.key === "Escape") onClose();+ }}+ role="presentation"+ />+ <div className="relative flex max-h-[80vh] w-full max-w-3xl flex-col rounded-xl border border-[var(--oh-border)] bg-[var(--oh-surface)] p-6">+ <button+ type="button"+ onClick={onClose}+ className="absolute right-4 top-4 text-muted hover:text-foreground"+ aria-label={t(I18nKey.AUTOMATIONS$CANCEL)}+ >+ <XMarkIcon className="size-5" />+ </button>++ <h2 className="pr-8 text-lg font-semibold text-white">+ {t(I18nKey.AUTOMATIONS$DETAIL$LOGS_TITLE)}+ </h2>++ <div+ role="tablist"+ aria-label={t(I18nKey.AUTOMATIONS$DETAIL$LOGS_TITLE)}+ className="mt-4 flex gap-1 border-b border-[var(--oh-border)]"+ >+ <button+ type="button"+ role="tab"+ aria-selected={activeTab === "stdout"}+ aria-controls="run-logs-panel-stdout"+ id="run-logs-tab-stdout"+ tabIndex={activeTab === "stdout" ? 0 : -1}+ onClick={() => setActiveTab("stdout")}+ className={`${tabBaseClass} ${+ activeTab === "stdout" ? tabActiveClass : tabInactiveClass+ }`}+ >+ {t(I18nKey.AUTOMATIONS$DETAIL$LOGS_TAB_OUTPUT)}+ </button>+ <button+ type="button"+ role="tab"+ aria-selected={activeTab === "stderr"}+ aria-controls="run-logs-panel-stderr"+ id="run-logs-tab-stderr"+ tabIndex={activeTab === "stderr" ? 0 : -1}+ onClick={() => setActiveTab("stderr")}+ className={`${tabBaseClass} ${+ activeTab === "stderr" ? tabActiveClass : tabInactiveClass+ }`}+ >+ {t(I18nKey.AUTOMATIONS$DETAIL$LOGS_TAB_ERROR)}+ </button>+ </div>++ <div+ role="tabpanel"+ id={`run-logs-panel-${activeTab}`}+ aria-labelledby={`run-logs-tab-${activeTab}`}+ className="mt-3 min-h-[12rem] flex-1 overflow-auto rounded-lg border border-[var(--oh-border)] bg-black/40 p-4 font-mono text-xs"+ >+ {noBashCommand && (+ <p className="text-muted italic">+ {t(I18nKey.AUTOMATIONS$DETAIL$LOGS_NO_COMMAND)}+ </p>+ )}++ {!noBashCommand && conversationMissing && (+ <p className="text-muted italic">+ {t(I18nKey.AUTOMATIONS$DETAIL$LOGS_CONVERSATION_MISSING)}+ </p>+ )}++ {!noBashCommand && !conversationMissing && sandboxIssue && (+ <p+ data-testid={`run-logs-sandbox-issue-${sandboxIssue}`}+ className="text-muted italic"+ >+ {t(SANDBOX_ISSUE_I18N[sandboxIssue])}+ </p>+ )}++ {!noBashCommand &&+ !conversationMissing &&+ !sandboxIssue &&+ loading && (+ <p className="text-muted italic">+ {t(I18nKey.AUTOMATIONS$DETAIL$LOGS_LOADING)}+ </p>+ )}++ {!noBashCommand &&+ !conversationMissing &&+ !sandboxIssue &&+ !loading &&+ error &&+ !outputs && (+ <p className="text-danger">+ {t(I18nKey.AUTOMATIONS$DETAIL$LOGS_ERROR)}: {String(error)}+ </p>+ )}++ {!loading && !sandboxIssue && outputs && (+ <pre+ data-testid={`run-logs-output-${activeTab}`}+ className={`whitespace-pre-wrap break-words ${+ activeTab === "stderr" ? "text-danger" : "text-content"+ }`}+ >+ {activeBody.length > 0 ? (+ activeBody+ ) : (+ <span className="text-muted italic">+ {t(I18nKey.AUTOMATIONS$DETAIL$LOGS_EMPTY)}+ </span>+ )}+ </pre>+ )}+ </div>+ </div>+ </div>+ );+}diff --git a/src/hooks/query/use-bash-command-logs.ts b/src/hooks/query/use-bash-command-logs.tsnew file mode 100644index 0000000000..a13c35fda4--- /dev/null+++ b/src/hooks/query/use-bash-command-logs.ts@@ -0,0 +1,178 @@+import { useQuery } from "@tanstack/react-query";+import axios from "axios";+import BashService from "#/api/bash-service/bash-service.api";+import { useActiveBackend } from "#/contexts/active-backend-context";+import type { SandboxStatus } from "#/api/conversation-service/agent-server-conversation-service.types";+import { useUserConversation } from "./use-user-conversation";++export const BASH_COMMAND_LOGS_QUERY_KEY = ["bash-command-logs"] as const;++/**+ * Reasons the modal can't fetch logs from a cloud sandbox, in priority+ * order. The hook surfaces at most one of these so the UI can render a+ * targeted message instead of a raw error.+ */+export type SandboxIssue =+ | "missing" // sandbox has been deleted (or conversation has no runtime URL)+ | "paused" // sandbox is paused — needs resuming+ | "starting" // sandbox is still booting+ | "errored" // sandbox is in a terminal error state+ | "unreachable"; // bash query attempted and failed at the network layer++interface UseBashCommandLogsOptions {+ /**+ * The agent-server conversation that hosts the bash command. Used to+ * resolve `conversation_url` and `session_api_key` for cloud+ * backends, and to gate the query on `sandbox_status` so we don't+ * fire requests at known-unreachable sandboxes.+ */+ conversationId: string | null | undefined;+ bashCommandId: string | null | undefined;+ enabled?: boolean;+}++/**+ * Map a cloud sandbox status to a stable issue code (or null when the+ * sandbox is healthy enough to attempt the fetch).+ */+function sandboxIssueFromStatus(+ status: SandboxStatus | null | undefined,+): SandboxIssue | null {+ switch (status) {+ case "MISSING":+ return "missing";+ case "PAUSED":+ return "paused";+ case "STARTING":+ return "starting";+ case "ERROR":+ return "errored";+ case "RUNNING":+ case null:+ case undefined:+ default:+ return null;+ }+}++/**+ * Detect "the runtime is unreachable" axios errors from the cloud+ * proxy. The proxy itself returns 5xx when the upstream sandbox is+ * gone; runtimes return 4xx/5xx for various ephemeral states. We+ * classify 5xx and network errors as "unreachable" so the modal can+ * render the sandbox-gone state instead of dumping an axios string.+ */+function classifyFetchError(error: unknown): SandboxIssue | null {+ if (!axios.isAxiosError(error)) return null;+ // No response at all → DNS/connect/abort+ if (!error.response) return "unreachable";+ const status = error.response.status;+ // Treat 502/503/504 (proxy can't reach upstream) and 404 (sandbox or+ // resource no longer exists) as the sandbox being gone. We do not+ // collapse 401/403 here — those are auth bugs we want to surface.+ if (status === 404 || status >= 500) return "unreachable";+ return null;+}++/**+ * Search `BashOutput` events for an automation run's bash command.+ *+ * - **Local backend**: the query fires as soon as the modal opens and+ * we have a `bash_command_id`. The conversation lookup runs in+ * parallel; if it resolves with `session_api_key`/`conversation_url`+ * those are passed through, but a missing/stale conversation does not+ * block the bash query (the local agent-server hosts events under a+ * single root).+ * - **Cloud backend**: pre-checks `sandbox_status` and the existence of+ * a `conversation_url` before firing — paused, starting, errored, or+ * missing sandboxes report a `sandboxIssue` and skip the request+ * entirely (saves a doomed round-trip and gives the UI a targeted+ * empty state). If the request does fire and fails with a 5xx /+ * network error / 404 we re-classify it as `unreachable`.+ */+export function useBashCommandLogs(options: UseBashCommandLogsOptions) {+ const { conversationId, bashCommandId, enabled = true } = options;+ const active = useActiveBackend();+ const conversationQuery = useUserConversation(conversationId ?? null);+ const conversation = conversationQuery.data;+ const conversationUrl = conversation?.conversation_url ?? null;+ const sessionApiKey = conversation?.session_api_key ?? null;++ const isCloud = active.backend.kind === "cloud";+ const conversationFetched = conversationQuery.isFetched;++ // Resolve a single "sandbox issue" only for cloud backends. Local+ // backends don't carry sandbox_status, and the agent-server hosts+ // events under a single root so there's nothing to gate on.+ let preflightIssue: SandboxIssue | null = null;+ let conversationMissing = false;+ if (isCloud && conversationFetched) {+ if (!conversation) {+ conversationMissing = true;+ } else {+ preflightIssue =+ sandboxIssueFromStatus(conversation.sandbox_status) ??+ (!conversation.conversation_url ? "missing" : null);+ }+ }++ // Cloud needs the conversation URL before it can talk to the+ // runtime; local does not.+ const hasRequiredAuth = isCloud ? !!conversationUrl : true;+ const canFire =+ enabled &&+ !!bashCommandId &&+ hasRequiredAuth &&+ !preflightIssue &&+ !conversationMissing;++ const query = useQuery({+ queryKey: [+ ...BASH_COMMAND_LOGS_QUERY_KEY,+ bashCommandId,+ conversationUrl,+ sessionApiKey,+ active.backend.id,+ active.orgId,+ ],+ queryFn: () =>+ BashService.listOutputs(+ conversationUrl,+ sessionApiKey,+ bashCommandId as string,+ ),+ enabled: canFire,+ // Completed-run logs don't change — cache long enough that reopening+ // the modal is instant but not forever.+ staleTime: 60 * 1000,+ gcTime: 5 * 60 * 1000,+ retry: false,+ });++ // If the request fired and failed in a way that suggests the+ // sandbox is gone/unreachable, surface it as a sandbox issue so the+ // modal can render the matching empty state instead of a raw error.+ const fetchIssue = isCloud ? classifyFetchError(query.error) : null;+ const sandboxIssue: SandboxIssue | null = preflightIssue ?? fetchIssue;++ return {+ data: query.data,+ /**+ * Set only when the request actually fired and failed AND the+ * failure isn't already classified as a sandbox issue. The modal+ * should render `sandboxIssue` first and only fall back to this.+ */+ error: fetchIssue ? null : query.error,+ isFetching: query.isFetching,+ isPending: query.isPending,+ /** True while we're still resolving the conversation runtime URL. */+ isResolvingConversation: isCloud && conversationQuery.isPending,+ /** Cloud-only: conversation lookup failed (deleted or no access). */+ conversationMissing,+ /**+ * Reason the bash query couldn't / didn't usefully complete. Always+ * null for healthy cloud sandboxes and for local backends.+ */+ sandboxIssue,+ };+}diff --git a/src/i18n/translation.json b/src/i18n/translation.jsonindex e7949e7b30..90be63eab5 100644--- a/src/i18n/translation.json+++ b/src/i18n/translation.json@@ -11729,6 +11729,261 @@"uk": "Розмову не створено","ca": "Conversa no creada"},+ "AUTOMATIONS$DETAIL$LOGS_VIEW": {+ "en": "View logs for run on {{timestamp}}",+ "ja": "{{timestamp}} の実行ログを表示",+ "zh-CN": "查看 {{timestamp}} 的运行日志",+ "zh-TW": "查看 {{timestamp}} 的執行日誌",+ "ko-KR": "{{timestamp}} 실행 로그 보기",+ "no": "Vis logger for kjøring {{timestamp}}",+ "it": "Visualizza i log per l'esecuzione del {{timestamp}}",+ "pt": "Ver registos da execução de {{timestamp}}",+ "es": "Ver registros de la ejecución del {{timestamp}}",+ "ar": "عرض السجلات لتشغيل {{timestamp}}",+ "fr": "Afficher les journaux pour l'exécution du {{timestamp}}",+ "tr": "{{timestamp}} çalıştırması için günlükleri görüntüle",+ "de": "Protokolle für Ausführung am {{timestamp}} anzeigen",+ "uk": "Переглянути журнали запуску від {{timestamp}}",+ "ca": "Mostra els registres de l'execució de {{timestamp}}"+ },+ "AUTOMATIONS$DETAIL$LOGS_VIEW_SHORT": {+ "en": "View logs",+ "ja": "ログを表示",+ "zh-CN": "查看日志",+ "zh-TW": "查看日誌",+ "ko-KR": "로그 보기",+ "no": "Vis logger",+ "it": "Visualizza log",+ "pt": "Ver registos",+ "es": "Ver registros",+ "ar": "عرض السجلات",+ "fr": "Afficher les journaux",+ "tr": "Günlükleri görüntüle",+ "de": "Protokolle anzeigen",+ "uk": "Переглянути журнали",+ "ca": "Mostra els registres"+ },+ "AUTOMATIONS$DETAIL$LOGS_TITLE": {+ "en": "Logs",+ "ja": "ログ",+ "zh-CN": "日志",+ "zh-TW": "日誌",+ "ko-KR": "로그",+ "no": "Logger",+ "it": "Log",+ "pt": "Registos",+ "es": "Registros",+ "ar": "السجلات",+ "fr": "Journaux",+ "tr": "Günlükler",+ "de": "Protokolle",+ "uk": "Журнали",+ "ca": "Registres"+ },+ "AUTOMATIONS$DETAIL$LOGS_TAB_OUTPUT": {+ "en": "Output",+ "ja": "出力",+ "zh-CN": "输出",+ "zh-TW": "輸出",+ "ko-KR": "출력",+ "no": "Utdata",+ "it": "Output",+ "pt": "Saída",+ "es": "Salida",+ "ar": "الإخراج",+ "fr": "Sortie",+ "tr": "Çıktı",+ "de": "Ausgabe",+ "uk": "Вивід",+ "ca": "Sortida"+ },+ "AUTOMATIONS$DETAIL$LOGS_TAB_ERROR": {+ "en": "Error",+ "ja": "エラー",+ "zh-CN": "错误",+ "zh-TW": "錯誤",+ "ko-KR": "오류",+ "no": "Feil",+ "it": "Errore",+ "pt": "Erro",+ "es": "Error",+ "ar": "الخطأ",+ "fr": "Erreur",+ "tr": "Hata",+ "de": "Fehler",+ "uk": "Помилка",+ "ca": "Error"+ },+ "AUTOMATIONS$DETAIL$LOGS_EMPTY": {+ "en": "(no output)",+ "ja": "(出力なし)",+ "zh-CN": "(无输出)",+ "zh-TW": "(無輸出)",+ "ko-KR": "(출력 없음)",+ "no": "(ingen utdata)",+ "it": "(nessun output)",+ "pt": "(sem saída)",+ "es": "(sin salida)",+ "ar": "(لا يوجد إخراج)",+ "fr": "(aucune sortie)",+ "tr": "(çıktı yok)",+ "de": "(keine Ausgabe)",+ "uk": "(немає виводу)",+ "ca": "(sense sortida)"+ },+ "AUTOMATIONS$DETAIL$LOGS_LOADING": {+ "en": "Loading logs…",+ "ja": "ログを読み込み中…",+ "zh-CN": "正在加载日志…",+ "zh-TW": "正在載入日誌…",+ "ko-KR": "로그를 불러오는 중…",+ "no": "Laster logger…",+ "it": "Caricamento dei log…",+ "pt": "A carregar registos…",+ "es": "Cargando registros…",+ "ar": "جارٍ تحميل السجلات…",+ "fr": "Chargement des journaux…",+ "tr": "Günlükler yükleniyor…",+ "de": "Protokolle werden geladen…",+ "uk": "Завантаження журналів…",+ "ca": "S'estan carregant els registres…"+ },+ "AUTOMATIONS$DETAIL$LOGS_ERROR": {+ "en": "Failed to load logs",+ "ja": "ログの読み込みに失敗しました",+ "zh-CN": "加载日志失败",+ "zh-TW": "載入日誌失敗",+ "ko-KR": "로그를 불러오지 못했습니다",+ "no": "Klarte ikke å laste logger",+ "it": "Caricamento dei log non riuscito",+ "pt": "Falha ao carregar registos",+ "es": "Error al cargar los registros",+ "ar": "تعذر تحميل السجلات",+ "fr": "Échec du chargement des journaux",+ "tr": "Günlükler yüklenemedi",+ "de": "Protokolle konnten nicht geladen werden",+ "uk": "Не вдалося завантажити журнали",+ "ca": "No s'han pogut carregar els registres"+ },+ "AUTOMATIONS$DETAIL$LOGS_NO_COMMAND": {+ "en": "No bash command was recorded for this run.",+ "ja": "この実行には bash コマンドが記録されていません。",+ "zh-CN": "此次运行未记录任何 bash 命令。",+ "zh-TW": "此次執行未記錄任何 bash 命令。",+ "ko-KR": "이 실행에는 bash 명령이 기록되지 않았습니다.",+ "no": "Ingen bash-kommando ble registrert for denne kjøringen.",+ "it": "Nessun comando bash registrato per questa esecuzione.",+ "pt": "Nenhum comando bash foi registado para esta execução.",+ "es": "No se registró ningún comando bash para esta ejecución.",+ "ar": "لم يتم تسجيل أمر bash لهذا التشغيل.",+ "fr": "Aucune commande bash n'a été enregistrée pour cette exécution.",+ "tr": "Bu çalıştırma için bash komutu kaydedilmedi.",+ "de": "Für diese Ausführung wurde kein Bash-Befehl aufgezeichnet.",+ "uk": "Для цього запуску не зафіксовано команд bash.",+ "ca": "No s'ha registrat cap ordre bash per a aquesta execució."+ },+ "AUTOMATIONS$DETAIL$LOGS_CONVERSATION_MISSING": {+ "en": "The conversation for this run is unavailable, so its logs cannot be loaded.",+ "ja": "この実行の会話が利用できないため、ログを読み込めません。",+ "zh-CN": "此次运行的对话不可用,无法加载日志。",+ "zh-TW": "此次執行的對話不可用,無法載入日誌。",+ "ko-KR": "이 실행의 대화를 사용할 수 없어 로그를 불러올 수 없습니다.",+ "no": "Samtalen for denne kjøringen er ikke tilgjengelig, så loggene kan ikke lastes.",+ "it": "La conversazione di questa esecuzione non è disponibile, quindi i log non possono essere caricati.",+ "pt": "A conversa desta execução não está disponível, pelo que os registos não podem ser carregados.",+ "es": "La conversación de esta ejecución no está disponible, por lo que no se pueden cargar los registros.",+ "ar": "محادثة هذا التشغيل غير متاحة، لذا لا يمكن تحميل السجلات.",+ "fr": "La conversation pour cette exécution est indisponible, les journaux ne peuvent pas être chargés.",+ "tr": "Bu çalıştırmaya ait konuşma kullanılamadığından günlükler yüklenemez.",+ "de": "Die Konversation für diese Ausführung ist nicht verfügbar, daher können die Protokolle nicht geladen werden.",+ "uk": "Розмова цього запуску недоступна, тому журнали неможливо завантажити.",+ "ca": "La conversa d'aquesta execució no està disponible, de manera que no es poden carregar els registres."+ },+ "AUTOMATIONS$DETAIL$LOGS_SANDBOX_MISSING": {+ "en": "Sandbox has been deleted — logs are no longer available.",+ "ja": "サンドボックスが削除されました — ログは利用できません。",+ "zh-CN": "沙箱已被删除 — 日志不再可用。",+ "zh-TW": "沙箱已被刪除 — 日誌不再可用。",+ "ko-KR": "샌드박스가 삭제되었습니다 — 로그를 사용할 수 없습니다.",+ "no": "Sandkassen er slettet — logger er ikke lenger tilgjengelige.",+ "it": "Il sandbox è stato eliminato — i log non sono più disponibili.",+ "pt": "O sandbox foi eliminado — os registos já não estão disponíveis.",+ "es": "El sandbox ha sido eliminado — los registros ya no están disponibles.",+ "ar": "تم حذف صندوق الحماية — السجلات لم تعد متاحة.",+ "fr": "Le sandbox a été supprimé — les journaux ne sont plus disponibles.",+ "tr": "Sandbox silindi — günlüklere artık erişilemiyor.",+ "de": "Sandbox wurde gelöscht — Protokolle sind nicht mehr verfügbar.",+ "uk": "Пісочницю видалено — журнали більше недоступні.",+ "ca": "El sandbox s'ha eliminat — els registres ja no estan disponibles."+ },+ "AUTOMATIONS$DETAIL$LOGS_SANDBOX_PAUSED": {+ "en": "Sandbox is paused — resume the conversation to view logs.",+ "ja": "サンドボックスは一時停止中です — ログを表示するには会話を再開してください。",+ "zh-CN": "沙箱已暂停 — 恢复对话以查看日志。",+ "zh-TW": "沙箱已暫停 — 恢復對話以查看日誌。",+ "ko-KR": "샌드박스가 일시 중지됨 — 로그를 보려면 대화를 재개하세요.",+ "no": "Sandkassen er satt på pause — gjenoppta samtalen for å se logger.",+ "it": "Il sandbox è in pausa — riprendi la conversazione per visualizzare i log.",+ "pt": "O sandbox está em pausa — retome a conversa para ver os registos.",+ "es": "El sandbox está pausado — reanuda la conversación para ver los registros.",+ "ar": "صندوق الحماية متوقف مؤقتًا — استأنف المحادثة لعرض السجلات.",+ "fr": "Le sandbox est en pause — reprenez la conversation pour voir les journaux.",+ "tr": "Sandbox duraklatıldı — günlükleri görmek için sohbete devam edin.",+ "de": "Sandbox ist pausiert — setze die Unterhaltung fort, um Protokolle zu sehen.",+ "uk": "Пісочницю призупинено — поновіть розмову, щоб переглянути журнали.",+ "ca": "El sandbox està en pausa — reprèn la conversa per veure els registres."+ },+ "AUTOMATIONS$DETAIL$LOGS_SANDBOX_STARTING": {+ "en": "Sandbox is starting — try again in a moment.",+ "ja": "サンドボックスを起動中です — しばらくしてから再試行してください。",+ "zh-CN": "沙箱正在启动 — 请稍后重试。",+ "zh-TW": "沙箱正在啟動 — 請稍後重試。",+ "ko-KR": "샌드박스를 시작하는 중 — 잠시 후 다시 시도하세요.",+ "no": "Sandkassen starter — prøv igjen om litt.",+ "it": "Il sandbox è in avvio — riprova tra un momento.",+ "pt": "O sandbox está a iniciar — tente novamente daqui a um momento.",+ "es": "El sandbox se está iniciando — inténtalo de nuevo en un momento.",+ "ar": "صندوق الحماية يبدأ — حاول مرة أخرى بعد لحظة.",+ "fr": "Le sandbox démarre — réessayez dans un instant.",+ "tr": "Sandbox başlatılıyor — biraz sonra tekrar deneyin.",+ "de": "Sandbox wird gestartet — versuche es in einem Moment erneut.",+ "uk": "Пісочниця запускається — спробуйте знову за хвилину.",+ "ca": "El sandbox s'està iniciant — torna-ho a provar d'aquí a un moment."+ },+ "AUTOMATIONS$DETAIL$LOGS_SANDBOX_ERROR": {+ "en": "Sandbox is in an error state — logs cannot be retrieved.",+ "ja": "サンドボックスがエラー状態です — ログを取得できません。",+ "zh-CN": "沙箱处于错误状态 — 无法获取日志。",+ "zh-TW": "沙箱處於錯誤狀態 — 無法獲取日誌。",+ "ko-KR": "샌드박스가 오류 상태입니다 — 로그를 가져올 수 없습니다.",+ "no": "Sandkassen er i en feiltilstand — logger kan ikke hentes.",+ "it": "Il sandbox è in stato di errore — impossibile recuperare i log.",+ "pt": "O sandbox está em estado de erro — não é possível obter os registos.",+ "es": "El sandbox está en estado de error — no se pueden recuperar los registros.",+ "ar": "صندوق الحماية في حالة خطأ — لا يمكن استرجاع السجلات.",+ "fr": "Le sandbox est en état d'erreur — impossible de récupérer les journaux.",+ "tr": "Sandbox hata durumunda — günlükler alınamıyor.",+ "de": "Sandbox befindet sich in einem Fehlerzustand — Protokolle können nicht abgerufen werden.",+ "uk": "Пісочниця в стані помилки — журнали неможливо отримати.",+ "ca": "El sandbox està en estat d'error — no es poden recuperar els registres."+ },+ "AUTOMATIONS$DETAIL$LOGS_SANDBOX_UNREACHABLE": {+ "en": "Sandbox is unreachable — it may have been stopped or scaled down.",+ "ja": "サンドボックスに到達できません — 停止またはスケールダウンされた可能性があります。",+ "zh-CN": "无法连接到沙箱 — 它可能已停止或缩减。",+ "zh-TW": "無法連接到沙箱 — 可能已停止或縮減。",+ "ko-KR": "샌드박스에 연결할 수 없습니다 — 중지되었거나 축소되었을 수 있습니다.",+ "no": "Sandkassen er ikke tilgjengelig — den kan ha blitt stoppet eller skalert ned.",+ "it": "Il sandbox è irraggiungibile — potrebbe essere stato arrestato o ridimensionato.",+ "pt": "O sandbox está inacessível — pode ter sido parado ou reduzido.",+ "es": "El sandbox no es accesible — puede haberse detenido o reducido.",+ "ar": "صندوق الحماية غير قابل للوصول — ربما تم إيقافه أو تقليصه.",+ "fr": "Le sandbox est inaccessible — il a peut-être été arrêté ou réduit.",+ "tr": "Sandbox erişilemez — durdurulmuş veya küçültülmüş olabilir.",+ "de": "Sandbox ist nicht erreichbar — möglicherweise wurde sie gestoppt oder herunterskaliert.",+ "uk": "Пісочниця недоступна — її могли зупинити або зменшити масштаб.",+ "ca": "El sandbox no és accessible — pot haver-se aturat o reduït."+ },"AUTOMATIONS$DETAIL$TIME_JUST_NOW": {"en": "Just now","ja": "たった今",diff --git a/src/mocks/automation-runs.mock.ts b/src/mocks/automation-runs.mock.tsindex b4b1b5325b..51265a8313 100644--- a/src/mocks/automation-runs.mock.ts+++ b/src/mocks/automation-runs.mock.ts@@ -19,6 +19,9 @@ function makeRun(id,status,conversation_id: hasConversation ? `conv-${id}` : null,+ // Runs that have a conversation also have a bash command; runs that+ // failed before sandbox creation have neither.+ bash_command_id: hasConversation ? `cmd-${id}` : null,error_detail:status === AutomationRunStatus.FAILED? "Process exited with code 1"diff --git a/src/types/automation.ts b/src/types/automation.tsindex 2b08d7c215..aa62ec46a3 100644--- a/src/types/automation.ts+++ b/src/types/automation.ts@@ -37,6 +37,14 @@ export interface AutomationRun {id: string;status: AutomationRunStatus;conversation_id: string | null;+ /**+ * ID of the bash command that ran the automation inside the agent-server+ * sandbox. Used to fetch run logs from+ * `/api/bash/bash_events/{bash_command_id}` and the matching+ * `BashOutput` events. Null when the run failed before a command was+ * dispatched (e.g. sandbox provisioning errors).+ */+ bash_command_id: string | null;error_detail: string | null;started_at: string;completed_at: string | null;