diff --git a/Sources/TingleCore/AppDelegate.swift b/Sources/TingleCore/AppDelegate.swift index 5dfed41..0c59a9f 100644 --- a/Sources/TingleCore/AppDelegate.swift +++ b/Sources/TingleCore/AppDelegate.swift @@ -53,8 +53,24 @@ public enum TingleApp { } -enum Log { +public enum Log { static let subsystem = "com.tutorintelligence.tingle" + + /// Wrap anything the user said before logging it. Dev builds keep the + /// words so rewrite bugs can be traced; release builds keep only the + /// length, because the unified log is readable by any admin process + /// and outlives the dictation. + static func transcript(_ text: String) -> String { + #if DEBUG + return text + #else + return redacted(text) + #endif + } + + public static func redacted(_ text: String) -> String { + "<\(text.count) chars>" + } } final class AppDelegate: NSObject, NSApplicationDelegate { diff --git a/Sources/TingleCore/DetectionCoordinator.swift b/Sources/TingleCore/DetectionCoordinator.swift index c57692b..08d1caa 100644 --- a/Sources/TingleCore/DetectionCoordinator.swift +++ b/Sources/TingleCore/DetectionCoordinator.swift @@ -220,14 +220,9 @@ final class DetectionCoordinator { } } - /// The ting enumerates as /dev/cu.usbmodemEPTXP* (see DESIGN.md). static func findSerialDevicePath() -> String? { - let names = (try? FileManager.default.contentsOfDirectory(atPath: "/dev")) ?? [] - return names - .filter { $0.hasPrefix("cu.usbmodemEPTXP") } - .sorted() - .first - .map { "/dev/\($0)" } + FirmwareUpgrader.serialDevicePath( + among: (try? FileManager.default.contentsOfDirectory(atPath: "/dev")) ?? []) } private func startSerial(path: String) { diff --git a/Sources/TingleCore/Dictation.swift b/Sources/TingleCore/Dictation.swift index 151a2d6..bf9fa6c 100644 --- a/Sources/TingleCore/Dictation.swift +++ b/Sources/TingleCore/Dictation.swift @@ -232,17 +232,17 @@ public final class DictationController { defer { if modelWillRun { DispatchQueue.main.async { notifyRewriteActive?(false) } } } let started = Date() var candidate = rewriteConfig.removeFillers ? RewritePrompt.stripFillers(text) : text - // Stage-by-stage logging (local unified log only): this is the - // ground truth for separating model behavior from apply bugs. - log.info("rewrite in: \(text, privacy: .public)") + // Stage-by-stage logging: the ground truth for separating model + // behavior from apply bugs. + log.info("rewrite in: \(Log.transcript(text), privacy: .public)") if candidate != text { - log.info("rewrite filler-stripped: \(candidate, privacy: .public)") + log.info("rewrite filler-stripped: \(Log.transcript(candidate), privacy: .public)") } if model.isAvailable { let instructions = RewritePrompt.instructions(config: rewriteConfig, vocabulary: vocabulary) if let out = try? await model.rewrite(candidate, instructions: instructions) { let processed = RewritePrompt.postProcess(out) - log.info("rewrite model out: \(processed, privacy: .public)") + log.info("rewrite model out: \(Log.transcript(processed), privacy: .public)") if let reason = RewritePrompt.gate(input: candidate, output: processed) { log.info("rewrite REJECTED by gate (\(reason, privacy: .public)); keeping filler-stripped text") } else { @@ -273,7 +273,7 @@ public final class DictationController { DictationKeystrokes.post(edit) self.takeStack[self.takeStack.count - 1].characterCount = finalText.count self.takeStack[self.takeStack.count - 1].lastCharacter = finalText.last - log.info("rewrite applied in \(String(format: "%.2f", elapsed), privacy: .public)s: -\(edit.backspaces) backspaces, retyped: \(edit.append, privacy: .public)") + log.info("rewrite applied in \(String(format: "%.2f", elapsed), privacy: .public)s: -\(edit.backspaces) backspaces, retyped: \(Log.transcript(edit.append), privacy: .public)") } } } diff --git a/Sources/TingleCore/FirmwareUpgrader.swift b/Sources/TingleCore/FirmwareUpgrader.swift index cbebaba..4f78e37 100644 --- a/Sources/TingleCore/FirmwareUpgrader.swift +++ b/Sources/TingleCore/FirmwareUpgrader.swift @@ -1,5 +1,6 @@ import AppKit import CryptoKit +import IOKit import os /// Guided ting firmware upgrade. The RP2350's bootloader is ROM-resident, @@ -46,6 +47,8 @@ public enum FirmwareUpgrader { case unzipFailed case bootloaderTimeout case tingdiskTimeout + case wrongVariant(String) + case alreadyNewer(String) var errorDescription: String? { switch self { @@ -59,6 +62,10 @@ public enum FirmwareUpgrader { return "Never saw the TING BOOT disk. Two things trip people up: KEEP the handle squeezed the whole time, and the button needs a true DOUBLE-CLICK — two quick presses in rapid succession, like a mouse double-click (two deliberate separate presses just power-cycle it). Lid off, USB connected, squeeze and hold, double-click the small button above the USB port. Run the upgrade again to retry." case .tingdiskTimeout: return "Firmware was written, but TINGDISK didn't come back. Power-cycle the ting and run Flash EP from the menu." + case .wrongVariant(let volume): + return "\(volume) is an FX MIC bootloader, but tingle's pinned firmware \(version) is the ting build. Nothing was written. Release the handle and power-cycle the device." + case .alreadyNewer(let running): + return "This device already runs firmware \(running), newer than tingle's pinned \(version). Nothing was written." } } } @@ -74,11 +81,21 @@ public enum FirmwareUpgrader { let report: (String) -> Void = { text in DispatchQueue.main.async { status(text) } } DispatchQueue.global(qos: .userInitiated).async { do { + if let running = runningVersion(), isVersion(running, atLeast: version), + running != version { + throw UpgradeError.alreadyNewer(running) + } + report("Downloading firmware \(version)…") let uf2 = try fetchUF2() report("Waiting for the TING BOOT disk (keep squeezing the handle)…") let bootVolume = try waitForBootloaderVolume(timeout: 180) + // TE ships separate ting and FX MIC builds since 1.1.x; the + // pinned image predates the split and targets the ting. + if bootVolume.lastPathComponent.uppercased().contains("FX MIC") { + throw UpgradeError.wrongVariant(bootVolume.lastPathComponent) + } report("Writing firmware…") try writeUF2(uf2, to: bootVolume) @@ -109,6 +126,73 @@ public enum FirmwareUpgrader { .map { $0.replacingOccurrences(of: "/dev/cu.usbmodem", with: "") } } + /// The CDC port is named after the USB serial number, which starts + /// with "EP" but varies by product variant: the ting enumerates as + /// cu.usbmodemEPTXP*, the FX MIC as cu.usbmodemEPXYW*. + public static func serialDevicePath(among deviceNames: [String]) -> String? { + deviceNames + .filter { $0.hasPrefix("cu.usbmodemEP") } + .sorted() + .first + .map { "/dev/\($0)" } + } + + /// True when this device needs no firmware flow: tingle flashed the + /// pinned version onto it, or it reports a version at least that new. + /// Without the second check, Flash EP on an FX MIC shipping 1.1.2 would + /// route through the ritual and DOWNGRADE it to the pinned 1.0.8. + public static func isFirmwareCurrent() -> Bool { + if Prefs.lastFlashedFirmware(serial: dockedSerial()) == version { return true } + guard let running = runningVersion() else { return false } + return isVersion(running, atLeast: version) + } + + /// Firmware the docked device reports in its USB product name. Newer + /// firmware embeds it ("EP_2350 1_1_2"); older builds only said + /// "EP-2350", so nil means unknown, not old. + public static func runningVersion() -> String? { + var iterator: io_iterator_t = 0 + guard IOServiceGetMatchingServices( + kIOMainPortDefault, IOServiceMatching("IOUSBHostDevice"), &iterator) == KERN_SUCCESS + else { return nil } + defer { IOObjectRelease(iterator) } + var service = IOIteratorNext(iterator) + while service != 0 { + defer { IOObjectRelease(service); service = IOIteratorNext(iterator) } + let vendor = IORegistryEntryCreateCFProperty( + service, "idVendor" as CFString, kCFAllocatorDefault, 0)? + .takeRetainedValue() as? Int + guard vendor == teenageEngineeringVendorID else { continue } + let name = IORegistryEntryCreateCFProperty( + service, "USB Product Name" as CFString, kCFAllocatorDefault, 0)? + .takeRetainedValue() as? String + if let name, let parsed = firmwareVersion(fromProductName: name) { return parsed } + } + return nil + } + + static let teenageEngineeringVendorID = 0x2367 + + public static func firmwareVersion(fromProductName name: String) -> String? { + let tokens = name.split(separator: " ") + guard tokens.count >= 2, tokens[0].replacingOccurrences(of: "_", with: "-") == "EP-2350" + else { return nil } + let parts = tokens[1].split(whereSeparator: { $0 == "_" || $0 == "." }) + guard parts.count == 3, parts.allSatisfy({ Int($0) != nil }) else { return nil } + return parts.joined(separator: ".") + } + + public static func isVersion(_ a: String, atLeast b: String) -> Bool { + let lhs = a.split(separator: ".").map { Int($0) ?? 0 } + let rhs = b.split(separator: ".").map { Int($0) ?? 0 } + for i in 0.. r } + } + return true + } + // MARK: - Steps private static func fetchUF2() throws -> Data { diff --git a/Sources/TingleCore/Flasher.swift b/Sources/TingleCore/Flasher.swift index fb55286..5bd642d 100644 --- a/Sources/TingleCore/Flasher.swift +++ b/Sources/TingleCore/Flasher.swift @@ -11,7 +11,28 @@ import os /// AppleDouble junk, ejects. "Restore stock" deletes the overrides instead — /// without main.py and 1-4.wav the device is 100% stock. public enum Flasher { - static let volumeURL = URL(fileURLWithPath: "/Volumes/TINGDISK", isDirectory: true) + /// The same EP-2350 hardware mounts under a different name per product + /// variant: the ting as TINGDISK, the FX MIC as "FX MIC DISK". + public static let volumeNames = ["TINGDISK", "FX MIC DISK"] + + /// The first mounted volume from `volumeNames`, falling back to the + /// ting's so error paths still name a concrete location. + static var volumeURL: URL { + mountedVolume(in: URL(fileURLWithPath: "/Volumes", isDirectory: true)) + ?? URL(fileURLWithPath: "/Volumes/\(volumeNames[0])", isDirectory: true) + } + + public static func mountedVolume(in volumesRoot: URL) -> URL? { + for name in volumeNames { + let url = volumesRoot.appendingPathComponent(name, isDirectory: true) + var isDirectory: ObjCBool = false + if FileManager.default.fileExists(atPath: url.path, isDirectory: &isDirectory), + isDirectory.boolValue { + return url + } + } + return nil + } private static let sampleFileNames = ["1.wav", "2.wav", "3.wav", "4.wav"] /// Everything FLASH EP can touch (and therefore backs up / restores). @@ -124,9 +145,7 @@ public enum Flasher { } static var isTingleiskMounted: Bool { - var isDirectory: ObjCBool = false - return FileManager.default.fileExists(atPath: volumeURL.path, isDirectory: &isDirectory) - && isDirectory.boolValue + mountedVolume(in: URL(fileURLWithPath: "/Volumes", isDirectory: true)) != nil } /// Mounted AND actually accepting writes. The volume appears in diff --git a/Sources/TingleCore/RewriteEngine.swift b/Sources/TingleCore/RewriteEngine.swift index 35aadd0..c7acef9 100644 --- a/Sources/TingleCore/RewriteEngine.swift +++ b/Sources/TingleCore/RewriteEngine.swift @@ -136,7 +136,7 @@ public enum RewritePrompt { return String(format: "word retention %.2f < 0.35", r) } if let word = censoredProfanity(input: input, output: out) { - return "censored '\(word)'" + return "censored '\(Log.transcript(word))'" } if let marker = refusalMarker(input: input, output: out) { return "refusal boilerplate '\(marker)'" diff --git a/Sources/TingleCore/StatusItemController.swift b/Sources/TingleCore/StatusItemController.swift index 9e3f2b2..a90dc87 100644 --- a/Sources/TingleCore/StatusItemController.swift +++ b/Sources/TingleCore/StatusItemController.swift @@ -424,9 +424,9 @@ final class StatusItemController: NSObject, NSMenuDelegate { // its running version over USB). let docked = lastBackendState == .connectedSerial || Flasher.isTingleiskMounted if !isFlashing, docked { - let flashed = Prefs.lastFlashedFirmware(serial: FirmwareUpgrader.dockedSerial()) - if flashed == FirmwareUpgrader.version { - firmwareItem.title = "ting firmware \(FirmwareUpgrader.version) (latest)" + if FirmwareUpgrader.isFirmwareCurrent() { + let shown = FirmwareUpgrader.runningVersion() ?? FirmwareUpgrader.version + firmwareItem.title = "ting firmware \(shown) (latest)" firmwareItem.isEnabled = false } else { firmwareItem.title = "Upgrade ting firmware to \(FirmwareUpgrader.version)…" @@ -444,7 +444,7 @@ final class StatusItemController: NSObject, NSMenuDelegate { // payload onto unknown firmware produces a device that half-works, // so route first-time devices through the full setup: firmware // ritual, then the payload flash rides on the end of that flow. - if Prefs.lastFlashedFirmware(serial: FirmwareUpgrader.dockedSerial()) != FirmwareUpgrader.version { + if !FirmwareUpgrader.isFirmwareCurrent() { startFirmwareUpgrade(newDevice: true) return } diff --git a/Tests/tingle-tests/DeviceDiscoveryTests.swift b/Tests/tingle-tests/DeviceDiscoveryTests.swift new file mode 100644 index 0000000..7785b39 --- /dev/null +++ b/Tests/tingle-tests/DeviceDiscoveryTests.swift @@ -0,0 +1,44 @@ +import Foundation +import TingleCore + +func runDeviceDiscoveryTests() { + // --- serial port: the FX MIC variant enumerates under a different + // USB serial prefix than the ting and went undiscovered (2026-10-01) --- + expectEqual(FirmwareUpgrader.serialDevicePath(among: ["cu.usbmodemEPTXP3R31"]), + "/dev/cu.usbmodemEPTXP3R31", "discovery: ting serial port") + expectEqual(FirmwareUpgrader.serialDevicePath(among: ["cu.usbmodemEPXYW1R31"]), + "/dev/cu.usbmodemEPXYW1R31", "discovery: FX MIC serial port") + expectEqual(FirmwareUpgrader.serialDevicePath( + among: ["cu.Bluetooth-Incoming-Port", "cu.usbmodem21201", "tty.usbmodemEPXYW1R31"]), + nil, "discovery: other usbmodems and tty nodes ignored") + + // --- FAT disk: TINGDISK on the ting, "FX MIC DISK" on the FX MIC --- + let root = FileManager.default.temporaryDirectory + .appendingPathComponent("tingle-volumes-\(UUID().uuidString)", isDirectory: true) + try? FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + expect(Flasher.mountedVolume(in: root) == nil, "discovery: no device disk mounted") + let fxMic = root.appendingPathComponent("FX MIC DISK", isDirectory: true) + try? FileManager.default.createDirectory(at: fxMic, withIntermediateDirectories: true) + expectEqual(Flasher.mountedVolume(in: root)?.lastPathComponent, "FX MIC DISK", + "discovery: FX MIC DISK found") + let ting = root.appendingPathComponent("TINGDISK", isDirectory: true) + try? FileManager.default.createDirectory(at: ting, withIntermediateDirectories: true) + expectEqual(Flasher.mountedVolume(in: root)?.lastPathComponent, "TINGDISK", + "discovery: TINGDISK found") + + // --- running firmware from the USB product name: the guard that stops + // Flash EP from downgrading a 1.1.2 FX MIC to the pinned 1.0.8 --- + expectEqual(FirmwareUpgrader.firmwareVersion(fromProductName: "EP_2350 1_1_2"), "1.1.2", + "firmware: USB product name parsed") + expectEqual(FirmwareUpgrader.firmwareVersion(fromProductName: "EP-2350 1.1.2"), "1.1.2", + "firmware: registry entry name parsed") + expectEqual(FirmwareUpgrader.firmwareVersion(fromProductName: "EP-2350"), nil, + "firmware: old builds report no version") + expectEqual(FirmwareUpgrader.firmwareVersion(fromProductName: "TS5 Plus USB 2 Hub"), nil, + "firmware: unrelated device ignored") + expect(FirmwareUpgrader.isVersion("1.1.2", atLeast: "1.0.8"), "firmware: 1.1.2 >= 1.0.8") + expect(FirmwareUpgrader.isVersion("1.0.10", atLeast: "1.0.8"), "firmware: numeric, not lexical") + expect(FirmwareUpgrader.isVersion("1.0.8", atLeast: "1.0.8"), "firmware: equal counts as current") + expect(!FirmwareUpgrader.isVersion("1.0.5", atLeast: "1.0.8"), "firmware: 1.0.5 is behind") +} diff --git a/Tests/tingle-tests/RewriteTests.swift b/Tests/tingle-tests/RewriteTests.swift index 0e6405c..c8b79a2 100644 --- a/Tests/tingle-tests/RewriteTests.swift +++ b/Tests/tingle-tests/RewriteTests.swift @@ -77,6 +77,12 @@ func runRewriteTests() { output: "And then the model said, I cannot comply with your request, which is hilarious.") == nil, "rewrite: gate allows refusal phrases the speaker dictated") + // Release builds log rewrite stages through Log.redacted: a user's + // exact dictation showed up in `log show` (2026-10-01). + let spoken = "meet me at the usual place at nine" + expect(!Log.redacted(spoken).contains("usual"), "rewrite: redacted log drops the words") + expectEqual(Log.redacted(spoken), "<\(spoken.count) chars>", "rewrite: redacted log keeps the length") + runRewriteEditTests() } diff --git a/Tests/tingle-tests/main.swift b/Tests/tingle-tests/main.swift index f848a59..ddb2c5b 100644 --- a/Tests/tingle-tests/main.swift +++ b/Tests/tingle-tests/main.swift @@ -178,6 +178,7 @@ runBeaconScannerTests() runGuardrailTests() runRewriteTests() runFlasherTests() +runDeviceDiscoveryTests() runAudioEngineOpsTests() runAudioHardwareTests()