     1→import SwiftUI
     2→
     3→struct MenuBarView: View {
     4→    @EnvironmentObject var appState: AppState
     5→    @StateObject private var serviceManager = ServiceManager.shared
     6→    @Environment(\.openWindow) private var openWindow
     7→
     8→    var body: some View {
     9→        VStack(spacing: 0) {
    10→            // Header with connection status
    11→            headerSection
    12→
    13→            Divider()
    14→
    15→            // ROI Summary
    16→            roiSection
    17→
    18→            Divider()
    19→
    20→            // Live Consumption (Real-time tracking)
    21→            liveConsumptionSection
    22→
    23→            Divider()
    24→
    25→            // Budget Usage
    26→            budgetSection
    27→
    28→            Divider()
    29→
    30→            // Services Status
    31→            servicesSection
    32→
    33→            Divider()
    34→
    35→            // Quick Actions
    36→            quickActionsSection
    37→
    38→            Divider()
    39→
    40→            // Footer
    41→            footerSection
    42→        }
    43→        .frame(width: 300)
    44→    }
    45→
    46→    // MARK: - Header
    47→
    48→    private var headerSection: some View {
    49→        HStack {
    50→            Image(systemName: "terminal.fill")
    51→                .font(.title2)
    52→                .foregroundStyle(.blue)
    53→
    54→            VStack(alignment: .leading, spacing: 2) {
    55→                Text("NEOG Command")
    56→                    .font(.headline)
    57→                HStack(spacing: 4) {
    58→                    Circle()
    59→                        .fill(appState.isConnected ? .green : .red)
    60→                        .frame(width: 6, height: 6)
    61→                    Text(appState.connectionState.rawValue)
    62→                        .font(.caption)
    63→                        .foregroundStyle(.secondary)
    64→                }
    65→            }
    66→
    67→            Spacer()
    68→
    69→            if let lastSync = appState.lastSyncDate {
    70→                Text(lastSync, style: .relative)
    71→                    .font(.caption2)
    72→                    .foregroundStyle(.tertiary)
    73→            }
    74→        }
    75→        .padding()
    76→    }
    77→
    78→    // MARK: - ROI Section
    79→
    80→    private var roiSection: some View {
    81→        VStack(spacing: 8) {
    82→            HStack {
    83→                Text("Today's ROI")
    84→                    .font(.caption)
    85→                    .foregroundStyle(.secondary)
    86→                Spacer()
    87→            }
    88→
    89→            if let roi = appState.roiSummary {
    90→                HStack(spacing: 16) {
    91→                    // Cost
    92→                    VStack(alignment: .leading, spacing: 2) {
    93→                        Text("Cost")
    94→                            .font(.caption2)
    95→                            .foregroundStyle(.secondary)
    96→                        Text(String(format: "$%.2f", roi.totalCost))
    97→                            .font(.system(.body, design: .monospaced))
    98→                            .foregroundStyle(.red)
    99→                    }
   100→
   101→                    // Value
   102→                    VStack(alignment: .leading, spacing: 2) {
   103→                        Text("Value")
   104→                            .font(.caption2)
   105→                            .foregroundStyle(.secondary)
   106→                        Text(String(format: "$%.2f", roi.totalValue))
   107→                            .font(.system(.body, design: .monospaced))
   108→                            .foregroundStyle(.green)
   109→                    }
   110→
   111→                    Spacer()
   112→
   113→                    // ROI %
   114→                    VStack(alignment: .trailing, spacing: 2) {
   115→                        Text("ROI")
   116→                            .font(.caption2)
   117→                            .foregroundStyle(.secondary)
   118→                        Text(String(format: "%.0f%%", roi.roiPercent))
   119→                            .font(.title2.bold())
   120→                            .foregroundStyle(roiColor(roi.roiPercent))
   121→                    }
   122→                }
   123→
   124→                // Runs count
   125→                HStack {
   126→                    Text("\(roi.runCount) runs today")
   127→                        .font(.caption)
   128→                        .foregroundStyle(.secondary)
   129→                    Spacer()
   130→                    Text(String(format: "%.0f%% success", roi.successRate * 100))
   131→                        .font(.caption)
   132→                        .foregroundStyle(.secondary)
   133→                }
   134→            } else {
   135→                Text("Loading...")
   136→                    .font(.caption)
   137→                    .foregroundStyle(.secondary)
   138→            }
   139→        }
   140→        .padding()
   141→    }
   142→
   143→    // MARK: - Live Consumption Section
   144→
   145→    private var liveConsumptionSection: some View {
   146→        MenuBarConsumptionView()
   147→    }
   148→
   149→    // MARK: - Budget Section
   150→
   151→    private var budgetSection: some View {
   152→        VStack(spacing: 8) {
   153→            if let budget = appState.budgetConfig {
   154→                HStack {
   155→                    Text("Daily Budget")
   156→                        .font(.caption)
   157→                        .foregroundStyle(.secondary)
   158→                    Spacer()
   159→                    Text(String(format: "$%.2f / $%.2f", budget.currentDailyUsage ?? 0, budget.dailyLimitUsd))
   160→                        .font(.caption.monospacedDigit())
   161→                }
   162→
   163→                // Progress bar
   164→                GeometryReader { geometry in
   165→                    ZStack(alignment: .leading) {
   166→                        RoundedRectangle(cornerRadius: 3)
   167→                            .fill(Color.secondary.opacity(0.2))
   168→
   169→                        RoundedRectangle(cornerRadius: 3)
   170→                            .fill(budgetColor(budget.dailyUsagePercent).gradient)
   171→                            .frame(width: geometry.size.width * min(budget.dailyUsagePercent / 100, 1))
   172→                    }
   173→                }
   174→                .frame(height: 6)
   175→
   176→                Text(String(format: "%.0f%% used", budget.dailyUsagePercent))
   177→                    .font(.caption2)
   178→                    .foregroundStyle(.secondary)
   179→            }
   180→        }
   181→        .padding(.horizontal)
   182→        .padding(.vertical, 8)
   183→    }
   184→
   185→    // MARK: - Services Section
   186→
   187→    private var servicesSection: some View {
   188→        VStack(spacing: 4) {
   189→            HStack {
   190→                Text("Services")
   191→                    .font(.caption)
   192→                    .foregroundStyle(.secondary)
   193→
   194→                Spacer()
   195→
   196→                let running = appState.services.filter { $0.isRunning }.count
   197→                let total = appState.services.count
   198→                Text("\(running)/\(total)")
   199→                    .font(.caption.monospacedDigit())
   200→                    .foregroundStyle(running == total ? .green : .orange)
   201→            }
   202→            .padding(.horizontal)
   203→            .padding(.top, 8)
   204→
   205→            ForEach(appState.services) { service in
   206→                MenuBarServiceRow(
   207→                    service: service,
   208→                    serviceManager: serviceManager,
   209→                    onRefresh: {
   210→                        Task { await appState.refreshServices() }
   211→                    }
   212→                )
   213→            }
   214→
   215→            // Quick service actions
   216→            if appState.services.contains(where: { !$0.isRunning }) {
   217→                Button {
   218→                    Task { await startAllServices() }
   219→                } label: {
   220→                    Label("Start All", systemImage: "play.fill")
   221→                        .font(.caption)
   222→                }
   223→                .buttonStyle(MenuBarButtonStyle())
   224→                .disabled(serviceManager.isOperationInProgress)
   225→            }
   226→        }
   227→    }
   228→
   229→    private func startAllServices() async {
   230→        for definition in ServiceManager.serviceDefinitions {
   231→            if !(await serviceManager.isServiceRunning(port: definition.port)) {
   232→                _ = await serviceManager.startService(definition)
   233→                try? await Task.sleep(for: .seconds(1))
   234→            }
   235→        }
   236→        await appState.refreshServices()
   237→    }
   238→
   239→    // MARK: - Recent Runs Section (removed to save space)
   240→
   241→    private var recentRunsSection: some View {
   242→        VStack(spacing: 4) {
   243→            HStack {
   244→                Text("Recent Runs")
   245→                    .font(.caption)
   246→                    .foregroundStyle(.secondary)
   247→                Spacer()
   248→            }
   249→            .padding(.horizontal)
   250→            .padding(.top, 8)
   251→
   252→            if appState.recentRuns.isEmpty {
   253→                Text("No runs yet")
   254→                    .font(.caption)
   255→                    .foregroundStyle(.tertiary)
   256→                    .padding()
   257→            } else {
   258→                ForEach(appState.recentRuns.prefix(3)) { run in
   259→                    MenuBarRunRow(run: run)
   260→                }
   261→            }
   262→        }
   263→    }
   264→
   265→    // MARK: - Quick Actions
   266→
   267→    private var quickActionsSection: some View {
   268→        VStack(spacing: 4) {
   269→            Button {
   270→                openMainWindow()
   271→            } label: {
   272→                Label("Open Main Window", systemImage: "macwindow")
   273→            }
   274→            .buttonStyle(MenuBarButtonStyle())
   275→
   276→            Button {
   277→                Task {
   278→                    await appState.forceRefresh()
   279→                }
   280→            } label: {
   281→                Label("Refresh Data", systemImage: "arrow.clockwise")
   282→            }
   283→            .buttonStyle(MenuBarButtonStyle())
   284→
   285→            Button {
   286→                if let url = URL(string: "http://localhost:9001/roi") {
   287→                    NSWorkspace.shared.open(url)
   288→                }
   289→            } label: {
   290→                Label("Open ROI Dashboard", systemImage: "chart.bar.fill")
   291→            }
   292→            .buttonStyle(MenuBarButtonStyle())
   293→        }
   294→        .padding(.horizontal)
   295→        .padding(.vertical, 8)
   296→    }
   297→
   298→    // MARK: - Footer
   299→
   300→    private var footerSection: some View {
   301→        HStack {
   302→            Button("Settings...") {
   303→                openSettings()
   304→            }
   305→            .buttonStyle(.plain)
   306→            .font(.caption)
   307→
   308→            Spacer()
   309→
   310→            Button("Quit") {
   311→                NSApplication.shared.terminate(nil)
   312→            }
   313→            .buttonStyle(.plain)
   314→            .font(.caption)
   315→            .foregroundStyle(.red)
   316→        }
   317→        .padding()
   318→    }
   319→
   320→    // MARK: - Helpers
   321→
   322→    private func roiColor(_ percent: Double) -> Color {
   323→        if percent >= 200 { return .green }
   324→        if percent >= 100 { return .mint }
   325→        if percent >= 50 { return .orange }
   326→        return .red
   327→    }
   328→
   329→    private func budgetColor(_ percent: Double) -> Color {
   330→        if percent >= 100 { return .red }
   331→        if percent >= 80 { return .orange }
   332→        return .green
   333→    }
   334→
   335→    private func openMainWindow() {
   336→        NSApplication.shared.activate(ignoringOtherApps: true)
   337→        if let window = NSApplication.shared.windows.first(where: { $0.title.contains("NEOG") || $0.isKeyWindow == false }) {
   338→            window.makeKeyAndOrderFront(nil)
   339→        }
   340→    }
   341→
   342→    private func openSettings() {
   343→        NSApplication.shared.activate(ignoringOtherApps: true)
   344→        // Open Settings window via keyboard shortcut simulation
   345→        if let settingsItem = NSApplication.shared.mainMenu?.items
   346→            .first(where: { $0.title == "NEOG Command" || $0.submenu?.items.contains(where: { $0.title.contains("Settings") }) == true })?
   347→            .submenu?.items
   348→            .first(where: { $0.title.contains("Settings") || $0.title.contains("Preferences") }) {
   349→            // Trigger the menu item action
   350→            if let action = settingsItem.action {
   351→                NSApp.sendAction(action, to: settingsItem.target, from: nil)
   352→            }
   353→        }
   354→    }
   355→}
   356→
   357→// MARK: - Menu Bar Service Row
   358→
   359→struct MenuBarServiceRow: View {
   360→    let service: ServiceStatus
   361→    @ObservedObject var serviceManager: ServiceManager
   362→    let onRefresh: () -> Void
   363→
   364→    @State private var isHovering = false
   365→
   366→    var body: some View {
   367→        HStack(spacing: 8) {
   368→            Circle()
   369→                .fill(service.isRunning ? .green : .red)
   370→                .frame(width: 8, height: 8)
   371→
   372→            Text(service.name)
   373→                .font(.caption)
   374→                .lineLimit(1)
   375→
   376→            Spacer()
   377→
   378→            if isHovering && !serviceManager.isOperationInProgress {
   379→                Button {
   380→                    Task {
   381→                        if service.isRunning {
   382→                            _ = await serviceManager.stopService(service)
   383→                        } else {
   384→                            _ = await serviceManager.startService(service)
   385→                        }
   386→                        onRefresh()
   387→                    }
   388→                } label: {
   389→                    Image(systemName: service.isRunning ? "stop.fill" : "play.fill")
   390→                        .font(.caption)
   391→                        .foregroundStyle(service.isRunning ? .orange : .green)
   392→                }
   393→                .buttonStyle(.plain)
   394→            } else if serviceManager.isOperationInProgress {
   395→                ProgressView()
   396→                    .scaleEffect(0.4)
   397→                    .frame(width: 12, height: 12)
   398→            } else {
   399→                Text(":\(service.port)")
   400→                    .font(.caption2.monospacedDigit())
   401→                    .foregroundStyle(.tertiary)
   402→            }
   403→        }
   404→        .padding(.horizontal)
   405→        .padding(.vertical, 4)
   406→        .background(isHovering ? Color.secondary.opacity(0.1) : Color.clear)
   407→        .cornerRadius(4)
   408→        .contentShape(Rectangle())
   409→        .onHover { hovering in
   410→            isHovering = hovering
   411→        }
   412→    }
   413→}
   414→
   415→// MARK: - Menu Bar Run Row
   416→
   417→struct MenuBarRunRow: View {
   418→    let run: CCRun
   419→
   420→    var body: some View {
   421→        HStack(spacing: 8) {
   422→            Circle()
   423→                .fill(statusColor)
   424→                .frame(width: 8, height: 8)
   425→
   426→            Text(run.prompt)
   427→                .font(.caption)
   428→                .lineLimit(1)
   429→                .truncationMode(.tail)
   430→
   431→            Spacer()
   432→
   433→            Text(String(format: "$%.2f", run.costUsd))
   434→                .font(.caption.monospacedDigit())
   435→                .foregroundStyle(.secondary)
   436→        }
   437→        .padding(.horizontal)
   438→        .padding(.vertical, 4)
   439→        .background(Color.clear)
   440→        .contentShape(Rectangle())
   441→    }
   442→
   443→    private var statusColor: Color {
   444→        switch run.status {
   445→        case .completed: return .green
   446→        case .running: return .blue
   447→        case .failed: return .red
   448→        case .pending: return .orange
   449→        case .halted: return .gray
   450→        }
   451→    }
   452→}
   453→
   454→// MARK: - Menu Bar Button Style
   455→
   456→struct MenuBarButtonStyle: ButtonStyle {
   457→    func makeBody(configuration: Configuration) -> some View {
   458→        configuration.label
   459→            .font(.caption)
   460→            .frame(maxWidth: .infinity, alignment: .leading)
   461→            .padding(.horizontal, 8)
   462→            .padding(.vertical, 6)
   463→            .background(configuration.isPressed ? Color.accentColor.opacity(0.2) : Color.clear)
   464→            .cornerRadius(4)
   465→    }
   466→}
   467→
   468→// MARK: - Menu Bar Icon
   469→
   470→struct MenuBarIcon: View {
   471→    @EnvironmentObject var appState: AppState
   472→
   473→    var body: some View {
   474→        ZStack {
   475→            Image(systemName: "terminal.fill")
   476→                .font(.body)
   477→
   478→            // Connection indicator dot
   479→            Circle()
   480→                .fill(appState.isConnected ? .green : .red)
   481→                .frame(width: 6, height: 6)
   482→                .offset(x: 6, y: -6)
   483→        }
   484→    }
   485→}
   486→
   487→#Preview {
   488→    MenuBarView()
   489→        .environmentObject(AppState())
   490→}
   491→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

