:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(desktop): back the loops screens with workflows behind a flag (#93225)
Harley Alexanderac68721044f8
diff --git a/products/desktop/packages/api-client/endpoint-allowlist.json b/products/desktop/packages/api-client/endpoint-allowlist.jsonindex 426198685ab1..4d59e3ba28d8 100644--- a/products/desktop/packages/api-client/endpoint-allowlist.json+++ b/products/desktop/packages/api-client/endpoint-allowlist.json@@ -53,6 +53,12 @@"ExternalDataSourceCreate","FeatureFlag","FeatureFlagStatusResponse",+ "HogFlow",+ "HogFlowAction",+ "HogFlowEdge",+ "HogFlowRunResponse",+ "HogFlowSchedule",+ "HogFlowStateEnum","MCPAuthTypeEnum","MCPServerCategoryEnum","MCPServerInstallation",@@ -60,10 +66,14 @@"MCPServerTemplate","MCPToolApprovalStateEnum","OAuthRedirectResponse",+ "PaginatedHogFlowMinimalList",+ "PaginatedTaskDetailDTOList","PaginatedTaskRunDetailDTOList","PaginatedTaskSummaryDTOList","PatchedExternalDataSourceBulkUpdateSchemas","PatchedExternalDataSourceSerializers",+ "PatchedHogFlowSchedule",+ "PatchedHogFlowUpdate","PatchedTaskWrite","PersonRecord","SessionRecording",diff --git a/products/desktop/packages/api-client/src/hogFlowLoops.test.ts b/products/desktop/packages/api-client/src/hogFlowLoops.test.tsnew file mode 100644index 000000000000..dd3d2f193847--- /dev/null+++ b/products/desktop/packages/api-client/src/hogFlowLoops.test.ts@@ -0,0 +1,180 @@+import { describe, expect, it, vi } from "vitest";+import { ApiRequestError } from "./fetcher";+import { type ApiClient, createApiClient, type Fetcher } from "./generated";+import {+ createHogFlow,+ createHogFlowSchedule,+ deleteHogFlow,+ deleteHogFlowSchedule,+ type HogFlowLoopBody,+ hogFlowRequestDetail,+ listHogFlowTasks,+ listLoopHogFlows,+ patchHogFlow,+ retrieveHogFlow,+ runHogFlow,+ updateHogFlowSchedule,+} from "./hogFlowLoops";++function fakeClient(data: unknown = {}): {+ client: ApiClient;+ fetchMock: ReturnType<typeof vi.fn>;+} {+ const fetchMock = vi.fn().mockResolvedValue({+ ok: true,+ status: 200,+ headers: {+ get: (key: string) =>+ key === "content-type" ? "application/json" : null,+ },+ json: () => Promise.resolve(data),+ });+ const fetcher: Fetcher = { fetch: fetchMock };+ const client = createApiClient(fetcher, "https://us.posthog.com");+ return { client, fetchMock };+}++const BODY: HogFlowLoopBody = {+ name: "Loop",+ description: "",+ status: "active",+ origin_product: "loops",+ exit_condition: "exit_only_at_end",+ actions: [],+ edges: [],+};++const SCHEDULE = {+ rrule: "FREQ=DAILY;BYHOUR=9;BYMINUTE=0;BYSECOND=0",+ starts_at: "2026-09-02T09:00:00.000Z",+ timezone: "UTC",+};++describe("hogFlowLoops requests", () => {+ it.each([+ {+ name: "lists only loop-tagged workflows",+ call: (client: ApiClient) => listLoopHogFlows(client, "7"),+ method: "get",+ url: "https://us.posthog.com/api/projects/7/hog_flows/",+ query: "origin_product=loops&limit=100",+ },+ {+ name: "retrieves one workflow",+ call: (client: ApiClient) => retrieveHogFlow(client, "7", "flow-1"),+ method: "get",+ url: "https://us.posthog.com/api/projects/7/hog_flows/flow-1/",+ },+ {+ name: "creates a workflow",+ call: (client: ApiClient) => createHogFlow(client, "7", BODY),+ method: "post",+ url: "https://us.posthog.com/api/projects/7/hog_flows/",+ body: BODY,+ },+ {+ name: "patches a workflow",+ call: (client: ApiClient) =>+ patchHogFlow(client, "7", "flow-1", { status: "draft" }),+ method: "patch",+ url: "https://us.posthog.com/api/projects/7/hog_flows/flow-1/",+ body: { status: "draft" },+ },+ {+ name: "patches a workflow against the version it last loaded",+ call: (client: ApiClient) =>+ patchHogFlow(client, "7", "flow-1", {+ name: "Renamed",+ base_updated_at: "2026-09-02T08:00:00Z",+ }),+ method: "patch",+ url: "https://us.posthog.com/api/projects/7/hog_flows/flow-1/",+ body: { name: "Renamed", base_updated_at: "2026-09-02T08:00:00Z" },+ },+ {+ name: "deletes a workflow",+ call: (client: ApiClient) => deleteHogFlow(client, "7", "flow-1"),+ method: "delete",+ url: "https://us.posthog.com/api/projects/7/hog_flows/flow-1/",+ },+ {+ name: "creates a schedule",+ call: (client: ApiClient) =>+ createHogFlowSchedule(client, "7", "flow-1", SCHEDULE),+ method: "post",+ url: "https://us.posthog.com/api/projects/7/hog_flows/flow-1/schedules/",+ body: SCHEDULE,+ },+ {+ name: "updates a schedule",+ call: (client: ApiClient) =>+ updateHogFlowSchedule(client, "7", "flow-1", "sched-1", SCHEDULE),+ method: "patch",+ url: "https://us.posthog.com/api/projects/7/hog_flows/flow-1/schedules/sched-1/",+ body: SCHEDULE,+ },+ {+ name: "deletes a schedule",+ call: (client: ApiClient) =>+ deleteHogFlowSchedule(client, "7", "flow-1", "sched-1"),+ method: "delete",+ url: "https://us.posthog.com/api/projects/7/hog_flows/flow-1/schedules/sched-1/",+ },+ {+ name: "lists the tasks a workflow created, newest first",+ call: (client: ApiClient) =>+ listHogFlowTasks(client, "7", "flow-1", { limit: 10 }),+ method: "get",+ url: "https://us.posthog.com/api/projects/7/tasks/",+ query: "hog_flow_id=flow-1&limit=10&ordering=-created_at&archived=all",+ },+ ])("$name", async ({ call, method, url, query, body }) => {+ const { client, fetchMock } = fakeClient();+ await call(client);+ expect(fetchMock).toHaveBeenCalledTimes(1);+ const request = fetchMock.mock.calls[0][0];+ expect(request.method).toBe(method);+ expect(request.url.toString()).toBe(url);+ expect(request.urlSearchParams?.toString() ?? "").toBe(query ?? "");+ if (body) {+ expect(request.parameters?.body).toEqual(body);+ }+ });++ it("sends the idempotency key with a run request", async () => {+ const { client, fetchMock } = fakeClient({+ status: "queued",+ invocation_id: "inv-1",+ });+ const result = await runHogFlow(client, "7", "flow-1", "key-123");+ expect(result.invocation_id).toBe("inv-1");+ const request = fetchMock.mock.calls[0][0];+ expect(request.url.toString()).toBe(+ "https://us.posthog.com/api/projects/7/hog_flows/flow-1/run/",+ );+ expect(request.parameters?.header).toEqual({+ "Idempotency-Key": "key-123",+ });+ });++ it.each([+ [+ "a DRF detail",+ { detail: "Workflow must be active to run." },+ "Workflow must be active to run.",+ ],+ [+ "a nested serializer rejection",+ { actions: [{ inputs: { prompt: ["Instructions are required."] } }] },+ "Instructions are required.",+ ],+ ["a body with no message", { count: 3 }, null],+ ])("reads %s out of a failed request", (_label, body, expected) => {+ const error = new ApiRequestError(400, JSON.stringify(body), body);+ expect(hogFlowRequestDetail(error)).toBe(expected);+ });++ it("ignores errors that did not come from a request", () => {+ expect(hogFlowRequestDetail(new Error("offline"))).toBeNull();+ });+});diff --git a/products/desktop/packages/api-client/src/hogFlowLoops.ts b/products/desktop/packages/api-client/src/hogFlowLoops.tsnew file mode 100644index 000000000000..8aa62d844828--- /dev/null+++ b/products/desktop/packages/api-client/src/hogFlowLoops.ts@@ -0,0 +1,213 @@+import { ApiRequestError } from "./fetcher";+import type { ApiClient, Schemas } from "./generated";++/**+ * Requests behind a workflow-backed loop: the `hog_flows` endpoints Desktop+ * Loops read and write when `loops-hog-flows` is on, plus the tasks list that+ * serves as the loop's run history.+ */++export const LOOPS_ORIGIN_PRODUCT = "loops";++export type HogFlowLoopStatus = Extract<+ Schemas.HogFlowStateEnum,+ "active" | "draft"+>;++/** The fields a loop writes on a workflow. Everything else keeps its default. */+export interface HogFlowLoopBody {+ name: string;+ description: string;+ status: HogFlowLoopStatus;+ origin_product: typeof LOOPS_ORIGIN_PRODUCT;+ exit_condition: "exit_only_at_end";+ actions: Schemas.HogFlowAction[];+ edges: Schemas.HogFlowEdge[];+}++/** Optimistic-concurrency fields a patch may carry beside the loop body.+ * `base_updated_at` is the `updated_at` the client last loaded; the server+ * answers 409 when the workflow moved past it, instead of taking the write. */+export interface HogFlowPatchOptions {+ base_updated_at?: string;+}++export interface HogFlowScheduleWrite {+ rrule: string;+ starts_at: string;+ timezone: string;+}++const HOG_FLOWS_LIST_LIMIT = 100;++export async function listLoopHogFlows(+ client: ApiClient,+ projectId: string,+): Promise<Schemas.PaginatedHogFlowMinimalList> {+ return client.get("/api/projects/{project_id}/hog_flows/", {+ path: { project_id: projectId },+ query: {+ origin_product: LOOPS_ORIGIN_PRODUCT,+ limit: HOG_FLOWS_LIST_LIMIT,+ },+ });+}++export async function retrieveHogFlow(+ client: ApiClient,+ projectId: string,+ hogFlowId: string,+): Promise<Schemas.HogFlow> {+ return client.get("/api/projects/{project_id}/hog_flows/{id}/", {+ path: { project_id: projectId, id: hogFlowId },+ });+}++// The generated create/patch bodies are the read schema, which carries server+// owned fields (id, version, timestamps). The loop body is the writable subset.+export async function createHogFlow(+ client: ApiClient,+ projectId: string,+ body: HogFlowLoopBody,+): Promise<Schemas.HogFlow> {+ return client.post("/api/projects/{project_id}/hog_flows/", {+ path: { project_id: projectId },+ body: body as unknown as Schemas.HogFlow,+ });+}++export async function patchHogFlow(+ client: ApiClient,+ projectId: string,+ hogFlowId: string,+ body: Partial<HogFlowLoopBody> & HogFlowPatchOptions,+): Promise<Schemas.HogFlow> {+ return client.patch("/api/projects/{project_id}/hog_flows/{id}/", {+ path: { project_id: projectId, id: hogFlowId },+ body: body as Schemas.PatchedHogFlowUpdate,+ });+}++export async function deleteHogFlow(+ client: ApiClient,+ projectId: string,+ hogFlowId: string,+): Promise<void> {+ await client.delete("/api/projects/{project_id}/hog_flows/{id}/", {+ path: { project_id: projectId, id: hogFlowId },+ });+}++export async function createHogFlowSchedule(+ client: ApiClient,+ projectId: string,+ hogFlowId: string,+ body: HogFlowScheduleWrite,+): Promise<Schemas.HogFlowSchedule> {+ return client.post("/api/projects/{project_id}/hog_flows/{id}/schedules/", {+ path: { project_id: projectId, id: hogFlowId },+ body: body as unknown as Schemas.HogFlowSchedule,+ });+}++export async function updateHogFlowSchedule(+ client: ApiClient,+ projectId: string,+ hogFlowId: string,+ scheduleId: string,+ body: HogFlowScheduleWrite,+): Promise<Schemas.HogFlowSchedule> {+ return client.patch(+ "/api/projects/{project_id}/hog_flows/{id}/schedules/{schedule_id}/",+ {+ path: { project_id: projectId, id: hogFlowId, schedule_id: scheduleId },+ body: body as Schemas.PatchedHogFlowSchedule,+ },+ );+}++export async function deleteHogFlowSchedule(+ client: ApiClient,+ projectId: string,+ hogFlowId: string,+ scheduleId: string,+): Promise<void> {+ await client.delete(+ "/api/projects/{project_id}/hog_flows/{id}/schedules/{schedule_id}/",+ {+ path: { project_id: projectId, id: hogFlowId, schedule_id: scheduleId },+ },+ );+}++/** Fires a schedule-triggered workflow now. The key dedupes a retry of the+ * same click: the server returns the first run instead of queueing a second. */+export async function runHogFlow(+ client: ApiClient,+ projectId: string,+ hogFlowId: string,+ idempotencyKey: string,+): Promise<Schemas.HogFlowRunResponse> {+ // The endpoint declares no header parameters, so the generated type has no+ // slot for one; the fetcher still forwards `header` at runtime. A variable+ // sidesteps the object-literal excess property check without a cast.+ const params = {+ path: { project_id: projectId, id: hogFlowId },+ body: {},+ header: { "Idempotency-Key": idempotencyKey },+ };+ return client.post("/api/projects/{project_id}/hog_flows/{id}/run/", params);+}++export async function listHogFlowTasks(+ client: ApiClient,+ projectId: string,+ hogFlowId: string,+ options: { limit: number },+): Promise<Schemas.PaginatedTaskDetailDTOList> {+ return client.get("/api/projects/{project_id}/tasks/", {+ path: { project_id: projectId },+ query: {+ hog_flow_id: hogFlowId,+ limit: options.limit,+ ordering: "-created_at",+ // Run history is an audit trail; archiving a task tidies the task list+ // and must not rewrite what the loop did.+ archived: "all",+ },+ });+}++function firstString(value: unknown): string | null {+ if (typeof value === "string") return value;+ if (Array.isArray(value)) {+ for (const item of value) {+ const found = firstString(item);+ if (found) return found;+ }+ return null;+ }+ if (value && typeof value === "object") {+ for (const item of Object.values(value)) {+ const found = firstString(item);+ if (found) return found;+ }+ }+ return null;+}++/**+ * A readable reason from a failed workflow request. DRF puts a plain+ * rejection under `detail`; a serializer rejection nests messages under field+ * names (`{"actions": [{"inputs": {"prompt": ["..."]}}]}`), so the first+ * string anywhere in the body is the message a person can act on.+ */+export function hogFlowRequestDetail(error: unknown): string | null {+ if (!(error instanceof ApiRequestError)) return null;+ const body = error.body;+ if (body && typeof body === "object" && "detail" in body) {+ const detail = (body as { detail: unknown }).detail;+ if (typeof detail === "string") return detail;+ }+ return firstString(body);+}diff --git a/products/desktop/packages/shared/src/flags.ts b/products/desktop/packages/shared/src/flags.tsindex f8576c0ea647..ad7d445bef66 100644--- a/products/desktop/packages/shared/src/flags.ts+++ b/products/desktop/packages/shared/src/flags.ts@@ -20,6 +20,8 @@ export const PROJECT_BLUEBIRD_FLAG = "project-bluebird";export const CHANNELS_LAYOUT_FLAG = "code-spaces-layout";// Gates the Loops feature: the sidebar Loops space and the per-channel Loops tab.export const LOOPS_FLAG = "loops";+/** Desktop Loops read and write workflows (`hog_flows`) instead of the loops API. */+export const LOOPS_HOG_FLOWS_FLAG = "loops-hog-flows";export const DESKTOP_HOME_FLAG = "desktop-home-flag";export const SAVED_SEARCHES_RAIL_FLAG = "posthog-desktop-saved-searches-rail";export const TASKS_PREWARM_SANDBOX_FLAG = "tasks-prewarm-sandbox";diff --git a/products/desktop/packages/ui/src/features/feature-flags/useLoopsHogFlowsEnabled.ts b/products/desktop/packages/ui/src/features/feature-flags/useLoopsHogFlowsEnabled.tsnew file mode 100644index 000000000000..98ccb68a7500--- /dev/null+++ b/products/desktop/packages/ui/src/features/feature-flags/useLoopsHogFlowsEnabled.ts@@ -0,0 +1,11 @@+import { LOOPS_HOG_FLOWS_FLAG } from "@posthog/shared";+import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";++/**+ * Whether the Loops screens are backed by workflows (`hog_flows`) instead of+ * the loops API. One hook so the list, detail, form and mutations flip+ * together; a mixed state would write to one backend and read from the other.+ */+export function useLoopsHogFlowsEnabled(): boolean {+ return useFeatureFlag(LOOPS_HOG_FLOWS_FLAG);+}diff --git a/products/desktop/packages/ui/src/features/loops/components/LoopDetailView.tsx b/products/desktop/packages/ui/src/features/loops/components/LoopDetailView.tsxindex a8e849be1316..c98ed153f842 100644--- a/products/desktop/packages/ui/src/features/loops/components/LoopDetailView.tsx+++ b/products/desktop/packages/ui/src/features/loops/components/LoopDetailView.tsx@@ -1,5 +1,6 @@import {ArrowLeftIcon,+ ArrowSquareOutIcon,CheckCircleIcon,LinkIcon,PauseIcon,@@ -7,6 +8,7 @@ import {PlayIcon,TrashIcon,} from "@phosphor-icons/react";+import { hogFlowRequestDetail } from "@posthog/api-client/hogFlowLoops";import type { LoopSchemas } from "@posthog/api-client/loops";import { isUploadableSkillSource } from "@posthog/core/message-editor/skillTags";import { useHostTRPC } from "@posthog/host-router/react";@@ -21,6 +23,7 @@ import {Badge,Button,} from "@posthog/quill";+import { getCloudUrlFromRegion } from "@posthog/shared";import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";import { UserAvatar } from "@posthog/ui/features/auth/UserAvatar";import { assertCloudUsageAvailable } from "@posthog/ui/features/billing/preflightCloudUsage";@@ -28,6 +31,7 @@ import { useUsageLimitStore } from "@posthog/ui/features/billing/usageLimitStoreimport { useChannelsLayout } from "@posthog/ui/features/canvas/hooks/useChannelsLayout";import { useOrgMembers } from "@posthog/ui/features/canvas/hooks/useOrgMembers";import { userDisplayName } from "@posthog/ui/features/canvas/utils/userDisplay";+import { useLoopsHogFlowsEnabled } from "@posthog/ui/features/feature-flags/useLoopsHogFlowsEnabled";import { useSetHeaderContent } from "@posthog/ui/hooks/useSetHeaderContent";import { Button as ActionButton } from "@posthog/ui/primitives/Button";import { TimezoneTimestamp } from "@posthog/ui/primitives/TimezoneTimestamp";@@ -40,13 +44,15 @@ import {} from "@posthog/ui/router/navigationBridge";import { getRouterOrNull } from "@posthog/ui/router/routerRef";import { track } from "@posthog/ui/shell/analytics";+import { openExternalUrl } from "@posthog/ui/shell/openExternal";import { useHostCapabilities } from "@posthog/ui/shell/useHostCapabilities";import { Flex, Text } from "@radix-ui/themes";import type { ParsedHistoryState } from "@tanstack/history";import { useQuery } from "@tanstack/react-query";import { useLocation } from "@tanstack/react-router";import { useCallback, useEffect, useMemo, useRef, useState } from "react";-import { useLoop } from "../hooks/useLoop";+import { useAuthStateValue } from "../../auth/store";+import { useLoop, useLoopHogFlow } from "../hooks/useLoop";import {useDeleteLoop,useRunLoop,@@ -67,10 +73,12 @@ import {nextScheduleRun,summarizeNotificationDestinations,} from "../loopDisplay";+import { hogFlowTeamSkills, isLoopShapedHogFlow } from "../loopHogFlowMapping";import { formatLoopModel } from "../loopModels";import { loopSkillBundles, primaryLoopSkillBundle } from "../loopSkill";import { copyLoopLink } from "../utils/copyLoopLink";import { LoopLoadError } from "./LoopFallbacks";+import { LoopForeignWorkflowNotice } from "./LoopForeignWorkflowNotice";import { LoopForm } from "./LoopForm";import { LoopHeaderTitle } from "./LoopHeaderTitle";import { LoopRunRow } from "./LoopRunRow";@@ -94,6 +102,23 @@ export function LoopDetailView({select: (location) => location.state.loopListOrigin === true,});const { data: loop, isLoading, isError } = useLoop(loopId);+ const workflowBacked = useLoopsHogFlowsEnabled();+ const { data: hogFlow } = useLoopHogFlow(workflowBacked ? loopId : undefined);+ // A loop-tagged workflow someone reshaped in the workflow editor: the form+ // would overwrite what they built, so the page goes read-only for it.+ const foreignWorkflow =+ workflowBacked && !!hogFlow && !isLoopShapedHogFlow(hogFlow);+ // An archived workflow maps to a paused loop, but resuming it would set it+ // active again rather than restore it, so it is shown read-only instead.+ const archived = workflowBacked && hogFlow?.status === "archived";+ const readOnly = foreignWorkflow || archived;+ const teamSkills = hogFlow ? hogFlowTeamSkills(hogFlow) : [];+ const cloudRegion = useAuthStateValue((state) => state.cloudRegion);+ const projectId = useAuthStateValue((state) => state.currentProjectId);+ const workflowUrl =+ workflowBacked && cloudRegion && projectId != null+ ? `${getCloudUrlFromRegion(cloudRegion)}/project/${projectId}/workflows/${loopId}/workflow`+ : null;const updateLoop = useUpdateLoop(loopId);const deleteLoop = useDeleteLoop();const runLoop = useRunLoop(loopId);@@ -206,7 +231,9 @@ export function LoopDetailView({}} catch (error) {toast.error("Failed to start run", {- description: error instanceof Error ? error.message : String(error),+ description:+ hogFlowRequestDetail(error) ??+ (error instanceof Error ? error.message : String(error)),});} finally {setRunNowPending(false);@@ -236,6 +263,14 @@ export function LoopDetailView({if (startEditing) setIsEditing(true);}, [startEditing]);+ // The workflow loads after the page opens, so an edit URL can land in the+ // form before the read-only check has an answer. Back out once it does.+ useEffect(() => {+ if (!readOnly) return;+ setIsEditing(false);+ setEditDirty(false);+ }, [readOnly]);+const leavePage = useCallback(() => {if (hasLoopListOrigin && canGoBackInHistory()) {goBackInHistory();@@ -360,6 +395,12 @@ export function LoopDetailView({return <LoopLoadError />;}+ // The workflow run endpoint only accepts schedule triggers; a GitHub loop+ // fires from its repository.+ const canRunNow =+ !readOnly && (!workflowBacked || loop.triggers[0]?.type === "schedule");+ const githubTriggered = loop.triggers[0]?.type === "github";+return (<div className="h-full min-h-0 overflow-y-auto"><Flex@@ -386,26 +427,32 @@ export function LoopDetailView({>{loop.name}</Text>- <Badge variant={loopStatusBadgeVariant(loop)}>- {loopStatusLabel(loop)}+ <Badge+ variant={archived ? "default" : loopStatusBadgeVariant(loop)}+ >+ {archived ? "Archived" : loopStatusLabel(loop)}</Badge>- <Badge>{formatVisibility(loop.visibility)}</Badge>+ {!workflowBacked ? (+ <Badge>{formatVisibility(loop.visibility)}</Badge>+ ) : null}</Flex><Flex align="center" gap="2">- <Button- variant="outline"- size="sm"- loading={updateLoop.isPending}- disabled={updateLoop.isPending}- onClick={() => handleToggleEnabled(!loop.enabled)}- >- {loop.enabled ? (- <PauseIcon size={14} />- ) : (- <PlayIcon size={14} />- )}- {loop.enabled ? "Pause" : "Resume"}- </Button>+ {!archived ? (+ <Button+ variant="outline"+ size="sm"+ loading={updateLoop.isPending}+ disabled={updateLoop.isPending}+ onClick={() => handleToggleEnabled(!loop.enabled)}+ >+ {loop.enabled ? (+ <PauseIcon size={14} />+ ) : (+ <PlayIcon size={14} />+ )}+ {loop.enabled ? "Pause" : "Resume"}+ </Button>+ ) : null}<Buttonvariant="outline"size="sm"@@ -414,39 +461,43 @@ export function LoopDetailView({<LinkIcon size={14} />Copy link</Button>- <Button- variant="outline"- size="sm"- loading={runNowPending}- disabled={runNowPending}- onClick={() => void handleRunNow()}- >- <PlayIcon size={14} />- Run now- </Button>- <Button- variant="outline"- size="sm"- className={- isEditing- ? "border-(--accent-7) bg-(--accent-3) text-(--accent-11)"- : undefined- }- onClick={() => {- if (isEditing) {- requestLeaveEdit("summary");- return;+ {canRunNow ? (+ <Button+ variant="outline"+ size="sm"+ loading={runNowPending}+ disabled={runNowPending}+ onClick={() => void handleRunNow()}+ >+ <PlayIcon size={14} />+ Run now+ </Button>+ ) : null}+ {!readOnly ? (+ <Button+ variant="outline"+ size="sm"+ className={+ isEditing+ ? "border-(--accent-7) bg-(--accent-3) text-(--accent-11)"+ : undefined}- setIsEditing(true);- }}- >- {isEditing ? (- <CheckCircleIcon size={14} weight="fill" />- ) : (- <PencilSimpleIcon size={14} />- )}- {isEditing ? "Editing" : "Edit"}- </Button>+ onClick={() => {+ if (isEditing) {+ requestLeaveEdit("summary");+ return;+ }+ setIsEditing(true);+ }}+ >+ {isEditing ? (+ <CheckCircleIcon size={14} weight="fill" />+ ) : (+ <PencilSimpleIcon size={14} />+ )}+ {isEditing ? "Editing" : "Edit"}+ </Button>+ ) : null}<Buttonvariant="destructive"size="sm"@@ -469,7 +520,11 @@ export function LoopDetailView({<PausedNotice loop={loop} /></Flex>- {isEditing ? (+ {archived ? (+ <LoopArchivedNotice workflowUrl={workflowUrl} />+ ) : foreignWorkflow ? (+ <LoopForeignWorkflowNotice workflowUrl={workflowUrl} />+ ) : isEditing ? (<LoopFormloop={loop}variant="embedded"@@ -483,7 +538,11 @@ export function LoopDetailView({/>) : (<>- <ConfigSummarySection loop={loop} />+ <ConfigSummarySection+ loop={loop}+ workflowBacked={workflowBacked}+ teamSkills={teamSkills}+ /><InstructionsSection loop={loop} /></>)}@@ -510,8 +569,11 @@ export function LoopDetailView({No runs yet</Text><Text className="max-w-sm text-[11.5px] text-gray-10 leading-snug">- Runs show up here once this loop fires. Trigger one with Run- now, or wait for its next trigger.+ {canRunNow+ ? "Runs show up here once this loop fires. Trigger one with Run now, or wait for its next trigger."+ : githubTriggered+ ? "Runs show up here once this loop fires. A matching event in the repository starts a run."+ : "Runs show up here once this loop fires."}</Text></Flex>) : (@@ -604,6 +666,36 @@ function formatVisibility(visibility: LoopSchemas.LoopVisibilityEnum): string {return visibility.charAt(0).toUpperCase() + visibility.slice(1);}+/**+ * Shown in place of the configuration summary for an archived workflow. The+ * loop API has no archived state, so resuming from here would set the workflow+ * active instead of restoring it; restoring happens in PostHog.+ */+function LoopArchivedNotice({ workflowUrl }: { workflowUrl: string | null }) {+ return (+ <div className="flex flex-col gap-2 rounded-(--radius-2) border border-border bg-(--gray-2) px-3 py-3">+ <span className="font-medium text-[12.5px] text-gray-12">+ This loop is archived+ </span>+ <span className="text-[12px] text-gray-11 leading-snug">+ It no longer runs and can't be edited here. Restore it in PostHog to+ bring it back, or delete it here. Run history stays available.+ </span>+ {workflowUrl ? (+ <Button+ variant="outline"+ size="sm"+ className="w-fit"+ onClick={() => openExternalUrl(workflowUrl)}+ >+ <ArrowSquareOutIcon size={14} />+ Open in PostHog+ </Button>+ ) : null}+ </div>+ );+}+function PausedNotice({ loop }: { loop: LoopSchemas.Loop }) {const description = loopPausedDescription(loop);if (!description) return null;@@ -634,7 +726,15 @@ function PausedNotice({ loop }: { loop: LoopSchemas.Loop }) {);}-function ConfigSummarySection({ loop }: { loop: LoopSchemas.Loop }) {+function ConfigSummarySection({+ loop,+ workflowBacked,+ teamSkills,+}: {+ loop: LoopSchemas.Loop;+ workflowBacked: boolean;+ teamSkills: string[];+}) {const displayModel = formatLoopModel(loop.runtime_adapter, loop.model);const {members,@@ -677,7 +777,7 @@ function ConfigSummarySection({ loop }: { loop: LoopSchemas.Loop }) {><SummaryRow label="Model">{[- loop.runtime_adapter,+ workflowBacked ? null : loop.runtime_adapter,displayModel,loop.reasoning_effort ? `${loop.reasoning_effort} reasoning` : null,]@@ -691,6 +791,10 @@ function ConfigSummarySection({ loop }: { loop: LoopSchemas.Loop }) {</SummaryRow>) : null}+ {teamSkills.length > 0 ? (+ <SummaryRow label="Skills">{teamSkills.join(", ")}</SummaryRow>+ ) : null}+<SummaryRow label="Repository">{loop.repositories.length > 0? loop.repositories.map((repo) => repo.full_name).join(", ")diff --git a/products/desktop/packages/ui/src/features/loops/components/LoopForeignWorkflowNotice.tsx b/products/desktop/packages/ui/src/features/loops/components/LoopForeignWorkflowNotice.tsxnew file mode 100644index 000000000000..900b74e6d0c1--- /dev/null+++ b/products/desktop/packages/ui/src/features/loops/components/LoopForeignWorkflowNotice.tsx@@ -0,0 +1,38 @@+import { ArrowSquareOut } from "@phosphor-icons/react";+import { Button } from "@posthog/quill";+import { openExternalUrl } from "@posthog/ui/shell/openExternal";++/**+ * Shown in place of the configuration summary when the workflow behind a loop+ * no longer has the shape the loop editor writes. Saving from here would+ * replace the whole graph, so editing moves to the workflow editor.+ */+export function LoopForeignWorkflowNotice({+ workflowUrl,+}: {+ workflowUrl: string | null;+}) {+ return (+ <div className="flex flex-col gap-2 rounded-(--radius-2) border border-(--amber-6) bg-(--amber-2) px-3 py-3">+ <span className="font-medium text-(--amber-12) text-[12.5px]">+ This loop was changed in the workflow editor+ </span>+ <span className="text-(--amber-11) text-[12px] leading-snug">+ It now has steps or triggers the loop editor can't show. Open it in+ PostHog to change it, or delete it here. Run history and the pause+ toggle still work.+ </span>+ {workflowUrl ? (+ <Button+ variant="outline"+ size="sm"+ className="w-fit"+ onClick={() => openExternalUrl(workflowUrl)}+ >+ <ArrowSquareOut size={14} />+ Open in PostHog+ </Button>+ ) : null}+ </div>+ );+}diff --git a/products/desktop/packages/ui/src/features/loops/components/LoopForm.test.tsx b/products/desktop/packages/ui/src/features/loops/components/LoopForm.test.tsxnew file mode 100644index 000000000000..3df51747d69b--- /dev/null+++ b/products/desktop/packages/ui/src/features/loops/components/LoopForm.test.tsx@@ -0,0 +1,380 @@+import { ApiRequestError } from "@posthog/api-client/fetcher";+import type { Schemas } from "@posthog/api-client/generated";+import { render, screen, waitFor } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { useLoopDraftStore } from "../loopDraftStore";+import {+ emptyLoopFormValues,+ type LoopFormValues,+ type LoopTriggerDraft,+} from "../loopFormTypes";+import { formValuesToHogFlowWrite, hogFlowToLoop } from "../loopHogFlowMapping";+import { LoopScheduleSaveError } from "../loopHogFlowWrites";+import { LoopForm } from "./LoopForm";++const mocks = vi.hoisted(() => ({+ hogFlow: undefined as unknown,+ workflowBacked: true,+ updateHogFlow: vi.fn(),+ createHogFlow: vi.fn(),+ toastError: vi.fn(),+}));++vi.mock("@posthog/ui/features/feature-flags/useLoopsHogFlowsEnabled", () => ({+ useLoopsHogFlowsEnabled: () => mocks.workflowBacked,+}));+vi.mock("@posthog/ui/features/feature-flags/useBluebirdFlag", () => ({+ useBluebirdFlag: () => false,+}));+vi.mock("@posthog/ui/features/canvas/hooks/useChannelsLayout", () => ({+ useChannelsLayout: () => false,+}));+vi.mock("@posthog/ui/features/sidebar/sidebarStore", () => ({+ useSidebarStore: (+ selector: (state: { channelsEnabled: boolean }) => unknown,+ ) => selector({ channelsEnabled: false }),+}));+vi.mock(+ "@posthog/ui/features/settings/sections/environments/useSandboxEnvironments",+ () => ({+ useSandboxEnvironments: () => ({ environments: [], isLoading: false }),+ }),+);+vi.mock("@posthog/ui/hooks/useSetHeaderContent", () => ({+ useSetHeaderContent: () => {},+}));+vi.mock("@posthog/ui/primitives/toast", () => ({+ toast: { error: mocks.toastError, success: vi.fn() },+}));+vi.mock("@posthog/ui/router/navigationBridge", () => ({+ navigateToLoopDetail: vi.fn(),+ navigateToLoops: vi.fn(),+}));+vi.mock("@posthog/ui/shell/analytics", () => ({ track: vi.fn() }));+vi.mock("../../auth/store", () => ({+ useAuthStateValue: (+ selector: (state: { currentProjectId: string }) => unknown,+ ) => selector({ currentProjectId: "7" }),+}));+vi.mock("../hooks/useLoop", () => ({+ useLoopHogFlow: () => ({ data: mocks.hogFlow }),+}));+vi.mock("../hooks/useLoopMutations", () => {+ const idle = () => ({ mutateAsync: vi.fn(), isPending: false });+ return {+ useCreateLoop: idle,+ useUpdateLoop: idle,+ useDeleteLoop: idle,+ useCreateLoopHogFlow: () => ({+ mutateAsync: mocks.createHogFlow,+ isPending: false,+ }),+ useUpdateLoopHogFlow: () => ({+ mutateAsync: mocks.updateHogFlow,+ isPending: false,+ }),+ };+});+vi.mock("../hooks/useLoopSkillBundles", () => {+ const idle = () => ({ mutateAsync: vi.fn(), isPending: false });+ return { useBundleLocalSkill: idle, useReplaceLoopSkillBundles: idle };+});+vi.mock("@posthog/ui/features/settings/SettingsOptionSelect", () => ({+ SettingsOptionSelect: () => null,+}));+vi.mock("./LoopBehaviorFields", () => ({ LoopBehaviorFields: () => null }));+vi.mock("./LoopContextFields", () => ({ LoopContextFields: () => null }));+vi.mock("./LoopHeaderTitle", () => ({ LoopHeaderTitle: () => null }));+vi.mock("./LoopModelFields", () => ({ LoopModelFields: () => null }));+vi.mock("./LoopNotificationsFields", () => ({+ LoopNotificationsFields: () => null,+}));+vi.mock("./LoopRepositoryPicker", () => ({ LoopRepositoryPicker: () => null }));+vi.mock("./LoopSkillFields", () => ({ LoopInstructionsFields: () => null }));+vi.mock("./LoopSpaceBreadcrumb", () => ({ LoopSpaceBreadcrumb: () => null }));+vi.mock("./LoopWorkflowPromptFields", () => ({+ LoopWorkflowPromptFields: () => null,+}));+vi.mock("./LoopTriggerEditor", () => ({+ LoopTriggerEditor: ({+ triggers,+ onChange,+ }: {+ triggers: LoopTriggerDraft[];+ onChange: (triggers: LoopTriggerDraft[]) => void;+ }) => (+ <div>+ <div data-testid="triggers">+ {triggers+ .map((trigger) =>+ "cron_expression" in trigger.config+ ? trigger.config.cron_expression+ : trigger.type,+ )+ .join(",")}+ </div>+ <button type="button" onClick={() => onChange([])}>+ Remove triggers+ </button>+ </div>+ ),+}));++const PROJECT_ID = 7;++function scheduleTrigger(cron: string): LoopTriggerDraft {+ return {+ key: "t1",+ type: "schedule",+ enabled: true,+ config: { cron_expression: cron, timezone: "UTC" },+ };+}++function formValues(overrides: Partial<LoopFormValues> = {}): LoopFormValues {+ return {+ ...emptyLoopFormValues(),+ name: "Morning triage",+ instructions: "Triage the inbox.",+ triggers: [scheduleTrigger("0 9 * * *")],+ ...overrides,+ };+}++/** A workflow shaped exactly as the form writes it, with the given stamp. */+function loopShapedFlow(+ values: LoopFormValues,+ updatedAt: string,+): Schemas.HogFlow {+ const { flow, schedule } = formValuesToHogFlowWrite(values, {+ enabled: true,+ });+ return {+ id: "flow-1",+ name: flow.name,+ description: flow.description,+ status: flow.status,+ created_at: "2026-09-01T08:00:00Z",+ updated_at: updatedAt,+ actions: flow.actions,+ edges: flow.edges,+ schedules: schedule+ ? [+ {+ id: "sched-1",+ ...schedule,+ status: "active",+ next_run_at: null,+ created_at: "2026-09-01T08:00:00Z",+ updated_at: "2026-09-01T08:00:00Z",+ },+ ]+ : [],+ } as unknown as Schemas.HogFlow;+}++function renderEdit(flow: Schemas.HogFlow) {+ mocks.hogFlow = flow;+ const loop = hogFlowToLoop(flow, { projectId: PROJECT_ID });+ const view = render(<LoopForm loop={loop} variant="embedded" />);+ const rerenderWith = (nextFlow: Schemas.HogFlow) => {+ mocks.hogFlow = nextFlow;+ view.rerender(+ <LoopForm+ loop={hogFlowToLoop(nextFlow, { projectId: PROJECT_ID })}+ variant="embedded"+ />,+ );+ };+ return { ...view, rerenderWith };+}++const saveButton = () => screen.getByRole("button", { name: "Save changes" });+const nameInput = () => screen.getByPlaceholderText("Daily standup summary");++describe("LoopForm", () => {+ beforeEach(() => {+ mocks.workflowBacked = true;+ mocks.hogFlow = undefined;+ mocks.updateHogFlow.mockReset();+ mocks.createHogFlow.mockReset();+ mocks.toastError.mockReset();+ useLoopDraftStore.getState().setPrefill(null);+ });++ it("refuses to save over a workflow that no longer has the loop shape", async () => {+ const user = userEvent.setup();+ const flow = loopShapedFlow(formValues(), "2026-09-02T08:00:00Z");+ // A staged draft in the workflow editor keeps the loop readable but+ // makes the graph foreign; the form itself still looks valid.+ renderEdit({ ...flow, draft: { actions: [] } } as Schemas.HogFlow);++ await user.click(saveButton());++ expect(mocks.updateHogFlow).not.toHaveBeenCalled();+ expect(mocks.toastError).toHaveBeenCalledWith(+ "This loop was changed in the workflow editor",+ expect.anything(),+ );+ });++ it("shows the remote-change banner and blocks saving after a stale-write refusal", async () => {+ const user = userEvent.setup();+ mocks.updateHogFlow.mockRejectedValue(+ new ApiRequestError(409, "{}", { detail: "stale" }),+ );+ renderEdit(loopShapedFlow(formValues(), "2026-09-02T08:00:00Z"));++ await user.click(saveButton());++ expect(+ await screen.findByText("This loop changed elsewhere"),+ ).toBeInTheDocument();+ expect(saveButton()).toBeDisabled();+ expect(mocks.toastError).toHaveBeenCalledWith(+ "Loop changed elsewhere",+ expect.anything(),+ );+ });++ it("lets the person save again after the graph stuck but the schedule did not", async () => {+ const user = userEvent.setup();+ const values = formValues();+ const flow = loopShapedFlow(values, "2026-09-02T08:00:00Z");+ const patched = loopShapedFlow(+ { ...values, name: "Renamed" },+ "2026-09-02T09:00:00Z",+ );+ mocks.updateHogFlow.mockRejectedValueOnce(+ new LoopScheduleSaveError(new Error("rrule"), patched),+ );+ const { rerenderWith } = renderEdit(flow);++ await user.clear(nameInput());+ await user.type(nameInput(), "Renamed");+ await user.click(saveButton());+ // The mutation caches the patched graph, which arrives as a new loop.+ rerenderWith(patched);++ expect(+ screen.queryByText("This loop changed elsewhere"),+ ).not.toBeInTheDocument();+ expect(saveButton()).toBeEnabled();++ mocks.updateHogFlow.mockResolvedValueOnce(+ hogFlowToLoop(patched, { projectId: PROJECT_ID }),+ );+ await user.click(saveButton());+ expect(mocks.updateHogFlow).toHaveBeenLastCalledWith(+ expect.objectContaining({+ existing: patched,+ values: expect.objectContaining({ name: "Renamed" }),+ }),+ );+ });++ it("picks up a schedule-only change that leaves the workflow stamp alone", () => {+ const values = formValues();+ const { rerenderWith } = renderEdit(+ loopShapedFlow(values, "2026-09-02T08:00:00Z"),+ );+ expect(screen.getByTestId("triggers")).toHaveTextContent("0 9 * * *");++ rerenderWith(+ loopShapedFlow(+ { ...values, triggers: [scheduleTrigger("0 17 * * *")] },+ "2026-09-02T08:00:00Z",+ ),+ );++ expect(screen.getByTestId("triggers")).toHaveTextContent("0 17 * * *");+ });++ it("flags a schedule-only change as remote when the form has edits", async () => {+ const user = userEvent.setup();+ const values = formValues();+ const { rerenderWith } = renderEdit(+ loopShapedFlow(values, "2026-09-02T08:00:00Z"),+ );+ await user.type(nameInput(), " edited");++ rerenderWith(+ loopShapedFlow(+ { ...values, triggers: [scheduleTrigger("0 17 * * *")] },+ "2026-09-02T08:00:00Z",+ ),+ );++ expect(+ await screen.findByText("This loop changed elsewhere"),+ ).toBeInTheDocument();+ expect(saveButton()).toBeDisabled();+ });++ it("keeps a workflow loop on the trigger step until it has one trigger", async () => {+ const user = userEvent.setup();+ const flow = loopShapedFlow(formValues(), "2026-09-02T08:00:00Z");+ mocks.hogFlow = flow;+ render(<LoopForm loop={hogFlowToLoop(flow, { projectId: PROJECT_ID })} />);++ await user.click(screen.getByRole("button", { name: "Next" }));+ expect(screen.getByRole("button", { name: "Next" })).toBeEnabled();++ await user.click(screen.getByRole("button", { name: "Remove triggers" }));++ expect(screen.getByRole("button", { name: "Next" })).toBeDisabled();+ });++ it.each([+ {+ workflowBacked: true,+ description:+ "Pick a schedule or a GitHub event. Every loop has one trigger.",+ },+ {+ workflowBacked: false,+ description: "Add automatic triggers, or leave this manual-only.",+ },+ ])(+ "describes the When step for workflowBacked=$workflowBacked",+ ({ workflowBacked, description }) => {+ mocks.workflowBacked = workflowBacked;+ renderEdit(loopShapedFlow(formValues(), "2026-09-02T08:00:00Z"));++ expect(screen.getByText(description)).toBeInTheDocument();+ },+ );++ it("drops a space attachment from a new workflow loop and says so", async () => {+ const user = userEvent.setup();+ useLoopDraftStore.getState().setPrefill({+ ...formValues(),+ contextTarget: {+ folderId: "folder-1",+ name: "general",+ outputs: { post_to_feed: true, update_context: false, canvas_id: null },+ },+ });+ mocks.createHogFlow.mockResolvedValue(+ hogFlowToLoop(loopShapedFlow(formValues(), "2026-09-02T08:00:00Z"), {+ projectId: PROJECT_ID,+ }),+ );+ render(<LoopForm />);++ expect(+ screen.getByText("This loop won't be attached to #general"),+ ).toBeInTheDocument();++ for (let i = 0; i < 3; i += 1) {+ await user.click(screen.getByRole("button", { name: "Next" }));+ }+ await user.click(screen.getByRole("button", { name: "Create loop" }));++ await waitFor(() => expect(mocks.createHogFlow).toHaveBeenCalled());+ expect(+ mocks.createHogFlow.mock.calls[0][0].values.contextTarget,+ ).toBeNull();+ });+});diff --git a/products/desktop/packages/ui/src/features/loops/components/LoopForm.tsx b/products/desktop/packages/ui/src/features/loops/components/LoopForm.tsxindex 4ce3cfeb22b8..155d3a8255b6 100644--- a/products/desktop/packages/ui/src/features/loops/components/LoopForm.tsx+++ b/products/desktop/packages/ui/src/features/loops/components/LoopForm.tsx@@ -4,11 +4,14 @@ import {CaretRight,Check,} from "@phosphor-icons/react";+import { requestErrorStatus } from "@posthog/api-client/fetcher";+import { hogFlowRequestDetail } from "@posthog/api-client/hogFlowLoops";import { type LoopSchemas, LoopsApiError } from "@posthog/api-client/loops";import { channelDisplayLabel } from "@posthog/core/canvas/channelName";import { ANALYTICS_EVENTS } from "@posthog/shared";import { useChannelsLayout } from "@posthog/ui/features/canvas/hooks/useChannelsLayout";import { useBluebirdFlag } from "@posthog/ui/features/feature-flags/useBluebirdFlag";+import { useLoopsHogFlowsEnabled } from "@posthog/ui/features/feature-flags/useLoopsHogFlowsEnabled";import { SettingsOptionSelect } from "@posthog/ui/features/settings/SettingsOptionSelect";import { useSandboxEnvironments } from "@posthog/ui/features/settings/sections/environments/useSandboxEnvironments";import { useSidebarStore } from "@posthog/ui/features/sidebar/sidebarStore";@@ -21,12 +24,15 @@ import {} from "@posthog/ui/router/navigationBridge";import { track } from "@posthog/ui/shell/analytics";import { Box, Flex, Text, TextArea, TextField } from "@radix-ui/themes";-import { type ReactNode, useEffect, useMemo, useState } from "react";+import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";import { useAuthStateValue } from "../../auth/store";+import { useLoopHogFlow } from "../hooks/useLoop";import {useCreateLoop,+ useCreateLoopHogFlow,useDeleteLoop,useUpdateLoop,+ useUpdateLoopHogFlow,} from "../hooks/useLoopMutations";import {useBundleLocalSkill,@@ -40,14 +46,26 @@ import {formValuesToLoopWrite,isAutoFixEnabled,isLoopFormValid,- isTriggerDraftValid,+ isTriggerListValid,+ LOOPS_API_RULES,type LoopContextTargetDraft,type LoopFormValues,loopToFormValues,normalizeLoopFormValues,+ WORKFLOW_RULES,} from "../loopFormTypes";+import {+ hogFlowTeamSkills,+ isLoopShapedHogFlow,+ UnsupportedLoopShapeError,+} from "../loopHogFlowMapping";+import {+ LoopForeignWorkflowError,+ LoopScheduleSaveError,+} from "../loopHogFlowWrites";import { formatLoopModel } from "../loopModels";import { buildSkillInstructions, loopSkillBundles } from "../loopSkill";+import { WORKFLOW_TRIGGER_LIMITS } from "../loopTriggerLimits";import { LoopBehaviorFields } from "./LoopBehaviorFields";import { LoopContextFields } from "./LoopContextFields";import { Field } from "./LoopFormPrimitives";@@ -58,6 +76,7 @@ import { LoopRepositoryPicker } from "./LoopRepositoryPicker";import { LoopInstructionsFields } from "./LoopSkillFields";import { LoopSpaceBreadcrumb } from "./LoopSpaceBreadcrumb";import { LoopTriggerEditor } from "./LoopTriggerEditor";+import { LoopWorkflowPromptFields } from "./LoopWorkflowPromptFields";const VISIBILITY_OPTIONS: {value: LoopSchemas.LoopVisibilityEnum;@@ -81,8 +100,14 @@ type LoopFormBaseline = {serialized: string;};-function buildLoopFormBaseline(loop: LoopSchemas.Loop): LoopFormBaseline {- const values = normalizeLoopFormValues(loopToFormValues(loop));+function buildLoopFormBaseline(+ loop: LoopSchemas.Loop,+ teamSkills: string[],+): LoopFormBaseline {+ const values = normalizeLoopFormValues({+ ...loopToFormValues(loop),+ teamSkills,+ });return {loopId: loop.id,updatedAt: loop.updated_at,@@ -110,22 +135,52 @@ export function LoopForm({const isEdit = !!loop;const isEmbedded = variant === "embedded";const projectId = useAuthStateValue((state) => state.currentProjectId);+ const workflowBacked = useLoopsHogFlowsEnabled();+ // The loop prop is a projection of this same cached workflow, so it is+ // already loaded whenever `loop` is; the raw flow carries the team skills+ // and the schedule row the save needs to reconcile.+ const { data: hogFlow } = useLoopHogFlow(+ workflowBacked ? loop?.id : undefined,+ );+ const teamSkills = useMemo(+ () => (hogFlow ? hogFlowTeamSkills(hogFlow) : []),+ [hogFlow],+ );+ const rules = workflowBacked ? WORKFLOW_RULES : LOOPS_API_RULES;+ // One-shot prefill from the landing prompt, a template, or a space; merged+ // over the blank defaults. Read (not consumed) here, then cleared in the+ // effect below so the manual "New loop" button always opens a blank form.+ const [prefill] = useState(() =>+ loop ? null : useLoopDraftStore.getState().prefill,+ );+ // A workflow has nowhere to keep a space attachment, so a loop started from+ // a space opens detached and the form says so instead of dropping it quietly.+ const detachedSpace = workflowBacked+ ? (prefill?.contextTarget ?? null)+ : null;const [values, setValues] = useState<LoopFormValues>(() => {- if (loop) return normalizeLoopFormValues(loopToFormValues(loop));- // One-shot prefill from the landing prompt or a template; merged over the- // blank defaults. Read (not consumed) here, then cleared in the effect- // below so the manual "New loop" button always opens a blank form.- const prefill = useLoopDraftStore.getState().prefill;+ if (loop) {+ return normalizeLoopFormValues({+ ...loopToFormValues(loop),+ teamSkills,+ });+ }return normalizeLoopFormValues({...emptyLoopFormValues(),...(prefill ?? {}),+ ...(workflowBacked ? { contextTarget: null } : {}),});});const [step, setStep] = useState(0);const [baseline, setBaseline] = useState<LoopFormBaseline | null>(() =>- loop ? buildLoopFormBaseline(loop) : null,+ loop ? buildLoopFormBaseline(loop, teamSkills) : null,);const [hasRemoteUpdate, setHasRemoteUpdate] = useState(false);+ // `updated_at` of a write this form made. When the loop with that stamp+ // arrives, the baseline moves onto it without treating it as someone+ // else's change, so a partial save (graph stuck, schedule did not) can be+ // saved again.+ const ownWriteUpdatedAtRef = useRef<string | null>(null);// Open when editing a loop that already pins a model, so the pinned value// is visible without hunting for it.const [showAdvanced, setShowAdvanced] = useState(@@ -140,7 +195,7 @@ export function LoopForm({useEffect(() => {if (!loop) return;- const nextBaseline = buildLoopFormBaseline(loop);+ const nextBaseline = buildLoopFormBaseline(loop, teamSkills);if (!baseline || baseline.loopId !== loop.id) {setBaseline(nextBaseline);setValues(nextBaseline.values);@@ -148,7 +203,20 @@ export function LoopForm({return;}- if (nextBaseline.updatedAt === baseline.updatedAt) return;+ // A schedule row edit moves only the row's own `updated_at`, so the+ // cadence is compared through the serialized values as well.+ if (+ nextBaseline.updatedAt === baseline.updatedAt &&+ nextBaseline.serialized === baseline.serialized+ ) {+ return;+ }++ if (nextBaseline.updatedAt === ownWriteUpdatedAtRef.current) {+ ownWriteUpdatedAtRef.current = null;+ setBaseline(nextBaseline);+ return;+ }if (isDirty) {setHasRemoteUpdate(true);@@ -158,7 +226,7 @@ export function LoopForm({setBaseline(nextBaseline);setValues(nextBaseline.values);setHasRemoteUpdate(false);- }, [loop, baseline, isDirty]);+ }, [loop, teamSkills, baseline, isDirty]);useEffect(() => {onDirtyChange?.(isDirty);@@ -170,7 +238,8 @@ export function LoopForm({const bluebirdEnabled = useBluebirdFlag();const channelsEnabled =useSidebarStore((s) => s.channelsEnabled) && bluebirdEnabled;- const showContextField = channelsEnabled || !!values.contextTarget;+ const showContextField =+ !workflowBacked && (channelsEnabled || !!values.contextTarget);const { environments, isLoading: environmentsLoading } =useSandboxEnvironments();const sandboxEnvironmentOptions = useMemo(() => {@@ -197,32 +266,37 @@ export function LoopForm({const createLoop = useCreateLoop();const updateLoop = useUpdateLoop(loop?.id ?? "");+ const createHogFlowLoop = useCreateLoopHogFlow();+ const updateHogFlowLoop = useUpdateLoopHogFlow(loop?.id ?? "");const deleteLoop = useDeleteLoop();const bundleSkill = useBundleLocalSkill();const replaceSkillBundles = useReplaceLoopSkillBundles();const isSubmitting =(isEdit ? updateLoop.isPending : createLoop.isPending) ||+ createHogFlowLoop.isPending ||+ updateHogFlowLoop.isPending ||bundleSkill.isPending ||replaceSkillBundles.isPending ||deleteLoop.isPending;const canSubmit =- isLoopFormValid(values) && !isSubmitting && !hasRemoteUpdate;+ isLoopFormValid(values, rules) && !isSubmitting && !hasRemoteUpdate;// Per-step gate for the Next button. The final Create button is gated on the// whole form being valid, so jumping between steps can't submit a bad loop.const stepComplete = [!!values.name.trim() &&(values.skill !== null || !!values.instructions.trim()),- values.triggers.every(isTriggerDraftValid),+ isTriggerListValid(values.triggers, rules),true,- isLoopFormValid(values),+ isLoopFormValid(values, rules),];const isLastStep = step === STEPS.length - 1;- // Building a loop for a space keeps a way back to it; without one the header- // still names the scene, it just has no parent to offer.+ // Building a loop for a space keeps a way back to it, attached or not;+ // without one the header still names the scene, it just has no parent to+ // offer.const spacesLayout = useChannelsLayout();- const contextTarget = values.contextTarget;+ const contextTarget = values.contextTarget ?? detachedSpace;const headerLeaf = isEdit ? loop.name : "New loop";useSetHeaderContent(useMemo(@@ -260,6 +334,79 @@ export function LoopForm({}};+ const reportForeignWorkflow = () => {+ toast.error("This loop was changed in the workflow editor", {+ description:+ "Open it in PostHog to change it. Saving here would replace those changes.",+ });+ };++ const submitWorkflowLoop = async () => {+ if (isEdit && !hogFlow) {+ toast.error("Loop is still loading", {+ description: "Wait a moment and save again.",+ });+ return;+ }+ // The detail page checks the shape when it renders; a reshaped flow can+ // still arrive while the form is open, or the form can open by URL.+ if (isEdit && hogFlow && !isLoopShapedHogFlow(hogFlow)) {+ reportForeignWorkflow();+ return;+ }+ try {+ const saved =+ isEdit && hogFlow+ ? await updateHogFlowLoop.mutateAsync({ values, existing: hogFlow })+ : await createHogFlowLoop.mutateAsync({ values, enabled: true });+ ownWriteUpdatedAtRef.current = saved.updated_at;+ track(+ isEdit ? ANALYTICS_EVENTS.LOOP_UPDATED : ANALYTICS_EVENTS.LOOP_CREATED,+ buildLoopSavedProps(saved),+ );+ if (onSaved) {+ onSaved(saved);+ } else {+ navigateToLoopDetail(saved.id);+ }+ } catch (error) {+ if (error instanceof LoopScheduleSaveError) {+ // Keep the form open with its state intact: saving again retries the+ // schedule write against the graph that already stuck.+ ownWriteUpdatedAtRef.current = error.flow.updated_at;+ toast.error("Loop saved, but its schedule didn't update", {+ description: [+ hogFlowRequestDetail(error.cause),+ "Save again to retry.",+ ]+ .filter(Boolean)+ .join(" "),+ });+ return;+ }+ if (error instanceof LoopForeignWorkflowError) {+ reportForeignWorkflow();+ return;+ }+ if (requestErrorStatus(error) === 409) {+ // The server refused a write based on an older version of the loop.+ setHasRemoteUpdate(true);+ toast.error("Loop changed elsewhere", {+ description:+ "Cancel and reopen editing to see the latest version before saving.",+ });+ return;+ }+ toast.error(isEdit ? "Failed to save loop" : "Failed to create loop", {+ description:+ error instanceof UnsupportedLoopShapeError+ ? error.message+ : (hogFlowRequestDetail(error) ??+ (error instanceof Error ? error.message : undefined)),+ });+ }+ };+const handleSubmit = async () => {if (hasRemoteUpdate) {toast.error("Loop changed elsewhere", {@@ -268,6 +415,10 @@ export function LoopForm({return;}if (!canSubmit) return;+ if (workflowBacked) {+ await submitWorkflowLoop();+ return;+ }const body = formValuesToLoopWrite(values);// Bundling runs before anything is persisted: a missing or broken local@@ -289,6 +440,7 @@ export function LoopForm({const saved = isEdit? await updateLoop.mutateAsync(body): await createLoop.mutateAsync(body);+ ownWriteUpdatedAtRef.current = saved.updated_at;track(isEdit ? ANALYTICS_EVENTS.LOOP_UPDATED : ANALYTICS_EVENTS.LOOP_CREATED,buildLoopSavedProps(saved),@@ -368,6 +520,10 @@ export function LoopForm({gap="4"className="rounded-(--radius-2) border border-border bg-(--gray-1) p-4">+ {detachedSpace ? (+ <DetachedSpaceNotice spaceName={detachedSpace.name} />+ ) : null}+<Steptitle="Prompt"description="Name it and write the prompt the agent runs each time."@@ -390,23 +546,36 @@ export function LoopForm({onChange={(e) => patch({ description: e.target.value })}/></Field>- <LoopInstructionsFields- values={values}- disabled={isSubmitting}- onPatch={patch}- />+ {workflowBacked ? (+ <LoopWorkflowPromptFields+ values={values}+ disabled={isSubmitting}+ onPatch={patch}+ />+ ) : (+ <LoopInstructionsFields+ values={values}+ disabled={isSubmitting}+ onPatch={patch}+ />+ )}</Step><Divider /><Steptitle="When"- description="Add automatic triggers, or leave this manual-only."+ description={+ workflowBacked+ ? "Pick a schedule or a GitHub event. Every loop has one trigger."+ : "Add automatic triggers, or leave this manual-only."+ }><LoopTriggerEditortriggers={values.triggers}triggerEndpointPath={triggerEndpointPath}disabled={isSubmitting}+ limits={workflowBacked ? WORKFLOW_TRIGGER_LIMITS : undefined}onChange={(triggers) => patch({ triggers })}/></Step>@@ -415,30 +584,36 @@ export function LoopForm({<Steptitle="Options"- description="Visibility, working context, and notifications."+ description={+ workflowBacked+ ? "The repository the agent works in."+ : "Visibility, working context, and notifications."+ }><div className="grid gap-4 md:grid-cols-2">- <Field- label="Visibility"- hint={- values.contextTarget- ? "Channel loops are team-visible."- : undefined- }- >- <SettingsOptionSelect- value={values.visibility}- options={VISIBILITY_OPTIONS}- disabled={isSubmitting || !!values.contextTarget}- size="lg"- ariaLabel="Visibility"- onValueChange={(value) =>- patch({- visibility: value as LoopSchemas.LoopVisibilityEnum,- })+ {!workflowBacked ? (+ <Field+ label="Visibility"+ hint={+ values.contextTarget+ ? "Channel loops are team-visible."+ : undefined}- />- </Field>+ >+ <SettingsOptionSelect+ value={values.visibility}+ options={VISIBILITY_OPTIONS}+ disabled={isSubmitting || !!values.contextTarget}+ size="lg"+ ariaLabel="Visibility"+ onValueChange={(value) =>+ patch({+ visibility: value as LoopSchemas.LoopVisibilityEnum,+ })+ }+ />+ </Field>+ ) : null}<Fieldlabel="Base repository"@@ -462,24 +637,26 @@ export function LoopForm({/></Field>- <Field- label="Sandbox environment"- hint="Applies its environment variables, network access, and image to every run."- >- <SettingsOptionSelect- value={values.sandboxEnvironmentId ?? ""}- options={sandboxEnvironmentOptions}- disabled={isSubmitting || environmentsLoading}- size="lg"- ariaLabel="Sandbox environment"- placeholder={- environmentsLoading ? "Loading environments…" : undefined- }- onValueChange={(value) =>- patch({ sandboxEnvironmentId: value || null })- }- />- </Field>+ {!workflowBacked ? (+ <Field+ label="Sandbox environment"+ hint="Applies its environment variables, network access, and image to every run."+ >+ <SettingsOptionSelect+ value={values.sandboxEnvironmentId ?? ""}+ options={sandboxEnvironmentOptions}+ disabled={isSubmitting || environmentsLoading}+ size="lg"+ ariaLabel="Sandbox environment"+ placeholder={+ environmentsLoading ? "Loading environments…" : undefined+ }+ onValueChange={(value) =>+ patch({ sandboxEnvironmentId: value || null })+ }+ />+ </Field>+ ) : null}</div>{showContextField ? (@@ -498,30 +675,42 @@ export function LoopForm({</Field>) : null}- <Field label="Notifications">- <LoopNotificationsFields- notifications={values.notifications}- disabled={isSubmitting}- onChange={(notifications) => patch({ notifications })}- />- </Field>+ {!workflowBacked ? (+ <Field label="Notifications">+ <LoopNotificationsFields+ notifications={values.notifications}+ disabled={isSubmitting}+ onChange={(notifications) => patch({ notifications })}+ />+ </Field>+ ) : null}</Step><Divider />- <Step title="Advanced" description="Behavior, model, and reasoning.">- <Field label="Behavior">- <LoopBehaviorFields- behaviors={values.behaviors}- disabled={isSubmitting}- onChange={(behaviors) => patch({ behaviors })}- />- </Field>+ <Step+ title="Advanced"+ description={+ workflowBacked+ ? "Model and reasoning."+ : "Behavior, model, and reasoning."+ }+ >+ {!workflowBacked ? (+ <Field label="Behavior">+ <LoopBehaviorFields+ behaviors={values.behaviors}+ disabled={isSubmitting}+ onChange={(behaviors) => patch({ behaviors })}+ />+ </Field>+ ) : null}<LoopModelFieldsadapter={values.runtimeAdapter}model={values.model}reasoningEffort={values.reasoningEffort}disabled={isSubmitting}+ adapterEditable={!workflowBacked}onAdapterChange={(runtimeAdapter) => patch({ runtimeAdapter })}onModelChange={(model) => patch({ model })}onReasoningEffortChange={(reasoningEffort) =>@@ -586,6 +775,12 @@ export function LoopForm({</Box><Box className="min-h-0 flex-1 overflow-y-auto px-6 py-6">+ {detachedSpace ? (+ <div className="mb-4">+ <DetachedSpaceNotice spaceName={detachedSpace.name} />+ </div>+ ) : null}+{step === 0 ? (<Steptitle="What should this loop do?"@@ -610,23 +805,36 @@ export function LoopForm({onChange={(e) => patch({ description: e.target.value })}/></Field>- <LoopInstructionsFields- values={values}- disabled={isSubmitting}- onPatch={patch}- />+ {workflowBacked ? (+ <LoopWorkflowPromptFields+ values={values}+ disabled={isSubmitting}+ onPatch={patch}+ />+ ) : (+ <LoopInstructionsFields+ values={values}+ disabled={isSubmitting}+ onPatch={patch}+ />+ )}</Step>) : null}{step === 1 ? (<Steptitle="When should it run?"- description="A loop can have several triggers, and any one of them starts a run. With no triggers, you run it yourself from the loop's page."+ description={+ workflowBacked+ ? "Pick a schedule or a GitHub event. Every loop has one trigger, and you can also run a scheduled loop from its page."+ : "A loop can have several triggers, and any one of them starts a run. With no triggers, you run it yourself from the loop's page."+ }><LoopTriggerEditortriggers={values.triggers}triggerEndpointPath={triggerEndpointPath}disabled={isSubmitting}+ limits={workflowBacked ? WORKFLOW_TRIGGER_LIMITS : undefined}onChange={(triggers) => patch({ triggers })}/></Step>@@ -635,32 +843,40 @@ export function LoopForm({{step === 2 ? (<Steptitle="Options"- description="Who can see it and how you hear about runs."+ description={+ workflowBacked+ ? "The repository the agent works in."+ : "Who can see it and how you hear about runs."+ }>- <Field- label="Visibility"- className="max-w-[340px]"- hint={- values.contextTarget- ? "Loops attached to a channel post runs to its shared feed, so they're visible to everyone on the project."- : undefined- }- >- <SettingsOptionSelect- value={values.visibility}- options={VISIBILITY_OPTIONS}- disabled={isSubmitting || !!values.contextTarget}- size="lg"- ariaLabel="Visibility"- onValueChange={(value) =>- patch({- visibility: value as LoopSchemas.LoopVisibilityEnum,- })- }- />- </Field>+ {!workflowBacked ? (+ <>+ <Field+ label="Visibility"+ className="max-w-[340px]"+ hint={+ values.contextTarget+ ? "Loops attached to a channel post runs to its shared feed, so they're visible to everyone on the project."+ : undefined+ }+ >+ <SettingsOptionSelect+ value={values.visibility}+ options={VISIBILITY_OPTIONS}+ disabled={isSubmitting || !!values.contextTarget}+ size="lg"+ ariaLabel="Visibility"+ onValueChange={(value) =>+ patch({+ visibility: value as LoopSchemas.LoopVisibilityEnum,+ })+ }+ />+ </Field>- <Divider />+ <Divider />+ </>+ ) : null}{showContextField ? (<>@@ -713,15 +929,19 @@ export function LoopForm({<Divider />- <Field label="Notifications">- <LoopNotificationsFields- notifications={values.notifications}- disabled={isSubmitting}- onChange={(notifications) => patch({ notifications })}- />- </Field>+ {!workflowBacked ? (+ <>+ <Field label="Notifications">+ <LoopNotificationsFields+ notifications={values.notifications}+ disabled={isSubmitting}+ onChange={(notifications) => patch({ notifications })}+ />+ </Field>- <Divider />+ <Divider />+ </>+ ) : null}<Flex direction="column" gap="4"><button@@ -739,23 +959,28 @@ export function LoopForm({Advanced</Text><Text className="text-[11.5px] text-gray-9">- Behavior, model and reasoning+ {workflowBacked+ ? "Model and reasoning"+ : "Behavior, model and reasoning"}</Text></button>{showAdvanced ? (<Flex direction="column" gap="4">- <Field label="Behavior">- <LoopBehaviorFields- behaviors={values.behaviors}- disabled={isSubmitting}- onChange={(behaviors) => patch({ behaviors })}- />- </Field>+ {!workflowBacked ? (+ <Field label="Behavior">+ <LoopBehaviorFields+ behaviors={values.behaviors}+ disabled={isSubmitting}+ onChange={(behaviors) => patch({ behaviors })}+ />+ </Field>+ ) : null}<LoopModelFieldsadapter={values.runtimeAdapter}model={values.model}reasoningEffort={values.reasoningEffort}disabled={isSubmitting}+ adapterEditable={!workflowBacked}onAdapterChange={(runtimeAdapter) =>patch({ runtimeAdapter })}@@ -775,7 +1000,11 @@ export function LoopForm({title="Review"description="Check everything before you create the loop.">- <ReviewList values={values} showContext={showContextField} />+ <ReviewList+ values={values}+ showContext={showContextField}+ workflowBacked={workflowBacked}+ /></Step>) : null}</Box>@@ -923,12 +1152,28 @@ function Divider() {return <Box className="h-px bg-(--gray-4)" />;}+function DetachedSpaceNotice({ spaceName }: { spaceName: string }) {+ return (+ <div className="flex flex-col gap-1 rounded-(--radius-2) border border-(--amber-6) bg-(--amber-2) px-3 py-2">+ <span className="font-medium text-(--amber-12) text-[12.5px]">+ This loop won't be attached to {channelDisplayLabel(spaceName)}+ </span>+ <span className="text-(--amber-11) text-[12px] leading-snug">+ Attaching loops to a space isn't available yet. You'll find it in the+ Loops list instead.+ </span>+ </div>+ );+}+function ReviewList({values,showContext,+ workflowBacked,}: {values: LoopFormValues;showContext: boolean;+ workflowBacked: boolean;}) {const reasoning = values.reasoningEffort ?? "auto";const channels = (["push", "email", "slack"] as const).filter(@@ -941,10 +1186,12 @@ function ReviewList({className="divide-y divide-(--gray-4) rounded-(--radius-3) border border-border"><ReviewRow label="Name" value={values.name || "Not set"} />- <ReviewRow- label="Visibility"- value={values.visibility === "team" ? "Team" : "Personal"}- />+ {!workflowBacked ? (+ <ReviewRow+ label="Visibility"+ value={values.visibility === "team" ? "Team" : "Personal"}+ />+ ) : null}<ReviewRowlabel="Prompt"value={@@ -954,12 +1201,23 @@ function ReviewList({}multiline/>+ {workflowBacked ? (+ <ReviewRow+ label="Skills"+ value={+ values.teamSkills.length > 0 ? values.teamSkills.join(", ") : "None"+ }+ />+ ) : null}<ReviewRowlabel="Model"- value={`${ADAPTER_LABELS[values.runtimeAdapter]} · ${formatLoopModel(- values.runtimeAdapter,- values.model,- )} · ${reasoning} reasoning`}+ value={[+ workflowBacked ? null : ADAPTER_LABELS[values.runtimeAdapter],+ formatLoopModel(values.runtimeAdapter, values.model),+ `${reasoning} reasoning`,+ ]+ .filter(Boolean)+ .join(" · ")}/>{showContext ? (<ReviewRow@@ -983,14 +1241,18 @@ function ReviewList({: values.triggers.map(summarizeTrigger).join(", ")}/>- <ReviewRow- label="Auto-fix PRs"- value={isAutoFixEnabled(values.behaviors) ? "On" : "Off"}- />- <ReviewRow- label="Notifications"- value={channels.length === 0 ? "None" : channels.join(", ")}- />+ {!workflowBacked ? (+ <>+ <ReviewRow+ label="Auto-fix PRs"+ value={isAutoFixEnabled(values.behaviors) ? "On" : "Off"}+ />+ <ReviewRow+ label="Notifications"+ value={channels.length === 0 ? "None" : channels.join(", ")}+ />+ </>+ ) : null}</Flex>);}diff --git a/products/desktop/packages/ui/src/features/loops/components/LoopModelFields.test.tsx b/products/desktop/packages/ui/src/features/loops/components/LoopModelFields.test.tsxnew file mode 100644index 000000000000..9da59575664b--- /dev/null+++ b/products/desktop/packages/ui/src/features/loops/components/LoopModelFields.test.tsx@@ -0,0 +1,152 @@+import type { LoopSchemas } from "@posthog/api-client/loops";+import { render, screen, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";+import { describe, expect, it, vi } from "vitest";+import { LoopModelFields } from "./LoopModelFields";++vi.mock("@posthog/ui/features/sessions/useModelRolloutFlags", () => ({+ useModelRolloutFlags: () => ({+ glm: false,+ glm53: false,+ glm53Flash: false,+ kimi: false,+ deepseek: false,+ }),+}));+vi.mock("../hooks/useLoopModelConfigOptions", () => ({+ useLoopModelConfigOptions: () => [],+}));+// A native select stands in for the dropdown so the test can read the offered+// options and pick one without driving a popup.+vi.mock("@posthog/ui/features/settings/SettingsOptionSelect", () => ({+ SettingsOptionSelect: ({+ value,+ options,+ onValueChange,+ disabled,+ ariaLabel,+ }: {+ value: string;+ options: { value: string; label: string }[];+ onValueChange: (value: string) => void;+ disabled?: boolean;+ ariaLabel: string;+ }) => (+ <select+ aria-label={ariaLabel}+ value={value}+ disabled={disabled}+ onChange={(event) => onValueChange(event.target.value)}+ >+ {options.map((option) => (+ <option key={option.value} value={option.value}>+ {option.label}+ </option>+ ))}+ </select>+ ),+}));++function renderFields({+ model = "",+ reasoningEffort = null,+ adapterEditable,+ onReasoningEffortChange = vi.fn(),+}: {+ model?: string;+ reasoningEffort?: LoopSchemas.LoopReasoningEffortEnum | null;+ adapterEditable: boolean;+ onReasoningEffortChange?: (+ effort: LoopSchemas.LoopReasoningEffortEnum | null,+ ) => void;+}) {+ render(+ <LoopModelFields+ adapter="claude"+ model={model}+ reasoningEffort={reasoningEffort}+ adapterEditable={adapterEditable}+ onAdapterChange={vi.fn()}+ onModelChange={vi.fn()}+ onReasoningEffortChange={onReasoningEffortChange}+ />,+ );+}++function effortOptionValues(): string[] {+ const select = screen.getByRole("combobox", { name: "Reasoning effort" });+ return within(select)+ .getAllByRole("option")+ .map((option) => (option as HTMLOptionElement).value);+}++describe("LoopModelFields reasoning effort", () => {+ it.each([+ {+ name: "waits for a pinned model in workflow mode",+ adapterEditable: false,+ model: "",+ expectedDisabled: true,+ expectedValues: ["auto"],+ },+ {+ name: "offers the pinned model's efforts in workflow mode",+ adapterEditable: false,+ model: "claude-sonnet-5",+ expectedDisabled: false,+ expectedValues: [+ "auto",+ "low",+ "medium",+ "high",+ "xhigh",+ "max",+ "ultracode",+ ],+ },+ {+ name: "offers the default model's efforts when the adapter is editable",+ adapterEditable: true,+ model: "",+ expectedDisabled: false,+ expectedValues: [+ "auto",+ "low",+ "medium",+ "high",+ "xhigh",+ "max",+ "ultracode",+ ],+ },+ ])(+ "$name",+ ({ adapterEditable, model, expectedDisabled, expectedValues }) => {+ renderFields({ adapterEditable, model });++ const select = screen.getByRole("combobox", { name: "Reasoning effort" });+ expect(select).toHaveProperty("disabled", expectedDisabled);+ expect(effortOptionValues()).toEqual(expectedValues);+ expect(+ screen.queryByText("Pick a model to set reasoning effort.") !== null,+ ).toBe(expectedDisabled);+ },+ );++ it("clears the effort when a workflow loop goes back to the default model", async () => {+ const onReasoningEffortChange = vi.fn();+ renderFields({+ adapterEditable: false,+ model: "claude-sonnet-5",+ reasoningEffort: "high",+ onReasoningEffortChange,+ });++ await userEvent.selectOptions(+ screen.getByRole("combobox", { name: "Model" }),+ "__default__",+ );++ expect(onReasoningEffortChange).toHaveBeenCalledWith(null);+ });+});diff --git a/products/desktop/packages/ui/src/features/loops/components/LoopModelFields.tsx b/products/desktop/packages/ui/src/features/loops/components/LoopModelFields.tsxindex e0f571586a94..f806a1ec42a6 100644--- a/products/desktop/packages/ui/src/features/loops/components/LoopModelFields.tsx+++ b/products/desktop/packages/ui/src/features/loops/components/LoopModelFields.tsx@@ -32,6 +32,8 @@ interface LoopModelFieldsProps {effort: LoopSchemas.LoopReasoningEffortEnum | null,) => void;disabled?: boolean;+ /** Hidden for a workflow-backed loop: the task step picks the adapter itself. */+ adapterEditable?: boolean;}/**@@ -52,6 +54,7 @@ export function LoopModelFields({onModelChange,onReasoningEffortChange,disabled,+ adapterEditable = true,}: LoopModelFieldsProps) {const modelFlags = useModelRolloutFlags();const configOptions = useLoopModelConfigOptions(adapter);@@ -71,12 +74,16 @@ export function LoopModelFields({[adapter, configOptions, modelFlags, model],);+ // A workflow only stores the effort next to a pinned model, so offering+ // efforts for the default model would confirm a value that is never saved.+ const effortNeedsModel = !adapterEditable && !model;+const reasoningOptions = useMemo(() => [{ value: AUTO_REASONING_VALUE, label: "Auto" },- ...loopReasoningEffortOptions(adapter, model),+ ...(effortNeedsModel ? [] : loopReasoningEffortOptions(adapter, model)),],- [adapter, model],+ [adapter, model, effortNeedsModel],);const handleAdapterChange = (value: string) => {@@ -91,11 +98,10 @@ export function LoopModelFields({const handleModelChange = (value: string) => {const nextModel = value === DEFAULT_MODEL_VALUE ? "" : value;onModelChange(nextModel);- const clamped = clampLoopReasoningEffort(- adapter,- nextModel,- reasoningEffort,- );+ const clamped =+ !adapterEditable && !nextModel+ ? null+ : clampLoopReasoningEffort(adapter, nextModel, reasoningEffort);if (clamped !== reasoningEffort) onReasoningEffortChange(clamped);};@@ -117,18 +123,28 @@ export function LoopModelFields({</Field><Flex gap="4" wrap="wrap">- <Field label="Adapter" className="min-w-[180px] flex-1">- <SettingsOptionSelect- value={adapter}- options={ADAPTER_OPTIONS}- onValueChange={handleAdapterChange}- disabled={disabled}- size="lg"- ariaLabel="Adapter"- />- </Field>+ {adapterEditable ? (+ <Field label="Adapter" className="min-w-[180px] flex-1">+ <SettingsOptionSelect+ value={adapter}+ options={ADAPTER_OPTIONS}+ onValueChange={handleAdapterChange}+ disabled={disabled}+ size="lg"+ ariaLabel="Adapter"+ />+ </Field>+ ) : null}- <Field label="Reasoning effort" className="min-w-[180px] flex-1">+ <Field+ label="Reasoning effort"+ className="min-w-[180px] flex-1"+ hint={+ effortNeedsModel+ ? "Pick a model to set reasoning effort."+ : undefined+ }+ ><SettingsOptionSelectvalue={reasoningEffort ?? AUTO_REASONING_VALUE}options={reasoningOptions}@@ -139,7 +155,7 @@ export function LoopModelFields({: (value as LoopSchemas.LoopReasoningEffortEnum),)}- disabled={disabled}+ disabled={disabled || effortNeedsModel}size="lg"ariaLabel="Reasoning effort"/>diff --git a/products/desktop/packages/ui/src/features/loops/components/LoopTeamSkillsFields.tsx b/products/desktop/packages/ui/src/features/loops/components/LoopTeamSkillsFields.tsxnew file mode 100644index 000000000000..868b6e2f5680--- /dev/null+++ b/products/desktop/packages/ui/src/features/loops/components/LoopTeamSkillsFields.tsx@@ -0,0 +1,139 @@+import { CaretDown, X } from "@phosphor-icons/react";+import {+ Combobox,+ ComboboxContent,+ ComboboxEmpty,+ ComboboxInput,+ ComboboxItem,+ ComboboxList,+ ComboboxTrigger,+ Button as QuillButton,+} from "@posthog/quill";+import { useTeamSkills } from "@posthog/ui/features/skills/useTeamSkills";+import { useRef, useState } from "react";+import { Field } from "./LoopFormPrimitives";++/** The "Create AI task" step accepts at most this many skills. */+export const MAX_LOOP_TEAM_SKILLS = 10;++/**+ * Picks the team skills a workflow-backed loop attaches to each run. Skills+ * come from the team's skills store by name, so the agent always reads the+ * current version and nothing is uploaded from this machine.+ */+export function LoopTeamSkillsFields({+ value,+ disabled,+ onChange,+}: {+ value: string[];+ disabled: boolean;+ onChange: (names: string[]) => void;+}) {+ const { data: listing, isLoading, isError } = useTeamSkills([]);+ const triggerRef = useRef<HTMLButtonElement>(null);+ const [open, setOpen] = useState(false);+ const [searchQuery, setSearchQuery] = useState("");++ const available = listing?.available ?? false;+ const options = (listing?.skills ?? [])+ .map((skill) => skill.name)+ .filter((name) => !value.includes(name));+ const atCap = value.length >= MAX_LOOP_TEAM_SKILLS;++ let hint: string;+ if (isLoading) {+ hint = "Loading team skills…";+ } else if (isError) {+ hint = "Couldn't load team skills. Reopen the form to try again.";+ } else if (!available) {+ hint = "Team skills aren't enabled for this organization.";+ } else if (atCap) {+ hint = `A loop can attach up to ${MAX_LOOP_TEAM_SKILLS} skills.`;+ } else {+ hint =+ "Optional. The agent reads the current version of each skill at the start of every run.";+ }++ const pickerDisabled =+ disabled || isLoading || isError || !available || atCap;++ return (+ <Field label="Skills" hint={hint}>+ <div className="flex flex-col gap-2">+ {value.length > 0 ? (+ <div className="flex flex-wrap gap-1.5">+ {value.map((name) => (+ <span+ key={name}+ className="flex items-center gap-1 rounded-(--radius-2) border border-border bg-(--gray-2) py-0.5 pr-1 pl-2 text-[12px] text-gray-12"+ >+ {name}+ <QuillButton+ variant="link-muted"+ size="icon-xs"+ disabled={disabled}+ aria-label={`Remove ${name}`}+ onClick={() =>+ onChange(value.filter((selected) => selected !== name))+ }+ >+ <X size={10} weight="bold" />+ </QuillButton>+ </span>+ ))}+ </div>+ ) : null}+ <Combobox+ items={options}+ value={null}+ onValueChange={(name) => {+ if (typeof name === "string" && name && !atCap) {+ onChange([...value, name]);+ }+ }}+ open={open}+ onOpenChange={(nextOpen) => {+ setOpen(nextOpen);+ if (!nextOpen) setSearchQuery("");+ }}+ inputValue={searchQuery}+ onInputValueChange={setSearchQuery}+ disabled={pickerDisabled}+ >+ <ComboboxTrigger+ render={+ <QuillButton+ ref={triggerRef}+ variant="outline"+ size="sm"+ disabled={pickerDisabled}+ aria-label="Add a skill"+ className="w-full max-w-[360px] justify-between"+ >+ <span className="min-w-0 truncate">Add a skill…</span>+ <CaretDown size={10} weight="bold" className="shrink-0" />+ </QuillButton>+ }+ />+ <ComboboxContent+ anchor={triggerRef}+ side="bottom"+ sideOffset={6}+ className="min-w-[280px]"+ >+ <ComboboxInput placeholder="Search team skills..." />+ <ComboboxEmpty>No skills found.</ComboboxEmpty>+ <ComboboxList>+ {(name: string) => (+ <ComboboxItem key={name} value={name}>+ {name}+ </ComboboxItem>+ )}+ </ComboboxList>+ </ComboboxContent>+ </Combobox>+ </div>+ </Field>+ );+}diff --git a/products/desktop/packages/ui/src/features/loops/components/LoopTriggerEditor.tsx b/products/desktop/packages/ui/src/features/loops/components/LoopTriggerEditor.tsxindex cad39dd74e4e..246b01f297cd 100644--- a/products/desktop/packages/ui/src/features/loops/components/LoopTriggerEditor.tsx+++ b/products/desktop/packages/ui/src/features/loops/components/LoopTriggerEditor.tsx@@ -53,10 +53,17 @@ import {defaultLoopTriggerOfType,githubTriggerActionOptions,isTriggerDraftValid,+ LOOPS_API_RULES,+ type LoopFormRules,type LoopTriggerDraft,+ WORKFLOW_RULES,withGithubTriggerEvents,withGithubTriggerFilters,} from "../loopFormTypes";+import {+ LOOPS_API_TRIGGER_LIMITS,+ type LoopTriggerEditorLimits,+} from "../loopTriggerLimits";import { LoopRepositoryPicker } from "./LoopRepositoryPicker";const TRIGGER_TYPES: {@@ -97,7 +104,11 @@ function triggerTypeMeta(type: LoopSchemas.LoopTriggerTypeEnum) {* reason. A blank condition row used to report the repository and events as missing. */function githubTriggerInvalidMessage(config: LoopSchemas.LoopGithubTriggerConfig,+ limits: LoopTriggerEditorLimits,): string {+ if (limits.singleGithubEvent) {+ return "Pick a repository and one event to finish this trigger.";+ }if (!config.repository ||!config.github_integration_id ||@@ -114,6 +125,7 @@ interface LoopTriggerEditorProps {/** Rendered in the API trigger card. Absent for a not-yet-created loop. */triggerEndpointPath: string | null;disabled?: boolean;+ limits?: LoopTriggerEditorLimits;}export function LoopTriggerEditor({@@ -121,6 +133,7 @@ export function LoopTriggerEditor({onChange,triggerEndpointPath,disabled,+ limits = LOOPS_API_TRIGGER_LIMITS,}: LoopTriggerEditorProps) {const updateTrigger = (key: string, patch: Partial<LoopTriggerDraft>) => {onChange(@@ -138,6 +151,10 @@ export function LoopTriggerEditor({onChange([...triggers, defaultLoopTriggerOfType(type)]);};+ const triggerRequired = limits.maxTriggers !== null;+ const canAddTrigger =+ limits.maxTriggers === null || triggers.length < limits.maxTriggers;+return (<Flex direction="column" gap="3">{triggers.length === 0 ? (@@ -148,8 +165,9 @@ export function LoopTriggerEditor({</EmptyMedia><EmptyTitle>No triggers</EmptyTitle><EmptyDescription>- This loop only runs when you start it from its page. Add a trigger- to run it automatically.+ {triggerRequired+ ? "Add a trigger to choose when this loop runs."+ : "This loop only runs when you start it from its page. Add a trigger to run it automatically."}</EmptyDescription></EmptyHeader></Empty>@@ -160,24 +178,36 @@ export function LoopTriggerEditor({trigger={trigger}triggerEndpointPath={triggerEndpointPath}disabled={disabled}+ limits={limits}onChange={(patch) => updateTrigger(trigger.key, patch)}onRemove={() => removeTrigger(trigger.key)}/>)))}- <AddTriggerMenu disabled={disabled} onAdd={addTrigger} />+ {canAddTrigger ? (+ <AddTriggerMenu+ disabled={disabled}+ triggerTypes={limits.triggerTypes}+ onAdd={addTrigger}+ />+ ) : null}</Flex>);}function AddTriggerMenu({disabled,+ triggerTypes,onAdd,}: {disabled?: boolean;+ triggerTypes: LoopSchemas.LoopTriggerTypeEnum[];onAdd: (type: LoopSchemas.LoopTriggerTypeEnum) => void;}) {+ const options = TRIGGER_TYPES.filter((option) =>+ triggerTypes.includes(option.type),+ );return (<DropdownMenu><DropdownMenuTrigger@@ -200,7 +230,7 @@ function AddTriggerMenu({sideOffset={6}className="w-auto min-w-[280px]">- {TRIGGER_TYPES.map((option) => (+ {options.map((option) => (<DropdownMenuItemkey={option.type}onClick={() => onAdd(option.type)}@@ -228,22 +258,27 @@ function TriggerCard({trigger,triggerEndpointPath,disabled,+ limits,onChange,onRemove,}: {trigger: LoopTriggerDraft;triggerEndpointPath: string | null;disabled?: boolean;+ limits: LoopTriggerEditorLimits;onChange: (patch: Partial<LoopTriggerDraft>) => void;onRemove: () => void;}) {const meta = triggerTypeMeta(trigger.type);const Icon = meta.icon;- const invalidMessage = isTriggerDraftValid(trigger)+ const rules: LoopFormRules =+ limits.maxTriggers === null ? LOOPS_API_RULES : WORKFLOW_RULES;+ const invalidMessage = isTriggerDraftValid(trigger, rules)? null: trigger.type === "github"? githubTriggerInvalidMessage(trigger.config as LoopSchemas.LoopGithubTriggerConfig,+ limits,): "Set when this trigger fires.";@@ -324,6 +359,7 @@ function TriggerCard({<GithubTriggerFieldsconfig={trigger.config as LoopSchemas.LoopGithubTriggerConfig}disabled={disabled}+ limits={limits}onChange={(config) => onChange({ config })}/>) : null}@@ -636,10 +672,12 @@ function PayloadConditionValues({function GithubTriggerFields({config,disabled,+ limits,onChange,}: {config: LoopSchemas.LoopGithubTriggerConfig;disabled?: boolean;+ limits: LoopTriggerEditorLimits;onChange: (config: LoopSchemas.LoopGithubTriggerConfig) => void;}) {const toggleEvent = (@@ -647,7 +685,9 @@ function GithubTriggerFields({checked: boolean,) => {const events = checked- ? [...config.events, event]+ ? limits.singleGithubEvent+ ? [event]+ : [...config.events, event]: config.events.filter((e) => e !== event);onChange(withGithubTriggerEvents(config, events));};@@ -761,71 +801,73 @@ function GithubTriggerFields({</SubField>) : null}- <SubField label="Payload conditions">- <div className="flex flex-col gap-2">- <span className="text-[12px] text-gray-10">- Optional. Match any other field in the GitHub payload, like{" "}- <code>requested_team.slug</code> for the team asked to review.- </span>- {conditions.map((condition, index) => (- <div- // Keying on the path instead would remount the input on every keystroke.- // biome-ignore lint/suspicious/noArrayIndexKey: rows carry no id and cannot be reordered, and both inputs are controlled off the config, so the index is a correct identity- key={index}- className="flex items-center gap-2"- >- <Input- value={condition.path}- disabled={disabled}- placeholder="requested_team.slug"- // The placeholder stops naming the field as soon as someone types into it.- aria-label="Condition path"- className="h-7 flex-1"- onChange={(event) =>- updateCondition(index, { path: event.target.value })- }- />- <span className="text-[12px] text-gray-10">is</span>- <PayloadConditionValues- values={- Array.isArray(condition.equals)- ? condition.equals- : [condition.equals].filter(Boolean)- }- disabled={disabled}- onChange={(equals) => updateCondition(index, { equals })}- />- <Button- variant="outline"- size="sm"- disabled={disabled}- aria-label={- condition.path- ? `Remove condition ${condition.path}`- : "Remove condition"- }- onClick={() =>- setConditions(conditions.filter((_, i) => i !== index))- }+ {limits.githubPayloadConditions ? (+ <SubField label="Payload conditions">+ <div className="flex flex-col gap-2">+ <span className="text-[12px] text-gray-10">+ Optional. Match any other field in the GitHub payload, like{" "}+ <code>requested_team.slug</code> for the team asked to review.+ </span>+ {conditions.map((condition, index) => (+ <div+ // Keying on the path instead would remount the input on every keystroke.+ // biome-ignore lint/suspicious/noArrayIndexKey: rows carry no id and cannot be reordered, and both inputs are controlled off the config, so the index is a correct identity+ key={index}+ className="flex items-center gap-2">- <Trash size={13} />- </Button>- </div>- ))}- <Button- variant="outline"- size="sm"- disabled={disabled}- className="self-start"- onClick={() =>- setConditions([...conditions, { path: "", equals: "" }])- }- >- <Plus size={13} />- Add condition- </Button>- </div>- </SubField>+ <Input+ value={condition.path}+ disabled={disabled}+ placeholder="requested_team.slug"+ // The placeholder stops naming the field as soon as someone types into it.+ aria-label="Condition path"+ className="h-7 flex-1"+ onChange={(event) =>+ updateCondition(index, { path: event.target.value })+ }+ />+ <span className="text-[12px] text-gray-10">is</span>+ <PayloadConditionValues+ values={+ Array.isArray(condition.equals)+ ? condition.equals+ : [condition.equals].filter(Boolean)+ }+ disabled={disabled}+ onChange={(equals) => updateCondition(index, { equals })}+ />+ <Button+ variant="outline"+ size="sm"+ disabled={disabled}+ aria-label={+ condition.path+ ? `Remove condition ${condition.path}`+ : "Remove condition"+ }+ onClick={() =>+ setConditions(conditions.filter((_, i) => i !== index))+ }+ >+ <Trash size={13} />+ </Button>+ </div>+ ))}+ <Button+ variant="outline"+ size="sm"+ disabled={disabled}+ className="self-start"+ onClick={() =>+ setConditions([...conditions, { path: "", equals: "" }])+ }+ >+ <Plus size={13} />+ Add condition+ </Button>+ </div>+ </SubField>+ ) : null}</Flex>);}diff --git a/products/desktop/packages/ui/src/features/loops/components/LoopWorkflowPromptFields.tsx b/products/desktop/packages/ui/src/features/loops/components/LoopWorkflowPromptFields.tsxnew file mode 100644index 000000000000..7ef0c5c14537--- /dev/null+++ b/products/desktop/packages/ui/src/features/loops/components/LoopWorkflowPromptFields.tsx@@ -0,0 +1,38 @@+import { Textarea } from "@posthog/quill";+import type { LoopFormValues } from "../loopFormTypes";+import { Field } from "./LoopFormPrimitives";+import { LoopTeamSkillsFields } from "./LoopTeamSkillsFields";++/**+ * The prompt of a workflow-backed loop: free-form instructions plus team+ * skills. There is no local-skill mode here, because the workflow reads skills+ * from the team store at run time instead of a snapshot uploaded from a laptop.+ */+export function LoopWorkflowPromptFields({+ values,+ disabled,+ onPatch,+}: {+ values: LoopFormValues;+ disabled: boolean;+ onPatch: (next: Partial<LoopFormValues>) => void;+}) {+ return (+ <>+ <Field label="Instructions" required>+ <Textarea+ value={values.instructions}+ placeholder="Summarize failing CI runs from the last 24 hours and post the summary to #eng-standup."+ disabled={disabled}+ className="min-h-[220px] text-[13px] leading-relaxed"+ onChange={(e) => onPatch({ instructions: e.target.value })}+ />+ </Field>+ <LoopTeamSkillsFields+ value={values.teamSkills}+ disabled={disabled}+ onChange={(teamSkills) => onPatch({ teamSkills })}+ />+ </>+ );+}diff --git a/products/desktop/packages/ui/src/features/loops/components/LoopsListView.stories.tsx b/products/desktop/packages/ui/src/features/loops/components/LoopsListView.stories.tsxindex 3c868e467085..ea5d7b3e9b63 100644--- a/products/desktop/packages/ui/src/features/loops/components/LoopsListView.stories.tsx+++ b/products/desktop/packages/ui/src/features/loops/components/LoopsListView.stories.tsx@@ -174,6 +174,14 @@ export const LongMixedList: Story = {},};+/** Loops backed by workflows: one team list, no personal/team tabs. */+export const WorkflowBacked: Story = {+ args: {+ workflowBacked: true,+ loops: MIXED_LOOPS.map((entry) => ({ ...entry, visibility: "team" })),+ },+};+export const WithBuilderSessions: Story = {args: {builderSessions: [diff --git a/products/desktop/packages/ui/src/features/loops/components/LoopsListView.test.tsx b/products/desktop/packages/ui/src/features/loops/components/LoopsListView.test.tsxindex a68ef64b5715..7568b601da60 100644--- a/products/desktop/packages/ui/src/features/loops/components/LoopsListView.test.tsx+++ b/products/desktop/packages/ui/src/features/loops/components/LoopsListView.test.tsx@@ -110,6 +110,38 @@ describe("LoopsListViewPresentation", () => {);});+ // The flag that switches loops onto workflows resolves after the first+ // render. Workflow loops are all team-visible and the trigger strip is+ // hidden for them, so a stale personal tab would show an empty page.+ it("shows workflow loops when the mode flips after mount", () => {+ const teamLoop = loop("mine-team", "team");+ const { rerender } = render(+ <Theme>+ <LoopsListViewPresentation+ loops={[teamLoop]}+ workflowBacked={false}+ onStartBlank={vi.fn()}+ onStartFromTemplate={vi.fn()}+ />+ </Theme>,+ );+ expect(screen.queryByText("team loop")).not.toBeInTheDocument();++ rerender(+ <Theme>+ <LoopsListViewPresentation+ loops={[teamLoop]}+ workflowBacked+ onStartBlank={vi.fn()}+ onStartFromTemplate={vi.fn()}+ />+ </Theme>,+ );++ expect(screen.queryByRole("tab")).not.toBeInTheDocument();+ expect(screen.getByText("team loop")).toBeVisible();+ });+it("hides the header trigger strip while loops are loading", () => {render(<Theme>diff --git a/products/desktop/packages/ui/src/features/loops/components/LoopsListView.tsx b/products/desktop/packages/ui/src/features/loops/components/LoopsListView.tsxindex 4aa69ef48830..87f1483fd3af 100644--- a/products/desktop/packages/ui/src/features/loops/components/LoopsListView.tsx+++ b/products/desktop/packages/ui/src/features/loops/components/LoopsListView.tsx@@ -4,6 +4,7 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@posthog/quill";import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";import type { UserBasic } from "@posthog/shared/domain-types";import { useOrgMembers } from "@posthog/ui/features/canvas/hooks/useOrgMembers";+import { useLoopsHogFlowsEnabled } from "@posthog/ui/features/feature-flags/useLoopsHogFlowsEnabled";import { StopCloudRunDialog } from "@posthog/ui/features/sessions/components/StopCloudRunDialog";import { useSetHeaderContent } from "@posthog/ui/hooks/useSetHeaderContent";import { Button } from "@posthog/ui/primitives/Button";@@ -77,6 +78,7 @@ export function LoopsListView({}) {const { data: loops, isLoading, isError, error } = useLoops();const limits = useLoopLimits();+ const workflowBacked = useLoopsHogFlowsEnabled();const limitReason =limits?.atLimit === true ? loopLimitReason(limits.max) : null;@@ -135,6 +137,7 @@ export function LoopsListView({isLoading={isLoading}error={isError ? error : null}limitReason={limitReason}+ workflowBacked={workflowBacked}members={members}membersLoading={membersLoading}membersError={membersError}@@ -153,6 +156,8 @@ interface LoopsListViewPresentationProps {isLoading?: boolean;error?: unknown;limitReason?: string | null;+ /** Loops backed by workflows are all team-visible and have no API trigger. */+ workflowBacked?: boolean;members?: UserBasic[];membersLoading?: boolean;membersError?: boolean;@@ -169,6 +174,7 @@ export function LoopsListViewPresentation({isLoading = false,error = null,limitReason = null,+ workflowBacked = false,members = EMPTY_MEMBERS,membersLoading = false,membersError = false,@@ -198,7 +204,9 @@ export function LoopsListViewPresentation({// Only the loaded, non-empty list has tabs to show — the skeleton, the error// notice and the empty state all render without them.- const hasTabs = !isLoading && !error && loops.length > 0;+ // Workflow-backed loops are all team-visible, so the personal/team split+ // would show one empty tab and one full one.+ const hasTabs = !isLoading && !error && loops.length > 0 && !workflowBacked;const body = (<>@@ -261,9 +269,12 @@ export function LoopsListViewPresentation({// One Tabs root spanning header and body: the trigger strip sits in the// header's sub-nav, its panels stay down in the scrolling body.+ // The default tab is read once at mount, and the flag can flip after that.+ // Remount on a mode change so workflow loops never sit behind a hidden tab.return (<Tabs- defaultValue="personal"+ key={workflowBacked ? "workflow" : "loops"}+ defaultValue={workflowBacked ? "team" : "personal"}className="flex h-full min-h-0 flex-col gap-0"><PageHeader>@@ -276,9 +287,9 @@ export function LoopsListViewPresentation({<PageHeaderActions>{createButton}</PageHeaderActions></PageHeaderTitleRow><PageHeaderDescription>- Put your work on autopilot. Loops run on a schedule, on an API call,- or when something happens on GitHub. You can finally close the- laptop!+ {workflowBacked+ ? "Put your work on autopilot. Loops run on a schedule or when something happens on GitHub. You can finally close the laptop!"+ : "Put your work on autopilot. Loops run on a schedule, on an API call, or when something happens on GitHub. You can finally close the laptop!"}</PageHeaderDescription></PageHeaderHeading>{hasTabs && (diff --git a/products/desktop/packages/ui/src/features/loops/hooks/loopsKeys.ts b/products/desktop/packages/ui/src/features/loops/hooks/loopsKeys.tsindex bb97e5e949cc..d2d9da5891fa 100644--- a/products/desktop/packages/ui/src/features/loops/hooks/loopsKeys.ts+++ b/products/desktop/packages/ui/src/features/loops/hooks/loopsKeys.ts@@ -6,4 +6,13 @@ export const loopsKeys = {["loops", "runs", projectId, loopId] as const,preview: (projectId: string | null, loopId: string) =>["loops", "preview", projectId, loopId] as const,+ // Workflow-backed loops cache under their own keys: the raw shapes differ+ // from the loops API, so a flag flip must not read one backend's cache as+ // the other's.+ hogFlowList: (projectId: string | null) =>+ ["loops", "hog-flows", "list", projectId] as const,+ hogFlow: (projectId: string | null, loopId: string) =>+ ["loops", "hog-flows", "detail", projectId, loopId] as const,+ hogFlowRuns: (projectId: string | null, loopId: string) =>+ ["loops", "hog-flows", "runs", projectId, loopId] as const,};diff --git a/products/desktop/packages/ui/src/features/loops/hooks/useLoop.ts b/products/desktop/packages/ui/src/features/loops/hooks/useLoop.tsindex 4cc80beeac61..53596bea35ec 100644--- a/products/desktop/packages/ui/src/features/loops/hooks/useLoop.ts+++ b/products/desktop/packages/ui/src/features/loops/hooks/useLoop.ts@@ -1,13 +1,48 @@+import type { Schemas } from "@posthog/api-client/generated";+import { retrieveHogFlow } from "@posthog/api-client/hogFlowLoops";import { type LoopSchemas, retrieveLoop } from "@posthog/api-client/loops";import { AUTH_SCOPED_QUERY_META } from "@posthog/ui/features/auth/useCurrentUser";+import { useLoopsHogFlowsEnabled } from "@posthog/ui/features/feature-flags/useLoopsHogFlowsEnabled";import { useQuery } from "@tanstack/react-query";+import { hogFlowToLoop } from "../loopHogFlowMapping";import { loopsKeys } from "./loopsKeys";-import { useLoopsClient } from "./useLoopsClient";+import { type LoopsApiClient, useLoopsClient } from "./useLoopsClient";++function hogFlowQueryOptions(+ loopsClient: LoopsApiClient | null,+ loopId: string | undefined,+ enabled: boolean,+) {+ return {+ queryKey: loopsKeys.hogFlow(loopsClient?.projectId ?? null, loopId ?? ""),+ queryFn: async (): Promise<Schemas.HogFlow> => {+ if (!loopsClient || !loopId) throw new Error("Not authenticated");+ return await retrieveHogFlow(+ loopsClient.client,+ loopsClient.projectId,+ loopId,+ );+ },+ enabled: enabled && !!loopsClient && !!loopId,+ staleTime: 15_000,+ meta: AUTH_SCOPED_QUERY_META,+ };+}++/** The workflow behind a loop, unmapped. Shares its cache entry with `useLoop`+ * so the detail page issues one request for both the loop and the shape check. */+export function useLoopHogFlow(loopId: string | undefined) {+ const hogFlows = useLoopsHogFlowsEnabled();+ const loopsClient = useLoopsClient();+ return useQuery(hogFlowQueryOptions(loopsClient, loopId, hogFlows));+}export function useLoop(loopId: string | undefined) {+ const hogFlows = useLoopsHogFlowsEnabled();const loopsClient = useLoopsClient();+ const projectId = Number(loopsClient?.projectId);- return useQuery<LoopSchemas.Loop>({+ const loopsApi = useQuery<LoopSchemas.Loop>({queryKey: loopsKeys.detail(loopsClient?.projectId ?? null, loopId ?? ""),queryFn: async () => {if (!loopsClient || !loopId) throw new Error("Not authenticated");@@ -17,8 +52,13 @@ export function useLoop(loopId: string | undefined) {loopId,);},- enabled: !!loopsClient && !!loopId,+ enabled: !hogFlows && !!loopsClient && !!loopId,staleTime: 15_000,meta: AUTH_SCOPED_QUERY_META,});+ const workflow = useQuery({+ ...hogFlowQueryOptions(loopsClient, loopId, hogFlows),+ select: (flow: Schemas.HogFlow) => hogFlowToLoop(flow, { projectId }),+ });+ return hogFlows ? workflow : loopsApi;}diff --git a/products/desktop/packages/ui/src/features/loops/hooks/useLoopMutations.ts b/products/desktop/packages/ui/src/features/loops/hooks/useLoopMutations.tsindex 90894764bdb7..57deaad991a3 100644--- a/products/desktop/packages/ui/src/features/loops/hooks/useLoopMutations.ts+++ b/products/desktop/packages/ui/src/features/loops/hooks/useLoopMutations.ts@@ -1,3 +1,5 @@+import type { Schemas } from "@posthog/api-client/generated";+import { deleteHogFlow } from "@posthog/api-client/hogFlowLoops";import {createLoop,destroyLoop,@@ -5,9 +7,47 @@ import {partialUpdateLoop,runLoop,} from "@posthog/api-client/loops";-import { useMutation, useQueryClient } from "@tanstack/react-query";+import { useLoopsHogFlowsEnabled } from "@posthog/ui/features/feature-flags/useLoopsHogFlowsEnabled";+import {+ type QueryClient,+ useMutation,+ useQueryClient,+} from "@tanstack/react-query";+import type { LoopFormValues } from "../loopFormTypes";+import { formValuesToHogFlowWrite, hogFlowToLoop } from "../loopHogFlowMapping";+import {+ createLoopHogFlow,+ LoopScheduleSaveError,+ runLoopHogFlow,+ setLoopHogFlowEnabled,+ updateLoopHogFlow,+} from "../loopHogFlowWrites";import { loopsKeys } from "./loopsKeys";-import { useLoopsClient } from "./useLoopsClient";+import { type LoopsApiClient, useLoopsClient } from "./useLoopsClient";++function invalidateLoopLists(+ queryClient: QueryClient,+ projectId: string | null,+): void {+ void queryClient.invalidateQueries({ queryKey: loopsKeys.list(projectId) });+ void queryClient.invalidateQueries({+ queryKey: loopsKeys.hogFlowList(projectId),+ });+}++/** Stores a saved workflow so the detail page reflects the write at once. */+function applyHogFlowToCache(+ queryClient: QueryClient,+ loopsClient: LoopsApiClient,+ flow: Schemas.HogFlow,+): LoopSchemas.Loop {+ queryClient.setQueryData(+ loopsKeys.hogFlow(loopsClient.projectId, flow.id),+ flow,+ );+ invalidateLoopLists(queryClient, loopsClient.projectId);+ return hogFlowToLoop(flow, { projectId: Number(loopsClient.projectId) });+}export function useCreateLoop() {const loopsClient = useLoopsClient();@@ -19,71 +59,169 @@ export function useCreateLoop() {return await createLoop(loopsClient.client, loopsClient.projectId, body);},onSuccess: () => {- void queryClient.invalidateQueries({- queryKey: loopsKeys.list(loopsClient?.projectId ?? null),- });+ invalidateLoopLists(queryClient, loopsClient?.projectId ?? null);},});}+/** Creates a workflow-backed loop from the form. `enabled` picks between a+ * live workflow and a draft, since the form has no separate enable step. */+export function useCreateLoopHogFlow() {+ const loopsClient = useLoopsClient();+ const queryClient = useQueryClient();++ return useMutation<+ LoopSchemas.Loop,+ Error,+ { values: LoopFormValues; enabled: boolean }+ >({+ mutationFn: async ({ values, enabled }) => {+ if (!loopsClient) throw new Error("Not authenticated");+ const flow = await createLoopHogFlow(+ loopsClient.client,+ loopsClient.projectId,+ formValuesToHogFlowWrite(values, { enabled }),+ );+ return applyHogFlowToCache(queryClient, loopsClient, flow);+ },+ });+}++/** Partial updates against the loop's lifecycle fields. For a workflow-backed+ * loop only `enabled` applies; content edits go through `useUpdateLoopHogFlow`. */export function useUpdateLoop(loopId: string) {+ const hogFlows = useLoopsHogFlowsEnabled();const loopsClient = useLoopsClient();const queryClient = useQueryClient();return useMutation<LoopSchemas.Loop, Error, LoopSchemas.PatchedLoop>({mutationFn: async (body) => {if (!loopsClient) throw new Error("Not authenticated");- return await partialUpdateLoop(+ if (!hogFlows) {+ return await partialUpdateLoop(+ loopsClient.client,+ loopsClient.projectId,+ loopId,+ body,+ );+ }+ if (typeof body.enabled !== "boolean") {+ throw new Error(+ "Only the enabled state can be patched on a workflow-backed loop.",+ );+ }+ const flow = await setLoopHogFlowEnabled(loopsClient.client,loopsClient.projectId,loopId,- body,+ body.enabled,);+ return applyHogFlowToCache(queryClient, loopsClient, flow);},onSuccess: (loop) => {+ if (hogFlows) return;queryClient.setQueryData(loopsKeys.detail(loopsClient?.projectId ?? null, loopId),loop,);+ invalidateLoopLists(queryClient, loopsClient?.projectId ?? null);+ },+ });+}++/** Saves the whole form onto an existing workflow-backed loop. Needs the+ * current workflow so the schedule row can be reconciled rather than rewritten. */+export function useUpdateLoopHogFlow(loopId: string) {+ const loopsClient = useLoopsClient();+ const queryClient = useQueryClient();++ return useMutation<+ LoopSchemas.Loop,+ Error,+ { values: LoopFormValues; existing: Schemas.HogFlow }+ >({+ mutationFn: async ({ values, existing }) => {+ if (!loopsClient) throw new Error("Not authenticated");+ try {+ const flow = await updateLoopHogFlow(+ loopsClient.client,+ loopsClient.projectId,+ existing,+ formValuesToHogFlowWrite(values, {+ enabled: existing.status === "active",+ existing,+ }),+ );+ return applyHogFlowToCache(queryClient, loopsClient, flow);+ } catch (error) {+ // The graph is live with a new `updated_at`; caching it keeps the+ // retry's `base_updated_at` current instead of refused as stale.+ if (error instanceof LoopScheduleSaveError) {+ applyHogFlowToCache(queryClient, loopsClient, error.flow);+ }+ throw error;+ }+ },+ onSettled: () => {+ // A partial failure (graph saved, schedule not) leaves the cache behind+ // the server; refetching the flow shows what actually stuck.void queryClient.invalidateQueries({- queryKey: loopsKeys.list(loopsClient?.projectId ?? null),+ queryKey: loopsKeys.hogFlow(loopsClient?.projectId ?? null, loopId),});},});}export function useDeleteLoop() {+ const hogFlows = useLoopsHogFlowsEnabled();const loopsClient = useLoopsClient();const queryClient = useQueryClient();return useMutation<void, Error, string>({mutationFn: async (loopId) => {if (!loopsClient) throw new Error("Not authenticated");+ if (hogFlows) {+ await deleteHogFlow(loopsClient.client, loopsClient.projectId, loopId);+ return;+ }await destroyLoop(loopsClient.client, loopsClient.projectId, loopId);},onSuccess: () => {- void queryClient.invalidateQueries({- queryKey: loopsKeys.list(loopsClient?.projectId ?? null),- });+ invalidateLoopLists(queryClient, loopsClient?.projectId ?? null);},});}export function useRunLoop(loopId: string) {+ const hogFlows = useLoopsHogFlowsEnabled();const loopsClient = useLoopsClient();const queryClient = useQueryClient();return useMutation<LoopSchemas.LoopFireRun, Error, void>({mutationFn: async () => {if (!loopsClient) throw new Error("Not authenticated");+ if (hogFlows) {+ return await runLoopHogFlow(+ loopsClient.client,+ loopsClient.projectId,+ loopId,+ );+ }return await runLoop(loopsClient.client, loopsClient.projectId, loopId);},onSuccess: () => {+ const projectId = loopsClient?.projectId ?? null;+ void queryClient.invalidateQueries({+ queryKey: loopsKeys.runs(projectId, loopId),+ });+ void queryClient.invalidateQueries({+ queryKey: loopsKeys.hogFlowRuns(projectId, loopId),+ });void queryClient.invalidateQueries({- queryKey: loopsKeys.runs(loopsClient?.projectId ?? null, loopId),+ queryKey: loopsKeys.detail(projectId, loopId),});void queryClient.invalidateQueries({- queryKey: loopsKeys.detail(loopsClient?.projectId ?? null, loopId),+ queryKey: loopsKeys.hogFlow(projectId, loopId),});},});diff --git a/products/desktop/packages/ui/src/features/loops/hooks/useLoopRuns.ts b/products/desktop/packages/ui/src/features/loops/hooks/useLoopRuns.tsindex d7f0a5a341f0..913c6d398df9 100644--- a/products/desktop/packages/ui/src/features/loops/hooks/useLoopRuns.ts+++ b/products/desktop/packages/ui/src/features/loops/hooks/useLoopRuns.ts@@ -1,6 +1,9 @@+import { listHogFlowTasks } from "@posthog/api-client/hogFlowLoops";import { type LoopSchemas, listLoopRuns } from "@posthog/api-client/loops";import { AUTH_SCOPED_QUERY_META } from "@posthog/ui/features/auth/useCurrentUser";+import { useLoopsHogFlowsEnabled } from "@posthog/ui/features/feature-flags/useLoopsHogFlowsEnabled";import { useQuery } from "@tanstack/react-query";+import { taskToLoopRun } from "../loopHogFlowMapping";import { loopsKeys } from "./loopsKeys";import { useLoopsClient } from "./useLoopsClient";@@ -8,10 +11,16 @@ export const RECENT_RUNS_LIMIT = 10;/** The most recent runs for a loop, polled so the detail view stays live. */export function useLoopRuns(loopId: string | undefined) {+ const hogFlows = useLoopsHogFlowsEnabled();const loopsClient = useLoopsClient();+ const projectId = loopsClient?.projectId ?? null;- return useQuery<LoopSchemas.LoopRunPage, Error, LoopSchemas.LoopRun[]>({- queryKey: loopsKeys.runs(loopsClient?.projectId ?? null, loopId ?? ""),+ const loopsApi = useQuery<+ LoopSchemas.LoopRunPage,+ Error,+ LoopSchemas.LoopRun[]+ >({+ queryKey: loopsKeys.runs(projectId, loopId ?? ""),queryFn: async () => {if (!loopsClient || !loopId) throw new Error("Not authenticated");return await listLoopRuns(@@ -22,9 +31,30 @@ export function useLoopRuns(loopId: string | undefined) {);},select: (page) => page.results.slice(0, RECENT_RUNS_LIMIT),- enabled: !!loopsClient && !!loopId,+ enabled: !hogFlows && !!loopsClient && !!loopId,staleTime: 10_000,refetchInterval: 15_000,meta: AUTH_SCOPED_QUERY_META,});++ // Run history for a workflow-backed loop is the tasks the workflow created.+ const workflow = useQuery<LoopSchemas.LoopRun[]>({+ queryKey: loopsKeys.hogFlowRuns(projectId, loopId ?? ""),+ queryFn: async () => {+ if (!loopsClient || !loopId) throw new Error("Not authenticated");+ const page = await listHogFlowTasks(+ loopsClient.client,+ loopsClient.projectId,+ loopId,+ { limit: RECENT_RUNS_LIMIT },+ );+ return page.results.map(taskToLoopRun);+ },+ enabled: hogFlows && !!loopsClient && !!loopId,+ staleTime: 10_000,+ refetchInterval: 15_000,+ meta: AUTH_SCOPED_QUERY_META,+ });++ return hogFlows ? workflow : loopsApi;}diff --git a/products/desktop/packages/ui/src/features/loops/hooks/useLoops.test.tsx b/products/desktop/packages/ui/src/features/loops/hooks/useLoops.test.tsxnew file mode 100644index 000000000000..3fd58c47a9af--- /dev/null+++ b/products/desktop/packages/ui/src/features/loops/hooks/useLoops.test.tsx@@ -0,0 +1,97 @@+import { listLoopHogFlows } from "@posthog/api-client/hogFlowLoops";+import type { LoopSchemas } from "@posthog/api-client/loops";+import { useLoopsHogFlowsEnabled } from "@posthog/ui/features/feature-flags/useLoopsHogFlowsEnabled";+import { QueryClient, QueryClientProvider } from "@tanstack/react-query";+import { renderHook, waitFor } from "@testing-library/react";+import type { ReactNode } from "react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import { loopsKeys } from "./loopsKeys";+import { useLoopLimits, useLoops } from "./useLoops";++vi.mock("@posthog/api-client/hogFlowLoops", () => ({+ listLoopHogFlows: vi.fn(),+}));+vi.mock("@posthog/api-client/loops", () => ({+ listLoops: vi.fn(),+}));+vi.mock("@posthog/ui/features/auth/useCurrentUser", () => ({+ AUTH_SCOPED_QUERY_META: {},+}));+vi.mock("@posthog/ui/features/feature-flags/useLoopsHogFlowsEnabled", () => ({+ useLoopsHogFlowsEnabled: vi.fn(),+}));+vi.mock("./useLoopsClient", () => ({+ useLoopsClient: () => ({ client: {}, projectId: "1" }),+}));+vi.mock("../loopHogFlowMapping", () => ({+ hogFlowToLoop: (flow: { id: string }) => ({ id: flow.id }),+}));++const mockedListLoopHogFlows = vi.mocked(listLoopHogFlows);+const mockedHogFlowsEnabled = vi.mocked(useLoopsHogFlowsEnabled);++function wrapperFor(queryClient: QueryClient) {+ return ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ );+}++beforeEach(() => {+ vi.clearAllMocks();+});++describe("useLoops", () => {+ it("drops archived workflows from the workflow-backed list", async () => {+ mockedHogFlowsEnabled.mockReturnValue(true);+ mockedListLoopHogFlows.mockResolvedValue({+ results: [+ { id: "live", status: "active" },+ { id: "gone", status: "archived" },+ { id: "unpublished", status: "draft" },+ ],+ } as Awaited<ReturnType<typeof listLoopHogFlows>>);+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });++ const { result } = renderHook(() => useLoops(), {+ wrapper: wrapperFor(queryClient),+ });++ await waitFor(() => expect(result.current.isSuccess).toBe(true));+ expect(result.current.data?.map((loop) => loop.id)).toEqual([+ "live",+ "unpublished",+ ]);+ });+});++describe("useLoopLimits", () => {+ const cachedPage = {+ results: [],+ max_loops_per_team: 5,+ total_loop_count: 5,+ } as unknown as LoopSchemas.PaginatedLoopList;++ // The loops query is disabled for workflow-backed loops, but a page cached+ // before the flag flipped would still be served.+ it.each([+ { hogFlows: true, expected: null },+ { hogFlows: false, expected: { max: 5, used: 5, atLimit: true } },+ ])(+ "returns $expected from a cached page when hogFlows is $hogFlows",+ ({ hogFlows, expected }) => {+ mockedHogFlowsEnabled.mockReturnValue(hogFlows);+ const queryClient = new QueryClient({+ defaultOptions: { queries: { retry: false } },+ });+ queryClient.setQueryData(loopsKeys.list("1"), cachedPage);++ const { result } = renderHook(() => useLoopLimits(), {+ wrapper: wrapperFor(queryClient),+ });++ expect(result.current).toEqual(expected);+ },+ );+});diff --git a/products/desktop/packages/ui/src/features/loops/hooks/useLoops.ts b/products/desktop/packages/ui/src/features/loops/hooks/useLoops.tsindex 458c4f0c9bd0..3b2eefe6c070 100644--- a/products/desktop/packages/ui/src/features/loops/hooks/useLoops.ts+++ b/products/desktop/packages/ui/src/features/loops/hooks/useLoops.ts@@ -1,6 +1,9 @@+import { listLoopHogFlows } from "@posthog/api-client/hogFlowLoops";import { type LoopSchemas, listLoops } from "@posthog/api-client/loops";import { AUTH_SCOPED_QUERY_META } from "@posthog/ui/features/auth/useCurrentUser";+import { useLoopsHogFlowsEnabled } from "@posthog/ui/features/feature-flags/useLoopsHogFlowsEnabled";import { useQuery } from "@tanstack/react-query";+import { hogFlowToLoop } from "../loopHogFlowMapping";import { loopsKeys } from "./loopsKeys";import { type LoopsApiClient, useLoopsClient } from "./useLoopsClient";@@ -9,7 +12,10 @@ const LOOPS_LIST_LIMIT = 100;/** Shared query for the loops list page. Both `useLoops` (the loop rows) and `useLoopLimits`* (the per-project cap) read from this single fetch via `select`, so the cap the backend serves* stays in lockstep with the list and there's no second request. */-function loopsPageQueryOptions(loopsClient: LoopsApiClient | null) {+function loopsPageQueryOptions(+ loopsClient: LoopsApiClient | null,+ enabled: boolean,+) {return {queryKey: loopsKeys.list(loopsClient?.projectId ?? null),queryFn: async (): Promise<LoopSchemas.PaginatedLoopList> => {@@ -18,18 +24,46 @@ function loopsPageQueryOptions(loopsClient: LoopsApiClient | null) {limit: LOOPS_LIST_LIMIT,});},- enabled: !!loopsClient,+ enabled: enabled && !!loopsClient,+ staleTime: 30_000,+ meta: AUTH_SCOPED_QUERY_META,+ };+}++function hogFlowLoopsQueryOptions(+ loopsClient: LoopsApiClient | null,+ enabled: boolean,+) {+ return {+ queryKey: loopsKeys.hogFlowList(loopsClient?.projectId ?? null),+ queryFn: async (): Promise<LoopSchemas.Loop[]> => {+ if (!loopsClient) throw new Error("Not authenticated");+ const page = await listLoopHogFlows(+ loopsClient.client,+ loopsClient.projectId,+ );+ const projectId = Number(loopsClient.projectId);+ // The list endpoint returns archived workflows too. They would map to+ // paused loops whose Resume sets them active instead of restoring them.+ return page.results+ .filter((flow) => flow.status !== "archived")+ .map((flow) => hogFlowToLoop(flow, { projectId }));+ },+ enabled: enabled && !!loopsClient,staleTime: 30_000,meta: AUTH_SCOPED_QUERY_META,};}export function useLoops() {+ const hogFlows = useLoopsHogFlowsEnabled();const loopsClient = useLoopsClient();- return useQuery({- ...loopsPageQueryOptions(loopsClient),+ const loopsApi = useQuery({+ ...loopsPageQueryOptions(loopsClient, !hogFlows),select: (page: LoopSchemas.PaginatedLoopList) => page.results,});+ const workflows = useQuery(hogFlowLoopsQueryOptions(loopsClient, hogFlows));+ return hogFlows ? workflows : loopsApi;}/** The per-project loop cap, straight from the backend so the frontend never hardcodes it. */@@ -42,15 +76,19 @@ export interface LoopLimits {atLimit: boolean;}+/** Null while loading, and always null for workflow-backed loops: workflows+ * cap task creation per run instead of capping how many loops exist. */export function useLoopLimits(): LoopLimits | null {+ const hogFlows = useLoopsHogFlowsEnabled();const loopsClient = useLoopsClient();const { data } = useQuery({- ...loopsPageQueryOptions(loopsClient),+ ...loopsPageQueryOptions(loopsClient, !hogFlows),select: (page: LoopSchemas.PaginatedLoopList): LoopLimits => ({max: page.max_loops_per_team,used: page.total_loop_count,atLimit: page.total_loop_count >= page.max_loops_per_team,}),});- return data ?? null;+ // A disabled query still serves its cached page, so guard on the flag too.+ return hogFlows ? null : (data ?? null);}diff --git a/products/desktop/packages/ui/src/features/loops/loopDisplay.test.ts b/products/desktop/packages/ui/src/features/loops/loopDisplay.test.tsindex b9db67269765..6edb4ae93b61 100644--- a/products/desktop/packages/ui/src/features/loops/loopDisplay.test.ts+++ b/products/desktop/packages/ui/src/features/loops/loopDisplay.test.ts@@ -120,6 +120,13 @@ describe("describeTrigger", () => {).toContain(`Schedule · ${expected} · Next run `);});+ // A workflow can carry a schedule trigger with no schedule row yet.+ it("names a schedule trigger with no cron as unset", () => {+ expect(describeTrigger({ type: "schedule", config: {} })).toBe(+ "Schedule · No schedule set",+ );+ });+it("keeps custom cron expressions visible", () => {expect(describeTrigger({diff --git a/products/desktop/packages/ui/src/features/loops/loopDisplay.ts b/products/desktop/packages/ui/src/features/loops/loopDisplay.tsindex e025c3718010..ca96b5f72b11 100644--- a/products/desktop/packages/ui/src/features/loops/loopDisplay.ts+++ b/products/desktop/packages/ui/src/features/loops/loopDisplay.ts@@ -24,7 +24,8 @@ function describeSchedule(const parsed = parseCronSchedule(cron);const timezone = config.timezone ?? "UTC";const timezoneLabel = formatTimezoneAbbreviation(timezone);- if (!parsed) return `${cron ?? "?"} (${timezoneLabel})`;+ if (!cron) return "No schedule set";+ if (!parsed) return `${cron} (${timezoneLabel})`;if (parsed.frequency === "hourly") return `Every hour (${timezoneLabel})`;const time = formatClockTime(parsed.time);diff --git a/products/desktop/packages/ui/src/features/loops/loopFormTypes.ts b/products/desktop/packages/ui/src/features/loops/loopFormTypes.tsindex 29b2cf702d4d..98f4fc6ffaf8 100644--- a/products/desktop/packages/ui/src/features/loops/loopFormTypes.ts+++ b/products/desktop/packages/ui/src/features/loops/loopFormTypes.ts@@ -56,6 +56,9 @@ export interface LoopFormValues {behaviors: LoopSchemas.LoopBehaviors;notifications: LoopSchemas.LoopNotifications;contextTarget: LoopContextTargetDraft | null;+ /** Names of team skills attached to a workflow-backed loop. The loops API+ * has no equivalent and ignores it. */+ teamSkills: string[];}function emptyLoopScheduleTriggerConfig(): LoopSchemas.LoopScheduleTriggerConfig {@@ -246,6 +249,7 @@ export function emptyLoopFormValues(): LoopFormValues {behaviors: defaultLoopBehaviors(),notifications: defaultLoopNotifications(),contextTarget: null,+ teamSkills: [],};}@@ -299,6 +303,7 @@ export function loopToFormValues(loop: LoopSchemas.Loop): LoopFormValues {outputs: loop.context_target.outputs,}: null,+ teamSkills: [],};}@@ -340,7 +345,22 @@ export function formValuesToLoopWrite(};}-export function isLoopFormValid(values: LoopFormValues): boolean {+/**+ * What a loop's backend can store. The loops API takes any trigger list; a+ * workflow holds exactly one trigger, resolves the GitHub repository itself+ * (so no integration id is needed), and listens to one event type.+ */+export interface LoopFormRules {+ backend: "loops" | "workflow";+}++export const LOOPS_API_RULES: LoopFormRules = { backend: "loops" };+export const WORKFLOW_RULES: LoopFormRules = { backend: "workflow" };++export function isLoopFormValid(+ values: LoopFormValues,+ rules: LoopFormRules = LOOPS_API_RULES,+): boolean {if (!values.name.trim()) {return false;}@@ -350,24 +370,43 @@ export function isLoopFormValid(values: LoopFormValues): boolean {if (values.contextTarget && values.visibility !== "team") {return false;}- return values.triggers.every((trigger) => isTriggerDraftValid(trigger));+ return isTriggerListValid(values.triggers, rules);+}++/** Whether the trigger list can be saved: the loops API takes any list, an+ * empty one included, and a workflow needs exactly one enabled trigger. */+export function isTriggerListValid(+ triggers: LoopTriggerDraft[],+ rules: LoopFormRules = LOOPS_API_RULES,+): boolean {+ if (rules.backend === "workflow") {+ const [trigger, ...rest] = triggers;+ if (!trigger || rest.length > 0 || !trigger.enabled) {+ return false;+ }+ }+ return triggers.every((trigger) => isTriggerDraftValid(trigger, rules));}-export function isTriggerDraftValid(trigger: LoopTriggerDraft): boolean {+export function isTriggerDraftValid(+ trigger: LoopTriggerDraft,+ rules: LoopFormRules = LOOPS_API_RULES,+): boolean {if (trigger.type === "schedule") {const config = trigger.config as LoopSchemas.LoopScheduleTriggerConfig;return !!config.run_at || !!config.cron_expression;}if (trigger.type === "github") {const config = trigger.config as LoopSchemas.LoopGithubTriggerConfig;+ const workflow = rules.backend === "workflow";return (!!config.repository &&- config.github_integration_id > 0 &&- config.events.length > 0 &&+ (workflow || config.github_integration_id > 0) &&+ (workflow ? config.events.length === 1 : config.events.length > 0) &&(config.filters?.payload ?? []).every(isPayloadConditionValid));}- return true;+ return rules.backend !== "workflow";}/** Each accepted value is its own chip in the editor, never a delimited string. An earlierdiff --git a/products/desktop/packages/ui/src/features/loops/loopHogFlowMapping.test.ts b/products/desktop/packages/ui/src/features/loops/loopHogFlowMapping.test.tsnew file mode 100644index 000000000000..006702db74e5--- /dev/null+++ b/products/desktop/packages/ui/src/features/loops/loopHogFlowMapping.test.ts@@ -0,0 +1,558 @@+import type { Schemas } from "@posthog/api-client/generated";+import { describe, expect, it } from "vitest";+import {+ emptyLoopFormValues,+ type LoopFormValues,+ loopToFormValues,+} from "./loopFormTypes";+import {+ formValuesToHogFlowWrite,+ hogFlowTeamSkills,+ hogFlowToLoop,+ isLoopShapedHogFlow,+ type LoopHogFlowSource,+ taskToLoopRun,+ UnsupportedLoopShapeError,+} from "./loopHogFlowMapping";++const PROJECT_ID = 42;++function must<T>(value: T | null | undefined): T {+ if (value == null) throw new Error("expected a value");+ return value;+}++function scheduleValues(+ overrides: Partial<LoopFormValues> = {},+): LoopFormValues {+ return {+ ...emptyLoopFormValues(),+ name: " Morning triage ",+ description: "Look at overnight errors ",+ instructions: "Triage the error tracking inbox.\n",+ triggers: [+ {+ key: "t1",+ type: "schedule",+ enabled: true,+ config: { cron_expression: "0 9 * * 1-5", timezone: "Europe/Lisbon" },+ },+ ],+ ...overrides,+ };+}++function githubValues(overrides: Partial<LoopFormValues> = {}): LoopFormValues {+ return scheduleValues({+ triggers: [+ {+ key: "t1",+ type: "github",+ enabled: true,+ config: {+ github_integration_id: 7,+ repository: "example/app",+ events: ["pull_request"],+ filters: { actions: ["opened", "reopened"] },+ },+ },+ ],+ ...overrides,+ });+}++/** The flow the API would hand back after a write, so read mapping can be+ * checked against exactly what write mapping produced. */+function flowFromWrite(+ values: LoopFormValues,+ options: { enabled: boolean } = { enabled: true },+): LoopHogFlowSource {+ const { flow, schedule } = formValuesToHogFlowWrite(values, options);+ return {+ id: "flow-1",+ name: flow.name,+ description: flow.description,+ status: flow.status,+ created_at: "2026-09-01T08:00:00Z",+ updated_at: "2026-09-02T08:00:00Z",+ created_by: { id: 5 },+ actions: flow.actions,+ edges: flow.edges,+ schedules: schedule+ ? [+ {+ id: "sched-1",+ ...schedule,+ status: "active",+ next_run_at: null,+ created_at: "2026-09-01T08:00:00Z",+ updated_at: "2026-09-01T08:00:00Z",+ } satisfies Schemas.HogFlowSchedule,+ ]+ : [],+ };+}++function taskAction(flow: LoopHogFlowSource): Record<string, unknown> {+ const actions = flow.actions as Array<Record<string, unknown>>;+ return must(actions.find((action) => action.type === "function"));+}++describe("loopHogFlowMapping", () => {+ it("writes a schedule loop as trigger, create-task step and exit plus a schedule row", () => {+ const { flow, schedule } = formValuesToHogFlowWrite(scheduleValues(), {+ enabled: true,+ });+ expect(flow).toMatchObject({+ name: "Morning triage",+ description: "Look at overnight errors",+ status: "active",+ origin_product: "loops",+ exit_condition: "exit_only_at_end",+ });+ expect(flow.actions.map((action) => [action.id, action.type])).toEqual([+ ["trigger", "trigger"],+ ["create_task", "function"],+ ["exit", "exit"],+ ]);+ expect(flow.actions[0].config).toEqual({ type: "schedule" });+ expect(flow.actions[1].config).toEqual({+ template_id: "template-posthog-create-task",+ inputs: { prompt: { value: "Triage the error tracking inbox." } },+ });+ expect(flow.edges).toEqual([+ { from: "trigger", to: "create_task", type: "continue" },+ { from: "create_task", to: "exit", type: "continue" },+ ]);+ expect(schedule).toMatchObject({+ rrule: "FREQ=WEEKLY;INTERVAL=1;BYDAY=MO,TU,WE,TH,FR",+ timezone: "Europe/Lisbon",+ });+ });++ it("writes a paused loop as a draft", () => {+ expect(+ formValuesToHogFlowWrite(scheduleValues(), { enabled: false }).flow+ .status,+ ).toBe("draft");+ });++ it("writes a GitHub loop as an internal-event trigger with exact filters and no schedule", () => {+ const { flow, schedule } = formValuesToHogFlowWrite(githubValues(), {+ enabled: true,+ });+ expect(schedule).toBeNull();+ expect(flow.actions[0].config).toEqual({+ type: "internal-event",+ filters: {+ source: "internal-events",+ events: [{ id: "$github_event_received", type: "events" }],+ properties: [+ {+ key: "repository",+ value: ["example/app"],+ operator: "exact",+ type: "event",+ },+ {+ key: "event_type",+ value: ["pull_request"],+ operator: "exact",+ type: "event",+ },+ {+ key: "actor_access",+ value: ["write"],+ operator: "exact",+ type: "event",+ },+ {+ key: "action",+ value: ["opened", "reopened"],+ operator: "exact",+ type: "event",+ },+ ],+ },+ });+ });++ it("only writes the task inputs the form filled in", () => {+ const { flow } = formValuesToHogFlowWrite(+ scheduleValues({+ repositories: [{ github_integration_id: 7, full_name: "example/app" }],+ model: "claude-opus-5",+ reasoningEffort: "high",+ teamSkills: ["error-triage", "db-runbook"],+ }),+ { enabled: true },+ );+ expect(flow.actions[1].config).toMatchObject({+ inputs: {+ prompt: { value: "Triage the error tracking inbox." },+ repository: { value: "example/app" },+ model: { value: { model: "claude-opus-5", reasoning_effort: "high" } },+ skills: { value: ["error-triage", "db-runbook"] },+ },+ });+ });++ it.each([+ [+ "an API trigger",+ scheduleValues({+ triggers: [{ key: "t1", type: "api", enabled: true, config: {} }],+ }),+ ],+ [+ "a cron outside the presets",+ scheduleValues({+ triggers: [+ {+ key: "t1",+ type: "schedule",+ enabled: true,+ config: { cron_expression: "*/15 * * * *" },+ },+ ],+ }),+ ],+ [+ "two enabled triggers",+ scheduleValues({+ triggers: [+ ...scheduleValues().triggers,+ ...githubValues().triggers.map((trigger) => ({+ ...trigger,+ key: "t2",+ })),+ ],+ }),+ ],+ ])("refuses to write %s", (_label, values) => {+ expect(() => formValuesToHogFlowWrite(values, { enabled: true })).toThrow(+ UnsupportedLoopShapeError,+ );+ });++ it.each([+ ["schedule", scheduleValues()],+ ["GitHub", githubValues()],+ ])(+ "reads a %s loop back into the form values that wrote it",+ (_label, values) => {+ const flow = flowFromWrite(values);+ expect(isLoopShapedHogFlow(flow)).toBe(true);+ const loop = hogFlowToLoop(flow, { projectId: PROJECT_ID });+ expect(loop).toMatchObject({+ id: "flow-1",+ team_id: PROJECT_ID,+ created_by_id: 5,+ name: "Morning triage",+ enabled: true,+ visibility: "team",+ origin_product: "loops",+ });+ const trigger = values.triggers[0];+ expect(loopToFormValues(loop)).toEqual({+ ...values,+ name: "Morning triage",+ description: "Look at overnight errors",+ instructions: "Triage the error tracking inbox.",+ visibility: "team",+ triggers: [+ {+ key: "trigger",+ id: "trigger",+ type: trigger.type,+ enabled: true,+ config:+ trigger.type === "github"+ ? { ...trigger.config, github_integration_id: 0 }+ : trigger.config,+ },+ ],+ });+ },+ );++ it("reads a draft flow as a paused loop with its model and repository", () => {+ const flow = flowFromWrite(+ scheduleValues({+ repositories: [{ github_integration_id: 7, full_name: "example/app" }],+ model: "claude-opus-5",+ reasoningEffort: "high",+ teamSkills: ["error-triage"],+ }),+ { enabled: false },+ );+ const loop = hogFlowToLoop(flow, { projectId: PROJECT_ID });+ expect(loop.enabled).toBe(false);+ expect(loop.model).toBe("claude-opus-5");+ expect(loop.reasoning_effort).toBe("high");+ expect(loop.repositories).toEqual([+ { github_integration_id: 0, full_name: "example/app" },+ ]);+ expect(hogFlowTeamSkills(flow)).toEqual(["error-triage"]);+ });++ it("treats a list row without schedules as loop-shaped with an empty cadence", () => {+ const { schedules: _omitted, ...row } = flowFromWrite(scheduleValues());+ expect(isLoopShapedHogFlow(row)).toBe(true);+ expect(+ hogFlowToLoop(row, { projectId: PROJECT_ID }).triggers[0].config,+ ).toEqual({});+ });++ it.each([+ [+ "an extra step in the graph",+ (flow: LoopHogFlowSource) => {+ (flow.actions as unknown[]).splice(1, 0, {+ id: "wait",+ name: "Wait",+ type: "delay",+ config: { delay_duration: "1h" },+ });+ },+ ],+ [+ "a different function template",+ (flow: LoopHogFlowSource) => {+ (taskAction(flow).config as Record<string, unknown>).template_id =+ "template-slack";+ },+ ],+ [+ "a schedule rule the form cannot express",+ (flow: LoopHogFlowSource) => {+ must(flow.schedules)[0].rrule = "FREQ=DAILY;INTERVAL=2";+ },+ ],+ ])(+ "marks a schedule loop with %s as foreign but still maps its metadata",+ (_label, mutate) => {+ const flow = flowFromWrite(scheduleValues());+ mutate(flow);+ expect(isLoopShapedHogFlow(flow)).toBe(false);+ expect(hogFlowToLoop(flow, { projectId: PROJECT_ID })).toMatchObject({+ name: "Morning triage",+ enabled: true,+ triggers: [],+ });+ },+ );++ it.each([+ [+ "a specific-people filter added in the workflow editor",+ {+ key: "sender",+ value: ["octocat"],+ operator: "exact",+ type: "event",+ },+ ],+ [+ "a substring repository match",+ {+ key: "repository",+ value: "example",+ operator: "icontains",+ type: "event",+ },+ ],+ [+ "an event type loops do not offer",+ {+ key: "event_type",+ value: ["pull_request_review"],+ operator: "exact",+ type: "event",+ },+ ],+ [+ "two event types",+ {+ key: "event_type",+ value: ["pull_request", "issues"],+ operator: "exact",+ type: "event",+ },+ ],+ ])("marks a GitHub loop with %s as foreign", (_label, property) => {+ const flow = flowFromWrite(githubValues());+ const trigger = (flow.actions as Array<Record<string, unknown>>)[0];+ const filters = (trigger.config as Record<string, unknown>).filters as {+ properties: Record<string, unknown>[];+ };+ filters.properties = [+ ...filters.properties.filter((existing) => existing.key !== property.key),+ property,+ ];+ expect(isLoopShapedHogFlow(flow)).toBe(false);+ });++ it.each([+ [+ "a running task",+ { status: "in_progress" },+ { status: "in_progress", completed_at: null },+ ],+ [+ "a legacy started status",+ { status: "started" },+ { status: "in_progress", completed_at: null },+ ],+ [+ "a finished task with no completion time",+ { status: "completed", environment: "local" },+ {+ status: "completed",+ environment: "local",+ completed_at: "2026-09-02T09:05:00Z",+ },+ ],+ [+ "a finished task with its own completion time",+ { status: "completed", completed_at: "2026-09-02T09:04:00Z" },+ { status: "completed", completed_at: "2026-09-02T09:04:00Z" },+ ],+ ])("maps %s to a loop run", (_label, run, expected) => {+ const task = {+ id: "task-1",+ created_at: "2026-09-02T09:00:00Z",+ latest_run: {+ id: "run-1",+ task: "task-1",+ environment: "cloud",+ branch: "loop/run-1",+ error_message: null,+ output: null,+ created_at: "2026-09-02T09:00:30Z",+ updated_at: "2026-09-02T09:05:00Z",+ ...run,+ },+ } as unknown as Schemas.TaskDetailDTO;+ expect(taskToLoopRun(task)).toMatchObject({+ id: "run-1",+ task_id: "task-1",+ loop_trigger_id: null,+ environment: "cloud",+ branch: "loop/run-1",+ created_at: "2026-09-02T09:00:30Z",+ ...expected,+ });+ });++ it("lists a task with no run yet as not started", () => {+ const task = {+ id: "task-1",+ created_at: "2026-09-02T09:00:00Z",+ latest_run: null,+ } as unknown as Schemas.TaskDetailDTO;+ expect(taskToLoopRun(task)).toMatchObject({+ id: "task-1",+ task_id: "task-1",+ status: "not_started",+ created_at: "2026-09-02T09:00:00Z",+ completed_at: null,+ });+ });++ it("marks a GitHub loop open to anyone as foreign", () => {+ const flow = flowFromWrite(githubValues());+ const trigger = (flow.actions as Array<Record<string, unknown>>)[0];+ const filters = (trigger.config as Record<string, unknown>).filters as {+ properties: Record<string, unknown>[];+ };+ filters.properties = filters.properties.filter(+ (property) => property.key !== "actor_access",+ );+ expect(isLoopShapedHogFlow(flow)).toBe(false);+ });++ it("marks a graph with an extra edge as foreign", () => {+ const flow = flowFromWrite(scheduleValues());+ (flow.edges as unknown[]).push({+ from: "trigger",+ to: "exit",+ type: "continue",+ });+ expect(isLoopShapedHogFlow(flow)).toBe(false);+ });++ it("marks a flow with a staged draft as foreign until it is published or discarded", () => {+ const flow = flowFromWrite(scheduleValues());+ expect(isLoopShapedHogFlow({ ...flow, draft: null })).toBe(true);+ expect(+ isLoopShapedHogFlow({+ ...flow,+ draft: { actions: flow.actions, edges: flow.edges },+ draft_updated_at: "2026-09-02T09:00:00Z",+ }),+ ).toBe(false);+ });++ it("keeps step settings the form does not own when rewriting an existing flow", () => {+ const existing = flowFromWrite(scheduleValues());+ const actions = existing.actions as Array<Record<string, unknown>>;+ Object.assign(taskAction(existing), {+ name: "Open a triage task",+ description: "Skips weekends",+ on_error: "continue",+ filters: { properties: [{ key: "weekday", value: "1", type: "event" }] },+ });+ actions[0].name = "Every weekday morning";++ const { flow } = formValuesToHogFlowWrite(+ scheduleValues({ instructions: "Updated prompt" }),+ { enabled: true, existing },+ );+ expect(flow.actions[0]).toMatchObject({+ id: "trigger",+ name: "Every weekday morning",+ config: { type: "schedule" },+ });+ expect(flow.actions[1]).toMatchObject({+ id: "create_task",+ name: "Open a triage task",+ description: "Skips weekends",+ on_error: "continue",+ filters: { properties: [{ key: "weekday", value: "1", type: "event" }] },+ config: {+ template_id: "template-posthog-create-task",+ inputs: { prompt: { value: "Updated prompt" } },+ },+ });+ expect(flow.actions[2]).toEqual(actions[2]);+ });++ it("keeps task inputs the form does not manage when rewriting an existing flow", () => {+ const existing = flowFromWrite(+ scheduleValues({+ repositories: [{ github_integration_id: 7, full_name: "example/app" }],+ }),+ );+ const inputs = taskAction(existing).config as {+ inputs: Record<string, unknown>;+ };+ inputs.inputs.max_parallel_tasks = { value: 2 };+ inputs.inputs.title = { value: "Triage" };++ const { flow } = formValuesToHogFlowWrite(+ scheduleValues({ instructions: "Updated prompt", repositories: [] }),+ { enabled: true, existing },+ );+ expect(flow.actions[1].config).toMatchObject({+ inputs: {+ prompt: { value: "Updated prompt" },+ max_parallel_tasks: { value: 2 },+ title: { value: "Triage" },+ },+ });+ expect(+ (flow.actions[1].config as { inputs: object }).inputs,+ ).not.toHaveProperty("repository");+ });+});diff --git a/products/desktop/packages/ui/src/features/loops/loopHogFlowMapping.ts b/products/desktop/packages/ui/src/features/loops/loopHogFlowMapping.tsnew file mode 100644index 000000000000..74e1a9c7533f--- /dev/null+++ b/products/desktop/packages/ui/src/features/loops/loopHogFlowMapping.ts@@ -0,0 +1,559 @@+import type { Schemas } from "@posthog/api-client/generated";+import {+ type HogFlowLoopBody,+ type HogFlowScheduleWrite,+ LOOPS_ORIGIN_PRODUCT,+} from "@posthog/api-client/hogFlowLoops";+import type { LoopSchemas } from "@posthog/api-client/loops";+import { defaultLoopBehaviors, type LoopFormValues } from "./loopFormTypes";+import {+ hogFlowScheduleToScheduleConfig,+ scheduleConfigToHogFlowSchedule,+} from "./loopScheduleRRule";++export const CREATE_TASK_TEMPLATE_ID = "template-posthog-create-task";+const GITHUB_EVENT_RECEIVED_EVENT = "$github_event_received";++const TRIGGER_ACTION_ID = "trigger";+const TASK_ACTION_ID = "create_task";+const EXIT_ACTION_ID = "exit";++const LOOP_GITHUB_EVENTS: ReadonlySet<string> =+ new Set<LoopSchemas.LoopGithubTriggerEventEnum>([+ "issues",+ "issue_comment",+ "pull_request",+ "push",+ ]);++/** Thrown when the form holds a trigger the workflow shape cannot carry. The+ * form's own validation stops this before submit; the error is the backstop. */+export class UnsupportedLoopShapeError extends Error {+ constructor(message: string) {+ super(message);+ this.name = "UnsupportedLoopShapeError";+ }+}++export interface LoopHogFlowWrite {+ flow: HogFlowLoopBody;+ /** Null for a GitHub-triggered loop, which has no schedule row. */+ schedule: HogFlowScheduleWrite | null;+}++/** The fields the mapper reads. Both the list row (`HogFlowMinimal`) and the+ * detail (`HogFlow`) satisfy it; only the detail carries `schedules`. */+export interface LoopHogFlowSource {+ id: string;+ name?: string | null;+ description?: string;+ status?: Schemas.HogFlowStateEnum;+ created_at: string;+ updated_at: string;+ created_by?: { id: number } | null;+ actions?: unknown;+ edges?: unknown;+ schedules?: Schemas.HogFlowSchedule[];+ /** Staged edits the workflow editor holds back from the live graph. Only+ * the detail carries it; a list row leaves it undefined. */+ draft?: unknown;+ draft_updated_at?: string | null;+}++/** Task inputs the form owns. Anything else on the step is left as found. */+const MANAGED_TASK_INPUTS: ReadonlySet<string> = new Set([+ "prompt",+ "repository",+ "model",+ "skills",+]);++type Json = Record<string, unknown>;++function isRecord(value: unknown): value is Json {+ return typeof value === "object" && value !== null && !Array.isArray(value);+}++function inputValue(inputs: Json, key: string): unknown {+ const input = inputs[key];+ return isRecord(input) ? input.value : undefined;+}++function exactFilter(key: string, value: string[]): Json {+ return { key, value, operator: "exact", type: "event" };+}++function githubTriggerConfig(+ config: LoopSchemas.LoopGithubTriggerConfig,+): Json {+ // Only people with write access can start a run: the event body reaches an+ // AI task that acts with the owner's access, so a drive-by issue or comment+ // must not be able to steer it. Same gate the loops webhook applied.+ const properties = [+ exactFilter("repository", [config.repository]),+ exactFilter("event_type", config.events),+ exactFilter("actor_access", ["write"]),+ ];+ const actions = config.filters?.actions ?? [];+ if (actions.length > 0) {+ properties.push(exactFilter("action", actions));+ }+ return {+ type: "internal-event",+ filters: {+ source: "internal-events",+ events: [{ id: GITHUB_EVENT_RECEIVED_EVENT, type: "events" }],+ properties,+ },+ };+}++function triggerFromForm(values: LoopFormValues): {+ config: Json;+ schedule: HogFlowScheduleWrite | null;+} {+ const enabledTriggers = values.triggers.filter((trigger) => trigger.enabled);+ if (enabledTriggers.length !== 1) {+ throw new UnsupportedLoopShapeError(+ "A workflow-backed loop has exactly one trigger.",+ );+ }+ const trigger = enabledTriggers[0];+ if (trigger.type === "schedule") {+ const schedule = scheduleConfigToHogFlowSchedule(+ trigger.config as LoopSchemas.LoopScheduleTriggerConfig,+ );+ if (!schedule) {+ throw new UnsupportedLoopShapeError(+ "This schedule is not one of the supported presets.",+ );+ }+ return { config: { type: "schedule" }, schedule };+ }+ if (trigger.type === "github") {+ const config = trigger.config as LoopSchemas.LoopGithubTriggerConfig;+ return { config: githubTriggerConfig(config), schedule: null };+ }+ throw new UnsupportedLoopShapeError(+ `Trigger type "${trigger.type}" is not supported for workflow-backed loops.`,+ );+}++function taskInputs(values: LoopFormValues): Json {+ const inputs: Json = { prompt: { value: values.instructions.trim() } };+ const repository = values.repositories[0]?.full_name;+ if (repository) {+ inputs.repository = { value: repository };+ }+ const model = values.model.trim();+ if (model) {+ inputs.model = {+ value: {+ model,+ ...(values.reasoningEffort+ ? { reasoning_effort: values.reasoningEffort }+ : {}),+ },+ };+ }+ if (values.teamSkills.length > 0) {+ inputs.skills = { value: [...values.teamSkills] };+ }+ return inputs;+}++/** Task inputs on an existing flow that the form does not manage, so a save+ * keeps what the workflow editor added (connectors, parallelism, a title). */+function preservedTaskInputs(existing: ParsedLoopActions | null): Json {+ if (!existing) return {};+ return Object.fromEntries(+ Object.entries(existing.taskInputs).filter(+ ([key]) => !MANAGED_TASK_INPUTS.has(key),+ ),+ );+}++/** One of the three steps the loop form draws, as the API holds it. */+interface LoopAction extends Schemas.HogFlowAction {+ type: "trigger" | "function" | "exit";+ config: Json;+}++function isLoopAction(value: unknown): value is LoopAction {+ return (+ isRecord(value) &&+ typeof value.id === "string" &&+ typeof value.name === "string" &&+ isRecord(value.config) &&+ (value.type === "trigger" ||+ value.type === "function" ||+ value.type === "exit")+ );+}++const DEFAULT_TRIGGER_ACTION: LoopAction = {+ id: TRIGGER_ACTION_ID,+ name: "Trigger",+ type: "trigger",+ config: {},+};++const DEFAULT_TASK_ACTION: LoopAction = {+ id: TASK_ACTION_ID,+ name: "Create AI task",+ type: "function",+ config: {},+};++const DEFAULT_EXIT_ACTION: LoopAction = {+ id: EXIT_ACTION_ID,+ name: "Exit",+ type: "exit",+ config: { reason: "Task created" },+};++/**+ * The workflow a loop form saves as: one trigger, one "Create AI task" step,+ * one exit. `enabled` decides whether the flow is created live or as a draft.+ * Pass `existing` on an edit: the save then only replaces the fields the form+ * owns (the trigger config, the task template and inputs), so step names,+ * skip filters and error handling set in the workflow editor survive.+ */+export function formValuesToHogFlowWrite(+ values: LoopFormValues,+ options: { enabled: boolean; existing?: LoopHogFlowSource },+): LoopHogFlowWrite {+ const trigger = triggerFromForm(values);+ const existing = options.existing+ ? parseLoopActions(options.existing.actions)+ : null;+ const triggerAction = existing?.actions.trigger ?? DEFAULT_TRIGGER_ACTION;+ const taskAction = existing?.actions.task ?? DEFAULT_TASK_ACTION;+ const exitAction = existing?.actions.exit ?? DEFAULT_EXIT_ACTION;+ return {+ flow: {+ name: values.name.trim(),+ description: values.description.trim(),+ status: options.enabled ? "active" : "draft",+ origin_product: LOOPS_ORIGIN_PRODUCT,+ exit_condition: "exit_only_at_end",+ actions: [+ { ...triggerAction, config: trigger.config },+ {+ ...taskAction,+ config: {+ ...taskAction.config,+ template_id: CREATE_TASK_TEMPLATE_ID,+ inputs: {+ ...preservedTaskInputs(existing),+ ...taskInputs(values),+ },+ },+ },+ exitAction,+ ],+ edges: [+ { from: triggerAction.id, to: taskAction.id, type: "continue" },+ { from: taskAction.id, to: exitAction.id, type: "continue" },+ ],+ },+ schedule: trigger.schedule,+ };+}++interface ParsedLoopActions {+ trigger: Json;+ taskInputs: Json;+ actions: { trigger: LoopAction; task: LoopAction; exit: LoopAction | null };+}++/** The trigger and task step of a loop-shaped graph, or null when the graph+ * holds anything the loop form did not put there. */+function parseLoopActions(actions: unknown): ParsedLoopActions | null {+ if (!Array.isArray(actions)) return null;+ let trigger: LoopAction | null = null;+ let task: LoopAction | null = null;+ let exit: LoopAction | null = null;+ for (const action of actions) {+ if (!isLoopAction(action)) return null;+ if (action.type === "trigger") {+ if (trigger) return null;+ trigger = action;+ } else if (action.type === "function") {+ if (task || action.config.template_id !== CREATE_TASK_TEMPLATE_ID) {+ return null;+ }+ task = action;+ } else {+ if (exit) return null;+ exit = action;+ }+ }+ if (!trigger || !task) return null;+ return {+ trigger: trigger.config,+ taskInputs: isRecord(task.config.inputs) ? task.config.inputs : {},+ actions: { trigger, task, exit },+ };+}++/** Whether the edges are exactly the straight line the form draws:+ * trigger to task, then task to exit. A branch or a loop back would be lost+ * when a save rewrites the edges. */+function hasLoopShapedEdges(+ edges: unknown,+ actions: ParsedLoopActions["actions"],+): boolean {+ if (edges === undefined || edges === null) return true;+ if (!Array.isArray(edges)) return false;+ const ids = {+ trigger: actions.trigger.id,+ task: actions.task.id,+ exit: actions.exit?.id ?? null,+ };+ const expected = [+ `${ids.trigger}>${ids.task}`,+ ...(ids.exit ? [`${ids.task}>${ids.exit}`] : []),+ ];+ const actual = edges.map((edge) =>+ isRecord(edge) && edge.type === "continue"+ ? `${edge.from}>${edge.to}`+ : "?",+ );+ return (+ actual.length === expected.length &&+ expected.every((edge) => actual.includes(edge))+ );+}++function filterValues(filter: Json): string[] | null {+ if (filter.operator !== "exact") return null;+ const raw = Array.isArray(filter.value) ? filter.value : [filter.value];+ if (!raw.every((value): value is string => typeof value === "string")) {+ return null;+ }+ return raw;+}++function githubConfigFromTrigger(+ trigger: Json,+): LoopSchemas.LoopGithubTriggerConfig | null {+ if (!isRecord(trigger.filters)) return null;+ const { events, properties } = trigger.filters;+ const subscribed =+ Array.isArray(events) &&+ events.length === 1 &&+ isRecord(events[0]) &&+ events[0].id === GITHUB_EVENT_RECEIVED_EVENT;+ if (!subscribed) return null;++ let repository: string | null = null;+ let eventTypes: string[] | null = null;+ let actions: string[] = [];+ let trustedActorsOnly = false;+ for (const property of Array.isArray(properties) ? properties : []) {+ if (!isRecord(property)) return null;+ const values = filterValues(property);+ if (!values) return null;+ switch (property.key) {+ case "actor_access":+ if (values.length !== 1 || values[0] !== "write") return null;+ trustedActorsOnly = true;+ break;+ case "repository":+ if (values.length !== 1) return null;+ repository = values[0];+ break;+ case "event_type":+ if (!values.every((value) => LOOP_GITHUB_EVENTS.has(value))) {+ return null;+ }+ eventTypes = values;+ break;+ case "action":+ actions = values;+ break;+ default:+ return null;+ }+ }+ // The form picks one event type; two would open as an invalid form.+ if (!repository || !eventTypes || eventTypes.length !== 1) return null;+ // A trigger open to anyone is outside what a loop offers; editing it here+ // would silently narrow it back to write access.+ if (!trustedActorsOnly) return null;+ return {+ github_integration_id: 0,+ repository,+ events: eventTypes as LoopSchemas.LoopGithubTriggerEventEnum[],+ ...(actions.length > 0 ? { filters: { actions } } : {}),+ };+}++function scheduleConfigFromFlow(+ schedules: Schemas.HogFlowSchedule[] | undefined,+): LoopSchemas.LoopScheduleTriggerConfig | null {+ // The list endpoint omits schedules; rows never render a cadence, so an+ // empty config is right there and only the detail decides the shape.+ const schedule = schedules?.[0];+ if (!schedule) return {};+ return hogFlowScheduleToScheduleConfig(schedule);+}++function loopTrigger(+ flow: LoopHogFlowSource,+ parsed: ParsedLoopActions,+): LoopSchemas.LoopTrigger | null {+ let type: LoopSchemas.LoopTriggerTypeEnum;+ let config: LoopSchemas.LoopTriggerConfig | null;+ if (parsed.trigger.type === "schedule") {+ type = "schedule";+ config = scheduleConfigFromFlow(flow.schedules);+ } else if (parsed.trigger.type === "internal-event") {+ type = "github";+ config = githubConfigFromTrigger(parsed.trigger);+ } else {+ return null;+ }+ if (!config) return null;+ return {+ id: TRIGGER_ACTION_ID,+ loop_id: flow.id,+ type,+ enabled: true,+ config,+ schedule_sync_status: null,+ last_fired_at: null,+ created_at: flow.created_at,+ updated_at: flow.updated_at,+ };+}++function readString(value: unknown): string {+ return typeof value === "string" ? value : "";+}++/** Team skill names the loop's task step attaches; empty for a foreign flow. */+export function hogFlowTeamSkills(flow: LoopHogFlowSource): string[] {+ const parsed = parseLoopActions(flow.actions);+ const skills = parsed ? inputValue(parsed.taskInputs, "skills") : undefined;+ return Array.isArray(skills)+ ? skills.filter((skill): skill is string => typeof skill === "string")+ : [];+}++/** Whether the form can edit this flow without dropping something a person+ * built elsewhere. A save writes the whole graph, so anything the form does+ * not model would be lost. */+export function isLoopShapedHogFlow(flow: LoopHogFlowSource): boolean {+ // A staged draft is edited work the live graph does not show; a save from+ // here would land underneath it and the next publish would overwrite it.+ if (flow.draft !== undefined && flow.draft !== null) return false;+ const parsed = parseLoopActions(flow.actions);+ return (+ parsed !== null &&+ hasLoopShapedEdges(flow.edges, parsed.actions) &&+ loopTrigger(flow, parsed) !== null+ );+}++/**+ * Projects a workflow onto the loop shape the list and detail views render. A+ * flow the form did not build still maps (name, status, dates) with no+ * triggers or instructions, so the detail view can show it read-only.+ */+export function hogFlowToLoop(+ flow: LoopHogFlowSource,+ context: { projectId: number },+): LoopSchemas.Loop {+ const parsed = parseLoopActions(flow.actions);+ const trigger = parsed ? loopTrigger(flow, parsed) : null;+ const inputs = parsed?.taskInputs ?? {};+ const model = inputValue(inputs, "model");+ const repository = readString(inputValue(inputs, "repository"));+ const reasoningEffort = isRecord(model)+ ? readString(model.reasoning_effort)+ : "";+ const off = { enabled: false, events: [], params: {} };+ return {+ id: flow.id,+ team_id: context.projectId,+ created_by_id: flow.created_by?.id ?? null,+ name: flow.name ?? "",+ description: flow.description ?? "",+ visibility: "team",+ instructions: readString(inputValue(inputs, "prompt")),+ runtime_adapter: "claude",+ model: isRecord(model) ? readString(model.model) : "",+ reasoning_effort: reasoningEffort+ ? (reasoningEffort as LoopSchemas.LoopReasoningEffortEnum)+ : null,+ repositories: repository+ ? [{ github_integration_id: 0, full_name: repository }]+ : [],+ sandbox_environment_id: null,+ enabled: flow.status === "active",+ disabled_reason: null,+ overlap_policy: "skip",+ behaviors: defaultLoopBehaviors(),+ connectors: { mcp_installation_ids: [], posthog_mcp_scopes: "read_only" },+ notifications: { push: { ...off }, email: { ...off }, slack: { ...off } },+ context_target: null,+ internal: false,+ origin_product: LOOPS_ORIGIN_PRODUCT,+ last_run_at: null,+ last_run_status: null,+ last_error: null,+ consecutive_failures: 0,+ created_at: flow.created_at,+ updated_at: flow.updated_at,+ triggers: trigger ? [trigger] : [],+ skill_bundles: [],+ };+}++const TERMINAL_RUN_STATUSES: ReadonlySet<LoopSchemas.LoopRunStatusEnum> =+ new Set(["completed", "failed", "cancelled"]);++function loopRunStatus(status: unknown): LoopSchemas.LoopRunStatusEnum {+ switch (status) {+ case "started":+ return "in_progress";+ case "queued":+ case "in_progress":+ case "completed":+ case "failed":+ case "cancelled":+ return status;+ default:+ return "not_started";+ }+}++/**+ * A task the workflow created, shown as one loop run. A task with no run yet+ * still lists (as not started) so a fire that queued a task is visible before+ * the sandbox picks it up.+ */+export function taskToLoopRun(+ task: Schemas.TaskDetailDTO,+): LoopSchemas.LoopRun {+ const run = task.latest_run ?? null;+ const status = loopRunStatus(run?.status);+ const createdAt = run?.created_at ?? task.created_at ?? "";+ return {+ id: run?.id ?? task.id,+ task_id: task.id,+ loop_trigger_id: null,+ status,+ environment: run?.environment === "local" ? "local" : "cloud",+ branch: run?.branch ?? null,+ error_message: run?.error_message ?? null,+ output: run?.output ?? null,+ created_at: createdAt,+ completed_at:+ run && TERMINAL_RUN_STATUSES.has(status)+ ? (run.completed_at ?? run.updated_at ?? null)+ : null,+ };+}diff --git a/products/desktop/packages/ui/src/features/loops/loopHogFlowWrites.test.ts b/products/desktop/packages/ui/src/features/loops/loopHogFlowWrites.test.tsnew file mode 100644index 000000000000..6c0e7b42b6dd--- /dev/null+++ b/products/desktop/packages/ui/src/features/loops/loopHogFlowWrites.test.ts@@ -0,0 +1,272 @@+import { ApiRequestError } from "@posthog/api-client/fetcher";+import {+ type ApiClient,+ createApiClient,+ type Fetcher,+} from "@posthog/api-client/generated";+import { describe, expect, it, vi } from "vitest";+import { emptyLoopFormValues } from "./loopFormTypes";+import {+ formValuesToHogFlowWrite,+ type LoopHogFlowSource,+ type LoopHogFlowWrite,+} from "./loopHogFlowMapping";+import {+ createLoopHogFlow,+ LoopForeignWorkflowError,+ LoopScheduleSaveError,+ updateLoopHogFlow,+} from "./loopHogFlowWrites";++type Route = { method: string; path: string };++/** A client whose responses are scripted per method+path, recording the+ * order of requests so a sequence can be asserted. */+function scriptedClient(+ responder: (route: Route) => { status: number; body?: unknown },+): { client: ApiClient; calls: Route[] } {+ const calls: Route[] = [];+ const fetchMock = vi.fn(async (request: { method: string; url: URL }) => {+ const route = { method: request.method, path: request.url.pathname };+ calls.push(route);+ const { status, body } = responder(route);+ if (status >= 400) {+ throw new ApiRequestError(status, JSON.stringify(body ?? {}), body);+ }+ return {+ ok: true,+ status,+ headers: { get: () => "application/json" },+ json: () => Promise.resolve(body ?? {}),+ };+ });+ const fetcher: Fetcher = {+ fetch: fetchMock as unknown as Fetcher["fetch"],+ };+ return { client: createApiClient(fetcher, "https://us.posthog.com"), calls };+}++const FLOW = { id: "flow-1", status: "active", schedules: [] };+const BASE_UPDATED_AT = "2026-09-02T08:00:00Z";+const SCHEDULE_ROW = {+ id: "sched-1",+ rrule: "FREQ=DAILY;INTERVAL=1",+ starts_at: "2026-01-01T09:00:00Z",+ timezone: "UTC",+ status: "active",+ next_run_at: null,+ created_at: "",+ updated_at: "",+} as const;++/** The workflow a save is based on: the graph the form itself wrote, plus+ * whichever schedule rows the case starts from. */+function existingFlow(+ write: LoopHogFlowWrite,+ schedules: LoopHogFlowSource["schedules"] = [],+): LoopHogFlowSource {+ return {+ id: "flow-1",+ created_at: BASE_UPDATED_AT,+ updated_at: BASE_UPDATED_AT,+ actions: write.flow.actions,+ edges: write.flow.edges,+ schedules,+ };+}++function scheduleWrite(cron = "0 9 * * *") {+ return formValuesToHogFlowWrite(+ {+ ...emptyLoopFormValues(),+ name: "Loop",+ instructions: "Do the thing",+ triggers: [+ {+ key: "t",+ type: "schedule",+ enabled: true,+ config: { cron_expression: cron, timezone: "UTC" },+ },+ ],+ },+ { enabled: true },+ );+}++function githubWrite() {+ return formValuesToHogFlowWrite(+ {+ ...emptyLoopFormValues(),+ name: "Loop",+ instructions: "Do the thing",+ triggers: [+ {+ key: "t",+ type: "github",+ enabled: true,+ config: {+ github_integration_id: 1,+ repository: "example/app",+ events: ["push"],+ },+ },+ ],+ },+ { enabled: true },+ );+}++describe("loopHogFlowWrites", () => {+ it("deletes the new workflow again when its schedule is rejected", async () => {+ const { client, calls } = scriptedClient(({ method, path }) => {+ if (method === "post" && path.endsWith("/schedules/")) {+ return { status: 400, body: { rrule: ["Invalid RRULE."] } };+ }+ return { status: 200, body: FLOW };+ });+ await expect(+ createLoopHogFlow(client, "7", scheduleWrite()),+ ).rejects.toThrow(ApiRequestError);+ expect(calls.map((call) => `${call.method} ${call.path}`)).toEqual([+ "post /api/projects/7/hog_flows/",+ "post /api/projects/7/hog_flows/flow-1/schedules/",+ "delete /api/projects/7/hog_flows/flow-1/",+ ]);+ });++ it("returns the new workflow with its schedule attached", async () => {+ const { client } = scriptedClient(({ method, path }) =>+ method === "post" && path.endsWith("/schedules/")+ ? { status: 200, body: SCHEDULE_ROW }+ : { status: 200, body: FLOW },+ );+ const flow = await createLoopHogFlow(client, "7", scheduleWrite());+ expect(flow.schedules).toEqual([SCHEDULE_ROW]);+ });++ it.each([+ {+ label: "leaves a matching schedule alone",+ write: scheduleWrite("0 9 * * *"),+ existing: [SCHEDULE_ROW],+ expected: ["patch /api/projects/7/hog_flows/flow-1/"],+ },+ {+ label: "updates the schedule in place when the cadence changes",+ write: scheduleWrite("0 17 * * *"),+ existing: [SCHEDULE_ROW],+ expected: [+ "patch /api/projects/7/hog_flows/flow-1/",+ "patch /api/projects/7/hog_flows/flow-1/schedules/sched-1/",+ ],+ },+ {+ label: "creates a schedule for a loop that lost its row",+ write: scheduleWrite(),+ existing: [],+ expected: [+ "patch /api/projects/7/hog_flows/flow-1/",+ "post /api/projects/7/hog_flows/flow-1/schedules/",+ ],+ },+ {+ label: "removes the schedule when the trigger becomes a GitHub event",+ write: githubWrite(),+ existing: [SCHEDULE_ROW],+ expected: [+ "patch /api/projects/7/hog_flows/flow-1/",+ "delete /api/projects/7/hog_flows/flow-1/schedules/sched-1/",+ ],+ },+ ])("$label", async ({ write, existing, expected }) => {+ const { client, calls } = scriptedClient(() => ({+ status: 200,+ body: { ...FLOW, schedules: existing },+ }));+ await updateLoopHogFlow(+ client,+ "7",+ existingFlow(write, [...existing]),+ write,+ );+ expect(calls.map((call) => `${call.method} ${call.path}`)).toEqual(+ expected,+ );+ });++ it("refuses to write over a workflow the form did not shape", async () => {+ const { client, calls } = scriptedClient(() => ({+ status: 200,+ body: FLOW,+ }));+ const write = scheduleWrite();+ await expect(+ updateLoopHogFlow(+ client,+ "7",+ { ...existingFlow(write), actions: [], edges: [] },+ write,+ ),+ ).rejects.toBeInstanceOf(LoopForeignWorkflowError);+ expect(calls).toEqual([]);+ });++ it("does not send status or the origin tag with an edit", async () => {+ let patched: Record<string, unknown> | undefined;+ const fetchMock = vi.fn(+ async (request: { parameters?: { body?: Record<string, unknown> } }) => {+ patched = request.parameters?.body;+ return {+ ok: true,+ status: 200,+ headers: { get: () => "application/json" },+ json: () => Promise.resolve({ ...FLOW, schedules: [SCHEDULE_ROW] }),+ };+ },+ );+ const client = createApiClient(+ { fetch: fetchMock as unknown as Fetcher["fetch"] },+ "https://us.posthog.com",+ );+ const write = scheduleWrite();+ await updateLoopHogFlow(+ client,+ "7",+ existingFlow(write, [SCHEDULE_ROW]),+ write,+ );+ const keys = Object.keys(patched ?? {});+ expect(keys).toContain("actions");+ expect(keys).not.toContain("status");+ expect(keys).not.toContain("origin_product");+ expect(keys).not.toContain("exit_condition");+ expect(patched?.actions).toHaveLength(3);+ expect(patched?.base_updated_at).toBe(BASE_UPDATED_AT);+ });++ it("reports a schedule that failed after the graph saved as its own error", async () => {+ const { client, calls } = scriptedClient(({ method, path }) =>+ method === "patch" && path.includes("/schedules/")+ ? { status: 400, body: { rrule: ["Invalid RRULE."] } }+ : { status: 200, body: { ...FLOW, schedules: [SCHEDULE_ROW] } },+ );+ const write = scheduleWrite("0 17 * * *");+ const error = await updateLoopHogFlow(+ client,+ "7",+ existingFlow(write, [SCHEDULE_ROW]),+ write,+ ).catch((thrown: unknown) => thrown);+ expect(error).toBeInstanceOf(LoopScheduleSaveError);+ // The patched graph rides on the error so the form can rebase on it.+ expect((error as LoopScheduleSaveError).flow).toEqual({+ ...FLOW,+ schedules: [SCHEDULE_ROW],+ });+ expect(calls.map((call) => `${call.method} ${call.path}`)).toEqual([+ "patch /api/projects/7/hog_flows/flow-1/",+ "patch /api/projects/7/hog_flows/flow-1/schedules/sched-1/",+ ]);+ });+});diff --git a/products/desktop/packages/ui/src/features/loops/loopHogFlowWrites.ts b/products/desktop/packages/ui/src/features/loops/loopHogFlowWrites.tsnew file mode 100644index 000000000000..8d0d6ca8e0a0--- /dev/null+++ b/products/desktop/packages/ui/src/features/loops/loopHogFlowWrites.ts@@ -0,0 +1,179 @@+import type { ApiClient, Schemas } from "@posthog/api-client/generated";+import {+ createHogFlow,+ createHogFlowSchedule,+ deleteHogFlow,+ deleteHogFlowSchedule,+ patchHogFlow,+ runHogFlow,+ updateHogFlowSchedule,+} from "@posthog/api-client/hogFlowLoops";+import type { LoopSchemas } from "@posthog/api-client/loops";+import {+ isLoopShapedHogFlow,+ type LoopHogFlowSource,+ type LoopHogFlowWrite,+} from "./loopHogFlowMapping";+import { hogFlowScheduleMatches } from "./loopScheduleRRule";++/** The graph saved but the schedule row did not follow. The loop is live with+ * its old cadence (or none), so the person has to save again. `flow` is the+ * workflow as the server returned it from the graph write. */+export class LoopScheduleSaveError extends Error {+ readonly cause: unknown;+ readonly flow: Schemas.HogFlow;++ constructor(cause: unknown, flow: Schemas.HogFlow) {+ super("Loop saved, but its schedule didn't update.");+ this.name = "LoopScheduleSaveError";+ this.cause = cause;+ this.flow = flow;+ }+}++/** The workflow no longer has the shape the form writes. A save would replace+ * steps or triggers someone built in the workflow editor, so nothing is sent. */+export class LoopForeignWorkflowError extends Error {+ constructor() {+ super(+ "This loop was changed in the workflow editor. Open it in PostHog to change it.",+ );+ this.name = "LoopForeignWorkflowError";+ }+}++/**+ * The request sequences behind saving a workflow-backed loop. A loop is a+ * workflow plus, for a schedule trigger, one schedule row; these keep the two+ * consistent when the second request fails.+ */++/**+ * Creates the workflow, then its schedule. If the schedule is rejected the+ * workflow is deleted again, so a failed save leaves nothing behind. Until the+ * schedule exists the workflow is inert: the scheduler only fires flows with an+ * active schedule row.+ */+export async function createLoopHogFlow(+ client: ApiClient,+ projectId: string,+ write: LoopHogFlowWrite,+): Promise<Schemas.HogFlow> {+ const flow = await createHogFlow(client, projectId, write.flow);+ if (!write.schedule) return flow;+ try {+ const schedule = await createHogFlowSchedule(+ client,+ projectId,+ flow.id,+ write.schedule,+ );+ return { ...flow, schedules: [schedule] };+ } catch (error) {+ try {+ await deleteHogFlow(client, projectId, flow.id);+ } catch {+ // The schedule rejection is the error worth reporting. A failed rollback+ // leaves an inert draft-like flow the person can delete from the list.+ }+ throw error;+ }+}++/**+ * Writes the graph, then reconciles the schedule row. The row is left alone+ * when it already matches: rewriting it re-anchors `starts_at`, which makes+ * the scheduler recompute `next_run_at` and can skip an occurrence about to+ * fire. Switching a loop to a GitHub trigger removes the old schedule, so the+ * workflow does not keep firing on the cadence it no longer shows.+ */+export async function updateLoopHogFlow(+ client: ApiClient,+ projectId: string,+ existing: LoopHogFlowSource,+ write: LoopHogFlowWrite,+): Promise<Schemas.HogFlow> {+ // Every caller's render-time guard can be stale by the time the save runs,+ // so the shape is rechecked against the flow the write is based on.+ if (!isLoopShapedHogFlow(existing)) {+ throw new LoopForeignWorkflowError();+ }+ // Status is owned by the enable toggle, the origin tag is immutable after+ // create, and the exit condition may have been changed in the workflow+ // editor, so none of them travel with an edit.+ const {+ status: _status,+ origin_product: _origin,+ exit_condition: _exit,+ ...content+ } = write.flow;+ const flow = await patchHogFlow(client, projectId, existing.id, {+ ...content,+ base_updated_at: existing.updated_at,+ });+ try {+ return await reconcileSchedule(client, projectId, existing, flow, write);+ } catch (error) {+ throw new LoopScheduleSaveError(error, flow);+ }+}++async function reconcileSchedule(+ client: ApiClient,+ projectId: string,+ existing: Pick<LoopHogFlowSource, "id" | "schedules">,+ flow: Schemas.HogFlow,+ write: LoopHogFlowWrite,+): Promise<Schemas.HogFlow> {+ const current = existing.schedules?.[0];+ if (!write.schedule) {+ for (const schedule of existing.schedules ?? []) {+ await deleteHogFlowSchedule(client, projectId, existing.id, schedule.id);+ }+ return { ...flow, schedules: [] };+ }+ if (current && hogFlowScheduleMatches(current, write.schedule)) {+ return flow;+ }+ const schedule = current+ ? await updateHogFlowSchedule(+ client,+ projectId,+ existing.id,+ current.id,+ write.schedule,+ )+ : await createHogFlowSchedule(+ client,+ projectId,+ existing.id,+ write.schedule,+ );+ return { ...flow, schedules: [schedule] };+}++/** Activation re-runs the workflow's full validation server-side, so a broken+ * flow fails the toggle with a readable error instead of firing broken. */+export async function setLoopHogFlowEnabled(+ client: ApiClient,+ projectId: string,+ hogFlowId: string,+ enabled: boolean,+): Promise<Schemas.HogFlow> {+ return patchHogFlow(client, projectId, hogFlowId, {+ status: enabled ? "active" : "draft",+ });+}++/** One key per click: a retry of the same click is deduped server-side, a+ * second click is a second run. */+export async function runLoopHogFlow(+ client: ApiClient,+ projectId: string,+ hogFlowId: string,+): Promise<LoopSchemas.LoopFireRun> {+ await runHogFlow(client, projectId, hogFlowId, crypto.randomUUID());+ // The run endpoint queues an invocation; the task it creates only exists+ // once the workflow step runs, so there is no task id to hand back yet.+ return { created: true, reason: "created", task_id: null, task_run_id: null };+}diff --git a/products/desktop/packages/ui/src/features/loops/loopScheduleRRule.test.ts b/products/desktop/packages/ui/src/features/loops/loopScheduleRRule.test.tsnew file mode 100644index 000000000000..b4bff5b7cf57--- /dev/null+++ b/products/desktop/packages/ui/src/features/loops/loopScheduleRRule.test.ts@@ -0,0 +1,215 @@+import { describe, expect, it } from "vitest";+import {+ hogFlowScheduleMatches,+ hogFlowScheduleToScheduleConfig,+ scheduleConfigToHogFlowSchedule,+} from "./loopScheduleRRule";++// A Wednesday, 10:37 UTC (11:37 in Lisbon, which is on summer time).+const NOW = new Date("2026-09-02T10:37:12.000Z");++function must<T>(value: T | null | undefined): T {+ if (value == null) throw new Error("expected a value");+ return value;+}++/** Clock time and weekday of an instant in a timezone, as the editor shows it. */+function inZone(instant: string, timezone: string): string {+ return new Intl.DateTimeFormat("en-US", {+ timeZone: timezone,+ hourCycle: "h23",+ weekday: "short",+ hour: "2-digit",+ minute: "2-digit",+ }).format(new Date(instant));+}++describe("loopScheduleRRule", () => {+ it.each([+ ["hourly", "0 * * * *", "FREQ=HOURLY;INTERVAL=1", "Wed 12:00"],+ ["daily", "0 9 * * *", "FREQ=DAILY;INTERVAL=1", "Thu 09:00"],+ [+ "weekdays",+ "30 8 * * 1-5",+ "FREQ=WEEKLY;INTERVAL=1;BYDAY=MO,TU,WE,TH,FR",+ "Thu 08:30",+ ],+ ["weekly", "15 17 * * 3", "FREQ=WEEKLY;INTERVAL=1;BYDAY=WE", "Wed 17:15"],+ ["sunday", "0 6 * * 0", "FREQ=WEEKLY;INTERVAL=1;BYDAY=SU", "Sun 06:00"],+ ])(+ "round-trips the %s preset with the clock time in starts_at",+ (_label, cron, rrule, startsAtInLisbon) => {+ const config = { cron_expression: cron, timezone: "Europe/Lisbon" };+ const schedule = must(scheduleConfigToHogFlowSchedule(config, NOW));+ expect(schedule.rrule).toBe(rrule);+ expect(schedule.timezone).toBe("Europe/Lisbon");+ expect(inZone(schedule.starts_at, "Europe/Lisbon")).toBe(+ startsAtInLisbon,+ );+ expect(new Date(schedule.starts_at).getTime()).toBeGreaterThan(+ NOW.getTime(),+ );+ expect(hogFlowScheduleToScheduleConfig(schedule)).toEqual(config);+ },+ );++ it("round-trips a one-off run as the editor's one-time rule anchored at run_at", () => {+ const config = { run_at: "2026-09-03T14:00:00.000Z", timezone: "UTC" };+ const schedule = scheduleConfigToHogFlowSchedule(config, NOW);+ expect(schedule).toEqual({+ rrule: "FREQ=DAILY;COUNT=1",+ starts_at: "2026-09-03T14:00:00.000Z",+ timezone: "UTC",+ });+ expect(hogFlowScheduleToScheduleConfig(must(schedule))).toEqual(config);+ });++ it("reads the clock time in the schedule's timezone, not UTC", () => {+ expect(+ hogFlowScheduleToScheduleConfig({+ rrule: "FREQ=DAILY;INTERVAL=1",+ starts_at: "2026-09-02T08:00:00Z",+ timezone: "Europe/Lisbon",+ }),+ ).toEqual({ cron_expression: "0 9 * * *", timezone: "Europe/Lisbon" });+ });++ it("reads a weekly rule with no BYDAY as the weekday of starts_at, like the editor", () => {+ expect(+ hogFlowScheduleToScheduleConfig({+ rrule: "FREQ=WEEKLY;INTERVAL=1",+ starts_at: "2027-01-01T00:00:00Z",+ timezone: "UTC",+ }),+ ).toEqual({ cron_expression: "0 0 * * 5", timezone: "UTC" });+ });++ it("defaults a missing timezone to UTC in both directions", () => {+ expect(+ scheduleConfigToHogFlowSchedule({ cron_expression: "0 9 * * *" }, NOW)+ ?.timezone,+ ).toBe("UTC");+ expect(+ hogFlowScheduleToScheduleConfig({+ rrule: "FREQ=DAILY;INTERVAL=1",+ starts_at: "2026-09-03T09:00:00Z",+ }),+ ).toEqual({ cron_expression: "0 9 * * *", timezone: "UTC" });+ });++ it.each(["*/15 * * * *", "0 9 1 * *", "0 9 * * 1,3", "", undefined])(+ "refuses a cron the picker cannot express: %s",+ (cron) => {+ expect(+ scheduleConfigToHogFlowSchedule({ cron_expression: cron }, NOW),+ ).toBeNull();+ },+ );++ it.each([+ ["a two-day interval", "FREQ=DAILY;INTERVAL=2", "2026-09-03T09:00:00Z"],+ ["a monthly rule", "FREQ=MONTHLY;BYMONTHDAY=1", "2026-09-03T09:00:00Z"],+ [+ "an end date",+ "FREQ=DAILY;UNTIL=20261231T000000Z",+ "2026-09-03T09:00:00Z",+ ],+ [+ "two weekdays",+ "FREQ=WEEKLY;INTERVAL=1;BYDAY=MO,WE",+ "2026-09-03T09:00:00Z",+ ],+ [+ "a clock time inside the rule",+ "FREQ=DAILY;BYHOUR=9;BYMINUTE=0",+ "2026-09-03T09:00:00Z",+ ],+ ["a count above one", "FREQ=DAILY;COUNT=3", "2026-09-03T09:00:00Z"],+ [+ "an hourly rule off the hour",+ "FREQ=HOURLY;INTERVAL=1",+ "2026-09-03T09:30:00Z",+ ],+ ["a malformed segment", "FREQ=DAILY;BYDAY", "2026-09-03T09:00:00Z"],+ ["an unreadable anchor", "FREQ=DAILY;INTERVAL=1", "not a date"],+ ])(+ "reads a rule the form did not write as foreign: %s",+ (_label, rrule, startsAt) => {+ expect(+ hogFlowScheduleToScheduleConfig({+ rrule,+ starts_at: startsAt,+ timezone: "UTC",+ }),+ ).toBeNull();+ },+ );++ it("treats a preset as unchanged when starts_at moves but keeps its clock time", () => {+ const desired = must(+ scheduleConfigToHogFlowSchedule(+ { cron_expression: "0 9 * * *", timezone: "Europe/Lisbon" },+ NOW,+ ),+ );+ // 08:00 UTC in January is 08:00 Lisbon (winter time), a different clock time.+ expect(+ hogFlowScheduleMatches(+ { ...desired, starts_at: "2026-01-05T09:00:00Z" },+ desired,+ ),+ ).toBe(true);+ expect(+ hogFlowScheduleMatches(+ { ...desired, starts_at: "2026-01-05T08:00:00Z" },+ desired,+ ),+ ).toBe(false);+ expect(+ hogFlowScheduleMatches({ ...desired, timezone: "UTC" }, desired),+ ).toBe(false);+ });++ it("treats an hourly preset as unchanged when only the anchor hour moves", () => {+ const desired = must(+ scheduleConfigToHogFlowSchedule(+ { cron_expression: "0 * * * *", timezone: "Europe/Lisbon" },+ NOW,+ ),+ );+ expect(inZone(desired.starts_at, "Europe/Lisbon")).toBe("Wed 12:00");+ expect(+ hogFlowScheduleMatches(+ { ...desired, starts_at: "2026-09-02T08:00:00Z" },+ desired,+ ),+ ).toBe(true);+ expect(+ hogFlowScheduleMatches(+ { ...desired, starts_at: "2026-09-02T08:30:00Z" },+ desired,+ ),+ ).toBe(false);+ });++ it("treats a one-off as changed when run_at moves", () => {+ const desired = must(+ scheduleConfigToHogFlowSchedule(+ { run_at: "2026-09-03T14:00:00.000Z" },+ NOW,+ ),+ );+ expect(+ hogFlowScheduleMatches(+ { ...desired, starts_at: "2026-09-03T14:00:00+00:00" },+ desired,+ ),+ ).toBe(true);+ expect(+ hogFlowScheduleMatches(+ { ...desired, starts_at: "2026-09-04T14:00:00.000Z" },+ desired,+ ),+ ).toBe(false);+ });+});diff --git a/products/desktop/packages/ui/src/features/loops/loopScheduleRRule.ts b/products/desktop/packages/ui/src/features/loops/loopScheduleRRule.tsnew file mode 100644index 000000000000..932483fec6ff--- /dev/null+++ b/products/desktop/packages/ui/src/features/loops/loopScheduleRRule.ts@@ -0,0 +1,215 @@+import type { HogFlowScheduleWrite } from "@posthog/api-client/hogFlowLoops";+import type { LoopSchemas } from "@posthog/api-client/loops";+import { nextRecurringRun } from "@posthog/ui/primitives/nextRecurringRun";+import { parseCronSchedule } from "./loopCron";++/**+ * Loop schedule <-> workflow schedule row, in the shape the workflow editor+ * writes: the RRULE carries frequency, interval and weekdays only, and the+ * time of day lives in `starts_at`. The scheduler expands the rule from+ * `starts_at` in the schedule's timezone, and the editor reads the clock time+ * back from it, so a rule that carries its own BYHOUR would show one time in+ * the editor and fire at another.+ */++const WEEKDAY_CODES = ["SU", "MO", "TU", "WE", "TH", "FR", "SA"] as const;+const WORKWEEK = "MO,TU,WE,TH,FR";+/** Same string the workflow editor writes for a one-time schedule. */+const ONE_TIME_RRULE = "FREQ=DAILY;COUNT=1";++/** Anything beyond these keys means a person edited the rule outside the loop+ * form, and the four presets can no longer describe it. */+const KNOWN_RRULE_KEYS = new Set([+ "FREQ",+ "INTERVAL",+ "COUNT",+ "BYDAY",+ "WKST",+]);++interface WallClock {+ /** 0 to 23. */+ hour: number;+ minute: number;+ /** "0" (Sunday) to "6" (Saturday), matching cron and the loop picker. */+ weekday: string;+}++const WEEKDAY_BY_SHORT_NAME: Record<string, string> = {+ Sun: "0",+ Mon: "1",+ Tue: "2",+ Wed: "3",+ Thu: "4",+ Fri: "5",+ Sat: "6",+};++/** The clock time and weekday of an instant in a timezone, or null when the+ * instant or the timezone cannot be read. */+function wallClock(instant: string, timezone: string): WallClock | null {+ const date = new Date(instant);+ if (Number.isNaN(date.getTime())) return null;+ let parts: Intl.DateTimeFormatPart[];+ try {+ parts = new Intl.DateTimeFormat("en-US", {+ timeZone: timezone,+ hourCycle: "h23",+ hour: "2-digit",+ minute: "2-digit",+ weekday: "short",+ }).formatToParts(date);+ } catch {+ return null;+ }+ const read = (type: string) =>+ parts.find((part) => part.type === type)?.value;+ const hour = read("hour");+ const minute = read("minute");+ const weekday = WEEKDAY_BY_SHORT_NAME[read("weekday") ?? ""];+ if (!hour || !minute || !weekday) return null;+ // Some engines render midnight as "24" under h23.+ return {+ hour: hour === "24" ? 0 : Number(hour),+ minute: Number(minute),+ weekday,+ };+}++function presetRRule(frequency: string, weekday: string): string {+ switch (frequency) {+ case "hourly":+ return "FREQ=HOURLY;INTERVAL=1";+ case "daily":+ return "FREQ=DAILY;INTERVAL=1";+ case "weekdays":+ return `FREQ=WEEKLY;INTERVAL=1;BYDAY=${WORKWEEK}`;+ default:+ return `FREQ=WEEKLY;INTERVAL=1;BYDAY=${WEEKDAY_CODES[Number(weekday)]}`;+ }+}++/**+ * Turns the loop form's schedule into a workflow schedule row. Returns null for+ * a cron the frequency picker cannot express, so a caller never sends a rule+ * that silently drops part of the cadence.+ *+ * `starts_at` is the next occurrence at the chosen time in the schedule's+ * timezone, so the row reads the same in the workflow editor as in the loop.+ */+export function scheduleConfigToHogFlowSchedule(+ config: LoopSchemas.LoopScheduleTriggerConfig,+ now: Date = new Date(),+): HogFlowScheduleWrite | null {+ const timezone = config.timezone ?? "UTC";+ if (config.run_at) {+ return { rrule: ONE_TIME_RRULE, starts_at: config.run_at, timezone };+ }+ const schedule = parseCronSchedule(config.cron_expression);+ if (!schedule) return null;+ const startsAt = nextRecurringRun(schedule, timezone, now);+ if (!startsAt) return null;+ return {+ rrule: presetRRule(schedule.frequency, schedule.weekday),+ starts_at: startsAt.toISOString(),+ timezone,+ };+}++function parseRRule(rrule: string): Map<string, string> | null {+ const parts = new Map<string, string>();+ for (const segment of rrule.split(";")) {+ if (!segment.trim()) continue;+ const [key, value, ...rest] = segment.split("=");+ if (!key || value === undefined || rest.length > 0) return null;+ parts.set(key.trim().toUpperCase(), value.trim().toUpperCase());+ }+ return parts;+}++/**+ * Reads a workflow schedule row back into the loop form's schedule config.+ * Returns null when the rule is not one the form (or the workflow editor's+ * matching controls) would write, which marks the loop as edited outside the+ * form rather than guessing at a nearby preset.+ */+export function hogFlowScheduleToScheduleConfig(schedule: {+ rrule: string;+ starts_at: string;+ timezone?: string | null;+}): LoopSchemas.LoopScheduleTriggerConfig | null {+ const parts = parseRRule(schedule.rrule);+ if (!parts) return null;+ for (const key of parts.keys()) {+ if (!KNOWN_RRULE_KEYS.has(key)) return null;+ }+ if ((parts.get("INTERVAL") ?? "1") !== "1") return null;+ const timezone = schedule.timezone ?? "UTC";+ const freq = parts.get("FREQ");+ const byDay = parts.get("BYDAY");++ if (parts.has("COUNT")) {+ if (parts.get("COUNT") !== "1" || freq !== "DAILY" || byDay) return null;+ return { run_at: schedule.starts_at, timezone };+ }++ const clock = wallClock(schedule.starts_at, timezone);+ if (!clock) return null;+ const { hour, minute } = clock;+ const cronTime = `${minute} ${hour}`;++ if (freq === "HOURLY") {+ // The picker's hourly preset is on the hour; an anchor at :30 would fire+ // at :30 and cannot be shown as "hourly".+ if (byDay || minute !== 0) return null;+ return { cron_expression: "0 * * * *", timezone };+ }+ if (freq === "DAILY") {+ if (byDay) return null;+ return { cron_expression: `${cronTime} * * *`, timezone };+ }+ if (freq === "WEEKLY") {+ if (byDay === WORKWEEK) {+ return { cron_expression: `${cronTime} * * 1-5`, timezone };+ }+ // No BYDAY means the weekday of starts_at, which is how the editor+ // stores a weekly schedule before a day pill is picked.+ if (!byDay) {+ return { cron_expression: `${cronTime} * * ${clock.weekday}`, timezone };+ }+ const weekday = WEEKDAY_CODES.indexOf(+ byDay as (typeof WEEKDAY_CODES)[number],+ );+ if (weekday === -1) return null;+ return { cron_expression: `${cronTime} * * ${weekday}`, timezone };+ }+ return null;+}++/**+ * Whether an existing schedule row already expresses the desired cadence. A+ * preset compares the clock time `starts_at` encodes rather than the instant,+ * because rewriting the anchor makes the scheduler recompute `next_run_at`+ * and can skip an occurrence that was about to fire. An hourly rule fires+ * every hour from its anchor, so only the anchor's minute carries cadence.+ */+export function hogFlowScheduleMatches(+ existing: { rrule: string; starts_at: string; timezone?: string | null },+ desired: HogFlowScheduleWrite,+): boolean {+ if (existing.rrule !== desired.rrule) return false;+ const timezone = existing.timezone ?? "UTC";+ if (timezone !== desired.timezone) return false;+ if (desired.rrule === ONE_TIME_RRULE) {+ return (+ new Date(existing.starts_at).getTime() ===+ new Date(desired.starts_at).getTime()+ );+ }+ const before = wallClock(existing.starts_at, timezone);+ const after = wallClock(desired.starts_at, timezone);+ if (!before || !after) return false;+ if (before.minute !== after.minute) return false;+ const hourly = parseRRule(desired.rrule)?.get("FREQ") === "HOURLY";+ return hourly || before.hour === after.hour;+}diff --git a/products/desktop/packages/ui/src/features/loops/loopTriggerLimits.ts b/products/desktop/packages/ui/src/features/loops/loopTriggerLimits.tsnew file mode 100644index 000000000000..cab12fe03a4f--- /dev/null+++ b/products/desktop/packages/ui/src/features/loops/loopTriggerLimits.ts@@ -0,0 +1,24 @@+import type { LoopSchemas } from "@posthog/api-client/loops";++/** What the loop's backend can store. Workflow-backed loops carry one trigger,+ * subscribe to one GitHub event type, and have no payload conditions. */+export interface LoopTriggerEditorLimits {+ triggerTypes: LoopSchemas.LoopTriggerTypeEnum[];+ maxTriggers: number | null;+ singleGithubEvent: boolean;+ githubPayloadConditions: boolean;+}++export const LOOPS_API_TRIGGER_LIMITS: LoopTriggerEditorLimits = {+ triggerTypes: ["schedule", "github", "api"],+ maxTriggers: null,+ singleGithubEvent: false,+ githubPayloadConditions: true,+};++export const WORKFLOW_TRIGGER_LIMITS: LoopTriggerEditorLimits = {+ triggerTypes: ["schedule", "github"],+ maxTriggers: 1,+ singleGithubEvent: true,+ githubPayloadConditions: false,+};