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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion Sources/TingleCore/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down
9 changes: 2 additions & 7 deletions Sources/TingleCore/DetectionCoordinator.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
12 changes: 6 additions & 6 deletions Sources/TingleCore/Dictation.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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)")
}
}
}
Expand Down
84 changes: 84 additions & 0 deletions Sources/TingleCore/FirmwareUpgrader.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import AppKit
import CryptoKit
import IOKit
import os

/// Guided ting firmware upgrade. The RP2350's bootloader is ROM-resident,
Expand Down Expand Up @@ -46,6 +47,8 @@ public enum FirmwareUpgrader {
case unzipFailed
case bootloaderTimeout
case tingdiskTimeout
case wrongVariant(String)
case alreadyNewer(String)

var errorDescription: String? {
switch self {
Expand All @@ -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."
}
}
}
Expand All @@ -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)
Expand Down Expand Up @@ -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..<max(lhs.count, rhs.count) {
let l = i < lhs.count ? lhs[i] : 0
let r = i < rhs.count ? rhs[i] : 0
if l != r { return l > r }
}
return true
}

// MARK: - Steps

private static func fetchUF2() throws -> Data {
Expand Down
27 changes: 23 additions & 4 deletions Sources/TingleCore/Flasher.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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).
Expand Down Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion Sources/TingleCore/RewriteEngine.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)'"
Expand Down
8 changes: 4 additions & 4 deletions Sources/TingleCore/StatusItemController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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)…"
Expand All @@ -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
}
Expand Down
44 changes: 44 additions & 0 deletions Tests/tingle-tests/DeviceDiscoveryTests.swift
Original file line number Diff line number Diff line change
@@ -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")
}
6 changes: 6 additions & 0 deletions Tests/tingle-tests/RewriteTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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()
}

Expand Down
1 change: 1 addition & 0 deletions Tests/tingle-tests/main.swift
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,7 @@ runBeaconScannerTests()
runGuardrailTests()
runRewriteTests()
runFlasherTests()
runDeviceDiscoveryTests()
runAudioEngineOpsTests()
runAudioHardwareTests()

Expand Down