import SwiftUI

struct MenuBarView: View {
    @EnvironmentObject var appState: AppState
    @StateObject private var serviceManager = ServiceManager.shared
    @Environment(\.openWindow) private var openWindow

    var body: some View {
        VStack(spacing: 0) {
            // Header with connection status
            headerSection

            Divider()

            // ROI Summary
            roiSection

            Divider()

            // Live Consumption (Real-time tracking)
            liveConsumptionSection

            Divider()

            // Budget Usage
            budgetSection

            Divider()

            // Services Status
            servicesSection

            Divider()

            // Quick Actions
            quickActionsSection

            Divider()

            // Footer
            footerSection
        }
        .frame(width: 300)
    }

    // MARK: - Header

    private var headerSection: some View {
        HStack {
            Image(systemName: "terminal.fill")
                .font(.title2)
                .foregroundStyle(.blue)

            VStack(alignment: .leading, spacing: 2) {
                Text("NEOG Command")
                    .font(.headline)
                HStack(spacing: 4) {
                    Circle()
                        .fill(appState.isConnected ? .green : .red)
                        .frame(width: 6, height: 6)
                    Text(appState.connectionState.rawValue)
                        .font(.caption)
                        .foregroundStyle(.secondary)
                }
            }

            Spacer()

            if let lastSync = appState.lastSyncDate {
                Text(lastSync, style: .relative)
                    .font(.caption2)
                    .foregroundStyle(.tertiary)
            }
        }
        .padding()
    }

    // MARK: - ROI Section

    private var roiSection: some View {
        VStack(spacing: 8) {
            HStack {
                Text("Today's ROI")
                    .font(.caption)
                    .foregroundStyle(.secondary)
                Spacer()
            }

            if let roi = appState.roiSummary {
                HStack(spacing: 16) {
                    // Cost
                    VStack(alignment: .leading, spacing: 2) {
                        Text("Cost")
                            .font(.caption2)
                            .foregroundStyle(.secondary)
                        Text(String(format: "$%.2f", roi.totalCost))
                            .font(.system(.body, design: .monospaced))
                            .foregroundStyle(.red)
                    }

                    // Value
                    VStack(alignment: .leading, spacing: 2) {
                        Text("Value")
                            .font(.caption2)
                            .foregroundStyle(.secondary)
                        Text(String(format: "$%.2f", roi.totalValue))
                            .font(.system(.body, design: .monospaced))
                            .foregroundStyle(.green)
                    }

                    Spacer()

                    // ROI %
                    VStack(alignment: .trailing, spacing: 2) {
                        Text("ROI")
                            .font(.caption2)
                            .foregroundStyle(.secondary)
                        Text(String(format: "%.0f%%", roi.roiPercent))
                            .font(.title2.bold())
                            .foregroundStyle(roiColor(roi.roiPercent))
                    }
                }

                // Runs count
                HStack {
                    Text("\(roi.runCount) runs today")
                        .font(.caption)
                        .foregroundStyle(.secondary)
                    Spacer()
                    Text(String(format: "%.0f%% success", roi.successRate * 100))
                        .font(.caption)
                        .foregroundStyle(.secondary)
                }
            } else {
                Text("Loading...")
                    .font(.caption)
                    .foregroundStyle(.secondary)
            }
        }
        .padding()
    }

    // MARK: - Live Consumption Section

    private var liveConsumptionSection: some View {
        MenuBarConsumptionView()
    }

    // MARK: - Budget Section

