From 561541e7b46a6aa52ca8570b2cc32db19b0d64e6 Mon Sep 17 00:00:00 2001
From: Ariver <shanghai3168@gmail.com>
Date: Thu, 28 May 2026 18:48:35 +0800
Subject: [PATCH] Consolidate app grid interaction state

---
 Scripts/window_logic_qa.sh |  334 +++++++++++++++++++++++++++++++++++++++++++++++++++++--
 1 files changed, 322 insertions(+), 12 deletions(-)

diff --git a/Scripts/window_logic_qa.sh b/Scripts/window_logic_qa.sh
index bb6877c..f93b3f2 100755
--- a/Scripts/window_logic_qa.sh
+++ b/Scripts/window_logic_qa.sh
@@ -14,6 +14,8 @@
 DEFAULTS_DOMAIN="$LAUNCH_AGENT_LABEL"
 SHOW_DOCK_ICON_WAS_SET=false
 SHOW_DOCK_ICON_VALUE=""
+APP_LANGUAGE_WAS_SET=false
+APP_LANGUAGE_VALUE=""
 FULLSCREEN_QA_PID=""
 CLICK_TOOL="${CLICK_TOOL:-$(command -v cliclick || true)}"
 
@@ -31,6 +33,10 @@
   if value="$(defaults read "$DEFAULTS_DOMAIN" showDockIcon 2>/dev/null)"; then
     SHOW_DOCK_ICON_WAS_SET=true
     SHOW_DOCK_ICON_VALUE="$value"
+  fi
+  if value="$(defaults read "$DEFAULTS_DOMAIN" appLanguage 2>/dev/null)"; then
+    APP_LANGUAGE_WAS_SET=true
+    APP_LANGUAGE_VALUE="$value"
   fi
 }
 
@@ -51,6 +57,12 @@
   else
     defaults delete "$DEFAULTS_DOMAIN" showDockIcon >/dev/null 2>&1 || true
   fi
