Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions apps/macos/Sequins/ViewModels/DashboardsViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,22 @@ final class DashboardsViewModel {
}
}

/// The built-in templates available in the "New from template" gallery.
func loadTemplates(dataSource: DataSource) -> [DashboardTemplateInfo] {
(try? dataSource.listDashboardTemplates()) ?? []
}

/// Instantiate a template into a fresh dashboard and select it.
func createFromTemplate(id: String, dataSource: DataSource) {
do {
let created = try dataSource.instantiateTemplate(id: id)
refresh(dataSource: dataSource)
select(created.id)
} catch {
errorMessage = error.localizedDescription
}
}

func deleteSelected(dataSource: DataSource) {
guard let id = selectedDashboardId else { return }
do {
Expand Down
42 changes: 20 additions & 22 deletions apps/macos/Sequins/ViewModels/HealthViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -100,13 +100,14 @@ final class HealthViewModel {
let duration = timeRange.bounds.end.timeIntervalSince(timeRange.bounds.start)
lastDuration = duration
let timeWindowMinutes = max(1.0, duration / 60.0)
let durationStr = formatDuration(duration)
let resourceFilter = buildResourceIdFilter(selectedService)
lastResourceFilter = resourceFilter
let serviceName = selectedService?.name ?? "unknown"

// Scope-less template queries — the selected range is passed structurally to
// `executeView` (see `timeRange:` below), overriding any inline scope.
let spanQuery =
"spans last \(durationStr)\(resourceFilter)"
"spans\(resourceFilter)"
+ " | group by {} {"
+ " count() where status == 2 as error_count,"
+ " count() as total,"
Expand All @@ -118,7 +119,7 @@ final class HealthViewModel {
+ " }"

let logQuery =
"logs last \(durationStr) | where severity_number >= 9\(resourceFilter)"
"logs | where severity_number >= 9\(resourceFilter)"
+ " | group by {} { count() as error_logs }"

print("🏥 [HealthViewModel] Span query: \(spanQuery)")
Expand All @@ -135,15 +136,19 @@ final class HealthViewModel {
feed = newFeed

do {
spanViewHandle = try dataSource.executeView(spanQuery, strategy: .aggregate) { [weak newFeed] deltas in
spanViewHandle = try dataSource.executeView(
spanQuery, timeRange: timeRange, strategy: .aggregate
) { [weak newFeed] deltas in
for d in deltas where d.type == .tableReplaced || d.type == .rowsAppended {
if let batch = d.data.first {
newFeed?.applySpanBatch(batch)
}
}
}

logViewHandle = try dataSource.executeView(logQuery, strategy: .aggregate) { [weak newFeed] deltas in
logViewHandle = try dataSource.executeView(
logQuery, timeRange: timeRange, strategy: .aggregate
) { [weak newFeed] deltas in
for d in deltas where d.type == .tableReplaced || d.type == .rowsAppended {
if let batch = d.data.first {
newFeed?.applyLogBatch(batch)
Expand Down Expand Up @@ -187,12 +192,15 @@ final class HealthViewModel {
}

let comparisonWindowMinutes = max(1.0, lastDuration / 60.0)
let durationStr = formatDuration(lastDuration)
let cutoffNs = UInt64((Date().timeIntervalSince1970 - offsetSeconds) * 1_000_000_000)

// The prior window `[now - offset - dur, now - offset]`, passed structurally so
// the queries stay scope-less templates (no baked `last` / cutoff filter).
let priorEnd = Date().addingTimeInterval(-offsetSeconds)
let priorStart = priorEnd.addingTimeInterval(-lastDuration)
let priorRange = TimeRange.absolute(start: priorStart, end: priorEnd)

let spanQuery =
"spans last \(durationStr)\(lastResourceFilter)"
+ " | where start_time_unix_nano < \(cutoffNs)"
"spans\(lastResourceFilter)"
+ " | group by {} {"
+ " count() where status == 2 as error_count,"
+ " count() as total,"
Expand All @@ -204,8 +212,7 @@ final class HealthViewModel {
+ " }"

let logQuery =
"logs last \(durationStr) | where severity_number >= 9\(lastResourceFilter)"
+ " | where start_time_unix_nano < \(cutoffNs)"
"logs | where severity_number >= 9\(lastResourceFilter)"
+ " | group by {} { count() as error_logs }"

currentFeed.clearComparison()
Expand All @@ -224,7 +231,7 @@ final class HealthViewModel {
let spanSink = SnapshotSink { [weak currentFeed] batch in
currentFeed?.applyComparisonSpanBatch(batch, timeWindowMinutes: comparisonWindowMinutes)
}
let _ = try dataSource.executeSeQL(spanQuery, sink: spanSink)
let _ = try dataSource.executeSeQL(spanQuery, timeRange: priorRange, sink: spanSink)
} catch {
print("🏥 [HealthViewModel] Comparison span query failed: \(error)")
}
Expand All @@ -233,7 +240,7 @@ final class HealthViewModel {
let logSink = SnapshotSink { [weak currentFeed] batch in
currentFeed?.applyComparisonLogBatch(batch, timeWindowMinutes: comparisonWindowMinutes)
}
let _ = try dataSource.executeSeQL(logQuery, sink: logSink)
let _ = try dataSource.executeSeQL(logQuery, timeRange: priorRange, sink: logSink)
} catch {
print("🏥 [HealthViewModel] Comparison log query failed: \(error)")
}
Expand Down Expand Up @@ -291,13 +298,4 @@ final class HealthViewModel {
let ids = service.resourceIds.map { String($0) }.joined(separator: ", ")
return " | where resource_id in [\(ids)]"
}

private func formatDuration(_ duration: TimeInterval) -> String {
let hours = Int(duration / 3600)
if hours > 0 && hours <= 24 {
return "\(hours)h"
}
let minutes = Int(duration / 60)
return "\(max(minutes, 1))m"
}
}
18 changes: 6 additions & 12 deletions apps/macos/Sequins/ViewModels/LogsViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -215,15 +215,8 @@ final class LogsViewModel {

self.dataSource = dataSource

let hours = Int(timeRange.bounds.end.timeIntervalSince(timeRange.bounds.start) / 3600)
var query: String
if hours > 0 && hours <= 24 {
query = "logs last \(hours)h"
} else {
let startNs = Int64(timeRange.bounds.start.timeIntervalSince1970 * 1_000_000_000)
let endNs = Int64(timeRange.bounds.end.timeIntervalSince1970 * 1_000_000_000)
query = "logs between(\(startNs), \(endNs))"
}
// Scope-less template — `timeRange` is applied structurally at execution.
var query = "logs"

if let filter = buildResourceIdFilter(selectedService) {
query += filter
Expand Down Expand Up @@ -251,7 +244,7 @@ final class LogsViewModel {
tableView = tv

do {
try tv.startSnapshot(dataSource: dataSource, query: query)
try tv.startSnapshot(dataSource: dataSource, query: query, timeRange: timeRange)
isLoading = false
} catch {
NSLog("📋 SeQL execution error: \(error)")
Expand All @@ -271,7 +264,7 @@ final class LogsViewModel {

cancel()

var query = "logs last 1h"
var query = "logs"
if let filter = buildResourceIdFilter(selectedService) {
query += filter
}
Expand All @@ -291,7 +284,8 @@ final class LogsViewModel {
tableView = tv

do {
try tv.start(dataSource: dataSource, query: query)
// Live mode uses a 1h initial window, applied structurally.
try tv.start(dataSource: dataSource, query: query, timeRange: .relative(duration: 3600))
} catch {
NSLog("📋 [LogsViewModel] Live stream failed to start: \(error)")
self.error = "Query failed: \(error.localizedDescription)"
Expand Down
36 changes: 11 additions & 25 deletions apps/macos/Sequins/ViewModels/MetricsViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -123,21 +123,14 @@ final class MetricsViewModel {
self.timeRange = timeRange

let duration = timeRange.bounds.end.timeIntervalSince(timeRange.bounds.start)
let hours = Int(duration / 3600)
let binSize = binSizeString(for: duration)

let timeStr: String
if hours > 0 && hours <= 24 {
timeStr = "last \(hours)h"
} else {
let minutes = Int(duration / 60)
timeStr = "last \(max(minutes, 1))m"
}

let resourceFilter = buildResourceIdFilter(selectedService) ?? ""

let gaugeQuery = "metrics \(timeStr)\(resourceFilter) | where metric_type != 'histogram' <- (datapoints | group by { ts() bin \(binSize) as bucket, metric_id } { avg(value) as val }) as datapoints"
let histQuery = "metrics \(timeStr)\(resourceFilter) | where metric_type = 'histogram' <- (histograms) as histograms"
// Scope-less templates — the range is applied structurally to the outer `metrics`
// scan (the nested datapoints/histograms subqueries are unchanged).
let gaugeQuery = "metrics\(resourceFilter) | where metric_type != 'histogram' <- (datapoints | group by { ts() bin \(binSize) as bucket, metric_id } { avg(value) as val }) as datapoints"
let histQuery = "metrics\(resourceFilter) | where metric_type = 'histogram' <- (histograms) as histograms"

print("📊 [MetricsViewModel] Gauge query: \(gaugeQuery)")
print("📊 [MetricsViewModel] Histogram query: \(histQuery)")
Expand All @@ -151,11 +144,11 @@ final class MetricsViewModel {
error = nil

do {
gaugeViewHandle = try dataSource.executeView(gaugeQuery, strategy: .table) { [weak self] deltas in
gaugeViewHandle = try dataSource.executeView(gaugeQuery, timeRange: timeRange, strategy: .table) { [weak self] deltas in
self?.processGaugeDeltas(deltas)
}

histogramViewHandle = try dataSource.executeView(histQuery, strategy: .table) { [weak self] deltas in
histogramViewHandle = try dataSource.executeView(histQuery, timeRange: timeRange, strategy: .table) { [weak self] deltas in
self?.processHistogramDeltas(deltas)
}
} catch {
Expand Down Expand Up @@ -207,26 +200,19 @@ final class MetricsViewModel {

self.timeRange = timeRange
let duration = timeRange.bounds.end.timeIntervalSince(timeRange.bounds.start)
let hours = Int(duration / 3600)
let liveBinSize = binSizeString(for: duration)
let timeStr: String
if hours > 0 && hours <= 24 {
timeStr = "last \(hours)h"
} else {
let minutes = Int(duration / 60)
timeStr = "last \(max(minutes, 1))m"
}
let resourceFilter = buildResourceIdFilter(selectedService) ?? ""

do {
let gaugeQuery = "metrics \(timeStr)\(resourceFilter) | where metric_type != 'histogram' <- (datapoints | group by { ts() bin \(liveBinSize) as bucket, metric_id } { avg(value) as val }) as datapoints"
gaugeViewHandle = try dataSource.executeView(gaugeQuery, strategy: .table) { [weak self] deltas in
// Scope-less templates — range applied structurally to the outer `metrics` scan.
let gaugeQuery = "metrics\(resourceFilter) | where metric_type != 'histogram' <- (datapoints | group by { ts() bin \(liveBinSize) as bucket, metric_id } { avg(value) as val }) as datapoints"
gaugeViewHandle = try dataSource.executeView(gaugeQuery, timeRange: timeRange, strategy: .table) { [weak self] deltas in
self?.processGaugeDeltas(deltas)
}

let histQuery = "metrics \(timeStr)\(resourceFilter) | where metric_type = 'histogram' <- (histograms) as histograms"
let histQuery = "metrics\(resourceFilter) | where metric_type = 'histogram' <- (histograms) as histograms"
histogramSnapshotComplete = false
histogramViewHandle = try dataSource.executeView(histQuery, strategy: .table) { [weak self] deltas in
histogramViewHandle = try dataSource.executeView(histQuery, timeRange: timeRange, strategy: .table) { [weak self] deltas in
self?.processHistogramDeltas(deltas)
}
} catch {
Expand Down
14 changes: 3 additions & 11 deletions apps/macos/Sequins/ViewModels/ProfilesViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -52,12 +52,12 @@ final class ProfilesViewModel {
self.dataSource = dataSource

let duration = timeRange.bounds.end.timeIntervalSince(timeRange.bounds.start)
let durationStr = formatDuration(duration)
let retentionNs = UInt64(duration * 1_000_000_000)
let resourceFilter = buildResourceIdFilter(selectedService)
let valueTypeFilter = selectedValueType.map { " | where value_type = '\($0)'" } ?? ""

let query = "samples last \(durationStr)\(resourceFilter)\(valueTypeFilter) <- stacks <- frames"
// Scope-less template — the range is applied structurally to the `samples` scan.
let query = "samples\(resourceFilter)\(valueTypeFilter) <- stacks <- frames"

cancel()
error = nil
Expand All @@ -68,6 +68,7 @@ final class ProfilesViewModel {
do {
viewHandle = try dataSource.executeView(
query,
timeRange: timeRange,
strategy: .flamegraph,
retentionNs: retentionNs
) { [weak newFeed] deltas in
Expand Down Expand Up @@ -180,13 +181,4 @@ final class ProfilesViewModel {
let ids = service.resourceIds.map { String($0) }.joined(separator: ", ")
return " | where resource_id in [\(ids)]"
}

private func formatDuration(_ duration: TimeInterval) -> String {
let hours = Int(duration / 3600)
if hours > 0 && hours <= 24 {
return "\(hours)h"
}
let minutes = Int(duration / 60)
return "\(max(minutes, 1))m"
}
}
30 changes: 6 additions & 24 deletions apps/macos/Sequins/ViewModels/TracesViewModel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -342,17 +342,8 @@ final class TracesViewModel {
self.timeRange = timeRange
self.currentServiceName = selectedService?.name ?? "unknown"

let duration = timeRange.bounds.end.timeIntervalSince(timeRange.bounds.start)
let hours = Int(duration / 3600)
let query: String
if hours > 0 && hours <= 24 {
query = "spans last \(hours)h"
} else {
let minutes = Int(duration / 60)
query = "spans last \(max(minutes, 1))m"
}

var fullQuery = query
// Scope-less template — `timeRange` is applied structurally at execution.
var fullQuery = "spans"
if let filter = buildResourceIdFilter(selectedService) {
fullQuery += filter
}
Expand All @@ -368,7 +359,7 @@ final class TracesViewModel {
tableView = tv

do {
try tv.startSnapshot(dataSource: dataSource, query: fullQuery)
try tv.startSnapshot(dataSource: dataSource, query: fullQuery, timeRange: timeRange)
isLoading = false

try? await Task.sleep(nanoseconds: 200_000_000)
Expand Down Expand Up @@ -398,17 +389,8 @@ final class TracesViewModel {
self.dataSource = dataSource
self.currentServiceName = serviceName

let duration = timeRange.bounds.end.timeIntervalSince(timeRange.bounds.start)
let hours = Int(duration / 3600)
let timeSpec: String
if hours > 0 && hours <= 24 {
timeSpec = "spans last \(hours)h"
} else {
let minutes = Int(duration / 60)
timeSpec = "spans last \(max(minutes, 1))m"
}

var query = timeSpec
// Scope-less template — `timeRange` is applied structurally at execution.
var query = "spans"
if let filter = buildResourceIdFilter(selectedService) {
query += filter
}
Expand All @@ -420,7 +402,7 @@ final class TracesViewModel {
tableView = tv

do {
try tv.start(dataSource: dataSource, query: query)
try tv.start(dataSource: dataSource, query: query, timeRange: timeRange)
} catch {
self.error = "Live stream failed: \(error.localizedDescription)"
}
Expand Down
23 changes: 19 additions & 4 deletions apps/macos/Sequins/Views/Dashboards/DashboardListPanel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ struct DashboardListPanel: View {
@Bindable var viewModel: DashboardsViewModel

@State private var showingNew = false
@State private var showingGallery = false
@State private var newName = ""

var body: some View {
Expand All @@ -15,13 +16,24 @@ struct DashboardListPanel: View {
Text("Dashboards")
.font(.headline)
Spacer()
Button {
newName = ""
showingNew = true
Menu {
Button {
newName = ""
showingNew = true
} label: {
Label("New Dashboard", systemImage: "square.grid.2x2")
}
Button {
showingGallery = true
} label: {
Label("New from Template…", systemImage: "rectangle.stack.badge.plus")
}
} label: {
Image(systemName: "plus")
}
.buttonStyle(.borderless)
.menuStyle(.borderlessButton)
.menuIndicator(.hidden)
.fixedSize()
.help("New dashboard")
}
.padding(.horizontal, 10)
Expand Down Expand Up @@ -69,6 +81,9 @@ struct DashboardListPanel: View {
}
Button("Cancel", role: .cancel) {}
}
.sheet(isPresented: $showingGallery) {
TemplateGallerySheet(viewModel: viewModel, dataSource: appState.dataSource)
}
}

private var selectionBinding: Binding<String?> {
Expand Down
Loading
Loading