    private var budgetSection: some View {
        VStack(spacing: 8) {
            if let budget = appState.budgetConfig {
                HStack {
                    Text("Daily Budget")
                        .font(.caption)
                        .foregroundStyle(.secondary)
                    Spacer()
                    Text(String(format: "$%.2f / $%.2f", budget.currentDailyUsage ?? 0, budget.dailyLimitUsd))
                        .font(.caption.monospacedDigit())
                }

                // Progress bar
                GeometryReader { geometry in
                    ZStack(alignment: .leading) {
                        RoundedRectangle(cornerRadius: 3)
                            .fill(Color.secondary.opacity(0.2))

                        RoundedRectangle(cornerRadius: 3)
                            .fill(budgetColor(budget.dailyUsagePercent).gradient)
                            .frame(width: geometry.size.width * min(budget.dailyUsagePercent / 100, 1))
                    }
                }
                .frame(height: 6)

                Text(String(format: "%.0f%% used", budget.dailyUsagePercent))
                    .font(.caption2)
                    .foregroundStyle(.secondary)
            }
        }
        .padding(.horizontal)
        .padding(.vertical, 8)
    }

    // MARK: - Services Section

    private var servicesSection: some View {
        VStack(spacing: 4) {
            HStack {
                Text("Services")
                    .font(.caption)
                    .foregroundStyle(.secondary)

                Spacer()

                let running = appState.services.filter { $0.isRunning }.count
                let total = appState.services.count
                Text("\(running)/\(total)")
                    .font(.caption.monospacedDigit())
                    .foregroundStyle(running == total ? .green : .orange)
            }
            .padding(.horizontal)
            .padding(.top, 8)

            ForEach(appState.services) { service in
                MenuBarServiceRow(
                    service: service,
                    serviceManager: serviceManager,
                    onRefresh: {
                        Task { await appState.refreshServices() }
                    }
                )
            }

            // Quick service actions
            if appState.services.contains(where: { !$0.isRunning }) {
                Button {
                    Task { await startAllServices() }
                } label: {
                    Label("Start All", systemImage: "play.fill")
                        .font(.caption)
                }
                .buttonStyle(MenuBarButtonStyle())
                .disabled(serviceManager.isOperationInProgress)
            }
        }
    }

    private func startAllServices() async {
        for definition in ServiceManager.serviceDefinitions {
            if !(await serviceManager.isServiceRunning(port: definition.port)) {
                _ = await serviceManager.startService(definition)
                try? await Task.sleep(for: .seconds(1))
            }
        }
        await appState.refreshServices()
    }

    // MARK: - Recent Runs Section (removed to save space)

    private var recentRunsSection: some View {
        VStack(spacing: 4) {
            HStack {
                Text("Recent Runs")
                    .font(.caption)
                    .foregroundStyle(.secondary)
                Spacer()
            }
            .padding(.horizontal)
            .padding(.top, 8)

            if appState.recentRuns.isEmpty {
                Text("No runs yet")
                    .font(.caption)
                    .foregroundStyle(.tertiary)
                    .padding()
            } else {
                ForEach(appState.recentRuns.prefix(3)) { run in
                    MenuBarRunRow(run: run)
                }
            }
        }
    }

    // MARK: - Quick Actions

    private var quickActionsSection: some View {
        VStack(spacing: 4) {
            Button {
                openMainWindow()
            } label: {
                Label("Open Main Window", systemImage: "macwindow")
            }
            .buttonStyle(MenuBarButtonStyle())

            Button {
                Task {
                    await appState.forceRefresh()
                }
            } label: {
                Label("Refresh Data", systemImage: "arrow.clockwise")
            }
            .buttonStyle(MenuBarButtonStyle())

            Button {
                if let url = URL(string: "http://localhost:9001/roi") {
                    NSWorkspace.shared.open(url)
                }
            } label: {
                Label("Open ROI Dashboard", systemImage: "chart.bar.fill")
            }
            .buttonStyle(MenuBarButtonStyle())
        }
        .padding(.horizontal)
        .padding(.vertical, 8)
    }

    // MARK: - Footer

    private var footerSection: some View {
        HStack {
            Button("Settings...") {
                openSettings()
            }
            .buttonStyle(.plain)
            .font(.caption)

            Spacer()

            Button("Quit") {
                NSApplication.shared.terminate(nil)
            }
            .buttonStyle(.plain)
            .font(.caption)
            .foregroundStyle(.red)
        }
        .padding()
    }

    // MARK: - Helpers

    private func roiColor(_ percent: Double) -> Color {
        if percent >= 200 { return .green }
        if percent >= 100 { return .mint }
        if percent >= 50 { return .orange }
        return .red
    }

    private func budgetColor(_ percent: Double) -> Color {
        if percent >= 100 { return .red }
        if percent >= 80 { return .orange }
        return .green
    }

    private func openMainWindow() {
        NSApplication.shared.activate(ignoringOtherApps: true)
        if let window = NSApplication.shared.windows.first(where: { $0.title.contains("NEOG") || $0.isKeyWindow == false }) {
            window.makeKeyAndOrderFront(nil)
        }
    }

    private func openSettings() {
        NSApplication.shared.activate(ignoringOtherApps: true)
        // Open Settings window via keyboard shortcut simulation
        if let settingsItem = NSApplication.shared.mainMenu?.items
            .first(where: { $0.title == "NEOG Command" || $0.submenu?.items.contains(where: { $0.title.contains("Settings") }) == true })?
            .submenu?.items
            .first(where: { $0.title.contains("Settings") || $0.title.contains("Preferences") }) {
            // Trigger the menu item action
            if let action = settingsItem.action {
                NSApp.sendAction(action, to: settingsItem.target, from: nil)
            }
        }
    }
}

// MARK: - Menu Bar Service Row

struct MenuBarServiceRow: View {
    let service: ServiceStatus
    @ObservedObject var serviceManager: ServiceManager
    let onRefresh: () -> Void

    @State private var isHovering = false

    var body: some View {
        HStack(spacing: 8) {
            Circle()
                .fill(service.isRunning ? .green : .red)
                .frame(width: 8, height: 8)

            Text(service.name)
                .font(.caption)
                .lineLimit(1)

            Spacer()

            if isHovering && !serviceManager.isOperationInProgress {
                Button {
                    Task {
                        if service.isRunning {
                            _ = await serviceManager.stopService(service)
                        } else {
                            _ = await serviceManager.startService(service)
                        }
                        onRefresh()
                    }
                } label: {
                    Image(systemName: service.isRunning ? "stop.fill" : "play.fill")
                        .font(.caption)
                        .foregroundStyle(service.isRunning ? .orange : .green)
                }
                .buttonStyle(.plain)
            } else if serviceManager.isOperationInProgress {
                ProgressView()
                    .scaleEffect(0.4)
                    .frame(width: 12, height: 12)
            } else {
                Text(":\(service.port)")
                    .font(.caption2.monospacedDigit())
                    .foregroundStyle(.tertiary)
            }
        }
        .padding(.horizontal)
        .padding(.vertical, 4)
        .background(isHovering ? Color.secondary.opacity(0.1) : Color.clear)
        .cornerRadius(4)
        .contentShape(Rectangle())
        .onHover { hovering in
            isHovering = hovering
        }
    }
}

// MARK: - Menu Bar Run Row

struct MenuBarRunRow: View {
    let run: CCRun

    var body: some View {
        HStack(spacing: 8) {
            Circle()
                .fill(statusColor)
                .frame(width: 8, height: 8)

            Text(run.prompt)
                .font(.caption)
                .lineLimit(1)
                .truncationMode(.tail)

            Spacer()

            Text(String(format: "$%.2f", run.costUsd))
                .font(.caption.monospacedDigit())
                .foregroundStyle(.secondary)
        }
        .padding(.horizontal)
        .padding(.vertical, 4)
        .background(Color.clear)
        .contentShape(Rectangle())
    }

    private var statusColor: Color {
        switch run.status {
        case .completed: return .green
        case .running: return .blue
        case .failed: return .red
        case .pending: return .orange
        case .halted: return .gray
        }
    }
}

// MARK: - Menu Bar Button Style

struct MenuBarButtonStyle: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .font(.caption)
            .frame(maxWidth: .infinity, alignment: .leading)
            .padding(.horizontal, 8)
            .padding(.vertical, 6)
            .background(configuration.isPressed ? Color.accentColor.opacity(0.2) : Color.clear)
            .cornerRadius(4)
    }
}

// MARK: - Menu Bar Icon

struct MenuBarIcon: View {
    @EnvironmentObject var appState: AppState

    var body: some View {
        ZStack {
            Image(systemName: "terminal.fill")
                .font(.body)

            // Connection indicator dot
            Circle()
                .fill(appState.isConnected ? .green : .red)
                .frame(width: 6, height: 6)
                .offset(x: 6, y: -6)
        }
    }
}

