Ariver
2026-05-22 8478c55e513bbbb4b1676d1d9207f7feb2509465
Apptag/ContentView.swift
@@ -9,6 +9,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 +202,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 +223,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 +241,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 +258,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()
            }
    }
}
@@ -346,10 +333,19 @@
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
    @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
    // Edit mode
    @State private var editPhase: EditPhase = .none
@@ -364,6 +360,7 @@
    @State private var tagNavDragModeActive = false
    @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
@@ -376,12 +373,34 @@
    @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 appDragResetToken = 0
    @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,12 +410,28 @@
    @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
    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
    }
    private let rightSidebarFloatingClearance: CGFloat = 44
    private var cardSurfaceColor: Color {
        colorScheme == .dark
            ? Color.white.opacity(0.055)
            : Color.white.opacity(0.62)
    }
    private var floatingButtonSurfaceColor: Color {
        colorScheme == .dark
            ? Color.white.opacity(0.10)
            : Color.white.opacity(0.78)
    }
    private var isSideLayout: Bool {
        tagPosition == "left" || tagPosition == "right"
@@ -414,37 +449,47 @@
        displayMode == "coloredContainer" || displayMode == "coloredGridContainer"
    }
    private var usesAppKitContainerGrid: Bool {
        displayMode == "gridContainer" || displayMode == "coloredGridContainer"
    }
    var body: some View {
        ZStack {
            VisualEffectView(material: .hudWindow, blendingMode: .behindWindow)
                .ignoresSafeArea()
                .allowsHitTesting(false)
            if !quickSearchVisible {
                VisualEffectView(material: .hudWindow, blendingMode: .behindWindow)
                    .ignoresSafeArea()
                    .allowsHitTesting(false)
            }
            if notchHeight > 0 {
                VStack {
                    Rectangle().fill(.black)
                        .frame(height: notchHeight)
                        .ignoresSafeArea(edges: .top)
                    Spacer()
            if !quickSearchVisible {
                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
            }
            switch editPhase {
            case .none:
                normalContent
            case .editingTags:
                editTagsView
            case .editingApps:
                editAppsView
            }
            quickSearchOverlay
            uncommonAppBubbleOverlay
            smartStartNoticeOverlay
            editActionFeedbackOverlay
            uncategorizedDropConfirmOverlay
            if let message = dropWarningToast {
            if !quickSearchVisible, let message = dropWarningToast {
                Text(message)
                    .font(.system(size: 16, weight: .semibold))
                    .foregroundStyle(.primary)
@@ -459,7 +504,7 @@
                    .allowsHitTesting(false)
            }
            if dropRefreshVisible {
            if !quickSearchVisible && dropRefreshVisible {
                Color.black.opacity(0.08)
                    .ignoresSafeArea()
                    .transition(.opacity)
@@ -480,14 +525,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
@@ -516,6 +588,30 @@
                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: pendingUncategorizedDrop != nil) { _, active in
            NotificationCenter.default.post(
                name: .tagLauncherModalInteractionChanged,
                object: nil,
                userInfo: ["active": active]
            )
        }
        .onDisappear {
            NotificationCenter.default.post(
                name: .tagLauncherModalInteractionChanged,
                object: nil,
                userInfo: ["active": false]
            )
        }
    }
    /// Set edit phase with synchronous notification BEFORE state change.
@@ -535,6 +631,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
            && pendingUncategorizedDrop == nil
            && smartStartNotice == nil
            && !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
@@ -575,7 +849,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
@@ -609,10 +883,7 @@
                            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)
@@ -653,10 +924,7 @@
                                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)
@@ -687,8 +955,33 @@
                Spacer()
                ProgressView().scaleEffect(0.8)
                Spacer()
            } else if displayMode == "gridContainer" || displayMode == "coloredGridContainer" {
                gridContainerGrid
            } else if usesAppKitContainerGrid {
                AppGridCollectionView(
                    groups: displayGroups,
                    tagColors: tagColors,
                    displayMode: displayMode,
                    iconSize: iconSize,
                    showNames: !hideAppNames,
                    bubbleDisabled: appBubbleDisabled,
                    showUncommonAppBubbles: showUncommonAppBubbles,
                    highlightedGroupName: filledColorlessContainer,
                    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)
                    },
                    onGroupActivate: { groupName in
                        if displayMode == "gridContainer" {
                            toggleColorlessFill(groupName)
                        }
                    },
                    onScrollActivity: handleAppGridScrollActivity,
                    onDragModeChange: { setAppDragMode($0) }
                )
            } else if displayMode == "container" || displayMode == "coloredContainer" {
                containerGrid
            } else {
@@ -823,7 +1116,7 @@
        ScrollViewReader { proxy in
            ScrollView {
                LazyVStack(alignment: .leading, spacing: 24) {
                    ForEach(groups) { group in
                    ForEach(displayGroups) { group in
                        TagGroupView(
                            group: group,
                            onSelectApp: { app in openApp(app) },
@@ -834,13 +1127,17 @@
                            onDragModeChange: { setAppDragMode($0) },
                            onBubbleHover: handleBubbleHover,
                            onEditNote: beginEditingBubbleNote,
                            hoveredAppItemID: $hoveredAppItemID,
                            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)
                }
                .padding(20)
                .background(AppGridScrollActivityObserver(onScroll: handleAppGridScrollActivity))
            }
            .id(displayMode)  // force rebuild on mode switch
            .onAppear { scrollProxy = proxy }
@@ -856,7 +1153,7 @@
            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)
            let columns = distributeToColumns(groups: displayGroups, colCount: colCount, colWidth: actualColW)
            ScrollViewReader { proxy in
                ScrollView {
@@ -871,6 +1168,7 @@
                        }
                    }
                    .padding(outerPad)
                    .background(AppGridScrollActivityObserver(onScroll: handleAppGridScrollActivity))
                }
                .id(displayMode)  // force rebuild on mode switch
                .onAppear { scrollProxy = proxy }
@@ -937,8 +1235,10 @@
                        onDragModeChange: { setAppDragMode($0) },
                        onBubbleHover: handleBubbleHover,
                        onEditNote: beginEditingBubbleNote,
                        bubbleDisabled: appBubbleDisabled,
                        showUncommonAppBubbles: showUncommonAppBubbles,
                        itemID: "\(group.name)|\(app.path.path)",
                        hoveredAppItemID: $hoveredAppItemID,
                        dragResetToken: appDragResetToken,
                        onSelect: { openApp(app) }
                    )
                }