+
+  if [[ "$APP_LANGUAGE_WAS_SET" == true ]]; then
+    defaults write "$DEFAULTS_DOMAIN" appLanguage -string "$APP_LANGUAGE_VALUE"
+  else
+    defaults delete "$DEFAULTS_DOMAIN" appLanguage >/dev/null 2>&1 || true
+  fi
 }
 
 restore_launch_agent_plist() {
@@ -64,6 +76,11 @@
   else
     rm -f "$LAUNCH_AGENT_PLIST"
   fi
+}
+
+reset_dock_for_qa() {
+  killall Dock >/dev/null 2>&1 || true
+  sleep 1.5
 }
 
 send_keycode() {
@@ -86,6 +103,26 @@
 
 send_cmd_w() {
   osascript -e 'tell application "System Events" to keystroke "w" using {command down}'
+}
+
+close_settings_window() {
+  osascript <<'OSA' >/dev/null 2>&1 || true
+tell application "System Events"
+  tell process "TagLauncher"
+    repeat 20 times
+      repeat with windowRef in windows
+        try
+          if (name of windowRef as text) is not "" then
+            click button 1 of windowRef
+            return
+          end if
+        end try
+      end repeat
+      delay 0.1
+    end repeat
+  end tell
+end tell
+OSA
 }
 
 dismiss_reopen_dialog() {
@@ -273,11 +310,13 @@
 
 assert_swift="$(mktemp -t taglauncher-window-assert.XXXXXX.swift)"
 coords_swift="$(mktemp -t taglauncher-window-coords.XXXXXX.swift)"
+settings_ax_swift="$(mktemp -t taglauncher-settings-ax.XXXXXX.swift)"
 screens_swift="$(mktemp -t taglauncher-screens.XXXXXX.swift)"
 fullscreen_swift="$(mktemp -t taglauncher-fullscreen-target.XXXXXX.swift)"
-trap 'cleanup; rm -f "$assert_swift" "$coords_swift" "$screens_swift" "$fullscreen_swift" "$LAUNCH_AGENT_BACKUP"' EXIT
+trap 'cleanup; rm -f "$assert_swift" "$coords_swift" "$settings_ax_swift" "$screens_swift" "$fullscreen_swift" "$LAUNCH_AGENT_BACKUP"' EXIT
 
 cat >"$assert_swift" <<'SWIFT'
+import AppKit
 import AppKit
 import CoreGraphics
 import Foundation
@@ -433,6 +472,107 @@
     }
     print("PASS fullscreen overlay above target: overlayLayer=\(tag[0].layer) targetLayer=\(target.layer)")
 
+case "fullscreen-settings":
+    guard tag.count == 2 else { fail("fullscreen settings expected 2 TagLauncher windows, got \(tag.count)") }
+    assertTagLayer(tag)
+    guard let target = windows.first(where: { $0.name == "TagLauncherFullscreenQATargetFullscreen" }) else {
+        fail("fullscreen target disappeared after opening settings; TagLauncher likely switched to another Space")
+    }
+    guard !tag[0].name.isEmpty, tag[1].name.isEmpty else {
+        fail("fullscreen settings order wrong: \(tag.map(\.name))")
+    }
+    guard tag.allSatisfy({ $0.layer > target.layer }) else {
+        fail("TagLauncher settings stack is not above fullscreen target")
+    }
+    print("PASS fullscreen settings above target: tagLayers=\(tag.map(\.layer)) targetLayer=\(target.layer)")
+
+case "split-geometry":
+    func isSingleFullscreenWindow(_ windowFrame: CGRect, on screenFrame: CGRect) -> Bool {
+        let widthMatches = abs(windowFrame.width - screenFrame.width) <= 12
+        let heightMatches = windowFrame.height >= screenFrame.height * 0.88
+        let horizontallyAligned = abs(windowFrame.midX - screenFrame.midX) <= 12
+        let verticallyAligned = abs(windowFrame.maxY - screenFrame.maxY) <= 32
+        return widthMatches && heightMatches && horizontallyAligned && verticallyAligned
+    }
+
+    func hasSplitViewFullscreenWindows(_ windows: [CGRect], on screenFrame: CGRect) -> Bool {
+        let clippedWindows = windows.map { $0.intersection(screenFrame) }
+        let tallWindows = clippedWindows
+            .filter { frame in
+                frame.height >= screenFrame.height * 0.86
+                    && frame.width >= screenFrame.width * 0.20
+                    && frame.width <= screenFrame.width * 0.86
+                    && abs(frame.maxY - screenFrame.maxY) <= 32
+            }
+            .sorted { $0.minX < $1.minX }
+
+        guard tallWindows.count >= 2 else { return false }
+
+        for startIndex in tallWindows.indices {
+            var union = tallWindows[startIndex]
+            var lastMaxX = union.maxX
+
+            for window in tallWindows.dropFirst(startIndex + 1) {
+                let gap = window.minX - lastMaxX
+                if gap < -32 || gap > 48 {
+                    break
+                }
+                union = union.union(window)
+                lastMaxX = max(lastMaxX, window.maxX)
+
+                let touchesLeft = abs(union.minX - screenFrame.minX) <= 32
+                let touchesRight = abs(union.maxX - screenFrame.maxX) <= 32
+                let coversWidth = union.width >= screenFrame.width * 0.92
+                let coversHeight = union.height >= screenFrame.height * 0.86
+                if touchesLeft && touchesRight && coversWidth && coversHeight {
+                    return true
+                }
+            }
+        }
+
+        return false
+    }
+
+    let screen = CGRect(x: 0, y: 0, width: 1710, height: 1112)
+    let single = CGRect(x: 0, y: 39, width: 1710, height: 1073)
+    let splitHalf = [
+        CGRect(x: 0, y: 39, width: 853, height: 1073),
+        CGRect(x: 857, y: 39, width: 853, height: 1073)
+    ]
+    let splitThird = [
+        CGRect(x: 0, y: 39, width: 568, height: 1073),
+        CGRect(x: 572, y: 39, width: 1138, height: 1073)
+    ]
+    let desktopTiledWithLargeGap = [
+        CGRect(x: 0, y: 90, width: 700, height: 900),
+        CGRect(x: 900, y: 90, width: 700, height: 900)
+    ]
+    let desktopSideBySideBelowDock = [
+        CGRect(x: 0, y: 39, width: 856, height: 983),
+        CGRect(x: 854, y: 39, width: 856, height: 983)
+    ]
+    let halfOnly = [CGRect(x: 0, y: 39, width: 853, height: 1073)]
+
+    guard isSingleFullscreenWindow(single, on: screen) else {
+        fail("split geometry expected single fullscreen window to match")
+    }
+    guard hasSplitViewFullscreenWindows(splitHalf, on: screen) else {
+        fail("split geometry expected 50/50 Split View to match")
+    }
+    guard hasSplitViewFullscreenWindows(splitThird, on: screen) else {
+        fail("split geometry expected 33/67 Split View to match")
+    }
+    guard !hasSplitViewFullscreenWindows(desktopTiledWithLargeGap, on: screen) else {
+        fail("split geometry should not match ordinary tiled desktop windows")
+    }
+    guard !hasSplitViewFullscreenWindows(desktopSideBySideBelowDock, on: screen) else {
+        fail("split geometry should not match side-by-side desktop windows below the Dock")
+    }
+    guard !hasSplitViewFullscreenWindows(halfOnly, on: screen) else {
+        fail("split geometry should not match a single half-width window")
+    }
+    print("PASS split fullscreen geometry detection")
+
 case "screen-count":
     print("INFO screens=\(NSScreen.screens.count) frames=\(NSScreen.screens.map { NSStringFromRect($0.frame) })")
 
@@ -442,12 +582,24 @@
 SWIFT
 
 cat >"$coords_swift" <<'SWIFT'
+import AppKit
 import CoreGraphics
 import Foundation
 
 let raw = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID) as? [[String: Any]] ?? []
 let tag = raw.filter { ($0[kCGWindowOwnerName as String] as? String) == "TagLauncher" }
 let mode = CommandLine.arguments.dropFirst().first ?? ""
