SPB Git

Repository Public

MissionControlView.swift 9.9 KB 199 lines swift

1import SwiftUI2import ClaudeIntegration3import TerminalCore4import WorkspaceCore56/// Dashboard of every session. "Verified" facts come from the PTY/kernel or Claude hooks;7/// "heuristic" ones (last output time) are labelled as such. Status is conveyed by glyph + text.8struct MissionControlView: View {9    @Environment(WorkspaceController.self) private var controller10    @State private var search = ""11    @State private var kindFilter: KindFilter = .all12    @State private var attentionOnly = false13    @State private var grouping: Grouping = .project1415    enum KindFilter: String, CaseIterable, Identifiable { case all, claude, remote, local; var id: String { rawValue } }16    enum Grouping: String, CaseIterable, Identifiable { case project, host, none; var id: String { rawValue } }1718    struct Row: Identifiable {19        let id: PaneID20        let session: TerminalSession21        let claude: ClaudeSessionInfo?22        let hostLabel: String23        let project: String24        let needsAttention: Bool25    }2627    var body: some View {28        VStack(spacing: 0) {29            toolbar30            Divider()31            if rows.isEmpty && externalClaudeSessions.isEmpty {32                ContentUnavailableView("No sessions", systemImage: "rectangle.3.group", description: Text("Open a terminal or start a Claude session."))33            } else {34                List {35                    ForEach(groups, id: \.title) { group in36                        Section(group.title) {37                            ForEach(group.rows) { row in rowView(row) }38                        }39                    }40                    if !externalClaudeSessions.isEmpty, kindFilter == .all || kindFilter == .claude {41                        Section("Claude sessions reporting hooks but not running in a NEXTERM pane") {42                            ForEach(externalClaudeSessions) { info in43                                HStack {44                                    Text(info.status.rawValue).font(.system(size: 11, weight: .medium)).frame(width: 150, alignment: .leading)45                                    VStack(alignment: .leading) {46                                        Text(info.projectDirectory.map(TerminalSession.abbreviate) ?? info.sessionID).font(.system(size: 12))47                                        Text(info.lastEvent ?? "").font(.system(size: 11)).foregroundStyle(.secondary).lineLimit(1)48                                    }49                                    Spacer()50                                    Text(info.lastEventAt.map { "hook \(relative($0)) · verified" } ?? "").font(.system(size: 10)).foregroundStyle(.secondary)51                                }52                            }53                        }54                    }55                }56                .listStyle(.inset)57            }58            Divider()59            footer60        }61        .frame(minWidth: 760, minHeight: 420)62    }6364    private var toolbar: some View {65        HStack(spacing: 12) {66            TextField("Search sessions, projects, hosts", text: $search).textFieldStyle(.roundedBorder).frame(maxWidth: 320)67            Picker("Kind", selection: $kindFilter) { ForEach(KindFilter.allCases) { Text($0.rawValue.capitalized).tag($0) } }.pickerStyle(.segmented).labelsHidden().frame(width: 260)68            Toggle("Needs attention", isOn: $attentionOnly).toggleStyle(.checkbox)69            Spacer()70            Picker("Group by", selection: $grouping) { ForEach(Grouping.allCases) { Text($0.rawValue.capitalized).tag($0) } }.frame(width: 160)71        }72        .padding(10)73    }7475    private var footer: some View {76        let claude = controller.claude77        return HStack(spacing: 14) {78            Label(claude.cli.map { "Claude Code \($0.version ?? "")" } ?? "Claude Code not found", systemImage: claude.cli == nil ? "exclamationmark.triangle" : "checkmark.circle")79            Label(claude.hooksActive ? "Hooks: active (\(claude.hookServerURL ?? ""))" : "Hooks: off (Settings ▸ Claude)", systemImage: claude.hooksActive ? "bolt.fill" : "bolt.slash")80            Spacer()81            Text("\(controller.registry.liveCount) live · \(controller.allSessions.count) total")82        }83        .font(.system(size: 11))84        .foregroundStyle(.secondary)85        .padding(.horizontal, 10).padding(.vertical, 6)86    }8788    private var rows: [Row] {89        var result: [Row] = []90        for (paneID, pane) in controller.workspace.panes {91            guard let session = controller.registry.session(pane.sessionID) else { continue }92            var claudeInfo: ClaudeSessionInfo?93            if case .claude(let id, _) = pane.profile.kind { claudeInfo = controller.claude.tracker.session(id.uuidString.lowercased()) }94            let host: String95            if case .ssh(let hostID, _) = pane.profile.kind { host = controller.hosts[hostID]?.displayName ?? "remote" } else { host = LocalHost.shortName }96            let project = (claudeInfo?.projectDirectory ?? session.currentDirectory ?? session.profile.workingDirectory).map(TerminalSession.abbreviate) ?? "—"97            let attention: Bool = {98                if let c = claudeInfo { return c.status == .waitingForPermission || c.status == .waitingForInput }99                return !session.status.isAlive100            }()101            let row = Row(id: paneID, session: session, claude: claudeInfo, hostLabel: host, project: project, needsAttention: attention)102            switch kindFilter {103            case .claude: guard case .claude = pane.profile.kind else { continue }104            case .remote: guard pane.profile.kind.isRemote else { continue }105            case .local: if pane.profile.kind.isRemote { continue }; if case .claude = pane.profile.kind { continue }106            case .all: break107            }108            if attentionOnly, !row.needsAttention { continue }109            if !search.isEmpty {110                let hay = [session.displayTitle, project, host, session.label ?? "", claudeInfo?.lastEvent ?? ""].joined(separator: " ").lowercased()111                guard hay.contains(search.lowercased()) else { continue }112            }113            result.append(row)114        }115        return result.sorted { ($0.needsAttention ? 0 : 1, $0.session.createdAt) < ($1.needsAttention ? 0 : 1, $1.session.createdAt) }116    }117118    /// Hook-reporting sessions with no pane (e.g. launched from another terminal with NEXTERM's settings file).119    private var externalClaudeSessions: [ClaudeSessionInfo] {120        controller.claude.tracker.orderedSessions.filter { controller.pane(forClaudeSession: $0.sessionID) == nil && $0.status != .ended }121    }122123    private var groups: [(title: String, rows: [Row])] {124        switch grouping {125        case .none: return [("All sessions", rows)]126        case .project: return Dictionary(grouping: rows, by: \.project).sorted { $0.key < $1.key }.map { ($0.key, $0.value) }127        case .host: return Dictionary(grouping: rows, by: \.hostLabel).sorted { $0.key < $1.key }.map { ($0.key, $0.value) }128        }129    }130131    @ViewBuilder132    private func rowView(_ row: Row) -> some View {133        HStack(spacing: 10) {134            statusBadge(row)135                .frame(width: 150, alignment: .leading)136            VStack(alignment: .leading, spacing: 2) {137                Text(row.session.displayTitle).font(.system(size: 12, weight: .medium)).lineLimit(1)138                Text(detail(row)).font(.system(size: 11)).foregroundStyle(.secondary).lineLimit(1)139            }140            Spacer()141            VStack(alignment: .trailing, spacing: 2) {142                Text(row.hostLabel).font(.system(size: 11))143                Text(activity(row)).font(.system(size: 10)).foregroundStyle(.secondary)144            }145            Button("Go") { controller.reveal(pane: row.id) }.buttonStyle(.bordered).controlSize(.small)146                .accessibilityLabel("Go to pane \(row.session.displayTitle)")147        }148        .padding(.vertical, 2)149        .contentShape(Rectangle())150        .onTapGesture(count: 2) { controller.reveal(pane: row.id) }151    }152153    private func statusBadge(_ row: Row) -> some View {154        let (symbol, text, verified): (String, String, Bool) = {155            if let c = row.claude {156                switch c.status {157                case .waitingForPermission: return ("hand.raised.fill", "Permission needed", true)158                case .waitingForInput: return ("text.cursor", "Waiting for you", true)159                case .working: return ("gearshape.2.fill", "Working", true)160                case .idle: return ("checkmark.circle", "Idle", true)161                case .ended: return ("stop.circle", "Ended", true)162                case .starting: return ("circle.dotted", "Starting", true)163                }164            }165            if !row.session.status.isAlive { return ("stop.circle", row.session.status.label, true) }166            if let program = row.session.foregroundProgram { return ("play.circle.fill", "Running \(program)", true) }167            return ("circle.fill", "Shell idle", true)168        }()169        return HStack(spacing: 5) {170            Image(systemName: symbol).font(.system(size: 11)).accessibilityHidden(true)171            Text(text).font(.system(size: 11, weight: .medium)).lineLimit(1)172            if !verified { Text("~").help("Heuristic estimate") }173        }174        .accessibilityLabel("Status: \(text)")175    }176177    private func detail(_ row: Row) -> String {178        if let c = row.claude {179            if let p = c.pendingPermission { return "Wants to run \(p.tool): \(p.input)" }180            return c.lastEvent ?? row.project181        }182        return row.project183    }184185    private func activity(_ row: Row) -> String {186        if let at = row.claude?.lastEventAt { return "hook \(relative(at)) · verified" }187        if let at = row.session.lastOutputAt { return "output \(relative(at)) · heuristic" }188        return "no activity yet"189    }190191    private func relative(_ date: Date) -> String {192        let s = Int(Date().timeIntervalSince(date))193        if s < 5 { return "just now" }194        if s < 60 { return "\(s)s ago" }195        if s < 3600 { return "\(s / 60)m ago" }196        return "\(s / 3600)h ago"197    }198}199
Files main
Menu

Theme