@@ -951,7 +1251,7 @@
                .fill((isColored || isColorlessActive) ? tagColor.opacity(0.30) : Color.clear)
                .background(
                    RoundedRectangle(cornerRadius: 14)
                        .fill(.ultraThinMaterial)
                        .fill(cardSurfaceColor)
                )
        )
        .overlay(
@@ -959,10 +1259,12 @@
                .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)
            if appDragModeActive {
                AppDropTargetView(targetTag: group.name) { path, source, copy in
                    dropApp(path: path, sourceTag: source, targetTag: group.name, copy: copy)
                }
                .allowsHitTesting(false)
            }
            .allowsHitTesting(false)
        }
        .shadow(color: .black.opacity((isColored && isHovered) || isColorlessActive ? 0.22 : 0),
                radius: (isColored && isHovered) || isColorlessActive ? 8 : 0,
@@ -970,11 +1272,17 @@
        .zIndex(isHovered ? 50 : 0)
        .animation(.easeOut(duration: 0.045), value: isHovered)
        .animation(.easeOut(duration: 0.08), value: isColorlessFilled)
        .onHover { hovering in
        .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 {
@@ -992,11 +1300,23 @@
            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)
            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 {
                    VStack(alignment: .leading, spacing: gap) {
                    LazyVStack(alignment: .leading, spacing: gap) {
                        ForEach(Array(rows.indices), id: \.self) { rowIndex in
                            let row = rows[rowIndex]
@@ -1011,9 +1331,28 @@
                    }
                    .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
                    )
                }
            }
        }
    }
