Skip to content

App shell: menu bar, CoreMIDI and UDP adapters, sandbox, CI build #14

Closed

Description

@Skeyelab

Parent

#12

What to build

A real, sandboxed menu-bar app runs the Kit against real CoreMIDI and UDP. With a virtual MIDI source standing in for the LC6000 and a UDP listener standing in for Syndicate, Play works end to end and the Play LED message comes back.

Acceptance criteria

  • The XcodeGen project follows ShowRecorder: a dev.ericdahl bundle id, Swift 6 strict concurrency, macOS 26, LSUIElement, the hardened runtime, ITSAppUsesNonExemptEncryption false and a sandbox with the network client and server entitlements.
  • The menu bar shows the connected or not-connected status, Settings… and Quit.
  • The CoreMIDI callback parses MIDI words into Sendable values before returning. MIDI, UDP feedback and the tick timer feed one ordered stream that the Coordinator consumes, with no Task per message. The MIDI client is created on the main thread. The menu reads a @MainActor @Observable copy of the status.
  • The feedback listener binds to 127.0.0.1:9096 by default. A bind failure is reported in the status, not a crash.
  • A smoke script drives the built, sandboxed app with a virtual MIDI source and a UDP loopback, and checks PlayPause out and the Play LED back. It is required locally and best-effort in CI.
  • CI builds the app with ad-hoc signing.
  • Written test-first with /tdd, at the agreed seams (the Coordinator with fakes, and OSC packet bytes). The adapters are covered by the smoke script, not unit tests.

Blocked by

