: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(loops): add embedded loop editing (#76844)
Dylan Martin74b3ef99987d
diff --git a/products/desktop/packages/ui/src/features/folder-picker/GitHubRepoPicker.tsx b/products/desktop/packages/ui/src/features/folder-picker/GitHubRepoPicker.tsxindex 05f5f8d17285..7837fad278a3 100644--- a/products/desktop/packages/ui/src/features/folder-picker/GitHubRepoPicker.tsx+++ b/products/desktop/packages/ui/src/features/folder-picker/GitHubRepoPicker.tsx@@ -35,6 +35,7 @@ interface GitHubRepoPickerProps {onSearchQueryChange?: (value: string) => void;hasMore?: boolean;onLoadMore?: () => void;+ triggerClassName?: string;}export function GitHubRepoPicker({@@ -55,6 +56,7 @@ export function GitHubRepoPicker({onSearchQueryChange,hasMore: controlledHasMore,onLoadMore,+ triggerClassName,}: GitHubRepoPickerProps) {const buttonSize = size === "2" ? "lg" : "sm";const buttonTextClass = size === "2" ? "text-[13px]" : "";@@ -98,7 +100,7 @@ export function GitHubRepoPicker({variant="outline"disabledsize={buttonSize}- className={buttonTextClass}+ className={`${buttonTextClass} ${triggerClassName ?? ""}`}><GithubLogo size={16} weight="regular" className="shrink-0" />Loading repos...@@ -119,7 +121,7 @@ export function GitHubRepoPicker({variant="outline"disabledsize={buttonSize}- className={buttonTextClass}+ className={`${buttonTextClass} ${triggerClassName ?? ""}`}><GithubLogo size={16} weight="regular" className="shrink-0" />No GitHub repos@@ -137,7 +139,7 @@ export function GitHubRepoPicker({size={buttonSize}disabledaria-label="Repository"- className={`pointer-events-none min-w-0 max-w-full cursor-default justify-start disabled:opacity-100 ${buttonTextClass}`}+ className={`pointer-events-none min-w-0 max-w-full cursor-default justify-start disabled:opacity-100 ${buttonTextClass} ${triggerClassName ?? ""}`}><GithubLogo size={14} weight="regular" className="shrink-0" /><span className="min-w-0 truncate">{onlyRepo}</span>@@ -181,7 +183,7 @@ export function GitHubRepoPicker({size={buttonSize}disabled={disabled}aria-label="Repository"- className={buttonTextClass}+ className={`${buttonTextClass} ${triggerClassName ?? ""}`}><GithubLogo size={14} weight="regular" className="shrink-0" /><span className="min-w-0 truncate">{value ?? placeholder}</span>diff --git a/products/desktop/packages/ui/src/features/loops/components/EditLoopView.tsx b/products/desktop/packages/ui/src/features/loops/components/EditLoopView.tsxdeleted file mode 100644index de57d1a57b94..000000000000--- a/products/desktop/packages/ui/src/features/loops/components/EditLoopView.tsx+++ /dev/null@@ -1,21 +0,0 @@-import { useLoop } from "../hooks/useLoop";-import { LoopLoadError } from "./LoopFallbacks";-import { LoopForm } from "./LoopForm";--export function EditLoopView({ loopId }: { loopId: string }) {- const { data: loop, isLoading, isError } = useLoop(loopId);-- if (isLoading) {- return (- <div className="mx-auto max-w-2xl px-6 py-6">- <div className="h-24 animate-pulse rounded-(--radius-2) border border-border bg-(--gray-2)" />- </div>- );- }-- if (isError || !loop) {- return <LoopLoadError />;- }-- return <LoopForm loop={loop} />;-}diff --git a/products/desktop/packages/ui/src/features/loops/components/LoopDetailView.tsx b/products/desktop/packages/ui/src/features/loops/components/LoopDetailView.tsxindex b48fffc1243c..a8e849be1316 100644--- a/products/desktop/packages/ui/src/features/loops/components/LoopDetailView.tsx+++ b/products/desktop/packages/ui/src/features/loops/components/LoopDetailView.tsx@@ -1,4 +1,12 @@-import { ArrowLeftIcon, LinkIcon } from "@phosphor-icons/react";+import {+ ArrowLeftIcon,+ CheckCircleIcon,+ LinkIcon,+ PauseIcon,+ PencilSimpleIcon,+ PlayIcon,+ TrashIcon,+} from "@phosphor-icons/react";import type { LoopSchemas } from "@posthog/api-client/loops";import { isUploadableSkillSource } from "@posthog/core/message-editor/skillTags";import { useHostTRPC } from "@posthog/host-router/react";@@ -12,8 +20,6 @@ import {AlertDialogTitle,Badge,Button,- Switch,- Textarea,} from "@posthog/quill";import { ANALYTICS_EVENTS } from "@posthog/shared/analytics-events";import { UserAvatar } from "@posthog/ui/features/auth/UserAvatar";@@ -30,15 +36,16 @@ import { toast } from "@posthog/ui/primitives/toast";import {canGoBackInHistory,goBackInHistory,- navigateToEditLoop,navigateToLoops,} from "@posthog/ui/router/navigationBridge";+import { getRouterOrNull } from "@posthog/ui/router/routerRef";import { track } from "@posthog/ui/shell/analytics";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 { useEffect, useMemo, useRef, useState } from "react";+import { useCallback, useEffect, useMemo, useRef, useState } from "react";import { useLoop } from "../hooks/useLoop";import {useDeleteLoop,@@ -64,11 +71,25 @@ import { formatLoopModel } from "../loopModels";import { loopSkillBundles, primaryLoopSkillBundle } from "../loopSkill";import { copyLoopLink } from "../utils/copyLoopLink";import { LoopLoadError } from "./LoopFallbacks";+import { LoopForm } from "./LoopForm";import { LoopHeaderTitle } from "./LoopHeaderTitle";import { LoopRunRow } from "./LoopRunRow";import { LoopSpaceBreadcrumb } from "./LoopSpaceBreadcrumb";-export function LoopDetailView({ loopId }: { loopId: string }) {+type PendingNavigation = {+ action: "PUSH" | "REPLACE" | "BACK" | "FORWARD" | "GO";+ delta: number | null;+ href: string;+ state: ParsedHistoryState;+};++export function LoopDetailView({+ loopId,+ startEditing = false,+}: {+ loopId: string;+ startEditing?: boolean;+}) {const hasLoopListOrigin = useLocation({select: (location) => location.state.loopListOrigin === true,});@@ -77,7 +98,14 @@ export function LoopDetailView({ loopId }: { loopId: string }) {const deleteLoop = useDeleteLoop();const runLoop = useRunLoop(loopId);const [deleteOpen, setDeleteOpen] = useState(false);+ const [discardOpen, setDiscardOpen] = useState(false);+ const [pendingLeaveAction, setPendingLeaveAction] = useState<+ "back" | "summary" | "navigation" | null+ >(null);+ const pendingNavigationRef = useRef<PendingNavigation | null>(null);const [runNowPending, setRunNowPending] = useState(false);+ const [isEditing, setIsEditing] = useState(startEditing);+ const [editDirty, setEditDirty] = useState(false);const runsQuery = useLoopRuns(loopId);const runs = runsQuery.data ?? [];@@ -204,6 +232,122 @@ export function LoopDetailView({ loopId }: { loopId: string }) {});};+ useEffect(() => {+ if (startEditing) setIsEditing(true);+ }, [startEditing]);++ const leavePage = useCallback(() => {+ if (hasLoopListOrigin && canGoBackInHistory()) {+ goBackInHistory();+ return;+ }+ navigateToLoops();+ }, [hasLoopListOrigin]);++ const requestLeaveEdit = (action: "back" | "summary") => {+ if (isEditing && editDirty) {+ setPendingLeaveAction(action);+ setDiscardOpen(true);+ return;+ }+ if (action === "back") {+ leavePage();+ } else {+ setIsEditing(false);+ setEditDirty(false);+ }+ };++ const continueBlockedNavigation = () => {+ const pendingNavigation = pendingNavigationRef.current;+ pendingNavigationRef.current = null;+ if (!pendingNavigation) return;++ const router = getRouterOrNull();+ if (!router) return;++ if (+ pendingNavigation.action === "BACK" ||+ pendingNavigation.action === "FORWARD" ||+ pendingNavigation.action === "GO"+ ) {+ if (pendingNavigation.delta !== null && pendingNavigation.delta !== 0) {+ router.history.go(pendingNavigation.delta, { ignoreBlocker: true });+ } else {+ router.history.push(pendingNavigation.href, pendingNavigation.state, {+ ignoreBlocker: true,+ });+ }+ return;+ }++ if (pendingNavigation.action === "REPLACE") {+ router.history.replace(pendingNavigation.href, pendingNavigation.state, {+ ignoreBlocker: true,+ });+ return;+ }++ router.history.push(pendingNavigation.href, pendingNavigation.state, {+ ignoreBlocker: true,+ });+ };++ const discardChanges = () => {+ const action = pendingLeaveAction;+ setDiscardOpen(false);+ setPendingLeaveAction(null);+ setEditDirty(false);+ setIsEditing(false);+ if (action === "back") {+ if (hasLoopListOrigin && canGoBackInHistory()) {+ getRouterOrNull()?.history.back({ ignoreBlocker: true });+ return;+ }+ navigateToLoops({ ignoreBlocker: true });+ } else if (action === "navigation") {+ continueBlockedNavigation();+ }+ };++ useEffect(() => {+ if (!isEditing || !editDirty) return;+ const router = getRouterOrNull();+ if (!router) return;++ return router.history.block({+ enableBeforeUnload: true,+ blockerFn: ({ currentLocation, nextLocation, action }) => {+ if (nextLocation.href === currentLocation.href) return false;++ const delta =+ typeof nextLocation.state.__TSR_index === "number" &&+ typeof currentLocation.state.__TSR_index === "number"+ ? nextLocation.state.__TSR_index - currentLocation.state.__TSR_index+ : null;+ pendingNavigationRef.current = {+ action,+ delta,+ href: nextLocation.href,+ state: nextLocation.state,+ };+ setPendingLeaveAction("navigation");+ setDiscardOpen(true);+ return true;+ },+ });+ }, [isEditing, editDirty]);++ useEffect(() => {+ if (!isEditing || !editDirty) return;+ const handleBeforeUnload = (event: BeforeUnloadEvent) => {+ event.preventDefault();+ event.returnValue = "";+ };+ window.addEventListener("beforeunload", handleBeforeUnload);+ return () => window.removeEventListener("beforeunload", handleBeforeUnload);+ }, [isEditing, editDirty]);+if (isLoading) {return (<div className="mx-auto w-full max-w-5xl px-8 py-8">@@ -227,13 +371,7 @@ export function LoopDetailView({ loopId }: { loopId: string }) {<Buttonvariant="link-muted"size="sm"- onClick={() => {- if (hasLoopListOrigin && canGoBackInHistory()) {- goBackInHistory();- return;- }- navigateToLoops();- }}+ onClick={() => requestLeaveEdit("back")}className="w-fit px-0"><ArrowLeftIcon size={15} />@@ -241,22 +379,33 @@ export function LoopDetailView({ loopId }: { loopId: string }) {</Button><Flex align="center" justify="between" gap="3" wrap="wrap">- <Flex align="center" gap="2" wrap="wrap">- <Text className="font-bold text-[22px] text-gray-12 leading-tight tracking-tight">+ <Flex align="center" gap="2" wrap="wrap" className="min-w-0">+ <Text+ className="truncate font-bold text-[22px] text-gray-12 leading-tight tracking-tight"+ title={loop.name}+ >{loop.name}</Text><Badge variant={loopStatusBadgeVariant(loop)}>{loopStatusLabel(loop)}</Badge>- <Badge>{loop.visibility}</Badge>+ <Badge>{formatVisibility(loop.visibility)}</Badge></Flex><Flex align="center" gap="2">- <Switch- checked={loop.enabled}+ <Button+ variant="outline"+ size="sm"+ loading={updateLoop.isPending}disabled={updateLoop.isPending}- aria-label={loop.enabled ? "Pause loop" : "Enable loop"}- onCheckedChange={handleToggleEnabled}- />+ onClick={() => handleToggleEnabled(!loop.enabled)}+ >+ {loop.enabled ? (+ <PauseIcon size={14} />+ ) : (+ <PlayIcon size={14} />+ )}+ {loop.enabled ? "Pause" : "Resume"}+ </Button><Buttonvariant="outline"size="sm"@@ -272,37 +421,72 @@ export function LoopDetailView({ loopId }: { loopId: string }) {disabled={runNowPending}onClick={() => void handleRunNow()}>+ <PlayIcon size={14} />Run now</Button><Buttonvariant="outline"size="sm"- onClick={() => navigateToEditLoop(loop.id)}+ className={+ isEditing+ ? "border-(--accent-7) bg-(--accent-3) text-(--accent-11)"+ : undefined+ }+ onClick={() => {+ if (isEditing) {+ requestLeaveEdit("summary");+ return;+ }+ setIsEditing(true);+ }}>- Edit+ {isEditing ? (+ <CheckCircleIcon size={14} weight="fill" />+ ) : (+ <PencilSimpleIcon size={14} />+ )}+ {isEditing ? "Editing" : "Edit"}</Button><Buttonvariant="destructive"size="sm"onClick={() => setDeleteOpen(true)}>+ <TrashIcon size={14} />Delete</Button></Flex></Flex>- {loop.description.trim() ? (- <Text className="max-w-3xl text-[12.5px] text-gray-11 leading-snug">- {loop.description}- </Text>- ) : null}+ <Text+ className={`max-w-3xl text-[12.5px] leading-snug ${+ loop.description.trim() ? "text-gray-11" : "text-gray-10"+ }`}+ >+ {loop.description.trim() || "No description"}+ </Text><PausedNotice loop={loop} /></Flex>- <ConfigSummarySection loop={loop} />-- <InstructionsSection loop={loop} />+ {isEditing ? (+ <LoopForm+ loop={loop}+ variant="embedded"+ onDirtyChange={setEditDirty}+ onCancel={() => requestLeaveEdit("summary")}+ onSaved={() => {+ setIsEditing(false);+ setEditDirty(false);+ toast.success("Loop updated");+ }}+ />+ ) : (+ <>+ <ConfigSummarySection loop={loop} />+ <InstructionsSection loop={loop} />+ </>+ )}<Flex direction="column" gap="2"><Flex align="center" gap="2">@@ -377,6 +561,32 @@ export function LoopDetailView({ loopId }: { loopId: string }) {</AlertDialogFooter></AlertDialogContent></AlertDialog>++ <AlertDialog open={discardOpen} onOpenChange={setDiscardOpen}>+ <AlertDialogContent className="max-w-md">+ <AlertDialogHeader>+ <AlertDialogTitle>Discard unsaved changes?</AlertDialogTitle>+ <AlertDialogDescription>+ <Text color="gray" className="text-[13px]">+ This loop has edits that haven't been saved. Leaving edit mode+ will discard them.+ </Text>+ </AlertDialogDescription>+ </AlertDialogHeader>+ <AlertDialogFooter>+ <AlertDialogClose+ render={+ <Button variant="outline" size="sm">+ Keep editing+ </Button>+ }+ />+ <Button variant="destructive" size="sm" onClick={discardChanges}>+ Discard changes+ </Button>+ </AlertDialogFooter>+ </AlertDialogContent>+ </AlertDialog></div>);}@@ -390,6 +600,10 @@ function loopStatusBadgeVariant(return "default";}+function formatVisibility(visibility: LoopSchemas.LoopVisibilityEnum): string {+ return visibility.charAt(0).toUpperCase() + visibility.slice(1);+}+function PausedNotice({ loop }: { loop: LoopSchemas.Loop }) {const description = loopPausedDescription(loop);if (!description) return null;@@ -595,74 +809,18 @@ function LoopSkillSummary({ loop }: { loop: LoopSchemas.Loop }) {}function InstructionsSection({ loop }: { loop: LoopSchemas.Loop }) {- const updateLoop = useUpdateLoop(loop.id);const primarySkill = primaryLoopSkillBundle(loop);- const [draft, setDraft] = useState<string | null>(null);- // Escape reverts and blurs; skip the resulting onBlur save.- const skipCommit = useRef(false);-- const commit = (value: string) => {- if (skipCommit.current) {- skipCommit.current = false;- return;- }- const trimmed = value.trim();- if (!trimmed) {- setDraft(null);- return;- }- if (updateLoop.isPending) return;- if (trimmed === loop.instructions.trim()) {- setDraft(null);- return;- }- updateLoop.mutate(- { instructions: trimmed },- {- onSuccess: () => {- setDraft(null);- toast.success("Instructions updated");- },- onError: (error) => {- setDraft(null);- toast.error("Failed to update instructions", {- description: error.message,- });- },- },- );- };return (<Flex direction="column" gap="3">- <Flex align="center" gap="2">- <Text className="font-medium text-[13px] text-gray-12">- Instructions- </Text>- {updateLoop.isPending ? (- <Text className="text-[11px] text-gray-10">Saving…</Text>- ) : null}- </Flex>- <Textarea- value={draft ?? loop.instructions}- disabled={updateLoop.isPending}- aria-label="Loop instructions"- className="max-h-[400px] min-h-[200px] bg-(--color-panel-solid) text-[12.5px] leading-relaxed"- onChange={(e) => setDraft(e.currentTarget.value)}- onBlur={(e) => commit(e.currentTarget.value)}- onKeyDown={(e) => {- if (e.key === "Escape") {- skipCommit.current = true;- setDraft(null);- e.currentTarget.blur();- }- }}- />+ <Text className="font-medium text-[13px] text-gray-12">Instructions</Text>+ <pre className="max-h-[400px] min-h-[160px] overflow-auto whitespace-pre-wrap rounded-(--radius-2) border border-border bg-(--color-panel-solid) p-3 font-sans text-[12.5px] text-gray-12 leading-relaxed">+ {loop.instructions}+ </pre>{primarySkill ? (<Text className="text-[11px] text-gray-10 leading-snug">This loop runs the {primarySkill.skill_name} skill: the leading /- {primarySkill.skill_name} line invokes its attached snapshot. Editing- here changes only the text; use Edit to change or detach the skill.+ {primarySkill.skill_name} line invokes its attached snapshot.</Text>) : null}</Flex>diff --git a/products/desktop/packages/ui/src/features/loops/components/LoopForm.tsx b/products/desktop/packages/ui/src/features/loops/components/LoopForm.tsxindex c41cf27ca596..95aeb1ba61d0 100644--- a/products/desktop/packages/ui/src/features/loops/components/LoopForm.tsx+++ b/products/desktop/packages/ui/src/features/loops/components/LoopForm.tsx@@ -18,7 +18,7 @@ import {navigateToLoops,} from "@posthog/ui/router/navigationBridge";import { track } from "@posthog/ui/shell/analytics";-import { Box, Flex, Text, TextField } from "@radix-ui/themes";+import { Box, Flex, Text, TextArea, TextField } from "@radix-ui/themes";import { type ReactNode, useEffect, useMemo, useState } from "react";import { useAuthStateValue } from "../../auth/store";import {@@ -72,13 +72,41 @@ const ADAPTER_LABELS: Record<LoopSchemas.LoopRuntimeAdapterEnum, string> = {const STEPS = ["Prompt", "When", "Options", "Review"] as const;+type LoopFormBaseline = {+ loopId: string;+ updatedAt: string;+ values: LoopFormValues;+ serialized: string;+};++function buildLoopFormBaseline(loop: LoopSchemas.Loop): LoopFormBaseline {+ const values = normalizeLoopFormValues(loopToFormValues(loop));+ return {+ loopId: loop.id,+ updatedAt: loop.updated_at,+ values,+ serialized: JSON.stringify(values),+ };+}+interface LoopFormProps {/** Present in edit mode; absent when creating a new loop. */loop?: LoopSchemas.Loop;+ variant?: "wizard" | "embedded";+ onCancel?: () => void;+ onDirtyChange?: (dirty: boolean) => void;+ onSaved?: (loop: LoopSchemas.Loop) => void;}-export function LoopForm({ loop }: LoopFormProps) {+export function LoopForm({+ loop,+ variant = "wizard",+ onCancel,+ onDirtyChange,+ onSaved,+}: LoopFormProps) {const isEdit = !!loop;+ const isEmbedded = variant === "embedded";const projectId = useAuthStateValue((state) => state.currentProjectId);const [values, setValues] = useState<LoopFormValues>(() => {if (loop) return normalizeLoopFormValues(loopToFormValues(loop));@@ -92,16 +120,48 @@ export function LoopForm({ loop }: LoopFormProps) {});});const [step, setStep] = useState(0);+ const [baseline, setBaseline] = useState<LoopFormBaseline | null>(() =>+ loop ? buildLoopFormBaseline(loop) : null,+ );+ const [hasRemoteUpdate, setHasRemoteUpdate] = useState(false);// Open when editing a loop that already pins a model, so the pinned value// is visible without hunting for it.const [showAdvanced, setShowAdvanced] = useState(() => !!(loop && (loop.model || loop.reasoning_effort)),);+ const isDirty = !!baseline && JSON.stringify(values) !== baseline.serialized;useEffect(() => {if (!loop) useLoopDraftStore.getState().setPrefill(null);}, [loop]);+ useEffect(() => {+ if (!loop) return;++ const nextBaseline = buildLoopFormBaseline(loop);+ if (!baseline || baseline.loopId !== loop.id) {+ setBaseline(nextBaseline);+ setValues(nextBaseline.values);+ setHasRemoteUpdate(false);+ return;+ }++ if (nextBaseline.updatedAt === baseline.updatedAt) return;++ if (isDirty) {+ setHasRemoteUpdate(true);+ return;+ }++ setBaseline(nextBaseline);+ setValues(nextBaseline.values);+ setHasRemoteUpdate(false);+ }, [loop, baseline, isDirty]);++ useEffect(() => {+ onDirtyChange?.(isDirty);+ }, [isDirty, onDirtyChange]);+// Contexts are a channels surface; hide the attachment UI when channels are// off, unless this loop is already attached so the link stays visible and// detachable.@@ -120,7 +180,8 @@ export function LoopForm({ loop }: LoopFormProps) {bundleSkill.isPending ||replaceSkillBundles.isPending ||deleteLoop.isPending;- const canSubmit = isLoopFormValid(values) && !isSubmitting;+ const canSubmit =+ isLoopFormValid(values) && !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.@@ -163,6 +224,10 @@ export function LoopForm({ loop }: LoopFormProps) {setValues((prev) => ({ ...prev, ...next }));const handleCancel = () => {+ if (onCancel) {+ onCancel();+ return;+ }if (isEdit) {navigateToLoopDetail(loop.id);} else {@@ -171,6 +236,12 @@ export function LoopForm({ loop }: LoopFormProps) {};const handleSubmit = async () => {+ if (hasRemoteUpdate) {+ toast.error("Loop changed elsewhere", {+ description: "Cancel and reopen editing before saving changes.",+ });+ return;+ }if (!canSubmit) return;const body = formValuesToLoopWrite(values);@@ -238,7 +309,11 @@ export function LoopForm({ loop }: LoopFormProps) {return;}}- navigateToLoopDetail(saved.id);+ if (onSaved) {+ onSaved(saved);+ } else {+ navigateToLoopDetail(saved.id);+ }} catch (error) {const safetyLimit =error instanceof LoopsApiError ? error.safetyLimit : null;@@ -261,6 +336,201 @@ export function LoopForm({ loop }: LoopFormProps) {}};+ if (isEmbedded) {+ return (+ <Flex+ direction="column"+ gap="4"+ className="rounded-(--radius-2) border border-border bg-(--gray-1) p-4"+ >+ <Step+ title="Prompt"+ description="Name it and write the prompt the agent runs each time."+ >+ <Field label="Name" required>+ <TextField.Root+ size="2"+ value={values.name}+ placeholder="Daily standup summary"+ disabled={isSubmitting}+ onChange={(e) => patch({ name: e.target.value })}+ />+ </Field>+ <Field label="Description">+ <TextArea+ value={values.description}+ placeholder="A short summary shown on the Loops list"+ disabled={isSubmitting}+ className="min-h-[72px] text-[13px] leading-relaxed"+ onChange={(e) => patch({ description: e.target.value })}+ />+ </Field>+ <LoopInstructionsFields+ values={values}+ disabled={isSubmitting}+ onPatch={patch}+ />+ </Step>++ <Divider />++ <Step+ title="When"+ description="Add automatic triggers, or leave this manual-only."+ >+ <LoopTriggerEditor+ triggers={values.triggers}+ triggerEndpointPath={triggerEndpointPath}+ disabled={isSubmitting}+ onChange={(triggers) => patch({ triggers })}+ />+ </Step>++ <Divider />++ <Step+ title="Options"+ description="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,+ })+ }+ />+ </Field>++ <Field+ label="Base repository"+ hint={+ values.repositories.length > 1+ ? `${values.repositories.length - 1} more attached.`+ : "Optional for report-only loops."+ }+ >+ <LoopRepositoryPicker+ value={values.repositories[0] ?? null}+ disabled={isSubmitting}+ onChange={(repository) =>+ setValues((prev) => ({+ ...prev,+ repositories: repository+ ? [repository, ...prev.repositories.slice(1)]+ : prev.repositories.slice(1),+ }))+ }+ />+ </Field>+ </div>++ {showContextField ? (+ <Field label="Context" hint="Attach runs to a sidebar channel.">+ <LoopContextFields+ value={values.contextTarget}+ disabled={isSubmitting}+ onChange={(contextTarget) =>+ patch(+ contextTarget+ ? { contextTarget, visibility: "team" }+ : { contextTarget },+ )+ }+ />+ </Field>+ ) : null}++ <Field label="Notifications">+ <LoopNotificationsFields+ notifications={values.notifications}+ disabled={isSubmitting}+ onChange={(notifications) => patch({ notifications })}+ />+ </Field>+ </Step>++ <Divider />++ <Step title="Advanced" description="Behavior, model, and reasoning.">+ <Field label="Behavior">+ <LoopBehaviorFields+ behaviors={values.behaviors}+ disabled={isSubmitting}+ onChange={(behaviors) => patch({ behaviors })}+ />+ </Field>+ <LoopModelFields+ adapter={values.runtimeAdapter}+ model={values.model}+ reasoningEffort={values.reasoningEffort}+ disabled={isSubmitting}+ onAdapterChange={(runtimeAdapter) => patch({ runtimeAdapter })}+ onModelChange={(model) => patch({ model })}+ onReasoningEffortChange={(reasoningEffort) =>+ patch({ reasoningEffort })+ }+ />+ </Step>++ {hasRemoteUpdate ? (+ <Flex+ direction="column"+ gap="1"+ className="rounded-(--radius-2) border border-(--amber-6) bg-(--amber-2) px-3 py-2"+ >+ <Text className="font-medium text-(--amber-12) text-[12.5px]">+ This loop changed elsewhere+ </Text>+ <Text className="text-(--amber-11) text-[12px] leading-snug">+ Cancel and reopen editing before saving, so you don't overwrite+ newer settings.+ </Text>+ </Flex>+ ) : null}++ <Flex+ align="center"+ justify="end"+ gap="2"+ className="sticky bottom-0 z-10 border-border border-t bg-(--gray-1) py-4"+ >+ <Button+ variant="soft"+ color="gray"+ size="2"+ disabled={isSubmitting}+ onClick={handleCancel}+ >+ Cancel+ </Button>+ <Button+ variant="solid"+ size="2"+ loading={isSubmitting}+ disabled={!canSubmit}+ onClick={() => void handleSubmit()}+ >+ Save changes+ </Button>+ </Flex>+ </Flex>+ );+ }+return (<Box className="flex h-full items-center justify-center p-6"><Flexdiff --git a/products/desktop/packages/ui/src/features/loops/components/LoopModelFields.tsx b/products/desktop/packages/ui/src/features/loops/components/LoopModelFields.tsxindex 7722fb06b32f..fb84cbd87fce 100644--- a/products/desktop/packages/ui/src/features/loops/components/LoopModelFields.tsx+++ b/products/desktop/packages/ui/src/features/loops/components/LoopModelFields.tsx@@ -1,7 +1,6 @@import type { LoopSchemas } from "@posthog/api-client/loops";import { GLM_MODEL_FLAG, KIMI_MODEL_FLAG } from "@posthog/shared";import { useFeatureFlag } from "@posthog/ui/features/feature-flags/useFeatureFlag";-import { ReasoningLevelDropdown } from "@posthog/ui/features/sessions/components/ReasoningLevelDropdown";import { SettingsOptionSelect } from "@posthog/ui/features/settings/SettingsOptionSelect";import { Flex } from "@radix-ui/themes";import { useMemo } from "react";@@ -129,10 +128,10 @@ export function LoopModelFields({</Field><Field label="Reasoning effort" className="min-w-[180px] flex-1">- <ReasoningLevelDropdown+ <SettingsOptionSelectvalue={reasoningEffort ?? AUTO_REASONING_VALUE}options={reasoningOptions}- onChange={(value) =>+ onValueChange={(value) =>onReasoningEffortChange(value === AUTO_REASONING_VALUE? null@@ -140,9 +139,8 @@ export function LoopModelFields({)}disabled={disabled}- side="bottom"- triggerVariant="outline"- triggerClassName="w-full justify-between text-[13px]"+ size="lg"+ ariaLabel="Reasoning effort"/></Field></Flex>diff --git a/products/desktop/packages/ui/src/features/loops/components/LoopNotificationsFields.tsx b/products/desktop/packages/ui/src/features/loops/components/LoopNotificationsFields.tsxindex ec20039d4c3b..da3e48601ec7 100644--- a/products/desktop/packages/ui/src/features/loops/components/LoopNotificationsFields.tsx+++ b/products/desktop/packages/ui/src/features/loops/components/LoopNotificationsFields.tsx@@ -46,20 +46,16 @@ export function LoopNotificationsFields({return (<Flex direction="column" gap="3">- <Text className="text-[12.5px] text-gray-10 leading-snug">- Each run and its full output live on this loop's page. Notifications- only send a short summary with a link when something happens.- </Text><NotificationChannelRowtitle="Push"- description="Sends a push notification to the loop owner's devices with PostHog installed."+ description="Owner devices"channel={notifications.push}disabled={disabled}onChange={(patch) => updateChannel("push", patch)}/><NotificationChannelRowtitle="Email"- description="Emails a run summary to the loop owner's account email."+ description="Owner account"channel={notifications.email}disabled={disabled}onChange={(patch) => updateChannel("email", patch)}@@ -91,13 +87,15 @@ function NotificationChannelRow({return (<Flexdirection="column"- gap="2"- className="rounded-(--radius-2) border border-border bg-(--gray-1) p-3"+ gap={channel.enabled ? "2" : "0"}+ className="rounded-(--radius-2) border border-border bg-(--gray-1) px-3 py-2.5"><Flex align="center" justify="between" gap="2">- <Flex direction="column" gap="0">+ <Flex align="baseline" gap="2" className="min-w-0"><Text className="font-medium text-[13px] text-gray-12">{title}</Text>- <Text className="text-[12px] text-gray-10">{description}</Text>+ <Text className="truncate text-[12px] text-gray-10">+ {description}+ </Text></Flex><Switchchecked={channel.enabled}@@ -116,7 +114,7 @@ function NotificationChannelRow({</Flex>{channel.enabled ? (- <Flex direction="column" gap="2">+ <Flex direction="column" gap="2" className="pt-2"><EventFilterCheckboxesevents={channel.events}disabled={disabled}@@ -201,7 +199,7 @@ function SlackNotificationRow({return (<NotificationChannelRowtitle="Slack"- description="Posts a run summary to the channel you pick, through this project's Slack connection."+ description="Channel summary"channel={channel}disabled={disabled}onChange={onChange}diff --git a/products/desktop/packages/ui/src/features/loops/components/LoopRepositoryPicker.tsx b/products/desktop/packages/ui/src/features/loops/components/LoopRepositoryPicker.tsxindex b6c622f8ffb8..04285b0d55c8 100644--- a/products/desktop/packages/ui/src/features/loops/components/LoopRepositoryPicker.tsx+++ b/products/desktop/packages/ui/src/features/loops/components/LoopRepositoryPicker.tsx@@ -53,6 +53,7 @@ export function LoopRepositoryPicker({placeholder="Select repository…"size="2"disabled={disabled || !hasGithubIntegration}+ triggerClassName="w-full max-w-[360px] justify-start"/>);}diff --git a/products/desktop/packages/ui/src/features/loops/components/LoopSkillFields.tsx b/products/desktop/packages/ui/src/features/loops/components/LoopSkillFields.tsxindex 1c4c3a932af3..869a44c52699 100644--- a/products/desktop/packages/ui/src/features/loops/components/LoopSkillFields.tsx+++ b/products/desktop/packages/ui/src/features/loops/components/LoopSkillFields.tsx@@ -217,11 +217,12 @@ export function LoopInstructionsFields({return (<>- <Field label="Prompt source" required>+ <Field label="Prompt source" required className="max-w-[260px]"><SettingsOptionSelectariaLabel="Prompt source"value={skill ? "skill" : "instructions"}disabled={disabled}+ size="lg"options={[{ value: "instructions", label: "Write instructions" },{ value: "skill", label: "Run a skill" },diff --git a/products/desktop/packages/ui/src/features/loops/components/LoopTriggerEditor.tsx b/products/desktop/packages/ui/src/features/loops/components/LoopTriggerEditor.tsxindex aa27187920d5..9e8dbde8b20d 100644--- a/products/desktop/packages/ui/src/features/loops/components/LoopTriggerEditor.tsx+++ b/products/desktop/packages/ui/src/features/loops/components/LoopTriggerEditor.tsx@@ -1,6 +1,7 @@import {CalendarBlank,Clock,+ DotsThreeVertical,GithubLogo,Globe,Plus,@@ -34,7 +35,7 @@ import {formatScheduleTimestamp,systemTimezone,} from "@posthog/ui/primitives/timezone";-import { Box, Checkbox, Flex, IconButton, Text } from "@radix-ui/themes";+import { Box, Checkbox, Flex, Text } from "@radix-ui/themes";import type { ReactNode } from "react";import {compileCronSchedule,@@ -224,15 +225,15 @@ function TriggerCard({return (<Flexdirection="column"- className="overflow-hidden rounded-(--radius-3) border border-border bg-(--gray-1)"+ className="overflow-hidden rounded-(--radius-2) border border-border bg-(--gray-1)">- <Flex align="center" gap="3" className="px-4 py-3">+ <Flex align="center" gap="2.5" className="px-3 py-2.5"><Flexalign="center"justify="center"- className="size-8 shrink-0 rounded-(--radius-2) bg-(--gray-3)"+ className="size-6 shrink-0 rounded-(--radius-1) bg-(--gray-3)">- <Icon size={16} className="text-gray-11" />+ <Icon size={14} className="text-gray-11" /></Flex><Flex direction="column" className="min-w-0 flex-1"><Text className="font-medium text-[13px] text-gray-12">@@ -248,20 +249,41 @@ function TriggerCard({disabled={disabled}aria-label={trigger.enabled ? "Disable trigger" : "Enable trigger"}/>- <IconButton- variant="ghost"- color="gray"- size="1"- aria-label="Remove trigger"- disabled={disabled}- onClick={onRemove}- >- <Trash size={15} />- </IconButton>+ <DropdownMenu>+ <DropdownMenuTrigger+ render={+ <Button+ type="button"+ variant="link-muted"+ size="sm"+ disabled={disabled}+ aria-label="Trigger actions"+ className="text-gray-10"+ >+ <DotsThreeVertical size={16} weight="bold" />+ </Button>+ }+ />+ <DropdownMenuContent align="end" side="bottom" sideOffset={6}>+ <DropdownMenuItem+ onClick={onRemove}+ render={+ <ItemMenuItem size="xs" className="w-full text-(--red-11)">+ <ItemMedia variant="icon" className="mt-2 ml-2">+ <Trash size={15} />+ </ItemMedia>+ <ItemContent variant="menuItem">+ <ItemTitle>Remove trigger</ItemTitle>+ </ItemContent>+ </ItemMenuItem>+ }+ />+ </DropdownMenuContent>+ </DropdownMenu></Flex><Box- className={`border-border border-t px-4 py-4 ${+ className={`border-border border-t px-3 py-3 ${trigger.enabled ? "" : "opacity-60"}`}>diff --git a/products/desktop/packages/ui/src/router/navigationBridge.ts b/products/desktop/packages/ui/src/router/navigationBridge.tsindex 4360eda4304e..1992d0fd8a03 100644--- a/products/desktop/packages/ui/src/router/navigationBridge.ts+++ b/products/desktop/packages/ui/src/router/navigationBridge.ts@@ -151,25 +151,26 @@ export function navigateToScoutFindings(): void {void getRouterOrNull()?.navigate({ to: "/code/agents/scouts/findings" });}-export function navigateToLoops(): void {- void getRouterOrNull()?.navigate({ to: "/code/loops" });+export function navigateToLoops(options?: { ignoreBlocker?: boolean }): void {+ void getRouterOrNull()?.navigate({+ to: "/code/loops",+ ignoreBlocker: options?.ignoreBlocker,+ });}export function navigateToNewLoop(): void {void getRouterOrNull()?.navigate({ to: "/code/loops/new" });}-export function navigateToLoopDetail(loopId: string): void {+export function navigateToLoopDetail(+ loopId: string,+ options?: { ignoreBlocker?: boolean; edit?: boolean },+): void {void getRouterOrNull()?.navigate({to: "/code/loops/$loopId",params: { loopId },- });-}--export function navigateToEditLoop(loopId: string): void {- void getRouterOrNull()?.navigate({- to: "/code/loops/$loopId/edit",- params: { loopId },+ search: options?.edit ? { edit: true } : {},+ ignoreBlocker: options?.ignoreBlocker,});}diff --git a/products/desktop/packages/ui/src/router/routes/code/loops/$loopId/edit.tsx b/products/desktop/packages/ui/src/router/routes/code/loops/$loopId/edit.tsxindex 1f00d3a71d27..a0dc897f4562 100644--- a/products/desktop/packages/ui/src/router/routes/code/loops/$loopId/edit.tsx+++ b/products/desktop/packages/ui/src/router/routes/code/loops/$loopId/edit.tsx@@ -1,5 +1,4 @@-import { EditLoopView } from "@posthog/ui/features/loops/components/EditLoopView";-import { createFileRoute } from "@tanstack/react-router";+import { createFileRoute, Navigate } from "@tanstack/react-router";export const Route = createFileRoute("/code/loops/$loopId/edit")({component: EditLoopRoute,@@ -7,5 +6,12 @@ export const Route = createFileRoute("/code/loops/$loopId/edit")({function EditLoopRoute() {const { loopId } = Route.useParams();- return <EditLoopView loopId={loopId} />;+ return (+ <Navigate+ replace+ to="/code/loops/$loopId"+ params={{ loopId }}+ search={{ edit: true }}+ />+ );}diff --git a/products/desktop/packages/ui/src/router/routes/code/loops/$loopId/index.tsx b/products/desktop/packages/ui/src/router/routes/code/loops/$loopId/index.tsxindex f409a7e6bbe1..90f48f3d80bb 100644--- a/products/desktop/packages/ui/src/router/routes/code/loops/$loopId/index.tsx+++ b/products/desktop/packages/ui/src/router/routes/code/loops/$loopId/index.tsx@@ -3,9 +3,13 @@ import { createFileRoute } from "@tanstack/react-router";export const Route = createFileRoute("/code/loops/$loopId/")({component: LoopDetailRoute,+ validateSearch: (search: Record<string, unknown>): { edit?: boolean } => ({+ edit: search.edit === true || search.edit === "true",+ }),});function LoopDetailRoute() {const { loopId } = Route.useParams();- return <LoopDetailView loopId={loopId} />;+ const { edit } = Route.useSearch();+ return <LoopDetailView loopId={loopId} startEditing={edit === true} />;}