I've update the code a bit so that it first tries to bring the app in front, if it is not focussed.
Some apps have a different title so i had to hack it a bit.
on alfred_script(q)
try
if application q is running then
tell application "System Events"
set vis to the visible of process q
-- get the active window name
set activeApp to name of first application process whose frontmost is true
end tell
-- Code active window seems to be Electron, working around that in a hacky way
-- similar for Teams
if activeApp is "Electron" then
display notification "Code workaround"
set activeApp to "Code"
else if activeApp is "Teams" then
display notification "Teams workaround"
set activeApp to "Microsoft Teams"
end if
if vis then
if activeApp is q then
display notification "hiding focused app"
tell app "System Events" to set visible of process q to false
else
display notification "focusing app, currently we have " & activeApp
tell application "System Events"
tell process q
set frontmost to true
end tell
end tell
end if
else
display notification "showing app"
tell application q to activate
end if
else
display notification "not running"
tell application q to activate
end if
on error
display notification "ups, got an error. Contact developer."
end try
return q
end alfred_script