-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProcessBeacon.swift
More file actions
631 lines (552 loc) · 21.3 KB
/
ProcessBeacon.swift
File metadata and controls
631 lines (552 loc) · 21.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
import SwiftUI
import AppKit
import UserNotifications
// MARK: - Models
struct ProcessInfo: Identifiable, Equatable {
let id: Int32 // PID
let name: String
let fullCommand: String
let parentPid: Int32
let cpuPercent: Double
let elapsedSeconds: Int
let isWatched: Bool
var elapsedFormatted: String { formatElapsed(elapsedSeconds) }
var shortName: String {
// Extract meaningful name from command path
let base = (fullCommand as NSString).lastPathComponent
// Trim common suffixes
if base.hasSuffix(" (Renderer)") { return String(base.dropLast(11)) }
return base
}
var category: ProcessCategory {
let cmd = fullCommand.lowercased()
if cmd.contains("cargo") || cmd.contains("rustc") || cmd.contains("swift") ||
cmd.contains("clang") || cmd.contains("gcc") || cmd.contains("make") ||
cmd.contains("xcodebuild") || cmd.contains("ninja") {
return .build
}
if cmd.contains("npm") || cmd.contains("bun") || cmd.contains("node") ||
cmd.contains("yarn") || cmd.contains("pnpm") || cmd.contains("deno") ||
cmd.contains("vite") || cmd.contains("webpack") || cmd.contains("next") {
return .node
}
if cmd.contains("python") || cmd.contains("pip") || cmd.contains("pytest") ||
cmd.contains("ruby") || cmd.contains("gem") || cmd.contains("java") ||
cmd.contains("go ") || cmd.contains("dotnet") {
return .runtime
}
if cmd.contains("docker") || cmd.contains("kubectl") || cmd.contains("terraform") ||
cmd.contains("ansible") || cmd.contains("vagrant") {
return .infra
}
if cmd.contains("git") || cmd.contains("gh ") || cmd.contains("claude") ||
cmd.contains("codex") {
return .devtool
}
if cmd.contains("test") || cmd.contains("spec") || cmd.contains("jest") ||
cmd.contains("vitest") || cmd.contains("xctest") {
return .test
}
return .other
}
}
enum ProcessCategory: String, CaseIterable {
case build = "Build"
case test = "Test"
case node = "JS/TS"
case runtime = "Runtime"
case infra = "Infra"
case devtool = "Dev Tool"
case other = "Other"
var icon: String {
switch self {
case .build: return "hammer.fill"
case .test: return "checkmark.circle.fill"
case .node: return "cube.fill"
case .runtime: return "gearshape.fill"
case .infra: return "cloud.fill"
case .devtool: return "wrench.fill"
case .other: return "circle.fill"
}
}
var color: Color {
switch self {
case .build: return .orange
case .test: return .green
case .node: return .yellow
case .runtime: return .blue
case .infra: return .purple
case .devtool: return .cyan
case .other: return .gray
}
}
}
// MARK: - Process Scanner
@Observable
class ProcessScanner {
var processes: [ProcessInfo] = []
var watchedPids: Set<Int32> = []
var completedProcesses: [(name: String, pid: Int32, date: Date)] = []
var lastScan: Date = Date()
var filterText: String = ""
private var timer: Timer?
init() {
requestNotificationPermission()
scan()
timer = Timer.scheduledTimer(withTimeInterval: 5.0, repeats: true) { [weak self] _ in
self?.scan()
}
}
deinit {
timer?.invalidate()
}
func scan() {
let pipe = Pipe()
let process = Process()
process.executableURL = URL(fileURLWithPath: "/bin/ps")
process.arguments = ["-eo", "pid,ppid,etime,pcpu,command"]
process.standardOutput = pipe
process.standardError = FileHandle.nullDevice
try? process.run()
let data = pipe.fileHandleForReading.readDataToEndOfFile()
process.waitUntilExit()
guard let output = String(data: data, encoding: .utf8) else { return }
let lines = output.components(separatedBy: "\n").dropFirst() // skip header
var scanned: [ProcessInfo] = []
for line in lines {
let trimmed = line.trimmingCharacters(in: .whitespaces)
guard !trimmed.isEmpty else { continue }
guard let parsed = parsePsLine(trimmed) else { continue }
// Filter out system processes
if shouldFilter(parsed.command) { continue }
let info = ProcessInfo(
id: parsed.pid,
name: (parsed.command as NSString).lastPathComponent,
fullCommand: parsed.command,
parentPid: parsed.ppid,
cpuPercent: parsed.cpu,
elapsedSeconds: parsed.elapsed,
isWatched: watchedPids.contains(parsed.pid)
)
scanned.append(info)
}
// Check for completed watched processes
let scannedPids = Set(scanned.map { $0.id })
let missingPids = watchedPids.subtracting(scannedPids)
for pid in missingPids {
// Find the name from previous scan
let name = processes.first { $0.id == pid }?.shortName ?? "PID \(pid)"
watchedPids.remove(pid)
completedProcesses.insert((name: name, pid: pid, date: Date()), at: 0)
if completedProcesses.count > 20 {
completedProcesses = Array(completedProcesses.prefix(20))
}
sendNotification(name: name, pid: pid)
}
// Sort: watched first, then by elapsed time descending
scanned.sort { a, b in
if a.isWatched != b.isWatched { return a.isWatched }
return a.elapsedSeconds > b.elapsedSeconds
}
processes = scanned
lastScan = Date()
}
func toggleWatch(_ pid: Int32) {
if watchedPids.contains(pid) {
watchedPids.remove(pid)
} else {
watchedPids.insert(pid)
}
// Update isWatched in the process list
processes = processes.map {
ProcessInfo(
id: $0.id, name: $0.name, fullCommand: $0.fullCommand,
parentPid: $0.parentPid, cpuPercent: $0.cpuPercent,
elapsedSeconds: $0.elapsedSeconds, isWatched: watchedPids.contains($0.id)
)
}
}
var filteredProcesses: [ProcessInfo] {
guard !filterText.isEmpty else { return processes }
let query = filterText.lowercased()
return processes.filter {
$0.shortName.lowercased().contains(query) ||
$0.fullCommand.lowercased().contains(query) ||
String($0.id).contains(query) ||
$0.category.rawValue.lowercased().contains(query)
}
}
var watchedCount: Int { watchedPids.count }
var menuBarText: String {
if watchedPids.isEmpty { return "" }
return "\(watchedPids.count)"
}
// MARK: - Parsing
private struct PsEntry {
let pid: Int32
let ppid: Int32
let elapsed: Int
let cpu: Double
let command: String
}
private func parsePsLine(_ line: String) -> PsEntry? {
// Format: " PID PPID ELAPSED %CPU COMMAND"
// Elapsed can be: "00:01", "01:23:45", "1-02:03:04"
let parts = line.split(separator: " ", maxSplits: 4, omittingEmptySubsequences: true)
guard parts.count >= 5 else { return nil }
guard let pid = Int32(parts[0]),
let ppid = Int32(parts[1]) else { return nil }
let elapsed = parseElapsed(String(parts[2]))
let cpu = Double(parts[3]) ?? 0.0
let command = String(parts[4])
return PsEntry(pid: pid, ppid: ppid, elapsed: elapsed, cpu: cpu, command: command)
}
private func shouldFilter(_ command: String) -> Bool {
let filters = [
"/System/", "/usr/libexec/", "/usr/sbin/", "/sbin/",
"/Library/Apple", "com.apple.", "kernel_task", "WindowServer",
"/Library/PrivilegedHelper", "mdworker", "mds_stores",
"launchd", "logd", "configd", "powerd", "remoted",
"watchdogd", "thermalmonitord", "fseventsd", "diskarbitrationd",
"UserEventAgent", "corespeechd", "contextstored", "xprotectd",
"kernelmanagerd", "systemstats", "syslogd", "automountd",
"autofsd", "mediaremoted", "IOMFB", "opendirectoryd",
"notifyd", "securityd", "trustd", "cloudd", "nsurlsessiond",
"lsd", "iconservicesagent", "containermanagerd",
"sandboxd", "symptomsd", "WiFiAgent", "airportd",
"bluetoothd", "coreaudiod", "hidd", "locationd",
"coreduetd", "biomed", "duetexpertd", "mediaanalysisd",
"filecoordinationd", "fileproviderd", "pkd",
"/Library/Developer/PrivateFrameworks/CoreSimulator",
"Google Chrome Helper", "Electron Helper",
"CEF Helper", "Safari Web Content",
"IMKLaunchAgent", "pboard", "secd", "cfprefsd",
"AXVisualSupportAgent", "universalaccessd", "talagent",
"Spotlight", "mds", "corespotlightd", "searchpartyd",
"ssh-agent", "gpg-agent", "cloudphotod", "photolibraryd",
"photoanalysisd", "mediaaccessibilityd", "CalendarAgent",
"remindd", "contactsd", "imagent", "identityservicesd",
"CommCenter", "parsecd", "rapportd", "sharingd",
"ctkd", "spindump", "ReportCrash", "diagnosticd",
"sysdiagnose", "amsaccountsd", "accountsd",
"ProcessBeacon", // Don't show ourselves
]
return filters.contains { command.contains($0) }
}
// MARK: - Notifications
private func requestNotificationPermission() {
let center = UNUserNotificationCenter.current()
center.requestAuthorization(options: [.alert, .sound]) { _, _ in }
}
private func sendNotification(name: String, pid: Int32) {
let center = UNUserNotificationCenter.current()
let content = UNMutableNotificationContent()
content.title = "Process Completed"
content.body = "\(name) (PID \(pid)) has finished."
content.sound = .default
let request = UNNotificationRequest(
identifier: "process-\(pid)-\(Date().timeIntervalSince1970)",
content: content,
trigger: nil
)
center.add(request)
}
}
// MARK: - Time Formatting
func parseElapsed(_ str: String) -> Int {
// Formats: "SS", "MM:SS", "HH:MM:SS", "D-HH:MM:SS"
var days = 0
var rest = str
if let dashIdx = rest.firstIndex(of: "-") {
days = Int(rest[..<dashIdx]) ?? 0
rest = String(rest[rest.index(after: dashIdx)...])
}
let parts = rest.split(separator: ":").compactMap { Int($0) }
switch parts.count {
case 1: return days * 86400 + parts[0]
case 2: return days * 86400 + parts[0] * 60 + parts[1]
case 3: return days * 86400 + parts[0] * 3600 + parts[1] * 60 + parts[2]
default: return days * 86400
}
}
func formatElapsed(_ seconds: Int) -> String {
if seconds < 60 { return "\(seconds)s" }
if seconds < 3600 {
let m = seconds / 60
let s = seconds % 60
return "\(m)m \(s)s"
}
if seconds < 86400 {
let h = seconds / 3600
let m = (seconds % 3600) / 60
return "\(h)h \(m)m"
}
let d = seconds / 86400
let h = (seconds % 86400) / 3600
return "\(d)d \(h)h"
}
// MARK: - App
@main
struct ProcessBeaconApp: App {
@State private var scanner = ProcessScanner()
var body: some Scene {
MenuBarExtra {
PopupView(scanner: scanner)
.frame(width: 380)
} label: {
HStack(spacing: 3) {
Image(systemName: scanner.watchedCount > 0 ? "antenna.radiowaves.left.and.right" : "antenna.radiowaves.left.and.right")
.font(.system(size: 11))
.symbolEffect(.variableColor.iterative, isActive: scanner.watchedCount > 0)
if !scanner.menuBarText.isEmpty {
Text(scanner.menuBarText)
.font(.system(size: 11, weight: .medium, design: .monospaced))
}
}
}
.menuBarExtraStyle(.window)
}
}
// MARK: - Popup View
struct PopupView: View {
@Bindable var scanner: ProcessScanner
var body: some View {
VStack(spacing: 0) {
header
Divider().overlay(Color.white.opacity(0.08))
// Watched section (if any)
if !scanner.watchedPids.isEmpty {
watchedSection
Divider().overlay(Color.white.opacity(0.08))
}
// Completed section (if any)
if !scanner.completedProcesses.isEmpty {
completedSection
Divider().overlay(Color.white.opacity(0.08))
}
// Search
searchBar
Divider().overlay(Color.white.opacity(0.08))
// Process list
processList
Divider().overlay(Color.white.opacity(0.08))
footer
}
.background(Color(nsColor: .windowBackgroundColor))
}
// MARK: - Header
private var header: some View {
HStack(spacing: 8) {
Image(systemName: "antenna.radiowaves.left.and.right")
.font(.system(size: 14))
.foregroundStyle(.secondary)
Text("ProcessBeacon")
.font(.system(size: 14, weight: .bold))
Spacer()
if scanner.watchedCount > 0 {
Text("\(scanner.watchedCount) watched")
.font(.system(size: 11, weight: .medium))
.foregroundStyle(.orange)
.padding(.horizontal, 6)
.padding(.vertical, 2)
.background(.orange.opacity(0.15), in: RoundedRectangle(cornerRadius: 4))
}
Button {
scanner.scan()
} label: {
Image(systemName: "arrow.clockwise")
.font(.system(size: 11))
.foregroundStyle(.secondary)
}
.buttonStyle(.borderless)
}
.padding(.horizontal, 14)
.padding(.vertical, 10)
}
// MARK: - Watched Processes
private var watchedSection: some View {
VStack(alignment: .leading, spacing: 4) {
HStack(spacing: 4) {
Image(systemName: "eye.fill")
.font(.system(size: 10))
Text("WATCHING")
.font(.system(size: 10, weight: .semibold))
Spacer()
}
.foregroundStyle(.orange)
.padding(.horizontal, 14)
.padding(.top, 8)
ForEach(scanner.processes.filter { $0.isWatched }) { proc in
ProcessRow(process: proc, scanner: scanner, compact: true)
}
}
.padding(.bottom, 4)
}
// MARK: - Completed Processes
private var completedSection: some View {
VStack(alignment: .leading, spacing: 4) {
HStack(spacing: 4) {
Image(systemName: "checkmark.circle.fill")
.font(.system(size: 10))
Text("COMPLETED")
.font(.system(size: 10, weight: .semibold))
Spacer()
Button {
scanner.completedProcesses.removeAll()
} label: {
Text("Clear")
.font(.system(size: 10))
}
.buttonStyle(.borderless)
}
.foregroundStyle(.green)
.padding(.horizontal, 14)
.padding(.top, 8)
ForEach(scanner.completedProcesses.indices, id: \.self) { idx in
let entry = scanner.completedProcesses[idx]
HStack(spacing: 6) {
Image(systemName: "checkmark.circle.fill")
.font(.system(size: 11))
.foregroundStyle(.green)
Text(entry.name)
.font(.system(size: 12, weight: .medium))
.lineLimit(1)
Spacer()
Text(entry.date, style: .relative)
.font(.system(size: 10))
.foregroundStyle(.tertiary)
}
.padding(.horizontal, 14)
.padding(.vertical, 3)
}
}
.padding(.bottom, 4)
}
// MARK: - Search
private var searchBar: some View {
HStack(spacing: 6) {
Image(systemName: "magnifyingglass")
.font(.system(size: 11))
.foregroundStyle(.tertiary)
TextField("Filter by name, PID, or category...", text: $scanner.filterText)
.textFieldStyle(.plain)
.font(.system(size: 12))
}
.padding(.horizontal, 14)
.padding(.vertical, 6)
}
// MARK: - Process List
private var processList: some View {
ScrollView {
LazyVStack(spacing: 1) {
let visible = scanner.filteredProcesses.filter { !$0.isWatched }
if visible.isEmpty {
VStack(spacing: 6) {
Image(systemName: "tray")
.font(.system(size: 24))
.foregroundStyle(.tertiary)
Text(scanner.filterText.isEmpty ? "No user processes" : "No matches")
.font(.system(size: 12))
.foregroundStyle(.secondary)
}
.frame(maxWidth: .infinity)
.padding(.vertical, 20)
} else {
ForEach(visible) { proc in
ProcessRow(process: proc, scanner: scanner, compact: false)
}
}
}
.padding(.vertical, 4)
}
.frame(maxHeight: 320)
}
// MARK: - Footer
private var footer: some View {
HStack(spacing: 8) {
Text("\(scanner.processes.count) processes")
.font(.system(size: 11))
.foregroundStyle(.secondary)
Spacer()
Text("Updated \(scanner.lastScan, style: .relative) ago")
.font(.system(size: 10))
.foregroundStyle(.tertiary)
Divider().frame(height: 10)
Button("Quit") {
NSApplication.shared.terminate(nil)
}
.font(.system(size: 11))
.buttonStyle(.borderless)
.foregroundStyle(.secondary)
}
.padding(.horizontal, 14)
.padding(.vertical, 8)
}
}
// MARK: - Process Row
struct ProcessRow: View {
let process: ProcessInfo
let scanner: ProcessScanner
let compact: Bool
@State private var isHovered = false
var body: some View {
HStack(spacing: 8) {
// Category icon
Image(systemName: process.category.icon)
.font(.system(size: 11))
.foregroundStyle(process.category.color)
.frame(width: 16)
// Name + details
VStack(alignment: .leading, spacing: 1) {
HStack(spacing: 4) {
Text(process.shortName)
.font(.system(size: 12, weight: process.isWatched ? .bold : .medium))
.lineLimit(1)
if process.cpuPercent > 5 {
Text(String(format: "%.0f%%", process.cpuPercent))
.font(.system(size: 9, weight: .bold, design: .monospaced))
.foregroundStyle(.red)
.padding(.horizontal, 3)
.padding(.vertical, 1)
.background(.red.opacity(0.15), in: RoundedRectangle(cornerRadius: 3))
}
}
HStack(spacing: 6) {
Text("PID \(process.id)")
.foregroundStyle(.tertiary)
Text(process.elapsedFormatted)
.foregroundStyle(process.isWatched ? .orange : .secondary)
Text(process.category.rawValue)
.foregroundStyle(process.category.color.opacity(0.6))
}
.font(.system(size: 10))
if isHovered {
Text(process.fullCommand)
.font(.system(size: 9, design: .monospaced))
.foregroundStyle(.tertiary)
.lineLimit(2)
}
}
Spacer()
// Watch toggle
Button {
scanner.toggleWatch(process.id)
} label: {
Image(systemName: process.isWatched ? "eye.fill" : "eye")
.font(.system(size: 12))
.foregroundStyle(process.isWatched ? .orange : .secondary.opacity(isHovered ? 1 : 0.3))
}
.buttonStyle(.borderless)
}
.padding(.horizontal, 14)
.padding(.vertical, 5)
.background(
process.isWatched ? Color.orange.opacity(0.06) :
isHovered ? Color.primary.opacity(0.04) : .clear,
in: RoundedRectangle(cornerRadius: 6)
)
.padding(.horizontal, 4)
.contentShape(Rectangle())
.onHover { isHovered = $0 }
}
}