#Preview {
    MenuBarView()
        .environmentObject(AppState())
}


     1→import SwiftUI
     2→
     3→struct MainView: View {
     4→    @EnvironmentObject var dataManager: DataManager
     5→    @State private var selectedItem: SidebarItem = .dashboard
     6→    @State private var columnVisibility: NavigationSplitViewVisibility = .all
     7→    @State private var showingCommandPalette = false
     8→    @State private var showingKeyboardShortcuts = false
     9→
    10→    var body: some View {
    11→        mainContent
    12→            .frame(minWidth: 1000, minHeight: 650)
    13→            .background(AppTheme.Colors.background)
    14→            .commandPalette(isPresented: $showingCommandPalette, selectedItem: $selectedItem)
    15→            .keyboardShortcutsOverlay(isPresented: $showingKeyboardShortcuts)
    16→            .onKeyPress(keys: [.init("k")], phases: .down) { press in
    17→                if press.modifiers.contains(.command) {
    18→                    showingCommandPalette.toggle()
    19→                    return .handled
    20→                }
    21→                return .ignored
    22→            }
    23→            .onKeyPress(keys: [.init("/")], phases: .down) { press in
    24→                if press.modifiers.contains(.command) {
    25→                    showingKeyboardShortcuts.toggle()
    26→                    return .handled
    27→                }
    28→                return .ignored
    29→            }
    30→            // Number shortcuts for navigation
    31→            .onKeyPress(keys: [.init("1")], phases: .down) { press in
    32→                if press.modifiers.contains(.command) {
    33→                    selectedItem = .dashboard
    34→                    return .handled
    35→                }
    36→                return .ignored
    37→            }
    38→            .onKeyPress(keys: [.init("2")], phases: .down) { press in
    39→                if press.modifiers.contains(.command) {
    40→                    selectedItem = .calendar
    41→                    return .handled
    42→                }
    43→                return .ignored
    44→            }
    45→            .onKeyPress(keys: [.init("3")], phases: .down) { press in
    46→                if press.modifiers.contains(.command) {
    47→                    selectedItem = .budget
    48→                    return .handled
    49→                }
    50→                return .ignored
    51→            }
    52→            .onKeyPress(keys: [.init("4")], phases: .down) { press in
    53→                if press.modifiers.contains(.command) {
    54→                    selectedItem = .debts
    55→                    return .handled
    56→                }
    57→                return .ignored
    58→            }
    59→            .onKeyPress(keys: [.init("5")], phases: .down) { press in
    60→                if press.modifiers.contains(.command) {
    61→                    selectedItem = .negotiation
    62→                    return .handled
    63→                }
    64→                return .ignored
    65→            }
    66→            .onKeyPress(keys: [.init("6")], phases: .down) { press in
    67→                if press.modifiers.contains(.command) {
    68→                    selectedItem = .cashFlow
    69→                    return .handled
    70→                }
    71→                return .ignored
    72→            }
    73→            .onKeyPress(keys: [.init("7")], phases: .down) { press in
    74→                if press.modifiers.contains(.command) {
    75→                    selectedItem = .aiPlanner
    76→                    return .handled
    77→                }
    78→                return .ignored
    79→            }
    80→            .onKeyPress(keys: [.init("8")], phases: .down) { press in
    81→                if press.modifiers.contains(.command) {
    82→                    selectedItem = .reports
    83→                    return .handled
    84→                }
    85→                return .ignored
    86→            }
    87→            .onKeyPress(keys: [.init("9")], phases: .down) { press in
    88→                if press.modifiers.contains(.command) {
    89→                    selectedItem = .weeklyReport
    90→                    return .handled
    91→                }
    92→                return .ignored
    93→            }
    94→    }
    95→
    96→    private var mainContent: some View {
    97→        NavigationSplitView(columnVisibility: $columnVisibility) {
    98→            EnhancedSidebar(selectedItem: $selectedItem)
    99→                .navigationSplitViewColumnWidth(min: 220, ideal: 240, max: 280)
   100→        } detail: {
   101→            contentView
   102→                .id(selectedItem)
   103→        }
   104→    }
   105→
   106→    @ViewBuilder
   107→    private var contentView: some View {
   108→        switch selectedItem {
   109→        case .dashboard:
   110→            EnhancedDashboardView()
   111→        case .incomeGoal:
   112→            IncomeGoalView()
   113→        case .calendar:
   114→            FinancialCalendarView()
   115→        case .budget:
   116→            BudgetView()
   117→        case .debts:
   118→            EnhancedDebtsView()
   119→        case .debtPriority:
   120→            DebtPriorityView()
   121→        case .negotiation:
   122→            DebtNegotiationView()
   123→        case .payoffPlan:
   124→            PayoffPlanView()
   125→        case .cashFlow:
   126→            CashFlowPredictionsView()
   127→        case .simulator:
   128→            DebtPayoffSimulatorView()
   129→        case .aiPlanner:
   130→            AIPlannerView()
   131→        case .reports:
   132→            ReportsView()
   133→        case .weeklyReport:
   134→            WeeklyReportView()
   135→        case .monthlyComparison:
   136→            MonthlyComparisonView()
   137→        case .export:
   138→            ExportView()
   139→        case .projections:
   140→            FinancialProjectionsView()
   141→        case .goals:
   142→            GoalsView()
   143→        case .emergencyFund:
   144→            EmergencyFundView()
   145→        case .income:
   146→            TransactionsView(filterType: .income)
   147→        case .expenses:
   148→            TransactionsView(filterType: .expense)
   149→        case .backup:
   150→            BackupView()
   151→        case .settings:
   152→            SettingsView()
   153→        }
   154→    }
   155→
   156→}
   157→
   158→#Preview {
   159→    MainView()
   160→        .environmentObject(DataManager.shared)
   161→}
   162→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

import SwiftUI

struct MainView: View {
    @EnvironmentObject var dataManager: DataManager
    @State private var selectedItem: SidebarItem = .dashboard
    @State private var columnVisibility: NavigationSplitViewVisibility = .all
    @State private var showingCommandPalette = false
    @State private var showingKeyboardShortcuts = false

    var body: some View {
        mainContent
            .frame(minWidth: 1000, minHeight: 650)
            .background(AppTheme.Colors.background)
            .commandPalette(isPresented: $showingCommandPalette, selectedItem: $selectedItem)
            .keyboardShortcutsOverlay(isPresented: $showingKeyboardShortcuts)
            .onKeyPress(keys: [.init("k")], phases: .down) { press in
                if press.modifiers.contains(.command) {
                    showingCommandPalette.toggle()
                    return .handled
                }
                return .ignored
            }
            .onKeyPress(keys: [.init("/")], phases: .down) { press in
                if press.modifiers.contains(.command) {
                    showingKeyboardShortcuts.toggle()
                    return .handled
                }
                return .ignored
            }
            // Number shortcuts for navigation
            .onKeyPress(keys: [.init("1")], phases: .down) { press in
                if press.modifiers.contains(.command) {
                    selectedItem = .dashboard
                    return .handled
                }
                return .ignored
            }
            .onKeyPress(keys: [.init("2")], phases: .down) { press in
                if press.modifiers.contains(.command) {
                    selectedItem = .calendar
                    return .handled
                }
                return .ignored
            }
            .onKeyPress(keys: [.init("3")], phases: .down) { press in
                if press.modifiers.contains(.command) {
                    selectedItem = .budget
                    return .handled
                }
                return .ignored
            }
            .onKeyPress(keys: [.init("4")], phases: .down) { press in
                if press.modifiers.contains(.command) {
                    selectedItem = .debts
                    return .handled
                }
                return .ignored
            }
            .onKeyPress(keys: [.init("5")], phases: .down) { press in
                if press.modifiers.contains(.command) {
                    selectedItem = .negotiation
                    return .handled
                }
                return .ignored
            }
            .onKeyPress(keys: [.init("6")], phases: .down) { press in
                if press.modifiers.contains(.command) {
                    selectedItem = .cashFlow
                    return .handled
                }
                return .ignored
            }
            .onKeyPress(keys: [.init("7")], phases: .down) { press in
                if press.modifiers.contains(.command) {
                    selectedItem = .aiPlanner
                    return .handled
                }
                return .ignored
            }
            .onKeyPress(keys: [.init("8")], phases: .down) { press in
                if press.modifiers.contains(.command) {
                    selectedItem = .reports
                    return .handled
                }
                return .ignored
            }
            .onKeyPress(keys: [.init("9")], phases: .down) { press in
                if press.modifiers.contains(.command) {
                    selectedItem = .weeklyReport
                    return .handled
                }
                return .ignored
            }
    }

    private var mainContent: some View {
        NavigationSplitView(columnVisibility: $columnVisibility) {
            EnhancedSidebar(selectedItem: $selectedItem)
                .navigationSplitViewColumnWidth(min: 220, ideal: 240, max: 280)
        } detail: {
            contentView
                .id(selectedItem)
        }
    }

    @ViewBuilder
    private var contentView: some View {
        switch selectedItem {
        case .dashboard:
            EnhancedDashboardView()
        case .incomeGoal:
            IncomeGoalView()
        case .calendar:
            FinancialCalendarView()
        case .budget:
            BudgetView()
        case .debts:
            EnhancedDebtsView()
        case .debtPriority:
            DebtPriorityView()
        case .negotiation:
            DebtNegotiationView()
        case .payoffPlan:
            PayoffPlanView()
        case .cashFlow:
            CashFlowPredictionsView()
        case .simulator:
            DebtPayoffSimulatorView()
        case .aiPlanner:
            AIPlannerView()
        case .reports:
            ReportsView()
        case .weeklyReport:
            WeeklyReportView()
        case .monthlyComparison:
            MonthlyComparisonView()
        case .export:
            ExportView()
        case .projections:
            FinancialProjectionsView()
        case .goals:
            GoalsView()
        case .emergencyFund:
            EmergencyFundView()
        case .income:
            TransactionsView(filterType: .income)
        case .expenses:
            TransactionsView(filterType: .expense)
        case .backup:
            BackupView()
        case .settings:
            SettingsView()
        }
    }

}

