CodexBar 是一个 macOS 菜单栏应用,用于查看本机 Codex 账号状态、额度、Token 用量、详细统计信息
Swift appkitcodexcodex-clideveloper-toolsmacosmacos-appmenu-bar-appopenai-codexproductivityswiftswiftuiusage-tracker
fix: 稳定活动卡片切换与菜单面板伸缩
Bobda244a710161
diff --git a/CodexBar/Controllers/StatusItemController.swift b/CodexBar/Controllers/StatusItemController.swiftindex 2bb4954..b2e789c 100644--- a/CodexBar/Controllers/StatusItemController.swift+++ b/CodexBar/Controllers/StatusItemController.swift@@ -231,7 +231,7 @@ final class StatusItemController: NSObject, NSMenuDelegate {animationState: MenuSurfaceAnimationState,usesPreferredContentSize: Bool) -> NSHostingController<AnyView> {- let rootView = CodexStatusMenuView(+ let menuContent = CodexStatusMenuView(viewModel: viewModel,historyViewModel: historyViewModel,mainPanelSettings: mainPanelSettings,@@ -255,12 +255,14 @@ final class StatusItemController: NSObject, NSMenuDelegate {.environmentObject(appUpdater).frame(width: CodexStatusMenuView.menuWidth).fixedSize(horizontal: false, vertical: true)- .onGeometryChange(for: CGFloat.self) { geometry in- geometry.size.height- } action: { [weak self] height in- guard !usesPreferredContentSize else { return }- self?.fallbackPanelController.resizeIfVisible(contentHeight: height)- }++ let rootView = MenuPanelLayout { menuContent }+ .onGeometryChange(for: CGFloat.self) { geometry in+ geometry.size.height+ } action: { [weak self] height in+ guard !usesPreferredContentSize else { return }+ self?.fallbackPanelController.resizeIfVisible(contentHeight: height)+ }let hostingController = NSHostingController(rootView: AnyView(rootView))if usesPreferredContentSize {diff --git a/CodexBar/Views/Menu/ActivityCard.swift b/CodexBar/Views/Menu/ActivityCard.swiftindex b3b256e..193ca8b 100644--- a/CodexBar/Views/Menu/ActivityCard.swift+++ b/CodexBar/Views/Menu/ActivityCard.swift@@ -11,6 +11,8 @@ struct ActivityCard: View {@State private var frameProvider = ScreenFrameProvider()@State private var isHovered = false@State private var wrappedHeaderTaskIDs: Set<UUID> = []+ @State private var retainedContent: ActivityCardContent?+ @State private var outgoingContent: ActivityCardContent?private var snapshot: ActivitySnapshot {activityMonitor.snapshot@@ -33,6 +35,14 @@ struct ActivityCard: View {keepAliveController.isActivelyPreventingSleep && !showsUnavailableState}+ private var currentContent: ActivityCardContent? {+ guard snapshot.hasTaskCenterContent || showsUnavailableState else { return nil }+ var value = content(at: timelineDate)+ value.showsKeepAliveBadge = showsKeepAliveBadge+ value.statusTextEffect = statusTextEffect+ return value+ }+// MARK: - 卡片布局var body: some View {@@ -40,7 +50,9 @@ struct ActivityCard: View {Button {onTaskCenterTap(frameProvider)} label: {- card(now: timelineDate)+ if let content = currentContent ?? retainedContent {+ card(content)+ }}.buttonStyle(ActivityCardButtonStyle()).disabled(!snapshot.hasTaskCenterContent)@@ -49,48 +61,82 @@ struct ActivityCard: View {ScreenFrameReader(provider: frameProvider)}.onHover { isHovered = $0 }+ .onChange(of: currentContent, initial: true) { _, content in+ // 退场期间保留最后一份展示内容, 不把正在收回的任务替换成空状态+ if let content {+ if allowsAnimations, let previous = retainedContent, content.requiresCrossfade(from: previous) {+ outgoingContent = previous+ }+ retainedContent = content+ }+ }+ .task(id: outgoingContent) {+ guard outgoingContent != nil else { return }+ // 先保留旧内容的完整一帧, 下一次更新只交接透明度, 不参与自然高度测量+ await Task.yield()+ guard !Task.isCancelled else { return }+ withAnimation(allowsAnimations ? .easeInOut(duration: 0.16) : nil) {+ outgoingContent = nil+ }+ }.onChange(of: retainedHeaderTaskIDs) { _, retainedIDs inwrappedHeaderTaskIDs.formIntersection(retainedIDs)}}- private func card(now: Date) -> some View {- let content = content(at: now)- return VStack(alignment: .leading, spacing: 0) {+ private func card(_ content: ActivityCardContent) -> some View {+ cardContent(content)+ .background {+ GeometryReader { geometry in+ Color.clear.preference(key: ActivityCardNaturalHeightKey.self, value: geometry.size.height)+ }+ }+ .opacity(outgoingContent == nil ? 1 : 0)+ .overlay(alignment: .topLeading) {+ if let outgoingContent {+ cardContent(outgoingContent)+ .transition(.opacity)+ .allowsHitTesting(false)+ }+ }+ // 外层可以收起整个区域, 内部文字始终按自然高度排版+ .frame(minHeight: 0, maxHeight: .infinity, alignment: .topLeading)+ .clipped()+ .activityStatusParticles(cornerRadius: MenuMetrics.panelCornerRadius)+ .liquidGlassSurface(cornerRadius: MenuMetrics.panelCornerRadius)+ .overlay {+ RoundedRectangle(cornerRadius: MenuMetrics.panelCornerRadius, style: .continuous)+ .strokeBorder(+ isTaskCenterPresented+ ? Color.accentColor.opacity(0.55)+ : Color.primary.opacity(isHovered && snapshot.hasTaskCenterContent ? 0.14 : 0),+ lineWidth: 1+ )+ .animation(.codexStatus, value: isHovered)+ .animation(.codexStatus, value: isTaskCenterPresented)+ }+ }++ private func cardContent(_ content: ActivityCardContent) -> some View {+ VStack(alignment: .leading, spacing: 0) {statusRow(content).frame(minHeight: content.detail == nil ? nil : Metrics.height)- .id(snapshot.hasTaskCenterContent)- .transition(.opacity)+ // 切换任务时重新建立文本状态, 不让前一个任务的数字过渡穿过新布局+ .id(content.taskID)+ .transition(.identity)if let tokenUsage = content.tokenUsage {VStack(spacing: 8) {LiquidGlassDivider()tokenUsageMetrics(tokenUsage)}.frame(height: Metrics.usageHeight - Metrics.height, alignment: .top)- .transition(.modifier(- active: ActivityTokenReveal(progress: 0),- identity: ActivityTokenReveal(progress: 1)- ))}}.padding(.horizontal, MenuMetrics.panelPadding).frame(maxWidth: .infinity)- .activityStatusParticles(cornerRadius: MenuMetrics.panelCornerRadius)- .liquidGlassSurface(cornerRadius: MenuMetrics.panelCornerRadius)- .overlay {- RoundedRectangle(cornerRadius: MenuMetrics.panelCornerRadius, style: .continuous)- .strokeBorder(- isTaskCenterPresented- ? Color.accentColor.opacity(0.55)- : Color.primary.opacity(isHovered && snapshot.hasTaskCenterContent ? 0.14 : 0),- lineWidth: 1- )- .animation(.codexStatus, value: isHovered)- .animation(.codexStatus, value: isTaskCenterPresented)- }- .animation(Metrics.expansionAnimation, value: snapshot.hasTaskCenterContent)- .animation(Metrics.expansionAnimation, value: content.tokenUsage != nil)- .animation(Metrics.expansionAnimation, value: content.detail == nil)+ .fixedSize(horizontal: false, vertical: true)+ // 内容只上报自然高度, 显示和尺寸变化都由区域容器统一驱动+ .transaction { $0.animation = nil }}private func statusRow(_ content: ActivityCardContent) -> some View {@@ -106,11 +152,12 @@ struct ActivityCard: View {if let detail = content.detail {ActivityStatusText(- text: detail, tint: content.tint, effect: statusTextEffect,+ text: detail, tint: content.tint, effect: allowsAnimations ? content.statusTextEffect : .none,lineLimit: nil, supplement: content.detailSupplement).numericTransition(value: [detail, content.detailSupplement], enabled: allowsAnimations).fixedSize(horizontal: false, vertical: true)+ .clipped()}if let recent = content.recent {Text(recent)@@ -118,15 +165,13 @@ struct ActivityCard: View {.foregroundStyle(Color.codexSecondaryLabel).numericTransition(value: recent, enabled: allowsAnimations).fixedSize(horizontal: false, vertical: true)+ .clipped()}}.frame(maxWidth: .infinity, alignment: .leading)}.padding(.top, 12).padding(.bottom, content.detail == nil ? 8 : 12)- .animation(.codexStatus, value: showsKeepAliveBadge)- // 徽标只占用标题行的宽度, 下方状态和附加信息可以使用完整文本区域- .animation(.codexStatus, value: content.otherTaskCount)}private func statusHeader(_ content: ActivityCardContent) -> some View {@@ -139,14 +184,13 @@ struct ActivityCard: View {singleLineWidthReserve: Metrics.headerWidthReserve,wrappedLayout: wrappedHeaderLayout(for: content.taskID))- // 换行锁定只属于当前任务, 新任务在首次布局时重新判断- .id(content.taskID).font(.caption.weight(.semibold)).foregroundStyle(Color.codexLabel).numericTransition(value: content.header, enabled: allowsAnimations).fixedSize(horizontal: false, vertical: true)+ .clipped().frame(maxWidth: .infinity, alignment: .leading)- if content.otherTaskCount > 0 || showsKeepAliveBadge {+ if content.otherTaskCount > 0 || content.showsKeepAliveBadge {statusBadges(content).fixedSize()}@@ -158,6 +202,7 @@ struct ActivityCard: View {+ snapshot.runningTasks.map(\.id)+ snapshot.recentCompletions.map { $0.taskID ?? $0.id }+ snapshot.recentTerminations.map { $0.taskID ?? $0.id })+ .union([retainedContent?.taskID].compactMap(\.self))}private func wrappedHeaderLayout(for taskID: UUID?) -> Binding<Bool>? {@@ -187,7 +232,7 @@ struct ActivityCard: View {.help(String(localized: "activity.summary.other-task-count", defaultValue: "\(content.otherTaskCount, specifier: "%lld")"))}// 防睡眠由任务状态驱动, 徽标跟随活动卡片展示- if showsKeepAliveBadge {+ if content.showsKeepAliveBadge {// 隐藏或关闭动画效果时移除整个旋转视图, 避免保留持续渲染调度Group {if allowsAnimations {@@ -201,6 +246,8 @@ struct ActivityCard: View {.transition(.opacity)}}+ .animation(.codexStatus, value: content.showsKeepAliveBadge)+ .animation(.codexStatus, value: content.otherTaskCount)}private func tokenUsageMetrics(_ tokenUsage: TokenUsage) -> some View {@@ -293,8 +340,8 @@ struct ActivityCard: View {)case .idle:return ActivityCardContent(- symbolName: "moon.zzz.fill",- tint: .secondary,+ symbolName: "bubble.left.and.exclamationmark.bubble.right",+ tint: .red,detail: activityMonitor.sourcePresentation?.text,otherTaskCount: 0,header: [String(localized: "common.codex")]@@ -343,28 +390,11 @@ struct ActivityCard: View {static let headerWidthReserve: CGFloat = 32static let height: CGFloat = 58static let usageHeight: CGFloat = 108- static let expansionAnimation = Animation.timingCurve(0.22, 1, 0.36, 1, duration: 0.32)}}// MARK: - 动画-/// 用展开进度控制显隐, 让动画中途反向时保持连贯-private struct ActivityTokenReveal: ViewModifier, Animatable {- var progress: CGFloat-- var animatableData: CGFloat {- get { progress }- set { progress = newValue }- }-- func body(content: Content) -> some View {- content- .opacity(Double(min(1, max(0, (progress - 0.6) / 0.4))))- .offset(y: (1 - progress) * 4)- }-}-private struct RotatingKeepAliveSun: View {@State private var isRotating = false@@ -385,7 +415,7 @@ private struct ActivityCardButtonStyle: ButtonStyle {}}-private struct ActivityCardContent {+private struct ActivityCardContent: Equatable {var taskID: UUID?let symbolName: Stringlet tint: Color@@ -395,6 +425,15 @@ private struct ActivityCardContent {let header: [String]var recent: String?var detailSupplement: String?+ var showsKeepAliveBadge = false+ var statusTextEffect = ActivityStatusText.Effect.none++ func requiresCrossfade(from previous: Self) -> Bool {+ taskID != previous.taskID || symbolName != previous.symbolName+ || (tokenUsage == nil) != (previous.tokenUsage == nil)+ || (detail == nil) != (previous.detail == nil)+ || (recent == nil) != (previous.recent == nil)+ }var headerLines: [String] {[header.first ?? "", header.dropFirst().joined(separator: " • ")]diff --git a/CodexBar/Views/Menu/ActivitySectionReveal.swift b/CodexBar/Views/Menu/ActivitySectionReveal.swiftnew file mode 100644index 0000000..6df4bd0--- /dev/null+++ b/CodexBar/Views/Menu/ActivitySectionReveal.swift@@ -0,0 +1,92 @@+import SwiftUI++nonisolated struct ActivityCardNaturalHeightKey: PreferenceKey {+ static let defaultValue: CGFloat = 0++ static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {+ value = max(value, nextValue())+ }+}++struct ActivitySection<Content: View>: View {+ let isVisible: Bool+ @ViewBuilder let content: () -> Content+ @Environment(\.mainPanelAnimationsEnabled) private var allowsAnimations+ @State private var retainsContent: Bool+ @State private var naturalHeight: CGFloat = 0+ @State private var height: CGFloat+ @State private var progress: CGFloat+ @State private var transitionGeneration = 0++ private var animation: Animation? {+ allowsAnimations ? .timingCurve(0.4, 0, 0.2, 1, duration: 0.32) : nil+ }++ init(isVisible: Bool, @ViewBuilder content: @escaping () -> Content) {+ self.isVisible = isVisible+ self.content = content+ _retainsContent = State(initialValue: isVisible)+ _height = State(initialValue: isVisible ? -1 : 0)+ _progress = State(initialValue: isVisible ? 1 : 0)+ }++ var body: some View {+ Group {+ if retainsContent {+ content()+ }+ }+ .modifier(ActivitySectionReveal(height: height, progress: progress))+ .allowsHitTesting(isVisible)+ .onPreferenceChange(ActivityCardNaturalHeightKey.self) { measuredHeight in+ guard measuredHeight > 0 else { return }+ naturalHeight = measuredHeight+ guard isVisible else { return }+ // 初次打开直接采用自然高度, 后续变化统一从当前可见高度继续+ withAnimation(height < 0 ? nil : animation) {+ height = measuredHeight+ progress = 1+ }+ }+ .onChange(of: isVisible) { _, visible in+ transitionGeneration &+= 1+ let generation = transitionGeneration+ if visible, !retainsContent {+ // 先测量内容, 再同时展开高度和间距, 插入本身不触发父布局动画+ retainsContent = true+ return+ }+ withAnimation(animation, completionCriteria: .removed) {+ height = visible ? naturalHeight : 0+ progress = visible ? 1 : 0+ } completion: {+ if transitionGeneration == generation, !isVisible {+ retainsContent = false+ }+ }+ }+ }+}++struct ActivitySectionReveal: ViewModifier, Animatable {+ var height: CGFloat+ var progress: CGFloat++ var animatableData: AnimatablePair<CGFloat, CGFloat> {+ get { AnimatablePair(height, progress) }+ set {+ height = newValue.first+ progress = newValue.second+ }+ }++ func body(content: Content) -> some View {+ let visibility = min(1, max(0, progress))+ content+ // 卡片按可见高度绘制背景, 内容裁剪由卡片内部负责, 外投影不参与裁剪+ .frame(height: height < 0 ? nil : max(0, height), alignment: .topLeading)+ // 连同玻璃背景和投影一起淡出, 避免末尾留下被压扁的亮边+ .opacity(visibility * visibility * (3 - 2 * visibility))+ .layoutValue(key: MenuSectionVisibilityKey.self, value: visibility)+ }+}diff --git a/CodexBar/Views/Menu/CodexStatusMenuView.swift b/CodexBar/Views/Menu/CodexStatusMenuView.swiftindex 1e905e2..98f4dc2 100644--- a/CodexBar/Views/Menu/CodexStatusMenuView.swift+++ b/CodexBar/Views/Menu/CodexStatusMenuView.swift@@ -58,7 +58,7 @@ struct CodexStatusMenuView: View {}var body: some View {- VStack(alignment: .leading, spacing: Metrics.verticalSpacing) {+ MenuSectionLayout(spacing: Metrics.verticalSpacing) {content}.environment(@@ -76,10 +76,6 @@ struct CodexStatusMenuView: View {.animation(Metrics.statusAnimation, value: syncSettings.isEnabled).animation(Metrics.statusAnimation, value: syncSettings.isSyncing).animation(Metrics.statusAnimation, value: syncSettings.hasSyncFailure)- .animation(- mainPanelSettings.areAnimationsEnabled ? Metrics.activityExpansionAnimation : nil,- value: showsActivitySection- ).onReceive(activityMonitor.$snapshot.combineLatest(activityMonitor.$isActivitySourceHealthy)@@ -103,7 +99,6 @@ private extension CodexStatusMenuView {static let surfaceCornerRadius: CGFloat = 14static let verticalSpacing: CGFloat = 10static let statusAnimation = Animation.codexStatus- static let activityExpansionAnimation = Animation.timingCurve(0.22, 1, 0.36, 1, duration: 0.32)}@ViewBuilder@@ -113,12 +108,15 @@ private extension CodexStatusMenuView {}let dataPlaceholderSection = dataPlaceholderSection(in: visibleSections)- ForEach(visibleSections) { section in- sectionView(section, dataPlaceholderSection: dataPlaceholderSection)- .transition(section == .activity ? .modifier(- active: ActivitySectionReveal(progress: 0),- identity: ActivitySectionReveal(progress: 1)- ) : .opacity)+ ForEach(mainPanelSettings.layout.visibleSections) { section in+ if section == .activity {+ ActivitySection(isVisible: showsActivitySection) {+ activitySection+ }+ } else {+ sectionView(section, dataPlaceholderSection: dataPlaceholderSection)+ .transition(.opacity)+ }}if !hasRenderableContent(@@ -286,39 +284,3 @@ private extension CodexStatusMenuView {)}}--private struct ActivitySectionReveal: ViewModifier, Animatable {- var progress: CGFloat-- var animatableData: CGFloat {- get { progress }- set { progress = newValue }- }-- func body(content: Content) -> some View {- ActivitySectionRevealLayout(progress: progress) {- content- }- // 完全展开后为玻璃表面的外投影留出空间, 不裁掉边缘高光和阴影- .clipShape(Rectangle().inset(by: progress < 1 ? 0 : -64))- }-}--private struct ActivitySectionRevealLayout: Layout {- var progress: CGFloat-- func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache _: inout ()) -> CGSize {- guard let subview = subviews.first else { return .zero }- let size = subview.sizeThatFits(ProposedViewSize(width: proposal.width, height: nil))- return CGSize(width: size.width, height: size.height * min(1, max(0, progress)))- }-- func placeSubviews(in bounds: CGRect, proposal _: ProposedViewSize, subviews: Subviews, cache _: inout ()) {- // 保留内容的自然高度, 只改变裁剪区域, 避免展开和收回时压缩文字- subviews.first?.place(- at: bounds.origin,- anchor: .topLeading,- proposal: ProposedViewSize(width: bounds.width, height: nil)- )- }-}diff --git a/CodexBar/Views/Menu/MenuPanelLayout.swift b/CodexBar/Views/Menu/MenuPanelLayout.swiftnew file mode 100644index 0000000..a8032eb--- /dev/null+++ b/CodexBar/Views/Menu/MenuPanelLayout.swift@@ -0,0 +1,55 @@+import SwiftUI++nonisolated struct MenuSectionVisibilityKey: LayoutValueKey {+ static let defaultValue: CGFloat = 1+}++/// 区域高度和相邻间距使用同一展开进度, 移除零高度区域时不再改变总高度+struct MenuSectionLayout: Layout {+ var spacing: CGFloat++ func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache _: inout ()) -> CGSize {+ var size = CGSize.zero+ var precedingVisibility: CGFloat = 0+ for subview in subviews {+ let visibility = subview[MenuSectionVisibilityKey.self]+ let childSize = subview.sizeThatFits(ProposedViewSize(width: proposal.width, height: nil))+ size.width = max(size.width, childSize.width)+ size.height += spacing * min(precedingVisibility, visibility) + childSize.height+ precedingVisibility = max(precedingVisibility, visibility)+ }+ return size+ }++ func placeSubviews(in bounds: CGRect, proposal _: ProposedViewSize, subviews: Subviews, cache _: inout ()) {+ var y = bounds.minY+ var precedingVisibility: CGFloat = 0+ for subview in subviews {+ let visibility = subview[MenuSectionVisibilityKey.self]+ let childProposal = ProposedViewSize(width: bounds.width, height: nil)+ y += spacing * min(precedingVisibility, visibility)+ subview.place(at: CGPoint(x: bounds.minX, y: y), anchor: .topLeading, proposal: childProposal)+ y += subview.sizeThatFits(childProposal).height+ precedingVisibility = max(precedingVisibility, visibility)+ }+ }+}++/// 宿主窗口和内容共用整点高度, 保持顶部位置稳定+struct MenuPanelLayout: Layout {+ func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache _: inout ()) -> CGSize {+ guard let subview = subviews.first else { return .zero }+ let size = subview.sizeThatFits(ProposedViewSize(width: proposal.width, height: nil))+ // NSPopover 的窗口按整点取整, 半点高度会使宿主内容在窗口内上下偏移+ return CGSize(width: size.width, height: size.height.rounded(.up))+ }++ func placeSubviews(in bounds: CGRect, proposal _: ProposedViewSize, subviews: Subviews, cache _: inout ()) {+ // 取整留下的空间放在底部, 不由默认居中对齐分配到顶部+ subviews.first?.place(+ at: bounds.origin,+ anchor: .topLeading,+ proposal: ProposedViewSize(width: bounds.width, height: nil)+ )+ }+}diff --git a/Tests/App/Presentation/ActivityCardLayoutTests.swift b/Tests/App/Presentation/ActivityCardLayoutTests.swiftindex f0c5c6a..90cf5ab 100644--- a/Tests/App/Presentation/ActivityCardLayoutTests.swift+++ b/Tests/App/Presentation/ActivityCardLayoutTests.swift@@ -2,7 +2,219 @@ import AppKitimport SwiftUIimport Testing+@Suite(.serialized)struct ActivityCardLayoutTests {+ @Test func hidingKeepsOriginalTaskSymbolVisible() async throws {+ let fixture = try CardFixture(hasTokens: true, anchorEdge: .minY)+ defer { fixture.close() }+ try await Task.sleep(for: .milliseconds(100))+ #expect(try fixture.bluePixelCount() > 12)+ fixture.monitor.graph.tasks.removeAll()+ fixture.monitor.refreshSnapshot(now: fixture.now)+ try await Task.sleep(for: .milliseconds(40))+ #expect(try fixture.bluePixelCount() > 12, "The departing task changed to the gray idle placeholder")+ }++ @Test(arguments: [false, true])+ func hidingSectionStartsGently(hasTokens: Bool) async throws {+ let fixture = try CardFixture(hasTokens: hasTokens, anchorEdge: .minY)+ defer { fixture.close() }+ try await Task.sleep(for: .milliseconds(100))+ let visible = fixture.height+ fixture.monitor.graph.tasks.removeAll()+ fixture.monitor.refreshSnapshot(now: fixture.now)+ try await Task.sleep(for: .milliseconds(60))+ let firstMovement = visible - fixture.height+ let totalMovement: CGFloat = (hasTokens ? 108 : 58) + 10+ #expect(firstMovement < totalMovement * 0.4, "The drawer collapsed too abruptly at the start: \(firstMovement) / \(totalMovement)")+ }++ @Test func resizingPopoverKeepsHeaderAtSameScreenPosition() async throws {+ let fixture = try CardFixture(hasTokens: false, anchorEdge: .minY, panelWidth: 491)+ defer { fixture.close() }+ try await Task.sleep(for: .milliseconds(100))+ let initial = try #require(fixture.headerFrame.currentScreenFrame()).maxY+ var offsets: [CGFloat] = []+ for hasTokens: Bool? in [true, false, nil, false, true, nil] {+ if let hasTokens {+ fixture.update(hasTokens: hasTokens, newTask: true)+ } else {+ fixture.monitor.graph.tasks.removeAll()+ fixture.monitor.refreshSnapshot(now: fixture.now)+ }+ for _ in 0 ..< 25 {+ try await Task.sleep(for: .milliseconds(16))+ let header = try #require(fixture.headerFrame.currentScreenFrame())+ offsets.append(header.maxY - initial)+ }+ }+ #expect(offsets.allSatisfy { abs($0) < 0.1 }, "Stationary header moved during resizing: \(offsets)")+ }++ @Test func restoringSectionKeepsCardAboveHistory() async throws {+ let fixture = try CardFixture(hasTokens: false, anchorEdge: .minY)+ defer { fixture.close() }+ fixture.monitor.graph.tasks.removeAll()+ fixture.monitor.refreshSnapshot(now: fixture.now)+ _ = try await fixture.sampleHeights()+ fixture.update(hasTokens: false, newTask: true)+ var gaps: [CGFloat] = []+ for _ in 0 ..< 25 {+ try await Task.sleep(for: .milliseconds(16))+ if let card = fixture.cardFrame.currentScreenFrame(), let history = fixture.historyFrame.currentScreenFrame() {+ gaps.append(card.minY - history.maxY)+ }+ }+ #expect(gaps.count > 3)+ #expect(gaps.allSatisfy { $0 >= 9.5 }, "The revealing card overlapped the history section: \(gaps)")+ }++ @Test(arguments: [false, true])+ func taskTokenHeightChangesContinuously(collapsing: Bool) async throws {+ let fixture = try CardFixture(hasTokens: collapsing)+ defer { fixture.close() }+ try await Task.sleep(for: .milliseconds(100))+ let initial = fixture.height+ fixture.update(hasTokens: !collapsing)+ let heights = try await fixture.sampleHeights()+ let final = try #require(heights.last)+ #expect(abs(final - initial) >= 49)+ expectContinuous(heights, from: initial, to: final)+ }++ @Test func switchingTasksAndReversingDuringExpansionStaysWithinBounds() async throws {+ let fixture = try CardFixture(hasTokens: false)+ defer { fixture.close() }+ try await Task.sleep(for: .milliseconds(100))+ let initial = fixture.height+ fixture.update(hasTokens: true, newTask: true)+ let expanding = try await fixture.sampleHeights(count: 6)+ let turningPoint = fixture.height+ #expect(turningPoint > initial + 1)+ fixture.update(hasTokens: false, newTask: true)+ let collapsing = try await fixture.sampleHeights()+ #expect(abs(fixture.height - initial) < 1)+ #expect((expanding + collapsing).allSatisfy { $0 >= initial - 1 && $0 <= initial + 51 })+ #expect(collapsing.contains { $0 > initial + 1 && $0 < turningPoint - 1 })+ // 反向时保留短暂的连续速度, 随后必须稳定收回且不能越过目标范围+ #expect((collapsing.max() ?? turningPoint) <= turningPoint + 10)+ let settledDirection = Array(collapsing.dropFirst(4))+ #expect(zip(settledDirection, settledDirection.dropFirst()).allSatisfy { $1 <= $0 + 1 }, "Reversal continued expanding: \(collapsing)")+ }++ @Test func disabledAnimationsApplyFinalHeightImmediately() async throws {+ let fixture = try CardFixture(hasTokens: false, allowsAnimations: false)+ defer { fixture.close() }+ try await Task.sleep(for: .milliseconds(100))+ let initial = fixture.height+ fixture.update(hasTokens: true)+ let heights = try await fixture.sampleHeights(count: 6)+ #expect(abs(fixture.height - initial - 50) < 1)+ #expect(heights.allSatisfy { abs($0 - initial) < 1 || abs($0 - initial - 50) < 1 })+ }++ @Test(arguments: [0.25, 0.75, 0.999, 1.0])+ func sectionRevealPreservesShadowOutsideVisibleCard(progress: CGFloat) throws {+ let fixture = try CardFixture(hasTokens: true)+ defer { fixture.close() }+ let card = ActivityCard(+ activityMonitor: fixture.monitor,+ presentationState: ActivityCenterPresentationState(),+ keepAliveController: KeepAliveController(activityMonitor: fixture.monitor, defaults: fixture.preferences.defaults),+ onTaskCenterTap: { _ in }+ )+ .modifier(ActivitySectionReveal(height: 108 * progress, progress: progress))+ .frame(width: 300)+ .padding(40)+ .environment(\.colorScheme, .light)+ let renderer = ImageRenderer(content: card)+ renderer.scale = 2+ let bitmap = try NSBitmapImageRep(cgImage: #require(renderer.cgImage))+ let shadow = try #require(bitmap.colorAt(x: bitmap.pixelsWide / 2, y: bitmap.pixelsHigh - 72))+ #expect(shadow.alphaComponent > 0, "The drawer clipped its shadow at the visible bottom edge")+ }++ @Test func switchingToWrappedHeaderAndBackAnimatesNaturalHeight() async throws {+ let fixture = try CardFixture(hasTokens: true)+ defer { fixture.close() }+ try await Task.sleep(for: .milliseconds(100))+ let initial = fixture.height+ fixture.update(hasTokens: true, newTask: true)+ fixture.monitor.graph.tasks[fixture.key]?.projectName = String(repeating: "Long project name ", count: 5)+ fixture.monitor.refreshSnapshot(now: fixture.now)+ let expanding = try await fixture.sampleHeights()+ let expanded = fixture.height+ #expect(expanded > initial + 1)+ expectContinuous(expanding, from: initial, to: expanded)+ fixture.update(hasTokens: true, newTask: true)+ let collapsing = try await fixture.sampleHeights()+ #expect(abs(fixture.height - initial) < 1)+ expectContinuous(collapsing, from: expanded, to: initial)+ }++ @Test func hidingAndRestoringSectionAnimatesHostHeight() async throws {+ let fixture = try CardFixture(hasTokens: false)+ defer { fixture.close() }+ try await Task.sleep(for: .milliseconds(100))+ let visible = fixture.height+ fixture.monitor.graph.tasks.removeAll()+ fixture.monitor.refreshSnapshot(now: fixture.now)+ let collapsing = try await fixture.sampleHeights()+ let hidden = fixture.height+ #expect(abs(visible - hidden - 68) < 1)+ expectContinuous(collapsing, from: visible, to: hidden)+ fixture.update(hasTokens: false, newTask: true)+ let expanding = try await fixture.sampleHeights()+ #expect(abs(fixture.height - visible) < 1)+ expectContinuous(expanding, from: hidden, to: visible)+ }++ @Test(arguments: [false, true], ActivityPlacement.allCases)+ func hidingSectionDoesNotSnapAtEnd(hasTokens: Bool, placement: ActivityPlacement) async throws {+ let fixture = try CardFixture(hasTokens: hasTokens, anchorEdge: .minY, placement: placement)+ defer { fixture.close() }+ try await Task.sleep(for: .milliseconds(100))+ let visible = fixture.height+ fixture.monitor.graph.tasks.removeAll()+ fixture.monitor.refreshSnapshot(now: fixture.now)+ let heights = try await fixture.sampleHeights(count: 35)+ let steps = zip(heights, heights.dropFirst()).map { abs($1 - $0) }.filter { $0 > 0 }+ let finalStep = try #require(steps.last)+ #expect(finalStep <= 2, "The drawer snapped on its final moving frame: \(heights)")+ let removedHeight: CGFloat = (hasTokens ? 108 : 58) + (placement == .only ? 0 : 10)+ #expect(abs(visible - fixture.height - removedHeight) < 1)+ }++ @Test func reversingSectionRemovalKeepsTheRestoredCard() async throws {+ let fixture = try CardFixture(hasTokens: false)+ defer { fixture.close() }+ try await Task.sleep(for: .milliseconds(100))+ let visible = fixture.height+ for _ in 0 ..< 3 {+ fixture.monitor.graph.tasks.removeAll()+ fixture.monitor.refreshSnapshot(now: fixture.now)+ _ = try await fixture.sampleHeights(count: 5)+ #expect(fixture.height < visible - 1)+ fixture.update(hasTokens: false, newTask: true)+ _ = try await fixture.sampleHeights(count: 5)+ }+ _ = try await fixture.sampleHeights()+ #expect(abs(fixture.height - visible) < 1)+ }++ private func expectContinuous(_ heights: [CGFloat], from initial: CGFloat, to final: CGFloat) {+ let lower = min(initial, final)+ let upper = max(initial, final)+ #expect(+ heights.filter { $0 > lower + 1 && $0 < upper - 1 }.count >= 3,+ "Host height jumped instead of revealing the drawer: \(heights)"+ )+ #expect(heights.allSatisfy { $0 >= lower - 1 && $0 <= upper + 1 })+ let changes = zip([initial] + heights, heights).map { $1 - $0 }+ #expect(changes.allSatisfy { abs($0) < (upper - lower) * 0.7 })+ #expect(changes.allSatisfy { final > initial ? $0 >= -1 : $0 <= 1 })+ }+@Test func narrowStatusContentExpandsWithoutClipping() {let short = statusSize(width: 300, long: false)let wide = statusSize(width: 480, long: true)@@ -48,3 +260,166 @@ struct ActivityCardLayoutTests {return NSHostingView(rootView: content).fittingSize}}++enum ActivityPlacement: CaseIterable {+ case first, middle, last, only+}++private final class CardFixture {+ let directory: TestDirectory+ let preferences: TestPreferences+ let monitor: ActivityMonitor+ let controller: NSHostingController<AnyView>+ let window: NSWindow+ let popover: NSPopover+ let now = Date()+ let key = ActivityTaskKey(thread: "drawer", turn: "turn")+ let headerFrame = ScreenFrameProvider()+ let cardFrame = ScreenFrameProvider()+ let historyFrame = ScreenFrameProvider()++ var height: CGFloat {+ controller.preferredContentSize.height+ }++ init(+ hasTokens: Bool,+ allowsAnimations: Bool = true,+ anchorEdge: NSRectEdge = .maxX,+ panelWidth: CGFloat = 560,+ placement: ActivityPlacement = .middle+ ) throws {+ directory = try TestDirectory()+ preferences = try TestPreferences()+ monitor = ActivityMonitor(+ protectionSettings: ProtectionSettings(defaults: preferences.defaults),+ protectionStore: ProtectionStore(directoryURL: directory.url),+ activityDataDirectoryURL: directory.url+ )+ var task = ActivityTask(+ displayID: UUID(), key: key,+ event: TestFixtures.event(at: now, thread: key.threadID, turn: key.turnID),+ state: .running, startedAt: now, progressGeneration: 1+ )+ task.projectName = "CodexBar"+ task.tokenUsage = hasTokens ? .zero : nil+ monitor.graph.tasks[key] = task+ monitor.isActivitySourceHealthy = true+ monitor.refreshSnapshot(now: now)+ let content = CardFixturePanel(+ monitor: monitor,+ keepAlive: KeepAliveController(activityMonitor: monitor, defaults: preferences.defaults),+ headerFrame: headerFrame,+ cardFrame: cardFrame,+ historyFrame: historyFrame,+ placement: placement+ )+ .padding(12)+ .frame(width: panelWidth)+ .fixedSize(horizontal: false, vertical: true)+ let root = MenuPanelLayout { content }+ .environment(\.mainPanelAnimationsEnabled, allowsAnimations)+ controller = NSHostingController(rootView: AnyView(root))+ controller.sizingOptions = [.preferredContentSize]+ let screen = NSScreen.main?.visibleFrame ?? NSRect(x: 0, y: 0, width: 1440, height: 900)+ let anchorY = anchorEdge == .minY ? screen.maxY - 64 : 400+ window = NSWindow(contentRect: NSRect(x: 100, y: anchorY, width: 40, height: 40), styleMask: [.borderless], backing: .buffered, defer: false)+ window.isReleasedWhenClosed = false+ window.contentView = NSView(frame: NSRect(x: 0, y: 0, width: 40, height: 40))+ window.orderFront(nil)+ popover = NSPopover()+ popover.animates = false+ popover.contentViewController = controller+ let anchor = try #require(window.contentView)+ popover.show(relativeTo: anchor.bounds, of: anchor, preferredEdge: anchorEdge)+ }++ func update(hasTokens: Bool, newTask: Bool = false) {+ if newTask {+ var task = ActivityTask(+ displayID: UUID(), key: key,+ event: TestFixtures.event(at: now, thread: key.threadID, turn: key.turnID),+ state: .running, startedAt: now, progressGeneration: 1+ )+ task.projectName = hasTokens ? "Peekaboo" : "CodexBar"+ monitor.graph.tasks[key] = task+ }+ monitor.graph.tasks[key]?.tokenUsage = hasTokens ? .zero : nil+ monitor.refreshSnapshot(now: now)+ }++ func sampleHeights(count: Int = 30) async throws -> [CGFloat] {+ var heights: [CGFloat] = []+ for _ in 0 ..< count {+ try await Task.sleep(for: .milliseconds(16))+ heights.append(height)+ #expect(abs(popover.contentSize.height - height) < 1)+ }+ return heights+ }++ func bluePixelCount() throws -> Int {+ let view = controller.view+ let bitmap = try #require(view.bitmapImageRepForCachingDisplay(in: view.bounds))+ view.cacheDisplay(in: view.bounds, to: bitmap)+ var count = 0+ for y in stride(from: 0, to: bitmap.pixelsHigh, by: 2) {+ for x in stride(from: 0, to: bitmap.pixelsWide, by: 2) {+ guard let color = bitmap.colorAt(x: x, y: y)?.usingColorSpace(.sRGB) else { continue }+ if color.blueComponent > color.redComponent + 0.2,+ color.blueComponent > color.greenComponent + 0.05 {+ count += 1+ }+ }+ }+ return count+ }++ func close() {+ popover.close()+ window.close()+ preferences.remove()+ try? directory.remove()+ }+}++private struct CardFixturePanel: View {+ @ObservedObject var monitor: ActivityMonitor+ let keepAlive: KeepAliveController+ let headerFrame: ScreenFrameProvider+ let cardFrame: ScreenFrameProvider+ let historyFrame: ScreenFrameProvider+ let placement: ActivityPlacement++ var body: some View {+ MenuSectionLayout(spacing: 10) {+ if placement == .first || placement == .only {+ activity+ }+ if placement != .only {+ Text("Quota").frame(maxWidth: .infinity).frame(height: 50).background(.gray.opacity(0.2))+ .background { ScreenFrameReader(provider: headerFrame) }+ if placement == .middle {+ activity+ }+ Text("History").frame(maxWidth: .infinity).frame(height: 100).background(.green.opacity(0.2))+ .background { ScreenFrameReader(provider: historyFrame) }+ }+ if placement == .last {+ activity+ }+ }+ }++ private var activity: some View {+ ActivitySection(isVisible: monitor.snapshot.hasTaskCenterContent) {+ ActivityCard(+ activityMonitor: monitor,+ presentationState: ActivityCenterPresentationState(),+ keepAliveController: keepAlive,+ onTaskCenterTap: { _ in }+ )+ .background { ScreenFrameReader(provider: cardFrame) }+ }+ }+}