+
+func dimension(_ bounds: NSDictionary, _ key: String) -> CGFloat {
+    if let value = bounds[key] as? CGFloat {
+        return value
+    }
+    if let value = bounds[key] as? NSNumber {
+        return CGFloat(truncating: value)
+    }
+    return 0
+}
+
 switch mode {
 case "data-tab":
     guard let settings = tag.first(where: { (($0[kCGWindowName as String] as? String) ?? "").isEmpty == false }),
@@ -457,7 +609,7 @@
         fputs("FAIL: could not find settings window bounds\n", stderr)
         exit(1)
     }
-    print("\(Int(round(x + 523))) \(Int(round(y + 50)))")
+    print("\(Int(round(x + 625))) \(Int(round(y + 50)))")
 case "export":
     guard let settings = tag.first(where: { (($0[kCGWindowName as String] as? String) ?? "").isEmpty == false }),
           let bounds = settings[kCGWindowBounds as String] as? NSDictionary,
@@ -468,16 +620,138 @@
     }
     print("\(Int(round(x + 375))) \(Int(round(y + 331)))")
 case "overlay-outside":
-    guard let overlay = tag.first(where: { (($0[kCGWindowName as String] as? String) ?? "").isEmpty }),
-          let overlayBounds = overlay[kCGWindowBounds as String] as? NSDictionary,
-          let overlayX = overlayBounds["X"] as? CGFloat,
-          let overlayY = overlayBounds["Y"] as? CGFloat else {
-        fputs("FAIL: could not find overlay window bounds\n", stderr)
+    guard let overlay = tag.max(by: { lhs, rhs in
+        let lhsBounds = lhs[kCGWindowBounds as String] as? NSDictionary ?? [:]
+        let rhsBounds = rhs[kCGWindowBounds as String] as? NSDictionary ?? [:]
+        let lhsArea = dimension(lhsBounds, "Width") * dimension(lhsBounds, "Height")
+        let rhsArea = dimension(rhsBounds, "Width") * dimension(rhsBounds, "Height")
+        return lhsArea < rhsArea
+    }), let overlayBounds = overlay[kCGWindowBounds as String] as? NSDictionary else {
+        let screen = NSScreen.screens.first?.frame ?? CGRect(x: 0, y: 0, width: 1200, height: 800)
+        print("\(Int(round(screen.minX + 120))) \(160)")
+        exit(0)
+    }
+    let overlayX = dimension(overlayBounds, "X")
+    let overlayY = dimension(overlayBounds, "Y")
+    print("\(Int(round(overlayX + 120))) \(Int(round(overlayY + 160)))")
+case "fullscreen-target-center":
+    guard let target = raw.first(where: { ($0[kCGWindowName as String] as? String) == "TagLauncherFullscreenQATargetFullscreen" }),
+          let bounds = target[kCGWindowBounds as String] as? NSDictionary else {
+        fputs("FAIL: could not find fullscreen target bounds\n", stderr)
         exit(1)
     }
-    print("\(Int(round(overlayX + 120))) \(Int(round(overlayY + 160)))")
+    let x = dimension(bounds, "X")
+    let y = dimension(bounds, "Y")
+    let width = dimension(bounds, "Width")
+    let height = dimension(bounds, "Height")
+    print("\(Int(round(x + width / 2))) \(Int(round(y + height / 2)))")
 default:
     fputs("FAIL: unknown coords mode \(mode)\n", stderr)
+    exit(1)
+}
+SWIFT
+
+cat >"$settings_ax_swift" <<'SWIFT'
+import AppKit
+import ApplicationServices
+import Foundation
+
+let mode = CommandLine.arguments.dropFirst().first ?? ""
+let bundleID = "com.taglauncher.app"
+
+guard let app = NSRunningApplication.runningApplications(withBundleIdentifier: bundleID).first else {
+    fputs("FAIL: TagLauncher is not running\n", stderr)
+    exit(1)
+}
+
+let root = AXUIElementCreateApplication(app.processIdentifier)
+
+func copyAttribute(_ element: AXUIElement, _ attribute: CFString) -> CFTypeRef? {
+    var value: CFTypeRef?
+    let result = AXUIElementCopyAttributeValue(element, attribute, &value)
+    guard result == .success else { return nil }
+    return value
+}
+
+func stringAttribute(_ element: AXUIElement, _ attribute: CFString) -> String? {
+    copyAttribute(element, attribute) as? String
+}
+
+func titleCandidates(for element: AXUIElement) -> [String] {
+    [
+        stringAttribute(element, kAXTitleAttribute as CFString),
+        stringAttribute(element, kAXDescriptionAttribute as CFString),
+        stringAttribute(element, kAXValueAttribute as CFString),
+        stringAttribute(element, kAXHelpAttribute as CFString)
+    ].compactMap { $0 }.filter { !$0.isEmpty }
+}
+
+func children(of element: AXUIElement) -> [AXUIElement] {
+    if let values = copyAttribute(element, kAXChildrenAttribute as CFString) as? [AXUIElement] {
+        return values
+    }
+    return []
+}
+
+func matches(_ element: AXUIElement, candidates: [String]) -> Bool {
+    let role = stringAttribute(element, kAXRoleAttribute as CFString) ?? ""
+    let titles = titleCandidates(for: element)
+    guard !titles.isEmpty else { return false }
+    let interactiveRole = role == kAXButtonRole as String
+        || role == kAXRadioButtonRole as String
+        || role == kAXTabGroupRole as String
+        || role == kAXMenuItemRole as String
+    guard interactiveRole else { return false }
+    return titles.contains { title in
+        candidates.contains { candidate in
+            title == candidate || title.localizedCaseInsensitiveContains(candidate)
+        }
+    }
+}
+
+func findMatchingElement(
+    _ element: AXUIElement,
+    candidates: [String],
+    depth: Int,
+    visited: inout Set<CFHashCode>
+) -> AXUIElement? {
+    guard depth >= 0 else { return nil }
+    let hash = CFHash(element)
+    guard !visited.contains(hash) else { return nil }
+    visited.insert(hash)
+
+    if matches(element, candidates: candidates) {
+        return element
+    }
+
+    for child in children(of: element) {
+        if let match = findMatchingElement(child, candidates: candidates, depth: depth - 1, visited: &visited) {
+            return match
+        }
+    }
+    return nil
+}
+
+let candidates: [String]
+switch mode {
+case "data-tab":
+    candidates = ["Data"]
+case "export":
+    candidates = ["Export"]
+default:
+    fputs("FAIL: unknown settings action \(mode)\n", stderr)
+    exit(1)
+}
+
+var visited = Set<CFHashCode>()
+guard let element = findMatchingElement(root, candidates: candidates, depth: 12, visited: &visited) else {
+    fputs("FAIL: could not find settings control for \(mode)\n", stderr)
+    exit(1)
+}
+
+let result = AXUIElementPerformAction(element, kAXPressAction as CFString)
+guard result == .success else {
+    fputs("FAIL: could not press settings control for \(mode): \(result.rawValue)\n", stderr)
     exit(1)
 }
 SWIFT