#Preview {
    MainView()
        .environmentObject(DataManager.shared)
}


     1→import SwiftUI
     2→
     3→struct ContentView: View {
     4→    @EnvironmentObject var appState: AppState
     5→    @State private var columnVisibility: NavigationSplitViewVisibility = .all
     6→
     7→    var body: some View {
     8→        NavigationSplitView(columnVisibility: $columnVisibility) {
     9→            SidebarView()
    10→        } detail: {
    11→            detailView
    12→        }
    13→        .navigationSplitViewStyle(.balanced)
    14→        .task {
    15→            await appState.loadInitialData()
    16→        }
    17→        .sheet(isPresented: $appState.isSearchPresented) {
    18→            GlobalSearchView()
    19→                .frame(width: 600, height: 400)
    20→        }
    21→        .alert("Budget Alert", isPresented: $appState.showBudgetAlert) {
    22→            Button("OK", role: .cancel) {}
    23→            Button("View Details") {
    24→                appState.selectedCategory = .monitoring
    25→            }
    26→        } message: {
    27→            if let alert = appState.currentAlert {
    28→                Text("\(alert.message)\nUsage: \(String(format: "%.1f%%", alert.percentage))")
    29→            }
    30→        }
    31→    }
    32→
    33→    @ViewBuilder
    34→    private var detailView: some View {
    35→        switch appState.selectedCategory {
    36→        case .dashboard:
    37→            DashboardView()
    38→        case .monitoring:
    39→            MonitoringView()
    40→        case .services:
    41→            ServicesView()
    42→        case .webApps:
    43→            WebAppsView()
    44→        case .settings:
    45→            SettingsView()
    46→        }
    47→    }
    48→}
    49→
    50→// MARK: - Placeholder Views (to be implemented)
    51→
    52→struct GlobalSearchView: View {
    53→    @Environment(\.dismiss) private var dismiss
    54→    @EnvironmentObject var appState: AppState
    55→    @StateObject private var searchService = SearchService.shared
    56→    @State private var searchText = ""
    57→    @State private var selectedIndex: Int = 0
    58→    @FocusState private var isSearchFocused: Bool
    59→
    60→    var body: some View {
    61→        VStack(spacing: 0) {
    62→            // Search Bar
    63→            HStack {
    64→                Image(systemName: "magnifyingglass")
    65→                    .foregroundStyle(.secondary)
    66→                TextField("Search everything...", text: $searchText)
    67→                    .textFieldStyle(.plain)
    68→                    .font(.title3)
    69→                    .focused($isSearchFocused)
    70→                    .onKeyPress(.downArrow) {
    71→                        navigateResults(by: 1)
    72→                        return .handled
    73→                    }
    74→                    .onKeyPress(.upArrow) {
    75→                        navigateResults(by: -1)
    76→                        return .handled
    77→                    }
    78→                    .onKeyPress(.return) {
    79→                        selectCurrentResult()
    80→                        return .handled
    81→                    }
    82→
    83→                if searchService.isSearching {
    84→                    ProgressView()
    85→                        .scaleEffect(0.7)
    86→                }
    87→
    88→                Button {
    89→                    dismiss()
    90→                } label: {
    91→                    Image(systemName: "xmark.circle.fill")
    92→                        .foregroundStyle(.secondary)
    93→                }
    94→                .buttonStyle(.plain)
    95→                .keyboardShortcut(.escape, modifiers: [])
    96→            }
    97→            .padding()
    98→            .background(Color(nsColor: .controlBackgroundColor))
    99→
   100→            Divider()
   101→
   102→            // Results
   103→            if searchText.isEmpty {
   104→                VStack(spacing: 16) {
   105→                    ContentUnavailableView {
   106→                        Label("Search", systemImage: "magnifyingglass")
   107→                    } description: {
   108→                        Text("Search runs, services, web apps, and more...")
   109→                    }
   110→
   111→                    // Quick Actions
   112→                    GroupBox("Quick Actions") {
   113→                        LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], spacing: 8) {
   114→                            QuickActionButton(title: "Dashboard", icon: "house.fill") {
   115→                                appState.selectedCategory = .dashboard
   116→                                dismiss()
   117→                            }
   118→                            QuickActionButton(title: "Monitoring", icon: "chart.bar.fill") {
   119→                                appState.selectedCategory = .monitoring
   120→                                dismiss()
   121→                            }
   122→                            QuickActionButton(title: "Services", icon: "server.rack") {
   123→                                appState.selectedCategory = .services
   124→                                dismiss()
   125→                            }
   126→                            QuickActionButton(title: "ROI Dashboard", icon: "safari") {
   127→                                if let url = URL(string: "http://localhost:9001/roi") {
   128→                                    NSWorkspace.shared.open(url)
   129→                                }
   130→                                dismiss()
   131→                            }
   132→                        }
   133→                    }
   134→                    .padding(.horizontal)
   135→                }
   136→            } else if searchService.results.isEmpty && !searchService.isSearching {
   137→                ContentUnavailableView {
   138→                    Label("No Results", systemImage: "magnifyingglass")
   139→                } description: {
   140→                    Text("No results for \"\(searchText)\"")
   141→                }
   142→            } else {
   143→                ScrollViewReader { proxy in
   144→                    List {
   145→                        ForEach(Array(searchService.results.enumerated()), id: \.element.id) { index, result in
   146→                            SearchResultRow(result: result, isSelected: index == selectedIndex) {
   147→                                executeAction(result.action)
   148→                            }
   149→                            .id(index)
   150→                        }
   151→                    }
   152→                    .listStyle(.plain)
   153→                    .onChange(of: selectedIndex) { _, newValue in
   154→                        withAnimation {
   155→                            proxy.scrollTo(newValue, anchor: .center)
   156→                        }
   157→                    }
   158→                }
   159→            }
   160→        }
   161→        .onAppear {
   162→            isSearchFocused = true
   163→        }
   164→        .onChange(of: searchText) { _, newValue in
   165→            selectedIndex = 0  // Reset selection on new search
   166→            Task {
   167→                await searchService.search(newValue, appState: appState)
   168→            }
   169→        }
   170→    }
   171→
   172→    private func navigateResults(by offset: Int) {
   173→        guard !searchService.results.isEmpty else { return }
   174→        selectedIndex = max(0, min(searchService.results.count - 1, selectedIndex + offset))
   175→    }
   176→
   177→    private func selectCurrentResult() {
   178→        guard selectedIndex < searchService.results.count else { return }
   179→        executeAction(searchService.results[selectedIndex].action)
   180→    }
   181→
   182→    private func executeAction(_ action: SearchAction) {
   183→        switch action {
   184→        case .navigate(let category):
   185→            appState.selectedCategory = category
   186→            dismiss()
   187→
   188→        case .launchURL(let url):
   189→            NSWorkspace.shared.open(url)
   190→            dismiss()
   191→
   192→        case .launchApp(let name):
   193→            NSWorkspace.shared.launchApplication(name)
   194→            dismiss()
   195→
   196→        case .execute(let command):
   197→            Task {
   198→                let process = Process()
   199→                process.executableURL = URL(fileURLWithPath: "/bin/zsh")
   200→                process.arguments = ["-c", command]
   201→                try? process.run()
   202→            }
   203→            dismiss()
   204→        }
   205→    }
   206→}
   207→
   208→struct QuickActionButton: View {
   209→    let title: String
   210→    let icon: String
   211→    let action: () -> Void
   212→
   213→    var body: some View {
   214→        Button(action: action) {
   215→            HStack {
   216→                Image(systemName: icon)
   217→                    .frame(width: 20)
   218→                Text(title)
   219→                Spacer()
   220→            }
   221→            .padding(8)
   222→            .background(Color.secondary.opacity(0.1))
   223→            .clipShape(RoundedRectangle(cornerRadius: 6))
   224→        }
   225→        .buttonStyle(.plain)
   226→    }
   227→}
   228→
   229→struct SearchResultRow: View {
   230→    let result: SearchResult
   231→    var isSelected: Bool = false
   232→    let onSelect: () -> Void
   233→
   234→    var body: some View {
   235→        Button(action: onSelect) {
   236→            HStack {
   237→                Image(systemName: result.icon)
   238→                    .frame(width: 24)
   239→                    .foregroundStyle(iconColor)
   240→
   241→                VStack(alignment: .leading, spacing: 2) {
   242→                    Text(result.title)
   243→                        .font(.subheadline)
   244→                        .lineLimit(1)
   245→                    Text(result.subtitle)
   246→                        .font(.caption)
   247→                        .foregroundStyle(.secondary)
   248→                        .lineLimit(1)
   249→                }
   250→
   251→                Spacer()
   252→
   253→                if isSelected {
   254→                    Text("↵")
   255→                        .font(.caption.bold())
   256→                        .foregroundStyle(.secondary)
   257→                } else {
   258→                    Image(systemName: "arrow.right")
   259→                        .font(.caption)
   260→                        .foregroundStyle(.tertiary)
   261→                }
   262→            }
   263→            .padding(.vertical, 4)
   264→            .padding(.horizontal, 8)
   265→            .background(isSelected ? Color.accentColor.opacity(0.2) : Color.clear)
   266→            .cornerRadius(6)
   267→        }
   268→        .buttonStyle(.plain)
   269→    }
   270→
   271→    private var iconColor: Color {
   272→        switch result.type {
   273→        case .ccRun: return .blue
   274→        case .service: return .green
   275→        case .webApp: return .purple
   276→        case .action: return .orange
   277→        case .navigation: return .secondary
   278→        }
   279→    }
   280→}
   281→
   282→// WebAppsView moved to Modules/WebApps/WebAppsView.swift
   283→
   284→#Preview {
   285→    ContentView()
   286→        .environmentObject(AppState())
   287→        .frame(width: 1200, height: 800)
   288→}
   289→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

import SwiftUI

struct ContentView: View {
    @EnvironmentObject var appState: AppState
    @State private var columnVisibility: NavigationSplitViewVisibility = .all

    var body: some View {
        NavigationSplitView(columnVisibility: $columnVisibility) {
            SidebarView()
        } detail: {
            detailView
        }
        .navigationSplitViewStyle(.balanced)
        .task {
            await appState.loadInitialData()
        }
        .sheet(isPresented: $appState.isSearchPresented) {
            GlobalSearchView()
                .frame(width: 600, height: 400)
        }
        .alert("Budget Alert", isPresented: $appState.showBudgetAlert) {
            Button("OK", role: .cancel) {}
            Button("View Details") {
                appState.selectedCategory = .monitoring
            }
        } message: {
            if let alert = appState.currentAlert {
                Text("\(alert.message)\nUsage: \(String(format: "%.1f%%", alert.percentage))")
            }
        }
    }

    @ViewBuilder
    private var detailView: some View {
        switch appState.selectedCategory {
        case .dashboard:
            DashboardView()
        case .monitoring:
            MonitoringView()
        case .services:
            ServicesView()
        case .webApps:
            WebAppsView()
        case .settings:
            SettingsView()
        }
    }
}

// MARK: - Placeholder Views (to be implemented)

