diff --git a/Sources/CodeCaps/CodeCapsAlertChannels.swift b/Sources/CodeCaps/CodeCapsAlertChannels.swift new file mode 100644 index 00000000..b1560527 --- /dev/null +++ b/Sources/CodeCaps/CodeCapsAlertChannels.swift @@ -0,0 +1,69 @@ +import Foundation +import QuotaCore + +/// One alert occurrence on its way to a delivery channel. +/// +/// Every event carries its stable `UsageAlertKind` identifier, so channels +/// select by kind — never by which producer emitted the event — and a +/// future per-kind channel opt-in needs no producer changes. +public struct CodeCapsAlertEvent: Equatable, Sendable { + public let kind: UsageAlertKind + public let title: String + public let body: String + public let identifier: String + public let occurredAt: Date + + public init(kind: UsageAlertKind, title: String, body: String, + identifier: String, occurredAt: Date) { + self.kind = kind + self.title = title + self.body = body + self.identifier = identifier + self.occurredAt = occurredAt + } +} + +/// A delivery channel for app-level alert events. +/// +/// The seam is deliberately at the app level, not inside any plugin: a new +/// channel registers once with the dispatcher and receives every producer's +/// events. The planned Twilio SMS channel is the expected second channel — +/// app-level, selecting a deliberately small set of kinds — and it slots in +/// here without reworking any monitor. +@MainActor +public protocol CodeCapsAlertChannel: AnyObject { + func deliver(_ event: CodeCapsAlertEvent) +} + +/// App-level fan-out for alert events. Producers emit here, never to a +/// channel directly. +@MainActor +public final class CodeCapsAlertDispatcher { + private var channels: [CodeCapsAlertChannel] = [] + + public init() {} + + public func register(_ channel: CodeCapsAlertChannel) { + channels.append(channel) + } + + public func emit(_ event: CodeCapsAlertEvent) { + for channel in channels { channel.deliver(event) } + } +} + +/// The only channel today: CodeCaps' own alert surface, through the same +/// per-kind preferences and delivery path as every other usage alert. +@MainActor +public final class LocalAlertChannel: CodeCapsAlertChannel { + private weak var manager: ResetAlarmManager? + + public init(manager: ResetAlarmManager) { + self.manager = manager + } + + public func deliver(_ event: CodeCapsAlertEvent) { + manager?.deliverUsageAlert(kind: event.kind, title: event.title, + body: event.body, identifier: event.identifier) + } +} diff --git a/Sources/CodeCaps/ConsoleViews.swift b/Sources/CodeCaps/ConsoleViews.swift index f21388e4..7436b114 100644 --- a/Sources/CodeCaps/ConsoleViews.swift +++ b/Sources/CodeCaps/ConsoleViews.swift @@ -8,6 +8,7 @@ enum ConsolePage: Hashable { case allPlatforms case platform(String) case runawayAlerts + case plugin(String) case settingsMenuBar case settingsPlatforms case settingsLogoStyle @@ -19,7 +20,7 @@ enum ConsolePage: Hashable { var isSettings: Bool { switch self { - case .allPlatforms, .platform, .runawayAlerts: return false + case .allPlatforms, .platform, .runawayAlerts, .plugin: return false default: return true } } @@ -29,6 +30,7 @@ enum ConsolePage: Hashable { case .allPlatforms: return "allPlatforms" case .platform(let providerKey): return "platform:" + providerKey case .runawayAlerts: return "runawayAlerts" + case .plugin(let pluginId): return "plugin:" + pluginId case .settingsMenuBar: return "settingsMenuBar" case .settingsPlatforms: return "settingsPlatforms" case .settingsLogoStyle: return "settingsLogoStyle" @@ -53,6 +55,9 @@ enum ConsolePage: Hashable { case "settingsInfisical": return .settingsInfisical case "settingsAbout": return .settingsAbout default: + if value.hasPrefix("plugin:") { + return .plugin(String(value.dropFirst(7))) + } guard value.hasPrefix("platform:") else { return nil } return .platform(String(value.dropFirst(9))) } @@ -63,6 +68,7 @@ enum ConsolePage: Hashable { switch self { case .allPlatforms: return "All Platforms" case .runawayAlerts: return "Runaway Alerts" + case .plugin(let pluginId): return CodeCapsPlugin.named(pluginId)?.title ?? "Plugin" case .settingsMenuBar: return "Menu Bar & PiP" case .settingsPlatforms: return "Platforms" case .settingsLogoStyle: return "Logo Style" @@ -79,6 +85,7 @@ enum ConsolePage: Hashable { switch self { case .allPlatforms: return "square.grid.2x2" case .runawayAlerts: return "flame.fill" + case .plugin(let pluginId): return CodeCapsPlugin.named(pluginId)?.symbol ?? "puzzlepiece.extension" case .settingsMenuBar: return "menubar.rectangle" case .settingsPlatforms: return "square.grid.2x2" case .settingsLogoStyle: return "photo.on.rectangle.angled" @@ -94,6 +101,8 @@ enum ConsolePage: Hashable { static let settingsPages: [ConsolePage] = [ .settingsMenuBar, .settingsPlatforms, .settingsLogoStyle, .settingsSourcesFleet, .settingsNotifications, .settingsAppearance, .settingsInfisical, .settingsAbout, ] + + static let pluginPages: [ConsolePage] = CodeCapsPlugin.allCases.map { .plugin($0.id) } } struct AlertNavigation: Equatable { @@ -192,6 +201,13 @@ final class ConsoleState: ObservableObject { awaitingInitialSelection = false return } + if case .plugin = page { + // A plugin page is local: it never waits on a quota read, and no + // source disappearing can invalidate it. + pendingStoredKey = nil + awaitingInitialSelection = false + return + } if page.isSettings && !awaitingInitialSelection { return } if sections.isEmpty && !readCompleted { return } isReconciling = true @@ -335,6 +351,9 @@ struct ConsoleView: View { case .runawayAlerts: RunawayAlertsPage(model: model, state: state) .padding(Metrics.pagePadding) + case .plugin(let pluginId): + MuseCodePluginPage(model: model, pluginId: pluginId) + .padding(Metrics.pagePadding) case .platform(let key): PlatformDetailPage(model: model, state: state, providerKey: key) .padding(Metrics.pagePadding) @@ -482,6 +501,7 @@ struct ConsoleSidebar: View { private var allPages: [ConsolePage] { var pages: [ConsolePage] = [.allPlatforms, .runawayAlerts] pages.append(contentsOf: model.displaySections.map { .platform($0.id) }) + pages.append(contentsOf: ConsolePage.pluginPages) pages.append(contentsOf: ConsolePage.settingsPages) return pages } @@ -539,6 +559,31 @@ struct ConsoleSidebar: View { } header: { Eyebrow("QUOTAS") } + Section { + ForEach(ConsolePage.pluginPages, id: \.self) { page in + sidebarRow(page: page) { + HStack(spacing: 8) { + Image(systemName: page.symbol) + .font(.system(size: 13)) + .foregroundStyle(model.museCodeBurnAlert == nil ? Theme.ink : Theme.warning) + .frame(width: 18) + Text(page.settingsTitle) + .font(.system(size: 13, weight: .medium)) + Spacer(minLength: 4) + if model.museCodeBurnAlert != nil { + Text("1") + .font(.system(size: 10, weight: .bold)) + .foregroundStyle(.white) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background(Theme.warning, in: Capsule()) + } + } + } + } + } header: { + Eyebrow("PLUGINS") + } Section { ForEach(ConsolePage.settingsPages, id: \.self) { page in sidebarRow(page: page) { diff --git a/Sources/CodeCaps/MonitorModel.swift b/Sources/CodeCaps/MonitorModel.swift index 6268b606..73e9f1d0 100644 --- a/Sources/CodeCaps/MonitorModel.swift +++ b/Sources/CodeCaps/MonitorModel.swift @@ -354,6 +354,50 @@ final class MonitorModel: ObservableObject { dismissedPlanChangeIds.insert(id) } @Published public private(set) var runawayAlertHistory: [RunawayAlertRecord] = [] + + // MARK: - Muse Plugin + + /// Latest Muse session-store reading, for the Plugins section. + @Published private(set) var museCodeReport: MuseCodeSessionReport? + @Published private(set) var museCodeIssue: String? + /// The alerts the current reading produces. Both stay visible on the + /// plugin page whether or not their delivery is inside a cooldown. + @Published private(set) var museCodeBurnAlert: MuseCodeBurnMonitor.BurnAlert? + /// The most recent standard-session event the detector fired. Unlike + /// the burn alert this is an event, not a state: it stays on the page + /// (with its observed time in the body) until a newer event replaces it. + @Published private(set) var museCodeStandardSessionAlert: MuseCodeStandardSessionEvent? + @Published private(set) var museCodeBridgeStatus: String? + /// Token threshold for the burn alert in the trailing 90-minute window. + /// A per-user tunable, so it stays in UserDefaults like the burn-rate + /// multipliers (see INFISICAL.md), never in Infisical. + @Published var museCodeBurnThresholdTokens: Int { + didSet { + defaults.set(museCodeBurnThresholdTokens, forKey: "museCodeBurnThresholdTokens") + if let museCodeReport { evaluateMuseCodeAlerts(report: museCodeReport) } + } + } + /// Ships on: the warning is the feature the plugin exists for. Either + /// alert kind can still be turned off on its own in Alerts & Alarms. + @Published var museCodeBurnAlertsEnabled: Bool { + didSet { + defaults.set(museCodeBurnAlertsEnabled, forKey: "museCodeBurnAlertsEnabled") + if museCodeBurnAlertsEnabled { + Task { await alarmManager.requestNotificationPermission() } + if let museCodeReport { evaluateMuseCodeAlerts(report: museCodeReport) } + } else { + museCodeBurnAlert = nil + museCodeStandardSessionAlert = nil + } + } + } + /// Whether the plugin also posts its session token events to Usage + /// Monitor through the sync endpoint. Off by default: the local monitor + /// is the feature; the bridge is provenance for the server. + @Published var museCodeUsageBridgeEnabled: Bool { + didSet { defaults.set(museCodeUsageBridgeEnabled, forKey: "museCodeUsageBridgeEnabled") } + } + public var resetAlertHistory: [ResetAlertRecord] { alarmManager.alertHistory } @@ -555,6 +599,16 @@ final class MonitorModel: ObservableObject { public let alarmManager: ResetAlarmManager + /// App-level alert fan-out. Producers emit `CodeCapsAlertEvent`s here + /// and registered channels deliver them; today the only channel is the + /// local alert surface, and a future channel registers here once rather + /// than inside any producer. + lazy var alertDispatcher: CodeCapsAlertDispatcher = { + let dispatcher = CodeCapsAlertDispatcher() + dispatcher.register(LocalAlertChannel(manager: alarmManager)) + return dispatcher + }() + private let presentsPipWindows: Bool private let defaults: UserDefaults private let burnRateHistoryURL: URL @@ -577,6 +631,20 @@ final class MonitorModel: ObservableObject { var settingsWriteForTesting: (@MainActor (String, String) async throws -> Void)? var pushForTesting: (@MainActor ([QuotaWindow], URL, String?, QuotaSyncFormat) async throws -> QuotaPublishResult)? var runawayNotificationForTesting: ((BurnRateNotification) -> Void)? + var museCodeReadForTesting: (@MainActor () async -> MuseCodeSessionResult?)? + var museCodePublishForTesting: (@MainActor ([[String: Any]], URL, String?) async throws -> MuseCodeIngestSummary)? + var museCodeTokenReadForTesting: (@MainActor () async -> String?)? + private var lastMuseCodeBurnAlertAt: Double = 0 + /// The standard-session detector's tracked state, persisted across + /// launches with the same JSON-in-UserDefaults pattern as the bridge + /// baselines, so a session already reported does not refire after a + /// restart. An earlier build persisted a + /// `museCodeContributorBelow100Active` bool for the share-based edge + /// trigger; that key is abandoned unread. + private var museCodeStandardSessionDetector = MuseCodeStandardSessionDetector() + private static let museCodeDetectorKey = "museCodeStandardSessionDetector" + private var museCodeRequest: Task? + private let museCodePoster = MuseCodeSessionPoster() var exhaustionNotificationForTesting: ((String, String) -> Void)? var exhaustionHistoryURLForTesting: URL? var skipsSnapshotIOForTesting = false @@ -719,6 +787,15 @@ final class MonitorModel: ObservableObject { syncEndpoint = defaults.string(forKey: "syncEndpoint") ?? "" syncFormat = QuotaSyncFormat(rawValue: defaults.string(forKey: "syncFormat") ?? "") ?? .usageMonitorV2 remoteAlertRelayEnabled = defaults.bool(forKey: "remoteAlertRelayEnabled") + museCodeBurnThresholdTokens = defaults.object(forKey: "museCodeBurnThresholdTokens") as? Int + ?? MuseCodeBurnMonitor.defaultThresholdTokens + museCodeBurnAlertsEnabled = defaults.object(forKey: "museCodeBurnAlertsEnabled") as? Bool ?? true + museCodeUsageBridgeEnabled = defaults.bool(forKey: "museCodeUsageBridgeEnabled") + lastMuseCodeBurnAlertAt = defaults.double(forKey: "museCodeBurnLastSent") + if let data = defaults.data(forKey: Self.museCodeDetectorKey), + let saved = try? JSONDecoder().decode(MuseCodeStandardSessionDetector.self, from: data) { + museCodeStandardSessionDetector = saved + } alarmManager = ResetAlarmManager(defaults: defaults) @@ -2457,6 +2534,7 @@ final class MonitorModel: ObservableObject { let widgetCandidates = unifiedMerged + split.groups.flatMap(\.windows) self.publishWidgetSnapshot(candidates: widgetCandidates) self.refreshRunawayUsageState(recordSamples: local != nil) + self.refreshMuseCodePlugin() self.refreshExhaustionWarnings(windows: widgetCandidates, now: self.now) self.alarmManager.evaluate(observations: self.resetAlarmObservationsForCurrentReadings(), now: self.now) self.evaluatePipLowQuota() @@ -2628,6 +2706,7 @@ final class MonitorModel: ObservableObject { let widgetCandidates = unifiedMerged + split.groups.flatMap(\.windows) publishWidgetSnapshot(candidates: widgetCandidates) refreshRunawayUsageState(recordSamples: recordSamples) + refreshMuseCodePlugin() refreshExhaustionWarnings(windows: widgetCandidates, now: now) alarmManager.evaluate(observations: resetAlarmObservationsForCurrentReadings(), now: now) evaluatePipLowQuota() @@ -3031,6 +3110,165 @@ final class MonitorModel: ObservableObject { defaults.set(lastRunawayAlertAt, forKey: "runawayAlertLastSent") } + // MARK: - Muse Plugin Evaluation + + /// Reads the Muse session store alongside the quota refresh paths and + /// applies the result. Mirrors the session-file reader's test guard: an + /// injected quota read must not silently start a real file scan in an + /// offline test. + func refreshMuseCodePlugin() { + guard localEnabled else { + museCodeReport = nil + museCodeIssue = nil + museCodeBurnAlert = nil + museCodeStandardSessionAlert = nil + return + } + if museCodeReadForTesting == nil, + skipsSnapshotIOForTesting || localReadForTesting != nil || localResultForTesting != nil + || serverFetchForTesting != nil { return } + guard museCodeRequest == nil else { return } + let readForTesting = museCodeReadForTesting + museCodeRequest = Task { [weak self] in + let result: MuseCodeSessionResult? + if let readForTesting { + result = await readForTesting() + } else { + result = await Task.detached(priority: .utility) { + MuseCodeSessionReader().read() + }.value + } + guard let self else { return } + self.museCodeRequest = nil + guard !Task.isCancelled else { return } + if let result { self.applyMuseCodeResult(result) } + } + } + + /// Applies one session-store reading: page state first, then the alert + /// events, then the optional Usage Monitor bridge. + func applyMuseCodeResult(_ result: MuseCodeSessionResult) { + museCodeReport = result.report + museCodeIssue = result.issue + guard let report = result.report else { + museCodeBurnAlert = nil + museCodeStandardSessionAlert = nil + return + } + evaluateMuseCodeAlerts(report: report) + if museCodeUsageBridgeEnabled { + Task { [weak self] in await self?.postMuseCodeBridge(report: report) } + } + } + + private func evaluateMuseCodeAlerts(report: MuseCodeSessionReport) { + guard museCodeBurnAlertsEnabled else { + museCodeBurnAlert = nil + museCodeStandardSessionAlert = nil + return + } + let burn = MuseCodeBurnMonitor.evaluateBurn(report: report, + thresholdTokens: museCodeBurnThresholdTokens) + museCodeBurnAlert = burn + if let burn, + now.timeIntervalSince1970 - lastMuseCodeBurnAlertAt >= MuseCodeBurnMonitor.alertCooldown { + lastMuseCodeBurnAlertAt = now.timeIntervalSince1970 + defaults.set(lastMuseCodeBurnAlertAt, forKey: "museCodeBurnLastSent") + alertDispatcher.emit(CodeCapsAlertEvent( + kind: .museCodeBurn, title: burn.title, body: burn.body, + identifier: "codecaps.musecode.burn", occurredAt: report.generatedAt)) + } + // The contributor finding is its own alert kind, independent of the + // burn threshold, and it is an event, not a share: the detector + // fires once when a session starts on a standard model or switches + // to one, and re-arms per session when it returns to a contributor + // model, so a channel that subscribes to the finding itself (the + // planned SMS channel is the expected one) never has to piggyback + // on the burn alert. Each event carries its own notification + // identifier, so two sessions' events never replace each other. + let events = museCodeStandardSessionDetector.observe( + report.latestObservations.map(MuseCodeSessionModelObservation.init)) + saveMuseCodeDetectorState() + if let latest = events.last { + museCodeStandardSessionAlert = latest + } + for event in events { + alertDispatcher.emit(CodeCapsAlertEvent( + kind: .museCodeStandardSession, title: event.title, body: event.body, + identifier: "codecaps.musecode.standard-session.\(event.sessionId)", + occurredAt: event.observedAt)) + } + } + + private func saveMuseCodeDetectorState() { + if let data = try? JSONEncoder().encode(museCodeStandardSessionDetector) { + defaults.set(data, forKey: Self.museCodeDetectorKey) + } + } + + /// Posts the reading's per-session token deltas to Usage Monitor under + /// the verified `muse-code` contract: the contract endpoint, the + /// muse-code scoped producer token from its own Keychain service, and + /// only the positive delta since the previous observation — a session's + /// latest snapshot total is cumulative, so posting totals would + /// double-count. Baselines persist only after every batch is + /// acknowledged; a failed post retries the same deltas next refresh, + /// and the stable event ids make the server dedupe any that did land. + private func postMuseCodeBridge(report: MuseCodeSessionReport) async { + guard !report.latestObservations.isEmpty else { + museCodeBridgeStatus = "No Muse sessions to post." + return + } + let plan = MuseCodeDeltaPlanner.plan(observations: report.latestObservations, + previous: loadMuseCodeIngestState()) + guard !plan.events.isEmpty else { + saveMuseCodeIngestState(plan.updated) + museCodeBridgeStatus = "No new Muse tokens to post." + return + } + let endpoint = MuseCodeSessionIngest.endpoint + let token: String? + if let museCodeTokenReadForTesting { + token = await museCodeTokenReadForTesting() + } else { + token = await TokenStore.read(server: endpoint.absoluteString, + service: TokenStore.museCodeIngestService) + .map(sanitizedToken(_:)) + } + guard let token, !token.isEmpty else { + museCodeBridgeStatus = "Bridge needs the muse-code ingest token saved in CodeCaps." + return + } + let events = plan.events.map { + MuseCodeSessionIngest.event(observation: $0.observation, delta: $0.delta) + } + do { + let summary: MuseCodeIngestSummary + if let museCodePublishForTesting { + summary = try await museCodePublishForTesting(events, endpoint, token) + } else { + summary = try await museCodePoster.publish(events: events, to: endpoint, token: token) + } + saveMuseCodeIngestState(plan.updated) + museCodeBridgeStatus = "Posted \(summary.sent) token events: \(summary.persisted) persisted, \(summary.duplicates) duplicates, \(summary.rejected) rejected." + } catch { + museCodeBridgeStatus = "Bridge failed: \((error as? LocalizedError)?.errorDescription ?? error.localizedDescription)" + } + } + + private func loadMuseCodeIngestState() -> [String: MuseCodeSessionObservation] { + guard let data = defaults.data(forKey: "museCodeIngestObservations"), + let decoded = try? JSONDecoder().decode([String: MuseCodeSessionObservation].self, + from: data) else { return [:] } + return decoded + } + + private func saveMuseCodeIngestState(_ state: [String: MuseCodeSessionObservation]) { + if let data = try? JSONEncoder().encode(state) { + defaults.set(data, forKey: "museCodeIngestObservations") + } + } + private func appendRunawayAlert(_ record: RunawayAlertRecord) { var list = runawayAlertHistory list.insert(record, at: 0) diff --git a/Sources/CodeCaps/MuseCodePlugin.swift b/Sources/CodeCaps/MuseCodePlugin.swift new file mode 100644 index 00000000..f856beb7 --- /dev/null +++ b/Sources/CodeCaps/MuseCodePlugin.swift @@ -0,0 +1,28 @@ +import Foundation + +/// A plugin shown in the Console's Plugins section. +/// +/// The raw value is the plugin's stable identifier: it is persisted in the +/// Console page's storage key (`plugin:`), so it must never be renamed +/// once shipped. +public enum CodeCapsPlugin: String, CaseIterable, Identifiable, Sendable { + case museCode = "muse-code" + + public var id: String { rawValue } + + public var title: String { + switch self { + case .museCode: return "Muse" + } + } + + public var symbol: String { + switch self { + case .museCode: return "puzzlepiece.extension" + } + } + + public static func named(_ id: String) -> CodeCapsPlugin? { + CodeCapsPlugin(rawValue: id) + } +} diff --git a/Sources/CodeCaps/MuseCodePluginView.swift b/Sources/CodeCaps/MuseCodePluginView.swift new file mode 100644 index 00000000..4140a6cb --- /dev/null +++ b/Sources/CodeCaps/MuseCodePluginView.swift @@ -0,0 +1,265 @@ +import QuotaCore +import SwiftUI + +/// Routes a Plugins-section page to the plugin that owns it. +struct MuseCodePluginPage: View { + @ObservedObject var model: MonitorModel + let pluginId: String + + var body: some View { + if let plugin = CodeCapsPlugin.named(pluginId), plugin == .museCode { + MuseCodeMonitorPage(model: model) + } else { + Text("Plugin unavailable") + .font(.system(size: 13, weight: .medium)) + .foregroundStyle(.secondary) + } + } +} + +/// The Muse monitor plugin: current burn, contributor share, the +/// per-model split, and the deterministic monitor's state and controls. +struct MuseCodeMonitorPage: View { + @ObservedObject var model: MonitorModel + + /// The standard-session kind's popup option, offered here beside the + /// feature it belongs to. It is the same preference the Alerts & + /// Alarms page edits — one stored option behind both surfaces — and + /// it ships off: the popup is opt-in. + private var standardSessionPopupBinding: Binding { + Binding(get: { model.alarmManager.preferences[.museCodeStandardSession].popup }, + set: { value in + var option = model.alarmManager.preferences[.museCodeStandardSession] + option.popup = value + model.alarmManager.preferences[.museCodeStandardSession] = option + }) + } + + private var window90: MuseCodeWindowUsage? { model.museCodeReport?.window(minutes: 90) } + private var window60: MuseCodeWindowUsage? { model.museCodeReport?.window(minutes: 60) } + + private var status: MuseCodeBurnMonitor.Status { + MuseCodeBurnMonitor.status(report: model.museCodeReport, issue: model.museCodeIssue, + thresholdTokens: model.museCodeBurnThresholdTokens) + } + + private var isWarning: Bool { + if case .warning = status { return true } + return false + } + + var body: some View { + VStack(alignment: .leading, spacing: 18) { + headerSection + if let issue = model.museCodeIssue { + Text(issue) + .font(.system(size: 12)) + .foregroundStyle(Theme.warning) + .fixedSize(horizontal: false, vertical: true) + } + monitorSection + burnSection + contributorSection + modelsSection + alertsSection + bridgeSection + Text("Session stores rotate snapshots aggressively, so every total on this page is a floor rather than an exact count.") + .font(.system(size: 11)) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + } + + // MARK: - Header + + private var headerSection: some View { + HStack(alignment: .top, spacing: 12) { + Image(systemName: "puzzlepiece.extension") + .font(.system(size: 26)) + .foregroundStyle(isWarning ? Theme.warning : Theme.ink.opacity(0.8)) + .frame(width: 32, height: 32) + VStack(alignment: .leading, spacing: 3) { + HStack(spacing: 8) { + Text("Muse Monitor") + .font(.system(size: 18, weight: .bold, design: .rounded)) + if isWarning { + Text("WARNING") + .font(.system(size: 10, weight: .bold)) + .foregroundStyle(.white) + .padding(.horizontal, 6) + .padding(.vertical, 2) + .background(Theme.warning, in: Capsule()) + } + } + Text("Deterministic monitoring of Muse token burn and standard-model sessions on this Mac.") + .font(.system(size: 12)) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + Spacer() + } + } + + // MARK: - Sections + + private var monitorSection: some View { + VStack(alignment: .leading, spacing: 10) { + Eyebrow("MONITOR") + VStack(alignment: .leading, spacing: 8) { + row("Status", status.text) + if let report = model.museCodeReport { + row("Last Read", report.generatedAt.formatted(date: .omitted, time: .standard)) + } + if let alert = model.museCodeBurnAlert { + row("Burn Alert", alert.body) + } else if let alert = model.museCodeStandardSessionAlert { + row("Standard Session Alert", alert.body) + } + } + .padding(16) + .background(Theme.surface, in: RoundedRectangle(cornerRadius: 10)) + .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(Theme.hairline)) + } + } + + private var burnSection: some View { + VStack(alignment: .leading, spacing: 10) { + Eyebrow("BURN") + VStack(alignment: .leading, spacing: 8) { + if let window = window90 { + row("Last 90 Minutes", "\(MuseCodeFormatting.grouped(window.totalTokens)) tokens") + row("Burn Rate", "\(MuseCodeFormatting.grouped(Int(window.tokensPerHour.rounded()))) tokens per hour") + row("Active Sessions", "\(window.activeSessions)") + } + if let window = window60 { + row("Last 60 Minutes", "\(MuseCodeFormatting.grouped(window.totalTokens)) tokens") + } + if window90 == nil { + row("Burn", "No reading yet") + } + } + .padding(16) + .background(Theme.surface, in: RoundedRectangle(cornerRadius: 10)) + .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(Theme.hairline)) + } + } + + private var contributorSection: some View { + VStack(alignment: .leading, spacing: 10) { + Eyebrow("CONTRIBUTOR SHARE") + VStack(alignment: .leading, spacing: 8) { + if let window = window90, let share = window.contributorShare { + row("Contributor Share (90 minutes)", MuseCodeFormatting.percent(share)) + row("Contributor Tokens", MuseCodeFormatting.grouped(window.contributorTokens)) + if share < 1 { + row("Standard Tokens", MuseCodeFormatting.grouped(window.totalTokens - window.contributorTokens)) + } + } else { + row("Contributor Share (90 minutes)", "No tokens in window") + } + } + .padding(16) + .background(Theme.surface, in: RoundedRectangle(cornerRadius: 10)) + .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(Theme.hairline)) + } + } + + private var modelsSection: some View { + VStack(alignment: .leading, spacing: 10) { + Eyebrow("MODELS") + VStack(alignment: .leading, spacing: 8) { + if let window = window90, !window.models.isEmpty { + ForEach(window.models) { usage in + HStack(spacing: 10) { + Text(usage.modelId) + .font(.system(size: 12).monospaced()) + .lineLimit(1) + .truncationMode(.middle) + Spacer(minLength: 8) + Text(usage.isContributor ? "Contributor" : "Standard") + .font(.system(size: 11, weight: .medium)) + .foregroundStyle(usage.isContributor ? Theme.accent : Theme.warning) + Text("\(MuseCodeFormatting.grouped(usage.tokens)) tokens") + .font(.system(size: 12).monospacedDigit()) + Text(MuseCodeFormatting.percent(usage.share(of: window.totalTokens))) + .font(.system(size: 12).monospacedDigit()) + .foregroundStyle(.secondary) + .frame(width: 52, alignment: .trailing) + } + } + } else { + row("Models", "No model activity in window") + } + } + .padding(16) + .background(Theme.surface, in: RoundedRectangle(cornerRadius: 10)) + .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(Theme.hairline)) + } + } + + private var alertsSection: some View { + VStack(alignment: .leading, spacing: 10) { + Eyebrow("ALERTS") + VStack(alignment: .leading, spacing: 12) { + Toggle("Muse Alerts", isOn: $model.museCodeBurnAlertsEnabled) + Toggle("Popup Warning For Standard Sessions", isOn: standardSessionPopupBinding) + Text("When the popup warning is on, a standard-session alert also opens a popup window naming the session and its model." + + sentenceGap + + "It is off by default and is the same switch as the Popup toggle for Muse Standard Sessions in Alerts & Alarms.") + .font(.system(size: 11)) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + HStack(spacing: 12) { + Text("Burn Threshold") + .font(.system(size: 13, weight: .medium)) + .frame(width: 150, alignment: .leading) + Text("\(MuseCodeFormatting.grouped(model.museCodeBurnThresholdTokens)) tokens in 90 minutes") + .font(.system(size: 13).monospacedDigit()) + Stepper("", value: $model.museCodeBurnThresholdTokens, + in: 100_000...50_000_000, step: 100_000) + .labelsHidden() + } + Text("Two alert kinds: museCodeBurn fires when burn passes the threshold while a session is on a standard model." + + sentenceGap + + "museCodeStandardSession fires on its own the moment a session starts on, or switches to, a standard model, whatever the burn rate.") + .font(.system(size: 11)) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + .padding(16) + .background(Theme.surface, in: RoundedRectangle(cornerRadius: 10)) + .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(Theme.hairline)) + } + } + + private var bridgeSection: some View { + VStack(alignment: .leading, spacing: 10) { + Eyebrow("USAGE MONITOR BRIDGE") + VStack(alignment: .leading, spacing: 12) { + Toggle("Post Token Events To Usage Monitor", isOn: $model.museCodeUsageBridgeEnabled) + row("Bridge Status", model.museCodeBridgeStatus ?? "Not posted yet") + Text("Posts each session's new tokens since the last reading to Usage Monitor, as muse-code token events." + + sentenceGap + + "Replays dedupe server-side, so a failed post is safe to retry.") + .font(.system(size: 11)) + .foregroundStyle(.secondary) + .fixedSize(horizontal: false, vertical: true) + } + .padding(16) + .background(Theme.surface, in: RoundedRectangle(cornerRadius: 10)) + .overlay(RoundedRectangle(cornerRadius: 10).strokeBorder(Theme.hairline)) + } + } + + private func row(_ label: String, _ value: String) -> some View { + HStack(alignment: .top, spacing: 12) { + Text(label) + .font(.system(size: 13, weight: .medium)) + .frame(width: 170, alignment: .leading) + Text(value) + .font(.system(size: 13)) + .fixedSize(horizontal: false, vertical: true) + Spacer(minLength: 0) + } + } +} diff --git a/Sources/CodeCaps/TokenStore.swift b/Sources/CodeCaps/TokenStore.swift index ff3a3fd3..a354c63c 100644 --- a/Sources/CodeCaps/TokenStore.swift +++ b/Sources/CodeCaps/TokenStore.swift @@ -26,11 +26,15 @@ enum TokenStore { static let readService = serviceName(suffix: "read-token") static let syncService = serviceName(suffix: "sync-token") - - /// The two service names this build owns: its Read Token and its Push - /// Token. A `.dev` build's names differ from the release app's, so neither - /// can reach the other's items. - static var ownServices: Set { [readService, syncService] } + /// The Muse plugin's bridge token: a producer-scoped Usage Monitor + /// ingest token for `muse-code`, kept apart from this app's own Push + /// Token because a scoped token authorizes exactly one producer. + static let museCodeIngestService = serviceName(suffix: "muse-code-ingest-token") + + /// The service names this build owns: its Read Token, its Push Token, + /// and the Muse bridge token. A `.dev` build's names differ from the + /// release app's, so neither can reach the other's items. + static var ownServices: Set { [readService, syncService, museCodeIngestService] } /// Whether `service` is exactly one of CodeCaps's own two items. The store /// refuses every other name before any Keychain call is made, so nothing diff --git a/Sources/QuotaCore/MuseCodeBurnMonitor.swift b/Sources/QuotaCore/MuseCodeBurnMonitor.swift new file mode 100644 index 00000000..acd4ed78 --- /dev/null +++ b/Sources/QuotaCore/MuseCodeBurnMonitor.swift @@ -0,0 +1,127 @@ +import Foundation + +/// Number formatting shared by the monitor's alert text and the plugin page, +/// so the words in a notification and the figures on screen cannot drift. +public enum MuseCodeFormatting { + public static func grouped(_ value: Int) -> String { + let formatter = NumberFormatter() + formatter.numberStyle = .decimal + return formatter.string(from: NSNumber(value: value)) ?? "\(value)" + } + + public static func percent(_ share: Double) -> String { + String(format: "%.1f%%", share * 100) + } +} + +/// The Muse plugin's deterministic rule set. Pure code: a report in, +/// an alert (or not) out — no I/O, no clock of its own, no model anywhere. +/// +/// Two distinct findings live here and in +/// `MuseCodeStandardSessionDetector`, because they are two distinct alert +/// kinds at the app level: +/// +/// - `BurnAlert` (kind `museCodeBurn`): the combined rule the owner asked +/// for — trailing-90-minute burn above the threshold AND at least one +/// session currently on a standard model. +/// - Standard-session events (kind `museCodeStandardSession`): the +/// contributor finding on its own, fired by the detector the moment a +/// session starts on, or switches to, a standard model, independent of +/// the burn threshold, so a future channel can subscribe to the finding +/// itself rather than to the burn alert's side effect. +/// +/// Neither rule uses the contributor token share. A share computed from +/// rotating session snapshots moves for reasons unrelated to either +/// question — stale sessions inside the window, token weight, last-segment +/// attribution — and reads below 100% even when every live session is on a +/// contributor model. Presence is the signal: which sessions are on +/// standard models right now. +public enum MuseCodeBurnMonitor { + public static let defaultThresholdTokens = 4_000_000 + public static let alertCooldown: TimeInterval = 3_600 + public static let windowMinutes = 90 + + public struct BurnAlert: Equatable, Sendable { + public let totalTokens: Int + public let thresholdTokens: Int + public let standardSessions: [MuseCodeStandardSessionEvent] + public let observedAt: Date + + public init(totalTokens: Int, thresholdTokens: Int, + standardSessions: [MuseCodeStandardSessionEvent], observedAt: Date) { + self.totalTokens = totalTokens + self.thresholdTokens = thresholdTokens + self.standardSessions = standardSessions + self.observedAt = observedAt + } + + public var title: String { "Muse Burn Above Threshold" } + + public var body: String { + "Muse used \(MuseCodeFormatting.grouped(totalTokens)) tokens in the last 90 minutes, above the \(MuseCodeFormatting.grouped(thresholdTokens)) token threshold." + + sentenceGap + + "Standard-model sessions: \(Self.sessionList(standardSessions))." + } + + static func sessionList(_ sessions: [MuseCodeStandardSessionEvent]) -> String { + sessions.map { "\($0.sessionId) on \($0.modelId)" }.joined(separator: ", ") + } + } + + /// The monitor state the plugin page shows, derived from the same + /// evaluation that fires the alerts. + public enum Status: Equatable, Sendable { + case storeUnavailable + case noActivity + case belowThreshold(totalTokens: Int) + case allContributor(totalTokens: Int) + case warning(BurnAlert) + + public var text: String { + switch self { + case .storeUnavailable: return "Session store unavailable" + case .noActivity: return "No Muse activity in the last 90 minutes" + case .belowThreshold: return "Below the burn threshold" + case .allContributor: return "All sessions on contributor models" + case .warning: return "Burn threshold exceeded on standard models" + } + } + } + + /// The standard-model sessions in one reading: the detector's presence + /// test over the reading's latest per-session observations. + public static func standardSessions(in report: MuseCodeSessionReport) -> [MuseCodeStandardSessionEvent] { + MuseCodeStandardSessionDetector.standardSessions( + in: report.latestObservations.map(MuseCodeSessionModelObservation.init)) + } + + /// The combined rule. "Exceeds" is strict: a window exactly at the + /// threshold has not exceeded it. The standard-model condition is + /// presence — at least one session in the reading is on a standard + /// model — never the contributor token share. + public static func evaluateBurn(report: MuseCodeSessionReport, + thresholdTokens: Int) -> BurnAlert? { + guard let window = report.window(minutes: windowMinutes), + window.totalTokens > thresholdTokens else { return nil } + let standard = standardSessions(in: report) + guard !standard.isEmpty else { return nil } + return BurnAlert(totalTokens: window.totalTokens, + thresholdTokens: thresholdTokens, + standardSessions: standard, + observedAt: report.generatedAt) + } + + public static func status(report: MuseCodeSessionReport?, issue: String?, + thresholdTokens: Int) -> Status { + guard let report else { return .storeUnavailable } + guard let window = report.window(minutes: windowMinutes), + window.totalTokens > 0 else { return .noActivity } + if let alert = evaluateBurn(report: report, thresholdTokens: thresholdTokens) { + return .warning(alert) + } + if standardSessions(in: report).isEmpty { + return .allContributor(totalTokens: window.totalTokens) + } + return .belowThreshold(totalTokens: window.totalTokens) + } +} diff --git a/Sources/QuotaCore/MuseCodeSessionIngest.swift b/Sources/QuotaCore/MuseCodeSessionIngest.swift new file mode 100644 index 00000000..f6a1ed75 --- /dev/null +++ b/Sources/QuotaCore/MuseCodeSessionIngest.swift @@ -0,0 +1,202 @@ +import Foundation + +/// The Muse bridge to Usage Monitor, built against the verified +/// session-event contract (Usage Monitor PR #1862): POST the v2 envelope to +/// `/api/ingest/usage` with the `muse-code` scoped producer token, one token +/// event per session observation. +/// +/// Delta discipline is the contract's core: a session's latest snapshot +/// total is cumulative for its current segment, so the bridge posts only the +/// positive delta since its previous observation — never the cumulative +/// total, which the server would sum into a double count. When a session's +/// segment resets (or its model changes), the new segment's total is the +/// delta. Event ids are stable per (session, snapshot, model), so a replay +/// after a failed post dedupes server-side instead of double-counting. +public enum MuseCodeSessionIngest { + public static let producerId = "muse-code" + public static let provider = "muse-code" + public static let service = "muse-code" + public static let source = "muse-session-stores" + public static let maxEventsPerBatch = 100 + public static let endpoint = URL(string: "https://usage.jays.services/api/ingest/usage")! + + public static func eventId(sessionId: String, snapshotId: String, modelId: String) -> String { + "codecaps-muse-code:\(sessionId):\(snapshotId):\(modelId)" + } + + public static func event(observation: MuseCodeSessionObservation, delta: Int) -> [String: Any] { + let metadata: [String: Any] = [ + "sessionId": observation.sessionId, + "contributor": observation.isContributor, + "source": source + ] + let event: [String: Any] = [ + "eventId": eventId(sessionId: observation.sessionId, + snapshotId: observation.snapshotId, + modelId: observation.modelId), + "provider": provider, + "service": service, + "producerKeyRef": observation.modelId, + "metricType": "usage", + "unit": "token", + "quantity": delta, + "billingMode": "estimated", + "confidence": "estimated", + "occurredAt": ISO8601DateFormatter().string(from: observation.observedAt), + "metadata": metadata + ] + return event + } + + public static func eventBatches(events: [[String: Any]]) -> [[[String: Any]]] { + stride(from: 0, to: events.count, by: maxEventsPerBatch).map { offset in + Array(events[offset.. Data { + let root: [String: Any] = [ + "schemaVersion": 2, + "producerId": producerId, + "events": events + ] + return try JSONSerialization.data(withJSONObject: root, options: [.sortedKeys]) + } +} + +/// One positive delta the bridge owes the server, with the observation it +/// came from. +public struct MuseCodePlannedEvent: Equatable, Sendable { + public let observation: MuseCodeSessionObservation + public let delta: Int + + public init(observation: MuseCodeSessionObservation, delta: Int) { + self.observation = observation + self.delta = delta + } +} + +/// Pure delta planning, so the discipline is testable without a server: the +/// previous observation per session in, the events to post and the baselines +/// to keep out. The caller persists `updated` only after every batch is +/// acknowledged, so a failed post retries the same deltas next refresh. +public enum MuseCodeDeltaPlanner { + public static let maxTrackedSessions = 1_024 + + public static func plan(observations: [MuseCodeSessionObservation], + previous: [String: MuseCodeSessionObservation]) + -> (events: [MuseCodePlannedEvent], updated: [String: MuseCodeSessionObservation]) { + var updated = previous + var events: [MuseCodePlannedEvent] = [] + for observation in observations { + let prior = previous[observation.sessionId] + let delta: Int + if let prior, prior.segmentKey == observation.segmentKey, + prior.modelId == observation.modelId { + delta = observation.totalTokens - prior.totalTokens + } else { + // First observation of the session, a segment reset, or a + // model switch: the current segment's total is the delta. + delta = observation.totalTokens + } + if delta > 0 { + events.append(MuseCodePlannedEvent(observation: observation, delta: delta)) + } + updated[observation.sessionId] = observation + } + if updated.count > maxTrackedSessions { + updated = Dictionary(uniqueKeysWithValues: updated.values + .sorted { $0.observedAt > $1.observedAt } + .prefix(maxTrackedSessions) + .map { ($0.sessionId, $0) }) + } + return (events, updated) + } +} + +/// Usage Monitor's ingest acknowledgment. A batch counts as delivered only +/// when the acknowledgment is complete: every counter present and +/// non-negative, `received` equal to the number sent, and the dispositions +/// adding up to `received`. +public struct MuseCodeIngestAcknowledgment: Decodable, Equatable, Sendable { + public let received: Int + public let persisted: Int + public let duplicates: Int + public let pruned: Int + public let rejected: Int + + public func isComplete(sent: Int) -> Bool { + let counts = [received, persisted, duplicates, pruned, rejected] + guard counts.allSatisfy({ $0 >= 0 }), received == sent else { return false } + // Subtract from the bounded sent count, so hostile counts cannot + // overflow while checking the complete disposition of the batch. + var unaccounted = received + for count in [persisted, duplicates, pruned, rejected] { + guard count <= unaccounted else { return false } + unaccounted -= count + } + return unaccounted == 0 + } +} + +public struct MuseCodeIngestSummary: Equatable, Sendable { + public var sent: Int + public var persisted: Int + public var duplicates: Int + public var pruned: Int + public var rejected: Int + + public init(sent: Int = 0, persisted: Int = 0, duplicates: Int = 0, + pruned: Int = 0, rejected: Int = 0) { + self.sent = sent + self.persisted = persisted + self.duplicates = duplicates + self.pruned = pruned + self.rejected = rejected + } +} + +/// Posts Muse token events to Usage Monitor's `/api/ingest/usage`, in +/// batches of at most 100 events, with the v2 telemetry headers. +public struct MuseCodeSessionPoster: Sendable { + private let transport: @Sendable (URLRequest) async throws -> (Data, HTTPURLResponse) + + public init(transport: (@Sendable (URLRequest) async throws -> (Data, HTTPURLResponse))? = nil) { + self.transport = transport ?? { request in + let (data, response) = try await URLSession.shared.data(for: request) + guard let http = response as? HTTPURLResponse else { + throw QuotaPublisherError.transport("Invalid response.") + } + return (data, http) + } + } + + public func publish(events: [[String: Any]], to endpoint: URL, token: String?) async throws -> MuseCodeIngestSummary { + var summary = MuseCodeIngestSummary() + for batch in MuseCodeSessionIngest.eventBatches(events: events) { + var request = URLRequest(url: endpoint) + request.httpMethod = "POST" + request.setValue("application/json", forHTTPHeaderField: "content-type") + request.setValue("2", forHTTPHeaderField: "x-usage-telemetry-version") + if let token = token.map(sanitizedToken(_:)), !token.isEmpty { + request.setValue("Bearer \(token)", forHTTPHeaderField: "Authorization") + } + request.httpBody = try MuseCodeSessionIngest.batchData(events: batch) + let (data, http) = try await transport(request) + guard (200..<300).contains(http.statusCode) else { + throw QuotaPublisherError.httpStatus(http.statusCode, nil) + } + guard let acknowledgment = try? JSONDecoder().decode(MuseCodeIngestAcknowledgment.self, from: data), + acknowledgment.isComplete(sent: batch.count) else { + throw QuotaPublisherError.serverError( + "Usage Monitor returned an incomplete ingest acknowledgment.") + } + summary.sent += batch.count + summary.persisted += acknowledgment.persisted + summary.duplicates += acknowledgment.duplicates + summary.pruned += acknowledgment.pruned + summary.rejected += acknowledgment.rejected + } + return summary + } +} diff --git a/Sources/QuotaCore/MuseCodeSessionReader.swift b/Sources/QuotaCore/MuseCodeSessionReader.swift new file mode 100644 index 00000000..f38b341c --- /dev/null +++ b/Sources/QuotaCore/MuseCodeSessionReader.swift @@ -0,0 +1,352 @@ +import Foundation + +/// One distinct conversation segment observed in a Muse session snapshot. +/// +/// A segment is the unit the fleet's survey scripts proved additive: distinct +/// source ranges inside one session sum to the session's burn, while the same +/// range re-read from a later snapshot is the same segment, never new burn. +public struct MuseCodeTokenSegment: Equatable, Sendable { + public let sessionId: String + public let modelId: String + public let totalTokens: Int + public let promptTokens: Int? + public let observedAt: Date + public let sourceFirstId: String? + public let sourceLastId: String? + + public init(sessionId: String, modelId: String, totalTokens: Int, promptTokens: Int? = nil, + observedAt: Date, sourceFirstId: String? = nil, sourceLastId: String? = nil) { + self.sessionId = sessionId + self.modelId = modelId + self.totalTokens = totalTokens + self.promptTokens = promptTokens + self.observedAt = observedAt + self.sourceFirstId = sourceFirstId + self.sourceLastId = sourceLastId + } + + /// The segment's identity inside its session, matching the dedupe key the + /// survey scripts use: (sourceRange first id, last id, model, total). + public var dedupeKey: String { + [sourceFirstId ?? "", sourceLastId ?? "", modelId, String(totalTokens)] + .joined(separator: "\u{1}") + } + + public var isContributor: Bool { modelId.hasSuffix("-contributor") } +} + +/// Token totals for one model inside one trailing window. +public struct MuseCodeModelUsage: Equatable, Sendable, Identifiable { + public let modelId: String + public let tokens: Int + public let segmentCount: Int + public let sessionCount: Int + + public var id: String { modelId } + public var isContributor: Bool { modelId.hasSuffix("-contributor") } + + public init(modelId: String, tokens: Int, segmentCount: Int, sessionCount: Int) { + self.modelId = modelId + self.tokens = tokens + self.segmentCount = segmentCount + self.sessionCount = sessionCount + } + + public func share(of total: Int) -> Double { + total > 0 ? Double(tokens) / Double(total) : 0 + } +} + +/// Aggregated Muse burn for one trailing window. +public struct MuseCodeWindowUsage: Equatable, Sendable { + public let windowMinutes: Int + public let totalTokens: Int + public let contributorTokens: Int + /// Nil when the window has no tokens at all: no burn is neither 0% nor + /// 100% contributor, and the monitor must not treat it as either. + public let contributorShare: Double? + public let activeSessions: Int + public let models: [MuseCodeModelUsage] + + public init(windowMinutes: Int, totalTokens: Int, contributorTokens: Int, + contributorShare: Double?, activeSessions: Int, models: [MuseCodeModelUsage]) { + self.windowMinutes = windowMinutes + self.totalTokens = totalTokens + self.contributorTokens = contributorTokens + self.contributorShare = contributorShare + self.activeSessions = activeSessions + self.models = models + } + + public var standardModels: [MuseCodeModelUsage] { + models.filter { !$0.isContributor && $0.tokens > 0 } + } + + public var tokensPerHour: Double { + Double(totalTokens) * 60 / Double(windowMinutes) + } +} + +/// A session's latest snapshot observation: the bridge's unit of work. +/// +/// The Usage Monitor bridge contract is defined over latest snapshots, not +/// over the segment sum the local monitor uses: per session, the latest +/// snapshot's `tokenUsage.totalTokens` is cumulative for its current +/// segment, and only the positive delta since the previous observation may +/// be posted. +public struct MuseCodeSessionObservation: Equatable, Sendable, Codable { + public let sessionId: String + public let snapshotId: String + public let modelId: String + public let totalTokens: Int + /// Identifies the segment the cumulative total belongs to (the token + /// usage's source-range start). A changed key means the segment reset, + /// and the new segment's total is the delta. + public let segmentKey: String + public let observedAt: Date + + public init(sessionId: String, snapshotId: String, modelId: String, + totalTokens: Int, segmentKey: String, observedAt: Date) { + self.sessionId = sessionId + self.snapshotId = snapshotId + self.modelId = modelId + self.totalTokens = totalTokens + self.segmentKey = segmentKey + self.observedAt = observedAt + } + + public var isContributor: Bool { modelId.hasSuffix("-contributor") } +} + +/// One reading of the Muse session store: per-window aggregates for the +/// local monitor, plus each active session's latest observation for the +/// Usage Monitor bridge. +public struct MuseCodeSessionReport: Equatable, Sendable { + public let generatedAt: Date + public let windows: [MuseCodeWindowUsage] + public let segments: [MuseCodeTokenSegment] + public let latestObservations: [MuseCodeSessionObservation] + + public init(generatedAt: Date, windows: [MuseCodeWindowUsage], + segments: [MuseCodeTokenSegment] = [], + latestObservations: [MuseCodeSessionObservation] = []) { + self.generatedAt = generatedAt + self.windows = windows + self.segments = segments + self.latestObservations = latestObservations + } + + public func window(minutes: Int) -> MuseCodeWindowUsage? { + windows.first { $0.windowMinutes == minutes } + } +} + +/// The reader's result, in the shape every QuotaCore reader uses: data or a +/// user-safe issue, never a throw to the caller. +public struct MuseCodeSessionResult: Equatable, Sendable { + public let report: MuseCodeSessionReport? + public let issue: String? + + public init(report: MuseCodeSessionReport?, issue: String?) { + self.report = report + self.issue = issue + } +} + +/// Reads the Muse session stores on this Mac. +/// +/// Muse writes one directory per session under +/// `~/.local/share/muse/sessions/.msp-view-g6//`, with a HEAD.json +/// naming the latest snapshot and `snapshot-.json` files whose +/// `continuation.view_materialization.current_state.tokenUsage` carries the +/// model and token total for one conversation segment. This reader scans the +/// snapshot files directly (the newest snapshot in a directory is the one +/// HEAD.json names), which covers both the latest-segment and the +/// segment-summed views the fleet's surveys validated. +public struct MuseCodeSessionReader: Sendable { + public static let storeRelativePath = ".local/share/muse/sessions/.msp-view-g6" + public static let windowMinutes = [60, 90] + + private static let maxSessionDirectories = 512 + private static let maxSnapshotsPerSession = 512 + private static let maxSnapshotBytes = 33_554_432 + private static let futureTolerance: TimeInterval = 120 + + private let homeDirectory: URL + private let now: @Sendable () -> Date + + public init(homeDirectory: URL = FileManager.default.homeDirectoryForCurrentUser, + now: @escaping @Sendable () -> Date = { Date() }) { + self.homeDirectory = homeDirectory.standardizedFileURL + self.now = now + } + + public func read() -> MuseCodeSessionResult { + let instant = now() + let root = homeDirectory.appendingPathComponent(Self.storeRelativePath, isDirectory: true) + var isDirectory: ObjCBool = false + guard FileManager.default.fileExists(atPath: root.path, isDirectory: &isDirectory), + isDirectory.boolValue else { + return MuseCodeSessionResult( + report: nil, + issue: "Muse session store was not found on this Mac.") + } + let cutoff = instant.addingTimeInterval(-90 * 60) + var segments: [MuseCodeTokenSegment] = [] + var activity: [String: Date] = [:] + var observations: [MuseCodeSessionObservation] = [] + let entries = (try? FileManager.default.contentsOfDirectory( + at: root, includingPropertiesForKeys: [.isDirectoryKey, .contentModificationDateKey])) ?? [] + let sessionDirs = entries + .filter { (try? $0.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true } + .sorted { Self.modification(of: $0) > Self.modification(of: $1) } + .prefix(Self.maxSessionDirectories) + for directory in sessionDirs { + let sessionId = directory.lastPathComponent + guard let files = try? FileManager.default.contentsOfDirectory( + at: directory, + includingPropertiesForKeys: [.contentModificationDateKey, .fileSizeKey]) else { continue } + let dated: [(url: URL, modified: Date, size: Int)] = files.map { url in + let values = try? url.resourceValues(forKeys: [.contentModificationDateKey, .fileSizeKey]) + return (url, values?.contentModificationDate ?? .distantPast, values?.fileSize ?? 0) + } + // A session counts as active in a window when any of its files — + // HEAD.json included — was written inside it, the same activity + // test the survey scripts use. + guard let newest = dated.map(\.modified).max(), newest >= cutoff else { continue } + activity[sessionId] = newest + let snapshots = dated + .filter { $0.url.lastPathComponent.hasPrefix("snapshot-") + && $0.url.pathExtension == "json" && $0.modified >= cutoff } + .sorted { $0.modified < $1.modified } + .prefix(Self.maxSnapshotsPerSession) + var parsed: [(snapshotId: String?, segment: MuseCodeTokenSegment)] = [] + for snapshot in snapshots { + if let segment = Self.segment(sessionId: sessionId, url: snapshot.url, + modified: snapshot.modified, size: snapshot.size) { + segments.append(segment) + parsed.append((Self.snapshotId(from: snapshot.url), segment)) + } + } + // The session's latest observation, for the bridge: the snapshot + // HEAD.json names when it was parsed, otherwise the newest one. + let headId = Self.headSnapshotId(in: dated) + let chosen = parsed.first { $0.snapshotId != nil && $0.snapshotId == headId } + ?? parsed.max { $0.segment.observedAt < $1.segment.observedAt } + if let chosen { + observations.append(MuseCodeSessionObservation( + sessionId: sessionId, + snapshotId: chosen.snapshotId ?? "", + modelId: chosen.segment.modelId, + totalTokens: chosen.segment.totalTokens, + segmentKey: chosen.segment.sourceFirstId ?? "", + observedAt: chosen.segment.observedAt)) + } + } + return MuseCodeSessionResult( + report: Self.aggregate(segments: segments, sessionActivity: activity, + latestObservations: observations.sorted { $0.sessionId < $1.sessionId }, + now: instant), + issue: nil) + } + + private static func snapshotId(from url: URL) -> String? { + let name = url.lastPathComponent + guard name.hasPrefix("snapshot-"), name.hasSuffix(".json") else { return nil } + return String(name.dropFirst("snapshot-".count).dropLast(".json".count)) + } + + private static func headSnapshotId(in files: [(url: URL, modified: Date, size: Int)]) -> String? { + guard let head = files.first(where: { $0.url.lastPathComponent == "HEAD.json" }), + head.size > 0, head.size <= 1_048_576, + let data = try? Data(contentsOf: head.url), + let root = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any], + let id = root["latest_snapshot_id"] as? String, !id.isEmpty else { return nil } + return id + } + + private static func modification(of url: URL) -> Date { + (try? url.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate) + ?? .distantPast + } + + private static func segment(sessionId: String, url: URL, modified: Date, size: Int) -> MuseCodeTokenSegment? { + guard size > 0, size <= maxSnapshotBytes, + let data = try? Data(contentsOf: url), + let root = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any], + let continuation = root["continuation"] as? [String: Any], + let materialization = continuation["view_materialization"] as? [String: Any], + let state = materialization["current_state"] as? [String: Any], + let usage = state["tokenUsage"] as? [String: Any], + let modelId = usage["modelId"] as? String, !modelId.isEmpty, + let total = number(usage["totalTokens"]), total >= 0 else { return nil } + let range = usage["sourceRange"] as? [String: Any] + return MuseCodeTokenSegment( + sessionId: sessionId, + modelId: modelId, + totalTokens: Int(total.rounded()), + promptTokens: number(usage["promptTokens"]).map { Int($0.rounded()) }, + observedAt: modified, + sourceFirstId: (range?["first"] as? [String: Any])?["id"] as? String, + sourceLastId: (range?["last"] as? [String: Any])?["id"] as? String) + } + + private static func number(_ raw: Any?) -> Double? { + guard let value = raw as? NSNumber, CFGetTypeID(value) != CFBooleanGetTypeID(), + value.doubleValue.isFinite else { return nil } + return value.doubleValue + } + + /// The aggregation the surveys validated, as a pure function so it can be + /// tested without a session store: dedupe segments per session by source + /// range, then sum per model inside each trailing window. + public static func aggregate(segments raw: [MuseCodeTokenSegment], + sessionActivity: [String: Date], + latestObservations: [MuseCodeSessionObservation] = [], + now: Date) -> MuseCodeSessionReport { + // The stores rotate snapshots aggressively: a segment whose snapshot + // file has already been rotated away is invisible here, and a session + // that ends mid-window leaves only the segments still on disk. Every + // total this aggregation produces is therefore a floor, not an exact + // count — the plugin page says so wherever it shows these numbers. + var seen = Set() + var segments: [MuseCodeTokenSegment] = [] + for segment in raw.sorted(by: { $0.observedAt < $1.observedAt }) { + guard seen.insert(segment.sessionId + "\u{1}" + segment.dedupeKey).inserted else { continue } + segments.append(segment) + } + let horizon = now.addingTimeInterval(futureTolerance) + let windows = windowMinutes.map { minutes -> MuseCodeWindowUsage in + let cutoff = now.addingTimeInterval(-Double(minutes) * 60) + var byModel: [String: (tokens: Int, segments: Int, sessions: Set)] = [:] + for segment in segments where segment.observedAt >= cutoff && segment.observedAt <= horizon { + var entry = byModel[segment.modelId] ?? (tokens: 0, segments: 0, sessions: []) + entry.tokens += segment.totalTokens + entry.segments += 1 + entry.sessions.insert(segment.sessionId) + byModel[segment.modelId] = entry + } + let models = byModel + .map { MuseCodeModelUsage(modelId: $0.key, tokens: $0.value.tokens, + segmentCount: $0.value.segments, + sessionCount: $0.value.sessions.count) } + .sorted { $0.tokens != $1.tokens ? $0.tokens > $1.tokens : $0.modelId < $1.modelId } + let total = models.reduce(0) { $0 + $1.tokens } + let contributor = models.filter(\.isContributor).reduce(0) { $0 + $1.tokens } + let active = sessionActivity.filter { $0.value >= cutoff && $0.value <= horizon }.count + return MuseCodeWindowUsage( + windowMinutes: minutes, + totalTokens: total, + contributorTokens: contributor, + contributorShare: total > 0 ? Double(contributor) / Double(total) : nil, + activeSessions: active, + models: models) + } + let cutoff90 = now.addingTimeInterval(-90 * 60) + return MuseCodeSessionReport( + generatedAt: now, + windows: windows, + segments: segments.filter { $0.observedAt >= cutoff90 && $0.observedAt <= horizon }, + latestObservations: latestObservations) + } +} diff --git a/Sources/QuotaCore/MuseCodeStandardSessionDetector.swift b/Sources/QuotaCore/MuseCodeStandardSessionDetector.swift new file mode 100644 index 00000000..a279a975 --- /dev/null +++ b/Sources/QuotaCore/MuseCodeStandardSessionDetector.swift @@ -0,0 +1,146 @@ +import Foundation + +/// One muse-code session's current model, as one poll of the session store +/// observed it. This is the detector's input, kept separate from the +/// reader's `MuseCodeSessionObservation` because a session whose current +/// segment carries no model id must be representable: `modelId` is nil for +/// such a session, and a nil model is never an event. +public struct MuseCodeSessionModelObservation: Equatable, Sendable { + public let sessionId: String + public let modelId: String? + public let observedAt: Date + + public init(sessionId: String, modelId: String?, observedAt: Date) { + self.sessionId = sessionId + self.modelId = modelId + self.observedAt = observedAt + } + + /// Adapts the reader's latest observation for one session. The reader + /// only emits observations for snapshots that carry a model, so the + /// adapted `modelId` is never nil today; the detector still tolerates + /// nil for any future source that can produce one. + public init(_ observation: MuseCodeSessionObservation) { + self.init(sessionId: observation.sessionId, + modelId: observation.modelId, + observedAt: observation.observedAt) + } +} + +/// A standard-model session event: one firing of the +/// `museCodeStandardSession` alert kind. The payload names the session, +/// the model it is on, and when it was observed — the three facts that say +/// which run of work left the contributor models. +public struct MuseCodeStandardSessionEvent: Equatable, Sendable { + public let sessionId: String + public let modelId: String + public let observedAt: Date + + public init(sessionId: String, modelId: String, observedAt: Date) { + self.sessionId = sessionId + self.modelId = modelId + self.observedAt = observedAt + } + + public var title: String { "Muse Standard Model Session" } + + public var body: String { + "Session \(sessionId) is running on the standard model \(modelId)." + + sentenceGap + + "Observed at \(observedAt.formatted(date: .abbreviated, time: .standard))." + } +} + +/// Event-based detection of standard-model Muse sessions. +/// +/// This replaces the contributor token share as the monitor's contributor +/// finding. A share computed from rotating session snapshots moves for +/// reasons unrelated to the question — stale sessions inside the window, +/// token weight, last-segment attribution — and reads below 100% even when +/// every live session is on a contributor model. Presence has no such +/// noise: a session either is on a standard model or it is not. +/// +/// The detector is a small state machine over polls. It remembers the last +/// model each session was observed on and fires exactly when a session +/// enters a standard model: +/// +/// - a session observed for the first time, already on a standard model; +/// - a session whose model changed from a contributor model to a standard +/// model. +/// +/// A session that stays on the same standard model across polls does not +/// refire. A session that returns to a contributor model re-arms, so going +/// standard again is a new event. Observations with no model id are +/// ignored entirely — they neither fire nor touch the tracked state — so a +/// model-less segment can neither manufacture an event nor mask a later +/// contributor-to-standard switch. +/// +/// The state is `Codable` so the owner of the detector can persist it with +/// the same JSON-in-UserDefaults pattern the plugin already uses for the +/// Usage Monitor bridge baselines, and detection survives app relaunches. +public struct MuseCodeStandardSessionDetector: Codable, Equatable, Sendable { + /// The last model each tracked session was observed on, by session id. + /// Only model-bearing observations are recorded, so a session absent + /// here has never been observed with a model. + public private(set) var lastKnownModels: [String: String] + + public init(lastKnownModels: [String: String] = [:]) { + self.lastKnownModels = lastKnownModels + } + + /// A contributor model is a model id ending in `-contributor`. + public static func isContributor(modelId: String) -> Bool { + modelId.hasSuffix("-contributor") + } + + /// A standard model is any non-empty model id that is not a contributor + /// model. A missing model id is not standard — it is no information. + public static func isStandard(modelId: String?) -> Bool { + guard let modelId, !modelId.isEmpty else { return false } + return !isContributor(modelId: modelId) + } + + /// Feeds one poll's session observations and returns the events that + /// fire, in observation order. + /// + /// On the first poll after install the tracked state is empty, so every + /// session in that first scan counts as first-observed and fires if it + /// is on a standard model. That is deliberate: a standard session that + /// was already running when the monitor was installed is still a + /// standard session, and suppressing it would hide exactly the finding + /// the alert exists for. + @discardableResult + public mutating func observe( + _ observations: [MuseCodeSessionModelObservation] + ) -> [MuseCodeStandardSessionEvent] { + var events: [MuseCodeStandardSessionEvent] = [] + for observation in observations { + guard let modelId = observation.modelId, !modelId.isEmpty else { continue } + let previous = lastKnownModels[observation.sessionId] + let wasContributor = previous.map { Self.isContributor(modelId: $0) } ?? false + if Self.isStandard(modelId: modelId), previous == nil || wasContributor { + events.append(MuseCodeStandardSessionEvent( + sessionId: observation.sessionId, modelId: modelId, + observedAt: observation.observedAt)) + } + lastKnownModels[observation.sessionId] = modelId + } + return events + } + + /// The sessions in one poll whose current model is standard, as events + /// with no firing semantics: the presence test the burn rule uses. A + /// standard session that has been running for an hour still counts here + /// even though its start event fired long ago. + public static func standardSessions( + in observations: [MuseCodeSessionModelObservation] + ) -> [MuseCodeStandardSessionEvent] { + observations.compactMap { observation in + guard let modelId = observation.modelId, + isStandard(modelId: modelId) else { return nil } + return MuseCodeStandardSessionEvent(sessionId: observation.sessionId, + modelId: modelId, + observedAt: observation.observedAt) + } + } +} diff --git a/Sources/QuotaCore/UsageAlertPreferences.swift b/Sources/QuotaCore/UsageAlertPreferences.swift index 39190ce1..df0b2d2e 100644 --- a/Sources/QuotaCore/UsageAlertPreferences.swift +++ b/Sources/QuotaCore/UsageAlertPreferences.swift @@ -31,8 +31,20 @@ public struct CompanionPushRemovalAcknowledgment: Decodable { } /// Stable categories shared by Mac, companion, and remote notification payloads. +/// +/// Raw values are the stable alert-kind identifiers every delivery channel +/// selects on — including a future per-kind channel opt-in — so a case's +/// raw value must never be renamed once shipped. public enum UsageAlertKind: String, CaseIterable, Codable, Sendable, Identifiable { case anomaly, runaway, vendorReset, quotaReset, quotaExhaustion + // Renamed before the plugin's first release: this kind was + // `museCodeContributorBelow100` while the finding was a contributor + // token share. The finding is now event-based (a session on a standard + // model), so the identifier names that instead. Preferences are stored + // keyed by raw-value strings, so an install that saved options under + // the old key simply never reads that entry again, and `load` backfills + // this kind from its shipped default — no migration is needed. + case museCodeBurn, museCodeStandardSession public var id: String { rawValue } public var title: String { @@ -42,6 +54,8 @@ public enum UsageAlertKind: String, CaseIterable, Codable, Sendable, Identifiabl case .vendorReset: return "Vendor Quota Resets" case .quotaReset: return "Scheduled Quota Resets" case .quotaExhaustion: return "Quota Exhaustion" + case .museCodeBurn: return "Muse Burn" + case .museCodeStandardSession: return "Muse Standard Sessions" } } public var detail: String { @@ -51,6 +65,8 @@ public enum UsageAlertKind: String, CaseIterable, Codable, Sendable, Identifiabl case .vendorReset: return "A provider restores quota before its scheduled reset." case .quotaReset: return "A quota window resets on schedule." case .quotaExhaustion: return "A quota window reaches its limit." + case .museCodeBurn: return "Muse token burn passes the plugin threshold on standard models." + case .museCodeStandardSession: return "A Muse session starts on, or switches to, a standard model." } } } @@ -96,7 +112,14 @@ public struct UsageAlertPreferences: Codable, Equatable, Sendable { resetEnabled: Bool, resetSound: ResetAlarmSound, runawayEnabled: Bool = false) -> Self { if let data = defaults.data(forKey: key), - let saved = try? JSONDecoder().decode(Self.self, from: data) { + var saved = try? JSONDecoder().decode(Self.self, from: data) { + // Kinds added after the owner's preferences were first saved + // start from their shipped default rather than the subscript's + // disabled fallback, until the owner changes them. + for kind in [UsageAlertKind.museCodeBurn, .museCodeStandardSession] + where saved.options[kind.rawValue] == nil { + saved[kind] = UsageAlertOption(enabled: true) + } return saved } var result = Self() @@ -106,6 +129,10 @@ public struct UsageAlertPreferences: Codable, Equatable, Sendable { case .quotaReset, .vendorReset: enabled = resetEnabled case .anomaly, .runaway: enabled = runawayEnabled case .quotaExhaustion: enabled = false + // The Muse monitor is the feature these kinds exist for, so + // they ship enabled; the owner can turn either off in + // Alerts & Alarms without touching the other. + case .museCodeBurn, .museCodeStandardSession: enabled = true } result[kind] = UsageAlertOption(enabled: enabled, sound: resetSound) } diff --git a/Tests/CodeCapsTests/MuseCodePluginTests.swift b/Tests/CodeCapsTests/MuseCodePluginTests.swift new file mode 100644 index 00000000..3432c7de --- /dev/null +++ b/Tests/CodeCapsTests/MuseCodePluginTests.swift @@ -0,0 +1,244 @@ +import XCTest +@testable import CodeCaps +import QuotaCore + +@MainActor +private final class SpyAlertChannel: CodeCapsAlertChannel { + var events: [CodeCapsAlertEvent] = [] + func deliver(_ event: CodeCapsAlertEvent) { events.append(event) } +} + +@MainActor +final class MuseCodePluginTests: XCTestCase { + private var suiteName = "" + private var defaults: UserDefaults! + + override func setUp() { + super.setUp() + suiteName = "MuseCodePluginTests." + UUID().uuidString + defaults = UserDefaults(suiteName: suiteName)! + } + + override func tearDown() { + defaults.removePersistentDomain(forName: suiteName) + defaults = nil + super.tearDown() + } + + // MARK: - Navigation and registry + + func testPluginPageRoundTripsThroughStorageKey() { + let page = ConsolePage.plugin("muse-code") + XCTAssertEqual(page.storageKey, "plugin:muse-code") + XCTAssertEqual(ConsolePage.fromStorageKey(page.storageKey), page) + XCTAssertFalse(page.isSettings) + XCTAssertEqual(page.settingsTitle, "Muse") + XCTAssertTrue(ConsolePage.pluginPages.contains(page)) + } + + func testPluginPageSurvivesReconcileWithoutQuotaRows() { + defaults.set("plugin:muse-code", forKey: "consoleLastPage") + let state = ConsoleState(defaults: defaults) + XCTAssertEqual(state.page, .plugin("muse-code")) + state.reconcile(available: [], readCompleted: true) + XCTAssertEqual(state.page, .plugin("muse-code"), + "a plugin page is local and never falls back to a platform") + } + + func testAlertKindsHaveStableIdentifiersAndShipEnabled() { + XCTAssertEqual(UsageAlertKind.museCodeBurn.rawValue, "museCodeBurn") + XCTAssertEqual(UsageAlertKind.museCodeStandardSession.rawValue, + "museCodeStandardSession") + let manager = ResetAlarmManager(defaults: defaults) + XCTAssertTrue(manager.preferences[.museCodeBurn].enabled) + XCTAssertTrue(manager.preferences[.museCodeStandardSession].enabled) + } + + func testStandardSessionPopupShipsOffAndPersistsWhenEnabled() { + let manager = ResetAlarmManager(defaults: defaults) + XCTAssertFalse(manager.preferences[.museCodeStandardSession].popup, + "the popup warning is opt-in and ships off") + var option = manager.preferences[.museCodeStandardSession] + option.popup = true + manager.preferences[.museCodeStandardSession] = option + let reloaded = ResetAlarmManager(defaults: defaults) + XCTAssertTrue(reloaded.preferences[.museCodeStandardSession].popup, + "the plugin page and Alerts & Alarms edit one stored preference") + } + + func testStandardSessionDeliveryCarriesThePopupOption() { + let (model, spy) = makeModel() + var delivered: [(kind: UsageAlertKind, option: UsageAlertOption)] = [] + model.alarmManager.onUsageDelivery = { kind, _, _, option in + delivered.append((kind, option)) + } + var option = model.alarmManager.preferences[.museCodeStandardSession] + option.popup = true + model.alarmManager.preferences[.museCodeStandardSession] = option + model.applyMuseCodeResult(result(total: 3_000_000, contributor: 2_000_000)) + XCTAssertEqual(spy.events.map(\.kind), [.museCodeStandardSession]) + XCTAssertEqual(delivered.map(\.kind), [.museCodeStandardSession]) + XCTAssertTrue(delivered.first?.option.popup == true, + "delivery reads the same popup option the plugin toggle sets") + } + + // MARK: - Monitor glue + + private func makeModel() -> (MonitorModel, SpyAlertChannel) { + let model = MonitorModel(defaults: defaults) + model.skipsSnapshotIOForTesting = true + let spy = SpyAlertChannel() + model.alertDispatcher.register(spy) + // Swallow the local channel so no test reaches the notification centre. + model.alarmManager.onUsageDelivery = { _, _, _, _ in } + return (model, spy) + } + + /// A reading whose window totals `total` tokens, `contributor` of them + /// on a contributor session; the rest, when any, sit on a standard + /// session. Callers may pass explicit observations instead — the bridge + /// tests do — in which case they are used as given. + private func result(total: Int, contributor: Int, + observations: [MuseCodeSessionObservation]? = nil) -> MuseCodeSessionResult { + var models: [MuseCodeModelUsage] = [] + var derived: [MuseCodeSessionObservation] = [] + if contributor > 0 { + models.append(MuseCodeModelUsage(modelId: "muse-spark-1.3-contributor", + tokens: contributor, segmentCount: 1, sessionCount: 1)) + derived.append(MuseCodeSessionObservation( + sessionId: "s-contributor", snapshotId: "snap-c", + modelId: "muse-spark-1.3-contributor", totalTokens: contributor, + segmentKey: "seg-c", observedAt: Date())) + } + if total > contributor { + models.append(MuseCodeModelUsage(modelId: "muse-wonder-1.0", tokens: total - contributor, + segmentCount: 1, sessionCount: 1)) + derived.append(MuseCodeSessionObservation( + sessionId: "s-standard", snapshotId: "snap-s", + modelId: "muse-wonder-1.0", totalTokens: total - contributor, + segmentKey: "seg-s", observedAt: Date())) + } + let window = MuseCodeWindowUsage( + windowMinutes: 90, totalTokens: total, contributorTokens: contributor, + contributorShare: total > 0 ? Double(contributor) / Double(total) : nil, + activeSessions: models.count, models: models) + return MuseCodeSessionResult( + report: MuseCodeSessionReport(generatedAt: Date(), windows: [window], + latestObservations: observations ?? derived), + issue: nil) + } + + func testOverThresholdMixedReadingEmitsBothAlertKinds() { + let (model, spy) = makeModel() + model.applyMuseCodeResult(result(total: 5_000_000, contributor: 4_000_000)) + model.applyMuseCodeResult(result(total: 5_000_000, contributor: 4_000_000)) + XCTAssertEqual(spy.events.map(\.kind), [.museCodeBurn, .museCodeStandardSession], + "the repeat reading re-fires neither kind: burn is in cooldown, the session is already reported") + XCTAssertNotNil(model.museCodeBurnAlert) + XCTAssertEqual(model.museCodeStandardSessionAlert?.sessionId, "s-standard") + XCTAssertTrue(spy.events.first?.body.contains("muse-wonder-1.0") == true) + XCTAssertTrue(spy.events.last?.body.contains("s-standard") == true, + "the standard-session event names the session") + } + + func testAllContributorReadingEmitsNothing() { + let (model, spy) = makeModel() + model.applyMuseCodeResult(result(total: 9_000_000, contributor: 9_000_000)) + XCTAssertTrue(spy.events.isEmpty) + XCTAssertNil(model.museCodeBurnAlert) + XCTAssertNil(model.museCodeStandardSessionAlert) + } + + func testBelowThresholdReadingEmitsOnlyTheStandardSessionKind() { + let (model, spy) = makeModel() + model.applyMuseCodeResult(result(total: 3_000_000, contributor: 2_000_000)) + XCTAssertEqual(spy.events.map(\.kind), [.museCodeStandardSession], + "the standard-session finding is its own event, not a burn side effect") + XCTAssertNil(model.museCodeBurnAlert) + XCTAssertNotNil(model.museCodeStandardSessionAlert) + } + + func testStandardSessionEventFiresOnSwitchAndRefiresAfterRecovery() { + let (model, spy) = makeModel() + func reading(modelId: String) -> MuseCodeSessionResult { + let observation = MuseCodeSessionObservation( + sessionId: "s1", snapshotId: "snap", modelId: modelId, + totalTokens: 100, segmentKey: "seg", observedAt: Date()) + return result(total: 100, + contributor: modelId.hasSuffix("-contributor") ? 100 : 0, + observations: [observation]) + } + model.applyMuseCodeResult(reading(modelId: "muse-spark-1.3-contributor")) + XCTAssertTrue(spy.events.isEmpty) + model.applyMuseCodeResult(reading(modelId: "muse-wonder-1.0")) + model.applyMuseCodeResult(reading(modelId: "muse-wonder-1.0")) + XCTAssertEqual(spy.events.filter { $0.kind == .museCodeStandardSession }.count, 1, + "the switch fires once; staying on the standard model does not refire") + model.applyMuseCodeResult(reading(modelId: "muse-spark-1.3-contributor")) + model.applyMuseCodeResult(reading(modelId: "muse-wonder-1.0")) + XCTAssertEqual(spy.events.filter { $0.kind == .museCodeStandardSession }.count, 2, + "returning to a contributor model re-arms the session") + XCTAssertEqual(model.museCodeStandardSessionAlert?.sessionId, "s1") + } + + func testStandardSessionStateSurvivesModelRecreation() { + let (model, spy) = makeModel() + model.applyMuseCodeResult(result(total: 3_000_000, contributor: 2_000_000)) + XCTAssertEqual(spy.events.filter { $0.kind == .museCodeStandardSession }.count, 1) + // A fresh model over the same defaults stands in for an app + // relaunch: the persisted detector state must keep the already + // reported standard session from firing again. + let (relaunched, relaunchedSpy) = makeModel() + relaunched.applyMuseCodeResult(result(total: 3_000_000, contributor: 2_000_000)) + XCTAssertTrue(relaunchedSpy.events.isEmpty, + "the standard session was already reported before the relaunch") + XCTAssertNil(relaunched.museCodeStandardSessionAlert) + } + + func testDisabledAlertsEmitNothing() { + let (model, spy) = makeModel() + model.museCodeBurnAlertsEnabled = false + model.applyMuseCodeResult(result(total: 5_000_000, contributor: 4_000_000)) + XCTAssertTrue(spy.events.isEmpty) + XCTAssertNil(model.museCodeBurnAlert) + XCTAssertNil(model.museCodeStandardSessionAlert) + } + + // MARK: - Bridge + + func testBridgePostsDeltasOnceAndAdvancesBaseline() async { + let model = MonitorModel(defaults: defaults) + model.skipsSnapshotIOForTesting = true + model.alarmManager.onUsageDelivery = { _, _, _, _ in } + var posted: [[String: Any]] = [] + model.museCodeTokenReadForTesting = { "scoped-token" } + model.museCodePublishForTesting = { events, _, token in + XCTAssertEqual(token, "scoped-token") + posted = events + return MuseCodeIngestSummary(sent: events.count, persisted: events.count) + } + model.museCodeUsageBridgeEnabled = true + let observation = MuseCodeSessionObservation( + sessionId: "s1", snapshotId: "snap1", modelId: "muse-spark-1.3-contributor", + totalTokens: 700, segmentKey: "seg-a", observedAt: Date()) + model.applyMuseCodeResult(result(total: 700, contributor: 700, observations: [observation])) + await waitForBridgeStatus(model) { $0?.contains("Posted 1 token events") == true } + XCTAssertEqual(posted.count, 1) + XCTAssertEqual(posted.first?["quantity"] as? Int, 700) + XCTAssertEqual(posted.first?["eventId"] as? String, + "codecaps-muse-code:s1:snap1:muse-spark-1.3-contributor") + + model.applyMuseCodeResult(result(total: 700, contributor: 700, observations: [observation])) + await waitForBridgeStatus(model) { $0 == "No new Muse tokens to post." } + XCTAssertEqual(posted.count, 1, "the same cumulative total is never posted twice") + } + + private func waitForBridgeStatus(_ model: MonitorModel, + _ predicate: @escaping (String?) -> Bool) async { + for _ in 0..<2_000 { + if predicate(model.museCodeBridgeStatus) { return } + try? await Task.sleep(nanoseconds: 1_000_000) + } + XCTFail("bridge status never matched; last status: \(model.museCodeBridgeStatus ?? "nil")") + } +} diff --git a/Tests/QuotaCoreTests/MuseCodeBurnMonitorTests.swift b/Tests/QuotaCoreTests/MuseCodeBurnMonitorTests.swift new file mode 100644 index 00000000..9d66b720 --- /dev/null +++ b/Tests/QuotaCoreTests/MuseCodeBurnMonitorTests.swift @@ -0,0 +1,97 @@ +import XCTest +@testable import QuotaCore + +final class MuseCodeBurnMonitorTests: XCTestCase { + private let now = Date(timeIntervalSince1970: 1_800_000_000) + + /// A reading whose window totals `total` tokens, `contributor` of them + /// on a contributor session; the rest, when any, sit on one standard + /// session, which is what the burn rule's presence test reads. + private func report(total: Int, contributor: Int, + standardModel: String = "muse-wonder-1.0") -> MuseCodeSessionReport { + var models: [MuseCodeModelUsage] = [] + var observations: [MuseCodeSessionObservation] = [] + if contributor > 0 { + models.append(MuseCodeModelUsage(modelId: "muse-spark-1.3-contributor", + tokens: contributor, segmentCount: 1, sessionCount: 1)) + observations.append(MuseCodeSessionObservation( + sessionId: "s-contributor", snapshotId: "snap-c", + modelId: "muse-spark-1.3-contributor", totalTokens: contributor, + segmentKey: "seg-c", observedAt: now)) + } + if total > contributor { + models.append(MuseCodeModelUsage(modelId: standardModel, tokens: total - contributor, + segmentCount: 1, sessionCount: 1)) + observations.append(MuseCodeSessionObservation( + sessionId: "s-standard", snapshotId: "snap-s", + modelId: standardModel, totalTokens: total - contributor, + segmentKey: "seg-s", observedAt: now)) + } + let window = MuseCodeWindowUsage(windowMinutes: 90, totalTokens: total, + contributorTokens: contributor, + contributorShare: total > 0 ? Double(contributor) / Double(total) : nil, + activeSessions: observations.count, models: models) + return MuseCodeSessionReport(generatedAt: now, windows: [window], + latestObservations: observations) + } + + func testBurnFiresOverThresholdWithStandardSessionPresent() { + let alert = MuseCodeBurnMonitor.evaluateBurn( + report: report(total: 5_000_000, contributor: 4_000_000), + thresholdTokens: MuseCodeBurnMonitor.defaultThresholdTokens) + let burn = try? XCTUnwrap(alert) + XCTAssertNotNil(burn) + XCTAssertEqual(burn?.totalTokens, 5_000_000) + XCTAssertEqual(burn?.standardSessions.map(\.sessionId), ["s-standard"]) + XCTAssertEqual(burn?.standardSessions.map(\.modelId), ["muse-wonder-1.0"]) + XCTAssertTrue(burn?.body.contains("s-standard") == true, + "the warning names the standard session present") + XCTAssertTrue(burn?.body.contains("muse-wonder-1.0") == true, + "the warning names the standard model present") + } + + func testBurnSuppressedOverThresholdWithNoStandardSessions() { + let report = report(total: 9_000_000, contributor: 9_000_000) + XCTAssertNil(MuseCodeBurnMonitor.evaluateBurn( + report: report, thresholdTokens: MuseCodeBurnMonitor.defaultThresholdTokens), + "a heavy window with zero standard-model sessions does not fire, however it is shared") + XCTAssertEqual(MuseCodeBurnMonitor.status(report: report, issue: nil, + thresholdTokens: 4_000_000), + .allContributor(totalTokens: 9_000_000)) + } + + func testBurnSuppressedBelowThresholdWithStandardSessionPresent() { + let report = report(total: 3_000_000, contributor: 2_000_000) + XCTAssertNil(MuseCodeBurnMonitor.evaluateBurn( + report: report, thresholdTokens: MuseCodeBurnMonitor.defaultThresholdTokens), + "below the threshold the combined burn rule stays silent; the standard session is the detector kind's event, not this one's") + XCTAssertEqual(MuseCodeBurnMonitor.status(report: report, issue: nil, + thresholdTokens: 4_000_000), + .belowThreshold(totalTokens: 3_000_000)) + } + + func testBurnSuppressedExactlyAtThreshold() { + let report = report(total: 4_000_000, contributor: 3_000_000) + XCTAssertNil(MuseCodeBurnMonitor.evaluateBurn( + report: report, thresholdTokens: 4_000_000), + "exceeds is strict: exactly at the threshold has not exceeded it") + } + + func testStatusForMissingAndEmptyReports() { + XCTAssertEqual(MuseCodeBurnMonitor.status(report: nil, issue: "missing", + thresholdTokens: 4_000_000), + .storeUnavailable) + XCTAssertEqual(MuseCodeBurnMonitor.status(report: report(total: 0, contributor: 0), + issue: nil, thresholdTokens: 4_000_000), + .noActivity) + } + + func testWarningStatusCarriesTheBurnAlert() { + let report = report(total: 5_000_000, contributor: 4_000_000) + guard case .warning(let alert) = MuseCodeBurnMonitor.status( + report: report, issue: nil, thresholdTokens: 4_000_000) else { + return XCTFail("an over-threshold window with a standard session is a warning state") + } + XCTAssertEqual(alert.totalTokens, 5_000_000) + } +} diff --git a/Tests/QuotaCoreTests/MuseCodeSessionIngestTests.swift b/Tests/QuotaCoreTests/MuseCodeSessionIngestTests.swift new file mode 100644 index 00000000..3a9ee609 --- /dev/null +++ b/Tests/QuotaCoreTests/MuseCodeSessionIngestTests.swift @@ -0,0 +1,148 @@ +import XCTest +@testable import QuotaCore + +final class MuseCodeSessionIngestTests: XCTestCase { + private let now = Date(timeIntervalSince1970: 1_800_000_000) + + private func observation(session: String = "s1", snapshot: String = "snap1", + model: String = "muse-wonder-1.0", total: Int, + segment: String = "seg-a", minutesAgo: Double = 5) -> MuseCodeSessionObservation { + MuseCodeSessionObservation(sessionId: session, snapshotId: snapshot, modelId: model, + totalTokens: total, segmentKey: segment, + observedAt: now.addingTimeInterval(-minutesAgo * 60)) + } + + // MARK: - Event shape (the verified contract) + + func testEventMatchesVerifiedContractShape() { + let event = MuseCodeSessionIngest.event( + observation: observation(model: "muse-spark-1.3-contributor", total: 5_000), delta: 1_250) + XCTAssertEqual(Set(event.keys), ["eventId", "provider", "service", "producerKeyRef", + "metricType", "unit", "quantity", "billingMode", + "confidence", "occurredAt", "metadata"]) + XCTAssertEqual(event["eventId"] as? String, + "codecaps-muse-code:s1:snap1:muse-spark-1.3-contributor") + XCTAssertEqual(event["provider"] as? String, "muse-code") + XCTAssertEqual(event["service"] as? String, "muse-code") + XCTAssertEqual(event["producerKeyRef"] as? String, "muse-spark-1.3-contributor") + XCTAssertEqual(event["metricType"] as? String, "usage") + XCTAssertEqual(event["unit"] as? String, "token") + XCTAssertEqual(event["quantity"] as? Int, 1_250, "quantity is the delta, never the cumulative total") + XCTAssertEqual(event["billingMode"] as? String, "estimated") + XCTAssertEqual(event["confidence"] as? String, "estimated") + let metadata = event["metadata"] as? [String: Any] + XCTAssertEqual(metadata?["sessionId"] as? String, "s1") + XCTAssertEqual(metadata?["contributor"] as? Bool, true) + XCTAssertEqual(metadata?["source"] as? String, "muse-session-stores") + } + + func testBatchEnvelopeMatchesVerifiedContractShape() throws { + let events = [MuseCodeSessionIngest.event(observation: observation(total: 10), delta: 10)] + let data = try MuseCodeSessionIngest.batchData(events: events) + let root = try XCTUnwrap(JSONSerialization.jsonObject(with: data) as? [String: Any]) + XCTAssertEqual(Set(root.keys), ["schemaVersion", "producerId", "events"]) + XCTAssertEqual(root["schemaVersion"] as? Int, 2) + XCTAssertEqual(root["producerId"] as? String, "muse-code") + XCTAssertEqual((root["events"] as? [Any])?.count, 1) + } + + func testBatchesChunkAtOneHundredEvents() { + let events = (0..<205).map { index in + MuseCodeSessionIngest.event(observation: observation(session: "s\(index)", total: 1), delta: 1) + } + XCTAssertEqual(MuseCodeSessionIngest.eventBatches(events: events).map(\.count), [100, 100, 5]) + } + + // MARK: - Delta discipline + + func testFirstObservationEmitsTheSegmentTotal() { + let plan = MuseCodeDeltaPlanner.plan(observations: [observation(total: 700)], previous: [:]) + XCTAssertEqual(plan.events.map(\.delta), [700]) + XCTAssertEqual(plan.updated["s1"]?.totalTokens, 700) + } + + func testSameSegmentEmitsOnlyThePositiveDelta() { + let previous = ["s1": observation(total: 700)] + let plan = MuseCodeDeltaPlanner.plan( + observations: [observation(snapshot: "snap2", total: 950)], previous: previous) + XCTAssertEqual(plan.events.map(\.delta), [250], + "950 cumulative minus the 700 already posted is a 250 delta, not 950") + XCTAssertEqual(plan.events.first?.observation.snapshotId, "snap2") + } + + func testUnchangedTotalEmitsNothingButAdvancesBaseline() { + let previous = ["s1": observation(total: 700)] + let plan = MuseCodeDeltaPlanner.plan( + observations: [observation(snapshot: "snap2", total: 700)], previous: previous) + XCTAssertTrue(plan.events.isEmpty) + XCTAssertEqual(plan.updated["s1"]?.snapshotId, "snap2") + } + + func testSegmentResetEmitsTheNewSegmentsTotal() { + let previous = ["s1": observation(total: 700, segment: "seg-a")] + let plan = MuseCodeDeltaPlanner.plan( + observations: [observation(snapshot: "snap2", total: 300, segment: "seg-b")], + previous: previous) + XCTAssertEqual(plan.events.map(\.delta), [300], + "a reset segment's total is the delta, even though it is below the old total") + } + + func testModelSwitchEmitsTheNewTotal() { + let previous = ["s1": observation(model: "muse-wonder-1.0", total: 700)] + let plan = MuseCodeDeltaPlanner.plan( + observations: [observation(snapshot: "snap2", model: "muse-spark-1.3-contributor", total: 200)], + previous: previous) + XCTAssertEqual(plan.events.map(\.delta), [200]) + XCTAssertEqual(plan.events.first?.observation.modelId, "muse-spark-1.3-contributor") + } + + func testDecreasedTotalInSameSegmentEmitsNothingAndRebaselines() { + let previous = ["s1": observation(total: 700)] + let plan = MuseCodeDeltaPlanner.plan( + observations: [observation(snapshot: "snap2", total: 400)], previous: previous) + XCTAssertTrue(plan.events.isEmpty, "a negative delta is never posted") + XCTAssertEqual(plan.updated["s1"]?.totalTokens, 400) + } + + // MARK: - Poster + + private func response(status: Int = 200) -> HTTPURLResponse { + HTTPURLResponse(url: MuseCodeSessionIngest.endpoint, statusCode: status, + httpVersion: nil, headerFields: nil)! + } + + func testPosterPostsBatchesAndValidatesCompleteAcknowledgment() async throws { + let events = [MuseCodeSessionIngest.event(observation: observation(total: 10), delta: 10), + MuseCodeSessionIngest.event(observation: observation(session: "s2", total: 5), delta: 5)] + var requests: [URLRequest] = [] + let poster = MuseCodeSessionPoster { request in + requests.append(request) + let ack: [String: Any] = ["received": 2, "persisted": 2, "duplicates": 0, + "pruned": 0, "rejected": 0] + return (try JSONSerialization.data(withJSONObject: ack), self.response()) + } + let summary = try await poster.publish(events: events, to: MuseCodeSessionIngest.endpoint, token: "scoped-token") + XCTAssertEqual(summary, MuseCodeIngestSummary(sent: 2, persisted: 2, duplicates: 0, pruned: 0, rejected: 0)) + XCTAssertEqual(requests.count, 1) + XCTAssertEqual(requests.first?.value(forHTTPHeaderField: "x-usage-telemetry-version"), "2") + XCTAssertEqual(requests.first?.value(forHTTPHeaderField: "Authorization"), "Bearer scoped-token") + let body = try XCTUnwrap(JSONSerialization.jsonObject( + with: try XCTUnwrap(requests.first?.httpBody)) as? [String: Any]) + XCTAssertEqual(body["producerId"] as? String, "muse-code") + } + + func testPosterRejectsIncompleteAcknowledgment() async { + let events = [MuseCodeSessionIngest.event(observation: observation(total: 10), delta: 10)] + let poster = MuseCodeSessionPoster { _ in + let ack: [String: Any] = ["received": 0, "persisted": 0, "duplicates": 0, + "pruned": 0, "rejected": 0] + return (try JSONSerialization.data(withJSONObject: ack), self.response()) + } + do { + _ = try await poster.publish(events: events, to: MuseCodeSessionIngest.endpoint, token: "scoped-token") + XCTFail("an acknowledgment that does not account for the sent events must throw") + } catch { + XCTAssertTrue(error is QuotaPublisherError) + } + } +} diff --git a/Tests/QuotaCoreTests/MuseCodeSessionReaderTests.swift b/Tests/QuotaCoreTests/MuseCodeSessionReaderTests.swift new file mode 100644 index 00000000..b4eed608 --- /dev/null +++ b/Tests/QuotaCoreTests/MuseCodeSessionReaderTests.swift @@ -0,0 +1,163 @@ +import XCTest +@testable import QuotaCore + +final class MuseCodeSessionReaderTests: XCTestCase { + private let now = Date(timeIntervalSince1970: 1_800_000_000) + + private func segment(session: String = "s1", model: String, tokens: Int, + minutesAgo: Double, first: String, last: String) -> MuseCodeTokenSegment { + MuseCodeTokenSegment(sessionId: session, modelId: model, totalTokens: tokens, + observedAt: now.addingTimeInterval(-minutesAgo * 60), + sourceFirstId: first, sourceLastId: last) + } + + func testAggregateDedupesRepeatedSegmentsPerSession() { + let original = segment(model: "muse-spark-1.3-contributor", tokens: 1_000, + minutesAgo: 10, first: "a", last: "b") + let reread = segment(model: "muse-spark-1.3-contributor", tokens: 1_000, + minutesAgo: 9, first: "a", last: "b") + let otherSession = segment(session: "s2", model: "muse-spark-1.3-contributor", + tokens: 1_000, minutesAgo: 8, first: "a", last: "b") + let report = MuseCodeSessionReader.aggregate( + segments: [original, reread, otherSession], + sessionActivity: ["s1": now, "s2": now], now: now) + let window = report.window(minutes: 90) + XCTAssertEqual(window?.totalTokens, 2_000, + "the same source range in one session is one segment; in another session it is its own") + XCTAssertEqual(window?.models.first?.segmentCount, 2) + XCTAssertEqual(window?.models.first?.sessionCount, 2) + XCTAssertEqual(report.segments.count, 2) + } + + func testAggregateWindowsAndContributorShare() { + let segments = [ + segment(model: "muse-spark-1.3-contributor", tokens: 3_000_000, + minutesAgo: 30, first: "a", last: "b"), + segment(model: "muse-wonder-1.0", tokens: 1_000_000, + minutesAgo: 20, first: "c", last: "d"), + segment(model: "muse-spark-1.3-contributor", tokens: 2_000_000, + minutesAgo: 75, first: "e", last: "f"), + segment(model: "muse-wonder-full-1.0", tokens: 9_000_000, + minutesAgo: 120, first: "g", last: "h") + ] + let report = MuseCodeSessionReader.aggregate( + segments: segments, sessionActivity: ["s1": now], now: now) + let window60 = report.window(minutes: 60) + XCTAssertEqual(window60?.totalTokens, 4_000_000) + XCTAssertEqual(window60?.contributorTokens, 3_000_000) + XCTAssertEqual(window60?.contributorShare, 0.75) + let window90 = report.window(minutes: 90) + XCTAssertEqual(window90?.totalTokens, 6_000_000) + XCTAssertEqual(window90?.contributorShare, 5.0 / 6.0) + XCTAssertEqual(window90?.standardModels.map(\.modelId), ["muse-wonder-1.0"], + "the 120-minute-old standard segment is outside both windows") + XCTAssertEqual(window90?.activeSessions, 1) + XCTAssertEqual(window90?.tokensPerHour, 4_000_000) + } + + func testAggregateEmptyWindowHasNoShare() { + let report = MuseCodeSessionReader.aggregate(segments: [], sessionActivity: [:], now: now) + XCTAssertEqual(report.window(minutes: 90)?.totalTokens, 0) + XCTAssertNil(report.window(minutes: 90)?.contributorShare, + "no burn is neither 0% nor 100% contributor") + } + + // MARK: - Filesystem + + private func makeHome() throws -> URL { + let home = FileManager.default.temporaryDirectory + .appendingPathComponent("MuseCodeSessionReaderTests." + UUID().uuidString) + try FileManager.default.createDirectory(at: home, withIntermediateDirectories: true) + return home + } + + private func writeSnapshot(home: URL, session: String, name: String, + usage: [String: Any]?, modified: Date, headId: String = "x") throws { + let directory = home + .appendingPathComponent(".local/share/muse/sessions/.msp-view-g6/\(session)") + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + let url = directory.appendingPathComponent(name) + if let usage { + let root: [String: Any] = ["continuation": ["view_materialization": + ["current_state": ["tokenUsage": usage]]]] + try JSONSerialization.data(withJSONObject: root).write(to: url) + } else { + try Data("not json".utf8).write(to: url) + } + try FileManager.default.setAttributes([.modificationDate: modified], ofItemAtPath: url.path) + let head = directory.appendingPathComponent("HEAD.json") + try JSONSerialization.data(withJSONObject: ["latest_snapshot_id": headId]).write(to: head) + try FileManager.default.setAttributes([.modificationDate: modified], ofItemAtPath: head.path) + } + + private func usage(model: String, tokens: Int, first: String, last: String) -> [String: Any] { + ["modelId": model, "totalTokens": tokens, "promptTokens": tokens / 2, + "sourceRange": ["first": ["id": first], "last": ["id": last]]] + } + + func testReaderScansStoreAndSkipsStaleAndMalformedSnapshots() throws { + let home = try makeHome() + defer { try? FileManager.default.removeItem(at: home) } + try writeSnapshot(home: home, session: "session-a", name: "snapshot-1.json", + usage: usage(model: "muse-spark-1.3-contributor", tokens: 2_000, first: "a1", last: "b1"), + modified: now.addingTimeInterval(-75 * 60)) + try writeSnapshot(home: home, session: "session-a", name: "snapshot-2.json", + usage: usage(model: "muse-spark-1.3-contributor", tokens: 1_000, first: "a2", last: "b2"), + modified: now.addingTimeInterval(-10 * 60)) + try writeSnapshot(home: home, session: "session-a", name: "snapshot-3.json", + usage: usage(model: "muse-spark-1.3-contributor", tokens: 1_000, first: "a2", last: "b2"), + modified: now.addingTimeInterval(-9 * 60)) + try writeSnapshot(home: home, session: "session-a", name: "snapshot-4.json", + usage: usage(model: "muse-wonder-1.0", tokens: 500, first: "a3", last: "b3"), + modified: now.addingTimeInterval(-8 * 60)) + try writeSnapshot(home: home, session: "session-a", name: "snapshot-bad.json", + usage: nil, modified: now.addingTimeInterval(-5 * 60)) + try writeSnapshot(home: home, session: "session-b", name: "snapshot-1.json", + usage: usage(model: "muse-wonder-1.0", tokens: 7_777, first: "z1", last: "z2"), + modified: now.addingTimeInterval(-180 * 60)) + + let result = MuseCodeSessionReader(homeDirectory: home, now: { self.now }).read() + XCTAssertNil(result.issue) + let report = try XCTUnwrap(result.report) + XCTAssertEqual(report.window(minutes: 60)?.totalTokens, 1_500) + XCTAssertEqual(report.window(minutes: 90)?.totalTokens, 3_500) + XCTAssertEqual(report.window(minutes: 90)?.contributorTokens, 3_000) + XCTAssertEqual(report.window(minutes: 90)?.activeSessions, 1, + "session-b's newest file is three hours old, so it is not active") + XCTAssertEqual(report.segments.count, 3, "the duplicate snapshot adds no segment") + XCTAssertEqual(report.latestObservations.map(\.sessionId), ["session-a"]) + let observation = report.latestObservations.first + XCTAssertEqual(observation?.snapshotId, "4", + "HEAD names an unknown id here, so the newest parsed snapshot is the latest") + XCTAssertEqual(observation?.modelId, "muse-wonder-1.0") + XCTAssertEqual(observation?.totalTokens, 500) + XCTAssertEqual(observation?.segmentKey, "a3") + } + + func testReaderLatestObservationFollowsHeadSnapshotId() throws { + let home = try makeHome() + defer { try? FileManager.default.removeItem(at: home) } + try writeSnapshot(home: home, session: "session-c", name: "snapshot-7.json", + usage: usage(model: "muse-spark-1.3-contributor", tokens: 300, first: "c1", last: "c2"), + modified: now.addingTimeInterval(-20 * 60), headId: "7") + try writeSnapshot(home: home, session: "session-c", name: "snapshot-9.json", + usage: usage(model: "muse-wonder-1.0", tokens: 900, first: "c3", last: "c4"), + modified: now.addingTimeInterval(-5 * 60), headId: "7") + + let result = MuseCodeSessionReader(homeDirectory: home, now: { self.now }).read() + let observation = result.report?.latestObservations.first + XCTAssertEqual(observation?.snapshotId, "7", + "HEAD.json's latest_snapshot_id wins over the newest file by mtime") + XCTAssertEqual(observation?.modelId, "muse-spark-1.3-contributor") + XCTAssertEqual(observation?.totalTokens, 300) + XCTAssertEqual(observation?.isContributor, true) + } + + func testReaderReportsMissingStore() throws { + let home = try makeHome() + defer { try? FileManager.default.removeItem(at: home) } + let result = MuseCodeSessionReader(homeDirectory: home, now: { self.now }).read() + XCTAssertNil(result.report) + XCTAssertNotNil(result.issue) + } +} diff --git a/Tests/QuotaCoreTests/MuseCodeStandardSessionDetectorTests.swift b/Tests/QuotaCoreTests/MuseCodeStandardSessionDetectorTests.swift new file mode 100644 index 00000000..3769e17f --- /dev/null +++ b/Tests/QuotaCoreTests/MuseCodeStandardSessionDetectorTests.swift @@ -0,0 +1,120 @@ +import XCTest +@testable import QuotaCore + +final class MuseCodeStandardSessionDetectorTests: XCTestCase { + private let now = Date(timeIntervalSince1970: 1_800_000_000) + private let contributorModel = "muse-spark-1.3-contributor" + private let standardModel = "muse-wonder-1.0" + + private func observation(_ sessionId: String, _ modelId: String?, + at offset: TimeInterval = 0) -> MuseCodeSessionModelObservation { + MuseCodeSessionModelObservation(sessionId: sessionId, modelId: modelId, + observedAt: now.addingTimeInterval(offset)) + } + + func testNewStandardSessionFiresOnceNamingSessionModelAndTime() { + var detector = MuseCodeStandardSessionDetector() + let events = detector.observe([observation("s1", standardModel, at: 60)]) + XCTAssertEqual(events.count, 1) + XCTAssertEqual(events.first?.sessionId, "s1") + XCTAssertEqual(events.first?.modelId, standardModel) + XCTAssertEqual(events.first?.observedAt, now.addingTimeInterval(60)) + XCTAssertTrue(events.first?.body.contains("s1") == true, + "the alert payload names the session") + XCTAssertTrue(events.first?.body.contains(standardModel) == true, + "the alert payload names the model") + } + + func testSameStandardSessionRepolledDoesNotRefire() { + var detector = MuseCodeStandardSessionDetector() + XCTAssertEqual(detector.observe([observation("s1", standardModel)]).count, 1) + XCTAssertTrue(detector.observe([observation("s1", standardModel, at: 120)]).isEmpty) + XCTAssertTrue(detector.observe([observation("s1", standardModel, at: 240)]).isEmpty, + "staying on the same standard model across polls is not a new event") + } + + func testStandardToDifferentStandardModelDoesNotRefire() { + var detector = MuseCodeStandardSessionDetector() + XCTAssertEqual(detector.observe([observation("s1", standardModel)]).count, 1) + XCTAssertTrue(detector.observe([observation("s1", "muse-wonder-full-1.0", at: 60)]).isEmpty, + "moving between standard models never left the standard side") + } + + func testContributorToStandardSwitchFires() { + var detector = MuseCodeStandardSessionDetector() + XCTAssertTrue(detector.observe([observation("s1", contributorModel)]).isEmpty) + let events = detector.observe([observation("s1", standardModel, at: 60)]) + XCTAssertEqual(events.map(\.sessionId), ["s1"]) + XCTAssertEqual(events.first?.modelId, standardModel) + } + + func testStandardContributorStandardRefires() { + var detector = MuseCodeStandardSessionDetector() + XCTAssertEqual(detector.observe([observation("s1", standardModel)]).count, 1) + XCTAssertTrue(detector.observe([observation("s1", contributorModel, at: 60)]).isEmpty, + "returning to a contributor model is not an event, it re-arms") + let events = detector.observe([observation("s1", standardModel, at: 120)]) + XCTAssertEqual(events.count, 1, "going standard again after recovery is a new event") + } + + func testContributorOnlySessionsNeverFire() { + var detector = MuseCodeStandardSessionDetector() + for offset in stride(from: 0, through: 600, by: 60) { + let events = detector.observe([ + observation("s1", contributorModel, at: TimeInterval(offset)), + observation("s2", "muse-wonder-full-1.0-contributor", at: TimeInterval(offset)), + ]) + XCTAssertTrue(events.isEmpty) + } + } + + func testNullModelSessionNeverFiresAndLeavesNoTrace() { + var detector = MuseCodeStandardSessionDetector() + XCTAssertTrue(detector.observe([observation("s1", nil)]).isEmpty) + XCTAssertTrue(detector.observe([observation("s1", nil, at: 60)]).isEmpty, + "a session with no model on its current segment is not an event") + XCTAssertEqual(detector.lastKnownModels.count, 0, + "a model-less observation records nothing") + // The later standard sighting is the first model-bearing one, so it + // fires as first-observed rather than being masked by the null. + XCTAssertEqual(detector.observe([observation("s1", standardModel, at: 120)]).count, 1) + } + + func testSessionsAreTrackedIndependently() { + var detector = MuseCodeStandardSessionDetector() + let first = detector.observe([ + observation("s1", contributorModel), + observation("s2", standardModel), + ]) + XCTAssertEqual(first.map(\.sessionId), ["s2"]) + let second = detector.observe([ + observation("s1", standardModel, at: 60), + observation("s2", standardModel, at: 60), + ]) + XCTAssertEqual(second.map(\.sessionId), ["s1"], + "s2 was already standard; only s1's switch is new") + } + + func testStateSurvivesCodableRoundTripWithoutRefiring() throws { + var detector = MuseCodeStandardSessionDetector() + XCTAssertEqual(detector.observe([observation("s1", standardModel)]).count, 1) + // The persistence pattern the app uses: JSON in UserDefaults, loaded + // back at launch. A relaunched detector must not re-report s1. + let data = try JSONEncoder().encode(detector) + var relaunched = try JSONDecoder().decode(MuseCodeStandardSessionDetector.self, from: data) + XCTAssertEqual(relaunched, detector) + XCTAssertTrue(relaunched.observe([observation("s1", standardModel, at: 60)]).isEmpty) + XCTAssertEqual(relaunched.observe([observation("s2", standardModel, at: 60)]).count, 1, + "a genuinely new standard session still fires after a relaunch") + } + + func testStandardSessionsPresenceListsCurrentStandardSessions() { + let present = MuseCodeStandardSessionDetector.standardSessions(in: [ + observation("s1", contributorModel), + observation("s2", standardModel), + observation("s3", nil), + ]) + XCTAssertEqual(present.map(\.sessionId), ["s2"]) + XCTAssertEqual(present.first?.modelId, standardModel) + } +}