mirror of
https://github.com/fabro-sh/fabro.git
synced 2026-10-08 03:10:26 +00:00
parent
740018aeb1
commit
b152c20137
6 changed files with 1390 additions and 17 deletions
495
run.json
495
run.json
File diff suppressed because one or more lines are too long
694
stages/005-implement@1/diff.patch
Normal file
694
stages/005-implement@1/diff.patch
Normal file
|
|
@ -0,0 +1,694 @@
|
|||
diff --git a/apps/fabro-web/app/components/automation-form.tsx b/apps/fabro-web/app/components/automation-form.tsx
|
||||
index 5f79f4a78..7b2b669e5 100644
|
||||
--- a/apps/fabro-web/app/components/automation-form.tsx
|
||||
+++ b/apps/fabro-web/app/components/automation-form.tsx
|
||||
@@ -1,9 +1,15 @@
|
||||
import { useRef, type ReactNode } from "react";
|
||||
import { Switch } from "@headlessui/react";
|
||||
-import type { Automation, AutomationTrigger } from "@qltysh/fabro-api-client";
|
||||
+import type {
|
||||
+ Automation,
|
||||
+ AutomationTrigger,
|
||||
+ Run,
|
||||
+ WorkflowSettings,
|
||||
+} from "@qltysh/fabro-api-client";
|
||||
|
||||
import { Panel, Row } from "./settings-panel";
|
||||
import { INPUT_CLASS } from "./ui";
|
||||
+import { sandboxRuntime } from "../lib/run-sandbox-lifecycle";
|
||||
|
||||
export interface AutomationFormValues {
|
||||
id: string;
|
||||
@@ -55,6 +61,40 @@ export function automationToFormValues(automation: Automation): AutomationFormVa
|
||||
};
|
||||
}
|
||||
|
||||
+export function automationFormValuesFromRun(
|
||||
+ run: Run,
|
||||
+ settings?: WorkflowSettings | null,
|
||||
+): AutomationFormValues {
|
||||
+ const name = firstPresentString(
|
||||
+ run.title,
|
||||
+ run.workflow.name,
|
||||
+ run.workflow.graph_name,
|
||||
+ run.workflow.slug,
|
||||
+ "New automation",
|
||||
+ );
|
||||
+ const workflowName = firstPresentString(
|
||||
+ run.workflow.name,
|
||||
+ run.workflow.graph_name,
|
||||
+ name,
|
||||
+ );
|
||||
+ return {
|
||||
+ ...EMPTY_AUTOMATION_FORM,
|
||||
+ id: kebabify(name),
|
||||
+ name,
|
||||
+ description: "",
|
||||
+ enabled: true,
|
||||
+ repository: githubRepositoryFromSettings(settings)
|
||||
+ ?? githubRepositoryName(run.repository?.name)
|
||||
+ ?? githubRepositoryFromOriginUrl(run.repository?.origin_url)
|
||||
+ ?? "",
|
||||
+ ref: sandboxRuntime(run.sandbox)?.clone_branch ?? EMPTY_AUTOMATION_FORM.ref,
|
||||
+ workflow: run.workflow.slug?.trim() || snakeify(workflowName),
|
||||
+ manualEnabled: true,
|
||||
+ scheduleEnabled: false,
|
||||
+ cron: EMPTY_AUTOMATION_FORM.cron,
|
||||
+ };
|
||||
+}
|
||||
+
|
||||
export function triggersFromFormValues(values: AutomationFormValues): AutomationTrigger[] {
|
||||
const triggers: AutomationTrigger[] = [];
|
||||
if (values.manualEnabled) {
|
||||
@@ -98,6 +138,54 @@ export function snakeify(value: string): string {
|
||||
.replace(/^_|_$/g, "");
|
||||
}
|
||||
|
||||
+function firstPresentString(...values: Array<string | null | undefined>): string {
|
||||
+ for (const value of values) {
|
||||
+ const trimmed = value?.trim();
|
||||
+ if (trimmed) return trimmed;
|
||||
+ }
|
||||
+ return "";
|
||||
+}
|
||||
+
|
||||
+function githubRepositoryFromSettings(
|
||||
+ settings?: WorkflowSettings | null,
|
||||
+): string | null {
|
||||
+ const owner = settings?.run?.scm?.owner;
|
||||
+ const repository = settings?.run?.scm?.repository;
|
||||
+ if (!owner || !repository) return null;
|
||||
+ return githubRepositoryName(`${owner}/${repository}`);
|
||||
+}
|
||||
+
|
||||
+function githubRepositoryName(value: string | null | undefined): string | null {
|
||||
+ const trimmed = value?.trim().replace(/\.git$/i, "");
|
||||
+ if (!trimmed) return null;
|
||||
+
|
||||
+ const match = trimmed.match(/^([A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)\/([A-Za-z0-9._-]+)$/);
|
||||
+ if (!match) return null;
|
||||
+ return `${match[1]}/${match[2]}`;
|
||||
+}
|
||||
+
|
||||
+function githubRepositoryFromOriginUrl(value: string | null | undefined): string | null {
|
||||
+ const trimmed = value?.trim();
|
||||
+ if (!trimmed) return null;
|
||||
+
|
||||
+ const scpLikeMatch = trimmed.match(
|
||||
+ /^git@github\.com:([A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)\/([A-Za-z0-9._-]+?)(?:\.git)?$/i,
|
||||
+ );
|
||||
+ if (scpLikeMatch) {
|
||||
+ return githubRepositoryName(`${scpLikeMatch[1]}/${scpLikeMatch[2]}`);
|
||||
+ }
|
||||
+
|
||||
+ try {
|
||||
+ const url = new URL(trimmed);
|
||||
+ if (url.hostname.toLowerCase() !== "github.com") return null;
|
||||
+ const parts = url.pathname.split("/").filter(Boolean);
|
||||
+ if (parts.length !== 2) return null;
|
||||
+ return githubRepositoryName(`${parts[0]}/${parts[1]}`);
|
||||
+ } catch {
|
||||
+ return null;
|
||||
+ }
|
||||
+}
|
||||
+
|
||||
function describeCron(expression: string): string {
|
||||
const trimmed = expression.trim();
|
||||
const preset = CRON_PRESETS.find((p) => p.value === trimmed);
|
||||
diff --git a/apps/fabro-web/app/routes/automations-new.test.tsx b/apps/fabro-web/app/routes/automations-new.test.tsx
|
||||
new file mode 100644
|
||||
index 000000000..47f471abf
|
||||
--- /dev/null
|
||||
+++ b/apps/fabro-web/app/routes/automations-new.test.tsx
|
||||
@@ -0,0 +1,300 @@
|
||||
+import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test";
|
||||
+import { createElement } from "react";
|
||||
+import TestRenderer, { act } from "react-test-renderer";
|
||||
+import { createMemoryRouter, RouterProvider } from "react-router";
|
||||
+
|
||||
+import { ToastProvider } from "../components/toast";
|
||||
+import { setupReactTestEnv } from "../lib/test-utils";
|
||||
+
|
||||
+let currentRun: any = null;
|
||||
+let currentRunError: unknown = null;
|
||||
+let currentRunLoading = false;
|
||||
+let currentRunSettings: any = null;
|
||||
+const queryCalls: Array<{ hook: string; id: string | undefined }> = [];
|
||||
+const mountedRenderers: TestRenderer.ReactTestRenderer[] = [];
|
||||
+let teardownReactEnv: (() => void) | undefined;
|
||||
+
|
||||
+const createAutomationMock = mock((_payload: unknown) =>
|
||||
+ Promise.resolve({ data: {} }),
|
||||
+);
|
||||
+const swrMutateMock = mock((_key: unknown) => Promise.resolve(undefined));
|
||||
+
|
||||
+mock.module("@headlessui/react", () => ({
|
||||
+ Dialog: ({ open, children }: any) =>
|
||||
+ open ? createElement("div", { role: "dialog" }, children) : null,
|
||||
+ DialogPanel: ({ children, ...props }: any) =>
|
||||
+ createElement("div", props, children),
|
||||
+ DialogTitle: ({ children, ...props }: any) =>
|
||||
+ createElement("h2", props, children),
|
||||
+ Switch: ({ checked, onChange, children, ...props }: any) =>
|
||||
+ createElement(
|
||||
+ "button",
|
||||
+ {
|
||||
+ ...props,
|
||||
+ type: "button",
|
||||
+ role: "switch",
|
||||
+ "aria-checked": checked,
|
||||
+ onClick: () => onChange(!checked),
|
||||
+ },
|
||||
+ children,
|
||||
+ ),
|
||||
+}));
|
||||
+
|
||||
+mock.module("../lib/queries", () => ({
|
||||
+ useRun: (id: string | undefined) => {
|
||||
+ queryCalls.push({ hook: "useRun", id });
|
||||
+ return {
|
||||
+ data: currentRun,
|
||||
+ error: currentRunError,
|
||||
+ isLoading: currentRunLoading,
|
||||
+ };
|
||||
+ },
|
||||
+ useRunSettings: (id: string | undefined) => {
|
||||
+ queryCalls.push({ hook: "useRunSettings", id });
|
||||
+ return {
|
||||
+ data: currentRunSettings,
|
||||
+ error: null,
|
||||
+ isLoading: false,
|
||||
+ };
|
||||
+ },
|
||||
+}));
|
||||
+
|
||||
+mock.module("../lib/api-client", () => ({
|
||||
+ ApiError: class ApiError extends Error {
|
||||
+ readonly status: number;
|
||||
+ readonly requestId: string | null;
|
||||
+ readonly body: unknown;
|
||||
+
|
||||
+ constructor({
|
||||
+ status,
|
||||
+ message,
|
||||
+ requestId,
|
||||
+ body,
|
||||
+ }: {
|
||||
+ status: number;
|
||||
+ message: string;
|
||||
+ requestId: string | null;
|
||||
+ body: unknown;
|
||||
+ }) {
|
||||
+ super(message);
|
||||
+ this.name = "ApiError";
|
||||
+ this.status = status;
|
||||
+ this.requestId = requestId;
|
||||
+ this.body = body;
|
||||
+ }
|
||||
+ },
|
||||
+ apiData: async function apiData<T>(
|
||||
+ call: () => Promise<{ data: T }>,
|
||||
+ ): Promise<T> {
|
||||
+ const response = await call();
|
||||
+ return response.data;
|
||||
+ },
|
||||
+ automationsApi: {
|
||||
+ createAutomation: createAutomationMock,
|
||||
+ },
|
||||
+}));
|
||||
+
|
||||
+mock.module("swr", () => ({
|
||||
+ useSWRConfig: () => ({ mutate: swrMutateMock }),
|
||||
+}));
|
||||
+
|
||||
+const { default: AutomationsNew } = await import("./automations-new");
|
||||
+mock.restore();
|
||||
+
|
||||
+function makeRun(overrides: Record<string, unknown> = {}) {
|
||||
+ return {
|
||||
+ id: "run_1",
|
||||
+ children_count: 0,
|
||||
+ goal: "Fix CI",
|
||||
+ title: "Fix failing tests",
|
||||
+ workflow: {
|
||||
+ slug: "fix_ci",
|
||||
+ name: "Fix CI",
|
||||
+ graph_name: "ci_graph",
|
||||
+ node_count: 0,
|
||||
+ edge_count: 0,
|
||||
+ },
|
||||
+ automation: null,
|
||||
+ repository: {
|
||||
+ name: "fallback/repo",
|
||||
+ origin_url: "https://github.com/fallback/repo.git",
|
||||
+ provider: "github",
|
||||
+ },
|
||||
+ created_by: null,
|
||||
+ origin: { kind: "api" },
|
||||
+ labels: {},
|
||||
+ lifecycle: {
|
||||
+ status: { kind: "succeeded", reason: "completed" },
|
||||
+ approval: null,
|
||||
+ pending_control: null,
|
||||
+ queue_position: null,
|
||||
+ error: null,
|
||||
+ archived: false,
|
||||
+ archived_at: null,
|
||||
+ },
|
||||
+ sandbox: {
|
||||
+ kind: "ready",
|
||||
+ plan: { provider: "docker", image: null, snapshot: null },
|
||||
+ instance: {
|
||||
+ provider: "docker",
|
||||
+ image: null,
|
||||
+ snapshot: null,
|
||||
+ runtime: {
|
||||
+ id: "container_1",
|
||||
+ working_directory: "/workspace",
|
||||
+ repo_cloned: true,
|
||||
+ clone_origin_url: "https://github.com/qltysh/fabro.git",
|
||||
+ clone_branch: "feature/from-run",
|
||||
+ },
|
||||
+ },
|
||||
+ },
|
||||
+ models: [],
|
||||
+ source_directory: null,
|
||||
+ timestamps: {
|
||||
+ created_at: "2026-04-20T12:00:00Z",
|
||||
+ started_at: null,
|
||||
+ last_event_at: null,
|
||||
+ completed_at: null,
|
||||
+ },
|
||||
+ timing: null,
|
||||
+ billing: null,
|
||||
+ size: "XS",
|
||||
+ ask_fabro: {
|
||||
+ available: false,
|
||||
+ unavailable_reason: "no_sandbox",
|
||||
+ default_model: null,
|
||||
+ },
|
||||
+ diff: null,
|
||||
+ pull_request: null,
|
||||
+ current_question: null,
|
||||
+ superseded_by: null,
|
||||
+ retried_from: null,
|
||||
+ links: { web: null },
|
||||
+ ...overrides,
|
||||
+ };
|
||||
+}
|
||||
+
|
||||
+function makeRunSettings() {
|
||||
+ return {
|
||||
+ run: {
|
||||
+ scm: {
|
||||
+ provider: "github",
|
||||
+ owner: "qltysh",
|
||||
+ repository: "fabro",
|
||||
+ github: null,
|
||||
+ },
|
||||
+ },
|
||||
+ };
|
||||
+}
|
||||
+
|
||||
+async function renderAutomationsNew(initialEntry: string) {
|
||||
+ const router = createMemoryRouter(
|
||||
+ [
|
||||
+ {
|
||||
+ path: "/automations",
|
||||
+ element: <div data-route="automations">Automations</div>,
|
||||
+ },
|
||||
+ {
|
||||
+ path: "/automations/new",
|
||||
+ element: <AutomationsNew />,
|
||||
+ },
|
||||
+ ],
|
||||
+ { initialEntries: [initialEntry] },
|
||||
+ );
|
||||
+
|
||||
+ let renderer!: TestRenderer.ReactTestRenderer;
|
||||
+ await act(async () => {
|
||||
+ renderer = TestRenderer.create(
|
||||
+ <ToastProvider>
|
||||
+ <RouterProvider router={router} />
|
||||
+ </ToastProvider>,
|
||||
+ );
|
||||
+ });
|
||||
+ mountedRenderers.push(renderer);
|
||||
+ return { renderer, router };
|
||||
+}
|
||||
+
|
||||
+function fieldValue(renderer: TestRenderer.ReactTestRenderer, label: string) {
|
||||
+ return renderer.root.findByProps({ "aria-label": label }).props.value;
|
||||
+}
|
||||
+
|
||||
+function switchChecked(renderer: TestRenderer.ReactTestRenderer, label: string) {
|
||||
+ const props = renderer.root.findByProps({ "aria-label": label }).props;
|
||||
+ return props["aria-checked"] ?? props.checked;
|
||||
+}
|
||||
+
|
||||
+function textFromNode(
|
||||
+ node: ReturnType<TestRenderer.ReactTestRenderer["toJSON"]>,
|
||||
+): string {
|
||||
+ if (!node) return "";
|
||||
+ if (typeof node === "string") return node;
|
||||
+ if (Array.isArray(node)) return node.map(textFromNode).join(" ");
|
||||
+ return (node.children ?? []).map(textFromNode).join(" ");
|
||||
+}
|
||||
+
|
||||
+beforeEach(() => {
|
||||
+ teardownReactEnv = setupReactTestEnv();
|
||||
+ currentRun = null;
|
||||
+ currentRunError = null;
|
||||
+ currentRunLoading = false;
|
||||
+ currentRunSettings = null;
|
||||
+ queryCalls.length = 0;
|
||||
+ createAutomationMock.mockClear();
|
||||
+ swrMutateMock.mockClear();
|
||||
+});
|
||||
+
|
||||
+afterEach(() => {
|
||||
+ for (const renderer of mountedRenderers.splice(0)) {
|
||||
+ act(() => renderer.unmount());
|
||||
+ }
|
||||
+ teardownReactEnv?.();
|
||||
+ teardownReactEnv = undefined;
|
||||
+});
|
||||
+
|
||||
+describe("AutomationsNew", () => {
|
||||
+ test("/automations/new renders empty form values", async () => {
|
||||
+ const { renderer } = await renderAutomationsNew("/automations/new");
|
||||
+
|
||||
+ expect(fieldValue(renderer, "Automation name")).toBe("");
|
||||
+ expect(fieldValue(renderer, "Automation slug")).toBe("");
|
||||
+ expect(fieldValue(renderer, "Repository")).toBe("");
|
||||
+ expect(fieldValue(renderer, "Default branch")).toBe("main");
|
||||
+ expect(fieldValue(renderer, "Workflow slug")).toBe("");
|
||||
+ expect(switchChecked(renderer, "Enable manual and API triggers")).toBe(true);
|
||||
+ expect(switchChecked(renderer, "Enable scheduled triggers")).toBe(false);
|
||||
+ });
|
||||
+
|
||||
+ test("/automations/new?from_run=run_1 pre-populates from run and settings data", async () => {
|
||||
+ currentRun = makeRun();
|
||||
+ currentRunSettings = makeRunSettings();
|
||||
+
|
||||
+ const { renderer } = await renderAutomationsNew("/automations/new?from_run=run_1");
|
||||
+
|
||||
+ expect(fieldValue(renderer, "Automation name")).toBe("Fix failing tests");
|
||||
+ expect(fieldValue(renderer, "Automation slug")).toBe("fix-failing-tests");
|
||||
+ expect(fieldValue(renderer, "Repository")).toBe("qltysh/fabro");
|
||||
+ expect(fieldValue(renderer, "Default branch")).toBe("feature/from-run");
|
||||
+ expect(fieldValue(renderer, "Workflow slug")).toBe("fix_ci");
|
||||
+ expect(switchChecked(renderer, "Enable manual and API triggers")).toBe(true);
|
||||
+ expect(switchChecked(renderer, "Enable scheduled triggers")).toBe(false);
|
||||
+ expect(
|
||||
+ renderer.root.findAllByProps({ "aria-label": "Cron expression" }),
|
||||
+ ).toHaveLength(0);
|
||||
+ expect(queryCalls).toContainEqual({ hook: "useRun", id: "run_1" });
|
||||
+ expect(queryCalls).toContainEqual({ hook: "useRunSettings", id: "run_1" });
|
||||
+ });
|
||||
+
|
||||
+ test("missing source run data renders an editable empty form with a non-blocking error", async () => {
|
||||
+ currentRun = null;
|
||||
+ currentRunError = new Error("not found");
|
||||
+
|
||||
+ const { renderer } = await renderAutomationsNew("/automations/new?from_run=run_1");
|
||||
+
|
||||
+ expect(textFromNode(renderer.toJSON())).toContain("could not be loaded");
|
||||
+ expect(textFromNode(renderer.toJSON())).toContain("fill it out manually");
|
||||
+ expect(fieldValue(renderer, "Automation name")).toBe("");
|
||||
+ expect(fieldValue(renderer, "Repository")).toBe("");
|
||||
+ expect(fieldValue(renderer, "Default branch")).toBe("main");
|
||||
+ expect(fieldValue(renderer, "Workflow slug")).toBe("");
|
||||
+ });
|
||||
+});
|
||||
diff --git a/apps/fabro-web/app/routes/automations-new.tsx b/apps/fabro-web/app/routes/automations-new.tsx
|
||||
index 1ee221c35..75454693a 100644
|
||||
--- a/apps/fabro-web/app/routes/automations-new.tsx
|
||||
+++ b/apps/fabro-web/app/routes/automations-new.tsx
|
||||
@@ -1,13 +1,15 @@
|
||||
import { useState } from "react";
|
||||
-import { Link, useNavigate } from "react-router";
|
||||
+import { Link, useNavigate, useSearchParams } from "react-router";
|
||||
import { useSWRConfig } from "swr";
|
||||
import { ChevronRightIcon } from "@heroicons/react/20/solid";
|
||||
|
||||
import { ApiError, apiData, automationsApi } from "../lib/api-client";
|
||||
import { queryKeys } from "../lib/query-keys";
|
||||
+import { useRun, useRunSettings } from "../lib/queries";
|
||||
import {
|
||||
AutomationFormFields,
|
||||
EMPTY_AUTOMATION_FORM,
|
||||
+ automationFormValuesFromRun,
|
||||
isFormValid,
|
||||
triggersFromFormValues,
|
||||
type AutomationFormValues,
|
||||
@@ -26,10 +28,65 @@ export function meta() {
|
||||
export const handle = { hideHeader: true };
|
||||
|
||||
export default function AutomationsNew() {
|
||||
+ const [searchParams] = useSearchParams();
|
||||
+ const fromRunId = searchParams.get("from_run")?.trim() || undefined;
|
||||
+ const runQuery = useRun(fromRunId);
|
||||
+ const settingsQuery = useRunSettings(fromRunId);
|
||||
+
|
||||
+ if (!fromRunId) {
|
||||
+ return (
|
||||
+ <AutomationCreateForm
|
||||
+ key="blank"
|
||||
+ initialValues={EMPTY_AUTOMATION_FORM}
|
||||
+ />
|
||||
+ );
|
||||
+ }
|
||||
+
|
||||
+ if (runQuery.isLoading && !runQuery.data) {
|
||||
+ return (
|
||||
+ <div className="space-y-6">
|
||||
+ <PageHeader />
|
||||
+ <p className="rounded-lg bg-panel-alt px-4 py-3 text-sm text-fg-3">
|
||||
+ Loading source run…
|
||||
+ </p>
|
||||
+ </div>
|
||||
+ );
|
||||
+ }
|
||||
+
|
||||
+ if (!runQuery.data) {
|
||||
+ return (
|
||||
+ <AutomationCreateForm
|
||||
+ key={`missing:${fromRunId}`}
|
||||
+ initialValues={EMPTY_AUTOMATION_FORM}
|
||||
+ sourceError="The source run could not be loaded. You can still fill it out manually."
|
||||
+ />
|
||||
+ );
|
||||
+ }
|
||||
+
|
||||
+ const initialValues = automationFormValuesFromRun(
|
||||
+ runQuery.data,
|
||||
+ settingsQuery.data ?? null,
|
||||
+ );
|
||||
+
|
||||
+ return (
|
||||
+ <AutomationCreateForm
|
||||
+ key={sourceFormKey(fromRunId, initialValues, Boolean(settingsQuery.data))}
|
||||
+ initialValues={initialValues}
|
||||
+ />
|
||||
+ );
|
||||
+}
|
||||
+
|
||||
+function AutomationCreateForm({
|
||||
+ initialValues,
|
||||
+ sourceError = null,
|
||||
+}: {
|
||||
+ initialValues: AutomationFormValues;
|
||||
+ sourceError?: string | null;
|
||||
+}) {
|
||||
const navigate = useNavigate();
|
||||
const { mutate } = useSWRConfig();
|
||||
const toast = useToast();
|
||||
- const [values, setValues] = useState<AutomationFormValues>(EMPTY_AUTOMATION_FORM);
|
||||
+ const [values, setValues] = useState<AutomationFormValues>(initialValues);
|
||||
const [submitting, setSubmitting] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
@@ -75,6 +132,7 @@ export default function AutomationsNew() {
|
||||
|
||||
<AutomationFormFields values={values} onChange={setValues} />
|
||||
|
||||
+ {sourceError ? <ErrorMessage message={sourceError} /> : null}
|
||||
{error ? <ErrorMessage message={error} /> : null}
|
||||
|
||||
<FormFooter
|
||||
@@ -86,6 +144,22 @@ export default function AutomationsNew() {
|
||||
);
|
||||
}
|
||||
|
||||
+function sourceFormKey(
|
||||
+ fromRunId: string,
|
||||
+ initialValues: AutomationFormValues,
|
||||
+ hasSettings: boolean,
|
||||
+) {
|
||||
+ return [
|
||||
+ "from-run",
|
||||
+ fromRunId,
|
||||
+ hasSettings ? "settings" : "run",
|
||||
+ initialValues.name,
|
||||
+ initialValues.repository,
|
||||
+ initialValues.ref,
|
||||
+ initialValues.workflow,
|
||||
+ ].join(":");
|
||||
+}
|
||||
+
|
||||
function PageHeader() {
|
||||
return (
|
||||
<div>
|
||||
diff --git a/apps/fabro-web/app/routes/run-detail.test.ts b/apps/fabro-web/app/routes/run-detail.test.ts
|
||||
index 844321220..012ba96a9 100644
|
||||
--- a/apps/fabro-web/app/routes/run-detail.test.ts
|
||||
+++ b/apps/fabro-web/app/routes/run-detail.test.ts
|
||||
@@ -50,6 +50,10 @@ mock.module("../lib/queries", () => ({
|
||||
data: currentRunSummary,
|
||||
isLoading: false,
|
||||
}),
|
||||
+ useRunSettings: () => ({
|
||||
+ data: null,
|
||||
+ isLoading: false,
|
||||
+ }),
|
||||
useRunQuestions: () => ({
|
||||
data: currentQuestions,
|
||||
}),
|
||||
@@ -190,6 +194,7 @@ function makeRunSummary(
|
||||
pullRequest: any = null,
|
||||
title = "Run 1",
|
||||
askFabro: any = null,
|
||||
+ automation: any = null,
|
||||
) {
|
||||
const apiStatus =
|
||||
status === "succeeded"
|
||||
@@ -207,7 +212,7 @@ function makeRunSummary(
|
||||
goal: "Run 1",
|
||||
title,
|
||||
workflow: { slug: "default", name: "Default", graph_name: null, node_count: 0, edge_count: 0 },
|
||||
- automation: null,
|
||||
+ automation,
|
||||
repository: { name: "fabro", origin_url: null, provider: "unknown" },
|
||||
created_by: null,
|
||||
origin: { kind: "api" },
|
||||
@@ -269,6 +274,7 @@ async function renderRunDetailHarness({
|
||||
pullRequest = null,
|
||||
title,
|
||||
askFabro = null,
|
||||
+ automation = null,
|
||||
}: {
|
||||
initialEntry: string;
|
||||
status?: string;
|
||||
@@ -277,8 +283,9 @@ async function renderRunDetailHarness({
|
||||
pullRequest?: any;
|
||||
title?: string;
|
||||
askFabro?: any;
|
||||
+ automation?: any;
|
||||
}) {
|
||||
- currentRunSummary = makeRunSummary(status, diffSummary, pullRequest, title, askFabro);
|
||||
+ currentRunSummary = makeRunSummary(status, diffSummary, pullRequest, title, askFabro, automation);
|
||||
currentQuestions = questions;
|
||||
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
|
||||
|
||||
@@ -303,6 +310,14 @@ async function renderRunDetailHarness({
|
||||
},
|
||||
],
|
||||
},
|
||||
+ {
|
||||
+ path: "/automations/new",
|
||||
+ element: h("div", { "data-route": "automations-new" }, "New automation"),
|
||||
+ },
|
||||
+ {
|
||||
+ path: "/automations/:automationId",
|
||||
+ element: h("div", { "data-route": "automation-detail" }, "Automation detail"),
|
||||
+ },
|
||||
],
|
||||
{ initialEntries: [initialEntry] },
|
||||
);
|
||||
@@ -373,6 +388,15 @@ function findButtonByText(
|
||||
)[0];
|
||||
}
|
||||
|
||||
+function findButtonsByText(
|
||||
+ renderer: TestRenderer.ReactTestRenderer,
|
||||
+ text: string,
|
||||
+) {
|
||||
+ return renderer.root.findAll(
|
||||
+ (node) => node.type === "button" && textFromTestNode(node).includes(text),
|
||||
+ );
|
||||
+}
|
||||
+
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T | PromiseLike<T>) => void;
|
||||
let reject!: (reason?: unknown) => void;
|
||||
@@ -782,6 +806,38 @@ describe("RunDetail full-height child routes", () => {
|
||||
expect(tabCountBadges(renderer)).toHaveLength(0);
|
||||
});
|
||||
|
||||
+ test("ordinary runs can navigate to create an automation from the run", async () => {
|
||||
+ const { renderer, router } = await renderRunDetailHarness({
|
||||
+ initialEntry: "/runs/run_1",
|
||||
+ });
|
||||
+
|
||||
+ expect(findButtonsByText(renderer, "Create automation from run")).toHaveLength(1);
|
||||
+ expect(findButtonsByText(renderer, "View automation")).toHaveLength(0);
|
||||
+
|
||||
+ await act(async () => {
|
||||
+ findButtonByText(renderer, "Create automation from run")!.props.onClick();
|
||||
+ });
|
||||
+
|
||||
+ expect(router.state.location.pathname).toBe("/automations/new");
|
||||
+ expect(router.state.location.search).toBe("?from_run=run_1");
|
||||
+ });
|
||||
+
|
||||
+ test("automation-created runs navigate to the existing automation instead of duplicate creation", async () => {
|
||||
+ const { renderer, router } = await renderRunDetailHarness({
|
||||
+ initialEntry: "/runs/run_1",
|
||||
+ automation: { id: "fix build", name: "Fix Build", trigger_id: "manual" },
|
||||
+ });
|
||||
+
|
||||
+ expect(findButtonsByText(renderer, "View automation")).toHaveLength(1);
|
||||
+ expect(findButtonsByText(renderer, "Create automation from run")).toHaveLength(0);
|
||||
+
|
||||
+ await act(async () => {
|
||||
+ findButtonByText(renderer, "View automation")!.props.onClick();
|
||||
+ });
|
||||
+
|
||||
+ expect(router.state.location.pathname).toBe("/automations/fix%20build");
|
||||
+ });
|
||||
+
|
||||
test("confirms deleting an archived run and navigates back to runs", async () => {
|
||||
const deletion = deferred<unknown>();
|
||||
deleteRunApiResult = deletion.promise;
|
||||
diff --git a/apps/fabro-web/app/routes/run-detail.tsx b/apps/fabro-web/app/routes/run-detail.tsx
|
||||
index b97da4026..ad75da0e0 100644
|
||||
--- a/apps/fabro-web/app/routes/run-detail.tsx
|
||||
+++ b/apps/fabro-web/app/routes/run-detail.tsx
|
||||
@@ -200,6 +200,18 @@ export default function RunDetail({ params }: { params: { id: string } }) {
|
||||
}
|
||||
};
|
||||
const hasPendingQuestions = isBlocked && pendingQuestions.length > 0;
|
||||
+ const automationId = summary.automation?.id ?? null;
|
||||
+ const automationAction = automationId
|
||||
+ ? {
|
||||
+ key: "view-automation",
|
||||
+ label: "View automation",
|
||||
+ onSelect: () => navigate(`/automations/${encodeURIComponent(automationId)}`),
|
||||
+ }
|
||||
+ : {
|
||||
+ key: "create-automation",
|
||||
+ label: "Create automation from run",
|
||||
+ onSelect: () => navigate(`/automations/new?from_run=${encodeURIComponent(params.id)}`),
|
||||
+ };
|
||||
const actionGroups: ActionGroups = {
|
||||
operations: [
|
||||
...(hasSandbox
|
||||
@@ -211,6 +223,7 @@ export default function RunDetail({ params }: { params: { id: string } }) {
|
||||
onSelect: () => void handlePreview(),
|
||||
}]
|
||||
: []),
|
||||
+ automationAction,
|
||||
{
|
||||
key: "interrupt",
|
||||
label: "Send interrupt",
|
||||
6
stages/005-implement@1/status.json
Normal file
6
stages/005-implement@1/status.json
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
{
|
||||
"outcome": "succeeded",
|
||||
"notes": "Stage completed: implement",
|
||||
"failure_reason": null,
|
||||
"timestamp": "2026-05-29T18:46:10.841760Z"
|
||||
}
|
||||
181
stages/006-simplify_opus@1/prompt.md
Normal file
181
stages/006-simplify_opus@1/prompt.md
Normal file
|
|
@ -0,0 +1,181 @@
|
|||
Goal: # Create Automation From Run Prefill Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Add a frontend-only flow that lets users start a new automation form from an existing run.
|
||||
|
||||
**Architecture:** Reuse the existing `/automations/new` route with an optional `from_run` search parameter. The route derives initial form values from existing run and run-settings queries, then mounts a keyed form child so source data initializes local form state without direct React effects. The run actions menu links to the prefill route for ordinary runs and to the existing automation detail page for automation-created runs.
|
||||
|
||||
**Tech Stack:** React 19, React Router, SWR, TypeScript, existing Fabro web API clients, Bun tests.
|
||||
|
||||
---
|
||||
|
||||
## Decisions
|
||||
|
||||
- Add only frontend behavior. Do not change backend routes, OpenAPI, generated clients, or automation persistence.
|
||||
- Use `/automations/new?from_run=<run_id>` as the public UI interface.
|
||||
- Treat `from_run` as a draft initializer only. Submitting still calls the existing `automationsApi.createAutomation`.
|
||||
- If a run already has `run.automation.id`, show `View automation` instead of `Create automation from run`.
|
||||
- Do not infer schedules from runs. Prefilled automations use manual/API trigger enabled and schedule disabled.
|
||||
- Do not use direct `useEffect` in route/component code; follow `docs/internal/react-effects-policy.md`.
|
||||
|
||||
## Files
|
||||
|
||||
- Modify `apps/fabro-web/app/routes/run-detail.tsx` for the actions menu navigation.
|
||||
- Modify `apps/fabro-web/app/routes/run-detail.test.ts` for run-action coverage.
|
||||
- Modify `apps/fabro-web/app/routes/automations-new.tsx` for query-param parsing, data loading, and keyed form initialization.
|
||||
- Modify `apps/fabro-web/app/components/automation-form.tsx` for a pure prefill helper built on existing `AutomationFormValues`, `kebabify`, `snakeify`, and `EMPTY_AUTOMATION_FORM`.
|
||||
- Create `apps/fabro-web/app/routes/automations-new.test.tsx` for route-level prefill behavior.
|
||||
|
||||
## Implementation Tasks
|
||||
|
||||
### Task 1: Add A Pure Prefill Helper
|
||||
|
||||
- [ ] In `apps/fabro-web/app/components/automation-form.tsx`, add an exported helper named `automationFormValuesFromRun(run, settings)`.
|
||||
- [ ] The helper should return a complete `AutomationFormValues` object:
|
||||
- `name`: run title if present, otherwise workflow name, graph name, slug, or `"New automation"`.
|
||||
- `id`: `kebabify(name)`.
|
||||
- `description`: empty string.
|
||||
- `enabled`: `true`.
|
||||
- `repository`: prefer `settings.run.scm.owner` plus `settings.run.scm.repository`; otherwise use a GitHub-looking `run.repository.name`; otherwise parse GitHub `origin_url`; otherwise empty string.
|
||||
- `ref`: prefer `sandboxRuntime(run.sandbox)?.clone_branch`; otherwise `"main"`.
|
||||
- `workflow`: prefer `run.workflow.slug`; otherwise `snakeify(workflow name, graph name, or name)`.
|
||||
- `manualEnabled`: `true`.
|
||||
- `scheduleEnabled`: `false`.
|
||||
- `cron`: preserve `EMPTY_AUTOMATION_FORM.cron`.
|
||||
- [ ] Keep repository parsing intentionally narrow: only produce `owner/repo` for GitHub-style values. Leave non-GitHub or unknown repositories blank so users can edit them.
|
||||
|
||||
### Task 2: Wire `/automations/new?from_run=...`
|
||||
|
||||
- [ ] In `apps/fabro-web/app/routes/automations-new.tsx`, import `useSearchParams`, `useRun`, and `useRunSettings`.
|
||||
- [ ] Split the route into a wrapper and a keyed form child:
|
||||
- Wrapper reads `from_run`.
|
||||
- Wrapper calls `useRun(fromRunId)` and `useRunSettings(fromRunId)` only when `from_run` is present.
|
||||
- Wrapper derives initial values during render.
|
||||
- Form child owns `useState(initialValues)` exactly as the current route does.
|
||||
- [ ] For the blank path, preserve current behavior and render immediately with `EMPTY_AUTOMATION_FORM`.
|
||||
- [ ] For `from_run`, render a small loading placeholder until the run query resolves.
|
||||
- [ ] If the source run cannot be loaded, render the normal empty form with a non-blocking `ErrorMessage` explaining that the source run could not be loaded and the automation can be filled manually.
|
||||
- [ ] On cancel, continue navigating to `/automations`.
|
||||
- [ ] On submit success, keep the current toast and navigation to `/automations`.
|
||||
|
||||
### Task 3: Add Run Detail Actions
|
||||
|
||||
- [ ] In `apps/fabro-web/app/routes/run-detail.tsx`, add an operations action after `Preview` and before interrupt/steering actions.
|
||||
- [ ] If `summary.automation?.id` is present:
|
||||
- key: `view-automation`
|
||||
- label: `View automation`
|
||||
- onSelect: navigate to `/automations/${encodeURIComponent(summary.automation.id)}`
|
||||
- [ ] Otherwise:
|
||||
- key: `create-automation`
|
||||
- label: `Create automation from run`
|
||||
- onSelect: navigate to `/automations/new?from_run=${encodeURIComponent(params.id)}`
|
||||
- [ ] Do not disable the action for terminal, active, archived, or demo runs. It is only navigation.
|
||||
|
||||
### Task 4: Add Focused Tests
|
||||
|
||||
- [ ] Add `apps/fabro-web/app/routes/automations-new.test.tsx`.
|
||||
- [ ] Mock `../lib/queries` so `useRun` and `useRunSettings` can return controlled data.
|
||||
- [ ] Test `/automations/new` still renders empty form values.
|
||||
- [ ] Test `/automations/new?from_run=run_1` pre-populates name, slug, repository, branch, workflow, manual trigger, and disabled schedule from mocked run/settings data.
|
||||
- [ ] Test missing source-run data renders the form with an error message and empty editable fields.
|
||||
- [ ] Extend `apps/fabro-web/app/routes/run-detail.test.ts`:
|
||||
- Unlinked run shows `Create automation from run`; selecting it navigates to `/automations/new?from_run=run_1`.
|
||||
- Linked run shows `View automation`; selecting it navigates to `/automations/<automation_id>`.
|
||||
|
||||
## Verification
|
||||
|
||||
- [ ] Run the focused tests:
|
||||
|
||||
```bash
|
||||
cd apps/fabro-web && bun test app/routes/automations-new.test.tsx app/routes/run-detail.test.ts
|
||||
```
|
||||
|
||||
- [ ] Run type checking:
|
||||
|
||||
```bash
|
||||
cd apps/fabro-web && bun run typecheck
|
||||
```
|
||||
|
||||
- [ ] If focused tests expose shared test setup issues, run the full web test suite before finishing:
|
||||
|
||||
```bash
|
||||
cd apps/fabro-web && bun test
|
||||
```
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- From an ordinary run detail page, the actions menu includes `Create automation from run`.
|
||||
- Selecting it opens `/automations/new?from_run=<run_id>` with editable prefilled automation fields.
|
||||
- From a run that already has automation metadata, the actions menu includes `View automation` and does not offer a duplicate-create action.
|
||||
- Creating the automation still uses the existing create automation API and persists the same automation shape as manual creation.
|
||||
- No backend, OpenAPI, generated client, or scheduler files are changed.
|
||||
|
||||
|
||||
## Completed stages
|
||||
- **toolchain**: succeeded
|
||||
- Script: `command -v cargo >/dev/null || { curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y && sudo ln -sf $HOME/.cargo/bin/* /usr/local/bin/; }; cargo --version 2>&1`
|
||||
- Output:
|
||||
```
|
||||
cargo 1.95.0 (f2d3ce0bd 2026-03-21)
|
||||
```
|
||||
- **preflight_compile**: succeeded
|
||||
- Script: `cargo check -q --workspace 2>&1`
|
||||
- Output: (empty)
|
||||
- **preflight_lint**: succeeded
|
||||
- Script: `cargo +nightly-2026-04-14 clippy -q --workspace --all-targets -- -D warnings 2>&1`
|
||||
- Output: (empty)
|
||||
- **implement**: succeeded
|
||||
- Model: gpt-5.5, 1.1m tokens in / 21.5k out
|
||||
|
||||
|
||||
# Simplify: Code Review and Cleanup
|
||||
|
||||
Review changes vs. origin for reuse, quality, and efficiency. Fix any issues found.
|
||||
|
||||
## Phase 1: Identify Changes
|
||||
|
||||
Run git diff (or git diff HEAD if there are staged changes) to see what changed. If there are no git changes, review the most recently modified files that the user mentioned or that you edited earlier in this conversation.
|
||||
|
||||
## Phase 2: Launch Three Review Agents in Parallel
|
||||
|
||||
Use the Agent tool to launch all three agents concurrently in a single message. Pass each agent the full diff so it has the complete context.
|
||||
|
||||
### Agent 1: Code Reuse Review
|
||||
|
||||
For each change:
|
||||
|
||||
1. Search for existing utilities and helpers that could replace newly written code. Use Grep to find similar patterns elsewhere in the codebase — common locations are utility directories, shared modules, and files adjacent to the changed ones.
|
||||
2. Flag any new function that duplicates existing functionality. Suggest the existing function to use instead.
|
||||
3. Flag any inline logic that could use an existing utility — hand-rolled string manipulation, manual path handling, custom environment checks, ad-hoc type guards, and similar patterns are common candidates.
|
||||
|
||||
Note: This is a greenfield app, so focus on maximizing simplicity and don't worry about changing things to achieve it.
|
||||
|
||||
### Agent 2: Code Quality Review
|
||||
|
||||
Review the same changes for hacky patterns:
|
||||
|
||||
1. Redundant state: state that duplicates existing state, cached values that could be derived, observers/effects that could be direct calls
|
||||
2. Parameter sprawl: adding new parameters to a function instead of generalizing or restructuring existing ones
|
||||
3. Copy-paste with slight variation: near-duplicate code blocks that should be unified with a shared abstraction
|
||||
4. Leaky abstractions: exposing internal details that should be encapsulated, or breaking existing abstraction boundaries
|
||||
5. Stringly-typed code: using raw strings where constants, enums (string unions), or branded types already exist in the codebase
|
||||
|
||||
Note: This is a greenfield app, so be aggressive in optimizing quality.
|
||||
|
||||
### Agent 3: Efficiency Review
|
||||
|
||||
Review the same changes for efficiency:
|
||||
|
||||
1. Unnecessary work: redundant computations, repeated file reads, duplicate network/API calls, N+1 patterns
|
||||
2. Missed concurrency: independent operations run sequentially when they could run in parallel
|
||||
3. Hot-path bloat: new blocking work added to startup or per-request/per-render hot paths
|
||||
4. Unnecessary existence checks: pre-checking file/resource existence before operating (TOCTOU anti-pattern) — operate directly and handle the error
|
||||
5. Memory: unbounded data structures, missing cleanup, event listener leaks
|
||||
6. Overly broad operations: reading entire files when only a portion is needed, loading all items when filtering for one
|
||||
|
||||
## Phase 3: Fix Issues
|
||||
|
||||
Wait for all three agents to complete. Aggregate their findings and fix each issue directly. If a finding is a false positive or not worth addressing, note it and move on — do not argue with the finding, just skip it.
|
||||
|
||||
When done, briefly summarize what was fixed (or confirm the code was already clean).
|
||||
5
stages/006-simplify_opus@1/provider_used.json
Normal file
5
stages/006-simplify_opus@1/provider_used.json
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
{
|
||||
"mode": "agent",
|
||||
"provider": "anthropic",
|
||||
"model": "claude-opus-4-7"
|
||||
}
|
||||
26
stages/006-simplify_opus@1/response.md
Normal file
26
stages/006-simplify_opus@1/response.md
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
## Summary of cleanup
|
||||
|
||||
Aggregated findings from three parallel review agents and fixed the meaningful issues:
|
||||
|
||||
**High-priority fixes:**
|
||||
|
||||
1. **Race condition causing lost edits** (`automations-new.tsx`) — Both query agents flagged that `sourceFormKey` keyed on derived `name/repository/ref/workflow` plus a `hasSettings` flag would remount the form (and discard user edits) when the parallel `useRunSettings` query resolved after `useRun`. Fixed by:
|
||||
- Waiting for both queries to settle before mounting the form
|
||||
- Reducing the key to `from-run:${fromRunId}` so SWR revalidation can't trigger spurious remounts
|
||||
- Deleted the `sourceFormKey` helper
|
||||
|
||||
2. **Parameter sprawl in `makeRunSummary`** (`run-detail.test.ts`) — The function had grown to 6 positional args (most `any`-typed and defaulting to `null`). Converted to an options bag and updated all call sites.
|
||||
|
||||
**Medium-priority fixes:**
|
||||
|
||||
3. **Redundant default fields in `automationFormValuesFromRun`** (`automation-form.tsx`) — Removed `description`, `enabled`, `manualEnabled`, `scheduleEnabled`, `cron`, and `ref` fallback since they're already provided by the `...EMPTY_AUTOMATION_FORM` spread. The function is now significantly tighter.
|
||||
|
||||
4. **Duplicated test helper** (`run-detail.test.ts`) — Collapsed `findButtonByText` to delegate to `findButtonsByText` instead of duplicating the `findAll` predicate.
|
||||
|
||||
**Skipped:**
|
||||
|
||||
- Extracting GitHub URL parsing to a shared lib — no other callers exist; keeping it co-located with its single consumer is fine for greenfield.
|
||||
- `firstPresentString` helper — borderline; agent confirmed no existing equivalent and inlining would hurt readability.
|
||||
- Test fixtures still use `any` — pre-existing pattern; not worth widening this diff.
|
||||
|
||||
**Verification:** All 31 tests pass in the focused test suite, `tsc` clean.
|
||||
Loading…
Add table
Reference in a new issue