I just realized that this is a different thread than I expected.
I had my problems with this script too. So I developed a preset which got rid of most of the quirks (not all though).
Try to install the preset and see if it works better for you:
One example for the quirks are, that some settings windows from Menubar-Apps are never registered as frontmost and do not close with the red button. For example 'AlDente' in my case. So whenever I need to change anything in this app I have to deactivate/activate BTT.
Another thing.
You can always open the Hovered/Focused UI Element Viewer to see what windows is registered as frontmost/hovered.
You get there by clicking on your trigger > Advanced Conditions (right panel) > Hovered/Focused UI Element Viewer.
tell application "System Events"
set activeProcesses to first process where it is frontmost
-- Get the name of the frontmost application
set frontAppName to name of activeProcesses
-- List of apps that should use default window closing behavior
set defaultCloseApps to {"Finder", "Slack", "WhatsApp", "Mail","Google Chrome","Google Chrome Canary"}
repeat with theProcess in activeProcesses
if not background only of theProcess then
tell theProcess
set processName to name
set theWindows to windows
end tell
set windowsCount to count of theWindows
end if
end repeat
end tell
-- Check if the frontmost app is in our list of special apps
if defaultCloseApps contains frontAppName then
tell application "System Events"
click button 1 of window 1 of process frontAppName
end tell
else
-- For all other apps, use the original logic
if windowsCount is less than or equal to 1 then
tell application (get path to frontmost application as text)
quit
end tell
else
tell application "System Events"
keystroke "w" using command down
end tell
end if
end if