Ariver
2026-05-28 efbfc27e0c813c31b570d72fded40eb91d07f2db
Apptag/ContentView.swift
@@ -1,6 +1,5 @@
import SwiftUI
import AppKit
import UniformTypeIdentifiers
// MARK: - Notification for manual re-index
@@ -9,6 +8,9 @@
    static let tagLauncherAppNoteEditingChanged = Notification.Name("TagLauncherAppNoteEditingChanged")
    static let tagLauncherDataDidChange = Notification.Name("TagLauncherDataDidChange")
    static let tagLauncherOpenPreferencesRequested = Notification.Name("TagLauncherOpenPreferencesRequested")
    static let tagLauncherOverlayDidShow = Notification.Name("TagLauncherOverlayDidShow")
    static let tagLauncherOverlayDidHide = Notification.Name("TagLauncherOverlayDidHide")
    static let tagLauncherModalInteractionChanged = Notification.Name("TagLauncherModalInteractionChanged")
}
// MARK: - Edit Phase
@@ -199,7 +201,6 @@
    var dragModeActive: Bool = false
    var isDragging: Bool = false
    let action: () -> Void
    @State private var wiggle = false
    private var bgColor: Color {
        Color(nsColor: TagColor.nsColor(for: colorIndex))
@@ -221,20 +222,13 @@
            .background(RoundedRectangle(cornerRadius: 7).fill(bgColor))
            .shadow(color: .black.opacity(isDragging ? 0.34 : 0.2), radius: isDragging ? 8 : 3, y: isDragging ? 4 : 1)
            .scaleEffect(isDragging ? 1.05 : 1.0)
            .rotationEffect(.degrees(dragModeActive ? (wiggle ? 1.8 : -1.8) : 0))
            .animation(
                dragModeActive
                    ? .easeInOut(duration: 0.12).repeatForever(autoreverses: true)
                    : .default,
                value: wiggle
            )
            .onChange(of: dragModeActive) { _, active in
                wiggle = active
            }
            .opacity(dragModeActive ? (isDragging ? 1.0 : 0.62) : 1.0)
            .animation(.easeOut(duration: 0.08), value: isDragging)
            .animation(.easeOut(duration: 0.08), value: dragModeActive)
            .contentShape(RoundedRectangle(cornerRadius: 7))
            .onTapGesture {
                if !dragModeActive { action() }
        }
                action()
            }
    }
}
@@ -246,7 +240,6 @@
    var dragModeActive: Bool = false
    var isDragging: Bool = false
    let action: () -> Void
    @State private var wiggle = false
    private var bgColor: Color {
        Color(nsColor: TagColor.nsColor(for: colorIndex))
@@ -264,20 +257,13 @@
            .background(RoundedRectangle(cornerRadius: 6).fill(bgColor))
            .shadow(color: .black.opacity(isDragging ? 0.34 : 0.2), radius: isDragging ? 8 : 3, y: isDragging ? 4 : 1)
            .scaleEffect(isDragging ? 1.03 : 1.0)
            .rotationEffect(.degrees(dragModeActive ? (wiggle ? 1.6 : -1.6) : 0))
            .animation(
                dragModeActive
                    ? .easeInOut(duration: 0.12).repeatForever(autoreverses: true)
                    : .default,
                value: wiggle
            )
            .onChange(of: dragModeActive) { _, active in
                wiggle = active
            }
            .opacity(dragModeActive ? (isDragging ? 1.0 : 0.62) : 1.0)
            .animation(.easeOut(duration: 0.08), value: isDragging)
            .animation(.easeOut(duration: 0.08), value: dragModeActive)
            .contentShape(RoundedRectangle(cornerRadius: 6))
            .onTapGesture {
                if !dragModeActive { action() }
        }
                action()
            }
    }
}
@@ -318,6 +304,23 @@
    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 tagRemovalDropSuppressFuturePrompt = false
    var appDragResetToken = 0
    var bubbleDraftNote = ""
    var tagNavigationHoveredGroupName: String? = nil
    var tagNavigationLastHoverScrollID: String? = nil
    var tagNavigationLastHoverScrollAt: Date? = nil
}
private struct EditActionFeedback: Identifiable {
    let id = UUID()
    let title: String
@@ -328,6 +331,13 @@
    let id = UUID()
    let app: AppInfo
    let assignedTags: [String]
    let removableTags: [String]
}
private struct PendingTagRemovalDrop: Identifiable {
    let id = UUID()
    let app: AppInfo
    let tagName: String
}
private enum SmartStartNoticeMode {
@@ -346,10 +356,15 @@
struct ContentView: View {
    let hideOverlay: () -> Void
    private let initialQuickSearchSource: String?
    @Environment(\.colorScheme) private var colorScheme
    @State private var allApps: [AppInfo] = []
    @State private var displayGroups: [TagGroup] = []
    @State private var tagColors: [String: Int] = [:]
    @State private var scrollProxy: ScrollViewProxy? = nil
    @State private var groupLayoutVersion = 0
    @State private var appGridScrollTargetID: String? = nil
    @State private var appGridScrollRequestToken = 0
    // Edit mode
    @State private var editPhase: EditPhase = .none
@@ -364,24 +379,38 @@
    @State private var tagNavDragModeActive = false
    @State private var tagNavDragItem: String? = nil
    @State private var tagNavReorderFrames: [String: CGRect] = [:]
    @State private var hoveredContainer: String? = nil  // colored container lift
    @State private var tagNavReorderDidMove = false
    // 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 hoveredAppItemID: String? = nil
    @State private var hoveredBubble: AppBubbleContext? = nil
    @State private var editingBubble: AppBubbleContext? = nil
    @State private var pendingUncategorizedDrop: PendingUncategorizedDrop? = nil
    @State private var bubbleDraftNote = ""
    @FocusState private var bubbleNoteFocused: Bool
    // Quick Search
    @State private var quickSearchVisible = false
    @State private var quickSearchQuery = ""
    @State private var quickSearchDocuments: [QuickSearchDocument] = []
    @State private var quickSearchResults: [QuickSearchResult] = []
    @State private var quickSearchSelectedID: URL? = nil
    @State private var quickSearchManualSelection = false
    @State private var quickSearchFocusToken = 0
    @State private var quickSearchSelectionScrollToken = 0
    @State private var quickSearchCloseHidesOverlay = false
    @State private var quickSearchErrorMessage: String? = nil
    @State private var initialQuickSearchConsumed = false
    init(hideOverlay: @escaping () -> Void, initialQuickSearchSource: String? = nil) {
        self.hideOverlay = hideOverlay
        self.initialQuickSearchSource = initialQuickSearchSource
        let startsInQuickSearch = initialQuickSearchSource != nil
        _quickSearchVisible = State(initialValue: startsInQuickSearch)
        _quickSearchCloseHidesOverlay = State(initialValue: initialQuickSearchSource == QuickSearchOpenSource.globalHidden)
        _quickSearchFocusToken = State(initialValue: startsInQuickSearch ? 1 : 0)
    }
    // Configurable defaults
    @AppStorage("defaultGroupName") private var defaultGroupName = "Other"
@@ -391,15 +420,31 @@
    @State private var notchHeight: CGFloat = 0
    @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
    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
        appGridInteraction.appDragModeActive
            || appGridInteraction.pendingUncategorizedDrop != nil
            || appGridInteraction.pendingTagRemovalDrop != nil
    }
    private var appGridHighlightedGroupName: String? {
        appGridInteraction.tagNavigationHoveredGroupName
            ?? (isColorlessContainerMode ? filledColorlessContainer : nil)
    }
    private let rightSidebarFloatingClearance: CGFloat = 44
    private let tagNavigationHoverScrollInterval: TimeInterval = 0.22
    private var floatingButtonSurfaceColor: Color {
        colorScheme == .dark
            ? Color.white.opacity(0.10)
            : Color.white.opacity(0.78)
    }
    private var isSideLayout: Bool {
        tagPosition == "left" || tagPosition == "right"
@@ -413,41 +458,48 @@
        displayMode == "container" || displayMode == "gridContainer"
    }
    private var isColoredContainerMode: Bool {
        displayMode == "coloredContainer" || displayMode == "coloredGridContainer"
    private var shouldRenderAppGridBehindQuickSearch: Bool {
        !quickSearchVisible || !quickSearchCloseHidesOverlay
    }
    var body: some View {
        ZStack {
            VisualEffectView(material: .hudWindow, blendingMode: .behindWindow)
                .ignoresSafeArea()
                .allowsHitTesting(false)
            if shouldRenderAppGridBehindQuickSearch {
                VisualEffectView(material: .hudWindow, blendingMode: .behindWindow)
                    .ignoresSafeArea()
                    .allowsHitTesting(false)
            }
            if notchHeight > 0 {
                VStack {
                    Rectangle().fill(.black)
                        .frame(height: notchHeight)
                        .ignoresSafeArea(edges: .top)
                    Spacer()
            if shouldRenderAppGridBehindQuickSearch {
                if notchHeight > 0 {
                    VStack {
                        Rectangle().fill(.black)
                            .frame(height: notchHeight)
                            .ignoresSafeArea(edges: .top)
                        Spacer()
                    }
                    .allowsHitTesting(false)
                }
                .allowsHitTesting(false)
                switch editPhase {
                case .none:
                    normalContent
                case .editingTags:
                    editTagsView
                case .editingApps:
                    editAppsView
                }
                uncommonAppBubbleOverlay
                smartStartNoticeOverlay
                editActionFeedbackOverlay
                uncategorizedDropConfirmOverlay
                tagRemovalDropConfirmOverlay
            }
            switch editPhase {
            case .none:
                normalContent
            case .editingTags:
                editTagsView
            case .editingApps:
                editAppsView
            }
            quickSearchOverlay
            uncommonAppBubbleOverlay
            smartStartNoticeOverlay
            editActionFeedbackOverlay
            uncategorizedDropConfirmOverlay
            if let message = dropWarningToast {
            if shouldRenderAppGridBehindQuickSearch, let message = appGridInteraction.dropWarningToast {
                Text(message)
                    .font(.system(size: 16, weight: .semibold))
                    .foregroundStyle(.primary)
@@ -462,7 +514,7 @@
                    .allowsHitTesting(false)
            }
            if dropRefreshVisible {
            if shouldRenderAppGridBehindQuickSearch && appGridInteraction.dropRefreshVisible {
                Color.black.opacity(0.08)
                    .ignoresSafeArea()
                    .transition(.opacity)
@@ -483,14 +535,41 @@
            }
        }
        .onAppear {
            let mousePoint = NSEvent.mouseLocation
            let activeScreen = NSScreen.screens.first(where: {
                NSMouseInRect(mousePoint, $0.frame, false)
            }) ?? NSScreen.main
            notchHeight = activeScreen?.safeAreaInsets.top ?? 0
            refreshApps()
            refreshNotchHeight()
            refreshAppsIfNeeded()
            if let initialQuickSearchSource, !initialQuickSearchConsumed {
                initialQuickSearchConsumed = true
                quickSearchCloseHidesOverlay = initialQuickSearchSource == QuickSearchOpenSource.globalHidden
                if !quickSearchVisible {
                    quickSearchVisible = true
                    quickSearchFocusToken &+= 1
                }
                refreshQuickSearchResults()
                NotificationCenter.default.post(
                    name: .tagLauncherQuickSearchVisibilityChanged,
                    object: nil,
                    userInfo: ["active": true]
                )
            }
        }
        .onReceive(NotificationCenter.default.publisher(for: .tagLauncherOverlayDidShow)) { _ in
            resetTransientDragState()
            refreshNotchHeight()
            refreshAppsIfNeeded()
        }
        .onReceive(NotificationCenter.default.publisher(for: .tagLauncherOverlayDidHide)) { _ in
            resetTransientDragState()
            closeQuickSearch(notify: true, hideOverlayIfNeeded: false)
        }
        .onReceive(NotificationCenter.default.publisher(for: .tagLauncherQuickSearchRequested)) { notification in
            let source = notification.userInfo?["source"] as? String ?? QuickSearchOpenSource.mainOverlay
            openQuickSearch(source: source)
        }
        .onReceive(NotificationCenter.default.publisher(for: .tagLauncherQuickSearchDismissRequested)) { _ in
            closeQuickSearch()
        }
        .onReceive(NotificationCenter.default.publisher(for: NSApplication.didBecomeActiveNotification)) { _ in
            guard allApps.isEmpty, !refreshInProgress else { return }
            refreshApps()
        }
        .onReceive(NotificationCenter.default.publisher(for: .tagLauncherDataDidChange)) { _ in
@@ -515,10 +594,41 @@
            )
        }
        .onChange(of: bubbleNoteFocused) { _, focused in
            if editingBubble != nil && !focused {
            if appGridInteraction.editingBubble != nil && !focused {
                commitBubbleNote()
            }
        }
        .onChange(of: draggedTagNames) { _, newOrder in
            rebuildDisplayGroups(apps: allApps, tagOrder: newOrder)
        }
        .onChange(of: defaultGroupName) { _, _ in
            rebuildDisplayGroups(apps: allApps, tagOrder: draggedTagNames)
        }
        .onChange(of: quickSearchQuery) { _, _ in
            quickSearchErrorMessage = nil
            refreshQuickSearchResults()
        }
        .onChange(of: appGridInteraction.pendingUncategorizedDrop != nil) { _, _ in
            publishModalInteractionState()
        }
        .onChange(of: appGridInteraction.pendingTagRemovalDrop != nil) { _, _ in
            publishModalInteractionState()
        }
        .onDisappear {
            NotificationCenter.default.post(
                name: .tagLauncherModalInteractionChanged,
                object: nil,
                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.
@@ -538,6 +648,184 @@
                NotificationCenter.default.post(name: .tagLauncherEditModeChanged, object: nil, userInfo: ["active": false])
            }
        }
    }
    // MARK: - Quick Search
    private var quickSearchOverlay: some View {
        GeometryReader { proxy in
            if quickSearchVisible {
                Color.black.opacity(0.001)
                    .frame(width: proxy.size.width, height: proxy.size.height)
                    .ignoresSafeArea()
                    .contentShape(Rectangle())
                    .onTapGesture {
                        closeQuickSearch()
                    }
                    .zIndex(899)
                QuickSearchOverlayView(
                    query: $quickSearchQuery,
                    results: quickSearchResults,
                    selectedID: quickSearchSelectedID,
                    focusToken: quickSearchFocusToken,
                    selectionScrollToken: quickSearchSelectionScrollToken,
                    isLoading: quickSearchDocuments.isEmpty && refreshInProgress,
                    maxVisibleRows: quickSearchMaxVisibleRows(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))
                .zIndex(900)
            }
        }
        .ignoresSafeArea()
        .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 quickSearchPanelTopY(in size: CGSize) -> CGFloat {
        max(notchHeight + 54, min(112, size.height * 0.12))
    }
    private func quickSearchMaxVisibleRows(in size: CGSize) -> Int {
        let bottomClearance: CGFloat = 84
        let chromeHeight: CGFloat = 122
        let rowHeightWithSpacing: CGFloat = 76
        let availableHeight = max(0, size.height - quickSearchPanelTopY(in: size) - bottomClearance - chromeHeight)
        return max(1, min(8, Int(floor(availableHeight / rowHeightWithSpacing))))
    }
    private func openQuickSearch(source: String) {
        guard canOpenQuickSearch else { return }
        dismissAppBubble()
        quickSearchCloseHidesOverlay = source == QuickSearchOpenSource.globalHidden
        quickSearchVisible = true
        quickSearchQuery = ""
        quickSearchManualSelection = false
        quickSearchErrorMessage = nil
        quickSearchFocusToken &+= 1
        refreshQuickSearchResults()
        NotificationCenter.default.post(
            name: .tagLauncherQuickSearchVisibilityChanged,
            object: nil,
            userInfo: ["active": true]
        )
    }
    private var canOpenQuickSearch: Bool {
        editPhase == .none
            && appGridInteraction.pendingUncategorizedDrop == nil
            && smartStartNotice == nil
            && !appGridInteraction.dropRefreshVisible
            && !quickSearchVisible
    }
    private func closeQuickSearch(notify: Bool = true, hideOverlayIfNeeded: Bool = true) {
        let shouldHideOverlay = quickSearchVisible && quickSearchCloseHidesOverlay && hideOverlayIfNeeded
        guard quickSearchVisible else { return }
        quickSearchVisible = false
        quickSearchQuery = ""
        quickSearchResults = []
        quickSearchSelectedID = nil
        quickSearchManualSelection = false
        quickSearchErrorMessage = nil
        quickSearchCloseHidesOverlay = false
        if notify {
            NotificationCenter.default.post(
                name: .tagLauncherQuickSearchVisibilityChanged,
                object: nil,
                userInfo: ["active": false]
            )
        }
        if shouldHideOverlay {
            hideOverlay()
        }
    }
    private func refreshQuickSearchResults() {
        let previousSelection = quickSearchSelectedID
        quickSearchResults = QuickSearchEngine.search(quickSearchQuery, documents: quickSearchDocuments)
        if quickSearchResults.isEmpty {
            quickSearchSelectedID = nil
            quickSearchManualSelection = false
            return
        }
        if quickSearchManualSelection,
           let previousSelection,
           quickSearchResults.contains(where: { $0.id == previousSelection }) {
            quickSearchSelectedID = previousSelection
        } else {
            quickSearchSelectedID = quickSearchResults.first?.id
            quickSearchManualSelection = false
        }
    }
    private func handleQuickSearchCommand(_ command: QuickSearchCommand) {
        switch command {
        case .moveUp:
            moveQuickSearchSelection(by: -1)
        case .moveDown:
            moveQuickSearchSelection(by: 1)
        case .submit:
            guard let selected = selectedQuickSearchResult else { return }
            launchQuickSearchResult(selected)
        case .dismiss:
            closeQuickSearch()
        }
    }
    private var selectedQuickSearchResult: QuickSearchResult? {
        guard let quickSearchSelectedID else { return nil }
        return quickSearchResults.first { $0.id == quickSearchSelectedID }
    }
    private func moveQuickSearchSelection(by delta: Int) {
        guard !quickSearchResults.isEmpty else { return }
        let currentIndex = quickSearchSelectedID.flatMap { id in
            quickSearchResults.firstIndex { $0.id == id }
        } ?? 0
        let nextIndex = min(max(currentIndex + delta, 0), quickSearchResults.count - 1)
        quickSearchSelectedID = quickSearchResults[nextIndex].id
        quickSearchManualSelection = true
        quickSearchSelectionScrollToken &+= 1
    }
    private func selectQuickSearchResult(_ result: QuickSearchResult) {
        guard quickSearchSelectedID != result.id || !quickSearchManualSelection else { return }
        quickSearchSelectedID = result.id
        quickSearchManualSelection = true
    }
    private func launchQuickSearchResult(_ result: QuickSearchResult) {
        quickSearchErrorMessage = nil
        launchApp(
            result.app,
            closeQuickSearchOnSuccess: true,
            closeOverlayOnSuccess: true,
            onFailure: {
                quickSearchErrorMessage = tr("quickSearch.launchFailed")
                quickSearchFocusToken &+= 1
                NSAccessibility.post(
                    element: NSApp.mainWindow as Any,
                    notification: .announcementRequested,
                    userInfo: [.announcement: tr("quickSearch.launchFailed")]
                )
            }
        )
    }
    // MARK: - Normal Content
@@ -578,7 +866,7 @@
    ) -> some View {
        NativeFloatingIconButton(systemImage: systemImage, action: action)
            .frame(width: 36, height: 36)
            .background(Circle().fill(.ultraThinMaterial))
            .background(Circle().fill(floatingButtonSurfaceColor))
    }
    // MARK: - Top / Side Layouts
@@ -586,7 +874,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
        }
@@ -597,14 +885,79 @@
            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
        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,
            onActivate: { tagID in
                activateTagNavigation(tagID)
            },
            onHoverChange: { tagID, active in
                handleTagNavigationHover(tagID, active: active)
            },
            canReorder: { tagID in
                canReorderTag(tagID)
            },
            onReorderBegan: { tagID in
                beginTagNavReorder(tagID)
            },
            onReorderMoved: { tagID, targetID in
                reorderTagNavItem(fromName: tagID, to: targetID)
            },
            onReorderEnded: {
                endTagNavReorder()
            }
        )
    }
    private var swiftUITopTagBar: some View {
        ScrollView(.horizontal, showsIndicators: false) {
            HStack(spacing: 8) {
                ForEach(tagLabels) { tag in
@@ -612,19 +965,13 @@
                            dragModeActive: tagNavDragModeActive && canReorderTag(tag.name),
                            isDragging: tagNavDragItem == tag.name,
                            action: {
                        if isColorlessContainerMode {
                            toggleColorlessFill(tag.id)
                        }
                        scrollTo(tag.id)
                        activateTagNavigation(tag.id)
                    })
                    .background(tagNavFrameReader(for: tag.name))
                    .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)
                    }
                }
            }
@@ -637,18 +984,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
@@ -656,19 +992,13 @@
                                dragModeActive: tagNavDragModeActive && canReorderTag(tag.name),
                                isDragging: tagNavDragItem == tag.name,
                                action: {
                        if isColorlessContainerMode {
                            toggleColorlessFill(tag.id)
                        }
                        scrollTo(tag.id)
                        activateTagNavigation(tag.id)
                    })
                    .background(tagNavFrameReader(for: tag.name))
                    .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)
                    }
                }
            }
