diff --git a/Sources/CodeCaps/MuseCodePluginView.swift b/Sources/CodeCaps/MuseCodePluginView.swift index fc11385d..30ad12d2 100644 --- a/Sources/CodeCaps/MuseCodePluginView.swift +++ b/Sources/CodeCaps/MuseCodePluginView.swift @@ -111,9 +111,12 @@ struct MuseCodeMonitorPage: View { if let report = model.museCodeReport { row("Last Read", report.generatedAt.formatted(date: .omitted, time: .standard)) } + // Burn and standard-session alerts are independent findings: + // both stay visible when both are present. if let alert = model.museCodeBurnAlert { row("Burn Alert", alert.body) - } else if let alert = model.museCodeStandardSessionAlert { + } + if let alert = model.museCodeStandardSessionAlert { row("Standard Session Alert", alert.body) } } diff --git a/Sources/QuotaCore/MuseCodeStandardSessionDetector.swift b/Sources/QuotaCore/MuseCodeStandardSessionDetector.swift index f7752a31..565cf246 100644 --- a/Sources/QuotaCore/MuseCodeStandardSessionDetector.swift +++ b/Sources/QuotaCore/MuseCodeStandardSessionDetector.swift @@ -92,8 +92,29 @@ public struct MuseCodeStandardSessionDetector: Codable, Equatable, Sendable { /// here has never been observed with a model. public private(set) var lastKnownModels: [String: String] - public init(lastKnownModels: [String: String] = [:]) { + /// When each tracked session was last observed, for staleness eviction. + /// Blobs persisted before the cap existed carry no stamps; those sessions + /// are kept and stamped on their next observation. + public private(set) var lastObservedAt: [String: Date] + + /// A session not observed for this long is no longer live: the reader's + /// window is ninety minutes, so a full day absent means it ended. + public static let sessionStateTTL: TimeInterval = 24 * 3_600 + /// Backstop bound on tracked sessions; the least recently observed are + /// evicted first. + public static let maxTrackedSessions = 512 + + public init(lastKnownModels: [String: String] = [:], lastObservedAt: [String: Date] = [:]) { self.lastKnownModels = lastKnownModels + self.lastObservedAt = lastObservedAt + } + + private enum CodingKeys: String, CodingKey { case lastKnownModels, lastObservedAt } + + public init(from decoder: Decoder) throws { + let container = try decoder.container(keyedBy: CodingKeys.self) + lastKnownModels = try container.decode([String: String].self, forKey: .lastKnownModels) + lastObservedAt = try container.decodeIfPresent([String: Date].self, forKey: .lastObservedAt) ?? [:] } /// A contributor model is a model id ending in `-contributor`. @@ -121,8 +142,10 @@ public struct MuseCodeStandardSessionDetector: Codable, Equatable, Sendable { public mutating func observe( _ observations: [MuseCodeSessionModelObservation] ) -> [MuseCodeStandardSessionEvent] { + evictExpiredSessions(relativeTo: observations.map(\.observedAt).max()) var events: [MuseCodeStandardSessionEvent] = [] for observation in observations { + lastObservedAt[observation.sessionId] = observation.observedAt guard let modelId = observation.modelId, !modelId.isEmpty else { continue } let previous = lastKnownModels[observation.sessionId] let wasContributor = previous.map { Self.isContributor(modelId: $0) } ?? false @@ -133,9 +156,52 @@ public struct MuseCodeStandardSessionDetector: Codable, Equatable, Sendable { } lastKnownModels[observation.sessionId] = modelId } + trimToCap() return events } + /// Drops sessions whose last observation is older than the TTL. Runs + /// before the poll so an evicted session that returns fires once as + /// first-observed, which a day-long absence warrants. An empty poll + /// falls back to the wall clock so idle periods still advance expiry. + private mutating func evictExpiredSessions(relativeTo newest: Date?) { + let cutoff = (newest ?? Date()).addingTimeInterval(-Self.sessionStateTTL) + for (sessionId, observedAt) in lastObservedAt where observedAt < cutoff { + lastKnownModels.removeValue(forKey: sessionId) + lastObservedAt.removeValue(forKey: sessionId) + } + } + + /// Trims the state to the cap by evicting the least recently observed. + /// Sessions without a liveness stamp predate the stamp field: any session + /// still live after the first poll of this version has been stamped, so + /// an unstamped entry is stale and sorts oldest, evicted first. + private mutating func trimToCap() { + if lastKnownModels.count > Self.maxTrackedSessions { + let overflow = lastKnownModels.count - Self.maxTrackedSessions + let oldest = lastKnownModels.keys.sorted { + (lastObservedAt[$0] ?? .distantPast) < (lastObservedAt[$1] ?? .distantPast) + }.prefix(overflow) + for sessionId in oldest { + lastKnownModels.removeValue(forKey: sessionId) + lastObservedAt.removeValue(forKey: sessionId) + } + } + // Model-less sessions never enter lastKnownModels, so without this + // their liveness stamps would accumulate unbounded until the TTL. + // Evict the oldest orphan stamps once the map itself passes the cap; + // stamps that back a tracked session are left alone. + let orphanOverflow = lastObservedAt.count - Self.maxTrackedSessions + if orphanOverflow > 0 { + let orphans = lastObservedAt.keys + .filter { lastKnownModels[$0] == nil } + .sorted { (lastObservedAt[$0] ?? .distantPast) < (lastObservedAt[$1] ?? .distantPast) } + for sessionId in orphans.prefix(orphanOverflow) { + lastObservedAt.removeValue(forKey: sessionId) + } + } + } + /// 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 diff --git a/Tests/CodeCapsTests/MuseCodePluginTests.swift b/Tests/CodeCapsTests/MuseCodePluginTests.swift index 648fb99a..6f9abada 100644 --- a/Tests/CodeCapsTests/MuseCodePluginTests.swift +++ b/Tests/CodeCapsTests/MuseCodePluginTests.swift @@ -10,9 +10,24 @@ private final class SpyAlertChannel: CodeCapsAlertChannel { @MainActor final class MuseCodePluginTests: XCTestCase { + private static var repoRoot: URL { + URL(fileURLWithPath: #filePath) + .deletingLastPathComponent() + .deletingLastPathComponent() + .deletingLastPathComponent() + } + private var suiteName = "" private var defaults: UserDefaults! + func testBothMuseAlertsStayVisibleTogether() throws { + let source = try String( + contentsOf: Self.repoRoot.appendingPathComponent("Sources/CodeCaps/MuseCodePluginView.swift"), + encoding: .utf8) + XCTAssertFalse(source.contains("} else if let alert = model.museCodeStandardSessionAlert"), + "the standard-session alert must not hide behind a burn alert; both stay visible") + } + override func setUp() { super.setUp() suiteName = "MuseCodePluginTests." + UUID().uuidString diff --git a/Tests/QuotaCoreTests/MuseCodeStandardSessionDetectorTests.swift b/Tests/QuotaCoreTests/MuseCodeStandardSessionDetectorTests.swift index 334ceeb7..7c56f42a 100644 --- a/Tests/QuotaCoreTests/MuseCodeStandardSessionDetectorTests.swift +++ b/Tests/QuotaCoreTests/MuseCodeStandardSessionDetectorTests.swift @@ -124,4 +124,85 @@ final class MuseCodeStandardSessionDetectorTests: XCTestCase { XCTAssertEqual(present.map(\.sessionId), ["s2"]) XCTAssertEqual(present.first?.modelId, standardModel) } + + func testSessionUnobservedPastTTLIsEvictedAndRefiresAsNew() { + var detector = MuseCodeStandardSessionDetector() + XCTAssertEqual(detector.observe([observation("s1", contributorModel)]).count, 0) + let later = MuseCodeStandardSessionDetector.sessionStateTTL + 600 + let events = detector.observe([observation("s2", contributorModel, at: later), + observation("s1", standardModel, at: later)]) + XCTAssertEqual(events.map(\.sessionId), ["s1"], + "a session silent past the TTL is evicted, so returning on a standard model fires as first-observed") + } + + func testTrackedStateIsCappedByEvictingLeastRecentlyObserved() { + var detector = MuseCodeStandardSessionDetector() + for i in 0..