@@ -604,6 +878,14 @@
   click_xy "$x" "$y"
 }
 
+click_settings_control() {
+  local mode="$1"
+  if swift "$settings_ax_swift" "$mode" >/dev/null 2>&1; then
+    return 0
+  fi
+  click_relative_to_settings "$mode"
+}
+
 click_overlay_outside_quick_search() {
   local coords
   coords="$(swift "$coords_swift" overlay-outside)"
@@ -641,11 +923,21 @@
   return 1
 }
 
+move_pointer_to_fullscreen_target() {
+  local coords
+  coords="$(swift "$coords_swift" fullscreen-target-center)"
+  read -r x y <<<"$coords"
+  move_xy "$x" "$y"
+  sleep 0.2
+}
+
 log "==> Building app"
 bash "$ROOT_DIR/build.sh" >/dev/null
 
 log "==> Preparing QA defaults"
 defaults write "$DEFAULTS_DOMAIN" showDockIcon -bool true
+defaults write "$DEFAULTS_DOMAIN" appLanguage -string en
+reset_dock_for_qa
 
 log "==> Starting clean app instance"
 prepare_isolated_app_instance
@@ -669,9 +961,12 @@
 sleep 2.0
 assert_single_qa_app_instance
 assert_single_dock_tile
-send_keycode 53
+kill_all_taglauncher_instances
 sleep 0.4
