From a7f2f5f48368c92bf135a64b8c31fe2d389a672f Mon Sep 17 00:00:00 2001
From: Ariver <shanghai3168@gmail.com>
Date: Wed, 03 Jun 2026 21:52:55 +0800
Subject: [PATCH] Prepare 7.8.11 quick search release

---
 Apptag/ContentView.swift | 1527 ++++++++++++++++++++--------------------------------------
 1 files changed, 536 insertions(+), 991 deletions(-)

diff --git a/Apptag/ContentView.swift b/Apptag/ContentView.swift
index 7ba68bf..0fbfc7f 100644
--- a/Apptag/ContentView.swift
+++ b/Apptag/ContentView.swift
@@ -1,6 +1,5 @@
 import SwiftUI
 import AppKit
-import UniformTypeIdentifiers
 
 // MARK: - Notification for manual re-index
 
@@ -305,6 +304,25 @@
     let arrowOffset: CGFloat
 }
 
+private struct AppGridInteractionState {
+    var appDragModeActive = false
+    var dropWarningToast: String? = nil
+    var dropRefreshVisible = false
+    var dropRefreshStartedAt: Date? = nil
+    var hoveredBubble: AppBubbleContext? = nil
+    var editingBubble: AppBubbleContext? = nil
+    var pendingUncategorizedDrop: PendingUncategorizedDrop? = nil
+    var pendingTagRemovalDrop: PendingTagRemovalDrop? = nil
+    var uncategorizedDropSuppressFuturePrompt = false
+    var tagRemovalDropSuppressFuturePrompt = false
+    var appDragResetToken = 0
+    var bubbleDraftNote = ""
+    var tagNavigationHoveredGroupName: String? = nil
+    var tagNavigationAppDropTargetName: String? = nil
+    var tagNavigationLastHoverScrollID: String? = nil
+    var tagNavigationLastHoverScrollAt: Date? = nil
+}
+
 private struct EditActionFeedback: Identifiable {
     let id = UUID()
     let title: String
@@ -315,20 +333,13 @@
     let id = UUID()
     let app: AppInfo
     let assignedTags: [String]
+    let removableTags: [String]
 }
 