@@ -1035,10 +1374,52 @@
        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
        )
    }
    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] {
@@ -1175,8 +1556,10 @@
                                onDragModeChange: { setAppDragMode($0) },
                                onBubbleHover: handleBubbleHover,
                                onEditNote: beginEditingBubbleNote,
                                bubbleDisabled: appBubbleDisabled,
                                showUncommonAppBubbles: showUncommonAppBubbles,
                                itemID: "\(group.name)|\(app.path.path)",
                                hoveredAppItemID: $hoveredAppItemID,
                                dragResetToken: appDragResetToken,
                                onSelect: { openApp(app) }
                            )
                                .frame(width: cellWidth)
@@ -1201,7 +1584,7 @@
                .fill((isColored || isColorlessGridActive) ? tagColor.opacity(0.30) : Color.clear)
                .background(
                    RoundedRectangle(cornerRadius: 14)
                        .fill(.ultraThinMaterial)
                        .fill(cardSurfaceColor)
                )
        )
        .overlay(
@@ -1209,10 +1592,12 @@
                .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)
            if appDragModeActive {
                AppDropTargetView(targetTag: group.name) { path, source, copy in
                    dropApp(path: path, sourceTag: source, targetTag: group.name, copy: copy)
                }
                .allowsHitTesting(false)
            }
            .allowsHitTesting(false)
        }
        .shadow(color: .black.opacity((isColored && isHovered) || isColorlessGridActive ? 0.22 : 0),
                radius: (isColored && isHovered) || isColorlessGridActive ? 8 : 0,
@@ -1220,13 +1605,19 @@
        .zIndex(isHovered ? 50 : 0)
        .animation(.easeOut(duration: 0.045), value: isHovered)
        .animation(.easeOut(duration: 0.08), value: isColorlessFilled)
        .onHover { hovering in
        .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 {
@@ -1747,14 +2138,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 {
@@ -1813,17 +2210,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)
            }
@@ -1834,8 +2224,18 @@
        }
    }
    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 editGroups: [TagGroup] {
        groups + [
        displayGroups + [
            TagGroup(
                name: tr("group.uncommon"),
                apps: allApps.filter(\.isUncommon).sorted {
@@ -1847,16 +2247,51 @@
    // 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() {
        if !scrollInteractionState.isFrozen {
            hoveredBubble = nil
            hoveredContainer = nil
        }
        scrollInteractionState.noteScroll()
    }
    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 {
        switch event {
        case .entered(let canShowBubble):
            if canShowBubble {
                hoveredBubble = AppBubbleContext(app: app, frame: frame)
            } else {
                hoveredBubble = nil
            }
        case .exited:
            guard hoveredBubble?.app.path == app.path else { return }
            hoveredBubble = nil
        }
    }
    private func beginEditingBubbleNote(app: AppInfo, frame: CGRect) {
        guard !appBubbleDisabled else {
            clearAppBubbleState()
            return
        }
        bubbleDraftNote = currentNote(for: app)
        hoveredBubble = nil
        editingBubble = AppBubbleContext(app: app, frame: frame)
@@ -1885,6 +2320,19 @@
        }
        editingBubble = nil
        bubbleNoteFocused = false
    }
    private func clearAppBubbleState() {
        if hoveredBubble != nil {
            hoveredBubble = nil
        }
        if editingBubble != nil {
            notifyAppNoteEditing(active: false)
            editingBubble = nil
        }
        if bubbleNoteFocused {
            bubbleNoteFocused = false
        }
    }
    private func notifyAppNoteEditing(active: Bool) {
@@ -1948,7 +2396,20 @@
    }
    func scrollTo(_ id: String) {
        withAnimation(.easeInOut(duration: 0.25)) { scrollProxy?.scrollTo(id, anchor: .top) }
        if usesAppKitContainerGrid {
            appGridScrollTargetID = id
            appGridScrollRequestToken &+= 1
        } else {
            withAnimation(.easeInOut(duration: 0.25)) { scrollProxy?.scrollTo(id, anchor: .top) }
        }
    }
    private func activateTagNavigation(_ id: String) {
        cancelTagNavReorderVisualState()
        if isColorlessContainerMode {
            toggleColorlessFill(id)
        }
        scrollTo(id)
    }
    private func fillColorlessContainer(_ id: String) {
@@ -1978,8 +2439,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 {
@@ -2005,16 +2466,27 @@
        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) {
@@ -2025,6 +2497,7 @@
              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)
@@ -2059,7 +2532,7 @@
    }
    private func dropApp(path: String, sourceTag: String, targetTag: String, copy: Bool) {
        appDragModeActive = false
        resetTransientDragState(keepingPendingUncategorizedDrop: true)
        if isUncategorizedDropTarget(targetTag) {
            confirmAndMoveAppToUncategorized(path: path)
@@ -2089,6 +2562,7 @@
        let assignedTags = assignedRegularDisplayTags(for: app)
        guard !assignedTags.isEmpty else { return }
        clearAppBubbleState()
        withAnimation(.spring(response: 0.24, dampingFraction: 0.84)) {
            pendingUncategorizedDrop = PendingUncategorizedDrop(app: app, assignedTags: assignedTags)
        }
@@ -2117,6 +2591,7 @@
    }
    private func dismissUncategorizedDropConfirm() {
        resetTransientDragState(keepingPendingUncategorizedDrop: true)
        withAnimation(.easeOut(duration: 0.18)) {
            pendingUncategorizedDrop = nil
        }
@@ -2126,6 +2601,7 @@
        guard let pendingDrop = pendingUncategorizedDrop else { return }
        let path = pendingDrop.app.path.path
        let tags = pendingDrop.app.tags
        resetTransientDragState(keepingPendingUncategorizedDrop: true)
        withAnimation(.easeOut(duration: 0.16)) {
            pendingUncategorizedDrop = nil
        }
@@ -2181,23 +2657,58 @@
    }
    private func setAppDragMode(_ active: Bool) {
        guard appDragModeActive != active else { return }
        if active {
            endTagNavReorder()
            clearAppBubbleState()
        }
        appDragModeActive = active
        if active {
            DispatchQueue.main.asyncAfter(deadline: .now() + 8) {
                if appDragModeActive {
                if appDragModeActive && !AppDragCoordinator.shared.hasActiveDrag {
                    appDragModeActive = false
                }
            }
        }
    }
    private func resetTransientDragState(keepingPendingUncategorizedDrop: Bool = false) {
        let hadAppDragState = appDragModeActive
        AppDragCoordinator.shared.cancelDrag()
        scrollInteractionState.reset()
        if appDragModeActive {
            appDragModeActive = false
        }
        if hadAppDragState {
            appDragResetToken &+= 1
        }
        if tagNavDragModeActive {
            tagNavDragModeActive = false
        }
        if tagNavDragItem != nil {
            tagNavDragItem = nil
        }
        if tagNavReorderDidMove {
            tagNavReorderDidMove = false
        }
        if dragItem != nil {
            dragItem = nil
        }
        if hoveredContainer != nil {
            hoveredContainer = nil
        }
        clearAppBubbleState()
        if !keepingPendingUncategorizedDrop, pendingUncategorizedDrop != nil {
            pendingUncategorizedDrop = nil
        }
    }
    func refreshApps(forceLayoutRefresh: Bool = false) {
        guard !refreshInProgress else {
            refreshAgainAfterCurrent = true
            refreshAgainForceLayout = refreshAgainForceLayout || forceLayoutRefresh
            if forceLayoutRefresh {
                refreshAgainAfterCurrent = true
                refreshAgainForceLayout = true
            }
            return
        }
@@ -2211,12 +2722,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()
@@ -2232,15 +2749,165 @@
        }
    }
    func openApp(_ app: AppInfo) {
    private func launchApp(
        _ app: AppInfo,
        closeQuickSearchOnSuccess: Bool = false,
        closeOverlayOnSuccess: Bool = true,
        onFailure: (() -> Void)? = nil
    ) {
        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) {
        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)
            }
        }
    }
}