Skip to content

🙌 OpenHands: AI-Driven Development

fix: load logs for script automation runs and show their script (#17519)

Hiep Led3b4f17cba20
diff --git a/__tests__/components/automations/detail/activity-log-item.test.tsx b/__tests__/components/automations/detail/activity-log-item.test.tsx
index 780bf0a6a7..4ba16efe48 100644
--- a/__tests__/components/automations/detail/activity-log-item.test.tsx
+++ b/__tests__/components/automations/detail/activity-log-item.test.tsx
@@ -27,13 +27,19 @@ vi.mock("#/components/features/automations/detail/run-logs-modal", () => ({
isOpen,
onClose,
bashCommandId,
+ sandboxId,
}: {
isOpen: boolean;
onClose: () => void;
bashCommandId: string | null;
+ sandboxId?: string | null;
}) =>
isOpen ? (
- <div data-testid="logs-modal" data-bash-command-id={bashCommandId}>
+ <div
+ data-testid="logs-modal"
+ data-bash-command-id={bashCommandId}
+ data-sandbox-id={sandboxId ?? ""}
+ >
<button type="button" onClick={onClose}>
close
</button>
@@ -579,3 +585,55 @@ describe("ActivityLogItem — run phase hidden for CANCELLED/SKIPPED", () => {
},
);
});
+
+describe("ActivityLogItem — script runs (a command but no conversation)", () => {
+ beforeEach(() => {
+ __resetActiveStoreForTests();
+ setRegisteredBackends([localBackend]);
+ setActiveSelection({ backendId: localBackend.id });
+ });
+
+ afterEach(() => {
+ __resetActiveStoreForTests();
+ });
+
+ it("explains that the run executed a script and points at the logs once it has finished", () => {
+ // Arrange: a script automation run — the bash command ran, no agent did.
+ const run = makeRun({
+ status: AutomationRunStatus.COMPLETED,
+ conversation_id: null,
+ bash_command_id: "cmd-1",
+ sandbox_id: "sb-1",
+ });
+
+ // Act
+ renderItem(run);
+
+ // Assert
+ expect(
+ screen.getByText(I18nKey.AUTOMATIONS$DETAIL$SCRIPT_RUN_NO_CONVERSATION),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByText(I18nKey.AUTOMATIONS$DETAIL$NO_CONVERSATION),
+ ).not.toBeInTheDocument();
+ });
+
+ it("hands the run's sandbox id to the logs modal", () => {
+ // Arrange
+ const run = makeRun({
+ conversation_id: null,
+ bash_command_id: "cmd-1",
+ sandbox_id: "sb-1",
+ });
+ renderItem(run);
+
+ // Act
+ fireEvent.click(screen.getByRole("button", { name: LOGS_BUTTON_NAME }));
+
+ // Assert
+ expect(screen.getByTestId("logs-modal")).toHaveAttribute(
+ "data-sandbox-id",
+ "sb-1",
+ );
+ });
+});
diff --git a/__tests__/components/automations/detail/run-logs-modal-script-run.test.tsx b/__tests__/components/automations/detail/run-logs-modal-script-run.test.tsx
new file mode 100644
index 0000000000..6973726009
--- /dev/null
+++ b/__tests__/components/automations/detail/run-logs-modal-script-run.test.tsx
@@ -0,0 +1,135 @@
+/**
+ * Regression for OHE-3105: a script automation's run has a bash command and a
+ * sandbox but no conversation. On a cloud backend the modal used to wait on
+ * a conversation lookup that could never run and showed "Loading logs…"
+ * forever. The hook runs for real here; only the services behind it are
+ * stubbed.
+ */
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { render, screen, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { I18nKey } from "#/i18n/declaration";
+import { RunLogsModal } from "#/components/features/automations/detail/run-logs-modal";
+import {
+ __resetActiveStoreForTests,
+ setActiveSelection,
+ setRegisteredBackends,
+} from "#/api/backend-registry/active-store";
+import { ActiveBackendProvider } from "#/contexts/active-backend-context";
+
+const { batchGetCloudSandboxesMock, listOutputsMock } = vi.hoisted(() => ({
+ batchGetCloudSandboxesMock: vi.fn(),
+ listOutputsMock: vi.fn(),
+}));
+
+vi.mock("#/api/cloud/sandbox-service.api", () => ({
+ batchGetCloudSandboxes: (...args: unknown[]) =>
+ batchGetCloudSandboxesMock(...args),
+}));
+
+vi.mock("#/api/bash-service/bash-service.api", () => ({
+ default: { listOutputs: (...args: unknown[]) => listOutputsMock(...args) },
+}));
+
+const runningSandbox = {
+ id: "sb-1",
+ created_by_user_id: "user-1",
+ sandbox_spec_id: "spec-1",
+ status: "RUNNING",
+ session_api_key: "sandbox-key",
+ exposed_urls: [{ name: "AGENT_SERVER", url: "https://runtime.example.com" }],
+ created_at: "2026-01-01T00:00:00Z",
+};
+
+function renderModal() {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ return render(
+ <QueryClientProvider client={queryClient}>
+ <ActiveBackendProvider>
+ <RunLogsModal
+ conversationId={null}
+ sandboxId="sb-1"
+ bashCommandId="cmd-1"
+ isOpen
+ onClose={() => {}}
+ />
+ </ActiveBackendProvider>
+ </QueryClientProvider>,
+ );
+}
+
+beforeEach(() => {
+ __resetActiveStoreForTests();
+ setRegisteredBackends([
+ {
+ id: "cloud-1",
+ name: "Cloud",
+ host: "https://app.example.com",
+ apiKey: "k",
+ kind: "cloud",
+ },
+ ]);
+ setActiveSelection({ backendId: "cloud-1", orgId: "org-1" });
+ batchGetCloudSandboxesMock.mockReset();
+ listOutputsMock.mockReset();
+});
+
+afterEach(() => {
+ __resetActiveStoreForTests();
+ vi.clearAllMocks();
+});
+
+describe("RunLogsModal — script run without a conversation (cloud)", () => {
+ it("shows the run's output instead of loading forever", async () => {
+ // Arrange
+ batchGetCloudSandboxesMock.mockResolvedValue([runningSandbox]);
+ listOutputsMock.mockResolvedValue([
+ {
+ kind: "BashOutput",
+ id: "out-1",
+ command_id: "cmd-1",
+ timestamp: "2026-01-01T10:00:00Z",
+ order: 0,
+ stdout: "scanned 3 repositories\n",
+ stderr: "",
+ },
+ ]);
+
+ // Act
+ renderModal();
+
+ // Assert
+ expect(
+ await screen.findByTestId("run-logs-output-stdout"),
+ ).toHaveTextContent("scanned 3 repositories");
+ expect(
+ screen.queryByText(I18nKey.AUTOMATIONS$DETAIL$LOGS_LOADING),
+ ).not.toBeInTheDocument();
+ expect(listOutputsMock).toHaveBeenCalledWith(
+ "https://runtime.example.com",
+ "sandbox-key",
+ "cmd-1",
+ );
+ });
+
+ it("says the sandbox is gone instead of loading forever once the run's sandbox was deleted", async () => {
+ // Arrange
+ batchGetCloudSandboxesMock.mockResolvedValue([null]);
+
+ // Act
+ renderModal();
+
+ // Assert
+ expect(
+ await screen.findByTestId("run-logs-sandbox-issue-missing"),
+ ).toBeInTheDocument();
+ await waitFor(() =>
+ expect(
+ screen.queryByText(I18nKey.AUTOMATIONS$DETAIL$LOGS_LOADING),
+ ).not.toBeInTheDocument(),
+ );
+ expect(listOutputsMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/__tests__/components/automations/detail/script-section.test.tsx b/__tests__/components/automations/detail/script-section.test.tsx
new file mode 100644
index 0000000000..1390f630f7
--- /dev/null
+++ b/__tests__/components/automations/detail/script-section.test.tsx
@@ -0,0 +1,167 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { render, screen } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+import { HttpError } from "@openhands/typescript-client";
+import { I18nKey } from "#/i18n/declaration";
+import { ScriptSection } from "#/components/features/automations/detail/script-section";
+import AutomationService from "#/api/automation-service/automation-service.api";
+import {
+ __resetActiveStoreForTests,
+ setActiveSelection,
+ setRegisteredBackends,
+} from "#/api/backend-registry/active-store";
+import { ActiveBackendProvider } from "#/contexts/active-backend-context";
+import type { Automation } from "#/types/automation";
+import { packTar, packTarGzip } from "#/utils/tar-gzip";
+
+const automation: Automation = {
+ id: "auto-1",
+ name: "Nightly scan",
+ prompt: null,
+ trigger: { type: "cron" },
+ enabled: true,
+ created_at: "2026-09-01T00:00:00Z",
+ updated_at: "2026-09-02T00:00:00Z",
+ entrypoint: "python main.py",
+};
+
+function renderSection(subject: Automation = automation) {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ return render(
+ <QueryClientProvider client={queryClient}>
+ <ActiveBackendProvider>
+ <ScriptSection automation={subject} />
+ </ActiveBackendProvider>
+ </QueryClientProvider>,
+ );
+}
+
+function filePaths(): string[] {
+ return screen
+ .getAllByTestId("automation-script-file")
+ .map((row) => row.querySelector(".truncate")?.textContent ?? "");
+}
+
+beforeEach(() => {
+ __resetActiveStoreForTests();
+ setRegisteredBackends([
+ {
+ id: "local-1",
+ name: "Local",
+ host: "http://localhost:8000",
+ apiKey: "k",
+ kind: "local",
+ },
+ ]);
+ setActiveSelection({ backendId: "local-1" });
+});
+
+afterEach(() => {
+ __resetActiveStoreForTests();
+ vi.restoreAllMocks();
+});
+
+describe("ScriptSection", () => {
+ it("lists the bundle's files with the entrypoint first and badged", async () => {
+ // Arrange
+ vi.spyOn(AutomationService, "fetchTarballBytes").mockResolvedValue(
+ new Uint8Array(
+ await packTarGzip([
+ { name: "lib/util.py", content: "x = 1\n" },
+ { name: "main.py", content: "print('hi')\n" },
+ { name: "config.json", content: "{}\n" },
+ ]),
+ ),
+ );
+
+ // Act
+ renderSection();
+
+ // Assert
+ expect(await screen.findAllByTestId("automation-script-file")).toHaveLength(
+ 3,
+ );
+ expect(filePaths()).toEqual(["main.py", "config.json", "lib/util.py"]);
+ expect(
+ screen.getByTestId("automation-script-entrypoint"),
+ ).toHaveTextContent("python main.py");
+ expect(
+ screen.getAllByText(I18nKey.AUTOMATIONS$DETAIL$SCRIPT_ENTRYPOINT),
+ ).toHaveLength(1);
+ expect(
+ screen.getAllByTestId("automation-script-file")[0],
+ ).toHaveTextContent("print('hi')");
+ expect(AutomationService.fetchTarballBytes).toHaveBeenCalledWith("auto-1");
+ });
+
+ it("shows a loading message until the bundle arrives", () => {
+ // Arrange
+ vi.spyOn(AutomationService, "fetchTarballBytes").mockReturnValue(
+ new Promise(() => {}),
+ );
+
+ // Act
+ renderSection();
+
+ // Assert
+ expect(
+ screen.getByText(I18nKey.AUTOMATIONS$DETAIL$SCRIPT_LOADING),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByTestId("automation-script-unavailable"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("points at the tarball download when the service cannot hand the bundle back", async () => {
+ // Arrange: an externally hosted bundle the service refuses to proxy.
+ vi.spyOn(AutomationService, "fetchTarballBytes").mockRejectedValue(
+ new HttpError(422, "Unprocessable Entity", {
+ detail: "Cannot proxy s3:// tarball URLs",
+ }),
+ );
+
+ // Act
+ renderSection();
+
+ // Assert
+ expect(
+ await screen.findByTestId("automation-script-unavailable"),
+ ).toBeInTheDocument();
+ expect(screen.queryAllByTestId("automation-script-file")).toHaveLength(0);
+ });
+
+ it("points at the tarball download when the bytes are not an archive", async () => {
+ // Arrange
+ vi.spyOn(AutomationService, "fetchTarballBytes").mockResolvedValue(
+ new Uint8Array(new TextEncoder().encode("<html>".padEnd(1024, "x"))),
+ );
+
+ // Act
+ renderSection();
+
+ // Assert
+ expect(
+ await screen.findByTestId("automation-script-unavailable"),
+ ).toBeInTheDocument();
+ });
+
+ it("labels a binary member instead of rendering it", async () => {
+ // Arrange: a member whose bytes are not UTF-8.
+ const archive = packTar([{ name: "model.bin", content: "AAAA" }]);
+ archive.fill(0xff, 512, 516);
+ vi.spyOn(AutomationService, "fetchTarballBytes").mockResolvedValue(archive);
+
+ // Act
+ renderSection({ ...automation, entrypoint: undefined });
+
+ // Assert
+ expect(
+ await screen.findByText(I18nKey.AUTOMATIONS$DETAIL$SCRIPT_BINARY_FILE),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByTestId("automation-script-entrypoint"),
+ ).not.toBeInTheDocument();
+ });
+});
diff --git a/__tests__/hooks/query/use-bash-command-logs.test.tsx b/__tests__/hooks/query/use-bash-command-logs.test.tsx
index d9bc65330d..29aee65ff2 100644
--- a/__tests__/hooks/query/use-bash-command-logs.test.tsx
+++ b/__tests__/hooks/query/use-bash-command-logs.test.tsx
@@ -17,12 +17,17 @@ 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(),
- }));
+const {
+ useUserConversationMock,
+ useActiveBackendMock,
+ listOutputsMock,
+ batchGetCloudSandboxesMock,
+} = vi.hoisted(() => ({
+ useUserConversationMock: vi.fn(),
+ useActiveBackendMock: vi.fn(),
+ listOutputsMock: vi.fn(),
+ batchGetCloudSandboxesMock: vi.fn(),
+}));
vi.mock("#/hooks/query/use-user-conversation", () => ({
useUserConversation: (...args: unknown[]) => useUserConversationMock(...args),
@@ -36,6 +41,12 @@ vi.mock("#/api/bash-service/bash-service.api", () => ({
default: { listOutputs: (...args: unknown[]) => listOutputsMock(...args) },
}));
+// The sandbox lookup behind `useCloudSandbox`; the hook itself runs for real.
+vi.mock("#/api/cloud/sandbox-service.api", () => ({
+ batchGetCloudSandboxes: (...args: unknown[]) =>
+ batchGetCloudSandboxesMock(...args),
+}));
+
// ── Helpers ───────────────────────────────────────────────────────────────────
function wrapper({ children }: { children: React.ReactNode }) {
@@ -60,10 +71,38 @@ function setConversation(partial: Partial<AppConversation> | null) {
});
}
+/**
+ * What `useUserConversation(null)` really returns: a disabled query, pending
+ * forever and never loading. Script automation runs land here because they
+ * have no conversation id.
+ */
+function setNoConversation() {
+ useUserConversationMock.mockReturnValue({
+ data: undefined,
+ isFetched: false,
+ isPending: true,
+ isLoading: false,
+ });
+}
+
+const runningSandbox = {
+ id: "sb-1",
+ created_by_user_id: "user-1",
+ sandbox_spec_id: "spec-1",
+ status: "RUNNING" as const,
+ session_api_key: "sandbox-key",
+ exposed_urls: [
+ { name: "VSCODE", url: "https://vscode.example.com" },
+ { name: "AGENT_SERVER", url: "https://runtime.example.com" },
+ ],
+ created_at: "2026-01-01T00:00:00Z",
+};
+
beforeEach(() => {
useUserConversationMock.mockReset();
useActiveBackendMock.mockReset();
listOutputsMock.mockReset();
+ batchGetCloudSandboxesMock.mockReset();
});
afterEach(() => {
@@ -389,3 +428,253 @@ describe("useBashCommandLogs — local backend", () => {
expect(listOutputsMock).toHaveBeenCalledTimes(1);
});
});
+
+describe("useBashCommandLogs — cloud runs without a conversation (script automations)", () => {
+ beforeEach(() => {
+ setActiveBackend("cloud");
+ setNoConversation();
+ });
+
+ it("resolves the agent-server through the run's sandbox and fetches the logs", async () => {
+ // Arrange
+ batchGetCloudSandboxesMock.mockResolvedValue([runningSandbox]);
+ listOutputsMock.mockResolvedValue([]);
+
+ // Act
+ const { result } = renderHook(
+ () =>
+ useBashCommandLogs({
+ conversationId: null,
+ sandboxId: "sb-1",
+ bashCommandId: "cmd-1",
+ }),
+ { wrapper },
+ );
+
+ // Assert
+ await waitFor(() => expect(listOutputsMock).toHaveBeenCalledTimes(1));
+ expect(batchGetCloudSandboxesMock).toHaveBeenCalledWith(["sb-1"]);
+ expect(listOutputsMock).toHaveBeenCalledWith(
+ "https://runtime.example.com",
+ "sandbox-key",
+ "cmd-1",
+ );
+ expect(result.current.isResolvingConversation).toBe(false);
+ expect(result.current.sandboxIssue).toBeNull();
+ expect(result.current.conversationMissing).toBe(false);
+ });
+
+ it("reports the runtime as resolving while the sandbox lookup is in flight", async () => {
+ // Arrange: a lookup that never answers.
+ batchGetCloudSandboxesMock.mockReturnValue(new Promise(() => {}));
+
+ // Act
+ const { result } = renderHook(
+ () =>
+ useBashCommandLogs({
+ conversationId: null,
+ sandboxId: "sb-1",
+ bashCommandId: "cmd-1",
+ }),
+ { wrapper },
+ );
+
+ // Assert
+ await waitFor(() =>
+ expect(result.current.isResolvingConversation).toBe(true),
+ );
+ expect(result.current.sandboxIssue).toBeNull();
+ expect(listOutputsMock).not.toHaveBeenCalled();
+ });
+
+ it("reports sandboxIssue=missing and skips the fetch when the sandbox is gone", async () => {
+ // Arrange: the lookup returns null for a deleted (or foreign) sandbox.
+ batchGetCloudSandboxesMock.mockResolvedValue([null]);
+
+ // Act
+ const { result } = renderHook(
+ () =>
+ useBashCommandLogs({
+ conversationId: null,
+ sandboxId: "sb-1",
+ bashCommandId: "cmd-1",
+ }),
+ { wrapper },
+ );
+
+ // Assert
+ await waitFor(() => expect(result.current.sandboxIssue).toBe("missing"));
+ expect(result.current.isResolvingConversation).toBe(false);
+ expect(listOutputsMock).not.toHaveBeenCalled();
+ });
+
+ it.each([
+ { status: "PAUSED" as const, issue: "paused" },
+ { status: "STARTING" as const, issue: "starting" },
+ { status: "ERROR" as const, issue: "errored" },
+ { status: "MISSING" as const, issue: "missing" },
+ ])(
+ "reports sandboxIssue=$issue and skips the fetch when the sandbox is $status",
+ async ({ status, issue }) => {
+ // Arrange
+ batchGetCloudSandboxesMock.mockResolvedValue([
+ { ...runningSandbox, status },
+ ]);
+
+ // Act
+ const { result } = renderHook(
+ () =>
+ useBashCommandLogs({
+ conversationId: null,
+ sandboxId: "sb-1",
+ bashCommandId: "cmd-1",
+ }),
+ { wrapper },
+ );
+
+ // Assert
+ await waitFor(() => expect(result.current.sandboxIssue).toBe(issue));
+ expect(listOutputsMock).not.toHaveBeenCalled();
+ },
+ );
+
+ it("reports sandboxIssue=missing when the sandbox exposes no agent-server URL", async () => {
+ // Arrange
+ batchGetCloudSandboxesMock.mockResolvedValue([
+ { ...runningSandbox, exposed_urls: [] },
+ ]);
+
+ // Act
+ const { result } = renderHook(
+ () =>
+ useBashCommandLogs({
+ conversationId: null,
+ sandboxId: "sb-1",
+ bashCommandId: "cmd-1",
+ }),
+ { wrapper },
+ );
+
+ // Assert
+ await waitFor(() => expect(result.current.sandboxIssue).toBe("missing"));
+ expect(listOutputsMock).not.toHaveBeenCalled();
+ });
+
+ it("reports sandboxIssue=unreachable when the sandbox lookup itself fails", async () => {
+ // Arrange
+ batchGetCloudSandboxesMock.mockRejectedValue(new Error("boom"));
+
+ // Act
+ const { result } = renderHook(
+ () =>
+ useBashCommandLogs({
+ conversationId: null,
+ sandboxId: "sb-1",
+ bashCommandId: "cmd-1",
+ }),
+ { wrapper },
+ );
+
+ // Assert
+ await waitFor(() =>
+ expect(result.current.sandboxIssue).toBe("unreachable"),
+ );
+ expect(listOutputsMock).not.toHaveBeenCalled();
+ });
+
+ it("reports sandboxIssue=missing at once for a run with neither a conversation nor a sandbox", () => {
+ // Act
+ const { result } = renderHook(
+ () =>
+ useBashCommandLogs({
+ conversationId: null,
+ sandboxId: null,
+ bashCommandId: "cmd-1",
+ }),
+ { wrapper },
+ );
+
+ // Assert: nothing to wait for, nothing to ask.
+ expect(result.current.isResolvingConversation).toBe(false);
+ expect(result.current.sandboxIssue).toBe("missing");
+ expect(batchGetCloudSandboxesMock).not.toHaveBeenCalled();
+ expect(listOutputsMock).not.toHaveBeenCalled();
+ });
+
+ it("does not look up the sandbox while the modal is closed", () => {
+ // Act
+ const { result } = renderHook(
+ () =>
+ useBashCommandLogs({
+ conversationId: null,
+ sandboxId: "sb-1",
+ bashCommandId: "cmd-1",
+ enabled: false,
+ }),
+ { wrapper },
+ );
+
+ // Assert
+ expect(batchGetCloudSandboxesMock).not.toHaveBeenCalled();
+ expect(result.current.isResolvingConversation).toBe(false);
+ expect(result.current.sandboxIssue).toBeNull();
+ });
+
+ it("keeps the conversation as the runtime source when the run has one", async () => {
+ // Arrange
+ setConversation({
+ conversation_url: "https://runtime.example.com/api/conversations/c1",
+ session_api_key: "conversation-key",
+ sandbox_status: "RUNNING",
+ });
+ listOutputsMock.mockResolvedValue([]);
+
+ // Act
+ renderHook(
+ () =>
+ useBashCommandLogs({
+ conversationId: "conv-1",
+ sandboxId: "sb-1",
+ bashCommandId: "cmd-1",
+ }),
+ { wrapper },
+ );
+
+ // Assert
+ await waitFor(() => expect(listOutputsMock).toHaveBeenCalledTimes(1));
+ expect(listOutputsMock).toHaveBeenCalledWith(
+ "https://runtime.example.com/api/conversations/c1",
+ "conversation-key",
+ "cmd-1",
+ );
+ expect(batchGetCloudSandboxesMock).not.toHaveBeenCalled();
+ });
+});
+
+describe("useBashCommandLogs — local runs without a conversation", () => {
+ beforeEach(() => {
+ setActiveBackend("local");
+ setNoConversation();
+ });
+
+ it("fetches through the backend host without a sandbox lookup", async () => {
+ // Arrange
+ listOutputsMock.mockResolvedValue([]);
+
+ // Act
+ renderHook(
+ () =>
+ useBashCommandLogs({
+ conversationId: null,
+ sandboxId: "sb-1",
+ bashCommandId: "cmd-1",
+ }),
+ { wrapper },
+ );
+
+ // Assert
+ await waitFor(() => expect(listOutputsMock).toHaveBeenCalledTimes(1));
+ expect(listOutputsMock).toHaveBeenCalledWith(null, null, "cmd-1");
+ expect(batchGetCloudSandboxesMock).not.toHaveBeenCalled();
+ });
+});
diff --git a/__tests__/routes/automation-detail.test.tsx b/__tests__/routes/automation-detail.test.tsx
index 53ace9b610..420f40b961 100644
--- a/__tests__/routes/automation-detail.test.tsx
+++ b/__tests__/routes/automation-detail.test.tsx
@@ -21,6 +21,7 @@ import AutomationDetail from "#/routes/automation-detail";
import type { Backend } from "#/api/backend-registry/types";
import { AutomationRunStatus } from "#/types/automation";
import type { Automation, AutomationRunsResponse } from "#/types/automation";
+import { packTarGzip } from "#/utils/tar-gzip";
vi.mock("#/api/automation-service/automation-service.api", () => ({
default: {
@@ -29,6 +30,7 @@ vi.mock("#/api/automation-service/automation-service.api", () => ({
toggleAutomation: vi.fn(),
deleteAutomation: vi.fn(),
dispatchAutomation: vi.fn(),
+ fetchTarballBytes: vi.fn(),
checkHealth: vi.fn(),
},
}));
@@ -391,3 +393,32 @@ describe("AutomationDetail — disabled reason banner", () => {
).not.toBeInTheDocument();
});
});
+
+describe("AutomationDetail — script automations", () => {
+ it("shows the bundle's script in place of the prompt for an automation without a prompt", async () => {
+ // Arrange
+ setRegisteredBackends([localBackend]);
+ setActiveSelection({ backendId: localBackend.id });
+ vi.mocked(AutomationService.getAutomation).mockResolvedValue({
+ ...automation,
+ prompt: null,
+ entrypoint: "python main.py",
+ });
+ vi.mocked(AutomationService.fetchTarballBytes).mockResolvedValue(
+ new Uint8Array(
+ await packTarGzip([{ name: "main.py", content: "print('hi')\n" }]),
+ ),
+ );
+
+ // Act
+ renderDetail();
+
+ // Assert
+ expect(
+ await screen.findByTestId("automation-script-file"),
+ ).toHaveTextContent("main.py");
+ expect(
+ screen.queryByTestId("automation-prompt-content"),
+ ).not.toBeInTheDocument();
+ });
+});
diff --git a/__tests__/utils/tar-unpack.test.ts b/__tests__/utils/tar-unpack.test.ts
new file mode 100644
index 0000000000..7716d46280
--- /dev/null
+++ b/__tests__/utils/tar-unpack.test.ts
@@ -0,0 +1,122 @@
+import { describe, expect, it } from "vitest";
+import { packTar, packTarGzip } from "#/utils/tar-gzip";
+import {
+ TarFormatError,
+ TarTooLargeError,
+ unpackTarGzip,
+} from "#/utils/tar-unpack";
+
+const files = [
+ { name: "main.py", content: "print('hi')\n" },
+ { name: "lib/util.py", content: "x = 1\n" },
+ { name: "setup.sh", content: "#!/bin/sh\n", mode: 0o755 },
+];
+const budget = { maxTotalBytes: 1024 * 1024 };
+
+/** ustar header field offsets, as `packTar` writes them. */
+const TYPEFLAG_OFFSET = 156;
+const PREFIX_OFFSET = 345;
+
+describe("unpackTarGzip", () => {
+ it("reads the files back out of a gzipped bundle", async () => {
+ // Arrange
+ const archive = new Uint8Array(await packTarGzip(files));
+
+ // Act
+ const entries = await unpackTarGzip(archive, budget);
+
+ // Assert
+ expect(entries).toEqual([
+ { path: "main.py", size: 12, text: "print('hi')\n" },
+ { path: "lib/util.py", size: 6, text: "x = 1\n" },
+ { path: "setup.sh", size: 10, text: "#!/bin/sh\n" },
+ ]);
+ });
+
+ it("reads an uncompressed tar as well", async () => {
+ // Act
+ const entries = await unpackTarGzip(packTar(files), budget);
+
+ // Assert
+ expect(entries.map((entry) => entry.path)).toEqual([
+ "main.py",
+ "lib/util.py",
+ "setup.sh",
+ ]);
+ });
+
+ it("strips a leading ./ from member names", async () => {
+ // Act
+ const entries = await unpackTarGzip(
+ packTar([{ name: "./main.py", content: "1" }]),
+ budget,
+ );
+
+ // Assert
+ expect(entries[0].path).toBe("main.py");
+ });
+
+ it("joins the ustar prefix field onto the name", async () => {
+ // Arrange: a header whose directory part lives in the prefix field.
+ const archive = packTar([{ name: "util.py", content: "1" }]);
+ archive.set(new TextEncoder().encode("lib"), PREFIX_OFFSET);
+
+ // Act
+ const entries = await unpackTarGzip(archive, budget);
+
+ // Assert
+ expect(entries[0].path).toBe("lib/util.py");
+ });
+
+ it("skips members that are not regular files", async () => {
+ // Arrange: mark the first member as a directory.
+ const archive = packTar([
+ { name: "lib", content: "" },
+ { name: "main.py", content: "1" },
+ ]);
+ archive[TYPEFLAG_OFFSET] = "5".charCodeAt(0);
+
+ // Act
+ const entries = await unpackTarGzip(archive, budget);
+
+ // Assert
+ expect(entries.map((entry) => entry.path)).toEqual(["main.py"]);
+ });
+
+ it("marks content that is not UTF-8 as binary", async () => {
+ // Arrange: overwrite the member's bytes with an invalid sequence.
+ const archive = packTar([{ name: "model.bin", content: "AAAA" }]);
+ archive.fill(0xff, 512, 516);
+
+ // Act
+ const entries = await unpackTarGzip(archive, budget);
+
+ // Assert
+ expect(entries).toEqual([{ path: "model.bin", size: 4, text: null }]);
+ });
+
+ it("returns no entries for an empty archive", async () => {
+ // Act
+ const entries = await unpackTarGzip(packTar([]), budget);
+
+ // Assert
+ expect(entries).toEqual([]);
+ });
+
+ it("rejects bytes that are not an archive", async () => {
+ // Arrange: an error page instead of a tarball.
+ const html = new TextEncoder().encode("<html>".padEnd(1024, "x"));
+
+ // Act + Assert
+ await expect(
+ unpackTarGzip(new Uint8Array(html), budget),
+ ).rejects.toBeInstanceOf(TarFormatError);
+ });
+
+ it("rejects an archive that unpacks past the size budget", async () => {
+ // Act + Assert
+ await expect(
+ unpackTarGzip(packTar(files), { maxTotalBytes: 20 }),
+ ).rejects.toBeInstanceOf(TarTooLargeError);
+ });
+});
diff --git a/src/api/automation-service/automation-service.api.ts b/src/api/automation-service/automation-service.api.ts
index e7b796d2a8..78588b192b 100644
--- a/src/api/automation-service/automation-service.api.ts
+++ b/src/api/automation-service/automation-service.api.ts
@@ -35,6 +35,7 @@ import type {
SetupRequestBody,
ValidateDraftResponse,
} from "#/manifests/types";
+import { downloadBlob } from "#/utils/utils";
import type { Backend, ResolvedActiveBackend } from "../backend-registry/types";
import {
getActiveBackend,
@@ -502,32 +503,34 @@ class AutomationService {
return AutomationService.updateAutomation(id, { enabled });
}
- static async downloadTarball(id: string, name: string): Promise<void> {
+ /** The automation's bundle as the service stores it: (gzipped) tar bytes. */
+ static async fetchTarballBytes(id: string): Promise<Uint8Array<ArrayBuffer>> {
const active = getActiveBackend().backend;
const path = `${AUTOMATION_BASE_PATH}${getAutomationIdEndpoint("tarball", id)}`;
- let blob: Blob;
if (active.kind === "cloud") {
- blob = await callCloudProxy<Blob>({
+ const buffer = await callCloudProxy<ArrayBuffer>({
backend: active,
method: "GET",
path,
- responseType: "blob",
+ responseType: "arrayBuffer",
headers: await buildAutomationRequestHeaders(),
});
- } else {
- const { data } = await localAutomationAxios.get<Blob>(path, {
- responseType: "blob",
- });
- blob = data;
+ return new Uint8Array(buffer);
}
- const url = URL.createObjectURL(blob);
- const a = document.createElement("a");
- a.href = url;
- a.download = `${name}.tar`;
- a.click();
- URL.revokeObjectURL(url);
+ const { data } = await localAutomationAxios.get<ArrayBuffer>(path, {
+ responseType: "arraybuffer",
+ });
+ return new Uint8Array(data);
+ }
+
+ static async downloadTarball(id: string, name: string): Promise<void> {
+ const bytes = await AutomationService.fetchTarballBytes(id);
+ downloadBlob(
+ new Blob([bytes], { type: "application/x-tar" }),
+ `${name}.tar`,
+ );
}
/**
diff --git a/src/api/cloud/proxy.ts b/src/api/cloud/proxy.ts
index f35ad63c2c..27cb6c9c6b 100644
--- a/src/api/cloud/proxy.ts
+++ b/src/api/cloud/proxy.ts
@@ -12,7 +12,7 @@ export interface CloudProxyRequest {
hostOverride?: string;
authMode?: "bearer" | "session-api-key" | "none";
sessionApiKey?: string | null;
- responseType?: "blob";
+ responseType?: "blob" | "arrayBuffer";
}
export async function callCloudProxy<TResponse = unknown>(
diff --git a/src/components/features/automations/detail/activity-log-item.tsx b/src/components/features/automations/detail/activity-log-item.tsx
index c7b45ae4dd..9ec8f4ed12 100644
--- a/src/components/features/automations/detail/activity-log-item.tsx
+++ b/src/components/features/automations/detail/activity-log-item.tsx
@@ -116,7 +116,13 @@ export function ActivityLogItem({ run, automation }: ActivityLogItemProps) {
<span className="text-sm text-content">{formattedTimestamp}</span>
{showNoConversationLabel && (
<span className="text-xs text-muted">
- {t(I18nKey.AUTOMATIONS$DETAIL$NO_CONVERSATION)}
+ {t(
+ hasBashCommand
+ ? // A command ran but no agent did: a script automation.
+ // Point at the logs button, the only place its output is.
+ I18nKey.AUTOMATIONS$DETAIL$SCRIPT_RUN_NO_CONVERSATION
+ : I18nKey.AUTOMATIONS$DETAIL$NO_CONVERSATION,
+ )}
</span>
)}
</div>
@@ -170,6 +176,7 @@ export function ActivityLogItem({ run, automation }: ActivityLogItemProps) {
{hasBashCommand && (
<RunLogsModal
conversationId={run.conversation_id}
+ sandboxId={run.sandbox_id ?? null}
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.tsx
index f174847b32..89a0ad0987 100644
--- a/src/components/features/automations/detail/run-logs-modal.tsx
+++ b/src/components/features/automations/detail/run-logs-modal.tsx
@@ -36,6 +36,11 @@ type LogTab = "stdout" | "stderr";
interface RunLogsModalProps {
/** Conversation that owns the bash command. */
conversationId: string | null;
+ /**
+ * Cloud sandbox that ran the command; the runtime handle for runs with
+ * no conversation (script automations).
+ */
+ sandboxId?: string | null;
/** Bash command id to fetch logs for. */
bashCommandId: string | null;
isOpen: boolean;
@@ -188,6 +193,7 @@ function RunInspectionSummary({ run }: { run: AutomationRun | undefined }) {
export function RunLogsModal({
conversationId,
+ sandboxId,
bashCommandId,
isOpen,
onClose,
@@ -206,6 +212,7 @@ export function RunLogsModal({
error,
} = useBashCommandLogs({
conversationId,
+ sandboxId,
bashCommandId,
enabled: isOpen,
});
diff --git a/src/components/features/automations/detail/script-section.tsx b/src/components/features/automations/detail/script-section.tsx
new file mode 100644
index 0000000000..6822391f1c
--- /dev/null
+++ b/src/components/features/automations/detail/script-section.tsx
@@ -0,0 +1,127 @@
+import { useTranslation } from "react-i18next";
+import { I18nKey } from "#/i18n/declaration";
+import TerminalIcon from "#/icons/terminal.svg?react";
+import { HighlightedSourceView } from "#/components/features/files-tab/highlighted-source-view";
+import { useAutomationTarballFiles } from "#/hooks/query/use-automation-tarball-files";
+import type { Automation } from "#/types/automation";
+import type { TarEntry } from "#/utils/tar-unpack";
+import { SectionCard } from "./section-card";
+
+interface ScriptSectionProps {
+ automation: Automation;
+}
+
+/**
+ * The bundle member the entrypoint runs, if it names one: the first token
+ * of the command that is a file in the archive (`python main.py` → `main.py`).
+ */
+function findEntrypointPath(
+ entrypoint: string | undefined,
+ entries: TarEntry[],
+): string | null {
+ if (!entrypoint) return null;
+ const paths = new Set(entries.map((entry) => entry.path));
+ for (const token of entrypoint.split(/\s+/)) {
+ const candidate = token.replace(/^\.\//, "");
+ if (paths.has(candidate)) return candidate;
+ }
+ return null;
+}
+
+/** Entrypoint first, then the rest by path. */
+function orderEntries(
+ entries: TarEntry[],
+ entrypointPath: string | null,
+): TarEntry[] {
+ return [...entries].sort((a, b) => {
+ if (a.path === entrypointPath) return -1;
+ if (b.path === entrypointPath) return 1;
+ return a.path.localeCompare(b.path);
+ });
+}
+
+/**
+ * What a script automation runs: the files of its uploaded bundle, read
+ * back from the same tarball the kebab menu offers for download. Takes the
+ * place of the prompt section for automations that have no prompt.
+ */
+export function ScriptSection({ automation }: ScriptSectionProps) {
+ const { t } = useTranslation("openhands");
+ const {
+ data: entries,
+ isPending,
+ isError,
+ } = useAutomationTarballFiles(automation);
+
+ const entrypointPath = findEntrypointPath(
+ automation.entrypoint,
+ entries ?? [],
+ );
+ // A bundle the service can't hand back (external URL, deleted upload) or
+ // that isn't an archive gets the same answer: download it instead.
+ const unavailable = isError || entries?.length === 0;
+
+ return (
+ <SectionCard
+ icon={<TerminalIcon className="size-4" />}
+ title={t(I18nKey.AUTOMATIONS$DETAIL$SCRIPT)}
+ >
+ <div className="flex flex-col gap-4">
+ {automation.entrypoint ? (
+ <code
+ data-testid="automation-script-entrypoint"
+ className="self-start rounded-md bg-surface-raised px-2 py-1 font-mono text-xs text-content"
+ >
+ {automation.entrypoint}
+ </code>
+ ) : null}
+
+ {isPending ? (
+ <p className="text-sm italic text-muted">
+ {t(I18nKey.AUTOMATIONS$DETAIL$SCRIPT_LOADING)}
+ </p>
+ ) : null}
+
+ {unavailable ? (
+ <p
+ data-testid="automation-script-unavailable"
+ className="text-sm text-muted"
+ >
+ {t(I18nKey.AUTOMATIONS$DETAIL$SCRIPT_UNAVAILABLE)}
+ </p>
+ ) : null}
+
+ {entries && entries.length > 0
+ ? orderEntries(entries, entrypointPath).map((entry) => (
+ <div
+ key={entry.path}
+ data-testid="automation-script-file"
+ className="overflow-hidden rounded-lg border border-[var(--oh-border)]"
+ >
+ <div className="flex items-center gap-2 border-b border-[var(--oh-border)] bg-black/20 px-3 py-2 font-mono text-xs text-content">
+ <span className="truncate">{entry.path}</span>
+ {entry.path === entrypointPath ? (
+ <span className="shrink-0 rounded-md bg-surface-raised px-2 py-0.5 text-[10px] font-medium text-muted">
+ {t(I18nKey.AUTOMATIONS$DETAIL$SCRIPT_ENTRYPOINT)}
+ </span>
+ ) : null}
+ </div>
+ {entry.text === null ? (
+ <p className="px-3 py-2 text-xs italic text-muted">
+ {t(I18nKey.AUTOMATIONS$DETAIL$SCRIPT_BINARY_FILE)}
+ </p>
+ ) : (
+ <div className="max-h-96 overflow-auto">
+ <HighlightedSourceView
+ path={entry.path}
+ text={entry.text}
+ />
+ </div>
+ )}
+ </div>
+ ))
+ : null}
+ </div>
+ </SectionCard>
+ );
+}
diff --git a/src/hooks/query/use-automation-tarball-files.ts b/src/hooks/query/use-automation-tarball-files.ts
new file mode 100644
index 0000000000..d139898d67
--- /dev/null
+++ b/src/hooks/query/use-automation-tarball-files.ts
@@ -0,0 +1,45 @@
+import { useQuery } from "@tanstack/react-query";
+import AutomationService from "#/api/automation-service/automation-service.api";
+import { useActiveBackend } from "#/contexts/active-backend-context";
+import type { Automation } from "#/types/automation";
+import { unpackTarGzip } from "#/utils/tar-unpack";
+
+export const AUTOMATION_TARBALL_FILES_QUERY_KEY = [
+ "automation-tarball-files",
+] as const;
+
+/** Bundles that unpack to more than this are reported as unavailable. */
+const MAX_UNPACKED_BYTES = 16 * 1024 * 1024;
+
+/**
+ * The files inside an automation's uploaded bundle, read back from the
+ * service's tarball endpoint so the detail page can show what a script
+ * automation runs. `updated_at` is part of the key: an edit that replaces
+ * the bundle changes it, so the stale unpack is not reused.
+ *
+ * Errors are the section's to render (the endpoint answers 404 for a
+ * deleted upload and 422 for an externally hosted bundle), so the global
+ * toast is disabled.
+ */
+export function useAutomationTarballFiles(
+ automation: Pick<Automation, "id" | "updated_at">,
+) {
+ const active = useActiveBackend();
+ return useQuery({
+ queryKey: [
+ ...AUTOMATION_TARBALL_FILES_QUERY_KEY,
+ automation.id,
+ automation.updated_at,
+ active.backend.id,
+ active.orgId,
+ ],
+ queryFn: async () =>
+ unpackTarGzip(await AutomationService.fetchTarballBytes(automation.id), {
+ maxTotalBytes: MAX_UNPACKED_BYTES,
+ }),
+ staleTime: 5 * 60 * 1000,
+ retry: false,
+ enabled: !!automation.id,
+ meta: { disableToast: true },
+ });
+}
diff --git a/src/hooks/query/use-bash-command-logs.ts b/src/hooks/query/use-bash-command-logs.ts
index 8adbbb9e86..7ff03e49b2 100644
--- a/src/hooks/query/use-bash-command-logs.ts
+++ b/src/hooks/query/use-bash-command-logs.ts
@@ -4,6 +4,7 @@ import { isSdkHttpError } from "#/api/agent-server-compatibility";
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 { useCloudSandbox } from "./use-cloud-sandbox";
import { useUserConversation } from "./use-user-conversation";
export const BASH_COMMAND_LOGS_QUERY_KEY = ["bash-command-logs"] as const;
@@ -28,10 +29,29 @@ interface UseBashCommandLogsOptions {
* fire requests at known-unreachable sandboxes.
*/
conversationId: string | null | undefined;
+ /**
+ * The cloud sandbox that ran the command. Script automations never
+ * create a conversation, so on cloud backends this is the only handle
+ * to their agent-server: its `AGENT_SERVER` exposed URL and
+ * `session_api_key` stand in for the conversation's `conversation_url`
+ * and `session_api_key`. Ignored when a conversation id is given, and
+ * on local backends.
+ */
+ sandboxId?: string | null;
bashCommandId: string | null | undefined;
enabled?: boolean;
}
+/** Name of the agent-server entry in a cloud sandbox's `exposed_urls`. */
+const AGENT_SERVER_EXPOSED_URL_NAME = "AGENT_SERVER";
+
+/** The agent-server that holds the command's events, however it was found. */
+interface RuntimeTarget {
+ url: string | null;
+ sessionApiKey: string | null;
+ sandboxStatus: SandboxStatus | null;
+}
+
/**
* Map a cloud sandbox status to a stable issue code (or null when the
* sandbox is healthy enough to attempt the fetch).
@@ -107,48 +127,103 @@ function classifyFetchError(error: unknown): SandboxIssue | null {
* 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`.
+ * - **Cloud backend**: the run's agent-server is found through its
+ * conversation when it has one, and through its sandbox otherwise
+ * (script automations never create a conversation). Either lookup
+ * pre-checks the sandbox status and the existence of a runtime 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). A run
+ * with neither handle reports `missing` at once. 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 { conversationId, sandboxId, bashCommandId, enabled = true } = options;
const active = useActiveBackend();
- // Only resolve the conversation when the modal is open. RunLogsModal mounts
+ const isCloud = active.backend.kind === "cloud";
+
+ // Only resolve the runtime when the modal is open. RunLogsModal mounts
// (closed) for every activity-log row, so an unconditional lookup would fire
// one /api/conversations request per row on page load. Passing null when
- // disabled trips useUserConversation's own `!!cid` gate.
+ // disabled trips each lookup hook's own `!!id` gate.
+ const viaConversation = enabled && !!conversationId;
+ const viaSandbox = enabled && isCloud && !viaConversation && !!sandboxId;
const conversationQuery = useUserConversation(
- enabled ? (conversationId ?? null) : null,
+ viaConversation ? (conversationId as string) : null,
);
+ const sandboxQuery = useCloudSandbox(viaSandbox ? sandboxId : 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 runtime: RuntimeTarget | null = null;
+ let isResolvingRuntime = false;
let conversationMissing = false;
- if (isCloud && conversationFetched) {
- if (!conversation) {
- conversationMissing = true;
- } else {
- preflightIssue =
- sandboxIssueFromStatus(conversation.sandbox_status) ??
- (!conversation.conversation_url ? "missing" : null);
+ let preflightIssue: SandboxIssue | null = null;
+
+ if (!isCloud) {
+ // Local backends don't carry sandbox_status, and the agent-server hosts
+ // events under a single root so there's nothing to gate on.
+ runtime = {
+ url: conversation?.conversation_url ?? null,
+ sessionApiKey: conversation?.session_api_key ?? null,
+ sandboxStatus: null,
+ };
+ } else if (viaConversation) {
+ // `isLoading`, not `isPending`: a query that is disabled — including
+ // when `useUserConversation` disables itself — stays `pending` forever
+ // without ever fetching, and reporting that as "resolving" is what left
+ // the modal loading with no request in flight.
+ isResolvingRuntime = conversationQuery.isLoading;
+ if (conversationQuery.isFetched) {
+ if (!conversation) {
+ conversationMissing = true;
+ } else {
+ runtime = {
+ url: conversation.conversation_url ?? null,
+ sessionApiKey: conversation.session_api_key ?? null,
+ sandboxStatus: conversation.sandbox_status ?? null,
+ };
+ }
}
+ } else if (viaSandbox) {
+ isResolvingRuntime = sandboxQuery.isLoading;
+ if (sandboxQuery.isFetched) {
+ const sandbox = sandboxQuery.data;
+ if (sandboxQuery.isError) {
+ preflightIssue = "unreachable";
+ } else if (!sandbox) {
+ // Deleted, or created by someone else: the lookup only returns the
+ // caller's own sandboxes.
+ preflightIssue = "missing";
+ } else {
+ runtime = {
+ url:
+ sandbox.exposed_urls?.find(
+ (exposed) => exposed.name === AGENT_SERVER_EXPOSED_URL_NAME,
+ )?.url ?? null,
+ sessionApiKey: sandbox.session_api_key,
+ sandboxStatus: sandbox.status,
+ };
+ }
+ }
+ } else if (enabled) {
+ // Neither a conversation nor a sandbox to ask: nothing to load, and
+ // nothing to wait for.
+ preflightIssue = "missing";
}
- // Cloud needs the conversation URL before it can talk to the
- // runtime; local does not.
- const hasRequiredAuth = isCloud ? !!conversationUrl : true;
+ if (isCloud && runtime && !preflightIssue) {
+ preflightIssue =
+ sandboxIssueFromStatus(runtime.sandboxStatus) ??
+ (!runtime.url ? "missing" : null);
+ }
+
+ const runtimeUrl = runtime?.url ?? null;
+ const sessionApiKey = runtime?.sessionApiKey ?? null;
+
+ // Cloud needs the runtime URL before it can talk to the agent-server;
+ // local does not.
+ const hasRequiredAuth = isCloud ? !!runtimeUrl : true;
const canFire =
enabled &&
!!bashCommandId &&
@@ -160,14 +235,14 @@ export function useBashCommandLogs(options: UseBashCommandLogsOptions) {
queryKey: [
...BASH_COMMAND_LOGS_QUERY_KEY,
bashCommandId,
- conversationUrl,
+ runtimeUrl,
sessionApiKey,
active.backend.id,
active.orgId,
],
queryFn: () =>
BashService.listOutputs(
- conversationUrl,
+ runtimeUrl,
sessionApiKey,
bashCommandId as string,
),
@@ -195,8 +270,11 @@ export function useBashCommandLogs(options: UseBashCommandLogsOptions) {
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,
+ /**
+ * True while we're still resolving the runtime URL through the
+ * conversation or, failing that, the sandbox.
+ */
+ isResolvingConversation: isResolvingRuntime,
/** Cloud-only: conversation lookup failed (deleted or no access). */
conversationMissing,
/**
diff --git a/src/i18n/translation.json b/src/i18n/translation.json
index 7f1d88d892..4e5d1565cd 100644
--- a/src/i18n/translation.json
+++ b/src/i18n/translation.json
@@ -14621,6 +14621,23 @@
"uk": "Немає розмови",
"ca": "Sense conversa"
},
+ "AUTOMATIONS$DETAIL$SCRIPT_RUN_NO_CONVERSATION": {
+ "en": "No conversation — this run executed a script. Use View logs for its output.",
+ "ja": "会話なし — この実行はスクリプトを実行しました。出力は「ログを表示」で確認してください。",
+ "zh-CN": "无对话 — 此次运行执行了脚本。请使用“查看日志”查看其输出。",
+ "zh-TW": "無對話 — 此次執行執行了指令碼。請使用「查看日誌」查看其輸出。",
+ "ko-KR": "대화 없음 — 이 실행은 스크립트를 실행했습니다. 출력은 로그 보기에서 확인하세요.",
+ "no": "Ingen samtale — denne kjøringen kjørte et skript. Bruk Vis logger for å se utdataene.",
+ "it": "Nessuna conversazione — questa esecuzione ha eseguito uno script. Usa Visualizza log per vederne l'output.",
+ "pt": "Sem conversa — esta execução executou um script. Use Ver registos para ver a saída.",
+ "es": "Sin conversación — esta ejecución ejecutó un script. Usa Ver registros para ver su salida.",
+ "ar": "لا توجد محادثة — نفّذ هذا التشغيل سكربتًا. استخدم عرض السجلات لرؤية مخرجاته.",
+ "fr": "Aucune conversation — cette exécution a lancé un script. Utilisez Afficher les journaux pour voir sa sortie.",
+ "tr": "Konuşma yok — bu çalıştırma bir betik çalıştırdı. Çıktısı için Günlükleri görüntüle'yi kullanın.",
+ "de": "Keine Konversation — diese Ausführung hat ein Skript ausgeführt. Verwende Protokolle anzeigen für die Ausgabe.",
+ "uk": "Немає розмови — цей запуск виконав скрипт. Скористайтеся Переглянути журнали, щоб побачити його вивід.",
+ "ca": "Sense conversa — aquesta execució ha executat un script. Utilitza Mostra els registres per veure'n la sortida."
+ },
"AUTOMATIONS$DETAIL$LOGS_VIEW": {
"en": "View logs for run on {{timestamp}}",
"ja": "{{timestamp}} の実行ログを表示",
@@ -15080,6 +15097,91 @@
"uk": "Запит",
"ca": "Indicació"
},
+ "AUTOMATIONS$DETAIL$SCRIPT": {
+ "en": "Script",
+ "ja": "スクリプト",
+ "zh-CN": "脚本",
+ "zh-TW": "指令碼",
+ "ko-KR": "스크립트",
+ "no": "Skript",
+ "it": "Script",
+ "pt": "Script",
+ "es": "Script",
+ "ar": "السكربت",
+ "fr": "Script",
+ "tr": "Betik",
+ "de": "Skript",
+ "uk": "Скрипт",
+ "ca": "Script"
+ },
+ "AUTOMATIONS$DETAIL$SCRIPT_ENTRYPOINT": {
+ "en": "Entrypoint",
+ "ja": "エントリーポイント",
+ "zh-CN": "入口点",
+ "zh-TW": "進入點",
+ "ko-KR": "진입점",
+ "no": "Startpunkt",
+ "it": "Punto di ingresso",
+ "pt": "Ponto de entrada",
+ "es": "Punto de entrada",
+ "ar": "نقطة الدخول",
+ "fr": "Point d'entrée",
+ "tr": "Giriş noktası",
+ "de": "Einstiegspunkt",
+ "uk": "Точка входу",
+ "ca": "Punt d'entrada"
+ },
+ "AUTOMATIONS$DETAIL$SCRIPT_LOADING": {
+ "en": "Loading script…",
+ "ja": "スクリプトを読み込み中…",
+ "zh-CN": "正在加载脚本…",
+ "zh-TW": "正在載入指令碼…",
+ "ko-KR": "스크립트를 불러오는 중…",
+ "no": "Laster skript…",
+ "it": "Caricamento dello script…",
+ "pt": "A carregar script…",
+ "es": "Cargando script…",
+ "ar": "جارٍ تحميل السكربت…",
+ "fr": "Chargement du script…",
+ "tr": "Betik yükleniyor…",
+ "de": "Skript wird geladen…",
+ "uk": "Завантаження скрипту…",
+ "ca": "S'està carregant l'script…"
+ },
+ "AUTOMATIONS$DETAIL$SCRIPT_UNAVAILABLE": {
+ "en": "The script bundle can't be shown here. Use Tarball in the menu to download it.",
+ "ja": "スクリプトバンドルをここに表示できません。メニューの「Tarball」からダウンロードしてください。",
+ "zh-CN": "无法在此显示脚本包。请使用菜单中的“Tarball”下载。",
+ "zh-TW": "無法在此顯示指令碼套件。請使用選單中的「Tarball」下載。",
+ "ko-KR": "스크립트 번들을 여기에 표시할 수 없습니다. 메뉴의 Tarball로 다운로드하세요.",
+ "no": "Skriptpakken kan ikke vises her. Bruk Tarball i menyen for å laste den ned.",
+ "it": "Il bundle dello script non può essere mostrato qui. Usa Tarball nel menu per scaricarlo.",
+ "pt": "O pacote do script não pode ser mostrado aqui. Use Tarball no menu para o transferir.",
+ "es": "El paquete del script no se puede mostrar aquí. Usa Tarball en el menú para descargarlo.",
+ "ar": "لا يمكن عرض حزمة السكربت هنا. استخدم Tarball في القائمة لتنزيلها.",
+ "fr": "Le bundle du script ne peut pas être affiché ici. Utilisez Tarball dans le menu pour le télécharger.",
+ "tr": "Betik paketi burada gösterilemiyor. İndirmek için menüdeki Tarball'ı kullanın.",
+ "de": "Das Skript-Bundle kann hier nicht angezeigt werden. Verwende Tarball im Menü, um es herunterzuladen.",
+ "uk": "Пакет скрипту неможливо показати тут. Скористайтеся Tarball у меню, щоб завантажити його.",
+ "ca": "El paquet de l'script no es pot mostrar aquí. Utilitza Tarball al menú per descarregar-lo."
+ },
+ "AUTOMATIONS$DETAIL$SCRIPT_BINARY_FILE": {
+ "en": "Binary file",
+ "ja": "バイナリファイル",
+ "zh-CN": "二进制文件",
+ "zh-TW": "二進位檔案",
+ "ko-KR": "바이너리 파일",
+ "no": "Binærfil",
+ "it": "File binario",
+ "pt": "Ficheiro binário",
+ "es": "Archivo binario",
+ "ar": "ملف ثنائي",
+ "fr": "Fichier binaire",
+ "tr": "İkili dosya",
+ "de": "Binärdatei",
+ "uk": "Двійковий файл",
+ "ca": "Fitxer binari"
+ },
"AUTOMATIONS$DETAIL$REPOSITORIES": {
"en": "Repositories",
"ja": "リポジトリ",
diff --git a/src/routes/automation-detail.tsx b/src/routes/automation-detail.tsx
index 7affec129c..f61bfa97cb 100644
--- a/src/routes/automation-detail.tsx
+++ b/src/routes/automation-detail.tsx
@@ -26,6 +26,7 @@ import { BackLink } from "#/components/features/automations/detail/back-link";
import { DetailHeader } from "#/components/features/automations/detail/detail-header";
import { DisabledReasonBanner } from "#/components/features/automations/detail/disabled-reason-banner";
import { PromptSection } from "#/components/features/automations/detail/prompt-section";
+import { ScriptSection } from "#/components/features/automations/detail/script-section";
import { ConfigurationSection } from "#/components/features/automations/detail/configuration-section";
import { PluginsSection } from "#/components/features/automations/detail/plugins-section";
import { ActivitySection } from "#/components/features/automations/detail/activity-section";
@@ -257,7 +258,11 @@ export default function AutomationDetail() {
canToggle={canToggle}
/>
<DisabledReasonBanner automation={automation} />
- {automation.prompt && <PromptSection prompt={automation.prompt} />}
+ {automation.prompt ? (
+ <PromptSection prompt={automation.prompt} />
+ ) : (
+ <ScriptSection automation={automation} />
+ )}
<ConfigurationSection automation={automation} runsAs={runsAs} />
{automation.plugins && automation.plugins.length > 0 && (
<PluginsSection plugins={automation.plugins} />
diff --git a/src/types/automation.ts b/src/types/automation.ts
index 55b61d2c5e..618874854f 100644
--- a/src/types/automation.ts
+++ b/src/types/automation.ts
@@ -69,6 +69,12 @@ export interface Automation {
created_at: string;
updated_at: string;
prompt: string | null;
+ /**
+ * Shell command the automation service runs in the unpacked bundle's root
+ * (e.g. `python main.py`). Mirrors `AutomationResponse.entrypoint`; the
+ * detail page uses it to point out which bundle file is the script.
+ */
+ entrypoint?: string;
branch?: string;
plugins?: string[];
notification?: string;
@@ -90,6 +96,7 @@ export type AutomationSpec = Omit<
| "updated_at"
| "last_triggered_at"
| "preset_metadata"
+ | "entrypoint"
| "disabled_reason"
| "disabled_detail"
| "disabled_at"
@@ -160,6 +167,14 @@ export interface AutomationRun {
* dispatched (e.g. sandbox provisioning errors).
*/
bash_command_id: string | null;
+ /**
+ * ID of the cloud sandbox that hosted the run. Script (deterministic)
+ * automations never create a conversation, so on cloud backends this is
+ * the only handle to the agent-server holding their logs. Null when the
+ * run failed before a sandbox was provisioned; absent entirely against an
+ * automation service that predates the field.
+ */
+ sandbox_id?: string | null;
error_detail: string | null;
status_detail?: AutomationRunStatusDetail | null;
run_metadata?: AutomationRunMetadata | null;
diff --git a/src/utils/tar-unpack.ts b/src/utils/tar-unpack.ts
new file mode 100644
index 0000000000..c4124ee9df
--- /dev/null
+++ b/src/utils/tar-unpack.ts
@@ -0,0 +1,168 @@
+/**
+ * Reading a script bundle back out of the `.tar.gz` the automation service
+ * stores, in the browser.
+ *
+ * The counterpart of `tar-gzip.ts`, and as deliberately narrow: the archives
+ * read here are the few small files an automation ships, so this walks POSIX
+ * ustar headers directly rather than pulling in a tar library. Gunzip is the
+ * platform's own `DecompressionStream`.
+ *
+ * Only regular files are returned. Directories, links, and the pax / GNU
+ * extension headers that carry long names are skipped without being applied,
+ * so a member whose path exceeds ustar's 155 + 100 bytes surfaces under its
+ * truncated header name — acceptable for a bundle, where names are short.
+ */
+
+const BLOCK_SIZE = 512;
+const USTAR_MAGIC = "ustar";
+const GZIP_MAGIC = [0x1f, 0x8b] as const;
+
+/** Header fields at their ustar offsets. */
+const NAME = { offset: 0, size: 100 };
+const SIZE = { offset: 124, size: 12 };
+const TYPEFLAG_OFFSET = 156;
+const MAGIC = { offset: 257, size: 5 };
+const PREFIX = { offset: 345, size: 155 };
+
+const REGULAR_FILE_TYPEFLAGS = new Set(["0", "\0"]);
+
+export interface TarEntry {
+ /** Path inside the archive, without a leading `./`. */
+ path: string;
+ /** Size in bytes of the member's content. */
+ size: number;
+ /** The content decoded as UTF-8, or null when it is not valid UTF-8. */
+ text: string | null;
+}
+
+/** The bytes are not a tar archive (nor a gzip of one). */
+export class TarFormatError extends Error {
+ constructor(message: string) {
+ super(message);
+ this.name = "TarFormatError";
+ }
+}
+
+/** The unpacked archive exceeds the caller's budget. */
+export class TarTooLargeError extends Error {
+ constructor(maxTotalBytes: number) {
+ super(`tar: archive exceeds ${maxTotalBytes} bytes unpacked`);
+ this.name = "TarTooLargeError";
+ }
+}
+
+const asciiDecoder = new TextDecoder("ascii");
+const utf8Decoder = new TextDecoder("utf-8", { fatal: true });
+
+function isGzip(bytes: Uint8Array): boolean {
+ return bytes[0] === GZIP_MAGIC[0] && bytes[1] === GZIP_MAGIC[1];
+}
+
+async function gunzip(
+ bytes: Uint8Array<ArrayBuffer>,
+): Promise<Uint8Array<ArrayBuffer>> {
+ // Streamed from the bytes rather than through a Blob, mirroring
+ // `packTarGzip`: a Blob's stream() is absent in the jsdom test environment.
+ const source = new ReadableStream<BufferSource>({
+ start(controller) {
+ controller.enqueue(bytes);
+ controller.close();
+ },
+ });
+ const inflated = new Response(
+ source.pipeThrough(new DecompressionStream("gzip")),
+ );
+ return new Uint8Array(await inflated.arrayBuffer());
+}
+
+/** A NUL-terminated header string field. */
+function stringField(
+ header: Uint8Array,
+ field: { offset: number; size: number },
+): string {
+ const raw = asciiDecoder.decode(
+ header.subarray(field.offset, field.offset + field.size),
+ );
+ const end = raw.indexOf("\0");
+ return end === -1 ? raw : raw.slice(0, end);
+}
+
+/** The member's path as ustar spells it: `prefix/name` when a prefix is set. */
+function entryPath(header: Uint8Array): string {
+ const name = stringField(header, NAME);
+ const prefix = stringField(header, PREFIX);
+ const joined = prefix ? `${prefix}/${name}` : name;
+ return joined.replace(/^\.\//, "");
+}
+
+function entrySize(header: Uint8Array): number {
+ // ustar writes sizes as octal; the base-256 extension (high bit set) is
+ // for members far larger than any bundle, so it is refused rather than
+ // parsed.
+ if (header[SIZE.offset] & 0x80) {
+ throw new TarFormatError("tar: base-256 size field is not supported");
+ }
+ const size = parseInt(stringField(header, SIZE).trim() || "0", 8);
+ if (!Number.isFinite(size) || size < 0) {
+ throw new TarFormatError("tar: malformed size field");
+ }
+ return size;
+}
+
+function decodeText(bytes: Uint8Array): string | null {
+ try {
+ return utf8Decoder.decode(bytes);
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Unpack a gzipped (or plain) ustar archive into its regular files.
+ *
+ * Throws `TarFormatError` when the bytes are not an archive — a response
+ * that is really an error page, say — and `TarTooLargeError` once the
+ * unpacked members exceed `maxTotalBytes`.
+ */
+export async function unpackTarGzip(
+ bytes: Uint8Array<ArrayBuffer>,
+ options: { maxTotalBytes: number },
+): Promise<TarEntry[]> {
+ const archive = isGzip(bytes) ? await gunzip(bytes) : bytes;
+ const entries: TarEntry[] = [];
+ let unpackedBytes = 0;
+
+ let offset = 0;
+ while (offset + BLOCK_SIZE <= archive.length) {
+ const header = archive.subarray(offset, offset + BLOCK_SIZE);
+ // Two zero blocks end the archive; one is enough to stop reading.
+ if (header.every((byte) => byte === 0)) break;
+ if (stringField(header, MAGIC) !== USTAR_MAGIC) {
+ throw new TarFormatError("tar: not a ustar archive");
+ }
+
+ const size = entrySize(header);
+ const contentStart = offset + BLOCK_SIZE;
+ const contentEnd = contentStart + size;
+ if (contentEnd > archive.length) {
+ throw new TarFormatError("tar: member runs past the end of the archive");
+ }
+
+ const typeflag = String.fromCharCode(header[TYPEFLAG_OFFSET]);
+ if (REGULAR_FILE_TYPEFLAGS.has(typeflag)) {
+ unpackedBytes += size;
+ if (unpackedBytes > options.maxTotalBytes) {
+ throw new TarTooLargeError(options.maxTotalBytes);
+ }
+ entries.push({
+ path: entryPath(header),
+ size,
+ text: decodeText(archive.subarray(contentStart, contentEnd)),
+ });
+ }
+
+ offset = contentStart + Math.ceil(size / BLOCK_SIZE) * BLOCK_SIZE;
+ }
+
+ return entries;
+}