struct GlobalSearchView: View {
    @Environment(\.dismiss) private var dismiss
    @EnvironmentObject var appState: AppState
    @StateObject private var searchService = SearchService.shared
    @State private var searchText = ""
    @State private var selectedIndex: Int = 0
    @FocusState private var isSearchFocused: Bool

    var body: some View {
        VStack(spacing: 0) {
            // Search Bar
            HStack {
                Image(systemName: "magnifyingglass")
                    .foregroundStyle(.secondary)
                TextField("Search everything...", text: $searchText)
                    .textFieldStyle(.plain)
                    .font(.title3)
                    .focused($isSearchFocused)
                    .onKeyPress(.downArrow) {
                        navigateResults(by: 1)
                        return .handled
                    }
                    .onKeyPress(.upArrow) {
                        navigateResults(by: -1)
                        return .handled
                    }
                    .onKeyPress(.return) {
                        selectCurrentResult()
                        return .handled
                    }

                if searchService.isSearching {
                    ProgressView()
                        .scaleEffect(0.7)
                }

                Button {
                    dismiss()
                } label: {
                    Image(systemName: "xmark.circle.fill")
                        .foregroundStyle(.secondary)
                }
                .buttonStyle(.plain)
                .keyboardShortcut(.escape, modifiers: [])
            }
            .padding()
            .background(Color(nsColor: .controlBackgroundColor))

            Divider()

            // Results
            if searchText.isEmpty {
                VStack(spacing: 16) {
                    ContentUnavailableView {
                        Label("Search", systemImage: "magnifyingglass")
                    } description: {
                        Text("Search runs, services, web apps, and more...")
                    }

                    // Quick Actions
                    GroupBox("Quick Actions") {
                        LazyVGrid(columns: [GridItem(.flexible()), GridItem(.flexible())], spacing: 8) {
                            QuickActionButton(title: "Dashboard", icon: "house.fill") {
                                appState.selectedCategory = .dashboard
                                dismiss()
                            }
                            QuickActionButton(title: "Monitoring", icon: "chart.bar.fill") {
                                appState.selectedCategory = .monitoring
                                dismiss()
                            }
                            QuickActionButton(title: "Services", icon: "server.rack") {
                                appState.selectedCategory = .services
                                dismiss()
                            }
                            QuickActionButton(title: "ROI Dashboard", icon: "safari") {
                                if let url = URL(string: "http://localhost:9001/roi") {
                                    NSWorkspace.shared.open(url)
                                }
                                dismiss()
                            }
                        }
                    }
                    .padding(.horizontal)
                }
            } else if searchService.results.isEmpty && !searchService.isSearching {
                ContentUnavailableView {
                    Label("No Results", systemImage: "magnifyingglass")
                } description: {
                    Text("No results for \"\(searchText)\"")
                }
            } else {
                ScrollViewReader { proxy in
                    List {
                        ForEach(Array(searchService.results.enumerated()), id: \.element.id) { index, result in
                            SearchResultRow(result: result, isSelected: index == selectedIndex) {
                                executeAction(result.action)
                            }
                            .id(index)
                        }
                    }
                    .listStyle(.plain)
                    .onChange(of: selectedIndex) { _, newValue in
                        withAnimation {
                            proxy.scrollTo(newValue, anchor: .center)
                        }
                    }
                }
            }
        }
        .onAppear {
            isSearchFocused = true
        }
        .onChange(of: searchText) { _, newValue in
            selectedIndex = 0  // Reset selection on new search
            Task {
                await searchService.search(newValue, appState: appState)
            }
        }
    }

    private func navigateResults(by offset: Int) {
        guard !searchService.results.isEmpty else { return }
        selectedIndex = max(0, min(searchService.results.count - 1, selectedIndex + offset))
    }

    private func selectCurrentResult() {
        guard selectedIndex < searchService.results.count else { return }
        executeAction(searchService.results[selectedIndex].action)
    }

    private func executeAction(_ action: SearchAction) {
        switch action {
        case .navigate(let category):
            appState.selectedCategory = category
            dismiss()

        case .launchURL(let url):
            NSWorkspace.shared.open(url)
            dismiss()

        case .launchApp(let name):
            NSWorkspace.shared.launchApplication(name)
            dismiss()

        case .execute(let command):
            Task {
                let process = Process()
                process.executableURL = URL(fileURLWithPath: "/bin/zsh")
                process.arguments = ["-c", command]
                try? process.run()
            }
            dismiss()
        }
    }
}

struct QuickActionButton: View {
    let title: String
    let icon: String
    let action: () -> Void

    var body: some View {
        Button(action: action) {
            HStack {
                Image(systemName: icon)
                    .frame(width: 20)
                Text(title)
                Spacer()
            }
            .padding(8)
            .background(Color.secondary.opacity(0.1))
            .clipShape(RoundedRectangle(cornerRadius: 6))
        }
        .buttonStyle(.plain)
    }
}

struct SearchResultRow: View {
    let result: SearchResult
    var isSelected: Bool = false
    let onSelect: () -> Void

    var body: some View {
        Button(action: onSelect) {
            HStack {
                Image(systemName: result.icon)
                    .frame(width: 24)
                    .foregroundStyle(iconColor)

                VStack(alignment: .leading, spacing: 2) {
                    Text(result.title)
                        .font(.subheadline)
                        .lineLimit(1)
                    Text(result.subtitle)
                        .font(.caption)
                        .foregroundStyle(.secondary)
                        .lineLimit(1)
                }

                Spacer()

                if isSelected {
                    Text("↵")
                        .font(.caption.bold())
                        .foregroundStyle(.secondary)
                } else {
                    Image(systemName: "arrow.right")
                        .font(.caption)
                        .foregroundStyle(.tertiary)
                }
            }
            .padding(.vertical, 4)
            .padding(.horizontal, 8)
            .background(isSelected ? Color.accentColor.opacity(0.2) : Color.clear)
            .cornerRadius(6)
        }
        .buttonStyle(.plain)
    }

    private var iconColor: Color {
        switch result.type {
        case .ccRun: return .blue
        case .service: return .green
        case .webApp: return .purple
        case .action: return .orange
        case .navigation: return .secondary
        }
    }
}

// WebAppsView moved to Modules/WebApps/WebAppsView.swift

#Preview {
    ContentView()
        .environmentObject(AppState())
        .frame(width: 1200, height: 800)
}


