-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathDeveloperDebugView.swift
More file actions
1207 lines (1101 loc) · 44.8 KB
/
Copy pathDeveloperDebugView.swift
File metadata and controls
1207 lines (1101 loc) · 44.8 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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Foundation
import SwiftUI
#if os(macOS)
import AppKit
#endif
enum DeveloperDebugMode {
static let environmentKey = "SMITHERS_GUI_DEBUG"
private static let enableArguments = ["--developer-debug", "--dev-debug", "--debug-mode"]
private static let disableArguments = ["--no-developer-debug", "--no-dev-debug"]
private static let truthyValues = ["1", "true", "yes", "on", "enabled"]
private static let falseyValues = ["0", "false", "no", "off", "disabled"]
static var isEnabled: Bool {
isEnabled(
environment: ProcessInfo.processInfo.environment,
arguments: ProcessInfo.processInfo.arguments,
isDebugBuild: _isDebugAssertConfiguration()
)
}
static func isEnabled(
environment: [String: String],
arguments: [String],
isDebugBuild: Bool
) -> Bool {
if arguments.contains(where: { disableArguments.contains($0) }) {
return false
}
if let rawValue = environment[environmentKey] {
let normalized = rawValue.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
if truthyValues.contains(normalized) { return true }
if falseyValues.contains(normalized) { return false }
}
if arguments.contains(where: { enableArguments.contains($0) }) {
return true
}
return isDebugBuild
}
}
enum DeveloperDebugTone: Equatable {
case normal
case good
case warning
case danger
var color: Color {
switch self {
case .normal: return Theme.textSecondary
case .good: return Theme.success
case .warning: return Theme.warning
case .danger: return Theme.danger
}
}
}
struct DeveloperDebugStateRow: Identifiable, Equatable {
let id: String
let label: String
let value: String
let tone: DeveloperDebugTone
init(label: String, value: String, tone: DeveloperDebugTone = .normal) {
self.id = label
self.label = label
self.value = value
self.tone = tone
}
}
struct DeveloperDebugSessionSummary: Identifiable, Equatable {
let id: String
let title: String
let preview: String
let isActive: Bool
let isRunning: Bool
let messageCount: Int
let model: String
}
struct DeveloperDebugRunTabSummary: Identifiable, Equatable {
let id: String
let title: String
let preview: String
}
struct DeveloperDebugMessageSummary: Identifiable, Equatable {
let id: String
let type: String
let timestamp: String
let preview: String
}
struct DeveloperDebugSnapshot: Equatable {
let capturedAt: Date
let destinationLabel: String
let destinationDetails: String
let appRows: [DeveloperDebugStateRow]
let sessionRows: [DeveloperDebugStateRow]
let logRows: [DeveloperDebugStateRow]
let sessions: [DeveloperDebugSessionSummary]
let runTabs: [DeveloperDebugRunTabSummary]
let recentMessages: [DeveloperDebugMessageSummary]
@MainActor
static func capture(
store: SessionStore,
smithers: SmithersClient,
destination: NavDestination,
logStats: LogFileStats?,
now: Date = Date()
) -> DeveloperDebugSnapshot {
let appRows = [
DeveloperDebugStateRow(label: "Destination", value: destination.label),
DeveloperDebugStateRow(label: "Route", value: destination.debugRouteDescription),
DeveloperDebugStateRow(
label: "Smithers CLI",
value: smithers.cliAvailable ? "available" : "missing",
tone: smithers.cliAvailable ? .good : .warning
),
DeveloperDebugStateRow(
label: "Smithers connection",
value: smithers.isConnected ? "connected" : "offline",
tone: smithers.isConnected ? .good : .warning
),
DeveloperDebugStateRow(label: "Smithers transport", value: smithers.connectionTransport.rawValue),
DeveloperDebugStateRow(
label: "Server reachable",
value: smithers.serverReachable ? "yes" : "no",
tone: smithers.serverReachable ? .good : .normal
),
DeveloperDebugStateRow(label: "Working directory", value: smithers.workingDirectory),
DeveloperDebugStateRow(label: "Server URL", value: smithers.serverURL?.nilIfBlank ?? "not configured"),
DeveloperDebugStateRow(
label: "Debug gate",
value: DeveloperDebugMode.isEnabled ? "enabled" : "disabled",
tone: DeveloperDebugMode.isEnabled ? .good : .warning
),
]
let sessionRows = [
DeveloperDebugStateRow(label: "Run tabs", value: "\(store.runTabs.count)"),
DeveloperDebugStateRow(label: "Terminal tabs", value: "\(store.terminalTabs.count)"),
]
let logRows = [
DeveloperDebugStateRow(label: "Log file", value: logStats?.fileURL.path ?? "loading"),
DeveloperDebugStateRow(label: "Entries", value: logStats.map { "\($0.entryCount)" } ?? "loading"),
DeveloperDebugStateRow(label: "Size", value: logStats.map { formattedBytes($0.sizeBytes) } ?? "loading"),
DeveloperDebugStateRow(
label: "Dropped writes",
value: logStats.map { "\($0.droppedWriteCount)" } ?? "loading",
tone: (logStats?.droppedWriteCount ?? 0) > 0 ? .danger : .normal
),
DeveloperDebugStateRow(
label: "Last write error",
value: logStats?.lastWriteError?.nilIfBlank ?? "none",
tone: logStats?.lastWriteError == nil ? .normal : .danger
),
]
let sessions: [DeveloperDebugSessionSummary] = []
let runTabs = store.runTabs.map { tab in
DeveloperDebugRunTabSummary(
id: tab.runId,
title: tab.title.nilIfBlank ?? "Run \(idPrefix(tab.runId))",
preview: trimmedPreview(tab.preview, limit: 140)
)
}
let recentMessages: [DeveloperDebugMessageSummary] = []
return DeveloperDebugSnapshot(
capturedAt: now,
destinationLabel: destination.label,
destinationDetails: destination.debugRouteDescription,
appRows: appRows,
sessionRows: sessionRows,
logRows: logRows,
sessions: sessions,
runTabs: runTabs,
recentMessages: recentMessages
)
}
private static func idPrefix(_ value: String) -> String {
String(value.prefix(8))
}
private static func trimmedPreview(_ value: String, limit: Int) -> String {
let normalized = value
.replacingOccurrences(of: "\n", with: " ")
.replacingOccurrences(of: "\r", with: " ")
.trimmingCharacters(in: .whitespacesAndNewlines)
guard !normalized.isEmpty else { return "empty" }
guard normalized.count > limit else { return normalized }
return "\(String(normalized.prefix(limit)))..."
}
private static func formattedBytes(_ bytes: Int) -> String {
if bytes < 1024 { return "\(bytes) B" }
if bytes < 1_048_576 { return "\(bytes / 1024) KB" }
return String(format: "%.1f MB", Double(bytes) / 1_048_576.0)
}
}
private enum DeveloperDebugTab: String, CaseIterable, Identifiable {
case state = "State"
case telemetry = "Metrics"
case events = "Events"
case logs = "Logs"
case actions = "Actions"
var id: String { rawValue }
}
@MainActor
struct DeveloperDebugPanel: View {
@ObservedObject var store: SessionStore
@ObservedObject var smithers: SmithersClient
@ObservedObject private var telemetry = DevTelemetryStore.shared
let destination: NavDestination
let onClose: () -> Void
let onOpenLogs: () -> Void
@State private var selectedTab: DeveloperDebugTab = .state
@State private var logStats: LogFileStats?
@State private var logEntries: [LogEntry] = []
@State private var logLevelFilter: LogLevel?
@State private var logSearchText = ""
@State private var eventLevelFilter: LogLevel?
@State private var eventSearchText = ""
@State private var autoRefresh = true
@State private var refreshTimer: Timer?
@State private var actionFeedback: String?
private var snapshot: DeveloperDebugSnapshot {
DeveloperDebugSnapshot.capture(
store: store,
smithers: smithers,
destination: destination,
logStats: logStats
)
}
private var filteredLogEntries: [LogEntry] {
logEntries.filter { entry in
if let logLevelFilter, entry.level != logLevelFilter { return false }
let query = logSearchText.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
guard !query.isEmpty else { return true }
return entry.message.lowercased().contains(query) ||
entry.category.rawValue.lowercased().contains(query) ||
entry.level.rawValue.lowercased().contains(query) ||
(entry.formattedMetadata?.lowercased().contains(query) ?? false)
}
}
var body: some View {
VStack(spacing: 0) {
header
Picker("Debug View", selection: $selectedTab) {
ForEach(DeveloperDebugTab.allCases) { tab in
Text(tab.rawValue).tag(tab)
}
}
.pickerStyle(.segmented)
.padding(12)
.accessibilityIdentifier("developerDebug.tabPicker")
Divider()
.overlay(Theme.border)
Group {
switch selectedTab {
case .state:
stateTab(snapshot)
case .telemetry:
telemetryTab()
case .events:
eventsTab()
case .logs:
logsTab(snapshot)
case .actions:
actionsTab()
}
}
}
.frame(minWidth: 420, idealWidth: 480, maxWidth: 640, maxHeight: .infinity)
.background(Theme.surface1)
.border(Theme.border, edges: [.leading])
.task { await refreshDiagnostics() }
.onAppear {
startAutoRefresh()
telemetry.start()
}
.onDisappear {
stopAutoRefresh()
telemetry.stop()
}
.onChange(of: autoRefresh) { _, newValue in
if newValue { startAutoRefresh() } else { stopAutoRefresh() }
}
.accessibilityIdentifier("developerDebug.panel")
}
private var header: some View {
HStack(spacing: 8) {
Image(systemName: "wrench.and.screwdriver")
.foregroundColor(Theme.accent)
VStack(alignment: .leading, spacing: 2) {
Text("Developer Debug")
.font(.system(size: 14, weight: .semibold))
.foregroundColor(Theme.textPrimary)
Text(snapshot.destinationDetails)
.font(.system(size: 10, design: .monospaced))
.foregroundColor(Theme.textTertiary)
.lineLimit(1)
}
Spacer()
Toggle("Auto", isOn: $autoRefresh)
.toggleStyle(.switch)
.controlSize(.small)
.labelsHidden()
.help("Auto refresh diagnostics")
.accessibilityIdentifier("developerDebug.autoRefresh")
Button {
Task { await refreshDiagnostics() }
} label: {
Image(systemName: "arrow.clockwise")
}
.buttonStyle(.plain)
.help("Refresh diagnostics")
.accessibilityIdentifier("developerDebug.refresh")
Button(action: onClose) {
Image(systemName: "xmark")
}
.buttonStyle(.plain)
.help("Close developer debug")
.accessibilityIdentifier("developerDebug.close")
}
.padding(.horizontal, 12)
.frame(height: 44)
.background(Theme.titlebarBg)
.border(Theme.border, edges: [.bottom])
}
private func stateTab(_ snapshot: DeveloperDebugSnapshot) -> some View {
ScrollView {
VStack(alignment: .leading, spacing: 12) {
DeveloperDebugSection(title: "Runtime") {
DeveloperDebugRows(rows: snapshot.appRows)
}
DeveloperDebugSection(title: "Store") {
DeveloperDebugRows(rows: snapshot.sessionRows)
}
DeveloperDebugSection(title: "Sessions") {
if snapshot.sessions.isEmpty {
DeveloperDebugEmptyRow(text: "No sessions")
} else {
VStack(spacing: 8) {
ForEach(snapshot.sessions) { session in
DeveloperDebugSessionRow(session: session)
}
}
}
}
DeveloperDebugSection(title: "Run Tabs") {
if snapshot.runTabs.isEmpty {
DeveloperDebugEmptyRow(text: "No run tabs")
} else {
VStack(spacing: 8) {
ForEach(snapshot.runTabs) { tab in
DeveloperDebugRunTabRow(tab: tab)
}
}
}
}
DeveloperDebugSection(title: "Recent Messages") {
if snapshot.recentMessages.isEmpty {
DeveloperDebugEmptyRow(text: "No active messages")
} else {
VStack(spacing: 8) {
ForEach(snapshot.recentMessages) { message in
DeveloperDebugMessageRow(message: message)
}
}
}
}
DeveloperDebugSection(title: "Libsmithers obs") {
DeveloperDebugRows(rows: telemetryStateRows())
}
}
.padding(12)
}
}
private func telemetryStateRows() -> [DeveloperDebugStateRow] {
let snap = telemetry.snapshot
let topMethods = snap.methods
.sorted { $0.count > $1.count }
.prefix(3)
.map { "\($0.key.suffix(28)) n=\($0.count) avg=\(Int($0.avgMs))ms" }
.joined(separator: "; ")
let topLine = topMethods.isEmpty ? "no calls yet" : topMethods
let totalErrors = snap.methods.reduce(0) { $0 + $1.errors }
return [
DeveloperDebugStateRow(label: "Polling", value: telemetry.isPolling ? "on" : "off",
tone: telemetry.isPolling ? .good : .warning),
DeveloperDebugStateRow(label: "Total events", value: "\(snap.totalEventSeq)"),
DeveloperDebugStateRow(label: "Dropped", value: "\(snap.droppedEvents)",
tone: snap.droppedEvents > 0 ? .warning : .normal),
DeveloperDebugStateRow(label: "Tracked methods", value: "\(snap.methods.count)"),
DeveloperDebugStateRow(label: "Method errors", value: "\(totalErrors)",
tone: totalErrors > 0 ? .danger : .normal),
DeveloperDebugStateRow(label: "Top methods", value: topLine),
]
}
private func logsTab(_ snapshot: DeveloperDebugSnapshot) -> some View {
VStack(spacing: 0) {
VStack(spacing: 10) {
DeveloperDebugRows(rows: snapshot.logRows)
HStack(spacing: 8) {
Picker("Level", selection: $logLevelFilter) {
Text("All").tag(LogLevel?.none)
ForEach(LogLevel.allCases, id: \.self) { level in
Text(level.rawValue.capitalized).tag(LogLevel?.some(level))
}
}
.frame(width: 110)
.accessibilityIdentifier("developerDebug.logs.levelFilter")
TextField("Search logs", text: $logSearchText)
.textFieldStyle(.roundedBorder)
.accessibilityIdentifier("developerDebug.logs.search")
Button(action: onOpenLogs) {
Image(systemName: "arrow.up.right.square")
}
.help("Open full log viewer")
.accessibilityIdentifier("developerDebug.logs.openFull")
}
}
.padding(12)
Divider()
.overlay(Theme.border)
if filteredLogEntries.isEmpty {
VStack(spacing: 10) {
Image(systemName: "doc.text.magnifyingglass")
.font(.system(size: 24))
.foregroundColor(Theme.textTertiary)
Text(logEntries.isEmpty ? "No log entries yet" : "No entries match filters")
.font(.system(size: 12))
.foregroundColor(Theme.textTertiary)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
} else {
ScrollViewReader { proxy in
ScrollView {
LazyVStack(alignment: .leading, spacing: 6) {
ForEach(filteredLogEntries) { entry in
DeveloperLogEntryRow(entry: entry)
.id(entry.id)
}
}
.padding(10)
}
.onChange(of: logEntries.count) { _, _ in
if let last = filteredLogEntries.last {
proxy.scrollTo(last.id, anchor: .bottom)
}
}
}
}
}
}
private func telemetryTab() -> some View {
let snap = telemetry.snapshot
return ScrollView {
VStack(alignment: .leading, spacing: 12) {
DeveloperDebugSection(title: "Runtime") {
DeveloperDebugRows(rows: telemetryRuntimeRows(snap))
}
DeveloperDebugSection(title: "Counters") {
if snap.counters.isEmpty {
DeveloperDebugEmptyRow(text: "No counters recorded yet")
} else {
DeveloperDebugRows(rows: snap.counters.map {
DeveloperDebugStateRow(label: $0.0, value: "\($0.1)")
})
}
}
DeveloperDebugSection(title: "Method latency") {
if snap.methods.isEmpty {
DeveloperDebugEmptyRow(text: "No method calls observed yet")
} else {
VStack(spacing: 6) {
ForEach(snap.methods) { method in
DeveloperMethodLatencyRow(method: method)
}
}
}
}
if let err = telemetry.lastPollError {
DeveloperDebugSection(title: "Telemetry health") {
DeveloperDebugRows(rows: [
DeveloperDebugStateRow(label: "Last poll error", value: err, tone: .danger)
])
}
}
}
.padding(12)
}
.accessibilityIdentifier("developerDebug.telemetry.scroll")
}
private func telemetryRuntimeRows(_ snap: DevTelemetrySnapshot) -> [DeveloperDebugStateRow] {
let uptime = max(0, snap.nowMs - snap.startedAtMs)
return [
DeveloperDebugStateRow(label: "Polling", value: telemetry.isPolling ? "on (2s)" : "off",
tone: telemetry.isPolling ? .good : .warning),
DeveloperDebugStateRow(label: "Uptime", value: "\(uptime / 1000)s"),
DeveloperDebugStateRow(label: "Events emitted", value: "\(snap.totalEventSeq)"),
DeveloperDebugStateRow(label: "Events dropped",
value: "\(snap.droppedEvents)",
tone: snap.droppedEvents > 0 ? .warning : .normal),
DeveloperDebugStateRow(label: "Ring capacity", value: "\(snap.ringCapacity)"),
DeveloperDebugStateRow(label: "Min level (Zig)", value: levelName(snap.minLevel)),
DeveloperDebugStateRow(label: "UI buffer", value: "\(telemetry.events.count)/1000"),
]
}
private func levelName(_ raw: Int) -> String {
switch raw {
case 0: return "trace"
case 1: return "debug"
case 2: return "info"
case 3: return "warn"
default: return "error"
}
}
private var filteredTelemetryEvents: [DevTelemetryEvent] {
let query = eventSearchText.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
return telemetry.events.reversed().filter { event in
if let eventLevelFilter, event.level != eventLevelFilter { return false }
guard !query.isEmpty else { return true }
return event.subsystem.lowercased().contains(query)
|| event.name.lowercased().contains(query)
|| (event.fieldsJSON?.lowercased().contains(query) ?? false)
}
}
private func eventsTab() -> some View {
VStack(spacing: 0) {
HStack(spacing: 8) {
Picker("Level", selection: $eventLevelFilter) {
Text("All").tag(LogLevel?.none)
ForEach(LogLevel.allCases, id: \.self) { level in
Text(level.rawValue.capitalized).tag(LogLevel?.some(level))
}
}
.frame(width: 110)
.accessibilityIdentifier("developerDebug.events.levelFilter")
TextField("Filter events", text: $eventSearchText)
.textFieldStyle(.roundedBorder)
.accessibilityIdentifier("developerDebug.events.search")
Button {
telemetry.poll()
} label: {
Image(systemName: "arrow.clockwise")
}
.buttonStyle(.plain)
.help("Force telemetry poll")
Button {
telemetry.clearLocalBuffer()
} label: {
Image(systemName: "trash")
}
.buttonStyle(.plain)
.help("Clear local event buffer")
.accessibilityIdentifier("developerDebug.events.clear")
}
.padding(12)
Divider().overlay(Theme.border)
let visible = filteredTelemetryEvents
if visible.isEmpty {
VStack(spacing: 10) {
Image(systemName: "waveform.path")
.font(.system(size: 24))
.foregroundColor(Theme.textTertiary)
Text(telemetry.events.isEmpty ? "No events yet — interact with the app" : "No events match filters")
.font(.system(size: 12))
.foregroundColor(Theme.textTertiary)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
} else {
ScrollView {
LazyVStack(alignment: .leading, spacing: 4) {
ForEach(visible) { event in
DeveloperTelemetryEventRow(event: event)
}
}
.padding(10)
}
}
}
}
private func actionsTab() -> some View {
ScrollView {
VStack(alignment: .leading, spacing: 16) {
DeveloperDebugSection(title: "Telemetry") {
VStack(alignment: .leading, spacing: 6) {
actionButton(title: "Force poll now", system: "arrow.clockwise") {
telemetry.poll()
actionFeedback = "Polled libsmithers obs ring"
}
actionButton(title: "Clear local event buffer", system: "trash") {
telemetry.clearLocalBuffer()
actionFeedback = "Cleared \(telemetry.events.count) events"
}
actionButton(title: "Emit test event", system: "bolt") {
DevTelemetryRecorder.emit(
level: .info,
subsystem: "swift.devtools",
name: "user_test_event",
fields: ["source": "DeveloperDebugPanel"]
)
actionFeedback = "Emitted swift.devtools.user_test_event"
}
actionButton(title: "Increment test counter", system: "plus.circle") {
DevTelemetryRecorder.incrementCounter("test.dev_panel.clicks")
actionFeedback = "test.dev_panel.clicks++"
}
}
}
DeveloperDebugSection(title: "Levels") {
VStack(alignment: .leading, spacing: 6) {
HStack(spacing: 6) {
ForEach(LogLevel.allCases, id: \.self) { level in
Button(level.rawValue.capitalized) {
DevTelemetryRecorder.setMinLevel(level)
actionFeedback = "Set Zig obs min level to \(level.rawValue)"
}
.buttonStyle(.bordered)
.controlSize(.small)
}
}
}
}
DeveloperDebugSection(title: "Diagnostics") {
VStack(alignment: .leading, spacing: 6) {
actionButton(title: "Copy diagnostics JSON", system: "doc.on.doc") {
copyDiagnosticsToPasteboard()
actionFeedback = "Diagnostics JSON copied to clipboard"
}
actionButton(title: "Open full log viewer", system: "arrow.up.right.square") {
onOpenLogs()
}
}
}
if let actionFeedback {
Text(actionFeedback)
.font(.system(size: 11, design: .monospaced))
.foregroundColor(Theme.success)
.padding(.top, 4)
.accessibilityIdentifier("developerDebug.actions.feedback")
}
}
.padding(12)
}
}
private func actionButton(title: String, system: String, _ action: @escaping () -> Void) -> some View {
Button(action: action) {
HStack(spacing: 8) {
Image(systemName: system)
Text(title)
.font(.system(size: 12))
Spacer()
}
.padding(.horizontal, 8)
.padding(.vertical, 6)
.frame(maxWidth: .infinity)
.background(Theme.surface2.opacity(0.7))
.clipShape(RoundedRectangle(cornerRadius: 6))
.overlay(
RoundedRectangle(cornerRadius: 6)
.stroke(Theme.border, lineWidth: 1)
)
}
.buttonStyle(.plain)
}
private func copyDiagnosticsToPasteboard() {
let snap = snapshot
let tel = telemetry.snapshot
let payload: [String: Any] = [
"captured_at": ISO8601DateFormatter().string(from: snap.capturedAt),
"destination": snap.destinationLabel,
"destination_details": snap.destinationDetails,
"app_rows": snap.appRows.map { ["label": $0.label, "value": $0.value, "tone": String(describing: $0.tone)] },
"session_rows": snap.sessionRows.map { ["label": $0.label, "value": $0.value] },
"log_rows": snap.logRows.map { ["label": $0.label, "value": $0.value] },
"telemetry": [
"started_at_ms": tel.startedAtMs,
"now_ms": tel.nowMs,
"events_seq": tel.totalEventSeq,
"events_dropped": tel.droppedEvents,
"counters": Dictionary(uniqueKeysWithValues: tel.counters.map { ($0.0, $0.1) }),
"methods": tel.methods.map { method -> [String: Any] in
[
"key": method.key,
"count": method.count,
"errors": method.errors,
"max_ms": method.maxMs,
"last_ms": method.lastMs,
"avg_ms": method.avgMs,
]
}
]
]
guard
let data = try? JSONSerialization.data(withJSONObject: payload, options: [.prettyPrinted, .sortedKeys]),
let text = String(data: data, encoding: .utf8)
else { return }
#if os(macOS)
NSPasteboard.general.clearContents()
NSPasteboard.general.setString(text, forType: .string)
#endif
}
@MainActor
private func refreshDiagnostics() async {
async let entries = AppLogger.fileWriter.readEntries(limit: 300)
async let stats = AppLogger.fileWriter.stats()
logEntries = await entries
logStats = await stats
}
private func startAutoRefresh() {
stopAutoRefresh()
guard autoRefresh else { return }
refreshTimer = Timer.scheduledTimer(withTimeInterval: 2, repeats: true) { _ in
Task { await refreshDiagnostics() }
}
}
private func stopAutoRefresh() {
refreshTimer?.invalidate()
refreshTimer = nil
}
}
private struct DeveloperDebugSection<Content: View>: View {
let title: String
@ViewBuilder let content: Content
var body: some View {
VStack(alignment: .leading, spacing: 8) {
Text(title.uppercased())
.font(.system(size: 10, weight: .bold))
.foregroundColor(Theme.textTertiary)
content
}
}
}
private struct DeveloperDebugRows: View {
let rows: [DeveloperDebugStateRow]
var body: some View {
VStack(spacing: 1) {
ForEach(rows) { row in
HStack(alignment: .top, spacing: 8) {
Text(row.label)
.font(.system(size: 11, weight: .medium))
.foregroundColor(Theme.textTertiary)
.frame(width: 128, alignment: .leading)
Text(row.value)
.font(.system(size: 11, design: .monospaced))
.foregroundColor(row.tone.color)
.textSelection(.enabled)
.lineLimit(3)
Spacer(minLength: 0)
}
.padding(.vertical, 5)
.padding(.horizontal, 8)
.background(Theme.surface2.opacity(0.7))
}
}
.clipShape(RoundedRectangle(cornerRadius: 6))
.overlay(
RoundedRectangle(cornerRadius: 6)
.stroke(Theme.border, lineWidth: 1)
)
}
}
private struct DeveloperDebugEmptyRow: View {
let text: String
var body: some View {
Text(text)
.font(.system(size: 11))
.foregroundColor(Theme.textTertiary)
.frame(maxWidth: .infinity, alignment: .leading)
.padding(10)
.background(Theme.surface2.opacity(0.7))
.clipShape(RoundedRectangle(cornerRadius: 6))
}
}
private struct DeveloperDebugSessionRow: View {
let session: DeveloperDebugSessionSummary
var body: some View {
VStack(alignment: .leading, spacing: 5) {
HStack {
Text(session.title)
.font(.system(size: 12, weight: .semibold))
.foregroundColor(Theme.textPrimary)
.lineLimit(1)
if session.isActive {
DeveloperDebugBadge(text: "ACTIVE", color: Theme.accent)
}
if session.isRunning {
DeveloperDebugBadge(text: "RUNNING", color: Theme.success)
}
Spacer()
Text(String(session.id.prefix(8)))
.font(.system(size: 10, design: .monospaced))
.foregroundColor(Theme.textTertiary)
}
HStack(spacing: 10) {
Text("\(session.messageCount) messages")
Text(session.model)
}
.font(.system(size: 10, design: .monospaced))
.foregroundColor(Theme.textTertiary)
Text(session.preview)
.font(.system(size: 11))
.foregroundColor(Theme.textSecondary)
.lineLimit(2)
}
.textSelection(.enabled)
.padding(10)
.background(Theme.surface2.opacity(0.7))
.clipShape(RoundedRectangle(cornerRadius: 6))
.overlay(
RoundedRectangle(cornerRadius: 6)
.stroke(session.isActive ? Theme.accent.opacity(0.45) : Theme.border, lineWidth: 1)
)
}
}
private struct DeveloperDebugRunTabRow: View {
let tab: DeveloperDebugRunTabSummary
var body: some View {
VStack(alignment: .leading, spacing: 5) {
HStack {
Text(tab.title)
.font(.system(size: 12, weight: .semibold))
.foregroundColor(Theme.textPrimary)
.lineLimit(1)
Spacer()
Text(String(tab.id.prefix(8)))
.font(.system(size: 10, design: .monospaced))
.foregroundColor(Theme.textTertiary)
}
Text(tab.preview)
.font(.system(size: 11))
.foregroundColor(Theme.textSecondary)
.lineLimit(2)
}
.textSelection(.enabled)
.padding(10)
.background(Theme.surface2.opacity(0.7))
.clipShape(RoundedRectangle(cornerRadius: 6))
}
}
private struct DeveloperDebugMessageRow: View {
let message: DeveloperDebugMessageSummary
var body: some View {
VStack(alignment: .leading, spacing: 5) {
HStack {
DeveloperDebugBadge(text: message.type.uppercased(), color: Theme.info)
Text(message.timestamp)
.font(.system(size: 10, design: .monospaced))
.foregroundColor(Theme.textTertiary)
Spacer()
Text(message.id)
.font(.system(size: 10, design: .monospaced))
.foregroundColor(Theme.textTertiary)
}
Text(message.preview)
.font(.system(size: 11))
.foregroundColor(Theme.textSecondary)
.lineLimit(3)
}
.textSelection(.enabled)
.padding(10)
.background(Theme.surface2.opacity(0.7))
.clipShape(RoundedRectangle(cornerRadius: 6))
}
}
private struct DeveloperDebugBadge: View {
let text: String
let color: Color
var body: some View {
Text(text)
.font(.system(size: 9, weight: .bold, design: .monospaced))
.foregroundColor(color)
.padding(.horizontal, 5)
.padding(.vertical, 2)
.background(color.opacity(0.14))
.clipShape(RoundedRectangle(cornerRadius: 4))
}
}
private struct DeveloperMethodLatencyRow: View {
let method: DevTelemetryMethodStat
private var p99Index: Int? {
guard method.count > 0 else { return nil }
let total = method.buckets.reduce(0, +)
guard total > 0 else { return nil }
let target = Double(total) * 0.99
var running: UInt64 = 0
for (idx, bucket) in method.buckets.enumerated() {
running += bucket
if Double(running) >= target { return idx }
}
return method.buckets.count - 1
}
private var maxBucket: UInt64 { method.buckets.max() ?? 0 }
var body: some View {
VStack(alignment: .leading, spacing: 4) {
HStack(spacing: 6) {
Text(method.key)
.font(.system(size: 11, weight: .semibold, design: .monospaced))
.foregroundColor(Theme.textPrimary)
.lineLimit(1)
.truncationMode(.middle)
Spacer()
if method.errors > 0 {
Text("\(method.errors) err")
.font(.system(size: 10, weight: .bold, design: .monospaced))
.foregroundColor(Theme.danger)
}
Text("n=\(method.count)")
.font(.system(size: 10, design: .monospaced))
.foregroundColor(Theme.textTertiary)
}
HStack(spacing: 10) {
Text("avg \(Int(method.avgMs))ms")
Text("last \(method.lastMs)ms")
Text("max \(method.maxMs)ms")
if let p99Index, p99Index < method.bucketUpperMs.count {
let upper = method.bucketUpperMs[p99Index]