@@ -4,6 +4,7 @@ import { SettingsOptionSelect } from "@posthog/ui/features/settings/SettingsOpti
44import { useHostCapabilities } from "@posthog/ui/shell/useHostCapabilities" ;
55import { TextArea } from "@radix-ui/themes" ;
66import { useQuery } from "@tanstack/react-query" ;
7+ import { useRef } from "react" ;
78import type { LoopFormValues } from "../loopFormTypes" ;
89import type { LoopSkillDraft } from "../loopSkill" ;
910import { Field } from "./LoopFormPrimitives" ;
@@ -41,6 +42,7 @@ export function LoopInstructionsFields({
4142} ) {
4243 const { localWorkspaces } = useHostCapabilities ( ) ;
4344 const trpc = useHostTRPC ( ) ;
45+ const lastSkill = useRef < LoopSkillDraft | null > ( values . skill ) ;
4446 const { data : localSkillData } = useQuery ( {
4547 ...trpc . skills . list . queryOptions ( ) ,
4648 enabled : localWorkspaces ,
@@ -94,10 +96,17 @@ export function LoopInstructionsFields({
9496
9597 const handleModeChange = ( mode : string ) => {
9698 if ( mode === "skill" ) {
97- const first = localSkills [ 0 ] ;
98- if ( ! first ) return ;
99- onPatch ( { skill : { kind : "local" , ...first } } ) ;
99+ // Restore whatever was picked before the toggle away; defaulting to the
100+ // first local skill would silently swap the loop onto an unrelated one.
101+ const restored =
102+ lastSkill . current ??
103+ ( localSkills [ 0 ] ? { kind : "local" as const , ...localSkills [ 0 ] } : null ) ;
104+ if ( ! restored ) return ;
105+ onPatch ( { skill : restored } ) ;
100106 } else {
107+ if ( skill ) {
108+ lastSkill . current = skill ;
109+ }
101110 onPatch ( { skill : null } ) ;
102111 }
103112 } ;
@@ -106,7 +115,9 @@ export function LoopInstructionsFields({
106115 if ( value === ATTACHED_OPTION_VALUE ) return ;
107116 const picked = localSkills . find ( ( local ) => local . path === value ) ;
108117 if ( picked ) {
109- onPatch ( { skill : { kind : "local" , ...picked } } ) ;
118+ const draft : LoopSkillDraft = { kind : "local" , ...picked } ;
119+ lastSkill . current = draft ;
120+ onPatch ( { skill : draft } ) ;
110121 }
111122 } ;
112123
0 commit comments