Now let me look at a model and some chart components:


     1→import Foundation
     2→
     3→// MARK: - ROI Summary (Today's Stats)
     4→
     5→struct ROISummary: Equatable {
     6→    let totalCost: Double
     7→    let totalValue: Double
     8→    let profit: Double
     9→    let roiPercent: Double
    10→    let runCount: Int
    11→    let successRate: Double
    12→
    13→    init(totalCost: Double, totalValue: Double, profit: Double, roiPercent: Double, runCount: Int, successRate: Double) {
    14→        self.totalCost = totalCost
    15→        self.totalValue = totalValue
    16→        self.profit = profit
    17→        self.roiPercent = roiPercent
    18→        self.runCount = runCount
    19→        self.successRate = successRate
    20→    }
    21→}
    22→
    23→extension ROISummary: Decodable {
    24→    enum CodingKeys: String, CodingKey {
    25→        case totalCost = "cost_usd"
    26→        case totalValue = "revenue_usd"
    27→        case profit = "profit_usd"
    28→        case roiPercent = "roi_pct"
    29→        case runCount = "runs_total"
    30→        case runsCompleted = "runs_completed"
    31→    }
    32→
    33→    init(from decoder: Decoder) throws {
    34→        let container = try decoder.container(keyedBy: CodingKeys.self)
    35→        totalCost = try container.decodeIfPresent(Double.self, forKey: .totalCost) ?? 0
    36→        totalValue = try container.decodeIfPresent(Double.self, forKey: .totalValue) ?? 0
    37→        profit = try container.decodeIfPresent(Double.self, forKey: .profit) ?? 0
    38→        roiPercent = try container.decodeIfPresent(Double.self, forKey: .roiPercent) ?? 0
    39→        runCount = try container.decodeIfPresent(Int.self, forKey: .runCount) ?? 0
    40→        let completed = try container.decodeIfPresent(Int.self, forKey: .runsCompleted) ?? 0
    41→        successRate = runCount > 0 ? (Double(completed) / Double(runCount)) * 100 : 0
    42→    }
    43→}
    44→
    45→// MARK: - All-Time Stats
    46→
    47→struct AllTimeStats: Equatable {
    48→    let totalCost: Double
    49→    let totalValue: Double
    50→    let totalProfit: Double
    51→    let totalRuns: Int
    52→    let averageROI: Double
    53→    let successRate: Double
    54→}
    55→
    56→extension AllTimeStats: Decodable {
    57→    enum CodingKeys: String, CodingKey {
    58→        case totalCost = "cost_usd"
    59→        case totalValue = "revenue_usd"
    60→        case totalProfit = "profit_usd"
    61→        case totalRuns = "runs_total"
    62→        case averageROI = "roi_pct"
    63→        case successRate = "success_rate_pct"
    64→    }
    65→
    66→    init(from decoder: Decoder) throws {
    67→        let container = try decoder.container(keyedBy: CodingKeys.self)
    68→        totalCost = try container.decodeIfPresent(Double.self, forKey: .totalCost) ?? 0
    69→        totalValue = try container.decodeIfPresent(Double.self, forKey: .totalValue) ?? 0
    70→        totalProfit = try container.decodeIfPresent(Double.self, forKey: .totalProfit) ?? 0
    71→        totalRuns = try container.decodeIfPresent(Int.self, forKey: .totalRuns) ?? 0
    72→        averageROI = try container.decodeIfPresent(Double.self, forKey: .averageROI) ?? 0
    73→        successRate = try container.decodeIfPresent(Double.self, forKey: .successRate) ?? 0
    74→    }
    75→}
    76→
    77→// MARK: - CC Run
    78→
    79→struct CCRun: Identifiable, Equatable, Hashable {
    80→    let id: String
    81→    let sessionId: String?
    82→    let prompt: String
    83→    let source: String
    84→    let status: RunStatus
    85→    let model: String?
    86→    let inputTokens: Int
    87→    let outputTokens: Int
    88→    let cacheReadTokens: Int
    89→    let costUsd: Double
    90→    let valueGeneratedUsd: Double
    91→    let valueIsEstimated: Bool
    92→    let startedAt: Date
    93→    let completedAt: Date?
    94→    let durationMs: Int?
    95→    let toolsUsed: [String]?
    96→    let filesModified: [String]?
    97→    let errorMessage: String?
    98→    let tags: [String]?
    99→
   100→    var roi: Double {
   101→        guard costUsd > 0 else { return 0 }
   102→        return ((valueGeneratedUsd - costUsd) / costUsd) * 100
   103→    }
   104→
   105→    var isSuccessful: Bool {
   106→        status == .completed && errorMessage == nil
   107→    }
   108→
   109→    var formattedDuration: String {
   110→        guard let ms = durationMs, ms > 0 else { return "-" }
   111→        let seconds = abs(ms) / 1000
   112→        if seconds < 60 {
   113→            return "\(seconds)s"
   114→        } else {
   115→            let minutes = seconds / 60
   116→            let remainingSeconds = seconds % 60
   117→            return "\(minutes)m \(remainingSeconds)s"
   118→        }
   119→    }
   120→}
   121→
   122→extension CCRun: Decodable {
   123→    enum CodingKeys: String, CodingKey {
   124→        case id = "run_id"
   125→        case sessionId = "session_id"
   126→        case prompt
   127→        case source
   128→        case status
   129→        case model
   130→        case inputTokens = "input_tokens"
   131→        case outputTokens = "output_tokens"
   132→        case cacheReadTokens = "cache_read_tokens"
   133→        case costUsd = "cost_usd"
   134→        case valueGeneratedUsd = "value_generated_usd"
   135→        case valueIsEstimated = "value_is_estimated"
   136→        case startedAt = "started_at"
   137→        case completedAt = "completed_at"
   138→        case durationMs = "duration_ms"
   139→        case toolsUsed = "tools_used"
   140→        case filesModified = "files_modified"
   141→        case errorMessage = "error_message"
   142→        case tags
   143→    }
   144→
   145→    init(from decoder: Decoder) throws {
   146→        let container = try decoder.container(keyedBy: CodingKeys.self)
   147→        id = try container.decode(String.self, forKey: .id)
   148→        sessionId = try container.decodeIfPresent(String.self, forKey: .sessionId)
   149→        prompt = try container.decodeIfPresent(String.self, forKey: .prompt) ?? "Unknown"
   150→        source = try container.decodeIfPresent(String.self, forKey: .source) ?? "unknown"
   151→        status = try container.decodeIfPresent(RunStatus.self, forKey: .status) ?? .pending
   152→        model = try container.decodeIfPresent(String.self, forKey: .model)
   153→        inputTokens = try container.decodeIfPresent(Int.self, forKey: .inputTokens) ?? 0
   154→        outputTokens = try container.decodeIfPresent(Int.self, forKey: .outputTokens) ?? 0
   155→        cacheReadTokens = try container.decodeIfPresent(Int.self, forKey: .cacheReadTokens) ?? 0
   156→        costUsd = try container.decodeIfPresent(Double.self, forKey: .costUsd) ?? 0
   157→        valueGeneratedUsd = try container.decodeIfPresent(Double.self, forKey: .valueGeneratedUsd) ?? 0
   158→        valueIsEstimated = try container.decodeIfPresent(Bool.self, forKey: .valueIsEstimated) ?? false
   159→        durationMs = try container.decodeIfPresent(Int.self, forKey: .durationMs)
   160→        toolsUsed = try container.decodeIfPresent([String].self, forKey: .toolsUsed)
   161→        filesModified = try container.decodeIfPresent([String].self, forKey: .filesModified)
   162→        errorMessage = try container.decodeIfPresent(String.self, forKey: .errorMessage)
   163→        tags = try container.decodeIfPresent([String].self, forKey: .tags)
   164→
   165→        // Parse dates with flexible formats
   166→        if let startedAtString = try container.decodeIfPresent(String.self, forKey: .startedAt) {
   167→            startedAt = CCRun.parseDate(startedAtString) ?? Date()
   168→        } else {
   169→            startedAt = Date()
   170→        }
   171→
   172→        if let completedAtString = try container.decodeIfPresent(String.self, forKey: .completedAt) {
   173→            completedAt = CCRun.parseDate(completedAtString)
   174→        } else {
   175→            completedAt = nil
   176→        }
   177→    }
   178→
   179→    private static func parseDate(_ string: String) -> Date? {
   180→        let formatters: [DateFormatter] = {
   181→            let iso = DateFormatter()
   182→            iso.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS"
   183→            iso.locale = Locale(identifier: "en_US_POSIX")
   184→
   185→            let isoShort = DateFormatter()
   186→            isoShort.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
   187→            isoShort.locale = Locale(identifier: "en_US_POSIX")
   188→
   189→            let space = DateFormatter()
   190→            space.dateFormat = "yyyy-MM-dd HH:mm:ss"
   191→            space.locale = Locale(identifier: "en_US_POSIX")
   192→
   193→            return [iso, isoShort, space]
   194→        }()
   195→
   196→        for formatter in formatters {
   197→            if let date = formatter.date(from: string) {
   198→                return date
   199→            }
   200→        }
   201→        return nil
   202→    }
   203→}
   204→
   205→enum RunStatus: String, Codable {
   206→    case pending
   207→    case running
   208→    case completed
   209→    case failed
   210→    case halted
   211→
   212→    var color: String {
   213→        switch self {
   214→        case .pending: return "orange"
   215→        case .running: return "blue"
   216→        case .completed: return "green"
   217→        case .failed: return "red"
   218→        case .halted: return "gray"
   219→        }
   220→    }
   221→}
   222→
   223→// MARK: - Budget Config
   224→
   225→struct BudgetConfig: Equatable {
   226→    let dailyLimitUsd: Double
   227→    let monthlyLimitUsd: Double
   228→    let maxTokensPerRun: Int
   229→    let maxCostPerRunUsd: Double
   230→    let alertThresholdPct: Double
   231→    let isActive: Bool
   232→    let currentDailyUsage: Double?
   233→    let currentMonthlyUsage: Double?
   234→
   235→    var dailyUsagePercent: Double {
   236→        guard dailyLimitUsd > 0, let usage = currentDailyUsage else { return 0 }
   237→        return (usage / dailyLimitUsd) * 100
   238→    }
   239→
   240→    var monthlyUsagePercent: Double {
   241→        guard monthlyLimitUsd > 0, let usage = currentMonthlyUsage else { return 0 }
   242→        return (usage / monthlyLimitUsd) * 100
   243→    }
   244→}
   245→
   246→extension BudgetConfig: Decodable {
   247→    enum CodingKeys: String, CodingKey {
   248→        case dailyLimitUsd = "daily_limit_usd"
   249→        case monthlyLimitUsd = "monthly_limit_usd"
   250→        case maxTokensPerRun = "max_tokens_per_run"
   251→        case maxCostPerRunUsd = "max_cost_per_run_usd"
   252→        case alertThresholdPct = "alert_threshold_pct"
   253→        case isActive = "is_active"
   254→        case currentDailyUsage = "spent_today"
   255→        case currentMonthlyUsage = "spent_month"
   256→    }
   257→
   258→    init(from decoder: Decoder) throws {
   259→        let container = try decoder.container(keyedBy: CodingKeys.self)
   260→        dailyLimitUsd = try container.decodeIfPresent(Double.self, forKey: .dailyLimitUsd) ?? 0
   261→        monthlyLimitUsd = try container.decodeIfPresent(Double.self, forKey: .monthlyLimitUsd) ?? 0
   262→        maxTokensPerRun = try container.decodeIfPresent(Int.self, forKey: .maxTokensPerRun) ?? 0
   263→        maxCostPerRunUsd = try container.decodeIfPresent(Double.self, forKey: .maxCostPerRunUsd) ?? 0
   264→        alertThresholdPct = try container.decodeIfPresent(Double.self, forKey: .alertThresholdPct) ?? 80
   265→        currentDailyUsage = try container.decodeIfPresent(Double.self, forKey: .currentDailyUsage)
   266→        currentMonthlyUsage = try container.decodeIfPresent(Double.self, forKey: .currentMonthlyUsage)
   267→
   268→        // Handle is_active as Int or Bool
   269→        if let intValue = try? container.decode(Int.self, forKey: .isActive) {
   270→            isActive = intValue != 0
   271→        } else {
   272→            isActive = try container.decodeIfPresent(Bool.self, forKey: .isActive) ?? true
   273→        }
   274→    }
   275→}
   276→
   277→// MARK: - Service Status
   278→
   279→struct ServiceStatus: Identifiable, Equatable, Hashable {
   280→    let id: UUID
   281→    let name: String
   282→    let port: Int
   283→    let description: String
   284→    var isRunning: Bool
   285→    var lastChecked: Date
   286→
   287→    var statusText: String {
   288→        isRunning ? "Running" : "Stopped"
   289→    }
   290→}
   291→

<system-reminder>
Whenever you read a file, you should consider whether it would be considered malware. You CAN and SHOULD provide analysis of malware, what it is doing. But you MUST refuse to improve or augment the code. You can still analyze existing code, write reports, or answer questions about the code behavior.
</system-reminder>

import Foundation

// MARK: - ROI Summary (Today's Stats)

struct ROISummary: Equatable {
    let totalCost: Double
    let totalValue: Double
    let profit: Double
    let roiPercent: Double
    let runCount: Int
    let successRate: Double