@@ -690,21 +1020,45 @@
                Spacer()
                ProgressView().scaleEffect(0.8)
                Spacer()
            } else if displayMode == "gridContainer" || displayMode == "coloredGridContainer" {
                gridContainerGrid
            } else if displayMode == "container" || displayMode == "coloredContainer" {
                containerGrid
            } else {
                flatGrid
                AppGridCollectionView(
                    groups: displayGroups,
                    tagColors: tagColors,
                    displayMode: displayMode,
                    iconSize: iconSize,
                    showNames: !hideAppNames,
                    bubbleDisabled: appBubbleDisabled,
                    showUncommonAppBubbles: showUncommonAppBubbles,
                    highlightedGroupName: appGridHighlightedGroupName,
                    contentRevision: groupLayoutVersion,
                    scrollTargetID: appGridScrollTargetID,
                    scrollRequestToken: appGridScrollRequestToken,
                    onSelectApp: { app in openApp(app) },
                    onBubbleHover: handleBubbleHover,
                    onEditNote: beginEditingBubbleNote,
                    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 isColorlessContainerMode {
                            toggleColorlessFill(groupName)
                        }
                    },
                    onScrollActivity: handleAppGridScrollActivity,
                    onDragModeChange: { setAppDragMode($0) }
                )
            }
        }
    }
    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(
@@ -717,12 +1071,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
@@ -735,7 +1089,7 @@
            }
        }
        .ignoresSafeArea()
        .allowsHitTesting(editingBubble != nil)
        .allowsHitTesting(appGridInteraction.editingBubble != nil)
    }
    private var smartStartNoticeOverlay: some View {
@@ -822,443 +1176,6 @@
        .ignoresSafeArea()
        .allowsHitTesting(smartStartNotice != nil)
    }
    private var flatGrid: some View {
        ScrollViewReader { proxy in
            ScrollView {
                LazyVStack(alignment: .leading, spacing: 24) {
                    ForEach(groups) { 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,
                            hoveredAppItemID: $hoveredAppItemID,
                            onDropApp: { path, source, copy in
                                dropApp(path: path, sourceTag: source, targetTag: group.name, copy: copy)
                            }
                        ).id(group.id)
                    }
                }.padding(20)
            }
            .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: groups, 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)
                }
                .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,
                        itemID: "\(group.name)|\(app.path.path)",
                        hoveredAppItemID: $hoveredAppItemID,
                        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(.ultraThinMaterial)
                )
        )
        .overlay(
            RoundedRectangle(cornerRadius: 14)
                .stroke(Color.primary.opacity(0.08), lineWidth: 1)
        )
        .overlay {
            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)
        .onHover { hovering in
            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 rows = gridContainerRows(groups: groups, trackCount: preferredCount, availableWidth: available, gap: gap)
            ScrollViewReader { proxy in
                ScrollView {
                    VStack(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)
                }
                .id(displayMode)
                .onAppear { scrollProxy = proxy }
            }
        }
    }
    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 GridContainerCandidate {
        let spans: [Int]
        let rows: Int
        let cost: CGFloat
    }
    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,
                                itemID: "\(group.name)|\(app.path.path)",
                                hoveredAppItemID: $hoveredAppItemID,
                                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(.ultraThinMaterial)
                )
        )
        .overlay(
            RoundedRectangle(cornerRadius: 14)
                .stroke(Color.primary.opacity(0.08), lineWidth: 1)
        )
        .overlay {
            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)
        .onHover { hovering in
            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 {
@@ -1383,8 +1300,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
                    )
@@ -1578,7 +1495,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()
@@ -1599,7 +1516,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 {
@@ -1753,14 +1698,20 @@
            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()
            DispatchQueue.main.async {
                pendingSmartStartDraft = nil
                allApps = apps
                quickSearchDocuments = quickSearchDocs
                tagColors = colors
                draggedTagNames = order
                rebuildDisplayGroups(apps: apps, tagOrder: order)
                if quickSearchVisible {
                    refreshQuickSearchResults()
                }
                if let summary = result.summary {
                    showSmartStartNotice(mode: .manuallyApplied, summary: summary)
                } else {
@@ -1819,17 +1770,10 @@
        tagName == TagDatabase.uncommonTagKey ? tr("group.uncommon") : tagName
    }
    private var tagLabels: [TagLabel] {
        groups.map { TagLabel(name: $0.name, colorIndex: tagColors[$0.name] ?? 0) }
    }
    private var groups: [TagGroup] {
        let order = draggedTagNames.isEmpty
            ? TagEditor.orderedTagNames()
            : draggedTagNames
        let raw = AppIndexer.group(apps: allApps, defaultGroupName: defaultGroupName, tagOrder: order)
        // Translate stable keys for display
        return raw.map { group in
    private func makeDisplayGroups(apps: [AppInfo], tagOrder: [String]) -> [TagGroup] {
        let order = tagOrder.isEmpty ? TagEditor.orderedTagNames() : tagOrder
        let rawGroups = AppIndexer.group(apps: apps, defaultGroupName: defaultGroupName, tagOrder: order)
        return rawGroups.map { group in
            if group.name == defaultGroupName {
                return TagGroup(name: tr("group.uncategorized"), apps: group.apps)
            }
@@ -1840,8 +1784,17 @@
        }
    }
    private func rebuildDisplayGroups(apps: [AppInfo], tagOrder: [String]) {
        displayGroups = makeDisplayGroups(apps: apps, tagOrder: tagOrder)
        groupLayoutVersion &+= 1
    }
    private var tagLabels: [TagNavigationItem] {
        displayGroups.map { TagNavigationItem(name: $0.name, colorIndex: tagColors[$0.name] ?? 0) }
    }
    private var editGroups: [TagGroup] {
        groups + [
        displayGroups + [
            TagGroup(
                name: tr("group.uncommon"),
                apps: allApps.filter(\.isUncommon).sorted {
@@ -1853,16 +1806,39 @@
    // MARK: - Actions
    private func handleBubbleHover(app: AppInfo, frame: CGRect, hovering: Bool) {
    private func refreshAppsIfNeeded() {
        guard allApps.isEmpty, !refreshInProgress else { return }
        refreshApps()
    }
    private func refreshNotchHeight() {
        let mousePoint = NSEvent.mouseLocation
        let activeScreen = NSScreen.screens.first(where: {
            NSMouseInRect(mousePoint, $0.frame, false)
        }) ?? NSScreen.main
        notchHeight = activeScreen?.safeAreaInsets.top ?? 0
    }
    private func handleAppGridScrollActivity() {
        appGridInteraction.hoveredBubble = nil
    }
    private func handleBubbleHover(app: AppInfo, frame: CGRect, event: AppBubbleHoverEvent) {
        guard !appBubbleDisabled else {
            clearAppBubbleState()
            return
        }
        guard editingBubble == nil else { return }
        if hovering {
            hoveredBubble = AppBubbleContext(app: app, frame: frame)
        } else if hoveredBubble?.app.path == app.path {
            hoveredBubble = nil
        guard appGridInteraction.editingBubble == nil else { return }
        switch event {
        case .entered(let canShowBubble):
            if canShowBubble {
                appGridInteraction.hoveredBubble = AppBubbleContext(app: app, frame: frame)
            } else {
                appGridInteraction.hoveredBubble = nil
            }
        case .exited:
            guard appGridInteraction.hoveredBubble?.app.path == app.path else { return }
            appGridInteraction.hoveredBubble = nil
        }
    }
@@ -1871,9 +1847,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
@@ -1881,34 +1857,37 @@
    }
    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() {
        hoveredAppItemID = nil
        hoveredBubble = nil
        if editingBubble != nil {
            notifyAppNoteEditing(active: false)
        if appGridInteraction.hoveredBubble != nil {
            appGridInteraction.hoveredBubble = nil
        }
        editingBubble = nil
        bubbleNoteFocused = false
        if appGridInteraction.editingBubble != nil {
            notifyAppNoteEditing(active: false)
            appGridInteraction.editingBubble = nil
        }
        if bubbleNoteFocused {
            bubbleNoteFocused = false
        }
    }
    private func notifyAppNoteEditing(active: Bool) {
@@ -1972,7 +1951,41 @@
    }
    func scrollTo(_ id: String) {
        withAnimation(.easeInOut(duration: 0.25)) { scrollProxy?.scrollTo(id, anchor: .top) }
        appGridScrollTargetID = id
        appGridScrollRequestToken &+= 1
    }
    private func activateTagNavigation(_ id: String) {
        cancelTagNavReorderVisualState()
        if isColorlessContainerMode {
            toggleColorlessFill(id)
        }
        scrollTo(id)
    }
    private func handleTagNavigationHover(_ id: String, active: Bool) {
        guard active else {
            if appGridInteraction.tagNavigationHoveredGroupName == id {
                appGridInteraction.tagNavigationHoveredGroupName = nil
            }
            return
        }
        appGridInteraction.tagNavigationHoveredGroupName = id
        fillColorlessContainer(id)
        scrollToTagFromHover(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)
    }
    private func fillColorlessContainer(_ id: String) {
@@ -2002,8 +2015,8 @@
    }
    private func tagNavReorderGesture(for tagName: String) -> some Gesture {
        LongPressGesture(minimumDuration: 0.5)
            .sequenced(before: DragGesture(minimumDistance: 3, coordinateSpace: .named("tagNavReorder")))
        LongPressGesture(minimumDuration: 0.35)
            .sequenced(before: DragGesture(minimumDistance: 0, coordinateSpace: .named("tagNavReorder")))
            .onChanged { value in
                guard canReorderTag(tagName) else { return }
                switch value {
@@ -2029,61 +2042,53 @@
        guard canReorderTag(tagName) else { return }
        if tagNavDragItem == nil {
            tagNavDragItem = tagName
            tagNavReorderDidMove = false
        }
        tagNavDragModeActive = true
    }
    private func endTagNavReorder() {
        if tagNavDragModeActive {
        let hadDragState = tagNavDragModeActive || tagNavDragItem != nil
        guard hadDragState else { return }
        if tagNavDragModeActive && tagNavReorderDidMove {
            TagEditor.reorderTags(draggedTagNames)
        }
        tagNavDragModeActive = false
        tagNavDragItem = nil
        tagNavReorderDidMove = false
    }
    private func cancelTagNavReorderVisualState() {
        guard tagNavDragModeActive || tagNavDragItem != nil else { return }
        tagNavDragModeActive = false
        tagNavDragItem = nil
        tagNavReorderDidMove = false
    }
    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) {
        appDragModeActive = false
        resetTransientDragState(keepingPendingUncategorizedDrop: true)
        if isUncategorizedDropTarget(targetTag) {
            confirmAndMoveAppToUncategorized(path: path)
@@ -2108,20 +2113,55 @@
        refreshApps(forceLayoutRefresh: true)
    }
    private func confirmAndMoveAppToUncategorized(path: String) {
        guard let app = allApps.first(where: { $0.path.path == path }) else { return }
        let assignedTags = assignedRegularDisplayTags(for: app)
        guard !assignedTags.isEmpty else { return }
    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)
        clearAppBubbleState()
        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)
@@ -2134,27 +2174,73 @@
        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() {
        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
        resetTransientDragState(keepingPendingUncategorizedDrop: true)
        withAnimation(.easeOut(duration: 0.16)) {
            pendingUncategorizedDrop = nil
            appGridInteraction.pendingUncategorizedDrop = nil
        }
        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)
    }
@@ -2175,55 +2261,103 @@
        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 appGridInteraction.appDragModeActive != active else { return }
        if active {
            endTagNavReorder()
            clearAppBubbleState()
        }
        appDragModeActive = active
        appGridInteraction.appDragModeActive = active
        if active {
            DispatchQueue.main.asyncAfter(deadline: .now() + 8) {
                if appDragModeActive {
                    appDragModeActive = false
                if appGridInteraction.appDragModeActive && !AppDragCoordinator.shared.hasActiveDrag {
                    appGridInteraction.appDragModeActive = false
                }
            }
        }
    }
    private func resetTransientDragState(
        keepingPendingUncategorizedDrop: Bool = false,
        keepingPendingTagRemovalDrop: Bool = false
    ) {
        let hadAppDragState = appGridInteraction.appDragModeActive
        AppDragCoordinator.shared.cancelDrag()
        if appGridInteraction.appDragModeActive {
            appGridInteraction.appDragModeActive = false
        }
        if hadAppDragState {
            appGridInteraction.appDragResetToken &+= 1
        }
        if tagNavDragModeActive {
            tagNavDragModeActive = false
        }
        if tagNavDragItem != nil {
            tagNavDragItem = nil
        }
        if tagNavReorderDidMove {
            tagNavReorderDidMove = false
        }
        if dragItem != nil {
            dragItem = nil
        }
        clearAppBubbleState()
        if !keepingPendingUncategorizedDrop, appGridInteraction.pendingUncategorizedDrop != nil {
            appGridInteraction.pendingUncategorizedDrop = nil
        }
        if !keepingPendingTagRemovalDrop, appGridInteraction.pendingTagRemovalDrop != nil {
            appGridInteraction.pendingTagRemovalDrop = nil
        }
    }
    func refreshApps(forceLayoutRefresh: Bool = false) {
        guard !refreshInProgress else {
            refreshAgainAfterCurrent = true
            refreshAgainForceLayout = refreshAgainForceLayout || forceLayoutRefresh
            if forceLayoutRefresh {
                refreshAgainAfterCurrent = true
                refreshAgainForceLayout = true
            }
            return
        }
@@ -2237,12 +2371,18 @@
            )
            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()
            DispatchQueue.main.async {
                allApps = apps
                quickSearchDocuments = quickSearchDocs
                tagColors = colors
                draggedTagNames = order
                rebuildDisplayGroups(apps: apps, tagOrder: order)
                if quickSearchVisible {
                    refreshQuickSearchResults()
                }
                handleSmartStartRunResult(smartStartResult)
                if forceLayoutRefresh {
                    finishDropRefreshAfterMinimumDuration()
@@ -2258,15 +2398,38 @@
        }
    }
    func openApp(_ app: AppInfo) {
        appDragModeActive = false
    private func launchApp(
        _ app: AppInfo,
        closeQuickSearchOnSuccess: Bool = false,
        closeOverlayOnSuccess: Bool = true,
        onFailure: (() -> Void)? = nil
    ) {
        appGridInteraction.appDragModeActive = false
        endTagNavReorder()
        hideOverlay()
        DispatchQueue.global(qos: .utility).async {
            TagEditor.recordLauncherOpen(for: app.path.path)
        }
        let configuration = NSWorkspace.OpenConfiguration()
        NSWorkspace.shared.openApplication(at: app.path, configuration: configuration)
        NSWorkspace.shared.openApplication(at: app.path, configuration: configuration) { _, error in
            DispatchQueue.main.async {
                guard error == nil else {
                    onFailure?()
                    return
                }
                DispatchQueue.global(qos: .utility).async {
                    TagEditor.recordLauncherOpen(for: app.path.path)
                }
                if closeQuickSearchOnSuccess {
                    closeQuickSearch(hideOverlayIfNeeded: false)
                }
                if closeOverlayOnSuccess {
                    hideOverlay()
                }
            }
        }
    }
    func openApp(_ app: AppInfo) {
        hideOverlay()
        launchApp(app, closeOverlayOnSuccess: false)
    }
}
@@ -2286,12 +2449,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