-wait_swift_assert no-overlay
+swift_assert no-overlay
+
+log "==> QA split-view fullscreen geometry detection"
+swift_assert split-geometry
 
 run_fullscreen_space_case() {
   local dock_value="$1"
@@ -679,9 +974,24 @@
   defaults write "$DEFAULTS_DOMAIN" showDockIcon -bool "$dock_value"
   prepare_isolated_app_instance
   start_fullscreen_qa_target
+  move_pointer_to_fullscreen_target
   send_main_hotkey
   wait_swift_assert fullscreen-overlay
   assert_fullscreen_overlay_stable
+  log "==> QA fullscreen Space: quick search from appgrid does not switch Space"
+  send_keycode 49
+  sleep 0.4
+  assert_fullscreen_overlay_stable
+  send_keycode 53
+  sleep 0.3
+  wait_swift_assert fullscreen-overlay
+  log "==> QA fullscreen Space: settings from appgrid does not switch Space"
+  send_cmd_comma
+  sleep 0.7
+  wait_swift_assert fullscreen-settings
+  close_settings_window
+  sleep 0.5
+  wait_swift_assert fullscreen-overlay
   send_keycode 53
   sleep 0.4
   wait_swift_assert no-overlay
@@ -709,9 +1019,9 @@
 swift_assert settings
 
 log "==> QA 2/7: import/export file panel floats above settings"
-click_relative_to_settings data-tab
+click_settings_control data-tab
 sleep 0.3
-click_relative_to_settings export
+click_settings_control export
 sleep 0.7
 swift_assert file-panel
 send_keycode 53

--
Gitblit v1.9.3