From 6837696060ac1050be5439cab24177919ff3e738 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 21 Oct 2026 17:48:05 +0000 Subject: [PATCH 1/3] Stop unbounded memory growth during long sessions - Time-box BLE scans and drop AllowDuplicates; saved lights reconnect without scanning, and a short scan runs only while one is missing - Break DeviceViewObject retain cycle (weak self in bind closures, remove the no-op 10s timer) - Free AudioSpectrogram's manually allocated buffers and stop stacking volume listeners - Clean up legacy MCP SSE sessions when the client disconnects Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_013kitTs6K338t9YLbyktXqU --- NeewerLite/NeewerLite/AppDelegate.swift | 95 +++++++++++++++---- NeewerLite/NeewerLite/Server.swift | 28 +++++- .../Spectrogram/AudioSpectrogram.swift | 7 ++ .../ViewModels/DeviceViewObject.swift | 48 ++++------ 4 files changed, 127 insertions(+), 51 deletions(-) diff --git a/NeewerLite/NeewerLite/AppDelegate.swift b/NeewerLite/NeewerLite/AppDelegate.swift index b0de99f..4ed3ab8 100644 --- a/NeewerLite/NeewerLite/AppDelegate.swift +++ b/NeewerLite/NeewerLite/AppDelegate.swift @@ -96,6 +96,12 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMenuDele } } var scanningTimer: Timer? + /// How long a scan for saved lights runs before it stops by itself. + private let backgroundScanDuration: TimeInterval = 60 + /// Minimum gap between background scans while a saved light is still missing. + private let backgroundScanRetryInterval: TimeInterval = 300 + private var scanStopWorkItem: DispatchWorkItem? + private var lastScanStartedAt: Date? var server: NeewerLiteServer? var launching: Bool = true var commonJobTimer: Timer? @@ -431,7 +437,70 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMenuDele viewObject.view?.grayOut() } } + self.scanForMissingLightsIfNeeded() + } + } + + // MARK: - Scan Lifecycle + + /// Starts a BLE scan. With a `duration` the scan stops by itself (or earlier, once + /// every saved light is connected); without one it runs until `stopScanning()`. + /// Scanning never runs indefinitely in the background: an endless scan makes + /// CoreBluetooth accumulate every nearby device, and memory grows for as long + /// as the app stays open. + func startScanning(duration: TimeInterval?) { + guard let central = cbCentralManager, central.state == .poweredOn else { return } + central.stopScan() + central.scanForPeripherals(withServices: nil, options: nil) + scanning = true + lastScanStartedAt = Date() + Logger.debug(LogTag.bluetooth, "scanForPeripherals, duration: \(String(describing: duration))") + + scanStopWorkItem?.cancel() + scanStopWorkItem = nil + if let duration { + let item = DispatchWorkItem { [weak self] in + guard let self, !self.scanningNewLightMode else { return } + self.stopScanning() + } + scanStopWorkItem = item + DispatchQueue.main.asyncAfter(deadline: .now() + duration, execute: item) + } + } + + func stopScanning() { + scanStopWorkItem?.cancel() + scanStopWorkItem = nil + if cbCentralManager?.state == .poweredOn { + cbCentralManager?.stopScan() + } + scanning = false + // Non-Neewer devices only need to be remembered while a scan is running. + peripheralInvalidCache.removeAll() + Logger.debug(LogTag.bluetooth, "scan stopped") + } + + private var hasMissingSavedLights: Bool { + if debugFakeLights { + return false } + return viewObjects.contains { $0.device.peripheral == nil } + } + + private func stopScanningIfAllLightsFound() { + if scanning && !scanningNewLightMode && !hasMissingSavedLights { + stopScanning() + } + } + + /// Saved lights that are already known reconnect through `connect()` without a scan. + /// A scan is only needed for a saved light the app has not found since launch. + private func scanForMissingLightsIfNeeded() { + guard !scanning, hasMissingSavedLights else { return } + if let last = lastScanStartedAt, Date().timeIntervalSince(last) < backgroundScanRetryInterval { + return + } + startScanning(duration: backgroundScanDuration) } // MARK: - XIB String Localization @@ -1535,6 +1604,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMenuDele Logger.info(LogTag.click, "Scan") } else { scanningNewLightMode = false + stopScanning() scanningStatus?.stringValue = "" sender.title = "Scan".localized Logger.info(LogTag.click, "Stop") @@ -1543,18 +1613,6 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMenuDele @IBAction func scanAction(_ sender: AnyObject) { - if scanning { - // stop scanning - cbCentralManager?.stopScan() - scanning = false - } else { - // start scanning - cbCentralManager?.scanForPeripherals(withServices: nil, options: nil) - // scanAction(self) - scanning = true - Logger.debug("scanForPeripherals...") - } - Logger.debug("\(peripheralCache)") peripheralCache.removeAll() peripheralInvalidCache.removeAll() @@ -1582,8 +1640,9 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMenuDele self.statusItemIcon = .off updateUI() - cbCentralManager?.scanForPeripherals( - withServices: nil, options: [CBCentralManagerScanOptionAllowDuplicatesKey: true]) + // A new-light scan runs until the user presses Stop; any other scan is time-boxed. + // No AllowDuplicates: it delivers every advertisement packet of every nearby device. + startScanning(duration: scanningNewLightMode ? nil : backgroundScanDuration) } @objc func scanningTimerFired() { @@ -1727,6 +1786,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMenuDele peripheral, characteristic1, characteristic2) targetViewObject.device.startLightOnNotify() forcePowerOffAfterLaunchIfNeeded(targetViewObject) + stopScanningIfAllLightsFound() } if !found { @@ -1826,13 +1886,10 @@ extension AppDelegate: CBCentralManagerDelegate { case .unsupported: break case .poweredOn: Logger.debug(LogTag.bluetooth, "powered on") - central.scanForPeripherals(withServices: nil, options: nil) - // scanAction(self) - self.scanning = true + startScanning(duration: scanningNewLightMode ? nil : backgroundScanDuration) case .poweredOff: - central.stopScan() + stopScanning() Logger.debug(LogTag.bluetooth, "powered off") - self.scanning = false case .resetting: Logger.debug(LogTag.bluetooth, "resetting") @unknown default: break diff --git a/NeewerLite/NeewerLite/Server.swift b/NeewerLite/NeewerLite/Server.swift index f8e7b39..1fcb8c4 100644 --- a/NeewerLite/NeewerLite/Server.swift +++ b/NeewerLite/NeewerLite/Server.swift @@ -102,6 +102,10 @@ private actor SessionManager { } func bindSessionID(_ sessionID: String, to context: MCPSessionContext) { + // A re-initialized context gets a new session ID; forget the old one. + if let previous = context.sessionID, previous != sessionID { + clientKeyBySessionID.removeValue(forKey: previous) + } context.sessionID = sessionID context.lastSeen = Date() clientKeyBySessionID[sessionID] = context.clientKey @@ -306,10 +310,25 @@ final class NeewerLiteServer { let endpointEvent = "event: endpoint\ndata: /messages?sessionId=\(sessionId)\n\n" try? await writer.writeBuffer(ByteBuffer(string: endpointEvent)) - // Stream outbound SSE events until the session ends + // A periodic SSE comment makes a dropped client show up as a write error + // even when no MCP traffic is flowing; otherwise the session lives forever. + let heartbeat = Task { + while !Task.isCancelled { + try? await Task.sleep(nanoseconds: 30_000_000_000) + session.pushSSE(": keepalive\n\n") + } + } + + // Stream outbound SSE events until the session ends or the client goes away for await chunk in session.outbound { - try? await writer.writeBuffer(ByteBuffer(string: chunk)) + do { + try await writer.writeBuffer(ByteBuffer(string: chunk)) + } catch { + break + } } + heartbeat.cancel() + session.finish() try? await writer.write(.end) // Clean up after client disconnects @@ -396,6 +415,11 @@ final class NeewerLiteServer { } } } + + // The SSE connection is gone; release its MCP session context. + if let context = await sessionManager.context(forClientKey: clientKey) { + await sessionManager.removeContext(context) + } } // MARK: - MCP Route (Vapor ↔ MCP SDK) diff --git a/NeewerLite/NeewerLite/Spectrogram/AudioSpectrogram.swift b/NeewerLite/NeewerLite/Spectrogram/AudioSpectrogram.swift index 8466943..5449fb7 100644 --- a/NeewerLite/NeewerLite/Spectrogram/AudioSpectrogram.swift +++ b/NeewerLite/NeewerLite/Spectrogram/AudioSpectrogram.swift @@ -221,6 +221,9 @@ public class AudioSpectrogram: NSObject { deinit { removeVolumeListener() + // Manually allocated buffers are not freed by ARC. + filterBank.deallocate() + sgemmResult.deallocate() } // A reusable array that contains the current frame of time domain audio data as single-precision @@ -515,6 +518,10 @@ extension AudioSpectrogram: AVCaptureAudioDataOutputSampleBufferDelegate { } private func startVolumeListener() { + // startRunning() is called every time the Music view is shown; drop the + // previous listener so repeated starts don't stack listeners. + removeVolumeListener() + var defaultOutputDeviceID = AudioDeviceID(0) var defaultOutputDeviceIDSize = UInt32(MemoryLayout.size(ofValue: defaultOutputDeviceID)) diff --git a/NeewerLite/NeewerLite/ViewModels/DeviceViewObject.swift b/NeewerLite/NeewerLite/ViewModels/DeviceViewObject.swift index 1fadf67..ec332da 100644 --- a/NeewerLite/NeewerLite/ViewModels/DeviceViewObject.swift +++ b/NeewerLite/NeewerLite/ViewModels/DeviceViewObject.swift @@ -8,7 +8,6 @@ import Cocoa class DeviceViewObject: NSObject { - private var syncLifetime: Timer? var device: NeewerLight var view: CollectionViewItem? @@ -20,12 +19,8 @@ class DeviceViewObject: NSObject { super.init() initing = true - self.syncLifetime = Timer.scheduledTimer(withTimeInterval: 10.0, repeats: true) { _ in - //device.sendReadRequest() - } - - self.device.isOn.bind { (_) in - guard !self.initing else { + self.device.isOn.bind { [weak self] (_) in + guard let self, !self.initing else { return } DispatchQueue.main.async { @@ -34,8 +29,8 @@ class DeviceViewObject: NSObject { } } } - self.device.channel.bind { (channel) in - guard !self.initing else { + self.device.channel.bind { [weak self] (channel) in + guard let self, !self.initing else { return } Logger.debug("Device channel update: \(channel)") @@ -45,8 +40,8 @@ class DeviceViewObject: NSObject { } } } - self.device.userLightName.bind { (name) in - guard !self.initing else { + self.device.userLightName.bind { [weak self] (name) in + guard let self, !self.initing else { return } Logger.debug("Device name update: \(name)") @@ -57,8 +52,8 @@ class DeviceViewObject: NSObject { } } - self.device.brrValue.bind { (val) in - guard !self.initing else { + self.device.brrValue.bind { [weak self] (val) in + guard let self, !self.initing else { return } Logger.debug("Device brightness update: \(val)") @@ -69,8 +64,8 @@ class DeviceViewObject: NSObject { } } - self.device.cctValue.bind { (val) in - guard !self.initing else { + self.device.cctValue.bind { [weak self] (val) in + guard let self, !self.initing else { return } Logger.debug("Device CCT update: \(val)") @@ -81,8 +76,8 @@ class DeviceViewObject: NSObject { } } - self.device.gmmValue.bind { (val) in - guard !self.initing else { + self.device.gmmValue.bind { [weak self] (val) in + guard let self, !self.initing else { return } Logger.debug("Device GM update: \(val)") @@ -93,8 +88,8 @@ class DeviceViewObject: NSObject { } } - self.device.hueValue.bind { (val) in - guard !self.initing else { + self.device.hueValue.bind { [weak self] (val) in + guard let self, !self.initing else { return } Logger.debug("Device HUE update: \(val)") @@ -105,8 +100,8 @@ class DeviceViewObject: NSObject { } } - self.device.satValue.bind { (val) in - guard !self.initing else { + self.device.satValue.bind { [weak self] (val) in + guard let self, !self.initing else { return } Logger.debug("Device HUE update: \(val)") @@ -117,8 +112,8 @@ class DeviceViewObject: NSObject { } } - self.device.supportGMRange.bind { support in - guard !self.initing else { + self.device.supportGMRange.bind { [weak self] support in + guard let self, !self.initing else { return } Logger.debug("Device supportGMRange update: \(support)") @@ -135,13 +130,6 @@ class DeviceViewObject: NSObject { deinit { Logger.debug("DeviceViewObject deinit") - clear() - } - - public func clear() { - if let safeTimer = self.syncLifetime { - safeTimer.invalidate() - } } public lazy var deviceName: String = { From 11d5d6e23157f917d035fe067530a57f7786bb32 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 21 Oct 2026 17:48:54 +0000 Subject: [PATCH 2/3] Add a Rescan for Lights menu item Background scans are now time-boxed, so give the user a manual way to start a fresh scan if a saved light doesn't reconnect. Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_013kitTs6K338t9YLbyktXqU --- NeewerLite/NeewerLite/AppDelegate.swift | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/NeewerLite/NeewerLite/AppDelegate.swift b/NeewerLite/NeewerLite/AppDelegate.swift index 4ed3ab8..b0f85c4 100644 --- a/NeewerLite/NeewerLite/AppDelegate.swift +++ b/NeewerLite/NeewerLite/AppDelegate.swift @@ -140,6 +140,7 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMenuDele self.viewsButton.selectSegment(withTag: idx ?? 0) localizeXIBStrings() + addRescanMenuItem() appMenu.delegate = self self.statusItem.menu = appMenu @@ -954,6 +955,25 @@ class AppDelegate: NSObject, NSApplicationDelegate, NSWindowDelegate, NSMenuDele } } + /// Adds "Rescan for Lights" to the status-bar menu, just above Quit. + /// Background scanning is time-boxed, so this lets the user force a fresh scan + /// when a saved light isn't reconnecting. + private func addRescanMenuItem() { + let item = NSMenuItem( + title: "Rescan for Lights".localized, + action: #selector(rescanLightsAction(_:)), + keyEquivalent: "") + item.target = self + let quitIndex = appMenu.items.firstIndex { $0.action == #selector(NSApplication.terminate(_:)) } + appMenu.insertItem(item, at: quitIndex ?? appMenu.items.count) + } + + @objc func rescanLightsAction(_ sender: Any) { + Logger.info(LogTag.click, "Rescan for Lights") + // Not new-light mode, so scanAction runs a time-boxed scan for saved lights. + scanAction(self) + } + @IBAction func syncDatabaseAction(_ sender: NSMenuItem) { ContentManager.shared.downloadDatabase(force: true) } From 97df318073b64fae0d4307a275b34293966a76aa Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 22 Oct 2026 17:59:00 +0000 Subject: [PATCH 3/3] Localize the Rescan for Lights menu item Co-Authored-By: Claude Opus 5.5 (1M context) Claude-Session: https://claude.ai/code/session_013kitTs6K338t9YLbyktXqU --- .../Resources/Localizable.xcstrings | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) diff --git a/NeewerLite/NeewerLite/Resources/Localizable.xcstrings b/NeewerLite/NeewerLite/Resources/Localizable.xcstrings index 49412e6..9199a20 100644 --- a/NeewerLite/NeewerLite/Resources/Localizable.xcstrings +++ b/NeewerLite/NeewerLite/Resources/Localizable.xcstrings @@ -8035,6 +8035,46 @@ } } }, + "Rescan for Lights" : { + "localizations" : { + "de" : { + "stringUnit" : { + "state" : "translated", + "value" : "Lichter erneut suchen" + } + }, + "es" : { + "stringUnit" : { + "state" : "translated", + "value" : "Volver a buscar luces" + } + }, + "fr" : { + "stringUnit" : { + "state" : "translated", + "value" : "Rechercher à nouveau les lumières" + } + }, + "ja" : { + "stringUnit" : { + "state" : "translated", + "value" : "ライトを再スキャン" + } + }, + "ko" : { + "stringUnit" : { + "state" : "translated", + "value" : "조명 다시 검색" + } + }, + "zh-Hans" : { + "stringUnit" : { + "state" : "translated", + "value" : "重新扫描灯" + } + } + } + }, "Restart Now" : { "extractionState" : "stale", "localizations" : {