-private enum SmartStartNoticeMode {
-    case autoApplied
-    case suggestionOnly
-    case manuallyApplied
-}
-
-private struct SmartStartNotice: Identifiable {
+private struct PendingTagRemovalDrop: Identifiable {
     let id = UUID()
-    let mode: SmartStartNoticeMode
-    let title: String
-    let message: String
-    let summary: SmartStartSummary
+    let app: AppInfo
+    let tagName: String
 }
 
 struct ContentView: View {
@@ -339,11 +350,7 @@
     @State private var allApps: [AppInfo] = []
     @State private var displayGroups: [TagGroup] = []
     @State private var tagColors: [String: Int] = [:]
-    @State private var scrollProxy: ScrollViewProxy? = nil
-    @StateObject private var scrollInteractionState = AppGridScrollInteractionState()
     @State private var groupLayoutVersion = 0
-    @State private var cachedGridContainerRowsKey: GridContainerRowsKey? = nil
-    @State private var cachedGridContainerRows: [GridContainerLayoutRow] = []
     @State private var appGridScrollTargetID: String? = nil
     @State private var appGridScrollRequestToken = 0
 
@@ -361,23 +368,14 @@
     @State private var tagNavDragItem: String? = nil
     @State private var tagNavReorderFrames: [String: CGRect] = [:]
     @State private var tagNavReorderDidMove = false
-    @State private var hoveredContainer: String? = nil  // colored container lift
     // Fixed interaction for "Colorless Container": hover fills persistently; click clears.
     @State private var filledColorlessContainer: String? = nil
-    @State private var appDragModeActive = false
-    @State private var dropWarningToast: String? = nil
+    @State private var appGridInteraction = AppGridInteractionState()
     @State private var smartStartNotice: SmartStartNotice? = nil
     @State private var pendingSmartStartDraft: SmartCategorizationDraft? = nil
-    @State private var dropRefreshVisible = false
-    @State private var dropRefreshStartedAt: Date? = nil
     @State private var refreshInProgress = false
     @State private var refreshAgainAfterCurrent = false
     @State private var refreshAgainForceLayout = false
-    @State private var hoveredBubble: AppBubbleContext? = nil
-    @State private var editingBubble: AppBubbleContext? = nil
-    @State private var pendingUncategorizedDrop: PendingUncategorizedDrop? = nil
-    @State private var appDragResetToken = 0
-    @State private var bubbleDraftNote = ""
     @FocusState private var bubbleNoteFocused: Bool
 
     // Quick Search
@@ -390,6 +388,7 @@
     @State private var quickSearchFocusToken = 0
     @State private var quickSearchSelectionScrollToken = 0
     @State private var quickSearchCloseHidesOverlay = false
+    @State private var quickSearchOnlySession = false
     @State private var quickSearchErrorMessage: String? = nil
     @State private var initialQuickSearchConsumed = false
 
@@ -397,8 +396,10 @@
         self.hideOverlay = hideOverlay
         self.initialQuickSearchSource = initialQuickSearchSource
         let startsInQuickSearch = initialQuickSearchSource != nil
+        let startsInQuickSearchOnlySession = initialQuickSearchSource == QuickSearchOpenSource.globalHidden
         _quickSearchVisible = State(initialValue: startsInQuickSearch)
-        _quickSearchCloseHidesOverlay = State(initialValue: initialQuickSearchSource == QuickSearchOpenSource.globalHidden)
+        _quickSearchCloseHidesOverlay = State(initialValue: startsInQuickSearchOnlySession)
+        _quickSearchOnlySession = State(initialValue: startsInQuickSearchOnlySession)
         _quickSearchFocusToken = State(initialValue: startsInQuickSearch ? 1 : 0)
     }
 
@@ -411,21 +412,25 @@
     @AppStorage("displayMode") private var displayMode = AppDefaults.displayMode
     @AppStorage("hideAppNames") private var hideAppNames = AppDefaults.hideAppNames
     @AppStorage("showUncommonAppBubbles") private var showUncommonAppBubbles = AppDefaults.showUncommonAppBubbles
+    @AppStorage("useAppKitTagNavigation") private var useAppKitTagNavigation = AppDefaults.useAppKitTagNavigation
+    @AppStorage("skipTagRemovalDropConfirm") private var skipTagRemovalDropConfirm = false
+    @AppStorage("skipUncategorizedDropConfirm") private var skipUncategorizedDropConfirm = false
 
     private let editSidebarWidth: CGFloat = 188
     private let editSidebarHorizontalInset: CGFloat = 12
     private let floatingControlsTrailingInset: CGFloat = 20
     private let floatingControlsReservedWidth: CGFloat = 120
     private var appBubbleDisabled: Bool {
-        appDragModeActive || pendingUncategorizedDrop != nil || scrollInteractionState.isFrozen
+        appGridInteraction.appDragModeActive
+            || appGridInteraction.pendingUncategorizedDrop != nil
+            || appGridInteraction.pendingTagRemovalDrop != nil
+    }
+    private var appGridHighlightedGroupName: String? {
+        appGridInteraction.tagNavigationHoveredGroupName
+            ?? (isColorlessContainerMode ? filledColorlessContainer : nil)
     }
     private let rightSidebarFloatingClearance: CGFloat = 44
-
-    private var cardSurfaceColor: Color {
-        colorScheme == .dark
-            ? Color.white.opacity(0.055)
-            : Color.white.opacity(0.62)
-    }
+    private let tagNavigationHoverScrollInterval: TimeInterval = 0.22
 
     private var floatingButtonSurfaceColor: Color {
         colorScheme == .dark
@@ -445,23 +450,22 @@
         displayMode == "container" || displayMode == "gridContainer"
     }
 
-    private var isColoredContainerMode: Bool {
-        displayMode == "coloredContainer" || displayMode == "coloredGridContainer"
-    }
-
-    private var usesAppKitContainerGrid: Bool {
-        displayMode == "gridContainer" || displayMode == "coloredGridContainer"
+    private var shouldRenderAppGridBehindQuickSearch: Bool {
+        if quickSearchOnlySession {
+            return false
+        }
+        return !quickSearchVisible || !quickSearchCloseHidesOverlay
     }
 
     var body: some View {
         ZStack {
-            if !quickSearchVisible {
+            if shouldRenderAppGridBehindQuickSearch {
                 VisualEffectView(material: .hudWindow, blendingMode: .behindWindow)
                     .ignoresSafeArea()
                     .allowsHitTesting(false)
             }
 
-            if !quickSearchVisible {
+            if shouldRenderAppGridBehindQuickSearch {
                 if notchHeight > 0 {
                     VStack {
                         Rectangle().fill(.black)
@@ -485,11 +489,12 @@
                 smartStartNoticeOverlay
                 editActionFeedbackOverlay
                 uncategorizedDropConfirmOverlay
+                tagRemovalDropConfirmOverlay
             }
 
             quickSearchOverlay
 
-            if !quickSearchVisible, let message = dropWarningToast {
+            if shouldRenderAppGridBehindQuickSearch, let message = appGridInteraction.dropWarningToast {
                 Text(message)
                     .font(.system(size: 16, weight: .semibold))
                     .foregroundStyle(.primary)
@@ -504,7 +509,7 @@
                     .allowsHitTesting(false)
             }
 
-            if !quickSearchVisible && dropRefreshVisible {
+            if shouldRenderAppGridBehindQuickSearch && appGridInteraction.dropRefreshVisible {
                 Color.black.opacity(0.08)
                     .ignoresSafeArea()
                     .transition(.opacity)
@@ -529,7 +534,10 @@
             refreshAppsIfNeeded()
             if let initialQuickSearchSource, !initialQuickSearchConsumed {
                 initialQuickSearchConsumed = true
-                quickSearchCloseHidesOverlay = initialQuickSearchSource == QuickSearchOpenSource.globalHidden
+                if initialQuickSearchSource == QuickSearchOpenSource.globalHidden {
+                    quickSearchCloseHidesOverlay = true
+                    quickSearchOnlySession = true
+                }
                 if !quickSearchVisible {
                     quickSearchVisible = true
                     quickSearchFocusToken &+= 1
@@ -538,7 +546,10 @@
                 NotificationCenter.default.post(
                     name: .tagLauncherQuickSearchVisibilityChanged,
                     object: nil,
-                    userInfo: ["active": true]
+                    userInfo: [
+                        "active": true,
+                        "hideOverlayOnClose": quickSearchCloseHidesOverlay
+                    ]
                 )
             }
         }
@@ -550,6 +561,8 @@
         .onReceive(NotificationCenter.default.publisher(for: .tagLauncherOverlayDidHide)) { _ in
             resetTransientDragState()
             closeQuickSearch(notify: true, hideOverlayIfNeeded: false)
+            quickSearchOnlySession = false
+            quickSearchCloseHidesOverlay = false
         }
         .onReceive(NotificationCenter.default.publisher(for: .tagLauncherQuickSearchRequested)) { notification in
             let source = notification.userInfo?["source"] as? String ?? QuickSearchOpenSource.mainOverlay
@@ -584,7 +597,7 @@
             )
         }
         .onChange(of: bubbleNoteFocused) { _, focused in
-            if editingBubble != nil && !focused {
+            if appGridInteraction.editingBubble != nil && !focused {
                 commitBubbleNote()
             }
         }
@@ -598,12 +611,11 @@
             quickSearchErrorMessage = nil
             refreshQuickSearchResults()
         }
-        .onChange(of: pendingUncategorizedDrop != nil) { _, active in
-            NotificationCenter.default.post(
-                name: .tagLauncherModalInteractionChanged,
-                object: nil,
-                userInfo: ["active": active]
-            )
+        .onChange(of: appGridInteraction.pendingUncategorizedDrop != nil) { _, _ in
+            publishModalInteractionState()
+        }
+        .onChange(of: appGridInteraction.pendingTagRemovalDrop != nil) { _, _ in
+            publishModalInteractionState()
         }
         .onDisappear {
             NotificationCenter.default.post(
@@ -612,6 +624,14 @@
                 userInfo: ["active": false]
             )
         }
+    }
+
+    private func publishModalInteractionState() {
+        NotificationCenter.default.post(
+            name: .tagLauncherModalInteractionChanged,
+            object: nil,
+            userInfo: ["active": appGridInteraction.pendingUncategorizedDrop != nil || appGridInteraction.pendingTagRemovalDrop != nil]
+        )
     }
 
     /// Set edit phase with synchronous notification BEFORE state change.
@@ -647,7 +667,7 @@
                     }
                     .zIndex(899)
 
-                QuickSearchOverlayView(
+                QuickSearchPanelPresentationView(
                     query: $quickSearchQuery,
                     results: quickSearchResults,
                     selectedID: quickSearchSelectedID,
@@ -655,16 +675,15 @@
                     selectionScrollToken: quickSearchSelectionScrollToken,
                     isLoading: quickSearchDocuments.isEmpty && refreshInProgress,
                     maxVisibleRows: quickSearchMaxVisibleRows(in: proxy.size),
+                    panelTopY: quickSearchPanelTopY(in: proxy.size),
+                    panelHeight: quickSearchPanelContentHeight(in: proxy.size),
                     errorMessage: quickSearchErrorMessage,
                     onCommand: handleQuickSearchCommand,
                     onHover: selectQuickSearchResult,
                     onLaunch: launchQuickSearchResult
                 )
-                .position(
-                    x: proxy.size.width / 2,
-                    y: quickSearchPanelCenterY(in: proxy.size)
-                )
-                .transition(.scale(scale: 0.98).combined(with: .opacity))
+                .frame(width: 0, height: 0)
+                .allowsHitTesting(false)
                 .zIndex(900)
             }
         }
@@ -672,10 +691,15 @@
         .animation(.easeOut(duration: 0.12), value: quickSearchVisible)
     }
 
-    private func quickSearchPanelCenterY(in size: CGSize) -> CGFloat {
-        let visibleRows = max(1, min(quickSearchResults.isEmpty ? 1 : quickSearchResults.count, quickSearchMaxVisibleRows(in: size)))
-        let estimatedPanelHeight = CGFloat(visibleRows) * 76 + 122
-        return quickSearchPanelTopY(in: size) + estimatedPanelHeight / 2
+    private func quickSearchPanelContentHeight(in size: CGSize) -> CGFloat {
+        let hasResultList = !(quickSearchDocuments.isEmpty && refreshInProgress)
+            && quickSearchErrorMessage == nil
+            && !quickSearchResults.isEmpty
+        let visibleRows = min(max(1, quickSearchResults.count), quickSearchMaxVisibleRows(in: size))
+        return QuickSearchPanelMetrics.contentHeight(
+            hasResultList: hasResultList,
+            visibleRows: visibleRows
+        )
     }
 
     private func quickSearchPanelTopY(in size: CGSize) -> CGFloat {
@@ -684,8 +708,11 @@
 
     private func quickSearchMaxVisibleRows(in size: CGSize) -> Int {
         let bottomClearance: CGFloat = 84
-        let chromeHeight: CGFloat = 122
-        let rowHeightWithSpacing: CGFloat = 76
+        let chromeHeight = QuickSearchPanelMetrics.headerHeight
+            + QuickSearchPanelMetrics.dividerHeight
+            + QuickSearchPanelMetrics.resultListVerticalInset * 2
+        let rowHeightWithSpacing = QuickSearchPanelMetrics.rowHeight
+            + QuickSearchPanelMetrics.rowSpacing
         let availableHeight = max(0, size.height - quickSearchPanelTopY(in: size) - bottomClearance - chromeHeight)
         return max(1, min(8, Int(floor(availableHeight / rowHeightWithSpacing))))
     }
@@ -693,25 +720,33 @@
     private func openQuickSearch(source: String) {
         guard canOpenQuickSearch else { return }
         dismissAppBubble()
-        quickSearchCloseHidesOverlay = source == QuickSearchOpenSource.globalHidden
+        if source == QuickSearchOpenSource.globalHidden {
+            quickSearchOnlySession = true
+        }
+        quickSearchCloseHidesOverlay = quickSearchCloseHidesOverlay
+            || source == QuickSearchOpenSource.globalHidden
         quickSearchVisible = true
         quickSearchQuery = ""
         quickSearchManualSelection = false
         quickSearchErrorMessage = nil
         quickSearchFocusToken &+= 1
         refreshQuickSearchResults()
+        refreshApps()
         NotificationCenter.default.post(
             name: .tagLauncherQuickSearchVisibilityChanged,
             object: nil,
-            userInfo: ["active": true]
+            userInfo: [
+                "active": true,
+                "hideOverlayOnClose": quickSearchCloseHidesOverlay
+            ]
         )
     }
 
     private var canOpenQuickSearch: Bool {
         editPhase == .none
-            && pendingUncategorizedDrop == nil
+            && appGridInteraction.pendingUncategorizedDrop == nil
             && smartStartNotice == nil
-            && !dropRefreshVisible
+            && !appGridInteraction.dropRefreshVisible
             && !quickSearchVisible
     }
 
@@ -724,22 +759,29 @@
         quickSearchSelectedID = nil
         quickSearchManualSelection = false
         quickSearchErrorMessage = nil
-        quickSearchCloseHidesOverlay = false
         if notify {
             NotificationCenter.default.post(
                 name: .tagLauncherQuickSearchVisibilityChanged,
                 object: nil,
-                userInfo: ["active": false]
+                userInfo: [
+                    "active": false,
+                    "hideOverlayOnClose": shouldHideOverlay
+                ]
             )
         }
         if shouldHideOverlay {
             hideOverlay()
+        } else {
+            quickSearchCloseHidesOverlay = false
         }
     }
 
     private func refreshQuickSearchResults() {
         let previousSelection = quickSearchSelectedID
-        quickSearchResults = QuickSearchEngine.search(quickSearchQuery, documents: quickSearchDocuments)
+        quickSearchResults = QuickSearchEngine.search(
+            quickSearchQuery,
+            documents: quickSearchDocuments.filter { FileManager.default.fileExists(atPath: $0.app.path.path) }
+        )
 
         if quickSearchResults.isEmpty {
             quickSearchSelectedID = nil
@@ -857,7 +899,7 @@
     private var topLayout: some View {
         VStack(spacing: 0) {
             Spacer().frame(height: notchHeight > 0 ? notchHeight + 14 : 28)
-            if !tagLabels.isEmpty { tagBar.padding(.bottom, 8) }
+            if !tagLabels.isEmpty { topTagNavigation.padding(.bottom, 8) }
             Divider().opacity(0.3)
             appGridContent
         }
@@ -868,14 +910,91 @@
             Spacer().frame(height: notchHeight > 0 ? notchHeight + 14 : 28)
             Divider().opacity(0.3)
             HStack(spacing: 0) {
-                if tagPosition == "left" { tagSidebar; sideDivider }
+                if tagPosition == "left" { leftTagSidebar; sideDivider }
                 appGridContent
                 if tagPosition == "right" { sideDivider; rightTagSidebar }
             }
         }
     }
 
-    private var tagBar: some View {
+    private var topTagNavigation: some View {
+        Group {
+            if useAppKitTagNavigation {
+                appKitTagNavigation(orientation: .horizontal)
+                    .frame(height: 34)
+            } else {
+                swiftUITopTagBar
+            }
+        }
+    }
+
+    private var leftTagSidebar: some View {
+        Group {
+            if useAppKitTagNavigation {
+                appKitTagNavigation(orientation: .vertical)
+            } else {
+                swiftUITagSidebarList
+            }
+        }
+        .frame(width: 135)
+    }
+
+    private var rightTagSidebar: some View {
+        Group {
+            if useAppKitTagNavigation {
+                appKitTagNavigation(orientation: .vertical)
+            } else {
+                swiftUITagSidebarList
+            }
+        }
+        .padding(.top, rightSidebarFloatingClearance)
+        .frame(width: 135)
+    }
+
+    private func appKitTagNavigation(orientation: TagNavigationView.Orientation) -> some View {
+        let isHorizontal = orientation == .horizontal
+        let appDropTargetID = appGridInteraction.tagNavigationAppDropTargetName
+        return TagNavigationView(
+            items: tagLabels,
+            orientation: orientation,
+            contentInsets: isHorizontal
+                ? NSEdgeInsets(top: 3, left: 24, bottom: 3, right: tagPosition == "top" ? floatingControlsReservedWidth : 24)
+                : NSEdgeInsets(top: 12, left: 12, bottom: 12, right: 12),
+            dragModeActive: tagNavDragModeActive,
+            draggingItemID: tagNavDragItem,
+            appDragModeActive: appGridInteraction.appDragModeActive,
+            appDropTargetID: appDropTargetID,
+            onActivate: { tagID in
+                activateTagNavigation(tagID)
+            },
+            onHoverChange: { tagID, active in
+                handleTagNavigationHover(tagID, active: active)
+            },
+            canReorder: { tagID in
+                canReorderTag(tagID)
+            },
+            canAcceptAppDrop: { tagID in
+                canAssignDroppedAppToTag(tagID)
+            },
+            onReorderBegan: { tagID in
+                beginTagNavReorder(tagID)
+            },
+            onReorderMoved: { tagID, targetID in
+                reorderTagNavItem(fromName: tagID, to: targetID)
+            },
+            onReorderEnded: {
+                endTagNavReorder()
+            },
+            onAppDropHoverChange: { tagID, active in
+                handleTagNavigationAppDropHover(tagID, active: active)
+            },
+            onAppDrop: { path, source, targetTag, copy in
+                dropAppOnTagNavigation(path: path, sourceTag: source, targetTag: targetTag, copy: copy)
+            }
+        )
+    }
+
+    private var swiftUITopTagBar: some View {
         ScrollView(.horizontal, showsIndicators: false) {
             HStack(spacing: 8) {
                 ForEach(tagLabels) { tag in
@@ -889,10 +1008,7 @@
                     .zIndex(tagNavDragItem == tag.name ? 1 : 0)
                     .highPriorityGesture(tagNavReorderGesture(for: tag.name))
                     .onHover { hovering in
-                        if hovering {
-                            fillColorlessContainer(tag.id)
-                            scrollTo(tag.id)
-                        }
+                        handleTagNavigationHover(tag.id, active: hovering)
                     }
                 }
             }
@@ -905,18 +1021,7 @@
         }
     }
 
-    private var tagSidebar: some View {
-        tagSidebarList
-            .frame(width: 135)
-    }
-
-    private var rightTagSidebar: some View {
-        tagSidebarList
-            .padding(.top, rightSidebarFloatingClearance)
-            .frame(width: 135)
-    }
-
-    private var tagSidebarList: some View {
+    private var swiftUITagSidebarList: some View {
         ScrollView(.vertical, showsIndicators: false) {
             VStack(spacing: 6) {
                 ForEach(tagLabels) { tag in
@@ -930,10 +1035,7 @@
                     .zIndex(tagNavDragItem == tag.name ? 1 : 0)
                     .highPriorityGesture(tagNavReorderGesture(for: tag.name))
                     .onHover { hovering in
-                        if hovering {
-                            fillColorlessContainer(tag.id)
-                            scrollTo(tag.id)
-                        }
+                        handleTagNavigationHover(tag.id, active: hovering)
                     }
                 }
             }
@@ -955,7 +1057,7 @@
                 Spacer()
                 ProgressView().scaleEffect(0.8)
                 Spacer()
-            } else if usesAppKitContainerGrid {
+            } else {
                 AppGridCollectionView(
                     groups: displayGroups,
                     tagColors: tagColors,
@@ -964,7 +1066,7 @@
                     showNames: !hideAppNames,
                     bubbleDisabled: appBubbleDisabled,
                     showUncommonAppBubbles: showUncommonAppBubbles,
-                    highlightedGroupName: filledColorlessContainer,
+                    highlightedGroupName: appGridHighlightedGroupName,
                     contentRevision: groupLayoutVersion,
                     scrollTargetID: appGridScrollTargetID,
                     scrollRequestToken: appGridScrollRequestToken,
@@ -974,27 +1076,26 @@
                     onDropApp: { path, source, target, copy in
                         dropApp(path: path, sourceTag: source, targetTag: target, copy: copy)
                     },
+                    onDropOutsideGroup: { path, source, copy in
+                        dropAppOutsideGroup(path: path, sourceTag: source, copy: copy)
+                    },
                     onGroupActivate: { groupName in
-                        if displayMode == "gridContainer" {
+                        if isColorlessContainerMode {
                             toggleColorlessFill(groupName)
                         }
                     },
                     onScrollActivity: handleAppGridScrollActivity,
                     onDragModeChange: { setAppDragMode($0) }
                 )
-            } else if displayMode == "container" || displayMode == "coloredContainer" {
-                containerGrid
-            } else {
-                flatGrid
             }
         }
     }
 
     private var uncommonAppBubbleOverlay: some View {
         GeometryReader { proxy in
-            if let context = editingBubble ?? hoveredBubble {
+            if let context = appGridInteraction.editingBubble ?? appGridInteraction.hoveredBubble {
                 let rootFrame = proxy.frame(in: .global)
-                let editing = editingBubble != nil
+                let editing = appGridInteraction.editingBubble != nil
                 let width = min(editing ? 440 : 520, max(260, proxy.size.width - 48))
                 let placement = bubblePlacement(for: context.frame, rootFrame: rootFrame)
                 let metrics = bubbleMetrics(
@@ -1007,12 +1108,12 @@
                 )
 
                 AppNameBubble(
-                    appName: context.app.name,
+                    appName: context.app.displayName,
                     note: currentNote(for: context.app),
                     isEditing: editing,
                     placement: placement,
                     arrowOffset: metrics.arrowOffset,
-                    draftNote: $bubbleDraftNote,
+                    draftNote: $appGridInteraction.bubbleDraftNote,
                     noteFocused: $bubbleNoteFocused,
                     onCommit: commitBubbleNote,
                     onCancel: dismissAppBubble
@@ -1025,625 +1126,17 @@
             }
         }
         .ignoresSafeArea()
-        .allowsHitTesting(editingBubble != nil)
+        .allowsHitTesting(appGridInteraction.editingBubble != nil)
     }
 
     private var smartStartNoticeOverlay: some View {
-        GeometryReader { proxy in
-            if let notice = smartStartNotice {
-                let panelWidth = min(560, max(320, proxy.size.width - 64))
-
-                ZStack {
-                    Color.black.opacity(0.10)
-                        .ignoresSafeArea()
-
-                    VStack(spacing: 18) {
-                        Image(systemName: notice.mode == .suggestionOnly ? "sparkles" : "checkmark.seal.fill")
-                            .font(.system(size: 30, weight: .semibold))
-                            .foregroundStyle(Color.accentColor)
-                            .frame(width: 58, height: 58)
-                            .background(
-                                Circle()
-                                    .fill(Color.accentColor.opacity(0.12))
-                            )
-
-                        VStack(spacing: 8) {
-                            Text(notice.title)
-                                .font(.system(size: 21, weight: .semibold))
-                                .foregroundStyle(.primary)
-                                .multilineTextAlignment(.center)
-
-                            Text(notice.message)
-                                .font(.system(size: 15, weight: .regular))
-                                .foregroundStyle(.secondary)
-                                .multilineTextAlignment(.center)
-                                .lineLimit(4)
-                                .fixedSize(horizontal: false, vertical: true)
-                        }
-
-                        HStack(spacing: 12) {
-                            switch notice.mode {
-                            case .suggestionOnly:
-                                Button(tr("smartstart.later")) {
-                                    dismissSmartStartNotice()
-                                }
-                                .buttonStyle(.bordered)
-                                .controlSize(.large)
-
-                                Button(tr("smartstart.apply")) {
-                                    applySmartStartSuggestion()
-                                }
-                                .buttonStyle(.borderedProminent)
-                                .controlSize(.large)
-                            case .autoApplied, .manuallyApplied:
-                                if notice.summary.backupPath != nil {
-                                    Button(tr("smartstart.undo")) {
-                                        undoSmartStart()
-                                    }
-                                    .buttonStyle(.bordered)
-                                    .controlSize(.large)
-                                }
-                                Button(tr("smartstart.ok")) {
-                                    dismissSmartStartNotice()
-                                }
-                                .buttonStyle(.borderedProminent)
-                                .controlSize(.large)
-                            }
-                        }
-                    }
-                    .padding(.horizontal, 30)
-                    .padding(.vertical, 26)
-                    .frame(width: panelWidth)
-                    .background(
-                        RoundedRectangle(cornerRadius: 16)
-                            .fill(.ultraThickMaterial)
-                            .shadow(color: .black.opacity(0.26), radius: 28, y: 16)
-                    )
-                    .overlay(
-                        RoundedRectangle(cornerRadius: 16)
-                            .stroke(.white.opacity(0.16), lineWidth: 1)
-                    )
-                }
-                .frame(width: proxy.size.width, height: proxy.size.height)
-                .transition(.scale(scale: 0.96).combined(with: .opacity))
-                .zIndex(650)
-            }
-        }
-        .ignoresSafeArea()
-        .allowsHitTesting(smartStartNotice != nil)
-    }
-    private var flatGrid: some View {
-        ScrollViewReader { proxy in
-            ScrollView {
-                LazyVStack(alignment: .leading, spacing: 24) {
-                    ForEach(displayGroups) { group in
-                        TagGroupView(
-                            group: group,
-                            onSelectApp: { app in openApp(app) },
-                            tagFontSize: tagFontSize,
-                            iconSize: iconSize,
-                            showNames: !hideAppNames,
-                            dragModeActive: appDragModeActive,
-                            onDragModeChange: { setAppDragMode($0) },
-                            onBubbleHover: handleBubbleHover,
-                            onEditNote: beginEditingBubbleNote,
-                            bubbleDisabled: appBubbleDisabled,
-                            showUncommonAppBubbles: showUncommonAppBubbles,
-                            dragResetToken: appDragResetToken,
-                            onDropApp: { path, source, copy in
-                                dropApp(path: path, sourceTag: source, targetTag: group.name, copy: copy)
-                            }
-                        ).id(group.id)
-                    }
-                }
-                .padding(20)
-                .background(AppGridScrollActivityObserver(onScroll: handleAppGridScrollActivity))
-            }
-            .id(displayMode)  // force rebuild on mode switch
-            .onAppear { scrollProxy = proxy }
-        }
-    }
-
-    private var containerGrid: some View {
-        GeometryReader { geo in
-            let outerPad: CGFloat = 20
-            let gap: CGFloat = 16
-            let available = geo.size.width - outerPad * 2
-            let colW: CGFloat = 280
-            let colCount = max(1, Int((available + gap) / (colW + gap)))
-            let actualColW = (available - gap * CGFloat(colCount - 1)) / CGFloat(colCount)
-
-            let columns = distributeToColumns(groups: displayGroups, colCount: colCount, colWidth: actualColW)
-
-            ScrollViewReader { proxy in
-                ScrollView {
-                    HStack(alignment: .top, spacing: gap) {
-                        ForEach(0..<colCount, id: \.self) { ci in
-                            LazyVStack(spacing: gap) {
-                                ForEach(columns[ci]) { group in
-                                    masonryCard(group, width: actualColW)
-                                        .id(group.id)
-                                }
-                            }
-                        }
-                    }
-                    .padding(outerPad)
-                    .background(AppGridScrollActivityObserver(onScroll: handleAppGridScrollActivity))
-                }
-                .id(displayMode)  // force rebuild on mode switch
-                .onAppear { scrollProxy = proxy }
-            }
-        }
-    }
-
-    /// Distribute groups to the shortest column.
-    private func distributeToColumns(groups: [TagGroup], colCount: Int, colWidth: CGFloat) -> [[TagGroup]] {
-        var cols = Array(repeating: [TagGroup](), count: colCount)
-        var h = Array(repeating: CGFloat(0), count: colCount)
-        for g in groups {
-            let est = estimatedCardHeight(g, width: colWidth)
-            let ci = h.firstIndex(of: h.min()!)!
-            cols[ci].append(g)
-            h[ci] += est + 16
-        }
-        return cols
-    }
-
-    private func estimatedCardHeight(_ group: TagGroup, width: CGFloat) -> CGFloat {
-        let inner = width - 32
-        let itemW = AppGridItem.stableWidth(iconSize: iconSize) + 6
-        let perRow = max(1, Int(inner / itemW))
-        let rows = (group.apps.count + perRow - 1) / perRow
-        return 32
-            + CGFloat(rows) * AppGridItem.stableHeight(iconSize: iconSize)
-            + CGFloat(max(0, rows - 1)) * 2
-    }
-
-    private func masonryCard(_ group: TagGroup, width: CGFloat) -> some View {
-        let isColored = displayMode == "coloredContainer"
-        let isColorless = isColorlessContainerMode
-        let isColorlessFilled = isColorless && filledColorlessContainer == group.name
-        let isHovered = hoveredContainer == group.name
-        let isColorlessActive = isColorless && (isColorlessFilled || isHovered)
-        let tagColor = Color(nsColor: TagColor.nsColor(for: tagColors[group.name] ?? 0))
-        return VStack(alignment: .leading, spacing: 6) {
-            HStack(spacing: 0) {
-                Rectangle().fill(.secondary.opacity(0.25)).frame(height: 1)
-                    .layoutPriority(0)
-                Text(group.name)
-                    .font(.system(size: tagFontSize, weight: .semibold))
-                    .foregroundStyle(.secondary)
-                    .lineLimit(1)
-                    .truncationMode(.middle)
-                    .padding(.horizontal, 10)
-                    .layoutPriority(1)
-                Rectangle().fill(.secondary.opacity(0.25)).frame(height: 1)
-                    .layoutPriority(0)
-            }
-            let itemSize = AppGridItem.stableWidth(iconSize: iconSize)
-            LazyVGrid(
-                columns: [GridItem(.adaptive(minimum: itemSize, maximum: itemSize + 36), spacing: 6)],
-                spacing: 2
-            ) {
-                ForEach(group.apps) { app in
-                    AppGridItem(
-                        app: app,
-                        iconSize: iconSize,
-                        showName: !hideAppNames,
-                        sourceTag: group.name,
-                        dragModeActive: appDragModeActive,
-                        onDragModeChange: { setAppDragMode($0) },
-                        onBubbleHover: handleBubbleHover,
-                        onEditNote: beginEditingBubbleNote,
-                        bubbleDisabled: appBubbleDisabled,
-                        showUncommonAppBubbles: showUncommonAppBubbles,
-                        itemID: "\(group.name)|\(app.path.path)",
-                        dragResetToken: appDragResetToken,
-                        onSelect: { openApp(app) }
-                    )
-                }
-            }
-        }
-        .frame(maxWidth: width)
-        .padding(16)
-        .background(
-            RoundedRectangle(cornerRadius: 14)
-                .fill((isColored || isColorlessActive) ? tagColor.opacity(0.30) : Color.clear)
-                .background(
-                    RoundedRectangle(cornerRadius: 14)
-                        .fill(cardSurfaceColor)
-                )
-        )
-        .overlay(
-            RoundedRectangle(cornerRadius: 14)
-                .stroke(Color.primary.opacity(0.08), lineWidth: 1)
-        )
-        .overlay {
-            if appDragModeActive {
-                AppDropTargetView(targetTag: group.name) { path, source, copy in
-                    dropApp(path: path, sourceTag: source, targetTag: group.name, copy: copy)
-                }
-                .allowsHitTesting(false)
-            }
-        }
-        .shadow(color: .black.opacity((isColored && isHovered) || isColorlessActive ? 0.22 : 0),
-                radius: (isColored && isHovered) || isColorlessActive ? 8 : 0,
-                y: (isColored && isHovered) || isColorlessActive ? 3 : 0)
-        .zIndex(isHovered ? 50 : 0)
-        .animation(.easeOut(duration: 0.045), value: isHovered)
-        .animation(.easeOut(duration: 0.08), value: isColorlessFilled)
-        .background(AppHoverTrackingView { hovering, _ in
-            guard !scrollInteractionState.isFrozen else {
-                if !hovering && hoveredContainer == group.name {
-                    hoveredContainer = nil
-                }
-                return
-            }
-            if isColored || isColorless {
-                hoveredContainer = hovering ? group.name : nil
-            }
-        })
-        .contentShape(RoundedRectangle(cornerRadius: 14))
-        .onTapGesture {
-            if isColorless {
-                toggleColorlessFill(group.name)
-            }
-        }
-        .onDrop(of: [UTType.plainText], isTargeted: nil) { providers in
-            handleAppDrop(providers, targetTag: group.name)
-        }
-    }
-
-    private var gridContainerGrid: some View {
-        GeometryReader { geo in
-            let outerPad: CGFloat = 20
-            let gap: CGFloat = 16
-            let available = geo.size.width - outerPad * 2
-            let preferredCount = preferredGridContainersPerRow(availableWidth: available)
-            let rowsKey = GridContainerRowsKey(
-                groupLayoutVersion: groupLayoutVersion,
-                trackCount: preferredCount,
-                availableWidth: Int(available.rounded()),
-                iconSize: Int(iconSize.rounded())
-            )
-            let rows = gridContainerRowsForRender(
-                key: rowsKey,
-                groups: displayGroups,
-                trackCount: preferredCount,
-                availableWidth: available,
-                gap: gap
-            )
-
-            ScrollViewReader { proxy in
-                ScrollView {
-                    LazyVStack(alignment: .leading, spacing: gap) {
-                        ForEach(Array(rows.indices), id: \.self) { rowIndex in
-                            let row = rows[rowIndex]
-
-                            HStack(alignment: .top, spacing: gap) {
-                                ForEach(Array(row.items.indices), id: \.self) { itemIndex in
-                                    let item = row.items[itemIndex]
-                                    gridContainerCard(item.group, width: item.width, fixedRows: row.fixedRows)
-                                        .id(item.group.id)
-                                }
-                            }
-                        }
-                    }
-                    .padding(outerPad)
-                    .frame(maxWidth: .infinity, alignment: .topLeading)
-                    .background(AppGridScrollActivityObserver(onScroll: handleAppGridScrollActivity))
-                }
-                .id(displayMode)
-                .onAppear { scrollProxy = proxy }
-                .onAppear {
-                    updateCachedGridContainerRows(
-                        key: rowsKey,
-                        groups: displayGroups,
-                        trackCount: preferredCount,
-                        availableWidth: available,
-                        gap: gap
-                    )
-                }
-                .onChange(of: rowsKey) { _, newKey in
-                    updateCachedGridContainerRows(
-                        key: newKey,
-                        groups: displayGroups,
-                        trackCount: preferredCount,
-                        availableWidth: available,
-                        gap: gap
-                    )
-                }
-            }
-        }
-    }
-
-    private func preferredGridContainersPerRow(availableWidth: CGFloat) -> Int {
-        let minCardWidth = max(260, AppGridItem.stableWidth(iconSize: iconSize) * 3 + 64)
-        if availableWidth >= minCardWidth * 3 + 32 { return 3 }
-        if availableWidth >= minCardWidth * 2 + 16 { return 2 }
-        return 1
-    }
-
-    private struct GridContainerLayoutItem {
-        let group: TagGroup
-        let width: CGFloat
-    }
-
-    private struct GridContainerLayoutRow {
-        let items: [GridContainerLayoutItem]
-        let fixedRows: Int
-    }
-
-    private struct GridContainerRowsKey: Equatable {
-        let groupLayoutVersion: Int
-        let trackCount: Int
-        let availableWidth: Int
-        let iconSize: Int
-    }
-
-    private struct GridContainerCandidate {
-        let spans: [Int]
-        let rows: Int
-        let cost: CGFloat
-    }
-
-    private func gridContainerRowsForRender(
-        key: GridContainerRowsKey,
-        groups: [TagGroup],
-        trackCount: Int,
-        availableWidth: CGFloat,
-        gap: CGFloat
-    ) -> [GridContainerLayoutRow] {
-        if cachedGridContainerRowsKey == key {
-            return cachedGridContainerRows
-        }
-        return gridContainerRows(
-            groups: groups,
-            trackCount: trackCount,
-            availableWidth: availableWidth,
-            gap: gap
+        SmartStartNoticeOverlay(
+            notice: smartStartNotice,
+            onDismiss: dismissSmartStartNotice,
+            onApply: applySmartStartSuggestion,
+            onUndo: undoSmartStart
         )
     }
-
-    private func updateCachedGridContainerRows(
-        key: GridContainerRowsKey,
-        groups: [TagGroup],
-        trackCount: Int,
-        availableWidth: CGFloat,
-        gap: CGFloat
-    ) {
-        guard cachedGridContainerRowsKey != key else { return }
-        cachedGridContainerRows = gridContainerRows(
-            groups: groups,
-            trackCount: trackCount,
-            availableWidth: availableWidth,
-            gap: gap
-        )
-        cachedGridContainerRowsKey = key
-    }
-
-    private func gridContainerRows(groups: [TagGroup], trackCount: Int, availableWidth: CGFloat, gap: CGFloat) -> [GridContainerLayoutRow] {
-        let trackCount = max(1, trackCount)
-        let trackWidth = (availableWidth - gap * CGFloat(trackCount - 1)) / CGFloat(trackCount)
-        let patterns = gridContainerSpanPatterns(trackCount: trackCount)
-        let n = groups.count
-        guard n > 0 else { return [] }
-
-        var bestCost = Array(repeating: CGFloat.greatestFiniteMagnitude, count: n + 1)
-        var bestPattern = Array(repeating: [Int](), count: n)
-        bestCost[n] = 0
-
-        for index in stride(from: n - 1, through: 0, by: -1) {
-            for pattern in patterns where index + pattern.count <= n {
-                let candidate = gridContainerCandidate(
-                    groups: groups,
-                    startIndex: index,
-                    spans: pattern,
-                    trackWidth: trackWidth,
-                    availableWidth: availableWidth,
-                    gap: gap
-                )
-                let totalCost = candidate.cost + bestCost[index + pattern.count]
-                if totalCost < bestCost[index] {
-                    bestCost[index] = totalCost
-                    bestPattern[index] = candidate.spans
-                }
-            }
-        }
-
-        var rows: [GridContainerLayoutRow] = []
-        var index = 0
-        while index < n {
-            let spans = bestPattern[index].isEmpty ? [trackCount] : bestPattern[index]
-            let widths = spans.map { gridContainerWidth(trackWidth: trackWidth, span: $0, gap: gap) }
-            let fixedRows = widths.indices.map {
-                iconRows(appCount: groups[index + $0].apps.count, width: widths[$0])
-            }.max() ?? 1
-            let items = widths.indices.map {
-                GridContainerLayoutItem(group: groups[index + $0], width: widths[$0])
-            }
-            rows.append(GridContainerLayoutRow(items: items, fixedRows: fixedRows))
-            index += spans.count
-        }
-        return rows
-    }
-
-    private func gridContainerSpanPatterns(trackCount: Int) -> [[Int]] {
-        switch trackCount {
-        case 3:
-            return [[1, 1, 1], [1, 2], [2, 1], [3]]
-        case 2:
-            return [[1, 1], [2]]
-        default:
-            return [[1]]
-        }
-    }
-
-    private func gridContainerCandidate(
-        groups: [TagGroup],
-        startIndex: Int,
-        spans: [Int],
-        trackWidth: CGFloat,
-        availableWidth: CGFloat,
-        gap: CGFloat
-    ) -> GridContainerCandidate {
-        let widths = spans.map { gridContainerWidth(trackWidth: trackWidth, span: $0, gap: gap) }
-        let rowCounts = widths.indices.map {
-            iconRows(appCount: groups[startIndex + $0].apps.count, width: widths[$0])
-        }
-        let fixedRows = rowCounts.max() ?? 1
-        let rowArea = CGFloat(fixedRows) * iconCellHeight() * availableWidth
-        let paddingCost = CGFloat(spans.count) * 0.001
-        return GridContainerCandidate(spans: spans, rows: fixedRows, cost: rowArea + paddingCost)
-    }
-
-    private func gridContainerWidth(trackWidth: CGFloat, span: Int, gap: CGFloat) -> CGFloat {
-        let span = max(1, span)
-        return trackWidth * CGFloat(span) + gap * CGFloat(span - 1)
-    }
-
-    private func iconColumns(width: CGFloat) -> Int {
-        let inner = width - 32
-        let itemW = AppGridItem.stableWidth(iconSize: iconSize) + 6
-        return max(1, Int((inner + 6) / itemW))
-    }
-
-    private func iconRows(appCount: Int, width: CGFloat) -> Int {
-        let cols = iconColumns(width: width)
-        return max(1, (appCount + cols - 1) / cols)
-    }
-
-    private func gridContainerCard(_ group: TagGroup, width: CGFloat, fixedRows: Int) -> some View {
-        let isColored = displayMode == "coloredGridContainer"
-        let isColorlessGrid = displayMode == "gridContainer"
-        let isColorless = isColorlessContainerMode
-        let isColorlessFilled = isColorless && filledColorlessContainer == group.name
-        let isHovered = hoveredContainer == group.name
-        let isColorlessGridActive = isColorlessGrid && (isColorlessFilled || isHovered)
-        let cols = iconColumns(width: width)
-        let contentWidth = max(1, width - 32)
-        let cellWidth = max(1, (contentWidth - 6 * CGFloat(cols - 1)) / CGFloat(cols))
-        let cellHeight = iconCellHeight()
-        let gridHeight = CGFloat(fixedRows) * cellHeight + CGFloat(max(0, fixedRows - 1)) * 2
-        let rows = appRows(group.apps, columns: cols, fixedRows: fixedRows)
-        let tagColor = Color(nsColor: TagColor.nsColor(for: tagColors[group.name] ?? 0))
-
-        return VStack(alignment: .leading, spacing: 6) {
-            HStack(spacing: 0) {
-                Rectangle().fill(.secondary.opacity(0.25)).frame(height: 1)
-                    .layoutPriority(0)
-                Text(group.name)
-                    .font(.system(size: tagFontSize, weight: .semibold))
-                    .foregroundStyle(.secondary)
-                    .lineLimit(1)
-                    .truncationMode(.middle)
-                    .padding(.horizontal, 10)
-                    .layoutPriority(1)
-                Rectangle().fill(.secondary.opacity(0.25)).frame(height: 1)
-                    .layoutPriority(0)
-            }
-
-            VStack(alignment: .leading, spacing: 2) {
-                ForEach(rows.indices, id: \.self) { rowIndex in
-                    HStack(alignment: .top, spacing: 6) {
-                        ForEach(rows[rowIndex]) { app in
-                            AppGridItem(
-                                app: app,
-                                iconSize: iconSize,
-                                showName: !hideAppNames,
-                                sourceTag: group.name,
-                                dragModeActive: appDragModeActive,
-                                onDragModeChange: { setAppDragMode($0) },
-                                onBubbleHover: handleBubbleHover,
-                                onEditNote: beginEditingBubbleNote,
-                                bubbleDisabled: appBubbleDisabled,
-                                showUncommonAppBubbles: showUncommonAppBubbles,
-                                itemID: "\(group.name)|\(app.path.path)",
-                                dragResetToken: appDragResetToken,
-                                onSelect: { openApp(app) }
-                            )
-                                .frame(width: cellWidth)
-                                .frame(height: cellHeight)
-                        }
-
-                        let emptyCells = max(0, cols - rows[rowIndex].count)
-                        ForEach(0..<emptyCells, id: \.self) { _ in
-                            Color.clear
-                                .frame(width: cellWidth, height: cellHeight)
-                        }
-                    }
-                    .frame(height: cellHeight)
-                }
-            }
-            .frame(height: gridHeight, alignment: .topLeading)
-        }
-        .frame(width: contentWidth)
-        .padding(16)
-        .background(
-            RoundedRectangle(cornerRadius: 14)
-                .fill((isColored || isColorlessGridActive) ? tagColor.opacity(0.30) : Color.clear)
-                .background(
-                    RoundedRectangle(cornerRadius: 14)
-                        .fill(cardSurfaceColor)
-                )
-        )
-        .overlay(
-            RoundedRectangle(cornerRadius: 14)
-                .stroke(Color.primary.opacity(0.08), lineWidth: 1)
-        )
-        .overlay {
-            if appDragModeActive {
-                AppDropTargetView(targetTag: group.name) { path, source, copy in
-                    dropApp(path: path, sourceTag: source, targetTag: group.name, copy: copy)
-                }
-                .allowsHitTesting(false)
-            }
-        }
-        .shadow(color: .black.opacity((isColored && isHovered) || isColorlessGridActive ? 0.22 : 0),
-                radius: (isColored && isHovered) || isColorlessGridActive ? 8 : 0,
-                y: (isColored && isHovered) || isColorlessGridActive ? 3 : 0)
-        .zIndex(isHovered ? 50 : 0)
-        .animation(.easeOut(duration: 0.045), value: isHovered)
-        .animation(.easeOut(duration: 0.08), value: isColorlessFilled)
-        .background(AppHoverTrackingView { hovering, _ in
-            guard !scrollInteractionState.isFrozen else {
-                if !hovering && hoveredContainer == group.name {
-                    hoveredContainer = nil
-                }
-                return
-            }
-            if isColored || isColorlessGrid {
-                hoveredContainer = hovering ? group.name : nil
-            } else if hovering {
-                fillColorlessContainer(group.name)
-            }
-        })
-        .contentShape(RoundedRectangle(cornerRadius: 14))
-        .onTapGesture {
-            if isColorlessGrid {
-                toggleColorlessFill(group.name)
-            }
-        }
-        .onDrop(of: [UTType.plainText], isTargeted: nil) { providers in
-            handleAppDrop(providers, targetTag: group.name)
-        }
-    }
-
-    private func iconCellHeight() -> CGFloat {
-        AppGridItem.stableHeight(iconSize: iconSize)
-    }
-
-    private func appRows(_ apps: [AppInfo], columns: Int, fixedRows: Int) -> [[AppInfo]] {
-        let columns = max(1, columns)
-        let rowCount = max(1, fixedRows)
-        return (0..<rowCount).map { rowIndex in
-            let start = rowIndex * columns
-            guard start < apps.count else { return [] }
-            let end = min(start + columns, apps.count)
-            return Array(apps[start..<end])
-        }
-    }
-
     // MARK: - Edit Tags View
 
     private var editTagsView: some View {
@@ -1768,8 +1261,8 @@
                 columns: [
                     GridItem(
                         .adaptive(
-                            minimum: AppGridItem.stableWidth(iconSize: iconSize),
-                            maximum: AppGridItem.stableWidth(iconSize: iconSize) + 36
+                            minimum: AppGridItemMetrics.stableWidth(iconSize: iconSize),
+                            maximum: AppGridItemMetrics.stableWidth(iconSize: iconSize) + 36
                         ),
                         spacing: 6
                     )
@@ -1963,7 +1456,7 @@
 
     private var uncategorizedDropConfirmOverlay: some View {
         GeometryReader { proxy in
-            if let pendingDrop = pendingUncategorizedDrop {
+            if let pendingDrop = appGridInteraction.pendingUncategorizedDrop {
                 ZStack {
                     Color.black.opacity(0.14)
                         .ignoresSafeArea()
@@ -1971,6 +1464,8 @@
                     UncategorizedDropConfirmBubble(
                         title: tr("drop.uncategorizedConfirmTitle"),
                         message: uncategorizedConfirmMessage(for: pendingDrop),
+                        doNotRemindTitle: tr("drop.removeTagDoNotAskAgain"),
+                        doNotRemind: $appGridInteraction.uncategorizedDropSuppressFuturePrompt,
                         cancelTitle: tr("tag.cancel"),
                         confirmTitle: tr("edit.confirm"),
                         onCancel: dismissUncategorizedDropConfirm,
@@ -1984,7 +1479,35 @@
             }
         }
         .ignoresSafeArea()
-        .allowsHitTesting(pendingUncategorizedDrop != nil)
+        .allowsHitTesting(appGridInteraction.pendingUncategorizedDrop != nil)
+    }
+
+    private var tagRemovalDropConfirmOverlay: some View {
+        GeometryReader { proxy in
+            if let pendingDrop = appGridInteraction.pendingTagRemovalDrop {
+                ZStack {
+                    Color.black.opacity(0.14)
+                        .ignoresSafeArea()
+
+                    TagRemovalDropConfirmBubble(
+                        title: tr("drop.removeTagConfirmTitle"),
+                        message: tagRemovalConfirmMessage(for: pendingDrop),
+                        doNotRemindTitle: tr("drop.removeTagDoNotAskAgain"),
+                        doNotRemind: $appGridInteraction.tagRemovalDropSuppressFuturePrompt,
+                        cancelTitle: tr("drop.removeTagConfirmNo"),
+                        confirmTitle: tr("drop.removeTagConfirmYes"),
+                        onCancel: dismissTagRemovalDropConfirm,
+                        onConfirm: confirmPendingTagRemovalDrop
+                    )
+                    .frame(width: min(560, max(350, proxy.size.width - 120)))
+                    .position(x: proxy.size.width / 2, y: proxy.size.height / 2)
+                    .transition(.scale(scale: 0.94).combined(with: .opacity))
+                }
+                .zIndex(711)
+            }
+        }
+        .ignoresSafeArea()
+        .allowsHitTesting(appGridInteraction.pendingTagRemovalDrop != nil)
     }
 
     private func buildEditActionFeedback(for selectedApps: [AppInfo], tags: [String]) -> EditActionFeedback {
@@ -2135,23 +1658,14 @@
 
         let scannedApps = allApps
         DispatchQueue.global(qos: .userInitiated).async {
-            let result = SmartStartService.applySuggestion(draft)
-            let store = result.store
-            let apps = TagEditor.annotate(apps: scannedApps, store: store)
-            let quickSearchDocs = QuickSearchEngine.makeDocuments(apps: apps, store: store)
-            let colors = store.tags.mapValues { $0.color }
-            let order = TagEditor.orderedTagNames()
+            let result = AppLibraryController.applySmartStartSuggestion(
+                draft,
+                scannedApps: scannedApps
+            )
 
             DispatchQueue.main.async {
                 pendingSmartStartDraft = nil
-                allApps = apps
-                quickSearchDocuments = quickSearchDocs
-                tagColors = colors
-                draggedTagNames = order
-                rebuildDisplayGroups(apps: apps, tagOrder: order)
-                if quickSearchVisible {
-                    refreshQuickSearchResults()
-                }
+                applyAppLibrarySnapshot(result.snapshot)
                 if let summary = result.summary {
                     showSmartStartNotice(mode: .manuallyApplied, summary: summary)
                 } else {
@@ -2227,11 +1741,10 @@
     private func rebuildDisplayGroups(apps: [AppInfo], tagOrder: [String]) {
         displayGroups = makeDisplayGroups(apps: apps, tagOrder: tagOrder)
         groupLayoutVersion &+= 1
-        cachedGridContainerRowsKey = nil
     }
 
-    private var tagLabels: [TagLabel] {
-        displayGroups.map { TagLabel(name: $0.name, colorIndex: tagColors[$0.name] ?? 0) }
+    private var tagLabels: [TagNavigationItem] {
+        displayGroups.map { TagNavigationItem(name: $0.name, colorIndex: tagColors[$0.name] ?? 0) }
     }
 
     private var editGroups: [TagGroup] {
@@ -2261,11 +1774,9 @@
     }
 
     private func handleAppGridScrollActivity() {
-        if !scrollInteractionState.isFrozen {
-            hoveredBubble = nil
-            hoveredContainer = nil
+        if appGridInteraction.hoveredBubble != nil {
+            appGridInteraction.hoveredBubble = nil
         }
-        scrollInteractionState.noteScroll()
     }
 
     private func handleBubbleHover(app: AppInfo, frame: CGRect, event: AppBubbleHoverEvent) {
@@ -2273,17 +1784,17 @@
             clearAppBubbleState()
             return
         }
-        guard editingBubble == nil else { return }
+        guard appGridInteraction.editingBubble == nil else { return }
         switch event {
         case .entered(let canShowBubble):
             if canShowBubble {
-                hoveredBubble = AppBubbleContext(app: app, frame: frame)
+                appGridInteraction.hoveredBubble = AppBubbleContext(app: app, frame: frame)
             } else {
-                hoveredBubble = nil
+                appGridInteraction.hoveredBubble = nil
             }
         case .exited:
-            guard hoveredBubble?.app.path == app.path else { return }
-            hoveredBubble = nil
+            guard appGridInteraction.hoveredBubble?.app.path == app.path else { return }
+            appGridInteraction.hoveredBubble = nil
         }
     }
 
@@ -2292,9 +1803,9 @@
             clearAppBubbleState()
             return
         }
-        bubbleDraftNote = currentNote(for: app)
-        hoveredBubble = nil
-        editingBubble = AppBubbleContext(app: app, frame: frame)
+        appGridInteraction.bubbleDraftNote = currentNote(for: app)
+        appGridInteraction.hoveredBubble = nil
+        appGridInteraction.editingBubble = AppBubbleContext(app: app, frame: frame)
         notifyAppNoteEditing(active: true)
         DispatchQueue.main.async {
             bubbleNoteFocused = true
@@ -2302,33 +1813,33 @@
     }
 
     private func commitBubbleNote() {
-        guard let context = editingBubble else { return }
-        let limited = String(bubbleDraftNote.prefix(TagDatabase.maxAppNoteLength))
+        guard let context = appGridInteraction.editingBubble else { return }
+        let limited = String(appGridInteraction.bubbleDraftNote.prefix(TagDatabase.maxAppNoteLength))
             .trimmingCharacters(in: .whitespacesAndNewlines)
         TagEditor.setAppNote(limited, for: context.app.path.path)
-        bubbleDraftNote = limited
-        editingBubble = nil
+        appGridInteraction.bubbleDraftNote = limited
+        appGridInteraction.editingBubble = nil
         bubbleNoteFocused = false
         notifyAppNoteEditing(active: false)
         refreshApps()
     }
 
     private func dismissAppBubble() {
-        hoveredBubble = nil
-        if editingBubble != nil {
+        appGridInteraction.hoveredBubble = nil
+        if appGridInteraction.editingBubble != nil {
             notifyAppNoteEditing(active: false)
         }
-        editingBubble = nil
+        appGridInteraction.editingBubble = nil
         bubbleNoteFocused = false
     }
 
     private func clearAppBubbleState() {
-        if hoveredBubble != nil {
-            hoveredBubble = nil
+        if appGridInteraction.hoveredBubble != nil {
+            appGridInteraction.hoveredBubble = nil
         }
-        if editingBubble != nil {
+        if appGridInteraction.editingBubble != nil {
             notifyAppNoteEditing(active: false)
-            editingBubble = nil
+            appGridInteraction.editingBubble = nil
         }
         if bubbleNoteFocused {
             bubbleNoteFocused = false
@@ -2396,12 +1907,8 @@
     }
 
     func scrollTo(_ id: String) {
-        if usesAppKitContainerGrid {
-            appGridScrollTargetID = id
-            appGridScrollRequestToken &+= 1
-        } else {
-            withAnimation(.easeInOut(duration: 0.25)) { scrollProxy?.scrollTo(id, anchor: .top) }
-        }
+        appGridScrollTargetID = id
+        appGridScrollRequestToken &+= 1
     }
 
     private func activateTagNavigation(_ id: String) {
@@ -2409,6 +1916,56 @@
         if isColorlessContainerMode {
             toggleColorlessFill(id)
         }
+        scrollTo(id)
+    }
+
+    private func handleTagNavigationHover(_ id: String, active: Bool) {
+        if appGridInteraction.appDragModeActive {
+            if !active, appGridInteraction.tagNavigationHoveredGroupName == id {
+                appGridInteraction.tagNavigationHoveredGroupName = nil
+            }
+            return
+        }
+
+        guard active else {
+            if appGridInteraction.tagNavigationHoveredGroupName == id {
+                appGridInteraction.tagNavigationHoveredGroupName = nil
+            }
+            return
+        }
+
+        appGridInteraction.tagNavigationHoveredGroupName = id
+        fillColorlessContainer(id)
+        scrollToTagFromHover(id)
+    }
+
+    private func handleTagNavigationAppDropHover(_ id: String, active: Bool) {
+        guard appGridInteraction.appDragModeActive else {
+            if appGridInteraction.tagNavigationAppDropTargetName == id {
+                appGridInteraction.tagNavigationAppDropTargetName = nil
+            }
+            return
+        }
+
+        guard active, canAssignDroppedAppToTag(id) else {
+            if appGridInteraction.tagNavigationAppDropTargetName == id {
+                appGridInteraction.tagNavigationAppDropTargetName = nil
+            }
+            return
+        }
+
+        appGridInteraction.tagNavigationAppDropTargetName = id
+    }
+
+    private func scrollToTagFromHover(_ id: String) {
+        let now = Date()
+        if appGridInteraction.tagNavigationLastHoverScrollID == id,
+           let lastScrollAt = appGridInteraction.tagNavigationLastHoverScrollAt,
+           now.timeIntervalSince(lastScrollAt) < tagNavigationHoverScrollInterval {
+            return
+        }
+        appGridInteraction.tagNavigationLastHoverScrollID = id
+        appGridInteraction.tagNavigationLastHoverScrollAt = now
         scrollTo(id)
     }
 
@@ -2492,43 +2049,23 @@
     private func reorderTagNavItem(at location: CGPoint) {
         guard let fromName = tagNavDragItem,
               let targetName = tagNavReorderFrames.first(where: { $0.value.contains(location) })?.key,
-              fromName != targetName,
+              fromName != targetName
+        else { return }
+        reorderTagNavItem(fromName: fromName, to: targetName)
+    }
+
+    private func reorderTagNavItem(fromName: String, to targetName: String) {
+        guard fromName != targetName,
+              canReorderTag(fromName),
+              canReorderTag(targetName),
               let fromIndex = draggedTagNames.firstIndex(of: fromName),
               let toIndex = draggedTagNames.firstIndex(of: targetName)
         else { return }
-
         tagNavReorderDidMove = true
         withAnimation(.spring(response: 0.22, dampingFraction: 0.82)) {
             let destination = toIndex > fromIndex ? toIndex + 1 : toIndex
             draggedTagNames.move(fromOffsets: IndexSet(integer: fromIndex), toOffset: destination)
         }
-    }
-
-    private func handleAppDrop(_ providers: [NSItemProvider], targetTag: String) -> Bool {
-        guard let provider = providers.first(where: { $0.hasItemConformingToTypeIdentifier(UTType.plainText.identifier) }) else {
-            return false
-        }
-        provider.loadItem(forTypeIdentifier: UTType.plainText.identifier, options: nil) { item, _ in
-            let text: String?
-            if let data = item as? Data {
-                text = String(data: data, encoding: .utf8)
-            } else if let string = item as? String {
-                text = string
-            } else if let string = item as? NSString {
-                text = string as String
-            } else {
-                text = nil
-            }
-            guard let text else { return }
-            let parts = text.components(separatedBy: "\n")
-            guard let path = parts.first, !path.isEmpty else { return }
-            let source = parts.dropFirst().first ?? ""
-            let copy = NSEvent.modifierFlags.contains(.option)
-            DispatchQueue.main.async {
-                dropApp(path: path, sourceTag: source, targetTag: targetTag, copy: copy)
-            }
-        }
-        return true
     }
 
     private func dropApp(path: String, sourceTag: String, targetTag: String, copy: Bool) {
@@ -2557,20 +2094,77 @@
         refreshApps(forceLayoutRefresh: true)
     }
 
-    private func confirmAndMoveAppToUncategorized(path: String) {
+    private func dropAppOnTagNavigation(path: String, sourceTag: String, targetTag: String, copy: Bool) {
+        resetTransientDragState()
+        guard canAssignDroppedAppToTag(targetTag) else { return }
         guard let app = allApps.first(where: { $0.path.path == path }) else { return }
-        let assignedTags = assignedRegularDisplayTags(for: app)
-        guard !assignedTags.isEmpty else { return }
+        guard !appHasTag(app, tagName: targetTag) else { return }
+        TagEditor.appendTags([targetTag], to: [path])
+        showDropRefresh()
+        refreshApps(forceLayoutRefresh: true)
+    }
+
+    private func canAssignDroppedAppToTag(_ tagName: String) -> Bool {
+        tagColors[tagName] != nil
+            && !isAppleBuiltInDropTarget(tagName)
+            && !isUncategorizedDropTarget(tagName)
+    }
+
+    private func dropAppOutsideGroup(path: String, sourceTag: String, copy: Bool) {
+        resetTransientDragState(keepingPendingTagRemovalDrop: true)
+        guard isRemovableRegularTag(sourceTag) else { return }
+        guard let app = allApps.first(where: { $0.path.path == path }),
+              appHasTag(app, tagName: sourceTag)
+        else { return }
+
+        if skipTagRemovalDropConfirm {
+            removeTagFromDroppedApp(app: app, tagName: sourceTag)
+            return
+        }
 
         clearAppBubbleState()
+        appGridInteraction.tagRemovalDropSuppressFuturePrompt = false
         withAnimation(.spring(response: 0.24, dampingFraction: 0.84)) {
-            pendingUncategorizedDrop = PendingUncategorizedDrop(app: app, assignedTags: assignedTags)
+            appGridInteraction.pendingTagRemovalDrop = PendingTagRemovalDrop(app: app, tagName: sourceTag)
         }
     }
 
-    private func assignedRegularDisplayTags(for app: AppInfo) -> [String] {
+    private func confirmAndMoveAppToUncategorized(path: String) {
+        guard let app = allApps.first(where: { $0.path.path == path }) else { return }
+        let removableTags = removableRegularTags(for: app)
+        guard !removableTags.isEmpty else { return }
+        let assignedTags = assignedRegularDisplayTags(for: removableTags)
+
+        if skipUncategorizedDropConfirm {
+            moveDroppedAppToUncategorized(path: app.path.path, tags: removableTags)
+            return
+        }
+
+        clearAppBubbleState()
+        appGridInteraction.uncategorizedDropSuppressFuturePrompt = false
+        withAnimation(.spring(response: 0.24, dampingFraction: 0.84)) {
+            appGridInteraction.pendingUncategorizedDrop = PendingUncategorizedDrop(
+                app: app,
+                assignedTags: assignedTags,
+                removableTags: removableTags
+            )
+        }
+    }
+
+    private func removableRegularTags(for app: AppInfo) -> [String] {
         var result: [String] = []
         for tag in app.tags {
+            guard isRemovableRegularTag(tag) else { continue }
+            if !result.contains(tag) {
+                result.append(tag)
+            }
+        }
+        return result
+    }
+
+    private func assignedRegularDisplayTags(for tags: [String]) -> [String] {
+        var result: [String] = []
+        for tag in tags {
             let name = displayTagName(tag)
             if !result.contains(name) {
                 result.append(name)
@@ -2583,29 +2177,83 @@
         formattedFeedbackMessage(
             forKey: "drop.uncategorizedConfirmMessage",
             replacements: [
-                "%appName%": pendingDrop.app.name,
+                "%appName%": pendingDrop.app.displayName,
                 "%tagCount%": "\(pendingDrop.assignedTags.count)",
                 "%tagNames%": pendingDrop.assignedTags.joined(separator: localizedListSeparator)
             ]
         )
     }
 
+    private func tagRemovalConfirmMessage(for pendingDrop: PendingTagRemovalDrop) -> String {
+        formattedFeedbackMessage(
+            forKey: "drop.removeTagConfirmMessage",
+            replacements: [
+                "%appName%": pendingDrop.app.displayName,
+                "%tagName%": displayTagName(pendingDrop.tagName)
+            ]
+        )
+    }
+
     private func dismissUncategorizedDropConfirm() {
+        appGridInteraction.uncategorizedDropSuppressFuturePrompt = false
         resetTransientDragState(keepingPendingUncategorizedDrop: true)
         withAnimation(.easeOut(duration: 0.18)) {
-            pendingUncategorizedDrop = nil
+            appGridInteraction.pendingUncategorizedDrop = nil
         }
     }
 
     private func confirmPendingUncategorizedDrop() {
-        guard let pendingDrop = pendingUncategorizedDrop else { return }
+        guard let pendingDrop = appGridInteraction.pendingUncategorizedDrop else { return }
         let path = pendingDrop.app.path.path
-        let tags = pendingDrop.app.tags
+        let tags = pendingDrop.removableTags
+        let shouldSuppressFuturePrompt = appGridInteraction.uncategorizedDropSuppressFuturePrompt
+        if shouldSuppressFuturePrompt {
+            skipUncategorizedDropConfirm = true
+        }
+        appGridInteraction.uncategorizedDropSuppressFuturePrompt = false
         resetTransientDragState(keepingPendingUncategorizedDrop: true)
         withAnimation(.easeOut(duration: 0.16)) {
-            pendingUncategorizedDrop = nil
+            appGridInteraction.pendingUncategorizedDrop = nil
         }
+        moveDroppedAppToUncategorized(path: path, tags: tags)
+    }
+
+    private func moveDroppedAppToUncategorized(path: String, tags: [String]) {
+        guard !tags.isEmpty else { return }
         TagEditor.removeTags(tags, from: [path])
+        showDropRefresh()
+        refreshApps(forceLayoutRefresh: true)
+    }
+
+    private func dismissTagRemovalDropConfirm() {
+        appGridInteraction.tagRemovalDropSuppressFuturePrompt = false
+        withAnimation(.easeOut(duration: 0.18)) {
+            appGridInteraction.pendingTagRemovalDrop = nil
+        }
+    }
+
+    private func confirmPendingTagRemovalDrop() {
+        guard let pendingDrop = appGridInteraction.pendingTagRemovalDrop else { return }
+        let app = pendingDrop.app
+        let tagName = pendingDrop.tagName
+        let shouldSuppressFuturePrompt = appGridInteraction.tagRemovalDropSuppressFuturePrompt
+        if shouldSuppressFuturePrompt {
+            skipTagRemovalDropConfirm = true
+        }
+        appGridInteraction.tagRemovalDropSuppressFuturePrompt = false
+        withAnimation(.easeOut(duration: 0.16)) {
+            appGridInteraction.pendingTagRemovalDrop = nil
+        }
+        DispatchQueue.main.async {
+            removeTagFromDroppedApp(app: app, tagName: tagName)
+        }
+    }
+
+    private func removeTagFromDroppedApp(app: AppInfo, tagName: String) {
+        guard isRemovableRegularTag(tagName),
+              appHasTag(app, tagName: tagName)
+        else { return }
+        TagEditor.removeTags([tagName], from: [app.path.path])
         showDropRefresh()
         refreshApps(forceLayoutRefresh: true)
     }
@@ -2626,61 +2274,83 @@
         return defaultNames.contains(targetTag)
     }
 
+    private func isRemovableRegularTag(_ tag: String) -> Bool {
+        let protectedNames = [
+            "Mac自带",
+            tr("group.appleBuiltIn"),
+            defaultGroupName,
+            tr("group.uncategorized"),
+            TagDatabase.uncommonTagKey,
+            tr("group.uncommon")
+        ]
+        return !protectedNames.contains(tag) && tagColors[tag] != nil
+    }
+
     private func showDropWarning() {
         withAnimation(.spring(response: 0.24, dampingFraction: 0.82)) {
-            dropWarningToast = tr("drop.systemDefaultWarning")
+            appGridInteraction.dropWarningToast = tr("drop.systemDefaultWarning")
         }
         DispatchQueue.main.asyncAfter(deadline: .now() + 1.6) {
             withAnimation(.easeOut(duration: 0.18)) {
-                dropWarningToast = nil
+                appGridInteraction.dropWarningToast = nil
             }
         }
     }
 
     private func showDropRefresh() {
-        dropRefreshStartedAt = Date()
+        appGridInteraction.dropRefreshStartedAt = Date()
         withAnimation(.spring(response: 0.22, dampingFraction: 0.82)) {
-            dropRefreshVisible = true
+            appGridInteraction.dropRefreshVisible = true
         }
     }
 
     private func finishDropRefreshAfterMinimumDuration() {
         let minimumDuration: TimeInterval = 0.85
-        let elapsed = dropRefreshStartedAt.map { Date().timeIntervalSince($0) } ?? minimumDuration
+        let elapsed = appGridInteraction.dropRefreshStartedAt.map { Date().timeIntervalSince($0) } ?? minimumDuration
         let delay = max(0, minimumDuration - elapsed)
         DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
             withAnimation(.easeOut(duration: 0.18)) {
-                dropRefreshVisible = false
+                appGridInteraction.dropRefreshVisible = false
             }
-            dropRefreshStartedAt = nil
+            appGridInteraction.dropRefreshStartedAt = nil
         }
     }
 
     private func setAppDragMode(_ active: Bool) {
-        guard appDragModeActive != active else { return }
+        guard appGridInteraction.appDragModeActive != active else { return }
         if active {
             endTagNavReorder()
             clearAppBubbleState()
+            appGridInteraction.tagNavigationAppDropTargetName = nil
         }
-        appDragModeActive = active
+        appGridInteraction.appDragModeActive = active
+        if !active {
+            appGridInteraction.tagNavigationAppDropTargetName = nil
+        }
         if active {
             DispatchQueue.main.asyncAfter(deadline: .now() + 8) {
-                if appDragModeActive && !AppDragCoordinator.shared.hasActiveDrag {
-                    appDragModeActive = false
+                if appGridInteraction.appDragModeActive && !AppDragCoordinator.shared.hasActiveDrag {
+                    appGridInteraction.appDragModeActive = false
+                    appGridInteraction.tagNavigationAppDropTargetName = nil
                 }
             }
         }
     }
 
-    private func resetTransientDragState(keepingPendingUncategorizedDrop: Bool = false) {
-        let hadAppDragState = appDragModeActive
+    private func resetTransientDragState(
+        keepingPendingUncategorizedDrop: Bool = false,
+        keepingPendingTagRemovalDrop: Bool = false
+    ) {
+        let hadAppDragState = appGridInteraction.appDragModeActive
         AppDragCoordinator.shared.cancelDrag()
-        scrollInteractionState.reset()
-        if appDragModeActive {
-            appDragModeActive = false
+        if appGridInteraction.appDragModeActive {
+            appGridInteraction.appDragModeActive = false
+        }
+        if appGridInteraction.tagNavigationAppDropTargetName != nil {
+            appGridInteraction.tagNavigationAppDropTargetName = nil
         }
         if hadAppDragState {
-            appDragResetToken &+= 1
+            appGridInteraction.appDragResetToken &+= 1
         }
         if tagNavDragModeActive {
             tagNavDragModeActive = false
@@ -2694,16 +2364,16 @@
         if dragItem != nil {
             dragItem = nil
         }
-        if hoveredContainer != nil {
-            hoveredContainer = nil
-        }
         clearAppBubbleState()
-        if !keepingPendingUncategorizedDrop, pendingUncategorizedDrop != nil {
-            pendingUncategorizedDrop = nil
+        if !keepingPendingUncategorizedDrop, appGridInteraction.pendingUncategorizedDrop != nil {
+            appGridInteraction.pendingUncategorizedDrop = nil
+        }
+        if !keepingPendingTagRemovalDrop, appGridInteraction.pendingTagRemovalDrop != nil {
+            appGridInteraction.pendingTagRemovalDrop = nil
         }
     }
 
-    func refreshApps(forceLayoutRefresh: Bool = false) {
+    func refreshApps(forceLayoutRefresh: Bool = false, useCache: Bool = true) {
         guard !refreshInProgress else {
             if forceLayoutRefresh {
                 refreshAgainAfterCurrent = true
@@ -2714,27 +2384,10 @@
 
         refreshInProgress = true
         DispatchQueue.global(qos: .userInitiated).async {
-            let scannedApps = AppIndexer.scan()
-            let reconciledStore = TagEditor.reconcileScannedApps(scannedApps)
-            let smartStartResult = SmartStartService.runIfNeeded(
-                apps: scannedApps,
-                store: reconciledStore
-            )
-            let store = smartStartResult.store
-            let apps = TagEditor.annotate(apps: scannedApps, store: store)
-            let quickSearchDocs = QuickSearchEngine.makeDocuments(apps: apps, store: store)
-            let colors = store.tags.mapValues { $0.color }
-            let order = TagEditor.orderedTagNames()
+            let result = AppLibraryController.refresh(useCache: useCache)
             DispatchQueue.main.async {
-                allApps = apps
-                quickSearchDocuments = quickSearchDocs
-                tagColors = colors
-                draggedTagNames = order
-                rebuildDisplayGroups(apps: apps, tagOrder: order)
-                if quickSearchVisible {
-                    refreshQuickSearchResults()
-                }
-                handleSmartStartRunResult(smartStartResult)
+                applyAppLibrarySnapshot(result.snapshot)
+                handleSmartStartRunResult(result.smartStartResult)
                 if forceLayoutRefresh {
                     finishDropRefreshAfterMinimumDuration()
                 }
@@ -2749,14 +2402,39 @@
         }
     }
 
+    private func applyAppLibrarySnapshot(_ snapshot: AppLibrarySnapshot) {
+        allApps = snapshot.apps
+        quickSearchDocuments = snapshot.quickSearchDocuments
+        tagColors = snapshot.tagColors
+        draggedTagNames = snapshot.tagOrder
+        rebuildDisplayGroups(apps: snapshot.apps, tagOrder: snapshot.tagOrder)
+        if quickSearchVisible {
+            refreshQuickSearchResults()
+        }
+    }
+
     private func launchApp(
         _ app: AppInfo,
         closeQuickSearchOnSuccess: Bool = false,
         closeOverlayOnSuccess: Bool = true,
         onFailure: (() -> Void)? = nil
     ) {
-        appDragModeActive = false
+        appGridInteraction.appDragModeActive = false
         endTagNavReorder()
+        guard FileManager.default.fileExists(atPath: app.path.path) else {
+            AppIndexer.invalidateScanCache()
+            refreshApps()
+            onFailure?()
+            return
+        }
+
+        let closeQuickSearchAndOverlayBeforeOpening = closeQuickSearchOnSuccess
+            && closeOverlayOnSuccess
+            && (quickSearchCloseHidesOverlay || quickSearchOnlySession)
+        if closeQuickSearchAndOverlayBeforeOpening {
+            closeQuickSearch(hideOverlayIfNeeded: true)
+            hideOverlay()
+        }
         let configuration = NSWorkspace.OpenConfiguration()
         NSWorkspace.shared.openApplication(at: app.path, configuration: configuration) { _, error in
             DispatchQueue.main.async {
@@ -2768,10 +2446,10 @@
                 DispatchQueue.global(qos: .utility).async {
                     TagEditor.recordLauncherOpen(for: app.path.path)
                 }
-                if closeQuickSearchOnSuccess {
-                    closeQuickSearch(hideOverlayIfNeeded: false)
+                if closeQuickSearchOnSuccess && !closeQuickSearchAndOverlayBeforeOpening {
+                    closeQuickSearch(hideOverlayIfNeeded: closeOverlayOnSuccess)
                 }
-                if closeOverlayOnSuccess {
+                if closeOverlayOnSuccess && !closeQuickSearchAndOverlayBeforeOpening {
                     hideOverlay()
                 }
             }
@@ -2779,135 +2457,8 @@
     }
 
     func openApp(_ app: AppInfo) {
-        launchApp(app)
-    }
-}
-
-private final class AppGridScrollInteractionState: ObservableObject {
-    @Published var isFrozen = false
-    private var unfreezeWorkItem: DispatchWorkItem?
-
-    func noteScroll() {
-        if !isFrozen {
-            isFrozen = true
-        }
-        unfreezeWorkItem?.cancel()
-        let workItem = DispatchWorkItem { [weak self] in
-            guard let self, self.isFrozen else { return }
-            self.isFrozen = false
-        }
-        unfreezeWorkItem = workItem
-        DispatchQueue.main.asyncAfter(deadline: .now() + 0.18, execute: workItem)
-    }
-
-    func reset() {
-        unfreezeWorkItem?.cancel()
-        unfreezeWorkItem = nil
-        if isFrozen {
-            isFrozen = false
-        }
-    }
-}
-
-private struct AppGridScrollActivityObserver: NSViewRepresentable {
-    let onScroll: () -> Void
-
-    func makeCoordinator() -> Coordinator {
-        Coordinator(onScroll: onScroll)
-    }
-
-    func makeNSView(context: Context) -> ScrollActivityNSView {
-        let view = ScrollActivityNSView()
-        view.coordinator = context.coordinator
-        return view
-    }
-
-    func updateNSView(_ view: ScrollActivityNSView, context: Context) {
-        context.coordinator.onScroll = onScroll
-        view.coordinator = context.coordinator
-    }
-
-    final class Coordinator {
-        var onScroll: () -> Void
-        private weak var observedClipView: NSClipView?
-        private var observer: NSObjectProtocol?
-        private var lastReportedBoundsOrigin: NSPoint?
-
-        init(onScroll: @escaping () -> Void) {
-            self.onScroll = onScroll
-        }
-
-        func install(from view: NSView) {
-            guard let clipView = view.enclosingScrollView?.contentView else { return }
-            guard observedClipView !== clipView else { return }
-            removeObserver()
-            observedClipView = clipView
-            lastReportedBoundsOrigin = clipView.bounds.origin
-            clipView.postsBoundsChangedNotifications = true
-            observer = NotificationCenter.default.addObserver(
-                forName: NSView.boundsDidChangeNotification,
-                object: clipView,
-                queue: .main
-            ) { [weak self, weak clipView] _ in
-                guard let self,
-                      let clipView,
-                      self.recordScrollIfNeeded(from: clipView)
-                else { return }
-                self.onScroll()
-            }
-        }
-
-        private func removeObserver() {
-            if let observer {
-                NotificationCenter.default.removeObserver(observer)
-            }
-            observer = nil
-            observedClipView = nil
-            lastReportedBoundsOrigin = nil
-        }
-
-        private func recordScrollIfNeeded(from clipView: NSClipView) -> Bool {
-            let origin = clipView.bounds.origin
-            guard let last = lastReportedBoundsOrigin else {
-                lastReportedBoundsOrigin = origin
-                return false
-            }
-            let didScroll = abs(origin.x - last.x) > 0.5
-                || abs(origin.y - last.y) > 0.5
-            if didScroll {
-                lastReportedBoundsOrigin = origin
-            }
-            return didScroll
-        }
-
-        deinit {
-            removeObserver()
-        }
-    }
-
-    final class ScrollActivityNSView: NSView {
-        weak var coordinator: Coordinator?
-        private var installScheduled = false
-
-        override func viewDidMoveToWindow() {
-            super.viewDidMoveToWindow()
-            installObserverIfPossible()
-        }
-
-        override func viewDidMoveToSuperview() {
-            super.viewDidMoveToSuperview()
-            installObserverIfPossible()
-        }
-
-        func installObserverIfPossible() {
-            guard !installScheduled else { return }
-            installScheduled = true
-            DispatchQueue.main.async { [weak self] in
-                guard let self else { return }
-                installScheduled = false
-                coordinator?.install(from: self)
-            }
-        }
+        hideOverlay()
+        launchApp(app, closeOverlayOnSuccess: false)
     }
 }
 
@@ -2927,12 +2478,6 @@
     static func reduce(value: inout [String: CGRect], nextValue: () -> [String: CGRect]) {
         value.merge(nextValue(), uniquingKeysWith: { _, new in new })
     }
-}
-
-private struct TagLabel: Identifiable {
-    var id: String { name }
-    let name: String
-    let colorIndex: Int
 }
 
 // MARK: - NSVisualEffectView bridge

--
Gitblit v1.9.3