Activity

  1. added this to the v1.0: native Mac app milestone on Nov 16, 2026
  2. Skeyelab commented on Nov 16, 2026

    @Skeyelab
    MemberAuthor

    Risk spike: sandboxed menu-bar app with CoreMIDI and loopback UDP

    Verdict: no blockers. A sandboxed, hardened-runtime, ad-hoc-signed menu-bar app does all of (a), (b) and (c). Two real gotchas came up, both about Swift 6 isolation (below).

    The probe lives outside the repo, in /private/tmp/claude-501/lc6000-spike. It has an XcodeGen app, a SpikeKit SwiftPM package with tests, and a non-sandboxed helper that stands in for the LC6000 (virtual MIDI source and destination) and for Syndicate (UDP 9090, and a sender to 9096). No repo changes.

    Test host: macOS 27.0 (26A428), Xcode 27.2, Swift 6.4.2, deployment target macOS 26.0, SWIFT_STRICT_CONCURRENCY: complete. I had no macOS 26 machine, so the build targets 26 but I only ran it on 27. No signing identity was installed, so everything is ad-hoc (CODE_SIGN_IDENTITY: "-").

    Results

    Check Result
    Sandbox active yes, APP_SANDBOX_CONTAINER_ID=dev.ericdahl.LC6000Bridge
    (a) list sources and destinations works
    (a) MIDIInputPortCreateWithProtocol(._1_0) from a virtual source 2000 of 2000 events, 0 out of order, Debug and Release
    (a) MIDISendEventList to a destination works, the helper got 2090017F
    (a) MIDIClientCreateWithBlock notifications objectAdded, objectRemoved and setupChanged arrive, all on the main thread (client created on main)
    CoreMIDI entitlement none needed
    (b) sendto 127.0.0.1:9090 works. Needs network.client: without it, EPERM (1)
    (c) bind and recv on 127.0.0.1:9096 100 of 100 datagrams. Needs network.server: without it, bind fails with EPERM (1)
    Hardened runtime (Release, adhoc,runtime flags) all of the above pass
    Launch through LaunchServices (open -n), Release works as an LSUIElement accessory with a status item. With the helper running, MIDI out and UDP to 9090 reached the helper.

    Entitlements (exact, as tested)

    <key>com.apple.security.app-sandbox</key><true/>
    <key>com.apple.security.network.client</key><true/>
    <key>com.apple.security.network.server</key><true/>

    I tested each one by removing it. Without network.server, bind gets EPERM. Without network.client, sendto gets EPERM. CoreMIDI works with neither. The spec's files.user-selected.read-write (per #28) is separate and wasn't needed here.

    Local network prompt

    Binding and sending only on 127.0.0.1 caused no local-network check, including when the app was launched through LaunchServices (open -n), so the check was charged to the app rather than to Terminal. In that run the helper got the 9090 datagram and the MIDI packet, and nehelper/networkextension logged 0 lines for the app in that window. The app has no NSLocalNetworkUsageDescription. This matches Apple's rule that loopback is exempt. Caveat: I couldn't see the screen. I'm basing this on unblocked traffic and the missing log line, not on watching for a dialog. Binding 0.0.0.0 or sending to a LAN address would bring the prompt back, so keep both sides on 127.0.0.1.

    When 9096 is already taken

    • BSD bind: returns -1 with errno 48 EADDRINUSE. Same result whether the other process holds 127.0.0.1:9096 or 0.0.0.0:9096.
    • NWListener with requiredLocalEndpoint = 127.0.0.1:9096: doesn't throw. stateUpdateHandler gets .failed(POSIXErrorCode(48)).
    • Neither crashes. Both map cleanly to a "feedback port in use" status.
    • Not tested, from socket semantics: don't set SO_REUSEPORT. With it, two processes could share the port and split the feedback without any error.

    Gotchas

    1. Swift 6 isolation trap on a non-main callback (observed crash). A DispatchSource read handler written inline in main.swift (top-level code, so @MainActor) trapped when it ran on the udp.rx queue: _dispatch_assert_queue_fail → swift_task_checkIsolatedSwift, EXC_BREAKPOINT, Debug build. The same handler moved into a nonisolated func ran fine. Rule: build every callback in a nonisolated func or type. The compiler then rejects any main-actor state the callback reaches for.
    2. CoreMIDI receive blocks don't trap, which is worse. Observed in Debug only: a MIDIReceiveBlock written inline in main-actor code, even one that read a main-actor var on the realtime thread, gave no trap and no compile error. That's a silent data race. My guess, not tested: MIDIReceiveBlock is a plain C block typedef (marked [[clang::nonblocking]], not Sendable), so Swift inserts no runtime isolation check. The rule from gotcha 1 covers it: build the receive block in a nonisolated factory that captures only the Sendable producer.
    3. Notify block thread. The header says "arbitrary thread", but in practice notifications arrive on the run loop of the thread that created the client. Create the client on main, as App shell: menu bar, CoreMIDI and UDP adapters, sandbox, CI build #14 already requires, and use MainActor.assumeIsolated inside the notify block. It traps loudly if that ever changes. setupChanged fires alongside every add or remove. Treat all of them as a plain "devices changed" and re-scan.
    4. Track connected sources by kMIDIPropertyUniqueID (Int32), not by MIDIEndpointRef. Pass the uid as connRefCon (UnsafeMutableRawPointer(bitPattern: Int(uid))) and read it back in the receive block. That gives each event its source: id. Not exercised in the probe (it never prunes): remove the uid on objectRemoved, or a replugged controller won't reconnect. The smoke script should cover replug.
    5. Debug build + hardened runtime + ad-hoc. Xcode's Debug build (ENABLE_DEBUG_DYLIB = YES) silently leaves off the runtime flag. If you force it on, dyld rejects *.debug.dylib ("different Team IDs", since ad-hoc has no team). Release builds carry adhoc,runtime and run fine. So the smoke script and CI should use Release (or ENABLE_DEBUG_DYLIB: NO).
    6. get-task-allow is still in the ad-hoc Release signature (CODE_SIGN_INJECT_BASE_ENTITLEMENTS). That's fine for CI and smoke runs. Archive/export strips it, but check the notarized build (Release pipeline: TestFlight and App Store from a tag #28).
    7. SwiftPM: .macOS(.v26) needs swift-tools-version: 6.2.

    Callback → actor stream (trimmed)

    This was test-driven in SpikeKit with Swift Testing: 9 tests, hand-worked UMP literals, fake producers on real threads. Seams:

    • MIDIParse.events(words:): pure UMP decode.
    • EventPipe: the stream boundary. Tests cover per-producer order across three OS threads, no drops (a mutation check showed .bufferingNewest fails the test), and producer calls being synchronous and never waiting on the reader.

    TDD note: the multi-thread order test and the non-blocking test passed on their first run, with no red, because the design already covered them. I mutation-checked the order test. The non-blocking test I didn't mutation-check; its compile-time half (a non-async caller) is the stronger guard. Real CoreMIDI, UDP and the sandbox are the manual probe above. The shape matches what agent1 agreed for #13's Coordinator input.

    // Kit (pure)
    public enum MIDIEvent: Sendable, Equatable {
        case noteOn(channel: UInt8, note: UInt8, velocity: UInt8)    // channel 0-based
        case noteOff(channel: UInt8, note: UInt8, velocity: UInt8)
        case controlChange(channel: UInt8, controller: UInt8, value: UInt8)
    }
    public enum PipeEvent: Sendable, Equatable {
        case midi(MIDIEvent, source: Int32)   // source = kMIDIPropertyUniqueID
        case udp([UInt8])
        case tick
    }
    public struct EventPipe: Sendable {
        public let events: AsyncStream<PipeEvent>
        public let producer: Producer
        public init() {
            let (s, c) = AsyncStream<PipeEvent>.makeStream(bufferingPolicy: .unbounded) // never drop
            events = s; producer = Producer(continuation: c)
        }
        public struct Producer: Sendable {           // any thread, incl. CoreMIDI realtime; never awaits
            let continuation: AsyncStream<PipeEvent>.Continuation
            public func midi(_ e: MIDIEvent, source: Int32) { continuation.yield(.midi(e, source: source)) }
            public func udp(_ b: [UInt8]) { continuation.yield(.udp(b)) }
            public func tick() { continuation.yield(.tick) }
            public func finish() { continuation.finish() }
        }
    }
    
    // MIDI adapter: build the block in nonisolated code so it can only capture Sendable things.
    nonisolated func makeReceiveBlock(_ producer: EventPipe.Producer) -> MIDIReceiveBlock {
        { list, connRefCon in
            let source = Int32(truncatingIfNeeded: Int(bitPattern: connRefCon))
            for packet in list.unsafeSequence() {
                for e in MIDIParse.events(words: Array(packet.words())) { producer.midi(e, source: source) }
            }
        }
    }
    
    // App: one consumer, one loop, no Task per message. Illustrative: OSCPacket/Coordinator are #13's API.
    actor Engine {
        let coordinator: Coordinator
        func run(_ events: AsyncStream<PipeEvent>) async {
            for await e in events {
                switch e {
                case .midi(let m, _): coordinator.midi(m)
                case .udp(let bytes): for msg in (try? OSCPacket(decoding: bytes))?.messages ?? [] { coordinator.feedback(msg) }
                case .tick: coordinator.tick()
                }
            }
        }
    }

    Realtime note: Array(packet.words()) and AsyncStream.yield (which takes a lock and appends) are not strictly realtime-safe. At controller rates that's fine; 2000 back-to-back events came through in order with no loss. If it ever matters, make MIDIParse generic over Sequence<UInt32> to drop the array, and only then consider a lock-free ring.

    MIDIParse handles UMP type 2 (MIDI 1.0 channel voice) only: 0x8n note off, 0x9n note on, 0xBn CC. It steps over other message types by their UMP word count (so a 4-word type 0xF is skipped whole) and ignores other statuses such as pitch bend. It yields note on with velocity 0 as is. The Coordinator treats that as a release (agreed with agent1). Pairing CC 8/40 into 14 bits stays in the codec.

    Recommendation: move MIDIParse into LC6000Kit Core

    I recommend Core. It's pure ([UInt32] -> [MIDIEvent], no CoreMIDI import). MIDIEvent already lives in Core per #13. And it's the only adapter logic worth unit tests, so it belongs at a tested seam rather than in the smoke-only adapter. The adapter then shrinks to Array(packet.words()) plus producer.midi. The cost is one more small public API in Core.

    For #14's project.yml (merged with #28's needs from agent3)

    PRODUCT_BUNDLE_IDENTIFIER: dev.ericdahl.LC6000Bridge
    SWIFT_VERSION: "6.0"
    SWIFT_STRICT_CONCURRENCY: complete
    ENABLE_HARDENED_RUNTIME: true
    CODE_SIGN_STYLE: Automatic                         # CI: CODE_SIGN_IDENTITY "-" for ad-hoc
    PROVISIONING_PROFILE_SPECIFIER: $(APP_PROFILE_NAME) # empty locally, set by release CI
    ASSETCATALOG_COMPILER_APPICON_NAME: AppIcon        # placeholder icon is fine
    # info: LSUIElement true, ITSAppUsesNonExemptEncryption false,
    #       LSApplicationCategoryType public.app-category.music,
    #       CFBundleShortVersionString $(MARKETING_VERSION), CFBundleVersion $(CURRENT_PROJECT_VERSION)
    # resources: PrivacyInfo.xcprivacy
    # entitlements: app-sandbox, network.client, network.server (+ files.user-selected.read-write per spec)

    Smoke script tip: build Release ad-hoc and run the binary directly (.../Contents/MacOS/<App>) to get stdout. The sandbox still applies when you launch it that way.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    ready-for-agentFully specified, ready for an AFK agent

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions