Skip to content

🙌 OpenHands: AI-Driven Development

feat: add Debug with OpenHands button to failed automation runs (#1603)

Hiep Le8a4be25a7a55
diff --git a/.pr/app2499-installed-mcp-card-configured-name.png b/.pr/app2499-installed-mcp-card-configured-name.png
deleted file mode 100644
index 7345378db5..0000000000
Binary files a/.pr/app2499-installed-mcp-card-configured-name.png and /dev/null differ
diff --git a/.pr/app2499-installed-mcp-card-fresh-configured-name.png b/.pr/app2499-installed-mcp-card-fresh-configured-name.png
deleted file mode 100644
index e3e93cf295..0000000000
Binary files a/.pr/app2499-installed-mcp-card-fresh-configured-name.png and /dev/null differ
diff --git a/.pr/app2499-installed-mcp-card-marketplace-or-url-fallback.png b/.pr/app2499-installed-mcp-card-marketplace-or-url-fallback.png
deleted file mode 100644
index cc19411c25..0000000000
Binary files a/.pr/app2499-installed-mcp-card-marketplace-or-url-fallback.png and /dev/null differ
diff --git a/.pr/app2499-installed-mcp-section-overview.png b/.pr/app2499-installed-mcp-section-overview.png
deleted file mode 100644
index 25cdd0a906..0000000000
Binary files a/.pr/app2499-installed-mcp-section-overview.png and /dev/null differ
diff --git a/__tests__/components/automations/detail/debug-automation-button.test.tsx b/__tests__/components/automations/detail/debug-automation-button.test.tsx
new file mode 100644
index 0000000000..c57e9c02e4
--- /dev/null
+++ b/__tests__/components/automations/detail/debug-automation-button.test.tsx
@@ -0,0 +1,159 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import { render, screen, fireEvent, waitFor } from "@testing-library/react";
+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
+
+import { DebugAutomationButton } from "#/components/features/automations/detail/debug-automation-button";
+import AgentServerConversationService from "#/api/conversation-service/agent-server-conversation-service.api";
+import ProfilesService from "#/api/profiles-service/profiles-service.api";
+import { ActiveBackendProvider } from "#/contexts/active-backend-context";
+import {
+ NavigationProvider,
+ type NavigationContextValue,
+} from "#/context/navigation-context";
+import {
+ __resetActiveStoreForTests,
+ setActiveSelection,
+ setRegisteredBackends,
+} from "#/api/backend-registry/active-store";
+import type { Backend } from "#/api/backend-registry/types";
+import {
+ AutomationRunStatus,
+ type Automation,
+ type AutomationRun,
+} from "#/types/automation";
+
+// Mock the underlying services (not the useCreateConversation hook), so the
+// real hook logic — id mapping + onSuccess navigation — is exercised.
+vi.mock(
+ "#/api/conversation-service/agent-server-conversation-service.api",
+ () => ({
+ default: { createConversation: vi.fn() },
+ }),
+);
+
+vi.mock("#/api/profiles-service/profiles-service.api", () => ({
+ default: { listProfiles: vi.fn() },
+}));
+
+type CreatedConversation = Awaited<
+ ReturnType<typeof AgentServerConversationService.createConversation>
+>;
+
+const localBackend: Backend = {
+ id: "local-1",
+ name: "Local",
+ host: "http://localhost:8000",
+ apiKey: "session-key",
+ kind: "local",
+};
+
+const failedRun: AutomationRun = {
+ id: "run-9",
+ status: AutomationRunStatus.FAILED,
+ conversation_id: "conv-1",
+ bash_command_id: "cmd-1",
+ error_detail: "Process exited with code 1",
+ started_at: "2026-01-01T10:00:00Z",
+ completed_at: "2026-01-01T10:02:00Z",
+};
+
+const automation: Automation = {
+ id: "auto-1",
+ name: "Daily Jira digest",
+ prompt: "Summarize new Jira issues",
+ trigger: { type: "cron", schedule: "0 9 * * *" },
+ enabled: true,
+ created_at: "2026-01-01T00:00:00Z",
+ updated_at: "2026-01-01T00:00:00Z",
+};
+
+function renderButton(stderr = "HTTP Error 410: Gone") {
+ const navigate = vi.fn();
+ const navValue: NavigationContextValue = {
+ currentPath: "/automations/auto-1",
+ conversationId: null,
+ isNavigating: false,
+ navigate,
+ };
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
+ });
+ render(
+ <QueryClientProvider client={queryClient}>
+ <ActiveBackendProvider>
+ <NavigationProvider value={navValue}>
+ <DebugAutomationButton
+ run={failedRun}
+ automation={automation}
+ stderr={stderr}
+ />
+ </NavigationProvider>
+ </ActiveBackendProvider>
+ </QueryClientProvider>,
+ );
+ return { navigate };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ __resetActiveStoreForTests();
+ setRegisteredBackends([localBackend]);
+ setActiveSelection({ backendId: localBackend.id });
+ vi.mocked(ProfilesService.listProfiles).mockResolvedValue({
+ profiles: [],
+ active_profile: null,
+ });
+});
+
+afterEach(() => {
+ __resetActiveStoreForTests();
+});
+
+describe("DebugAutomationButton", () => {
+ it("seeds a new conversation with the run's error details and navigates to it", async () => {
+ // Arrange — a null app_conversation_id resolves to a `task-<id>` route.
+ vi.mocked(
+ AgentServerConversationService.createConversation,
+ ).mockResolvedValue({
+ id: "abc123",
+ app_conversation_id: null,
+ agent_server_url: null,
+ } as CreatedConversation);
+ const { navigate } = renderButton("HTTP Error 410: Gone");
+
+ // Act
+ fireEvent.click(screen.getByTestId("debug-automation-button"));
+
+ // Assert — the first arg is the initial user message (the debug prompt).
+ await waitFor(() =>
+ expect(
+ AgentServerConversationService.createConversation,
+ ).toHaveBeenCalledTimes(1),
+ );
+ const query = vi.mocked(AgentServerConversationService.createConversation)
+ .mock.calls[0][0];
+ expect(query).toContain("HTTP Error 410: Gone");
+ expect(query).toContain("Daily Jira digest");
+
+ await waitFor(() =>
+ expect(navigate).toHaveBeenCalledWith("/conversations/task-abc123"),
+ );
+ });
+
+ it("disables the button while the conversation is being created", async () => {
+ // Arrange — a never-settling promise keeps the mutation pending.
+ vi.mocked(
+ AgentServerConversationService.createConversation,
+ ).mockReturnValue(new Promise<CreatedConversation>(() => {}));
+ renderButton();
+
+ const button = screen.getByTestId("debug-automation-button");
+
+ // Act
+ fireEvent.click(button);
+
+ // Assert
+ await waitFor(() => expect(button).toBeDisabled());
+ expect(button).toHaveAttribute("aria-busy", "true");
+ });
+});
diff --git a/__tests__/components/automations/detail/run-logs-modal.test.tsx b/__tests__/components/automations/detail/run-logs-modal.test.tsx
index 5b30f3dc7c..20a500b0de 100644
--- a/__tests__/components/automations/detail/run-logs-modal.test.tsx
+++ b/__tests__/components/automations/detail/run-logs-modal.test.tsx
@@ -2,6 +2,7 @@ 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";
+import { AutomationRunStatus, type AutomationRun } from "#/types/automation";
const { useBashCommandLogsMock } = vi.hoisted(() => ({
useBashCommandLogsMock: vi.fn(),
@@ -11,6 +12,17 @@ vi.mock("#/hooks/query/use-bash-command-logs", () => ({
useBashCommandLogs: useBashCommandLogsMock,
}));
+// The debug button owns its own query/navigation stack; stub it so these tests
+// only verify whether the modal chooses to render it.
+vi.mock(
+ "#/components/features/automations/detail/debug-automation-button",
+ () => ({
+ DebugAutomationButton: ({ run }: { run: AutomationRun }) => (
+ <div data-testid="debug-automation-button-stub" data-run-id={run.id} />
+ ),
+ }),
+);
+
function makeHookResult(
overrides: Partial<ReturnType<typeof baseResult>> = {},
) {
@@ -274,3 +286,47 @@ describe("RunLogsModal", () => {
expect(onClose).toHaveBeenCalledTimes(1);
});
});
+
+describe("RunLogsModal — Debug with OpenHands button", () => {
+ const makeRun = (status: AutomationRunStatus): AutomationRun => ({
+ id: "run-1",
+ status,
+ conversation_id: "conv-1",
+ bash_command_id: "cmd-1",
+ error_detail: status === AutomationRunStatus.FAILED ? "boom" : null,
+ started_at: "2026-01-01T10:00:00Z",
+ completed_at: "2026-01-01T10:02:00Z",
+ });
+
+ it("renders the debug button for a failed run", () => {
+ useBashCommandLogsMock.mockReturnValue(makeHookResult());
+ render(
+ <RunLogsModal
+ isOpen
+ conversationId="conv-1"
+ bashCommandId="cmd-1"
+ onClose={() => {}}
+ run={makeRun(AutomationRunStatus.FAILED)}
+ />,
+ );
+ expect(
+ screen.getByTestId("debug-automation-button-stub"),
+ ).toBeInTheDocument();
+ });
+
+ it("does not render the debug button for a successful run", () => {
+ useBashCommandLogsMock.mockReturnValue(makeHookResult());
+ render(
+ <RunLogsModal
+ isOpen
+ conversationId="conv-1"
+ bashCommandId="cmd-1"
+ onClose={() => {}}
+ run={makeRun(AutomationRunStatus.COMPLETED)}
+ />,
+ );
+ expect(
+ screen.queryByTestId("debug-automation-button-stub"),
+ ).not.toBeInTheDocument();
+ });
+});
diff --git a/__tests__/utils/automation-debug-prompt.test.ts b/__tests__/utils/automation-debug-prompt.test.ts
new file mode 100644
index 0000000000..3af5012e83
--- /dev/null
+++ b/__tests__/utils/automation-debug-prompt.test.ts
@@ -0,0 +1,89 @@
+import { describe, it, expect } from "vitest";
+import { buildAutomationDebugPrompt } from "#/utils/automation-debug-prompt";
+
+describe("buildAutomationDebugPrompt", () => {
+ it("includes the automation name, its instructions, the stderr, and the run id", () => {
+ // Arrange
+ const input = {
+ automationName: "Daily Jira digest",
+ automationPrompt: "Summarize new Jira issues each morning",
+ errorDetail: "Process exited with code 1",
+ stderr: "Traceback ...\nHTTP Error 410: Gone",
+ runId: "run-42",
+ };
+
+ // Act
+ const prompt = buildAutomationDebugPrompt(input);
+
+ // Assert
+ expect(prompt).toContain("Daily Jira digest");
+ expect(prompt).toContain("Summarize new Jira issues each morning");
+ expect(prompt).toContain("HTTP Error 410: Gone");
+ expect(prompt).toContain("run-42");
+ // The live stderr is preferred over the run-level error_detail.
+ expect(prompt).not.toContain("Process exited with code 1");
+ });
+
+ it("falls back to error_detail when stderr is blank", () => {
+ // Arrange — sandbox gone, so no stderr was fetched.
+ const prompt = buildAutomationDebugPrompt({
+ automationName: "Daily Jira digest",
+ automationPrompt: "Summarize new Jira issues",
+ errorDetail: "Process exited with code 1",
+ stderr: " \n ",
+ runId: "run-42",
+ });
+
+ // Assert
+ expect(prompt).toContain("Process exited with code 1");
+ expect(prompt).not.toContain("No error output");
+ });
+
+ it("omits the instructions section when the automation prompt is absent", () => {
+ // Act
+ const prompt = buildAutomationDebugPrompt({
+ automationName: "Daily Jira digest",
+ automationPrompt: null,
+ errorDetail: "boom",
+ stderr: "",
+ runId: "run-42",
+ });
+
+ // Assert
+ expect(prompt).not.toContain("What the automation was set up to do");
+ });
+
+ it("reports missing output when neither stderr nor error_detail is available", () => {
+ // Act
+ const prompt = buildAutomationDebugPrompt({
+ automationName: "Daily Jira digest",
+ automationPrompt: "Summarize new Jira issues",
+ errorDetail: null,
+ stderr: "",
+ runId: "run-42",
+ });
+
+ // Assert
+ expect(prompt).toContain("No error output was captured");
+ });
+
+ it("truncates oversized stderr, keeping the tail", () => {
+ // Arrange — an error stream well over the 4000-char cap, with distinct
+ // head and tail markers so we can prove which end survives.
+ const stderr = `HEAD_MARKER${"x".repeat(5000)}TAIL_MARKER`;
+
+ // Act
+ const prompt = buildAutomationDebugPrompt({
+ automationName: "Daily Jira digest",
+ automationPrompt: "Summarize new Jira issues",
+ errorDetail: null,
+ stderr,
+ runId: "run-42",
+ });
+
+ // Assert — the tail (the actual error) is kept, the head is dropped.
+ expect(prompt).toContain("TAIL_MARKER");
+ expect(prompt).toContain("…(truncated)…");
+ expect(prompt).not.toContain("HEAD_MARKER");
+ });
+});
diff --git a/src/components/features/automations/detail/activity-log-item.tsx b/src/components/features/automations/detail/activity-log-item.tsx
index 715e31ed46..c56735389d 100644
--- a/src/components/features/automations/detail/activity-log-item.tsx
+++ b/src/components/features/automations/detail/activity-log-item.tsx
@@ -2,12 +2,17 @@ import { useState } from "react";
import { useTranslation } from "react-i18next";
import { I18nKey } from "#/i18n/declaration";
import TerminalIcon from "#/icons/terminal.svg?react";
-import { AutomationRunStatus, type AutomationRun } from "#/types/automation";
+import {
+ AutomationRunStatus,
+ type Automation,
+ type AutomationRun,
+} from "#/types/automation";
import { RunStatusBadge } from "./run-status-badge";
import { RunLogsModal } from "./run-logs-modal";
interface ActivityLogItemProps {
run: AutomationRun;
+ automation?: Automation;
}
function formatRunTimestamp(dateStr: string, locale: string): string {
@@ -33,7 +38,7 @@ function getConversationUrl(conversationId: string): string {
return `/conversations/${conversationId}`;
}
-export function ActivityLogItem({ run }: ActivityLogItemProps) {
+export function ActivityLogItem({ run, automation }: ActivityLogItemProps) {
const { t, i18n } = useTranslation("openhands");
const hasConversation = !!run.conversation_id;
const hasBashCommand = !!run.bash_command_id;
@@ -126,6 +131,8 @@ export function ActivityLogItem({ run }: ActivityLogItemProps) {
bashCommandId={run.bash_command_id}
isOpen={logsOpen}
onClose={() => setLogsOpen(false)}
+ run={run}
+ automation={automation}
/>
)}
</>
diff --git a/src/components/features/automations/detail/activity-log-section.tsx b/src/components/features/automations/detail/activity-log-section.tsx
index d6c552506e..37712273ef 100644
--- a/src/components/features/automations/detail/activity-log-section.tsx
+++ b/src/components/features/automations/detail/activity-log-section.tsx
@@ -4,18 +4,19 @@ import { I18nKey } from "#/i18n/declaration";
import { useAutomationRuns } from "#/hooks/query/use-automation-detail";
import ActivityIcon from "#/icons/activity.svg?react";
import { ActivityLogItem } from "./activity-log-item";
+import type { Automation } from "#/types/automation";
interface ActivityLogSectionProps {
- automationId: string;
+ automation: Automation;
}
const PAGE_SIZE = 20;
-export function ActivityLogSection({ automationId }: ActivityLogSectionProps) {
+export function ActivityLogSection({ automation }: ActivityLogSectionProps) {
const { t } = useTranslation("openhands");
const [limit, setLimit] = useState(PAGE_SIZE);
const { data, isLoading } = useAutomationRuns({
- id: automationId,
+ id: automation.id,
limit,
offset: 0,
});
@@ -60,7 +61,7 @@ export function ActivityLogSection({ automationId }: ActivityLogSectionProps) {
key={run.id}
className={index > 0 ? "border-t border-[var(--oh-border)]" : ""}
>
- <ActivityLogItem run={run} />
+ <ActivityLogItem run={run} automation={automation} />
</div>
))}
diff --git a/src/components/features/automations/detail/debug-automation-button.tsx b/src/components/features/automations/detail/debug-automation-button.tsx
new file mode 100644
index 0000000000..f3c6248b16
--- /dev/null
+++ b/src/components/features/automations/detail/debug-automation-button.tsx
@@ -0,0 +1,66 @@
+import { useTranslation } from "react-i18next";
+import { I18nKey } from "#/i18n/declaration";
+import { BrandButton } from "#/components/features/settings/brand-button";
+import { useCreateConversation } from "#/hooks/mutation/use-create-conversation";
+import { useNavigation } from "#/context/navigation-context";
+import { buildAutomationDebugPrompt } from "#/utils/automation-debug-prompt";
+import type { Automation, AutomationRun } from "#/types/automation";
+
+interface DebugAutomationButtonProps {
+ /** The failed run being debugged. */
+ run: AutomationRun;
+ /** The parent automation, used to add context to the debug prompt. */
+ automation?: Automation;
+ /** The run's stderr, already computed by the enclosing logs modal. */
+ stderr: string;
+}
+
+/**
+ * Starts a new OpenHands conversation seeded with the failed run's error
+ * details so the agent begins debugging immediately. Kept as its own component
+ * (rather than inlined into the logs modal) so `useCreateConversation` — which
+ * requires a QueryClientProvider — only mounts for failed runs.
+ */
+export function DebugAutomationButton({
+ run,
+ automation,
+ stderr,
+}: DebugAutomationButtonProps) {
+ const { t } = useTranslation("openhands");
+ const { navigate } = useNavigation();
+ const createConversation = useCreateConversation();
+
+ const handleClick = () => {
+ if (createConversation.isPending) return;
+
+ const query = buildAutomationDebugPrompt({
+ automationName: automation?.name,
+ automationPrompt: automation?.prompt,
+ errorDetail: run.error_detail,
+ stderr,
+ runId: run.id,
+ });
+
+ createConversation.mutate(
+ { query },
+ {
+ onSuccess: (data) => {
+ navigate(`/conversations/${data.conversation_id}`);
+ },
+ },
+ );
+ };
+
+ return (
+ <BrandButton
+ testId="debug-automation-button"
+ type="button"
+ variant="primary"
+ onClick={handleClick}
+ isDisabled={createConversation.isPending}
+ aria-busy={createConversation.isPending}
+ >
+ {t(I18nKey.AUTOMATIONS$DETAIL$DEBUG_WITH_OPENHANDS)}
+ </BrandButton>
+ );
+}
diff --git a/src/components/features/automations/detail/run-logs-modal.tsx b/src/components/features/automations/detail/run-logs-modal.tsx
index 88df46c947..edda217f9e 100644
--- a/src/components/features/automations/detail/run-logs-modal.tsx
+++ b/src/components/features/automations/detail/run-logs-modal.tsx
@@ -9,6 +9,12 @@ import {
import type { BashOutput } from "@openhands/typescript-client";
import { cn } from "#/utils/utils";
import { modalTitleLgMediumClassName } from "#/utils/modal-classes";
+import {
+ AutomationRunStatus,
+ type Automation,
+ type AutomationRun,
+} from "#/types/automation";
+import { DebugAutomationButton } from "./debug-automation-button";
/**
* Localized empty-state message key for each `SandboxIssue` reason.
@@ -31,6 +37,10 @@ interface RunLogsModalProps {
bashCommandId: string | null;
isOpen: boolean;
onClose: () => void;
+ /** The run these logs belong to; enables the debug action for failed runs. */
+ run?: AutomationRun;
+ /** The parent automation, used to add context to the debug prompt. */
+ automation?: Automation;
}
function concatStream(outputs: BashOutput[], key: "stdout" | "stderr"): string {
@@ -52,6 +62,8 @@ export function RunLogsModal({
bashCommandId,
isOpen,
onClose,
+ run,
+ automation,
}: RunLogsModalProps) {
const { t } = useTranslation("openhands");
const [activeTab, setActiveTab] = useState<LogTab>("stdout");
@@ -231,6 +243,16 @@ export function RunLogsModal({
</pre>
)}
</div>
+
+ {run?.status === AutomationRunStatus.FAILED && (
+ <div className="mt-4 flex justify-end">
+ <DebugAutomationButton
+ run={run}
+ automation={automation}
+ stderr={stderr}
+ />
+ </div>
+ )}
</div>
</div>
);
diff --git a/src/i18n/translation.json b/src/i18n/translation.json
index 23a31d5fcf..da5ec91a06 100644
--- a/src/i18n/translation.json
+++ b/src/i18n/translation.json
@@ -13667,6 +13667,23 @@
"uk": "Переглянути журнали",
"ca": "Mostra els registres"
},
+ "AUTOMATIONS$DETAIL$DEBUG_WITH_OPENHANDS": {
+ "en": "Debug with OpenHands",
+ "ja": "OpenHandsでデバッグ",
+ "zh-CN": "使用 OpenHands 调试",
+ "zh-TW": "使用 OpenHands 偵錯",
+ "ko-KR": "OpenHands로 디버그",
+ "no": "Feilsøk med OpenHands",
+ "it": "Esegui il debug con OpenHands",
+ "pt": "Depurar com OpenHands",
+ "es": "Depurar con OpenHands",
+ "ar": "التصحيح باستخدام OpenHands",
+ "fr": "Déboguer avec OpenHands",
+ "tr": "OpenHands ile hata ayıkla",
+ "de": "Mit OpenHands debuggen",
+ "uk": "Налагодити за допомогою OpenHands",
+ "ca": "Depura amb OpenHands"
+ },
"AUTOMATIONS$DETAIL$LOGS_TITLE": {
"en": "Logs",
"ja": "ログ",
diff --git a/src/routes/automation-detail.tsx b/src/routes/automation-detail.tsx
index 562cc96eaa..76c6d57810 100644
--- a/src/routes/automation-detail.tsx
+++ b/src/routes/automation-detail.tsx
@@ -189,7 +189,7 @@ export default function AutomationDetail() {
createdAt={automation.created_at}
lastRunAt={automation.last_triggered_at}
/>
- <ActivityLogSection automationId={automation.id} />
+ <ActivityLogSection automation={automation} />
<DeleteConfirmationModal
automationName={automation.name}
isOpen={showDeleteModal}
diff --git a/src/utils/automation-debug-prompt.ts b/src/utils/automation-debug-prompt.ts
new file mode 100644
index 0000000000..05a1455464
--- /dev/null
+++ b/src/utils/automation-debug-prompt.ts
@@ -0,0 +1,65 @@
+export interface AutomationDebugPromptInput {
+ /** Human-readable automation name, if known. */
+ automationName?: string;
+ /** The automation's instructions (what it was set up to do). */
+ automationPrompt?: string | null;
+ /** Run-level error string; the durable fallback when stderr is unavailable. */
+ errorDetail?: string | null;
+ /** The run's captured stderr (the traceback shown in the Error tab). */
+ stderr?: string | null;
+ /** The failed run's id, included as a reference. */
+ runId: string;
+}
+
+// Keep the seeded first message bounded. A traceback's most useful part is the
+// tail (the actual error), so when the captured output is huge we keep the end.
+const MAX_ERROR_CHARS = 4000;
+
+function keepTail(text: string, max: number): string {
+ if (text.length <= max) return text;
+ return `…(truncated)…\n${text.slice(text.length - max)}`;
+}
+
+/**
+ * Build the first message for a "Debug with OpenHands" conversation started
+ * from a failed automation run. This is an instruction to the agent (not
+ * user-facing UI copy), so it is intentionally in English and not localized.
+ */
+export function buildAutomationDebugPrompt({
+ automationName,
+ automationPrompt,
+ errorDetail,
+ stderr,
+ runId,
+}: AutomationDebugPromptInput): string {
+ // Prefer the live stderr the user is looking at; fall back to the run-level
+ // error_detail when the sandbox is gone and stderr couldn't be fetched.
+ const rawError = stderr?.trim() || errorDetail?.trim() || "";
+ const errorSection = rawError
+ ? keepTail(rawError, MAX_ERROR_CHARS)
+ : "No error output was captured for this run.";
+
+ const trimmedName = automationName?.trim();
+ const intro = trimmedName
+ ? `The scheduled automation "${trimmedName}" failed during a run.`
+ : "A scheduled automation failed during a run.";
+
+ const lines: string[] = [
+ `${intro} Please investigate the error and fix the root cause.`,
+ ];
+
+ const trimmedPrompt = automationPrompt?.trim();
+ if (trimmedPrompt) {
+ lines.push("", "What the automation was set up to do:", trimmedPrompt);
+ }
+
+ lines.push(
+ "",
+ `Error output from the failed run (run ${runId}):`,
+ errorSection,
+ "",
+ "Please diagnose why it failed and propose or implement a fix.",
+ );
+
+ return lines.join("\n");
+}