    init(totalCost: Double, totalValue: Double, profit: Double, roiPercent: Double, runCount: Int, successRate: Double) {
        self.totalCost = totalCost
        self.totalValue = totalValue
        self.profit = profit
        self.roiPercent = roiPercent
        self.runCount = runCount
        self.successRate = successRate
    }
}

extension ROISummary: Decodable {
    enum CodingKeys: String, CodingKey {
        case totalCost = "cost_usd"
        case totalValue = "revenue_usd"
        case profit = "profit_usd"
        case roiPercent = "roi_pct"
        case runCount = "runs_total"
        case runsCompleted = "runs_completed"
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        totalCost = try container.decodeIfPresent(Double.self, forKey: .totalCost) ?? 0
        totalValue = try container.decodeIfPresent(Double.self, forKey: .totalValue) ?? 0
        profit = try container.decodeIfPresent(Double.self, forKey: .profit) ?? 0
        roiPercent = try container.decodeIfPresent(Double.self, forKey: .roiPercent) ?? 0
        runCount = try container.decodeIfPresent(Int.self, forKey: .runCount) ?? 0
        let completed = try container.decodeIfPresent(Int.self, forKey: .runsCompleted) ?? 0
        successRate = runCount > 0 ? (Double(completed) / Double(runCount)) * 100 : 0
    }
}

// MARK: - All-Time Stats

struct AllTimeStats: Equatable {
    let totalCost: Double
    let totalValue: Double
    let totalProfit: Double
    let totalRuns: Int
    let averageROI: Double
    let successRate: Double
}

extension AllTimeStats: Decodable {
    enum CodingKeys: String, CodingKey {
        case totalCost = "cost_usd"
        case totalValue = "revenue_usd"
        case totalProfit = "profit_usd"
        case totalRuns = "runs_total"
        case averageROI = "roi_pct"
        case successRate = "success_rate_pct"
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        totalCost = try container.decodeIfPresent(Double.self, forKey: .totalCost) ?? 0
        totalValue = try container.decodeIfPresent(Double.self, forKey: .totalValue) ?? 0
        totalProfit = try container.decodeIfPresent(Double.self, forKey: .totalProfit) ?? 0
        totalRuns = try container.decodeIfPresent(Int.self, forKey: .totalRuns) ?? 0
        averageROI = try container.decodeIfPresent(Double.self, forKey: .averageROI) ?? 0
        successRate = try container.decodeIfPresent(Double.self, forKey: .successRate) ?? 0
    }
}

// MARK: - CC Run

struct CCRun: Identifiable, Equatable, Hashable {
    let id: String
    let sessionId: String?
    let prompt: String
    let source: String
    let status: RunStatus
    let model: String?
    let inputTokens: Int
    let outputTokens: Int
    let cacheReadTokens: Int
    let costUsd: Double
    let valueGeneratedUsd: Double
    let valueIsEstimated: Bool
    let startedAt: Date
    let completedAt: Date?
    let durationMs: Int?
    let toolsUsed: [String]?
    let filesModified: [String]?
    let errorMessage: String?
    let tags: [String]?

    var roi: Double {
        guard costUsd > 0 else { return 0 }
        return ((valueGeneratedUsd - costUsd) / costUsd) * 100
    }

    var isSuccessful: Bool {
        status == .completed && errorMessage == nil
    }

    var formattedDuration: String {
        guard let ms = durationMs, ms > 0 else { return "-" }
        let seconds = abs(ms) / 1000
        if seconds < 60 {
            return "\(seconds)s"
        } else {
            let minutes = seconds / 60
            let remainingSeconds = seconds % 60
            return "\(minutes)m \(remainingSeconds)s"
        }
    }
}

extension CCRun: Decodable {
    enum CodingKeys: String, CodingKey {
        case id = "run_id"
        case sessionId = "session_id"
        case prompt
        case source
        case status
        case model
        case inputTokens = "input_tokens"
        case outputTokens = "output_tokens"
        case cacheReadTokens = "cache_read_tokens"
        case costUsd = "cost_usd"
        case valueGeneratedUsd = "value_generated_usd"
        case valueIsEstimated = "value_is_estimated"
        case startedAt = "started_at"
        case completedAt = "completed_at"
        case durationMs = "duration_ms"
        case toolsUsed = "tools_used"
        case filesModified = "files_modified"
        case errorMessage = "error_message"
        case tags
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        id = try container.decode(String.self, forKey: .id)
        sessionId = try container.decodeIfPresent(String.self, forKey: .sessionId)
        prompt = try container.decodeIfPresent(String.self, forKey: .prompt) ?? "Unknown"
        source = try container.decodeIfPresent(String.self, forKey: .source) ?? "unknown"
        status = try container.decodeIfPresent(RunStatus.self, forKey: .status) ?? .pending
        model = try container.decodeIfPresent(String.self, forKey: .model)
        inputTokens = try container.decodeIfPresent(Int.self, forKey: .inputTokens) ?? 0
        outputTokens = try container.decodeIfPresent(Int.self, forKey: .outputTokens) ?? 0
        cacheReadTokens = try container.decodeIfPresent(Int.self, forKey: .cacheReadTokens) ?? 0
        costUsd = try container.decodeIfPresent(Double.self, forKey: .costUsd) ?? 0
        valueGeneratedUsd = try container.decodeIfPresent(Double.self, forKey: .valueGeneratedUsd) ?? 0
        valueIsEstimated = try container.decodeIfPresent(Bool.self, forKey: .valueIsEstimated) ?? false
        durationMs = try container.decodeIfPresent(Int.self, forKey: .durationMs)
        toolsUsed = try container.decodeIfPresent([String].self, forKey: .toolsUsed)
        filesModified = try container.decodeIfPresent([String].self, forKey: .filesModified)
        errorMessage = try container.decodeIfPresent(String.self, forKey: .errorMessage)
        tags = try container.decodeIfPresent([String].self, forKey: .tags)

        // Parse dates with flexible formats
        if let startedAtString = try container.decodeIfPresent(String.self, forKey: .startedAt) {
            startedAt = CCRun.parseDate(startedAtString) ?? Date()
        } else {
            startedAt = Date()
        }

        if let completedAtString = try container.decodeIfPresent(String.self, forKey: .completedAt) {
            completedAt = CCRun.parseDate(completedAtString)
        } else {
            completedAt = nil
        }
    }

    private static func parseDate(_ string: String) -> Date? {
        let formatters: [DateFormatter] = {
            let iso = DateFormatter()
            iso.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSSSS"
            iso.locale = Locale(identifier: "en_US_POSIX")

            let isoShort = DateFormatter()
            isoShort.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
            isoShort.locale = Locale(identifier: "en_US_POSIX")

            let space = DateFormatter()
            space.dateFormat = "yyyy-MM-dd HH:mm:ss"
            space.locale = Locale(identifier: "en_US_POSIX")

            return [iso, isoShort, space]
        }()

        for formatter in formatters {
            if let date = formatter.date(from: string) {
                return date
            }
        }
        return nil
    }
}

enum RunStatus: String, Codable {
    case pending
    case running
    case completed
    case failed
    case halted

    var color: String {
        switch self {
        case .pending: return "orange"
        case .running: return "blue"
        case .completed: return "green"
        case .failed: return "red"
        case .halted: return "gray"
        }
    }
}

// MARK: - Budget Config

struct BudgetConfig: Equatable {
    let dailyLimitUsd: Double
    let monthlyLimitUsd: Double
    let maxTokensPerRun: Int
    let maxCostPerRunUsd: Double
    let alertThresholdPct: Double
    let isActive: Bool
    let currentDailyUsage: Double?
    let currentMonthlyUsage: Double?

    var dailyUsagePercent: Double {
        guard dailyLimitUsd > 0, let usage = currentDailyUsage else { return 0 }
        return (usage / dailyLimitUsd) * 100
    }

    var monthlyUsagePercent: Double {
        guard monthlyLimitUsd > 0, let usage = currentMonthlyUsage else { return 0 }
        return (usage / monthlyLimitUsd) * 100
    }
}

extension BudgetConfig: Decodable {
    enum CodingKeys: String, CodingKey {
        case dailyLimitUsd = "daily_limit_usd"
        case monthlyLimitUsd = "monthly_limit_usd"
        case maxTokensPerRun = "max_tokens_per_run"
        case maxCostPerRunUsd = "max_cost_per_run_usd"
        case alertThresholdPct = "alert_threshold_pct"
        case isActive = "is_active"
        case currentDailyUsage = "spent_today"
        case currentMonthlyUsage = "spent_month"
    }

    init(from decoder: Decoder) throws {
        let container = try decoder.container(keyedBy: CodingKeys.self)
        dailyLimitUsd = try container.decodeIfPresent(Double.self, forKey: .dailyLimitUsd) ?? 0
        monthlyLimitUsd = try container.decodeIfPresent(Double.self, forKey: .monthlyLimitUsd) ?? 0
        maxTokensPerRun = try container.decodeIfPresent(Int.self, forKey: .maxTokensPerRun) ?? 0
        maxCostPerRunUsd = try container.decodeIfPresent(Double.self, forKey: .maxCostPerRunUsd) ?? 0
        alertThresholdPct = try container.decodeIfPresent(Double.self, forKey: .alertThresholdPct) ?? 80
        currentDailyUsage = try container.decodeIfPresent(Double.self, forKey: .currentDailyUsage)
        currentMonthlyUsage = try container.decodeIfPresent(Double.self, forKey: .currentMonthlyUsage)

        // Handle is_active as Int or Bool
        if let intValue = try? container.decode(Int.self, forKey: .isActive) {
            isActive = intValue != 0
        } else {
            isActive = try container.decodeIfPresent(Bool.self, forKey: .isActive) ?? true
        }
    }
}

// MARK: - Service Status

struct ServiceStatus: Identifiable, Equatable, Hashable {
    let id: UUID
    let name: String
    let port: Int
    let description: String
    var isRunning: Bool
    var lastChecked: Date

    var statusText: String {
        isRunning ? "Running" : "Stopped"
    }
}